text
stringlengths
184
4.48M
import { CheckoutWrapper, BasketWrapper, ItemWrapper, ColumnWrapper, CheckoutPrice, CheckoutButton, ButtonWrapper } from "./Checkout.style"; import { useEffect } from "react"; import { Link } from "react-router-dom"; export const Checkout = ({basket, setBasketPrice, basketPrice, setBasket, setFullCatList, fullCatList}) => { useEffect(() => { let totalPrice = 0; basket.forEach(element => totalPrice += parseInt(element.price)); setBasketPrice(totalPrice); }, [basket, setBasketPrice]) const removeCatFromBasket = (index) => { let tempArray = [...basket]; let tempFullArray = [...fullCatList]; tempFullArray.forEach(i => { if (i.url === tempArray[index].url){ i.inCart = !i.inCart; } }) setFullCatList(tempFullArray); tempArray.splice(index, 1); setBasket(tempArray); setBasketPrice(0); } return( <CheckoutWrapper> <h1>Checkout</h1> <BasketWrapper> <ColumnWrapper> <h2>Name</h2> <h2>Breed</h2> <h2>Price</h2> </ColumnWrapper> {basket.map((cat, i) => { return( <ItemWrapper key={i}> <h2>{cat.name}</h2> <h2>{cat.breed}</h2> <h2>£{cat.price}</h2> <ButtonWrapper> <button onClick={() => removeCatFromBasket(i)}>X</button> </ButtonWrapper> </ItemWrapper> ) })} </BasketWrapper> <CheckoutPrice onClick={() => {console.log(basketPrice)}}>{`Total Price: £${basketPrice}`}</CheckoutPrice> <Link className="link" to="/"><CheckoutButton onClick={() => setBasket([])}>Confirm Checkout</CheckoutButton></Link> </CheckoutWrapper> ) }
#ifndef TABLA_H #define TABLA_H #include "Constantes.h" #include "Cadena.h" #include "CalifCol.h" #include "Columna.h" #include "Tupla.h" #include "ListaPos.h" #include "ListaPosImp.h" class Tabla; // Operador de salida de flujo ostream &operator<<(ostream& out, const Tabla &t); class Tabla { public: // Constructores Tabla(Cadena &nombreTabla); Tabla(const Tabla &t); // Destructor virtual ~Tabla(); //PRE: //POS: Iguala la Tabla (this) con la Tabla pasada por parametro Tabla &operator=(const Tabla &t); // Operadores de comparacion bool operator==(const Tabla &t) const; bool operator!=(const Tabla &t) const; bool operator<(const Tabla &t) const; bool operator>(const Tabla &t) const; bool operator<=(const Tabla &t) const; bool operator>=(const Tabla &t) const; //PRE: //POS: Retorna true si las 2 tablas tienen las mismas columnas (mismo nombre y orden) y tienen los mismos datos en sus tuplas bool sonIguales(const Tabla &t) const; //PRE: //POS: Retorna el nombre de this const Cadena &GetNombre() const; //PRE: //POS: Retorna el nombre de this, no permite modificar const ListaPos<Columna>& GetColumnas() const; //PRE: //POS: Agrega la columna a la tabla y retorna OK. Si no se puede realizar despliega un mensaje de error y retorna ERROR. TipoRetorno addCol(Cadena &nombreCol, CalifCol calificadorColumna); //PRE: //POS: Elimina la columna a la tabla y retorna OK. Si no se puede realizar despliega un mensaje de error y retorna ERROR. TipoRetorno delCol(Cadena &nombreCol); //PRE: //POS: Inserta los datos separados por : en la tabla y retorna OK. Si no se puede realizar despliega un mensaje de error y retorna ERROR. TipoRetorno insertInto(Cadena &valoresTupla); //PRE: //POS: Elimina los datos que cumplan con la condicion y retorna OK. Si no se puede realizar despliega un mensaje de error y retorna ERROR. TipoRetorno deleteFrom(Cadena &condicionEliminar); //PRE: //POS: Imprime la metadata de la tabla void printMetadata(); //PRE: //POS: Imprime los datos de la tabla void printDataTable(); //PRE: //POS: Realiza el join entre t1 y t2 guardando el resultado en this y retorna OK. Si no se puede realizar despliega un mensaje de error y retorna ERROR. TipoRetorno join(Tabla &t1, Tabla &t2); private: protected: // Constructor por defecto Tabla(); //Atributos Cadena name; ListaPos<Columna>* columns; ListaPos<Tupla>* tuplas; }; #endif
import {Body, Controller, Delete, Get, Param, Patch, Put} from '@nestjs/common'; import {PriorityService} from "./priority.service"; import {Priority} from "./priority.entity"; @Controller('priority') export class PriorityController { constructor( private priorityService: PriorityService ) {} @Get(':priorityId') getPriorityById(@Param() params): Promise<Priority> { return this.priorityService.findById(params.priorityId) } @Put() createPriority(@Body() priority: Priority): Promise<Priority> { return this.priorityService.create(priority) } @Patch(':priorityId') updatePriority(@Param() params, @Body() priority: Priority): Promise<Priority> { return this.priorityService.update(params.priorityId, priority) } @Delete(':priorityId') deletePriority(@Param() params): Promise<void> { return this.priorityService.delete(params.priorityId) } }
import React, { Component } from "react"; import { connect } from "react-redux"; import { layDanhSachKhoaHoc } from "../../redux/actions/QuanLyKhoaHocAction"; import CoursePopular from "../CoursePopular/CoursePopular"; export class ListCoursePopular extends Component { componentDidMount() { this.props.layDanhSachKhoaHoc(); } renderCourse = maDanhMuc => { let arr = []; if (maDanhMuc === "") { arr = this.props.mangDanhSachKhoaHoc; } else { arr = this.props.mangDanhSachKhoaHoc.filter(item => { return item.danhMucKhoaHoc.maDanhMucKhoahoc === maDanhMuc; }); } return arr.map((item, index) => { return ( <div className="col-md-3" key={index}> <CoursePopular item={item} /> </div> ); }); }; render() { return ( <div className="ListCoursePopular"> <div className="row">{this.renderCourse(this.props.maDanhMuc)}</div> </div> ); } } export const mapDispatchToProps = dispatch => { return { layDanhSachKhoaHoc: () => { dispatch(layDanhSachKhoaHoc()); } }; }; export const mapStateToProps = state => { return { mangDanhSachKhoaHoc: state.QuanLyKhoaHocReducer.mangDanhSachKhoaHoc }; }; export default connect(mapStateToProps, mapDispatchToProps)(ListCoursePopular);
<template> <div> <div class="filters"> <p>Filter:</p> <button class="filters__button" @click="toggleFilter('stock')">In Stock</button> <button class="filters__button" @click="toggleFilter('price')">&lt; $ 20</button> </div> <div class="wrapper"> <div v-for="album in displayedAlbums" :key="album.id" class="productCard"> <RouterLink :to="{ name: 'productDetailPage', params: { id: album.id }}"> <img class="productCard__image" :src="album.src" alt=""> </RouterLink> <div class="productCard__info"> <p class="productCard__info__headline">{{ album.title }}</p> <p class="productCard__info__price">$ {{ album.price }}</p> </div> </div> </div> <div class="pagination"> <button class="pagination__button" @click="prevPage" :disabled="currentPage === 1">Previous</button> <span>Page {{ currentPage }} of {{ totalPages }}</span> <button class="pagination__button" @click="nextPage" :disabled="currentPage === totalPages">Next</button> </div> </div> <div class="items-per-page"> <label class="items-per-page__label" for="itemsPerPage">Items per page:</label> <select class="items-per-page__select" v-model="itemsPerPage" @change="handleItemsPerPageChange" id="itemsPerPage"> <option class="items-per-page__option" value="8">8</option> <option class="items-per-page__option" value="16">16</option> <option class="items-per-page__option" value="24">24</option> </select> </div> </template> <script> import albumsData from "@/albums.json"; export default { data() { return { albums: albumsData, filters: { stock: false, price: false, }, itemsPerPage: 8, currentPage: 1, }; }, computed: { filteredAlbums() { return this.albums.filter((album) => { const meetsStockCriteria = !this.filters.stock || album.stock >= 1; const meetsPriceCriteria = !this.filters.price || album.price < 20; return meetsStockCriteria && meetsPriceCriteria; }); }, displayedAlbums() { const start = (this.currentPage - 1) * this.itemsPerPage; const end = start + this.itemsPerPage; return this.filteredAlbums.slice(start, end); }, totalPages() { return Math.ceil(this.filteredAlbums.length / this.itemsPerPage); }, }, methods: { toggleFilter(filterType) { this.filters[filterType] = !this.filters[filterType]; this.currentPage = 1; }, prevPage() { if (this.currentPage > 1) { this.currentPage--; } }, nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; } }, handleItemsPerPageChange() { this.currentPage = 1; }, }, }; </script> <style> </style>
import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:loading_animation_widget/loading_animation_widget.dart'; import 'search.dart'; class SelectCategory extends StatefulWidget { final List<dynamic> services; const SelectCategory({Key? key, required this.services}) : super(key: key); @override State<SelectCategory> createState() => _SelectCategoryState(); } class _SelectCategoryState extends State<SelectCategory> { TextEditingController searchController = TextEditingController(); List<dynamic> filteredServices = []; List<int> selectedCategories = []; @override void initState() { super.initState(); filteredServices = widget.services; } @override Widget build(BuildContext context) { final screenWidth = MediaQuery.of(context).size.width; final screenHeight = MediaQuery.of(context).size.height; return Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { List<int> selectedCategoriesData = selectedCategories.map((index) => int.parse(filteredServices[index]['id'])).toList(); Navigator.push( context, MaterialPageRoute(builder: (context) => SearchPage(services_id: selectedCategoriesData)), ); }, child: Icon(Icons.arrow_forward), ), appBar: AppBar( backgroundColor: Colors.white, shadowColor: Colors.grey, elevation: 2, title: Text( "Select needed category", style: TextStyle(color: Colors.black), ), iconTheme: IconThemeData(color: Colors.black), ), body: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(15.0), child: TextField( controller: searchController, onChanged: filterServices, decoration: InputDecoration( labelText: 'Search by service name', border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), prefixIcon: Icon(Icons.search), ), ), ), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, // Number of items in each row crossAxisSpacing: 10, // Spacing between items horizontally mainAxisSpacing: 10, // Spacing between items vertically childAspectRatio: 0.75, // Aspect ratio of each item ), itemCount: filteredServices.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { setState(() { if (selectedCategories.contains(index)) { selectedCategories.remove(index); } else { selectedCategories.add(index); } }); }, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), elevation: selectedCategories.contains(index) ? 8 : 5, child: Stack( alignment: Alignment.center, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(15), topRight: Radius.circular(15), ), child: CachedNetworkImage( imageUrl: "https://switch.unotelecom.com/fixpert/assets/services_image/${filteredServices[index]['image_uri']}", placeholder: (context, url) => LoadingAnimationWidget.prograssiveDots( color: Colors.blueAccent, size: 50, ), // Loading indicator errorWidget: (context, url, error) => Icon( Icons.error, size: 50, ), // Error widget if image fails to load width: double.infinity, height: screenHeight * 0.2, fit: BoxFit.cover, ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( filteredServices[index]['name'], style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, ), textAlign: TextAlign.center, ), ), ], ), if (selectedCategories.contains(index)) // Display check icon if selected Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.green.withOpacity(0.8), // Adjust opacity as needed ), padding: EdgeInsets.all(8), // Adjust padding as needed child: Icon( Icons.check, color: Colors.white, size: 40, ), ), ], ), ), ); }, ), ), ), ], ), ); } void filterServices(String query) { // If the query is empty, display all services if (query.isEmpty) { setState(() { filteredServices = widget.services; }); return; } // Filter services based on the query List<dynamic> filteredList = widget.services.where((service) { return service['name'].toLowerCase().contains(query.toLowerCase()); }).toList(); setState(() { filteredServices = filteredList; }); } }
import { useNavigate, useParams } from "react-router-dom"; import { Single_solution_data } from "./index"; import "./Single.css"; import { cards1_AllSolutions, cards1_Sectors } from "../index"; // Import cards1_Sectors import { useState } from "react"; export default function Single() { const [isHovered, setIsHovered] = useState(false); const { single } = useParams(); const navigate = useNavigate(); const singleData = Single_solution_data.find(item => item.route === single); console.log(singleData) if (!singleData) { return <div>No data found for this route</div>; } return ( <div> <div className="top_main"> <img className="sol_banner" src='images/Homepage/singl_sol1.jpg' alt="" /> <div className="img_cont"> <p className="head_text">{singleData.route}</p> <div className="bred"> <img src="images/Homepage/Home.svg" alt="" /> <p><span onClick={()=>navigate('/')}>Home</span>/<span onClick={()=>navigate('/all-solutions')}>Solutions</span></p> </div> </div> </div> <div className="mid_single"> <div className="overview"> <p className="head_text">Overview</p> <p className="desc_text">{singleData.overviewDesc}</p> </div> <div className="features"> <p className="head_text">Features</p> <div className="feature_container"> {singleData.features.map((feature, index) => ( <div className="single_feature" key={index}> <p className="head_feature">{feature.feature_head}</p> <p className="desc_feature">{feature.feature_desc}</p> </div> ))} </div> </div> { singleData.solution_arch && ( <div className="info_graphics"> <p className="head_text">Solution Architecture</p> <img className="info_g" src={singleData.solution_arch} alt="" /> </div> ) } {/* { singleData.solution_img && ( <div className="permanent"> <p className="head_text">Services</p> <img className="perm_img" src={singleData.solution_img} alt="" /> </div> ) } */} </div> <div className="sols_links"> { singleData.tag === 'solutions' ? ( <> <p className="head_text">List of Solutions</p> <div className="links"> { cards1_AllSolutions.map((data, idx) => ( <div className={`single_link ${singleData.route === data.head ? 'active' : ''}`} key={idx} onClick={() => navigate(`/${data.head}`)} onMouseEnter={() => setIsHovered(idx)} onMouseLeave={() => setIsHovered(null)}> <div className="inner"> <img className="link_img" src={isHovered === idx || singleData.route === data.head ? data.hover : data.img} alt="" /> <p className="link_text">{data.head}</p> </div> <p className="arrow-right">→</p> </div> )) } </div> </> ) : ( <> <p className="head_text">List of Sectors</p> <div className="links"> { cards1_Sectors.map((data, idx) => ( <div className="single_link" key={idx} onClick={() => navigate(`/${data.head}`)} onMouseEnter={() => setIsHovered(idx)} onMouseLeave={() => setIsHovered(null)}> <div className="inner"> <img className="link_img" src={isHovered === idx ? data.hover : data.img} alt="" /> <p className="link_text">{data.head}</p> </div> <p className="arrow-right">→</p> </div> )) } </div> </> ) } </div> </div> ); }
package brady; import ai.core.AIWithComputationBudget; import ai.core.ParameterSpecification; import ai.abstraction.pathfinding.AStarPathFinding; import rts.GameState; import rts.units.Unit; import rts.units.UnitTypeTable; import rts.PlayerAction; import rts.PlayerActionGenerator; import rts.UnitAction; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class BradyBot extends AIWithComputationBudget { UnitTypeTable m_utt = null; private AStarPathFinding pathfinder = new AStarPathFinding(); public BradyBot(UnitTypeTable utt) { super(-1, -1); m_utt = utt; } @Override public AIWithComputationBudget clone() { return new BradyBot(m_utt); } @Override public void reset() { // Optional: Initialize bot state at the beginning of each new game } @Override public PlayerAction getAction(int player, GameState gs) { try { if (!gs.canExecuteAnyAction(player)) return new PlayerAction(); PlayerActionGenerator pag = new PlayerActionGenerator(gs, player); PlayerAction pa = pag.getRandom(); // Check available resources and if a light unit can be trained if (gs.getPlayer(player).getResources() >= m_utt.getUnitType("Light").cost) { for (Unit u : gs.getUnits()) { if (u.getPlayer() == player && u.getType().name.equals("Base")) { System.out.println( "Producing a Light unit from Base at position (" + u.getX() + ", " + u.getY() + ")"); pa.addUnitAction(u, new UnitAction(UnitAction.TYPE_PRODUCE, -1, m_utt.getUnitType("Light"))); } } } // Find closest enemy unit for each light unit and attack for (Unit u : gs.getUnits()) { if (u.getPlayer() == player && u.getType().name.equals("Light")) { Unit closestEnemy = findClosestEnemy(gs, u); if (closestEnemy != null) { int targetpos = closestEnemy.getY() * gs.getPhysicalGameState().getWidth() + closestEnemy.getX(); UnitAction moveAction = pathfinder.findPathToPositionInRange(u, targetpos, 1, gs, null); if (moveAction != null) { pa.addUnitAction(u, moveAction); } } } } return pa; } catch (Exception e) { // The only way the player action generator returns an exception is if there are // no units that // can execute actions, in this case, just return an empty action: // However, this should never happen, since we are checking for this at the // beginning e.printStackTrace(); return new PlayerAction(); } } @Override public List<ParameterSpecification> getParameters() { // Optional: Specify parameters for the bot to expose in the GUI return new ArrayList<>(); } // Method to find the closest enemy unit to a given unit private Unit findClosestEnemy(GameState gs, Unit unit) { Unit closestEnemy = null; int closestDistance = Integer.MAX_VALUE; for (Unit enemyUnit : gs.getUnits()) { if (enemyUnit.getPlayer() != unit.getPlayer()) { // Check if the unit belongs to an enemy player int distance = Math.abs(unit.getX() - enemyUnit.getX()) + Math.abs(unit.getY() - enemyUnit.getY()); if (distance < closestDistance) { closestDistance = distance; closestEnemy = enemyUnit; } } } return closestEnemy; } }
package com.example.demo.domain.models; import com.example.demo.TestConfig; import com.example.demo.adapters.mongodb.entities.LibraryEntity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @TestConfig public class LibraryTests { @Test void testEquals() { Library library1 = Library.builder() .address("X.º XX XXXXXXX, XX, 28001, XXXXXX, Madrid") .telephone("6669996669") .name("BIBLIOTECA") .email("[email protected]") .postalCode("28001") .businessHours("Monday to Friday 10:00 to 22:00 Saturday and Sunday 10:00 to 16:00") .introduction("this is test introduction") .twitter("https://www.twitter.com/") .googleMail("https://mail.google.com/") .instagram("https://www.instagram.com/") .facebook("https://www.facebook.com/") .discord("https://www.discord.com/") .build(); Library library2 = Library.builder() .address("X.º XX XXXXXXX, XX, 28001, XXXXXX, Madrid") .telephone("6669996669") .name("BIBLIOTECA") .email("[email protected]") .postalCode("28001") .businessHours("Monday to Friday 10:00 to 22:00 Saturday and Sunday 10:00 to 16:00") .introduction("this is test introduction") .twitter("https://www.twitter.com/") .googleMail("https://mail.google.com/") .instagram("https://www.instagram.com/") .facebook("https://www.facebook.com/") .discord("https://www.discord.com/") .build(); Library library3 = Library.builder() .address("X.º XX XXXXXXX, XX, 28001, XXXXXX, Madrid") .telephone("6669996669") .name("BIBLIOTECA2") .email("[email protected]") .postalCode("28001") .businessHours("Monday to Friday 10:00 to 22:00 Saturday and Sunday 10:00 to 16:00") .introduction("this is test introduction") .twitter("https://www.twitter.com/") .googleMail("https://mail.google.com/") .instagram("https://www.instagram.com/") .facebook("https://www.facebook.com/") .discord("https://www.discord.com/") .build(); assertEquals(library1, library2); assertNotEquals(library1, library3); } @Test void testHashCode() { Library library1 = Library.builder() .address("X.º XX XXXXXXX, XX, 28001, XXXXXX, Madrid") .telephone("6669996669") .name("BIBLIOTECA") .email("[email protected]") .postalCode("28001") .businessHours("Monday to Friday 10:00 to 22:00 Saturday and Sunday 10:00 to 16:00") .introduction("this is test introduction") .twitter("https://www.twitter.com/") .googleMail("https://mail.google.com/") .instagram("https://www.instagram.com/") .facebook("https://www.facebook.com/") .discord("https://www.discord.com/") .build(); Library library2 = Library.builder() .address("X.º XX XXXXXXX, XX, 28001, XXXXXX, Madrid") .telephone("6669996669") .name("BIBLIOTECA") .email("[email protected]") .postalCode("28001") .businessHours("Monday to Friday 10:00 to 22:00 Saturday and Sunday 10:00 to 16:00") .introduction("this is test introduction") .twitter("https://www.twitter.com/") .googleMail("https://mail.google.com/") .instagram("https://www.instagram.com/") .facebook("https://www.facebook.com/") .discord("https://www.discord.com/") .build(); Library library3 = Library.builder() .address("X.º XX XXXXXXX, XX, 28001, XXXXXX, Madrid") .telephone("6669996669") .name("BIBLIOTECA2") .email("[email protected]") .postalCode("28001") .businessHours("Monday to Friday 10:00 to 22:00 Saturday and Sunday 10:00 to 16:00") .introduction("this is test introduction") .twitter("https://www.twitter.com/") .googleMail("https://mail.google.com/") .instagram("https://www.instagram.com/") .facebook("https://www.facebook.com/") .discord("https://www.discord.com/") .build(); assertEquals(library1.hashCode(), library2.hashCode()); assertNotEquals(library1.hashCode(), library3.hashCode()); } }
import { useContext, useState } from "react"; import FormData from "form-data"; import axios from "axios"; import { useNavigate } from "react-router-dom"; import { UserContext } from "../context/UserContext"; import { toast } from "react-hot-toast"; const LoginForm = () => { const { setUser, setIsLoggedIn } = useContext(UserContext); const navigate = useNavigate(); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [loading, setLoading] = useState(false); const handleLoginFormSubmit = async (ev) => { ev.preventDefault(); try { setLoading(true); const formData = new FormData(); formData.append("email", email); formData.append("password", password); const res = await axios.post( "http://localhost:4000/api/v1/users/login", formData, { headers: { "Content-Type": "application/json", }, withCredentials: true, } ); if (res.data.success === true) { setUser(res.data.user); setIsLoggedIn(true); toast.success(res.data.message); setLoading(false); navigate("/"); } } catch (error) { toast.error("Invalid email or password!"); } }; return ( <form className="bg-violet-800 mt-[40px] flex flex-col items-center justify-center rounded-lg mx-[220px] py-[20px]" onSubmit={handleLoginFormSubmit} > <div> <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className="my-4 w-[1400px] py-4 px-2 bg-gray-200 border-4 border-black rounded-lg" placeholder="Enter your email" /> </div> <div> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className="my-4 w-[1400px] py-4 px-2 bg-gray-200 border-4 border-black rounded-lg" placeholder="Enter your password" /> </div> <div> <button className="border-4 border-black w-[1400px] py-4 text-white rounded-lg hover:bg-white hover:text-black" type="submit" disabled={loading} > Login </button> </div> </form> ); }; export default LoginForm;
package jz_offer.all.JZ38; import java.util.LinkedList; import java.util.Queue; public class Solution { public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } //递归解法 public int TreeDepth1(TreeNode root) { if (root == null) return 0; //求出左子树的最大深度 int left = TreeDepth1(root.left); //求出右子树的最大深度 int right = TreeDepth1(root.right); return Math.max(left, right) + 1; } //借助队列,层次遍历 public int TreeDepth2(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int high = 0; int size; TreeNode node; while (queue.size() != 0) { size = queue.size(); while (size != 0) { node = queue.poll(); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); size--; } high++; } return high; } }
import random import pygame.time from player import Player from ennemis import * from text import Text from wall import Wall from random import randint from constantes import * import csv import sys class Game: def __init__(self, window, clock): self.window = window self.screen_surface = pygame.surface.Surface(SIZE) self.clock = clock pygame.display.set_caption(TITLE) self.sound_volume = 1 self.continuer = True self.backgrounds = ["image/background/Space Background(3).png", "image/background/Space Background.png", "image/background/Space Background2.png", "image/background/Space Background3.png", "image/background/Space Background4.png", "image/background/Space Background5.png"] self.background_img = pygame.image.load(random.choice(self.backgrounds)) # 255 = 1.0 donc on garde la couleur de base de l'image et on mutliplie simplement le canal alpha : 1 * (160/255) # permet d'obtenir un arrière plan en parti transparent # self.background_img.fill((255, 255, 255, 150), special_flags=BLEND_RGBA_MULT) # on créer une image pour le nombre de vies tourné vers la droite self.player_image = pygame.transform.rotate(pygame.image.load(PLAYER_IMAGE).convert_alpha(), - 90) # on fait le carré principale en fonction de la taille de la fenetre self.center_square = pygame.rect.Rect((0, 0, SIZE[0] // 3, SIZE[1] // 3)) self.center_square.center = (SIZE[0] // 2, SIZE[1] // 2) # on place le carré au centre de l'écran self.score = 0 with open("saves/score.txt", "r") as fichier: self.high_score = int(fichier.readline()) # les 4 textes à afficher pour score et high score text1 = Text("score", 24, self.center_square.right - 5, self.center_square.top, "white") self.score_text = Text(str(self.score), 24, self.center_square.right - 5, text1.rect.bottom, "white") text3 = Text("high score", 24, self.center_square.right - 5, self.score_text.rect.bottom, "white") self.high_score_text = Text(str(self.high_score), 24, self.center_square.right - 5, text3.rect.bottom, "white") self.level_text = Text("niveau 1", 24, self.center_square.center[0], self.center_square.top + 5, "white") # on créer un groupe qui contient les sprites de text self.text_group = pygame.sprite.Group(text1, self.score_text, text3, self.high_score_text, self.level_text) ##### walls ###### top_wall = Wall(WALL_DISTANCE, WALL_DISTANCE, SIZE[0] - WALL_DISTANCE * 2, 1, 1, "white") right_wall = Wall(SIZE[0] - WALL_DISTANCE, WALL_DISTANCE, 1, SIZE[1] - WALL_DISTANCE * 2, 1, "white") down_wall = Wall(WALL_DISTANCE, SIZE[1] - WALL_DISTANCE, SIZE[0] - WALL_DISTANCE * 2, 1, 1, "white") left_wall = Wall(WALL_DISTANCE, WALL_DISTANCE, 1, SIZE[1] - WALL_DISTANCE * 2, 1, "white") self.walls = pygame.sprite.Group(top_wall, right_wall, down_wall, left_wall) self.particles = [] self.ennemis = Ennemy_list() self.starting_ennemis_number = 1 #### Levels #### self.level = 1 self.levels = [] self.loop = 0 # nombre de fois que le joueur a fait le tour des niveaux import csv with open("saves/levels.csv", "r") as fichier: ligne = csv.reader(fichier, delimiter=',', quotechar='|') for case in ligne: self.levels.append(case) self.levels.pop(0) for i in range(len(self.levels)): self.levels[i].pop(0) for j in range(len(self.levels[i])): self.levels[i][j] = int(self.levels[i][j]) #### self.player = Player(PLAYER_INITIAL_POSITION[0], PLAYER_INITIAL_POSITION[1], self.center_square, self.ennemis.tab) self.player_group = pygame.sprite.Group() # on creer une instance du joueur self.player_group.add(self.player) self.game_over = GameOver(self.window, self.clock) self.time_after_death = 0 self.respawn_with_pause = False self.screen_shake_offset = [0, 0] self.screenshake = 0 def pause(self): continuer = True pause_text = Text("Pause", 80, 0, 0, "orange") pause_text.rect.center = SIZE[0] // 2, SIZE[1] // 2 while continuer: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if pygame.key.get_pressed()[pygame.K_ESCAPE]: continuer = False self.screen_surface.blit(pause_text.image, pause_text.rect) self.window.blit(self.screen_surface, self.screen_shake_offset) # on affiche la surface sur la fenetre pygame.display.flip() def start_of_level(self): continuer = True pause_text = Text("appuyez sur une ", 30, 0, 0, "orange") pause_text_2 = Text("touche pour jouer", 30, 0, 0, "orange") pause_text.rect.center = SIZE[0] // 2, SIZE[1] // 2 pause_text_2.rect.center = SIZE[0] // 2, SIZE[1] // 2 + 30 if pygame.time.get_ticks() - self.time_after_death > 100: while continuer: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() if event.type == pygame.KEYDOWN: continuer = False keys = pygame.key.get_pressed() if pygame.time.get_ticks() - self.time_after_death > 500 and (keys[pygame.K_UP] or keys[pygame.K_z] or keys[pygame.K_RIGHT] or keys[pygame.K_LEFT] or keys[pygame.K_SPACE]): continuer = False self.screen_surface.blit(pause_text.image, pause_text.rect) self.screen_surface.blit(pause_text_2.image, pause_text_2.rect) pygame.display.flip() self.respawn_with_pause = False def reset_game(self): self.continuer = True self.background_img = pygame.image.load(random.choice(self.backgrounds)) self.score = 0 with open("saves/score.txt", "r") as fichier: self.high_score = int(fichier.readline()) self.high_score_text.change_text(str(self.high_score)) self.ennemis = Ennemy_list() self.level = 1 self.level_text.change_text("Niveau " + str(self.level)) self.player.nb_life = LIFE_NB self.player.respawn_function() self.player.alive = True self.player.explosion_anim.show = False self.spawn(self.levels[(self.level - 1) % 10]) pygame.mixer.music.unload() pygame.mixer.music.load(GAME_MUSIC) pygame.mixer.music.play(loops=-1, fade_ms=1000) def wall_collisions(self): for wall in self.walls: if self.player.hitbox.colliderect(wall.rect): wall.show() def spawn(self, level): # self.levels[self.level-1] spawnbox = pygame.rect.Rect((self.player.x, self.player.y), PLAYER_SAFE_SPAWN_ZONE) spawnbox.center = self.player.hitbox.center for i in range(len(level)): ennemis_apparus = 0 while ennemis_apparus < level[i]: if i == 0: self.ennemis.tab.append( Mine(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square)) elif i == 1: self.ennemis.tab.append( Asteroid(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square)) elif i == 2: self.ennemis.tab.append( Chargeur(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square)) elif i == 3: self.ennemis.tab.append( Tourelle(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square)) elif i == 4: self.ennemis.tab.append( Miner(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square)) elif i == 5: self.ennemis.tab.append( Tourelle(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square, True)) elif i == 6: self.ennemis.tab.append( Chargeur(randint(40, SIZE[0] - 40), randint(40, SIZE[1] - 40), self.screen_surface, self.center_square, True)) spawncenter = pygame.rect.Rect((self.center_square.x, self.center_square.y), ( self.center_square.width + self.ennemis.tab[-1].hitbox.width, self.center_square.height + self.ennemis.tab[-1].hitbox.height)) spawncenter.center = self.center_square.center if self.ennemis.tab[-1].colide(spawnbox) or self.ennemis.tab[-1].colide(spawncenter): self.ennemis.tab[-1].alive = False self.ennemis.tab.pop(-1) else: ennemis_apparus += 1 def update(self): self.player_group.update( self.screen_surface) # on continue à l'update pour savoir quand il doit respawn (on fait le calcul dans player) if self.player.alive: self.player.ennemis = self.ennemis.tab self.walls.update() particule_copy = [particle for particle in self.particles if particle.radius > 0] self.particles = particule_copy self.score = self.ennemis.update(self.player, self.player.projectiles, self.score) particule_copy = [particle for particle in self.player.particles if particle.radius > 0] self.player.particles = particule_copy for particle in self.player.particles: particle.update() for particle in self.ennemis.particle_list: particle.update() if self.respawn_with_pause: self.start_of_level() self.screenshake_func() # permet de vérifier si l'on doit faire un screenshake et de l'activer si oui else: self.time_after_death = pygame.time.get_ticks() # on appelle cette ligne qu'une seule fois après la mort du joueur self.respawn() # le joueur ne respawn que si il est mort ou qu'on passe au niveau suivant if self.game_over.restart: self.reset_game() self.game_over.restart = False self.score_text.change_text(str(self.score)) def decompter(self): ret = [0 for i in range(7)] for en in self.ennemis.tab: if type(en) == Mine: ret[0] += 1 if type(en) == Asteroid: ret[1] += 1 if type(en) == Chargeur: if en.shield: ret[6] += 1 else: ret[2] += 1 if type(en) == Tourelle: if en.shield: ret[5] += 1 else: ret[3] += 1 if type(en) == Miner: ret[4] += 1 return ret def respawn(self): if len(self.ennemis.tab) == 0 or self.ennemis.only_bullet: self.level += 1 self.level_text.change_text("niveau " + str(self.level)) self.player.respawn_function() # le joueur doit respawn pour ne pas être à la même position qu'au niveau précédent if self.player.respawn: if self.player.nb_life < 0: # on update le meilleur score if self.high_score < self.score: with open("saves/score.txt", "w") as fichier: fichier.write(str(self.score)) self.game_over.score = self.score # on change le score à afficher dans game over self.continuer = False pygame.mixer.music.unload() pygame.mixer.music.load(MENU_MUSIC) pygame.mixer.music.play(loops=-1, fade_ms=1000) self.game_over.run() else: if len(self.ennemis.tab) == 0 or self.ennemis.only_bullet: self.ennemis = Ennemy_list() while self.level > 10 * (self.loop + 1): self.loop += 1 level = self.levels[(self.level - 1) % 10] if self.loop > 0: for i in range(len(level)): level[i] += self.levels[10 + (self.level - 1) % 10][i] * self.loop self.spawn(level) else: tempo_level = self.decompter() self.ennemis = Ennemy_list() self.spawn(tempo_level) self.player.respawn = False self.player.alive = True # si le joueur était mort après son respawn il est à nouveau vivant self.player.projectiles = pygame.sprite.Group() # on enlève tous les projectiles du joueur self.time_after_death = pygame.time.get_ticks() self.respawn_with_pause = True def draw(self): self.screen_surface.blit(self.background_img, (0, 0)) for i in range(self.player.nb_life): # on affiche un vaisseau pour chaque vie du personnage self.screen_surface.blit(self.player_image, (self.center_square.left, self.center_square.top + i * 50)) for wall in self.walls.sprites(): if wall.displayed: wall.draw(self.screen_surface) self.player.player_anim.draw(self.screen_surface) if self.player.alive: self.player_group.draw(self.screen_surface) self.ennemis.draw() self.player.projectiles.draw(self.screen_surface) self.text_group.draw(self.screen_surface) # on affiche l'ensemble des sprites Text dans text_group for particle in self.player.particles: pygame.draw.circle(self.screen_surface, "white", (particle.x, particle.y), particle.radius) for particle in self.ennemis.particle_list: pygame.draw.circle(self.screen_surface, "white", (particle.x, particle.y), particle.radius) pygame.draw.rect(self.screen_surface, "white", self.center_square, 2) # rectangle du milieu self.window.blit(self.screen_surface, self.screen_shake_offset) # on affiche la surface sur la fenetre def game_loop(self): self.update() if self.high_score < self.score: with open("saves/score.txt", "w") as fichier: fichier.write(str(self.score)) self.wall_collisions() # sert uniquement pour l'affichage des murs def screenshake_func(self): self.screenshake = self.ennemis.screenshake # self.screenshake = self.player.screenshake # récupère le temps du screenshake pour le moment ou le joueur meurt if self.screenshake > 0: self.screenshake -= 1 self.ennemis.screenshake -= 1 self.screen_shake_offset[0] = randint(0, 4) - 2 self.screen_shake_offset[1] = randint(0, 3) - 2 def run(self): while self.continuer: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() if event.type == pygame.KEYDOWN: if pygame.key.get_pressed()[pygame.K_ESCAPE]: self.pause() if pygame.key.get_pressed()[pygame.K_SPACE]: self.screenshake = 10 self.game_loop() if self.continuer: # évite un clignement à l'écran quand on revient au menu après un game over self.draw() pygame.display.flip() self.clock.tick(60) class GameOver: def __init__(self, window, clock): self.window = window self.clock = clock self.score = 0 self.game_over_text = Text("Game Over", 90, SIZE[0] // 2, SIZE[1] // 2, "red") self.game_over_text.rect.center = SIZE[0] // 2, SIZE[1] // 2 - 250 self.score_text = Text("Score : " + str(self.score), 60, SIZE[0] // 2, SIZE[1] // 2, "white") self.score_text.rect.center = SIZE[0] // 2, SIZE[1] // 2 - 100 self.rejouer = Text("Rejouer", 60, SIZE[0] // 2, SIZE[1] // 2, "white") self.rejouer.rect.center = SIZE[0] // 2, SIZE[1] // 2 + 50 self.menu = Text("Menu", 60, SIZE[0] // 2, SIZE[1] // 2, "white") self.menu.rect.center = SIZE[0] // 2, SIZE[1] // 2 + 150 self.text_group = pygame.sprite.Group(self.rejouer, self.menu, self.game_over_text, self.score_text) self.select_sound = pygame.mixer.Sound("sound/select.wav") self.menu_image = pygame.image.load("image/background/menu_background.png").convert_alpha() self.restart = False pygame.mixer.music.load(MENU_MUSIC) def run(self): continuer = True pressed = False self.score_text.change_text("Score : " + str(self.score), False) self.score_text.rect.center = SIZE[0] // 2, SIZE[1] // 2 - 100 while continuer: self.window.blit(self.menu_image, (0, 0)) pressed = False for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0]: pressed = True self.rejouer.color = "white" self.rejouer.change_text("Rejouer", False) self.menu.color = "white" self.menu.change_text("Menu", False) if self.rejouer.rect.collidepoint(pygame.mouse.get_pos()): self.rejouer.color = "orange" self.rejouer.change_text("Rejouer", False) if pressed: self.select_sound.play() self.restart = True continuer = False elif self.menu.rect.collidepoint(pygame.mouse.get_pos()): self.menu.color = "orange" self.menu.change_text("Menu", False) if pressed: self.select_sound.play() continuer = False self.text_group.draw(self.window) pygame.display.update() self.clock.tick(60)
import { useState, useEffect, useRef } from 'react' export type Option = { value: string label: string } interface DropdownProps { options: Option[] onSelect: (selectedOption: Option) => void hover?: string } export const Dropdown: React.FC<DropdownProps> = ({ options, onSelect, hover }) => { const [isOpen, setIsOpen] = useState(false) const [selectedOption, setSelectedOption] = useState<Option | null>(null) const dropdownRef = useRef<HTMLDivElement | null>(null) useEffect(() => { const handleOutsideClick = (event: MouseEvent) => { if ( dropdownRef.current && !dropdownRef.current.contains(event.target as Node) ) { setIsOpen(false) } } document.addEventListener('click', handleOutsideClick) return () => { document.removeEventListener('click', handleOutsideClick) } }, []) const toggleDropdown = () => { setIsOpen(!isOpen) } const handleOptionClick = (option: Option) => { setSelectedOption(option) setIsOpen(false) onSelect(option) } return ( <div className='relative inline-block' ref={dropdownRef}> <div> <button type='button' onClick={toggleDropdown} className='inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-sm text-gray-700 hover:bg-gray-50 focus:outline-none' id='options-menu' aria-haspopup='true' aria-expanded='true' > {selectedOption ? selectedOption.label : hover ? hover : 'Select an option'} <svg className='-mr-1 ml-2 h-5 w-5' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true' > <path fillRule='evenodd' d='M6.293 9.293a1 1 0 011.414 0L10 11.586l2.293-2.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z' clipRule='evenodd' /> </svg> </button> </div> {isOpen && ( <div className=' absolute left-1 mt-2 w-56 rounded-md bg-white ring-1 ring-black ring-opacity-5 text-black z-50'> <div className='py-1 z-50' role='menu'> {options.map(option => ( <button key={option.value} onClick={() => handleOptionClick(option)} className={`${ selectedOption?.value === option.value ? 'bg-gray-500 text-black' : 'text-gray-700' } block w-full text-left px-4 py-2 text-sm text-black`} role='menuitem' > {option.label} </button> ))} </div> </div> )} </div> ) }
#ifndef PHILO_H #define PHILO_H #include <stdbool.h> #include <pthread.h> #include <sys/time.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct s_philosopher t_philosopher; typedef struct s_simulation t_simulation; struct s_philosopher { int id; pthread_t thread; pthread_mutex_t *left_fork; pthread_mutex_t *right_fork; long long last_meal; int meals_eaten; bool is_dead; t_simulation *simulation; }; struct s_simulation { int num_philosophers; unsigned long long time_to_die; int time_to_eat; int time_to_sleep; int meals_required; bool simulation_ended; pthread_mutex_t *forks; pthread_mutex_t state_mutex; t_philosopher *philosophers; }; // main.c int main(int argc, char **argv); bool parse_arguments(t_simulation *simulation, int argc, char **argv); bool validate_arguments(t_simulation *simulation); // philosopher.c void *philosopher_routine(void *arg); void think(t_philosopher *philosopher); void sleep_philosopher(t_philosopher *philosopher); bool eat(t_philosopher *philosopher); bool check_death(t_philosopher *philosopher); void update_last_meal(t_philosopher *philosopher); void update_meals_eaten(t_philosopher *philosopher); // simulation.c bool init_simulation(t_simulation *simulation); void run_simulation(t_simulation *simulation); void stop_simulation(t_simulation *simulation); void cleanup_simulation(t_simulation *simulation); // utils.c unsigned long get_timestamp(void); void ms_sleep(unsigned int ms); int ft_atoi(const char *str); void print_status(t_simulation *simulation, int philosopher_id, const char *status); void write_logs(t_simulation *simulation, int philosopher_id,const char *message); #endif // PHILO_H
import axiosInstance from "../../Connections/axiosConfig"; import { useEffect, useState } from "react"; import { useNavigate } from 'react-router-dom'; export const AdministrarUsuarios = () => { const rol = window.localStorage.getItem('Rol') if(rol !== 'ADMINISTRADOR'){ window.location.href = "/" return null; } const navigate = useNavigate(); const [usuarios, setUsuarios] = useState([]); useEffect(() => { const fetchUsuarios = async () => { const Usuarios = await obtenerPedidos(); setUsuarios(Usuarios); }; fetchUsuarios(); }, []); // Asegúrate de pasar un arreglo vacío para que useEffect solo se ejecute una vez al montar el componente const obtenerPedidos = async () => { try { const respuesta = await axiosInstance.get(`/api/v1/u`); console.log(respuesta.data) return respuesta.data; } catch (error) { console.error('Error al obtener usuarios desde la API:', error); return []; } } const IrADetalle = (e) => { navigate('DetallePedido',{e}) } return ( <table> <thead> <tr> <th>Numero Usuario</th> <th>Nombre Usuario</th> <th>Email</th> <th>Nombre</th> <th>Apellido</th> <th>Rol</th> <th>Usuario</th> {/* <th>Detalle</th> */} </tr> </thead> <tbody> {usuarios.map((usuario) => ( <tr key={usuario.id}> <td>{usuario.id}</td> <td>{usuario.username}</td> <td>{usuario.email}</td> <td>{usuario.firstname}</td> <td>{usuario.lastname}</td> <td>{usuario.rol}</td> <td>{usuario.username}</td> {/* {<td><button onClick={() => IrADetalle(pedido.id)}>Detalle</button></td>} */} </tr> ))} </tbody> </table> ); } export default AdministrarUsuarios;
package Week5_PL_ContadoresDomesticos; public class EletricidadeTarifaBiHorario extends Contadores{ /** * Preço do KWH nas horas de vazio */ protected final double tarifarioHorasDeVazio = 0.066; /** * Preço do KWH nas horas fora de Vazio */ protected final double tarifarioHorasForasVazio = 0.14; /** * horas de vazio */ private int horasDeVazio; /** * horas fora de vazio */ private int horasForaVazio; /** * número de horas de vazio por omissão */ protected final int HORAS_VAZIO_POR_OMISSAO = 0; /** * número de horas fora de vazio por omissão */ protected final int HORAS_FORA_VAZIO_POR_OMISSAO = 0; /** * Mostra o número de horas de vazio * @return número de horas de vazio */ public int getHorasDeVazio() { return horasDeVazio; } /** * Mostra o número de horas fora de vazio * @return número de horas fora de vazio */ public int getHorasForaVazio() { return horasForaVazio; } /** * Modifica o número de horas de vazio * @param horasDeVazio atributo a ser alterado, neste caso, o número de horas de vazio */ public void setHorasDeVazio(int horasDeVazio) { this.horasDeVazio = horasDeVazio; } /** * Modifica o número de horas fora de vazio * @param horasForaVazio atributo a ser alterado, neste caso, o número de horas fora de vazio */ public void setHorasForaVazio(int horasForaVazio) { this.horasForaVazio = horasForaVazio; } /** * Constroí um contador de eletricidade bi-horário com os atributos : * @param identificacao identificação do construtor * @param nomeCliente nome do cliente que possui o contador * @param horasDeVazio horas de vazio * @param horasForaVazio horas fora de vazio */ public EletricidadeTarifaBiHorario ( String identificacao, String nomeCliente, int horasDeVazio, int horasForaVazio){ super(identificacao,nomeCliente); this.horasDeVazio = horasDeVazio; this.horasForaVazio = horasForaVazio; } /** * Constroí um contador de eletricidade bi-horário com todos os atributos por omissão */ public EletricidadeTarifaBiHorario (){ super(); this.horasDeVazio = HORAS_VAZIO_POR_OMISSAO; this.horasForaVazio = HORAS_FORA_VAZIO_POR_OMISSAO; } /** * Mostra todas as informações acerca do contador de eletricidade de tarifa bi-horário * @return string com todas as informações acerca do contador de eletricidade de tarifa bi-horária */ @Override public String toString() { return super.toString() + ", é um contador de eletricidade de tarifa bi-horária e o custo mensal é " + calcularCustoConsumo() + " euros!"; } /** * calcula o custo mensal do consumo de eletricidade de tarifa bi-horária * @return soma dos produtos entre (horas de vazio e horas fora de vazio e as respetivas tarifas) */ @Override public double calcularCustoConsumo() { return horasDeVazio * tarifarioHorasDeVazio + horasForaVazio * tarifarioHorasForasVazio; } }
#pragma once class CStringStack { public: CStringStack() = default; CStringStack(CStringStack const &other); CStringStack(CStringStack &&other) noexcept; ~CStringStack() noexcept; CStringStack &operator=(CStringStack const &other); CStringStack &operator=(CStringStack &&other) noexcept; void Push(std::string const &str); void Push(std::string &&str); void Pop(); std::string Top() const; bool Empty() const; std::size_t Size() const; void Clear(); private: struct Item; typedef std::shared_ptr<Item> ItemPtr; struct Item { Item(std::string const &value, ItemPtr const &next) : value(value), next(next) { } explicit Item(std::string const &value) : value(value) { } std::string value; ItemPtr next = nullptr; }; ItemPtr m_top = nullptr; std::size_t m_size = 0; };
<template> <div slot="header" class="clearfix card"> <el-button class="close-button" icon="el-icon-close" round size="mini" style="float: left;background: #fff" @click="closeCard"></el-button> <div v-show="isQRlogin" class="QRlogin"> <p class="QRhead"> 扫码登录</p> <el-image :src="qrurl" fit="fill" style="width: 170px; height: 170px"> <div slot="error" class="image-slot"> <i class="el-icon-picture-outline"></i> </div> </el-image> <p class="Applogin">使用 <el-link :underline="false" href="https://music.163.com/#/download" target="_blank" type="primary">网易云音乐APP </el-link> 扫码登录 </p> <el-link :underline="false" class="footer" @click="otherLogin">用其他方式登录></el-link> </div> <div v-show="!isQRlogin" class="Userlogin"> <el-image :src="require('@/assets/img/login-phone.jpg')" style="width: 260px; height: 84px;margin: 71px auto 42px auto"> <div slot="error" class="image-slot"> <i class="el-icon-picture-outline"></i> </div> </el-image> <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm" style="width:260px; margin: 0 auto;"> <el-input v-model="ruleForm.phoneNumber" class="phone-number" placeholder="请输入手机号" prefix-icon="el-icon-mobile"> <template slot="prepend"> <el-cascader v-model="value" :options="phoneNumberPlace" :props="props" @change="handleChange" > <template v-slot:scope="{ node, data }"> <span>{{ data.label }}</span> <span> ({{ data.value }}) </span> </template> </el-cascader> </template> </el-input> <el-form-item prop="password"> <el-input v-model="ruleForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock" type="password"></el-input> </el-form-item> <el-button style="width: 100% ;margin-top: 20px" type="danger" @click="login">登录</el-button> <el-link :underline="false" style="width: 100% ;margin-top: 10px" @click="clickroundBtn">注册</el-link> <el-row style="padding: 0 6px;display: flex; justify-content: space-between;margin: 10px 0;"> <el-button circle icon="icon-weixin" @click="clickroundBtn"></el-button> <el-button circle icon="icon-qq" @click="clickroundBtn"></el-button> <el-button circle icon="icon-weibo" @click="clickroundBtn"></el-button> <el-button circle icon="icon-wangyi" @click="clickroundBtn"></el-button> </el-row> <el-checkbox v-model="isAgree" class="agree" label="1" @click="!isAgree">同意 <el-link :underline="false" href="https://st.music.163.com/official-terms/service" style="width: 100% ;" target="_blank"> 《服务条款》 </el-link> <el-link :underline="false" href="https://st.music.163.com/official-terms/privacy" style="width: 100% ;" target="_blank"> 《隐私政策》 </el-link> <el-link :underline="false" href="https://st.music.163.com/official-terms/children" style="width: 100% ;" target="_blank"> 《儿童隐私政策》 </el-link> </el-checkbox> </el-form> <el-button class="QRloginBtn" round size="mini" type="danger" @click="qrlogin">二维码</el-button> </div> </div> </template> <script> import {getcountries, login} from '@/utils/api' import {mapActions} from 'vuex' export default { name: "loginCard", data() { return { timer: null,//计时器 // 级联选择器定义 props: { label: 'zh', value: 'code' }, // 是否同意条款 isAgree: false, // 选定的结果 value: [], // 手机号地区列表 phoneNumberPlace: [], // 是否显示二维码登录或 密码登录 isQRlogin: true, qrurl: '', // 表单绑定的内容 ruleForm: { phoneNumber: '16621272164', password: '2442854604', }, rules: { phonenumber: [ {required: true, message: '请输入11位手机号', trigger: 'blur'} ], password: [ {required: true, message: '请输入密码', trigger: 'blur'} ] } } }, props: { isShow: { type: Boolean, default: false } }, watch: { isShow(isShow) { if (isShow) { this.getcountries() this.qrlogin() } } }, created() { }, methods: { ...mapActions(['saveUserId']), closeCard() { this.$emit("update:isShow", false); clearInterval(this.timer) }, otherLogin() { this.isQRlogin = !this.isQRlogin clearInterval(this.timer) }, // 获取国家列表 async getcountries() { this.phoneNumberPlace = [] let {data: res} = await getcountries() res.map((item) => { this.phoneNumberPlace.push(...item.countryList) }) this.value = this.phoneNumberPlace[0].code }, // 调用手机密码登录 async login() { if (this.isAgree == false) { this.$message.warning('请允许条款') return } let res = await login('cellphone/', { phone: this.ruleForm.phoneNumber, password: this.ruleForm.password, countrycode: this.value }) if (res.code == 200) { this.$message.success('登陆成功') // this.saveUserId({id:res.account.id}) this.$bus.$emit('test', res.account.id) this.closeCard() } else { this.$message.error('账号或密码错误,请重试') } }, clickroundBtn() { this.$message.error('ε=(´ο`*)))唉~功能还在开发中~') }, handleChange(value) { console.log(value); }, async qrlogin() { this.isQRlogin = true // 获取二维码 let timenow = Date.now() let key = await login('qr/key', { timerstamp: timenow, withCredentials: true, //关键 }) let {data: url} = await login('qr/create', { key: key.data.unikey, qrimg: true, timerstamp: Date.now(), withCredentials: true, //关键 }) this.qrurl = url.qrimg this.timer = setInterval(async () => { const res = await this.checkStatus(key.data.unikey) if (res.code === 800) { alert('二维码已过期,请重新获取') clearInterval(this.timer) } if (res.code === 803) { // 这一步会返回cookie console.log(res) this.closeCard() this.$message.success('授权登录成功') } }, 3000) }, async checkStatus(key) { const res = await login( `qr/check`, { key, timerstamp: Date.now(), withCredentials: true, //关键} }) return res } } } </script> <style scoped> .QRloginBtn { position: absolute; top: 10px; right: 10px; } >>> .el-input__prefix { transition: all 0s !important; } .el-button.is-circle { padding: 8px; } .el-checkbox { position: relative; left: -15px; margin-top: 30px; line-height: 12px; font-size: 8px !important; -webkit-transform: scale(0.8) !important; } .el-checkbox .el-link { width: auto !important; font-size: 8px; } .el-cascader-menu { width: 450px; } .el-popper { position: absolute; left: 110px !important; } .demo-ruleForm >>> .el-input-group__prepend { background-color: #fff; padding: 0 0 0 30px; } .el-cascader >>> .el-input__inner { border: 0; min-width: 52px !important; padding: 0 24px 0 0 !important; } .phone-number >>> .el-input__inner { padding: 0 0 0 15px; } .input-with-select .el-input-group__prepend { background-color: #fff; } .demo-ruleForm >>> .el-icon-mobile:before { position: relative; left: -83px; } .card { position: absolute; top: 70px; left: 300px; float: left; width: 350px; height: 530px; z-index: 99; background: #ffffff; border-radius: 12px; } .close-button { position: absolute; top: 10px; left: 10px; border: 0; width: 8px; height: 8px; padding: 0; margin: 0; font-size: 16px; } .card .QRhead { margin: 100px 0 30px 0; display: block; width: 100%; text-align: center; font-size: 26px; line-height: 26px; } .card .Applogin { text-align: center; font-size: 14px; line-height: 14px; margin: 0 auto; } .el-image { display: block; text-align: center; margin: 0 auto 20px; } .card p { width: 100%; } .footer { width: 100%; text-align: center; position: absolute; left: 0; bottom: 60px; } .footer :hover { color: #2d2d2d; } .Userlogin { } </style>
1. Explain the different behaviors of ls -l /usr and ls -l /root. => ls -l /usr will show the long listing of files present in usr directory while ls -l /root will show the long listing of files in root directory 2. How can you enter multiple commands in a single line? => we can use (;) between two command or can use (&&) to seperate two commands. 3. How can you enter one command in multiple lines (like ls in one line and -l in the second? => we can use backslash(\) break the command into two lines. 4. . Enter the command wc without any arguments. Write a few lines, and then hit control-d (with the control button pressed, hit d) at the beginning of a new line. See what happens. Explain the output. What does control-d do here? => wc stands for word count, after writing any word or any lines then doing ctrl+d will let u know the (no. of newline character, no. of words , no. of characters(including \n). 5. Repeat the last exercise with cat (without any arguments)? => cat is used to print content of the file (cat <file name>) but here it will reprint what u will write in terminal. 6. What happens if you press control-c instead of control-d? => It will terminate the process. 7. Enter ls -l | wc | wc as a command. Explain the output. => This command is a pipe in which output of first command is passed as input to the other commna ls -l will generate the long listing of file and this group of lines will be read as input for wc and ls -l | wc will generate a one line sentence in which will have the count of new line words and total char, this one line will be passed to wc as an argument and it will print ( 1 3 (total char in ls -l | wc) ) 8. Go to a directory that contains both regular files and subdirectories. Type the following commands and explain the differences: du, du -a, du -s, du -sk, du -sm,and du -sh. Explain the outputs. => du stands for disk usage, it shows the disk usage(in blocks) of the files and directory{du: shows disk usage of current directory and sub-directory; du -a: it shows disk usage of all the files whose location starts from ./(means all the files in the directory and sub-directory); du -s: total disk usage of the directory; du -sk:disk usage in kilbytes 9. Explain why the count of links to a directory is always > 2 (look at the number appearing immediately after the permissions, in each line of ls -l). => Because every directory contains atleast two subdirectory (. and ..) that's why link of count for any directory is greater than 2. 10. Create a non-empty text file testfile.txt. See the directory listing using ls -l. Then type the command ln -s testfile.txt T. Do ls -l again. Whatis the permission of T? Try changing the permission of T as chmod 000 T. What happens? Why? Remove T. What happens? Create another symbolic link TT to testfile.txt. Remove testfile.txt. What happens? => ln -s testfile.txt T will create a linker 'T' to the text file, it is same like reference in cpp if the permission of T is changed then permission of .txt will also be changed and if we remove the file and try to acess using linker it will give error as broken link as the file is removed. 11. Create a text file abc.txt. See the directory listing. Then enter the command ln abc.txt ABC.txt. Again see the directory listing. What are the differences? Explain. Add some extra lines to abc.txt. Again see the directory listing. Explain the changes.Remove the original file abc.txt. Explain what the directory listing shows => ls abc.txt Abc.txt will create a hard link means both file will be linked to the same memory as if u will change the content of file other will be changed sync. and if u remove one file still memory is linked to other file.
<?php namespace Controller; use App\Session; use App\AbstractController; use App\ControllerInterface; use Model\Entities\Category; use Model\Managers\CategoryManager; use Model\Managers\TopicManager; use Model\Managers\MessageManager; use Model\Managers\UserManager; class CategoryController extends AbstractController implements ControllerInterface { public function index() { $categoryManager = new CategoryManager(); return [ "view" => VIEW_DIR."category/listCategories.php", "data" => [ "categories" => $categoryManager->findAll(["nameCategory", "ASC"]) ] ]; } public function detailCategory($id) { $topicManager = new TopicManager(); $categoryManager = new CategoryManager(); return [ "view" => VIEW_DIR."category/detailCategory.php", "data" => [ "detail" => $topicManager->findTopicsByCategory($id), "category" => $categoryManager->findOneById($id) ] ]; } public function addCategory() { $categoryManager = new CategoryManager(); if(isset($_POST['submit'])) { $nameCategory = filter_input(INPUT_POST, 'name_category', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $nameCategory = $_POST["name_category"]; if($nameCategory) { $categoryManager->add([ 'nameCategory' => $nameCategory ]); $this->redirectTo("category", "listCategories"); } } } public function addTopicByCategory($id){ if(isset($_POST['submit'])){ $titleTopic = filter_input(INPUT_POST, 'title_topic', FILTER_SANITIZE_FULL_SPECIAL_CHARS); $message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_FULL_SPECIAL_CHARS); // var_dump($titleTopic); // var_dump($message); // die; // $titleTopic = $_POST["title_topic"]; // $message = $_POST["message"]; if($titleTopic && $message){ $topicManager = new TopicManager(); $messageManager = new MessageManager(); $idTopic = $topicManager->add([ 'title' => $titleTopic, 'user_id' => 1, 'category_id' => $id ]); $messageManager->add([ 'text' => $message, 'topic_id' => $idTopic, 'user_id' => 1 ]); } } $this->redirectTo("category", "detailCategory", $id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpPluginLoader.Core.Memory; namespace SharpPluginLoader.Core.Networking { /// <summary> /// Provides access to the game's networking system. /// </summary> public static class Network { /// <summary> /// The sMhNetwork singleton instance. /// </summary> public static MtObject SingletonInstance => SingletonManager.GetSingleton("sMhNetwork")!; /// <summary> /// Sends a packet to other people in the specified session. /// </summary> /// <param name="packet">The packet to send.</param> /// <param name="broadcast">Whether or not to broadcast the packet to everyone in the session.</param> /// <param name="memberIndex">If <paramref name="broadcast"/> is false, the index of the member to send the packet to.</param> /// <param name="targetSession">The session to send the packet to.</param> public static unsafe void SendPacket(IPacket packet, bool broadcast = true, uint memberIndex = 0, SessionIndex targetSession = SessionIndex.Current) { var assembledPacket = PacketBuilder.Build(packet); fixed (byte* ptr = assembledPacket.Buffer) { var dst = broadcast ? 0xC0 : memberIndex; var option = broadcast ? 0x10u : 0x30u; SendPacketFunc.Invoke(SingletonInstance.Instance, (nint)ptr, dst, option, (uint)targetSession); } } #region Internal private static void SendPacketHook(nint instance, nint packet, uint dst, uint option, uint sessionIndex) { var packetObj = new Packet(packet); var isBroadcast = (option & 0x20) == 0 && dst > 0x40; foreach (var plugin in PluginManager.Instance.GetPlugins(p => p.OnSendPacket)) plugin.OnSendPacket(packetObj, isBroadcast, (SessionIndex)sessionIndex); _sendPacketHook.Original(instance, packet, dst, option, sessionIndex); } private static unsafe void ReceivePacketHook(nint instance, int src, nint data, int dataSize) { var dataOffset = 6; var buffer = new NetBuffer(new ReadOnlySpan<byte>((void*)data, dataSize)); var id = buffer.ReadUInt32(); var session = buffer.ReadByte(); var type = buffer.ReadByte(); if (id == Utility.MakeDtiId("cPacketBase")) // Decoy Header { id = buffer.ReadUInt32(); session = buffer.ReadByte(); type = buffer.ReadByte(); dataOffset += 6; } var offsettedData = new ReadOnlySpan<byte>((void*)(data + dataOffset), dataSize - dataOffset); foreach (var plugin in PluginManager.Instance.GetPlugins(p => p.OnReceivePacket)) plugin.OnReceivePacket(id, (PacketType)type, (SessionIndex)session, new NetBuffer(offsettedData)); _receivePacketHook.Original(instance, src, data, dataSize); } internal static void Initialize() { _sendPacketHook = new Hook<SendPacketDelegate>(SendPacketHook, AddressRepository.Get("Network:SendPacket")); _receivePacketHook = new Hook<ReceivePacketDelegate>(ReceivePacketHook, AddressRepository.Get("Network:ReceivePacket")); } private delegate void SendPacketDelegate(nint instance, nint packet, uint dst, uint option, uint sessionIndex); private delegate void ReceivePacketDelegate(nint instance, int src, nint data, int dataSize); private static Hook<SendPacketDelegate> _sendPacketHook = null!; private static Hook<ReceivePacketDelegate> _receivePacketHook = null!; private static readonly NativeAction<nint, nint, uint, uint, uint> SendPacketFunc = new(AddressRepository.Get("Network:SendPacket")); #endregion } }
import React from 'react' import TextField from '@mui/material/TextField'; import MenuItem from '@mui/material/MenuItem'; const SavingsFilter = ({ filterCriteria, setFilterCriteria }) => { const handleDateFromChange = (event) => { setFilterCriteria({ ...filterCriteria, dateFrom: event.target.value }); } const handleDateToChange = (event) => { setFilterCriteria({ ...filterCriteria, dateTo: event.target.value }); } const handleStatusChange = (e)=> { setFilterCriteria({...filterCriteria, status: e.target.value}) } return ( <div> <TextField type="date" label="Date From" value={filterCriteria.dateFrom} onChange={handleDateFromChange} variant="outlined" InputLabelProps={{ shrink: true }} /> <TextField type="date" label="Date To" value={filterCriteria.dateTo} onChange={handleDateToChange} variant="outlined" InputLabelProps={{ shrink: true }} /> <TextField select label="Status" value={filterCriteria.status} onChange={handleStatusChange} variant="outlined" > <MenuItem value="">All</MenuItem> <MenuItem value="Yet to Start">Yet to Start</MenuItem> <MenuItem value="In Progress">In Progress</MenuItem> <MenuItem value="Completed">Completed</MenuItem> <MenuItem value="Abandoned">Abandoned</MenuItem> <MenuItem value="On Hold">On Hold</MenuItem> </TextField> </div> ) } export default SavingsFilter
# Common Mistakes ## Not Considering Imbalance in Even and Odd Cases During Dynamic Programming (DP) When working with Dynamic Programming (DP), it's crucial to take into account the differences between even and odd cases. In some situations, it is more efficient to handle evenly divided even cases and single odd cases separately, rather than treating them all uniformly. - **Bad Case: Recursively Handling Odd Cases That Generate Two Recursive Function Calls** ```cpp matrix ret; if (b % 2 == 0) { matrix mm = m*m; ret = solve(mm, b / 2); } else { ret = solve(mm, b / 2) * solve(mm, b / 2 + 1); } ``` In this approach, when 'b' is an odd number, the odd case generates two separate recursive function calls, which can lead to inefficiency. - **Good Case: Handling Odd Cases at Once** ```cpp matrix ret; matrix mm = m*m; if (b % 2 == 0) { ret = solve(mm, b / 2); } else { ret = solve(mm, b / 2) * m; } ``` In the improved approach, we precompute 'mm' before the conditional statement, and when 'b' is odd, we handle the odd case directly by multiplying 'mm' by 'm' without generating two separate recursive calls. This optimization can significantly enhance the efficiency of your dynamic programming solution.
package visualization; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import java.awt.*; public class BarChart { ChartPanel frame1; public BarChart(){ CategoryDataset dataset = getDataSet(); JFreeChart chart = ChartFactory.createBarChart3D( "共享单车", // 图表标题 "单车种类", // 目录轴的显示标签 "数量", // 数值轴的显示标签 dataset, // 数据集 PlotOrientation.VERTICAL, // 图表方向:水平、垂直 true, // 是否显示图例(对于简单的柱状图必须是false) false, // 是否生成工具 false // 是否生成URL链接 ); //从这里开始 CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象 CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表 domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题 domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题 ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状 rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15)); chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15)); chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体 //到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题 frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame } private static CategoryDataset getDataSet() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100, "北京", "ofo"); dataset.addValue(100, "上海", "ofo"); dataset.addValue(100, "广州", "ofo"); dataset.addValue(200, "北京", "酷奇"); dataset.addValue(200, "上海", "酷奇"); dataset.addValue(200, "广州", "酷奇"); dataset.addValue(300, "北京", "青桔"); dataset.addValue(300, "上海", "青桔"); dataset.addValue(300, "广州", "青桔"); dataset.addValue(400, "北京", "摩拜"); dataset.addValue(400, "上海", "摩拜"); dataset.addValue(400, "广州", "摩拜"); dataset.addValue(500, "北京", "二八大杠"); dataset.addValue(500, "上海", "二八大杠"); dataset.addValue(500, "广州", "二八大杠"); return dataset; } public ChartPanel getChartPanel(){ return frame1; } }
<?php class PartFutbol extends Partido { private $cofMenores; private $cofJuveniles; private $cofMayores; public function __construct($idPartido, $fecha, $objEquipo1, $cantGolesE1, $objEquipo2, $cantGolesEquipo2) { parent::__construct($idPartido, $fecha, $objEquipo1, $cantGolesE1, $objEquipo2, $cantGolesEquipo2); $this->cofMenores = 0.13; $this->cofJuveniles = 0.19; $this->cofMayores = 0.27; } public function getCofMenores() { return $this->cofMenores; } public function setCofMenores($value) { $this->cofMenores = $value; } public function getCofJuveniles() { return $this->cofJuveniles; } public function setCofJuveniles($value) { $this->cofJuveniles = $value; } public function getCofMayores() { return $this->cofMayores; } public function setCofMayores($value) { $this->cofMayores = $value; } public function __toString() { $cadena = parent::__toString(); $cadena .= "Cof Menores :" . $this->getCofMenores() . "\n" . "Cof juveniles :" . $this->getCofJuveniles() . "\n" . "Cof mayores :" . $this->getCofMayores() . "\n"; return $cadena; } public function coeficientePartido() { $cantGoles = $this->getCantGolesE1() + $this->getCantGolesE2(); $jugadores = $this->getObjEquipo1()->getCantJugadores() + $this->getObjEquipo2()->getCantJugadores(); if ($this->getCofMenores()) { $result = $this->getCofMenores() * $cantGoles * $jugadores; } elseif ($this->getCofJuveniles()) { $result = $this->getCofJuveniles() * $cantGoles * $jugadores; } elseif ($this->getCofMayores()) { $result = $this->getCofMayores() * $cantGoles * $jugadores; } return $result; } }
package study.webboard.board.Dto; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import study.webboard.board.entity.Company; @Getter @NoArgsConstructor @Data public class CompanyDetailDto { private Long comId; private String comName; private String comCountry; private String comArea; private String comPosition; private Long comCompensation; private String comStack; private String comContent; @Builder public CompanyDetailDto(Long comId, String comName, String comCountry, String comArea, String comPosition, Long comCompensation, String comStack, String comContent) { this.comId = comId; this.comName = comName; this.comCountry = comCountry; this.comArea = comArea; this.comPosition = comPosition; this.comCompensation = comCompensation; this.comStack = comStack; this.comContent = comContent; } public CompanyDetailDto(Company company) { comId=company.getId(); comName=company.getName(); comCountry=company.getCountry(); comArea=company.getArea(); comPosition=company.getPosition(); comCompensation = company.getCompensation(); comStack = company.getStack(); comContent = company.getContent(); } }
###1.Show the total number of prizes awarded.### SELECT COUNT(winner) FROM nobel; ###2.List each subject - just once### SELECT DISTINCT subject FROM nobel; ###3.Show the total number of prizes awarded for Physics.### SELECT COUNT(*) FROM nobel WHERE subject = 'Physics'; ###4.For each subject show the subject and the number of prizes.### SELECT subject, COUNT(*) FROM nobel GROUP BY subject ###5.For each subject show the first year that the prize was awarded.### SELECT subject, MIN(yr) FROM nobel GROUP BY subject ###6.For each subject show the number of prizes awarded in the year 2000.### SELECT subject, COUNT(*) FROM nobel WHERE yr = 2000 GROUP BY subject ###7.Show the number of different winners for each subject.### SELECT subject, COUNT(DISTINCT winner) FROM nobel GROUP BY subject ###8.For each subject show how many years have had prizes awarded### SELECT subject, COUNT(DISTINCT yr) FROM nobel GROUP BY subject ###9.Show the years in which three prizes were given for Physics### SELECT yr FROM nobel WHERE subject='Physics' GROUP BY yr HAVING COUNT(yr)=3 ###10.Show winners who have won more than once### SELECT winner FROM nobel GROUP BY winner HAVING COUNT(winner) >1 ###11.Show winners who have won more than one subject.### SELECT winner FROM nobel GROUP BY winner HAVING COUNT(DISTINCT subject) >1 ###12.Show the year and subject where 3 prizes were given. Show only years 2000 onwards.### SELECT yr, subject FROM nobel WHERE yr >= 2000 GROUP BY yr, subject HAVING COUNT(subject) =3
package com.github.GuilhermeBauer.Ecommerce.services; import com.github.GuilhermeBauer.Ecommerce.controller.CartItemController; import com.github.GuilhermeBauer.Ecommerce.data.vo.v1.CartItemVO; import com.github.GuilhermeBauer.Ecommerce.exceptions.CartItemNotFound; import com.github.GuilhermeBauer.Ecommerce.exceptions.InsufficientQuantityAvailable; import com.github.GuilhermeBauer.Ecommerce.exceptions.ProductNotFound; import com.github.GuilhermeBauer.Ecommerce.exceptions.RequiredObjectsNullException; import com.github.GuilhermeBauer.Ecommerce.mapper.Mapper; import com.github.GuilhermeBauer.Ecommerce.model.CartItemModel; import com.github.GuilhermeBauer.Ecommerce.model.ProductModel; import com.github.GuilhermeBauer.Ecommerce.repository.CartItemRepository; import com.github.GuilhermeBauer.Ecommerce.repository.ProductRepository; import com.github.GuilhermeBauer.Ecommerce.services.contract.ServicesDatabaseContract; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @Service public class CartItemServices implements ServicesDatabaseContract<CartItemVO> { private static final String PRODUCT_NOT_FOUND_MESSAGE = "No product was found for that ID!"; private static final String CART_ITEM_NOT_FOUND_MESSAGE = "No cart item was found for that ID!"; private static final String INSUFFICIENT_AVAILABLE_QUANTITY_MESSAGE = "Don't have enough quantity available"; private static final String QUANTITY_MESSAGE = "Please type a quantity plus to 0!"; @Autowired private CartItemRepository repository; @Autowired private ProductRepository productRepository; @Override public CartItemVO create(CartItemVO cartItemVO) throws Exception { if (cartItemVO == null) { throw new RequiredObjectsNullException(); } cartItemHadQuantityAvailable(cartItemVO); CartItemModel entity = Mapper.parseObject(cartItemVO, CartItemModel.class); ProductModel productModel = productRepository.findById(cartItemVO.getProduct().getId()) .orElseThrow(() -> new ProductNotFound(PRODUCT_NOT_FOUND_MESSAGE)); entity.setProduct(productModel); checkIfQuantityIsLess(cartItemVO, entity); CartItemVO vo = Mapper.parseObject(repository.save(entity), CartItemVO.class); vo.add(linkTo(methodOn(CartItemController.class).findById(cartItemVO.getId())).withSelfRel()); return vo; } @Override public Page<EntityModel<CartItemVO>> findAll(Pageable pageable) throws Exception { Page<CartItemModel> allCartItems = repository.findAll(pageable); List<CartItemVO> cartItems = Mapper.parseObjectList(allCartItems.getContent(), CartItemVO.class); List<EntityModel<CartItemVO>> cartItemEntities = new ArrayList<>(); for (CartItemVO cartItemVO : cartItems) { Link selfLink = linkTo( methodOn(CartItemController.class) .findById(cartItemVO.getId())).withSelfRel(); EntityModel<CartItemVO> apply = EntityModel.of(cartItemVO, selfLink); cartItemEntities.add(apply); } return new PageImpl<>(cartItemEntities, pageable, allCartItems.getTotalElements()); } @Override public CartItemVO update(CartItemVO cartItemVO) throws Exception { if (cartItemVO == null) { throw new RequiredObjectsNullException(); } CartItemModel entity = repository.findById(cartItemVO.getId()) .orElseThrow(() -> new CartItemNotFound(CART_ITEM_NOT_FOUND_MESSAGE)); checkIfQuantityIsLess(cartItemVO, entity); if (cartItemVO.getQuantity() > 1) { entity.setQuantity(cartItemVO.getQuantity()); } CartItemVO vo = Mapper.parseObject(repository.save(entity), CartItemVO.class); vo.add(linkTo(methodOn(CartItemController.class).findById(cartItemVO.getId())).withSelfRel()); return vo; } @Override public CartItemVO findById(UUID uuid) throws Exception { CartItemModel entity = repository.findById(uuid) .orElseThrow(() -> new CartItemNotFound(CART_ITEM_NOT_FOUND_MESSAGE)); CartItemVO vo = Mapper.parseObject(entity, CartItemVO.class); Link selfLink = linkTo(methodOn(CartItemController.class).findById(uuid)).withSelfRel(); vo.add(selfLink); return vo; } @Override public void delete(UUID uuid) throws Exception { CartItemModel entity = repository.findById(uuid) .orElseThrow(() -> new ProductNotFound(PRODUCT_NOT_FOUND_MESSAGE)); repository.delete(entity); } public void cartItemHadQuantityAvailable(CartItemVO cartItemVO) { if (cartItemVO.getQuantity() <= 0) { throw new InsufficientQuantityAvailable(QUANTITY_MESSAGE); } } public void checkIfQuantityIsLess(CartItemVO cartItemVO, CartItemModel cartItem) { if (cartItemVO == null || cartItemVO.getQuantity() == null || cartItem == null || cartItem.getProduct() == null || cartItem.getProduct().getQuantity() == null) { throw new RequiredObjectsNullException(); } if (cartItemVO.getQuantity() > cartItem.getProduct().getQuantity()) { throw new InsufficientQuantityAvailable(INSUFFICIENT_AVAILABLE_QUANTITY_MESSAGE); } } }
package ua.klesaak.mineperms.manager.storage.sql; import com.zaxxer.hikari.HikariDataSource; import lombok.Getter; import ua.klesaak.mineperms.manager.storage.StorageType; import ua.klesaak.mineperms.manager.storage.sql.driver.AbstractConnectionFactory; import ua.klesaak.mineperms.manager.storage.sql.driver.MariaDbConnectionFactory; import ua.klesaak.mineperms.manager.storage.sql.driver.MySqlConnectionFactory; import ua.klesaak.mineperms.manager.storage.sql.driver.PostgresConnectionFactory; @Getter public class SQLConfig { private final String username, password, database, address, groupsPermissionsTableSuffix; private final int port; private final boolean isUseSSL; public SQLConfig(String username, String password, String database, String address, String groupsTableSuffix, int port, boolean isUseSSL) { this.username = username; this.password = password; this.database = database; this.address = address; this.groupsPermissionsTableSuffix = groupsTableSuffix; this.port = port; this.isUseSSL = isUseSSL; } public HikariDataSource getSource(StorageType storageType) { AbstractConnectionFactory connectionFactory = new MySqlConnectionFactory(null, null, null, null, null, false); switch (storageType) { case MYSQL: { connectionFactory = new MySqlConnectionFactory(this.username, this.password, this.address, String.valueOf(this.port), this.database, this.isUseSSL); break; } case MARIADB: { connectionFactory = new MariaDbConnectionFactory(this.username, this.password, this.address, String.valueOf(this.port), this.database, this.isUseSSL); break; } case POSTGRESQL: { connectionFactory = new PostgresConnectionFactory(this.username, this.password, this.address, String.valueOf(this.port), this.database, this.isUseSSL); } } return new HikariDataSource(connectionFactory.getHikariConfig()); } @Override public String toString() { return "MySQLConfig{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", database='" + database + '\'' + ", address='" + address + '\'' + ", groupsPermissionsTableSuffix='" + groupsPermissionsTableSuffix + '\'' + ", port=" + port + ", isUseSSL=" + isUseSSL + '}'; } }
"use strict"; const quoteContainer = document.getElementById("quote-container"); const quoteText = document.getElementById("quote"); const authorText = document.getElementById("author"); const twitterBtn = document.getElementById("twitter"); const newQuoteBtn = document.getElementById("new-quote"); const loader = document.getElementById("loader"); let apiQuotes = []; function showLoadingSpinner() { loader.hidden = false; quoteContainer.hidden = true; } function removeLoadingSpinner() { loader.hidden = true; quoteContainer.hidden = false; } // Show new quote function function newQuote() { showLoadingSpinner(); // pick a random quote from apiQuotes array const quote = apiQuotes[Math.floor(Math.random() * apiQuotes.length)]; console.log(quote); // check if author field is blank and if so replace it with 'Unknown' if (!quote.author) { authorText.textContent = "Unknown"; } else { authorText.textContent = quote.author; } // check the quote length to determine the styling if (quote.length > 120) { quoteText.classList.add("long-quote"); } else { quoteText.classList.remove("long-quote"); } quoteText.textContent = quote.text; removeLoadingSpinner(); } // Get Quotes from an API async function getQuotes() { showLoadingSpinner(); const apiUrl = "https://type.fit/api/quotes"; try { const response = await fetch(apiUrl); apiQuotes = await response.json(); newQuote(); } catch (error) { console.error("Whoops, something went wrong - Try again !", error); } } // Tweet/share quote on twitter function tweetQuote() { const twitterUrl = `https://twitter.com/intent/tweet?text=${quoteText.textContent} - ${authorText.textContent}`; window.open(twitterUrl, "_blank"); } // Event Listeners newQuoteBtn.addEventListener("click", getQuotes); twitterBtn.addEventListener("click", tweetQuote); // On page Loading getQuotes();
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ProfileModule } from './modules/profile/profile.module'; import { ArticlesModule } from './modules/articles/articles.module'; import { AuthModule } from './modules/auth/auth.module'; import { FavoritedArticlesComponent } from './modules/profile/components/favorited-articles/favorited-articles.component'; import { MyArticlesComponent } from './modules/profile/components/my-articles/my-articles.component'; import { ProfilePageComponent } from './modules/profile/pages/profile-page/profile-page.component'; import { LoginPageComponent } from './modules/auth/pages/login-page/login-page.component'; import { RegisterPageComponent } from './modules/auth/pages/register-page/register-page.component'; import { ArticlePageComponent } from './modules/articles/pages/article-page/article-page.component'; import { HomePageComponent } from './modules/articles/pages/home-page/home-page.component'; import { EditorPageComponent } from './modules/articles/pages/editor-page/editor-page.component'; import { SettingsPageComponent } from './modules/profile/pages/settings-page/settings-page.component'; import { AlreadyAuthenticatedGuard } from './modules/auth/guards/already-authenticated.guard'; import { NotAuthenticatedGuard } from './modules/auth/guards/not-authenticated.guard'; const routes: Routes = [ { path: '', component: HomePageComponent }, { path: 'login', component: LoginPageComponent, canActivate: [AlreadyAuthenticatedGuard], }, { path: 'register', component: RegisterPageComponent, canActivate: [AlreadyAuthenticatedGuard], }, { path: 'article/:slug', component: ArticlePageComponent, }, { path: 'editor', component: EditorPageComponent, canActivate: [NotAuthenticatedGuard], }, { path: 'editor/:slug', component: EditorPageComponent, canActivate: [NotAuthenticatedGuard], }, { path: 'profile/:username', component: ProfilePageComponent, children: [ { path: '', component: MyArticlesComponent }, { path: 'favorites', component: FavoritedArticlesComponent }, ], }, { path: 'settings', component: SettingsPageComponent, canActivate: [NotAuthenticatedGuard], }, { path: '**', redirectTo: '/' }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
// import 'package:acyuta/pages/manualinput.dart'; import 'dart:typed_data'; import 'package:acyuta/getimage/getimage.dart'; import 'package:acyuta/pages/manualinput.dart'; import 'package:acyuta/pages/shcdetail.dart'; // import 'package:acyuta/textrecog/textrecog.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; class Upload extends StatefulWidget { const Upload({super.key}); @override State<Upload> createState() => _UploadState(); } late Uint8List uploadedimage; bool found = false; const titleStyle = TextStyle(fontWeight: FontWeight.w600, color: Colors.black, fontSize: 20); class _UploadState extends State<Upload> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color.fromARGB(255, 68, 121, 96), appBar: AppBar( leading: const BackButton( color: Colors.black, ), backgroundColor: Colors.greenAccent, title: const Text( "अच्युता", style: TextStyle( color: Colors.black, fontSize: 30, fontWeight: FontWeight.w500), ), ), body: ListView( children: [ const SizedBox( height: 20, ), GestureDetector( onTap: () { showDialog( context: context, builder: (context) { return AlertDialog( backgroundColor: Colors.greenAccent, icon: Image.asset("assets/infor.jpg"), title: const Text( "मृदा स्वास्थ्य कार्ड अपलोड करने के लिए कृपया एक विकल्प चुनें ", style: TextStyle(color: Colors.black), ), content: const Text( "कृपया सुनिश्चित करें कि आपके द्वारा अपलोड किया गया फोटो ठीक से ज़ूम या क्रॉप किया जाना चाहिए ताकि केवल ये मान चित्र में हों या कम से कम मानों के बाईं ओर कुछ भी नहीं होना चाहिए|\nPlease make ensure the photo you upload should be zoomed or cropped properly so that only these values should be in the picture or atleast nothing should be on left side of the values.", style: TextStyle( color: Colors.red, fontWeight: FontWeight.w600), ), actions: [ IconButton( //! onPressed: () async { final image = await pickImage(ImageSource.camera); if (image == null) { // ignore: use_build_context_synchronously ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( "No image found (कोई चित्र नहीं मिला)"))); } setState(() { uploadedimage = image; found = true; Navigator.of(context).push(MaterialPageRoute( builder: (context) => const ShcDetail())); }); }, icon: const Icon( Icons.camera_alt_outlined, size: 50, color: Colors.black, )), const SizedBox( height: 20, ), //! IconButton( onPressed: () async { final image = await pickImage(ImageSource.gallery); if (image == null) { // ignore: use_build_context_synchronously ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( "No image found (कोई चित्र नहीं मिला)"))); } setState(() { uploadedimage = image; found = true; Navigator.of(context).push(MaterialPageRoute( builder: (context) => const ShcDetail())); }); }, icon: const Icon( Icons.file_copy_outlined, size: 50, color: Colors.black, )), const SizedBox( height: 20, ), TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text( "रद्द करें", style: TextStyle(color: Colors.red), )), ], ); }, ); }, child: Image.asset("assets/uploadimage.png")), const SizedBox( height: 30, ), GestureDetector( onTap: () { showDialog( context: context, builder: (context) { return AlertDialog( backgroundColor: Colors.greenAccent, icon: Image.asset("assets/infor.jpg"), title: const Text( "मृदा स्वास्थ्य कार्ड अपलोड करने के लिए कृपया एक विकल्प चुनें", style: TextStyle(color: Colors.black), ), content: const Text( " कृपया सुनिश्चित करें कि आपके द्वारा अपलोड किया गया फोटो ठीक से ज़ूम या क्रॉप किया जाना चाहिए ताकि केवल ये मान चित्र में हों या कम से कम मानों के बाईं ओर कुछ भी नहीं होना चाहिए|\nPlease make ensure the photo you upload should be zoomed or cropped properly so that only these values should be in the picture or atleast nothing should be on left side of the values.", style: TextStyle( color: Colors.red, fontWeight: FontWeight.w600), ), actions: [ IconButton( //! onPressed: () async { final image = await pickImage(ImageSource.camera); if (image == null) { // ignore: use_build_context_synchronously ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( "No image found (कोई चित्र नहीं मिला)"))); } setState(() { uploadedimage = image; found = true; Navigator.of(context).push(MaterialPageRoute( builder: (context) => const ShcDetail())); }); }, icon: const Icon( Icons.camera_alt_outlined, size: 50, color: Colors.black, )), const SizedBox( height: 20, ), //! IconButton( onPressed: () async { final image = await pickImage(ImageSource.gallery); if (image == null) { // ignore: use_build_context_synchronously ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( "No image found (कोई चित्र नहीं मिला)"))); } setState(() { uploadedimage = image; found = true; Navigator.of(context).push(MaterialPageRoute( builder: (context) => const ShcDetail())); }); }, icon: const Icon( Icons.file_copy_outlined, size: 50, color: Colors.black, )), const SizedBox( height: 20, ), TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text( "रद्द करें", style: TextStyle(color: Colors.red), )), ], ); }, ); }, child: const Card( color: Colors.greenAccent, child: Column( children: [ Padding( padding: EdgeInsets.all(8.0), child: Text( "Upload Your Soil Health Card", style: titleStyle, ), ), Padding( padding: EdgeInsets.all(8.0), child: Text( "अपना मृदा स्वास्थ्य कार्ड अपलोड करें", style: titleStyle, ), ), ], ), ), ), const SizedBox( height: 30, ), GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => const ManualInput(), ), ); }, child: const Padding( padding: EdgeInsets.all(8.0), child: Card( elevation: 5, color: Colors.greenAccent, child: Column( children: [ Padding( padding: EdgeInsets.all(8.0), child: Text( "Upload Soil Health Card Manually ", style: titleStyle, ), ), Padding( padding: EdgeInsets.all(8.0), child: Text( "अपना मृदा स्वास्थ्य कार्ड लिखकर अपलोड करें", style: titleStyle, ), ), ], ), ), ), ) ], ), ); } }
# -*- coding: utf-8 -*- import json import mock from nose.tools import eq_ from passport.backend.api.test.mock_objects import mock_headers from passport.backend.api.test.views import ( BaseTestViews, ViewsTestEnvironment, ) import passport.backend.core.authtypes as authtypes from passport.backend.core.builders import blackbox from passport.backend.core.builders.blackbox.faker.blackbox import ( blackbox_createsession_response, blackbox_editsession_response, blackbox_lrandoms_response, blackbox_sessionid_multi_response, blackbox_userinfo_response, ) from passport.backend.core.cookies import ( cookie_l, cookie_lah, cookie_y, ) from passport.backend.core.historydb.entry import AuthEntry from passport.backend.core.logging_utils.helpers import mask_sessionid from passport.backend.core.test.test_utils.mock_objects import mock_grants from passport.backend.core.test.test_utils.utils import ( check_all_url_params_match, check_url_contains_params, with_settings_hosts, ) from passport.backend.core.test.time_utils.time_utils import TimeNow from passport.backend.utils.common import merge_dicts TEST_UID = 1 TEST_HOST = '.yandex.ru' TEST_USER_IP = '127.0.0.1' TEST_USER_AGENT = 'curl' TEST_YANDEXUID_COOKIE = 'cookie_yandexuid' TEST_USER_COOKIES = 'yandexuid=%s' % TEST_YANDEXUID_COOKIE TEST_REFERER = 'http://passportdev-python.yandex.ru/passport?mode=passport' EXPECTED_SESSIONID_COOKIE = u'Session_id=2:session; Domain=.yandex.ru; Secure; HttpOnly; Path=/' EXPECTED_SESSIONID_SECURE_COOKIE = u'sessionid2=2:sslsession; Domain=.yandex.ru; Expires=Mon, 10 Jun 2013 14:33:47 GMT; Secure; HttpOnly; Path=/' EXPECTED_AUTH_ID = '123:1422501443:126' COOKIE_L_VALUE = 'VFV5DX94f0RRfXFTXVl5YH8GB2F6VlJ7XzNUTyYaIB1HBlpZBSd6QFkfOAJ7OgEACi5QFlIEGUM+KjlhRgRXZw==.1376993918.1002323.298859.ee75287c1d\ fd8b073375aee93158eb5b' EXPECTED_L_COOKIE = u'L=%s; Domain=.yandex.ru; Expires=Tue, 19 Jan 2038 03:14:07 GMT; Path=/' % COOKIE_L_VALUE COOKIE_YP_VALUE = '1692607429.udn.bG9naW4%3D%0A' EXPECTED_YP_COOKIE = u'yp=%s; Domain=.yandex.ru; Expires=Tue, 19 Jan 2038 03:14:07 GMT; Secure; Path=/' % COOKIE_YP_VALUE COOKIE_YS_VALUE = 'udn.bG9naW4%3D%0A' EXPECTED_YS_COOKIE = u'ys=%s; Domain=.yandex.ru; Secure; Path=/' % COOKIE_YS_VALUE EXPECTED_YANDEX_LOGIN_COOKIE = u'yandex_login=test; Domain=.yandex.ru; Max-Age=31536000; Secure; Path=/' COOKIE_LAH_VALUE = 'OG5EOF8wU_bOAGhjXFp7YXkHAGB9UVFyB2IACGZedV4DWl8FWXF5BgJXYFVzYQVKV3kFVlpaU0p2f31iRkZRYQ.1473090908.1002323.1.2fe2104fff29aa69e867d7d1ea601470' COOKIE_LAH_TEMPLATE = u'lah=%s; Domain=.passport-test.yandex.ru; Expires=Tue, 19 Jan 2038 03:14:07 GMT; Secure; HttpOnly; Path=/' EXPECTED_LAH_COOKIE = COOKIE_LAH_TEMPLATE % COOKIE_LAH_VALUE EXPECTED_SESSGUARD_COOKIE = u'sessguard=1.sessguard; Domain=.passport-test.yandex.ru; Secure; HttpOnly; Path=/' TEST_SESSIONID = '0:old-session' TEST_USER_COOKIES_WITH_SESSION = TEST_USER_COOKIES + ';Session_id=%s' % TEST_SESSIONID MDA2_BEACON_VALUE = '1551270703270' EXPECTED_MDA2_BEACON_COOKIE = u'mda2_beacon=%s; Domain=.passport-test.yandex.ru; Secure; Path=/' % MDA2_BEACON_VALUE def build_headers(cookie=TEST_USER_COOKIES): return mock_headers( host=TEST_HOST, user_ip=TEST_USER_IP, user_agent=TEST_USER_AGENT, cookie=cookie, referer=TEST_REFERER, ) class BaseTestSessionCreate(BaseTestViews): def setUp(self): self.env = ViewsTestEnvironment() self.env.start() self.env.grants.set_grants_return_value(mock_grants(grants={'session': ['create']})) self.track_manager, self.track_id = self.env.track_manager.get_manager_and_trackid('authorize') with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.uid = TEST_UID track.login = 'test' track.human_readable_login = 'test' track.machine_readable_login = 'test' track.language = 'ru' track.allow_authorization = True track.have_password = True track.is_password_passed = True track.auth_method = 'password' self.env.blackbox.set_blackbox_lrandoms_response_value(blackbox_lrandoms_response()) self.env.blackbox.set_blackbox_response_value( 'userinfo', blackbox_userinfo_response(uid=TEST_UID), ) self._cookie_l_pack = mock.Mock(return_value=COOKIE_L_VALUE) self._cookie_ys_pack = mock.Mock(return_value=COOKIE_YS_VALUE) self._cookie_yp_pack = mock.Mock(return_value=COOKIE_YP_VALUE) self._cookie_lah_pack = mock.Mock(return_value=COOKIE_LAH_VALUE) self.patches = [] cookies_patches = [ mock.patch.object( cookie_l.CookieL, 'pack', self._cookie_l_pack, ), mock.patch.object( cookie_y.SessionCookieY, 'pack', self._cookie_ys_pack, ), mock.patch.object( cookie_y.PermanentCookieY, 'pack', self._cookie_yp_pack, ), mock.patch.object( cookie_lah.CookieLAH, 'pack', self._cookie_lah_pack, ), mock.patch( 'passport.backend.api.common.authorization.generate_cookie_mda2_beacon_value', return_value=MDA2_BEACON_VALUE, ), ] self.patches += cookies_patches for patch in self.patches: patch.start() def tearDown(self): for patch in reversed(self.patches): patch.stop() self.env.stop() del self.env del self.patches del self.track_manager del self._cookie_l_pack del self._cookie_yp_pack del self._cookie_ys_pack del self._cookie_lah_pack def build_auth_log_entry(self, status, uid, login, comment): return [ ('login', login), ('type', authtypes.AUTH_TYPE_WEB), ('status', status), ('uid', uid), ('useragent', TEST_USER_AGENT), ('yandexuid', TEST_YANDEXUID_COOKIE), ('comment', comment), ] def build_auth_log_entries(self, *args): entries = [ ('login', 'test'), ('type', authtypes.AUTH_TYPE_WEB), ('status', 'ses_create'), ('uid', '1'), ('useragent', TEST_USER_AGENT), ('yandexuid', TEST_YANDEXUID_COOKIE), ] entries += args return entries def session_create_request(self, data, headers): return self.env.client.post( '/1/session/?consumer=dev', data=data, headers=headers, ) def query_params(self): return { 'track_id': self.track_id, } def assert_createsession_called(self, call_index=1, password_check_time_is_sent=True): sessionid_url = self.env.blackbox._mock.request.call_args_list[call_index][0][1] expected_params = { 'method': 'createsession', 'lang': '1', 'have_password': '1', 'ver': '3', 'uid': '1', 'format': 'json', 'keyspace': 'yandex.ru', 'is_lite': '0', 'ttl': '5', 'userip': TEST_USER_IP, 'host_id': '7f', 'create_time': TimeNow(), 'auth_time': TimeNow(as_milliseconds=True), 'guard_hosts': 'passport-test.yandex.ru', 'request_id': mock.ANY, 'get_login_id': 'yes', } if password_check_time_is_sent: expected_params['password_check_time'] = TimeNow() check_all_url_params_match(sessionid_url, expected_params) @with_settings_hosts( PERMANENT_COOKIE_TTL=5, PASSPORT_SUBDOMAIN='passport-test', ) class TestSessionCreate(BaseTestSessionCreate): def test_no_host_header(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) rv = self.session_create_request( self.query_params(), {}, ) eq_(rv.status_code, 400, [rv.status_code, rv.data]) def test_without_track(self): rv = self.session_create_request( {}, build_headers(), ) eq_(rv.status_code, 400, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { u'status': u'error', u'errors': [ { u'field': u'track_id', u'message': u'Missing value', u'code': u'missingvalue', }, ], }, ) def test_incorrect_track_id(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) with self.track_manager.transaction(self.track_id).delete(): pass rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 400, [rv.status_code, rv.data]) def test_with_authorization_not_allowed(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.allow_authorization = False rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 400) eq_(json.loads(rv.data), {u'status': u'error', u'errors': [{u'field': None, u'message': u'Authorization is not allowed for this track', u'code': u'authorizationnotallowed'}]}) def test_with_already_created_session(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = 'abc123' track.sslsession = 'abc123' rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 400) eq_(json.loads(rv.data), {u'status': u'error', u'errors': [{u'field': None, u'message': u'Session already created for this account', u'code': u'sessionalreadycreatederror'}]}) def test_https_session_response_password_not_passed(self): ''' Просим создать сессию по хттпс, но пароль не передавался. Секьюрная кука должна быть выписана. ''' with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.is_password_passed = False self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) expected_response = { 'status': 'ok', 'cookies': [ EXPECTED_SESSIONID_COOKIE, EXPECTED_SESSIONID_SECURE_COOKIE, EXPECTED_YP_COOKIE, EXPECTED_YS_COOKIE, EXPECTED_L_COOKIE, EXPECTED_YANDEX_LOGIN_COOKIE, EXPECTED_LAH_COOKIE, EXPECTED_MDA2_BEACON_COOKIE, ], 'default_uid': TEST_UID, 'session': { 'domain': '.yandex.ru', 'expires': 0, 'secure': True, 'http-only': True, 'value': '2:session', }, 'sslsession': { 'domain': '.yandex.ru', 'expires': 1370874827, 'secure': True, 'http-only': True, 'value': '2:sslsession', }, } assert json.loads(rv.data) == expected_response self.assert_createsession_called(password_check_time_is_sent=False) self.check_auth_log_entries( self.env.auth_handle_mock, self.build_auth_log_entries( ('comment', AuthEntry.format_comment_dict({ 'aid': EXPECTED_AUTH_ID, 'ttl': 5, })), ), ) track = self.track_manager.read(self.track_id) eq_(track.session, '2:session') eq_(track.sslsession, '2:sslsession') def test_https_session_response(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) expected_response = { 'status': 'ok', 'cookies': [ EXPECTED_SESSIONID_COOKIE, EXPECTED_SESSIONID_SECURE_COOKIE, EXPECTED_YP_COOKIE, EXPECTED_YS_COOKIE, EXPECTED_L_COOKIE, EXPECTED_YANDEX_LOGIN_COOKIE, EXPECTED_LAH_COOKIE, EXPECTED_MDA2_BEACON_COOKIE, ], 'default_uid': TEST_UID, 'session': { 'domain': '.yandex.ru', 'expires': 0, 'secure': True, 'http-only': True, 'value': '2:session', }, 'sslsession': { 'domain': '.yandex.ru', 'expires': 1370874827, 'secure': True, 'http-only': True, 'value': '2:sslsession', }, } assert json.loads(rv.data) == expected_response self.check_auth_log_entries( self.env.auth_handle_mock, self.build_auth_log_entries( ('comment', AuthEntry.format_comment_dict({ 'aid': EXPECTED_AUTH_ID, 'ttl': 5, })), ), ) track = self.track_manager.read(self.track_id) eq_(track.session, '2:session') eq_(track.sslsession, '2:sslsession') def test_ok_with_sessguard(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response( sessguard_hosts=['passport-test.yandex.ru'], ), ) rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) expected_response = { 'status': 'ok', 'cookies': [ EXPECTED_SESSIONID_COOKIE, EXPECTED_SESSIONID_SECURE_COOKIE, EXPECTED_SESSGUARD_COOKIE, EXPECTED_YP_COOKIE, EXPECTED_YS_COOKIE, EXPECTED_L_COOKIE, EXPECTED_YANDEX_LOGIN_COOKIE, EXPECTED_LAH_COOKIE, EXPECTED_MDA2_BEACON_COOKIE, ], 'default_uid': TEST_UID, 'session': { 'domain': '.yandex.ru', 'expires': 0, 'secure': True, 'http-only': True, 'value': '2:session', }, 'sslsession': { 'domain': '.yandex.ru', 'expires': 1370874827, 'secure': True, 'http-only': True, 'value': '2:sslsession', }, 'sessguard': { 'domain': '.passport-test.yandex.ru', 'expires': 0, 'secure': True, 'http-only': True, 'value': '1.sessguard', }, } assert json.loads(rv.data) == expected_response self.check_auth_log_entries( self.env.auth_handle_mock, self.build_auth_log_entries( ('comment', AuthEntry.format_comment_dict({ 'aid': EXPECTED_AUTH_ID, 'ttl': 5, })), ), ) track = self.track_manager.read(self.track_id) eq_(track.session, '2:session') eq_(track.sslsession, '2:sslsession') eq_(track.sessguard, '1.sessguard') def test_create_session_with_captcha_passed(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.is_captcha_checked = True track.is_captcha_recognized = True rv = self.session_create_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200) self.check_auth_log_entries( self.env.auth_handle_mock, self.build_auth_log_entries( ('comment', AuthEntry.format_comment_dict({ 'aid': EXPECTED_AUTH_ID, 'cpt': 1, 'ttl': 5, })), ), ) track = self.track_manager.read(self.track_id) eq_(track.session, '2:session') @with_settings_hosts( PERMANENT_COOKIE_TTL=5, PASSPORT_SUBDOMAIN='passport-test', ) class TestMultiSessionCreate(BaseTestSessionCreate): def setUp(self): super(TestMultiSessionCreate, self).setUp() self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) self.env.blackbox.set_blackbox_response_value( 'editsession', blackbox_editsession_response( authid=EXPECTED_AUTH_ID, ip=TEST_USER_IP, ), ) def get_expected_cookies(self, with_lah=True): result = [ EXPECTED_SESSIONID_COOKIE, EXPECTED_SESSIONID_SECURE_COOKIE, EXPECTED_YP_COOKIE, EXPECTED_YS_COOKIE, EXPECTED_L_COOKIE, EXPECTED_YANDEX_LOGIN_COOKIE, ] if with_lah: result.append(EXPECTED_LAH_COOKIE) result.append(EXPECTED_MDA2_BEACON_COOKIE) return result def assert_response_ok(self, rv, with_lah=True): eq_(rv.status_code, 200, [rv.status_code, rv.data]) expected_response = { 'status': 'ok', 'cookies': self.get_expected_cookies(with_lah=with_lah), 'default_uid': TEST_UID, 'session': { 'domain': '.yandex.ru', 'expires': 0, 'secure': True, 'http-only': True, 'value': '2:session', }, 'sslsession': { 'domain': '.yandex.ru', 'expires': 1370874827, 'secure': True, 'http-only': True, 'value': '2:sslsession', }, } assert json.loads(rv.data) == expected_response track = self.track_manager.read(self.track_id) eq_(track.session, '2:session') eq_(track.sslsession, '2:sslsession') def assert_auth_log_ok(self, *args): eq_(self.env.auth_handle_mock.call_count, len(args)) self.check_all_auth_log_records( self.env.auth_handle_mock, args, ) def assert_sessionid_called(self): sessionid_url = self.env.blackbox._mock.request.call_args_list[0][0][1] check_url_contains_params( sessionid_url, { 'method': 'sessionid', 'multisession': 'yes', 'sessionid': TEST_SESSIONID, 'request_id': mock.ANY, }, ) def assert_editsession_called(self, call_index=1, password_check_time_is_sent=True): sessionid_url = self.env.blackbox._mock.request.call_args_list[call_index][0][1] expected_params = { 'method': 'editsession', 'sessionid': TEST_SESSIONID, 'sslsessionid': '0:old-sslsession', 'lang': '1', 'have_password': '1', 'uid': '1', 'new_default': '1', 'format': 'json', 'host': '.yandex.ru', 'keyspace': u'yandex.ru', 'userip': TEST_USER_IP, 'op': 'add', 'create_time': TimeNow(), 'guard_hosts': 'passport-test.yandex.ru', 'request_id': mock.ANY, 'get_login_id': 'yes', } if password_check_time_is_sent: expected_params['password_check_time'] = TimeNow() check_all_url_params_match(sessionid_url, expected_params) def assert_statbox_ok(self, uids_count='1', method='create', login='test', with_check_cookie=True, **kwargs): statbox_cookie_set_params = self.env.statbox.entry( 'cookie_set', **{ 'track_id': self.track_id, 'session_method': method, 'uids_count': uids_count, 'yandexuid': TEST_YANDEXUID_COOKIE, 'ip': TEST_USER_IP, 'input_login': login, 'user_agent': TEST_USER_AGENT, } ) statbox_cookie_set_params.update(kwargs) statbox_check_cookies_param = self.env.statbox.entry('check_cookies', host='.yandex.ru') lines = [] if with_check_cookie: lines.append(statbox_check_cookies_param) lines.append(statbox_cookie_set_params) self.env.statbox.assert_has_written(lines) def test_ok_without_cookie(self): rv = self.session_create_request( self.query_params(), build_headers(), ) self.assert_response_ok(rv) self.assert_createsession_called() self.assert_auth_log_ok( self.build_auth_log_entry( status='ses_create', uid='1', login='test', comment='aid=%s;ttl=5' % EXPECTED_AUTH_ID, ), ) self.assert_statbox_ok(with_check_cookie=False) def test_with_cookies__overflow_error(self): """ Пришли с мультикукой, на которую ЧЯ говорит, что в куку больше нельзя дописать пользователей """ self.env.blackbox.set_blackbox_response_value( 'sessionid', blackbox_sessionid_multi_response( uid='1234', login='other_login', ttl=5, allow_more_users=False, ), ) resp = self.session_create_request( self.query_params(), build_headers(cookie=TEST_USER_COOKIES_WITH_SESSION), ) eq_(resp.status_code, 400, [resp.status_code, resp.data]) actual_response = json.loads(resp.data) eq_( actual_response, { u'status': u'error', u'errors': [ { u'field': None, u'message': u'No more users allowed', u'code': u'sessionoverflowerror', }, ], }, ) def test_with_cookies__no_overflow_for_same_uid(self): """ Пришли с мультикукой, на которую ЧЯ говорит, что в куку больше нельзя дописать пользователей, но мы пришли с пользователем, который уже есть в куке, значит ошибки нет. """ self.env.blackbox.set_blackbox_response_value( 'sessionid', blackbox_sessionid_multi_response( uid='1', login='test', ttl=5, allow_more_users=False, ), ) resp = self.session_create_request( self.query_params(), build_headers( cookie='%s;sessionid2=%s' % (TEST_USER_COOKIES_WITH_SESSION, '0:old-sslsession'), ), ) self.assert_response_ok(resp) self.assert_sessionid_called() self.assert_editsession_called(call_index=2) self.assert_auth_log_ok( self.build_auth_log_entry( status='ses_update', uid='1', login='test', comment='aid=%s;ttl=5' % EXPECTED_AUTH_ID, ), ) self.assert_statbox_ok(method='edit', uids_count='1', old_session_uids='1') def test_ok_with_invalid_cookie(self): self.env.blackbox.set_blackbox_response_value( 'sessionid', blackbox_sessionid_multi_response( status=blackbox.BLACKBOX_SESSIONID_INVALID_STATUS, ), ) rv = self.session_create_request( self.query_params(), build_headers(cookie=TEST_USER_COOKIES_WITH_SESSION), ) self.assert_response_ok(rv) self.assert_sessionid_called() self.assert_createsession_called(call_index=2) self.assert_auth_log_ok( self.build_auth_log_entry( status='ses_create', uid='1', login='test', comment='aid=%s;ttl=5' % EXPECTED_AUTH_ID, ), ) self.assert_statbox_ok() def test_ok_with_valid_short_cookie(self): self.env.blackbox.set_blackbox_response_value( 'sessionid', blackbox_sessionid_multi_response( uid='1234', login='other_login', ), ) rv = self.session_create_request( self.query_params(), build_headers( cookie='%s;sessionid2=%s' % (TEST_USER_COOKIES_WITH_SESSION, '0:old-sslsession'), ), ) self.assert_response_ok(rv, with_lah=False) self.assert_sessionid_called() self.assert_editsession_called(call_index=2) self.assert_auth_log_ok( self.build_auth_log_entry( status='ses_update', uid='1234', login='other_login', comment='aid=%s;ttl=0' % EXPECTED_AUTH_ID, ), self.build_auth_log_entry( status='ses_create', uid='1', login='test', comment='aid=%s;ttl=0' % EXPECTED_AUTH_ID, ), ) self.assert_statbox_ok(method='edit', uids_count='2', old_session_uids='1234', ttl='0') @with_settings_hosts( PASSPORT_SUBDOMAIN='passport-test', ) class TestSessionCheck(BaseTestViews): def setUp(self): self.env = ViewsTestEnvironment() self.env.start() self.env.grants.set_grants_return_value(mock_grants(grants={'session': ['check']})) self.track_manager, self.track_id = self.env.track_manager.get_manager_and_trackid('authorize') def tearDown(self): self.env.stop() del self.env del self.track_manager def session_check_request(self, data, headers): return self.env.client.post( '/1/session/check/?consumer=dev', data=data, headers=headers, ) def query_params(self, **kwargs): base_params = { 'track_id': self.track_id, 'session': '2:session', } return merge_dicts(base_params, kwargs) def test_incorrect_track_id(self): with self.track_manager.transaction(self.track_id).delete(): pass rv = self.session_check_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 400, [rv.status_code, rv.data]) def test_track_id_without_session(self): rv = self.session_check_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 400, [rv.status_code, rv.data]) def test_ok(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' rv = self.session_check_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': True, 'session_has_users': True, }, ) def test_ok_empty_session(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '' rv = self.session_check_request( self.query_params(session=''), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': True, 'session_has_users': False, }, ) def test_extra_params(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.retpath = 'http://yandex.ru' track.fretpath = 'http://yandex.com' track.clean = 'yes' rv = self.session_check_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': True, 'session_has_users': True, 'retpath': 'http://yandex.ru', 'fretpath': 'http://yandex.com', 'clean': 'yes', }, ) def test_not_equal(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' rv = self.session_check_request( self.query_params(session='2:notsession'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_not_equal_empty_session(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '' rv = self.session_check_request( self.query_params(), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_equal_session_and_sslsession_and_sessguard(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.sslsession = '2:sslsession' track.sessguard = '1.sessguard' rv = self.session_check_request( self.query_params(session='2:session', sslsession='2:sslsession', sessguard='1.sessguard'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': True, 'session_has_users': True, }, ) def test_equal_session_and_sslsession_both_empty(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '' track.sslsession = '' rv = self.session_check_request( self.query_params(session='', sslsession=''), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': True, 'session_has_users': False, }, ) def test_equal_session_and_not_equal_sslsession(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.sslsession = '2:sslsession' rv = self.session_check_request( self.query_params(session='2:session', sslsession='2:ssl-not-equal'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_equal_session_and_not_equal_empty_sslsession(self): self.env.blackbox.set_blackbox_response_value( 'createsession', blackbox_createsession_response(), ) with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.sslsession = '' rv = self.session_check_request( self.query_params(session='2:session', sslsession='2:ssl-not-equal'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_not_equal_session_and_equal_sslsession(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.sslsession = '2:sslsession' rv = self.session_check_request( self.query_params(session='2:session-not-equal', sslsession='2:sslsession'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_not_equal_session_and_sslsession(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.sslsession = '2:sslsession' rv = self.session_check_request( self.query_params(session='2:session-not-equal', sslsession='2:ssl-not-equal'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_equal_session_and_sslsession_and_not_equal_sessguard(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' track.sslsession = '2:sslsession' track.sessguard = '1.sessguard' rv = self.session_check_request( self.query_params(session='2:session', sslsession='2:sslsession', sessguard='1.sessguard-not-equal'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': False, }, ) def test_equal_session_and_sslsession_not_in_track(self): with self.track_manager.transaction(self.track_id).rollback_on_error() as track: track.session = '2:session' rv = self.session_check_request( self.query_params(session='2:session', sslsession='2:sslsession'), build_headers(), ) eq_(rv.status_code, 200, [rv.status_code, rv.data]) eq_( json.loads(rv.data), { 'status': 'ok', 'session_is_correct': True, 'session_has_users': True, }, )
import AddToBag from "@/app/components/AddToBag"; import CheckoutNow from "@/app/components/CheckoutNow"; import ImageGallery from "@/app/components/ImageGallery"; import { fullProduct } from "@/app/interface"; import { client } from "@/app/lib/sanity"; import { Button } from "@/components/ui/button"; import { Star, Truck } from "lucide-react"; async function getData(slug: string){ const query = `*[_type == 'product' && slug.current == "${slug}"][0]{ _id, name, images, price, description, "slug": slug.current, "category": category->name, stripe }` return await client.fetch(query); } export const dynamic = 'force-dynamic' export default async function ProductPage( {params}:{params: {slug: string}} ){ const product: fullProduct = await getData(params.slug); return( <div className="bg-white"> <div className="mx-auto max-w-screen-xl px-4 md:px-8"> <div className="grid gap-8 md:grid-cols-2"> <ImageGallery images={product.images}/> <div className="md:py-8"> <div className="mb-2 md:mb-3"> <span className="mb-0.5 inline-block text-gray-500"> {product.category} </span> <h2 className="text-2xl font-bold text-gray-800 lg:text-3xl"> {product.name} </h2> </div> <div className="mg-6 flex items-center gap-3 md:mb-10"> <Button className="rounded gap-x-2"> <span className="text-sm">4.2</span> <Star className="h-5 w-5"/> </Button> <span className="text-sm text-gray-500 transition duration-100"> 56 Ratings</span> </div> <div className="mb-4"> <div className="flex items-end gap-2"> <span className="text-xl font-bold"> {product.price}€ </span> <span className="mb-0.5 text-red-500 line-through"> {product.price +30}€</span> </div> <span className="text-sm text-gray-500">Incl. Vat plus Shipping</span> </div> <div className="mb-6 flex items-center gap-2 text-gray-500"> <Truck/> <span className="text-sm">2-4 Day Shipping</span> </div> <div className="flex gap-2.5"> <AddToBag currency="EUR" description={product.description} image={product.images[0]} name={product.name} price={product.price} price_id={product.stripe} key={product._id} /> <CheckoutNow currency="EUR" description={product.description} image={product.images[0]} name={product.name} price={product.price} price_id={product.stripe} key={product._id} /> </div> <p className="mt-12 text-base text-gray-500 tracking-wide"> {product.description} </p> </div> </div> </div> </div> ) }
# importing the libraries import pandas as pd from datetime import datetime # Load the data df = pd.read_excel('Final_Lead_Data.xlsx') # Remove duplicates based on 'Email' df = df.drop_duplicates('Email') # Select necessary columns selected_columns = ["ID", "First Name", "Email", "Created", "Academic Year", "What is your current academic year?"] df = df[selected_columns] # Function to extract year from 'Created' column def get_year(date_str): date = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p') return date.year # Apply the function to 'Created' column df['Year'] = df['Created'].astype(str).apply(get_year) # Function to compute graduation year def compute_grad_year(row): return row['Year'] + (4 - row['Academic Year']) # Compute 'Graduation Year' df['Graduation Year'] = df.apply(compute_grad_year, axis=1) # Select output columns output_df = df[['ID', 'First Name', 'Email', 'Graduation Year']] # Save the output output_df.to_excel('Graduation Year.xlsx', index=False)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoundedNPC : Sign { private Vector3 directionVector; private Transform myTransform; public float speed; private Rigidbody2D myRigidbody; private Animator anim; public Collider2D bounds; private bool isMoving; public float minMoveTime; public float maxMoveTime; private float moveTimeSeconds; public float minWaitTime; public float maxWaitTime; private float waitTimeSeconds; public Inventory playerInventory; public item letter; public item mask; public SignalSender raiseItem; // Start is called before the first frame update void Start() { moveTimeSeconds = Random.Range(minMoveTime, maxMoveTime); waitTimeSeconds = Random.Range(minMoveTime, maxMoveTime); anim = GetComponent<Animator>(); myTransform = GetComponent<Transform>(); myRigidbody = GetComponent<Rigidbody2D>(); ChangeDirection(); } // Update is called once per frame public override void Update() { if (playerInRange && playerInventory.items.Contains(letter)) { dialog = "Oh, is that a letter? Someone told me to give this pear to a dude with felt hat, beard, and glasses. But you took a long time so I ate it. Uh, but you can have this mask!"; playerInventory.AddItem(mask); playerInventory.currentItem = mask; raiseItem.Raise(); } //if (playerInventory.items.Contains(mask)) //{ // dialog = "Yeah, sorry about that... But hopefully that mask comes in handy.. I love wearing it and seeing everyone's reactions. BOO!"; //} base.Update(); if (isMoving) { moveTimeSeconds -= Time.deltaTime; if(moveTimeSeconds <= 0) { moveTimeSeconds = Random.Range(minMoveTime, maxMoveTime); isMoving = false; } if (!playerInRange) { Move(); } } else { waitTimeSeconds -= Time.deltaTime; if (waitTimeSeconds <= 0) { ChooseNewDirection(); isMoving = true; waitTimeSeconds = Random.Range(minMoveTime, maxMoveTime); } } } private void ChooseNewDirection() { Vector3 temp = directionVector; ChangeDirection(); int loops = 0; while (temp == directionVector && loops < 100) { Debug.Log("Here"); loops++; ChangeDirection(); } } private void Move() { Vector3 temp = myTransform.position + directionVector * speed * Time.deltaTime; if (bounds.bounds.Contains(temp)) { myRigidbody.MovePosition(temp); } else { ChangeDirection(); } } void ChangeDirection() { int direction = Random.Range(0, 4); switch (direction) { case 0: directionVector = Vector3.right; break; case 1: directionVector = Vector3.up; break; case 2: directionVector = Vector3.left; break; case 3: directionVector = Vector3.down; break; default: break; } UpdateAnimation(); } void UpdateAnimation() { anim.SetFloat("moveX", directionVector.x); anim.SetFloat("moveY", directionVector.y); } private void OnCollisionEnter2D(Collision2D other) { ChooseNewDirection(); } }
package com.br.ciapoficial.adapters; import android.content.Context; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.widget.RecyclerView; import com.br.ciapoficial.R; import com.br.ciapoficial.helper.DateFormater; import com.br.ciapoficial.model.Servico; import java.util.ArrayList; import java.util.List; public class ServicosAtendidoAdapter extends RecyclerView.Adapter<ServicosAtendidoAdapter.MyViewHolder> { private List<Servico> servicos; private Context context; public ServicosAtendidoAdapter(List<Servico> lista, Context c) { this.servicos = lista; this.context = c; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_atendimentos_atendido, parent, false); return new MyViewHolder(itemLista); } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { Servico servico = servicos.get(position); holder.data.setText(DateFormater.localDateToString(servico.getData())); if(!servico.getEspecialistas().isEmpty() && servico.getEspecialistas() != null) { String resumoOficiais = new ArrayList<>(servico.getEspecialistas()).get(0).toString(). replace("[", "").replace("]", ""); if(servico.getEspecialistas().size() > 1) { holder.nomeOficiais.setText(resumoOficiais + "...+(" + (servico.getEspecialistas().size() - 1) + ")"); }else { holder.nomeOficiais.setText(servico.getEspecialistas().toString(). replace("[", "").replace("]", "")); } } } @Override public int getItemCount() { return servicos.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView data, nomeOficiais; public MyViewHolder(View itemView) { super(itemView); data = itemView.findViewById(R.id.txtData); nomeOficiais = itemView.findViewById(R.id.txtNomeOficial); } } }
:: choices modifier fire: 7 _example: "[[label -> passage name [ variable: value, otherVariable : existingVar + 5 ]]" -- The choices modifier does the same as forks in chapbook but with a few additional features. The modifier is called with `[choices]` which, if you want the links to reveal the rest, can take the argument `reveal` lik `[choices reveal]`. If the `reveal` parameter is set, the link will be rendered as a `reval-passage` type link instead of a `go`. On click, if you chose reveal, the active choice link will me be moved out of the `choices` section and wrapped in a new empty `<div>`, then the choices will be hidden and the content appended. The `[choices]` modifier makes usage of the extended links with a custom syntax. The links inside can set additional data in the state. the syntax is : <br>` {_example} `. <div class="warning"> Spaces before and after the `->` will be trimmed, so if you put them in or not doesn't matter really. The choices are also cleared of any `tabs`, `4 spaces` and `line returns` before being parsed, so feel free to use them to make it more readable.<br> _and don't rely on them for data as the will be removed_ </div> It shows something like this : { embed passage: "choices modifier : example" } With a modifier like this ```markdown [javascript] write(engine.story.passageNamed('choices modifier : example').source) [continue] ``` rendering something like : ```html { embed passage: "choices modifier : example" } ``` ### usecase : dissapearing choices If you want to have choices that dissapear after they have been selected, you can use the `hidden` property of the `lk` insert to your advantage. take the following example : click on a link, then on "back" at the bottom on the page. The link is no longer available. Click on the remaining link and then on back, now the default link is displayed. { embed passage: 'dissapearing choices' } Obtained with this setup : ```js [javascript] write(engine.story.passageNamed('dissapearing choices').source) [continue] ``` rendering : ```html { embed passage: 'dissapearing choices' } ``` :: dissapearing choices [javascript] if (!engine.state.get('visitedExample')) engine.state.set('visitedExample', '') [continue] [choices go] [[ draw : circle -> draw : circle [ hidden: visitedExample.indexOf('draw : circle') !== -1, visitedExample: visitedExample + 'draw : circle|' ] ]] [[ draw : progress -> draw : progress [ hidden: visitedExample.indexOf('draw : progress') !== -1, visitedExample: visitedExample + 'draw : progress|' ] ]] [[ default link -> draw : progress [ hidden: visitedExample.split('|').filter(Boolean).length < 2 ] ]] [continue] :: choices modifier : example [choices reveal] [[say you're sorry -> scene modifier : sorry [ fire : 4 ]] [[defend yourself -> scene modifier : defend [ fire: fire + 4 ]] [continue]
// Definir un módulo para el dropdown de nacionalidades const NacionalidadesDropdown = (function() { // Función para cargar las nacionalidades desde el archivo JSON function cargarNacionalidades() { fetch('/FrontEnd/Json/Nacionalidades.json') .then(response => response.json()) .then(data => { construirMenu(data, 'MenuSelNac'); }) .catch(error => console.error('Error al cargar el JSON de nacionalidades:', error)); } // Función para construir el menú desplegable de nacionalidades function construirMenu(nacionalidades, menuId) { const dropdownMenu = document.getElementById(menuId); // Limpiar el contenido del menú desplegable dropdownMenu.innerHTML = ''; // Iterar sobre los datos de las nacionalidades nacionalidades.forEach(nacionalidad => { const listItem = document.createElement('li'); const link = document.createElement('a'); link.classList.add('dropdown-item'); link.href = '#'; link.textContent = nacionalidad.Nombre; // Agregar evento de clic para actualizar el nombre del país seleccionado link.addEventListener('click', () => { actualizarNombrePais(nacionalidad.Nombre); actualizarBanderaPais(nacionalidad.URL_bandera); }); listItem.appendChild(link); dropdownMenu.appendChild(listItem); }); } // Retornar las funciones y variables públicas del módulo return { cargarNacionalidades: cargarNacionalidades }; })(); // Llamar a la función para cargar las nacionalidades cuando la página se carga window.onload = function() { NacionalidadesDropdown.cargarNacionalidades(); };
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.22 <0.9.0; contract AccountStrut { modifier _moreMoney(uint amount, uint givenMoney) { require(amount >= givenMoney); _; } struct Account { address _address; uint _amount; } Account public _acc1 = Account({ _address: 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2, _amount: 50 }); Account public _acc2 = Account({ _address: msg.sender, _amount: 100 }); function addAmount(uint _addMoney) public returns (uint){ _acc1._amount += _addMoney; return _acc1._amount; } function addAmount2(uint _addMoney) public returns (uint) { _acc2._amount += _addMoney; return _acc2._amount; } function withdraw(uint _money) public _moreMoney(_acc1._amount, _money) returns (uint) { _acc1._amount -= _money; return _acc1._amount; } function transfer(uint _money) public _moreMoney(_acc1._amount, _money) returns (bool) { withdraw(_money); addAmount2(_money); return true; } }
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <link th:href="@{/webjars/bootstrap/3.4.1/css/bootstrap.min.css}" rel="stylesheet" media="screen"> <script type="text/javascript" th:src="@{/webjars/jquery/3.5.1/css/jquery.min.css}"></script> <title></title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-xs-offset-2 "> <form class="form-horizontal" th:object="${product}" th:action="@{/product}" method="post"> <h2 style="text-align: center;">Product Detail</h2> <input type="hidden" th:field="*{id}"> <div class="form-group"> <label class="col-sm-4 control-label">Product Description</label> <div class="col-sm-8"> <input type="text" class=" form-control" th:field="*{description}"></input> </div> </div> <div class="form-group"> <label class=" col-sm-4 control-label">Product price</label> <div class="col-sm-8"> <input type="text" class="col-sm-8 form-control" th:field="*{price}"></input> </div> </div> <div class="form-group"> <label class=" col-sm-4 control-label">Product image</label> <div class="col-sm-8"> <input type="text" class="col-md-4 form-control" th:field="*{imageUrl}"></input> </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </body> </html>
# HTML+CSS+JS - 코딩자율학습 HTML+CSS+JS 연습 코드 업로드 - This repository is for practice HTML+CSS+JS ## JAN 30th: 기초 문법(Basic Grammar) 1p~66p - HTML 기초 및 실행 방법, 라이브러리 다운로드 - Basic Setting for HTML. Download Live Server, Css Support, Code Runner - index.html upload - Basic Grammar: tag,content, paragraph etc... the elements of basic HTML ## JAN 31th: 그룹짓기(Grouping), 목록 만들기(make list) 67p~ 74p - 그룹짓기 연습 및 목록 관련 태그 학습(I studied Grouping & listing tag) - classify the paragraphs with div and span - list the elements with dl(description list),ul(unordered list) and ol(ordered list) ## Feb 1st: 링크와 이미지 넣기, 텍스트 강조하기 (75p~81p) - a태그 실습: a href = "링크", target, title: 링크 넣고 제목 띄우기, 열리는 방식 정의 - img태그: img src = "경로" alt= "뜨는 말". a태그로 링크 넣기 가능 - strong: 문자열 강조. 옛날에는 b였지만 현재는 쓰지 않는다 - em: 기울여 쓰기. i였지만 더이상 쓰지 않는다. 중첩 가능 ## Feb 2nd,3rd: 폼 구성하기(82p~85p) - 상호작용 요소의 구성 - input 타입 구성하기 ## Feb 4th,5th: 폼 구성하기(85p~86p) - input 타입 구성 보충 및 이미지 사이즈 구성. - label 태그와 fieldset ## Feb 6th: 폼 구성하기(86~90p) - textarea를 통한 여러줄 입력 가능한 블로그 양식 만들기 ## Feb 7th: select 구성하기(90~92p) - select로 선택하는 상자 만들기. option, optbox 활용 - size로 한번에 보일 양 선택하기 - multiple로 여러개 선택가능하게 하기 - selected 설정으로 디폴트 값 설정하기 ## Feb 8th: button 구성하기(92p~97p) - button 태그 구성 - disabled, readonly, maxlength, checked, placeholder 속성 ## Feb 9th: 3.7 표 만들기 시작 (98p~) - 3.7,3.8 ## Feb 10th: 3.9.1,3.9.2 - 연습문제 풀이 ## Feb 11th: 3.9.2, 3.9.3 - 연습문제풀이 - html 로그인 화면 구현 실습 - 3.9.3 위키백과 목록 구현하기 ## Feb 12th: CSS 적용하기 기초 - 기초 문법. 외부스타일 시트 - 전체선택자 ## Feb 13th: CSS 적용 기초 - 태그 선택자, 클래스선택자, 기본선택자 ## Feb 14th~15th: 선형회귀 분석(빅데이터) - 기타 빅데이터 폴더에 업로드. 통계공부(SDEM) ## Feb 16th~19th: 파이썬 알고리즘 공부 - 구름 및 백준 풀이 ## Feb 20th: 하위선택자 및 조합선택자 선택하기 - 아이디선택자 - 자식선택자, 부모-형제 선택자 ## Feb 21th: 파이썬 알고리즘 공부 - 윤년 알고리즘 짜기 ## Fev 22~23th: 가상 선택자 클래스 - 입력 요소 가상클래스 선택자(checked, disabled) - 구조적 가상클래스 선택자(nth-child, nth-last-child) ## Feb 24th: 파이썬 알고리즘 공부 - 출력_꼬마 정민(map 쓰지 않기) ## Apr 21th: JS 기본문법 - 멋사 FE 3주차 JS 기본 문법 문서 1 - let, var, const - for, while, if , switch-case - 화살표함수 - 백팁 ` ## Apr 26th : 리액트 기초 - HTML 및 JS 연동방법 기초 ## May 12th: velog 개시 - JS 상식 및 이벤트루프 글 작성 - (https://velog.io/@brillante03/posts)
import CrisisCleanup import Firebase class TagLogger: AppLogger { let appEnv: AppEnv let tag: String init(appEnv: AppEnv, tag: String) { self.appEnv = appEnv self.tag = tag } func logDebug(_ items: Any...) { if appEnv.isDebuggable { print(self.tag, items) } } func logError(_ e: Error) { if e is CancellationError { return } if appEnv.isDebuggable { if let ge = e as? GenericError { print(self.tag, ge.message) } else { print(self.tag, e) } } else { Crashlytics.crashlytics().record(error: e) } } func logCapture(_ message: String) { if !appEnv.isDebuggable { Crashlytics.crashlytics().log(message) } } } class AppLoggerProvider: AppLoggerFactory { let appEnv: AppEnv init(_ appEnv: AppEnv) { self.appEnv = appEnv } func getLogger(_ tag: String = "app") -> AppLogger { return TagLogger(appEnv: self.appEnv, tag: tag) } }
<template> <div class="container col-xl-12"> <!-- Check whether the person is authenticated or Not with v-if $gate is imported globAly from app.js and the file Gate.js is Created for Authentication --> <div class="row" v-if="$gate.isAdmin()"> <div class="col-xl-12"> <!-- Card --> <div class="card p-0"> <div class="card-header"> <div class="card-title"> <h4>Breeding Details</h4> </div> <div class="card-tools"> <button class="btn btn-success" @click="addModal()"><i class="fas fa-plus" aria-hidden="true"></i>&nbsp;Add New</button> </div> </div> <!-- /.card-header --> <div class="card-body table-responsive p-0"> <table class="table table-hover table-bordered" id="mytable"> <thead> <tr> <th scope="col">Breed</th> <th scope="col">Date_of_cohabitation</th> <th scope="col">Sire #</th> <th scope="col">Dam #</th> <th scope="col">Date_of_Separation</th> <th scope="col">Date_of_Delivery</th> <th scope="col">LITTER male</th> <th scope="col">LITTER female</th> <th scope="col">Total</th> <th scope="col">Date_of_Weaning</th> <th scope="col">Pup Male</th> <th scope="col">pup female</th> <th scope="col">Mortality male</th> <th scope="col">Mortality female</th> <th scope="col">Total</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr v-for="breeding in breedings.data" :key="breeding.id"> <td>{{breeding.breed}}</td> <td>{{breeding.start}}</td> <td>{{breeding.male_id}}</td> <td>{{breeding.female_id}}</td> <td>{{breeding.seperate}}</td> <td>{{breeding.delivery}}</td> <td>{{breeding.del_male}}</td> <td>{{breeding.del_female}}</td> <td>{{breeding.tot}}</td> <td>{{breeding.weaning}}</td> <td>{{breeding.pup_male}}</td> <td>{{breeding.pup_female}}</td> <td>{{breeding.m_male}}</td> <td>{{breeding.m_female}}</td> <td>{{breeding.total}}</td> <td> <button class="btn btn-sm btn-light" @click="editModal(breeding)"> <i class="fa fa-edit orange"></i> </button> <button class="btn btn-sm btn-light" @click="deleteData(breeding.id)"> <i class="fa fa-trash red"></i> </button> </td> </tr> </tbody> </table> </div> <!-- /.card-body --> <div class="card-footer"> <div class="float-right"> <button class="btn btn-primary btn-sm" id="button-a" @click="exportExcel('xlsx')"><i class="fas fa-download"></i> Export</button> </div> <pagination :data="breedings" @pagination-change-page="getResults"></pagination> </div> </div> <!-- /.card --> </div> <!-- File Upload --> <div class="col-md-12"> <div class="card"> <div class="card-body"> <p>Choose Excel file to import into Database</p> <div class="input-group"> <input type="file" name="import_file" @change="fieldchange"> <span class="input-group-prepend"> <button type="button" @click="uploadfile" class="btn btn-success btn-sm "><i class="fa fa-upload" aria-hidden="true"></i>&nbsp; Upload</button> </span> </div> </div> </div> </div> <!-- /fileupload --> </div> <div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="addNewLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" v-show="!editmode" id="addNewLabel">Add New</h5> <h5 class="modal-title" v-show="editmode" id="addNewLabel">Update Data</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form @submit.prevent="editmode ? updateData() : addData()"> <div class="modal-body"> <div class="row justify-content-center"> <div class="col-md-4"> <div class="card"> <div class="card-header"> Cohabitation & Separate</div> <div class="card-body"> <div class="form-group"> <select v-model="form.breed" name="breed" class="form-control" :class="{ 'is-invalid': form.errors.has('breed') }"> <option value="" disabled selected>Species</option> <option v-for="(spec,k) in specs" :key="k">{{spec}}</option> </select> <has-error :form="form" field="breed"></has-error> </div> <div class="form-group"> <input v-model="form.start" type="text" onfocus="(this.type='date')" @change="addDate" name="start" class="form-control" :class="{ 'is-invalid': form.errors.has('start') }" placeholder="Cohabitation Date"> <has-error :form="form" field="start"></has-error> </div> <div class="form-group"> <input v-model="form.male_id" type="text" name="male_id" class="form-control" :class="{ 'is-invalid': form.errors.has('male_id') }" placeholder="Male_id"> <has-error :form="form" field="male_id"></has-error> </div> <div class="form-group"> <input v-model="form.female_id" type="text" name="female_id" class="form-control" :class="{ 'is-invalid': form.errors.has('female_id') }" placeholder="Female_id"> <has-error :form="form" field="female_id"></has-error> </div> <div class="form-group"> <input :value="this.form.seperate" type="text" name="seperate" class="form-control" :class="{ 'is-invalid': form.errors.has('seperate') }" placeholder="Seperate Date"> <has-error :form="form" field="seperate"></has-error> </div> </div> </div> </div> <div class="col-md-4"> <div class="card"> <div class="card-header">Delivery & Weaning</div> <div class="card-body"> <div class="form-group"> <input v-model="form.delivery" type="text" onfocus="(this.type='date')" name="delivery" class="form-control" :class="{ 'is-invalid': form.errors.has('delivery') }" placeholder="Delivery Date"> <has-error :form="form" field="delivery"></has-error> </div> <div class="form-group"> <input :value="this.form.del_male" @change="sumNuma" type="number" name="del_male" class="form-control" :class="{ 'is-invalid': form.errors.has('del_male') }" placeholder="del_male"> <has-error :form="form" field="del_male"></has-error> </div> <div class="form-group"> <input :value="this.form.del_female" @change="sumNumb" type="number" name="del_female" class="form-control" :class="{ 'is-invalid': form.errors.has('del_female') }" placeholder="del_female"> <has-error :form="form" field="del_female"></has-error> </div> <div class="form-group"> <input v-model="form.tot" type="text" name="tot" class="form-control" :class="{ 'is-invalid': form.errors.has('tot') }" placeholder="Total"> <has-error :form="form" field="tot"></has-error> </div> <div class="form-group"> <input v-model="form.weaning" type="text" onfocus="(this.type='date')" name="weaning" class="form-control" :class="{ 'is-invalid': form.errors.has('weaning') }" placeholder="Weaning Date"> <has-error :form="form" field="weaning"></has-error> </div> </div> </div> </div> <div class="col-md-4"> <div class="card"> <div class="card-header">Mortality & Total</div> <div class="card-body"> <div class="form-group"> <input :value="this.form.pup_male" @change="addNuma" type="text" name="pup_male" class="form-control" :class="{ 'is-invalid': form.errors.has('pup_male') }" placeholder="pup_male"> <has-error :form="form" field="pup_male"></has-error> </div> <div class="form-group"> <input :value="this.form.pup_female" @change="addNumb" type="text" name="pup_female" class="form-control" :class="{ 'is-invalid': form.errors.has('pup_female') }" placeholder="pup_female"> <has-error :form="form" field="pup_female"></has-error> </div> <div class="form-group"> <input :value="this.form.m_male" type="number" @change="subNuma" name="m_male" class="form-control" :class="{ 'is-invalid': form.errors.has('m_male') }" placeholder="mor_male"> <has-error :form="form" field="m_male"></has-error> </div> <div class="form-group"> <input :value="this.form.m_female" type="number" @change="subNumb" name="m_female" class="form-control" :class="{ 'is-invalid': form.errors.has('m_female') }" placeholder="mor_female"> <has-error :form="form" field="m_female"></has-error> </div> <div class="form-group"> <input v-model="form.total" type="number" name="total" class="form-control" :class="{ 'is-invalid': form.errors.has('total') }" placeholder="total"> <has-error :form="form" field="total"></has-error> </div> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <button v-show="editmode" type="submit" class="btn btn-success">Update</button> <button v-show="!editmode" type="submit" class="btn btn-primary">Create</button> </div> </form> </div> </div> </div> <!-- /row --> </div> </template> <script> export default { data() { return { editmode: false, breedings: {}, attachment: null, specs: ['Rat', 'Mouse', 'Guinea pig'], forms: new FormData, form: new Form({ id: '', breed: '', start: '', male_id: '', female_id: '', seperate: '', delivery: '', del_male: '', del_female: '', tot: '', weaning: '', pup_male: '', pup_female: '', m_male: '', m_female: '', total: '' }) } }, methods: { //Pagination Function getResults(page = 1) { axios.get('api/breeding?page=' + page) .then(response => { this.breedings = response.data; }); }, //get the file fieldchange(e) { let selectedfile = e.target.files[0]; this.attachment = selectedfile; }, //add two Date addNuma(event) { this.form.pup_male = event.target.value; this.form.total = parseInt(this.form.pup_male) + parseInt(this.form.pup_female); // this.form.tot = parseInt(this.form.pup_male) + parseInt(this.form.pup_male); }, sumNuma(event) { this.form.del_male = event.target.value; this.form.tot = parseInt(this.form.del_male) + parseInt(this.form.del_female); // this.form.tot = parseInt(this.form.pup_male) + parseInt(this.form.pup_male); }, sumNumb(event) { this.form.del_female = event.target.value; this.form.tot = parseInt(this.form.del_male) + parseInt(this.form.del_female); // this.form.tot = parseInt(this.form.pup_male) + parseInt(this.form.pup_male); }, addNumb(event) { this.form.pup_female = event.target.value; this.form.total = parseInt(this.form.pup_male) + parseInt(this.form.pup_female); // this.form.tot = parseInt(this.form.pup_male) + parseInt(this.form.pup_male); }, subNuma(event) { this.form.m_male = event.target.value; this.form.total -= parseInt(this.form.m_male); }, subNumb(event) { this.form.m_female = event.target.value; this.form.total -= parseInt(this.form.m_female); }, addDate(event) { let date, sumDate, finalDate, parts; date = new Date(event.target.value); date.setDate(date.getDate() + 10); // finalDate = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear(); finalDate = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate(); // parts = sumDate.split('-'); // this.form.seperate =new Date.(this.form.start) + 10; // console.log( typeof(finalDate) ); this.form.seperate = finalDate; // finalDate = new Date(sumDate); // console.log(finalDate); }, exportExcel(type, fn, dl) { var elt = document.getElementById('mytable'); var wb = XLSX.utils.table_to_book(elt, { sheet: "Sheet JS" }); return dl ? XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) : XLSX.writeFile(wb, fn || ('breeding.' + (type || 'xlsx'))); }, //upload file uploadfile() { this.forms.append('pic', this.attachment); const config = { headers: { 'Content-Type': 'multipart/formdata' } }; axios.post('api/breedimport', this.forms, config) .then(response => { Fire.$emit('refreshData'); swal.fire( 'uploaded', 'Your file has been uploaded.', 'success' ) }) .catch(response => { swal.fire( 'Error', 'please choose appropriate file for uploading.', 'error' ) }) }, // update the existing the data updateData() { this.$Progress.start(); this.form.put('api/breeding/' + this.form.id) .then(() => { $('#addNew').modal('hide'); swal.fire( 'Updated!', 'Your file has been Updated.', 'success' ) this.$Progress.finish(); Fire.$emit('refreshData'); }) .catch(() => { swal.fire( 'Failed!', 'Your file has been Updated.', 'error' ) this.$Progress.fail(); }); }, // edit the Existing Data editModal(breeding) { this.editmode = true; this.form.reset(); $('#addNew').modal('show'); this.form.fill(breeding); }, //open new Model addModal() { this.editmode = false; this.form.reset(); $('#addNew').modal('show') }, // add new Data addData() { this.$Progress.start(); this.form.post('api/breeding') .then(() => { Fire.$emit('refreshData'); $('#addNew').modal('hide') toast.fire({ icon: 'success', title: 'Data added successfuly' }) this.$Progress.finish(); }) .catch(() => { toast.fire({ icon: 'error', title: 'Please Enter proper Input' }) }) }, // delete the data deleteData(id) { swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value) { this.form.delete('api/breeding/' + id).then(() => { swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' ) Fire.$emit('refreshData'); }).catch(() => { swal('Failed', 'Something Went Teeribly Wrong'); }); } }) }, //load the Data loadData() { if (this.$gate.isAdmin()) { axios.get('api/breeding') .then(({ data }) => (this.breedings = data)); } }, // Searching and load data Function }, created() { Fire.$on('searching', () => { let query = this.$parent.search; axios.get('api/findBGdata?q=' + query) .then((data) => { this.breedings = data.data }) .catch(() => { }) }) this.loadData(); Fire.$on('refreshData', () => { this.loadData(); }); }, } </script>
// Module dependencies import { useEffect, useReducer } from 'react'; import type { AppProps } from 'next/app'; import { AppContext, initialState, reducer } from '../state/reducers'; import actionDispatcher from '../state/action-dipatchers'; // Styles import '../styles/index.scss' // UI Components import { Layout, Alert, Spin } from 'antd'; import CustomHeader from '../components/custom-header'; // Assets import { wording } from '../utils/constants'; const { Content } = Layout; const MyApp = ({ Component, pageProps }: AppProps) => { const [state, dispatch] = useReducer(reducer, initialState); const actions = actionDispatcher(state, dispatch); const { error, errorMsg, loading } = state; const { WEB3_ERROR } = wording; /** * Check if the site is already connected on metamask and * update the global state. */ useEffect(() => { const checkSiteAlreadyConnected = async (): Promise<void> => { const accounts = await window.ethereum .request({ method: 'eth_accounts' }); if (accounts.length > 0) actions.handleConnect(); }; checkSiteAlreadyConnected(); }, []); return ( <AppContext.Provider value={{ state, dispatch }}> <Layout> <CustomHeader /> <Content> <Component {...pageProps} /> </Content> {error && ( <Alert message={WEB3_ERROR} description={errorMsg} type="error" showIcon onClose={actions.handleDismissError} closable banner /> )} {loading && ( <div className="spin-container"> <Spin size="large" /> </div> )} </Layout> </AppContext.Provider> ); }; export default MyApp;
/* Freeware License, some rights reserved Copyright (c) 2023 Iuliana Cosmina Permission is hereby granted, free of charge, to anyone obtaining a copy of this software and associated documentation files (the "Software"), to work with the Software within the limits of freeware distribution and fair use. This includes the rights to use, copy, and modify the Software for personal use. Users are also allowed and encouraged to submit corrections and modifications to the Software for the benefit of other users. It is not allowed to reuse, modify, or redistribute the Software for commercial use in any way, or for a user's educational materials such as books or blog articles without prior permission from the copyright holder. The above copyright notice and this permission notice need to be included in all copies or substantial portions of the software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.apress.prospring6.three.constructor import com.apress.prospring6.two.decoupled.MessageProvider import com.apress.prospring6.two.decoupled.MessageRenderer import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration import org.springframework.stereotype.Component /** * Created by iuliana.cosmina on 05/03/2022 */ object ConstructorInjectionDemo { @JvmStatic fun main(args: Array<String>) { val ctx: ApplicationContext = AnnotationConfigApplicationContext(HelloWorldConfiguration::class.java) // <1> val mr: MessageRenderer = ctx.getBean("renderer", MessageRenderer::class.java) mr.render() } } // --- Kotlin configuration class --- @Configuration @ComponentScan internal open class HelloWorldConfiguration() // --- bean definitions using @Component --- //simple bean @Component("provider") internal class HelloWorldMessageProvider() : MessageProvider { override val message: String get() = "Hello World!" } //complex bean requiring a dependency @Component("renderer") internal class StandardOutMessageRenderer @Autowired constructor(override var messageProvider: MessageProvider?) : MessageRenderer { init { println(" ~~ Injecting dependency using constructor ~~") } override fun render() { val msg = messageProvider?:throw RuntimeException( "You must provide a messageProvider constructor param for:" + StandardOutMessageRenderer::class.java.name ) println(msg.message) } }
package org.egorkazantsev.library.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class EntityNotFoundException extends LibraryException { public EntityNotFoundException(String message) { super(message); } public EntityNotFoundException(String type, Object id) { this(formatMessage(type, id)); } private static String formatMessage(String type, Object id) { checkTypeAndId(type, id); return String.format("Entity '%s' with ID '%s' not found", type, id); } }
<template> <header> <div class="wrapper"> <div class="logo"> <img src="@/assets/img/OIG2.png" alt="Logo"> </div> <nav v-if="route.name != 'about'"> <div v-if="showNav" class="nav-links"> <div class="close" @click="showNav = !showNav"><i>Menu</i></div> <RouterLink class="separator1" to="/home">Início</RouterLink> <RouterLink class="separator2" to="/read">Buscar um pet</RouterLink> <RouterLink class="separator3" to="/create">Registrar um pet</RouterLink> <RouterLink v-if="!isLoggedIn" class="separator6" to="/login"><i class="fa-solid fa-user"></i>Entrar</RouterLink> <RouterLink v-else class="separator6" to="/account"><i class="fa-solid fa-user"></i>Minha conta</RouterLink> <RouterLink v-if="!isLoggedIn" class="separator4" to="/signup">Cadastre-se</RouterLink> <a v-else class="separator4" @click="signOut">Sair</a> </div> <div class="hamburger" @click="showNav = !showNav"> <i>Menu</i> </div> </nav> </div> </header> <main> <div class="content"> <RouterView/> </div> </main> <footer> <FooterView/> </footer> </template> <script setup> import { RouterLink, RouterView, useRoute } from 'vue-router'; import { ref, onMounted, watch } from 'vue'; import { supabase } from './supabase'; import FooterView from '@/components/FooterView.vue'; const isLoggedIn = ref(false) supabase.auth.onAuthStateChange((event, session) => { isLoggedIn.value = event === 'SIGNED_IN' || event === 'USER_UPDATED'; }); //logout async function signOut() { const { error } = await supabase.auth.signOut(); if (error) { console.log(error); } else { console.log("Logout has been successful") } } const showNav = ref(window.innerWidth > 768); let route = useRoute(); watch(route, (newRoute) => { route = newRoute; }); onMounted(async () => { const { user } = await supabase.auth.getSession(); isLoggedIn.value = user ? true : false; window.addEventListener('resize', () => { showNav.value = window.innerWidth > 768; }); }); </script> <style> header { background-color: var(--primary-color); height: 16%; display: flex; } .header img { width: 600px; margin-left: 60px; } div.logo { display: flex; flex-direction: column; align-items: flex-start; margin: 20px 50px; animation: slideRight 3s forwards; } div.wrapper { display: flex; justify-content: space-between; } .active-class { display: flex; justify-content: flex-end; } nav { display: flex; justify-content: space-between; gap: 8px; } .nav-links { display: flex; flex-direction: row; align-items: center; justify-content: center; gap: 32px; margin-left: 80px; font-size: 20px; } .separator1 { animation: zoomIn 1s forwards; } .separator2 { animation: zoomIn 2s forwards; } .separator3 { animation: zoomIn 3s forwards; } .separator4 { text-align: center; font-size: 20px; gap: 8px; color: var(--text-color); background-color: var(--secondary-color); margin-left: 6em; padding: 16px; border-radius: 24px; animation: zoomIn 4s forwards; } .separator6 { order: 2; text-align: center; font-size: 16px; gap: 8px; border: 2px solid var(--secondary-color); color: var(--text-color); background-color: var(--secondary-color); padding: 16px; border-radius: 32px; animation: zoomIn 5s forwards; } .hamburger, .close { display: none; cursor: pointer; } .v-application__wrap { min-height: 10dvh; height: 300px; } @media (max-width: 768px) { div.logo { display: flex; align-items: center; } nav { margin: 12% 10% 0 15%; } .nav-links { position: fixed; bottom: 80px; right: 80px; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.4); z-index: 9999; background-color: var(--primary-color); opacity: 1; border-radius: 16px; display: flex; flex-direction: column; padding: 24px 40px; gap: 10px; margin-left: 0; font-size: 2em; } .nav-links.show-nav { transform: translateX(0%); } .nav-links span { display: none; } .separator1, .separator2, .separator3 { color: var(--text-color); font-size: 0.5em; } .separator4 { margin: 0 auto; font-size: 0.5em; color: var(--secondary-color); background-color: transparent; padding: 0; order: 2; } .separator6 { margin: 0 auto; font-size: 0.5em; color: var(--secondary-color); background-color: transparent; border: none; padding: 0; } .hamburger { font-size: 1em; color: #fff; height: 80px; width: 80px; text-align: center; display: flex; align-items: center; justify-content: center; position: fixed; bottom: 40px; right: 40px; background-color: var(--primary-color); padding: 16px; border-radius: 50%; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.4); z-index: 9999; } .close { font-size: 1.5em; color: white; font-weight: 600; } } </style>
/* Esto siempre va a ser igual */ //1. exportacion de la clase Error export class AppError extends Error { //2. constructor con mesaje y codigo de estado, este constructor es un metodo y se va a ejecutar cuando la clase sea instanciada constructor(message, statusCode) { //3. obtencion de todas las funcionalidades de la clase error. Super es como instanciar la clase error super(message) //4. propiedad statusCode = statusCode que le envien por el constructor this.statusCode = statusCode //5. si el status empieza con 4 es error, de lo contrario es fail this.status = `${statusCode}`.startsWith('4') ? 'error' : 'fail' //6. creacion de propiedad es operacional this.isOperational = true //7. captura de toda la pila de errores con referencia la objeto Error.captureStackTrace(this, this.constructor) } }
use crate::{ error::{RuntimeError, RuntimeFailure}, eval::Context, value::Value, }; use actyx_sdk::{ language::{AggrOp, Galactus, Num, SimpleExpr, Tactic, Var}, service::{EventMeta, Order}, }; use anyhow::anyhow; use cbor_data::Encoder; use futures::{future::BoxFuture, FutureExt}; use std::{cmp::Ordering, marker::PhantomData, ops::AddAssign, sync::Arc}; pub trait Aggregator { fn feed(&mut self, input: Value) -> anyhow::Result<()>; fn flush(&mut self, cx: &Context) -> anyhow::Result<Value>; fn has_value(&self) -> bool; } trait SumOp { fn bool(l: u64, r: bool, anti: bool) -> u64; fn to_bool(n: u64) -> bool; fn num(l: Num, r: Num, anti: bool) -> anyhow::Result<Num>; } #[derive(Default)] struct AddOp; impl SumOp for AddOp { fn bool(l: u64, r: bool, anti: bool) -> u64 { if r { if anti { l - 1 } else { l + 1 } } else { l } } fn to_bool(n: u64) -> bool { n > 0 } fn num(l: Num, r: Num, anti: bool) -> anyhow::Result<Num> { if anti { Ok(l.sub(&r)?) } else { Ok(l.add(&r)?) } } } #[derive(Default)] struct MulOp; impl SumOp for MulOp { fn bool(l: u64, r: bool, anti: bool) -> u64 { if r { l } else if anti { l - 1 } else { l + 1 } } fn to_bool(n: u64) -> bool { n == 0 } fn num(l: Num, r: Num, anti: bool) -> anyhow::Result<Num> { if anti { Ok(l.div(&r)?) } else { Ok(l.mul(&r)?) } } } enum Summable<T: SumOp> { Empty(PhantomData<T>), Bool(EventMeta, u64), Num(EventMeta, Num), Error(anyhow::Error), } impl<T: SumOp> AddAssign<&Value> for Summable<T> { #[allow(clippy::suspicious_op_assign_impl)] fn add_assign(&mut self, rhs: &Value) { let anti = rhs.is_anti(); match std::mem::replace(self, Self::Empty(PhantomData)) { Summable::Empty(_) => { *self = rhs .as_bool() .map(|b| Self::Bool(rhs.meta().clone(), T::bool(0, b, anti))) .or_else(|_| rhs.as_number().map(|n| Self::Num(rhs.meta().clone(), n))) .unwrap_or_else(Self::Error) } Summable::Bool(mut meta, b) => { *self = rhs .as_bool() .map(|o| { meta += rhs.meta(); Self::Bool(meta, T::bool(b, o, anti)) }) .unwrap_or_else(Self::Error) } Summable::Num(mut meta, n) => { *self = rhs .as_number() .and_then(|o| { let result = T::num(n, o, anti)?; meta += rhs.meta(); Ok(Self::Num(meta, result)) }) .unwrap_or_else(Self::Error) } Summable::Error(e) => *self = Self::Error(e), } } } impl<T: SumOp> Default for Summable<T> { fn default() -> Self { Summable::Empty(PhantomData) } } #[derive(Default)] struct Sum<T: SumOp>(Summable<T>); impl<T: SumOp> Aggregator for Sum<T> { fn feed(&mut self, input: Value) -> anyhow::Result<()> { self.0 += &input; Ok(()) } fn flush(&mut self, cx: &Context) -> anyhow::Result<Value> { match &self.0 { Summable::Empty(_) => Err(RuntimeError::NoValueYet.into()), Summable::Bool(meta, n) => Ok(Value::new_meta( cx.mk_cbor(|b| b.encode_bool(T::to_bool(*n))), meta.clone(), )), Summable::Num(meta, n) => Ok(Value::new_meta(cx.number(n), meta.clone())), Summable::Error(e) => Err(anyhow!("incompatible types in sum: {}", e)), } } fn has_value(&self) -> bool { true } } struct First(Option<Value>); impl Aggregator for First { fn feed(&mut self, input: Value) -> anyhow::Result<()> { if input.is_anti() { return Err(RuntimeFailure::AntiInputInFirst.into()); } if let Some(v) = &mut self.0 { if input.min_key() < v.min_key() || input.min_key() == v.min_key() && input.max_key() < v.max_key() { *v = input; } } else { self.0 = Some(input); } Ok(()) } fn flush(&mut self, _cx: &Context) -> anyhow::Result<Value> { self.0.clone().ok_or_else(|| RuntimeError::NoValueYet.into()) } fn has_value(&self) -> bool { self.0.is_some() } } struct Last(Option<Value>); impl Aggregator for Last { fn feed(&mut self, input: Value) -> anyhow::Result<()> { if input.is_anti() { return Err(RuntimeFailure::AntiInputInLast.into()); } if let Some(v) = &mut self.0 { if input.max_key() > v.max_key() || input.max_key() == v.max_key() && input.min_key() > v.min_key() { *v = input; } } else { self.0 = Some(input); } Ok(()) } fn flush(&mut self, _cx: &Context) -> anyhow::Result<Value> { self.0.clone().ok_or_else(|| RuntimeError::NoValueYet.into()) } fn has_value(&self) -> bool { self.0.is_some() } } struct Min(Option<anyhow::Result<Value>>); impl Aggregator for Min { fn feed(&mut self, input: Value) -> anyhow::Result<()> { if input.is_anti() { return Err(RuntimeFailure::AntiInputInMin.into()); } self.0 = match self.0.take() { Some(Ok(v)) => match v.partial_cmp(&input) { Some(o) => Some(Ok(if o == Ordering::Greater { input } else { v })), None => Some(Err(anyhow!("cannot compare {} to {}", v, input))), }, Some(Err(e)) => Some(Err(e)), None => Some(Ok(input)), }; Ok(()) } fn flush(&mut self, _cx: &Context) -> anyhow::Result<Value> { self.0 .as_ref() .ok_or_else(|| RuntimeError::NoValueYet.into()) .and_then(|r| match r { Ok(v) => Ok(v.clone()), Err(e) => Err(anyhow!("incompatible types in min: {}", e)), }) } fn has_value(&self) -> bool { self.0.is_some() } } struct Max(Option<anyhow::Result<Value>>); impl Aggregator for Max { fn feed(&mut self, input: Value) -> anyhow::Result<()> { if input.is_anti() { return Err(RuntimeFailure::AntiInputInMax.into()); } self.0 = match self.0.take() { Some(Ok(v)) => match v.partial_cmp(&input) { Some(o) => Some(Ok(if o == Ordering::Less { input } else { v })), None => Some(Err(anyhow!("cannot compare {} to {}", v, input))), }, Some(Err(e)) => Some(Err(e)), None => Some(Ok(input)), }; Ok(()) } fn flush(&mut self, _cx: &Context) -> anyhow::Result<Value> { self.0 .as_ref() .ok_or_else(|| RuntimeError::NoValueYet.into()) .and_then(|r| match r { Ok(v) => Ok(v.clone()), Err(e) => Err(anyhow!("incompatible types in max: {}", e)), }) } fn has_value(&self) -> bool { self.0.is_some() } } struct AggrState { key: Arc<(AggrOp, SimpleExpr)>, aggregator: Box<dyn Aggregator + Send + Sync + 'static>, variable: u32, } struct Aggregate { expr: SimpleExpr, state: Vec<AggrState>, order: Option<Order>, previous: Option<Value>, } impl super::Processor for Aggregate { fn apply<'a, 'b: 'a>(&'a mut self, cx: &'a mut Context<'b>) -> BoxFuture<'a, Vec<anyhow::Result<Value>>> { async move { /* * Anti-flag propagation: * * If we get an anti-input, the specific aggregator will either ingest it or * emit an error. Aggregators always build on a (positive) set of inputs, so * they cannot contain an anti-value. */ let anti = cx .lookup_opt("_") .map(|v| v.as_ref().map(|v| v.is_anti()).unwrap_or_default()) .unwrap_or_default(); let mut errors = vec![]; for aggr in self.state.iter_mut() { match cx.eval(&aggr.key.1).await { Ok(mut v) => { if anti { v.anti(); } if let Err(e) = aggr.aggregator.feed(v) { errors.push(Err(e)) } } Err(e) => errors.push(Err(e)), } } errors } .boxed() } fn flush<'a, 'b: 'a>(&'a mut self, cx: &'a mut Context<'b>) -> BoxFuture<'a, Vec<anyhow::Result<Value>>> { async move { let mut cx = cx.child(); for aggr in self.state.iter_mut() { cx.bind_placeholder(format!("!{}", aggr.variable), aggr.aggregator.flush(&cx)); } let v = match cx.eval(&self.expr).await { Ok(v) => v, e => return vec![e], }; if let Some(mut p) = self.previous.take() { if p == v { self.previous = Some(p); vec![] } else { self.previous = Some(v.clone()); p.anti(); vec![Ok(p), Ok(v)] } } else { self.previous = Some(v.clone()); vec![Ok(v)] } } .boxed() } fn preferred_order(&self) -> Option<Order> { self.order } fn is_done(&self, order: Order) -> bool { Some(order) == self.order && self.state.iter().all(|a| a.aggregator.has_value()) || self.state.is_empty() } } pub(super) fn aggregate(expr: &SimpleExpr) -> Box<dyn super::Processor> { struct G<'a> { state: &'a mut Vec<AggrState>, counter: &'a mut u32, } impl<'a> Galactus for G<'a> { fn visit_expr(&mut self, expr: &SimpleExpr) -> Tactic<SimpleExpr, Self> { match expr { SimpleExpr::AggrOp(a) => { let name = match self.state.binary_search_by_key(&a, |x| &x.key) { Ok(found) => self.state[found].variable, Err(idx) => { let aggregator: Box<dyn Aggregator + Send + Sync> = match a.0 { AggrOp::Sum => Box::<Sum<AddOp>>::default(), AggrOp::Prod => Box::<Sum<MulOp>>::default(), AggrOp::Min => Box::new(Min(None)), AggrOp::Max => Box::new(Max(None)), AggrOp::First => Box::new(First(None)), AggrOp::Last => Box::new(Last(None)), }; *self.counter += 1; self.state.insert( idx, AggrState { key: a.clone(), aggregator, variable: *self.counter, }, ); *self.counter } }; // it is important that these internal variables are not legal in user queries, // hence the exclamation mark Tactic::Devour(SimpleExpr::Variable(Var::internal(format!("!{}", name)))) } // leave sub-queries alone // // This is about delineated contexts: an AGGREGATE expression treats the AggrOps // (like LAST()) specially, but the expression may also include sub-queries that // run once the aggregation is finished. Inside those sub-queries there might be // an AGGREGATE step, but it is not our place to touch that — it will be treated // properly when its evaluation time comes. SimpleExpr::SubQuery(_) => Tactic::KeepAsIs, _ => Tactic::Scrutinise, } } } let mut state = Vec::<AggrState>::new(); let mut counter: u32 = 0; let expr = expr .rewrite(&mut G { state: &mut state, counter: &mut counter, }) .0; let order = { let mut first = false; let mut last = false; let mut other = false; for s in &state { match s.key.0 { AggrOp::Sum => other = true, AggrOp::Prod => other = true, AggrOp::Min => other = true, AggrOp::Max => other = true, AggrOp::First => first = true, AggrOp::Last => last = true, } } if other || first && last { None } else if first { Some(Order::Asc) } else if last { Some(Order::Desc) } else { None } }; Box::new(Aggregate { expr, state, order, previous: None, }) } #[cfg(test)] mod tests { use super::*; use crate::{ eval::RootContext, operation::{Operation, Processor}, query::Query, }; use actyx_sdk::{app_id, language, tags, EventKey, Metadata, NodeId}; use swarm::event_store_ref::EventStoreRef; fn a(s: &str) -> Box<dyn Processor> { let s = format!("FROM 'x' AGGREGATE {}", s); let q = Query::from(language::Query::parse(&s).unwrap(), app_id!("com.actyx.test")).0; match q.stages.into_iter().next().unwrap() { Operation::Aggregate(a) => aggregate(&a), _ => panic!(), } } fn store() -> EventStoreRef { EventStoreRef::new(|_x| Err(swarm::event_store_ref::Error::Aborted)) } fn ctx() -> RootContext { Context::new(store()) } async fn apply<'a, 'b: 'a>(a: &'a mut dyn Processor, cx: &'a mut Context<'b>, v: u64, t: u64) -> Vec<Value> { cx.bind( "_", Value::new_meta( cx.mk_cbor(|b| b.encode_u64(v)), EventMeta::Event { key: EventKey { lamport: t.into(), stream: NodeId::default().stream(0.into()), offset: 0.into(), }, meta: Metadata { timestamp: 0.into(), tags: tags!(), app_id: app_id!("x"), }, }, ), ); a.apply(cx).await.into_iter().collect::<anyhow::Result<_>>().unwrap() } async fn flush<'a, 'b: 'a>(a: &'a mut dyn Processor, cx: &'a mut Context<'b>) -> String { let v = a .flush(cx) .await .into_iter() .map(|r| { let v = r.unwrap(); if v.is_anti() { format!("!{}", v.cbor()) } else { v.cbor().to_string() } }) .collect::<Vec<_>>(); v.join(",") } #[tokio::test] async fn sum() { let mut s = a("42 - SUM(_ * 2)"); let cx = ctx(); let mut cx = cx.child(); assert_eq!(apply(&mut *s, &mut cx, 1, 1).await, vec![]); assert_eq!(apply(&mut *s, &mut cx, 2, 2).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "36"); let mut s = a("CASE SUM(_ ≥ 2) => 11 CASE TRUE => 12 ENDCASE"); assert_eq!(apply(&mut *s, &mut cx, 1, 3).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "12"); assert_eq!(apply(&mut *s, &mut cx, 2, 4).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "!12,11"); } #[tokio::test] async fn product() { let mut s = a("42 - PRODUCT(_ * 2)"); let cx = ctx(); let mut cx = cx.child(); assert_eq!(apply(&mut *s, &mut cx, 1, 1).await, vec![]); assert_eq!(apply(&mut *s, &mut cx, 2, 2).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "34"); let mut s = a("CASE PRODUCT(_ ≥ 2) => 11 CASE TRUE => 12 ENDCASE"); assert_eq!(apply(&mut *s, &mut cx, 2, 3).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "11"); assert_eq!(apply(&mut *s, &mut cx, 1, 4).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "!11,12"); } #[tokio::test] async fn min_max() { let mut s = a("[FIRST(_), LAST(_), MIN(_), MAX(_)]"); let cx = ctx(); let mut cx = cx.child(); assert_eq!(apply(&mut *s, &mut cx, 2, 1).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "[2, 2, 2, 2]"); assert_eq!(apply(&mut *s, &mut cx, 1, 2).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "![2, 2, 2, 2],[2, 1, 1, 2]"); assert_eq!(apply(&mut *s, &mut cx, 4, 3).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "![2, 1, 1, 2],[2, 4, 1, 4]"); assert_eq!(apply(&mut *s, &mut cx, 3, 4).await, vec![]); assert_eq!(flush(&mut *s, &mut cx).await, "![2, 4, 1, 4],[2, 3, 1, 4]"); } }
Barlesque ========= DESCRIPTION Barlesque is an extension for Mozilla Firefox 4.x that reclaims useful window space by collapsing the wide grey add-on bar into a neat set of add-on buttons. This extension is Firefox 4.x-only, as add-on bar is a new feature (introduced in Firefox 4.0b7). Extension implements this proposal of Jennifer Boriss from Mozilla user experience group: http://jboriss.wordpress.com/2010/06/16/removing-firefox%E2%80%99s-status-bar-and-rehousing-add-on-icons-part-3-of-2-wut/ USAGE ===== Barlesque expects user to have the add-on bar switched on ("View" menu -> "Toolbars" -> check the "Add-on Bar"). You'll see the effect of extension immediately after installation; add-on bar won't be the solid horizontal band at the bottom, but will cover only a portion of the space instead. Also, you can quickly hide the add-on bar by clicking on the dark-grey down arrow icon at the left (if add-on bar is bound to the right edge of screen) or right (left edge of screen) side of add-on bar. Later you can expand the add-on bar with the same icon (it will show up-facing arrow). You can customize some aspects of Barlesque behavior through the options dialog ("Tools" menu -> "Add-ons" item -> "Options" button of "Barlesque"): - "Show the collapser icon" option allows you to show/hide a small collapser icon next to the add-on bar; this icon allows you to quickly collapse/expand the bar. By default, extension shows the icon. - By default, extension doesn't persist the collapsed/expanded state of add-on bar between browser sessions; "Remember the collapsed/expanded state of the add-on bar" checkbox changes this. - "Side the add-on bar is aligned to" option allows you to choose, obviously, the side of screen the add-on buttons are bound to. Default alignment is bottom-right corner of screen. - "Position of add-on bar when find bar is shown" option allows you to decide how add-on bar behaves when find bar is called. Possible values are "on top" (default; add-on bar will be shown above the find bar), "overlaid" (add-on bar will be shown over the right side of add-on bar) and "hidden". - You can switch on and customize the keyboard shortcut to collapse/expand the add-on bar. - You can switch on and customize the keyboard shortcut to change the alignment (side of screen) for the add-on bar. - You can switch on and customize the auto-collapse timer, that will automatically collapse the add-on bar after a given number of seconds. Time is counted from user's last interaction with add-on bar (hover, click, etc.) or the last event/notification happening in the add-on bar. All changes made through the options dialog take effect immediately. USABILITY CONSIDERATIONS Please note that the default bottom-right positioning of the add-on bar may interfere with UI elements of some websites (e.g. Facebook chat). If you're frequent visitor to such sites, you may want to change the positioning of add-on bar through the options dialog (or even refrain from using the extension). You'd probably want to read the comments to the article linked above and this discussion on Mozillazine: http://forums.mozillazine.org/viewtopic.php?f=23&t=1951751 PACKAGING ========= The .xpi file can be created manually by using the 'zip' command (or any other zipping software). The resulting .xpi file should contain the following files: chrome/content/options.js chrome/content/options.xul chrome/content/overlay.js chrome/content/overlay.xul chrome/locale/de/barlesque.dtd chrome/locale/de/barlesque.properties chrome/locale/en-US/barlesque.dtd chrome/locale/en-US/barlesque.properties chrome/locale/fr/barlesque.dtd chrome/locale/fr/barlesque.properties chrome/locale/pl/barlesque.dtd chrome/locale/pl/barlesque.properties chrome/locale/ru/barlesque.dtd chrome/locale/ru/barlesque.properties chrome/locale/sr/barlesque.dtd chrome/locale/sr/barlesque.properties chrome/locale/sv-SE/barlesque.dtd chrome/locale/sv-SE/barlesque.properties chrome/locale/zh-CN/barlesque.dtd chrome/locale/zh-CN/barlesque.properties chrome/locale/zh-TW/barlesque.dtd chrome/locale/zh-TW/barlesque.properties chrome/skin/options.css chrome/skin/overlay.css chrome/skin/arrow-down.png chrome/skin/arrow-up.png chrome/skin/barlesque.png defaults/preferences/barlesque.js chrome.manifest install.rdf LICENSE Under linux, the following instruction builds the .xpi file: $ zip -r barlesque.xpi install.rdf chrome.manifest LICENSE chrome defaults INSTALLATION The extension can be installed by drag-and-dropping the 'barlesque.xpi' file over an existing Firefox window, or by pointing Firefox (through File menu, "Open File..." item) to the local URL where the file is stored. Alternatively, if you have Firefox 4 and have the menu bar switched off, you can click on Firefox button -> Addons -> click on gear icon in the top-right corner of screen -> "Install Add-on From File..." FEEDBACK ======== I'd like to hear from you. If you have any issues with Barlesque or have an idea on how to improve it - please feel free to e-mail me: [email protected] PERSONNEL ========= Idea: Jennifer Boriss. Author & principal developer: Dmitriy Khudorozhkov. Contributors: Nils Maier, Drugoy, Vitaly Piryatinsky. Translators: HorstS (de), Goofy (fr), Krzysztof Klimczak (pl), Vitaly Piryatinsky (ru), ДакСРБИЈА (sr), Mikael Hiort af Ornas (sv-SE), yfdyh000 (zh-CN), velociraptor (zh-TW). LEGAL STUFF Copyright 2010 Dmitriy Khudorozhkov.
<?php declare(strict_types=1); namespace ArrayAccess\TrayDigita\App\Modules\Users\Entities; use ArrayAccess\TrayDigita\Database\Entities\Abstracts\AbstractEntity; use ArrayAccess\TrayDigita\Database\TypeList; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\Mapping\Column; use Doctrine\ORM\Mapping\Entity; use Doctrine\ORM\Mapping\HasLifecycleCallbacks; use Doctrine\ORM\Mapping\Id; use Doctrine\ORM\Mapping\Index; use Doctrine\ORM\Mapping\JoinColumn; use Doctrine\ORM\Mapping\ManyToOne; use Doctrine\ORM\Mapping\Table; use Doctrine\ORM\Mapping\UniqueConstraint; /** * @property-read string $name * @property-read mixed $value * @property-read bool $autoload * @property-read int $site_id * @property-read Site $site */ #[Entity] #[Table( name: self::TABLE_NAME, options: [ 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'comment' => 'Site settings', 'primaryKey' => ['name', 'site_id'] ] )] #[Index( columns: ['site_id'], name: 'relation_options_site_id_sites_id' )] #[HasLifecycleCallbacks] class Options extends AbstractEntity { public const TABLE_NAME = 'options'; #[Id] #[Column( name: 'name', type: Types::STRING, length: 255, nullable: false, updatable: true, options: [ 'comment' => 'Option name primary key' ] )] protected string $name; #[Column( name: 'site_id', type: Types::BIGINT, length: 20, nullable: true, options: [ 'unsigned' => true, 'default' => null, 'comment' => 'Site id' ] )] protected ?int $site_id = null; #[ JoinColumn( name: 'site_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE', options: [ 'relation_name' => 'relation_options_site_id_sites_id', 'onUpdate' => 'CASCADE', 'onDelete' => 'CASCADE' ] ), ManyToOne( targetEntity: Site::class, cascade: [ "persist" ], fetch: 'EAGER' ) ] protected ?Site $site = null; #[Column( name: 'value', type: TypeList::DATA, length: 4294967295, nullable: true, options: [ 'default' => null, 'comment' => 'Option value data' ] )] protected mixed $value = null; #[Column( name: 'autoload', type: Types::BOOLEAN, nullable: false, options: [ 'default' => false, 'comment' => 'Autoload reference' ] )] protected bool $autoload = false; public function __construct() { $this->autoload = false; } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $name; } public function isAutoload(): bool { return $this->autoload; } public function setAutoload(bool $autoload): void { $this->autoload = $autoload; } public function getValue(): mixed { return $this->value; } public function setValue(mixed $value): void { $this->value = $value; } public function getSiteId(): ?int { return $this->site_id; } public function setSiteId(?int $site_id): void { $this->site_id = $site_id; } public function getSite(): ?Site { return $this->site; } public function setSite(?Site $site): void { $this->site = $site; $this->setSiteId($site?->getId()); } }
import React, {ComponentType} from 'react'; import {connect} from 'react-redux'; import {AppStateType} from '../../redux/redux-store'; import Header from './Header'; import {logout} from '../../redux/auth-reducer'; import {compose} from 'redux'; type MapStatePropsType = { userId: number | null email: string | null login: string | null isAuth: boolean } type MapDispatchPropsType = { logout: () => void } type OwnPropsType = {} type PropsType = MapStatePropsType & MapDispatchPropsType & OwnPropsType class AuthContainer extends React.Component<PropsType> { render() { return <> <Header login={this.props.login} isAuth={this.props.isAuth} logout={this.props.logout}/> </> } } const mapStateToProps = (state: AppStateType) => { return { userId: state.auth.userId, email: state.auth.email, login: state.auth.login, isAuth: state.auth.isAuth, } } export default compose<ComponentType>( connect<MapStatePropsType, MapDispatchPropsType, OwnPropsType, AppStateType>(mapStateToProps, {logout}))(AuthContainer)
#include "main.h" /** * _strlen_recursion - is a function which returns the length of a string * @s: contains the string to measure * * Return: the string length */ int _strlen_recursion(char *s) { int x = 0; if (*s) { x++; x += _strlen_recursion(s + 1); } return (x); }
#include <iostream> #include <bits/stdc++.h> using namespace std; struct Node; struct ride { int ride_number; int ride_cost; int trip_duration; int idx; }; struct Node { ride data; // int data; // holds the key Node *parent; // pointer to the parent Node *left; // pointer to left child Node *right; // pointer to right child int color; // 1 -> Red, 0 -> Black }; typedef Node *NodePtr; // changed the code from a struct to class. class MinHeap { private: vector<ride> heap; unordered_map<int, int> indices; void heapify(int i) { int left = 2 * i + 1; int right = 2 * i + 2; int smallest = i; if (left < heap.size() && ((heap[left].ride_cost < heap[smallest].ride_cost) || (heap[left].ride_cost == heap[smallest].ride_cost && heap[left].trip_duration < heap[smallest].trip_duration))) { smallest = left; } if (right < heap.size() && ((heap[right].ride_cost < heap[smallest].ride_cost) || (heap[right].ride_cost == heap[smallest].ride_cost && heap[right].trip_duration < heap[smallest].trip_duration))) { smallest = right; } if (smallest != i) { swap(heap[i], heap[smallest]); // update the idx values of the swapped rides indices[heap[i].ride_number] = i; indices[heap[smallest].ride_number] = smallest; heapify(smallest); } // update the idx value of the current ride indices[heap[i].ride_number] = i; } public: void insert(ride value) { value.idx = heap.size(); // update the idx value of the ride to be inserted heap.push_back(value); int i = heap.size() - 1; while (i > 0) { int parent_idx = (i - 1) / 2; if (heap[parent_idx].ride_cost < heap[i].ride_cost || (heap[parent_idx].ride_cost == heap[i].ride_cost && heap[parent_idx].trip_duration < heap[i].trip_duration)) { break; } swap(heap[i], heap[parent_idx]); // update the idx values of the swapped rides indices[heap[i].ride_number] = i; indices[heap[parent_idx].ride_number] = parent_idx; i = parent_idx; } // update the idx value of the inserted ride indices[value.ride_number] = value.idx; heapify(i); } ride extractMin() { if (heap.size() == 0) { cout << "No active ride requests" << endl; return ride{-1, -1, -1, -1}; } ride min = heap[0]; heap[0] = heap.back(); heap.pop_back(); heapify(0); return min; } ride getMin() { if (heap.size() == 0) { throw runtime_error("Heap is empty"); } return heap[0]; } ride updateTrip(int rideNumber, int new_tripDuration) { // Check if rideNumber is in the heap if (indices.find(rideNumber) == indices.end()) { // Ride not found return {0, 0, 0, 0}; // return a default ride object with all values set to 0 } int index = indices[rideNumber]; ride existing_ride = heap[index]; if (new_tripDuration <= heap[index].trip_duration) { // Case a: Trip Duration update existing_ride.trip_duration = new_tripDuration; heap[index].trip_duration = new_tripDuration; // Update the heap heapify(index); return existing_ride; } else if (existing_ride.trip_duration < new_tripDuration && new_tripDuration <= 2 * existing_ride.trip_duration) { // Case b: driver cancels existing ride with a penalty of 10 and a new ride is created int new_cost = existing_ride.ride_cost + 10; ride new_ride = {existing_ride.ride_number, new_cost, new_tripDuration, existing_ride.idx}; cancelRide(existing_ride.ride_number); insert(new_ride); return new_ride; } else { // Case c: ride is automatically declined and removed from the heap cancelRide(rideNumber); indices.erase(rideNumber); existing_ride.ride_number = -1; return existing_ride; } } void cancelRide(int rideNum) { // Replace the element with the last element of the heap // cout << "iniside cancelRide " << index << " " << indices[index].ride_number << " " << heap[index].ride_cost << endl; int index = indices[rideNum]; heap[index] = heap.back(); heap.pop_back(); // Restore the min heap property while (index > 0 && heap[index].ride_cost < heap[(index - 1) / 2].ride_cost) { swap(heap[index], heap[(index - 1) / 2]); // update the idx values of the swapped rides indices[heap[index].ride_number] = index; indices[heap[(index - 1) / 2].ride_number] = (index - 1) / 2; index = (index - 1) / 2; } heapify(index); } bool isEmpty() { return heap.size() == 0; } void print() { for (int i = 0; i < heap.size(); i++) { cout << "Ride Number: " << heap[i].ride_number << ", Cost: " << heap[i].ride_cost << ", Duration: " << heap[i].trip_duration << ", index: " << heap[i].idx << endl; } } }; // RBTREE class class RBTree { private: Node *root; // Node *TNULL; //implemented it in the public to make it public variable // initializes the nodes with appropriate values void initializeNULLNode(Node *node, Node *parent) { node->data.ride_number = 0; node->data.ride_cost = 0; node->data.trip_duration = 0; node->parent = parent; node->left = nullptr; node->right = nullptr; node->color = 0; } Node *searchTreeHelper(Node *node, int key) { if (node == TNULL || key == node->data.ride_number) { return node; } if (key < node->data.ride_number) { return searchTreeHelper(node->left, key); } else { return searchTreeHelper(node->right, key); } } // fix the rb tree modified by the delete operation void fixDelete(NodePtr x) { NodePtr s; while (x != root && x->color == 0) { if (x == x->parent->left) { s = x->parent->right; if (s->color == 1) { // case 3.1 s->color = 0; x->parent->color = 1; leftRotate(x->parent); s = x->parent->right; } if (s->left->color == 0 && s->right->color == 0) { // case 3.2 s->color = 1; x = x->parent; } else { if (s->right->color == 0) { // case 3.3 s->left->color = 0; s->color = 1; rightRotate(s); s = x->parent->right; } // case 3.4 s->color = x->parent->color; x->parent->color = 0; s->right->color = 0; leftRotate(x->parent); x = root; } } else { s = x->parent->left; if (s->color == 1) { // case 3.1 s->color = 0; x->parent->color = 1; rightRotate(x->parent); s = x->parent->left; } if (s->right->color == 0 && s->right->color == 0) { // case 3.2 s->color = 1; x = x->parent; } else { if (s->left->color == 0) { // case 3.3 s->right->color = 0; s->color = 1; leftRotate(s); s = x->parent->left; } // case 3.4 s->color = x->parent->color; x->parent->color = 0; s->left->color = 0; rightRotate(x->parent); x = root; } } } x->color = 0; } void rbTransplant(NodePtr u, NodePtr v) { if (u->parent == nullptr) { root = v; } else if (u == u->parent->left) { u->parent->left = v; } else { u->parent->right = v; } v->parent = u->parent; } void deleteNodeHelper(NodePtr node, int key) { // find the node containing key NodePtr z = TNULL; NodePtr x, y; while (node != TNULL) { if (node->data.ride_number == key) { z = node; } if (node->data.ride_number <= key) { node = node->right; } else { node = node->left; } } if (z == TNULL) { // cout << "Couldn't find key in the tree" << endl; return; } y = z; int y_original_color = y->color; if (z->left == TNULL) { x = z->right; rbTransplant(z, z->right); } else if (z->right == TNULL) { x = z->left; rbTransplant(z, z->left); } else { y = minimum(z->right); y_original_color = y->color; x = y->right; if (y->parent == z) { x->parent = y; } else { rbTransplant(y, y->right); y->right = z->right; y->right->parent = y; } rbTransplant(z, y); y->left = z->left; y->left->parent = y; y->color = z->color; } delete z; if (y_original_color == 0) { fixDelete(x); } } // fix the red-black tree void fixInsert(NodePtr k) { NodePtr u; while (k->parent->color == 1) { if (k->parent == k->parent->parent->right) { u = k->parent->parent->left; // uncle if (u->color == 1) { // case 3.1 u->color = 0; k->parent->color = 0; k->parent->parent->color = 1; k = k->parent->parent; } else { if (k == k->parent->left) { // case 3.2.2 k = k->parent; rightRotate(k); } // case 3.2.1 k->parent->color = 0; k->parent->parent->color = 1; leftRotate(k->parent->parent); } } else { u = k->parent->parent->right; // uncle if (u->color == 1) { // mirror case 3.1 u->color = 0; k->parent->color = 0; k->parent->parent->color = 1; k = k->parent->parent; } else { if (k == k->parent->right) { // mirror case 3.2.2 k = k->parent; leftRotate(k); } // mirror case 3.2.1 k->parent->color = 0; k->parent->parent->color = 1; rightRotate(k->parent->parent); } } if (k == root) { break; } } root->color = 0; } void printHelper(NodePtr root, int least, int max, vector<string> &triplets) { if (root == TNULL) { return; } if (root->data.ride_number < least) { printHelper(root->right, least, max, triplets); } else if (root->data.ride_number > max) { printHelper(root->left, least, max, triplets); } else { if (root->left != TNULL) { printHelper(root->left, least, max, triplets); } if (root->data.ride_number >= least && root->data.ride_number <= max) { ostringstream oss; oss << "(" << root->data.ride_number << "," << root->data.ride_cost << "," << root->data.trip_duration << ")"; triplets.push_back(oss.str()); } if (root->right != TNULL) { printHelper(root->right, least, max, triplets); } } } public: Node *TNULL; RBTree() { TNULL = new Node; TNULL->color = 0; TNULL->left = nullptr; TNULL->right = nullptr; root = TNULL; } // search the tree for the key k // and return the corresponding node Node *searchTree(int k) { return searchTreeHelper(this->root, k); } // find the node with the minimum key NodePtr minimum(NodePtr node) { while (node->left != TNULL) { node = node->left; } return node; } // find the node with the maximum key // not really used anywhere but implemented it before in case I needed it NodePtr maximum(NodePtr node) { while (node->right != TNULL) { node = node->right; } return node; } // rotate left at node x void leftRotate(NodePtr x) { NodePtr y = x->right; x->right = y->left; if (y->left != TNULL) { y->left->parent = x; } y->parent = x->parent; if (x->parent == nullptr) { this->root = y; } else if (x == x->parent->left) { x->parent->left = y; } else { x->parent->right = y; } y->left = x; x->parent = y; } // rotate right at node x void rightRotate(NodePtr x) { NodePtr y = x->left; x->left = y->right; if (y->right != TNULL) { y->right->parent = x; } y->parent = x->parent; if (x->parent == nullptr) { this->root = y; } else if (x == x->parent->right) { x->parent->right = y; } else { x->parent->left = y; } y->right = x; x->parent = y; } void updateTrip(int rideNumber, int cost, int duration) { if (searchTree(rideNumber) == TNULL) { cout << "Ride doesn't exist" << endl; return; } else { // Ordinary Binary Search Insertion NodePtr node = searchTree(rideNumber); node->data.ride_cost = cost; node->data.trip_duration = duration; } } // insert the key to the tree in its appropriate position // and fix the tree void insert(ride key) { if (searchTree(key.ride_number) != TNULL) { cout << "Duplicate RideNumber" << endl; // throw runtime_error("Duplicate RideNumber"); abort(); return; } // Ordinary Binary Search Insertion NodePtr node = new Node; node->parent = nullptr; node->data.ride_number = key.ride_number; node->data.ride_cost = key.ride_cost; node->data.trip_duration = key.trip_duration; node->left = TNULL; node->right = TNULL; node->color = 1; // new node must be red NodePtr y = nullptr; NodePtr x = this->root; while (x != TNULL) { y = x; if (node->data.ride_number < x->data.ride_number) { x = x->left; } else { x = x->right; } } // y is parent of x // when the inserting node is the first node it skips the above while loop and reaches this // which sets the inserting node's parent to y in a way saying that this the root node as it won't have any parent. node->parent = y; if (y == nullptr) { root = node; } else if (node->data.ride_number < y->data.ride_number) { y->left = node; } else { y->right = node; } // if new node is a root node, simply return if (node->parent == nullptr) { node->color = 0; return; } // if the grandparent is null, simply return if (node->parent->parent == nullptr) { return; } // Fix the tree fixInsert(node); } NodePtr getRoot() { return this->root; } // delete the node from the tree void deleteNode(int ridenumber) { deleteNodeHelper(this->root, ridenumber); } // print the tree structure on the screen void prettyPrint(int n1, int n2) { vector<string> triplets; printHelper(root, n1, n2, triplets); if (triplets.empty()) { cout << "(0,0,0)"; } else { if (!triplets.empty()) { cout << triplets.front(); for (size_t i = 1; i < triplets.size(); ++i) { cout << "," << triplets[i]; } } } cout << endl; } }; int main(int argc, char **argv) { // cout << "welcome to the gator taxi\n"; ofstream outfile("output_file.txt"); // open output file streambuf *coutbuf = cout.rdbuf(); // save cout buffer cout.rdbuf(outfile.rdbuf()); // redirect cout to output file if (argc != 2) { cout << "Usage: " << argv[0] << " input_file" << endl; return 1; } ifstream fin(argv[1]); if (!fin.is_open()) { cout << "Unable to open input file" << endl; return 1; } // map<int, tuple<int, int>> redBlackTree; //ride number, tuple = ride cost and trip duration. //can't use this as of now. MinHeap heap; // initialized heap at this point RBTree rbt; // initialized Red-black tree. string command; string line; int count = 1; while (getline(fin, line)) { stringstream ss(line); string command, data; ss >> command; // cout << command << endl; int ride_num, ride_cost, trip_duration; if (command.find("Insert") != string::npos) { data = command.substr(command.find("(") + 1, command.find(")") - command.find("(") - 1); stringstream ss(data); string token; getline(ss, token, ','); ride_num = stoi(token); getline(ss, token, ','); ride_cost = stoi(token); getline(ss, token, ','); trip_duration = stoi(token); ride r = {ride_num, ride_cost, trip_duration}; // cout << "inserting" << r.ride_number << endl; heap.insert(r); rbt.insert(r); } else if (command.find("Print") != string::npos) { int ride_num1 = 0, ride_num2 = 0; data = command.substr(command.find("(") + 1, command.find(")") - command.find("(") - 1); // cout << data << endl; if (data.find(",") != string::npos) { // Print(rideNumber1, rideNumber2) stringstream ss(data); string token; getline(ss, token, ','); ride_num1 = stoi(token); getline(ss, token, ','); ride_num2 = stoi(token); // cout << ride_num1 << " " << ride_num2; rbt.prettyPrint(ride_num1, ride_num2); } else { // cout << "here" << endl; ride_num1 = stoi(data); // cout << ride_num1; Node *res = rbt.searchTree(ride_num1); if (res == rbt.TNULL) { cout << "(0,0,0)" << endl; } else { cout << "(" << res->data.ride_number << "," << res->data.ride_cost << "," << res->data.trip_duration << ")" << endl; } // cout << "Found the node-Here are the triplets: " // cout << "(" << res->data.ride_number << "," << res->data.ride_cost << "," << res->data.trip_duration << ")" << endl; } } else if (command.find("UpdateTrip") != string::npos) { int number = 0, duration = 0; data = command.substr(command.find("(") + 1, command.find(")") - command.find("(") - 1); stringstream ss(data); string token; getline(ss, token, ','); number = stoi(token); getline(ss, token, ','); duration = stoi(token); ride isdeleted = heap.updateTrip(number, duration); if (isdeleted.ride_number == -1) { rbt.deleteNode(number); } else if (isdeleted.ride_number == number) { rbt.updateTrip(isdeleted.ride_number, isdeleted.ride_cost, isdeleted.trip_duration); // cout << "here" << number << endl; } } else if (command.find("GetNextRide") != string::npos) { ride nextRide = heap.extractMin(); if (nextRide.ride_number != -1) { rbt.deleteNode(nextRide.ride_number); // rbt.prettyPrint(nextRide.ride_number, nextRide.ride_number); // cout << "Inside the getNextRide" << endl; cout << "(" << nextRide.ride_number << "," << nextRide.ride_cost << "," << nextRide.trip_duration << ")" << endl; // TODO: implement GetNextRide command } } else if (command.find("CancelRide") != string::npos) { // cout << command << endl; data = command.substr(command.find("(") + 1, command.find(")") - command.find("(") - 1); stringstream ss(data); string token; getline(ss, token, ','); ride_num = stoi(token); Node *res = rbt.searchTree(ride_num); if (res != rbt.TNULL) { // cout << "canceling " << ride_num << endl; heap.cancelRide(ride_num); rbt.deleteNode(ride_num); } } } fin.close(); cout.rdbuf(coutbuf); // restore cout buffer outfile.close(); // close output file return 0; }
{% extends 'base.html' %} {% block title %}Register ny ingrediens{% endblock %} {% block heading %}Ingredienser{% endblock %} {% block description %}Registrere ny ingrediens{% endblock %} <style> * { box-sizing: border-box; } #myInput { background-image: url('/css/searchicon.png'); background-position: 10px 10px; background-repeat: no-repeat; width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } #myTable { border-collapse: collapse; width: 100%; border: 1px solid #ddd; font-size: 18px; } #myTable th, #myTable td { text-align: left; padding: 12px; } #myTable tr { border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { background-color: #f1f1f1; } </style> {% block content %} {% include 'flash_messages.html' %} <div class="container mt-5"> <div class="row align-items-center"> <div class="card p-3 m-auto" style="width: 50%;"> <form method="POST" action="{{ url_for('ingredient.new') }}"> {{ form.csrf_token }} <div class="row mb-3 g-2 justify-content-center"> <div class="col-sm-3"> {{ form.ingredientName.label(class_="col-form-label") }} </div> <div class="col-sm-9"> {{ form.ingredientName(class="form-control") }} </div> </div> <div class="row mb-3 g-2 justify-content-center"> <div class="col-sm-3"> {{ form.price.label(class_="col-form-label") }} </div> <div class="col-sm-9"> {{ form.price(class="form-control") }} </div> </div> <div class="row mb-3 g-2 justify-content-center"> <div class="col-sm-3"> {{ form.unit.label(class_="col-form-label") }} </div> <div class="col-sm-9"> {{ form.unit(class="form-control") }} </div> </div> <div class="col-sm-2"> {{ form.submit(class_="btn btn-success") }} </div> </form> </div> </div> </div> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Søk etter ingrediens..." title="Type in a name"> <table class="table table-striped table-hover header" id="myTable"> <thead> <tr> <th>Ingrediens</th> <th>Mengde</th> <th>Enhet</th> <th>Pris</th> </tr> </thead> <tbody class="table-search-body"> {% for ingredient in ingredients %} <tr> <td>{{ ingredient[0].ingredientName }}</td> <td>{{ ingredient[1].quantity }}</td> <td>{{ ingredient[1].unit }}</td> <td>{{ ingredient[1].price }}</td> <td> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modal{{ ingredient[0].ingredientName }}">Rediger </button> </td> </tr> <!-- Modal --> <div class="modal fade" id="modal{{ ingredient[0].ingredientName }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Rediger {{ ingredient.ingredientName }}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body row align-items-end"> <div class="form-group col"> <label>Ingrediens</label> <input id="{{ loop.index }}-nameForm" class="form-control" type="text" value="{{ ingredient[0].ingredientName }}" disabled readonly> </div> <div class="form-group col"> <label>Antall</label> <input id="{{ loop.index }}-quantityForm" type="number" min="0" class="form-control" id="exampleFormControlInput1" value="{{ ingredient[1].quantity }}"> </div> <div class="form-group col"> <label>Enhet</label> <input id="{{ loop.index }}-unitForm" class="form-control" type="text" value="{{ ingredient[1].unit }}" disabled readonly> </div> <div class="form-group col"> <label>Pris</label> <input id="{{ loop.index }}-prisForm" type="number" min="0" class="form-control" id="exampleFormControlInput1" value="{{ ingredient[1].price }}"> </div> </div> <div class="modal-footer"> <a href="#" id="{{ loop.index }}-myLink" type="button" class="btn btn-primary">Oppdater</a> <script> document.getElementById("{{ loop.index }}-myLink").onclick = function () { var getQuantity = document.getElementById('{{ loop.index }}-quantityForm').value; var getPrice = document.getElementById('{{ loop.index }}-prisForm').value; document.getElementById('{{ loop.index }}-myLink').href = '/ingredient/{{ ingredient[1].ingredient_idingredient }}/' + getQuantity + '/' + getPrice + '/update'; } </script> </div> </div> </div> </div> {% endfor %} </tbody> </table> <script> function myFunction() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> {% endblock %}
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\ValidationException; use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Http\JsonResponse; use Illuminate\Contracts\Validation\Validator; class CustomValidationRegister extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'Email' => 'required|email|unique:users', 'Password' => 'required|min:5', // 'password' => ['required', 'same:password'], ]; } // protected function failedValidation(Validator $validator) // { // $errors = (new ValidationException($validator))->errors(); // throw new HttpResponseException( // response()->json(['errors' => $errors], JsonResponse::HTTP_UNPROCESSABLE_ENTITY) // ); // } }
import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { RootState, AppDispatch } from '@/store/store'; import { fetchVinhos, fetchFornecedores } from '@/store/slices/vinhoThunks'; import styles from './cadastrar-vinhos.module.css'; import Modal from '@/app/components/Modal/Modal'; import WineForm from './WineForm'; import axiosInstance from '@/app/api/axios'; import { Vinho, Fornecedor } from '@/app/types/apiResponses'; import DownloadExcel from '@/app/components/dashboard/cadastrar-vinhos/DownloadExel'; import UploadExcel from "@/app/components/dashboard/cadastrar-vinhos/UploadExcel"; const CadastrarVinhos: React.FC = () => { const dispatch = useDispatch<AppDispatch>(); const vinhos = useSelector((state: RootState) => state.vinhos.vinhos); const fornecedores = useSelector((state: RootState) => state.vinhos.fornecedores); const [isModalOpen, setIsModalOpen] = useState(false); const [nome, setNome] = useState(''); const [vinicula, setVinicula] = useState(''); const [pais, setPais] = useState(''); const [uva, setUva] = useState(''); const [safra, setSafra] = useState(''); const [tamanho, setTamanho] = useState('inteira'); const [valorCusto, setValorCusto] = useState(''); const [markup, setMarkup] = useState(''); const [estoque, setEstoque] = useState(''); const [fornecedoresSelecionados, setFornecedoresSelecionados] = useState<string[]>([]); const [imagem, setImagem] = useState<File | null>(null); const [mensagem, setMensagem] = useState(''); const [filtro, setFiltro] = useState(''); const [groupByFornecedor, setGroupByFornecedor] = useState(false); useEffect(() => { dispatch(fetchVinhos()); dispatch(fetchFornecedores()); }, [dispatch]); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(); formData.append('nome', nome); formData.append('vinicula', vinicula); formData.append('pais', pais); formData.append('uva', uva); formData.append('safra', safra); formData.append('tamanho', tamanho); formData.append('valor_custo', valorCusto); formData.append('markup', markup); formData.append('estoque', estoque); if (imagem) { formData.append('imagem', imagem); } fornecedoresSelecionados.forEach(fornecedorId => { formData.append('fornecedores', fornecedorId); }); try { const response = await axiosInstance.post('/wines/wines/', formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); dispatch({ type: 'vinhos/setMensagem', payload: 'Vinho cadastrado com sucesso!' }); setIsModalOpen(false); setNome(''); setVinicula(''); setPais(''); setUva(''); setSafra(''); setTamanho('inteira'); setValorCusto(''); setMarkup(''); setEstoque(''); setImagem(null); setFornecedoresSelecionados([]); dispatch({ type: 'vinhos/setVinhos', payload: [...vinhos, response.data] }); } catch (error) { dispatch({ type: 'vinhos/setMensagem', payload: 'Erro ao cadastrar vinho.' }); } }; const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.files && e.target.files[0]) { setImagem(e.target.files[0]); } }; const handleFornecedorChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const options = Array.from(e.target.selectedOptions); setFornecedoresSelecionados(options.map(option => option.value)); }; const filteredVinhos = vinhos.filter((vinho) => vinho.nome.toLowerCase().includes(filtro.toLowerCase()) ); // Organize vinhos por fornecedores const vinhosPorFornecedor = fornecedores.reduce((acc: { fornecedor: Fornecedor, vinhos: Vinho[] }[], fornecedor: Fornecedor) => { const vinhosFornecedor = filteredVinhos.filter((vinho) => vinho.fornecedores.includes(fornecedor.id) ); if (vinhosFornecedor.length) { acc.push({ fornecedor, vinhos: vinhosFornecedor }); } return acc; }, []); const handlePrint = () => { window.print(); }; const handleDownloadCSV = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); try { const response = await axiosInstance.post('/wines/export/', { headers: { 'Content-Type': 'multipart/form-data', }, }); } catch (error) { dispatch({ type: 'vinhos/setMensagem', payload: 'Erro ao cadastrar vinho.' }); } }; return ( <div className={styles.container}> <div className={`${styles.header} hide-on-print`}> <button onClick={() => setIsModalOpen(true)}>+ Cadastrar Vinho</button> <input type="text" placeholder="Buscar por nome" value={filtro} onChange={(e) => setFiltro(e.target.value)} className={styles.filtro} /> <button onClick={() => setGroupByFornecedor(!groupByFornecedor)}> {groupByFornecedor ? 'Ver Todos' : 'Agrupar por Fornecedor'} </button> <button onClick={handlePrint}>Imprimir</button> <DownloadExcel/> <UploadExcel/> </div> <div className="printableArea"> {groupByFornecedor ? ( <div className={styles.vinhosList}> {vinhosPorFornecedor.map((group) => ( <div key={group.fornecedor.id} className={styles.fornecedorGroup}> <h3>{group.fornecedor.nome}</h3> <ul className={styles.card}> {group.vinhos.map((vinho) => ( <li key={vinho.id} className={styles.cell}> <img src={vinho.imagem} alt={vinho.nome} /> <p>Vinho: {vinho.nome}</p> <p>Safra: {vinho.safra}</p> <p>Vinicula: {vinho.vinicula}</p> <p>Uva: {vinho.uva}</p> <p>Valor: {vinho.valorCusto}</p> <p>Pais: {vinho.pais}</p> </li> ))} </ul> </div> ))} </div> ) : ( <ul className={styles.card}> {filteredVinhos.map((vinho) => ( <li key={vinho.id} className={styles.cell}> <img src={vinho.imagem} alt={vinho.nome} /> <p>Vinho: {vinho.nome}</p> <p>Safra: {vinho.safra}</p> <p>Vinicula: {vinho.vinicula}</p> <p>Uva: {vinho.uva}</p> <p>Valor: {vinho.valorCusto}</p> <p>Pais: {vinho.pais}</p> </li> ))} </ul> )} </div> <Modal isOpen={isModalOpen} onRequestClose={() => setIsModalOpen(false)}> <WineForm handleSubmit={handleSubmit} nome={nome} setNome={setNome} vinicula={vinicula} setVinicula={setVinicula} pais={pais} setPais={setPais} uva={uva} setUva={setUva} safra={safra} setSafra={setSafra} tamanho={tamanho} setTamanho={setTamanho} valorCusto={valorCusto} setValorCusto={setValorCusto} markup={markup} setMarkup={setMarkup} estoque={estoque} setEstoque={setEstoque} fornecedores={fornecedores} fornecedoresSelecionados={fornecedoresSelecionados} handleFornecedorChange={handleFornecedorChange} handleImageChange={handleImageChange} imagem={imagem} mensagem={mensagem} /> </Modal> </div> ); }; export default CadastrarVinhos;
<script lang="ts"> const information = { name: 'Nintendo Game Boy Advance', released: '2001', generation: 'Sixth', initialPrice: 99.99, unitsSold: 81.51, description: "The Game Boy Advance is a 32-bit sixth generation handheld game console \ developed by Nintendo. The Game Boy Advance was praised for it's graphical capabilities, \ battery life, and backwards compatibility with Game Boy cartridges. The lack of a back-lit \ screen was often mentioned as a drawback. Later iterations of the Game Boy Advance would \ address this issue. Some Game Boy Advance games had special built-in features including \ rumble features, tilt sensors, and solar sensors. Many games were also ported to the Game \ Boy Advance from previous 8-bit and 16-bit generations" }; </script> <div class="grid grid-cols-12 gap-x-4 gap-y-8 lg:gap-6"> <div class="col-span-12 lg:col-span-6"> <p class="max-w-3xl">{information.description}</p> </div> <div class="col-span-12 lg:col-span-6 justify-self-center max-h-72"> <img src="images/GBA.png" alt="Nintendo Game Boy Advance" class="h-full" /> </div> <div class="col-span-12"> <dl class="grid sm:grid-cols-2 lg:grid-cols-4 gap-x-8 gap-y-12 sm:gap-y-16"> <div class="flex flex-col-reverse gap-y-3 border-s ps-7 border-zinc-50/20"> <dt class="text-zinc-300 text-base leading-7">Released</dt> <dd class="text-zinc-50 text-3xl font-semibold tracking-tight">{information.released}</dd> </div> <div class="flex flex-col-reverse gap-y-3 border-s ps-7 border-zinc-50/20"> <dt class="text-zinc-300 text-base leading-7">Generation</dt> <dd class="text-zinc-50 text-3xl font-semibold tracking-tight">{information.generation}</dd> </div> <div class="flex flex-col-reverse gap-y-3 border-s ps-7 border-zinc-50/20"> <dt class="text-zinc-300 text-base leading-7">Price</dt> <dd class="text-zinc-50 text-3xl font-semibold tracking-tight"> {information.initialPrice.toLocaleString('en-US', { style: 'currency', currency: 'USD', currencyDisplay: 'symbol' })} </dd> </div> <div class="flex flex-col-reverse gap-y-3 border-s ps-7 border-zinc-50/20"> <dt class="text-zinc-300 text-base leading-7">Sold <span class="text-sm">(units)</span></dt> <dd class="text-zinc-50 text-3xl font-semibold tracking-tight"> {information.unitsSold}M </dd> </div> </dl> </div> </div>
/// <reference types="cypress" /> describe('Navigation Test', () => { it('should navigate to different tabs', () => { cy.visit('/') // make sure we are on navigate page initially cy.location('pathname').should('eq', '/tabs/tab-navigate') cy.get('[routerlink="/tabs/tab-saved"]').click() cy.location('pathname').should('eq', '/tabs/tab-saved') cy.get('[routerlink="/tabs/tab-schedule"]').click() cy.location('pathname').should('eq', '/tabs/tab-schedule') cy.get('[routerlink="/tabs/tab-statistics"]').click() cy.location('pathname').should('eq', '/tabs/tab-statistics') cy.get('[routerlink="/tabs/tab-profile"]').click() cy.location('pathname').should('eq','/tabs/tab-profile') cy.get('[routerlink="/tabs/tab-navigate"]').click() cy.location('pathname').should('eq', '/tabs/tab-navigate') }) }) describe('Canvas Map Test', () => { it('should have a canvas map', () => { // Stub the navigator.geolocation API cy.window().then((win) => { cy.stub(win.navigator.geolocation, 'getCurrentPosition', (successCallback, errorCallback, options) => { // Define a mock position const mockPosition = { coords: { latitude: -25.754355915724386, // Example latitude longitude: 28.231426139280625, // Example longitude accuracy: 100, // Example accuracy }, }; // Call the success callback with the mock position successCallback(mockPosition); }); }); // cy.viewport('iphone-6') cy.visit('/tabs/tab-navigate') cy.get('.mapboxgl-canvas').should('exist') }) }) describe('Authentication Test', () => { it('should create a new user', () => { cy.visit('/tabs/tab-profile') cy.get('.in-toolbar > .list-md > :nth-child(2)').click() cy.get('[data-cy="input-fn"]').type("Bob") cy.get('[data-cy="input-ln"]').type("Marley") cy.get('[data-cy="input-email"]').type("[email protected]") cy.get('[data-cy="input-password"]').type("@bobmarley1") cy.get('[data-cy="btn-confirm-signup"]').click() // cy.get('[data-cy="Welcome-text"]').should("to.have.text"," Welcome Bob !") }) it('should log in as Bob Marley', () => { cy.visit('/tabs/tab-profile') cy.get('.in-toolbar > .list-md > :nth-child(1)').click() cy.get('[data-cy="login-email-input"]').type("[email protected]") cy.get('[data-cy="login-password-input"]').type("@bobmarley1") // cy.get('[data-cy="btn-login-confirm"]').click() // cy.get('[data-cy="Welcome-text"]').should("to.have.text"," Welcome Bob !") }) it('should log out', () => { cy.viewport('iphone-6') cy.visit('/tabs/tab-profile') cy.get('.in-toolbar > .list-md > :nth-child(2)').click() cy.get('[data-cy="input-fn"]').type("Bob") cy.get('[data-cy="input-ln"]').type("Marley") cy.get('[data-cy="input-email"]').type("[email protected]") cy.get('[data-cy="input-password"]').type("@bobmarley1") cy.get('[data-cy="btn-confirm-signup"]').click() cy.get('[data-cy="logout-button"]').click() cy.get('[data-cy="login-button"]').should('exist'); }) })
import { message } from "@/utils/message"; import dayjs from "dayjs"; import { addDialog } from "@/components/ReDialog"; import editForm from "../update.vue"; import { ElMessageBox, Sort } from "element-plus"; import { type PaginationProps } from "@pureadmin/table"; import { CommonUtils } from "@/utils/common"; import { AddGroupRequest } from "../utils/grouptypes"; import { isString, isEmpty } from "@pureadmin/utils"; import { useMultiTagsStoreHook } from "@/store/modules/multiTags"; import { GroupQuery, getGroupList, addGroupApi, CosGroupRequest, updateGroupApi, deleteSystemNoticeApi } from "@/api/system/group"; import { reactive, ref, onMounted, h, toRaw } from "vue"; import { useRouter, useRoute, type LocationQueryRaw, type RouteParamsRaw } from "vue-router"; export function useGroup() { const route = useRoute(); const router = useRouter(); const getParameter = isEmpty(route.params) ? route.query : route.params; const defaultSort: Sort = { prop: "createTime", order: "descending" }; const formRef = ref(); const dataList = ref([]); const pageLoading = ref(true); const multipleSelection = ref([]); const pagination: PaginationProps = { total: 0, pageSize: 10, currentPage: 1, background: true }; const searchParam = reactive<GroupQuery>({ group_name: undefined, page_num: "1", page_size: "20", orderColumn: defaultSort.prop, orderDirection: defaultSort.order }); const tableColumns: TableColumnList = [ { type: "selection", align: "left" }, { label: "序号", prop: "id", minWidth: 100 }, { label: "组名称", prop: "groupName", minWidth: 120 }, { label: "组描述", prop: "groupDescription", minWidth: 120 }, { label: "是否免费", prop: "isFree", minWidth: 120 }, { label: "价格", prop: "price", minWidth: 120 }, { label: "创建时间", minWidth: 180, prop: "createTime", sortable: "custom", formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") }, { label: "更新时间", minWidth: 180, prop: "updateTime", sortable: "custom", formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss") }, { label: "操作", fixed: "right", width: 240, slot: "operation" } ]; function detail( parameter: LocationQueryRaw | RouteParamsRaw, model: "query" | "params" ) { Object.keys(parameter).forEach(param => { if (!isString(parameter[param])) { parameter[param] = parameter[param].toString(); } }); if (model === "params") { useMultiTagsStoreHook().handleTags("push", { path: `/system/cos/media:group_id`, name: "SystemCosMedia", params: parameter, meta: { title: { zh: `No.${parameter.id} - 详情信息`, en: `No.${parameter.id} - DetailInfo` } } }); } router.push({ name: "SystemCosMedia", params: parameter }); } const initToDetail = (model: "query" | "params") => { if (getParameter) detail(getParameter, model); }; function openDialog(title = "新增", row?: AddGroupRequest) { addDialog({ title: `${title}组`, props: { formInline: { id: row?.id ?? "", groupName: row?.groupName ?? "", groupDescription: row?.groupDescription ?? "", isFree: row?.isFree ?? "", price: row?.price ?? "" } }, width: "40%", draggable: true, fullscreenIcon: true, closeOnClickModal: false, contentRenderer: () => h(editForm, { ref: formRef }), beforeSure: (done, { options }) => { const formRuleRef = formRef.value.getFormRuleRef(); const curData = options.props.formInline as AddGroupRequest; formRuleRef.validate(valid => { if (valid) { console.log("curData", curData); // 表单规则校验通过 if (title === "新增") { handleAdd(curData, done); } else { curData.id = row.id; handleUpdate(curData, done); } } }); } }); } async function handleAdd(row, done) { await addGroupApi(row as CosGroupRequest).then(() => { message(`您新增了通知标题为${row.groupName}的这条数据`, { type: "success" }); // 关闭弹框 done(); // 刷新列表 getGroupTable(); }); } async function handleUpdate(row, done) { await updateGroupApi(row as CosGroupRequest).then(() => { message(`您新增了通知标题为${row.groupName}的这条数据`, { type: "success" }); // 关闭弹框 done(); // 刷新列表 getGroupTable(); }); } async function getGroupTable(sort: Sort = defaultSort) { if (sort != null) { CommonUtils.fillSortParams(searchParam, sort); } CommonUtils.fillPaginationParams(searchParam, pagination); pageLoading.value = true; const { data } = await getGroupList(toRaw(searchParam)).finally(() => { pageLoading.value = false; }); dataList.value = data.rows; pagination.total = data.total; } async function handleDelete(row) { await deleteSystemNoticeApi([row.noticeId]).then(() => { message(`您删除了通知标题为${row.name}的这条数据`, { type: "success" }); // 刷新列表 getGroupTable(); }); } async function handleBulkDelete(tableRef) { if (multipleSelection.value.length === 0) { message("请选择需要删除的数据", { type: "warning" }); return; } ElMessageBox.confirm( `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的通知吗?`, "系统提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning", dangerouslyUseHTMLString: true, draggable: true } ) .then(async () => { await deleteSystemNoticeApi(multipleSelection.value).then(() => { message(`您删除了通知编号为[ ${multipleSelection.value} ]的数据`, { type: "success" }); // 刷新列表 getGroupTable(); }); }) .catch(() => { message("取消删除", { type: "info" }); // 清空checkbox选择的数据 tableRef.getTableRef().clearSelection(); }); } function doSearch() { // 点击搜索的时候 需要重置分页 pagination.currentPage = 1; getGroupTable(); } function resetForm(formEl, tableRef) { if (!formEl) return; // 清空查询参数 formEl.resetFields(); // 清空排序 searchParam.orderColumn = undefined; searchParam.orderDirection = undefined; tableRef.getTableRef().clearSort(); // 重置分页并查询 doSearch(); } onMounted(() => { getGroupTable(); }); return { searchParam, getGroupTable, doSearch, resetForm, openDialog, dataList, tableColumns, pageLoading, defaultSort, pagination, handleBulkDelete, multipleSelection, handleDelete, detail, initToDetail, getParameter, router }; }
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\SeriesController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/ola', function () { return view('ola'); }); Route::get('/series', 'App\Http\Controllers\SeriesController@listarSeries'); Route::get('/series/criar', 'App\Http\Controllers\SeriesController@create'); Route::post('/series/store', 'App\Http\Controllers\SeriesController@store'); Route::post('/series/destroy/{serie}', 'App\Http\Controllers\SeriesController@destroy')->name('series.destroy'); Route::get('/series/{serie}/edit', 'App\Http\Controllers\SeriesController@edit')->name('series.edit'); Route::post('/series/{serie}', 'App\Http\Controllers\SeriesController@update')->name('series.update');
"use client"; import { useState } from "react"; import AccountHeader from "./AccountHeader"; import SectionWrapper from "./SectionWrapper"; import DashboardSidebar from "./DashboardSidebar"; import Login from "./Auth/Login"; import { useSession } from "next-auth/react"; const Dashboard = ({ pastOrders }) => { const [tab, setTab] = useState("Overview"); const { data: session } = useSession(); const resetTab = () => { setTab("Overview"); }; return ( <> {session ? ( <div className="flex flex-col mb-6 lg:mb-4"> <AccountHeader session={session} tab={tab} resetTab={resetTab} /> {tab === "Overview" ? ( <div className="md:flex md:flex-row w-full h-full my-2 md:my-8 md:gap-6"> <DashboardSidebar tab={tab} setTab={setTab} resetTab={resetTab} /> <div className="hidden md:flex w-full"> <SectionWrapper session={session} pastOrders={pastOrders} tab={tab} /> </div> </div> ) : ( <div className="md:flex md:flex-row my-2 md:my-8 md:gap-6"> <div className="hidden md:flex"> <DashboardSidebar tab={tab} setTab={setTab} resetTab={resetTab}/> </div> <SectionWrapper session={session} pastOrders={pastOrders} tab={tab} /> </div> )} </div> ) : ( <Login /> )} </> ); }; export default Dashboard;
import { StyleSheet, TouchableNativeFeedback, View, ActivityIndicator, } from "react-native"; import React from "react"; import themes from "../constants/themes"; import useMode from "../hooks/useMode"; import { useRouter } from "expo-router"; import Avatar from "./Avatar"; import Typography from "./Typography"; import { IChat, IUser } from "../types"; import axios from "axios"; import Constants from "expo-constants"; type IUserListItem = { isLast: boolean; user: IUser; }; const UserListItem = (props: IUserListItem) => { const { user, isLast } = props; const mode = useMode(); const router = useRouter(); const [loading, setLoading] = React.useState(false); const [createdChat, setCreatedChat] = React.useState<IChat | null>(null); const apiUrl = Constants.expoConfig?.extra?.apiUrl; const goToChat = async () => { setLoading(true); try { const response = await axios.post( `${apiUrl}/chats/private`, { userId: user._id, }, { headers: { "Content-Type": "application/json", }, } ); if (response.data.success) { setCreatedChat(response.data.chat); } } catch (error) { // console.log(error); } setLoading(false); }; React.useEffect(() => { if (createdChat) { router.push(`/chats/${createdChat._id}`); } setCreatedChat(null); }, [createdChat]); return ( <TouchableNativeFeedback background={TouchableNativeFeedback.Ripple( themes[mode].colors.chatListItemRipple, false )} onPress={goToChat} disabled={loading} > <View style={[ styles.container, { borderBottomWidth: isLast ? 0 : 1, borderBottomColor: themes[mode].colors.chatListItemBorder, }, ]} > <Avatar uri={user.photoURL} size={48} /> <View style={styles.center}> <Typography variant="h3" textProps={{ numberOfLines: 1 }}> {user.displayName} </Typography> <View style={{ height: 2 }} /> <Typography variant="body1" textProps={{ numberOfLines: 1 }}> {user.email} </Typography> </View> <View> {loading && ( <ActivityIndicator size="small" color={themes[mode].colors.highlight} /> )} </View> </View> </TouchableNativeFeedback> ); }; export default UserListItem; const styles = StyleSheet.create({ container: { flexDirection: "row", alignItems: "center", flex: 1, padding: 10, paddingVertical: 15, }, center: { flex: 1, paddingHorizontal: 20, }, });
/* * Copyright (c) 2015-2022, Episode Six and/or its affiliates. All rights reserved. * EPISODE SIX PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * THIS IS CONFIDENTIAL AND PROPRIETARY TO EPISODE SIX, and any * copying, reproduction, redistribution, dissemination, modification, or * other use, in whole or in part, is strictly prohibited without the prior * written consent of (or as may be specifically permitted in a fully signed * agreement with) Episode Six. Violations may result in severe civil and/or * criminal penalties, and Episode Six will enforce its rights to the maximum * extent permitted by law. */ import React, { useState } from "react"; export const MessageContext = React.createContext<any>({}); // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const MessageContextProvider = (props: any) => { const { children } = props; const [errorMsg, setErrorMsg] = useState(undefined); const [warningMsg, setWarningMsg] = useState(undefined); const [successMsg, setSuccessMsg] = useState(undefined); const resetMessageValues = () => { setErrorMsg(undefined); setWarningMsg(undefined); setSuccessMsg(undefined); }; const value = { errorMsg, setErrorMsg, warningMsg, setWarningMsg, successMsg, setSuccessMsg, resetMessageValues, }; return ( <MessageContext.Provider value={value}>{children}</MessageContext.Provider> ); }; export default MessageContextProvider;
import 'package:dartz/dartz.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:numbers/features/numbers_trivia/domain/entities/number_trivia.dart'; import 'package:numbers/features/numbers_trivia/domain/repositories/number_trivia_repository.dart'; import 'package:numbers/features/numbers_trivia/domain/usecases/get_concrete_number_trivia.dart'; // class MockNumberTriviaRepository extends Mock // implements NumberTriviaRepository {} @GenerateMocks([NumberTriviaRepository]) import 'get_concrete_number_trivia_test.mocks.dart'; void main() { late GetConcreteNumberTrivia usecase; late MockNumberTriviaRepository mockNumberTriviaRepository; setUp(() { mockNumberTriviaRepository = MockNumberTriviaRepository(); usecase = GetConcreteNumberTrivia(mockNumberTriviaRepository); }); var testNumber = 1; var testNumberTrivia = NumberTrivia(text: 'test', number: testNumber); test("should get a trivia for the number from the repository", () async { //arrange when(mockNumberTriviaRepository.getConcreteNumberTrivia(testNumber)) .thenAnswer((realInvocation) async => Right(testNumberTrivia)); //execute final result = await usecase.call(number: testNumber); //verify expect(result, Right(testNumberTrivia)); verify(mockNumberTriviaRepository.getConcreteNumberTrivia(testNumber)); verifyNoMoreInteractions(mockNumberTriviaRepository); }); }
import 'package:flutter/material.dart'; import 'package:flutter_crud/models/user.dart'; import 'package:provider/provider.dart'; import 'package:provider/single_child_widget.dart'; import '../providers/users.dart'; class UserForm extends StatelessWidget{ final _form = GlobalKey<FormState>(); final Map<String?, String?> _formData = {}; void loadFormData(User user){ if(user != null){ _formData['id'] = user.id; _formData['nome'] = user.nome; _formData['email'] = user.email; _formData['avatarURL'] = user.avatarURL; } } @override Widget build(BuildContext context){ final user = ModalRoute.of(context)?.settings.arguments as User?; if (user != null) { loadFormData(user); } return Scaffold( appBar: AppBar(title: Text('Formulário de usuário'), actions: <Widget>[ IconButton(icon: Icon(Icons.save), onPressed: (){ //final isValid = _form.currentState!.validate(); // if(isValid){ _form.currentState?.save(); Provider.of<Users>(context, listen: false).put(User( id: _formData['id'] ?? '', nome: _formData['nome'] ?? '', email: _formData['email'] ?? '', avatarURL: _formData['avatarURL'] ?? '', ), ); // User Navigator.of(context).pop(); } //}, ), ], ), body: Padding(padding: EdgeInsets.all(15), child: Form( key: _form, child: Column( children: <Widget>[ TextFormField( initialValue: _formData['nome'], decoration: InputDecoration(labelText: 'Nome'), validator: (value){ return 'Ocorreu um erro'; }, onSaved:(value) => _formData['nome'] = value, ), TextFormField( initialValue: _formData['email'], decoration: InputDecoration(labelText: 'Email'), validator: (value){ return 'Ocorreu um erro'; }, onSaved:(value) => _formData['email'] = value, ), TextFormField( initialValue: _formData['avatarURL'], decoration: InputDecoration(labelText: 'URL do avatar'), validator: (value){ return 'Ocorreu um erro'; }, onSaved:(value) => _formData['avatarURL'] = value, ), ] ), ) ) ); } }
{% extends "base.html" %} {% load staticfiles %} {% block content %} <!--/#header--> <section id="page-breadcrumb"> <div class="vertical-center sun"> <div class="container"> <div class="row"> <div class="action"> <div class="col-sm-12"> <strong><h1 class="title wow fadeInLeft">DIREKTORI SISWA</h1></strong> <ol class="breadcrumb wow fadeInRight"> <li><a href='{% url "post_home" %}'>Home</a> </li> <li class="active">Siswa</li> <li class="active">Direktori Siswa</li> </ol> </div> </div> </div> </div> </div> </section> <!--/#action--> <section id="blog" class="padding-top"> <div class="container "> <div class="row "> <div class="col-md-9 col-sm-7 "> <div class="row"> <div class="well table-responsive"> <table id="" class="display table table-bordered table-striped"> <thead> <tr class="headings"> <!-- <th>No </th> --> <th>NIS </th> <th style="width:200px;">NAMA </th> <th style="width:150px;">Jenis Kelamin </th> <th>Jurusan </th> <th>Kelas </th> <th style="width:20px;">&nbsp;</th> </tr> </thead> <tbody> {% for obj in list_siswa %} <tr> <!-- <td>1</td> --> <td class=" ">{{ obj.nis_siswa }}</td> <td class=" ">{{ obj.nama_siswa }}</td> {% if obj.kelamin_siswa == 1 %} <td class=" ">Perempuan</td> {% elif obj.kelamin_siswa == 2 %} <td class=" ">Laki-Laki</td> {% else %} <td class=" ">not specified</td> {% endif %} <td class=" ">{{ obj.siswa_jurusan }}</td> <td class=" ">{{ obj.siswa_kelas }}</td> <td class=" "> <div class="btn-group"> <a href="#" data-toggle="modal" data-target="#{{ obj.id_siswa }}" class="btn btn-sm bg-orange btn-flat" data-toggle="tooltip" data-original-title="Preview"><i class="glyphicon glyphicon-zoom-in"></i></a> </div> </td> <!-- Modal --> <div class="modal fade" id="{{ obj.id_siswa }}" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Tutup"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Biodata Siswa</h4> </div> <div class="modal-body"> <div class="row"> <div class="col-md-3"> {% if obj.foto_siswa %} <img src="{{ obj.foto_siswa.url }}" style="max-width:200px;"> {% else %} <img src="{% static 'img/ico/avatar.png' %}" style="max-width:200px;"> {% endif %} </div> <div class="col-md-9"> <dl class="dl-horizontal"> <dt>NIS</dt> <dd>{{ obj.nis_siswa }}</dd> <dt>Nama</dt> <dd>{{ obj.nama_siswa }}</dd> <dt>Jenis Kelamin</dt> {% if obj.kelamin_siswa == 1 %} <dd>Perempuan</dd> {% elif obj.kelamin_siswa == 2 %} <dd>Laki-Laki</dd> {% else %} <dd>not specified</dd> {% endif %} <dt>Jurusan</dt> <dd>{{ obj.siswa_jurusan }}</dd> <dt>Kelas</dt> <dd>{{ obj.siswa_kelas }}</dd> </dl> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button> </div> </div> </div> </div> </tr> {% endfor %} </tbody> </table> </div> </div> </div> {% endblock %}
import { Android, Email, GitHub, LinkedIn, ViewQuilt, Web, } from "@mui/icons-material"; import { motion } from "framer-motion"; import React from "react"; import { Link } from "react-router-dom"; const myServices = [ { image: <Web sx={{ color: "#3cefab" }} />, title: "Web Development", description: "Building modern and responsive websites tailored to your needs.", work: "12 projects", }, { image: <Android sx={{ color: "#3cefab" }} />, title: "Mobile App Development", description: "Creating cross-platform mobile applications for iOS and Android.", work: "5 projects", }, { image: <ViewQuilt sx={{ color: "#3cefab" }} />, title: "Backend development", description: "Developing different backend apps which are secure, reliable and scalable.", work: "10 projects", }, { image: <ViewQuilt sx={{ color: "#3cefab" }} />, title: "Automation Expert", description: "Crafting different bots which are helpful in handling day to day repetitive tasks.", work: "7 projects", }, ]; const Services = () => { return ( <div className="text-[#FFFFFF]" style={{ // height: "100%", background: "#272727", // flex: 1, }} > <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.5 }} className="flex items-start p-4 gap-2 flex-col mt-2" > <h1 className="text-3xl font-bold ml-4 text-[#3cefab]">Services</h1> <div className="p-4 gap-4 grid grid-cols-1 md:grid-cols-1 lg:grid-cols-2 w-full" style={{ display: "flex", flexWrap: "wrap", }} > <div className="flex gap-6 flex-col items-start justify-start w-[500px]"> <motion.p className="text-[#3cefab] text-[16px]" initial={{ y: -50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 0 * 0.5, duration: 0.7 }} > introduction </motion.p> <motion.h1 className="text-[#FFFFFF] text-[36px] font-bold" initial={{ y: -50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 1 * 0.5, duration: 0.7 }} > Hello! I'M <br /> Abreham Tilahun </motion.h1> <motion.p className="text-[#FFFFFF] text-[20px]" initial={{ y: -50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 2 * 0.5, duration: 0.7 }} > Every great design being with an even better story </motion.p> <motion.p className="text-[#8d8d8d] text-[15px]" initial={{ y: -50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: 3 * 0.5, duration: 0.7 }} > I am Abreham Tilahun, a highly skilled full-stack developer with expertise in MERN stack and Automation Expert and React Native mobile app development. With over more than one year of experience, I have successfully completed numerous projects that have involved both front-end and back-end development. </motion.p> </div> <div className=" flex gap-4 flex-col w-[500px] justify-between"> {myServices.map((service, index) => ( <motion.div key={index} className="bg-[#222222] p-5 flex justify-between items-start" initial={{ y: -50, opacity: 0 }} animate={{ y: 0, opacity: 1 }} transition={{ delay: index * 0.5, duration: 0.7 }} > <div className="flex gap-3 flex-col items-start justify-start"> <div className="flex items-start justify-start flex-col"> <h2 className="text-[#3cefab] text-[20px] font-bold"> {service.title} </h2> <p className="text-[#8d8d8d] text-[14px]"> {service.description} </p> </div> <p>{service.work}</p> </div> <i>{service.image}</i> </motion.div> ))} </div> </div> </motion.div> </div> ); }; export default Services;
body { font-family: "Lato", sans-serif; /* font is inherit by child tags. More efficient then use the universal selector */ font-weight: 400; /*font-size: 16px;*/ /* Remove . Now we are using 10px root font-size*/ line-height: 1.7; color: $color-grey-dark; } .heading-primary { color: $color-white; text-transform: uppercase; margin-bottom: 6rem; /*add margin to separate main button*/ &--main { display: block; font-size: 6rem; font-weight: 700; letter-spacing: 3.5rem; animation: moveInLeft 1s ease-out; @include respond(phone) { letter-spacing: 1rem; } } &--sub { display: block; font-size: 2rem; font-weight: 400; letter-spacing: 1.75rem; animation: moveInRight 1s ease-out; @include respond(phone) { letter-spacing: .5rem; } } } .heading-secondary { font-size: 3.5rem; text-transform: uppercase; font-weight: 700; display: inline-block; background-image: linear-gradient(to right, $color-primary-light, $color-primary-dark); // background-color can not use gradients -webkit-background-clip: text; // clip background to the text color: transparent; // hide the text to show the backgroup clipped letter-spacing: 2px; // using px instead rem transition: all .2s; @include respond(tab-port) { font-size: 3rem; } @include respond(phone) { font-size: 2.5rem; } &:hover { transform: skewY(2deg) skewX(15deg) scale(1.1); text-shadow: .5rem 1rem 2rem rgba($color-black, .2); } } .heading-tertiary { font-size: $default-font-size; font-weight: 700; text-transform: uppercase; } .paragraph { font-size: $default-font-size; &:not(:last-child) { margin-bottom: 3rem; } }
<?php $args = array( 'posts_per_page' => 3, 'orderby' => 'date', 'order' => 'DESC', 'post_status' => 'publish' ); $posts = new WP_Query($args); if ($posts->have_posts()) : ?> <section class="grid-posts latest-posts"> <div class="container"> <h2 class="section-title"> <span>Latest Articles</span> </h2> <div class="post-block"> <?php while ($posts->have_posts()): $posts->the_post(); global $post; $img = get_the_post_thumbnail($post->ID); ?> <div class="post-item item"> <div class="item-img"> <?php echo $img; ?> </div> <div class="item-text"> <?php if (get_the_title()):?> <h3 class="item-title"> <a href="<?php the_permalink($post->ID); ?>"> <?php the_title(); ?> </a> </h3> <?php endif; ?> <?php if (get_the_excerpt()):?> <div class="excerpt"><?php the_excerpt(); ?></div> <?php endif; ?> <a href="<?php echo esc_url( get_permalink() ) ?>" rel="bookmark">More</a> </div> </div> <?php endwhile;?> </div> <?php wp_reset_query(); ?> </div> </section> <?php endif; ?>
import { prismaPG } from '@/config'; import faker from '@faker-js/faker'; async function createFoodType() { const foodType = await prismaPG.productTypes.create({ data: { name: 'foods', }, }); return foodType; } async function createCategories(typeId: number) { await prismaPG.productCategories.createMany({ data: [ { name: faker.name.firstName(), image: faker.internet.url(), typeId, }, { name: faker.name.firstName(), image: faker.internet.url(), typeId, }, { name: faker.name.firstName(), image: faker.internet.url(), typeId, }, { name: faker.name.firstName(), image: faker.internet.url(), typeId, }, ], }); } async function getCategoriesIds() { const categories = await prismaPG.productCategories.findMany({}); return categories; } async function createSingleCategory(typeId: number) { return await prismaPG.productCategories.create({ data: { name: faker.name.firstName(), image: faker.internet.url(), typeId, }, }); } const categoriesFactory = { createFoodType, createCategories, getCategoriesIds, createSingleCategory, }; export default categoriesFactory;
import { acceptHMRUpdate, defineStore } from 'pinia' import { shallowRef, ShallowRef } from 'vue' import useMvtStyles from '@/composables/mvt-styles/mvt-styles.composable' import type { LayerId } from '@/stores/map.store.model' import { IMvtConfig, SimpleStyle, StyleItem, VectorSourceDict, VectorStyleDict, StyleSpecification, } from '@/composables/mvt-styles/mvt-styles.model' import { bgConfigFixture } from '@/__fixtures__/background.config.fixture' export const useStyleStore = defineStore( 'style', () => { const styleService = useMvtStyles() const bgStyle: ShallowRef<StyleItem[] | undefined | null> = shallowRef() const bgVectorSources: ShallowRef<VectorSourceDict> = shallowRef(new Map()) const bgVectorBaseStyles: ShallowRef<VectorStyleDict> = shallowRef( new Map() ) const isExpertStyleActive: ShallowRef<boolean> = shallowRef(false) const styleSerial: ShallowRef<String | null> = shallowRef(null) const appliedStyle: ShallowRef<StyleSpecification | undefined> = shallowRef() const registerUrls: ShallowRef<Map<string, string>> = shallowRef( new Map([ ['get', '/getvtstyle'], ['upload', '/uploadvtstyle'], ['delete', '/deletevtstyle'], ]) ) const promises: Promise<{ id: LayerId; config: IMvtConfig }>[] = [] bgConfigFixture().bg_layers.forEach(bgLayer => { if (bgLayer.vector_id) { const conf = styleService.setConfigForLayer( bgLayer.icon_id, bgLayer.vector_id ) promises.push( conf.then(c => { return { id: bgLayer.id, config: c as IMvtConfig } }) ) } }) Promise.all(promises).then(styleConfigs => { const vectorDict: VectorSourceDict = new Map() styleConfigs.forEach(c => vectorDict.set(c.id, c.config)) bgVectorSources.value = vectorDict }) function setRegisterUrl(key: string, url: string) { registerUrls.value.set(key, url) } function setBgVectorSources(vectorDict: VectorSourceDict) { bgVectorSources.value = vectorDict } function removeBaseStyle(id: LayerId) { const styleDict: VectorStyleDict = new Map() bgVectorBaseStyles.value.forEach((style, key) => { if (key !== id) styleDict.set(key, style) }) bgVectorBaseStyles.value = styleDict } function setBaseStyle(id: LayerId, baseStyle: StyleSpecification) { const styleDict: VectorStyleDict = new Map() bgVectorBaseStyles.value.forEach((style, key) => styleDict.set(key, style) ) styleDict.set(id, baseStyle) bgVectorBaseStyles.value = styleDict } function setSimpleStyle(simpleStyle: SimpleStyle | null) { bgStyle.value = styleService.getRoadStyleFromSimpleStyle(simpleStyle) disableExpertStyle() } function setStyle(style: StyleItem[] | null) { bgStyle.value = style disableExpertStyle() } function disableExpertStyle() { isExpertStyleActive.value = false } function enableExpertStyle() { isExpertStyleActive.value = true } return { bgStyle, bgVectorSources, bgVectorBaseStyles, isExpertStyleActive, appliedStyle, removeBaseStyle, setBaseStyle, setBgVectorSources, setRegisterUrl, setSimpleStyle, setStyle, disableExpertStyle, enableExpertStyle, styleSerial, registerUrls, } }, {} ) if (import.meta.hot) { import.meta.hot.accept(acceptHMRUpdate(useStyleStore, import.meta.hot)) }
// ** Next Imports import Head from 'next/head' import { Router } from 'next/router' // ** Loader Import import NProgress from 'nprogress' // ** Emotion Imports import { CacheProvider } from '@emotion/react' // ** Config Imports import themeConfig from 'src/configs/themeConfig' // ** Component Imports import UserLayout from 'src/layouts/UserLayout' import ThemeComponent from 'src/@core/theme/ThemeComponent' // ** Contexts import { SettingsConsumer, SettingsProvider } from 'src/@core/context/settingsContext' // ** Utils Imports import { createEmotionCache } from 'src/@core/utils/create-emotion-cache' // ** React Perfect Scrollbar Style import 'react-perfect-scrollbar/dist/css/styles.css' // ** Global css styles import '../../styles/globals.css' // Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyBwD-48GnILxzepH4Nm9ETp7b2eEZptZRc", authDomain: "shree-durga-jewellers-e7a42.firebaseapp.com", projectId: "shree-durga-jewellers-e7a42", storageBucket: "shree-durga-jewellers-e7a42.appspot.com", messagingSenderId: "462889931288", appId: "1:462889931288:web:e6562adbc67ceb07d8296d", measurementId: "G-ET4V6Q045S" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const auth = getAuth(app); const clientSideEmotionCache = createEmotionCache() // ** Pace Loader if (themeConfig.routingLoader) { Router.events.on('routeChangeStart', () => { NProgress.start() }) Router.events.on('routeChangeError', () => { NProgress.done() }) Router.events.on('routeChangeComplete', () => { NProgress.done() }) } // ** Configure JSS & ClassName const App = props => { const { Component, emotionCache = clientSideEmotionCache, pageProps } = props // Variables const getLayout = Component.getLayout ?? (page => <UserLayout>{page}</UserLayout>) return ( <CacheProvider value={emotionCache}> <Head> <title>{`SHREE DURGA JEWELLERS`}</title> <meta name='description' content={`Shree Durga Jewellers Bhilai`} /> <meta name='keywords' content='Shree Durga Jewellers, Jitendra Kumar Verma, Harsh Verma, SDJ, Shree Durga Jewellers Bhilai, Jewellery shops in Bhilai, Jewellery shops in Chhattisgarh' /> <meta name='viewport' content='initial-scale=1, width=device-width' /> </Head> <SettingsProvider> <SettingsConsumer> {({ settings }) => { return <ThemeComponent settings={settings}>{getLayout(<Component {...pageProps} />)}</ThemeComponent> }} </SettingsConsumer> </SettingsProvider> </CacheProvider> ) } export default App
# Functions for sourcing # Calculate parameters # takes input from GUI # returns vector with calculated parameters CalculateParameters <- function (d, S.plus, q) { p <- 2*d # resilience parameter k <- (p * S.plus)/q h <- p*S.plus b <- (2*d)/q return(c(p, k, h, b)) } # Initialize vectors # takes input from GUI # returns list with initialized vectors InitializeVectors <- function (C.init, S.plus, E.init, lamda.init, A.init, weeks, no.simulations, d) { Crav <- numeric(length = weeks+1) Crav[1] <- C.init S <- numeric(length = weeks+1) S[1] <- S.plus E <- numeric(length = weeks+1) E[1] <- E.init for (i in 1:weeks) { E[i+1] <- round((E[i] - d * E[1]), 2) } lamda <- numeric(length = weeks+1) lamda[1] <- lamda.init for (i in 1:weeks) { lamda[i+1] <- lamda[i] + d * lamda[1] } cues <- numeric(length = weeks+1) V <- numeric(length = weeks+1) V[1] <- min(c(1, max(c(0, (S.plus - Crav[1] - E[1]) )) )) A <- numeric(length = weeks+1) A[1] <- A.init addiction.all <- logical(no.simulations) return(list(Crav = Crav, S = S, E = E, lamda = lamda, cues = cues, V = V, A = A, addiction.all = addiction.all)) } # Initialize list for datastorage # takes no arguments # returns empty list InitializeList <- function () { list.output <- list() return(list.output) } # Simulate C, S, V, and A - core process # takes list "vectors" from InitializeVectors and vector "parameters" CalculateParameters, and input from GUI # returns list with simulated parameters SimulateAddictionComponents <- function (vectors, parameters, S.plus, q, weeks, d) { Crav <- vectors$Crav S <- vectors$S E <- vectors$E lamda <- vectors$lamda cues <- vectors$cues V <- vectors$V A <- vectors$A p <- parameters[1] k <- parameters[2] h <- parameters[3] b <- parameters[4] for (i in 1:weeks) { # calculate C(t+1) Crav[i+1] <- ( Crav[i] + b * min(c(1, (1-Crav[i]))) * A[i] - d * Crav[i] ) # calculate S(t+1) S[i+1] <- ( S[i] + p * max(c(0, (S.plus - S[i]))) - h * Crav[i] - k * A[i] ) # calculate V(t+1) V[i+1] <- min(c(1, max(c(0, (Crav[i] - S[i] - E[i]))))) # calculate A(t+1) # generate random component (cues) # set.seed(1) # for testing purposes - TAKE OUT AT THE END!!! cues[i] <- rpois(1, lamda[i]) f <- cues[i] * (q/7) # calculate A(t+1) if (f <= (q * (1 - V[i])) ) { # stay under max A[i+1] <- q * V[i] + f } else { A[i+1] <- q } } if (V[weeks+1] != 1) { addiction <- FALSE } else { addiction <- TRUE } return(list(cues = cues, A = A, Crav = Crav, S = S, V = V, addiction = addiction)) } # Build output dataframe # takes list "simulation" from SimulateAddictionComponents and list "vectors" # from InitializeVectorsand input from GUI # returns dataframe BuildOutputDataframe <- function (weeks, simulation, vectors) { cues <- simulation$cues A <- simulation$A Crav <- simulation$Crav S <- simulation$S V <- simulation$V E <- vectors$E lamda <- vectors$lamda output <- data.frame("t" = (1: (weeks+1))-1, "A" = A, "C" = Crav, "S" = S, "E" = E, "lamda" = lamda, "cues" = cues, "V" = V) return(output) } # Build the list for final storage # takes data.frame "df.output" from BuildOutputDataframe, list "simulation" from # SimulateAddictionComponents, and list "list.output" from InitializeList # returns list "output.addiction" BuildOutputList <- function (df.output, simulation, list.output) { addiction <- simulation$addiction output.w.success <- list(df.output, addiction) # includes success data list.output <- c(list.output, list(output.w.success)) # adds the new data to the list return(list.output) } # Looping function - calls functions SimulateAddictionComponents, BuildOutputDataframe, and # BuildOutputList # takes input from GUI, list "vectors" from InitializeVectors, vector "parameters" from # CalculateParameters, and list "list.output" from InitializeList # returns list "list.output" SimulateMultiple <- function (no.simulations, vectors, parameters, S.plus, q, weeks, d, list.output) { for (i in 1:no.simulations) { thisi <- i simulation <- SimulateAddictionComponents(vectors, parameters, S.plus, q, weeks, d) # returns list "simulation" df.output <- BuildOutputDataframe(weeks, simulation, vectors) # returns "df.outout" list.output <-BuildOutputList(df.output, simulation, list.output) # returns "output.addiction" } return(list.output) } # Calculate how often of the simulations patient is addicted after the time and get percentage # takes list "output.addiction" from SimulateMultiple and input from GUI # returns list "success.list" CalculateSuccess <- function (output.addiction, no.simulations) { addiction.all <- logical() for (i in 1:length(output.addiction)) { addiction.all <- c(addiction.all, output.addiction[[i]][[2]]) } success.percent <- (sum(addiction.all == FALSE) / no.simulations) * 100 trials.success <- which(addiction.all == FALSE) trials.fail <- which(addiction.all == TRUE) return(list(success.percent = success.percent, trials.success = trials.success, trials.fail = trials.fail)) } ############################################################################### # GRAPHS # Graphs over time # uses the output list to get data; x is always time t MakeGraphs <- function (graph.type, graph.success, output.addiction, success.list, q, S.plus) { a <- numeric() if (graph.success == TRUE) { a <- as.numeric( success.list[[2]][1]) } else if (graph.success == FALSE) { a <- as.numeric(success.list[[3]][1]) } x <- output.addiction[[ a ]][[1]]$t # time is always on x-axis x.lim <- c(0, length(x)) y <- numeric() y1 <- numeric() y.lim <- numeric() g.title <- character() ytile <- character() # SINGLE PLOTS if (graph.type == 1) { y <- 100*(output.addiction[[a]][[1]]$A) ytitle <- "A(t) in alcoholic beverages" g.title <- "Addictive acts A(t) per week over time" y.lim <- c(-0.05, 100*q) } else if (graph.type == 2) { y <- output.addiction[[a]][[1]]$C ytitle <- "C(t)" g.title <- "Craving over time" y.lim <- c(-0.05, 1.05) } else if (graph.type == 3) { y <- output.addiction[[a]][[1]]$S ytitle <- "S(t)" g.title <- "Self-control over time" y.lim <- c(-0.05, S.plus) } else if (graph.type == 4) { y <- output.addiction[[a]][[1]]$V ytitle <- "V(t)" g.title <- "Vulnerability over time" y.lim <- c(-0.05, 1) } else if (graph.type == 6) { y <- output.addiction[[a]][[1]]$V ytitle <- "V(t) and S(t)" g.title <- "Vulnerability V(t) and Self-Control S(t) over time" y.lim <- c(-0.05, 1) y1 <- output.addiction[[a]][[1]]$S g.legend <- c("S(t)", "V(t)") } else if (graph.type == 5) { y <- output.addiction[[a]][[1]]$A ytitle <- "A(t) and C(t)" g.title <- "Addictive acts A(t) and craving C(t) over time" y.lim <- c(-0.25, 1) y1 <- output.addiction[[a]][[1]]$C g.legend <- c("C(t)", "A(t)") } plot(x, y, bty = "n", las = 1, xlab = "Time (in weeks)", lwd = 2, xlim = x.lim, type = "l", ylab = ytitle, ylim = y.lim, main = g.title, cex.lab = 1.5) if (graph.type == 5 | graph.type == 6) { lines(x, y1, lty = 2, lwd = 2) legend("bottomright", legend = g.legend, lty = c(2, 1), lwd = 2) } } # Bifurcation diagrams # takes list "bifurc", Y ("C" or "S"), input from GUI # renders a plot MakeBifurcationDiagram <- function (bifurc, Y, S.plus, q, d, C.init, E.init, lamda.init, A.init) { weeks <- 300 # simulate total 500, later burn 250 no.simulations <- 1 # 1 time for each bifurcation parameter step # Arguments to be called in CalculateParameters args1 <- list(d = d, S.plus = S.plus, q = q) # argument list to be used in InitializeVectors args2 <- list(C.init = C.init, S.plus = S.plus, E.init = E.init, lamda.init = lamda.init, A.init = A.init, weeks = weeks, no.simulations = no.simulations, d = d) # create lists to be used in plot creation if (bifurc == 1) { bifurc.list <- list(name = "E", min = -1, max = 1) } else if (bifurc == 2) { bifurc.list <- list(name = "S.plus", min = 0, max = 1) } else if (bifurc == 3) { bifurc.list <- list(name = "d", min = 0, max = 1) } else if (bifurc == 4) { bifurc.list <- list(name = "C.init", min = 0, max = 1) } else if (bifurc == 5) { bifurc.list <- list(name = "lamda", min = 0, max = 1) } else if (bifurc == 6) { bifurc.list <- list(name = "A.init", min = 0, max = 1) } # make sequence of bifurcation parameter min <- bifurc.list[[2]] max <- bifurc.list[[3]] if (bifurc == 6) { max <- q } bifurc.sequence <- seq(min, max, 0.05) # sequence for bifurc # set to take either C or S from dataframe if (Y == "C") { y <- 3 y.lim <- c(-0.25, 1.25) } else if (Y == "S") { y <- 4 y.lim <- c(-0.25, (S.plus+0.25)) } # create empty plot plot(c(min, max), c(0, 0), type = "n", pch = ".", xlab = bifurc.list[[1]], ylab = Y, bty = "n", las = 1, ylim = y.lim, cex.lab = 1.5, main = "Bifurcation Diagram", lwd = 2) # simulate the data for (i in bifurc.sequence) { thisi <- i # circumvents some weird ShinyR behavior if (bifurc == 1) { args2[[3]] <- thisi } else if (bifurc == 2) { args1[[2]] <- thisi args2[[2]] <- thisi } else if (bifurc == 3) { args1[[1]] <- thisi args2[[8]] <- thisi } else if (bifurc == 4) { args2[[1]] <- thisi } else if (bifurc == 5) { args2[[4]] <- thisi } else if (bifurc == 6) { args2[[5]] <- thisi } for (k in 1:50) { thisk <- k parameters <- do.call(CalculateParameters, args1) # returns "parameters" vectors <- do.call(InitializeVectors, args2) # returns "vectors" #necessary once at this point to create argslist with "parameters" and "vectors" # argument list to be used in SimulateAddictionComponents args3 <- list(vectors = vectors, parameters = parameters, S.plus = S.plus, q = q, weeks = weeks, d = d) if (bifurc == 2) { args3[[3]] <- thisi } else if (bifurc == 3) { args3[[6]] <- thisi } simulation <- do.call(SimulateAddictionComponents, args3) # returns list "simulation" df.output <- BuildOutputDataframe(weeks, simulation, vectors) # returns "df.outout" # burn first 250 of previously 500 created, plot last 250 for (j in 100:weeks) { points(i, df.output[j, y]) } } } }
### How community forest management performs when REDD+ payments fail [supplemental] ### Data management of Pemba forest cover observations, ### followed by sign test of the matching estimator for ATET, ### as described in Ferman (2021) J. of Econometrics. ### SECTION 0: DATA MANAGEMENT ### SECTION 1: SPATIAL PREDICTIVE MODEL ### SECTION 2: FIND MATCHING CONTROLS FOR EACH TREATED SHEHIA (COFMA) WARDS ### SECTION 3: ESTIMATION AND SIGNIFICANCE TESTING OF ATET (SUPPLEMENTAL) ### Packages. library(MatchIt) library(dplyr) library(spdep) library(tidyverse) library(robust) library(plyr) # some functions in spdep will be masked (over-written) by functions of spatialreg library(spatialreg) ########## SECTION 0. DATA MANAGEMENT. ####### # forest calculations derived from Google Earth Engine, plus covariates rawd <-read.csv("collins_etal_REDD_df.csv") # subset to remove wards w/o any forest and wards that are urban d <- rawd %>% subset(rawd$F12_15m_percent != 0 & rawd$WARD_TYPE != "Urban") # create variable for forest area in km_sq (not m_sq) for 15m smoothed d$F_0215M_km_sq <- d$f_02_15m_aream / (1000^2) # ratio of total area to forest area d$f12_v_area_15m <- d$F12_15m_percent / 100 d$f02_v_area_15m <- d$F02_15m_percent / 100 # convert road and coast and wete distances to km d$road_median_km <- d$road_median / 1000 d$coast_median_km <- d$coast_median / 1000 d$wete_median_km <- d$wete_median / 1000 #check wete distribution hist(d$wete_median_km) #multiply the annual growth rate by 100 to produce percent d$annual_rate_P1_15m <-d$annual_rate_P1_15m *100 d$annual_rate_P2_15m <-d$annual_rate_P2_15m *100 # begin building the data frame for analysis # take natural logarithm of selected continuous variables d.contin <- log(d[, c("AREA", "POP_DEN", "f12_v_area_15m", "f02_v_area_15m", "aprppn_median")]) # introduce other variables not indicated for log transform d.contin <- cbind(d$annual_rate_P1_15m, d$RATE, d$elev_median, d$slope_median, d$coast_median_km, d$road_median_km, d$wete_median_km, d.contin) # name all variables names(d.contin) <- c("annual_rate_P1_15m", "RATE", "elev_median", "slope_median", "coast_median", "road_median", "wete_median", "AREA", "POP_DEN", "f12_v_area_15m", "f02_v_area_15m", "aprppn_median") # remove 'forest vs area in 2001' from the covariate data frame, # as it is too correlated with 'forest vs area in 2012'. d.contin <- subset(d.contin, select = -f02_v_area_15m) # introduce treatment indicator back in to d.contin. d.contin$protection <- d$protection # introduce soil_mode as categorical variable d.contin$soil_mode <- factor(d$soil_mode) # introduce annual rate of change in period 2 as the dependent variable d.contin$depvar <- d$annual_rate_P2_15m # the rownames of d.contin will be the ward names, in the same order as in d rownames(d.contin) <- d$NAME_3 ### SECTION 1. SPATIAL PREDICTIVE MODEL. ###### # read in neighbor info neigh <- read.csv("Collins_etal_REDD_neighboring_wards.csv", na.strings = c(" ", ""), stringsAsFactors = FALSE) #neigh <- read.csv("neighboring_wards.csv", na.strings = c(" ", ""), stringsAsFactors = FALSE) # format binary neighbor matrix nb.mat <- matrix(0, nrow=dim(d.contin)[1], ncol=dim(d.contin)[1]) rownames(nb.mat) <- rownames(d.contin) colnames(nb.mat) <- rownames(nb.mat) dim(nb.mat) # Loop over wards in rownames of d.contin, place a "1" in nb.mat where # a column name there matches a neighbor in neigh. for(ward in rownames(nb.mat)){ #print(ward) nb.mat[ward, ] <- colnames(nb.mat) %in% as.character(neigh[neigh$NAME_3 == ward, -1]) # -1 in column slot to remove the focal ward from the vector of neighbors. } isSymmetric(nb.mat) sum(nb.mat[lower.tri(nb.mat)]) sum(nb.mat[upper.tri(nb.mat)]) # The neighbor information imported in neigh omits reporting of the symmetric pair. # I.e., if wardB is a neighbor of wardA, then it is not reported that # wardA is a neighbor of wardB. # Therefore, add the resulting binary neighbor matrix # to its transpose, to incorporate the full set of symmetric relationships. nb.mat <- nb.mat + t(nb.mat) # Make neighbor list structure for all wards. # This is the basic structure required for spatial models below. nb.list <- mat2listw(nb.mat) summary(nb.list, zero.policy=TRUE) # Socio-ecological spatial model: Fit spatial model to the whole dataset the Two-stage least-squares with robust standard errors for heteroskedasticity #update Sep1 2021 - removing forest cover change P1 # m.stsls <- stsls(depvar ~ annual_rate_P1_15m + RATE + elev_median + # slope_median + coast_median + road_median + AREA + POP_DEN + # f12_v_area_15m + aprppn_median + soil_mode + wete_median, # data=d.contin, listw=nb.list, zero.policy=TRUE, # robust=TRUE) # summary(m.stsls) m.stsls <- stsls(depvar ~ RATE + elev_median + slope_median + coast_median + road_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + soil_mode + wete_median, data=d.contin, listw=nb.list, zero.policy=TRUE, robust=TRUE) summary(m.stsls) #now calculate the adjusted r2 adjr2 <- 1-(m.stsls$sse/m.stsls$df) / var(d.contin$depvar) adjr2 #ordinary R2 ordr2 <- 1-(m.stsls$sse) / (var(d.contin$depvar) * (length(d.contin$depvar) -1)) ordr2 #calculate bonferroni (edited 1 sep) #qnorm(p=0.05/(13*2), lower.tail = FALSE) qnorm(p=0.05/(12*2), lower.tail = FALSE) #fit a null model to the control + treated datasaet and compare to the m.stsls m.null <- stsls(depvar ~ +1, data=d.contin, listw=nb.list, zero.policy=TRUE, robust=TRUE) summary(m.null) # checking for z score associated with the bonferroni threshold for 14 coefficients qnorm(p=0.05/(14*2), lower.tail = FALSE) # Fit spatial models. # Set up data frames of treated and control wards. # Ward names are carried along as the rownames of data frames treated, control. treated <- d.contin[d.contin$protection == 1, ] control <- d.contin[d.contin$protection == 0, ] n <- dim(treated)[1] m <- dim(control)[1] # Neighbor list structure for controls. nb.mat.control <- nb.mat[rownames(control), rownames(control)] nb.list.control <- mat2listw(nb.mat.control) # ATET spatial model: Fit spatially-lagged model to controls using Two-stage least-squares with robust standard errors for heteroskedasticity. m.control.stsls <- stsls(depvar ~ annual_rate_P1_15m + RATE + elev_median + slope_median + coast_median + road_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + soil_mode + wete_median, data=control, listw=nb.list.control, zero.policy=TRUE, robust=TRUE) summary(m.control.stsls) #now calculate the adjusted r2 control.adjr2 <- 1-(m.control.stsls$sse/m.control.stsls$df) / var(control$depvar) control.adjr2 # Recover predicted values from matrix operation. # The prediction formula is y = (I - rho W)^{-1} %*% X %*% beta, # see Bivand and Piras 2015, J. of Statistical Software, p.8. spatial.lag <- diag(nrow = nrow(control)) - m.control.stsls$coefficients["Rho"] * nb.mat.control svd(spatial.lag)$d # The spatial lag matrix is non-singular, so invertible. inv.spatial.lag <- solve(spatial.lag, diag(nrow=nrow(spatial.lag))) stsls.model.frame <- model.frame(depvar ~ annual_rate_P1_15m + RATE + elev_median + slope_median + coast_median + road_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + soil_mode + wete_median, data=control) stsls.model.matrix <- model.matrix(depvar ~ annual_rate_P1_15m + RATE + elev_median + slope_median + coast_median + road_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + soil_mode + wete_median, data=stsls.model.frame) CEC.stsls <- inv.spatial.lag %*% stsls.model.matrix %*% m.control.stsls$coefficients[-1] # Recover observed y using the full equation on pg. 8 in Bivand and Piras 2015. my.y <- CEC.stsls + inv.spatial.lag %*% m.control.stsls$residuals plot(control$depvar, my.y) # These are the same. abline(0, 1) stsls_stats <- round(cbind(m.control.stsls$coefficients[-1], sqrt(diag(m.control.stsls$var)[-1])), 3) write.csv(stsls_stats, "stats_for_stsls_model.csv") # Make predicted values for the treated sample, based on the two-stage robust # model trained on the controls. # Set the columns of the neighbor matrix corresponding to CoFMAs equal to zero. # Thus the dependent variable in CoFMAs is not endogenized by implication, # in the predictive equation y = (I - rho W)^{-1} %*% X %*% beta. # The neighbor-weights matrix W will be non-symmetric for the predictions. training.mat <- nb.mat training.mat[, rownames(treated)] <- 0 isSymmetric(training.mat) spatial.lag <- diag(nrow = nrow(training.mat)) - m.control.stsls$coefficients["Rho"] * training.mat svd(spatial.lag)$d # The spatial lag matrix is non-singular, so invertible. inv.spatial.lag <- solve(spatial.lag, diag(nrow=nrow(spatial.lag))) stsls.model.frame <- model.frame(depvar ~ annual_rate_P1_15m + RATE + elev_median + slope_median + coast_median + road_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + soil_mode + wete_median, data=d.contin) stsls.model.matrix <- model.matrix(depvar ~ annual_rate_P1_15m + RATE + elev_median + slope_median + coast_median + road_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + soil_mode + wete_median, data=stsls.model.frame) CECC.stsls <- (inv.spatial.lag %*% stsls.model.matrix %*% m.control.stsls$coefficients[-1])[d.contin$protection == 1] ### SECTION 2. FIND MATCHING CONTROLS FOR EACH TREATED CoFMA WARD. ######### M <- 5 # number of matched controls for each CoFMA match.out <- matchit(protection ~ annual_rate_P1_15m + RATE + elev_median + slope_median + AREA + POP_DEN + f12_v_area_15m + aprppn_median + coast_median + road_median + wete_median, data=d.contin, method="nearest", distance="mahalanobis", exact="soil_mode", ratio=M, replace=TRUE) summary(match.out) Zcon <- match.out$match.matrix Zcon write.csv(data.frame(Zcon), "5_matched_controls_names.csv") ### SECTION 3. ESTIMATION AND SIGNIFICANCE TESTING OF ATET (SUPPLEMENTAL). ########## # Ferman's (2021) sign-test requires that we keep the contributions to ATET from # treated units together with their matching controls. matched.nullmatrix <- matrix(0, nrow=n, ncol=M) colnames(matched.nullmatrix) <- paste("match.biascorrected", seq(1, M, 1), sep = ".") atet.frame <- data.frame(treated.biascorrected = treated$depvar - CECC.stsls, matched.nullmatrix) rownames(atet.frame) <- rownames(treated) controls.biascorrected <- control$depvar - CEC.stsls # Fill in the contributions from bias-corrected matches using the key/values from Zcon. # For any given row in atet.frame, the column-order of matched controls will not in general # be the same as the column-order in Zcon. for(treated.ward in rownames(treated)){ atet.frame[treated.ward, colnames(matched.nullmatrix)] <- controls.biascorrected[rownames(controls.biascorrected) %in% Zcon[treated.ward,]] } # Calculate the sample ATET. # Multiplier matrix for use in subtracting the average of each group of matched controls. mult.mat <- cbind(rep(1, n), matrix(-1/M, nrow=n, ncol=M)) atet.ferman <- sum(mult.mat * atet.frame)/n # Note the above reproduces the numerical ATET calculated using the algebra in Otsu and Rai. # The test-statistic in Ferman 2021, eq. 7, is a normalized ATET. atet.sample.contribs <- rowSums(mult.mat * atet.frame) atet.test.stat <- abs(mean(atet.sample.contribs))/sd(atet.sample.contribs) # Generate the reference distribution for the sign test. # Populate a matrix of random sign vectors. R <- 9999 sign.mat <- matrix(sample(x=c(-1, 1), size=n*R, replace=TRUE), nrow=n, ncol=R) sign.fun <- function(sign.column, sample.contribs){ signed.contribs <- sign.column*sample.contribs abs(mean(signed.contribs))/sd(signed.contribs) } sign.test.samples <- apply(sign.mat, MAR=2, FUN=sign.fun, sample.contribs=atet.sample.contribs) # Calculate the p-value. sum(sign.test.samples > atet.test.stat)/(R+1) # Graph a kernel density of the reference distribution, place an arrow at the sample statistic. ref.density <- density(sign.test.samples, from = 0) ymax <- max(ref.density$y) ymin <- -1.9 xmin<- -0.1 xmax <-max(ref.density$x) axis.ticks <- seq(from=0, to=max(ref.density$x), by=0.2) axis.level <- -0.25 png(paste("sign.test.distrib.png"), width=6, height=4, units="in", res=500) par(mar=c(0, 1, 1, 1)+0.5) plot(x=ref.density$x, y=ref.density$y, ylim=c(ymin, ymax), yaxt="n", xaxt="n", xlim = c(xmin, xmax), xlab="", ylab="", #main="Sign Test Null Distribution", type="n", bty="n") lines(x=ref.density$x, y=ref.density$y, lwd=3, col="grey40") axis(side=1, at=axis.ticks, pos= axis.level) text(x=mean(axis.ticks), y=axis.level - 1.25, labels="Sign Test quantile") text(x=atet.test.stat, y= ymin+0.2, labels="Sample\\nStatistic", font=3, cex=0.9, pos=2) arrows(x0=atet.test.stat, y0= ymin+0.1, y1=axis.level - 1, length=0.1, col="tomato2", lwd=3) graphics.off()
// Definimos las carreras disponibles para inscribirse const carreras = [ new Carrera(1, "Analista en Sistemas de Computación"), new Carrera(2, "Tec. Universitaria en celulosa y Papel"), new Carrera(3, "Tec. Universitaria en Tecnologías de la Información"), new Carrera(4, "Bioquímica"), new Carrera(5, "Farmacia"), new Carrera(6, "Ing. en Alimentos"), new Carrera(7, "Ing. Química"), new Carrera(8, "Lic. en Análisis Químicos y Bromatológicos"), new Carrera(9, "Lic. en Sistemas de Información"), new Carrera(10, "Prof. Universitario en Computación"), ]; // Cargamos la lista de carreras disponibles en la UI con la lista creada anteriormente let carrerasList = document.getElementById("carreras"); carreras.forEach((element) => { let item = document.createElement("option"); item.value = element.id.toString(); item.innerText = element.toString(); carrerasList.append(item); }); // Definimos los Estudiantes que se hallan registrados const unTipo = new TipoDocumento(1, "Documento Nacional de Identidad", "DNI"); const estudiantes = [ new Estudiante( 100, unTipo, "11222333", "Gonzalez", "Veronica", "[email protected]" ), new Estudiante( 200, unTipo, "22333444", "Iparraguirre", "Juan", "[email protected]" ), new Estudiante( 300, unTipo, "33444555", "Mendez", "Silmara", "[email protected]" ), new Estudiante( 400, unTipo, "44555666", "Casimiró", "Brian", "[email protected]" ), ]; // Cargamos la lista de estudiantes disponibles en la UI con la lista creada anteriormente let estudiantesList = document.getElementById("estudiantes"); estudiantes.forEach((element) => { let item = document.createElement("option"); item.value = element.id.toString(); item.innerText = element.toString(); estudiantesList.append(item); }); let matriculas = []; function buscarCarreraById(id) { return carreras.find((element) => element.id === id); } function buscarEstudianteById(id) { return estudiantes.find((element) => element.id === id); } function buscarCarrera(idCarrera) { return carreras.find((element) => element.id === idCarrera); } function existeMatricula(idCarrera, legajo) { return matriculas.some( (element) => element.carrera.id === idCarrera && element.estudiante.id === legajo ); } const formulario = document.getElementById("formulario"); function pintarTabla(collection = []) { // Pintar la lista de estudiantes matriculados en a UI let bodyTable = document.getElementById("tableBody"); bodyTable.innerHTML = ""; collection.forEach((element) => { let record = document.createElement("tr"); record.innerHTML = `<tr> <td scope="row">${element.id}</td> <td>${element.carrera.toString()}</td> <td>${element.estudiante.toString()}</td> </tr>`; bodyTable.append(record); }); } function crearMatricula() { // Recuperaremos de cada uno de los inputs, el valor que ingreso/seleccionó el usaurio const idEstudiante = document.getElementById("estudiantes").value; const idCarrera = document.getElementById("carreras").value; // Buscamos el estudiante seleccionado y evaluamos si existe o no let unEstudiante = buscarEstudianteById(parseInt(idEstudiante)); if (!unEstudiante) { showErrorMessage(["No se encuentra el estudiante seleccionado"]); return false; } // Buscamos la carrera seleccionada y evaluamos si existe o no let unaCarrera = buscarCarreraById(parseInt(idCarrera)); if (!unaCarrera) { // informar de error showErrorMessage(["No se encuentra la carrera seleccionada"]); return false; } // Evaluamos si existe el Estudiante matriculado en la carrera seleccionada const existe = existeMatricula(unaCarrera.id, unEstudiante.id); if (existe) { // informar de error showErrorMessage([ "Estudiante " + unEstudiante.toString() + " ya se encuentra matriculado/a a la carrera " + unaCarrera.toString(), ]); return false; } // Creamos una Matricula const unaMatricula = new Matricula( generarLegajo(matriculas.map((element) => element.id)), unaCarrera, unEstudiante ); unEstudiante.addMatricula(unaMatricula); unaCarrera.addMatricula(unaMatricula); // Añadimos la nueva matricula a la lista de matriculas existente matriculas.push(unaMatricula); pintarTabla(matriculas); return true; } function limpiarCampos() { // Limpiar todos y cada uno de los inputs formulario.reset(); } function validarFormulario() { let errores = []; const idEstudiante = document.getElementById("estudiantes").value; const idCarrera = document.getElementById("carreras").value; return errores; } formulario.addEventListener("submit", (event) => { event.preventDefault(); event.target.setAttribute("class", "needs-validation"); hideMessage(); let errores = validarFormulario(); if (errores.length > 0) { showErrorMessage(errores); event.target.classList.add("was-validated"); return false; } let resultado = crearMatricula(); if (resultado) { showSuccessMessage(["Estudiante matriculado a la carrera!"]); limpiarCampos(); } return resultado; }); formulario.addEventListener("reset", (event) => { formulario.reset(); hideMessage(); }); const formularioSearch = document.getElementById("searchForm"); formularioSearch.addEventListener("submit", (event) => { event.preventDefault(); hideMessage(); const searchText = document.getElementById("searchText").value; if (searchText.length < 1) { showErrorMessage([ "Para poder hacer un filtrado de datos es necesario ingresar un criterio", ]); return false; } let resultados = matriculas.filter((element) => element.carrera.nombre.toUpperCase().includes(searchText.toUpperCase()) ); if (resultados.length < 1) { showErrorMessage([ "No encontramos registros que coincidan con la búsqueda", ]); return false; } pintarTabla(resultados); return true; }); formularioSearch.addEventListener("reset", (event) => { pintarTabla(matriculas); });
using Microsoft.EntityFrameworkCore; using Practice.Domain; using System; namespace Practice.Persistence { public class PracticeDbContext : DbContext { public PracticeDbContext(DbContextOptions<PracticeDbContext> options) : base(options) { } public DbSet<Course> Courses { get; set; } // DbSet para la entidad Course que se mapeará en la base de datos. protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configurando el modelo de base de datos. modelBuilder.Entity<Course>() .Property(e => e.Price) .HasPrecision(14, 2); // Configuración de precisión para la propiedad Price de la entidad Course. modelBuilder.Entity<Course>().HasData( // Inserción de datos iniciales. new Course { CourseId = Guid.NewGuid(), Title = "Mastering Clean Architecture: Robust and Scalable Software Design", Description = "This Clean Architecture course will immerse you in the exciting world of robust and scalable software design. Clean Architecture, also known as 'Clean Architecture,' is a software development methodology that encourages the creation of flexible, maintainable, and high-quality systems.", CreationDate = DateTime.Now, PublicationDate = DateTime.Now.AddMonths(2), Price = 60 } ); modelBuilder.Entity<Course>().HasData( // Inserción de datos iniciales. new Course { CourseId = Guid.NewGuid(), Title = "Mastering SOLID Principles: Building Robust and Maintainable Software", Description = "This SOLID Principles course will take you deep into the realm of building robust and maintainable software. SOLID is a set of five design principles in object-oriented programming that aim to make software more understandable, flexible, and maintainable.", CreationDate = DateTime.Now, PublicationDate = DateTime.Now.AddMonths(4), Price = 40 } ); modelBuilder.Entity<Course>().HasData( // Inserción de datos iniciales. new Course { CourseId = Guid.NewGuid(), Title = "Mastering Docker: Container Development and Orchestration", Description = "This Docker course will immerse you in the exciting world of container development and orchestration. Docker is a platform that revolutionizes the way we develop, deploy, and run applications, enabling efficient and scalable management of development and production environments.", CreationDate = DateTime.Now, PublicationDate = DateTime.Now.AddMonths(6), Price = 45 } ); base.OnModelCreating(modelBuilder); // Llamada al método base para completar la configuración del modelo. } } }
<script> import $ from 'jquery' import About from './components/About.vue'; import NewIncident from './components/NewIncident.vue'; //npm run dev -- --port 8000 <-to run the server //npm run build <-to make the actual files we will turn in //------------------------TODO------------------------------------------------------- //Clamp input values if lat/long is outside of St. Paul's bounding box //Incident upload and Bio stuff idk how far yall got //Style the background color of rows in the table to categorize crimes as "violent crimes" (crimes against another person), // "property crimes" (crimes against a person's or business' property), or "other crimes" (anything else) //Add a 'delete' button for each crime in the table //Add a marker to the map at exact crime location when selected from the table export default { data() { return { view: 'map', lookup: '', current_lookup_marker: null, narcotic: false, property: false, violent: false, start_date: "2014-08-14", end_date: "2022-06-01", max_result: 1000, currentHoodMarkers: null, greenIcon: null, NeighborhoodLayer: null, codes: [], neighborhoods: [], neighborhood_popups: [], neighborhood_stats: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], incidents: [], args: [], //Dont know if we will need this to be global but i figured it wouldn't hurt. NewIncidentData: null, leaflet: { map: null, center: { lat: 44.955139, lng: -93.102222, address: "" }, zoom: 12, bounds: { nw: {lat: 45.008206, lng: -93.217977}, se: {lat: 44.883658, lng: -92.993787} }, neighborhood_markers: [ //Includes number so it can be used to filter {location: [44.942068, -93.020521], include: true, number: 1, marker: "Conway/Battlecreek/Highwood"}, {location: [44.977413, -93.025156], include: true, number: 2, marker: "Greater East Side"}, {location: [44.931244, -93.079578], include: true, number: 3, marker: "West Side"}, {location: [44.956192, -93.060189], include: true, number: 4, marker: "Dayton's Bluff"}, {location: [44.978883, -93.068163], include: true, number: 5, marker: "Payne/Phalen"}, {location: [44.975766, -93.113887], include: true, number: 6, marker: "North End"}, {location: [44.959639, -93.121271], include: true, number: 7, marker: "Thomas/Dale(Frogtown)"}, {location: [44.947700, -93.128505], include: true, number: 8, marker: "Summit/University"}, {location: [44.930276, -93.119911], include: true, number: 9, marker: "West Seventh"}, {location: [44.982752, -93.147910], include: true, number: 10, marker: "Como"}, {location: [44.963631, -93.167548], include: true, number: 11, marker: "Hamline/Midway"}, {location: [44.973971, -93.197965], include: true, number: 12, marker: "St. Anthony"}, {location: [44.949043, -93.178261], include: true, number: 13, marker: "Union Park"}, {location: [44.934848, -93.176736], include: true, number: 14, marker: "Macalester-Groveland"}, {location: [44.913106, -93.170779], include: true, number: 15, marker: "Highland"}, {location: [44.937705, -93.136997], include: true, number: 16, marker: "Summit Hill"}, {location: [44.949203, -93.093739], include: true, number: 17, marker: "Capitol River"} ] } }; }, components: { About, NewIncident }, methods: { statusColor(codeNumber){ if(codeNumber > 99 && codeNumber < 454){ return '#FFCCCB'; } if(codeNumber > 499 && codeNumber < 1437){ return '#FFD580'; } if(codeNumber > 1799 && codeNumber < 9987){ return '#FFFF99'; } else { return 'white'; } }, FilterList(){ let newList = []; if (this.violent || this.property || this.narcotic ) { this.incidents.forEach(element => { if(this.violent && element.code > 99 && element.code < 454){ newList.push(element); } else if (this.property && element.code > 499 && element.code < 1437){ newList.push(element); } else if (this.narcotic && element.code > 1799 && element.code < 9987){ newList.push(element); } }) } else { newList = this.incidents; } return newList; }, CheckHoodBounds(){ let bounds = this.leaflet.map.getBounds(); this.leaflet.neighborhood_markers.forEach(element =>{ if( element.location[0] > bounds._southWest.lat && element.location[0] < bounds._northEast.lat && element.location[1] > bounds._southWest.lng && element.location[1] < bounds._northEast.lng){ element.include = true; } else { element.include = false; } }) }, PopulateTable(){ //Makes request to server to get incidents. Checks bounds of map to see what neighborhoods to include. console.log("start date: ", this.start_date); let url = 'http://localhost:8888/incidents?start_date='+this.start_date+"&end_date="+this.end_date+"&limit="+this.max_result; url = url + '&neighborhood=' this.leaflet.neighborhood_markers.forEach(element=>{ if(element.include){url = url + element.number + ',';} }) console.log("API GET request:", url); this.getJSON(url) .then((data)=>{ this.incidents = data; this.neighborhood_stats = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; data.forEach(element=>{ let n = element.neighborhood_number-1; this.neighborhood_stats[n] += 1; }); this.UpdateNeighborhoodPopups(); console.log('incidents: ', data); }).catch((err)=>{ console.log(err); }) this.args = []; }, Locate(){ //Takes the center of the current map view and tries to place marker as close as possible. let url = 'https://nominatim.openstreetmap.org/search?q=' + this.lookup + '&format=json&limit=25&accept-language=en'; this.getJSON(url) .then((data)=>{ if(data[0].lat > 45.008206 || data[0].lat < 44.883658 || data[0].lon < -93.217977 || data[0].lon > -92.993787){ console.log("NONONONNONONO"); window.alert("Outside of St.Paul"); } else { this.current_marker = new L.Marker([data[0].lat,data[0].lon]).addTo(this.leaflet.map); this.leaflet.map.setView([data[0].lat, data[0].lon], 15); } console.log("DATA", data); }) this.lookup = ''; }, DeleteInc(inc){ console.log("DELETE: "+'http://localhost:8888/remove-incident?case_number=' + inc); this.uploadJSON('DELETE','http://localhost:8888/remove-incident?case_number=' + inc, { case_number:inc }) .then(()=>{ this.PopulateTable(); }) }, viewMap(event) { this.view = 'map'; }, viewNewIncident(event) { this.view = 'new_incident'; }, viewAbout(event) { this.view = 'about'; }, getJSON(url) { return new Promise((resolve, reject) => { $.ajax({ dataType: 'json', url: url, success: (response) => { resolve(response); }, error: (status, message) => { reject({status: status.status, message: status.statusText}); } }); }); }, uploadJSON(method, url, data) { return new Promise((resolve, reject) => { $.ajax({ type: method, url: url, contentType: 'application/json; charset=utf-8', data: JSON.stringify(data), dataType: 'text', success: (response) => { resolve(response); }, error: (status, message) => { reject({status: status.status, message: status.statusText}); } }); }); }, onSubmit(submitData) { // this method will store the new incident data from the NewIncident child component for use in uploadJSON this.NewIncidentData = submitData; this.uploadJSON('PUT', 'http://localhost:8888/new-incident', this.NewIncidentData) .then( (data) => { console.log('DATA: ', data); this.PopulateTable(); }).catch( (reason) => { console.log(reason); }); }, UpdateNeighborhoodPopups(){ console.log("update"); this.leaflet.neighborhood_markers.forEach(element =>{ this.neighborhood_popups[element.number-1]._popup.setContent(element.marker+ ": " + this.neighborhood_stats[element.number-1]+" crimes reported."); }); }, PlaceMarkers(){ //Places markers on all of the neighborhoods. Called ONCE now. this.leaflet.neighborhood_markers.forEach(element =>{ let mark = new L.Marker(element.location,{title: element.marker, clickable: true}); let label = element.marker+ ": " + this.neighborhood_stats[element.number-1]+" crimes reported."; mark.bindPopup(label); this.neighborhood_popups.push(mark); }); this.currentHoodMarkers = L.layerGroup(this.neighborhood_popups); var BaseMap = {}; var OverlayMap = { 'NeighborhoodMarkers' : this.currentHoodMarkers }; this.NeighborhoodLayer = L.control.layers(BaseMap,OverlayMap).addTo(this.leaflet.map); this.currentHoodMarkers.addTo(this.leaflet.map); }, CreateIncidentMarker(inc){ let greenIcon = new L.Icon({ iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png', shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] }); let url = 'https://nominatim.openstreetmap.org/search?q='; let string = inc.block.split(' '); if( /[0-9]/.test(string[0][0] )){ let NewBlock = ''; for(let i = 0; i<string[0].length; i++){ if(string[0][i] == 'X'){NewBlock = NewBlock + '0';} else{NewBlock = NewBlock + string[0][i]} } string[0] = NewBlock; string.forEach(element => { url = url + element + ' ' }) url = url + '&format=json&limit=25&accept-language=en'; } else { url = 'https://nominatim.openstreetmap.org/search?q=' + inc.block + '&format=json&limit=25&accept-language=en'; } console.log('Creating marker at:' + url); this.getJSON(url) .then((data)=>{ let IncMarker = new L.Marker([data[0].lat,data[0].lon],{icon: greenIcon}).addTo(this.leaflet.map); IncMarker.bindPopup('Date: ' + inc.date + '\nTime: '+ inc.time+ '\nIncident' + inc.incident + '<button class="button" onclick="(function(this){ this.remove(); })();" > DELETE </button>' ); }) } }, mounted() { this.leaflet.map = L.map('leafletmap').setView([this.leaflet.center.lat, this.leaflet.center.lng], this.leaflet.zoom,); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', minZoom: 11, maxZoom: 18 }).addTo(this.leaflet.map); this.leaflet.map.setMaxBounds([[44.883658, -93.217977], [45.008206, -92.993787]]); let district_boundary = new L.geoJson(); district_boundary.addTo(this.leaflet.map); this.PlaceMarkers(); this.getJSON('/data/StPaulDistrictCouncil.geojson').then((result) => { // St. Paul GeoJSON $(result.features).each((key, value) => { district_boundary.addData(value); }); }).catch((error) => { console.log('Error:', error); }); this.leaflet.map.on('dragend', ()=> { //Updtaes map with center address and what neighborhoods to include in the table console.log("Center: ", this.leaflet.map.getCenter()); if(this.current_marker != null){ this.leaflet.map.removeLayer(this.current_marker) } let templat = this.leaflet.map.getCenter().lat; let templng = this.leaflet.map.getCenter().lng; if(templat > 45.008206 || templat < 44.883658 || templng < -93.217977 || templng > -92.993787){ console.log("NONONONNONONO"); window.alert("Outside of St.Paul"); } else { let url = 'https://nominatim.openstreetmap.org/reverse?lat=' + templat + '&lon=' + templng+"&format=json"; this.getJSON(url) .then((data)=>{ console.log("nominatim data: ", data); this.current_marker = new L.Marker([data.lat,data.lon]); this.current_marker.addTo(this.leaflet.map); this.leaflet.map.setView([data.lat, data.lon]); this.lookup = data.display_name; }) .catch((error) => { console.log('Error:', error); }); } this.CheckHoodBounds(); this.PopulateTable(); console.log("crime stats: ", this.neighborhood_stats); }); this.leaflet.map.on('zoomend', ()=> { //Updtaes map with center address and what neighborhoods to include in the table if(this.current_marker != null){ this.leaflet.map.removeLayer(this.current_marker) } console.log("Center: ", this.leaflet.map.getCenter()); if(this.current_marker != null){ this.leaflet.map.removeLayer(this.current_marker) } let templat = this.leaflet.map.getCenter().lat; let templng = this.leaflet.map.getCenter().lng; if(templat > 45.008206 || templat < 44.883658 || templng < -93.217977 || templng > -92.993787){ console.log("NONONONNONONO"); window.alert("Outside of St.Paul"); } else { let url = 'https://nominatim.openstreetmap.org/reverse?lat=' + templat + '&lon=' + templng+"&format=json"; this.getJSON(url) .then((data)=>{ console.log("nominatim data: ", data); this.current_marker = new L.Marker([data.lat,data.lon]); this.current_marker.addTo(this.leaflet.map); this.leaflet.map.setView([data.lat, data.lon]); this.lookup = data.display_name; }) .catch((error) => { console.log('Error:', error); }); } this.CheckHoodBounds(); this.PopulateTable(); }); this.getJSON('http://localhost:8888/neighborhoods').then((data)=>{ //Populates neighborhoods list. Should only need to do this once. this.neighborhoods = data; this.PopulateTable(); console.log("neighborhoods: ", data); }).catch((err)=>{ console.log(err); }) } } </script> <template> <div class="grid-container"> <div class="grid-x grid-padding-x"> <p :class="'cell small-4 ' + ((view === 'map') ? 'selected' : 'unselected')" @click="viewMap">Map</p> <p :class="'cell small-4 ' + ((view === 'new_incident') ? 'selected' : 'unselected')" @click="viewNewIncident">New Incident</p> <p :class="'cell small-4 ' + ((view === 'about') ? 'selected' : 'unselected')" @click="viewAbout">About</p> </div> </div> <div v-show="view === 'map'"> <div class="grid-container"> <div class="grid-x grid-padding-x"> <div id="leafletmap" class="cell auto"></div> <div class = "cell 12"> <form @submit.prevent="Locate"> <input v-model="lookup" placeholder="Hamline" style="width: 1000px"> <input class="button" type="submit" value="GO"> </form> </div> <input class="cell small-3" v-model="max_result" placeholder="Max Number of Results"> <input class="cell small-3" type="date" name="Start-Date" v-model="start_date" min="2014-08-14" max="2022-05-31"> <input class="cell small-3" type="date" name="End-Date" v-model="end_date" min="2014-08-14" max="2022-05-31"> <button class="button cell small-3" @click="PopulateTable">Apply Filters</button> <!--Creates a box for every neighborhood--> <ul style="list-style: none"> <li class="cell small-3" v-for="neighborhood in leaflet.neighborhood_markers" > <input type="checkbox" v-model="neighborhood.include"> {{neighborhood.marker}} </li> </ul> <div class = "cell small-12"> <input type="checkbox" id="Violent Crimes" v-model="violent" /> <label for="Violent Crimes">Violent Crimes</label> <input type="checkbox" id="Property Crimes" v-model="property" /> <label for="Property Crimes">Property Crimes</label> <input type="checkbox" id="Narcotics Crimes" v-model="narcotic" /> <label for="Narcotics Crimes">Narcotics/Other Crimes</label> </div> <table class="cell small-12" style = "border:2px solid"> <th>Legend</th> <tr style = "border:2px solid"> <td> <dl> <dt class="red"></dt> <dd>Violent Crimes</dd> <dt class="orange"></dt> <dd>Proterty Crimes</dd> <dt class="yellow"></dt> <dd>Narcotic/Other Crimes</dd> </dl> </td> </tr> </table> <!--The table of incidents. No idea what data he wants in it this is the bare minimum. Remove 2nd neighbohood when all done, just shows neighborhood number for now--> <table class="cell small-12" style = "border:2px solid"> <tr style = "border:2px solid"> <td>Case Number</td> <td>Date</td> <td>Code</td> <td>Type Of Incident</td> <td>Neighborhood</td> <td></td> <td></td> </tr> <tr v-for="incident in FilterList()" v-bind:style="{ 'background-color': statusColor(incident.code) }"> <td>{{incident.case_number}}</td> <td>{{incident.date}}</td> <td>{{incident.time}}</td> <td>{{incident.incident}}</td> <td>{{neighborhoods[incident.neighborhood_number-1].neighborhood_name}}</td> <td><button class="button" @click="CreateIncidentMarker(incident)">Show On Map</button></td> <td><button class="button" @click="DeleteInc(incident.case_number)">DELETE</button></td> </tr> </table> </div> </div> </div> <div v-if="view === 'new_incident'"> <NewIncident @submitted="onSubmit"/> </div> <div v-if="view === 'about'"> <About /> </div> </template> <style> #leafletmap { height: 500px; } .selected { background-color: rgb(10, 100, 126); color: white; border: solid 1px white; text-align: center; cursor: pointer; } .unselected { background-color: rgb(200, 200, 200); color: black; border: solid 1px white; text-align: center; cursor: pointer; } ul li{ display: inline; } </style>
var http = require('http'); var fs = require('fs'); var url = require('url'); //url이라는 모듈을 사용할 것이다. var qs = require('querystring'); var template = require('./lib/template.js'); var path = require('path'); var sanitizeHTML = require('sanitize-html'); //아래 template을 모듈로 빼고 (lib/template.js) 받아서 활용~ /* var template = { HTML: function(title, list, body, control) { return ` <!doctype html> <html> <head> <title>WEB1 - ${title}</title> <meta charset="utf-8"> </head> <body> <h1><a href="/">WEB</a></h1> ${list} ${control} ${body} </body> </html> ` ; }, List:function(filelist){ var list = '<ul>'; var i = 0; while (i < filelist.length) { list = list + `<li><a href= "/?id=${filelist[i]}">${filelist[i]}</a></li>`; i = i + 1; } list = list + '</ul>'; return list; } } */ /* function templateHTML(title, list, body, control) { return ` <!doctype html> <html> <head> <title>WEB1 - ${title}</title> <meta charset="utf-8"> </head> <body> <h1><a href="/">WEB</a></h1> ${list} ${control} ${body} </body> </html> ` ; } function templateList(filelist) { var list = '<ul>'; var i = 0; while (i < filelist.length) { list = list + `<li><a href= "/?id=${filelist[i]}">${filelist[i]}</a></li>`; i = i + 1; } list = list + '</ul>'; return list; } */ var app = http.createServer(function (request, response) { //request는 요청할 때 웹브라우저가 보낸 정보 , response 응답할 떄 우리가 웹브라우저에 보낼 정보 var _url = request.url; //그래서 여기url을 _url로 바꿔줌 var queryData = url.parse(_url, true).query; var pathname = url.parse(_url, true).pathname; //위처럼 타이틀 변수 설정해 주어 아래 ${queryData.id} 이 부분을 ${title} 로 바꿔준다 if (pathname === '/') { if (queryData.id === undefined) { fs.readdir('./data', function (err, filelist) { var title = 'Welcome'; var description = 'Hello, Node.js' /* var list = templateList(filelist); var template = templateHTML(title, list, `<h2>${title}</h2> ${description}`, `<a href="/create">create</a>`); response.writeHead(200); response.end(template); 원래 코드 아래 코드는 함수 이용해서 변경*/ var list = template.List(filelist); var html = template.HTML(title, list, `<h2>${title}</h2> ${description}`, `<a href="/create">create</a>`); response.writeHead(200); response.end(html); }); } else { fs.readdir('./data', function (err, filelist) { var filteredId = path.parse(queryData.id).base; fs.readFile(`data/${filteredId}`, 'utf8', function (err, description) { var title = queryData.id; var sanitizedTitle = sanitizeHTML(title); var sanitizedDescription = sanitizeHTML(description); var list = template.List(filelist); var html = template.HTML(sanitizedTitle, list, `<h2>${sanitizedTitle}</h2> ${sanitizedDescription}`, ` <a href="/create">create</a> <a href="/update?id=${sanitizedTitle}">update</a> <form action="delete_process" method="post" > <input type="hidden" name="id" value="${sanitizedTitle}"> <input type="submit" value="delete"> </form>` ); response.writeHead(200); response.end(html); }); }); } } else if (pathname === '/create') { fs.readdir('./data', function (err, filelist) { var title = 'WEB - create'; var list = template.List(filelist); var html = template.HTML(title, list, ` <form action="/create_process" method="post"> <p><input type="text" name="title" placeholder="title"></p> <p> <textarea name="description" placeholder="description"></textarea> </p> <p> <input type="submit"> </p> </form>`,''); response.writeHead(200); response.end(html); }); } else if(pathname === '/create_process'){ var body = ''; request.on('data', function(data){ //웹브라우저가 post방식으로 데이터를 전송할 때 엄청 많으면 데이터 한번에 처리하다보면 무리하면 컴터 꺼짐 그거에 대비해서 요렇게 사용방법을 제공 body = body + data; }); request.on('end', function(){ var post = qs.parse(body); //쿼리스트링이라는 모듈의 parse를 객체화 할 수 있다 var title = post.title; var description = post.description; fs.writeFile(`data/${title}`, description, 'utf8', function(err){ response.writeHead(302, {Location: `/?id=${title}`}); //200은 성공 302는 다른 페이지로 리다이렉션 response.end(); }) }); }else if(pathname === '/update'){ fs.readdir('./data', function (err, filelist) { var filteredId = path.parse(queryData.id).base; fs.readFile(`data/${filteredId}`, 'utf8', function (err, description) { var title = queryData.id; var list = template.List(filelist); var html = template.HTML(title, list, ` <form action="/update_process" method="post"> <input type="hidden" name="id" value="${title}"> <p><input type="text" name="title" placeholder="title" value="${title}"></p> <p> <textarea name="description" placeholder="description">${description}</textarea> </p> <p> <input type="submit"> </p> </form> `, `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`); response.writeHead(200); response.end(html); }); }); } else if(pathname === '/update_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); var id = post.id; var title = post.title; var description = post.description; //console.log(post); fs.rename(`data/${id}`, `data/${title}`, function(error){ fs.writeFile(`data/${title}`, description, 'utf8', function(err){ response.writeHead(302, {Location: `/?id=${title}`}); //200은 성공 302는 다른 페이지로 리다이렉션 response.end(); }); }); }); } else if(pathname === '/delete_process'){ var body = ''; request.on('data', function(data){ body = body + data; }); request.on('end', function(){ var post = qs.parse(body); var id = post.id; var filteredId = path.parse(id).base; fs.unlink(`data/${filteredId}`, function(error){ response.writeHead(302, {location: `/`}); response.end(); }); }); }else { response.writeHead(404); response.end('Not found'); } //console.log(__dirname + url); //response.end(fs.readFileSync(__dirname + _url)); }); app.listen(5050);
import os import cv2 import numpy as np from itertools import product import matplotlib.pyplot as plt def load_images(directory, before): images = {} for filename in os.listdir(directory): if filename.endswith(('.jpg', '.jpeg', '.png', '.tiff', '.tif')): img_path = os.path.join(directory, filename) img = cv2.imread(img_path) identifier = filename.split('_blur')[0] if not before else filename.split('.')[0] # Extract the common identifier # breakpoint() if identifier in images: images[identifier].append((filename, img)) else: images[identifier] = [(filename, img)] return images def resize_image(image, target_size): return cv2.resize(image, target_size[::-1], interpolation=cv2.INTER_AREA) def convert_to_png(original_image): _, encoded_image = cv2.imencode('.png', original_image) png_image = cv2.imdecode(encoded_image, cv2.IMREAD_UNCHANGED) return png_image def save_images_in_grid(images, grid_size, output_path, top_image=None, row_headers=None, col_headers=None): """ Save a list of OpenCV images in a grid with a central top image above the grid and headers along rows and columns. Parameters: - images: List of OpenCV images (NumPy arrays) for the grid. - grid_size: Tuple (rows, cols) specifying the grid layout. - output_path: Output file path for the saved image. - top_image: Single OpenCV image (NumPy array) to be displayed centered above the grid. - row_headers: List of row headers. - col_headers: List of column headers. """ rows, cols = grid_size total_images = len(images) # Ensure the number of provided images matches the grid size if total_images != (rows * cols): raise ValueError("Number of images does not match the grid size.") # Get the dimensions of a single image image_height, image_width, _ = images[0].shape # Calculate the size of the grid grid_width = image_width * cols grid_height = image_height * rows # Calculate the size of the combined image combined_width = grid_width combined_height = grid_height + top_image.shape[0] if top_image is not None else grid_height # Adjust the combined width if row headers are present if row_headers is not None: max_row_header_width = 0 font = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1.7 font_thickness = 2 for header in row_headers: text_size = cv2.getTextSize(header, font, font_scale, font_thickness)[0] max_row_header_width = max(max_row_header_width, text_size[0]) combined_width += max_row_header_width + 10 # Create an empty combined image combined_image = np.zeros((combined_height, combined_width, 3), dtype=np.uint8) # Add the top image centered above the grid if top_image is not None: top_start_x = (combined_width - top_image.shape[1]) // 2 top_start_y = 0 combined_image[top_start_y:top_start_y + top_image.shape[0], top_start_x:top_start_x + top_image.shape[1], :] = top_image # Populate the grid with images for i in range(rows): for j in range(cols): image_index = i * cols + j combined_image[ top_image.shape[0] + i * image_height: top_image.shape[0] + (i + 1) * image_height, (max_row_header_width if row_headers else 0) + j * image_width: (max_row_header_width if row_headers else 0) + (j + 1) * image_width, : ] = images[image_index] # Add row headers if row_headers is not None: row_padding = 5 # Adjust the row padding as needed row_highlight_color = (0, 0, 0) # Black color for the row highlight for i, header in enumerate(row_headers): text_x = 10 + row_padding text_y = top_image.shape[0] + i * image_height + int((image_height + font_scale) // 2) # Draw a filled rectangle as the row highlight text_size = cv2.getTextSize(header, font, font_scale, font_thickness)[0] rect_start = (text_x - row_padding, text_y - int(text_size[1] / 2) - row_padding) rect_end = (text_x + text_size[0] + 2 * row_padding, text_y + int(text_size[1] / 2) + row_padding) cv2.rectangle(combined_image, rect_start, rect_end, row_highlight_color, thickness=cv2.FILLED) # Draw the row header text cv2.putText(combined_image, header, (text_x, text_y), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA) # Add column headers if col_headers is not None: col_padding = 5 # Adjust the column padding as needed col_highlight_color = (0, 0, 0) # Black color for the column highlight for j, header in enumerate(col_headers): text_size = cv2.getTextSize(header, font, font_scale, font_thickness)[0] text_x = (max_row_header_width if row_headers else 0) + j * image_width + int((image_width - text_size[0]) // 2) text_y = top_image.shape[0] - 10 # Draw a filled rectangle as the column highlight rect_start = (text_x - col_padding, text_y - text_size[1] - col_padding) rect_end = (text_x + text_size[0] + col_padding, text_y + col_padding) cv2.rectangle(combined_image, rect_start, rect_end, col_highlight_color, thickness=cv2.FILLED) # Draw the column header text cv2.putText(combined_image, header, (text_x, text_y), font, font_scale, (255, 255, 255), font_thickness, cv2.LINE_AA) # Save the combined image combined_image = cv2.imencode('.jpg', combined_image, [int(cv2.IMWRITE_JPEG_QUALITY), 90])[1] cv2.imwrite(output_path, combined_image) col_headers = ["Downscale 0%", "Downscale 25%", "Downscale 50%"] row_headers = ["Blur 0, Noise 0", "Blur 0, Noise 27", "Blur 0, Noise 45", "Blur 11, Noise 0", "Blur 11, Noise 27", "Blur 11, Noise 45", "Blur 21, Noise 0", "Blur 21, Noise 27", "Blur 21, Noise 45"] def save_comparison_images(before_images, after_images, output_directory): os.makedirs(output_directory, exist_ok=True) for identifier, before_image_list in before_images.items(): for img in before_image_list: after_image_list = after_images.get(identifier, []) # breakpoint() after_image_list = sorted(after_image_list, key=lambda x : x[0]) # should be 27x27 # breakpoint() after_image_list = [resize_image(x[1], img[1].shape[0:2]) for x in after_image_list] output_path = os.path.join(output_directory, f"comparison_{identifier}.png") save_images_in_grid(after_image_list, (9,3), output_path, top_image=img[1], row_headers=row_headers, col_headers=col_headers) def main(): script_directory = os.path.dirname(__file__) before_directory = os.path.join(script_directory, input("Enter the relative path for non-preprocessed images: ")) after_directory = os.path.join(script_directory, input("Enter the relative path for images after machine learning model: ")) output_directory = os.path.join(script_directory, input("Enter the relative path to save comparison images: ")) before_images = load_images(before_directory, True) after_images = load_images(after_directory, False) if not before_images or not after_images: print("No images found in the specified directories.") return # breakpoint() # combinations = generate_combinations() # # Create after images for each combination of settings # for identifier, before_image_list in before_images.items(): # for combination in combinations: # after_image_list = [[[]]] # for blur, noise, downscale in zip(*combination): # after_image_id_list = after_images.get(f"{identifier}", []) # # breakpoint() # for x in after_image_id_list: # if x[0] == f"{identifier}_blur_{blur}_noise_{noise}_downscale_{downscale}.png": after_image_info = x # if after_image_info: # after_image_list.extend(after_image_info) save_comparison_images(before_images, after_images, output_directory) print("Comparison images saved in the specified output directory as PNG.") if __name__ == "__main__": main()
## Two Sum ### Description ```Python Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ``` ### Solutions #### Approach 1: Brute Force * Time complexity : O(n^2) * Space complexity : O(1) ```Python class Solution(object): def twoSum(self, nums, target): """ Given an array of integers, return indices of the two numbers such that they add up to a specific target. Args: nums(List[int]): the name of array of integers target(int): the value that we assign Returns: the indices of the two numbers from the array """ for index in range(len(nums)): another_addend = target - nums[index] if another_addend in nums[index+1:]: return [index, nums.index(another_addend, index+1)] return None ``` #### Approach 2: dict(Hash Table) * Time complexity : O(n) * Space complexity : O(n) ```Python class Solution(object): def twoSum(self, nums, target): """ Given an array of integers, return indices of the two numbers such that they add up to a specific target. Args: nums(List[int]): the name of array of integers target(int): the value that we assign Returns: the indices of the two numbers from the array """ lookup = {} for index, num in enumerate(nums): if target - num in lookup: return [lookup[target - num], index] else: lookup[num] = index return None ```
import { AppThunk } from './../index' import axios from 'axios' import { Invoice, invoiceTypes } from '../../Types/Invoice' export interface IAddItem { type: 'ADD_ITEM' payload: Invoice } export interface IRemoveItem { type: 'REMOVE_ITEM' payload: string } export interface IRemoveCompleted { type: 'REMOVE_COMPLETED' } export interface IChangeCompletion { type: 'CHANGE_COMPLETION' payload: string } export enum ActionType { LOGOUT = 'LOGOUT', CHANGE_FILTER = 'CHANGE_FILTER', REMOVE_INVOICE_SUCCESS = 'REMOVE_INVOICE_SUCCESS', REMOVE_INVOICE_FAILURE = 'REMOVE_INVOICE_FAILURE', REMOVE_INVOICE_REQUEST = 'REMOVE_INVOICE_REQUEST', ADD_INVOICE_SUCCESS = 'ADD_INVOICE_SUCCESS', ADD_INVOICE_FAILURE = 'ADD_INVOICE_FAILURE', ADD_INVOICE_REQUEST = 'ADD_INVOICE_REQUEST', FETCH_INVOICES_REQUEST = 'FETCH_INVOICES_REQUEST', FETCH_INVOICES_SUCCESS = 'FETCH_INVOICES_SUCCESS', FETCH_INVOICES_FAILURE = 'FETCH_INVOICES_FAILURE', UPDATE_INVOICE_REQUEST = 'UPDATE_INVOICE_REQUEST', UPDATE_INVOICE_SUCCESS = 'UPDATE_INVOICE_SUCCESS', UPDATE_INVOICE_FAILURE = 'UPDATE_INVOICE_FAILURE', AUTH_REQUEST = 'AUTH_REQUEST', AUTH_SUCCESS = 'AUTH_SUCCESS', AUTH_FAILURE = 'AUTH_FAILURE', REGISTER_REQUEST = 'REGISTER_REQUEST', REGISTER_SUCCESS = 'REGISTER_SUCCESS', REGISTER_FAILURE = 'REGISTER_FAILURE', } export type Action = IAddItem | IRemoveItem | IChangeCompletion | IRemoveCompleted const API_URL = 'https://anotherinvoiceapp-backend.herokuapp.com/api' const TestInvoices = [ { _id: '1234', type: 'pending' as invoiceTypes, from: { street: 'Piotrowska 7A', city: 'Jawiszowice', post_code: '32-626', country: 'USA', }, to: { name: 'John Marston', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Jawiszowice', street: 'Wyszyńskiego 44F', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-04-19', items_list: [ { name: 'milk', quantity: '46.4', price: '95.9', }, ], }, { _id: '123EG5', type: 'paid' as invoiceTypes, from: { street: 'Borelowskiego 6B', city: 'Jawiszowice', post_code: '32-626', country: 'Polska', }, to: { name: 'Arthur Morgan', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Oświęcim', street: 'Wyszyńskiego', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-05-15', items_list: [ { name: 'bread', quantity: '29', price: '6.5', }, ], }, { _id: 'E1235', type: 'draft' as invoiceTypes, from: { street: 'Borelowskiego 6B', city: 'Jawiszowice', post_code: '32-626', country: 'Polska', }, to: { name: 'Jan Kowalski', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Oświęcim', street: 'Wyszyńskiego', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-05-15', items_list: [ { name: 'bread', quantity: '9', price: '6', }, ], }, { _id: '125G35', type: 'draft' as invoiceTypes, from: { street: 'Borelowskiego 6B', city: 'Jawiszowice', post_code: '32-626', country: 'Polska', }, to: { name: 'Lidl', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Oświęcim', street: 'Wyszyńskiego', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-05-15', items_list: [ { name: 'bread', quantity: '55', price: '1.50', }, ], }, { _id: '124G35', type: 'paid' as invoiceTypes, from: { street: 'Borelowskiego 6B', city: 'Jawiszowice', post_code: '32-626', country: 'Polska', }, to: { name: 'Kamil Grabowski', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Oświęcim', street: 'Wyszyńskiego', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-05-15', items_list: [ { name: 'bread', quantity: '29', price: '5', }, ], }, { _id: '12G335', type: 'paid' as invoiceTypes, from: { street: 'Borelowskiego 6B', city: 'Jawiszowice', post_code: '32-626', country: 'Polska', }, to: { name: 'Asdf-BsdfB-CsdfC', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Oświęcim', street: 'Wyszyńskiego', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-05-15', items_list: [ { name: 'bread', quantity: '29', price: '9.9', }, ], }, { _id: '12G352', type: 'pending' as invoiceTypes, from: { street: 'Borelowskiego 6B', city: 'Jawiszowice', post_code: '32-626', country: 'Polska', }, to: { name: 'AAA-BBB-CCC', email: '[email protected]', country: 'Poland', post_code: '32-626', city: 'Oświęcim', street: 'Wyszyńskiego', }, description: 'description about invoice details', invoice_date: '2022-05-01', payment_term: '2022-05-15', items_list: [ { name: 'bread', quantity: '29', price: '6.79', }, ], }, ] export const authenticate = (username: string, password: string): AppThunk => async (dispatch) => { dispatch({ type: ActionType.AUTH_REQUEST }) if (username == 'admin' && password == 'admin') { sessionStorage.setItem('userID', '1234') dispatch({ type: ActionType.AUTH_SUCCESS, payload: { data: { _id: 1234, username: 'admin', invoices: [...TestInvoices], }, }, }) return } return axios .post(`${API_URL}/user/login`, { username, password, }) .then((payload) => { sessionStorage.setItem('userID', payload.data._id) dispatch({ type: ActionType.AUTH_SUCCESS, payload }) return true }) .catch((err) => { console.log(err) dispatch({ type: ActionType.AUTH_FAILURE }) return err }) } export const registration = (username: string, email: string, password: string): AppThunk => { return async (dispatch, getState) => { dispatch({ type: ActionType.REGISTER_REQUEST }) return axios .post(`${API_URL}/user/register`, { username, password, }) .then((payload) => { dispatch({ type: ActionType.REGISTER_SUCCESS, payload }) const promises = TestInvoices.map((invoice) => { return axios.post(`${API_URL}/invoice`, { userID: getState().userID, ...invoice, }) }) Promise.all(promises).then((results) => { results.forEach((result) => { dispatch({ type: ActionType.ADD_INVOICE_SUCCESS, payload: { data: result.data }, }) }) }) return payload.data.username }) .catch((err) => { console.log(err) dispatch({ type: ActionType.REGISTER_FAILURE }) }) } } export const logout = (): AppThunk => (dispatch, getState) => { sessionStorage.removeItem('userID') dispatch({ type: ActionType.LOGOUT }) } export const changeFilter = (filter: string): AppThunk => (dispatch) => { dispatch({ type: ActionType.CHANGE_FILTER, payload: { filter } }) } export const addItem = (invoiceContent: Invoice): AppThunk => async (dispatch, getState) => { dispatch({ type: ActionType.ADD_INVOICE_REQUEST }) try { const { data } = await axios.post(`${API_URL}/invoice`, { userID: getState().userID, ...invoiceContent, }) dispatch({ type: ActionType.ADD_INVOICE_SUCCESS, payload: { data }, }) } catch (err) { console.log('error:' + err) dispatch({ type: ActionType.ADD_INVOICE_FAILURE }) } } export const updateItem = (invoiceContent: Invoice, invoiceId: string): AppThunk => async (dispatch, getState) => { dispatch({ type: ActionType.UPDATE_INVOICE_REQUEST }) try { const { data } = await axios.put(`${API_URL}/invoice/${invoiceId}`, { userID: getState().userID, ...invoiceContent, }) dispatch({ type: ActionType.UPDATE_INVOICE_SUCCESS, payload: { data } }) } catch (err) { console.log('error:' + err) dispatch({ type: ActionType.UPDATE_INVOICE_FAILURE }) } } export const deleteItem = (invoiceId: string): AppThunk => async (dispatch) => { dispatch({ type: ActionType.REMOVE_INVOICE_REQUEST }) try { await axios.delete(`${API_URL}/invoice/${invoiceId}`) dispatch({ type: ActionType.REMOVE_INVOICE_SUCCESS, payload: { id: invoiceId } }) } catch (err) { console.log('error:' + err) dispatch({ type: ActionType.REMOVE_INVOICE_FAILURE }) } } export const fetchInvoices = (): AppThunk => async (dispatch, getState) => { dispatch({ type: ActionType.FETCH_INVOICES_REQUEST }) try { const { data } = await axios.get(`${API_URL}/invoices`, { params: { userID: getState().userID || sessionStorage.getItem('userID') }, }) dispatch({ type: ActionType.FETCH_INVOICES_SUCCESS, payload: { data } }) } catch (err) { console.log('error:' + err) dispatch({ type: ActionType.FETCH_INVOICES_FAILURE }) } }
#include "pch.hpp" #include "Date.h" #include <chrono> #include <algorithm> #include <sstream> #include <iomanip> std::string monthToString(Month m) { switch (m) { case Month::JAN: return "01"; case Month::FEB: return "02"; case Month::MAR: return "03"; case Month::APR: return "04"; case Month::MAY: return "05"; case Month::JUN: return "06"; case Month::JUL: return "07"; case Month::AUG: return "08"; case Month::SEP: return "09"; case Month::OKT: return "10"; case Month::NOV: return "11"; case Month::DEC: return "12"; default: return "??"; } } void Date::to_json(std::ostringstream& sstr) const { sstr << "{"; sstr << "\"formatted\" : "; sstr << std::setfill('0') << "\"" << std::setw(4) << (year == Date::EmptyYear ? 0 : year) << "/" << std::setw(2) << monthToString(month) << "/" << static_cast<int>(day) << "\""; sstr << ",\"day\":\"" << (int)day << "\""; sstr << ",\"month\":\"" << (int)month<< "\""; sstr << ",\"year\":\"" << year<< "\""; sstr << "}"; } Duration Date::operator-(const Date& d2) { Duration dd; dd.years = this->year - d2.year; dd.months = (char)this->month - (char)d2.month; dd.days = this->day - d2.day; return dd; } Date Date::operator+(const Duration& dur) { Date d = *this; if(!dur.error.isNone()) { d.errors.push_back(dur.error); return d; } Duration duur = dur; duur.normalize(); //get rid of the NaN values. long days = d.day + duur.days; long months_in_days = (long)std::floor(days/30.0); days = (days+30)%30; long months= (long)d.month + duur.months + months_in_days; long years_in_months = (long)std::floor(months/12.0); months = (months+12)%12; long years = (long)d.year + duur.years + years_in_months; d.day = (char)days; d.month = (Month)months; d.year = years; return d; } Date Date::operator-(const Duration& dur) { Date d = *this; //TODO: just call operator+ with a negative duration. return d; } Date Date::operator+(const Number& num) { return operator+(Duration(num, range)); } Date Date::operator-(const Number& num) { return operator-(Duration(num, range)); } bool Date::isValid() { return year != EmptyYear; //a very basic check... }
<template> <v-container> <Chart v-if="loaded" :chartdata="objeto" :options="opciones"/> </v-container> </template> <script> import Chart from './Chart.vue' import { mapState } from 'vuex' export default { name: "Grafico", components: { Chart }, data (){ return { loaded: false, objeto: {}, opciones: { maintainAspectRatio: false, scales: { xAxes: [{ type: 'time', distribution: 'spread', time: { unit: 'month' }, }] } } } }, computed: { ...mapState(["relatorio"]) }, methods: { getPromedioGrafico (grafico) { let custo_fixo = grafico.map(e => e.custo_fixo).reduce((accum, current) => accum + current); return custo_fixo / grafico.length; }, renderizar(){ //Para estilizar las barras var obj = { datasets: [] }; var chartColors = [ 'rgb(255, 205, 86)', 'rgb(255, 99, 132)', 'rgb(201, 203, 207)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)', 'rgb(75, 192, 192)', 'rgb(153, 102, 255)' ]; var cont = 0; const periodo = this.relatorio.map(e => { return {anio: e.anio, mes: e.mes} //}).filter((value, index, self) => console.log(index)); }).filter((value, index, self) => self.findIndex(i => i.anio === value.anio && i.mes === value.mes) === index); console.log(periodo) ; new Date(periodo[0].anio, periodo[0].mes, 1) this.opciones.scales.xAxes.push({ticks: { min: new Date(periodo[0].anio, periodo[0].mes, 1), max: new Date(periodo[periodo.length-1].anio, periodo[periodo.length-1].mes, 30) } }) const custo_fixo_promedio = this.getPromedioGrafico(this.relatorio); //PARA LLENAR LA DATA DEL PROMEDIO obj.datasets.push({ type: "line", fill: false, label: "Promedio", backgroundColor: "blue", data: [] }); for(let item of periodo) { //LLenado de la linea obj.datasets[0].data.push( { x: new Date(item.anio, item.mes-1), //x: mes_anio[1], y: custo_fixo_promedio }); }; //PARA LLENAR LAS BARRAS DE LOS CONSULTORES const consultores = this.relatorio.map(e => { return {co_usuario: e.co_usuario, no_usuario: e.no_usuario} }).filter((value, index, self) => self.findIndex(i => i.co_usuario === value.co_usuario) === index); consultores.forEach((value, index, array) => { obj.datasets.push({ label: value.no_usuario, backgroundColor: chartColors[index+1], fill: false, data: [] }); const consultorActual = this.relatorio.filter(e => e.co_usuario === value.co_usuario); for(let item of consultorActual) { //Llenado de las barras obj.datasets[index+1].data.push( { x: new Date(item.anio, item.mes-1), //x: item.mes, y: item.receita_liquida }); } }); return obj; } }, watch: { }, mounted() { this.loaded = false; this.objeto = this.renderizar(); this.loaded = true; } } </script>
import React, { useEffect } from 'react'; import { LinkContainer } from 'react-router-bootstrap'; import { Table, Button, Row, Col } from 'react-bootstrap'; import { useDispatch, useSelector } from 'react-redux'; import Loader from '../components/Spinner'; import Message from '../components/Message'; import Paginate from '../components/Paginate'; import { getProducts, deleteProduct, createProduct, resetProductCreate, } from '../features/products/productSlice'; import { useLocation, useNavigate } from 'react-router-dom'; function ProductList() { const dispatch = useDispatch(); const navigate = useNavigate(); const location = useLocation(); const productList = useSelector((state) => state.product.productList); const { isLoading, isError, error, products, pages, page } = productList; const productDelete = useSelector((state) => state.product.productDelete); const { isLoading: loadingDelete, message: errorDelete, isSuccess: successDelete, } = productDelete; const productCreate = useSelector((state) => state.product.productCreate); const { isLoading: loadingCreate, error: errorCreate, isSuccess: successCreate, product: createdProduct, } = productCreate; const userLogin = useSelector((state) => state.user.userLogin); const { userInfo } = userLogin; const keyword = location.search; useEffect(() => { dispatch(resetProductCreate()); if (!userInfo.isAdmin || !userInfo) { navigate('/login'); } if (successCreate) { navigate(`/admin/product/${createdProduct._id}/edit`); } else { dispatch(getProducts(keyword)); } }, [ dispatch, navigate, userInfo, successDelete, successCreate, createdProduct, keyword, ]); const deleteHandler = (id) => { if (window.confirm('Are you sure you want to delete this product?')) { dispatch(deleteProduct(id)); } }; const createProductHandler = () => { dispatch(createProduct()); }; return ( <div> <Row className="align-items-center"> <Col> <h1>Products</h1> </Col> <Col className="text-right"> <Button className="my-3" onClick={createProductHandler}> <i className="fas fa-plus"></i> Create Product </Button> </Col> </Row> {loadingDelete && <Loader />} {errorDelete && <Message variant="danger">{errorDelete}</Message>} {loadingCreate && <Loader />} {errorCreate && <Message variant="danger">{errorCreate}</Message>} {isLoading ? ( <Loader /> ) : isError ? ( <Message variant="danger">{error}</Message> ) : ( <div> <Table striped bordered hover responsive className="table-sm"> <thead> <tr> <th>ID</th> <th>NAME</th> <th>PRICE</th> <th>CATEGORY</th> <th>BRAND</th> <th></th> </tr> </thead> <tbody> {products.map((product) => ( <tr key={product._id}> <td>{product._id}</td> <td>{product.name}</td> <td>${product.price}</td> <td>{product.category}</td> <td>{product.brand}</td> <td> <LinkContainer to={`/admin/product/${product._id}/edit`}> <Button variant="light" className="btn-sm"> <i className="fas fa-edit"></i> </Button> </LinkContainer> <Button variant="danger" className="btn-sm" onClick={() => deleteHandler(product._id)} > <i className="fas fa-trash"></i> </Button> </td> </tr> ))} </tbody> </Table> <Paginate pages={pages} page={page} isAdmin={true} /> </div> )} </div> ); } export default ProductList;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Rules Related To 'aide'</title> <style> </style> </head> <body> <h1>Rules Related To 'aide'</h1> <h2>Component overview</h2> <h3>Relevant packages:</h3> <ul> <li>aide</li> </ul> <h3>Relevant groups:</h3> <ul> <li>aide</li> </ul> <h3>Changelog:</h3> <div>No changes recorded.</div> <h3>Relevant rules:</h3> <ul> <li><a href="#aide_build_database">aide_build_database</a></li> <li><a href="#aide_check_audit_tools">aide_check_audit_tools</a></li> <li><a href="#aide_periodic_cron_checking">aide_periodic_cron_checking</a></li> <li><a href="#aide_scan_notification">aide_scan_notification</a></li> <li><a href="#aide_use_fips_hashes">aide_use_fips_hashes</a></li> <li><a href="#aide_verify_acls">aide_verify_acls</a></li> <li><a href="#aide_verify_ext_attributes">aide_verify_ext_attributes</a></li> <li><a href="#file_audit_tools_group_ownership">file_audit_tools_group_ownership</a></li> <li><a href="#file_audit_tools_ownership">file_audit_tools_ownership</a></li> <li><a href="#file_audit_tools_permissions">file_audit_tools_permissions</a></li> <li><a href="#package_aide_installed">package_aide_installed</a></li> </ul> <h2>Rule details</h2> <div id="aide_build_database" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Build and Test AIDE Database</h3> <div>aide_build_database</div> <h4>Description</h4> <p>Run the following command to generate a new database: <pre>$ sudo /usr/sbin/aide --init</pre> By default, the database will be written to the file <tt>/var/lib/aide/aide.db.new.gz</tt>. Storing the database, the configuration file <tt>/etc/aide.conf</tt>, and the binary <tt>/usr/sbin/aide</tt> (or hashes of these files), in a secure location (such as on read-only media) provides additional assurance about their integrity. The newly-generated database can be installed as follows: <pre>$ sudo cp /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz</pre> To initiate a manual check, run the following command: <pre>$ sudo /usr/sbin/aide --check</pre> If this check produces any unexpected output, investigate.</p> <h4>Rationale</h4> <p>For AIDE to be effective, an initial database of "known-good" information about files must be captured and it should be able to be verified against the installed files.</p> </div> <div id="aide_check_audit_tools" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Configure AIDE to Verify the Audit Tools</h3> <div>aide_check_audit_tools</div> <h4>Description</h4> <p>The operating system file integrity tool must be configured to protect the integrity of the audit tools.</p> <h4>Rationale</h4> <p>Protecting the integrity of the tools used for auditing purposes is a critical step toward ensuring the integrity of audit information. Audit information includes all information (e.g., audit records, audit settings, and audit reports) needed to successfully audit information system activity. Audit tools include but are not limited to vendor-provided and open-source audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators. It is not uncommon for attackers to replace the audit tools or inject code into the existing tools to provide the capability to hide or erase system activity from the audit logs. To address this risk, audit tools must be cryptographically signed to provide the capability to identify when the audit tools have been modified, manipulated, or replaced. An example is a checksum hash of the file or files.</p> </div> <div id="aide_periodic_cron_checking" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Configure Periodic Execution of AIDE</h3> <div>aide_periodic_cron_checking</div> <h4>Description</h4> <p>At a minimum, AIDE should be configured to run a weekly scan. To implement a daily execution of AIDE at 4:05am using cron, add the following line to <tt>/etc/crontab</tt>: <pre>05 4 * * * root /usr/sbin/aide --check</pre> To implement a weekly execution of AIDE at 4:05am using cron, add the following line to <tt>/etc/crontab</tt>: <pre>05 4 * * 0 root /usr/sbin/aide --check</pre> AIDE can be executed periodically through other means; this is merely one example. The usage of cron's special time codes, such as <tt>@daily</tt> and <tt>@weekly</tt> is acceptable.</p> <h4>Rationale</h4> <p>By default, AIDE does not install itself for periodic execution. Periodically running AIDE is necessary to reveal unexpected changes in installed files. <br /><br /> Unauthorized changes to the baseline configuration could make the system vulnerable to various attacks or allow unauthorized access to the operating system. Changes to operating system configurations can have unintended side effects, some of which may be relevant to security. <br /><br /> Detecting such changes and providing an automated response can help avoid unintended, negative consequences that could ultimately affect the security state of the operating system. The operating system's Information Management Officer (IMO)/Information System Security Officer (ISSO) and System Administrators (SAs) must be notified via email and/or monitoring system trap when there is an unauthorized modification of a configuration item.</p> </div> <div id="aide_scan_notification" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Configure Notification of Post-AIDE Scan Details</h3> <div>aide_scan_notification</div> <h4>Description</h4> <p>AIDE should notify appropriate personnel of the details of a scan after the scan has been run. If AIDE has already been configured for periodic execution in <tt>/etc/crontab</tt>, append the following line to the existing AIDE line: <pre> | /bin/mail -s "$(hostname) - AIDE Integrity Check" root@localhost</pre> Otherwise, add the following line to <tt>/etc/crontab</tt>: <pre>05 4 * * * root /usr/sbin/aide --check | /bin/mail -s "$(hostname) - AIDE Integrity Check" root@localhost</pre> AIDE can be executed periodically through other means; this is merely one example.</p> <h4>Rationale</h4> <p>Unauthorized changes to the baseline configuration could make the system vulnerable to various attacks or allow unauthorized access to the operating system. Changes to operating system configurations can have unintended side effects, some of which may be relevant to security. <br /><br /> Detecting such changes and providing an automated response can help avoid unintended, negative consequences that could ultimately affect the security state of the operating system. The operating system's Information Management Officer (IMO)/Information System Security Officer (ISSO) and System Administrators (SAs) must be notified via email and/or monitoring system trap when there is an unauthorized modification of a configuration item.</p> </div> <div id="aide_use_fips_hashes" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Configure AIDE to Use FIPS 140-2 for Validating Hashes</h3> <div>aide_use_fips_hashes</div> <h4>Description</h4> <p>By default, the <tt>sha512</tt> option is added to the <tt>NORMAL</tt> ruleset in AIDE. If using a custom ruleset or the <tt>sha512</tt> option is missing, add <tt>sha512</tt> to the appropriate ruleset. For example, add <tt>sha512</tt> to the following line in <tt>/etc/aide.conf</tt>: <pre>NORMAL = FIPSR+sha512</pre> AIDE rules can be configured in multiple ways; this is merely one example that is already configured by default.</p> <h4>Rationale</h4> <p>File integrity tools use cryptographic hashes for verifying file contents and directories have not been altered. These hashes must be FIPS 140-2 approved cryptographic hashes.</p> </div> <div id="aide_verify_acls" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Configure AIDE to Verify Access Control Lists (ACLs)</h3> <div>aide_verify_acls</div> <h4>Description</h4> <p>By default, the <tt>acl</tt> option is added to the <tt>FIPSR</tt> ruleset in AIDE. If using a custom ruleset or the <tt>acl</tt> option is missing, add <tt>acl</tt> to the appropriate ruleset. For example, add <tt>acl</tt> to the following line in <tt>/etc/aide.conf</tt>: <pre>FIPSR = p+i+n+u+g+s+m+c+acl+selinux+xattrs+sha256</pre> AIDE rules can be configured in multiple ways; this is merely one example that is already configured by default. The remediation provided with this rule adds <tt>acl</tt> to all rule sets available in <tt>/etc/aide.conf</tt></p> <h4>Rationale</h4> <p>ACLs can provide permissions beyond those permitted through the file mode and must be verified by the file integrity tools.</p> </div> <div id="aide_verify_ext_attributes" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Configure AIDE to Verify Extended Attributes</h3> <div>aide_verify_ext_attributes</div> <h4>Description</h4> <p>By default, the <tt>xattrs</tt> option is added to the <tt>FIPSR</tt> ruleset in AIDE. If using a custom ruleset or the <tt>xattrs</tt> option is missing, add <tt>xattrs</tt> to the appropriate ruleset. For example, add <tt>xattrs</tt> to the following line in <tt>/etc/aide.conf</tt>: <pre>FIPSR = p+i+n+u+g+s+m+c+acl+selinux+xattrs+sha256</pre> AIDE rules can be configured in multiple ways; this is merely one example that is already configured by default. The remediation provided with this rule adds <tt>xattrs</tt> to all rule sets available in <tt>/etc/aide.conf</tt></p> <h4>Rationale</h4> <p>Extended attributes in file systems are used to contain arbitrary data and file metadata with security implications.</p> </div> <div id="file_audit_tools_group_ownership" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Audit Tools Must Be Group-owned by Root</h3> <div>file_audit_tools_group_ownership</div> <h4>Description</h4> <p>Red Hat Enterprise Linux 8 systems providing tools to interface with audit information will leverage user permissions and roles identifying the user accessing the tools, and the corresponding rights the user enjoys, to make access decisions regarding the access to audit tools. Audit tools include, but are not limited to, vendor-provided and open source audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators. Audit tools must have the correct group owner.</p> <h4>Rationale</h4> <p>Protecting audit information also includes identifying and protecting the tools used to view and manipulate log data. Therefore, protecting audit tools is necessary to prevent unauthorized operations on audit information.</p> </div> <div id="file_audit_tools_ownership" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Audit Tools Must Be Owned by Root</h3> <div>file_audit_tools_ownership</div> <h4>Description</h4> <p>Red Hat Enterprise Linux 8 systems providing tools to interface with audit information will leverage user permissions and roles identifying the user accessing the tools, and the corresponding rights the user enjoys, to make access decisions regarding the access to audit tools. Audit tools include, but are not limited to, vendor-provided and open source audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators. Audit tools must have the correct owner.</p> <h4>Rationale</h4> <p>Protecting audit information also includes identifying and protecting the tools used to view and manipulate log data. Therefore, protecting audit tools is necessary to prevent unauthorized operations on audit information.</p> </div> <div id="file_audit_tools_permissions" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Audit Tools Must Have a Mode of 0755 or Less Permissive</h3> <div>file_audit_tools_permissions</div> <h4>Description</h4> <p>Red Hat Enterprise Linux 8 systems providing tools to interface with audit information will leverage user permissions and roles identifying the user accessing the tools, and the corresponding rights the user enjoys, to make access decisions regarding the access to audit tools. Audit tools include, but are not limited to, vendor-provided and open source audit tools needed to successfully view and manipulate audit information system activity and records. Audit tools include custom queries and report generators. Audit tools must have a mode of 0755 or less permissive.</p> <h4>Rationale</h4> <p>Protecting audit information also includes identifying and protecting the tools used to view and manipulate log data. Therefore, protecting audit tools is necessary to prevent unauthorized operations on audit information.</p> </div> <div id="package_aide_installed" class="rule" style="border-bottom: 2px solid; margin-bottom: 1cm; padding-bottom: 1cm;"> <h3>Install AIDE</h3> <div>package_aide_installed</div> <h4>Description</h4> <p>The <code>aide</code> package can be installed with the following command: <pre> $ sudo yum install aide</pre></p> <h4>Rationale</h4> <p>The AIDE package must be installed if it is to be available for integrity checking.</p> </div> </body> </html>
{% extends "layout/base.html" %} {% block title %}Tough Glove | Members {% endblock %} {% block extra_head %} <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css"> {% endblock %} {% block content %} <!-- page heading --> <h1 class="text-center text-danger mt-4 mb-4">Members</h1> <div class="container"> <!-- bootstrap feedback messages --> {% if messages %} {% for message in messages %} {% if message.tags == 'success' or message.tags == 'info' %} <div class="alert alert-success"> {{ message }} </div> {% elif message.tags == 'error' or message.tags == 'debug' or message.tags == 'warning' %} <div class="alert alert-danger"> {{ message }} </div> {% endif %} {% endfor %} {% endif %} <!-- end of bootstrap feedback messages --> <div class="row"> <div class="col-12 mb-3 mb-lg-5"> <div class="card table-nowrap table-card"> <div class="card-header d-flex justify-content-between align-items-center"> <h2 class="mb-0 text-danger">Tough Glove Members</h2> <a href="{% url 'create_member' %}" class="btn btn-danger btn-sm">CREATE NEW MEMBER</a> </div> <div class="table-responsive"> <!-- members table --> <table class="table mb-0"> <thead class="small text-uppercase bg-body text-muted"> <tr> <th>Name</th> <th>Email</th> <th>Username</th> <th>Phone</th> <th>Date Joined</th> <th class="text-end">Action</th> </tr> </thead> <tbody> {% for user in users %} <tr class="align-middle"> <td> <div class="d-flex align-items-center"> <i class="fa fa-user avatar sm rounded-pill me-3 flex-shrink-0" aria-hidden="true"></i> <div> <div class="h6 mb-0 lh-1">{{ user.first_name}} {{ user.last_name }}</div> </div> </div> </td> <td>{{ user.email }}</td> <td> <span class="d-inline-block align-middle">{{ user.username }}</span></td> <td><span>{{ user.members.phone_number}}</span></td> <td>{{ user.date_joined }}</td> <td class="text-end"> <!-- dropdown menu for each member to perform update or delete actions on the member --> <div class="drodown"> <a data-bs-toggle="dropdown" href="#" class="btn p-1" aria-expanded="false"> <i class="fa fa-bars" aria-hidden="true"></i> </a> <div class="dropdown-menu dropdown-menu-end"> <a href="{% url 'update_member' user.id %}" class="dropdown-item">Update {{user.first_name}}</a> <a href="{% url 'delete_member' user.id %}" class="dropdown-item">Delete {{user.first_name}}</a> </div> </div> </td> </tr> {% endfor %} </tbody> <tfoot class="mt-3 mb-3"> <!-- user count indicator --> <tr> <td id="full-width-row">Total Users: </td> <td>{{ user_count }}</td> </tr> </tfoot> </table> </div> </div> </div> </div> </div> {% endblock %}
import React from "react"; import { Button } from "react-bootstrap"; import Classes from "../../styles/Components.module.css"; import { useState } from "react"; import { useEffect } from "react"; import { getRam } from "../../services/ram"; import ramlogo from "../../assests/icons/ram.png" import { useNavigate } from "react-router-dom"; function RamCard() { const [outputRam, setOutputRam] = useState(); const navigate = useNavigate() useEffect(() => { getRam() .then((res) => { setOutputRam(res.data.Ram); }) .catch((error) => { console.log(error); }); }, []); return ( <> {outputRam && ( outputRam.map((val, index) => { return ( <div className={Classes.container}> <div className={Classes.productContainer}> <div className={Classes.icon}> <img src={ramlogo} alt="product logo" /> </div> <div className={Classes.productInfoBlock}> <h4 className={Classes.productName}> {val.VendorName} {val.Model} </h4> <div className={Classes.productDescription}> <ul> <li>Memory Type: {val.MemoryType}</li> <li>Bus Speed : {val.BusSpeed}</li> <li>Capacity: {val.Capacity} GB</li> </ul> </div> </div> <div className={Classes.price}> <span className="mx-2">{val.Price}TK</span> </div> <div className={Classes.action}> <br /> <br /> <Button onClick={()=> { navigate("/ram_manage", { state: { Vendor: val.VendorName, Model: val.Model, BusSpeed: val.BusSpeed, MemoryType: val.MemoryType, Capacity: val.Capacity, Price: val.Price, id: val._id, logo: ramlogo, } }) }} > Manage </Button> </div> </div> </div> ); }) ) } </> ); } export default RamCard;
// // ViewController.swift // UITableView-load-images-Swift-Json // // Created by Luccas Santana Marinho on 04/04/22. // import UIKit struct listData { var name: String var description: String var image: UIImage } class ViewController: UIViewController { private lazy var tableView: UITableView = { let tv = UITableView(frame: .zero, style: .plain) tv.translatesAutoresizingMaskIntoConstraints = false tv.tableFooterView = UIView(frame: .zero) tv.delegate = self tv.dataSource = self tv.bounces = true tv.register(TableViewCell.self, forCellReuseIdentifier: "listCell") return tv }() var heroes = [HeroStats]() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) setupConstraint() downloadJSON { self.tableView.reloadData() } } @objc func viewTwoNavigation() { let viewController = ViewTwo() viewController.modalPresentationStyle = .fullScreen self.present(viewController, animated: true) } func setupConstraint() { tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } func downloadJSON(completed: @escaping () -> ()) { let url = URL(string: "https://api.opendota.com/api/heroStats") URLSession.shared.dataTask(with: url!) { (data, response, error) in if error == nil { do { self.heroes = try JSONDecoder().decode([HeroStats].self, from: data!) DispatchQueue.main.async { completed() } } catch { print("JSON Error") } } }.resume() } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return heroes.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.text = heroes[indexPath.row].localized_name.capitalized cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController = ViewTwo() viewController.hero = heroes[indexPath.row] viewController.modalPresentationStyle = .fullScreen present(viewController, animated: true, completion: nil) } }
/* TaxPayers: Employees, BusinessOwners Number of child classes will be fixed if we want to use variants Algebraic Data type(ADT) Variant is also an ADT. using variants for runtime polymorphism is called functional polymorphism */ #include <iostream> #include <iomanip> #include <array> #include <variant> class Employee; class BusinessOwner; using VType = std::variant<Employee *, BusinessOwner *>; using Container = std::array<VType, 2>; class BusinessOwner { private: std::string _name; std::string _comanyGSTnumber; float _revenue; float _expenses; public: BusinessOwner() = default; BusinessOwner(const BusinessOwner &) = delete; BusinessOwner(BusinessOwner &&) = delete; BusinessOwner &operator=(const BusinessOwner &) = delete; BusinessOwner &operator=(BusinessOwner &&) = delete; ~BusinessOwner() = default; BusinessOwner(std::string name, std::string gst, float rev, float exp) : _name{name}, _comanyGSTnumber{gst}, _revenue{rev}, _expenses{exp} {} float CalculateTaxAmount() { return 0.3f * (_revenue - _expenses); } std::string name() const { return _name; } void setName(const std::string &name) { _name = name; } float revenue() const { return _revenue; } void setRevenue(float revenue) { _revenue = revenue; } }; class Employee { private: std::string _name; float _salary; public: Employee() = default; Employee(const Employee &) = delete; Employee(Employee &&) = delete; Employee &operator=(const Employee &) = delete; Employee &operator=(Employee &&) = delete; ~Employee() = default; Employee(std::string name, float sal) : _name{name}, _salary{sal} {} std::string name() const { return _name; } void setName(const std::string &name) { _name = name; } void Display() { std::cout << std::setprecision(2) << std::fixed << _salary << std::endl; } }; void CommonAction(Container &arr) { for (VType v : arr) { std::visit([](auto &&val) { std::cout << val->name() << "\n"; }, v); /* auto &&val----------------> Template parameter for lambda */ } } void NotSoCommonAction(Container &arr) { for (VType v : arr) { if (std::holds_alternative<BusinessOwner *>(v)) { BusinessOwner *ow = std::get<1>(v); std::cout << ow->CalculateTaxAmount() << std::endl; } if (std::holds_alternative<Employee *>(v)) { Employee *em = std::get<0>(v); em->Display(); } } } int main() { Employee *emp = new Employee("himanshu", 25000.0f); BusinessOwner *bow = new BusinessOwner("Muskan Limited", "05AKK783623", 10560070.0f, 34000.0f); Container arr{emp, bow}; CommonAction(arr); NotSoCommonAction(arr); return 0; } /* Employee | Business Employee | Business [ 0x100H | //////// ] [ /////// | 0x987H ] <------------------------------arr------------------------------> Both slot can't fill at the same time Scenario 1 : I want to execute a function that present in all types of variant e.g getter for name(just open the variant and call getter) Scenario 2 : You want to call a function that only exists in some but not all type of variant -> for variants in array check whether variant has Employee and perform action else continue */
import modal app = modal.App('llama') volume = modal.Volume.from_name("model-store") model_store_path = "/vol/models" image = modal.Image.debian_slim().pip_install('transformers', 'torch', 'huggingface-cli', 'accelerate') @app.function(image=image, volumes={model_store_path: volume}, gpu="l4") def load_model(): import torch import os from transformers import AutoTokenizer, AutoModelForCausalLM model_id = "meta-llama/Meta-Llama-3-8B-Instruct" print('loading model and tokenizer') tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=model_store_path) model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="cuda:0", cache_dir=model_store_path) print('committing model to volume') volume.commit() messages = [ {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"}, {"role": "user", "content": "Who are you?"}, ] input_ids = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_tensors="pt" ).to(model.device) terminators = [ tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|eot_id|>") ] outputs = model.generate( input_ids, max_new_tokens=256, eos_token_id=terminators, do_sample=True, temperature=0.6, top_p=0.9, ) response = outputs[0][input_ids.shape[-1]:] print(tokenizer.decode(response, skip_special_tokens=True))
# -*- coding: utf-8 -*- #!/usr/bin/python from mininet.net import Mininet from mininet.node import Controller, OVSSwitch from mininet.cli import CLI from mininet.link import TCLink from mininet.log import setLogLevel from os import environ POXDIR = environ[ 'HOME' ] + '/pox' #Definindo a classe POX para ser utilizada como controlador class POX( Controller ): def __init__( self, name, cdir=POXDIR, command='python pox.py', cargs=( 'openflow.of_01 --port=%s ' 'forwarding.hub' ), **kwargs ): Controller.__init__( self, name, cdir=cdir, command=command, cargs=cargs, **kwargs ) def simulaRede(): "Criando um ambiente de simulacao mininet" net = Mininet( controller=POX, switch=OVSSwitch, link=TCLink ) print("*** Criando o Controlador na porta 6634") c1 = net.addController( 'c1', port=6634 ) print ("*** Criando um comutador") s1 = net.addSwitch( 's1' ) print ("*** Criando host 1") h1 = net.addHost('h1') print ("*** Criando host 2") h2 = net.addHost('h2') print ("*** Criando host 3") h3 = net.addHost('h3') print ("*** Criando host 4") h4 = net.addHost('h4') print ("*** Criando os enlaces dos hosts para o comutador") net.addLink( s1, h1, bw=100, delay='50ms', loss=0, use_htb=True ) net.addLink( s1, h2, bw=100, delay='50ms', loss=0, use_htb=True ) net.addLink( s1, h3, bw=100, delay='50ms', loss=0, use_htb=True ) net.addLink( s1, h4, bw=100, delay='50ms', loss=0, use_htb=True ) print ("*** Iniciando o rede") net.build() print ("*** Iniciando o controlador") c1.start() print ("*** Iniciando o comutado, conectado ao Controlador C1") s1.start( [ c1 ] ) # Iniciando a interface de linha de comando do Mininet CLI(net) print ("Parando a Simulacao") net.stop() simulaRede()
package day07 import ( "fmt" "testing" "github.com/google/go-cmp/cmp" ) func TestDetermineHandType(t *testing.T) { tests := []struct { label string input []int want handType }{ { label: "QQQQQ", input: []int{11, 11, 11, 11, 11}, want: FiveOfAKind, }, { label: "99992", input: []int{8, 8, 8, 8, 1}, want: FourOfAKind, }, { label: "33322", input: []int{2, 2, 2, 1, 1}, want: FullHouse, }, { label: "T55J5", input: []int{9, 4, 4, 10, 4}, want: ThreeOfAKind, }, { label: "KK677", input: []int{12, 12, 5, 6, 6}, want: TwoPairs, }, { label: "32T3K", input: []int{2, 1, 9, 2, 12}, want: OnePair, }, { label: "9TJQK", input: []int{9, 10, 11, 12, 13}, want: HighCard, }, } for i, test := range tests { test := test t.Run(fmt.Sprintf("case %d", i+1), func(tt *testing.T) { tt.Parallel() got := determineHandType(test.input) if diff := cmp.Diff(test.want, got); diff != "" { t.Errorf("determineHandType(%v) mismatch (-want +got):\n%s", test.label, diff) } }) } } func TestDetermineHandTypeWithJoker(t *testing.T) { tests := []struct { label string input []int want handType }{ { label: "QQQQQ", input: []int{11, 11, 11, 11, 11}, want: FiveOfAKind, }, { label: "99992", input: []int{8, 8, 8, 8, 1}, want: FourOfAKind, }, { label: "33322", input: []int{2, 2, 2, 1, 1}, want: FullHouse, }, { label: "T55J5", input: []int{9, 4, 4, 10, 4}, want: FourOfAKind, }, { label: "KK677", input: []int{12, 12, 5, 6, 6}, want: TwoPairs, }, { label: "32T3K", input: []int{2, 1, 9, 2, 12}, want: OnePair, }, { label: "9TJQK", input: []int{9, 10, 11, 12, 13}, want: OnePair, }, // 5 jokers { label: "JJJJJ", input: []int{10, 10, 10, 10, 10}, want: FiveOfAKind, }, // 4 jokers { label: "JJJJ5", input: []int{10, 10, 10, 10, 4}, want: FiveOfAKind, }, // 3 jokers { label: "JJJ66", input: []int{10, 10, 10, 5, 5}, want: FiveOfAKind, }, { label: "JJJ65", input: []int{10, 10, 10, 5, 4}, want: FourOfAKind, }, // 2 jokers { label: "JJ666", input: []int{10, 10, 5, 5, 5}, want: FiveOfAKind, }, { label: "JJ665", input: []int{10, 10, 5, 5, 4}, want: FourOfAKind, }, { label: "JJ654", input: []int{10, 10, 5, 4, 3}, want: ThreeOfAKind, }, // 1 joker { label: "J6666", input: []int{10, 5, 5, 5, 5}, want: FiveOfAKind, }, { label: "J6665", input: []int{10, 5, 5, 5, 4}, want: FourOfAKind, }, { label: "J6654", input: []int{10, 5, 5, 4, 3}, want: ThreeOfAKind, }, { label: "J6543", input: []int{10, 5, 4, 3, 2}, want: OnePair, }, { label: "J6655", input: []int{10, 5, 5, 4, 4}, want: FullHouse, }, } for i, test := range tests { test := test t.Run(fmt.Sprintf("case %d", i+1), func(tt *testing.T) { tt.Parallel() got := determineHandTypeWithJoker(test.input) if diff := cmp.Diff(test.want, got); diff != "" { t.Errorf("determineHandTypeWithJoker(%s) mismatch (-want +got):\n%s", test.label, diff) } }) } }
import React from 'react' import './services.css' import OrangeJuice from '../../assets/orange-juice.svg' import Chef from '../../assets/chef.svg' import Restaurant from '../../assets/restaurant.svg' import ServiceCard from '../../components/ServiceCard' const data = [ { id : 1, icon : OrangeJuice, title : 'Fresh food', description : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sollicitudin hendrerit a amet viverra. Nunc pretium in amet at mattis cras. ' }, { id : 2, icon : Chef, title : 'skilled Chef', description : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sollicitudin hendrerit a amet viverra. Nunc pretium in amet at mattis cras. ' }, { id : 3, icon : Restaurant, title : 'Exotic dishes', description : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sollicitudin hendrerit a amet viverra. Nunc pretium in amet at mattis cras. ' }, ] const Services = () => { return ( <section className='services'> <h2>Special</h2> <p className='under_title'>What makes us special</p> <div className="services_box"> { data.map(item => <ServiceCard key={item.id} icon={item.icon} title={item.title} description={item.description} />) } </div> </section> ) } export default Services
package ch.epfl.bluebrain.nexus.delta.sdk.schemas import cats.effect.{Clock, IO} import cats.syntax.all._ import ch.epfl.bluebrain.nexus.delta.kernel.kamon.KamonMetricComponent import ch.epfl.bluebrain.nexus.delta.kernel.utils.UUIDF import ch.epfl.bluebrain.nexus.delta.rdf.IriOrBNode.Iri import ch.epfl.bluebrain.nexus.delta.rdf.Vocabulary.{contexts, nxv} import ch.epfl.bluebrain.nexus.delta.rdf.jsonld.ExpandedJsonLd import ch.epfl.bluebrain.nexus.delta.rdf.jsonld.api.JsonLdApi import ch.epfl.bluebrain.nexus.delta.sdk._ import ch.epfl.bluebrain.nexus.delta.sdk.identities.model.Caller import ch.epfl.bluebrain.nexus.delta.sdk.implicits._ import ch.epfl.bluebrain.nexus.delta.sdk.jsonld.JsonLdSourceProcessor.JsonLdSourceResolvingParser import ch.epfl.bluebrain.nexus.delta.sdk.model.IdSegmentRef.{Latest, Revision, Tag} import ch.epfl.bluebrain.nexus.delta.sdk.model._ import ch.epfl.bluebrain.nexus.delta.sdk.projects.FetchContext import ch.epfl.bluebrain.nexus.delta.sdk.resolvers.ResolverContextResolution import ch.epfl.bluebrain.nexus.delta.sdk.schemas.Schemas.{entityType, expandIri} import ch.epfl.bluebrain.nexus.delta.sdk.schemas.SchemasImpl.SchemasLog import ch.epfl.bluebrain.nexus.delta.sdk.schemas.model.SchemaCommand._ import ch.epfl.bluebrain.nexus.delta.sdk.schemas.model.SchemaRejection.{ProjectContextRejection, RevisionNotFound, SchemaNotFound, TagNotFound} import ch.epfl.bluebrain.nexus.delta.sdk.schemas.model.{SchemaCommand, SchemaEvent, SchemaRejection, SchemaState} import ch.epfl.bluebrain.nexus.delta.sourcing._ import ch.epfl.bluebrain.nexus.delta.sourcing.model.Identity.Subject import ch.epfl.bluebrain.nexus.delta.sourcing.model.ProjectRef import ch.epfl.bluebrain.nexus.delta.sourcing.model.Tag.UserTag import io.circe.Json final class SchemasImpl private ( log: SchemasLog, fetchContext: FetchContext[ProjectContextRejection], schemaImports: SchemaImports, sourceParser: JsonLdSourceResolvingParser[SchemaRejection] ) extends Schemas { implicit private val kamonComponent: KamonMetricComponent = KamonMetricComponent(entityType.value) override def create( projectRef: ProjectRef, source: Json )(implicit caller: Caller): IO[SchemaResource] = createCommand(None, projectRef, source).flatMap(eval).span("createSchema") override def create( id: IdSegment, projectRef: ProjectRef, source: Json )(implicit caller: Caller): IO[SchemaResource] = createCommand(Some(id), projectRef, source).flatMap(eval).span("createSchema") override def createDryRun(projectRef: ProjectRef, source: Json)(implicit caller: Caller): IO[SchemaResource] = createCommand(None, projectRef, source).flatMap(dryRun) private def createCommand(id: Option[IdSegment], projectRef: ProjectRef, source: Json)(implicit caller: Caller ): IO[CreateSchema] = for { pc <- fetchContext.onCreate(projectRef) iri <- id.traverse(expandIri(_, pc)) jsonLd <- sourceParser(projectRef, pc, iri, source) expandedResolved <- resolveImports(jsonLd.iri, projectRef, jsonLd.expanded) } yield CreateSchema(jsonLd.iri, projectRef, source, jsonLd.compacted, expandedResolved, caller.subject) override def update( id: IdSegment, projectRef: ProjectRef, rev: Int, source: Json )(implicit caller: Caller): IO[SchemaResource] = { for { pc <- fetchContext.onModify(projectRef) iri <- expandIri(id, pc) (compacted, expanded) <- sourceParser(projectRef, pc, iri, source).map { j => (j.compacted, j.expanded) } expandedResolved <- resolveImports(iri, projectRef, expanded) res <- eval(UpdateSchema(iri, projectRef, source, compacted, expandedResolved, rev, caller.subject)) } yield res }.span("updateSchema") override def refresh( id: IdSegment, projectRef: ProjectRef )(implicit caller: Caller): IO[SchemaResource] = { for { pc <- fetchContext.onModify(projectRef) iri <- expandIri(id, pc) schema <- log.stateOr(projectRef, iri, SchemaNotFound(iri, projectRef)) (compacted, expanded) <- sourceParser(projectRef, pc, iri, schema.source).map { j => (j.compacted, j.expanded) } expandedResolved <- resolveImports(iri, projectRef, expanded) res <- eval(RefreshSchema(iri, projectRef, compacted, expandedResolved, schema.rev, caller.subject)) } yield res }.span("refreshSchema") override def tag( id: IdSegment, projectRef: ProjectRef, tag: UserTag, tagRev: Int, rev: Int )(implicit caller: Subject): IO[SchemaResource] = { for { pc <- fetchContext.onModify(projectRef) iri <- expandIri(id, pc) res <- eval(TagSchema(iri, projectRef, tagRev, tag, rev, caller)) } yield res }.span("tagSchema") override def deleteTag( id: IdSegment, projectRef: ProjectRef, tag: UserTag, rev: Int )(implicit caller: Subject): IO[SchemaResource] = (for { pc <- fetchContext.onModify(projectRef) iri <- expandIri(id, pc) res <- eval(DeleteSchemaTag(iri, projectRef, tag, rev, caller)) } yield res).span("deleteSchemaTag") override def deprecate( id: IdSegment, projectRef: ProjectRef, rev: Int )(implicit caller: Subject): IO[SchemaResource] = (for { pc <- fetchContext.onModify(projectRef) iri <- expandIri(id, pc) res <- eval(DeprecateSchema(iri, projectRef, rev, caller)) } yield res).span("deprecateSchema") override def fetch(id: IdSegmentRef, projectRef: ProjectRef): IO[SchemaResource] = { for { pc <- fetchContext.onRead(projectRef) iri <- expandIri(id.value, pc) state <- id match { case Latest(_) => log.stateOr(projectRef, iri, SchemaNotFound(iri, projectRef)) case Revision(_, rev) => log.stateOr(projectRef, iri, rev, SchemaNotFound(iri, projectRef), RevisionNotFound) case Tag(_, tag) => log.stateOr(projectRef, iri, tag, SchemaNotFound(iri, projectRef), TagNotFound(tag)) } } yield state.toResource }.span("fetchSchema") private def eval(cmd: SchemaCommand) = log.evaluate(cmd.project, cmd.id, cmd).map(_._2.toResource) private def dryRun(cmd: SchemaCommand) = log.dryRun(cmd.project, cmd.id, cmd).map(_._2.toResource) private def resolveImports(id: Iri, projectRef: ProjectRef, expanded: ExpandedJsonLd)(implicit caller: Caller) = schemaImports.resolve(id, projectRef, expanded.addType(nxv.Schema)) } object SchemasImpl { type SchemasLog = ScopedEventLog[Iri, SchemaState, SchemaCommand, SchemaEvent, SchemaRejection] /** * Constructs a [[Schemas]] instance. */ final def apply( fetchContext: FetchContext[ProjectContextRejection], schemaImports: SchemaImports, contextResolution: ResolverContextResolution, validate: ValidateSchema, config: SchemasConfig, xas: Transactors, clock: Clock[IO] )(implicit api: JsonLdApi, uuidF: UUIDF ): Schemas = { val parser = new JsonLdSourceResolvingParser[SchemaRejection]( List(contexts.shacl, contexts.schemasMetadata), contextResolution, uuidF ) new SchemasImpl( ScopedEventLog(Schemas.definition(validate, clock), config.eventLog, xas), fetchContext, schemaImports, parser ) } }
/* eslint-disable @typescript-eslint/no-explicit-any */ import { FullClassDefinition, Scope, MethodDefinition, PropertyDefinition, ReadOnlyPropertyDefinition, ClassDefinition, GetScopedMembersFrom, VariableDefinition, FullMemberDefinition, MemberDefinition } from './models'; import { AnyObject } from 'anux-common'; import { getInstanceMetaFromDefinition } from './registry'; import { MetaNotFound } from './errors'; function createSmartClassWrapper(definition: MemberDefinition, func: Function, bindFunc: boolean) { return function smartClassWrapper(this: AnyObject, ...args: any[]) { const meta = getInstanceMetaFromDefinition(this, definition as FullMemberDefinition); if (!meta) throw new MetaNotFound(this); const instance = meta.internalInstance; return bindFunc ? func.bind(instance) : func.call(instance, ...args); }; } function defineMethod(prototype: AnyObject, memberName: string, methodDefinition: MethodDefinition): void { Object.defineProperty(prototype, memberName, { get: createSmartClassWrapper(methodDefinition, methodDefinition.definition, true), enumerable: true, configurable: true, }); } function defineProperty(prototype: AnyObject, memberName: string, propertyDefinition: PropertyDefinition | ReadOnlyPropertyDefinition): void { Object.defineProperty(prototype, memberName, { get: createSmartClassWrapper(propertyDefinition, propertyDefinition.get, true), set: 'set' in propertyDefinition ? createSmartClassWrapper(propertyDefinition, propertyDefinition.set, false) : undefined, enumerable: true, configurable: true, }); } function defineVariable(prototype: AnyObject, memberName: string, definition: VariableDefinition): void { function variableGetter(this: AnyObject) { const meta = getInstanceMetaFromDefinition(this, definition as FullMemberDefinition); if (!meta) throw new MetaNotFound(this); return meta.variables[memberName]; } function variableSetter(this: AnyObject, value: any) { const meta = getInstanceMetaFromDefinition(this, definition as FullMemberDefinition); if (!meta) throw new MetaNotFound(this); meta.variables[memberName] = value; } const get = variableGetter.setName(`${memberName}_getter`); const set = variableSetter.setName(`${memberName}_setter`); Object.defineProperty(prototype, memberName, { get, set, enumerable: true, configurable: true, }); } export function createPrototype<T extends ClassDefinition, S extends Scope[]>(definition: T, scopes: S) { const prototype: AnyObject = {}; Object.entries(definition as FullClassDefinition).forEach(([memberName, memberDefinition]) => { if (!scopes.includes(memberDefinition.scope)) return; switch (memberDefinition.type) { case 'method': defineMethod(prototype, memberName, memberDefinition); break; case 'property': defineProperty(prototype, memberName, memberDefinition); break; case 'variable': defineVariable(prototype, memberName, memberDefinition); break; } }); return prototype as GetScopedMembersFrom<T, S[number]>; }
from collections.abc import Iterable from django.db import models from django.core.validators import MinLengthValidator from django.utils.text import slugify # Create your models here. class Band(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, blank=True, unique=True, editable=False) def __str__(self) -> str: return self.name def save(self): self.slug = slugify(self.name) return super().save() class Artist(models.Model): name = models.CharField(max_length=255) band = models.ForeignKey(Band, on_delete=models.CASCADE, related_name='artists') def __str__(self) -> str: return self.name class Album(models.Model): title = models.CharField(max_length=255) year = models.IntegerField() band = models.ForeignKey(Band, on_delete=models.CASCADE, related_name='albums', null=True) slug = models.SlugField(max_length=255, blank=True, unique=True, editable=False) def __str__(self) -> str: return self.title def save(self): self.slug = slugify(self.title) return super().save() class Song(models.Model): title = models.CharField(max_length=255) band = models.ForeignKey(Band, on_delete=models.CASCADE, related_name='songs') year = models.IntegerField() album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='songs') slug = models.SlugField(max_length=255, blank=True, unique=True, editable=False) def __str__(self) -> str: return self.title def save(self): self.slug = slugify(self.title) return super().save() class Comment(models.Model): user_name = models.CharField(max_length=120) user_email = models.EmailField() content = models.TextField(validators=[MinLengthValidator(4)], max_length=400) song = models.ForeignKey(Song, on_delete=models.CASCADE, related_name="comments") def __str__(self) -> str: return self.user_name
class Settings(): """Класс хранения настроек игры.""" def __init__(self): """Инициализация настроек игры.""" self.screen_width = 1200 self.screen_heigh = 800 self.bg_color = (230, 230, 230) self.ship_speed = 2 self.ship_limit = 3 self.alien_speed = 1.0 self.fleet_drop_speed = 10 self.fleet_direction = 1 self.bullet_speed = 1.5 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullets_allowed = 5 self.speedup_scale = 1.1 self.score_scale = 1.5 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): """Инициализация меняющихся настроек игры.""" self.ship_speed_factor = 1.5 self.bullet_speed_factor = 3.0 self.alien_speed_factor = 1.0 self.fleet_direction = 1 self.alien_points = 50 def increase_speed(self): """Увеличение настроек скорости и стоимости пришельцев.""" self.ship_speed_factor *= self.speedup_scale self.bullet_speed_factor *= self.speedup_scale self.alien_speed_factor *= self.speedup_scale self.alien_points = int(self.alien_points * self.score_scale)
import React, { useState } from "react"; const TicTacToe = () => { const [board, setBoard] = useState(Array(9).fill(null)); const [player, setPlayer] = useState("X"); const [winner, setWinner] = useState(null); const handleClick = (index) => { if (winner) return; if (board[index]) return; const newBoard = [...board]; newBoard[index] = player; setBoard(newBoard); const newPlayer = player === "X" ? "O" : "X"; setPlayer(newPlayer); checkForWinner(newBoard); }; const checkForWinner = (board) => { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (board[a] && board[a] === board[b] && board[a] === board[c]) { setWinner(board[a]); return; } } if (!board.includes(null)) { setWinner("draw"); } }; const renderSquare = (index) => { return ( <button className="square" onClick={() => handleClick(index)} > {board[index]} </button> ); }; const renderStatus = () => { if (winner) { return winner === "draw" ? "It's a draw!" : `${winner} has won!`; } else { return `Next player: ${player}`; } }; return ( <div className="container"> <div className="status">{renderStatus()}</div> <div className="board"> <div className="row"> {renderSquare(0)} {renderSquare(1)} {renderSquare(2)} </div> <div className="row"> {renderSquare(3)} {renderSquare(4)} {renderSquare(5)} </div> <div className="row"> {renderSquare(6)} {renderSquare(7)} {renderSquare(8)} </div> </div> </div> ); }; export default TicTacToe;