text
stringlengths
184
4.48M
import dadosFetch from "../../axios/config"; import { useState } from "react"; import { useNavigate } from "react-router-dom"; import "./NewPost.css" const NewPostTurma = () => { const navigate = useNavigate(); // Gerenciando o estado dos inputs html const [titulo, setTitulo] = useState(); const [descricao, setDescricao] = useState(); const [cargaHoraria, setCargaHoraria] = useState(); // Função que envia os dados do formulário para a API const createPost = async (e) => { e.preventDefault(); // Evita recarregamento da mesma página const turma = {titulo, descricao, cargaHoraria}; try { //salvando os dados com post await dadosFetch.post("/turmas", turma); //redireciona para a homepage navigate('/'); } catch (error) { console.error("Erro na requisição POST:", error); } } return( <div className="new-post"> <h2>Cadastrar Turma</h2> <form onSubmit={(e) => createPost(e)}> <div className="form-controll"> <label htmlFor="titulo">Título:</label> <input type="text" name="titulo" id="titulo" placeholder="Digite o título" onChange={(e) => setTitulo(e.target.value)} /> </div> <div className="form-controll"> <label htmlFor="descricao">Descrição:</label> <input type="text" name="descricao" id="descricao" placeholder="Digite a descrição " onChange={(e) => setDescricao(e.target.value)} /> </div> <div className="form-controll"> <label htmlFor="cargaHoraria">Carga horária:</label> <input type="number" name="cargaHoraria" id="cargaHoraria" placeholder="Digite a carga horária" onChange={(e) => setCargaHoraria(e.target.value)} /> </div> <input type="submit" value="Criar turma" className="btn" /> </form> </div> ) } export default NewPostTurma;
from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Employee, Department class EmployeeListView(ListView): model = Employee template_name = 'employee_list.html' context_object_name = 'employees' class EmployeeCreateView(CreateView): model = Employee template_name = 'employee_form.html' fields = ['name', 'email', 'address', 'designation', 'reporting_manager', 'department'] success_url = reverse_lazy('employee_app:employee-list') class EmployeeUpdateView(UpdateView): model = Employee template_name = 'employee_form.html' fields = ['name', 'email', 'address', 'designation', 'reporting_manager', 'department'] class EmployeeDeleteView(DeleteView): model = Employee template_name = 'employee_confirm_delete.html' success_url = reverse_lazy('employee_app:employee-list') class DepartmentListView(ListView): model = Department template_name = 'department_list.html' context_object_name = 'departments' class DepartmentCreateView(CreateView): model = Department template_name = 'department_form.html' fields = ['name', 'floor'] class DepartmentUpdateView(UpdateView): model = Department template_name = 'department_form.html' fields = ['name', 'floor'] class DepartmentDeleteView(DeleteView): model = Department template_name = 'department_confirm_delete.html' success_url = reverse_lazy('employee_app:department-list')
from typing import Literal from person import Artist class Album: def __init__( self, navn: str, artist: Artist, plateselskap: str, utgivelsesår: int ) -> None: self.__navn = navn self.__artist = artist self.__plateselskap = plateselskap self.__utgivelsesår = utgivelsesår @property def navn(self) -> str: return self.__navn @property def artist(self) -> Artist: return self.__artist def vis_info(self) -> None: print(str(self)) def __str__(self) -> str: return f"Album: {self.__navn}. Laget av: {self.__artist.navn}. Utgitt av {self.__plateselskap} i {self.__utgivelsesår}" class CD(Album): def __str__(self) -> str: return super().__str__() + ". Type: CD" type VinylHastighet = Literal[33, 45] type FargeRGB = tuple[int, int, int] class Vinyl(Album): def __init__( self, navn: str, artist: Artist, plateselskap: str, utgivelsesår: int, hastighet: VinylHastighet, farge: FargeRGB, ) -> None: super().__init__(navn, artist, plateselskap, utgivelsesår) self.__hastighet = hastighet self.__farge = farge def __str__(self) -> str: return ( super().__str__() + f". Type: Vinyl. Hastighet: {self.__hastighet}. Farge: rgb{self.__farge}" )
import React from "react"; import { Box, Text } from "@mantine/core"; import CommonButton from "../common/Button"; import classes from "../styles/Todos.module.css"; import TableData from "../common/Table"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import TodoByCategory from "./TodoByCategory"; import { useTodoContext } from "../context/TodoContext"; const Todos = () => { const queryClient = new QueryClient(); const { todo } = useTodoContext(); return ( <> <Text size="lg" fw={700} c={"blue"} tt={"uppercase"} style={{ textAlign: "center", margin: "20px 0" }} > Welcome To Todo </Text> <Box className={classes.TodoBox}> <Text size="lg" fw={700} c={"blue"} tt={"uppercase"}> My Todos </Text> <Box style={{ display: "flex", gap: "2px" }}> <CommonButton props={{ btnTitle: "Create Todo" }} /> <CommonButton props={{ btnTitle: "Create category" }} /> </Box> </Box> {/* <hr /> */} <Box> <QueryClientProvider client={queryClient}> <TableData /> </QueryClientProvider> {/* <hr /> */} <Text size="md" fw={600} ta="end" c={"blue"} tt={"uppercase"}> {todo.length ? <>You have total: {todo.length} todos</> : <></>} </Text> </Box> <hr style={{marginTop: "20px"}} /> <Box> <Text size="lg" fw={700} c={"blue"} tt={"uppercase"} ta="center" style={{ margin: "20px 0" }} > Todos By Category </Text> <TodoByCategory /> </Box> </> ); }; export default Todos;
import 'package:cep_list/pages/home_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:google_fonts/google_fonts.dart'; void main() async { await dotenv.load(fileName: ".env"); runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( colorScheme: ColorScheme.fromSeed( seedColor: const Color.fromARGB(0, 0, 129, 72)), textTheme: GoogleFonts.poppinsTextTheme(), scaffoldBackgroundColor: Colors.grey[300]), home: const HomePage()); } }
import type { Logger } from "../types.ts"; /** * Simple logger that logs to stderr when the DEBUG environment variable is set to true. */ const log = ( message: string, method: "log" | "error" | "info" | "warn" | "debug" = "log", ) => { Deno.stderr.write( new TextEncoder().encode( `${method}: ${message}\n`, ), ); }; export const getLogger = (): Logger => { const debug = Deno.env.get("DEBUG") === "true"; if (debug) { return { debug: (message: string) => log(message, "debug"), error: (message: string) => log(message, "error"), info: (message: string) => log(message, "info"), warn: (message: string) => log(message, "warn"), }; } else { return { debug: () => {}, error: () => {}, info: () => {}, warn: () => {}, }; } };
請運用DHT22+LCD或四數位七段顯示器(兩者選一),設計程式,讓溫度(攝氏)及相對溼度資料在顯示器上呈現。 完成期限:108年10月30日 #include "DHT.h" // 匯入DHT函式庫 #define DHTPIN 2 // 定義DHT函式庫中,所使用的訊號來源 #define DHTTYPE DHT22 // 定義DHT函式庫中,所使用的感測器 DHT dht(DHTPIN, DHTTYPE); #include <Wire.h> #include <LiquidCrystal_I2C.h> int x=123; //設定整數型態x變數 /*設定 LCD I2C 位址,市面上兩種不同晶片有不同設定方式,如果第一個不行請改第二個 */ LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); void setup() { Serial.begin(9600); lcd.begin(16, 2); //初始化 LCD,代表我們使用的LCD一行有16個字元,共2行。 lcd.backlight(); //開啟背光 dht.begin(); } void loop() { delay(200); float dhtT = dht.readTemperature(); //設定浮點變數dhtT,讀取溫度 float dhtH = dht.readHumidity(); lcd.home(); //LCD歸零,清除所有內容 lcd.clear(); //LCD歸零,清除所有內容 lcd.setCursor(0, 1); lcd.print("dhtH:"); lcd.setCursor(6,1); lcd.print(dhtH); lcd.setCursor(0, 0); lcd.print("dhtT:"); lcd.setCursor(6, 0); lcd.print(dhtT); lcd.setCursor(12, 0); lcd.print("C"); lcd.setCursor(12, 1); lcd.print("RH"); }
import React from "react"; import Link from "next/link"; import { AiFillGithub, AiFillTwitterCircle, AiFillInstagram} from "react-icons/ai"; const Footer = () => { const links = [ { link: "#", label: "About" }, { link: "#", label: "Skills" }, { link: "#", label: "Experience" }, { link: "#", label: "Contact Me" }, ]; return ( <div className="absolute w-full z-10"> <div className="max-w-[2560px] mx-auto flex justify-between items-center sm:px-16 px-6 py-2"> <div>Mitoru Dev</div> <div> <ul className="hidden md:flex"> {links.map(({ link, label }) => ( <li key={label} className="capitalize px-4 text-sm hover:underline underline-offset-4" > <Link href={link}>{label}</Link> </li> ))} </ul> </div> <div className="flex items-center"> <span className="p-1 rounded-full hover:bg-gradient-to-br from-purple-600 to-cyan-500 drop-shadow-md ml-3 hoverbg-red-500"> <AiFillGithub className="text-2xl" /> </span> <span className="p-1 rounded-full hover:bg-gradient-to-br from-purple-600 to-cyan-500 drop-shadow-md ml-3 hoverbg-red-500"> <AiFillTwitterCircle className="text-2xl" /> </span> <span className="p-1 rounded-full hover:bg-gradient-to-br from-purple-600 to-cyan-500 drop-shadow-md ml-3 hoverbg-red-500"> <AiFillInstagram className="text-2xl" /> </span> </div> </div> </div> ); }; export default Footer;
// 密码安全配置 参数验证 export const updatePasswordSafetySchema = { type: 'object', properties: { minLength: { type: 'number', positiveRange: [8, 64], errorMessage: { type: 'api.validate.number', positiveRange: 'api.validate.positiveRange|{"range":"8-64"}', }, }, maxSameLetter: { type: 'integer', integerRange: [0, 9], errorMessage: { type: 'api.validate.integer', integerRange: 'api.validate.integerRange|{"range":"0-9"}', }, }, lowercase: { type: 'boolean', errorMessage: { type: 'api.validate.boolean', }, }, uppercase: { type: 'boolean', errorMessage: { type: 'api.validate.boolean', }, }, number: { type: 'boolean', errorMessage: { type: 'api.validate.boolean', }, }, specialLetter: { type: 'boolean', errorMessage: { type: 'api.validate.boolean', }, }, weakCheck: { type: 'boolean', errorMessage: { type: 'api.validate.boolean', }, }, excludeWord: { type: 'array', uniqueItemsBlur: true, maxItems: 15, items: { type: 'string', format: 'letterNumber_' }, errorMessage: { type: 'api.validate.array', maxItems: 'api.validate.maxItems|{"value": 15}', uniqueItemsBlur: 'api.validate.uniqueItemsBlur', }, }, }, errorMessage: { properties: { excludeWord: 'api.validate.letterNumber_', }, }, };
// **************************************************************************** // // Aevol - An in silico experimental evolution platform // // **************************************************************************** // // Copyright: See the AUTHORS file provided with the package or <www.aevol.fr> // Web: http://www.aevol.fr/ // E-mail: See <http://www.aevol.fr/contact/> // Original Authors : Guillaume Beslon, Carole Knibbe, David Parsons // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // **************************************************************************** #ifndef AEVOL_GRID_CELL_H_ #define AEVOL_GRID_CELL_H_ // Libraries #include <cinttypes> #include <cstdio> #include <cstdlib> #include <cassert> #include <zlib.h> // Project Files #include "Individual.h" #include "HabitatFactory.h" #ifndef __REGUL #include "Habitat.h" #else #include "raevol/Habitat_R.h" #endif namespace aevol { // Class declarations class ExpManager; class GridCell { friend class World; public : // Constructors GridCell() = delete; GridCell(const GridCell &) = delete; GridCell(int16_t x, int16_t y, #ifdef __REGUL std::unique_ptr<Habitat_R>&& habitat, #else std::unique_ptr<Habitat> habitat, #endif Individual * indiv, std::shared_ptr<JumpingMT> mut_prng, std::shared_ptr<JumpingMT> stoch_prng); GridCell(gzFile backup_file, ExpManager * exp_m, std::shared_ptr<PhenotypicTargetHandler> phenotypic_target_handler); // Destructors virtual ~GridCell(); // Accessors: getters inline int16_t x() const {return x_;}; inline int16_t y() const {return y_;}; inline double compound_amount() const; inline Individual * individual() const; inline Individual * individual_nonconst() {return individual_;} inline double secreted_amount() const; inline double metabolic_fitness() const; inline double total_fitness() const; #ifdef __REGUL const Habitat_R& habitat() const { return *habitat_; } #else const Habitat& habitat() const { return *habitat_; } #endif #ifdef __REGUL Habitat_R& habitat_non_const() { return *habitat_; } #else Habitat& habitat_non_const() { return *habitat_; } #endif Habitat* habitat_ptr() { return habitat_.get(); } #ifndef __REGUL const PhenotypicTarget& phenotypic_target() const { return habitat_->phenotypic_target(); } #endif std::shared_ptr<JumpingMT> mut_prng() const; std::shared_ptr<JumpingMT> stoch_prng() const; // Accessors: setters inline void set_compound_amount(double compound_amount); inline void set_individual(Individual * indiv); inline void set_mut_prng(std::shared_ptr<JumpingMT> prng); inline void set_stoch_prng(std::shared_ptr<JumpingMT> prng); inline void set_reprod_prng(std::unique_ptr<JumpingMT>&& prng); inline void set_reprod_prng_simd(std::unique_ptr<JumpingMT>&& prng); // Public Methods void ApplyHabitatVariation(); void save(gzFile backup_file, bool skip_phenotypic_target = false) const; void load(gzFile backup_file, ExpManager * exp_m, std::shared_ptr<PhenotypicTargetHandler> phenotypic_target_handler); std::unique_ptr<JumpingMT> reprod_prng_ = nullptr; std::unique_ptr<JumpingMT> reprod_prng_simd_ = nullptr; double * probs; double * local_fit_array; double * local_meta_array; double sum_local_fit; double* loc_phenotype; int * indiv_index; Individual* old_one; protected : // Protected Methods // Protected Attributes // Position on the grid int16_t x_; int16_t y_; // Pointer to the individual in this cell Individual* individual_ = NULL; #ifdef __REGUL std::unique_ptr<Habitat_R> habitat_ = nullptr; #else std::unique_ptr<Habitat> habitat_ = nullptr; #endif std::shared_ptr<JumpingMT> mut_prng_ = nullptr; std::shared_ptr<JumpingMT> stoch_prng_ = nullptr; }; // Getters' definitions inline double GridCell::compound_amount() const { return habitat_->compound_amount(); } inline Individual *GridCell::individual() const { return individual_; } inline double GridCell::secreted_amount() const { return individual_->fitness_by_feature(SECRETION); } inline double GridCell::metabolic_fitness() const { return individual_->fitness_by_feature(METABOLISM); } inline double GridCell::total_fitness() const { return individual_->fitness(); } // Setters' definitions inline void GridCell::set_compound_amount(double compound_amount) { habitat_->set_compound_amount(compound_amount); } inline void GridCell::set_individual(Individual * indiv) { individual_ = indiv; if (individual_->grid_cell() != this) { individual_->set_grid_cell(this); } } inline void GridCell::set_mut_prng(std::shared_ptr<JumpingMT> prng) { mut_prng_ = prng; // printf("%d %d -- Update Mut PRNG\n",x(),y()); } inline void GridCell::set_stoch_prng(std::shared_ptr<JumpingMT> prng) { stoch_prng_ = prng; // printf("%d %d -- Update Stoch PRNG\n",x(),y()); } inline void GridCell::set_reprod_prng(std::unique_ptr<JumpingMT>&& prng) { reprod_prng_ = std::move(prng); } inline void GridCell::set_reprod_prng_simd(std::unique_ptr<JumpingMT>&& prng) { reprod_prng_simd_ = std::move(prng); } // Inline functions' definition } // namespace aevol #endif // AEVOL_GRID_CELL_H_
import { Table, TableColumnType, Typography } from 'antd'; import { useProductQuery } from '@/service/product'; import { Product } from '@/types'; const columns: TableColumnType<Product>[] = [ { title: 'ID', dataIndex: 'id', key: 'id', }, { title: 'Name', dataIndex: 'title', key: 'title', }, { title: 'Price', dataIndex: 'price', key: 'price', }, ]; const Products = () => { const { products, isLoading } = useProductQuery(); return ( <> <div className="mb-4"> <Typography.Title level={4}>Products</Typography.Title> </div> <Table loading={isLoading} columns={columns} dataSource={products} rowKey="id" /> </> ); }; export default Products;
import React from "react"; import { FlatList, Image, StyleSheet, Text, TouchableOpacity, View, } from "react-native"; import { maxChars } from "../utils/textFunctions"; import { useNavigation } from "@react-navigation/native"; const ResultList = ({ results }) => { const navigation = useNavigation(); return ( <FlatList data={results} renderItem={({ item }) => ( <RenderItem item={item} navigation={navigation} /> )} scrollEnabled={true} style={styles.list} /> ); }; export default ResultList; const RenderItem = ({ item, navigation }) => { return ( <TouchableOpacity style={styles.container} onPress={() => navigation.navigate("Movie", { item })} > <Image source={{ uri: `https://image.tmdb.org/t/p/w500${item.poster_path}` }} style={styles.image} /> <View style={styles.content}> <Text style={styles.title}>{item.title || item.name}</Text> <View style={styles.row}> <Text style={styles.text}>{item.vote_average}</Text> <Text style={styles.text}>{item.release_date}</Text> </View> <Text style={styles.text}>{maxChars(item.overview, 120)}</Text> </View> </TouchableOpacity> ); }; const styles = StyleSheet.create({ container: { width: "100%", height: 200, // backgroundColor: "white", borderRadius: 10, flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginBottom: 10, }, image: { width: "35%", height: "100%", borderRadius: 10, }, content: { height: "100%", width: "65%", justifyContent: "flex-start", alignItems: "flex-start", paddingVertical: 10, paddingHorizontal: 10, // backgroundColor: "rgba(255, 7, 7, 0.5)", }, row: { flexDirection: "row", justifyContent: "space-between", width: "100%", }, title: { fontSize: 20, fontWeight: "bold", color: "white", }, text: { color: "white", }, list: { flex: 1, backgroundColor: "#00000080", }, });
package main import "fmt" func divmod(numerator, denominator int) (quotient, remainder int) { quotient = numerator / denominator remainder = numerator % denominator return } func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { carry := 0 head := &ListNode{Val: -1} curr := head for l1 != nil && l2 != nil { x, y := l1.Val, l2.Val l1, l2 = l1.Next, l2.Next d, m := divmod(x+y+carry, 10) curr.Next = &ListNode{Val: m} curr = curr.Next carry = d } for l1 != nil { x := l1.Val l1 = l1.Next d, m := divmod(x+carry, 10) curr.Next = &ListNode{Val: m} curr = curr.Next carry = d } for l2 != nil { y := l2.Val l2 = l2.Next d, m := divmod(y+carry, 10) curr.Next = &ListNode{Val: m} curr = curr.Next carry = d } if carry > 0 { curr.Next = &ListNode{Val: carry} } return head.Next } type ListNode struct { Val int Next *ListNode } func newNode(val int) *ListNode { node := new(ListNode) node.Val = val return node } func createList(nums []int) *ListNode { head := newNode(-1) curr := head for _, num := range nums { curr.Next = newNode((num)) curr = curr.Next } return head.Next } func (head *ListNode) printList() { if head == nil { fmt.Println("]") return } if head.Next == nil { fmt.Printf("%v", head.Val) } else { fmt.Printf("%v, ", head.Val) } head.Next.printList() } func printFailedTest(actual *ListNode, expected *ListNode, testNum int) { fmt.Printf("Test %d failed:\n", testNum+1) fmt.Printf(" \tActual : [") actual.printList() fmt.Printf(" \tExpected: [") expected.printList() } func main() { tests := []struct { nums1 []int nums2 []int expected []int }{ {[]int{2, 4, 3}, []int{5, 6, 4}, []int{7, 0, 8}}, {[]int{0}, []int{0}, []int{0}}, {[]int{9, 9, 9, 9, 9, 9, 9}, []int{9, 9, 9, 9}, []int{8, 9, 9, 9, 0, 0, 0, 1}}, } passedAll := true testOnly := 0 for i, test := range tests { if testOnly != 0 && testOnly != i+1 { continue } nums1, nums2, nums3 := test.nums1, test.nums2, test.expected list1 := createList(nums1) list2 := createList(nums2) actual := addTwoNumbers(list1, list2) expected := createList(nums3) currA, currB := actual, expected broke := false for currA != nil && currB != nil { if currA.Val != currB.Val { passedAll = false printFailedTest(actual, expected, i) broke = true break } currA = currA.Next currB = currB.Next } if !broke { if currA != nil || currB != nil { passedAll = false printFailedTest(currA, currB, i) } } } if passedAll { fmt.Println("Passed all tests.") } }
import axios from "axios"; import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import PopularMovies from "../Movies/PopularMovies"; import Footer from "../Footer/Footer"; import TopRated from "./TopRated"; import NavDisplay from "../NavBar/NavDisplay"; import XO from "./XO.gif"; const Movies = () => { const Navigate = useNavigate(); const [Loader, setLoader] = useState(true); const [Movies, setMovies] = useState([]); const MovieData = async () => { setLoader(true); const { data } = await axios( `https://api.themoviedb.org/3/movie/popular?api_key=678c9b4411286f011b3e28f4eae6599e&language=en-US&page=1` ); setMovies(data.results); console.log(data.results); setLoader(false); }; useEffect(() => { MovieData(); }, []); return ( <div> <NavDisplay /> <div className="row"> <h2>NETFLIX ORIGINALS</h2> <div className="row1"> <div className="row2"> {Loader ? ( <div className="Loader"> <img src={XO} alt="" /> </div> ) : ( Movies.map((e, i) => ( <img key={i} onClick={() => Navigate(`/SingleMovie/${e.id}`)} src={` https://image.tmdb.org/t/p/w500${ e.poster_path || e.backdrop_path || e.profile_path || "/csU9xxVn8tVyhwx4rw96zse1xrU.jpg" }`} alt="" /> )) )} </div> </div> </div> </div> ); }; export default Movies;
hessian <- function(theta, grad, eps,...) { g<-grad n<-length(theta) hess<-matrix(nrow=n,ncol=n) h<-rep(0, 2) h[1] <- eps h[2] <- eps for (i in 1:n){ for (j in 1:n){ e_i=rep(0,n) e_i[i]=1 e_j=rep(0,n) e_j[j]=1 hess[i, j] = ((g(theta + eps*e_j,...)[i] - g(theta-eps*e_j,...)[i])/(4*eps) + ((g(theta+eps*e_i,...)[j] - g(theta-eps*e_i,...)[j])/(4*eps))) } } return(hess) } newt <- function(theta, func, grad, hess=NULL, ..., tol=1e-8, fscale=1, maxit=100, max.half=20,eps=1e-6) {#,max.half=20){ g <- grad(theta,...) if (is.null(hess)){ hess<-function(theta,...){hessian(theta,grad,eps,...)} } if(is.infinite(func(theta, ...))) stop('The objective function is not finite at the initial theta') if (all(is.finite(g))==FALSE) stop('The gradient is not finite at the initial theta') #for counting how many times we iterate Newton's method iterations<-0 #breaks when there is convergence while (length(g[abs(g) >= tol*(abs(func(theta))+fscale)]) > 0) { #ends the algorithm if we exceed the maximum number of iterations maxit if (iterations > maxit) stop("Iterations exceeded maxit ", maxit) #check if the hessian is positive definite. If it isn't, the we perturb it multiple<-1 H<-hess(theta,...) notPosDef <- FALSE while (inherits(try(chol(H), silent=TRUE), "try-error")) { notPosDef <- TRUE #perturb the hessian if it isn't positive definite H <- H + diag(length(theta))*(abs(min(eigen(H)$values))+1) multiple<-multiple+10 } #chol2inv(chol(H)) <-> solve(H) <-> H^-1 because H is positive definite Hi <- chol2inv(chol(H)) delta <- -Hi %*% grad(theta,...) #step-halving #we need to check that the function's value is actually being minimised counter <- 0 while(func(theta + delta,...) > func(theta,...) || is.infinite(func(theta, ...))) { if (counter >= max.half) { warning("Step halving fails to reduce the objective function despite trying max.half step halvings") } #halves the step size delta <- delta/2 #counts the number of step halvings counter <- counter + 1 } #update the value for theta theta <- theta + delta g <- grad(theta,...) iterations<-iterations+1 } if (notPosDef) warning("Hessian not positive definite at minimum, Hi is the inverse of the nearest positive definite Hessian") list(f=func(theta, ...), theta=theta, iter=iterations, g=grad(theta, ...), Hi=Hi) } #test case 1 rb <- function(th,k) { k*(th[2]-th[1]^2)^2 + (1-th[1])^2 } gb <- function(th,k) { c(-2*(1-th[1])-k*4*th[1]*(th[2]-th[1]^2),k*2*(th[2]-th[1]^2)) } hb <- function(th,k) { h <- matrix(0,2,2) h[1,1] <- 2-k*2*(2*(th[2]-th[1]^2) - 4*th[1]^2) h[2,2] <- 2*k h[1,2] <- h[2,1] <- -4*k*th[1] h } #Test case 2 dummy<-function(theta){ x<-theta[1];y<-theta[2] return((1.5-x+x*y)^2 + (2.25 - x + x*y^2)^2 + (2.625-x+x*y^3)^2) } dummy_grad<-function(theta){ return(grad(dummy,theta)) } dummy_hess<-function(theta){ return(hessian_csd(dummy,theta)) } findgradient<-function(theta){ trig.exp <- expression((1.5-x+x*y)^2 + (2.25 - x + x*y^2)^2 + (2.625-x+x*y^3)^2) ( dxy <- deriv(trig.exp, c("x", "y")) ) y <- theta[2] x<- theta[1] eval(dxy) } t80 <- 1:13 ## years since 1980 y1 <- c(12,14,33,50,67,74,123,141,165,204,253,246,240) ## AIDS cases nll <- function(theta) { ## -ve log likelihood for AIDS model y_i ~ Poi(alpha*exp(beta*t_i)) ## theta = (alpha,beta) mu <- theta[1] * exp(theta[2] * t80) ## mu = E(y) -sum(dpois(y1,mu,log=TRUE)) ## the negative log likelihood } ## nll gll <- function(theta) { ## grad of -ve log lik of Poisson AIDS early epidemic model alpha <- theta[1];beta <- theta[2] ## enhances readability ebt <- exp(beta*t80) ## avoid computing twice -c(sum(y1)/alpha - sum(ebt), ## -dl/dalpha sum(y1*t80) - alpha*sum(t80*ebt)) ## -dl/dbeta } ## gll newt(c(400,1),dummy,dummy_grad, maxit=500)
import React from 'react' // import ChatBot from 'react-simple-chatbot' import ChatBot from 'react-simple-chatbot' import { ThemeProvider } from 'styled-components'; const theme = { background: '#f5f8fb', fontFamily: 'Helvetica Neue', headerBgColor: 'black', headerFontColor: '#fff', headerFontSize: '15px', botBubbleColor: 'black', botFontColor: '#fff', userBubbleColor: '#fff', userFontColor: '#4a4a4a', }; export const Chatbot = () => { const steps = [ { id: '0', message: `Welcome`, trigger: '1', }, { id: '1', message: 'How can I help you', trigger: '2', }, { id: '2', options: [ { value: 1, label: 'Expense', trigger: '3' }, { value: 2, label: 'Income', trigger: '4' }, { value: 3, label: 'Investment', trigger: '5' }, ], }, { id: '3', message: 'Expense', end: true, }, { id: '4', message: 'Income', end: true, }, { id: '5', options: [ { value: 1, label: 'Types Of Investment', trigger: '6' }, ], }, { id: '6', message: "1)Stocks 2)Bonds 3)Mutual Funds 4)Real Estate 5)Commodities", trigger: '1' } ]; return ( <> <div> <ThemeProvider theme={theme}> <ChatBot steps={steps} headerTitle="ExpenseStreet" floating={true} /> </ThemeProvider> </div> </> ) }
document.addEventListener("DOMContentLoaded", () => { const cardArr = [ { name: "chesseburger", img: "images/cheeseburger.png", }, { name: "fries", img: "images/fries.png", }, { name: "hotdog", img: "images/hotdog.png", }, { name: "ice-cream", img: "images/ice-cream.png", }, { name: "milkshake", img: "images/milkshake.png", }, { name: "pizza", img: "images/pizza.png", }, { name: "chesseburger", img: "images/cheeseburger.png", }, { name: "fries", img: "images/fries.png", }, { name: "hotdog", img: "images/hotdog.png", }, { name: "ice-cream", img: "images/ice-cream.png", }, { name: "milkshake", img: "images/milkshake.png", }, { name: "pizza", img: "images/pizza.png", }, ]; cardArr.sort(() => 0.5 - Math.random()); // console.log(cardArr); let choosenCardName = []; let choosenCardId = []; let wonCards = 0; const conatinerEl = document.querySelector(".container"); const resultEl = document.querySelector('.result'); function createBoard() { for (let i = 0; i < cardArr.length; i++) { let card = document.createElement("img"); card.setAttribute("src", "images/blank.png"); card.setAttribute("data-id", i); // console.log(card); conatinerEl.appendChild(card); card.addEventListener("click", flipCard); } } function checkCardMatch() { let firstChoosenCard = choosenCardId[0]; let secondChoosenCard = choosenCardId[1]; let Cards = document.querySelectorAll(".container img"); // console.log(Cards); if (firstChoosenCard === secondChoosenCard) { alert("You have clicked the same image!"); Cards[firstChoosenCard].setAttribute("src", "images/blank.png"); Cards[secondChoosenCard].setAttribute("src", "images/blank.png"); } else if(choosenCardName[0] === choosenCardName[1]){ alert("You got a matching card!"); Cards[choosenCardId[0]].setAttribute('src', 'images/white.png'); Cards[choosenCardId[1]].setAttribute('src', 'images/white.png'); Cards[firstChoosenCard].removeEventListener('click', flipCard); Cards[secondChoosenCard].removeEventListener('click', flipCard); wonCards++; } else{ Cards[choosenCardId[0]].setAttribute('src', 'images/blank.png'); Cards[choosenCardId[1]].setAttribute('src', 'images/blank.png'); alert("Sorry try again"); } choosenCardId = []; choosenCardName = []; resultEl.textContent = wonCards; if(wonCards === cardArr.length/2){ resultEl.textContent = "Congratulation! you won"; } } function flipCard() { let cardId = this.getAttribute("data-id"); // console.log(cardId); choosenCardName.push(cardArr[cardId].name); // console.log(choosenCardName); choosenCardId.push(cardId); // console.log(choosenCardId); this.setAttribute("src", cardArr[cardId].img); if (choosenCardId.length === 2) { setTimeout(checkCardMatch, 100); } } createBoard(); });
import { render, screen, waitFor } from '@testing-library/react'; import { Input } from './Input'; describe('<Input />', () => { const getProps: any = () => ({ form: { touched: false, errors: {} }, field: { name: 'input', value: 'default', onBlur: vi.fn() }, label: 'Title', placeholder: 'Title', }); const input = <Input {...getProps()} />; it('renders <Input /> component', () => { const { getByTestId } = render(input); expect(getByTestId('input')).toBeInTheDocument(); }); it('should have correct label', () => { const { getByTestId } = render(input); expect(getByTestId('inputLabel')).toHaveTextContent('Title'); }); it('should have an initial value', () => { const { getByDisplayValue } = render(input); expect(getByDisplayValue('default')).toBeInTheDocument(); }); it('should show the password if togglePassword is enabled', async () => { const props = getProps(); props.togglePassword = true; props.type = 'password'; render(<Input {...props} />); await waitFor(() => { expect(screen.getByDisplayValue('default')).toBeInTheDocument(); }); }); it('should show translation if the value is passed', () => { const props = getProps(); props.translation = 'This is a translation'; render(<Input {...props} />); expect(screen.getByText('This is a translation')).toBeInTheDocument(); }); });
// https://randomnerdtutorials.com/esp32-web-server-slider-pwm/ // https://microcontrollerslab.com/esp32-multiple-sliders-websocket-web-server/ #include <EEPROM.h> #include <WiFi.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> #include <Arduino.h> // Replace with your network credentials const char* ssid = "NETGEAR56"; const char* password = "newcream317"; #define RightFrontFWD 27 #define RightFrontBWD 26 #define LeftFrontFWD 14 #define LeftFrontBWD 12 short LeftStartLevel = 100; short RightStartLevel = 104; int motorspeed = 64; String Serial0InputString = ""; // a String to hold incoming data bool Serial0InputComplete = false; // whether the string is complete char serialdata[3]; unsigned long LastOneSecTimeInMs; short LargePulseWidthInMs = 50; short LargeFulseSpeed = 100; short LargeFulseMaxCountPerHalfSec = 8; short PendingMoves_Left = 0; short PendingMoves_Right = 0; short RunStep_Left = 0; short RunStep_Right = 0; unsigned long DelayStartTimeInMs_Left; unsigned long DelayStartTimeInMs_Right; int PulseGapTimeInMs_Left; int PulseGapTimeInMs_Right; void ReadSettingFromEEPROM() { LeftStartLevel = EEPROM.readShort(0); RightStartLevel = EEPROM.readShort(4); LargePulseWidthInMs = EEPROM.readShort(8); LargeFulseSpeed = EEPROM.readShort(12); // PWM duty cycle LargeFulseMaxCountPerHalfSec = EEPROM.readShort(16); // if ( LargePulseWidthInMs < 0 ) LargePulseWidthInMs = 0; if ( LargeFulseSpeed < 0 ) LargeFulseSpeed = 0; if ( LargeFulseMaxCountPerHalfSec < 0 ) LargeFulseMaxCountPerHalfSec = 0; if ( LargePulseWidthInMs > 200 ) LargePulseWidthInMs = 200; if ( LargeFulseSpeed > 200 ) LargeFulseSpeed = 200; if ( LargeFulseMaxCountPerHalfSec > 20 ) LargeFulseMaxCountPerHalfSec = 20; } void DisplaySettings() { Serial.print("LeftStartLevel: "); Serial.println(LeftStartLevel); Serial.print("RightStartLevel: "); Serial.println(RightStartLevel); Serial.print("LargePulseWidthInMs: "); Serial.println(LargePulseWidthInMs); Serial.print("LargeFulseSpeed: "); Serial.println(LargeFulseSpeed); Serial.print("LargeFulseMaxCountPerHalfSec: "); Serial.println(LargeFulseMaxCountPerHalfSec); } String sliderValue = "0"; const char* PARAM_INPUT = "value"; const char* PARAM_SW = "sw"; // Create AsyncWebServer object on port 80 AsyncWebServer server(80); const char index_html[] PROGMEM = R"rawliteral( <!DOCTYPE HTML><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ESP Web Server</title> <style> html {font-family: Arial; display: inline-block; text-align: center;} h2 {font-size: 2.3rem;} p {font-size: 1.9rem;} body {max-width: 400px; margin:0px auto; padding-bottom: 25px;} .slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C; outline: none; -webkit-transition: .2s; transition: opacity .2s;} .slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px; background: #003249; cursor: pointer;} .slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; } </style> </head> <body> <h2>Pulse Width</h2> <p><span id="textSliderValue1">%SLIDERVALUE1%</span></p> <p><input type="range" onchange="updateSliderPWM(this, 1)" id="pwmSlider1" min="0" max="200" value="%SLIDERVALUE1%" step="1" class="slider"></p> <h2>PWM Duty</h2> <p><span id="textSliderValue2">%SLIDERVALUE2%</span></p> <p><input type="range" onchange="updateSliderPWM(this, 2)" id="pwmSlider2" min="0" max="200" value="%SLIDERVALUE2%" step="1" class="slider"></p> <h2>Repeats</h2> <p><span id="textSliderValue3">%SLIDERVALUE3%</span></p> <p><input type="range" onchange="updateSliderPWM(this, 3)" id="pwmSlider3" min="0" max="20" value="%SLIDERVALUE3%" step="1" class="slider"></p> <script> function updateSliderPWM(element, id) { var sliderValue = document.getElementById("pwmSlider" + id).value; document.getElementById("textSliderValue" + id).innerHTML = sliderValue; console.log(sliderValue); var xhr = new XMLHttpRequest(); xhr.open("GET", "/slider?sw=" + id + "&value="+sliderValue, true); xhr.send(); } </script> </body> </html> )rawliteral"; // Replaces placeholder with button section in your web page String processor(const String& var){ //Serial.println(var); if (var == "SLIDERVALUE1"){ return String(LargePulseWidthInMs); } if (var == "SLIDERVALUE2"){ return String(LargeFulseSpeed); } if (var == "SLIDERVALUE3"){ return String(LargeFulseMaxCountPerHalfSec); } return String(); } void setup(){ EEPROM.begin(100); pinMode(RightFrontFWD, OUTPUT); pinMode(RightFrontBWD, OUTPUT); pinMode(LeftFrontFWD, OUTPUT); pinMode(LeftFrontBWD, OUTPUT); // put your setup code here, to run once: Serial.begin(115200); // make sure your Serial Monitor is also set at this baud rate. ReadSettingFromEEPROM(); DisplaySettings(); serialdata[2] = '\0'; LastOneSecTimeInMs = millis(); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP Local IP Address Serial.println(WiFi.localIP()); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); // Send a GET request to <ESP_IP>/slider?value=<inputMessage> server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) { String inputMessage; String swMessage; // GET input1 value on <ESP_IP>/slider?value=<inputMessage> if (request->hasParam(PARAM_INPUT)) { inputMessage = request->getParam(PARAM_INPUT)->value(); swMessage = request->getParam(PARAM_SW)->value(); sliderValue = inputMessage; if ( swMessage == "1" ) { LargePulseWidthInMs = sliderValue.toInt(); EEPROM.writeShort(8, LargePulseWidthInMs); EEPROM.commit(); // Serial.print("Set LargePulseWidthInMs to "); Serial.println(LargePulseWidthInMs); // Serial.print("Verify LargePulseWidthInMs is "); Serial.println(EEPROM.readShort(8)); } if ( swMessage == "2" ) { LargeFulseSpeed = sliderValue.toInt(); EEPROM.writeShort(12, LargeFulseSpeed); EEPROM.commit(); // Serial.print("Set LargeFulseSpeed to "); Serial.println(LargeFulseSpeed); // Serial.print("Verify LargeFulseSpeed is "); Serial.println(EEPROM.readShort(12)); } if ( swMessage == "3" ) { LargeFulseMaxCountPerHalfSec = sliderValue.toInt(); EEPROM.writeShort(16, LargeFulseMaxCountPerHalfSec); EEPROM.commit(); // Serial.print("Set LargeFulseMaxCountPerHalfSec to "); Serial.println(LargeFulseMaxCountPerHalfSec); // Serial.print("Verify LargeFulseMaxCountPerHalfSec is "); Serial.println(EEPROM.readShort(16)); } } else { inputMessage = "No message sent"; } Serial.println(inputMessage); request->send(200, "text/plain", "OK"); }); // Start server server.begin(); } void loop() { unsigned long NowInMs = millis(); short tmpShort; if ( NowInMs - LastOneSecTimeInMs > 1000 ) { LastOneSecTimeInMs = NowInMs; // Serial.print("L: Stp="); Serial.print(RunStep_Left); // Serial.print(" Cnt="); Serial.print(PendingMoves_Left); // Serial.print(" A="); Serial.print(NowInMs - DelayStartTimeInMs_Left); // Serial.print(" B="); Serial.println(PulseGapTimeInMs_Left); // Serial.print("R: Stp="); Serial.print(RunStep_Right); // Serial.print(" Cnt="); Serial.print(PendingMoves_Right); // Serial.print(" A="); Serial.print(NowInMs - DelayStartTimeInMs_Right); // Serial.print(" B="); Serial.println(PulseGapTimeInMs_Right); } switch( RunStep_Left ) { case 0: // Idle if ( PendingMoves_Left != 0 ) { RunStep_Left = 1; // Start the pulse DelayStartTimeInMs_Left = NowInMs; moveLeft(LargeFulseSpeed, PendingMoves_Left); if ( abs(PendingMoves_Left) > LargeFulseMaxCountPerHalfSec ) tmpShort = LargeFulseMaxCountPerHalfSec; else tmpShort = abs(PendingMoves_Left); PulseGapTimeInMs_Left = (500-10) / tmpShort - LargePulseWidthInMs; // Serial.print("L: 0=>1 Cnt="); Serial.print(PendingMoves_Left); } break; case 1: // Wait for the pulse to stop if ( NowInMs - DelayStartTimeInMs_Left > LargePulseWidthInMs ) { RunStep_Left = 2; // Start the idle wait gap DelayStartTimeInMs_Left = NowInMs; moveLeft(0, 0); if (PendingMoves_Left>0) PendingMoves_Left--; else PendingMoves_Left++; // Serial.print("L: 1=>2 Cnt="); Serial.println(PendingMoves_Left); } break; case 2: // Wait for the wait gap to pass if ( NowInMs - DelayStartTimeInMs_Left > PulseGapTimeInMs_Left ) { if ( PendingMoves_Left != 0 ) { RunStep_Left = 1; // Start the pulse DelayStartTimeInMs_Left = NowInMs; moveLeft(LargeFulseSpeed, PendingMoves_Left); } else { RunStep_Left = 0; } // Serial.print("L: 2=>"); Serial.print(RunStep_Left); // Serial.print(", Cnt="); Serial.println(PendingMoves_Left); } break; } switch( RunStep_Right ) { case 0: // Idle if ( PendingMoves_Right != 0 ) { RunStep_Right = 1; // Start the pulse DelayStartTimeInMs_Right = NowInMs; moveRight(LargeFulseSpeed, PendingMoves_Right); if ( abs(PendingMoves_Right) > LargeFulseMaxCountPerHalfSec ) tmpShort = LargeFulseMaxCountPerHalfSec; else tmpShort = abs(PendingMoves_Right); PulseGapTimeInMs_Right = (500-10) / tmpShort - LargePulseWidthInMs; // Serial.print("R: 0=>1 Cnt="); Serial.print(PendingMoves_Right); } break; case 1: // Wait for the pulse to stop if ( NowInMs - DelayStartTimeInMs_Right > LargePulseWidthInMs ) { RunStep_Right = 2; // Start the idle wait gap DelayStartTimeInMs_Right = NowInMs; moveRight(0, 0); if (PendingMoves_Right>0) PendingMoves_Right--; else PendingMoves_Right++; // Serial.print("R: 1=>2 Cnt="); Serial.println(PendingMoves_Right); } break; case 2: // Wait for the wait gap to pass if ( NowInMs - DelayStartTimeInMs_Right > PulseGapTimeInMs_Right ) { if ( PendingMoves_Right != 0 ) { RunStep_Right = 1; // Start the pulse DelayStartTimeInMs_Right = NowInMs; moveRight(LargeFulseSpeed, PendingMoves_Right); } else { RunStep_Right = 0; } // Serial.print("R: 2=>"); Serial.print(RunStep_Right); // Serial.print(", Cnt="); Serial.println(PendingMoves_Right); } break; } ReadSerial0CommandInput(); /* Serial.print('\t'); int a = GamePad.getAngle(); Serial.print("Angle: "); Serial.print(a); Serial.print('\t'); int b = GamePad.getRadius(); Serial.print("Radius: "); Serial.print(b); Serial.print('\t'); float c = GamePad.getXaxisData(); Serial.print("x_axis: "); Serial.print(c); Serial.print('\t'); float d = GamePad.getYaxisData(); Serial.print("y_axis: "); Serial.println(d); Serial.println(); */ } void moveLeft(short myMotorSpeed, short Direction) { if ( Direction > 0 ) { analogWrite(LeftFrontFWD, myMotorSpeed); analogWrite(LeftFrontBWD, 0); } else if ( Direction < 0 ) { analogWrite(LeftFrontFWD, 0); analogWrite(LeftFrontBWD, myMotorSpeed); } else { analogWrite(LeftFrontBWD, 0); analogWrite(LeftFrontFWD, 0); } } void moveRight(short myMotorSpeed, short Direction ) { if ( Direction > 0 ) { analogWrite(RightFrontFWD, myMotorSpeed); analogWrite(RightFrontBWD, 0); } else if ( Direction < 0 ) { analogWrite(RightFrontFWD, 0); analogWrite(RightFrontBWD, myMotorSpeed); } else { analogWrite(RightFrontBWD, 0); analogWrite(RightFrontFWD, 0); } } void moveForward(short myMotorSpeed) { analogWrite(RightFrontFWD, myMotorSpeed); analogWrite(RightFrontBWD, 0); analogWrite(LeftFrontFWD, myMotorSpeed); analogWrite(LeftFrontBWD, 0); } void moveBackward() { analogWrite(RightFrontFWD, 0); analogWrite(RightFrontBWD, motorspeed); analogWrite(LeftFrontFWD, 0); analogWrite(LeftFrontBWD, motorspeed); } void rotateRight() { analogWrite(RightFrontFWD, 0); analogWrite(RightFrontBWD, motorspeed); analogWrite(LeftFrontFWD, motorspeed); analogWrite(LeftFrontBWD, 0); } void rotateLeft() { analogWrite(RightFrontFWD, motorspeed); analogWrite(RightFrontBWD, 0); analogWrite(LeftFrontFWD, 0); analogWrite(LeftFrontBWD, motorspeed); } void stopMoving() { analogWrite(RightFrontFWD, 0); analogWrite(RightFrontBWD, 0); analogWrite(LeftFrontFWD, 0); analogWrite(LeftFrontBWD, 0); } void ReadSerial0CommandInput(){ while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // Serial.print(inChar, HEX); // digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // turn the LED on (HIGH is the voltage level) // add it to the inputString: Serial0InputString += inChar; // if the incoming character is a newline, set a flag so the main loop can // do something about it: if (inChar == '\n' || inChar == 0x0A) { Serial0InputComplete = true; // Serial.print("A:"); // Serial.print(Serial0InputString); } } if ( Serial0InputComplete ) { Serial0InputComplete = false; int inputlen = Serial0InputString.length(); char c1 = Serial0InputString[0]; char c2; String strValue; switch ( c1 ) { case 'S': if ( inputlen <= 2 ) { Serial0InputString = ""; return; } c2 = Serial0InputString[1]; strValue = Serial0InputString.substring(2, inputlen); switch ( c2 ) { case 'a': LeftStartLevel = strValue.toInt(); EEPROM.writeShort(0, LeftStartLevel); EEPROM.commit(); Serial.print("Set LeftStartLevel to "); Serial.println(LeftStartLevel); Serial.print("Verify LeftStartLevel is "); Serial.println(EEPROM.readShort(0)); break; case 'b': RightStartLevel = strValue.toInt(); EEPROM.writeShort(4, RightStartLevel); EEPROM.commit(); Serial.print("Set RightStartLevel to "); Serial.println(RightStartLevel); Serial.print("Verify RightStartLevel is "); Serial.println(EEPROM.readShort(4)); break; case 'c': LargePulseWidthInMs = strValue.toInt(); EEPROM.writeShort(8, LargePulseWidthInMs); EEPROM.commit(); Serial.print("Set LargePulseWidthInMs to "); Serial.println(LargePulseWidthInMs); Serial.print("Verify LargePulseWidthInMs is "); Serial.println(EEPROM.readShort(8)); break; case 'd': LargeFulseSpeed = strValue.toInt(); EEPROM.writeShort(12, LargeFulseSpeed); EEPROM.commit(); Serial.print("Set LargeFulseSpeed to "); Serial.println(LargeFulseSpeed); Serial.print("Verify LargeFulseSpeed is "); Serial.println(EEPROM.readShort(12)); break; } break; case 'D': if ( inputlen <= 4 ) { Serial0InputString = ""; return; } serialdata[0] = Serial0InputString[1]; serialdata[1] = Serial0InputString[2]; short valLeft = (short) strtol(serialdata, 0, 16) - 128; serialdata[0] = Serial0InputString[3]; serialdata[1] = Serial0InputString[4]; short valRight = (short) strtol(serialdata, 0, 16) - 128; PendingMoves_Left = valLeft; PendingMoves_Right = valRight; /* if ( valLeft < 127 ) { valLeft = 128 - valLeft + LeftStartLevel; if ( valLeft > 255 ) valLeft = 255; if ( valLeft < 0 ) valLeft = 0; analogWrite(LeftFrontFWD, 0); analogWrite(LeftFrontBWD, valLeft); } else if ( valLeft > 129 ) { valLeft = valLeft - 128 + LeftStartLevel; if ( valLeft > 255 ) valLeft = 255; if ( valLeft < 0 ) valLeft = 0; analogWrite(LeftFrontFWD, valLeft); analogWrite(LeftFrontBWD, 0); } else { analogWrite(LeftFrontFWD, 0); analogWrite(LeftFrontBWD, 0); } if ( valRight < 127 ) { valRight = 128 - valRight + RightStartLevel; if ( valRight > 255 ) valRight = 255; if ( valRight < 0 ) valRight = 0; analogWrite(RightFrontFWD, 0); analogWrite(RightFrontBWD, valRight); } else if ( valRight > 129 ) { valRight = valRight - 128 + RightStartLevel; if ( valRight > 255 ) valRight = 255; if ( valRight < 0 ) valRight = 0; analogWrite(RightFrontFWD, valRight); analogWrite(RightFrontBWD, 0); } else { analogWrite(RightFrontFWD, 0); analogWrite(RightFrontBWD, 0); } */ break; } Serial0InputString = ""; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://cdn.jsdelivr.net/npm/emailjs-com@2.6.4/dist/email.min.js"></script> <script src="https://cdn.emailjs.com/sdk/2.3.2/email.min.js"></script> <link rel="stylesheet" href="../css/style.css" /> <title>This is Luke - Blog</title> </head> <body> <header> <h1>Welcome to My Blog</h1> </header> <main> <!-- article section --> <section> <h2 id="article1-title"> The Controversial Shift: Why a 4-Day Work Week and 6-Hour Work Day is the Future of Productivity </h2> <img src="../articles/article-images/6hourworkday-image1.jpg" alt="Article 1 Image" class="article-image" /> <p>In todays forever changing landscape the next leap in respect for humanity is a shift in work times</p> <button class="like-btn"> Likes <span class="like-count">10124</span> </button> <button class="save-btn">Save</button> <button class="comments-btn">Comments</button> <a href="../articles/6hourWorkDay.html" class="view-full-article-btn" data-article-id="1"> View Full Article </a> </section> <section> <h2 id="article2-title">Embracing the Future: Why Coding Interviews Should Include AI and Allow Tooling</h2> <img src="../articles/article-images/aiincoding-wide.jpg" alt="Article 2 Image" class="article-image" /> <p>Its high time that interviews should include the use of advanced AI prompting to compile code as this is the future</p> <p id="article2-text" class="hidden"> Full content of Article 2... </p> <button class="like-btn"> Likes <span class="like-count">9322</span> </button> <button class="save-btn">Save</button> <button class="comments-btn">Comments</button> <a href="../articles/aiincodinginterviews.html" class="view-full-article-btn" data-article-id="1"> View Full Article </a> </section> <section> <h2 id="article3-title">Spelling the word "cat" wrong</h2> <img src="../articles/article-images/cat.jpg" alt="Article 3 Image" class="article-image" /> <p>Our Education System Will Mark the Spelling of "Cat" Wrong if you Would Spell it "Kat" or "Xqw" as Equally Incorrect.</p> <p id="article3-text" class="hidden"> Full content of Article 3... </p> <button class="like-btn"> Likes <span class="like-count">0</span> </button> <button class="save-btn">Save</button> <button class="comments-btn">Comments</button> <a href="../articles/spellingcat.html" class="view-full-article-btn" data-article-id="1"> View Full Article </a> </section> <section> <h2 id="article4-title">Our Education Systems Need a Drastic Overhaul Thanks to AI</h2> <img src="../articles/article-images/education.jpg" alt="Article 1 Image" class="article-image" /> <p>In the rapidly evolving world approaching singularity we must look to our old systems and rapidly ulter the education system</p> <p id="article4-text" class="hidden"> Full content of Article 4... </p> <button class="like-btn"> Likes <span class="like-count">0</span> </button> <button class="save-btn">Save</button> <button class="comments-btn">Comments</button> <a href="../articles/aieducation.html" class="view-full-article-btn" data-article-id="1"> View Full Article </a> </section> </main> <!-- comments modal --> <div class="comments-modal"> <div class="comments-modal-content"> <span class="comments-close-button">×</span> <h1>Comments</h1> <form class="comment-form"> <label for="comment-input">Leave a comment:</label> <textarea name="comment-input" class="comment-input" rows="5" ></textarea> <button type="submit">Submit</button> </form> <div class="comments"></div> </div> </div> <!-- show saved articles modal --> <button class="trigger">Show saved articles</button> <div class="modal"> <div class="modal-content"> <span class="close-button">×</span> <h1>Saved Articles</h1> <h2> Total saved Articles: <span class="saved-articles-count">0</span> </h2> <ul class="saved-articles-list"></ul> </div> </div> <!-- contact me modal --> <button id="contactModalBtn">Contact Me</button> <div id="contactModal" style="display: none"> <div class="modal-content"> <span class="close">&times;</span> <form id="contactForm"> <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <br /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <br /> <label for="message">Message:</label> <textarea id="message" name="message" required></textarea> <br /> <input type="submit" value="Send" /> </form> </div> </div> <script type="module" src="../js/main.js"></script> </body> </html>
This homework lets you explore some real code that uses locks and condition variables to implement various forms of the producer/consumer queue discussed in the chapter. You'll look at the real code, run it in various configurations, and use it to learn about what works and what doesn't, as well as other intricacies. The different versions of the code correspond to different ways to "solve" the producer/consumer problem. Most are incorrect; one is correct. Read the chapter to learn more about what the producer/consumer problem is, and what the code generally does. The first step is to download the code and type make to build all the variants. You should see four: - main-one-cv-while.c: The producer/consumer problem solved with a single condition variable. - main-two-cvs-if.c: Same but with two condition variables and using an if to check whether to sleep. - main-two-cvs-while.c: Same but with two condition variables and while to check whether to sleep. This is the correct version. - main-two-cvs-while-extra-unlock.c: Same but releasing the lock and then reacquiring it around the fill and get routines. It's also useful to look at pc-header.h which contains common code for all of these different main programs, and the Makefile so as to build the code properly. Each program takes the following flags: -l <number of items each producer produces> -m <size of the shared producer/consumer buffer> -p <number of producers> -c <number of consumers> -P <sleep string: how producer should sleep at various points> -C <sleep string: how consumer should sleep at various points> -v [verbose flag: trace what is happening and print it] -t [timing flag: time entire execution and print total time] The first four arguments are relatively self-explanatory: -l specifies how many times each producer should loop (and thus how many data items each producer produces), -m controls the size of the shared buffer (greater than or equal to one), and -p and -c set how many producers and consumers there are, respectively. What is more interesting are the two sleep strings, one for producers, and one for consumers. These flags allow you to make each thread sleep at certain points in an execution and thus switch to other threads; doing so allows you to play with each solution and perhaps pinpoint specific problems or study other facets of the producer/consumer problem. The string is specified as follows. If there are three producers, for example, the string should specify sleep times for each producer separately, with a colon separator. The sleep string for these three producers would look something like this: sleep_string_for_p0:sleep_string_for_p1:sleep_string_for_p2 Each sleep string, in turn, is a comma-separated list, which is used to decide how much to sleep at each sleep point in the code. To understand this per-producer or per-consumer sleep string better, let's look at the code in main-two-cvs-while.c, specifically at the producer code. In this code snippet, a producer thread loops for a while, putting elements into the shared buffer via calls to do\_fill(). Around this filling routine are some waiting and signaling code to ensure the buffer is not full when the producer tries to fill it. See the chapter for more details. void *producer(void *arg) { int id = (int) arg; int i; for (i = 0; i < loops; i++) { p0; Mutex_lock(&m); p1; while (num_full == max) { p2; Cond_wait(&empty, &m); p3; } do_fill(i); p4; Cond_signal(&fill); p5; Mutex_unlock(&m); p6; } return NULL; } As you can see from the code, there are a number of points labeled p0, p1, etc. These points are where the code can be put to sleep. The consumer code (not shown here) has similar wait points (c0, etc.). Specifying a sleep string for a producer is easy: just identify how long the producer should sleep at each point p0, p1, ..., p6. For example, the string 1,0,0,0,0,0,0 specifies that the producer should sleep for 1 second at marker p0 (before grabbing the lock), and then not at all each time through the loop. Now let's show the output of running one of these programs. To begin, let's assume that the user runs with just one producer and one consumer. Let's not add any sleeping at all (this is the default behavior). The buffer size, in this example, is set to 2 (-m 2). First, let's build the code: prompt> make gcc -o main-two-cvs-while main-two-cvs-while.c -Wall -pthread gcc -o main-two-cvs-if main-two-cvs-if.c -Wall -pthread gcc -o main-one-cv-while main-one-cv-while.c -Wall -pthread gcc -o main-two-cvs-while-extra-unlock main-two-cvs-while-extra-unlock.c -Wall -pthread Now we can run something: prompt> ./main-two-cvs-while -l 3 -m 2 -p 1 -c 1 -v In this case, if you trace the code (with the verbose flag, -v), you will get the following output (or something like it) on the screen: NF P0 C0 0 [*--- --- ] p0 0 [*--- --- ] c0 0 [*--- --- ] p1 1 [u 0 f--- ] p4 1 [u 0 f--- ] p5 1 [u 0 f--- ] p6 1 [u 0 f--- ] p0 1 [u 0 f--- ] c1 0 [ --- *--- ] c4 0 [ --- *--- ] c5 0 [ --- *--- ] c6 0 [ --- *--- ] c0 0 [ --- *--- ] p1 1 [f--- u 1 ] p4 1 [f--- u 1 ] p5 1 [f--- u 1 ] p6 1 [f--- u 1 ] p0 1 [f--- u 1 ] c1 0 [*--- --- ] c4 0 [*--- --- ] c5 0 [*--- --- ] c6 0 [*--- --- ] c0 0 [*--- --- ] p1 1 [u 2 f--- ] p4 1 [u 2 f--- ] p5 1 [u 2 f--- ] p6 1 [u 2 f--- ] c1 0 [ --- *--- ] c4 0 [ --- *--- ] c5 0 [ --- *--- ] c6 1 [f--- uEOS ] [main: added end-of-stream marker] 1 [f--- uEOS ] c0 1 [f--- uEOS ] c1 0 [*--- --- ] c4 0 [*--- --- ] c5 0 [*--- --- ] c6 Consumer consumption: C0 -> 3 Before describing what is happening in this simple example, let's understand the depiction of the shared buffer in the output, as is shown on the left. At first it is empty (an empty slot indicated by ---, and the two empty slots shown as [*--- --- ]); the output also shows the number of entries in the buffer (num\_full), which starts at 0. Then, after P0 puts a value in it, its state changes to [u 0 f--- ] (and num\_full changes to 1). You might also notice a few additional markers here; the u marker shows where the use\_ptr is (this is where the next consumer to consume a value will get something from); similarly, the f marker shows where the fill\_ptr is (this is where the next producer will produce a value). When you see the * marker, it just means the use\_ptr and fill\_ptr are pointing to the same slot. Along the right you can see the trace of which step each producer and consumer is about to execute. For example, the producer grabs the lock (p1), and then, because the buffer has an empty slot, produces a value into it (p4). It then continues until the point where it releases the lock (p6) and then tries to reacquire it. In this example, the consumer acquires the lock instead and consumes the value (c1, c4). Study the trace further to understand how the producer/consumer solution works with a single producer and consumer. Now let's add some pauses to change the behavior of the trace. In this case, let's say we want to make the producer sleep so that the consumer can run first. We can accomplish this as follows: prompt> ./main-two-cvs-while -l 1 -m 2 -p 1 -c 1 -P 1,0,0,0,0,0,0 -C 0 -v The results: NF P0 C0 0 [*--- --- ] p0 0 [*--- --- ] c0 0 [*--- --- ] c1 0 [*--- --- ] c2 0 [*--- --- ] p1 1 [u 0 f--- ] p4 1 [u 0 f--- ] p5 1 [u 0 f--- ] p6 1 [u 0 f--- ] p0 1 [u 0 f--- ] c3 0 [ --- *--- ] c4 0 [ --- *--- ] c5 0 [ --- *--- ] c6 0 [ --- *--- ] c0 0 [ --- *--- ] c1 0 [ --- *--- ] c2 ... As you can see, the producer hits the p0 marker in the code and then grabs the first value from its sleep specification, which in this case is 1, and thus each sleeps for 1 second before even trying to grab the lock. Thus, the consumer gets to run, grabs the lock, but finds the queue empty, and thus sleeps (releasing the lock). The producer then runs (eventually), and all proceeds as you might expect. Do note: a sleep specification must be given for each producer and consumer. Thus, if you create two producers and three consumers (with -p 2 -c 3, you must specify sleep strings for each (e.g., -P 0:1 or -C 0,1,2:0:3,3,3,1,1,1). Sleep strings can be shorter than the number of sleep points in the code; the remaining sleep slots are initialized to be zero. ____________________________QUESTIONS___________________________- Question 1: - do_fill() -> Checkt ob der BUffer nicht leer ist, wenn er leer ist, wird er mit dem Parameter gefüllt und der Buffergröße erhöht - do_get() -> Checkt ob der Buffer nicht leer ist, wenn ja, dann wird er auf empty gesetzt und der Parameter zurückgegeben - producer() -> Loopt für eine gewisse Anzahl und produziert mit do_fill() neue Einträge, jedoch nur, wenn nicht der consumer das Lock hat und der Buffer nicht bei MAX ist - consumer() -> Loopt bis END_OF_STREAM und konsumiert mit do_get die Buffer Einträge, jedoch nur, wenn nicht der producer das Lock hat oder der Buffer leer ist Question 2: ./main-two-cvs-while -l 5 -m 1 -p 1 -c 1 -v -t NF P0 C0 0 [*--- ] p0 0 [*--- ] c0 0 [*--- ] p1 1 [* 0 ] p4 1 [* 0 ] p5 1 [* 0 ] p6 1 [* 0 ] p0 1 [* 0 ] p1 1 [* 0 ] p2 1 [* 0 ] c1 0 [*--- ] c4 0 [*--- ] c5 0 [*--- ] c6 0 [*--- ] c0 0 [*--- ] c1 0 [*--- ] c2 0 [*--- ] p3 1 [* 1 ] p4 1 [* 1 ] p5 1 [* 1 ] p6 1 [* 1 ] p0 1 [* 1 ] c3 0 [*--- ] c4 0 [*--- ] c5 0 [*--- ] c6 0 [*--- ] c0 0 [*--- ] c1 0 [*--- ] c2 0 [*--- ] p1 1 [* 2 ] p4 1 [* 2 ] p5 1 [* 2 ] p6 1 [* 2 ] p0 1 [* 2 ] p1 1 [* 2 ] p2 1 [* 2 ] c3 0 [*--- ] c4 0 [*--- ] c5 0 [*--- ] c6 0 [*--- ] c0 0 [*--- ] c1 0 [*--- ] c2 0 [*--- ] p3 1 [* 3 ] p4 1 [* 3 ] p5 1 [* 3 ] p6 1 [* 3 ] p0 1 [* 3 ] p1 1 [* 3 ] p2 1 [* 3 ] c3 0 [*--- ] c4 0 [*--- ] c5 0 [*--- ] c6 0 [*--- ] c0 0 [*--- ] p3 1 [* 4 ] p4 1 [* 4 ] p5 1 [* 4 ] p6 1 [* 4 ] c1 0 [*--- ] c4 0 [*--- ] c5 0 [*--- ] c6 0 [*--- ] c0 0 [*--- ] c1 0 [*--- ] c2 1 [*EOS ] [main: added end-of-stream marker] 1 [*EOS ] c3 0 [*--- ] c4 0 [*--- ] c5 0 [*--- ] c6 Consumer consumption: C0 -> 5 Total time: 0.00 seconds ./main-two-cvs-while -l 5 -m 4 -p 1 -c 1 -v -t NF P0 C0 0 [*--- --- --- --- ] p0 0 [*--- --- --- --- ] c0 0 [*--- --- --- --- ] p1 1 [u 0 f--- --- --- ] p4 1 [u 0 f--- --- --- ] p5 1 [u 0 f--- --- --- ] p6 1 [u 0 f--- --- --- ] p0 1 [u 0 f--- --- --- ] p1 2 [u 0 1 f--- --- ] p4 2 [u 0 1 f--- --- ] p5 2 [u 0 1 f--- --- ] p6 2 [u 0 1 f--- --- ] p0 2 [u 0 1 f--- --- ] c1 1 [ --- u 1 f--- --- ] c4 1 [ --- u 1 f--- --- ] c5 1 [ --- u 1 f--- --- ] c6 1 [ --- u 1 f--- --- ] c0 1 [ --- u 1 f--- --- ] c1 0 [ --- --- *--- --- ] c4 0 [ --- --- *--- --- ] c5 0 [ --- --- *--- --- ] c6 0 [ --- --- *--- --- ] c0 0 [ --- --- *--- --- ] p1 1 [ --- --- u 2 f--- ] p4 1 [ --- --- u 2 f--- ] p5 1 [ --- --- u 2 f--- ] p6 1 [ --- --- u 2 f--- ] p0 1 [ --- --- u 2 f--- ] p1 2 [f--- --- u 2 3 ] p4 2 [f--- --- u 2 3 ] p5 2 [f--- --- u 2 3 ] p6 2 [f--- --- u 2 3 ] p0 2 [f--- --- u 2 3 ] c1 1 [f--- --- --- u 3 ] c4 1 [f--- --- --- u 3 ] c5 1 [f--- --- --- u 3 ] c6 1 [f--- --- --- u 3 ] c0 1 [f--- --- --- u 3 ] c1 0 [*--- --- --- --- ] c4 0 [*--- --- --- --- ] c5 0 [*--- --- --- --- ] c6 0 [*--- --- --- --- ] c0 0 [*--- --- --- --- ] p1 1 [u 4 f--- --- --- ] p4 1 [u 4 f--- --- --- ] p5 1 [u 4 f--- --- --- ] p6 1 [u 4 f--- --- --- ] c1 0 [ --- *--- --- --- ] c4 0 [ --- *--- --- --- ] c5 0 [ --- *--- --- --- ] c6 1 [ --- uEOS f--- --- ] c0 1 [ --- uEOS f--- --- ] [main: added end-of-stream marker] 1 [ --- uEOS f--- --- ] c1 0 [ --- --- *--- --- ] c4 0 [ --- --- *--- --- ] c5 0 [ --- --- *--- --- ] c6 Consumer consumption: C0 -> 5 Total time: 0.00 seconds -> Mit einem Größeren Buffer kommt öfters auch der Producer mehrmals dran -> 2 Einträge auf einmal -> Eine kleine geringere Code-Zeilen Menge -> Jedoch ist nicht ein sehr großer Unterschied erkennbar NUM_FULL: Different Buffer Sizes: - Nie komplett voll, könnte aber theoretisch sein, wenn der Producer 10 Einträge hat und die alle sofort reinschreibt -> Die Wahrscheinlichkeit ist aber hoch, das dabei ein Consumer eingeschaltet wird, der diese Einträge wieder runternimmt -> Schwer vorherzusagen was passiert Number of Prduced Items: - Mit 100 Einträgen pro Producer ist die Wahrscheinlichkeit hoch, dass auch der Buffer mal voll ist -> 9 Einträge -> Sind relativ viele Einträge und 1 Consumer kann nicht sehr effizient alle EInträge behandeln Sleep String: - Mit diesem Sleep String wird der Buffer komplett voll geschrieben, und dann erst danach wird immer wieder der Consumer eingeschalten um 1 Eintrag zu konsumieren -> Jedoch wird sofort danach wieder 1 Eintrag nachgelegt -> Hierbei wird zu wenig konsumiert (Sleeped) was zur folge hat, dass das Program sehr lange läuft -> Total time: 101.24 seconds Question 3: - ./main-two-cvs-while -l 100 -m 10 -p 1 -c 1 -v -t -> Bei diesem Beispiel ist ein kleiner Unterschied zwischen Mac und Linux: -> Bei Mac wird hierbei der Buffer von Zeit zu Zeit relativ groß gefüllt, wobei bei Linux immer der Buffer meistens zwischen 0 und 1 wechselt, da sofort nach einem Producer der Consumer kommt Question 4: - Da der Consumer 1s wartet bei c3 dauert es bei 10 Einträgen ungefähr bisschen mehr als 10 Sekunden (End-Of-Stream Time, etc.) Consumer consumption: C0 -> 5 C1 -> 2 C2 -> 3 Total time: 11.02 seconds Question 5: - Da sich die Zeit nicht verändert sondern nur der Buffer ändert es sich nichts im VErgleich zu Aufgabe 4 -> Da der Consumer 1s wartet und immer nur 1 Consumer drann ist, ändert es sich nichts an der Zeit -> Auch wenn der Buffer voller wird und der Producer möglicherweise mehr als 1 Item reinschreiben kann ändert sich in dem Fall nichts Question 6: - Müsste schneller gehen, da die Stelle an dem der Consumer schlafen gelegt wird, nicht die anderen Consumer auch verhindert -> Der Consumer gibt das Lock frei und während der Consumer schläft, können andere Threads, dieses lock acquiren und damit dann weiterverfahren -> Ca. kann man dann die vorheirge Zeit durch 3 teilen Consumer consumption: C0 -> 4 C1 -> 3 C2 -> 3 Total time: 5.01 seconds Question 7: - Es wird sich wieder nicht ändern an der Zeit, da es wieder draufankommt wie oft ein Consumer läuft, und dieser dann 1s dann schläft - Dabei ändert sich nichts, von der Zeit des Producers her -> In dem ersten Beispiel wird alles Linear consumiert -> 1 Producer-1 Consumer, usw. -> Mit Buffer Größe 3 -> 3 -> Producer -> 1 Consumer -> 1 Consumer -> 1 Consumer -> usw. Question 8: - Mit nur einem CV ist das Problem, dass ein Thread nicht weis, wem er als nächstes das Signal senden soll - Dementsprechend kann man mit nur 1 Producer und 1 Consumer kein Problem darstellen Question 9: ./main-one-cv-while -p 1 -c 2 -m 1 -P 0,0,0,1,0,0,0 -C 0,0,0,1,0,0,0:0,0,0,1,0,0,0 -l 5 -v -t -> Mit diesem String, kann man ein Deadlock verursachen, indem ein Consumer Thread einem anderen Thread signalisiert jedoch den falschen Thread nimmt (Consumer) und der dann kein Eintrag zum holen hat und somit stuck ist -> Der Producer schläft hierbei auch, da er von niemandem geweckt wird -> Und der Consumer hängt auch, da es kein Eintrag gibt den er Consumen kann Question 10: -> Mit einem Producer und Consumer gibt es wieder keine Probleme -> Mit 2 Consumer kann man ein Problem erstellen: ./main-two-cvs-if -p 1 -c 2 -m 1 -C 0,0,1,0,0,0,0:0,0,1,0,0,0,0 -l 5 -v -t -> error: tried to get an empty buffer (GEHT NUR AUF CONTAINER, NICHT AUF MAC) Question 11: -> Wenn man das Get und Fill nicht mit Locks sichert, dann könnte man mit dem Producer sleepen ohne zu fillen und dann mit dem Consumer getten ohne das was drinn ist ./main-two-cvs-while-extra-unlock -p 1 -c 2 -m 10 -l 10 -v -C 0,0,0,0,1,0,0:0,0,0,0,0,0,0 -> Der erste Consumer konsumiert nur einen Wert
import { useEffect, useState } from 'react'; import { useSearchParams, useLocation } from 'react-router-dom'; import { fetchMovie } from '../Services/API'; import { StyledLi, StyledLink, StyledUl, StyledHeader, } from '../StyledTags/Tags.styled'; const Movies = () => { const location = useLocation(); const [movies, setMovie] = useState([]); const [searchParams, setSearchParams] = useSearchParams(); const movieName = searchParams.get('movieName'); useEffect(() => { if (movieName === '') return; async function getMovie() { const movies = await fetchMovie(movieName); setMovie(movies); } getMovie(); }, [movieName]); const handleSubmit = e => { e.preventDefault(); setSearchParams({ movieName: e.currentTarget.elements.movieName.value }); e.currentTarget.reset(); }; return ( <> <StyledHeader> Search Movies </StyledHeader> <form onSubmit={handleSubmit}> <input type="text" name="movieName" autoComplete="off" autoFocus placeholder="Search movies" /> <button type="submit">Search</button> </form> {movies && ( <div> <StyledUl> {movies.map(movie => { return ( <StyledLi key={movie.id}> <StyledLink to={`${movie.id}`} state={{ from: location }}> {movie.original_title} </StyledLink> </StyledLi> ); })} </StyledUl> </div> )} </> ); }; export { Movies };
\documentclass[11pt,journal]{IEEEtran} %\usepackage{hyperref} %\usepackage[breaklinks]{hyperref} \usepackage{breakurl} \usepackage{url} \ifCLASSOPTIONcompsoc % IEEE Computer Society needs nocompress option % requires cite.sty v4.0 or later (November 2003) \usepackage[nocompress]{cite} \else % normal IEEE \usepackage{cite} \fi \hyphenation{op-tical net-works semi-conduc-tor} \begin{document} \title{High-Performance Computing Assignment 1: Diffusion Equations} \author{Agata~Borkowska,~UID: 1690550,~\IEEEmembership{MSc in Computer Science,~University of Warwick}% <-this % stops a space \protect\\ \thanks{}} % The paper headers \markboth{}% { \MakeLowercase{\textit{}}: } % IEEEtran.cls defaults to using nonbold math in the Abstract. % This preserves the distinction between vectors and scalars. However, % if the journal you are submitting to favors bold math in the abstract, % then you can use LaTeX's standard command \boldmath at the very start % of the abstract to achieve this. Many IEEE journals frown on math % in the abstract anyway. In particular, the Computer Society does % not want either math or citations to appear in the abstract. % Note that keywords are not normally used for peerreview papers. % make the title area \maketitle % To allow for easy dual compilation without having to reenter the % abstract/keywords data, the \IEEEcompsoctitleabstractindextext text will % not be used in maketitle, but will appear (i.e., to be "transported") % here as \IEEEdisplaynotcompsoctitleabstractindextext when compsoc mode % is not selected <OR> if conference mode is selected - because compsoc % conference papers position the abstract like regular (non-compsoc) % papers do! \IEEEdisplaynotcompsoctitleabstractindextext % \IEEEdisplaynotcompsoctitleabstractindextext has no effect when using % compsoc under a non-conference mode. % For peer review papers, you can put extra information on the cover % page as needed: % \ifCLASSOPTIONpeerreview % \begin{center} \bfseries EDICS Category: 3-BBND \end{center} % \fi % % For peerreview papers, this IEEEtran command inserts a page break and % creates the second title. It will be ignored for other modes. \IEEEpeerreviewmaketitle \section{Introduction} \IEEEPARstart{W}{e are} presented with a sequential code that calculates the result of the diffusion equations, at a specified interval, at given points of a grid. We begin by providing a brief overview of the code. <<<<<<< HEAD The \emph{Main} method only parses the input file to instantiate and run the \emph{Driver}. The \emph{Driver} class is responsible for setting up the mesh, then advancing the calculation step by step by calls to the \emph{Diffusion} class, and writing the result to the file each time via the file writer. It contains the loop that makes call at each step - at dt intervals, rather than at each cell of the mesh. This is the longest loop in the program, and the most timely one, however each calculation directly depends on the results of the previous iteration, and thus it cannot be parallelised. Hence we can keep the number of steps small, and focus on other loops. We will therefore focus on all methods which iterate over the mesh, and attempt to parallelise those. The results of all the tests are in subdirectory \emph{results}, and a short index can be found in Appendix A. \section{Initial readings} We use gmon to get the proportion of the time each function is running, and \emph{omp\_get\_wtime()} to measure total time. The first three tests done, \emph{test.txt}, \emph{testx.txt}, and \emph{testy.txt} are readings taken after running deqn on the three original tests provided. In the latter two, the runtimes of the functions are negligible. We will return later to problems which have a very long and narrow, rather than an almost square grid. For now, let us focus on problems with a square region. The most costly operations are summarised in the table below, excluding standard library, which takes over 40\% of the time on a square grid, and methods which have negligible runtimes. It demonstrates a comparison between running the program on a $100^2$, $1000^2$, and $10000^2$ (with 2 steps) grid, and the difference in the percentage of time take by each method. For comparison, we added a test on a long and narrow grid. \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|c|} \hline Function & $100^2$ & $1000^2$ & $10000^2$ & $10\times 10^7$\\ \hline VtkWriter::writeVtk(...) & 23.34 & 28.21 & 24.16 & 35.22\\ \hline Mesh::getTotal... & 16.67 & 15.39 & 6.73 & 5.35\\ \hline Mesh::getNx() & 8.34 & 11.54 & 12.58 & 7.51\\ \hline ExplicitScheme::reset() & 3.33 & 5.13 & 7.53 & 6.69\\ \hline ExplicitScheme::reflect... & 3.33 & 2.56 & 0.00 &1.63\\ \hline Mesh::getU0() & 1.67 & 3.85 & 3.47 & 2,23\\ \hline Mesh::getDim() & 1.67 & 1.28 & 2.87 & 2.30\\ \hline Mesh::Mesh(...) & 1.67 & 1.28 & 1.29 & 1.34\\ \hline Diffusion::init() & 0.00 & 0.00 & 9.01 & 10.48\\ \hline \end{tabular} \emph{Table 1: Summary of most costly methods in the program.} \end{table} \emph{Mesh} and \emph{ExplicitScheme} are the two classes responsible for calculations, which are also most costly. Especially in the case of \emph{Mesh::getTotalTemperature(...)} it isn't surprising to see that it contributes to a significant proportion of the runtime, as it sums over each cell of the mesh. As the problem size increases, the time needed to set it up is extended. Therefore on the $1000^2$ grid we begin to notice the impact of methods such as \emph{Mesh::Mesh()} and \emph{Diffusion::init()} It also isn't unexpected that \emph{ExplicitScheme::reset()} takes up more time as the problem size increases. This will be our second focus in improving performance. What is much more surprising in this table, are the three getters in \emph{Mesh}. Closer inspection of them is in Table 2, using $1000^2$ grid. \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|} \hline Method & total time (s) & number of calls & time per call (ms) \\ \hline getNx() & 0.05 & 42084401 & 0.00 \\ \hline getU0() & 0.02 &21000125 & 0.00 \\ \hline getDim() &0.01 &21& 0.24\\ \hline \end{tabular} \emph{Table 2: More information about the unexpectedly costly getters} \end{table} As we can see, those methods take a significant proportion of the time not because of their complexity, but because of numerous calls, and so we can't do anything about it with OpenMP. The most important part of the code is the loop in \emph{Driver.C}, iterating over each step, in dt intervals, from start time to end time. However after inspecting the code, we notice that each iteration depends on the results from the previous one, and thus we cannot parallelise it at all. Since all other loops operate on the mesh, rather than on the steps, we can reduce the number of steps, to speed up the testing. We will use 2 steps. \section{Speed up} \subsection{Mesh} From Table 1 we can see that the file writer takes most time, but also it cannot be parallelised, as we want the results in a file to appear in order. Therefore we move to \emph{Mesh::getTotalTemperature()}. It simply sums the value of each cell, and there's no dependency between cells. The only thing we will have to be careful of, is to take care of the critical section. We found that using a $10000 \times 10000$ is the maximum problem size our machines can deal with. Anything larger, even by one order of magnitude will cause integer overflow. To deal with that, we could use arrays of long long int, however it is worth considering the memory required to hold such array. Take an array of integers, each one being 32 bits. An array of size $(1 \times 10^4) \times (1 \times 10^5)$ - just 10 times larger than the problem in \emph{square\_mesh.in} - will require $32 \times 10^{9}$ bits, which is 4 GB. Therefore not much can be achieved here with the aid of just OpenMP. We first add \emph{\#pragman omp parallel for private(k) schedule(static)} just before the for loop in \emph{Mesh::getTotalTemperature()}, and also \emph{\#pragma omp critical} before summation of the temperature inside the loop. The results of this ran on the $1000^2$ grid (\emph{square1.in}). As the program runs, the results are redirected to the file. We can easily get the total run time from it, which is 153.015 s. For comparison, the sequential code runs in 116.075 s. Instead of using a critical section, we can use reduction. Our next test is adding \emph{\#reduction(+:temperature)} to the pragma options. With that, the total time to run the program is again around 116 s. Finally we try to change schedule to dynamic. It gives us a slightly better overall time, with 110.024 s average over 3 runs, and the results are very close together. Nevertheless, in the gmon's output we can see that the methods now takes a much smaller proportion of the time. Since this method is called multiple times, it would be interesting to see how big a difference it makes when the problem has more steps. We use files labelled \emph{square1\_xxsteps.in} as inputs, and compare the runtimes between the original and the parallelised program. Here's a comparison: \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|} \hline No. of steps & original runtime & static runtime& dynamic runtime \\ \hline 10 & 7.0223 & 7.12566 & 6.32213 \\ \hline 20 & 13.0044 & 11.9042 & 11.2931 \\ \hline 40 & 23.1150 & 23.1293 & 22.6300 \\ \hline 50 & 29.0084 & 29.0960 & 28.9210 \\ \hline \end{tabular} \emph{Table 3: Parallelising Mesh::getTotalTemperature() statically and dynamically} \end{table} Although the difference isn't overwhelming, a dynamic schedule of the thread consistently performs better than the others, so we're going to keep it. Last thing which we can do with Mesh - and which is only relevant with big problems - is parallelising the constructor. In a small problem, such as \emph{square.in} we expect to see a lot of overhead. To do this, we will put each loop as a section in \emph{\#pragma omp parallel sections}, and record the time through \emph{Driver} right before and after creating the mesh. The results are recorded in files \emph{test\_square20\_mesh\_xx.txt}. The average time taken to create the mesh is $0.00570391$, which is 117 times more than without parallelism - 2 orders of magnitude. The difference - $0.00566$ s. - is the overhead of using OpenMP. For comparison, we run the same code with a much larger program - such as the one in \emph{square\_mesh,in}. The times have been recorded in the file \emph{test\_square10k\_mesh\_00.txt}. The average is 0.005053462 with parallelism. For comparison, the same test was performed with the original code. The average was 0.0002356191, with results that can be found in \emph{test\_square10k\_mesh\_01.txt}. The difference is smaller but still non-negligible, being of one order of magnitude, and there's more variance. Gmon suggests that creating the mesh takes now about 1.03\% of the runtime (1.29\%-1.91\% previously), which is a slight improvement. The pragma is commented out in the code, as it gives no benefits for smaller problems. It has to be stressed that this is the best case scenario for creating the Mesh, where the problem is calculated on a square region, and each one of the two for loops has the same amount of work to do. There would be no point in parallelising this part of the program, in problems with a big difference between the loops, for example with a matrix of size $1 \times 1000$. \subsection{ExplicitScheme} Similarly to \emph{Mesh::getTotalTemperature()} above, we add the same pragma with dynamic scheduling to \emph{ExplicitScheme::reset()}, which we identified earlier as one of the longer methods. \subsection{Diffusion} Similarly to the constructor of the mesh, Diffusion takes up a significant portion of the time in large programs. We can again add the same pragma to the loop in the init. \subsection{Number of threads} So far we have been relying on OpenMP automatically choosing the number of threads. We will use \emph{ExplicitScheme::reset()} to test the effects of changing the number of threads. To this end we set the number of threads in the pragma in \emph{ExplicitScheme}. The average time for the program to run on \emph{square1.in} without a pragma there is $11.6004$ s. Very surprisingly we found no significant difference between the runtimes with different numbers of threads. The same test was repeated with the same pragma in \emph{Mesh::getTotalTemperature()} and a different test, and again the results didn't differ. They are presented in Table 4. \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|c|} \hline Test & 1 thread & 2 threads& 3 threads & 4 threads \\ \hline ExplicitScheme & 11.3941 & 11.8007 & 11.5279 & 11.3947 \\ \hline Mesh & 6.2594 & 6.3017 & 6.3169 &6.2404\\ \hline \end{tabular} \emph{Table 4: Comparison of runtimes with different number of threads} \end{table} We are certain that the specified number of threads has been running, as it was confirmed by adding additional logging with \emph{omp\_get\_num\_threads()} in both cases. The changes in code of Explicit Scheme have been copied to the file \emph{ExplicitScheme.txt}. To experiment with it further, we ran the problem \emph{square2.in} with the number of threads specified in the Explicit Scheme pragma. This problem has a small mesh, but 10000 of steps. The reason behind trying this was to see if the overhead of scheduling threads multiple times for a small problem, will become noticeable. It did, as demonstrated in Table 5. \begin{table}[h] \centering \begin{tabular}{|c|c|c|c|c|} \hline Test & 1 thread & 2 threads& 3 threads & 4 threads \\ \hline square2.in& 69.2724 & 76.5163 & 79.1382 & 91.0424 \\ \hline \end{tabular} \emph{Table 5: The runtime increases with the number of threads in a simple problem} \end{table} The runtime increases with the number of threads. The best runtime is with just one thread, as the problem size is small ($100^2$ grid). \section{Discussion of Methods} Something that has not been addressed in this writeup, and is beyond the scope of the project, is optimisation at compile time. The only change made to the MAKEFILE was adding debugging gmon flags, namely \emph{-g} and \emph{-pg}, and everything else was left as it was. It was expected that background processes running on the machine while the code was executing, could affect the results. Hence to mitigate that, multiple readings were taken. Finally, most of the work has been done on a personal laptop, which has a 2-core i5 processor. It was unfortunately unavoidable, as I had to travel, and couldn't even connect remotely to joshua.dcs.warwick.ac.uk. \section{Conclusion} Thus we ended up with the pragmas before the loops in the following methods: \begin{itemize} \item Mesh::getTotalTemperature() \item Diffusion::init() \item ExplicitScheme::reset() \item ExplicitScheme::diffuse() \end{itemize} We decided against running the two loops in the constructor of Mesh concurrently, because due to their simplicity, we lost more performance to the overhead of using OpenMP parallel sections, than we gained from the concurrency. Finally, while the overall runtime wasn't improved significantly, the four aforementioned methods now have negligible contribution to the runtime, and the majority of it is caused by the VtkWriter, standard library, and an overwhelming number of calls to the getters. It was rather disappointing that changing the number of threads didn't demonstrate the expected behaviour of better performance as the number of threads increases, up to a certain point after which the performance worsens. ======= The \emph{Main} method only parses the input file to instantiate and run the \emph{Driver}. The \emph{Driver} class is responsible for setting up the mesh, then advancing the calculation step by step by calls to the \emph{Diffusion} class, and writing the result to the file each time via the file writer. It contains the loop that makes call at each step - at dt intervals, rather than at each cell of the mesh. This is the longest loop in the program, and we identify it as the key to improving the performance. More specifically, the Driver's constructor directly calls \emph{Mesh}, \emph{Diffusion}, and \emph{Writer} constructors, in that order, as the created mesh is an input to the latter two constructors. Therefore, the mesh will be the focus of our first attempt at parallelism. The \emph{Mesh} class is responsible for creating the grid described in the input file. It runs two for loops, one for the x, one for the y coordinates. In the original code they are ran one after another, but as there is no overlap between them, running them in parallel is an obvious first step. The loops in it are very simple, and can be run concurrently, so it will help us measure the overhead, and we do not expect to achieve as much with this as with the other classes. The \emph{Diffusion} class sets up the scheme, and the \emph{Diffusion.doCycle()} method acts as a wrapper for the scheme's \emph{doAdvance()} method. The constructor has a nested for loop, however we'll leave that one for later, and focus on speeding up the calculations. The scheme makes a call to three methods in each step. The first one is \emph{diffuse(dt)}, which is key to the calculations. It contains two nested for loops, that iterate over each cell of the grid. The calculations are independent of each other, and that will be our next focus in an attempt to speed up the code. The remaining two methods, \emph{reset()} and \emph{updateBoundaries()}, update the Mesh with the result of the calculations. The former simply iterates over each cell in the grid. The latter performs calculations on the boundaries of the region in the problem. Thus, it has a for loop, iterating over each of the four boundaries, which should also be easily sped up. The \emph{VtWriter} class is responsible for writing the values in each cell to a file, one per a time step. Thus it also iterates over the cells of the mesh at each step. Thus we recognized three areas for improvement in performance: creating the mesh, the three methods iterating over each cell of the mesh (which will all be treated in a similar manner), and most importantly the loop that advances the calculations step by step. The results of all the tests are in subdirectory \emph{results}, and a short index can be found in Appendix A. \section{Setting up the tests and measuring overhead} Before we can objectively measure the improvement in performance, it is essential that we assess the overhead of using OpenMP. To begin with, we measure the time taken to create the mesh and perform the calculations of the provided \emph{square.in} problem. To get a reading of the time taken, we use the \emph{omp\_get\_wtime()} just before and after creating the mesh, and likewise at the start and end of the \emph{Driver.run()} method. The readings can be found in the files \emph{test\_square20\_xx.txt}. The average time to create the mesh is $4.8640 \times 10^{-5}$, and to run the Driver is $0.165044$. It is clear that the problem size is not sufficient to give much room for improvement. Furthermore, increasing it will aid us with the statistical analysis of the results. For this reason we have also used a variety of machines. The files mentioned earlier are recorded on a personal laptop. Similar tests were ran for comparison on the DCS machines, and the results were found to be similar ($3.1258 \times 10^{-5}$ average mesh time, $0.257189$ average calculation time). There is also very little variance, which is why we deem a sample of 10 tests to be enough. After some trial and error, we found that increasing the grid size to $1000 \times 1000$ and the number of steps to $100$ gives us execution time of around a minute. It is a reasonable balance between obtaining meaningful results and repeating the tests. However the time taken to create the mesh was still of the same order of magnitude. We will use the simple loop to create mesh to measure the overhead of OpenMP. To do this, we will put each loop as a section in \emph{\#pragma omp parallel sections}, and record the time through \emph{Driver} right before and after creating the mesh. The results are recorded in files \emph{test\_square20\_mesh\_xx.txt}. The average time taken to create the mesh is $0.00570391$, which is 117 times more than without parallelism - 2 orders of magnitude. The difference - $0.00566$ s. - is the overhead of using OpenMP. \section{Speed up} \subsection{Mesh} As shown before, OpenMP creates a very significant overhead, so perhaps rather than asking "how much can we speed up creating the mesh?", we should work out how big the problem needs to be, to overcome the overhead. We found that using a $10000 \times 10000$ is the maximum problem size our machines can deal with. Anything larger, even by one order of magnitude will cause integer overflow. To deal with that, we could use arrays of long long int, however it is worth considering the memory required to hold such array. Take an array of integers, each one being 32 bits. An array of size $(1 \times 10^4) \times (1 \times 10^5)$ - just 10 times larger than the problem in \emph{square\_mesh.in} - will require $32 \times 10^{9}$ bits, which is 4 GB. Therefore not much can be achieved here with the aid of just OpenMP. The times have been recorded in the file \emph{test\_square10k\_mesh\_00.txt}. The average is 0.005053462 with parallelism. For comparison, the same test was performed with the original code. The average was 0.0002356191, with results that can be found in \emph{test\_square10k\_mesh\_01.txt}. The difference is smaller but still non-negligible, being of one order of magnitude, and there's more variance. It has to be stressed that this is the best case scenario for creating the Mesh, where the problem is calculated on a square region, and each one of the two for loops has the same amount of work to do. There would be no point in parallelising this part of the program, in problems with a big difference between the loops, for example with a matrix of size $1 \times 1000$. Thus, we won't be able to achieve any speed up in the mesh. \subsection{Diffusion} Another attempt we can make is to parallelise the scheme. After a brief inspection of the \emph{ExplicitScheme.C} and the loops in it, we conclude that there are no dependencies between the iterations. Each iteration of the nested loops calculates the value at a given cell of the Mesh, independently of the other cells. Therefore we can not worry with a critical section, which would just create an additional overhead. To take an initial reading for the time taken to calculate the diffusion, we use \emph{square2.in}. It is a $100 \times 100$ grid with 100000 steps. The average time taken by the Driver is 68.0825 s, and the results are recorded in the files named \emph{test\_square100\_1ksteps\_0x.txt}. We use \emph{\#pragma omp parallel for private(k) schedule(static)}, which schedules the iterations of the loop between available threads - chosen automatically based on the architecture. In the case of my laptop, it picks 4 threads. The average is 89.1293 s, with the results recorded in the files \emph{test\_square100\_1ksteps\_1x.txt}. This is significantly worse than a sequential performance. For comparison, we specify the number of threads, from 1 to 4, by adding \emph{num\_threads(x)} at the end of the pragma. The results are presented in the Table 1 below. \begin{table}[h] \centering \begin{tabular}{|c||c|c|c|c|c||c|} \hline & Run 1 & Run 2 & Run 3 & Run 4 & Run 5 & Average \\ \hline 1 & 73.6722 & 68.6994 & 68.2287 & 67.4667 & 68.2951 & 69.2724 \\ \hline 2 & 80.5171 & 74.4021 & 75,1654 & 74.5040 & 77.9940 & 76.5163 \\ \hline 3& 81.0917 & 79.0574 & 78.0048 & 79.5261 & 78.0110 & 79.1382 \\ \hline 4& 97.8915 & 89.3469 & 88.6477 & 89.2015 & 90.1243 & 91.0424 \\ \hline \end{tabular} \emph{Table 1: Comparison of Runtimes with Pragma in ExplicitScheme.C} \end{table} It is clear that with this problem size, there is no point in attempting to parallelise the remaining loops in the \emph{ExplicitScheme.C}. The runtime increases with each additional thread. \subsection{Driver} The most important part of the code where we can improve performance, is the loop in \emph{Driver.C}, iterating over each step, in dt intervals, from start time to end time. We also take more readings than previously, as after some initial trial and error, we noticed that we can achieve quite significant speedup here. Before we can add the pragma before the for loop, we need to make sure to iterate over an integer, rather than a double as it currently is. It is done by creating a new variable, i, running from 0 to $(t\_start - t\_end) / dt$ (cast into int). While the results are looking very well, we've noticed a worrying trend: there is a little variance in the total temperature, which should stay constant. It is in the range of $\pm 0.03$. \section{Discussion of Methods} Something that has not been addressed in this writeup, and is beyong the scope of the project, is optimisation at compile time. The only change made to the MAKEFILE was adding debugging flags, and everything else was left as it was. It was expected that background processes running on the machine while the code was executing, could affect the results. Hence to mitigate that, multiple readings were taken. A note on writing the result files: to avoid any performances difference in the program, the results weren't recorded by changing the location of the output of the program in \emph{Driver.C}. Instead, we redirected it from the terminal to a specified file through bash. \section{Conclusion} %\IEEEPARstart{}{} %\begin{thebibliography} %\end{thebibliography} \appendices \section{Index of test inputs and results} The following tests were added: \begin{itemize} \item \textbf{square1.in} - $1000 \times 1000$ matrix, 20 steps. \item \textbf{square\_mesh.in} - $10000 \times 10000$ grid, 1 step \item \textbf{x1.in} - $10 \times 10^7$ grid, 2 steps \item \textbf{square1\_xxsteps.in} - as in \emph{square1.in}, with a different number of steps each time \end{itemize} The following files were the first readings, without amending any code, other than to print out time taken: \begin{itemize} \item \textbf{test.txt} - gmon.out output of the runtimes, using \emph{square.in} \item \textbf{testx.txt, testy.txt} - gmon output of the runtimes, using \emph{x.in} and \emph{y.in} respectively \item \textbf{test1.txt} - output of gmon using \emph{square1.in}, which is a $1000 \times 1000$ grid \item \textbf{testx1.txt} - output of gnom, using a very long and narrow grid (\emph{x1.in}) \item \textbf{test\_xxsteps\_original.txt} - output of gnome, when the original code is ran on the \emph{square1\_xxsteps.in} \item \textbf{final\_test.txt} - running the final version of the program on \emph{square1.in} \end{itemize} The following files are results of various attempts at parallelism: \begin{itemize} \item \textbf{test\_xxsteps\_static.txt} - code ran on the \emph{square1\_xxsteps.in} with static scheduling \item \textbf{test\_xxsteps.txt}- code ran on the \emph{square1\_xxsteps.in} with dynamic scheduling \item \textbf{test\_square1\_scheme\_testx.txt} - parallelising ExplicitScheme with dynamic schedule \item \textbf{test\_ythreadsx.txt} - statically scheduling x threads for Explicit Scheme \end{itemize} For the above files, we dumped the stack to a file. It includes readings of time taken to create the Mesh and for overall calculations, more as a reference. In our considerations, we used times from gmon. \begin{itemize} \item \textbf{dump\_mesh\_plain\_1.txt} - running the original programwith \emph{square\_mesh.in} \item \textbf{dump\_mesh\_1loop\_x.txt} - running the program with a single pragma in \emph{Mesh::getTotalTemperature()}, on a $1000^2$ grid \emph{square\_mesh.in} \item \textbf{dump\_xxsteps\_original.txt} \item \textbf{dump\_xxsteps\_static.txt} \item \textbf{dump\_xxsteps.txt} \item \textbf{dump\_square20\_mesh\_xx.txt} - times taken to create a mesh with and without parallel sections, showing the overhead of OpenMP \item \textbf{test\_square10k\_mesh\_xx.txt} -- as above, with a large problem \item \textbf{dump\_square1\_scheme\_testx.txt} - dump of the program with parallelism in the \emph{ExplicitScheme::reset()} method \item \textbf{final\_dump.txt} - running the final version of the program on \emph{square1.in} \item \textbf{test\_square100\_ythread\_xx.txt} - results of specifying number of threads in ExplicitScheme, and running it on a large problem. \end{itemize} % that's all folks \end{document}
import 'package:dog_app/model/api_wrapper.dart'; import 'package:dog_app/model/sub_breed.dart'; import '../../core/network/client.dart'; import '../../model/breed.dart'; import 'i_dog_service.dart'; final class DogService implements IDogService { DogService(); @override Future<ApiWrapper<List<Breed>>> getBreedList() async { final response = await Client().request( path: '/breeds/list/all', httpMethod: HttpMethods.get, ); ApiWrapper<List<Breed>>? breedsListModel; if (response == null) return ApiWrapper.error(); if (response.statusCode != 200) { return ApiWrapper.error(message: 'http error: ${response.statusCode}'); } if (response.data!! is Map<String, List<String>>) return ApiWrapper.error(); late final Map<String, dynamic> rawData; if ((response.data as Map<String, dynamic>)['message']! is! Map<String, dynamic>) { return ApiWrapper.error(); } rawData = (response.data as Map<String, dynamic>)['message'] as Map<String, dynamic>; final breedList = rawData.entries.map((entry) { final List<SubBreed> breedTypes = []; if (entry.value is List) { for (final type in entry.value) { breedTypes.add(SubBreed(subBreedName: type.toString())); } } return Breed( breedName: entry.key, subBreeds: breedTypes, ); }).toList(); breedsListModel = ApiWrapper(data: breedList, isSuccess: true, message: 'success'); return breedsListModel; } @override Future<ApiWrapper<String>> getRandomBreedImage(String breedName) async { final response = await Client().request( path: '/breed/$breedName/images/random', httpMethod: HttpMethods.get, ); if (response == null) return ApiWrapper.error(); if (response.statusCode != 200) { return ApiWrapper.error(message: 'http error: ${response.statusCode}'); } if (response.data!! is Map<String, List<String>>) return ApiWrapper.error(); if ((response.data as Map<String, dynamic>)['message'] is! String) { return ApiWrapper.error(); } return ApiWrapper( data: (response.data as Map<String, dynamic>)['message'] as String, isSuccess: true, message: 'success'); } }
<template> <nav> <h2>Выбрать период отображения цены биткоина</h2> <ul> <li v-for="period in periods" :key="period.id" @click="per(period)"> {{ period.value }} </li> </ul> <form action=""> <input type="date" name="start" v-model="start" /> <input type="date" name="end" v-model="end" /> <button @click="getHistory">Показать</button> </form> </nav> </template> <script lang="ts" setup> import type { PeriodType } from "~/types/Period"; const dateNow = ref(new Date()); const start = ref(new Date()); const end = ref(new Date()); const day = dateNow.value.getDate(); const month = dateNow.value.getMonth(); const year = dateNow.value.getFullYear(); const periods = ref([ { id: 1, value: "День", step: "h1", start: +dateNow.value.getTime() - 1000 * 60 * 60 * 24, end: dateNow.value.getTime(), }, { id: 2, value: "Неделя", step: "d1", start: +dateNow.value.getTime() - 1000 * 60 * 60 * 24 * 9, end: dateNow.value.getTime(), }, { id: 3, value: "Месяц", step: "d1", start: new Date().setMonth(dateNow.value.getMonth() - 1), end: dateNow.value.getTime(), }, { id: 4, value: "Год", step: "d1", start: new Date(`${year - 1}-${month + 1}-${day}`).getTime(), end: dateNow.value.getTime(), }, ]); const store = datasStore(); function per(period: PeriodType): void { store.changePeriod(period); } function getHistory(e: Event) { e.preventDefault(); if (start.value.toString() === "" || end.value.toString() === "") { alert("Введите Нижнюю и верхнюю границы временного интервала"); return; } const millStart = new Date(start.value).getTime(); const millEnd = new Date(end.value).getTime(); let step = "d1"; if (millEnd - millStart - 1000 * 60 * 60 * 24 * 2 <= 0) { step = "h1"; } const period: PeriodType = { id: 5, value: "Пользотельский", step, start: millStart, end: millEnd, }; store.changePeriod(period); } onMounted(async () => { store.changePeriod(periods.value[3]); }); </script> <style scoped> nav { display: flex; flex-direction: column; align-items: center; } h2 { text-align: center; padding-top: 5px; } ul { font-size: 20px; list-style: none; margin: 0; padding: 0; display: flex; justify-content: center; gap: 15px; transition: border-bottom 2s ease-in-out; } li:after { display: block; content: ""; border-bottom: solid 3px #f87979; transform: scaleX(0); transition: transform 250ms ease-in-out; } li:hover:after { transform: scaleX(1); } form { margin-top: 5px; display: flex; justify-content: center; align-items: center; flex-direction: column; gap: 10px; width: 150px; } input { width: 100%; height: 25px; font-size: 18px; } button { padding: 5px 12px; border-radius: 8px; border: 1px solid #f87979; background-color: #fff; font-size: 18px; transition: all 0.4s ease-in-out; } button:hover { background-color: #f87979; color: #fff; box-shadow: 0px 0px 3px 1px #f87979; } </style>
<script> import axios from 'axios'; import { store } from '../data/store'; import Loader from "../components/partials/Loader.vue" export default { name:'EditPizza', data(){ return{ name: '', price: '', photo: '', description: '', pizza: null, store, loaded: false, sending: false, success: false, errors: {}, errorMessage: false, } }, components:{ Loader }, methods:{ getOldPizza() { this.loaded = false; //*rotta definita in PIzzaApiController del progetto Spring // axios.get(store.apiUrl + "/pizzas/" + this.$route.params.id) // oppure axios.get(`${store.apiUrl}/pizzas/${this.$route.params.id}`) .then(result => { this.pizza = result.data; this.loaded = true; }) .catch(error => { console.error('Error fetching pizza details:', error); this.loaded = true; }); }, sendForm() { this.sending = true; this.errors = {}; this.errorMessage = false; this.success = false; const newPizza = { name: this.pizza.name, price: this.pizza.price, photo: this.pizza.photo, description: this.pizza.description }; // axios.put(`${store.apiUrl}/edit/${this.$route.params.id}`, newPizza) // oppure axios.put(store.apiUrl + "/edit/" + this.$route.params.id, newPizza) .then(result => { this.success = result.status == 200; console.log('result.status', result.status); // ulteriore controllo per gli errori if(!this.success){ this.errorMessage = true; this.errors = result.data.errors; console.log("prova 1", this.success, this.errors); }else{ this.errors = {}; this.errorMessage = false; console.log("prova 2", this.success, this.errors); } this.sending = false; console.log('Pizza created: ', result); console.log("prova 3", this.success, this.errors); }) .catch(error => { this.sending = false; this.errorMessage = true; console.log("error ", this.success, this.errors); if (error.response && error.response.data && error.response.data.errors) { // se ci sono errori nella risposta, assegna gli errori alla variabile errors this.errors = error.response.data.errors; console.log("error 1", this.success, this.errors); // this.errorMessage = true; } else { console.log("error 2", this.success, this.errors); // console.error('Error creating pizza: ', this.errors); console.log(error); // this.errorMessage = true; } }); }, }, mounted() { this.getOldPizza(); } } </script> <template> <div class="container-inner d-flex flex-column align-items-center justify-content-start" style=" max-width: 90%;"> <!-- oppure con mx-auto --> <!-- <div class="container-inner mx-auto"> --> <div v-if="loaded && pizza" class="d-flex flex-column align-items-center justify-content-start"> <div v-if="loaded && pizza" class="d-flex align-items-center justify-content-center mb-4"> <h2 class="text-center me-2">Edit {{ pizza.name }}</h2> <router-link class="def-link" :to="{ name: 'pizzaDetail', params:{ id: pizza.id } }"> <button style="min-height: 40px;" class="btn-icon btn btn-warning-c fw-custom d-flex align-items-center justify-content-center me-1" title="Edit offer"><i class="fa-solid fa-eye"></i></button> </router-link> <!-- funzione per eliminare una pizza //* DALLO STORE --> <button @click="store.deletePizza(pizza.id, this.$router.push('/'))" style="min-height: 40px" class="btn-icon btn btn-danger-c fw-custom d-flex align-items-center justify-content-center " title="Delete pizza"><i class="fa-solid fa-trash"></i></button> </div> <div v-if="success" class="alert alert-success mt-4" role="alert"> <h5 class="text-success p-0 m-0">Pizza Edited! Check the menu</h5> </div> <div v-if="errorMessage === true" class="alert alert-danger p-0 mt-4" role="alert"> <h4 class="text-danger text-center mt-2">Error</h4> <div class="text-danger text-center my-2 mx-4"><strong>Some values entered in the form are incorrect</strong></div> <div v-for="(error,index) in errors" :key="index" class="text-danger mx-4 my-2">- {{ error[0] }}</div> </div> <div class="d-flex flex-column align-items-center justify-content-center"> <!--//* @submit.prevent="sendForm()" nel form impedisce il ricaricamento della pagina quando viene inviato e, allo stesso tempo, chiama la funzione sendForm --> <form @submit.prevent="sendForm()"> <div class="mb-3" style="width: 80vw"> <label for="name" class="fw-bold form-label">Name</label> <input :class="{ 'is-invalid' : errors.name }" v-model.trim="pizza.name" type="text" name="name" class="form-control" placeholder="Margherita"> <!-- //* CONTROLLO LATO FRONTEND (viene effettuato prima di un controllo tramite backend) - minlength potrebbe non funzionare come previsto con v-model quindi bisogna fare una funzione apposita in js --> <!-- //! DA DECOMMENTARE (LASCIATO COMMENTATO PER FAR VEDERE CHE FUNZIONA IL CONTROLLO DEGLI ERRORI LATO BACKEND) --> <!-- <input :class="{ 'is-invalid' : errors.name }" v-model.trim="pizza.name" required minlength="2" type="text" name="name" class="form-control" placeholder="Margherita"> --> <div v-for="(error,index) in errors.name" :key="index" class="text-danger mt-1">{{ error }}</div> </div> <div class="mb-3" style="width: 80vw"> <label for="price" class="fw-bold form-label">Price</label> <input :class="{ 'is-invalid' : errors.price }" v-model.trim="pizza.price" pattern="[0-9.]*" type="number" step="0.01" min="1" class="form-control" name="price" placeholder="10.50"> <!-- //* CONTROLLO LATO FRONTEND (viene effettuato prima di un controllo tramite backend) - minlength potrebbe non funzionare come previsto con v-model quindi bisogna fare una funzione apposita in js --> <!-- //! DA DECOMMENTARE (LASCIATO COMMENTATO PER FAR VEDERE CHE FUNZIONA IL CONTROLLO DEGLI ERRORI LATO BACKEND) --> <!-- <input :class="{ 'is-invalid' : errors.price }" v-model.trim="pizza.price" required minlength="1" pattern="[0-9.]*" type="number" step="0.10" min="1" class="form-control" name="price" placeholder="10.50"> --> <div v-for="(error,index) in errors.price" :key="index" class="text-danger mt-1">{{ error }}</div> </div> <div class="mb-3" style="width: 80vw"> <label for="photo" class="fw-bold form-label">Image</label> <input :class="{ 'is-invalid' : errors.photo }" v-model.trim="pizza.photo" type="text" class="form-control" name="photo" placeholder="https://www.marcobianchi.blog/wp-content/uploads/2023/01/pizza-2048x1365.jpg"> <!-- //* CONTROLLO LATO FRONTEND (viene effettuato prima di un controllo tramite backend) - minlength potrebbe non funzionare come previsto con v-model quindi bisogna fare una funzione apposita in js --> <!-- //! DA DECOMMENTARE (LASCIATO COMMENTATO PER FAR VEDERE CHE FUNZIONA IL CONTROLLO DEGLI ERRORI LATO BACKEND) --> <!-- <input :class="{ 'is-invalid' : errors.photo }" v-model.trim="pizza.photo" required minlength="1" type="text" class="form-control" name="photo" placeholder="https://www.marcobianchi.blog/wp-content/uploads/2023/01/pizza-2048x1365.jpg"> --> <div v-for="(error,index) in errors.photo" :key="index" class="text-danger mt-1">{{ error }}</div> </div> <div class="mb-3" style="width: 80vw"> <label for="description" class="fw-bold form-label">Description</label> <textarea :class="{ 'is-invalid' : errors.description }" v-model.trim="pizza.description" type="text" name="description" class="form-control" placeholder="Description" cols="10" rows="10"></textarea> <div v-for="(error,index) in errors.description" :key="index" class="text-danger mt-1">{{ error }}</div> </div> <button type="submit" class="btn btn-danger-c" :btn-danger="sending" :disabled="sending">{{ sending ? 'Loading...' : 'Edit' }}</button> </form> </div> </div> <Loader v-if="!loaded"/> </div> </template> <style scoped> .btn-danger-c{ background-color: #ff001e !important; color: white; } a{ color: inherit; } </style>
import { ChangeEvent } from "react"; import "./SelectOrder.css"; type SelectOrder = { onChange: (event: ChangeEvent<HTMLSelectElement>) => void; }; export const SelectOrder: React.FC<SelectOrder> = ({ onChange }) => { let OrderByOptions = [ { value: "FullName Asc", name: "Nome Ascendente" }, { value: "FullName Desc", name: "Nome Descendente" }, { value: "CreatedDate Asc", name: "Data Criação Ascendente" }, { value: "CreatedDate Desc", name: "Data Criação Descendente" }, { value: "UpdatedDate Asc", name: "Data Actualização Ascendente" }, { value: "UpdatedDate Desc", name: "Data Actualização Descendente" }, ]; return ( <select id="orderBy" onChange={onChange} defaultValue={""} className="order" > <option className="order-placeholder" value={""} disabled hidden> Ordenar </option> {OrderByOptions.map((option, i) => ( <option key={i} value={option.value}> {option.name} </option> ))} </select> ); };
package com.example.englishapp; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.englishapp.model.Folder; import com.example.englishapp.model.Vocab; import com.example.englishapp.view.VocabAdapter; import com.example.englishapp.viewmodel.FolderVM; import com.example.englishapp.viewmodel.VocabVM; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.gson.Gson; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.ArrayList; import java.util.List; public class my_word extends AppCompatActivity { private String m_Text = ""; private List<Vocab> vocabList= new ArrayList<>(); private List<Vocab> vocabListFav= new ArrayList<>(); private VocabVM vocabViewModel; private VocabAdapter vocabAdapter; EditText search; FloatingActionButton add_vocab, play_fav; String idTopic, idOwner; ArrayList<ArrayList<Vocab>> allVocabListstest; private Button pc1, pc2, pc3, btn_fav; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_word); // Khởi tạo VocabVM vocabViewModel = new VocabVM(); Bundle bundle = getIntent().getExtras(); // idOwner = bundle.getString("idOwner"); // idTopic = bundle.getString("idTopic"); SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); idOwner = sharedPreferences.getString("idUser", "user_2"); getWordsForUserAndTopicInBackground(idOwner); BottomNavigationView bottomNavigationView = findViewById(R.id.bottonnavMyword); bottomNavigationView.getMenu().getItem(0).setChecked(false); bottomNavigationView.getMenu().getItem(2).setChecked(true); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.proPage) { startActivity(new Intent(getApplicationContext(), Profile.class)); overridePendingTransition(0, 0); finish(); return true; } else if (item.getItemId() == R.id.homePage) { // Thêm các xử lý cho trang chủ nếu cần startActivity(new Intent(getApplicationContext(), home.class)); overridePendingTransition(0, 0); finish(); return true; } else if (item.getItemId() == R.id.folderPage) { startActivity(new Intent(getApplicationContext(), folderTopic.class)); overridePendingTransition(0, 0); finish(); return true; } else if (item.getItemId() == R.id.mywordPage) { // Thêm các xử lý cho trang chủ nếu cần return true; }else if (item.getItemId() == R.id.gamePage) { startActivity(new Intent(getApplicationContext(), gamePlay.class)); overridePendingTransition(0, 0); finish(); return true; } return false; } }); vocabAdapter = new VocabAdapter(my_word.this, vocabList); RecyclerView recyclerView = findViewById(R.id.rcv_Vocab); recyclerView.setLayoutManager(new LinearLayoutManager(my_word.this)); recyclerView.setAdapter(vocabAdapter); search = findViewById(R.id.edt_search_vovab); search.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { m_Text = charSequence.toString(); // Sau đó, áp dụng bộ lọc dựa trên m_Text filter(m_Text); } @Override public void afterTextChanged(Editable editable) { } }); add_vocab = findViewById(R.id.btn_add_vocab); // add_vocab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(my_word.this, com.example.englishapp.add_vocab.class); // intent.putExtra("idTopic",idTopic); // startActivity(intent); // } // }); pc1 = findViewById(R.id.btn_process_1); pc2 = findViewById(R.id.btn_process_2); pc3 = findViewById(R.id.btn_process_3); pc1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { filterProcess(1); } }); pc2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { filterProcess(2); } }); pc3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { filterProcess(3); } }); btn_fav = findViewById(R.id.btn_show_fav); btn_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { filterFavorite(); } }); play_fav = findViewById(R.id.btn_play_fav); play_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getListFavorite(); String jsonVocabList = new Gson().toJson(vocabListFav); // Tạo Intent để mở hoạt động FlashcardActivity Intent intent = new Intent(my_word.this, flashcard.class); // Đưa chuỗi JSON vào Intent intent.putExtra("jsonVocabList", jsonVocabList); // Khởi động hoạt động FlashcardActivity startActivity(intent); } }); } private void updateRecyclerView() { // Gọi hàm để lấy từ vựng và xử lý kết quả // getWordsForUserAndTopic(idOwner, idTopic); // Cập nhật dữ liệu mới cho adapter và thông báo thay đổi vocabAdapter.update(); } private void getWordsForUserAndTopic(String userId) { vocabViewModel.getAllVocabForUser(userId, new VocabVM.OnTopicsFetchedListener() { @Override public void onTopicFetched(String topicName, String topicId) { // Xử lý khi topic được lấy thành công (nếu cần) // Bạn có thể thêm mã xử lý ở đây để hiển thị thông tin topic // Toast.makeText(my_word.this,"success",Toast.LENGTH_SHORT).show(); } @Override public void onVocabListFetched(Vocab vocab) { // Chờ 3 giây trước khi gán giá trị cho vocabList vocabList.add(vocab); // Cập nhật giao diện người dùng (nếu cần) runOnUiThread(new Runnable() { @Override public void run() { vocabAdapter.notifyDataSetChanged(); // Gọi notifyDataSetChanged từ adapter // Hiển thị thông báo thành công // Toast.makeText(my_word.this, "Thành công", Toast.LENGTH_SHORT).show(); } }); } @Override public void onVocabAllFetched(ArrayList<ArrayList<Vocab>> allVocabLists) { // allVocabListstest = allVocabLists; // Toast.makeText(my_word.this, allVocabLists.size()+"",Toast.LENGTH_SHORT).show(); } @Override public void onFetchError(Exception e) { // Xử lý khi có lỗi trong quá trình lấy dữ liệu // Bạn có thể thêm mã xử lý ở đây để thông báo về lỗi Toast.makeText(my_word.this,"error",Toast.LENGTH_SHORT).show(); } }); } private boolean isVocabExists(Vocab vocab) { for (Vocab existingVocab : vocabList) { // Ở đây, bạn cần xác định cách so sánh giữa các phần tử Vocab, ví dụ, so sánh theo id, word, trans, etc. // Dưới đây là một ví dụ sơ bộ kiểm tra theo id if (existingVocab.getId().equals(vocab.getId())) { return true; // vocab đã tồn tại trong vocabList } } return false; // vocab chưa tồn tại trong vocabList } private void filter(String text) { // Tạo một danh sách mới để lưu trữ kết quả lọc ArrayList<Vocab> filteredList = new ArrayList<>(); // Duyệt qua tất cả thư mục trong danh sách gốc for (Vocab item : vocabList) { // Kiểm tra xem tên thư mục chứa văn bản tìm kiếm không, không phân biệt hoa thường if (item.getWord().toLowerCase().contains(text.toLowerCase())) { // Nếu tìm thấy, thêm vào danh sách đã lọc filteredList.add(item); } } // Kiểm tra xem danh sách đã lọc có dữ liệu hay không if (filteredList.isEmpty()) { // Hiển thị thông báo nếu không có kết quả tìm kiếm Toast.makeText(my_word.this, "Không tìm thấy dữ liệu.", Toast.LENGTH_SHORT).show(); } // Cập nhật danh sách trong Adapter với danh sách đã lọc vocabAdapter.filterList(filteredList); } private class FetchVocabTask extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... userIds) { String userId = userIds[0]; vocabViewModel.getAllVocabForUser(userId, new VocabVM.OnTopicsFetchedListener() { @Override public void onTopicFetched(String topicName, String topicId) { // Xử lý khi topic được lấy thành công (nếu cần) } @Override public void onVocabListFetched(Vocab vocab) { vocabList.add(vocab); // Cập nhật giao diện người dùng (nếu cần) runOnUiThread(new Runnable() { @Override public void run() { vocabAdapter.notifyDataSetChanged(); } }); } @Override public void onVocabAllFetched(ArrayList<ArrayList<Vocab>> allVocabLists) { // Xử lý khi tất cả vocab đã được lấy (nếu cần) } @Override public void onFetchError(Exception e) { // Xử lý khi có lỗi trong quá trình lấy dữ liệu } }); return null; } } private void getWordsForUserAndTopicInBackground(String userId) { new FetchVocabTask().execute(userId); } private void filterProcess(int processLevel) { // Tạo một danh sách mới để lưu trữ kết quả lọc ArrayList<Vocab> filteredList = new ArrayList<>(); // Duyệt qua tất cả các mục trong danh sách gốc for (Vocab item : vocabList) { // Kiểm tra xem mức xử lý nằm trong khoảng không if (isProcessLevelInRange(item, processLevel)) { // Nếu mức xử lý nằm trong khoảng, thêm vào danh sách đã lọc filteredList.add(item); } } // Kiểm tra xem danh sách đã lọc có dữ liệu hay không if (filteredList.isEmpty()) { // Hiển thị thông báo nếu không có kết quả lọc Toast.makeText(my_word.this, "Không tìm thấy dữ liệu.", Toast.LENGTH_SHORT).show(); } // Cập nhật danh sách trong Adapter với danh sách đã lọc vocabAdapter.filterList(filteredList); } private boolean isProcessLevelInRange(Vocab item, int processLevel) { // Lấy giá trị process từ đối tượng Vocab int processValue = Integer.parseInt(item.getProcess()); // Xác định khoảng giá trị process cho mỗi mức int lowerBound; int upperBound; if (processLevel == 1) { lowerBound = 0; upperBound = 3; } else if (processLevel == 2) { lowerBound = 4; upperBound = 7; } else if (processLevel == 3) { lowerBound = 8; upperBound = 10; } else { // Nếu mức không hợp lệ, trả về false return false; } // Kiểm tra xem giá trị process có nằm trong khoảng không return processValue >= lowerBound && processValue <= upperBound; } private void filterFavorite() { // Tạo một danh sách mới để lưu trữ kết quả lọc ArrayList<Vocab> filteredList = new ArrayList<>(); // Duyệt qua tất cả các mục trong danh sách gốc for (Vocab item : vocabList) { // Kiểm tra xem trường favorite có giá trị "true" không if (item.getFav() != null && item.getFav().equalsIgnoreCase("true")) { // Nếu favorite là "true", thêm vào danh sách đã lọc vocabListFav.add(item); filteredList.add(item); } } // Kiểm tra xem danh sách đã lọc có dữ liệu hay không // Cập nhật danh sách trong Adapter với danh sách đã lọc vocabAdapter.filterList(filteredList); } private void getListFavorite() { // Tạo một danh sách mới để lưu trữ kết quả lọc ArrayList<Vocab> filteredList = new ArrayList<>(); // Duyệt qua tất cả các mục trong danh sách gốc for (Vocab item : vocabList) { // Kiểm tra xem trường favorite có giá trị "true" không if (item.getFav() != null && item.getFav().equalsIgnoreCase("true")) { // Nếu favorite là "true", thêm vào danh sách đã lọc vocabListFav.add(item); } } // Kiểm tra xem danh sách đã lọc có dữ liệu hay không } @Override public void onBackPressed() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Xác nhận thoát"); builder.setMessage("Bạn có chắc chắn muốn thoát ứng dụng?"); builder.setPositiveButton("Có", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); // Đóng ứng dụng nếu người dùng chọn "Có" } }); builder.setNegativeButton("Không", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Không làm gì cả nếu người dùng chọn "Không" dialog.dismiss(); } }); builder.show(); } }
import React from "react"; import postData from "../components/adminpostjob"; import { useSelector, useDispatch } from "react-redux"; import { useRef } from "react"; import setJobList from "../actions/setJobList.js"; import fetchData from "../components/fetchjobdata"; import "../styles/adminjobcreate.css"; const AdminJobCreate = () => { const dispatch = useDispatch(); const jobTitle = useRef(); const jobSalary = useRef(); const jobDescription = useRef(); const companyName = useRef(); const hourly = useRef(); const industry = useRef(); const location = useRef(); const indexStore = useSelector((state) => state.index); const checkPostData = () => { if ( jobTitle.current.value === "" || jobSalary.current.value === "" || jobDescription.current.value === "" || companyName.current.value === "" || industry.current.value === "" || location.current.value === "" ) { alert("Please fill out all fields."); } else { const result = postData( indexStore.accessToken, jobTitle.current.value, jobSalary.current.value, jobDescription.current.value, companyName.current.value, hourly.current.checked ? 1 : 0, industry.current.value, location.current.value ); if (result) { alert("Job posted successfully!"); jobTitle.current.value = ""; jobSalary.current.value = ""; jobDescription.current.value = ""; companyName.current.value = ""; hourly.current.checked = false; industry.current.value = "banking"; fetchData().then((result) => { dispatch(setJobList(result)); }); } else { alert("Error posting job."); } } }; return ( <div className="admin-job-create-container" style={{ width: "100%", height: "100%" }} > <form className="admin-create-form"> <div className="form-group"> <label htmlFor="jobTitle">Job Title:</label> <input type="text" id="jobTitle" name="jobTitle" ref={jobTitle} /> </div> <div className="form-group"> <label htmlFor="industry">Job Industry:</label> <select id="industry" name="industry" ref={industry}> <option value="accounting">Accounting</option> <option value="operations">Operations</option> <option value="hr">HR</option> <option value="marketing">Marketing</option> <option value="executive">Executive</option> <option value="compliance">Compliance</option> <option value="it">I.T.</option> <option value="administration">Administration</option> <option value="mortgage">Mortgage</option> </select> </div> <div className="form-group"> <label htmlFor="location">Location:</label> <input type="text" id="location" name="location" ref={location} /> </div> <div className="form-group"> <label htmlFor="companyName">Company Name:</label> <input type="text" id="companyName" name="companyName" ref={companyName} /> </div> <div className="form-group-radio"> <label htmlFor="salaryType">Salary Type:</label> <div> <label htmlFor="salary">Salary</label> <input type="radio" id="salary" name="salaryType" value="0" /> </div> <div> <label htmlFor="hourly">Hourly</label> <input type="radio" id="hourly" name="salaryType" value="1" ref={hourly} /> </div> </div> <div className="form-group"> <label htmlFor="jobSalary">Job Salary/Hourly Rate:</label> <input type="number" id="jobSalary" name="jobSalary" ref={jobSalary} /> </div> <div className="form-group"> <label htmlFor="jobDescription">Job Description:</label> <textarea id="jobDescription" name="jobDescription" ref={jobDescription} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); const textarea = e.target; const start = textarea.selectionStart; const end = textarea.selectionEnd; const value = textarea.value; textarea.value = value.substring(0, start) + "\n" + value.substring(end); textarea.selectionStart = textarea.selectionEnd = start + 1; } else if (e.key === "Tab") { e.preventDefault(); const textarea = e.target; const start = textarea.selectionStart; const end = textarea.selectionEnd; const value = textarea.value; textarea.value = value.substring(0, start) + "\t" + value.substring(end); textarea.selectionStart = textarea.selectionEnd = start + 1; } }} /> </div> <h2 onClick={() => checkPostData()} className="admin-submit-button"> Submit </h2> </form> </div> ); }; export default AdminJobCreate;
import {ChangeDetectionStrategy, Component, OnDestroy, OnInit} from '@angular/core'; import {StepperService} from './components/stepper/services'; import {Observable, Subject, zip} from 'rxjs'; import {switchMap, takeUntil} from 'rxjs/operators'; import {select, Store} from '@ngrx/store'; import * as fromRoot from '@app/store'; import * as fromDictionaries from '@app/store/dictionaries'; import {PersonalForm} from './components/personal/personal.component'; import {ProfessionalForm} from './components/professional/professional.component'; import * as fromUser from '@app/store/user'; import * as fromForm from '../../store/form'; import {ActivatedRoute, Router} from '@angular/router'; import {MapperService} from './services/mapper/mapper.service'; export interface ProfileForm { personal: PersonalForm; professional: ProfessionalForm; } @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush // to prevent page rendering too often }) export class FormComponent implements OnInit, OnDestroy { dictionaries$: Observable<fromDictionaries.Dictionaries>; dictionariesIsReady$: Observable<boolean>; private user: fromUser.User; personal$: Observable<PersonalForm>; professional$: Observable<ProfessionalForm>; private profile$: Observable<ProfileForm>; private isEditing: boolean; private destroy = new Subject<any>(); loading$: Observable<boolean>; constructor(public stepper: StepperService, private store: Store<fromRoot.State>, private route: ActivatedRoute, private router: Router, private mapper: MapperService) { } ngOnInit(): void { this.user = this.route.snapshot.data.user; this.isEditing = !!this.user; // set it to TRUE if the user data came from resolver this.profile$ = this.store.pipe(select(fromForm.getFormState)); this.personal$ = this.store.pipe(select(fromForm.getPersonalForm)); this.professional$ = this.store.pipe(select(fromForm.getProfessionalForm)); this.dictionaries$ = this.store.pipe(select(fromDictionaries.getDictionaries)); this.dictionariesIsReady$ = this.store.pipe(select(fromDictionaries.getIsReady)); this.loading$ = this.store.pipe(select(fromUser.getLoading)); if (this.user) { const form = this.mapper.userToForm(this.user); this.store.dispatch(new fromForm.Set(form)); } this.stepper.init([ {key: 'personal', label: 'Personal'}, {key: 'professional', label: 'Professional'} ]); this.stepper.complete$.pipe( switchMap(() => zip(this.profile$, this.dictionaries$)), takeUntil(this.destroy) ).subscribe(([profile, dictionaries]) => { this.onComplete(profile, this.user, dictionaries); }); this.stepper.cancel$.pipe(takeUntil(this.destroy)).subscribe(() => { this.router.navigate(['/profile', this.user.uid]); }); } ngOnDestroy(): void { this.destroy.next(); this.destroy.complete(); this.store.dispatch(new fromForm.Clear()); } get title(): string { return this.isEditing ? 'Edit Profile' : 'New Profile'; } onChangedPersonal(data: PersonalForm): void { this.store.dispatch(new fromForm.Update({personal: data})); } onChangedProfessional(data: ProfessionalForm): void { this.store.dispatch(new fromForm.Update({professional: data})); } private onComplete(profile: ProfileForm, user: fromUser.User, dictionaries: fromDictionaries.Dictionaries): void { if (this.isEditing) { const request = this.mapper.formToUserUpdate(profile, user, dictionaries); this.store.dispatch(new fromUser.Update(request)); } else { const request = this.mapper.formToUserCreate(profile, dictionaries); this.store.dispatch(new fromUser.Create(request)); } } }
pragma circom 2.1.4; include "utils.circom"; template BoardID (n, m) { // n = size of board // m = # ships per player signal input board[n][n]; signal input salt; signal output boardID; var sum = 0; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { // board[i][j] should be 0/1 valued board[i][j] * (1 - board[i][j]) === 0; // if it is 0/1, compute the sum and assert that it is equal to m sum += board[i][j]; } } sum === m; // Compute hash of unique serialization component boardToHash = BoardToHash(n); boardToHash.board <== board; boardToHash.salt <== salt; boardID <== boardToHash.hash; } component main = BoardID(3, 3); /* INPUT = { "board": [[0,0,1], [1,0,0], [0,0,1]], "salt": "354729834751283645" } */
package org.techtown.project8_1; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import org.techtown.project7_11.R; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("파일 처리 기초"); Button btnRead, btnWrite; btnRead = findViewById(R.id.btnRead); btnWrite = findViewById(R.id.btnWrite); btnWrite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { FileOutputStream outFs = openFileOutput("file.txt", Context.MODE_PRIVATE); String str = "굿모닝 안드로이드"; outFs.write(str.getBytes()); outFs.close(); Toast.makeText(getApplicationContext(), "file.txt가 생성됨", Toast.LENGTH_SHORT).show(); } catch (IOException e){ btnRead.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try{ FileInputStream inFs = openFileInput("file.txt"); byte[] txt = new byte[30]; inFs.read(txt); String str = new String(txt); Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); inFs.close(); }catch (IOException e){ Toast.makeText(getApplicationContext(), "파일 없음", Toast.LENGTH_SHORT).show(); } } }); } } }); } }
// // Config.swift // NiceComponents // // Created by Brendan on 2021-01-29. // Copyright © 2022 Steamclock Software. All rights reserved. // import os import SwiftUI /// Global settings for all components. /// Themes here will be applied to any components that don't define their own theme. public struct Config { /// Your current component configuration. /// Note that you can only set this configuration once, ideally during app startup. Subsequent updates will be ignored. public static var current: Config { get { return _current } set { guard !hasSetConfig else { os_log("Error! Config has already been set once, at startup. Ignoring config update. ") return } hasSetConfig = true _current = newValue } } private static var _current = Config() private static var hasSetConfig: Bool = false /// The collection of color styles and settings used across components. public var colorTheme: ColorTheme /// The collection of font styles used across components. public var fontTheme: FontTheme // Button Styles public var primaryButtonStyle: NiceButtonStyle public var secondaryButtonStyle: NiceButtonStyle public var borderlessButtonStyle: NiceButtonStyle public var destructiveButtonStyle: NiceButtonStyle // Text and Title Styles public var itemTitleStyle: NiceTextStyle public var screenTitleStyle: NiceTextStyle public var sectionTitleStyle: NiceTextStyle public var bodyTextStyle: NiceTextStyle public var detailTextStyle: NiceTextStyle /// Default is: x:0, y:4, blur: 4px, opacity: 0.15 (black) public var shadowStyle: NiceShadowStyle /** * Create a new component configuration to use for all components in your project. * * - Parameters: * - colorTheme: The collection of color styles and settings used across components. * - fontTheme: The collection of font styles used across components. */ public init(colorTheme: ColorTheme? = nil, fontTheme: FontTheme? = nil) { self.colorTheme = colorTheme ?? ColorTheme() self.fontTheme = fontTheme ?? FontTheme() // Set Button styles primaryButtonStyle = NiceButtonStyle( fontStyle: self.fontTheme.button, surfaceColor: self.colorTheme.primary, onSurfaceColor: self.colorTheme.onPrimary, border: .rounded(color: self.colorTheme.primary, cornerRadius: 8, width: 1) ) secondaryButtonStyle = NiceButtonStyle( fontStyle: self.fontTheme.button, surfaceColor: self.colorTheme.secondary, onSurfaceColor: self.colorTheme.onSecondary, border: .rounded(color: self.colorTheme.secondary, cornerRadius: 8, width: 1) ) borderlessButtonStyle = NiceButtonStyle( fontStyle: self.fontTheme.button, surfaceColor: Color.clear, onSurfaceColor: self.colorTheme.primary, border: NiceBorderStyle.none ) destructiveButtonStyle = NiceButtonStyle( fontStyle: self.fontTheme.button, surfaceColor: self.colorTheme.error, onSurfaceColor: self.colorTheme.onError, border: .rounded(color: self.colorTheme.error, cornerRadius: 8, width: 1) ) // Set Text styles bodyTextStyle = NiceTextStyle( color: self.colorTheme.onSurface, fontStyle: self.fontTheme.body ) detailTextStyle = NiceTextStyle( color: self.colorTheme.onSurface, fontStyle: self.fontTheme.detail ) // Set Title styles itemTitleStyle = NiceTextStyle( color: self.colorTheme.onSurface, fontStyle: self.fontTheme.itemTitle ) screenTitleStyle = NiceTextStyle( color: self.colorTheme.onSurface, fontStyle: self.fontTheme.screenTitle ) sectionTitleStyle = NiceTextStyle( color: self.colorTheme.onSurface, fontStyle: self.fontTheme.sectionTitle ) // Set Shadow style shadowStyle = NiceShadowStyle( color: self.colorTheme.shadow, radius: 4.0, x: 0, y: 4 ) } }
const Category = require('../../models/category') const BaseValidation = require('../base/base-validation') class CategoryValidation extends BaseValidation{ /** * * @param {Category} category */ constructor(category) { super(); this.addValidation(() => this.checkNotNull(category.name, 'Category name must not be null', 10001)) // () - validator() this.addValidation(()=> this.checkLength(category.name,3,10,'Name must be 3-5 interval', 10002)) this.addValidation(()=>this.checkCustomValidation(this.checkContainsXY,category.name,'XY must not be included', 10003)) } checkContainsXY(field) { return !field.includes('xy'); } } module.exports = CategoryValidation;
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { RouterLink } from '@angular/router'; import { SignupService } from '../../services/signup.service'; import Swal from 'sweetalert2'; @Component({ selector: 'app-signup', standalone: true, imports: [RouterLink, ReactiveFormsModule], templateUrl: './signup.component.html', styleUrl: './signup.component.scss' }) export class SignupComponent implements OnInit { public userForm: FormGroup; constructor(private service: SignupService, private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ firstName: ['', Validators.required], lastName: ['', Validators.required], email: ['', Validators.required], password: ['', Validators.required], confirmPassword: ['', Validators.required] }); console.log(this.userForm); } ngOnInit(): void { this.init(); } public addUsers() { this.service.addUsers(this.userForm.value).subscribe( (result: any) => { console.log('Registration Successfully:', result); if (!result.Id) { // Success scenario const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "success", title: "Registration successful" }); } else if (result.status === 401) { // Unauthorized scenario const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "warning", title: "Unauthorized" }); } else if (result.emailExists) { // Email already exists scenario const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "warning", title: "Email already exists" }); } else { // Registration failed scenario const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "error", title: "Registration failed!" }); } }, error => { console.error('Error occurred while adding user:', error); if (error.error && error.error.status === 409) { // Email already registered scenario const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "error", title: "Email already registered!" }); } else if (this.userForm.value.firstName === null || this.userForm.value.lastName === null || this.userForm.value.email === null || this.userForm.value.password === null || this.userForm.value.confirmPassword === null) { // Empty firstName or lastName scenario const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "warning", title: "Something went wrong!" }); } else if (this.userForm.value.password != this.userForm.value.confirmPassword) { // Other registration failure scenarios const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "error", title: "Password not match!" }); } else { // Other registration failure scenarios const Toast = Swal.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 2500, timerProgressBar: true, didOpen: (toast) => { toast.onmouseenter = Swal.stopTimer; toast.onmouseleave = Swal.resumeTimer; } }); Toast.fire({ icon: "error", title: "Registration failed!" }); } } ); } private init(): void { this.userForm = this.formBuilder.group({ firstName: [], lastName: [], email: [], password: [], confirmPassword: [] }); // console.log(this.userForm); } }
@extends('layouts.app') @section('title') Nueva orden de trabajo @endsection @section('content') <div class="card-body"> <form action="{{url('/admin/ordenes')}}" method="post" enctype="multipart/form-data"> @csrf <div class="form-group row"> <label class="col-md-4 col-form-label" for="tipo"> Estado </label> <div class="col-md-8 form-radio"> <div class="form-check-inline my-1"> <label> <input type="radio" name="estado" id="estado" value="0" checked="checked"> <i class="helper"></i>En proceso </label> </div> <div class="form-check-inline my-1"> <label> <input type="radio" name="estado" id="estado" value="1"> <i class="helper"></i>Concluido </label> </div> </div> </div> <div class="form-group row {{ $errors->has('nombre') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="nombre"> Nombres o razon social </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('nombres') ? ' form-control-warning' : '' }}" type="text" id="nombres" name="nombres" value="{{old('nombres')}}" > @if ($errors->has('nombres')) <div class="col-form-label"> {{ $errors->first('nombres') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('email') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="email"> Email </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('email') ? ' form-control-warning' : '' }}" type="text" id="email" name="email" value="{{old('email')}}"> @if ($errors->has('email')) <div class="col-form-label"> {{ $errors->first('email') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('doc') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="doc"> DNI o RUC </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('doc') ? ' form-control-warning' : '' }}" type="text" id="doc" name="doc" value="{{old('doc')}}"> @if ($errors->has('doc')) <div class="col-form-label"> {{ $errors->first('doc') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('cel') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="cel"> Cel. </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('cel') ? ' form-control-warning' : '' }}" type="text" id="cel" name="cel" value="{{old('cel')}}"> @if ($errors->has('cel')) <div class="col-form-label"> {{ $errors->first('cel') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('direccion') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="direccion"> Dirección </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('direccion') ? ' form-control-warning' : '' }}" type="text" id="direccion" name="direccion" value="{{old('direccion')}}"> @if ($errors->has('direccion')) <div class="col-form-label"> {{ $errors->first('direccion') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('tipo') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="tipo"> Tipo de servicio </label> <div class="col-sm-8"> {!! Form::select('tipo',$tipo,old('tipo'),["class"=>"form-control select2 ",'placeholder' => '-- Tipo de servicio --',"required"=>"","id"=>"tipo"]) !!} @if ($errors->has('tipo')) <div class="col-form-label"> {{ $errors->first('tipo') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('observaciones') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="descripcion"> Descripción </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('descripcion') ? ' form-control-warning' : '' }}" type="text" id="descripcion" name="descripcion" value="{{old('descripcion')}}"> @if ($errors->has('descripcion')) <div class="col-form-label"> {{ $errors->first('descripcion') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('horometro') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="horometro"> Horometro </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('horometro') ? ' form-control-warning' : '' }}" type="number" id="horometro" name="horometro" value="{{old('horometro')}}"> @if ($errors->has('horometro')) <div class="col-form-label"> {{ $errors->first('horometro') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('kilometraje') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="kilometraje"> Kilometraje </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('kilometraje') ? ' form-control-warning' : '' }}" type="number" id="kilometraje" name="kilometraje" value="{{old('kilometraje')}}"> @if ($errors->has('kilometraje')) <div class="col-form-label"> {{ $errors->first('kilometraje') }} </div> @endif </div> </div> <div class="form-group row {{ $errors->has('entrega') ? ' has-warning' : '' }}"> <label for="example-text-input" class="col-sm-4 col-form-label" for="entrega"> Fecha de entrega </label> <div class="col-sm-8"> <input class="form-control {{ $errors->has('entrega') ? ' form-control-warning' : '' }}" type="date" id="entrega" name="entrega" value="{{old('entrega')}}"> @if ($errors->has('entrega')) <div class="col-form-label"> {{ $errors->first('entrega') }} </div> @endif </div> </div> <br> <br> <div class="col-sm-10 offset-sm-1"> <div class="form-group row text-center"> <div class="col-sm-6"> <button type="submit" class="btn btn-lg btn-warning waves-effect waves-light"> <i class="icofont icofont-save"></i> Guardar </button> </div> <div class="col-sm-6"> <button type="reset" class="btn btn-lg btn-danger waves-effect waves-light"> <i class="icofont icofont-save"></i> Borrar </button> </div> </div> </div> </form> </div> @endsection @section('js') <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <script> $(document).ready(function() { $('.select2').select2(); }); $( ".select2" ).select2({ theme: "bootstrap4" }); </script> @endsection
import React, { useEffect, useMemo } from 'react'; import { makeStyles, Button, Box, Typography, FormHelperText, FormLabel } from '@material-ui/core' import { change, Field, formValueSelector, initialize, reduxForm, SubmissionError } from 'redux-form'; import axios from 'axios'; import TextInput from '../../library/form/TextInput'; import { showProgressBar, hideProgressBar } from '../../../store/actions/progressActions'; import { connect } from 'react-redux'; import { showSuccess } from '../../../store/actions/alertActions'; import { compose } from 'redux'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faLongArrowAltLeft } from '@fortawesome/free-solid-svg-icons'; import { Link, useHistory } from 'react-router-dom'; import { addNewTxns } from '../../../store/actions/accountActions'; import RadioInput from '../../library/form/RadioInput'; import SelectInput from '../../library/form/SelectInput'; import { paymentModes, accountHeadTypes } from '../../../utils/constants'; import { useSelector } from 'react-redux'; import DateTimeInput from '../../library/form/DateTimeInput'; import moment from 'moment'; import { allowOnlyPostiveNumber } from '../../../utils'; import ReactGA from "react-ga4"; const paymentModeOptions = [ { id: paymentModes.PAYMENT_MODE_CASH, title: "Cash" }, { id: paymentModes.PAYMENT_MODE_BANK, title: "Bank" }, ] const transactionTypeLabelMap = { [accountHeadTypes.ACCOUNT_HEAD_TYPE_GENERAL]: "Transfer amount in", [accountHeadTypes.ACCOUNT_HEAD_TYPE_INCOME]: "Receive amount in", [accountHeadTypes.ACCOUNT_HEAD_TYPE_EXPENSE]: "Pay amount in", } const generalHeadTxnTypes = [ { id: -1, title: "Pay amount"}, { id: 1, title: "Receive amount"}, ] const bankAccountHeadTxnTypes = [ { id: -1, title: "Deposit Cash"}, { id: 1, title: "Withdraw Cash"}, ] const formName = 'newTransaction'; const formSelector = formValueSelector(formName); const useStyles = makeStyles(theme => ({ box: { display: 'flex', justifyContent: 'center', alignItems: 'center', margin: 'auto' }, progress: { marginLeft: theme.spacing(1) }, formError: { textAlign: "center" } })); function NewTransaction(props) { const history = useHistory(); const classes = useStyles(); const { handleSubmit, pristine, submitSucceeded, submitting, error, invalid, dirty, dispatch } = props; const { banks, heads, defaultBankId, lastEndOfDay } = props; useEffect(() => { ReactGA.send({ hitType: "pageview", page: "/accounts/transactions/new", 'title' : "New Account Txn" }); }, []); useEffect(() => { dispatch( initialize(formName, { headId: 0, type: paymentModes.PAYMENT_MODE_CASH, generalTxnType: -1, time: moment().format("DD MMMM, YYYY hh:mm A") } ) ); }, [dispatch]); const headId = useSelector(state => formSelector(state, 'headId')); const type = useSelector(state => formSelector(state, 'type')); const generalTxnType = useSelector(state => formSelector(state, 'generalTxnType')); const headOptions = useMemo(() => { let options = heads.map(head => ({ id: head._id, title: head.name }) ); return [{ id: 0, title: "Select Account" }, ...options] }, [heads]); const selectedHead = useMemo(() => heads.find(head => head._id === headId), [heads, headId]); const bankOptions = useMemo(() => { return banks.map(bank => ({ id: bank._id, title: bank.name }) ); }, [banks]); useEffect(() => { if(selectedHead && selectedHead.name === "Bank Account") dispatch( change(formName, 'type', paymentModes.PAYMENT_MODE_CASH) ); if((selectedHead && selectedHead.name === "Bank Account") || parseInt(type) === paymentModes.PAYMENT_MODE_BANK) dispatch( change(formName, 'bankId', defaultBankId) ); else if ( parseInt(type) === paymentModes.PAYMENT_MODE_CASH ) dispatch( change(formName, 'bankId', null) ); }, [selectedHead, type, defaultBankId, dispatch]); useEffect(() => { dispatch( change(formName, 'bankId', defaultBankId) ); }, [defaultBankId, dispatch]); useEffect(() => { if(submitSucceeded) history.push('/accounts'); }, [submitSucceeded, history]) return( <> <Box width="100%" justifyContent="flex-end" display="flex"> <Button disableElevation color="primary" startIcon={<FontAwesomeIcon icon={faLongArrowAltLeft} />} component={Link} to="/accounts"> Transactions </Button> </Box> <Box margin="auto" width={{ xs: '100%', md: '50%' }}> <Typography gutterBottom variant="h6" align="center">Add New Transaction</Typography> <form onSubmit={handleSubmit}> <Box textAlign="center" mb={2}> <Field component={DateTimeInput} label="Transaction Time" name="time" dateFormat="DD MMMM, YYYY hh:mm A" fullWidth={true} inputVariant="outlined" margin="dense" emptyLabel="" minDate={ moment(lastEndOfDay).toDate() } maxDate={ moment().toDate() } showTodayButton /> </Box> <Box textAlign="center"> <Field component={SelectInput} options={headOptions} name="headId" fullWidth={true} variant="outlined" margin="dense" /> </Box> <Box textAlign="center"> { selectedHead && selectedHead.name === "Bank Account" ? <FormLabel> Cash Transaction <br/> withdraw/deposit store cash into bank</FormLabel> : <Field component={RadioInput} options={paymentModeOptions} label={ selectedHead ? transactionTypeLabelMap[selectedHead.type] : "Mode" } id="type" name="type" disabled={headId === 0} /> } </Box> { (selectedHead && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_GENERAL ) ? <Box textAlign="center" mb={2} width="100%"> <Field component={RadioInput} options={selectedHead && selectedHead.name === "Bank Account" ? bankAccountHeadTxnTypes : generalHeadTxnTypes} name="generalTxnType" variant="outlined" margin="dense" disabled={headId === 0} /> </Box> : null } <Box textAlign="center" mb={2}> <FormLabel> { /*Bank Deposit or withdrawl*/ } { (selectedHead && selectedHead.name === "Bank Account") && parseInt(generalTxnType) === -1 ? "This will reduce cash in store and amount will be added to your selected bank" : null } { (selectedHead && selectedHead.name === "Bank Account") && parseInt(generalTxnType) === 1 ? "This will increase cash in store and amount will be deducted from your selected bank" : null } { /*General Head except "Bank Account" Cash transaction*/ } { (selectedHead && selectedHead.name !== "Bank Account" && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_GENERAL) && parseInt(type) === paymentModes.PAYMENT_MODE_CASH && parseInt(generalTxnType) === -1 ? "This will reduce cash in store" : null } { (selectedHead && selectedHead.name !== "Bank Account" && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_GENERAL) && parseInt(type) === paymentModes.PAYMENT_MODE_CASH && parseInt(generalTxnType) === 1 ? "This will increase cash in store" : null } { /*General Head except "Bank Account" Bank transaction*/ } { (selectedHead && selectedHead.name !== "Bank Account" && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_GENERAL) && parseInt(type) === paymentModes.PAYMENT_MODE_BANK && parseInt(generalTxnType) === -1 ? "The amount will be deducted from your selected bank account" : null } { (selectedHead && selectedHead.name !== "Bank Account" && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_GENERAL) && parseInt(type) === paymentModes.PAYMENT_MODE_BANK && parseInt(generalTxnType) === 1 ? "The amount will be added to your selected bank account" : null } { /*Income heads cash transaction*/ } { (selectedHead && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_INCOME) && parseInt(type) === paymentModes.PAYMENT_MODE_CASH ? "This will increase cash in store" : null } { (selectedHead && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_INCOME) && parseInt(type) === paymentModes.PAYMENT_MODE_BANK ? "The income amount will be added to your selected bank account" : null } { /*Income heads cash transaction*/ } { (selectedHead && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_EXPENSE) && parseInt(type) === paymentModes.PAYMENT_MODE_CASH ? "This will reduce cash in store" : null } { (selectedHead && selectedHead.type === accountHeadTypes.ACCOUNT_HEAD_TYPE_EXPENSE) && parseInt(type) === paymentModes.PAYMENT_MODE_BANK ? "The expense amount will be deducted from your selected bank account" : null } </FormLabel> </Box> { (selectedHead && selectedHead.name === "Bank Account") || parseInt(type) === paymentModes.PAYMENT_MODE_BANK ? <Box> <Field component={SelectInput} options={bankOptions} name="bankId" fullWidth={true} variant="outlined" margin="dense" disabled={headId === 0} /> </Box> : null } <Box> <Field component={TextInput} id="amount" name="amount" label="Amount" placeholder="Amount..." fullWidth={true} variant="outlined" margin="dense" onKeyDown={allowOnlyPostiveNumber} disabled={headId === 0} /> </Box> <Box> <Field component={TextInput} id="notes" name="notes" label="Notes" placeholder="Notes..." type="text" fullWidth={true} variant="outlined" multiline rows={3} margin="dense" disabled={headId === 0} /> </Box> <Box textAlign="center"> <Button disableElevation type="submit" variant="contained" color="primary" disabled={pristine || submitting || invalid || !dirty} > Add Transaction </Button> { <FormHelperText className={classes.formError} error={true} style={{visibility: !submitting && error ? 'visible' : 'hidden' }}> <Typography component="span">{ error ? error : 'invalid request' }</Typography> </FormHelperText> } </Box> </form> </Box> </> ) } const onSubmit = (values, dispatch, { storeId }) => { dispatch(showProgressBar()); return axios.post('/api/accounts/transactions/new', {storeId, ...values, time: moment(values.time, "DD MMMM, YYYY hh:mm A").toDate()}).then( response => { dispatch(hideProgressBar()); if(response.data.length) { dispatch( addNewTxns(storeId, response.data) ); dispatch( showSuccess("New transaction added") ); } }).catch(err => { dispatch(hideProgressBar()); throw new SubmissionError({ _error: err.response && err.response.data.message ? err.response.data.message: err.message }); }); } const validate = (values, props) => { const { dirty, lastEndOfDay } = props; if(!dirty) return {}; const errors = {}; if(lastEndOfDay && moment(values.time, "DD MMMM, YYYY hh:mm A") <= moment(lastEndOfDay)) errors.time = "Date & time should be after last day closing: " + moment(lastEndOfDay).format("DD MMMM, YYYY hh:mm A"); else if(moment(values.time, "DD MMMM, YYYY hh:mm A") > moment()) errors.time = "Date & time should not be after current time: " + moment().format("DD MMMM, YYYY hh:mm A"); if(!values.headId) errors.headId = "Please select an account head first"; if(!values.amount) errors.amount = "Amount is required"; else if(Number(values.amount) < 1) errors.amount = "invalid amount"; return errors; } const mapStateToProps = state => { const storeId = state.stores.selectedStoreId; const store = state.stores.stores.find(store => store._id === storeId); let heads = state.accounts.heads[storeId] ? state.accounts.heads[storeId] : []; heads = heads.filter(head => head.systemHead === false);//get only non system head for custom transaction const banks = state.accounts.banks[storeId] ? state.accounts.banks[storeId] : []; const defaultBank = banks.find(bank => bank.default === true); return{ storeId, heads, banks, defaultBankId: defaultBank ? defaultBank._id : null, lastEndOfDay: store.lastEndOfDay } } export default compose( connect(mapStateToProps), reduxForm({ 'form': formName, validate, onSubmit }) )(NewTransaction);
import os import numpy as np import scipy as sp import scipy.constants as const from scipy.interpolate import interp1d from scipy.integrate import quad from scipy.interpolate import RegularGridInterpolator import time import configparser from multiprocessing import Pool import itertools import pickle from marcia import Data from marcia import GPconfig from marcia.backend import kernel as kbackend class Kernel(object): """ General Gaussian process modelling that all the specific kernels must be inherited from. Inputs would be the appropriate amplitude and scaling parameters needed for the particular model. This initialisation retuns the final covarinace matrices as functions of kernal paramters. """ def __init__(self, data, filename = None): """ Initialisation takes the data and the filename for the config file, which declares all the GP configurations. """ self.clight = 299792458. / 1000. # km/s # Read the config file self.filename = filename if filename else os.path.join(os.path.dirname(__file__), 'GPconfig.ini') print(f'Loading the config file from {self.filename} ... ') MTGP = GPconfig.GPConfig(self.filename).__dict__ # Read the models and the number of tasks self.models = MTGP['models'] self.nTasks = MTGP['n_Tasks'] self.nmodel = self.nTasks # Read the nus from the config file self.nus = MTGP['nus'] # The data contains the list/lists of x-axes self.data = data self.ndata = len(data) # Print details of the run when the class is initialised print(f'Number of tasks: {self.nTasks}') print(f'Number of datasets: {len(self.data)}') print(f'Kernels: {self.models}') self.setup_kernel_data() # To check if the number of datasets is equal to the number of models if len(self.data) != self.nmodel: raise ValueError(f'Error: data length is {len(self.data)} and does not match the number of kernels {self.nmodel}') if len(set(self.models)) == 1 and self.nTasks > 1 and self.models[0] == 'SE': print(f'Perfroming a multi task Gaussian process regression using {self.models[0]} kernels and {self.nTasks} tasks') pass elif len(set(self.models)) == 1 and self.nTasks > 1 and self.models[0] in ['M92', 'M72', 'M52', 'M32']: # if all the kernels are the same, we can define the cross covariance matrix print(f'Perfroming a multi task Gaussian process regression using {self.models[0]} kernels and {self.nTasks} tasks') # To check if the interpolated cross covariance matrix exists in the backend folder self.file_path = os.path.join(os.path.dirname(__file__), f'backend/cross_kernels/KcMM_{self.models[0]}_{self.models[0]}.pck') print(f'Checking if the cross covariance matrix exists in {self.file_path} ... ') if not os.path.exists(self.file_path): # Here we update any necessary interpolation parameters self.nu1 = self.nu2 = self.nus[0] self.make_cross_kernel() print(f'Loading the cross covariance matrix for the multi task GP model with the {self.models[0]} kernel ... ') with open(self.file_path, 'rb') as f: self.KcMM_int = pickle.load(f) elif len(set(self.models)) == 1 and self.nTasks==1: print(f'Perfroming a simple Gaussian process regression for a single task using {self.models[0]} kernel') else: # Cross covariance is not defined for different kernels raise ValueError('Error: Multi kernel cross covariance matrix is not defined, only multi task for same kernel is defined') # To initialise the total covariance matrix as a dictionary which is a function of the kernel parameters self.CovMat = {} def setup_kernel_data(self): """Define kernels and data in a dictionary.""" self.kernel_f = {} self.data_f = {} for i in range(self.nTasks): self.kernel_f[f't_{i}'] = self.models[i] self.data_f[f't_{i}'] = self.data[i] # Define the data_tau dictionary, which contains the difference between the x-axes of the datasets self.data_tau = {} for i in range(self.nTasks): for j in range(self.nTasks): self.data_tau[f't_{i}{j}'] = self.data_f[f't_{i}'][:, None] - self.data_f[f't_{j}'][None, :] def __call__(self, pars): """ It returns the covariance matrix for the GP model for the given paramters """ # We set the self-scaling in the likelihood function and here simply create the dictionary of parameters # self.CovMat_all = np.block([[ pars[i,0]* pars[j,0]*self.CovMat[f't_{i}{j}']([pars[i,1]* pars[j,1], self.data_tau[f't_{i}{j}']]) for i in range(self.nTasks)] for j in range(self.nTasks)]) self.CovMat_all = self.CovMat_all(pars) return self.CovMat_all # Define the special fucntions needed for the generalised matern kernel def _spkv_(self, tau, l1): return sp.special.kv(2., 3. * np.abs(tau) / l1) def _spgamma_(self, x): return sp.special.gamma(x) def gMdef(self, tau, nu, l1): """ Defines the basis function for the GP model and returns a vector Finally I define only ine single function for the basis function This is independent of the amplitude paramter sigma_f """ x = np.abs(tau) if nu == 0.0: # Squared Exponential kernel return np.exp(- (x**2.)/(2. * l1**2.)) else: # Generalised Matern kernel A, B, C = kbackend.gMdef(tau,l1,nu) A = A * (self._spgamma_(nu/2. - 1./4.)/self._spgamma_(nu/2. + 1./4.))**(1./2.) * (self._spgamma_(nu + 1./2.)/self._spgamma_(nu))**(1./4.) B = B / self._spgamma_(nu/2. - 1./4.) return A**2. * B * C**(nu/2. - 1./4.) * self._spkv_(tau,l1) / np.pi def gdMdef(self, tau, nu, l1): """ Defines the derivative of the basis function for the GP model and returns a vector Finally I define only ine single function for the basis function""" B = sp.special.kv(1./4. * (5. - 2. * nu), np.sqrt(2.) * np.sqrt(nu) * np.sqrt(tau**2.) / l1) C = np.sqrt(self._spgamma_(1./2. + nu) / self._spgamma_(nu)) A, D = kbackend.gdMdef(tau, l1, nu) D = D * self._spgamma_(1./4. + nu/2.) return A * B * C / D def gMMdef_integrand(self, params): tau, l1, l2 = params gMMdef_integrand = lambda u: self.gMdef(u, self.nu1, l1) * self.gMdef(tau - u, self.nu2, l2) integral, _ = quad(gMMdef_integrand, -np.inf, np.inf, epsabs=1e-8, epsrel=1e-8, limit=100) return integral def KcMM(self, l1_values, l2_values, tau_values): """ Defines the cross kernel function for the GP model and returns the covariance matrix """ integrals = np.zeros((len(tau_values), len(l2_values), len(l1_values))) params = list(itertools.product(tau_values, l2_values, l1_values)) with Pool() as pool: integrals = pool.map(self.gMMdef_integrand, params) integrals = np.array(integrals).reshape((len(tau_values), len(l2_values), len(l1_values))) return RegularGridInterpolator((tau_values, l2_values, l1_values), integrals, bounds_error=False, fill_value=None) def matern(self, nu, x1, x2, l_s): """ Defines the generalised matern kernel https://en.wikipedia.org/wiki/Mat%C3%A9rn_covariance_function nu is a positive half-integer that determines the differentiability of the function and the smoothness of the resulting Gaussian process sample paths. nu = 1/2, 3/2, 5/2, ... tend to be used most often in practice. nu tends to infinity, the matern kernel tends to the squared exponential kernel nu tends to 0, the matern kernel tends to the absolute exponential kernel The input x1 and x2 are the x-axes of the data points and l_s is the scale length """ # Here to-do the nu = half-integer cases -- Sandeep # This fucntion returns nan when x1 = x2, so we need to replace nan with zero return np.nan_to_num((2.**(1.-nu)/sp.special.gamma(nu)) * ((np.sqrt(2.*nu) * np.abs(x1-x2))/l_s)**nu * sp.special.kv(nu, (np.sqrt(2.*nu) * np.abs(x1-x2))/l_s)) + np.eye(len(x1)) def kernel(self, model, params, x1, x2=None, mat_nu=None): """ Defines the kernel function for the GP model and returns the covariance matrix """ if x2 is None: x2 = x1 if model == 'SE': # Squared Exponential kernel return params[0]**2. * np.exp(- ((x1[:, None]-x2[None, :])**2.)/(2. * params[1]**2.)) if model in ['M92', 'M72', 'M52', 'M32']: # Matern 9/2 kernel return params[0]**2. * self.matern(mat_nu, x1[:, None], x2[None, :], params[1]) if model == 'matern' and mat_nu is not None: return params[0]**2. * self.matern(mat_nu, x1[:, None], x2[None, :], params[1]) def cross_kernel(self, model1, model2, params1, params2, x1, x2): """ Defines the cross kernel function for the GP model and returns the covariance matrix """ if model1 == model2: model_here = model1 # difference between x1 and x2 x1x2 = x1[:, None]-x2[None, :] # product of the sigmas sig1sig2 = params1[0] * params2[0] if model_here == 'SE': # Squared Exponential kernel # product of the scale lengths l1l2 = params1[1] * params2[1] # quadrature of length scales l1l2_quad = params1[1]**2. + params2[1]**2. # This fucntion boils down to the SE kernel function when the scale lengths are equal for both the datasets return sig1sig2 * np.exp(- (x1x2**2.)/(l1l2_quad)) * np.sqrt(2. * l1l2 / l1l2_quad) elif model_here in ['M92', 'M72', 'M52', 'M32']: # the pickle file name is the 'KcMM_M92_M92.pkl' where the first M92 is the model1 and the second M92 is the model2 lambda_func = np.vectorize(lambda x: self.KcMM_int([x, params1[1], params2[1]])) return sig1sig2 * np.array(lambda_func(x1x2)) else: raise ValueError(f'Error: Cross kernel not defined for {model1} and {model2}') def Cov_Mat(self, params): """ Defines the covariance matrix for the GP model and returns the covariance matrix """ # To create a dictionary of covariance matrices for each task for i in range(self.nTasks): for j in range(self.nTasks): if i == j: self.CovMat[f't_{i}{j}'] = self.kernel(self.kernel_f[f't_{i}'], params[i], self.data_f[f't_{i}'], mat_nu=self.nus[i]) elif i < j: self.CovMat[f't_{i}{j}'] = np.transpose(self.cross_kernel(self.kernel_f[f't_{i}'], self.kernel_f[f't_{j}'], params[i], params[j], self.data_f[f't_{i}'], self.data_f[f't_{j}'])) else: self.CovMat[f't_{i}{j}'] = np.transpose(self.CovMat[f't_{j}{i}']) # To join all the covariance matrices defined above in the dictionaries into one big covariance matrix taking into account the cross correlations between the datasets CovMat_all = np.block([[ self.CovMat[f't_{i}{j}'] for i in range(self.nTasks)] for j in range(self.nTasks)]) return CovMat_all def make_cross_kernel(self): """This function is used to create and save the interpolated cross kernel for the multi task GP model""" print(f'Constructing the cross covariance matrix for the multi task GP model with the {self.models[0]} kernel ... ') self.nu1 = self.nu2 = self.nus[0] # The following has to be changed to modify the resolution of the cross covariance matrix l1_values = np.linspace(0.01, 20, 100) l2_values = np.linspace(0.01, 20, 100) tau_values = np.linspace(-10, 10, 100) integrals = np.zeros((len(tau_values), len(l2_values), len(l1_values))) params = list(itertools.product(tau_values, l2_values, l1_values)) with Pool() as pool: integrals = pool.map(self.gMMdef_integrand, params) integrals = np.array(integrals).reshape((len(tau_values), len(l2_values), len(l1_values))) KcMM_int = RegularGridInterpolator((tau_values, l2_values, l1_values), integrals, bounds_error=False, fill_value=None) with open(self.file_path, 'wb') as f: pickle.dump(KcMM_int, f) print(f'Cross covariance matrix saved in {self.file_path}') # def reconstruct(self, x_star): # """ Function to reconstruct the GP model for the given x_star values""" # # We define the covariance matrix for the given parameters # self.CovMat_all = self.Cov_Mat(self.params) # # We define the mean function for the given parameters # self.mean = np.zeros(len(self.CovMat_all)) # # We define the data covariance matrix for the given parameters # self.D_covmat = self.Cov_Mat(self.params)[0:self.ndata, 0:self.ndata]
color cCrowded = color(205, 30, 0); color cLonely = color(205, 100, 0); color cHappy = color(30, 105, 0); class Boid { PVector position; PVector direction; float speed; int viewRange;// = 100; int personalSpace;// = 20; float agility;// = .95; float maxSpeed;// = 5; boolean lonely, crowded; Boid(int width, int height) { //apply attributes viewRange = int(random(50, 100)); personalSpace = int(random(20, 40)); agility = random(.95, .9999); maxSpeed = random(3, 5); //set position & speed position = new PVector(random(width), random(height)); direction = PVector.random2D(); speed = random(maxSpeed/4, maxSpeed); } void flock(Boid[] swarm) { lonely = true; crowded = false; int nsCount = 0, psCount = 0; PVector swarmCom = new PVector(), nsDirection = new PVector(), psPressure = new PVector(); float nsSpeed = 0; //find visible boids & close boids for (int i=0; i<swarm.length; i++) { swarmCom.add(swarm[i].position); if (swarm[i]==this) continue; float dist = swarm[i].position.dist(position); if (dist<viewRange) { //add vector to near swarm average nsCount++; nsDirection.add(swarm[i].direction); nsSpeed += swarm[i].speed; if (dist<=personalSpace) { psCount++; psPressure.add(swarm[i].position); } } } if (nsCount > 0) { lonely = false; //normalize swarm average nsSpeed = nsSpeed/nsCount; nsDirection.normalize(); //apply swarm average to boid speed = min((agility*speed)+((1-agility)*nsSpeed), maxSpeed); direction.mult(agility).add(nsDirection.mult(1-agility)).normalize(); } //adjust heading towards COM swarmCom.div(swarm.length).sub(position).normalize(); direction.mult(agility).add(swarmCom.mult(1-agility)).normalize(); if (psCount > 0) { crowded = true; //adjust heading to avoid other boids psPressure.div(psCount).sub(position).mult(-1); speed = min((agility*speed)+((1-agility)*(psPressure.mag()*maxSpeed/personalSpace)), maxSpeed); psPressure.normalize(); direction.mult(agility*1.05).add(psPressure.mult(1-(agility/1.05))).normalize(); } } void move() { //move based on current vectors position.add(PVector.mult(direction, speed)); //toroidal space, although flocking won't calculate correctly at the edges if (position.x<0) position.x += width; if (position.x>width) position.x -= width; if (position.y<0) position.y += height; if (position.y>height) position.y -= height; } void draw() { drawBoid( position, direction, speed, maxSpeed, viewRange, personalSpace, agility, lonely ? cLonely : crowded ? cCrowded : cHappy ); } }
#include "Cat.hpp" /* ** ------------------------------- CONSTRUCTOR -------------------------------- */ Cat::Cat() { this->type = "Cat"; this->brain = new Brain(); std::cout << "Cat constructor executed" << std::endl; } Cat::Cat(const Cat& src) { std::cout << "Cat copy constructor executed" << std::endl; if (this != &src) { *this = src; } } /* ** -------------------------------- DESTRUCTOR -------------------------------- */ Cat::~Cat() { delete this->brain; std::cout << "Cat destructor executed" << std::endl; } /* ** --------------------------------- OVERLOAD --------------------------------- */ Cat& Cat::operator=(Cat const& rhs) { if (this != &rhs) { Animal::operator=(rhs); delete this->brain; this->brain = new Brain(*(rhs.brain)); } return *this; } /* ** --------------------------------- METHODS ---------------------------------- */ void Cat::makeSound() const { std::cout << "Nya-! Nya-!" << std::endl; } void Cat::showIdeas() const { this->brain->showIdeas(); }; void Cat::setIdea(std::string idea) { this->brain->setIdea(idea); }; /* ** --------------------------------- ACCESSOR --------------------------------- */ /* ************************************************************************** */
step "Aprende la versión de tu Mac OS X" do message <<-MARKDOWN * Haz click en el ícono de Apple en la esquina superior izquierda de tu pantalla. * Selecciona "Acerca de esta Mac". * En la ventana que se muestra, debajo del título "Mac OS X" habrá un número de versión. * Si comienza con 10.9, tienes **Mavericks**. * Si comienza con 10.8, tienes **Mountain Lion**. * Si comienza con 10.7, tienes **Lion**. * Si comienza con 10.6, tienes **Snow Leopard**. * Si comienza con 10.5, tienes **Leopard**. * Si comienza con 10.4, tienes **Tiger**. * Si comienza con 10.3, tienes **Panther**. * Escribe la versión de Mac OS X que tienes. * Además, a la derecha de "Processor", habrá un tipo de procesador. * Si termina con **Intel Core i7**, **Intel Core i5**, o **Intel Core i3**, puedes seguir. * Si termina con **Intel Core 2 Duo**, puedes seguir. * Si termina con **Intel Core Duo** o algo más, no puedes seguir. Por favor contacta a un instructor. * Una vez que hayas terminado, puedes cerrar la ventana "Acerca de esta Mac". Abajo hay un ejemplo. ![OS X Snow Leopard](img/AboutThisMac.png) MARKDOWN end step "Escoge tus instrucciones" do option "Mavericks" do link "osx_rvm" end option "Mountain Lion/Lion/Snow Leopard" do option_half "RailsInstaller" do message "RailsInstaller es una forma fácil de empezar a trabajar con Ruby y Rails en OSX. Intenta esto primero." link "osx_instalador_rails" end option_half "Manualmente" do message "Si algo va mal con RailsInstaller, o quieres hacer las cosas por 'el camino largo', usa estas instrucciones." link "osx_rvm" end end option "Leopard/Tiger/Panther" do important "Si es posible, deberías intentar actualizar a **Snow Leopard**. Apple ya no lo vende en la App Store, por lo que tendrás que comprarlo [online](http://store.apple.com/us/product/MC573Z/A/mac-os-x-106-snow-leopard) o conseguir una copia de un amigo." message "De lo contrario, puedes intentar seguir las intrucciones de Panther, pero prepárate para algunas dificultades." link "osx_panther" end end
import { useTranslation } from 'next-i18next' import styles from './ConfirmDialog.module.scss' export type ConfirmDialogProps = { open: boolean title: string children: React.ReactNode colorTheme?: 'light' | 'dark' buttonString?: string ariaLabel?: string onConfirm: () => void } export const ConfirmDialog = ({ open, title, children, colorTheme = 'light', buttonString, ariaLabel = 'Confirm_OK', onConfirm }: ConfirmDialogProps) => { const { t } = useTranslation() const displayDialog = open ? 'dialog-visible' : 'dialog-hidden' const btnString = buttonString ? buttonString : t('STRID_cmn_ok') return ( <div className={styles[displayDialog]}> <div className={styles[`overlay-${colorTheme}`]}> <div className={`absolute-center ${styles[`dialog-${colorTheme}`]}`}> <div className={styles.contentsWrap}> <h2 className={`text-xl-bold ${styles.title}`}>{title}</h2> {children} </div> <div className={styles[`horizon-${colorTheme}`]}></div> <button className={`${`button-active-${colorTheme}`} ${styles.confirmButton}`} aria-label={ariaLabel} onClick={onConfirm}> {btnString} </button> </div> </div> </div> ) }
# xlsx2xliff ### Convert Bilingual Excel Files to XLIFF with a GUI ![image](https://github.com/wtigga/xlsx2xliff/assets/7037184/e3124d6b-ade6-455d-ba2b-35f245104bae) ## Description `xlsx2xliff` is a user-friendly Python script that allows you to convert bilingual Excel files into XLIFF (XML Localization Interchange File Format). This tool is especially useful for localization and translation tasks, such as QA with xBench. Key features: - Runs locally on your computer and does not transfer any data outside of your system. - Automatically add 'TextID' and 'EXTRA' information to the 'note' section of translatable elements (if such columns are present). - Written in Python, and it can be compiled into an executable (*.exe) for use on any computer. It can also be compiled for other platforms such as macOS and Linux from the source code. ## How It Works 1. **Select Source File:** Click the 'Select Excel File' button to open your bilingual Excel file. 2. **Choose Output Location:** Click the 'Save XLIFF to' button to select the location where the XLIFF file will be saved. 3. **Select Source and Target Language Columns:** Use the drop-down menus to choose the source and target language columns from your Excel file. 4. **Select Language Codes**: Use dropdown on the right to pick the corresponding codes. 5. **Perform Conversion:** Click 'Save to XLIFF' to convert the Excel file into XLIFF format. The program will automatically iterate over all sheets in the Excel file, so ensure that the headers are consistent across all sheets. ## Libraries Used This project utilizes the following Python libraries: - [pandas](https://pandas.pydata.org/): For data manipulation and handling Excel files. - [tkinter](https://docs.python.org/3/library/tkinter.html): For the graphical user interface. - [xml.etree.ElementTree](https://docs.python.org/3/library/xml.etree.elementtree.html): For working with XML data. - [webbrowser](https://docs.python.org/3/library/webbrowser.html): For opening URLs in a web browser. ## Prerequisites - The program is compiled into an executable, so you don't need to install Python separately. However, make sure you have the required Excel files ready for conversion. ## Things to consider 1. Columns that you select as source and target should be identical across all the pages in the source file. There can be many other columns, but those two should have the same name. Otherwise results might not be good. 2. By default, it won't encapsulate inline code (tags) as it is supposed to be done. At the same time, some CAT/TMS won't do that either. You can play with this feature if you expand the window of the script down a little bit, then there will be a field for regex and a checkbox to activate it. ## Windows Download Pre-compiled EXE file can be found under \dist\ directory as a ZIP archive. ## Acknowledgments - This project is maintained by [wtigga](https://github.com/wtigga). --- **Disclaimer:** Use this tool responsibly and exercise caution when dealing with sensitive data. The authors are not responsible for any loss or damage incurred during the use of this tool.
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { BodegaProductoComponent } from './bodega-producto.component'; import { BodegaService } from '../bodega.service'; import { ProductoService } from 'src/app/producto/producto.service'; import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { ToastrModule } from 'ngx-toastr'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { RouterTestingModule } from '@angular/router/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from 'src/app/app.component'; import { MenuComponent } from 'src/app/menu/menu.component'; import { NgbCollapse } from '@ng-bootstrap/ng-bootstrap'; describe('BodegaProductoComponent', () => { let component: BodegaProductoComponent; let fixture: ComponentFixture<BodegaProductoComponent>; let bodegaService: BodegaService; let productoService: ProductoService; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ BodegaProductoComponent, MenuComponent ], imports: [FormsModule, HttpClientModule, NgbCollapse, ReactiveFormsModule, RouterTestingModule, ToastrModule.forRoot(), TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (http: HttpClient) => { return new TranslateHttpLoader(http, './assets/i18n/', '.json'); }, deps: [HttpClient] } }),], providers: [BodegaService, ProductoService, TranslateService, { provide: AppComponent, useValue: {} },] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(BodegaProductoComponent); component = fixture.componentInstance; bodegaService = TestBed.inject(BodegaService); productoService = TestBed.inject(ProductoService); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
/* * Copyright 2020 Crown Copyright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.gchq.palisade.integrationtests.palisade.mock; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import uk.gov.gchq.palisade.data.serialise.LineSerialiser; import uk.gov.gchq.palisade.data.serialise.Serialiser; import uk.gov.gchq.palisade.resource.LeafResource; import uk.gov.gchq.palisade.resource.impl.FileResource; import uk.gov.gchq.palisade.service.ConnectionDetail; import uk.gov.gchq.palisade.service.SimpleConnectionDetail; import uk.gov.gchq.palisade.service.palisade.request.AddResourceRequest; import uk.gov.gchq.palisade.service.palisade.request.GetResourcesByIdRequest; import uk.gov.gchq.palisade.service.palisade.request.GetResourcesByResourceRequest; import uk.gov.gchq.palisade.service.palisade.request.GetResourcesBySerialisedFormatRequest; import uk.gov.gchq.palisade.service.palisade.request.GetResourcesByTypeRequest; import uk.gov.gchq.palisade.util.ResourceBuilder; import java.io.IOException; import java.io.OutputStream; import java.util.stream.Stream; @RestController @RequestMapping(path = "/resource-service-mock") public class StreamingResourceControllerMock { private static final Logger LOGGER = LoggerFactory.getLogger(StreamingResourceControllerMock.class); private final Serialiser<LeafResource> serialiser = new LineSerialiser<>() { @Override public String serialiseLine(final LeafResource obj) { try { return new ObjectMapper().writeValueAsString(obj); } catch (JsonProcessingException e) { LOGGER.error("Encountered JSONProccessingException while serialising object {}", obj); LOGGER.error("Exception was ", e); throw new RuntimeException(e); } } @Override public LeafResource deserialiseLine(final String line) { LOGGER.warn("No implementation of deserialiseLine, ignoring argument {}", line); return null; } }; public static Stream<LeafResource> getResources() { ConnectionDetail connectionDetail = new SimpleConnectionDetail().serviceName("data-service-mock"); LeafResource resource = ((FileResource) ResourceBuilder.create("file:/root/resource-id")) .type("type") .serialisedFormat("format") .connectionDetail(connectionDetail); return Stream.of(resource); } private void streamResources(final OutputStream outputStream) throws IOException { serialiser.serialise(getResources(), outputStream); } @PostMapping(path = "/getResourcesById", consumes = "application/json", produces = "application/octet-stream") public ResponseEntity<StreamingResponseBody> getResourcesById(@RequestBody final GetResourcesByIdRequest request) { LOGGER.info("Invoking MOCKED getResourcesById"); StreamingResponseBody stream = this::streamResources; return new ResponseEntity<>(stream, HttpStatus.OK); } @PostMapping(path = "/getResourcesByResource", consumes = "application/json", produces = "application/octet-stream") public ResponseEntity<StreamingResponseBody> getResourcesByResource(@RequestBody final GetResourcesByResourceRequest request) { LOGGER.info("Invoking MOCKED getResourcesByResource"); StreamingResponseBody stream = this::streamResources; return new ResponseEntity<>(stream, HttpStatus.OK); } @PostMapping(path = "/getResourcesByType", consumes = "application/json", produces = "application/octet-stream") public ResponseEntity<StreamingResponseBody> getResourcesByType(@RequestBody final GetResourcesByTypeRequest request) { LOGGER.info("Invoking MOCKED getResourcesByType"); StreamingResponseBody stream = this::streamResources; return new ResponseEntity<>(stream, HttpStatus.OK); } @PostMapping(path = "/getResourcesBySerialisedFormat", consumes = "application/json", produces = "application/octet-stream") public ResponseEntity<StreamingResponseBody> getResourcesBySerialisedFormat(@RequestBody final GetResourcesBySerialisedFormatRequest request) { LOGGER.info("Invoking MOCKED getResourcesBySerialisedFormat"); StreamingResponseBody stream = this::streamResources; return new ResponseEntity<>(stream, HttpStatus.OK); } @PostMapping(path = "/addResource", consumes = "application/json", produces = "application/json") public Boolean addResource(@RequestBody final AddResourceRequest request) { LOGGER.info("Invoking MOCKED addResource"); return true; } }
import { Dispatch, SetStateAction, useEffect, useState } from 'react'; import { Card } from '../../interfaces/card.interface'; import { dealHand, drawCard } from '../../services/deck'; import { HandOfCards } from '../hand-of-cards/hand-of-cards'; import { PlayerActions } from '../player-actions/player-actions'; import * as styles from './player.module.css'; interface PlayerProps { name: string; dealerDrewBlackjack: boolean; onHasFinishedActions(playerFinalHandOfCards: Card[]): void; } interface PlayerState { handOfCards: Card[]; canPerformMoreActions: boolean; } export const Player = (props: PlayerProps) => { let [playerState, setPlayerState]: [PlayerState, Dispatch<SetStateAction<PlayerState>>] = useState( { handOfCards: dealHand(), canPerformMoreActions: true }); useEffect(() => { if (props.dealerDrewBlackjack) { stand(); } }, [props.dealerDrewBlackjack]); function hit(): void { setPlayerState({ ...playerState, handOfCards: [...playerState.handOfCards, drawCard()] }); } function doubleDown(): void { const finalPlayerHand: Card[] = [...playerState.handOfCards, drawCard()]; setPlayerState({ handOfCards: finalPlayerHand, canPerformMoreActions: false }); props.onHasFinishedActions(finalPlayerHand); } function split(): void { } function stand(): void { setPlayerState({ ...playerState, canPerformMoreActions: false }); props.onHasFinishedActions(playerState.handOfCards); } function bust(): void { stand(); } return ( <div className={styles.player}> <div className={styles.name}>{props.name}</div> <HandOfCards cards={playerState.handOfCards} onBust={bust} onTotalTwentyOne={stand}/> { playerState.canPerformMoreActions && <PlayerActions handOfCards={playerState.handOfCards} onHit={hit} onDoubleDown={doubleDown} onSplit={split} onStand={stand}/> } </div> ); }
<?php declare(strict_types=1); namespace Tests\Feature\Http\EatingOut; use App\Actions\EatingOut\GetMostRatedPlacesInCountyAction; use App\Actions\EatingOut\GetTopRatedPlacesInCountyAction; use App\Models\EatingOut\Eatery; use App\Models\EatingOut\EateryCounty; use Database\Seeders\EateryScaffoldingSeeder; use Illuminate\Testing\TestResponse; use Inertia\Testing\AssertableInertia as Assert; use Tests\TestCase; class NationwideTest extends TestCase { protected EateryCounty $county; protected function setUp(): void { parent::setUp(); $this->seed(EateryScaffoldingSeeder::class); $this->county = EateryCounty::query()->withoutGlobalScopes()->first(); $this->county->update(['slug' => 'nationwide']); $this->build(Eatery::class) ->create([ 'county_id' => $this->county->id, ]); } protected function visitPage(): TestResponse { return $this->get(route('eating-out.nationwide')); } /** @test */ public function itReturnsOk(): void { $this->visitPage()->assertOk(); } /** @test */ public function itCallsTheGetMostRatedPlacesInCountyAction(): void { $this->expectAction(GetMostRatedPlacesInCountyAction::class); $this->visitPage(); } /** @test */ public function itCallsTheGetTopRatedPlacesInCountyAction(): void { $this->expectAction(GetTopRatedPlacesInCountyAction::class); $this->visitPage(); } /** @test */ public function itRendersTheInertiaPage(): void { $this->visitPage() ->assertInertia( fn (Assert $page) => $page ->component('EatingOut/Nationwide') ->has('county') ->where('county.name', $this->county->county) ->etc() ); } }
import { getFirestore, collection, setDoc, doc, getDoc, getDocs, serverTimestamp, } from "firebase/firestore" import app from "./firebase" const db = getFirestore(app) // Initialize the ID counter and currentDate globally let alertSID = 1 let currentDate = getFormattedDate() export const addMessageData = async () => { const recipient = 43434 const message = "QQQQQQQQQ" const alert_type = "QNOUNCEM3NT" try { // Check if the current date is different from the stored date const currentDateNow = getFormattedDate() if (currentDateNow !== currentDate) { // If it's a new day, reset alertSID to 1 and update the stored date alertSID = 1 currentDate = currentDateNow } // Generate the alert_id by concatenating the current date and alertSID const alert_id = `${currentDate}${alertSID}` // Create a Firestore document reference using the generated alert_id const alertDocRef = doc(db, "Alert", alert_id) // Set the document data with recipient, message, and alert_type await setDoc(alertDocRef, { alert_id, recipient, message, alert_type, }) // Increment alertSID for the next alert alertSID++ return alert_id // Return the generated alert_id } catch (error) { console.error("Error adding message: ", error) return null } } export const add2MessageData = async ( alertType, recipientInfo, message, messageData ) => { try { const currentDateNow = getFormattedDate() if (currentDateNow !== currentDate) { alertSID = 1 currentDate = currentDateNow } let alert_id let isUnique = false while (!isUnique) { alert_id = `${currentDate}${alertSID}` const alertDocRef = doc(db, "Alert", alert_id) const alertDocSnapshot = await getDoc(alertDocRef) if (!alertDocSnapshot.exists()) { // If the document does not exist, it's a unique ID isUnique = true } else { // If the document exists, increment alertSID and try again alertSID++ } } // Now we have a unique alert_id const alertDocRef = doc(db, "Alert", alert_id) await setDoc(alertDocRef, { alert_id, alert_type: alertType, recipientInfo, message, messageData, created_at: serverTimestamp(), }) alertSID++ return alert_id } catch (error) { console.error("Error adding message: ", error) return null } } // Helper function to get the current date in YYYYMMDD format function getFormattedDate() { const now = new Date() const year = now.getFullYear() const month = String(now.getMonth() + 1).padStart(2, "0") const day = String(now.getDate()).padStart(2, "0") return `${year}${month}${day}` } // get AlertData export const fetchAlertData = async () => { const alertRef = collection(db, "Alert") const alertSnapshot = await getDocs(alertRef) const alertData = [] alertSnapshot.forEach((doc) => { alertData.push({ id: doc.id, ...doc.data() }) }) return alertData }
import { when } from 'jest-when'; import { determineEditor } from './editor'; import * as envModule from './env'; import * as miscUtils from './misc-utils'; jest.mock('./env'); jest.mock('./misc-utils'); describe('editor', () => { describe('determineEditor', () => { it('returns information about the editor from EDITOR if it resolves to an executable', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: 'editor' }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('editor') .mockResolvedValue('/path/to/resolved-editor'); expect(await determineEditor()).toStrictEqual({ path: '/path/to/resolved-editor', args: [], }); }); it('falls back to VSCode if it exists and if EDITOR does not point to an executable', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: 'editor' }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('editor') .mockResolvedValue(null) .calledWith('code') .mockResolvedValue('/path/to/code'); expect(await determineEditor()).toStrictEqual({ path: '/path/to/code', args: ['--wait'], }); }); it('returns null if resolving EDITOR returns null and resolving VSCode returns null', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: 'editor' }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('editor') .mockResolvedValue(null) .calledWith('code') .mockResolvedValue(null); expect(await determineEditor()).toBeNull(); }); it('returns null if resolving EDITOR returns null and resolving VSCode throws', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: 'editor' }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('editor') .mockResolvedValue(null) .calledWith('code') .mockRejectedValue(new Error('some error')); expect(await determineEditor()).toBeNull(); }); it('returns null if resolving EDITOR throws and resolving VSCode returns null', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: 'editor' }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('editor') .mockRejectedValue(new Error('some error')) .calledWith('code') .mockResolvedValue(null); expect(await determineEditor()).toBeNull(); }); it('returns null if resolving EDITOR throws and resolving VSCode throws', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: 'editor' }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('editor') .mockRejectedValue(new Error('some error')) .calledWith('code') .mockRejectedValue(new Error('some error')); expect(await determineEditor()).toBeNull(); }); it('returns null if EDITOR is unset and resolving VSCode returns null', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: undefined }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('code') .mockResolvedValue(null); expect(await determineEditor()).toBeNull(); }); it('returns null if EDITOR is unset and resolving VSCode throws', async () => { jest .spyOn(envModule, 'getEnvironmentVariables') .mockReturnValue({ EDITOR: undefined }); when(jest.spyOn(miscUtils, 'resolveExecutable')) .calledWith('code') .mockRejectedValue(new Error('some error')); expect(await determineEditor()).toBeNull(); }); }); });
/* eslint-disable no-unused-vars */ import React, { useState } from "react"; import { Line } from "react-chartjs-2"; import "./LineChart.scss"; import { Chart } from "chart.js/auto"; import { CategoryScale } from "chart.js"; function LineChart({ width, height, data }) { const options = { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: "bottom", align: "start", labels: { font: { size: 18, weight: 500, family: "Plus Jakarta Sans" }, padding: 20, usePointStyle: true, }, }, tooltip: { bodyFont: { size: 18, family: "Plus Jakarta Sans", }, displayColors: false, callbacks: { label: function (tooltipItem) { return `${tooltipItem.dataset.label}: ${tooltipItem.raw} mins`; }, title: function () {}, }, }, }, scales: { y: { beginAtZero: true, grid: { color: "rgba(112, 112, 112, 0.24)", lineWidth: 3, borderWidth: 0, }, ticks: { font: { size: 18, weight: 500, family: "Plus Jakarta Sans", }, color: "#919191", padding: 15, callback: function (val, index) { // Hide the label of every 2nd dataset return val + "m"; }, }, }, x: { grid: { display: false, }, ticks: { font: { size: 18, weight: 600, family: "Plus Jakarta Sans", }, padding: 15, color: "#919191", }, }, }, }; return ( <Line data={data} width={width} height={height} options={options}></Line> ); } export default LineChart;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <header> <h1 id="title">PlayStation® Survey Form</h1> <p id="description">We listen our community. Take the survey and help us improve</p> </header> <form action="" id="survey-form"> <div class="form-group"> <label for="name"id="name-label">Name</label> <input type="text " name="name" id="name" class="form-control" placeholder="Enter Your name" required> </div> <div class="form-group"> <label for="email" id="email-label">Email</label> <input type="email" name="email" id="email" class="form-control" placeholder="Enter Your Email" required> </div> <div class="form-group"> <label for="number" id="number-label">Age (optional)</span></label> <input type="number" name="age" id="number" min="10" max="99" class="form-control" placeholder="Age"> </div> <div class="form-group"> <p class="one">Which PlayStation console do you own?</p> <select name="role" id="dropdown" placeholder="Select current role"> <option disabled selected value>Select your current system</option> <option value="ps5">Playstation 5</option> <option value="ps4">Playstation 4</option> <option value="ps3">Playstation 3</option> <option value="ps2">Playstation 2</option> <option value="ps1">Playstation 1</option> </select> </div> <div class="form-group"> <p>Have you ever consider to become a PlayStation Plus member?</p> <label for="yes"> <input type="radio" value="yes" name="member" class="input-radio"> Yes </label> <label for="no"> <input type="radio" value="no" name="member" class="input-radio"> No </label> <label for="maybe"> <input type="radio" value="maybe" name="member" class="input-radio"> Maybe </label> </div> <div class="form-group "> <p class="one">What would you like to see next on our Playstation Platform?</p> <select name="role2" id="role2"> <option disabled selected value>Select an option</option> <option value="cgm">Cross-generation multiplayer</option> <option value="gamehub">Better Game Hub</option> <option value="activities">Better Activities</option> <option value="cc">Better Control Center</option> <option value="gamerec">Better Game recommendations</option> </select> </div> <div class="form-group text2"> <p class="one">Which apps are you using the most on your console? (Check all that aplly)</p> </p> <label for="one"> <input type="checkbox" value="one" name="app" class="checkboox1"> ShareFactory </label> <label for="two"> <input type="checkbox" value="two" name="app" class="checkboox1"> PlayStation Music </label> <label for="three"> <input type="checkbox" value="three" name="app" class="checkboox1"> Plex </label> <label for="four"> <input type="checkbox" value="four" name="app" class="checkboox1"> Twitch </label> <label for="five+"> <input type="checkbox" value="five" name="app" class="checkboox1"> Netflix </label> <label for="six"> <input type="checkbox" value="six" name="app" class="checkboox1"> YouTube </label> <label for="seven"> <input type="checkbox" value="seven" name="app" class="checkboox1"> PlayStation Now </label> <label for="eight"> <input type="checkbox" value="eight" name="app" class="checkboox1"> Crunchyroll </label> <label for="nine"> <input type="checkbox" value="nine" name="app" class="checkboox1"> WWE Network </label> <label for="ten"> <input type="checkbox" value="ten" name="app" class="checkboox1"> Amazon Prime Video </label> <label for="eleven"> <input type="checkbox" value="eleven" name="app" class="checkboox1"> HBO NOW </label> <label for="twelve"> <input type="checkbox" value="twelve" name="app" class="checkboox1"> DAZN </label> <label for="thirteen"> <input type="checkbox" value="thirteen" name="app" class="checkboox1"> VRV </label> <label for="fourteen"> <input type="checkbox" value="fourteen" name="app" class="checkboox1"> BBC iPlayer </label> </div> <div class="form-group text"> <p class="one text">Tell us your thoughts about our service? </p> <textarea name="txtarea" id="txtareas" cols="30" rows="5" placeholder="Enter your comment here..." ></textarea> </div> <div class="form-group"> <button type="submit" id="submit" class="button-submit">Submit</button> </div> </div> </form> </div> </body> </html>
import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { allGroups } from "../../store/groups"; import { Link } from 'react-router-dom'; import './Groups.css'; import { allEvents } from "../../store/events"; const Groups = () => { const dispatch = useDispatch(); const groupData = Object.values(useSelector((state) => state.groupState)); const events = Object.values(useSelector((state) => state.eventState)); const [groupsLoaded, setGroupsLoaded] = useState(false); const [eventsLoaded, setEventsLoaded] = useState(false); useEffect(() => { dispatch(allGroups()).then(() => setGroupsLoaded(true)) }, [dispatch]); useEffect(() => { dispatch(allEvents()).then(() => setEventsLoaded(true)) }, [ dispatch]); //console.log(groupData) const numEvents = (id) => { const groupEvents = events.filter((event) => event.groupId === id); if (!groupEvents.length) { return "0 Events"; } if (groupEvents.length === 1) { return "1 Event"; } else { return `${groupEvents.length} Events`; } }; if(!eventsLoaded || !groupsLoaded){ return null } return ( groupsLoaded && eventsLoaded && ( <> <div className="container"> <div></div> <div> <div> <div className="header top-spacing"> <span> <Link to="/events" style={{ textDecoration: "none", color: "gray" }} onMouseEnter={(e) => { e.target.style.textDecoration = "underline"; }} onMouseLeave={(e) => { e.target.style.textDecoration = "none"; }} > Events </Link> </span> <Link to="/groups" className="left-spacing" style={{ textDecoration: "underline", color: "teal", cursor: "default", }} > Groups </Link> </div> <div style={{ paddingLeft: "40px", paddingRight: "10px" }}> <div style={{ height: "7px" }}> <h6 style={{ color: "gray", fontSize: "13.4" }}> Groups in What's Up </h6> </div> </div> </div> <ul> {groupData.map((group) => { return ( <li style={{ paddingTop: "10px", cursor: "pointer" }} className="borders box-width" onClick={() => (window.location.href = `/groups/${group.id}`) } > <div className="image-container no-top-padding"> <img src={`${group.previewImage}`} alt="previewImage" style={{ width: 200 }} className="group-image" /> </div> <div className="word-container"> <h4 className="no-top-padding no-bottom-padding">{`${group.name}`}</h4> <h6 className="location">{`${group.city}, ${group.state}`}</h6> <div className="text-width">{`${group.about}`}</div> <div style={{ display: "flex" }}> <h6 className="location">{numEvents(group.id)}</h6> <h6 className="location">{`${group.type}`}</h6> </div> </div> </li> ); })} </ul> </div> <div></div> </div> </> ) ); }; export default Groups;
package ru.practicum.main.user.controller; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import ru.practicum.main.user.dto.UserDto; import ru.practicum.main.user.service.UserService; import javax.validation.Valid; import javax.validation.constraints.Positive; import javax.validation.constraints.PositiveOrZero; import java.util.List; @Slf4j @RestController @RequestMapping(path = "/admin/users") @Validated @RequiredArgsConstructor public class AdminUserController { private final UserService userService; @PostMapping @ResponseStatus(HttpStatus.CREATED) public UserDto create(@RequestBody @Valid UserDto userDto) { log.info("Пользователь добавлен: {}", userDto.getName()); return userService.create(userDto); } @DeleteMapping("/{userId}") @ResponseStatus(HttpStatus.NO_CONTENT) public void delete(@PathVariable Long userId) { log.debug("Удаление пользователя"); userService.delete(userId); } @GetMapping public List<UserDto> findAll(@RequestParam(required = false) List<Long> ids, @PositiveOrZero @RequestParam(name = "from", defaultValue = "0") int from, @Positive @RequestParam(name = "size", defaultValue = "10") int size) { log.info("Получение всех пользователей"); return userService.findAll(ids, from, size); } }
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Место Россия</title> </head> <body> <div class="page"> <header class="header"> <img class="header__logo" src="./images/logo.svg" alt="Логотип"> </header> <main class="main"> <section class="profile"> <div class="profile__edit-group"> <img class="profile__avatar" name="avatar" src="./images/Avatar_image.jpeg" alt="Портрет Кусто"> <button class="profile__edit-button" type="button"></button> </div> <div class="profile__info"> <div class="profile__list"> <h1 class="profile__title">Жак-Ив Кусто</h1> <button class="profile__rectangle-button" type="button"></button> </div> <p class="profile__subtitle">Исследователь океана</p> </div> <button class="profile__add-button" type="button">+</button> </section> <section class="elements"> <ul class="elements__list"></ul> </section> </main> <footer class="footer"> <p class="footer__text">&#169; 2022 Mesto Russia</p> </footer> </div> <div class="popup popup_type_profile"> <div class="popup__container"> <button class="popup__close" type="button"></button> <h2 class="popup__title">Редактировать профиль</h2> <form class="popup__form popup__form_profile" name="form" novalidate> <input type="text" name="name" value="1" placeholder="Имя" class="popup__input popup__input_field_name" id="name-input" required minlength="2" maxlength="40"> <span class="name-input-error popup__input-error"></span> <input type="text" name="about" value="2" placeholder="Информация" class="popup__input popup__input_field_info" id="info-input" required minlength="2" maxlength="200"> <span class="info-input-error popup__input-error popup__input-error_centrate"></span> <button class="popup__submit-button popup__submit-button_type_profile" type="submit">Сохранить</button> </form> </div> </div> <div class="popup popup_type_cards"> <div class="popup__container"> <button class="popup__close popup__close_type_cards" type="button"></button> <h2 class="popup__title popup__title_type_cards">Новое место</h2> <form class="popup__form popup__form_type_cards" name="cards-form" novalidate> <input type="text" placeholder="Название" class="popup__input popup__input_card_name" id="cards-name" name="name" required minlength="2" maxlength="30"> <span class="cards-name-error popup__input-error"></span> <input type="url" name="link" placeholder="Ссылка на картинку" class="popup__input popup__input_card_link" id="cards-link" required> <span class="cards-link-error popup__input-error popup__input-error_centrate"></span> <button class="popup__submit-button popup__submit-button_type_cards" type="submit">Сохранить</button> </form> </div> </div> <div class="popup popup_type_avatar"> <div class="popup__container popup__container_type_avatar"> <h2 class="popup__title">Обновить аватар</h2> <form class="popup__form popup__form_type_avatar" name="avatar-form" novalidate> <input type="url" name="link" placeholder="Ссылка на картинку" class="popup__input popup__input_avatar_link" id="avatar-link" required> <span class="avatar-link-error popup__input-error popup__input-error_centrate"></span> <button class="popup__submit-button popup__submit-button_type_avatar" type="submit">Сохранить</button> </form> <button class="popup__close" type="button" aria-label="Закрыть окно"></button> </div> </div> <div class="popup popup_type_picture"> <div class="popup__container popup__container_type_picture"> <button class="popup__close popup__close_type_picture" type="button"></button> <img class="popup__image" src="#" alt="Картинка"> <h2 class="popup__title popup__title_type_picture"></h2> </div> </div> <div class="popup popup_type_accept"> <div class="popup__container popup__container_type_accept"> <button class="popup__close" type="button" aria-label="Закрыть окно"></button> <h2 class="popup__title popup__title_type_accept">Вы уверены?</h2> <form class="popup__form"> <button class="popup__submit-button popup__submit-button_type_accept" type="submit" aria-label="Подтвердить удаление">Да</button> </form> </div> </div> <template id="item_template"> <li class="element"> <button class="element__delete-card" type="button"></button> <img class="element__photo" src="#" alt="Картинка"> <div class="element__title"> <h2 class="element__text"></h2> <div class="element__group"> <button class="element__like" type="button"></button> <p class="element__sum"></p> </div> </div> </li> </template> </body> </html>
using System; using System.Collections.Generic; using Tonga.Scalar; namespace Tonga.Scalar { /// <summary> /// <see cref="IEnumerable{T}"/> whose items are reduced to one item using the given function. /// </summary> /// <typeparam name="T">type of elements in a list to reduce</typeparam> public sealed class Reduced<T> : ScalarEnvelope<T> { /// <summary> /// <see cref="IEnumerable{Element}"/> whose items are folded to one item using the given function. /// </summary> /// <param name="elements">enumerable to reduce</param> /// <param name="fnc">reducing function</param> public Reduced(IEnumerable<T> elements, IBiFunc<T, T, T> fnc) : this( elements, fnc.Invoke ) { } /// <summary> /// <see cref="IEnumerable{Element}"/> whose items are reduced to one item using the given function. /// </summary> /// <param name="elements">enumerable to reduce</param> /// <param name="fnc">reducing function</param> public Reduced(IEnumerable<T> elements, Func<T, T, T> fnc) : base(() => { var enm = elements.GetEnumerator(); if (!enm.MoveNext()) throw new ArgumentException($"Cannot reduce, at least one element is needed but the enumerable is empty."); T result = enm.Current; while (enm.MoveNext()) { result = fnc.Invoke(result, enm.Current); } return result; } ) { } } /// <summary> /// <see cref="IEnumerable{T}"/> whose items are reduced to one item using the given function. /// </summary> public static class Reduced { /// <summary> /// <see cref="IEnumerable{Element}"/> whose items are folded to one item using the given function. /// </summary> /// <param name="elements">enumerable to reduce</param> /// <param name="fnc">reducing function</param> public static Reduced<T> _<T>(IEnumerable<T> elements, IBiFunc<T, T, T> fnc) => new Reduced<T>(elements, fnc); /// <summary> /// <see cref="IEnumerable{Element}"/> whose items are reduced to one item using the given function. /// </summary> /// <param name="elements">enumerable to reduce</param> /// <param name="fnc">reducing function</param> public static Reduced<T> _<T>(IEnumerable<T> elements, Func<T, T, T> fnc) => new Reduced<T>(elements, fnc); } }
# 关于 ReviewFiles --- 每一次长时间不用Ubuntu上的ROS环境,就会忘记如何使用。之前每一次都新建一个工作空间然后在里面调试,感觉很混乱,这个ReviewFiles可以按照“所学知识内容”建立不同的工作空间,实现了具体的功能之后就另起炉灶,互不干扰,有独立的Readme.md文件。 此库已经建立了VMware中和双系统中的Ubuntu工程文件的跨平台使用。但是可能会有些混乱。 因为ROS中能够搬来搬去的是包,而不是工程文件。 因此,本文件中的工程文件是在双系统中使用的,而工程文件可以搬来搬去。 ## assets目录 用来放通目录下md文件图片的。与md文件名解耦,防止git后或者复制后出各种问题。(印象里反正是有问题hhh) ## /BasicStructures [20240227] 基本的ROS代码架构,不用VSCODE实现; 如果失忆了,完全不记得ros文件架构了,看看这个。(233) 【关于节点命名的AT】 ## /BasicVSCode [20240227] 基本的ROS代码架构,使用VSCODE实现; 使用launch文件。 【关于.vscode文件的说明】 【关于launch文件中标签的说明】 ## /CmdTopic [20240228] 包含两个pkg。 第一个pkg实现了两个node之间的同一个topic的发送和接受; 第二个pkg实现了编写node发送消息控制turtlesim的小乌龟运动。 【关于ros::spinOnce()和ros::spin()的说明】 ## /BasicUrdf [20240229] 包含两个pkg。 basic_urdf_pkg:基本的urdf使用方式与launch启动方式。 basic_xacro_pkg:基本的xacro使用方式与launch启动方式。 【关于 joint_states robot_states 的 ***提 及***(没有详细研究这些pkgs和nodes)】 ## /BasicGazebo [20240229] 一个pkg。两个部分。 robot1.urdf/launch: 基本的在gazebo环境中载入一个模型。 robot2.launch + /xacro2 : 在gazebo环境中(含有障碍物的环境)载入一个xacro描述的复杂模型。 【gazebo载入模型所涉及的launch xml代码还是值得看一看的】 ## /BasicWIP [20240302] 一个pkg,两个部分。 robot1. xacro /robot1.launch 在gazebo中载入wip模型(不含控制器、驱动器、传感器) robot2 xacro/yaml/launch | wip_ctrl.cpp (wip_ctrl_node) 在gazebo中载入wip ,绑定控制器(底层transmission & ros_control) 与传感器、编写控制逻辑[通过topic给下层controller发送控制指令 , 实现了位置闭环PD控制] ## /BasicWBR [20240312]时间过得很快 ## /BasicLQR # 关于常用的一些内容 (在各个文件当中不断习得的,可能会反复用到的内容) ## 各种需要的前置包 ``` dynamic_reconfigure gazebo_plugins gazebo_ros gazebo_ros_control roscpp rospy std_msgs urdf xacro ``` ## tasks.json 文件 ```json { // 有关 tasks.json 格式的文档,请参见 // https://go.microsoft.com/fwlink/?LinkId=733558 "version": "2.0.0", "tasks": [ { "label": "catkin_make:debug", //代表提示的描述性信息 "type": "shell", //可以选择shell或者process,如果是shell代码是在shell里面运行一个命令,如果是process代表作为一个进程来运行 "command": "catkin_make",//这个是我们需要运行的命令 "args": [],//如果需要在命令后面加一些后缀,可以写在这里,比如-DCATKIN_WHITELIST_PACKAGES=“pac1;pac2” "group": {"kind":"build","isDefault":true}, "presentation": { "reveal": "always"//可选always或者silence,代表是否输出信息 }, "problemMatcher": "$msCompile" } ] } ``` ## Gazebo ### Gazebo&Launch #### 模型位置 ​ 设置加载到Gazebo当中的模型的初始位置。 ```xml <node pkg="gazebo_ros" type="spawn_model" name="model" args="-urdf -model mycar -param robot_description" /> <!-- 在 Gazebo 中加载一个机器人模型,该功能由 gazebo_ros 下的 spawn_model 提供: -urdf 加载的是 urdf 文件 -model mycar 模型名称是 mycar -param robot_description 从参数 robot_description 中载入模型 -x 模型载入的 x 坐标 -y 模型载入的 y 坐标 -z 模型载入的 z 坐标 --> ```
<?php declare(strict_types=1); namespace App\Controller; /** * Factureclients Controller * * @property \App\Model\Table\FactureclientsTable $Factureclients * @method \App\Model\Entity\Factureclient[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = []) */ class FactureclientsController extends AppController { /** * Index method * * @return \Cake\Http\Response|null|void Renders view */ public function index() { $this->paginate = [ 'contain' => ['Clients', 'Pointdeventes', 'Depots', 'Commandeclients'], ]; $factureclients = $this->paginate($this->Factureclients); $this->set(compact('factureclients')); } /** * View method * * @param string|null $id Factureclient id. * @return \Cake\Http\Response|null|void Renders view * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id = null) { $factureclient = $this->Factureclients->get($id, [ 'contain' => ['Clients', 'Pointdeventes', 'Depots', 'Commandeclients', 'Factureavoirs'], ]); $this->set(compact('factureclient')); } /** * Add method * * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise. */ public function add() { $factureclient = $this->Factureclients->newEmptyEntity(); if ($this->request->is('post')) { $factureclient = $this->Factureclients->patchEntity($factureclient, $this->request->getData()); if ($this->Factureclients->save($factureclient)) { $this->Flash->success(__('The factureclient has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The factureclient could not be saved. Please, try again.')); } $clients = $this->Factureclients->Clients->find('list', ['limit' => 200])->all(); $pointdeventes = $this->Factureclients->Pointdeventes->find('list', ['limit' => 200])->all(); $depots = $this->Factureclients->Depots->find('list', ['limit' => 200])->all(); $commandeclients = $this->Factureclients->Commandeclients->find('list', ['limit' => 200])->all(); $this->set(compact('factureclient', 'clients', 'pointdeventes', 'depots', 'commandeclients')); } /** * Edit method * * @param string|null $id Factureclient id. * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function edit($id = null) { $factureclient = $this->Factureclients->get($id, [ 'contain' => [], ]); if ($this->request->is(['patch', 'post', 'put'])) { $factureclient = $this->Factureclients->patchEntity($factureclient, $this->request->getData()); if ($this->Factureclients->save($factureclient)) { $this->Flash->success(__('The factureclient has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The factureclient could not be saved. Please, try again.')); } $clients = $this->Factureclients->Clients->find('list', ['limit' => 200])->all(); $pointdeventes = $this->Factureclients->Pointdeventes->find('list', ['limit' => 200])->all(); $depots = $this->Factureclients->Depots->find('list', ['limit' => 200])->all(); $commandeclients = $this->Factureclients->Commandeclients->find('list', ['limit' => 200])->all(); $this->set(compact('factureclient', 'clients', 'pointdeventes', 'depots', 'commandeclients')); } /** * Delete method * * @param string|null $id Factureclient id. * @return \Cake\Http\Response|null|void Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $factureclient = $this->Factureclients->get($id); if ($this->Factureclients->delete($factureclient)) { $this->Flash->success(__('The factureclient has been deleted.')); } else { $this->Flash->error(__('The factureclient could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); } }
import { useSelector, useDispatch } from 'react-redux'; import { useEffect } from 'react'; import { reserveRocket } from '../features/rocketSlice'; import fetchRockets from '../API/apiRockets'; const Rockets = () => { const dispatch = useDispatch(); const { rockets } = useSelector((state) => state.rockets); const { status } = useSelector((state) => state.rockets); useEffect(() => { if (status === false) dispatch(fetchRockets()); }, [dispatch, status]); return ( <div className="container"> {status && rockets.map((each) => ( <div key={each.id} className="article"> <img src={each.image} className="img" alt={each.name} /> <div> <h2 className="title">{each.name}</h2> <p className="rocketDetails"> {each.reserved ? <span className="span">Reserved</span> : ''} {each.description} </p> <button type="button" className={each.reserved ? 'unreserve' : 'reserve'} onClick={() => dispatch(reserveRocket(each.id))} > {each.reserved ? 'Cancel Reservation' : 'Reserve Rocket'} </button> </div> </div> ))} </div> ); }; export default Rockets;
package PageObjects; import Utilities.BaseClass; import org.openqa.selenium.*; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.IOException; public class ValidatePage extends BaseClass { public ValidatePage(WebDriver driver, WebDriverWait wait) { super(driver, wait); PageFactory.initElements(driver, this); } JavascriptExecutor js = (JavascriptExecutor) driver; int totalWords = WordsPage.getTotalWords(); int totalCharacters = WordsPage.getTotalCharacters(); String dataCounted = CountPage.getDataCounted(); String word1 = WordsPage.getWord1(); String word2 = WordsPage.getWord2(); String word3 = WordsPage.getWord3(); String txt1 = CountPage.getTxt1(); String txt2 = CountPage.getTxt2(); String txt3 = CountPage.getTxt3(); public void validateWebData() throws InterruptedException, IOException { // Extract numbers from the dataCounted string int[] numberDataC = extractNumbers(dataCounted); // Compare the extracted values with the expected values //Words are my logic data and txts are the web data try { verifyNumbers(numberDataC, totalWords, totalCharacters); System.out.println("The tests are correct."); // Verify that word1 is equal to txt1 if (word1.equals(txt1)) { System.out.println("The string are equals."); } else { System.out.println("The string are different."); System.out.println(txt1); System.out.println(word1); throw new AssertionError("The fist word is different Because the program does not count compound words well and counts the words one by one in a url ."); } if (word2.equals(txt2)) { System.out.println("The string are equals."); } else { System.out.println("The string are different."); System.out.println(txt2); System.out.println(word2); throw new AssertionError("The second word is different because because in the first word the counting of uppercase and lowercase letters was tested but from the second word the limit values are counted ( individual letters, numbers, pronouns in English, special characters) and these are not counted by the application."); } if (word3.equals(txt3)) { System.out.println("The string are equals."); } else { System.out.println("The string are different."); System.out.println(txt3); System.out.println(word3); throw new AssertionError("The third word is different."); } System.out.println("The test are correct."); } catch (AssertionError e) { System.out.println("Error: " + e.getMessage()); throw new AssertionError("The test failed due to the following exception:" + e.getMessage()); } } private static int[] extractNumbers(String chain) { // Split the chain by spaces and extract the numbers String[] parts = chain.split("\\D+"); // \\D+ matches any non-digit int[] numbers = new int[parts.length]; // Convert parts to numbers for (int i = 0; i < parts.length; i++) { numbers[i] = Integer.parseInt(parts[i]); } return numbers; } private static void verifyNumbers(int[] numbersDataC, int totalWords, int totalCharacthers) { // Verify that numbers are equal if (numbersDataC.length >= 1 && numbersDataC[0] != totalWords) { throw new AssertionError("The number of words on the page does not match the expected value."); } if (numbersDataC.length >= 2 && numbersDataC[1] != totalCharacthers) { throw new AssertionError("The number of characters on the page does not match the expected value."); } } }
#' Add a CRAN Status badge #' #' @description #' This function adds a **CRAN Status** badge to the `README.Rmd`. If the #' package is not hosted on the CRAN the badge will indicate #' _not published on the CRAN_. #' #' Make sure that 1) a `README.Rmd` file exists at the project root and 2) it #' contains a block starting with the line `<!-- badges: start -->` and ending #' with the line `<!-- badges: end -->`. #' #' Don't forget to re-render the `README.md`. #' #' @param quiet A logical value. If `TRUE` messages are deleted. Default is #' `FALSE`. #' #' @return A badge as a markdown expression. #' #' @export #' #' @family adding badges #' #' @examples #' \dontrun{ #' add_cran_badge() #' } add_cran_badge <- function(quiet = FALSE) { stop_if_not_logical(quiet) ## Create Badge Markdown Expression ---- project_name <- get_package_name() alt <- "CRAN status" href <- paste0("https://CRAN.R-project.org/package=", project_name) img <- paste0("https://www.r-pkg.org/badges/version/", project_name) badge <- paste0("[![", alt, "](", img, ")](", href, ")") ## Add Badge ---- add_badge(badge, pattern = "CRAN status") if (!quiet) { ui_done(paste0("Adding {ui_field('CRAN status')} badge to ", "{ui_value('README.Rmd')}")) } invisible(badge) }
import React, {Fragment} from 'react' import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { logout } from '../../actions/auth'; //racf const Navbar = ({auth:{isAuthenticated, loading}, logout}) => { const authLinks = ( <ul> <li> <Link to="/profiles">Developers</Link> </li> <li> <Link to="/posts">Posts</Link> </li> <li> <Link to="/dashboard"><i className="fas fa-user"/>{' '} <span className='hide-sm'>Dashboard</span></Link> </li> <li><Link onClick={logout} to="#!"> <i className='fas fa-sign-out-alt'/>{' '} <span className='hide-sm'>Logout</span> </Link></li> </ul> ); const guestLinks = ( <ul> <li><Link to="/profiles">Developers</Link></li> <li><Link to="/register">Register</Link></li> <li><Link to="/login">Login</Link></li> </ul> ); return ( <nav className="navbar bg-dark"> <h1> <Link to="/"><i className="fas fa-code"></i> DevConnector</Link> </h1> {!loading && (<Fragment>{isAuthenticated ? authLinks : guestLinks}</Fragment>)} </nav> ) } Navbar.propTypes = { logout : PropTypes.func.isRequired, auth: PropTypes.object.isRequired }; const mapStateToProps = state => ({ auth: state.auth }); export default connect(mapStateToProps,{logout})(Navbar);
<?php namespace App; use Illuminate\Support\Facades\Mail; use Illuminate\Notifications\Notifiable; use App\Mail\RepresentanteResetPasswordMail; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Auth\User as Authenticable; use App\Notifications\RepresentanteResetPasswordNotification; use Carbon\Carbon; class Representante extends Authenticable { use Notifiable, SoftDeletes; private $gerentiRepository; protected $guard = 'representante'; protected $fillable = ['cpf_cnpj', 'registro_core', 'ass_id', 'nome', 'email', 'password', 'verify_token', 'aceite', 'ativo']; protected $hidden = ['password', 'remember_token']; // Tipos de pessoa. const PESSOA_FISICA = "PF"; const PESSOA_JURIDICA = "PJ"; const RESP_TECNICO = "RT"; // Tipos de empresa. const EMPRESA_INDIVIDUAL = "Empresa Individual"; // Situações do Representante Comercial. const EM_DIA = "Situação: Em dia."; const PARCELAMENTO_EM_ABERTO = "Situação: Parcelamento em aberto."; const EXECUÇÃO_FISCAL = 'Situação: Execução Fiscal.'; const CANCELADO_BLOQUEADO = 'Situação: Cancelado ou Bloqueado'; // Status do Representante Comercial. const ATIVO = "Ativo"; // Situações do pagamento de cobranças. const PAGO = "Pago"; const EM_ABERTO = "Em aberto"; /** * Mapeia código retornado pelo GERENTI na busca por Representante Comercial */ public static function mapaCodigoTipoPessoa($codigo) { switch ($codigo) { case '1': return Representante::PESSOA_JURIDICA; break; case '2': return Representante::PESSOA_FISICA; break; case '5': return Representante::RESP_TECNICO; break; default: return 'Indefinida'; break; } } public function sendPasswordResetNotification($token) { $body = emailResetRepresentante($token); // $this->notify(new RepresentanteResetPasswordNotification($token)); - FALLBACK Mail::to($this->email)->queue(new RepresentanteResetPasswordMail($token, $body)); } public function tipoPessoa() { return strlen($this->cpf_cnpj) === 14 ? Representante::PESSOA_FISICA : Representante::PESSOA_JURIDICA; } public function getCpfCnpjAttribute($value) { if(strlen($value) === 11) { return substr($value, 0, 3) . '.' . substr($value, 3, 3) . '.' . substr($value, 6, 3) . '-' . substr($value, 9, 2); } elseif(strlen($value) === 14) { return substr($value, 0, 2) . '.' . substr($value, 2, 3) . '.' . substr($value, 5, 3) . '/' . substr($value, 8, 4) . '-' . substr($value, 12, 2); } else { return 'Indefinido'; } } public function getRegistroCoreAttribute($value) { return substr_replace($value, '/', -4, 0); } public function solicitacoesEnderecos() { return RepresentanteEndereco::where('ass_id', '=', $this->ass_id)->where('status', '!=', 'Enviado')->orderBy('created_at', 'DESC')->get(); } public function cedulas() { return $this->hasMany('App\SolicitaCedula', 'idrepresentante'); } public function termos() { return $this->hasMany('App\TermoConsentimento', 'idrepresentante'); } public function agendamentosSalas() { return $this->hasMany('App\AgendamentoSala', 'idrepresentante'); } public function suspensao() { return $this->hasMany('App\SuspensaoExcecao', 'idrepresentante')->first(); } public function agendamentosAtivos() { return $this->agendamentosSalas() ->with('sala.regional') ->whereNull('status') ->orderBy('dia', 'ASC') ->orderBy('periodo', 'ASC') ->orderBy('status', 'ASC') ->paginate(4); } public function podeAgendar($mes = null, $ano = null) { $total = 4; // devido poder agendar somente no dia seguinte $dia = Carbon::tomorrow(); while($dia->isWeekend()) $dia->addDay(); $atual = $this->agendamentosSalas() ->when(isset($mes) && !isset($ano), function($query) use($mes){ $query->whereMonth('dia', $mes) ->whereYear('dia', now()->year); }) ->when(isset($ano) && !isset($mes), function($query) use($ano){ $query->whereMonth('dia', now()->month) ->whereYear('dia', $ano); }) ->when(isset($mes) && isset($ano), function($query) use($mes, $ano){ $query->whereMonth('dia', $mes) ->whereYear('dia', $ano); }) ->when(!isset($mes) && !isset($ano), function($query) use($dia){ $query->whereMonth('dia', $dia->month) ->whereYear('dia', $dia->year); }) ->where(function($query){ $query->whereNull('status') ->orWhere('status', 'Compareceu'); }) ->count() < $total; $seguinte = false; // Evitar que pule mês. Ex: janeiro para fevereiro. $dataSeguinte = Carbon::parse($dia->format('Y-m') . '-01')->addMonth(); $mesSeguinte = $dataSeguinte->month; $anoSeguinte = $dataSeguinte->year; if(!isset($mes) && !isset($ano)) $seguinte = $this->agendamentosSalas() ->whereMonth('dia', $mesSeguinte) ->whereYear('dia', $anoSeguinte) ->where(function($query){ $query->whereNull('status') ->orWhere('status', 'Compareceu'); }) ->count() < $total; return $atual || $seguinte; } public function getPeriodoByDia($dia, $periodosDisponiveis) { $agendados = $this->agendamentosSalas() ->where('dia', $dia) ->whereNull('status') ->orderBy('dia') ->orderBy('periodo_todo', 'DESC') ->get(); foreach($agendados as $agendado) $periodosDisponiveis = $agendado->getHorasPermitidas($periodosDisponiveis); return $periodosDisponiveis; } public function getAgendamentos30Dias($diasLotados = array()) { $diasAgendado = array(); $agendados = $this->agendamentosSalas() ->whereNull('status') ->whereBetween('dia', [Carbon::tomorrow()->format('Y-m-d'), Carbon::today()->addMonth()->format('Y-m-d')]) ->orderBy('dia') ->get(); foreach($agendados as $agendado) { $add = true; $dia = Carbon::parse($agendado->dia); foreach($diasLotados as $dias){ if($dias === [$dia->month, $dia->day, 'lotado']) $add = false; } if($add) array_push($diasAgendado, [$dia->month, $dia->day, 'agendado']); } return $diasAgendado; } }
import { useState } from 'react'; import { View, Modal, ModalProps, Text, TouchableOpacity, Alert, ActivityIndicator } from 'react-native'; import * as Clipboard from 'expo-clipboard'; import { Heading } from '../Heading'; import { styles } from './styles'; import { MaterialIcons } from '@expo/vector-icons' import { THEME } from '../../theme'; interface Props extends ModalProps { discord: string; onClose: () => void } export function DuoModalMatch({ discord, onClose, ...rest }: Props) { const [isCopying, setIsCopying] = useState(false) async function handleCopyDiscordToClipboard() { setIsCopying(true) await Clipboard.setStringAsync(discord) Alert.alert('Discord Copiado!', 'Conteúdo copiado para sua área de transferência.') setIsCopying(false) } return ( <Modal {...rest} transparent statusBarTranslucent animationType='fade' > <View style={styles.container}> <View style={styles.content}> <TouchableOpacity style={styles.closeIcon} onPress={onClose} > <MaterialIcons name='close' size={20} color={THEME.COLORS.CAPTION_500} /> </TouchableOpacity> <MaterialIcons name='check-circle-outline' size={64} color={THEME.COLORS.SUCCESS} /> <Heading title='Let’s play!' subtitle='Agora é só começar a jogar!' style={{ alignItems: 'center', marginTop: 24 }} /> <Text style={styles.label}> Adicione no Discord </Text> <TouchableOpacity style={styles.discordButton} onPress={handleCopyDiscordToClipboard} disabled={isCopying} > <Text style={styles.discord}> {isCopying ? <ActivityIndicator color={THEME.COLORS.PRIMARY} /> : discord} </Text> </TouchableOpacity> </View> </View> </Modal> ); }
import React, { Component } from 'react' class RobotText extends Component { constructor() { super() this.state = { text: 'Hi, I am robot!', time: 5, } } componentDidMount() { this.interval = setInterval( () => this.setState(prev => ({ time: prev.time - 1 })), 1000 ) this.timeout = setTimeout(() => { this.setState({ text: 'Well, actually nope..' }) clearInterval(this.interval) }, 5000) } componentWillUnmount() { clearInterval(this.interval) clearTimeout(this.timeout) } render() { return <div> <h1>{this.state.text}</h1> <h2>You will know the truth after {this.state.time} s</h2> </div> } } export default RobotText
#include <stdio.h> #include <stdlib.h> #include <time.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } int checkArray(int arr[], int n) { for (int i = 1 ; i < n; i++) { if (arr[i] < arr[i - 1]) { return 0; } } return 1; } void shuffleArray(int arr[], int n) { srand(time(NULL)); for (int i = n - 1; i > 0; i--) { int j = rand() % (i + 1); swap(&arr[i], &arr[j]); } } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int worstSort(int arr[] , int n ){ int count = 0; while(checkArray(arr,n) == 0){ count++; shuffleArray(arr,n); } return count; } int main() { int arr[] = {4,3,2,1}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); clock_t start_time = clock(); int count = worstSort(arr, n); clock_t end_time = clock(); printf("Sorted array: "); printArray(arr, n); double time_taken = ((double)(end_time - start_time)) / CLOCKS_PER_SEC; printf("Time taken: %f seconds\n", time_taken); printf("Number of shuffles: %d\n", count); return 0; }
import { Button, ButtonGroup, Card, CardBody, CardFooter, Divider, Heading, Image, Stack, Text, useToast, } from '@chakra-ui/react' import { useContext } from 'react' import { Link } from 'react-router-dom' import { CartContext } from '../context/CartContext' export const ProductCard = ({ product }) => { const { image, name, price, id } = product const { addProduct } = useContext(CartContext) const toast = useToast() const addProductToCart = (product, quantity) => { addProduct({ ...product, quantity, }) toast({ title: 'Producto agregado', status: 'success', colorScheme: 'blackAlpha', duration: 2500, isClosable: false, }) } return ( <Card maxW="sm"> <CardBody> <Link to={'/productos/' + id}> <Image src={image} alt={name} borderRadius="lg" width="100%" height="400px" objectFit='cover'/> </Link> <Stack mt="6" spacing="3"> <Heading size="md" fontWeight={400}> {name} </Heading> <Text fontWeight={300} fontSize="2xl"> ${price} </Text> </Stack> </CardBody> <Divider /> <CardFooter> <ButtonGroup gap={2} display="flex" flexWrap="wrap" justifyContent="center" > <Button as={Link} to={'/productos/' + id} variant="solid" bg="black" color="white" textTransform="uppercase" _hover={{ transform: 'translateY(1px)', boxShadow: 'lg', color:'#008100', transition: 'all .3s ease-in-out', }} > Ver Detalles </Button> <Button variant="ghost" color="#008100" onClick={() => addProductToCart(product, 1)} _hover={{ transition: 'all .3s ease-in-out', backgroundColor: 'gray.300', }} > Agregar al carrito </Button> </ButtonGroup> </CardFooter> </Card> ) }
enum StatusTarefa { Aguardando = 'AGUARDANDO', EmAndamento = 'EM_ANDAMENTO', Concluida = 'CONCLUIDA' } export class Tarefa { private Id: string; private Titulo: string; private Descricao: string; private StatusTarefa: StatusTarefa; private HistoriaDeUsuarioId: string; private Dependencias: string[]; constructor( id: string, titulo: string, descricao: string, statusTarefa: StatusTarefa, historiaDeUsuarioId: string, dependencias: string[] ) { this.Id = id; this.Titulo = titulo; this.Descricao = descricao; this.StatusTarefa = statusTarefa; this.HistoriaDeUsuarioId = historiaDeUsuarioId; this.Dependencias = dependencias; } // Getters get id(): string { return this.Id; } get titulo(): string { return this.Titulo; } get descricao(): string { return this.Descricao; } get statusTarefa(): StatusTarefa { return this.StatusTarefa; } get historiaDeUsuarioId(): string { return this.HistoriaDeUsuarioId; } get dependencias(): string[] { return this.Dependencias; } }
#include <unistd.h> #include <sys/types.h> #include <stdio.h> #include <string.h> #define BUF_SIZE 100 int main() { char buf[BUF_SIZE]; // Creating first child pid_t n1 = fork(); // Creating second child. First child also executes this line and creates grandchild. pid_t n2 = fork(); if (n1 > 0 && n2 > 0) // Parent block { sprintf(buf, "\nparent\n%d %d \nmy id is %d \nmy parentid is %d \n", n1, n2, getpid(), getppid()); write(1, buf, strlen(buf)); } else if (n1 == 0 && n2 > 0) // First child block { sprintf(buf, "\nfirst child\n%d %d \nmy id is %d \nmy parentid is %d \n", n1, n2, getpid(), getppid()); write(1, buf, strlen(buf)); } else if (n1 > 0 && n2 == 0) // Second child block { sprintf(buf, "\nsecond child\n%d %d \nmy id is %d \nmy parentid is %d \n", n1, n2, getpid(), getppid()); write(1, buf, strlen(buf)); } else // if (n1 == 0 && n2 == 0) { // Third child block - grandchild of parent, child of first child sprintf(buf, "\nthird child\n%d %d \nmy id is %d \nmy parentid is %d \n", n1, n2, getpid(), getppid()); write(1, buf, strlen(buf)); } return 0; }
#################################################################################################################################################################################### # Author: Dilara Genc (494808dg) # Study: Econometrics and Operational Research # This program shows step 2 up until 4 for the research # of the thesis for k-means and AGNES clustering with Isomap as its dimension # reduction technique #################################################################################################################################################################################### # Step 0: Import full data set install packages #################################################################################################################################################################################### #install and load packages install.packages("readxl") install.packages("vegan") install.packages("cluster") install.packages("fpc") install.packages("clValid") install.packages("clusterSim") library(readxl) library(vegan) library(cluster) library(fpc) library(clValid) library(clusterSim) # NOTE: The data set consists of 73.421 observations (users) of 101 variables jester_dataset_full <- read_excel("~/Econometrie/Econometrie Jaar 3/Thesis/Data/jester_dataset_full.xlsx") id <- which(jester_dataset_full$user_id == 100) # Select complete cases # Take a subset because you do not want to use the user_id column in you analysis jester_dataset_full_change <- jester_dataset_full[, 2:101] # Specify the value to remove remove <- 99 # Replace the 99 values with NA jester_dataset_full_change[jester_dataset_full_change == remove] <- NA # Omit the NA cases and obtain a matrix without NA Jester_no_NA <- na.omit(jester_dataset_full_change) # Take subset of 5000 samples set.seed(100) # Set the seed for reproducibility # Get random row indices random_rows <- sample(nrow(Jester_no_NA), size = 50, replace = FALSE) # Take the random subset of the matrix, 50x100=5000 jester_dataset_full_subset <- Jester_no_NA[random_rows, 1:100] #jester_dataset_full_subset_change <- Jester_no_NA[random_rows, 1:100] #jester_dataset_full_subset <- Jester_no_NA[450:500, 1:100] # Remove unneeded data rm(jester_dataset_full) rm(jester_dataset_full_change) rm(jester_dataset_full_sample) #################################################################################################################################################################################### #step 2: Data Transformation #################################################################################################################################################################################### # (7) (NON-Linear Data Transformation) Isomap # Perform Isomap isomap_jester_dataset_full_subset <- isomap(dist(jester_dataset_full_subset), k=3) # Get the the low-dimensional representation and view the Isomap coordinates isomap_jester_dataset_full_subset_coordinates <- isomap_jester_dataset_full_subset$points #reduced data set print(isomap_jester_dataset_full_subset_coordinates) #################################################################################################################################################################################### # step 3: Clustering with the transformed data sets #################################################################################################################################################################################### # (1) k-means with k = 3 (found in step 1, see other code) k <- 3 # (vii) k-means with Isomap kmeans_isomap <- kmeans(isomap_jester_dataset_full_subset_coordinates, centers = k, nstart = 1000) # Get the cluster assignments for internal validation cluster_assignments_kmeans_isomap <- kmeans_isomap$cluster # (2) AGNES with k = 3(found in step 1) # (vii) AGNES with Isomap agnes_isomap <- agnes(isomap_jester_dataset_full_subset_coordinates, metric = "euclidian", method = "average") # Get and view the cluster assignments cluster_agnes_isomap <- cutree(agnes_isomap, k=3) print(cluster_agnes_isomap) # Get kmeans with t-SNE visualization plot(isomap_jester_dataset_full_subset_coordinates, col = cluster_assignments_kmeans_isomap, main = "K-means - with Isomap", xlab = "C1", ylab = "C2", pch = 15) # Get AGNES with t-SNE visualisation plot(isomap_jester_dataset_full_subset_coordinates, col = cluster_agnes_isomap, main = "AGNES - with Isomap", xlab = "C1", ylab = "C2", pch = 15) #################################################################################################################################################################################### # step 4: Internal cluster validation #################################################################################################################################################################################### # (6) For k_means and Isomap combined # (i) Dunn Index dunn_index_kmeans_isomap <- dunn(clusters = cluster_assignments_kmeans_isomap, Data = dist(isomap_jester_dataset_full_subset_coordinates)) # (ii) Calinski-Harabasz Index calinski_index_kmeans_isomap <- calinhara(dist(isomap_jester_dataset_full_subset_coordinates), cluster_assignments_kmeans_isomap, cn = max(cluster_assignments_kmeans_isomap)) # (iii) Silhouette Index silhouette_kmeans_isomap <- silhouette(cluster_assignments_kmeans_isomap, dist(isomap_jester_dataset_full_subset_coordinates)) silhouette_index_kmeans_isomap <- mean(silhouette_kmeans_isomap[, 3]) # (iv) Davies-Bouldin index cl1 <- pam(cluster_assignments_kmeans_isomap, 3) davies_index_kmeans_isomap <- index.DB(cluster_assignments_kmeans_isomap, cl1$clustering, d=dist(isomap_jester_dataset_full_subset_coordinates), centrotypes="centroids", p=2, q=1)$DB # For AGNES and Isomap combined # (i) Dunn Index dunn_index_agnes_isomap <- dunn(clusters = cluster_agnes_isomap, Data = dist(isomap_jester_dataset_full_subset_coordinates)) # (ii) Calinski-Harabasz Index calinski_index_agnes_isomap <- calinhara(dist(isomap_jester_dataset_full_subset_coordinates), cluster_agnes_isomap, cn = max(cluster_agnes_isomap)) # (iii) Silhouette Index silhouette_agnes_isomap <- silhouette(cluster_agnes_isomap, dist(isomap_jester_dataset_full_subset_coordinates)) silhouette_index_agnes_isomap <- mean(silhouette_agnes_isomap[, 3]) # (iv) Davies-Bouldin index cl2 <- pam(cluster_agnes_isomap, 3) davies_index_agnes_isomap <- index.DB(cluster_agnes_isomap, cl2$clustering, d=dist(isomap_jester_dataset_full_subset_coordinates), centrotypes="centroids", p=2, q=1)$DB # Print internal validation metrics for kmeans print(dunn_index_kmeans_isomap) print(calinski_index_kmeans_isomap) print(silhouette_index_kmeans_isomap) print(davies_index_kmeans_isomap) # Print internal validation metrics for AGNES print(dunn_index_agnes_isomap) print(calinski_index_agnes_isomap) print(silhouette_index_agnes_isomap) print(davies_index_agnes_isomap)
<template> <main @click.self="closeModal" class="auth modal"> <div class="auth__container modal__container"> <form @submit.prevent="submitHandler" class="auth__form"> <p class="auth__message" :class="{ error: authError || message }"> {{ authError || message || authLabels[authType]?.title }} </p> <v-input v-if="isRegistration" v-model.trim="name" @update:modelValue="v$.name.$touch" @touch="v$.name.$touch" :errors="getErrors(v$.name)" :name="'name'" class="auth__field" >Имя Фамилия*</v-input > <v-input v-model.trim="email" @update:modelValue="v$.email.$touch" @touch="v$.email.$touch" :errors="getErrors(v$.email)" :name="'email'" :type="'email'" class="auth__field" >Email*</v-input > <v-input v-if="isRegistration" v-model.trim="phone" @update:modelValue="v$.phone.$touch" @touch="v$.phone.$touch" :errors="getErrors(v$.phone)" :name="'phone'" :type="'tel'" class="auth__field" >Телефон*</v-input > <v-input v-if="!isRecovery" v-model="password" @update:modelValue="v$.password.$touch" @touch="v$.password.$touch" :errors="getErrors(v$.password)" :name="'password'" :type="'password'" class="auth__field" >Пароль*</v-input > <v-input v-if="isRegistration" v-model="passwordRepeat" @update:modelValue="updatePasswordRepeatHandler" @touch="v$.passwordRepeat.$touch" :errors="getErrors(v$.passwordRepeat)" :name="'passwordRepeat'" :type="'password'" class="auth__field" >Повтор пароля*</v-input > <p v-if="isRegistration" class="auth__button auth__privacy-agree"> Нажимая на кнопку зарегистрироваться вы соглашаетесь с <button @click.stop="showPrivacy" type="button" class="auth__link"> Политикой конфиденциальности </button> </p> <form-button class="auth__submit">{{ authLabels[authType].submit }}</form-button> <button v-if="!isAuthorization" @click.stop="switchToLogin" type="button" class="auth__button" > Войти в аккаунт </button> <button v-if="!isRegistration" @click.stop="switchToRegister" type="button" class="auth__button" > Создать аккаунт </button> </form> </div> </main> </template> <script> import FormButton from '@/components/FormButton.vue' import vInput from '@/components/Input.vue' import { mapMutations } from 'vuex' import useVuelidate from '@vuelidate/core' import { helpers, email, required, minLength, maxLength, sameAs, } from '@vuelidate/validators' export default { props: { message: String, }, emits: ['close:modal', 'update:user'], components: { FormButton, vInput, }, inject: ['axiosNotify'], setup() { return { v$: useVuelidate(), authLabels: { authorization: { title: 'Авторизация', submit: 'Войти', }, registration: { title: 'Регистрация', submit: 'Зарегистрироваться', }, }, } }, data() { return { authType: 'authorization', authError: null, name: '', email: '', phone: '', password: '', passwordRepeat: '', } }, validations() { const numberCaser = (number) => { const lastDigit = number % 10 if (lastDigit === 1) return 'Символ' if (lastDigit > 1 && lastDigit < 5) return 'Символа' return 'Символов' } const needValidation = (validator) => { const helper = validator.$validator validator.$validator = (value) => !this.isRegistration || helper(value) return validator } const minPassword = 8 const maxPassword = 30 const minName = 4 const maxName = 30 return { name: { required: helpers.withMessage( 'Имя Фамилия - обязательное поле', needValidation(required) ), minLength: helpers.withMessage( (field) => `Минимальная длина имени ${field.$params.min} ${numberCaser( field.$params.min )}`, needValidation(minLength(minName)) ), maxLength: helpers.withMessage( (field) => `Максимальная длина имени ${field.$params.max} ${numberCaser( field.$params.max )}`, needValidation(maxLength(maxName)) ), }, email: { required: helpers.withMessage( 'Электронная почта - обязательное поле', required ), email: helpers.withMessage( 'Неверный формат электронной почты', needValidation(email) ), }, phone: { required: helpers.withMessage( 'Телефон - обязательное поле', needValidation(required) ), }, password: { required: helpers.withMessage('Пароль - обязательное поле', required), minLength: helpers.withMessage( (field) => `Минимальная длина пароля ${field.$params.min} ${numberCaser( field.$params.min )}`, needValidation(minLength(minPassword)) ), maxLength: helpers.withMessage( (field) => `Максимальная длина пароля ${field.$params.max} ${numberCaser( field.$params.max )}`, needValidation(maxLength(maxPassword)) ), }, passwordRepeat: { required: helpers.withMessage( 'Подтверждение пароля - обязательное поле', needValidation(required) ), sameAs: helpers.withMessage( 'Пароли не совпадают', needValidation(sameAs(this.password)) ), }, } }, computed: { isRegistration() { return this.authType === 'registration' }, isAuthorization() { return this.authType === 'authorization' }, isRecovery() { return this.authType === 'recovery' }, }, methods: { ...mapMutations(['updateUser', 'updateToken']), closeModal() { this.$emit('close:modal') }, showPrivacy() { this.showModal('privacy') }, getErrors(vuelidatable) { return vuelidatable?.$errors?.map((err) => err.$message) }, updatePasswordRepeatHandler() { if (this.password.length <= this.passwordRepeat.length) this.v$.passwordRepeat.$touch() }, switchToRegister() { this.authType = 'registration' this.switchAuthType() }, switchToLogin() { this.authType = 'authorization' this.switchAuthType() }, switchAuthType() { this.v$.$reset() this.authError = null }, async submitHandler(e) { if (!(await this.v$.$validate())) return let data = {}, options = {}, url = '/user' if (this.isRegistration) { data = { name: this.name, email: this.email.toLowerCase(), phone: this.phone, password: this.password, } url += '/register' } else if (this.isAuthorization) { data = { email: this.email.toLowerCase(), password: this.password, } url += '/login' } else { return (this.authError = 'Кажется что-то сломалось. Обновите страницу') } const loader = this.$loading.show({ container: e.target, canCancel: false, }) const response = await this.$axios .post(url, data, options) .then((res) => { console.log(res) return { message: res.data, status: res.status } }) .catch((err) => ({ message: err?.response?.data.detail, status: err?.response?.status, })) loader.hide() if (response.status >= 400) { if (response.message instanceof Array) return (this.authError = 'Что-то пошло не так') const res = response.message === 'Not authorized' ? 'Неверный логин или пароль' : response.message if (res) this.authError = res || 'Что-то пошло не так' return } const token = `bearer ${response.message.accessToken}` this.updateToken(token) this.$emit('update:user') this.$emit('close:modal') }, }, watch: { 'v$.$errors'(errors) { if (errors.length === 0) this.authError = null }, }, } </script> <style lang="scss" scoped> .auth { &__container { width: min(100%, 500px); max-height: 100%; } &__form { padding: 0 32px 32px; position: relative; display: flex; flex-direction: column; justify-content: flex-start; align-items: center; width: 100%; height: 100%; border-radius: 1px; background-color: #fff; } &__message { margin: 24px 0; font-weight: 700; font-size: 20px; &.error { color: #c72727; } } &__submit { font-size: 24px; font-weight: 700; } &__button { margin: 10px 0 0; color: var(--font-dark); font-weight: 300; font-size: 14px; background-color: transparent; } &__privacy-agree { margin: 0; text-align: center; } &__link { font-size: inherit; font-weight: 500; font-family: inherit; text-decoration: underline; text-decoration-thickness: 2px; text-decoration-color: var(--primary-dark); color: var(--primary-dark); background-color: transparent; } } </style>
import * as remoteMain from '@electron/remote/main'; import { app, BrowserWindow, ipcMain, shell } from 'electron'; import log from 'electron-log'; import { autoUpdater } from 'electron-updater'; import moment from 'moment'; import path from 'path'; import 'regenerator-runtime/runtime'; import MenuBuilder from './menu'; import { resolveHtmlPath } from './util'; const sqlite3 = require('sqlite3').verbose(); const { mkdirSync, copyFileSync, existsSync } = require('fs'); remoteMain.initialize(); /********************* TYPES ***********************/ type ErrorType = { message: string; }; declare global { interface Window { get_employee_designation: any; insert_employee_designation: any; delete_employee_designation: any; insert_department: any; fetch_department: any; delete_department: any; insert_sub_department: any; fetch_sub_department: any; delete_sub_department: any; insert_salary_advance: any; fetch_salary_advance: any; delete_salary_advance: any; insert_employee: any; insert_floor: any; delete_floor: any; fetch_floor: any; insert_customer_table: any; fetch_customer_table: any; delete_customer_table: any; fetch_table_based_on_floor_id: any; fetch_table_based_on_floor_id_response: any; send_status_to_create_table: any; get_table_data: any; } } // Initialize db path var dbPath = app.getPath('userData'); export default class AppUpdater { constructor() { log.transports.file.level = 'info'; autoUpdater.logger = log; autoUpdater.checkForUpdatesAndNotify(); } } let mainWindow: BrowserWindow | null | null = null; if (process.env.NODE_ENV === 'production') { const sourceMapSupport = require('source-map-support'); sourceMapSupport.install(); } const isDevelopment = process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true'; if (isDevelopment) { require('electron-debug')(); } const installExtensions = async () => { const installer = require('electron-devtools-installer'); const forceDownload = !!process.env.UPGRADE_EXTENSIONS; const extensions = ['REACT_DEVELOPER_TOOLS']; return installer .default( extensions.map((name) => installer[name]), forceDownload ) .catch((err: ErrorType) => console.log(err)); }; const createWindow = async () => { if (isDevelopment) { await installExtensions(); } const RESOURCES_PATH = app.isPackaged ? path.join(process.resourcesPath, 'assets') : path.join(__dirname, '../../assets'); const getAssetPath = (...paths: any) => { return path.join(RESOURCES_PATH, ...paths); }; mainWindow = new BrowserWindow({ minWidth: 1024, minHeight: 600, icon: getAssetPath('favicon.png'), webPreferences: { preload: path.join(__dirname, 'preload.js'), webSecurity: false, nativeWindowOpen: true, nodeIntegration: true, // enableRemoteModule: true, }, }); remoteMain.enable(mainWindow.webContents); mainWindow.maximize(); mainWindow.loadURL(resolveHtmlPath('index.html')); mainWindow.on('ready-to-show', () => { if (!mainWindow) { throw new Error('"mainWindow" is not defined'); } if (process.env.START_MINIMIZED) { mainWindow.minimize(); } else { mainWindow.show(); } }); mainWindow.on('closed', () => { mainWindow = null; }); const menuBuilder = new MenuBuilder(mainWindow); menuBuilder.buildMenu(); // Open urls in the user's browser mainWindow.webContents.on('new-window', (event, url) => { event.preventDefault(); shell.openExternal(url); }); // Remove this if your app does not use auto updates // eslint-disable-next-line new AppUpdater(); }; /** * Add event listeners... */ // Get parent category data ipcMain.on('parent_category', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { let sql = `SELECT category_id, category_name, parent_id, category_is_active FROM add_item_category ORDER BY category_id DESC`; db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('parent_category', rows); }); }); db.close(); } }); SETTINGS // Insert & Update Settings ipcMain.on('insert_settings', (_event, args) => { let appFavicon: any = null, appLogo: any = null; if (args.newFavicon) { appFavicon = JSON.parse(args.favicon); } else { appFavicon = args.favicon; } if (args.newLogo) { appLogo = JSON.parse(args.logo); } else { appLogo = args.logo; } // Set setting images and icons path let settings_favicon_folder_name = 'settings_favicon'; let settings_logo_folder_name = 'settings_logo'; setImagePath( settings_favicon_folder_name, // Setting images folder name settings_logo_folder_name, // Setting icons folder name appFavicon?.path, // Setting image path appFavicon?.name, // Setting image name appLogo?.path, // Setting icon path appLogo?.name // Setting icon namesettings_logo ); let { title, storename, address, email, phone, opentime, closetime, vat, vattinno, discount_type, discountrate, servicecharge, service_chargeType, currency, min_prepare_time, language, timezone, dateformat, site_align, powerbytxt, footer_text, } = args; // Create DB connection let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run(`DROP TABLE IF EXISTS setting`) .run( `CREATE TABLE IF NOT EXISTS setting ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "title" varchar(255), "storename" varchar(100), "address" TEXT, "email" varchar(255), "phone" varchar(25), "favicon" varchar(100), "logo" varchar(255), "opentime" varchar(255), "closetime" varchar(255), "vat" REAL, "vattinno" varchar(30), "discount_type" INT, "discountrate" REAL, "servicecharge" REAL, "service_chargeType" INT, "currency" INT, "min_prepare_time" varchar(50), "language" varchar(100), "timezone" varchar(150), "dateformat" TEXT, "site_align" varchar(50), "powerbytxt" TEXT, "footer_text" varchar(255) )` ) .run( `INSERT INTO setting ( title, storename, address, email, phone, favicon, logo, opentime, closetime, vat, vattinno, discount_type, discountrate, servicecharge, service_chargeType, currency, min_prepare_time, language, timezone, dateformat, site_align, powerbytxt, footer_text ) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )`, [ title, storename, address, email, phone, appFavicon?.name ? path?.join( app.getPath('userData'), 'assets', settings_favicon_folder_name, appFavicon.name ) : appFavicon, appLogo?.name ? path?.join( app.getPath('userData'), 'assets', settings_logo_folder_name, appLogo.name ) : appLogo, opentime, closetime, vat, vattinno, discount_type, discountrate, servicecharge, service_chargeType, currency, min_prepare_time, language, timezone, dateformat, site_align, powerbytxt, footer_text, ], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_settings_response', err.message ) : mainWindow.webContents.send('insert_settings_response', { status: 'inserted', }); } ); }); db.close(); }); // Get Settings for the application settings fields to display them in the fields getListItems( 'get_app_settings', //Channel Name 'get_app_settings_response', //Channel response 'setting' //Table Name ); // Get Settings for the whole application ipcMain.on('get_settings', (_event: Electron.IpcMainEvent, args) => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let { status } = args; let sql = `SELECT setting.*, currency.currency_icon, currency.position FROM setting INNER JOIN currency ON setting.currency=currency.id`; if (status) { db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { if (rows) { const settingsData = { ...rows[0], isAppSetupDone: true, }; mainWindow.webContents.send('get_settings_response', settingsData); } else { mainWindow.webContents.send('get_settings_response', { isAppSetupDone: false, }); } }); }); } db.close(); }); // getListItems( // 'get_settings', //Channel Name // 'get_settings_response', //Channel response // 'setting', //Table Name // 'title, storename, address, logo, opentime, closetime, vat, vattinno, discount_type, discountrate, servicecharge, service_chargeType, currency, site_align, dateformat, timezone' //Columns // ); /** * Set images paths * @params string images folder name * @params string icons folder name * @params string image path * @params string image name * @params string icon path * @params string icon name * */ function setImagePath( images_folder_name: string, icons_folder_name: string, image_path: string, image_name: string, icon_path: string, icon_name: string ) { try { mkdirSync(path.join(app.getPath('userData'), 'assets')); if (image_path) { let folderToCreate = path.join( app.getPath('userData'), 'assets', images_folder_name ); if (existsSync(folderToCreate)) { let fileToCopy = image_path; let newFileName = image_name; let dest = path.join(folderToCreate, newFileName); copyFileSync(fileToCopy, dest); } else { let fileToCopy = image_path; let newFileName = image_name; let dest = path.join(folderToCreate, newFileName); mkdirSync(folderToCreate); copyFileSync(fileToCopy, dest); } } if (icon_path) { let folderToCreate = path.join( app.getPath('userData'), 'assets', icons_folder_name ); if (existsSync(folderToCreate)) { let fileToCopy = icon_path; let newFileName = icon_name; let dest = path.join(folderToCreate, newFileName); copyFileSync(fileToCopy, dest); } else { let fileToCopy = icon_path; let newFileName = icon_name; let dest = path.join(folderToCreate, newFileName); mkdirSync(folderToCreate); copyFileSync(fileToCopy, dest); } } } catch (error) { if (image_path) { let folderToCreate = path.join( app.getPath('userData'), 'assets', images_folder_name ); if (existsSync(folderToCreate)) { let fileToCopy = image_path; let newFileName = image_name; let dest = path.join(folderToCreate, newFileName); copyFileSync(fileToCopy, dest); } else { let fileToCopy = image_path; let newFileName = image_name; let dest = path.join(folderToCreate, newFileName); mkdirSync(folderToCreate); copyFileSync(fileToCopy, dest); } } if (icon_path) { let folderToCreate = path.join( app.getPath('userData'), 'assets', icons_folder_name ); if (existsSync(folderToCreate)) { let fileToCopy = icon_path; let newFileName = icon_name; let dest = path.join(folderToCreate, newFileName); copyFileSync(fileToCopy, dest); } else { let fileToCopy = icon_path; let newFileName = icon_name; let dest = path.join(folderToCreate, newFileName); mkdirSync(folderToCreate); copyFileSync(fileToCopy, dest); } } } } // Insert and Update Category data ipcMain.on('insertCategoryData', (_event, args) => { let cat_img: any = null, cat_icon: any = null; if (args.new_category_image) { cat_img = JSON.parse(args.category_image); } else { cat_img = args.category_image; } if (args.new_category_icon) { cat_icon = JSON.parse(args.category_icon); } else { cat_icon = args.category_icon; } // Set categories images and icons path let cat_image_folder_name = 'categories_images'; let cat_icon_folder_name = 'categories_icons'; setImagePath( cat_image_folder_name, // Category images folder name cat_icon_folder_name, // Category icons folder name cat_img?.path, // Category image path cat_img?.name, // Category image name cat_icon?.path, // Category icon path cat_icon?.name // Category icon name ); let { category_name, parent_id, category_is_active, offer_start_date, offer_end_date, category_color, } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); if (args.category_id !== undefined) { db.serialize(() => { db.run( `INSERT OR REPLACE INTO add_item_category ( category_id, category_name, parent_id, category_image, category_icon, category_is_active, offer_start_date, offer_end_date, category_color ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ args.category_id, category_name, parent_id, cat_img?.name ? path.join( app.getPath('userData'), 'assets', cat_image_folder_name, cat_img.name ) : cat_img, cat_icon?.name ? path.join( app.getPath('userData'), 'assets', cat_icon_folder_name, cat_icon.name ) : cat_icon, category_is_active, offer_start_date, offer_end_date, category_color, ], (err: ErrorType) => { err ? mainWindow.webContents.send( 'after_insert_get_response', err.message ) : mainWindow.webContents.send('after_insert_get_response', { status: 'updated', }); } ); }); } else { db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS add_item_category ( 'category_id' INTEGER PRIMARY KEY AUTOINCREMENT, 'category_name' varchar(255), 'category_image' varchar(255), 'position' INT, 'category_is_active' INT, 'offer_start_date' DATE , 'offer_end_date' DATE, 'isoffer' INT, 'category_color' varchar(50), 'category_icon' varchar(255), 'parent_id' INT, 'user_id_inserted' INT, 'user_id_updated' INT, 'user_id_locked' INT, 'date_inserted' DATETIME, 'date_updated' DATETIME, 'date_locked' DATETIME )` ).run( `INSERT OR REPLACE INTO add_item_category ( category_name, parent_id, category_image, category_icon, category_is_active, offer_start_date, offer_end_date, category_color ) VALUES (?, ?, ?, ?, ?, ?, ?, ? )`, [ category_name, parent_id, cat_img?.name ? path.join( app.getPath('userData'), 'assets', cat_image_folder_name, cat_img.name ) : cat_img?.name, cat_icon?.name ? path.join( app.getPath('userData'), 'assets', cat_icon_folder_name, cat_icon.name ) : cat_icon?.name, category_is_active, offer_start_date, offer_end_date, category_color, ], (err: ErrorType) => { err ? mainWindow.webContents.send( 'after_insert_get_response', err.message ) : mainWindow.webContents.send('after_insert_get_response', { status: 'inserted', }); } ); }); } db.close(); }); // Get all category list ipcMain.on('sendResponseForCategory', (_event: Electron.IpcMainEvent, args) => { let { status } = args; if (status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let db2 = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sqlQ = `SELECT * FROM add_item_category WHERE parent_id IS NULL`; let sqlQ2 = `SELECT * FROM add_item_category WHERE parent_id IS NOT NULL`; db.serialize(() => { db.all(sqlQ, [], (_err: ErrorType, categories: any) => { db2.all(sqlQ2, [], (_err: ErrorType, sub_categories: any) => { sub_categories?.map((s: any) => { categories?.map((c: any) => { if (c.category_id === s.parent_id) { let sub_cat = { category_id: s.category_id, category_name: s.category_name, category_image: s.category_image, category_is_active: s.category_is_active, category_color: s.category_color, parent_id: s.parent_id, category_icon: s.category_icon, parent_cat: c.category_name, }; if (Array.isArray(c.subCategories)) { c.subCategories.push(sub_cat); } else { c.subCategories = [{ ...sub_cat }]; } } }); }); }); db2.close(); setTimeout(() => { mainWindow.webContents.send('sendCategoryData', categories); }, 1000); }); }); db.close(); } }); // Delete category data ipcMain.on('delete_category', (_event, args) => { let { id } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `DELETE FROM add_item_category WHERE category_id = ?`, id, (err: ErrorType) => { err ? mainWindow.webContents.send('delete_category_response', { status: err, }) : mainWindow.webContents.send('delete_category_response', { status: true, }); } ); }); db.close(); }); // Insert and update addons data ipcMain.on('add_addons', (_event, args) => { let { add_on_name, price, is_active } = args; if (args.add_on_id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO addons ( add_on_id, add_on_name, price, is_active, date_inserted ) VALUES ( ?, ?, ?, ?, ?)`, [args.add_on_id, add_on_name, price, is_active, Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send('add_addons_response', err.message) : mainWindow.webContents.send('add_addons_response', { status: 'updated', }); } ); }); db.close(); } else { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS addons ( "add_on_id" INTEGER PRIMARY KEY AUTOINCREMENT, "add_on_name" varchar(255), "price" REAL, "is_active" INT, "tax0" TEXT, "tax1" TEXT, "date_inserted" DATETIME )` ).run( `INSERT OR REPLACE INTO addons ( add_on_name, price, is_active, date_inserted ) VALUES ( ?, ?, ?, ?)`, [add_on_name, price, is_active, Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send('add_addons_response', err.message) : mainWindow.webContents.send('add_addons_response', { status: 'inserted', }); } ); }); db.close(); } }); // Get all addons from DB getListItems('addons_list', 'addons_list_response', 'addons'); // Delete addons data deleteListItem( 'delete_addons', //channel name 'delete_addons_response', //response event, 'addons' //table name ); ipcMain.on('delete_addons', (_event, args) => { let { id } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run(`DELETE FROM addons WHERE add_on_id = ?`, id, (err: ErrorType) => { err ? mainWindow.webContents.send('delete_addons_response', { status: err }) : mainWindow.webContents.send('delete_addons_response', { status: true, }); }); }); db.close(); }); Insert and update foods to DB ipcMain.on('add_new_foods', (_event, args) => { let product_img: any; try { if (args?.food_image) { product_img = JSON.parse(args.food_image); } } catch (error) { product_img = args.food_image; } // Set food images and icons path let foods_images_folder_name = 'foods_images'; setImagePath( foods_images_folder_name, // Food images folder name '', // Food icons folder name product_img?.path, // Food image path product_img?.name, // Food image name '', // Food icon path '' // Food icon name ); let { category_name, kitchen_select, food_name, component, notes, description, vat, offer_is_available, special, custom_quantity, cooking_time, menu_type, food_status, offer_rate, offer_start_date, offer_end_date, date_inserted, } = args; if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO item_foods (id, category_id, product_name, product_image, component, description, item_note, menu_type, product_vat, special, offers_rate, offer_is_available, offer_start_date, offer_end_date, kitchen_id, is_custom_quantity, cooked_time, is_active, date_inserted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ args.id, category_name, food_name, product_img?.name ? path.join( app.getPath('userData'), 'assets', foods_images_folder_name, product_img.name ) : product_img, component, description, notes, menu_type, vat, special, offer_rate, offer_is_available, offer_start_date, offer_end_date, kitchen_select, custom_quantity, cooking_time, food_status, date_inserted, ], (err: ErrorType) => { err ? mainWindow.webContents.send('add_new_foods_response', err.message) : mainWindow.webContents.send('add_new_foods_response', { status: 'updated', }); } ); }); db.close(); } else { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS item_foods ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'category_id' INT NOT NULL, 'product_name' varchar(255), 'product_image' varchar(200), 'big_thumb' varchar(255), 'medium_thumb' varchar(255), 'small_thumb' varchar(255), 'component' TEXT, 'description' TEXT, 'item_note' varchar(255), 'menu_type' varchar(25), 'product_vat' REAL DEFAULT 0.00, 'special' INT, 'offers_rate' INT, 'offer_is_available' INT, 'offer_start_date' DATETIME , 'offer_end_date' DATETIME, 'position' INT, 'kitchen_id' INT, 'is_group' INT, 'is_custom_quantity' INT, 'cooked_time' varchar(10), 'is_active' INT, 'user_id_inserted' INT, 'user_id_updated' INT, 'user_id_locked' INT, 'date_inserted' DATETIME, 'date_updated' DATETIME, 'date_locked' DATETIME, 'tax0' TEXT, 'tax1' TEXT )` ).run( `INSERT OR REPLACE INTO item_foods (category_id, product_name, product_image, component, description, item_note, menu_type, product_vat, special, offers_rate, offer_is_available, offer_start_date, offer_end_date, kitchen_id, is_custom_quantity, cooked_time, is_active, date_inserted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ category_name, food_name, product_img?.name ? path.join( app.getPath('userData'), 'assets', foods_images_folder_name, product_img.name ) : product_img?.name, component, description, notes, menu_type, vat, special, offer_rate, offer_is_available, offer_start_date, offer_end_date, kitchen_select, custom_quantity, cooking_time, food_status, Date.now(), ], (err: ErrorType) => { err ? mainWindow.webContents.send('add_new_foods_response', err.message) : mainWindow.webContents.send('add_new_foods_response', { status: 'inserted', }); } ); }); db.close(); } }); // Get all food list to display in the food list page ipcMain.on('get_food_list', (_event: Electron.IpcMainEvent, args) => { let { status } = args; let sql = `SELECT item_foods.id, item_foods.category_id, add_item_category.category_name, item_foods.product_name, item_foods.product_image, item_foods.component, item_foods.description, item_foods.item_note, item_foods.menu_type, item_foods.product_vat, item_foods.special, item_foods.offers_rate, item_foods.offer_is_available, item_foods.offer_start_date, item_foods.offer_end_date, item_foods.kitchen_id, item_foods.is_custom_quantity, item_foods.cooked_time, item_foods.is_active FROM item_foods INNER JOIN add_item_category ON item_foods.category_id=add_item_category.category_id`; if (status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('get_food_list_response', rows); }); }); db.close(); } }); // item_foods.menu_type, item_foods.is_active // Food list for the POS with (variants & addons) // SELECT variants.id, variants.food_id, variants.variant_name, variants.price FROM variants ipcMain.on('get_food_list_pos', (_event: Electron.IpcMainEvent, args) => { let { status } = args; // let sql = `SELECT item_foods.id, item_foods.category_id, item_foods.product_name, item_foods.product_image, item_foods.item_note, item_foods.product_vat, item_foods.special, item_foods.offers_rate, item_foods.offer_is_available, item_foods.is_custom_quantity, // variants.id AS variant_id, variants.food_id, variants.variant_name, variants.price // FROM item_foods JOIN variants ON item_foods.id = variants.food_id`; let sql = `select DISTINCT item_foods.* FROM item_foods INNER JOIN variants ON variants.food_id = item_foods.id`; if (status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('get_food_list_pos_response', rows); }); }); db.close(); } }); // Invoice id genaretor const tokenGenaretor = () => { return new Promise((resolve, reject) => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.all( 'SELECT token_no, creation_date FROM orders ORDER BY order_id DESC LIMIT 1', [], (err: ErrorType, rows: any) => { if (err) reject(err); resolve(rows); } ); }); db.close(); }); }; // Insert order ipcMain.on('insert_order_info', (_event, args: any) => { let { cartItems, customer_id, grandTotal, discount, serviceCharge, waiter_id, customer_type_id, cooking_time, floor_id, table_id, booked, vat, } = args; // let waiter_id = 1; // let customer_type_id = 2; // let cooking_time = 2022; // let floor_id = [6, 4]; // let table_id = [1, 2, 3]; // let booked = [3,5,8]; tokenGenaretor() .then((results: any) => { let date = new Date(results[0].creation_date); let existingDateFormat = date.toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric', }); let todaysDateTimeMilisec = Date.now(); let todaysDate = new Date(todaysDateTimeMilisec); let todaysDateFormat = todaysDate.toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric', }); let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS orders( "order_id" INTEGER PRIMARY KEY AUTOINCREMENT, "order_info" varchar(255), "customer_id" INT, "creation_date" DATETIME, "discount" REAL, "serviceCharge" REAL, "vat" REAL, "grand_total" REAL, "token_no" INT, "waiter_id" INT, "customer_type_id" INT, "floor_id" INT, "table_id" INT, "cooking_time" varchar(50), "booked" INT, "status" INT NOT NULL DEFAULT 1, "creation_date" INT )` ).run( `INSERT INTO orders (order_info, customer_id, discount, serviceCharge, vat, grand_total, token_no, waiter_id, customer_type_id, floor_id, table_id, cooking_time, booked, creation_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ JSON.stringify(cartItems), customer_id, discount, serviceCharge, vat, grandTotal, results[0] ? todaysDateFormat === existingDateFormat ? results[0].token_no + 1 : 1 : 1, waiter_id ? waiter_id : 'Munir', customer_type_id, JSON.stringify(floor_id), JSON.stringify(table_id), cooking_time, JSON.stringify(booked), Date.now(), ] ); }); db.close(); }) .catch((err) => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS orders( "order_id" INTEGER PRIMARY KEY AUTOINCREMENT, "order_info" varchar(255), "customer_id" INT, "discount" REAL, "serviceCharge" REAL, "vat" REAL, "grand_total" REAL, "token_no" INT, "waiter_id" INT, "customer_type_id" INT, "floor_id" INT, "table_id" INT, "cooking_time" varchar(50), "booked" INT, "status" INT NOT NULL DEFAULT 1, "creation_date" INT )` ).run( `INSERT INTO orders (order_info, customer_id, discount, serviceCharge, vat, grand_total, token_no, waiter_id, customer_type_id, floor_id, table_id, cooking_time, booked, creation_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ JSON.stringify(cartItems), customer_id, discount, serviceCharge, vat, grandTotal, 1, waiter_id, customer_type_id, JSON.stringify(floor_id), JSON.stringify(table_id), cooking_time, JSON.stringify(booked), Date.now(), ] ); }); db.close(); }); }); // get table data for orders ipcMain.on('get_table_data', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.all( `SELECT orders.order_id, orders.creation_date, orders.floor_id, orders.table_id, orders.booked FROM orders`, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('get_table_data_response', rows); } ); }); db.close(); } }); // Update order info after edit ipcMain.on('update_order_info_after_edit', (_event, args) => { let { order_info, order_id, discount, serviceCharge, vat, grand_total } = args; let order_info_to_string = JSON.stringify(order_info); let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `UPDATE orders SET order_info = ?, discount = ?, serviceCharge = ?, vat = ?, grand_total = ?, creation_date = ? WHERE order_id = ?`, [ order_info_to_string, discount, serviceCharge, vat, grand_total, Date.now(), order_id, ] ); }); db.close(); }); // SELECT orders.*, (employees.first_name ||' ' || employees.last_name)AS waiter_name, customer_type.customertype AS customer_type // FROM orders // INNER JOIN employees // ON orders.waiter_id = employees.id // INNER JOIN customer_type // ON orders.customer_type_id = customer_type.id // WHERE orders.status = 1 // Get all order info ipcMain.on('get_all_order_info_ongoing', (_event, args) => { let { status } = args; if (status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT orders.*, (employees.first_name ||' ' || CASE WHEN employees.last_name IS NOT NULL THEN employees.last_name ELSE '' END) AS waiter_name, customer_type.customertype AS customer_type FROM orders INNER JOIN employees ON orders.waiter_id = employees.id INNER JOIN customer_type ON orders.customer_type_id = customer_type.id WHERE orders.status = 1`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send( 'get_all_order_info_ongoing_response', rows ); }); }); db.close(); } }); // Get only today's completed order ipcMain.on('get_todays_completed_orders', (_event, args) => { let { status } = args; if (status) { // Get current datetime let datetime = Date.now(); let date = new Date(datetime); // Get current date from datetime let result = date.toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric', }); // Convert current date to milliseconds let d = new Date(result); let milliseconds = d.getTime(); let sql = `SELECT * FROM orders where status = 2 AND creation_date > ?`; let creation_date = milliseconds.toString(); let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.all(sql, [creation_date], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { const todaysOrders = rows.map((order: any) => { return { creation_date: moment(order.creation_date).format('ll'), order_id: order.order_id, customer_id: order.customer_id, grand_total: order.grand_total, invoice_id: order.order_id, status: order.status, }; }); mainWindow.webContents.send( 'get_todays_completed_orders_response', todaysOrders ); } }); }); db.close(); } }); // Complete order info ipcMain.on('update_order_info_ongoing', (_event: any, args: any) => { let { order_id, grand_total, discount } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); // grand_total // discount db.serialize(() => { db.run( `UPDATE orders SET status = 2, grand_total = ${grand_total}, discount = ${discount} WHERE order_id = ${order_id}` ); }); db.close(); }); // Get sales report ipcMain.on('get_all_order_for_sales_report', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT orders.*, customer_info.customer_name FROM orders INNER JOIN customer_info ON orders.customer_id = customer_info.id ORDER BY creation_date DESC`; db.all(sql, [], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { const allOrders = rows.map((order: any, index: number) => { let temp = JSON.parse(order.order_info); let amount = 0; temp.map((t: any) => { return (amount = t.total_price + amount); }); return { key: index, saleDate: moment(order.creation_date).format('ll'), invoiceNo: order.order_id, customerName: order.customer_id == 1 ? 'Walk In' : order.customer_name, paymentMethod: 'Cash Payment', totalAmount: amount, vatOrTax: order.vat, serviceCharge: order.serviceCharge, discount: order.discount, grandTotal: order.grand_total, }; }); mainWindow.webContents.send( 'get_all_order_for_sales_report_response', allOrders ); } }); db.close(); } }); // Get item sales report ipcMain.on( 'get_order_info_for_item_sales_report', (_event: Electron.IpcMainEvent, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT orders.order_info FROM orders`; db.all(sql, [], (_err: ErrorType, rows: any) => { if (rows && rows.length) { let newData = new Array(); rows.forEach((data: any) => { let temp = JSON.parse(data.order_info); temp.map((t: any) => newData.push(t)); }); const unique = newData; const group: any = {}; unique.forEach((e) => { const o = (group[e.id] = group[e.id] || { ...e, quantity: 0 }); o.quantity += e.quantity; }); const res = Object.values(group); mainWindow.webContents.send( 'get_order_info_for_item_sales_report_response', res ); } }); db.close(); } } ); // Get dashboard report ipcMain.on('get_dashboard_data', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT creation_date FROM orders`; let sql2 = `SELECT creation_date FROM orders WHERE status = 2`; let lifeTimeOrderQ = `SELECT COUNT(*) FROM orders`; let totalCustomerQ = `SELECT COUNT(*) FROM customer_info`; // let totalSalesQ = `SELECT COUNT(*) FROM orders where status = 2`; let todaysSalesQ = `SELECT COUNT(*) FROM orders where status = 2 and creation_date > ?`; let todaysOrderQ = `SELECT COUNT(*) FROM orders where creation_date > ?`; let promise1 = new Promise((resolve, _reject) => { db.all(sql, [], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { let orderCount = rows.map((row: any) => moment(row.creation_date).format('MMMM') ); const ordersCounts = { January: 0, February: 0, March: 0, April: 0, May: 0, June: 0, July: 0, August: 0, September: 0, October: 0, November: 0, December: 0, }; orderCount?.forEach((x: any) => { ordersCounts[x] = (ordersCounts[x] || 0) + 1; }); resolve(ordersCounts); } }); }); let promise2 = new Promise((resolve, _reject) => { db.all(sql2, [], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { let salesCount = rows.map((row: any) => moment(row.creation_date).format('MMMM') ); const salesCounts = { January: 0, February: 0, March: 0, April: 0, May: 0, June: 0, July: 0, August: 0, September: 0, October: 0, November: 0, December: 0, }; salesCount?.forEach((x: any) => { salesCounts[x] = (salesCounts[x] || 0) + 1; }); resolve(salesCounts); } }); }); let promise3 = new Promise((resolve, _reject) => { db.all(lifeTimeOrderQ, [], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { resolve(rows[0]['COUNT(*)']); } }); }); let promise4 = new Promise((resolve, _reject) => { // Get current datetime let datetime = Date.now(); let date = new Date(datetime); // Get current date from datetime let result = date.toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric', }); // Convert current date to milliseconds let d = new Date(result); let milliseconds = d.getTime(); let creation_date = milliseconds.toString(); let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.all(todaysSalesQ, [creation_date], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { resolve(rows[0]['COUNT(*)']); } }); db.close(); }); let promise5 = new Promise((resolve, _reject) => { db.all(totalCustomerQ, [], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { resolve(rows[0]['COUNT(*)']); } }); }); let promise6 = new Promise((resolve, _reject) => { // Get current datetime let datetime = Date.now(); let date = new Date(datetime); // Get current date from datetime let result = date.toLocaleDateString('en', { year: 'numeric', month: 'numeric', day: 'numeric', }); // Convert current date to milliseconds let d = new Date(result); let milliseconds = d.getTime(); let creation_date = milliseconds.toString(); let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.all(todaysOrderQ, [creation_date], (_err: ErrorType, rows: any) => { if (rows && rows.length > 0) { resolve(rows[0]['COUNT(*)']); } }); db.close(); }); Promise.all([ promise1, promise2, promise3, promise4, promise5, promise6, ]).then( (values) => { mainWindow.webContents.send('get_dashboard_data_response', values); }, (reason) => { mainWindow.webContents.send('get_dashboard_data_response', reason); } ); } }); // Delete food deleteListItem( 'delete_foods', // channel name 'delete_foods_response', // response event, 'item_foods' // table name ); // Get only food lists as an Array for (Food Availability) getListItems( 'food_lists_channel', 'food_lists_response', 'item_foods', 'id, product_name', true ); MENU TYPE - in the add food item getListItems( 'get_menu_type_list', 'get_menu_type_list_response', 'menu_type', 'id, menu_type', true ); FOOD VARIANT // Insert and update foods variant ipcMain.on('add_new_foods_variant', (_event, args) => { let { food_id, food_variant, food_price, date_inserted } = args; if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO variants (id, food_id, variant_name, price, date_inserted) VALUES (?, ?, ?, ?, ?)`, [args.id, food_id, food_variant, Number(food_price), date_inserted], (err: ErrorType) => { err ? mainWindow.webContents.send( 'add_new_foods_variant_response', err.message ) : mainWindow.webContents.send('add_new_foods_variant_response', { status: 'updated', }); } ); }); db.close(); } else { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS variants ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'food_id' INT, 'variant_name' varchar(255), 'price' REAL, 'date_inserted' DATETIME )` ).run( `INSERT OR REPLACE INTO variants (food_id, variant_name, price, date_inserted) VALUES (?, ?, ?, ?)`, [food_id, food_variant, Number(food_price), Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send( 'add_new_foods_variant_response', err.message ) : mainWindow.webContents.send('add_new_foods_variant_response', { status: 'inserted', }); } ); }); db.close(); } }); // get all variant list from DB ipcMain.on('variant_lists_channel', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT variants.id, variants.variant_name, variants.price, variants.food_id, variants.date_inserted, item_foods.product_name FROM variants INNER JOIN item_foods ON variants.food_id=item_foods.id`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('variant_lists_response', rows); }); }); db.close(); } }); // Delete variant from DB deleteListItem( 'delete_foods_variant', //channel name 'delete_foods_variant_response', //response event, 'variants' //table name ); FOOD AVAILABILITY // Insert Food availability data // Insert and update foods variant ipcMain.on('context_bridge_food_available_time', (_event, args) => { let { food_id, avail_day, avail_time, is_active } = args; if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO food_variable (id, food_id, avail_day, avail_time, is_active) VALUES (?, ?, ?, ?, ?)`, [args.id, food_id, avail_day, avail_time, is_active], (err: ErrorType) => { err ? mainWindow.webContents.send( 'context_bridge_food_available_time_response', err.message ) : mainWindow.webContents.send( 'context_bridge_food_available_time_response', { status: 'updated', } ); } ); }); db.close(); } else { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS food_variable ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'food_id' INT, 'avail_day' varchar(30), 'avail_time' varchar(50), 'is_active' INT )` ).run( `INSERT OR REPLACE INTO food_variable (food_id, avail_day, avail_time, is_active) VALUES (?, ?, ?, ?)`, [food_id, avail_day, avail_time, is_active], (err: ErrorType) => { err ? mainWindow.webContents.send( 'context_bridge_food_available_time_response', err.message ) : mainWindow.webContents.send( 'context_bridge_food_available_time_response', { status: 'inserted', } ); } ); }); db.close(); } }); ipcMain.on('get_food_availability_lists_channel', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT food_variable.*, item_foods.product_name FROM food_variable, item_foods WHERE food_variable.food_id == item_foods.id`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send( 'get_food_availability_lists_channel_response', rows ); }); }); db.close(); } }); // Delete food available day & time list channel from deleteListItem( 'channel_delete_food_available_day_time', //channel name 'delete_food_available_day_time_response', //response event, 'food_variable' //table name ); MENU TYPE // Insert Menu type ipcMain.on('context_bridge_menu_type', (_event, args) => { let { id, menu_type, menu_icon, is_active } = args; let menu_type_icon: any; try { if (menu_icon) { menu_type_icon = JSON.parse(menu_icon); } } catch (error) { menu_type_icon = args.menu_icon; } // Set categories images and icons path let menu_icon_folder_name = 'menu_icons'; setImagePath( menu_icon_folder_name, // Menu images folder name '', // Menu icons folder name menu_type_icon?.path, // Menu image path menu_type_icon?.name, // Menu image name '', // Menu icon path '' // Menu icon name ); // Execute if the event has menu type ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO menu_type (id, menu_type, menu_icon, is_active) VALUES (?, ?, ?, ?)`, [ id, menu_type, menu_type_icon?.name ? path.join( app.getPath('userData'), 'assets', menu_icon_folder_name, menu_type_icon.name ) : menu_type_icon, is_active, ], (err: ErrorType) => { err ? mainWindow.webContents.send( 'context_bridge_menu_type_response', err.message ) : mainWindow.webContents.send('context_bridge_menu_type_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new and then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS menu_type ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'menu_type' varchar(120), 'menu_icon' varchar(150), 'is_active' INT )` ).run( `INSERT OR REPLACE INTO menu_type (menu_type, menu_icon, is_active) VALUES (?, ?, ?)`, [ menu_type, menu_type_icon?.name ? path.join( app.getPath('userData'), 'assets', menu_icon_folder_name, menu_type_icon.name ) : menu_type_icon, is_active, ], (err: ErrorType) => { err ? mainWindow.webContents.send( 'context_bridge_menu_type_response', err.message ) : mainWindow.webContents.send('context_bridge_menu_type_response', { status: 'inserted', }); } ); }); db.close(); } }); // Get menu type lists as an Array getListItems( 'get_menu_type_lists', 'get_menu_type_lists_response', 'menu_type' ); // Get menu_type only is_active items & id, menu_type etc. getListItems( 'get_active_menu_type_lists', 'get_active_menu_type_lists_response', 'menu_type', 'menu_type', true ); //Delete menu type from the DB deleteListItem( 'delete_menu_type_item', //channel name 'delete_menu_type_item_response', //response event, 'menu_type' //table name ); MENU ADDONS // Insert menu addons ipcMain.on('context_bridge_menu_addons', (_event, args) => { let { id, menu_id, add_on_id, is_active, date_inserted } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO menu_add_on (id, menu_id, add_on_id, is_active, date_inserted) VALUES (?, ?, ?, ?, ?)`, [id, menu_id, add_on_id, is_active, date_inserted], (err: ErrorType) => { err ? mainWindow.webContents.send( 'context_bridge_menu_addons_response', err.message ) : mainWindow.webContents.send( 'context_bridge_menu_addons_response', { status: 'updated', } ); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS menu_add_on ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'menu_id' INT, 'add_on_id' INT, 'is_active' INT, 'date_inserted' DATETIME )` ).run( `INSERT OR REPLACE INTO menu_add_on (menu_id, add_on_id, is_active, date_inserted) VALUES (?, ?, ?, ?)`, [menu_id, add_on_id, is_active, Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send( 'context_bridge_menu_addons_response', err.message ) : mainWindow.webContents.send( 'context_bridge_menu_addons_response', { status: 'inserted', } ); } ); }); db.close(); } }); // Get addons lists as an Array getListItems( 'get_menu_add_on_lists_channel', 'get_menu_add_on_lists_channel_response', 'menu_add_on', 'id, menu_id, add_on_id' ); //Delete menu addons from the DB deleteListItem( 'delete_menu_addons_item', //channel name 'delete_menu_addons_item_response', //response event, 'menu_add_on' //table name ); // Get addons lists in names as an Array getListItems( 'get_addons_name_list', 'get_addons_name_list_response', 'addons', 'add_on_id, add_on_name', true ); ipcMain.on('get_addons_list_for_pos', (_event, args) => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let { status } = args; // let sql = `SELECT ${query} FROM ${table} ${ // condition && 'WHERE is_active = 1' // }`; let sql = `SELECT menu_add_on.menu_id AS food_id, addons.*, addons.price AS total_price FROM addons INNER JOIN menu_add_on ON menu_add_on.add_on_id = addons.add_on_id WHERE addons.is_active = 1`; if (status) { db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('get_addons_list_for_pos_response', rows); }); }); } db.close(); }); // Get food lists as an Array from the DB only [id, product_name] getListItems( 'get_food_name_lists_channel', 'get_food_name_lists_channel_response', 'item_foods', 'id, product_name, product_image', true ); // Get Currency Lists getListItems('get_currency_lists', 'get_currency_lists_response', 'currency'); deleteListItem( 'delete_currency_list_item', //channel name 'delete_currency_list_item_response', //response event, 'currency' //table name ); // const columns insertData( 'insert_currency', //Event Name 'insert_currency_response', //Event response 'currency', //Table name 'currency_name, currency_icon, position, currency_rate' //columns name ); New Customer Name in to POS // Insert New Customer Info ipcMain.on('insert_customer_info', (_event, args: any) => { let { id, customer_name, customer_email, customer_phone, customer_address } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO customer_info (id, customer_name, customer_email, customer_phone, customer_address) VALUES (?, ?, ?, ?, ?)`, [id, customer_name, customer_email, customer_phone, customer_address], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_customer_info_response', err.message ) : mainWindow.webContents.send('insert_customer_info_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS customer_info ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'customer_name' varchar(150), 'customer_email' varchar(100), 'customer_phone' varchar(200), 'customer_address' varchar(250) )` ).run( `INSERT OR REPLACE INTO customer_info (customer_name, customer_email, customer_phone, customer_address) VALUES (?, ?, ?, ?)`, [customer_name, customer_email, customer_phone, customer_address], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_customer_info_response', err.message ) : mainWindow.webContents.send('insert_customer_info_response', { status: 'inserted', }); } ); }); db.close(); } }); Get addons and variants ipcMain.on('get_addons_and_variant', (_event: any, args) => { let food_addon_variants: any = {}; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT addons.add_on_id, addons.add_on_name, addons.price FROM addons INNER JOIN menu_add_on ON menu_add_on.add_on_id = addons.add_on_id INNER JOIN item_foods ON menu_add_on.menu_id = item_foods.id WHERE item_foods.id = ${args} and menu_add_on.is_active = 1`; let sql2 = `SELECT variants.* FROM variants INNER JOIN item_foods ON item_foods.id = variants.food_id WHERE item_foods.id = ${args}`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { food_addon_variants['addons'] = rows; }); db.all(sql2, [], (_err: ErrorType, rows: any) => { food_addon_variants['variants'] = rows; }); }); db.close(); setTimeout(() => { mainWindow.webContents.send( 'get_addons_and_variant_response', food_addon_variants ); }, 1000); }); // Get Customer names as an Array getListItems( 'get_customer_names', 'get_customer_names_response', 'customer_info', 'id, customer_name' ); // Language table created (() => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS language ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'key_words' varchar(255) )` ); }); db.close(); })(); ipcMain.on('get_language', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT language.* FROM language`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('get_language_response', rows); }); }); db.close(); } }); FUNCTIONS DEFINITIONS /** * * * @params string event name * @params string event response * @params string database table name * @params string event name */ function insertData( eventName: any, eventResponse: any, table: any, columns: any ) { ipcMain.on(eventName, (_event, args) => { let { id, currency_name, currency_icon, position, currency_rate } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR REPLACE INTO ${table} (id, currency_name, currency_icon, position, currency_rate) VALUES (?, ?, ?, ?, ?)`, [id, currency_name, currency_icon, position, currency_rate], (err: ErrorType) => { err ? mainWindow.webContents.send(eventResponse, err.message) : mainWindow.webContents.send(eventResponse, { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS ${table} ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'currency_name' varchar(50), 'currency_icon' varchar(50), 'position' INT, 'currency_rate' real )` ).run( `INSERT OR REPLACE INTO ${table} (${columns}) VALUES (?, ?, ?, ?)`, [currency_name, currency_icon, position, currency_rate], (err: ErrorType) => { err ? mainWindow.webContents.send(eventResponse, err.message) : mainWindow.webContents.send(eventResponse, { status: 'inserted', }); } ); }); db.close(); } }); } /** * Delete single item from the database based on the ID * * @params string channel name * @params string event response * @params string database table name * */ function deleteListItem( channel: string, eventResponse: string, table: string ): void { ipcMain.on(channel, (_event, args) => { let { id } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run(`DELETE FROM ${table} WHERE id = ?`, id, (err: ErrorType) => { err ? mainWindow.webContents.send(eventResponse, { status: err, }) : mainWindow.webContents.send(eventResponse, { status: true, }); }); }); db.close(); }); } // Get addons lists in names as an Array function getListItems( channelName: string, response: string, table: string, query: string = '*', condition?: boolean ) { ipcMain.on(channelName, (_event: Electron.IpcMainEvent, args) => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let { status } = args; let sql = `SELECT ${query} FROM ${table} ${ condition && 'WHERE is_active = 1' }`; if (status) { db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send(response, rows); }); }); } db.close(); }); } // Get order data to create token ipcMain.on('get_data_to_create_token', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.all( `SELECT * FROM orders ORDER BY order_id DESC LIMIT 1`, [], (_err: ErrorType, rows: any) => { if (rows) { mainWindow.webContents.send( 'get_data_to_create_token_response', rows[0] ); } } ); }); db.close(); } }); app.on('window-all-closed', () => { // Respect the OSX convention of having the application in memory even // after all windows have been closed if (process.platform !== 'darwin') { app.quit(); } }); app .whenReady() .then(() => { createWindow(); app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) createWindow(); }); }) .catch((err) => console.log(err)); /************************************************ * HRM ***********************************************/ // INSERT DESIGNATION DATA ipcMain.on('insert_employee_designation', (_event, args) => { let { id, designation, designation_details, waiter, chef, manager } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR replace INTO emp_designation (id, designation, designation_details, waiter, chef, manager) VALUES (?, ?, ?, ?, ?, ?)`, [id, designation, designation_details, waiter, chef, manager], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_employee_designation_response', err.message ) : mainWindow.webContents.send( 'insert_employee_designation_response', { status: 'updated', } ); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS emp_designation ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'designation' varchar(150), 'designation_details' varchar(100), 'waiter' INT, 'chef' INT, 'manager' INT )` ).run( `INSERT OR REPLACE INTO emp_designation (designation, designation_details, waiter, chef, manager) VALUES (?, ?, ?, ?, ?)`, [designation, designation_details, waiter, chef, manager], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_employee_designation_response', err.message ) : mainWindow.webContents.send( 'insert_employee_designation_response', { status: 'inserted', } ); } ); }); db.close(); } }); getListItems( 'get_employee_designation', 'get_employee_designation_response', 'emp_designation' ); deleteListItem( 'delete_employee_designation', 'delete_employee_designation_response', 'emp_designation' ); /********************* * DEPARTMENT ********************/ // INSERT DEPARTMENT DATA ipcMain.on('insert_department', (_event, args) => { let { id, department_name } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR replace INTO department (id, department_name) VALUES (?, ?)`, [id, department_name], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_department_response', err.message ) : mainWindow.webContents.send('insert_department_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS department ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'department_name' varchar(150) )` ).run( `INSERT OR REPLACE INTO department (department_name) VALUES (?)`, [department_name], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_department_response', err.message ) : mainWindow.webContents.send('insert_department_response', { status: 'inserted', }); } ); }); db.close(); } }); // Fetch department data getListItems('fetch_department', 'fetch_department_response', 'department'); deleteListItem('delete_department', 'delete_department_response', 'department'); /********************* * SUB DEPARTMENT ********************/ // INSERT SUB DEPARTMENT DATA ipcMain.on('insert_sub_department', (_event, args) => { let { id, sub_department_name, department_id } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR replace INTO sub_department (id, sub_department_name, department_id) VALUES (?, ?, ?)`, [id, sub_department_name, department_id], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_sub_department_response', err.message ) : mainWindow.webContents.send('insert_sub_department_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS sub_department ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'sub_department_name' varchar(150), 'department_id' INT )` ).run( `INSERT OR REPLACE INTO sub_department (sub_department_name, department_id) VALUES (?, ?)`, [sub_department_name, department_id], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_sub_department_response', err.message ) : mainWindow.webContents.send('insert_sub_department_response', { status: 'inserted', }); } ); }); db.close(); } }); getListItems( 'fetch_sub_department', 'fetch_sub_department_response', 'sub_department' ); deleteListItem( 'delete_sub_department', 'delete_sub_department_response', 'sub_department' ); // INSERT SALARY ADVANCE DATA ipcMain.on('insert_salary_advance', (_event, args) => { let { id, employee_id, req_amount, release_amount, salary_month } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `INSERT OR replace INTO salary_advance (id, employee_id, req_amount, release_amount, salary_month) VALUES (?, ?, ?, ?, ?)`, [id, employee_id, req_amount, release_amount, salary_month], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_salary_advance_response', err.message ) : mainWindow.webContents.send('insert_salary_advance_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS salary_advance ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'employee_id' INT NOT NULL, 'req_amount' INT, 'release_amount' INT DEFAULT 0, 'salary_month' TEXT, 'created_at' DATETIME )` ).run( `INSERT OR REPLACE INTO salary_advance (employee_id, req_amount, release_amount, salary_month, created_at) VALUES (?, ?, ?, ?, ?)`, [employee_id, req_amount, release_amount, salary_month, Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_salary_advance_response', err.message ) : mainWindow.webContents.send('insert_salary_advance_response', { status: 'inserted', }); } ); }); db.close(); } }); ipcMain.on('send_status_to_create_table', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS emp_attendance_time ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "attendance_time" VARCHAR(100) )` ) .run( `CREATE TABLE IF NOT EXISTS emp_types ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "emp_type" VARCHAR(100) )` ) .run( `CREATE TABLE IF NOT EXISTS emp_pay_frequency ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "frequency" VARCHAR(100) )` ) .run( `CREATE TABLE IF NOT EXISTS emp_duty_types ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "duty_type" VARCHAR(100) )` ) .run( `CREATE TABLE IF NOT EXISTS emp_rate_types ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "rate_type" VARCHAR(100) )` ) .all(`SELECT * FROM emp_types`, [], (_err: ErrorType, rows: any) => { if (!rows.length) { db.run( `INSERT INTO emp_attendance_time(attendance_time) VALUES("Attendance Time (15:30 - 20:30)"),("Attendance Time (15:30 - 20:30)")` ) .run( `INSERT INTO emp_types(emp_type) VALUES("Full Time"),("Part Time")` ) .run( `INSERT INTO emp_pay_frequency(frequency) VALUES("Weekly"),("Monthly"),("Annual")` ) .run( `INSERT INTO emp_duty_types(duty_type) VALUES("Full Time"),("Part Time"),("Contractual")` ) .run( `INSERT INTO emp_rate_types(rate_type) VALUES("Hourly"),("Monthly")` ); db.close(); } else { db.close(); } }); }); } }); // INSERT EMPLOYEE ipcMain.on('insert_employee', (_event: Electron.IpcMainEvent, args: any) => { let { first_name, last_name, email, phone, country, state, city, zip_code, attendance_time, employee_type, account_number, bank_name, bban_number, branch_name, division, hire_date, pay_frequency_text, home_department, termination_date, termination_reason, designation, original_hire_date, voluntary_termination, pay_frequency, hourly_rate2, department_text, duty_type, re_hire_date, rate_type, rate, hourly_rate3, benefit_class_code, benefit_accrual_date, benefit_description, benefit_status, supervisor_name, supervisor_report, is_supervisor, date_of_birth, eeo_class, work_in_state, gender, ethnic_group, live_in_state, marital_status, ssn, citizenship, pp_image, home_email, home_phone, cell_phone, business_email, business_phone, emergency_contact, emergency_work_phone, alter_emergency_contact, alt_emergency_work_phone, emergency_home_phone, emergency_contact_relation, alt_emergency_home_phone, custom_field_name, custom_value, custom_field_type, basic_salary, house_rent, medical, others_allowance, gross_salary, tranport_allowance, } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS employees ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'first_name' VARCHAR(255) NOT NULL, 'last_name' VARCHAR(255) DEFAULT NULL, 'email' VARCHAR(255) NOT NULL, 'phone' VARCHAR(50) NOT NULL, 'country' INT, 'state' INT, 'city' VARCHAR(255), 'zip_code' INT, 'attendance_time' INT, 'employee_type' INT, 'account_number' INT NOT NULL, 'bank_name' VARCHAR(255) NOT NULL, 'bban_number' VARCHAR(255) NOT NULL, 'branch_name' VARCHAR(255) NOT NULL, 'division' INT NOT NULL, 'hire_date' INT, 'pay_frequency_text' VARCHAR(255) NOT NULL, 'home_department' VARCHAR(255) NOT NULL, 'termination_date' INT, 'termination_reason' TEXT NOT NULL, 'designation' INT NOT NULL, 'original_hire_date' INT, 'voluntary_termination' INT NOT NULL, 'pay_frequency' INT NOT NULL, 'hourly_rate2' REAL NOT NULL, 'department_text' VARCHAR(255) NOT NULL, 'duty_type' INT NOT NULL, 're_hire_date' INT, 'rate_type' INT NOT NULL, 'rate' REAL NOT NULL, 'hourly_rate3' INT NOT NULL, 'benefit_class_code' VARCHAR(255), 'benefit_accrual_date' INT, 'benefit_description' TEXT, 'benefit_status' INT, 'supervisor_name' INT, 'supervisor_report' VARCHAR(255), 'is_supervisor' INT, 'date_of_birth' INT NOT NULL, 'eeo_class' VARCHAR(255), 'work_in_state' VARCHAR(255), 'gender' VARCHAR(50) NOT NULL, 'ethnic_group' VARCHAR(255), 'live_in_state' VARCHAR(255), 'marital_status' VARCHAR(100), 'ssn' VARCHAR(255), 'citizenship' VARCHAR(255), 'pp_image' VARCHAR(255), 'home_email' VARCHAR(255), 'home_phone' VARCHAR(50), 'cell_phone' VARCHAR(50), 'business_email' VARCHAR(255), 'business_phone' VARCHAR(50), 'emergency_contact' VARCHAR(50), 'emergency_work_phone' VARCHAR(50), 'alter_emergency_contact' VARCHAR(50), 'alt_emergency_work_phone' VARCHAR(50), 'emergency_home_phone' VARCHAR(50), 'emergency_contact_relation' VARCHAR(50), 'alt_emergency_home_phone' VARCHAR(50), 'custom_field_name' VARCHAR(255), 'custom_value' VARCHAR(255), 'custom_field_type' VARCHAR(255) )` ) .run( `CREATE TABLE IF NOT EXISTS employees_salary ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'basic_salary' REAL, 'house_rent' REAL, 'medical' REAL, 'others_allowance' REAL, 'gross_salary' REAL NOT NULL, 'tranport_allowance' REAL )` ) .run( `INSERT INTO employees ( first_name, last_name, email, phone, country, state, city, zip_code, attendance_time, employee_type, account_number, bank_name, bban_number, branch_name, division, hire_date, pay_frequency_text, home_department, termination_date, termination_reason, designation, original_hire_date, voluntary_termination, pay_frequency, hourly_rate2, department_text, duty_type, re_hire_date, rate_type, rate, hourly_rate3, benefit_class_code, benefit_accrual_date, benefit_description, benefit_status, supervisor_name, supervisor_report, is_supervisor, date_of_birth, eeo_class, work_in_state, gender, ethnic_group, live_in_state, marital_status, ssn, citizenship, pp_image, home_email, home_phone, cell_phone, business_email, business_phone, emergency_contact, emergency_work_phone, alter_emergency_contact, alt_emergency_work_phone, emergency_home_phone, emergency_contact_relation, alt_emergency_home_phone, custom_field_name, custom_value, custom_field_type ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, [ first_name, last_name ? last_name : null, email, phone, country ? country : null, state ? state : null, city ? city : null, zip_code ? zip_code : null, attendance_time ? attendance_time : null, employee_type ? employee_type : null, account_number, bank_name, bban_number, branch_name, division, hire_date ? hire_date : null, pay_frequency_text, home_department, termination_date ? termination_date : null, termination_reason, designation, original_hire_date ? original_hire_date : null, voluntary_termination, pay_frequency, hourly_rate2, department_text, duty_type, re_hire_date ? re_hire_date : null, rate_type, rate, hourly_rate3, benefit_class_code ? benefit_class_code : null, benefit_accrual_date ? benefit_accrual_date : null, benefit_description ? benefit_description : null, benefit_status ? benefit_status : null, supervisor_name ? supervisor_name : null, supervisor_report ? supervisor_report : null, is_supervisor ? is_supervisor : null, date_of_birth, eeo_class ? eeo_class : null, work_in_state, gender, ethnic_group ? ethnic_group : null, live_in_state ? live_in_state : null, marital_status ? marital_status : null, ssn ? ssn : null, citizenship ? citizenship : null, pp_image ? pp_image : null, home_email ? home_email : null, home_phone ? home_phone : null, cell_phone, business_email ? business_email : null, business_phone ? business_phone : null, emergency_contact, emergency_work_phone, alter_emergency_contact ? emergency_contact : null, alt_emergency_work_phone ? alt_emergency_work_phone : null, emergency_home_phone, emergency_contact_relation ? emergency_contact_relation : null, alt_emergency_home_phone ? alt_emergency_home_phone : null, custom_field_name ? custom_field_name : null, custom_value ? custom_value : null, custom_field_type ? custom_field_type : null, ], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_employee_response', err.message ) : mainWindow.webContents.send('insert_employee_response', { status: 'inserted', }); } ) .run( `INSERT INTO employees_salary (basic_salary, house_rent, medical, others_allowance, gross_salary, tranport_allowance) VALUES (?,?,?,?,?,?)`, [ basic_salary ? basic_salary : null, house_rent ? house_rent : null, medical ? medical : null, others_allowance ? others_allowance : null, gross_salary ? gross_salary : null, tranport_allowance ? tranport_allowance : null, ] ); }); db.close(); }); // TODO: JOINING QUERY getListItems( 'fetch_salary_advance', 'fetch_salary_advance_response', 'salary_advance' ); deleteListItem( 'delete_salary_advance', 'delete_salary_advance_response', 'salary_advance' ); // INSERT FLOOR ipcMain.on('insert_floor', (_event, args) => { let { id, floorName } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `UPDATE floor SET floorName = ? WHERE id = ?`, [floorName, id], (err: ErrorType) => { err ? mainWindow.webContents.send('insert_floor_response', err.message) : mainWindow.webContents.send('insert_floor_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS floor ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'floorName' varchar(15) NOT NULL, 'created_at' DATETIME )` ).run( `INSERT OR REPLACE INTO floor (floorName, created_at) VALUES (?, ?)`, [floorName, Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send('insert_floor_response', err.message) : mainWindow.webContents.send('insert_floor_response', { status: 'inserted', }); } ); }); db.close(); } }); getListItems('fetch_floor', 'fetch_floor_response', 'floor', 'id, floorName'); deleteListItem('delete_floor', 'delete_floor_response', 'floor'); // INSERT TABLE DATA ipcMain.on('insert_customer_table', (_event, args) => { let { id, tablename, person_capacity, table_icon, floorId, status } = args; // Execute if the event has row ID / data ID. It is used to update a specific item if (args.id !== undefined) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `UPDATE customer_table SET tablename = ?, person_capacity = ?, table_icon = ?, floorId = ? WHERE id = ?`, [tablename, person_capacity, table_icon, floorId, id], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_customer_table_response', err.message ) : mainWindow.webContents.send('insert_customer_table_response', { status: 'updated', }); } ); }); db.close(); } else { // Execute if it is new, then insert it let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS customer_table ( 'id' INTEGER PRIMARY KEY AUTOINCREMENT, 'tablename' varchar(50) NOT NULL, 'person_capacity' INT NOT NULL, 'table_icon' TEXT, 'floorId' INT, 'status' INT NOT NULL, 'created_at' INT )` ).run( `INSERT OR REPLACE INTO customer_table (tablename, person_capacity, table_icon, floorId, status, created_at) VALUES (?, ?, ?, ?, ?, ?)`, [tablename, person_capacity, table_icon, floorId, status, Date.now()], (err: ErrorType) => { err ? mainWindow.webContents.send( 'insert_customer_table_response', err.message ) : mainWindow.webContents.send('insert_customer_table_response', { status: 'inserted', }); } ); }); db.close(); } }); // Get waiter Name ipcMain.on('get_waiter_names', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT employees.id, employees.first_name, employees.last_name from employees WHERE employees.designation = (SELECT id FROM emp_designation WHERE waiter = 1)`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('get_waiter_names_response', rows); }); }); } }); ipcMain.on('fetch_customer_table', (_event: Electron.IpcMainEvent, args) => { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let { status } = args; let sql = `SELECT customer_table.id, customer_table.tablename, customer_table.person_capacity, customer_table.table_icon, customer_table.floorId, customer_table.status, floor.floorName FROM customer_table INNER JOIN floor ON customer_table.floorId = floor.id`; if (status) { db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send('fetch_customer_table_response', rows); }); }); } db.close(); }); deleteListItem( 'delete_customer_table', 'delete_customer_table_response', 'customer_table' ); // CREATE TABLE WHEN THE APP IS INSTALLED ipcMain.on('create_customer_type', (_event, args) => { if (args.status) { let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); db.serialize(() => { db.run( `CREATE TABLE IF NOT EXISTS customer_type ( "id" INTEGER PRIMARY KEY AUTOINCREMENT, "customertype" VARCHAR(100) )` ).all(`SELECT * FROM customer_type`, [], (_err: ErrorType, rows: any) => { if (!rows.length) { db.run( `INSERT INTO customer_type(customertype) VALUES ("Walk In"), ("Online Customer"), ("Third Party"), ("Take Away")` ); db.close(); } else { db.all( `SELECT * FROM customer_type`, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send( 'create_customer_type_response', rows ); } ); db.close(); } }); }); } }); // FETCH FLOOR & TABLE INFO ipcMain.on( 'fetch_table_based_on_floor_id', (_event: Electron.IpcMainEvent, args) => { const { floorId } = args; let db = new sqlite3.Database(`${dbPath}/restora-pos.db`); let sql = `SELECT customer_table.id, customer_table.tablename, customer_table.person_capacity, customer_table.status, customer_table.floorId FROM customer_table WHERE floorId = ${floorId}`; db.serialize(() => { db.all(sql, [], (_err: ErrorType, rows: any) => { mainWindow.webContents.send( 'fetch_table_based_on_floor_id_response', rows ); }); }); db.close(); } );
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:househarbor/screens/campaings.dart'; import 'package:househarbor/screens/contacts-screen.dart'; import 'package:househarbor/screens/home-screen.dart'; import 'package:househarbor/screens/profile-screen.dart'; class TipsScreen extends StatefulWidget { const TipsScreen({Key? key}); @override State<TipsScreen> createState() => _TipsScreenState(); } class _TipsScreenState extends State<TipsScreen> { int _currentIndex = 2; // Initialize the current index void _onNavBarItemTapped(BuildContext context, int index) { // Handle navigation based on the selected index if (index == 0) { // Handle Telegram icon tap Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => CampaingScreen(), // Replace with your home screen widget )); } else if (index == 1) { // Handle Bulb icon tap Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => TipsScreen(), // Replace with your home screen widget )); } else if (index == 2) { // Handle Home icon tap Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => HomeScreen(), // Replace with your home screen widget )); } else if (index == 3) { // Handle Profile icon tap Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => ContactScreen(), // Replace with your profile screen widget )); } else if (index == 4) { // Handle Calendar icon tap } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xFF151515), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( padding: EdgeInsets.fromLTRB(16, 44, 16, 0), // Added top padding child: Row( mainAxisAlignment: MainAxisAlignment.end, // Align to the right children: [ // Notification icon (Right-aligned with right padding) Padding( padding: EdgeInsets.only(right: 16), child: Icon( Icons.notifications, size: 30, color: Color(0xffB1BDBD), ), ), // Profile circle as a button (Right-aligned) InkWell( onTap: () { // Handle the profile circle button click here Navigator.push(context, MaterialPageRoute(builder: (context) { return ProfileScreen(); // Replace with your account settings screen })); }, child: CircleAvatar( radius: 30, backgroundImage: AssetImage( 'assets/images/Profile.png'), // Add your image URL ), ), ], ), ), Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( padding: EdgeInsets.fromLTRB( 16, 84, 16, 40), // Added top padding and left padding child: Row( mainAxisAlignment: MainAxisAlignment.start, // Center-align the row children: [ // Back icon (Left-aligned) Padding( padding: const EdgeInsets.fromLTRB(0, 0, 70, 0), child: InkWell( onTap: () { // Handle the back button click here Navigator.pop(context); }, child: Icon( Icons.arrow_back_ios, size: 30, color: Color(0xffB1BDBD), ), ), ), SizedBox( width: 30), // Add spacing between back icon and profile text // Profile text with left padding Padding( padding: const EdgeInsets.fromLTRB( 0, 0, 60, 0), // Add left padding child: Text( 'TIPS', style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: Color(0xffB1BDBD), fontFamily: 'Arial', ), ), ), ], ), ), ], ), ), Expanded( child: SingleChildScrollView( child: Container( // Container for the topic and paragraphs padding: EdgeInsets.all(16), margin: EdgeInsets.fromLTRB(20, 0, 20, 0), // Padding on all sides color: Color.fromARGB(216, 49, 179, 86), // Yellow background color child: Column( crossAxisAlignment: CrossAxisAlignment.start, // Align left children: [ Text( 'Tips', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), // List of 10 topics and paragraphs Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Segment Your Audience ', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( 'Divide your email list into smaller segments based on factors like demographics, purchase history, or engagement level. This allows you to send more targeted and relevant content to each group.', style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), Text( 'Compelling Subject Lines', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( 'Craft subject lines that are attention-grabbing, concise, and relevant to the content of the email. Avoid clickbait and overly salesy language.', style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), Text( 'Engaging Content ', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( 'Provide valuable content that resonates with your audience. This could include informative articles, how-to guides, videos, or special offers.', style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), Text( 'Visual Appeal', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( "Use images and visuals that complement your message but don't overdo it. Balance text and visuals for better readability.", style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), Text( 'Frequency and Consistency', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( "Find the right balance between sending enough emails to stay on your audience's radar without overwhelming them. Consistency in your sending schedule helps build anticipation.", style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), Text( 'Engagement-Based Send Times', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( 'Experiment with sending emails at different times to see when your audience is most engaged. This can vary depending on your target demographic.', style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), Text( 'Stay GDPR Compliant', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), SizedBox(height: 10), Text( "If you're sending emails to recipients in the European Union, ensure that you're following GDPR regulations regarding data privacy and consent.", style: TextStyle( fontSize: 14, ), ), SizedBox(height: 20), ], ), ], ), ), ), ), ], ), bottomNavigationBar: Container( width: double.infinity, // Set the width to your desired value // height: 105, padding: EdgeInsets.fromLTRB(16, 15, 16, 20), // Add padding as needed decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(0)), // Add border radius color: Color(0xFF151515), // Background color of the container ), child: ClipRRect( borderRadius: BorderRadius.vertical( top: Radius.circular(10), bottom: Radius.circular(10), ), child: BottomNavigationBar( type: BottomNavigationBarType.fixed, backgroundColor: Color(0xFF316868), currentIndex: _currentIndex, onTap: (index) { setState(() { _currentIndex = index; }); _onNavBarItemTapped(context, index); }, iconSize: 32, unselectedItemColor: Colors.white, // Change unselected icon color to white selectedItemColor: Colors.yellow, // Change selected icon color to yellow items: [ BottomNavigationBarItem( icon: Padding( padding: EdgeInsets.only(top: 10), child: Icon(Icons.campaign_outlined), ), label: '', ), BottomNavigationBarItem( icon: Padding( padding: EdgeInsets.only(top: 10), child: Icon(Icons.lightbulb_outline), ), label: '', ), BottomNavigationBarItem( icon: Padding( padding: EdgeInsets.only(top: 10), child: Icon(Icons.home), ), label: '', ), BottomNavigationBarItem( icon: Padding( padding: EdgeInsets.only(top: 10), child: Icon(Icons.person_2_outlined), ), label: '', ), BottomNavigationBarItem( icon: Padding( padding: EdgeInsets.only(top: 10), child: Icon(Icons.calendar_today_outlined), ), label: '', ), ], ), ), ), ); } }
<?php namespace App\Http\Controllers; use App\Http\Requests\BookRequest; use App\Models\Book; use App\Traits\OfferTrait; use Illuminate\Http\Request; class BookController extends Controller { use OfferTrait; /** * Display a listing of the resource. */ public function index() { $books = Book::orderBy('id','DESC')->get(); return view('books.books', compact('books')); } public function show($id) { $book = Book::find($id); return view('books.show', compact('book')); } /** * Store a newly created resource in storage. */ public function addBook(BookRequest $request) { $file_name = $this->saveImage($request->file, 'uploads/books'); $img_name = $this->saveImage($request->img, 'uploads/books'); Book::create([ 'title' => $request->title, 'auther' => $request->auther, 'page_count' => $request->page_count, 'size' => $request->size, 'file' => $file_name, 'img' => $img_name, 'lang' => $request->lang ]); return response()->json([ 'status' => 'success', ]); } public function updateBook(Request $request) { // $file_name = $this->saveImage($request->update_file, 'uploads/books'); Book::where('id', $request->update_id)->update([ 'title' => $request->update_title, 'auther' => $request->update_auther, 'page_count' => $request->update_page_count, 'size' => $request->update_size, 'lang' => $request->update_lang, // 'file' => $request-> $file_name ]); return response()->json([ 'status' => 'success', ]); } /** * Remove the specified resource from storage. */ public function deleteBook(Request $request) { Book::find($request->book_id)->delete(); return response()->json([ 'status' => 'success', ]); } public function search(Request $request) { $keyword = $request->keyword; $books = Book::where('title', 'like', "%$keyword%")->get(); return response()->json($books); } }
import NextImage from 'next/image' import { Callout } from '@theguild/components' import cdnTokenImage from '../../../../public/docs/pages/guides/cdn_token.png' import tokenImage from '../../../../public/docs/pages/guides/token.png' import newTargetFormImage from '../../../../public/docs/pages/management/new-target-form.png' import tagetConditionalBreakingChangesImage from '../../../../public/docs/pages/management/target-conditional-breaking-changes.png' import tokenCreateSuccess from '../../../../public/docs/pages/management/target-created-token.png' # Target Management Within a Hive **project**, you can create **targets** (which are equivalent to runtime environments) and manage different schemas across different contextual runtimes. When it comes to the GraphQL schema, every target is considered standalone, and can have different states of the same schema, within the same GraphQL API project (just like different runtime environments). When a new Hive **project** is created, default targets are created (`development`, `staging` and `production`). You can create more targets if needed, or remove the default ones if they are not in use. ## Create a new target From your Hive **project** page, you can see the list of targets created under the project. You can also use the **New Target** button to create a new target. <NextImage alt="Create Target Form" src={newTargetFormImage} className="mt-10 max-w-xl drop-shadow-md" /> ## Manage existing target ### Conditional Breaking Changes Conditional Breaking Changes is a concept that involves marking breaking changes in your GraphQL schemas as safe, based on real-life data and traffic reported to Hive. This is done through the [Usage Reporting](/docs/features/usage-reporting) feature. When a new schema of your GraphQL schema is published to the registry, Hive uses the data collected from your API gateway to identify whether the change in your schema actually affects consumers. <NextImage alt="Conditional Breaking Changes" src={tagetConditionalBreakingChangesImage} className="mt-10 max-w-3xl drop-shadow-md" /> Under your target's **Settings** page, you can enable the **Conditional Breaking Changes** feature and configure the following settings: #### Traffic Threshold and Duration You can choose to mark a breaking change as safe, if it affects some percentage of your traffic, in a specific time range. Here are a few examples and their meaning: - **Traffic Threshold:** `0%`: A breaking change is considered as breaking and dangerous if the field was was used at least once. - **Traffic Threshold:** `10%`: A breaking change is considered as breaking and dangerous if the field was requested by more than 10% of all GraphQL operation. <Callout type="info"> The maximum duration is defined by the retention of your [Hive plan](/docs/management/organizations#subscription-and-billing). </Callout> #### Client Exclusions Real-life data and traffic is collected from your API gateway can be annotated with specific **Client**. In most cases, the **Client** matches a specific `User-Agent` and reported through the Hive agent. You can read more about this in the [Usage Reporting](/docs/features/usage-reporting) page. You many choose to exclude specific clients from the **Conditional Breaking Changes** if you wish to have more control over the process. #### Cross-target Checks When a new schema is published to the registry, Hive checks the usage of the field in the current target. However, you may choose to also check the usage of the field in other targets. This is useful if you wish to use the `production` target as a reference for the usage of the field, while checking the schemas of other targets, like `staging` or `development`. ### Schema Extensions Hive allow you to have a pre-defined GraphQL schema that is automatically merged with your published schemas, before being checked and validated. This feature is useful with some frameworks that defines internal GraphQL schemas, and doesn't include it while exporting the schema to a file. #### Schema Stitching Directives If you are using [Schema Stitching Directives](https://the-guild.dev/graphql/stitching/docs/approaches/stitching-directives), you probably want to the core directives as schema extensions, and avoid pushing it through every service. You can find the complete definition of the [Stitching Directives SDL in the documentation](https://the-guild.dev/graphql/stitching/docs/approaches/stitching-directives#directives-glossary) #### AWS AppSync/Amplify If you are using [AWS AppSync](https://aws.amazon.com/appsync/) [AWS Amplify](https://docs.amplify.aws/), you are probably familiar with the [GraphQL directives (`@aws_subscribe`, `@aws_auth`, etc.)](https://docs.amplify.aws/cli-legacy/graphql-transformer/directives/) that are used to define the GraphQL schema or models. While building your GraphQL schema within the AWS AppSync console, you don't need to define those directives. However, when you try to publish your schema to Hive, you will notice that those directives are missing, and schema is marked with errors. You can use the **Schema Extensions** feature to define a pre-defined schema that is automatically merged with your published schemas, before being checked and validated. [You can find here the directive and scalar SDL needed for AWS AppSync](https://github.com/kamilkisiela/graphql-inspector/blob/d0efec031b64aae94818d749b697e73276f0f239/packages/loaders/loaders/src/index.ts#L57-L82) ### Rename a target You can easily change the name of your targets in Hive by adjusting the settings of your target. To do this, go to the **Settings** tab of your target, and use the **Target Name** form to rename your target. <Callout type="warning"> Changing the name of your target will also change the slug of your target URL, and will invalidate any existing links to your target. </Callout> ### Delete a target As the owner of an organization, you have the option to delete a target, including all targets, settings and all data collected during your use of Hive. To delete an target, go to the **Settings** tab of your target, and use the **Delete Target** section. <Callout type="warning">This action is not reversible!</Callout> ## Manage Tokens Under a target's **Settings** page, you can manage two different types of tokens: ### Registry Access Tokens **Registry Access Tokens** are used to access to Hive Registry and perform actions on your targets/projects. In most cases, this token is used from the Hive CLI. Under the **Registry Access Tokens** section, click the **Generate new token** button. Give your access token a either select a predefined preset for your token (under **Simple** view), or create a token with custom permissions (under **Advanced** view). <NextImage alt="Create Registry Token Form" src={tokenImage} className="mt-10 max-w-md drop-shadow-md" /> Click on **Generate Token** button and you should get your CLI token created, with permissions to publish GraphQL schemas. <NextImage alt="Created Token" src={tokenCreateSuccess} className="mt-10 max-w-xl drop-shadow-md" /> Make sure to copy your token and keep it safe. **You won't be able to see it again.** <Callout type="info"> **Note:** You can create multiple tokens with different permissions for different use cases. </Callout> ### CDN Access Tokens #### Creating a CDN Access Token The Hive Cloud service leverages the [CloudFlare Global Network](https://www.cloudflare.com/network/) to deliver your GraphQL schema and schema metadata. This means that your schema will be available from the nearest location to your GraphQL gateway, with 100% uptime, regardless of Hive's status. This ensures that everything required for your GraphQL API is always available, and reduces the risk of depending on Hive as a single point of failure. [You can read more about Hive's CDN here](/docs/features/high-availability-cdn). Managing your **CDN Access Token** is located under your target's **Settings** page. Click on **Create new CDN Token** to create a new CDN token. Describe your token with an alias, and click **Create**. In most cases, CDN Access Tokens are used directly from other tools, like a gateway, so please store this access token securely. **You will not be able to see it again.** <Callout type="info"> **Why are Registry and CDN tokens different?** We use a separate, externally managed storage to manage CDN tokens to ensure high availability of your schemas. This approach ensures that your GraphQL schemas are fully secured and highly available. CDN tokens are read-only and can only fetch schemas from the CDN. They do not have permissions to perform any other action on your Hive organization. </Callout> #### Revoking a CDN Access Token In case of a security breach, you can revoke a CDN Access Token by clicking on the **Revoke** button in the list of CDN tokens. <Callout type="info"> Revoking CDN access token can take up to 5 minutes to update across the CDN network. </Callout>
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const Sentry = __importStar(require("@sentry/node")); const sequelize_1 = require("sequelize"); const Setting_1 = __importDefault(require("../../models/Setting")); const Ticket_1 = __importDefault(require("../../models/Ticket")); const Contact_1 = __importDefault(require("../../models/Contact")); const logger_1 = require("../../utils/logger"); const socket_1 = require("../../libs/socket"); const CreateOrUpdateBaileysService_1 = __importDefault(require("../BaileysServices/CreateOrUpdateBaileysService")); const CreateMessageService_1 = __importDefault(require("../MessageServices/CreateMessageService")); const wbotMonitor = async (wbot, whatsapp, companyId) => { const io = (0, socket_1.getIO)(); const sessionName = whatsapp.name; try { wbot.ws.on("CB:call", async (node) => { const content = node.content[0]; if (content.tag === "offer") { const { from, id } = node.attrs; console.log(`${from} is calling you with id ${id}`); } if (content.tag === "terminate") { const sendMsgCall = await Setting_1.default.findOne({ where: { key: "acceptCallWhatsapp", companyId: companyId } }); if (sendMsgCall?.value === "enabled") { await wbot.sendMessage(node.attrs.from, { text: "*Asistente Virtual:*\nAs chamadas de voz e vídeo estão desativadas para este WhatsApp, envie uma mensagem de texto..\n\nObrigado(a)!" }); const number = node.attrs.from.replace(/\D/g, ""); const contact = await Contact_1.default.findOne({ where: { number, companyId } }); const ticket = await Ticket_1.default.findOne({ where: { contactId: contact.id, whatsappId: wbot.id, status: { [sequelize_1.Op.or]: ["open", "pending"] }, companyId: companyId } }); // se não existir o ticket não faz nada. if (!ticket) return; const date = new Date(); const hours = date.getHours(); const minutes = date.getMinutes(); const body = `Chamada de voz/video perdida às ${hours}:${minutes}`; const messageData = { id: content.attrs["call-id"], ticketId: ticket.id, contactId: contact.id, body, fromMe: false, mediaType: "call_log", read: true, quotedMsgId: null, ack: 1 }; await ticket.update({ lastMessage: body }); return (0, CreateMessageService_1.default)({ messageData, companyId }); } } }); wbot.ev.on("contacts.upsert", async (contacts) => { console.log("upsert", contacts); await (0, CreateOrUpdateBaileysService_1.default)({ whatsappId: whatsapp.id, contacts }); }); // USO FUTURO // wbot.ev.on("messages.upsert", async () => { // const showStatus = await Setting.findOne({ // where: { key: "showOnline" } // }); // if (showStatus.value === "disabled") { // await wbot.sendPresenceUpdate('unavailable'); // } else { // await wbot.sendPresenceUpdate('available'); // } // }); } catch (err) { Sentry.captureException(err); logger_1.logger.error(err); } }; exports.default = wbotMonitor;
from collections import deque class HopcroftKarp: def __init__(self, graph): self.graph = graph self.pair_u = {} self.pair_v = {} self.dist = {} self.matching = 0 def bfs(self): queue = deque() for u in self.graph.keys(): if u not in self.pair_u: self.dist[u] = 0 queue.append(u) else: self.dist[u] = float('inf') self.dist[None] = float('inf') while queue: u = queue.popleft() if self.dist[u] < self.dist[None]: for v in self.graph[u]: if self.dist.get(self.pair_v.get(v), float('inf')) == float('inf'): self.dist[self.pair_v.get(v)] = self.dist[u] + 1 queue.append(self.pair_v.get(v)) return self.dist[None] != float('inf') def dfs(self, u): if u is not None: for v in self.graph[u]: if self.dist.get(self.pair_v.get(v)) == self.dist[u] + 1: if self.dfs(self.pair_v.get(v)): self.pair_v[v] = u self.pair_u[u] = v return True self.dist[u] = float('inf') return False return True def max_matching(self): while self.bfs(): for u in self.graph.keys(): if u not in self.pair_u: if self.dfs(u): self.matching += 1 return self.matching if __name__ == "__main__": graph = { 'A': ['1', '2'], 'B': ['1'], 'C': ['2', '3'], 'D': ['3'] } hk = HopcroftKarp(graph) max_matching = hk.max_matching() print("Tamanho do emparelhamento máximo:", max_matching) print("Emparelhamento máximo:", hk.pair_u)
--- import { Image } from "astro:assets"; import Dialog from "./Dialog.astro"; import { getEntry } from "astro:content"; import ListItem from "./ListItem.astro"; import List from "./List.astro"; import Subtitle from "./Subtitle.astro"; const { slug, title, description, cover } = Astro.props; const [folder, product] = slug.split("_"); const markdown: any = await getEntry(folder, product); const { Content } = await markdown.render(); --- <li id='additive-item' data-slug={slug} class='relative rounded-lg shadow-lg bg-white overflow-hidden z-20' > <div class='group aspect-h-7 aspect-w-10 block w-full h-56 bg-gray-100'> { cover && ( <Image src={cover} alt={title} width='1080' height='720' class='pointer-events-none object-cover w-full h-full transition-all group-hover:scale-105' /> ) } <button type='button' class='absolute inset-0 focus:outline-none'> <span class='sr-only'>View details for {title}</span> </button> </div> <div class='px-4 py-2'> <p class='pointer-events-none mt-2 truncate text-lg font-medium text-gray-900' > {title} </p> <p class='pointer-events-none text-sm font-regular text-gray-500 line-clamp-2' > {description} </p> </div> <Dialog id={slug}> <Content components={{ li: ListItem, ul: List, h3: Subtitle }} /> </Dialog> </li>
import { Injectable, Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Coffee } from './coffee.entity'; import { COFFEE_BRANDS, COFFEE_BRANDS_FACTORY } from './coffees.contants'; import { CoffeesController } from './coffees.controller'; import { CoffeesService } from './coffees.service'; import { Flavor } from './entities/flavor.entity/flavor.entity'; class ConfigSercive {} class DevelopmentConfigService {} class ProductionConfigService {} @Injectable() export class CoffeeBrandsFactory { create() { return ['buddy brew-f', 'nescafe-f']; } } @Module({ imports: [TypeOrmModule.forFeature([Coffee, Flavor, Event])], controllers: [CoffeesController], //controller本身也是Provider providers: [ CoffeesService, CoffeeBrandsFactory, { provide: ConfigSercive, useClass: process.env.Node_ENV === 'development' ? DevelopmentConfigService : ProductionConfigService, }, { provide: COFFEE_BRANDS, useValue: ['buddy brew', 'nescafe'], }, { provide: COFFEE_BRANDS_FACTORY, useFactory: (brandsfactory: CoffeeBrandsFactory) => brandsfactory.create(), inject: [CoffeeBrandsFactory], }, ], //注册provider exports: [CoffeesService], }) export class CoffeesModule {}
import "../css/admin/section.css"; import "../css/admin/reviewManage.css"; import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { LOAD_REVIEWS_REQUEST } from "../reducers/review"; import { DELETE_REVIEW_REQUEST } from "../reducers/admin"; import AdminModal from "./adminModal"; import AddReviewModal from "./addReviewModal"; const ReviewManage = () => { const dispatch = useDispatch(); const [openModal, setOpenModal] = useState(false); const [modalMsg, setModalMsg] = useState(""); const [openAddModal, setOpenAddModal] = useState(false); const { reviews } = useSelector((state) => state.review); const { deleteReviewDone, addReviewDone } = useSelector( (state) => state.admin ); const [deletedId, setDeletedId] = useState(null); const deleteReview = (id) => { setModalMsg("정말로 삭제하시겠습니까?"); setDeletedId(id); setOpenModal(true); }; const handleClose = () => { setOpenModal(false); }; const handleAddClose = () => { setOpenAddModal(false); }; const handleConfirm = (data) => { if (data === "항목 삭제") { dispatch({ type: DELETE_REVIEW_REQUEST, data: { deletedId, }, }); } }; useEffect(() => { if (deleteReviewDone) { setOpenModal(false); dispatch({ type: LOAD_REVIEWS_REQUEST, }); } }, [deleteReviewDone]); // useEffect(() => { // if (addReviewDone) { // setOpenAddModal(false); // dispatch({ // type: LOAD_REVIEWS_REQUEST, // }); // } // }, [addReviewDone]); return ( <div className="section reviewManage"> <p>배송후기 등록/삭제</p> <div className="table_container"> <div className="row_head row"> <p>No</p> <p>상품명</p> <p>주문자</p> <p>후기 이미지</p> <p></p> </div> {reviews && reviews.map((review, index) => { return ( <div className={ index % 2 === 0 ? "row_content row" : "row_content row even" } key={index} > <p>{review.id}</p> <p>{review.review_name}</p> <p>{review.review_orderer}</p> <p>{review.review_imgSrc}</p> <div className="delete_btn" onClick={() => { deleteReview(review.id); }} > 삭제 </div> </div> ); })} </div> {openModal ? ( <AdminModal data={modalMsg} onConfirm={handleConfirm} onClose={handleClose} /> ) : ( "" )} <div className="add_btn" onClick={() => { setOpenAddModal(true); }} > 리뷰 추가 하기 </div> {openAddModal ? <AddReviewModal onClose={handleAddClose} /> : ""} </div> ); }; export default ReviewManage;
import { persistReducer } from 'redux-persist'; import { createSlice } from '@reduxjs/toolkit'; import storage from 'redux-persist/lib/storage'; interface CategoryState { selectedCategory: string | null; } const categoriesPersistConfig = { key: 'categories', storage, whitelist: ['selectedCategory'], }; const initialState: CategoryState = { selectedCategory: null, }; const categoriesSlice = createSlice({ name: 'categories', initialState, reducers: { setSelectedCategory: (state, action) => { state.selectedCategory = action.payload; }, resetSelectedCategory: (state) => { state.selectedCategory = null; }, }, }); const persistedCategoryReducer = persistReducer( categoriesPersistConfig, categoriesSlice.reducer ); export const { setSelectedCategory, resetSelectedCategory } = categoriesSlice.actions; export default persistedCategoryReducer;
--- title: Yerelleştirme araçları ms.date: 02/15/2019 ms.topic: reference helpviewer_keywords: - globalization [Visual Studio] - Visual Basic code, international applications - C#, international applications - localization [Visual Studio] - world-ready applications - international applications [Visual Studio] ms.assetid: 4d9815ae-3e80-4b4d-933d-f8309aee18d5 author: jillre ms.author: jillfra manager: jillfra ms.workload: - multiple ms.openlocfilehash: 886c31eb76a2cd440f1f8189aaacf592e43d34fa ms.sourcegitcommit: a8e8f4bd5d508da34bbe9f2d4d9fa94da0539de0 ms.translationtype: MT ms.contentlocale: tr-TR ms.lasthandoff: 10/19/2019 ms.locfileid: "72603453" --- # <a name="develop-globalized-and-localized-apps"></a>Genelleştirilmiş ve yerelleştirilmiş uygulamalar geliştirin Visual Studio, [.net](/dotnet/standard/globalization-localization/)' te yerleşik hizmetlerden yararlanarak uluslararası bir hedef kitle için geliştirmeyi kolaylaştırır. Örneğin, Windows Forms uygulamalar için proje sistemi hem geri dönüş Kullanıcı arabirimi kültürü hem de her ek kullanıcı arabirimi kültürü için kaynak dosyaları oluşturabilir. Visual Studio 'da bir proje oluşturduğunuzda, kaynak dosyaları Visual Studio XML biçiminden (. resx), daha sonra uydu derlemelerine gömülü bir ara ikili biçimi (. resources) ile derlenir. Daha fazla bilgi için bkz. [Visual Studio 'Da kaynak dosyaları](/dotnet/framework/resources/creating-resource-files-for-desktop-apps#VSResFiles) ve [Masaüstü uygulamaları Için uydu derlemeleri oluşturma](/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps). ## <a name="bidirectional-languages"></a>Çift yönlü diller Arapça ve Ibranice gibi sağdan sola yazılan dillerde metni doğru şekilde görüntüleyen uygulamalar oluşturmak için Visual Studio 'Yu kullanabilirsiniz. Bazı özellikler için, yalnızca özellikleri ayarlayabilirsiniz. Diğer durumlarda, koddaki özellikleri uygulamanız gerekir. > [!NOTE] > Çift yönlü dilleri girip görüntülemesi için, uygun dille yapılandırılmış bir Windows sürümüyle çalışmanız gerekir. Bu, uygun dil paketinin yüklü olduğu bir Windows Ingilizce sürümü ya da Windows 'un uygun şekilde yerelleştirilmiş sürümü olabilir. ### <a name="apps-that-support-bidirectional-languages"></a>Çift yönlü dilleri destekleyen uygulamalar - Windows uygulamaları Çift yönlü metin, sağdan sola okuma düzeni ve yansıtma (pencere, menü ve iletişim kutularının düzenini tersine çevirme) için destek içeren tam çift yönlü uygulamalar oluşturabilirsiniz. Yansıtma haricinde, bu özellikler varsayılan olarak veya özellik ayarları olarak kullanılabilir. Yansıtma, ileti kutuları gibi bazı özellikler için kendiliğinden desteklenir. Ancak, diğer durumlarda kodda yansıtma uygulamanız gerekir. Daha fazla bilgi için bkz. [Windows Forms uygulamalar için çift yönlü destek](/dotnet/framework/winforms/advanced/bi-directional-support-for-windows-forms-applications). - Web uygulamaları Web Hizmetleri, çift yönlü dilleri içeren uygulamalar için uygun hale getirerek UTF-8 ve Unicode metin gönderip almayı destekler. Web istemcisi uygulamaları, Kullanıcı arabirimi için tarayıcıları kullanır, bu nedenle bir Web uygulamasında çift yönlü destek derecesi, kullanıcı tarayıcısının bu çift yönlü özellikleri ne kadar iyi desteklediğine bağlıdır. Visual Studio 'da Arapça veya Ibranice metin, sağdan sola okuma düzeni, dosya kodlama ve yerel kültür ayarları desteğiyle uygulamalar oluşturabilirsiniz. Daha fazla bilgi için bkz. [ASP.NET Web uygulamaları Için çift yönlü destek](https://msdn.microsoft.com/Library/5576f9b1-9b86-41ef-8354-092d366bcd03). > [!NOTE] > Konsol uygulamaları çift yönlü diller için metin desteği içermez. Bu, Windows 'un konsol uygulamalarıyla nasıl çalıştığı hakkında bir sonucudur. ## <a name="see-also"></a>Ayrıca bkz. - [Visual Studio 'da çift yönlü diller için destek](use-bidirectional-languages.md) - [.NET uygulamalarını globalize ve yerelleştirin](/dotnet/standard/globalization-localization/) - [.NET uygulamalarında kaynaklar](/dotnet/framework/resources/)
// 1 Вывести текст, введенный в инпут, в консоль const showTextBtn = document.querySelector(".show_text_btn"); const showTextInput = document.querySelector(".show_text_input"); showTextBtn.addEventListener("click", () => console.log(showTextInput.value)); console.log(showTextBtn); console.log(showTextInput); // ------------------------------------------------------------------------------------------------------------------------------ // 2 Поменять текст в инпуте с ??? на !!! const changeTextBtn = document.querySelector(".change_text_btn"); const changeTextInput = document.querySelector(".change_text_input"); changeTextBtn.addEventListener("click", () => (changeTextInput.value = "!!!")); // ------------------------------------------------------------------------------------------------------------------------------ // 3 Поменять фон на черный // 1 способ const black_mode_btn = document.querySelector(".black_mode_btn"); black_mode_btn.addEventListener( "click", () => (document.body.style.backgroundColor = "black") ); // 2 способ // const black_mode_btn2 = document.querySelector(".black_mode_btn"); // const body = document.querySelector("body"); // black_mode_btn2.addEventListener( // "click", // () => (body.style.backgroundColor = "black") // ); // ------------------------------------------------------------------------------------------------------------------------------ // classList.add(); // - добовляет класс // classList.remove(); //- удаляет класс // classList.toggle(); // - добовляет класс, если он есть удаляет класс если его нет / универсальный метод // ------------------------------------------------------------------------------------------------------------------------------ // 4 Поменять фон на черный // 1 способ // const change_mode_btn = document.querySelector(".change_mode_btn"); // change_mode_btn.addEventListener("click", () => { // document.body.classList.toggle("black_mode"); // }); // способ работает с css // 2 способ const change_mode_btn = document.querySelector(".change_mode_btn"); change_mode_btn.addEventListener("click", () => { const backgroundColor = document.body.style.backgroundColor === "black" ? "white" : "black"; document.body.style.backgroundColor = backgroundColor; }); // способ работает без css // 3 способ // const change_mode_btn = document.querySelector(".change_mode_btn"); // change_mode_btn.addEventListener("click", () => { // if (document.body.style.backgroundColor === "black") { // return "white"; // } else { // return "black"; // } // }); // прсмотреть не работает // ------------------------------------------------------------------------------------------------------------------------------ // 5 Меняет цвет кнопки на red const redColorBtn = document.querySelector(".red_color_btn"); redColorBtn.addEventListener( "click", (event) => (event.target.style.backgroundColor = "red") ); // ------------------------------------------------------------------------------------------------------------------------------ // 6 Меняет цвет кнопки на random // https://www.rapidtables.com/web/color/RGB_Color.html const randomColorBtn = document.querySelector(".random_color_btn"); const getRandomNum = () => Math.round(Math.random() * 255); //Math.random() => дробное от 0 до 1 //Math.random() * 255 => дробное от 0 до 255 //Math.round(Math.random() * 255) => целое число от 0 до 255 randomColorBtn.addEventListener( "click", (event) => (event.target.style.backgroundColor = `rgb(${getRandomNum()}, ${getRandomNum()}, ${getRandomNum()})`) ); // 7 Менять цвет фон на случайный const randomBackground = document.querySelector(".random_bacgraund_btn"); const getRandomBackgraund = () => Math.round(Math.random() * 255); randomBackground.addEventListener("click", () => { document.body.style.backgroundColor = `rgb(${getRandomBackgraund()}, ${getRandomBackgraund()}, ${getRandomBackgraund()})`; }); // ------------------------------------------------------------------------------------------------------------------------------ // 8 Менять содержимое инпута на значение из массива const changeBtn = document.querySelector(".change_btn"); const changeInput = document.querySelector(".change_input"); const symbols = ["!!!", "...", "+++", "@@@"]; let symbol_index = 0; changeBtn.addEventListener( "click", () => (changeInput.value = symbols[symbol_index++ % symbols.length]) ); //symbols_index++ % symbols.length // 0 % 4 = 0 // 1 % 4 = 1 // 2 % 4 = 2 // 3 % 4 = 3 // 4 % 4 = 0 // 5 % 4 = 1 // 6 % 4 = 2 // 7 % 4 = 3 // 8 % 4 = 0 // ------------------------------------------------------------------------------------------------------------------------------ // 9 Создать слайдер с фотографиями из массива // 1 способ // const imgSlider = document.querySelector(".img_slider"); // const photos = [ // "https://www.ardalpha.de/wissen/weltall/raumfahrt/elefant-asiatischer-ohren-ruessel-sri-lanka-asien-100~_v-img__16__9__l_-1dc0e8f74459dd04c91a0d45af4972b9069f1135.jpg?version=3123b", // "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Elephant_near_ndutu.jpg/300px-Elephant_near_ndutu.jpg", // "https://static.nationalgeographic.de/files/styles/image_3200/public/nationalgeographic_2706457.jpg?w=1600&h=900", // "file:///Users/bogdanlarionov/Desktop/A.gif", // ]; // let img_slider = 0; // imgSlider.addEventListener( // "click", // (event) => (imgSlider.src = photos[img_slider++ % photos.length]) // ); // 2 способ const photos = [ "https://image.geo.de/30039574/t/b1/v3/w1440/r1/-/afrikanischer-elefant-gross-jpg--15463-.jpg", "https://image.stern.de/32837894/t/tc/v2/w1440/r1/-/elefant-baby.jpg", "https://www.fr.de/bilder/2022/03/14/91409793/28439211-eigentlich-sind-afrikas-elefanten-durch-das-washingtoner-artenschutzabkommen-geschuetzt-imago-images-2jw2YakuLDec.jpg", // "file:///Users/bogdanlarionov/Desktop/A.gif", ]; const imgSlider = document.querySelector(".img_slider"); let photoIndex = 0; imgSlider.addEventListener( "click", (event) => (event.target.src = photos[photoIndex++ % photos.length]) ); // homework // слайдер const photosBtn = [ "https://image.geo.de/30039574/t/b1/v3/w1440/r1/-/afrikanischer-elefant-gross-jpg--15463-.jpg", "https://image.stern.de/32837894/t/tc/v2/w1440/r1/-/elefant-baby.jpg", "https://www.fr.de/bilder/2022/03/14/91409793/28439211-eigentlich-sind-afrikas-elefanten-durch-das-washingtoner-artenschutzabkommen-geschuetzt-imago-images-2jw2YakuLDec.jpg", // "file:///Users/bogdanlarionov/Desktop/A.gif", ]; const imgBtnSlider = document.querySelector(".img_btn_slider"); const leftBtn = document.querySelector(".left_btn"); const rightBtn = document.querySelector(".right_btn"); let photo_index = 0; leftBtn.addEventListener("click", () => { imgBtnSlider.src = photosBtn[photo_index++ % photosBtn.length]; }); rightBtn.addEventListener("click", () => { imgBtnSlider.src = photosBtn[++photo_index % photosBtn.length]; }); // кнопка const btnBig = document.querySelector(".btn_big"); btnBig.addEventListener("click", () => { btnBig.style.height = "60px"; btnBig.style.width = "60px"; btnBig.style.backgroundColor = "green"; btnBig.style.marginLeft = "50rem"; });
#if REMOVE_OFFICE_PLUGIN #error Remove OfficeDocumentFontPropertiesVisualEditorToolStrip from the project. #endif using System; using System.Windows; using Vintasoft.Imaging.Office.OpenXml.Editor; using Vintasoft.Imaging.Wpf; namespace WpfDemosCommonCode.Office { /// <summary> /// Interaction logic for OpenXmlParagraphPropertiesWindow.xaml /// </summary> public partial class OpenXmlParagraphPropertiesWindow : Window { #region Fields /// <summary> /// The initial paragraph properties. /// </summary> OpenXmlParagraphProperties _intalParagraphProperties; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="OpenXmlParagraphPropertiesWindow"/> class. /// </summary> public OpenXmlParagraphPropertiesWindow() { InitializeComponent(); textJustificationComboBox.Items.Add(OpenXmlParagraphJustification.Left); textJustificationComboBox.Items.Add(OpenXmlParagraphJustification.Center); textJustificationComboBox.Items.Add(OpenXmlParagraphJustification.Right); textJustificationComboBox.Items.Add(OpenXmlParagraphJustification.Both); } #endregion #region Properties OpenXmlParagraphProperties _paragraphProperties; /// <summary> /// Gets or sets the paragraph properties. /// </summary> public OpenXmlParagraphProperties ParagraphProperties { get { return _paragraphProperties; } set { if (value == null) throw new ArgumentNullException(); _paragraphProperties = value; _intalParagraphProperties = value.Clone(); UpdateUI(); } } #endregion #region Methods #region PUBLIC /// <summary> /// Returns the paragraph properties, which contain changed properties. /// </summary> public OpenXmlParagraphProperties GetChangedParagraphProperties() { OpenXmlParagraphProperties result = OpenXmlParagraphProperties.GetChanges(_intalParagraphProperties, _paragraphProperties); if (result.IsEmpty) return null; return result; } #endregion #region PRIVATE /// <summary> /// Handles the Click event of OkButton object. /// </summary> private void okButton_Click(object sender, RoutedEventArgs e) { if (UpdateParagraphProperties()) DialogResult = true; } /// <summary> /// Handles the Click event of CancelButton object. /// </summary> private void cancelButton_Click(object sender, RoutedEventArgs e) { DialogResult = false; } /// <summary> /// Updates the User Interface from <see cref="ParagraphProperties"/>. /// </summary> private void UpdateUI() { textJustificationComboBox.SelectedItem = _paragraphProperties.Justification; fillColorPanel.Color = WpfObjectConverter.CreateWindowsColor(_paragraphProperties.FillColor.Value); firstLineIndentationComboBox.Text = DemosTools.ToString(_paragraphProperties.FirstLineIndentation); leftIndentationComboBox.Text = DemosTools.ToString(_paragraphProperties.LeftIndentation); rightIndentationComboBox.Text = DemosTools.ToString(_paragraphProperties.RightIndentation); lineHeightComboBox.Text = DemosTools.ToString(_paragraphProperties.LineHeightFactor); spacingBeforeComboBox.Text = DemosTools.ToString(_paragraphProperties.SpacingBeforeParagraph); spacingAfterComboBox.Text = DemosTools.ToString(_paragraphProperties.SpacingAfterParagraph); keepLinesCheckBox.IsChecked = _paragraphProperties.KeepLines.Value; keepNextCheckBox.IsChecked = _paragraphProperties.KeepNext.Value; pageBreakBeforeCheckBox.IsChecked = _paragraphProperties.PageBreakBefore.Value; widowControlCheckBox.IsChecked = _paragraphProperties.WidowControl.Value; } /// <summary> /// Updates the <see cref="ParagraphProperties"/> from User Interface. /// </summary> /// <returns></returns> private bool UpdateParagraphProperties() { _paragraphProperties.Justification = (OpenXmlParagraphJustification)textJustificationComboBox.SelectedItem; _paragraphProperties.FillColor = WpfObjectConverter.CreateDrawingColor(fillColorPanel.Color); float value; if (!DemosTools.ParseFloat(firstLineIndentationComboBox.Text, "First Line Indentation", out value)) return false; _paragraphProperties.FirstLineIndentation = value; if (!DemosTools.ParseFloat(leftIndentationComboBox.Text, "Left Indentation", out value)) return false; _paragraphProperties.LeftIndentation = value; if (!DemosTools.ParseFloat(rightIndentationComboBox.Text, "Right Indentation", out value)) return false; _paragraphProperties.RightIndentation = value; if (!DemosTools.ParseFloat(lineHeightComboBox.Text, "Line Height Factor", out value)) return false; _paragraphProperties.LineHeightFactor = value; if (!DemosTools.ParseFloat(spacingBeforeComboBox.Text, "Spacing Before Paragraph", out value)) return false; _paragraphProperties.SpacingBeforeParagraph = value; if (!DemosTools.ParseFloat(spacingAfterComboBox.Text, "Spacing After Paragraph", out value)) return false; _paragraphProperties.SpacingAfterParagraph = value; _paragraphProperties.KeepLines = keepLinesCheckBox.IsChecked.Value; _paragraphProperties.KeepNext = keepNextCheckBox.IsChecked.Value; _paragraphProperties.PageBreakBefore = pageBreakBeforeCheckBox.IsChecked.Value; _paragraphProperties.WidowControl = widowControlCheckBox.IsChecked.Value; return true; } #endregion #endregion } }
import { useEffect, useState } from "react"; export const useDebounce = (value, milliSeconds = 300) => { // State to hold the debounced value const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { // Set a timeout to update the debounced value after the specified duration const handler = setTimeout(() => { setDebouncedValue(value); }, milliSeconds); // Cleanup function to clear the timeout if the value or milliSeconds change return () => { clearTimeout(handler); }; }, [value, milliSeconds]); // Return the debounced value return debouncedValue; };
/*---- SDL Pong Mayhem :-) ----------------------------------------- Copyright (c) 2020 Adrian Petrila, YO3GFH Simple pong game built with the Pelle's C compiler and SDL graphic/media library: http://www.smorgasbordet.com/pellesc/ https://www.libsdl.org/download-2.0.php It also uses SDL_TTF, SDL_Image and SDL_Mix: https://www.libsdl.org/projects/ It uses the Muli true-type font, designed by Vernon Adams https://fonts.google.com/specimen/Muli 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/>. Features -------- - Multiplayer 8-) W/S keys for left player, UP/DOWN for right player. You can even play left hand against right hand :-)) - Variable ball speed, change it with -/= (or keypad +/-). - Wallpaper =) just put something called "wallpaper.png" in game folder. - Music and sound effects, yayy :)) put something called "music.wav" in game folder to play as music (looped) and "bump.wav" to play when hitting the ball with the paddles. This was done with the Pelle's C compiler v9.0 as my first SDL app. Had a ton of fun scribbling it. It's taylored to my own needs/taste, modify it to suit your own. I'm not a professional programmer, so this isn't the best code you'll find on the web, you have been warned :-)) To install SDL (and TTF, Mix and Image) with Pelle, download the devel packages and copy the .lib files in Pelle Lib/Win and Lib/Win64. Go to Pelle include folder and make a subfolder called sdl. Copy all the header files found in the devel packages include folder here. Put the dll's in the project folder (if the target is 32 bits, copy the 32 bit dll, if 64 then the 64 bit one, you get the picture). In project options, add the include/sdl folder you just created to the include path. Also, go to linker properties and add sdl2.lib, sdl2main.lib, sdl2_mixer.lib, sdl2_ttf.lib and sdl2_image.lib to the library list. All the bugs are guaranteed to be genuine, and are exclusively mine =) */ #include <windows.h> #include <SDL.h> #include <SDL_mixer.h> #include <SDL_ttf.h> #include <SDL_image.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include "sdl-pong.h" // // function prototypes // static void update_score ( void ); static void update_status ( void ); static void update_idle_time ( void ); static void update_help ( void ); static void move_paddles ( void ); static void move_ball ( void ); static BOOL detect_collisions ( void ); static void game_cleanup ( void ); static INIT_STATUS game_init ( void ); #ifdef DEBUG static void clear_screen ( void ); static void goto_xy ( const BYTE col, const BYTE row ); #endif static void process_events ( SDL_Event * pevent ); #ifdef PSYCHEDELIC static void rotate_colors ( SDL_Color * color ); #endif // // globals (waaay too many :-)) // SDL_Window * g_gamewin = NULL; SDL_Renderer * g_renderer = NULL; SDL_Texture * g_wallpaper = NULL; TTF_Font * g_font = NULL; SDL_Color g_fgcolor = { 255, 255, 255, 220 };// for score font SDL_Color g_sfgcolor = { 255, 255, 255, 150 };// for statusbar font SDL_Color g_hfgcolor = { 250, 130, 0, 180 }; // for help text font SDL_Color g_bgcolor = { 32, 32, 32, 200 }; // bump sound and music Mix_Chunk * g_pong_snd = NULL; Mix_Music * g_music = NULL; // left paddle SDL_Rect g_left_paddle = { INITIAL_L_PADDLE_X, INITIAL_L_PADDLE_Y, L_PADDLE_WIDTH, L_PADDLE_HEIGHT }; // right paddle SDL_Rect g_right_paddle = { INITIAL_R_PADDLE_X, INITIAL_R_PADDLE_Y, R_PADDLE_WIDTH, R_PADDLE_HEIGHT }; // ball :-) SDL_Rect g_ball = { INITIAL_BALL_X_R, INITIAL_BALL_Y, BALL_WIDTH, BALL_HEIGHT }; // rects to check for top/bottom bounce SDL_Rect g_top_bounce_rect = { 0, 1, SCREEN_WIDTH, 1 }; SDL_Rect g_bottom_bounce_rect = { 0, SCREEN_HEIGHT - 1, SCREEN_WIDTH, 1 }; BOOL g_quitting = FALSE; BOOL g_paused = FALSE; BOOL g_minimized = FALSE; BOOL g_already_colliding = FALSE; BOOL g_have_audio = FALSE; BOOL g_have_music = FALSE; BOOL g_have_pong = FALSE; BOOL g_have_img = FALSE; BOOL g_help = FALSE; Uint32 g_frame_count, g_start_ticks, g_crt_time, g_idle_time; float g_avg_fps; int g_pad_velocity, g_ball_x_velocity, g_ball_y_velocity, g_lpad_direction, g_rpad_direction, g_volume; unsigned long g_player_one_score, g_player_two_score; // // Implementation // /*-@@+@@--------------------------------------------------------------------*/ // Function: main /*--------------------------------------------------------------------------*/ // Type: int // Param. 1: int argc : // Param. 2: char ** argv : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: Main program loop /*--------------------------------------------------------------------@@-@@-*/ int main ( int argc, char ** argv ) /*--------------------------------------------------------------------------*/ { INIT_STATUS status; SDL_Event event; status = game_init(); if ( status != ERR_SUCCESS ) { fprintf ( stderr, g_err_messages[status], SDL_GetError() ); // die only on critical errors if ( status == ERR_SDL_INIT || status == ERR_SDL_WINDOWS || status == ERR_SDL_REND || status == ERR_SDL_FONT_INIT || status == ERR_FONT_RES_LOAD ) { game_cleanup(); return 1; } } g_frame_count = 0; g_idle_time = 0; g_start_ticks = SDL_GetTicks(); if ( g_have_music ) { Mix_VolumeMusic ( g_volume ); Mix_PlayMusic( g_music, -1 ); } while ( !g_quitting ) { process_events ( &event ); // check for kb/mouse/window events if ( !g_paused && !g_minimized ) { // move the paddles move_paddles(); // check for col. with paddles or top/bottom if ( detect_collisions() && g_have_pong ) { Mix_PlayChannel ( -1, g_pong_snd, 0 ); } // move the ball move_ball(); // have we scored? if ( ( g_ball.x > SCREEN_WIDTH + 25 ) || ( g_ball.x < -25 ) ) { // see which player lost and position // the ball on the opposite side if ( g_ball_x_velocity > 0 ) { ++g_player_one_score; g_ball.x = INITIAL_BALL_X_L; } else { ++g_player_two_score; g_ball.x = INITIAL_BALL_X_R; } // choose a random y g_ball.y = rand() % ( SCREEN_HEIGHT - BALL_HEIGHT ); // choose a random angle g_ball_y_velocity = 1 + ( rand() % ( abs ( g_ball_x_velocity ) - 1 ) ); if ( g_ball.y > SCREEN_MID_Y ) { g_ball_y_velocity *= -1; } } // render scene #ifdef PSYCHEDELIC rotate_colors ( &g_bgcolor ); #endif SDL_SetRenderDrawColor ( g_renderer, g_bgcolor.r, g_bgcolor.g, g_bgcolor.b, g_bgcolor.a ); SDL_RenderClear( g_renderer ); SDL_SetRenderDrawColor( g_renderer, g_fgcolor.r, g_fgcolor.g, g_fgcolor.b, g_fgcolor.a ); if ( g_have_img ) { SDL_RenderCopy ( g_renderer, g_wallpaper, NULL, NULL ); } SDL_RenderFillRect ( g_renderer, &g_left_paddle ); SDL_RenderFillRect ( g_renderer, &g_right_paddle ); SDL_RenderFillRect ( g_renderer, &g_ball ); g_crt_time = SDL_GetTicks() - g_start_ticks; g_crt_time -= g_idle_time; g_avg_fps = g_frame_count / ( g_crt_time / 1000.f ); if ( g_avg_fps > 500 ) { g_avg_fps = 0; } update_score(); update_help(); update_status(); SDL_RenderPresent ( g_renderer ); #ifdef DEBUG fprintf ( stderr, "g_frame_count %-8lu, x=%-4d, y=%-4d," " x_vel=%-2d, y_vel=%-2d\n", g_frame_count, g_ball.x, g_ball.y, g_ball_x_velocity, g_ball_y_velocity ); #endif g_frame_count++; } else // while paused, process help at least { SDL_SetRenderDrawColor ( g_renderer, g_bgcolor.r, g_bgcolor.g, g_bgcolor.b, g_bgcolor.a ); SDL_RenderClear( g_renderer ); SDL_SetRenderDrawColor( g_renderer, g_fgcolor.r, g_fgcolor.g, g_fgcolor.b, g_fgcolor.a ); if ( g_have_img ) { SDL_RenderCopy ( g_renderer, g_wallpaper, NULL, NULL ); } SDL_RenderFillRect ( g_renderer, &g_left_paddle ); SDL_RenderFillRect ( g_renderer, &g_right_paddle ); SDL_RenderFillRect ( g_renderer, &g_ball ); update_score(); update_help(); update_status(); SDL_RenderPresent ( g_renderer ); } } game_cleanup(); return 0; } /*-@@+@@--------------------------------------------------------------------*/ // Function: update_score /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: update game score /*--------------------------------------------------------------------@@-@@-*/ static void update_score ( void ) /*--------------------------------------------------------------------------*/ { SDL_Texture * score; SDL_Surface * text; SDL_Rect message_rect; char buf[256]; SDL_snprintf ( buf, sizeof ( buf ), g_score_txt, g_player_one_score, g_player_two_score ); text = TTF_RenderText_Blended ( g_font, buf, g_fgcolor ); if ( text != NULL ) { message_rect.x = ( SCREEN_WIDTH - text->w ) / 2; message_rect.y = 10; message_rect.w = text->w; message_rect.h = text->h; score = SDL_CreateTextureFromSurface ( g_renderer, text ); SDL_RenderCopy ( g_renderer, score, NULL, &message_rect ); SDL_DestroyTexture ( score ); SDL_FreeSurface ( text ); } } /*-@@+@@--------------------------------------------------------------------*/ // Function: update_status /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: update fps and ball velocity /*--------------------------------------------------------------------@@-@@-*/ static void update_status ( void ) /*--------------------------------------------------------------------------*/ { SDL_Texture * status; SDL_Surface * text; SDL_Rect message_rect; char buf[256]; SDL_snprintf ( buf, sizeof ( buf ), g_status_txt, abs ( g_ball_x_velocity ), abs ( g_ball_y_velocity ), g_avg_fps, g_volume ); text = TTF_RenderText_Blended ( g_font, buf, g_sfgcolor ); if ( text != NULL ) { message_rect.x = ( SCREEN_WIDTH - text->w ) / 2; message_rect.y = SCREEN_HEIGHT - ( text->h + 10 ); message_rect.w = text->w; message_rect.h = text->h; status = SDL_CreateTextureFromSurface ( g_renderer, text ); SDL_RenderCopy ( g_renderer, status, NULL, &message_rect ); SDL_DestroyTexture ( status ); SDL_FreeSurface ( text ); } } /*-@@+@@--------------------------------------------------------------------*/ // Function: update_help /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: display help msg /*--------------------------------------------------------------------@@-@@-*/ static void update_help ( void ) /*--------------------------------------------------------------------------*/ { SDL_Texture * help; SDL_Surface * text; SDL_Rect message_rect; char buf[256]; if ( g_help ) { SDL_snprintf ( buf, sizeof ( buf ), g_hlp_txt ); } else { SDL_snprintf ( buf, sizeof ( buf ), "F1 for help" ); } text = TTF_RenderText_Blended ( g_font, buf, g_hfgcolor ); if ( text != NULL ) { message_rect.x = ( SCREEN_WIDTH - text->w ) / 2; message_rect.y = SCREEN_HEIGHT - ( 2*text->h + 10 ); message_rect.w = text->w; message_rect.h = text->h; help = SDL_CreateTextureFromSurface ( g_renderer, text ); SDL_RenderCopy ( g_renderer, help, NULL, &message_rect ); SDL_DestroyTexture ( help ); SDL_FreeSurface ( text ); } if ( g_help ) { SDL_snprintf ( buf, sizeof ( buf ), g_game_title ); } else { SDL_snprintf ( buf, sizeof ( buf ), " " ); } text = TTF_RenderText_Blended ( g_font, buf, g_hfgcolor ); if ( text != NULL ) { message_rect.x = ( SCREEN_WIDTH - text->w ) / 2; message_rect.y = SCREEN_HEIGHT - ( 3*text->h + 5 ); message_rect.w = text->w; message_rect.h = text->h; help = SDL_CreateTextureFromSurface ( g_renderer, text ); SDL_RenderCopy ( g_renderer, help, NULL, &message_rect ); SDL_DestroyTexture ( help ); SDL_FreeSurface ( text ); } } #ifdef DEBUG /*-@@+@@--------------------------------------------------------------------*/ // Function: clear_screen /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: support function for DEBUG mode /*--------------------------------------------------------------------@@-@@-*/ static void clear_screen ( void ) /*--------------------------------------------------------------------------*/ { system ( "cls" ); } /*-@@+@@--------------------------------------------------------------------*/ // Function: goto_xy /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: const BYTE col : column coordinate // Param. 2: const BYTE row : row coordinate /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: move cursor (for debug) /*--------------------------------------------------------------------@@-@@-*/ static void goto_xy ( const BYTE col, const BYTE row ) /*--------------------------------------------------------------------------*/ { HANDLE h; COORD pos; h = GetStdHandle ( STD_OUTPUT_HANDLE ); pos.X = col; pos.Y = row; SetConsoleCursorPosition ( h, pos ); } #endif /*-@@+@@--------------------------------------------------------------------*/ // Function: detect_collisions /*--------------------------------------------------------------------------*/ // Type: static BOOL // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: detect collisions between ball and paddles/walls /*--------------------------------------------------------------------@@-@@-*/ static BOOL detect_collisions ( void ) /*--------------------------------------------------------------------------*/ { SDL_Rect isex; int temp; // we hit the left paddle? if ( SDL_IntersectRect ( &g_ball, &g_left_paddle, &isex ) ) { // stop checking if already in collison if ( g_already_colliding ) return FALSE; // reverse ball direction if ( g_ball_x_velocity < 0 ) g_ball_x_velocity *= -1; // choose some random y temp = 1 + ( rand() % ( abs ( g_ball_x_velocity ) - 1 ) ); // sync with the initial ball direction if ( g_ball_y_velocity < 0 ) temp *= -1; // if not full frontal collision if ( isex.h != BALL_HEIGHT ) { if ( g_lpad_direction == UP ) // we hit with the paddle top { if (( g_ball_y_velocity > 0 ) && ( g_ball.y < g_left_paddle.y )) { temp *= -1; } } else // or the bottom { if (( g_ball_y_velocity < 0 ) && ( g_ball.y > g_left_paddle.y )) { temp *= -1; } } } g_ball_y_velocity = temp; g_already_colliding = TRUE; return TRUE; } // right paddle if ( SDL_IntersectRect ( &g_ball, &g_right_paddle, &isex ) ) { if ( g_already_colliding ) return FALSE; if ( g_ball_x_velocity > 0 ) g_ball_x_velocity *= -1; temp = 1 + ( rand() % ( abs ( g_ball_x_velocity ) - 1 ) ); if ( g_ball_y_velocity < 0 ) temp *= -1; if ( isex.h != BALL_HEIGHT ) { if ( g_rpad_direction == UP ) { if (( g_ball_y_velocity > 0 ) && ( g_ball.y < g_right_paddle.y )) { temp *= -1; } } else { if (( g_ball_y_velocity < 0 ) && ( g_ball.y > g_right_paddle.y )) { temp *= -1; } } } g_ball_y_velocity = temp; g_already_colliding = TRUE; return TRUE; } // bounce from top! if ( SDL_IntersectRect ( &g_ball, &g_top_bounce_rect, &isex ) ) { if ( g_ball_y_velocity < 0 ) g_ball_y_velocity *= -1; return TRUE; } // bounce from bottom if ( SDL_IntersectRect ( &g_ball, &g_bottom_bounce_rect, &isex ) ) { if ( g_ball_y_velocity > 0 ) g_ball_y_velocity *= -1; return TRUE; } g_already_colliding = FALSE; return FALSE; } /*-@@+@@--------------------------------------------------------------------*/ // Function: game_cleanup /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: free used resources /*--------------------------------------------------------------------@@-@@-*/ static void game_cleanup ( void ) /*--------------------------------------------------------------------------*/ { if ( g_renderer != NULL ) SDL_DestroyRenderer ( g_renderer ); if ( g_gamewin != NULL ) SDL_DestroyWindow ( g_gamewin ); if ( g_pong_snd != NULL ) Mix_FreeChunk ( g_pong_snd ); if ( g_music != NULL ) Mix_FreeMusic ( g_music ); if ( g_font != NULL ) TTF_CloseFont ( g_font ); if ( g_wallpaper != NULL ) SDL_DestroyTexture ( g_wallpaper ); TTF_Quit(); if ( g_have_img ) IMG_Quit(); if ( g_have_audio ) Mix_Quit(); SDL_Quit(); } /*-@@+@@--------------------------------------------------------------------*/ // Function: game_init /*--------------------------------------------------------------------------*/ // Type: static INIT_STATUS // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: game setup /*--------------------------------------------------------------------@@-@@-*/ static INIT_STATUS game_init ( void ) /*--------------------------------------------------------------------------*/ { int img_flags = IMG_INIT_PNG | IMG_INIT_JPG; SDL_Surface * tmpsurface; // died early if ( SDL_Init ( SDL_INIT_EVERYTHING ) != 0 ) return ERR_SDL_INIT; // init font lib if ( TTF_Init() < 0 ) return ERR_SDL_FONT_INIT; g_font = TTF_OpenFont ( g_game_font, DEFAULT_FONT_SIZE ); if ( g_font == NULL ) return ERR_FONT_RES_LOAD; TTF_SetFontStyle ( g_font, TTF_STYLE_NORMAL ); TTF_SetFontOutline ( g_font, 0 ); TTF_SetFontKerning ( g_font, 1 ); TTF_SetFontHinting ( g_font, TTF_HINTING_NORMAL ); // init audio if ( Mix_OpenAudio ( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) return ERR_SDL_AUDIO_INIT; g_have_audio = TRUE; g_pong_snd = Mix_LoadWAV ( g_bump_wav ); if ( g_pong_snd == NULL ) return ERR_WAV_RES_LOAD; g_have_pong = TRUE; g_music = Mix_LoadMUS ( g_music_wav ); if ( g_music == NULL ) return ERR_WAV_RES_LOAD; g_have_music = TRUE; g_volume = DEF_VOL; g_gamewin = SDL_CreateWindow ( g_game_title, SCREEN_X, SCREEN_Y, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if ( g_gamewin == NULL ) return ERR_SDL_WINDOWS; g_renderer = SDL_CreateRenderer ( g_gamewin, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ); if ( g_renderer == NULL ) return ERR_SDL_REND; if (!( IMG_Init ( img_flags ) & img_flags )) return ERR_IMG_INIT; tmpsurface = IMG_Load ( g_walp_png ); if ( tmpsurface == NULL ) return ERR_IMG_RES_LOAD; g_wallpaper = SDL_CreateTextureFromSurface ( g_renderer, tmpsurface ); if ( g_wallpaper == NULL ) return ERR_IMG_RES_LOAD; g_have_img = TRUE; SDL_FreeSurface( tmpsurface ); srand ( time ( NULL ) ); g_pad_velocity = INITIAL_PADDLE_VELOCITY; g_lpad_direction = UP; g_rpad_direction = UP; g_player_one_score = 0; g_player_two_score = 0; g_ball_x_velocity = INITIAL_BALL_X_VELOCITY; g_ball_y_velocity = INITIAL_BALL_Y_VELOCITY; g_ball.x = INITIAL_BALL_X_R; g_ball.y = rand() % ( SCREEN_HEIGHT - BALL_HEIGHT ); if ( g_ball.y > SCREEN_MID_Y ) g_ball_y_velocity *= -1; g_ball_x_velocity *= -1; #ifdef PSYCHEDELIC g_bgcolor.r = rand() % MAX_R; g_bgcolor.g = rand() % MAX_G; g_bgcolor.b = rand() % MAX_B; #endif return ERR_SUCCESS; } /*-@@+@@--------------------------------------------------------------------*/ // Function: process_events /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: SDL_Event * pevent : pointer to SDL_Event object /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: event processing loop; the heart of the game /*--------------------------------------------------------------------@@-@@-*/ static void process_events ( SDL_Event * pevent ) /*--------------------------------------------------------------------------*/ { while ( SDL_PollEvent ( pevent ) ) { switch ( pevent->type ) { case SDL_QUIT: g_quitting = TRUE; break; case SDL_WINDOWEVENT_CLOSE: g_quitting = TRUE; break; case SDL_WINDOWEVENT: switch ( pevent->window.event ) { // repaint when needed case SDL_WINDOWEVENT_EXPOSED: SDL_RenderPresent ( g_renderer ); break; // pause the game if minimized case SDL_WINDOWEVENT_MINIMIZED: g_minimized = TRUE; if ( !g_paused ) update_idle_time(); break; // restore the game case SDL_WINDOWEVENT_RESTORED: g_minimized = FALSE; if ( !g_paused ) update_idle_time(); break; default: break; } break; case SDL_KEYDOWN: switch ( pevent->key.keysym.sym ) { case SDLK_ESCAPE: g_quitting = TRUE; break; case SDLK_KP_PLUS: case SDLK_EQUALS: if ( g_ball_x_velocity > 0 ) { g_ball_x_velocity++; if ( g_ball_x_velocity > MAX_BALL_VELOCITY ) g_ball_x_velocity = MAX_BALL_VELOCITY; } else { g_ball_x_velocity--; if ( abs (g_ball_x_velocity) > MAX_BALL_VELOCITY) g_ball_x_velocity = -MAX_BALL_VELOCITY; } if ( abs ( g_ball_x_velocity ) < MAX_BALL_VELOCITY ) { if ( g_ball_y_velocity > 0 ) { g_ball_y_velocity++; if ( g_ball_y_velocity > MAX_BALL_VELOCITY ) g_ball_y_velocity = MAX_BALL_VELOCITY; } else { g_ball_y_velocity--; if ( abs (g_ball_y_velocity) > MAX_BALL_VELOCITY) g_ball_y_velocity = -MAX_BALL_VELOCITY; } } break; case SDLK_KP_MINUS: case SDLK_MINUS: if ( g_ball_x_velocity > 0 ) { g_ball_x_velocity--; if ( g_ball_x_velocity < MIN_BALL_VELOCITY ) g_ball_x_velocity = MIN_BALL_VELOCITY; } else { g_ball_x_velocity++; if ( abs (g_ball_x_velocity) < MIN_BALL_VELOCITY ) g_ball_x_velocity = -MIN_BALL_VELOCITY; } if ( abs ( g_ball_x_velocity ) > MIN_BALL_VELOCITY ) { if ( g_ball_y_velocity > 0 ) { g_ball_y_velocity--; if (g_ball_y_velocity < MIN_BALL_VELOCITY) g_ball_y_velocity = MIN_BALL_VELOCITY; } else { g_ball_y_velocity++; if ( abs ( g_ball_y_velocity ) < MIN_BALL_VELOCITY ) g_ball_y_velocity = -MIN_BALL_VELOCITY; } } break; case SDLK_KP_DIVIDE: case SDLK_COMMA: g_volume--; if ( g_volume < MIN_VOL ) g_volume = MIN_VOL; if ( g_have_music ) Mix_VolumeMusic ( g_volume ); break; case SDLK_KP_MULTIPLY: case SDLK_PERIOD: g_volume++; if ( g_volume > MAX_VOL ) g_volume = MAX_VOL; if ( g_have_music ) Mix_VolumeMusic ( g_volume ); break; case SDLK_SPACE: g_paused = !g_paused; update_idle_time(); break; case SDLK_F1: g_help = !g_help; break; #ifdef PSYCHEDELIC case SDLK_F10: g_bgcolor.r = rand() % MAX_R; g_bgcolor.g = rand() % MAX_G; g_bgcolor.b = rand() % MAX_B; break; #endif default: break; } break; default: break; } } } #ifdef PSYCHEDELIC /*-@@+@@--------------------------------------------------------------------*/ // Function: rotate_colors /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: SDL_Color * color : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: something to watch while drunk :-) /*--------------------------------------------------------------------@@-@@-*/ static void rotate_colors ( SDL_Color * color ) /*--------------------------------------------------------------------------*/ { static int r, g, b; if ( ( color->b < MAX_B ) && ( b > 0 ) ) b = 1; else { b = -1; if ( color->b == 0 ) b = 1; } if ( ( color->r < MAX_R ) && ( r > 0 ) ) r = 1; else { r = -1; if ( color->r == 0 ) r = 1; } if ( ( color->g < MAX_G ) && ( g > 0 ) ) g = 1; else { g = -1; if ( color->g == 0 ) g = 1; } color->r += r; color->g += g; color->b += b; } #endif /*-@@+@@--------------------------------------------------------------------*/ // Function: move_paddles /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: move the paddles /*--------------------------------------------------------------------@@-@@-*/ static void move_paddles ( void ) /*--------------------------------------------------------------------------*/ { const Uint8 * kbstate; kbstate = SDL_GetKeyboardState ( NULL ); if ( kbstate[SDL_SCANCODE_W] ) { g_left_paddle.y -= g_pad_velocity; g_lpad_direction = UP; } if ( kbstate[SDL_SCANCODE_S] ) { g_left_paddle.y += g_pad_velocity; g_lpad_direction = DOWN; } if ( kbstate[SDL_SCANCODE_UP] ) { g_right_paddle.y -= g_pad_velocity; g_rpad_direction = UP; } if ( kbstate[SDL_SCANCODE_DOWN] ) { g_right_paddle.y += g_pad_velocity; g_rpad_direction = DOWN; } } /*-@@+@@--------------------------------------------------------------------*/ // Function: move_ball /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: move the ball /*--------------------------------------------------------------------@@-@@-*/ static void move_ball ( void ) /*--------------------------------------------------------------------------*/ { g_ball.x += g_ball_x_velocity; g_ball.y += g_ball_y_velocity; } /*-@@+@@--------------------------------------------------------------------*/ // Function: update_idle_time /*--------------------------------------------------------------------------*/ // Type: static void // Param. 1: void : /*--------------------------------------------------------------------------*/ // AUTHOR: Adrian Petrila, YO3GFH // DATE: 02.06.2021 // DESCRIPTION: accumulate idle time for correct framerate calculation /*--------------------------------------------------------------------@@-@@-*/ static void update_idle_time ( void ) /*--------------------------------------------------------------------------*/ { g_idle_time = SDL_GetTicks() - g_idle_time; }
import React from "react"; import "./App.css"; import { BrowserRouter as Router, Route, Routes, Navigate, } from "react-router-dom"; import Register from "./Auth/Register"; import Login from "./Auth/Login"; import Dashboard from "./pages/Dashboard"; import { useAuth } from "./context/AuthContext"; const App = () => { const { isAuthenticated } = useAuth(); return ( <Router> <Routes> <Route path="/" element={ !isAuthenticated ? <Register /> : <Navigate to="/dashboard" /> } /> <Route path="/login" element={!isAuthenticated ? <Login /> : <Navigate to="/dashboard" />} /> <Route path="/dashboard" element={isAuthenticated ? <Dashboard /> : <Login />} /> </Routes> </Router> ); }; export default App;
from collections import defaultdict from datetime import datetime from typing import Dict, List, Literal, Union, overload from lightning import Callback from lightning.pytorch.utilities.exceptions import MisconfigurationException from more_itertools import windowed class TimeProfiler(Callback): """ Parameters ---------- keys : Union[str, bool] Optional keys for logging. If set to `True` it will log all keys. """ @overload def __init__(self, *keys: str): ... @overload def __init__(self, keys: Literal[True]): ... def __init__(self, *keys: Union[str, bool]): self._default_keys = ( "train batch", "validation batch", "train epoch", "validation epoch", "avg train downtime", "avg val downtime", ) self._optional_keys = ( "backward", "optimizer step", "total train downtime", "total val downtime", ) if len(keys) != 0 and keys[0] is True: keys = sorted(self._optional_keys) _keys = sorted(set(keys).intersection(self._optional_keys)) if _keys != sorted(keys): raise ValueError(f"TimeProfiler got unknown keys: {set(keys) - set(_keys)}") self.keys = sorted(set(keys).union(self._default_keys)) self.time_stamps: Dict[str, List[datetime]] = defaultdict(list) self.batch_sizes: Dict[str, List[int]] = defaultdict(list) def log_time(self, key: str) -> None: self.time_stamps[key].append(datetime.now()) def log_batch_size(self, batch, key: str) -> None: if isinstance(batch, (list, tuple)): batch = batch[0] self.batch_sizes[key].append(len(batch)) def compute_time_delta(self) -> Dict[str, float]: deltas = {} for key, time_stamps in self.time_stamps.items(): deltas[key] = [(t[1] - t[0]).total_seconds() for t in windowed(time_stamps, 2, step=2)] deltas[key] = sum(deltas[key]) / len(deltas[key]) if "train epoch" in deltas: if "validation epoch" in deltas: deltas["train epoch"] -= deltas["validation epoch"] n_train_batches = len(self.batch_sizes["train batch"]) deltas["total train downtime"] = deltas["train epoch"] - n_train_batches * deltas["train batch"] deltas["avg train downtime"] = deltas["total train downtime"] / sum(self.batch_sizes["train batch"]) if "validation epoch" in deltas: n_val_batches = len(self.batch_sizes["validation batch"]) deltas["total val downtime"] = deltas["validation epoch"] - n_val_batches * deltas["validation batch"] deltas["avg val downtime"] = deltas["total val downtime"] / sum(self.batch_sizes["validation batch"]) return deltas def log_to_logger(self, pl_module): deltas = self.compute_time_delta() pl_module.log_dict( {f"{self.__class__.__name__}/{k}": v for k, v in deltas.items() if k in self.keys}, prog_bar=False, on_step=False, on_epoch=True, ) self.time_stamps.clear() self.batch_sizes.clear() def on_train_batch_start(self, trainer, pl_module, batch, batch_idx): self.log_time("train batch") self.log_batch_size(batch, "train batch") def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): self.log_time("train batch") self.log_time("optimizer step") def on_train_epoch_start(self, trainer, pl_module): self.log_time("train epoch") def on_train_epoch_end(self, trainer, pl_module): self.log_time("train epoch") self.log_to_logger(pl_module) def on_validation_batch_start(self, trainer, pl_module, batch, batch_idx, dataloader_idx=0): self.log_time("validation batch") self.log_batch_size(batch, "validation batch") def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0): self.log_time("validation batch") def on_validation_epoch_start(self, trainer, pl_module): self.log_time("validation epoch") def on_validation_epoch_end(self, trainer, pl_module): self.log_time("validation epoch") def on_before_backward(self, trainer, pl_module, loss): self.log_time("backward") def on_after_backward(self, trainer, pl_module): self.log_time("backward") def on_before_optimizer_step(self, trainer, pl_module, optimizer): self.log_time("optimizer step") def setup(self, trainer, pl_module, stage: str): if not trainer.loggers: raise MisconfigurationException(f"Cannot use {self.__class__.__name__} callback with no logger") if stage == "fit": self.time_stamps.clear() self.batch_sizes.clear() def teardown(self, trainer, pl_module, stage: str): if stage == "fit": self.time_stamps.clear() self.batch_sizes.clear()
import { entityItemSelector } from '../../support/commands'; import { entityTableSelector, entityDetailsButtonSelector, entityDetailsBackButtonSelector, entityCreateButtonSelector, entityCreateSaveButtonSelector, entityCreateCancelButtonSelector, entityEditButtonSelector, entityDeleteButtonSelector, entityConfirmDeleteButtonSelector, } from '../../support/entity'; describe('Breeder e2e test', () => { const breederPageUrl = '/breeder'; const breederPageUrlPattern = new RegExp('/breeder(\\?.*)?$'); const username = Cypress.env('E2E_USERNAME') ?? 'user'; const password = Cypress.env('E2E_PASSWORD') ?? 'user'; const breederSample = {}; let breeder: any; beforeEach(() => { cy.login(username, password); }); beforeEach(() => { cy.intercept('GET', '/api/breeders+(?*|)').as('entitiesRequest'); cy.intercept('POST', '/api/breeders').as('postEntityRequest'); cy.intercept('DELETE', '/api/breeders/*').as('deleteEntityRequest'); }); afterEach(() => { if (breeder) { cy.authenticatedRequest({ method: 'DELETE', url: `/api/breeders/${breeder.id}`, }).then(() => { breeder = undefined; }); } }); it('Breeders menu should load Breeders page', () => { cy.visit('/'); cy.clickOnEntityMenuItem('breeder'); cy.wait('@entitiesRequest').then(({ response }) => { if (response!.body.length === 0) { cy.get(entityTableSelector).should('not.exist'); } else { cy.get(entityTableSelector).should('exist'); } }); cy.getEntityHeading('Breeder').should('exist'); cy.url().should('match', breederPageUrlPattern); }); describe('Breeder page', () => { describe('create button click', () => { beforeEach(() => { cy.visit(breederPageUrl); cy.wait('@entitiesRequest'); }); it('should load create Breeder page', () => { cy.get(entityCreateButtonSelector).click(); cy.url().should('match', new RegExp('/breeder/new$')); cy.getEntityCreateUpdateHeading('Breeder'); cy.get(entityCreateSaveButtonSelector).should('exist'); cy.get(entityCreateCancelButtonSelector).click(); cy.wait('@entitiesRequest').then(({ response }) => { expect(response!.statusCode).to.equal(200); }); cy.url().should('match', breederPageUrlPattern); }); }); describe('with existing value', () => { beforeEach(() => { cy.authenticatedRequest({ method: 'POST', url: '/api/breeders', body: breederSample, }).then(({ body }) => { breeder = body; cy.intercept( { method: 'GET', url: '/api/breeders+(?*|)', times: 1, }, { statusCode: 200, body: [breeder], } ).as('entitiesRequestInternal'); }); cy.visit(breederPageUrl); cy.wait('@entitiesRequestInternal'); }); it('detail button click should load details Breeder page', () => { cy.get(entityDetailsButtonSelector).first().click(); cy.getEntityDetailsHeading('breeder'); cy.get(entityDetailsBackButtonSelector).click(); cy.wait('@entitiesRequest').then(({ response }) => { expect(response!.statusCode).to.equal(200); }); cy.url().should('match', breederPageUrlPattern); }); it('edit button click should load edit Breeder page', () => { cy.get(entityEditButtonSelector).first().click(); cy.getEntityCreateUpdateHeading('Breeder'); cy.get(entityCreateSaveButtonSelector).should('exist'); cy.get(entityCreateCancelButtonSelector).click(); cy.wait('@entitiesRequest').then(({ response }) => { expect(response!.statusCode).to.equal(200); }); cy.url().should('match', breederPageUrlPattern); }); it('last delete button click should delete instance of Breeder', () => { cy.get(entityDeleteButtonSelector).last().click(); cy.getEntityDeleteDialogHeading('breeder').should('exist'); cy.get(entityConfirmDeleteButtonSelector).click(); cy.wait('@deleteEntityRequest').then(({ response }) => { expect(response!.statusCode).to.equal(204); }); cy.wait('@entitiesRequest').then(({ response }) => { expect(response!.statusCode).to.equal(200); }); cy.url().should('match', breederPageUrlPattern); breeder = undefined; }); }); }); describe('new Breeder page', () => { beforeEach(() => { cy.visit(`${breederPageUrl}`); cy.get(entityCreateButtonSelector).click(); cy.getEntityCreateUpdateHeading('Breeder'); }); it('should create an instance of Breeder', () => { cy.get(`[data-cy="gUID"]`) .type('64b4b53a-08ae-4ece-9c33-cc695d9c80c4') .invoke('val') .should('match', new RegExp('64b4b53a-08ae-4ece-9c33-cc695d9c80c4')); cy.get(`[data-cy="breederName"]`).type('Refined District Locks').should('have.value', 'Refined District Locks'); cy.get(`[data-cy="breederType"]`).type('79652').should('have.value', '79652'); cy.get(`[data-cy="breederStatus"]`).type('58993').should('have.value', '58993'); cy.get(`[data-cy="breederDescription"]`).type('Account Realigned Borders').should('have.value', 'Account Realigned Borders'); cy.get(`[data-cy="createdBy"]`).type('63197').should('have.value', '63197'); cy.get(`[data-cy="createdOn"]`).type('2022-08-02T17:49').should('have.value', '2022-08-02T17:49'); cy.get(`[data-cy="updatedBy"]`).type('56959').should('have.value', '56959'); cy.get(`[data-cy="updatedOn"]`).type('2022-08-02T15:33').should('have.value', '2022-08-02T15:33'); cy.get(entityCreateSaveButtonSelector).click(); cy.wait('@postEntityRequest').then(({ response }) => { expect(response!.statusCode).to.equal(201); breeder = response!.body; }); cy.wait('@entitiesRequest').then(({ response }) => { expect(response!.statusCode).to.equal(200); }); cy.url().should('match', breederPageUrlPattern); }); }); });
import { Todo } from '../../src/app/models/Todo' import { Color } from '../../src/app/models/Color' import { Status } from '../../src/app/models/Status' import { Category } from '../../src/app/models/Category' describe('Make Data', () => { let categoryMap: Map<number, Category> = new Map<number, Category>(); let colorMap: Map<number, string> = new Map<number, string>(); let stateMap: Map<number, string> = new Map<number, string>(); before(() => { category.map((cat: Category) => { categoryMap.set(cat['id'], cat); }); status.map((res: Status) => { stateMap.set(res['code'], res); }); }) it('store test data', () => { cy.visit('/') todos.forEach(todo => { cy.visit('/') cy.wait(1000); cy.get("[data-cy='todo_header_item']").click(); cy.get("[id=title]").type(todo.title); cy.get("[id=body]").type(todo.body); cy.get("[id=category]").select(String(todo.categoryId)); cy.get("#submitBtn").click(); }) }); it('Update todo', () => { cy.visit('/') let i = 0; todos.forEach(todo => { cy.visit('/') cy.get(`[data-cy=content${i}]`).click() i++; cy.get("[data-cy='upd-form']").each(($el, index, $list) => { cy.get("[id=state]").select(String(stateMap.get(todo.state).code)); }) cy.get("#submit").click(); }) }); function assertCards() { cy.get("[data-cy='card']").each(($el, index, $list) => { cy.get(`[data-cy=title${index}]`).should('have.text', todo[index].title) cy.get(`[data-cy=body${index}]`).should('have.text', todo[index].body) cy.get(`[data-cy=status${index}]`).should('have.text', stateMap.get(todo[index].state)) cy.get(`[data-cy=category${index}]`).should('have.text', categoryMap.get(todo[index].categoryId).name) }) } const todos = [ { "id": 1, "categoryId": 1, "title": "デザインをいい感じにする", "body": "ヘッダーのデザインをもっといい感じに", "state": 0 }, { "id": 12, "categoryId": 7, "title": "title update", "body": "body", "state": 0 }, { "id": 26, "categoryId": 26, "title": "BtestAAA", "body": "CaAA\n\nAAA", "state": 2 }, { "id": 27, "categoryId": 2, "title": "Crud処理を追加", "body": "Crud処理を追加", "state": 0 } ] const category = [ { "id": 1, "name": "フロントエンド", "slug": "front", "color": 1 }, { "id": 2, "name": "バックエンド", "slug": "back", "color": 2 }, { "id": 3, "name": "インフラ", "slug": "infra", "color": 3 }, { "id": 7, "name": "セールス", "slug": "sales", "color": 5 }, { "id": 26, "name": "バックオフィス", "slug": "backoffice", "color": 4 } ] const status = [ { "code": 0, "name": "TODO" }, { "code": 1, "name": "進行中" }, { "code": 2, "name": "完了" } ] })
import React, { useState, useEffect } from 'react'; import styles from '../Emprestimo/emprestimo.module.css'; import MenuComponent from '../../../components/Menu/Menu'; import CardEmprestimosComponent from '../../../components/CardEmprestimos/card_emprestimos'; import ModalEmprestimosComponent from '../../../components/ModalEmprestimos/modal_emprestimos.js'; import { Link } from 'react-router-dom'; const extractIdFromUrl = (url) => { if (!url) return ''; const parts = url.split('/'); return parts[parts.length - 2]; }; const Emprestimo = () => { const [search, setSearch] = useState(''); const [emprestimos, setEmprestimos] = useState([]); const [filteredEmprestimos, setFilteredEmprestimos] = useState([]); const [showModal, setShowModal] = useState(false); const [selectedEmprestimo, setSelectedEmprestimo] = useState(null); const fetchEmprestimos = async () => { const token = localStorage.getItem('token'); try { const response = await fetch('http://192.168.7.17:8000/emprestimos/', { headers: { 'Authorization': `Token ${token}`, }, }); if (!response.ok) { throw new Error('Erro ao carregar os Emprestimos'); } const data = await response.json(); setEmprestimos(data.filter(emprestimo => emprestimo.dataDevolucao === null)); setFilteredEmprestimos(data.filter(emprestimo => emprestimo.dataDevolucao === null)); } catch (error) { console.error('Erro:', error); } }; const fetchNome = async (url, token) => { try { const response = await fetch(url, { headers: { 'Authorization': `Token ${token}`, }, }); if (!response.ok) { throw new Error('Erro ao carregar o nome'); } const data = await response.json(); return data.nome; } catch (error) { console.error('Erro:', error); return ''; } }; useEffect(() => { fetchEmprestimos(); }, []); useEffect(() => { const filterEmprestimos = async () => { const token = localStorage.getItem('token'); const filtered = await Promise.all( emprestimos.map(async (emprestimo) => { const nomeFerramenta = await fetchNome(`http://192.168.7.17:8000/ferramentas/${extractIdFromUrl(emprestimo.numSerie)}/`, token); const nomeFuncionario = await fetchNome(`http://192.168.7.17:8000/funcionarios/${extractIdFromUrl(emprestimo.matriculaFuncionario)}/`, token); return { ...emprestimo, nomeFerramenta, nomeFuncionario }; }) ); const result = filtered.filter(emprestimo => { const searchLower = search.toLowerCase(); const codigoEmprestimoMatch = emprestimo.codigoEmprestimo.toString().includes(searchLower); const emprestimoStringMatch = `emprestimo ${emprestimo.codigoEmprestimo}`.toLowerCase().includes(searchLower); const emprestimoAcentoStringMatch = `empréstimo ${emprestimo.codigoEmprestimo}`.toLowerCase().includes(searchLower); const nomeFuncionarioMatch = emprestimo.nomeFuncionario.toLowerCase().includes(searchLower); const nomeFerramentaMatch = emprestimo.nomeFerramenta.toLowerCase().includes(searchLower); return ( codigoEmprestimoMatch || emprestimoStringMatch || emprestimoAcentoStringMatch || nomeFuncionarioMatch || nomeFerramentaMatch ) && emprestimo.dataDevolucao === null; }); setFilteredEmprestimos(result); }; filterEmprestimos(); }, [search, emprestimos]); const defaultFerramenta = 'url_to_default_image'; const toggleModal = (emprestimo) => { setSelectedEmprestimo(emprestimo); setShowModal(!showModal); }; return ( <div id={styles.div_emprestimo}> <MenuComponent id="menu" /> <Link to={'/emprestimo_cadastro'}> <p id={styles.adicionar}>+</p> </Link> <div id={styles.searchbar}> <input id={styles.input_searchbar} className="conteudo_searchbar" type='search' value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Pesquisar por código, número de série, nome do funcionário ou nome da ferramenta" /> </div> <div className={styles.div_pai}> <div className={styles.card_container}> {filteredEmprestimos.map((emprestimo, index) => ( <CardEmprestimosComponent key={emprestimo.codigoEmprestimo ? emprestimo.codigoEmprestimo : index} emprestimo={emprestimo} defaultFerramenta={defaultFerramenta} onShowModal={() => toggleModal(emprestimo)} /> ))} </div> </div> {showModal && <ModalEmprestimosComponent onClose={toggleModal} emprestimo={selectedEmprestimo} />} </div> ); } export default Emprestimo;
//Car Class// class Car { //Variables of each class, most are pretty self explanatory float carSpeed; float carAcceleration; float carDeceleration; float minSpeed; float maxSpeed; float carY; float carX; float carM; //Used to move the car along the curved ramp using curvePoint color carColor; float carWidth; float carHeight; float rotateFactor; //the rotation of the car along its centre int laneNumber; //lane the car is currently in Road highWay; boolean wantToPass; //if a car wants to pass boolean canPass; //if a car is able to pass float passFactor; //chance to pass int passLane; //Lane the car wants to pass into int passTime; //How long it has been since the last pass //if on the on ramp or off ramp boolean onRamp; boolean offRamp; float offRampFactor; //chance to use off ramp float ignoreFactor; //chance to ignore common sense boolean collision; //if collision has occured int collisionTime; //how long it has been since the collison float collisionRotation; //Car constructor Car(float cS, float cA, float cD, float min, float max, float cY, float cX, Road hW, int lN, float pF, boolean onR, float offRF, float igFact) { this.carWidth = 50; //car height and car width are always the same this.carHeight = 25; this.rotateFactor = 0; this.carSpeed = cS; this.carAcceleration = cA; this.carDeceleration = cD; this.minSpeed = min; this.maxSpeed = max; this.carY = cY; this.carX = cX; this.carM = 0; this.rotateFactor = 0; //0 means straight this.highWay = hW; this.laneNumber = lN; this.wantToPass = false; //The car doesn't want to or can pass initially this.canPass = false; this.passTime = 0; this.passFactor = pF; this.passLane = this.laneNumber; //the pass lane is intially the same as the current lane this.onRamp = onR; this.offRampFactor = offRF; this.offRamp = false; //the car does not start at the off ramp this.ignoreFactor = igFact; this.collision = false; this.collisionTime = 0; this.collisionRotation = random(0, TWO_PI); //When the car has collided, it has been rotated to a random value } //draws the car void drawCar() { if (!(this.collision)) { //if the car has not collided, its colour will depend on its speed this.carColor = lerpColor(red, blue, this.carSpeed/this.maxSpeed); } else { //otherwise, the car will be orange this.carColor = orange; } rectMode(CENTER); //transfomrs, rotates and draws the car pushMatrix(); //allows the transformation to only occur on one car translate(this.carX, this.carY); //moves origin to car x and y values rotate(this.rotateFactor); fill(carColor); stroke(carColor); rect(0, 0, this.carWidth, this.carHeight); //since origin is car x and y, the coords of the rect are 0 popMatrix(); } //Moves the car along the right of the screen void moveCarRight() { if (this.carSpeed > 0) { this.carX += this.carSpeed; } } //Accelerates the car void accelerate() { float mxSpeed; if (this.ignoreFactor < ignoreChance) { //Depending on the aggresion factor, the max speed of the car will be its max speed or the road speed limit mxSpeed = this.maxSpeed; } else { mxSpeed = highWaySpeedLimit; } if (!this.collision) { //if a collison hasn't occured dont accelerate if (this.carSpeed < mxSpeed ) { //accelerate the car until it reaches the max speed if (!(this.onRamp)) { this.carSpeed += this.carAcceleration; } else if (this.onRamp) { //accelerate slower on the on ramp this.carSpeed += this.carAcceleration/3.0; } } if (this.carSpeed > mxSpeed ) { //if the car is over the max speed set the speed to max this.carSpeed = mxSpeed; } } } //Decelerates/brakes the car void decelerate() { if (this.carSpeed > this.minSpeed) { //if the car is over its min speed, then decelerate this.carSpeed -= this.carDeceleration; } if (this.carSpeed < this.minSpeed) { //if the car is below its min speed, then set the speed to min speed this.carSpeed = this.minSpeed; } } //finds the distance a car will travel given its initial speed, final speed, and deceleration rate float getBrakingDistance(float finalVelocity) { float distance = ( pow(finalVelocity, 2) - pow(this.carSpeed, 2) ) / (2*(-1.0)*this.carDeceleration) ; return distance; } //Moves the cars between lanes void crossLane() { float laneMoveIncrement = 10; //how fast the car will move between lanes if (this.passLane < this.laneNumber) { //Moves the car to lane above it this.carY -= laneMoveIncrement; if (!(this.offRamp)) { //Since the car will move up to the off ramp, some values may need to be changed sometimes this.rotateFactor = radians(highWay.centreLines[this.passLane] - this.carY); } else { this.rotateFactor = radians(highWay.offRampY1+5 - this.carY); } } if (this.passLane > this.laneNumber) { //Moves the car to the lane below it this.carY += laneMoveIncrement; this.rotateFactor = radians(highWay.centreLines[this.passLane] - this.carY); } try { //If the car has reached the same y value as the lane it wants to pass to, the passing is complete if (!(offRamp)) { if ((abs(int(this.carY) - int(highWay.centreLines[this.passLane]))) <= 10) { //Resets the passing variables of the cars once the passing has been completed this.carY = highWay.centreLines[this.passLane]; this.laneNumber = this.passLane; this.wantToPass = false; this.canPass = false; this.rotateFactor = 0; } } else { //if passing to off ramp if ((abs(int(this.carY) - int(highWay.offRampY1+5))) <= 10) { this.carY = highWay.offRampY1 + 5; this.laneNumber = this.passLane; this.wantToPass = false; this.canPass = false; this.rotateFactor = 0; } } } catch (IndexOutOfBoundsException E) { } } //Moves the car along the on ramp void moveOnRamp() { if (carM <= highWay.onRampX1+25) { //if the car is on the curve of the ramp float t = this.carM / highWay.onRampX1; this.carX = curvePoint(highWay.onRampX3, 0, highWay.onRampX1, highWay.onRampX2, t); //uses the points of the highway ramp to move the car this.carY = curvePoint(highWay.onRampY3, highWay.onRampY2, highWay.onRampY1, highWay.onRampY1, t); this.carM += this.carSpeed; if (this.carM < 100) { //rotates the car along the curve of the ramp this.rotateFactor = radians((highWay.onRampY1 - this.carY)/2.8); } else { this.rotateFactor = radians((highWay.onRampY1 - this.carY)/(1/t)); } } else { //if the car is on the accleration lane this.rotateFactor = 0; this.moveAccelerationLane(); } } //Moves the car along the acceleration lane void moveAccelerationLane() { this.carY = highWay.onRampY1-5; if (carX > (highWay.onRampX1) + 100) { //Once car has driven far enough, it will want to pass this.wantToPass = true; this.passLane = this.laneNumber-1; } if (!(this.canPass)) { //if it cant pass yet, keep moving it to the right this.moveCarRight(); } else if (this.canPass) { //if it can pass, reset some values, and move it to the lane above this.carSpeed = maxS/2; this.onRamp = false; this.carM = 0; } } //Moves the car along the off ramp void moveOffRamp() { if (this.carX <= highWay.offRampX2 - 25) { //If at a specific x value, move it accross the deceleration lane this.moveDecelerationLane(); } else { //Otherwise, move it along the curve of the off ramp float t = this.carM / highWay.onRampX1; this.carX = curvePoint(highWay.offRampX1, highWay.offRampX2, width, width+50, t); //uses the variables of the road to move the car this.carY = curvePoint(highWay.offRampY1, highWay.offRampY1, highWay.offRampY2, highWay.offRampY3, t); this.carM += this.carSpeed; if (this.carM > 100) { //rotates the car along the curve this.rotateFactor = radians((this.carY - highWay.offRampY1)/2.8); } else { this.rotateFactor = radians((this.carY - highWay.offRampY1)/(1/t)); } } } //moves the car along the deceleration lane void moveDecelerationLane() { if (this.laneNumber == 0) { //if the car is still on the main road, make sure it wants to pass to the decleration lane this.wantToPass = true; this.passLane = this.laneNumber - 1; } this.moveCarRight(); //move the car right, until it reaches the curved part of the ramp } //Moves the car once it has entered a collision void collisionMovement() { if (this.collisionTime <= 3) { //For a few seconds this.canPass = false; this.wantToPass = false; this.minSpeed = 0; this.decelerate(); this.carDeceleration += 0.1; } else { this.carAcceleration = 0; this.carDeceleration = 0; } this.moveCarRight(); this.rotateFactor = this.collisionRotation; } }
import React, { createContext, useContext, useReducer, useEffect } from 'react'; import axios from 'axios'; const MusicDataContext = createContext(); const initialState = { albumIndex: {}, // Albums stored by ID songIndex: {}, // Songs stored by Album ID queue: [], currentSongIndex: 0, repeat: false, isLoading: false, activeTab: null, error: null, }; // Reducer function to handle actions const musicDataReducer = (state, action) => { switch (action.type) { case 'FETCH_START': return { ...state, isLoading: true, error: null }; case 'FETCH_ALBUMS_SUCCESS': const albumsById = action.payload.reduce((obj, album) => { obj[album.id] = album; return obj; }, {}); return { ...state, albumIndex: albumsById, isLoading: false }; case 'FETCH_SONGS_SUCCESS': const { albumId, songs } = action.payload; return { ...state, songIndex: { ...state.songIndex, [albumId]: songs }, isLoading: false }; case 'SET_QUEUE': return { ...state, queue: action.payload, currentSongIndex: 0 }; case 'NEXT_SONG': let nextIndex = (state.currentSongIndex + 1) % state.queue.length; return { ...state, currentSongIndex: nextIndex }; case 'PREV_SONG': let prevIndex = (state.currentSongIndex - 1 + state.queue.length) % state.queue.length; return { ...state, currentSongIndex: prevIndex }; case 'FETCH_FAILURE': return { ...state, isLoading: false, error: action.payload }; default: return state; } }; // Custom hook to use music data reducer export const useMusicDataReducer = () => { const [state, dispatch] = useReducer(musicDataReducer, initialState); useEffect(() => { dispatch({ type: 'FETCH_START' }); const fetchData = async () => { try { const response = await axios.get('/api/albums'); const albums = await response.data; dispatch({ type: 'FETCH_ALBUMS_SUCCESS', payload: albums }); // Fetch songs for each album and dispatch them for (const album of albums) { const response = await axios.get(`/api/songs/album/${album.id}`); const songs = await response.data; dispatch({ type: 'FETCH_SONGS_SUCCESS', payload: { albumId: album.id, songs } }); } } catch (error) { console.error("Error fetching data:", error); dispatch({ type: 'FETCH_FAILURE', payload: error.toString() }); } }; fetchData(); }, []); return { state, dispatch }; }; // Context provider component export const MusicDataProvider = ({ children }) => { const { state, dispatch } = useMusicDataReducer(); return ( <MusicDataContext.Provider value={{ state, dispatch }}> {children} </MusicDataContext.Provider> ); }; // Hook to use music data context export const useMusicData = () => useContext(MusicDataContext); export { MusicDataContext };
# Longest Arithmetic Subsequence [题目](https://leetcode.com/problems/longest-arithmetic-subsequence/description/) 至少这题的for循环我自己写出来了。你问我dp数组?哈哈,完全错误。 ```c# //https://leetcode.com/problems/longest-arithmetic-subsequence/solutions/274611/java-c-python-dp/ //类似的解法(有解释): https://leetcode.com/problems/longest-arithmetic-subsequence/solutions/3671662/beats-100-c-java-python-beginner-friendly/ public class Solution { public int LongestArithSeqLength(int[] nums) { int res = 2, n = nums.Length; Dictionary<int, int>[] dp = new Dictionary<int, int>[n]; int temp; for (int j = 0; j < nums.Length; j++) { //考虑i-j范围里的数字 dp[j] = new(); for (int i = 0; i < j; i++) { int d = nums[j] - nums[i]; //计算所有可能的差值 temp=1; if(dp[i].ContainsKey(d)){ //这块感觉逻辑是这样的:dp[i][d]表示nums[0..i]中差值为d的数列长度为temp。base case为1 temp=dp[i][d]; } dp[j][d]=temp + 1; //i永远小于j,nums[0..i]中差值为d的数列长度为temp,那么到j就是temp+1(前提是差值d一样,不过键不一样也加不起来) res = Math.Max(res, dp[j][d]); //总感觉dp的另一个灵魂就在这,每个dp解法总会有类似的一句 } } return res; } } ``` ``` Runtime 557 ms Beats 74.69% Memory 65.6 MB Beats 35.19% ``` 或者不用字典,根据description里的constraint直接初始化那么长的数组好了。 ```c# //采样区的最佳解 //感觉类似 https://leetcode.com/problems/longest-arithmetic-subsequence/solutions/910303/c-quadratic-time-space-bottom-up-dp/ public class Solution { public int LongestArithSeqLength(int[] nums) { int n = nums.Length; if (n <= 2) return n; int longest = 2; int[][] dp = new int[n][]; for (int i = 0; i < n; i++) { dp[i] = new int[1002]; Array.Fill(dp[i], 1); for (int j = 0; j < i; j++) { int diff = nums[i] - nums[j] + 501; //保证不会有负值 dp[i][diff] = dp[j][diff] + 1; longest = Math.Max(longest, dp[i][diff]); } } return longest; } } ``` ``` Runtime 117 ms Beats 99.82% Memory 61.1 MB Beats 75.23% ```
// // SettingsCoordinator.swift // Deeplink Example // // Created by Тарас Коцур on 12.06.2022. // import UIKit import CoordinatorKit import DeepCoordinatorKit protocol SettingsCoordinatorProtocol: Coordinatable, DeepLinkResponder { func startSettingsItem(_ item: SettingsItem, animated: Bool) } final class SettingsCoordinator: SettingsCoordinatorProtocol { // MARK: - Public properties var rootViewController: UIViewController? { navigationController } var deepLinkLocator: DeepLinkLocatorProtocol = DeepLinkLocator() var childLocator: CoordinatorLocatorProtocol = CoordinatorLocator() var parent: Coordinatable? // MARK: - Private properties private let navigationController: UINavigationController private let settingsScreenBuilder: SettingsScreenBuilderProtocol = SettingsScreenBuilder() // MARK: - Initializers init( navigationController: UINavigationController ) { self.navigationController = navigationController deepLinkLocator.add(routes: [ makeWifiHandler(), makeBluetoothHandler() ]) } convenience init() { let navigationController = UINavigationController() navigationController.navigationBar.prefersLargeTitles = true self.init(navigationController: navigationController) } // MARK: - Methods func start(animated: Bool) { let view = settingsScreenBuilder.buildSettingsList(output: self) navigationController.pushViewController(view, animated: animated) } func startSettingsItem(_ item: SettingsItem, animated: Bool) { let view = settingsScreenBuilder.buildSettingsItem(item) navigationController.pushViewController(view, animated: animated) } func finish(animated: Bool) { childLocator.popAll() } } // MARK: - SettingsOutput extension SettingsCoordinator: SettingsOutput { func setting(_ presenter: SettingsPresenterProtocol, didSelectSettingItem item: SettingsItem) { startSettingsItem(item, animated: true) } } // MARK: - Deeplink handler factory extension SettingsCoordinator { func makeWifiHandler() -> DeepLinkRoute { .init(path: "settings" / "wifi") { [weak self] json in self?.startSettingsItem(.wifi, animated: true) } } func makeBluetoothHandler() -> DeepLinkRoute { .init(path: "settings" / "bluetooth") { [weak self] json in self?.startSettingsItem(.bluetooth, animated: true) } } }
import 'package:cbt_flutter/core/datasources/cbt_notes_api.dart'; import 'package:cbt_flutter/core/entities/cbt_note.dart'; import 'package:cbt_flutter/core/entities/cbt_notes_filter.dart'; import 'package:injectable/injectable.dart'; import 'package:rxdart/subjects.dart'; @singleton class CbtNotesRepo { CbtNotesRepo({ required CbtNotesApi cbtNotesApi, }) : _cbtNotesApi = cbtNotesApi; final CbtNotesApi _cbtNotesApi; late final BehaviorSubject<List<CbtNote>> _streamController; CbtNotesFilter? _filter; Future<Stream<List<CbtNote>>> getCbtNotesStream(CbtNotesFilter? filter) async { _filter = filter; final list = await _getCbtNotes(); _streamController = BehaviorSubject<List<CbtNote>>.seeded(list); return _streamController.asBroadcastStream(); } Future<void> updateCbtNotesStream() async { final list = await _getCbtNotes(); _streamController.add(list); } void setCbtNotesFilter(CbtNotesFilter filter) { _filter = filter; } Future<void> insertCbtNote(CbtNote cbtNote) async { await _cbtNotesApi.insertCbtNote(cbtNote); } Future<void> updateCbtNote(CbtNote cbtNote) async { await _cbtNotesApi.updateCbtNote(cbtNote); } Future<void> removeCbtNote(String uuid) async { await _cbtNotesApi.deleteCbtNote(uuid); } Future<int> countCbtNotes(filter) async { return _cbtNotesApi.countCbtNotes(filter); } Future<List<CbtNote>> _getCbtNotes() async { return _cbtNotesApi.getCbtNotes(_filter); } }
import 'dart:math'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(MyPortfolio()); } class MyPortfolio extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Omar\'s portofolio', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _animation; bool _isAnimationCompleted = false; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: Duration(seconds: 2), ); _animation = Tween<double>(begin: 0, end: 1).animate(_controller) ..addListener(() { setState(() {}); }) ..addStatusListener((status) { if (status == AnimationStatus.completed) { _isAnimationCompleted = true; } }); _controller.forward(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, body: Stack( children: [ // Background section AnimatedBackground(animation: _animation), // Main content section SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Banner section Container( width: double.infinity, height: 400, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/images/banner.jpeg'), fit: BoxFit.cover, ), /*gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.pinkAccent, Colors.blue, ], ),*/ ), child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomRight, colors: [ Colors.black.withOpacity(.9), Colors.black.withOpacity(.3), ], ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ //Row() CircleAvatar( radius: 100, backgroundImage:AssetImage('assets/images/meee.jpeg'), ), SizedBox(height: 10), Text( ' Hello! I am omar almas', style: TextStyle( fontSize: 22, color: Colors.white, fontWeight: FontWeight.bold, ), ), SizedBox(height: 5), Text( ' And That \'s my portofolio', style: TextStyle( fontSize: 18, color: Colors.white, ), ), SizedBox(height: 20), Center( child: Quote( text: '"Commitment and hard work are better than intelligence."', author: '"small baby steps can differ"', ), ), ], ), ), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SocialMediaButton( icon: Icons.mail_outline, color: Colors.red, text: 'email', url: 'omaralmas262@gmail.com', ), SocialMediaButton( icon: Icons.code, color: Colors.green, text: 'Guithub', url: 'https://github.com/Maso2000', ), SocialMediaButton( icon: Icons.link, color: Colors.blue, text: 'Linkedin', url: 'https://www.linkedin.com/in/omar-almas-33366625a/', ), SocialMediaButton( icon: Icons.person, color: Colors.purple, text: 'My resume', url: 'https://docs.google.com/document/d/1Z0CZso09jOT4SUjUkWN0BGnH5_6iubZMTTc4GWW0v04/edit', ), ], ), // Introduction section Container( padding: const EdgeInsets.only( left: 20, right: 20, top: 30, bottom: 20, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'About Me', style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w600, ), ), SizedBox(height: 10), Text( 'I am a software engineer ,graduated from faculty of engineering Alexandria University,I am An eager learner, hard worker, love problem solving and team work.', style: TextStyle( color: Colors.white70, fontSize: 18, height: 1.5, ), ), SizedBox(height: 20), Text( 'Skills', style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w600, ), ), SizedBox(height: 10), Wrap( spacing: 10, children: [ SkillChip('Python'), SkillChip('Java'), SkillChip('Kotlin'), SkillChip('Javascript'), SkillChip('C++/C'), SkillChip('C#'), SkillChip('PHP'), SkillChip('SQL'), SkillChip('MySQL'), ], ), SizedBox(height: 20), Text( 'Projects that I am proud of', style: TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.w600, ), ), SizedBox(height: 10), ProjectCard( title: 'Restaurant reservation system', description: 'A restaurent reservation system done using java,applying object oriented programming principles .' 'The project was divided in admin side and client side.' 'Has a stunning user interface .', image:'assets/images/submitt.png', projectUrl: 'https://github.com/Maso2000/Restaurant_Reservation_System', ), SizedBox(height: 20), ProjectCard( title: 'Aggarly', description: 'A car rental website ,developed using php and sql for the backend and database.' 'Html ,Css and JavaScript for the frontend.' 'The project was divided in client side and server side.', image:'assets/images/submitt.png', projectUrl: 'https://github.com/Maso2000/Car_Rental_System', ), SizedBox(height: 20), Text( 'Let\'s Connect', style: TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.w600, ), ), SizedBox(height: 10), Text( 'If you\'d like to discuss a project or just say hi, feel free to drop me an email at ', style: TextStyle( color: Colors.white70, fontSize: 16, height: 1.5, ), ), SizedBox(height: 5), InkWell( onTap: () => launch('omaralmas262@gmail.com'), child: Text( 'omaralmas262@gmail.com', style: TextStyle( color: Colors.indigo[900], fontSize: 16, height: 1.5, ), ), ), SizedBox(height: 20), ], ), ), ], ), ), ], ), ); } } class SkillChip extends StatelessWidget { final String label; SkillChip(this.label); @override Widget build(BuildContext context) { return Chip( label: Text( label, style: TextStyle(color: Colors.white), ), backgroundColor: Colors.indigo[900], ); } } class ProjectCard extends StatelessWidget { final String title; final String description; final String image; final String projectUrl; ProjectCard({ required this.title, required this.description, required this.image, required this.projectUrl, }); @override Widget build(BuildContext context) { return Container( width: 800, child: Card( color: Colors.grey[800], child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( //width: 100, height: 120, decoration: BoxDecoration( image: DecorationImage( image: AssetImage(image), fit: BoxFit.fitWidth, ), ), ), Container( padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600, ), ), SizedBox(height: 5), Text( description, style: TextStyle( color: Colors.white70, fontSize: 16, height: 1.5, ), ), SizedBox(height: 10), InkWell( onTap: () => launch(projectUrl), child: Text( 'Learn more', style: TextStyle( color: Colors.indigo[900], fontSize: 16, fontWeight: FontWeight.w600, ), ), ), ], ), ), ], ), ), ); } } class AnimatedBackground extends StatelessWidget { final Animation<double> animation; final Random random = Random(); AnimatedBackground({required this.animation}); @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animation, builder: (context, child) { return Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Color(00000), ], ), ), ); }, ); } } class SocialMediaButton extends StatelessWidget { final IconData icon; final String text; final Color color; final String url; SocialMediaButton({ required this.icon, required this.color, required this.text, required this.url, }); @override Widget build(BuildContext context) { return FloatingActionButton.extended( backgroundColor: Colors.black54, icon: Icon( icon, color: Colors.indigo[900], ), //color: color, onPressed: () { launch(url); }, label: Text(text), ); } }class Quote extends StatelessWidget { final String text; final String author; Quote({required this.text, required this.author}); @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( color: Colors.black54, borderRadius: BorderRadius.circular(20), ), padding: EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( text, style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.white), ), SizedBox(height: 16), Text( author, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold,color: Colors.white), ), ], ), ); } }
from typing import Optional, List, Union from pydantic import BaseModel, Field from qdrant_client.http.models import RecommendStrategy import settings ProductId = Union[int, str] # class Location(BaseModel): # latitude: float # longitude: float # class LocationFilter(Location): # radius_km: float class SearchQuery(BaseModel): # location: Optional[LocationFilter] = None positive: Optional[List[ProductId]] = None negative: Optional[List[ProductId]] = None queries: Optional[List[str]] = None limit: int = Field(settings.DEFAULT_LIMIT, ge=1, le=settings.MAX_SEARCH_LIMIT) strategy: RecommendStrategy = RecommendStrategy.BEST_SCORE class Restaurant(BaseModel): name: str rating: Optional[float] # location: Location slug: Optional[str] = None address: Optional[str] = None class Product(BaseModel): id: ProductId name: str description: str image_url: str restaurant: Restaurant payload: dict score: float @classmethod def from_point(cls, point) -> "Product": # location = Location( # latitude=point.payload["cafe"]["location"]["lat"], # longitude=point.payload["cafe"]["location"]["lon"], # ) restaurant = Restaurant( name=point.payload["cafe"]["name"], rating=point.payload["cafe"]["rating"], # location=location, slug=point.payload["cafe"]["slug"], address=point.payload["cafe"]["address"], ) return Product( id=point.id, name=point.payload["name"], description=point.payload["description"], image_url=point.payload["image"], restaurant=restaurant, payload=point.payload, score=point.score, )
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:form id="frmCHITIET"> <p:dialog header="THÔNG TIN CHI TIẾT HÓA ĐƠN" id="dlgCTHoaDon" widgetVar="dlgCTHoaDon" closable="true" closeOnEscape="false" width="800" modal="true" height="2000"> <p:panel styleClass="card pnlTableResize" style="background-color: #e0ebff"> <p:outputLabel value=" ĐƠN ĐẶT HÀNG" style="color:#2191c0;font-size:18px;text-align:center" /> <p:panel id="shake" style="text-align:center"> <p:outputLabel style="color:red" value="ĐÃ NHẬN ĐƠN HÀNG" rendered="#{qlThongTinKhachHangController.order.status == 0}" /> <p:outputLabel style="color:blue" value="ĐANG GIAO HÀNG" rendered="#{qlThongTinKhachHangController.order.status == 1}" /> <p:outputLabel style="color:green" value="ĐƠN HÀNG HOÀN TẤT" rendered="#{qlThongTinKhachHangController.order.status == 2}" /> <p:effect type="shake" event="click" /> </p:panel> <p:dataTable id="tblCartOrder" value="#{qlThongTinKhachHangController.cartList}" var="cartorder" lazy="true" rows="3" paginator="true" paginatorPosition="bottom" paginatorTemplate="{PreviousPageLink} {PageLinks} {NextPageLink}"> <f:facet name="footer"> <p:outputPanel style="text-align:right"> <h:outputText style="color:red;margin-right:80px" value="Tổng tiền thanh toán:" /> <p:outputLabel style="color:red;text-align:right" value="#{qlThongTinKhachHangController.total}"> VNĐ <f:convertNumber locale="vi_VN" /> </p:outputLabel> </p:outputPanel> </f:facet> <p:column width="70" headerText="Tên sách" style="text-align:left"> <p:outputLabel value="#{qlThongTinKhachHangController.getProductById(cartorder.productId).name}" /> </p:column> <p:column width="20" style="text-align: right" headerText="Số lượng"> <p:outputLabel value="#{cartorder.count}"> <f:convertNumber locale="vi_VN" /> </p:outputLabel> </p:column> <p:column width="30" style="text-align: right" headerText="Thành tiền (VNĐ)"> <p:outputLabel value="#{cartorder.money * cartorder.count}"> <f:convertNumber locale="vi_VN" /> </p:outputLabel> </p:column> </p:dataTable> <p:panel header="Thông tin thanh toán" styleClass="card pnlTableResize"> <div class="form-group"> <p:outputLabel class="col-sm-3 col-md-3" value="Họ tên:" /> <div class="col-sm-9 col-md-9"> <p:outputLabel value="#{qlThongTinKhachHangController.customer.fullName}" /> </div> </div> <div class="form-group"> <p:outputLabel class="col-sm-3 col-md-3" value="Địa chỉ nhận hàng:" /> <div class="col-sm-9 col-md-9"> <p:outputLabel value="#{qlThongTinKhachHangController.customer.address}" /> </div> </div> <div class="form-group"> <p:outputLabel class="col-sm-3 col-md-3" value="Thành phố:" /> <div class="col-sm-9 col-md-9"> <p:outputLabel value="#{danhmucUtils.getDmhcProvinceById(qlThongTinKhachHangController.customer.tinhTp).provinceName}" /> </div> </div> <div class="form-group"> <p:outputLabel class="col-sm-3 col-md-3" value="Quận huyện:" /> <div class="col-sm-9 col-md-9"> <p:outputLabel value="#{danhmucUtils.getDistrictByProvinceId(qlThongTinKhachHangController.customer.quanHuyen).districtName}" /> </div> </div> <div class="form-group"> <p:outputLabel class="col-sm-3 col-md-3" value="Số điện thoại:" /> <div class="col-sm-9 col-md-9"> <p:outputLabel value="#{qlThongTinKhachHangController.customer.phone}" /> </div> </div> <div class="form-group"> <p:outputLabel class="col-sm-3 col-md-3" value="Email:" /> <div class="col-sm-9 col-md-9"> <p:outputLabel value="#{qlThongTinKhachHangController.customer.email}" /> </div> </div> </p:panel> </p:panel> <div class="EmptyBox20" /> <div class="text-center"> <p:commandButton value="Đóng" onclick="PF('dlgCTHoaDon').hide();" actionListener="#{qlThongTinKhachHangController.onBack()}"> </p:commandButton> </div> </p:dialog> </h:form> </ui:composition>
<%= form_for(@author) do |f| %> <% if @author.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@author.errors.count, "error") %> prohibited this author from being saved:</h2> <ul> <% @author.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :Name %><br> <%= f.text_field :Name %> </div> <div class="field"> <%= f.label :Address %><br> <%= f.text_field :Address %> </div> <div class="field"> <%= f.label :Email %><br> <%= f.text_field :Email %> </div> <div class="field"> <%= f.label :No_of_books_published %><br> <%= f.text_field :no_of_books_published %> </div> <div class="field"> <%= f.label :active %><br> <%= f.check_box :active %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
import { Routes, Route, Navigate, useSearchParams, useNavigate, } from "react-router-dom"; import { CssBaseline } from "@mui/material"; import { useEffect } from "react"; import ThemeProvider from "./theme/index"; import Login from "./pages/Login"; import Cars from "./features/Cars"; import { PrivateOutlet, PublicOutlet } from "./components/Outlets"; import { ROUTES } from "./config"; import Home from "./pages/Home"; import SnackBar from "./components/UI/Snackbar"; import Profile from "./pages/Profile"; import Posts from "./pages/Posts"; import ListingDetails from "./features/Listings/ListingDetails"; import PurchaseHistory from "./pages/PurchaseHistory"; const App = () => { const [searchParams] = useSearchParams(); const navigate = useNavigate(); useEffect(() => { if (searchParams.has("token")) { searchParams.delete("token"); navigate("/"); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <ThemeProvider> <CssBaseline /> <SnackBar /> <Routes> <Route element={<PublicOutlet />}> <Route path={ROUTES.SIGN_IN} element={<Login />} /> </Route> <Route path="/" element={<PrivateOutlet />}> <Route path="/" element={<Home />} /> <Route path={ROUTES.CARS} element={<Cars />} /> <Route path={ROUTES.PROFILE} element={<Profile />} /> <Route path={ROUTES.LISTINGS} element={<Posts />} /> <Route path="listings/:listingId" element={<ListingDetails />} /> <Route path={ROUTES.PURCHASE_HISTORY} element={<PurchaseHistory />} /> </Route> <Route path="*" element={<Navigate to="/" />} /> </Routes> </ThemeProvider> ); }; export default App;