text
stringlengths
184
4.48M
import { Avatar, Badge, Box, Button, Container, FormControl, FormLabel, Heading, IconButton, InputGroup, List, ListItem, Modal, ModalBody, ModalCloseButton, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Stack, StackDivider, Text, Textarea, useDisclosure, VStack } from "@chakra-ui/react"; import { Form, Formik } from "formik"; import React, { useEffect, useState } from "react"; import { BiUserPlus } from "react-icons/bi"; import { BsBookmarkFill } from "react-icons/bs"; import { useQueryClient } from "react-query"; import { ScrollRestoration, useNavigate, useParams } from "react-router-dom"; import { toast, ToastContainer } from "react-toastify"; import styled from "styled-components"; import SkeletonPage from "../../components/common/skeleton.page"; import InputFieldSelect from "../../components/RentalProperty/InputField.select"; import { useRentalPosts } from "../../hooks/rentalPost"; import { useUser } from "../../hooks/user"; import capitalize from "../../utils/Capitalize"; import { Report_Type } from "../../utils/list"; import NumberWithCommas from "../../utils/numberWithCommas"; import InputFieldTextarea from "./../../components/RentalProperty/InputField.textarea"; const GridContainer = styled.div` display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); grid-auto-rows: repeat(auto-fill, minmax(200px, 1fr)); grid-gap: 20px; `; const PropertyDetailPage = () => { const { isOpen: isOpenReport, onOpen: onOpenReport, onClose: onCloseReport } = useDisclosure(); // const notify = (message) => toast(message); // notify("Welcome to the property detail page"); const { postId } = useParams(); const queryClient = useQueryClient(); const navigate = useNavigate(); const { fetchRentalPost, refetchRentalPost, isFetchingRentalPost, isLoadingRentalPost, errorRentalPost, saveRentalPost, saveRentalPostData, isSavingRentalPost, } = useRentalPosts(postId); // report: actionReportPost.mutateAsync, // isReportLoading: actionReportPost.isLoading, const { follow, followData, refetchFollow, isFollowLoading, isFollowFetching, report, isReportLoading, } = useUser(); const [navClick, setNavClick] = React.useState(); React.useEffect(() => { window.scrollTo(0, 0); }, [navClick]); useEffect( (postId) => { refetchRentalPost(postId); }, [refetchRentalPost], ); const [isSavedPost, setIsSavePost] = useState(false); if ((isFetchingRentalPost, isLoadingRentalPost || !fetchRentalPost)) { return <SkeletonPage page="rental detail" />; } const post = fetchRentalPost?.post; const author = fetchRentalPost?.post.author; const handleSavePost = () => { saveRentalPost(post.id); }; const handleFollow = async () => { await follow(author.id).then((data) => {}); }; return ( <Container maxW={"7xl"} className="p-2 m-4 z-10 w-full md:!w-2/3 overflow-auto "> <Modal isOpen={isOpenReport} onClose={onCloseReport}> <ModalOverlay /> <ModalContent> <ModalHeader>Report</ModalHeader> <ModalCloseButton /> <ModalBody className="p-4"> <Formik initialValues={{ Report_Type: "", Report_Description: "", }} onSubmit={async (values, actions) => { // alert(JSON.stringify(values, null, 2)); report({ postId: post.id, ...values }).then((data) => { onCloseReport(); }); }} > {(formik) => ( <Form> <div className="flex flex-col space-y-2"> <InputFieldSelect required={true} placeholder="Please Select" name="Report_Type" label="Report Type" options={Report_Type} /> <InputFieldTextarea name="Report_Description" label="Description" placeholder="Description" type="text" /> <Button isLoading={isReportLoading} colorScheme="blue" mr={3} type="submit"> Submit </Button> </div> </Form> )} </Formik> </ModalBody> {/* <ModalFooter> <Button colorScheme="blue" mr={3} onClick={onCloseReport}> Close </Button> <Button variant="ghost">Secondary Action</Button> </ModalFooter> */} </ModalContent> </Modal> <div className="flex flex-col"> <div className="flex justify-between items-center p-2"> <div onClick={() => { if (author.id === fetchRentalPost.requestUserId) { navigate(`/user`); } else { navigate(`/user/${author.username}`); } }} className="flex cursor-pointer justify-center items-center space-x-4" > <Avatar name="user" size={"lg"} aria-label="User menu" src={`/api/user/profileimage/${author.username}`} /> <div className="flex flex-col"> <span className="text-md md:text-lg font-bold">{capitalize(author.username)}</span> <div className="flex flex-col md:flex-row text-xs md:text-sm font-light md:space-x-4"> <span>4.2</span> <span className="whitespace-nowrap">{`${capitalize(author.address[0].region)}, ${capitalize(author.address[0].city)}`}</span> <span>{author.firstName}</span> </div> </div> </div> <div className="flex space-x-2"> {author.id !== fetchRentalPost.requestUserId && ( <div className="flex items-center space-x-2"> <Button onClick={onOpenReport} colorScheme="orange" size="xs"> Report </Button> <Button isLoading={isFollowLoading || isFollowFetching} onClick={handleFollow} colorScheme="messenger"> {followData ? followData.follow ? <span className="text-white">Unfollow</span> : <span className="text-white">Follow</span> : fetchRentalPost.isFollowed ? <span className="text-white">Unfollow</span> : <span className="text-white">Follow</span>} </Button> </div> )} <div onClick={handleSavePost} className="p-2 right-2 cursor-pointer top-2 z-[2]"> <BsBookmarkFill style={{ color: saveRentalPostData ? (saveRentalPostData.isSaved ? "red" : "black") : post.savedBy.length > 0 ? "red" : "black", }} className={` transition-all duration-150 ease-in-out font-bold text-lg`} /> </div> </div> </div> {post.propertyImages.length > 0 && ( <div className="flex flex-col md:flex-row justify-evenly space-x-4 w-full h-[50vh] "> <div className="md:w-1/2 w-full flex-1 "> <Box rounded={"lg"} className="h-full" backgroundPosition={"center"} backgroundRepeat={"no-repeat"} backgroundSize={"cover"} backgroundImage={`url(/api/posts/images/${post.propertyImages[0].image})`} /> </div> {post.propertyImages.length > 1 && ( <div className="md:w-1/2 w-full flex "> {/* <div className="md:grid md:grid-cols-3 md:grid-rown-3 w-full gap-4 hidden"></div> */} <div style={{ width: "100%", display: "grid", gridTemplateColumns: `repeat(${Math.ceil(post.propertyImages.slice(1).length / 2)}, minmax(auto, 1fr))`, gridAutoRows: "repeat(auto-fill, minmax(200px, 1fr))", gridGap: "20px", }} > {post.propertyImages.slice().map((image, index) => { return <Box key={index} rounded={"lg"} overflow={"clip"} className="h-full" backgroundPosition={"center"} backgroundRepeat={"no-repeat"} backgroundSize={"cover"} backgroundImage={`url(/api/posts/images/${image.image})`} />; })} </div> </div> )} </div> )} <Stack w={"full"} spacing={{ base: 6, md: 10 }}> <Box as={"header"}> <Heading lineHeight={1.1} fontWeight={600} fontSize={{ base: "2xl", sm: "4xl", lg: "5xl" }}> {post.propertyTitle} </Heading> <Text color={"gray.900"} fontWeight={300} fontSize={"2xl"}> {`${NumberWithCommas(post.propertyPrice[post.propertyPrice.length - 1].price)} birr / ${post.propertyPrice[post.propertyPrice.length - 1].priceType.toLowerCase()}`} </Text> </Box> <Stack spacing={{ base: 4, sm: 6 }} direction={"column"} divider={<StackDivider borderColor={"gray.200"} />}> <VStack spacing={{ base: 4, sm: 6 }}> <Text color={"gray.500"} fontSize={"2xl"} fontWeight={"300"}> {post.propertyDescription} </Text> </VStack> <Box> <Text fontSize={{ base: "16px", lg: "18px" }} color={"yellow.500"} fontWeight={"500"} textTransform={"uppercase"} mb={"4"}> Product Details </Text> <List spacing={2}> <ListItem> <Text as={"span"} fontWeight={"bold"}> Avalibliity: </Text>{" "} {post.isAvailable ? ( <Badge fontWeight={"bold"} fontSize={"x-small"} p={1} px={2} bg={"green.500"} textColor={"white"} rounded={"full"}> Available </Badge> ) : ( <Badge fontWeight={"bold"} fontSize={"x-small"} p={1} px={2} bg={"red.500"} textColor={"white"} rounded={"full"}> Not Available </Badge> )} </ListItem> <ListItem> <Text as={"span"} fontWeight={"bold"}> Property Name: </Text>{" "} <span>{post.propertyTitle}</span> </ListItem> <ListItem> <Text as={"span"} fontWeight={"bold"}> Type: </Text>{" "} <span>{post.propertyType}</span> </ListItem> <ListItem> <Text as={"span"} fontWeight={"bold"}> Quantity: </Text>{" "} <span>{post.propertyQuantity}</span> </ListItem> <ListItem> <Text as={"span"} fontWeight={"bold"}> Address: </Text>{" "} <span>{`${post.propertyStreet} ${post.propertyRegion}, ${post.propertyCity}`}</span> </ListItem> <ListItem> <Text as={"span"} fontWeight={"bold"}> Maximum Lease Length: </Text>{" "} <span>{`${post.maxLeaseLengthValue} ${post.maxLeaseLengthType}`}</span> </ListItem> <ListItem> <Text as={"span"} fontWeight={"bold"}> Minimum Lease Length: </Text>{" "} <span>{`${post.minLeaseLengthValue} ${post.minLeaseLengthType}`}</span> </ListItem> <ListItem> <div className="flex space-x-2 items-start"> <Text as={"span"} fontWeight={"bold"}> Price: </Text> <div className="flex flex-col"> {post.propertyPrice.map((price, index) => { return <span key={index}>{`${NumberWithCommas(price.price)} birr / ${price.priceType.toLowerCase()}`}</span>; })} </div> </div> </ListItem> {post.propertyContact.map((contact, index) => { return ( <ListItem key={index}> <Text as={"span"} fontWeight={"bold"}> {capitalize(contact.type)}: </Text>{" "} <span>{contact.value}</span> </ListItem> ); })} </List> </Box> </Stack> <Button rounded={"none"} w={"full"} mt={8} size={"lg"} py={"7"} bg={"gray.900"} color={"white"} textTransform={"uppercase"} _hover={{ transform: "translateY(2px)", boxShadow: "lg", }} > Message </Button> {/* <Stack direction="row" alignItems="center" justifyContent={"center"}> <MdLocalShipping /> <Text></Text> </Stack> */} </Stack> </div> </Container> ); }; export default PropertyDetailPage;
<#include "../../../_layout/_layout2.0.html"><#t> <@header/> <div id="form-save" style="margin: 15px"> <form name="custom-form" class="layui-form layui-form-pane" id="custom-form"> <blockquote class="layui-elem-quote">客户信息:</blockquote> <div class="layui-form-item"> <label class="layui-form-label"><span>*</span>姓名:</label> <div class="layui-input-inline "> <input type="text" name="name" autocomplete="off" class="layui-input" lay-verify="required" value="${data.name!''}"> <input name="mid" value="${data.mid!''}" id="mid" type="hidden"> </div> <label class="layui-form-label"><span>*</span>联系方式:</label> <div class="layui-input-inline "> <input type="text" name="contact" autocomplete="off" class="layui-input" lay-verify="required" value="${data.contact!''}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"><span>*</span>计划出行时间:</label> <div class="layui-input-inline "> <#if data.planTime??> <input type="text" name="planTime" placeholder="开始时间" id="plan-time" value="${data.planTime?string('yyyy-MM-dd HH:mm:ss')}" class="layui-input" lay-verify="required"> <#else> <input type="text" name="planTime" autocomplete="off" class="layui-input" lay-verify="required" id="plan-time"> </#if> </div> <label class="layui-form-label"><span>*</span>出行天数:</label> <div class="layui-input-inline "> <input type="number" name="travelDay" autocomplete="off" class="layui-input" lay-verify="required" value="${data.travelDay!''}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"><span>*</span>出发地:</label> <div class="layui-input-inline "> <input type="text" name="departure" autocomplete="off" class="layui-input" value="${data.departure!''}" lay-verify="required"> </div> <label class="layui-form-label"><span>*</span>目的地:</label> <div class="layui-input-inline "> <input type="text" name="destination" autocomplete="off" class="layui-input" lay-verify="required" value="${data.destination!''}"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"><span>*</span>出行人数:</label> <div class="layui-input-inline "> <input type="number" name="travelNumber" autocomplete="off" class="layui-input" lay-verify="required" value="${data.travelNumber!''}"> </div> <label class="layui-form-label"><span>*</span>房间数:</label> <div class="layui-input-inline "> <input type="number" name="roomNumber" autocomplete="off" class="layui-input" value="${data.roomNumber!''}" lay-verify="required"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"><span>*</span>人均预算:</label> <div class="layui-input-inline"> <#if data.budget??> <input type="text" name="budget" autocomplete="off" class="layui-input" lay-verify="decimal" value="${data.budget?string('#.##')}"> <#else> <input type="text" name="budget" autocomplete="off" class="layui-input" lay-verify="decimal" > </#if> </div> </div> <#if data.createTime??> <div class="layui-form-item"> <label class="layui-form-label">提交时间:</label> <div class="layui-input-inline"> <input type="text" readonly autocomplete="off" class="layui-input" lay-verify="required" value="${data.createTime?string('yyyy-MM-dd HH:mm:ss')}"> </div> <label class="layui-form-label">客户来源:</label> <div class="layui-input-inline"> <#if data.source?? && data.source == 1> <input type="text" readonly autocomplete="off" class="layui-input" value="独立开发"> </#if> <#if data.source?? && data.source == 2> <input type="text" readonly autocomplete="off" class="layui-input" value="公众号"> </#if> </div> </div> </#if> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">特殊需求:</label> <div class="layui-input-block"> <textarea placeholder="请输入内容" class="layui-textarea" name="specialNeed">${data.specialNeed!''}</textarea> </div> </div> <blockquote class="layui-elem-quote">补充信息:</blockquote> <div class="layui-form-item"> <div class="layui-form-item"> <label class="layui-form-label">酒店级别:</label> <div class="layui-input-block"> <input type="radio" name="hotelType" title="顶级奢华" <#if data.hotelType??&&data.hotelType==1>checked</#if> value="1"> <input type="radio" name="hotelType" title="豪华尊贵" <#if data.hotelType??&&data.hotelType==2>checked</#if> value="2"> <input type="radio" name="hotelType" title="小型精品" <#if data.hotelType??&&data.hotelType==3>checked</#if> value="3"> </div> </div> </div> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">补充备注:</label> <div class="layui-input-block"> <textarea placeholder="请输入内容" class="layui-textarea" name="remark">${data.remark!''}</textarea> </div> </div> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">之前的处理记录:</label> <div class="layui-input-block"> <textarea placeholder="请输入内容" class="layui-textarea" readonly>${data.operationLog!''}</textarea> </div> </div> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">处理记录:</label> <div class="layui-input-block"> <textarea placeholder="请输入内容" class="layui-textarea" name="operationLog"></textarea> </div> <div class="layui-form-mid layui-word-aux">*填写处理定制旅游信息的记录</div> </div> <div class="layui-form-item"> <button type="button" class="layui-btn layui-btn-primary" id="attachment"><i class="layui-icon"></i>上传附件</button> <#if data.attachment??> <input type="hidden" value="${data.attachment!''}" name="attachment"/> <a class="layui-btn" href="${data.attachment!''}" target="_blank">查看附件</a> <#else> <input type="hidden" name="attachment"/> <a class="layui-btn" target="_blank" style="display: none">查看附件</a> </#if> </div> <div class="layui-form-item"> <div class="layui-input-block layui-form-save"> <button class="layui-btn" id="custom" type="button">立即保存</button> </div> </div> </form> </div> <@footer> <script> //入口 layui.use(['element','form','upload','laydate'], function() { var element = layui.element, form = layui.form, $ = layui.jquery ,upload = layui.upload, laydate = layui.laydate; //自定义验证规则 form.verify({ decimal: function(value){ if (value == "") { return '个人预算不能为空!'; } if(!/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(value)){ return '价格只能是整数或小数!'; } } }); //时间选择器 laydate.render({ elem: '#plan-time' ,type: 'datetime' }); // 上传附件 upload.render({ //允许上传的文件后缀 elem: '#attachment' ,url: '${ctx}upload' ,accept: 'file' //普通文件 ,size: 4096 //限制文件大小,单位 KB ,exts: 'doc|pdf|docx' //只允许上传压缩文件 ,before: function(obj){ var index = layer.msg('图片上传中...', { icon: 16, shade: 0.01, time: 0 }) },done: function(res){ layer.close(layer.msg());//关闭上传提示窗口 $("#attachment").parent().find("input[name = attachment]").attr("value",res.data); $("#attachment").parent().find("a").css("display","").attr("href",res.data); } }); $("#custom").on('click',function () { var formEm = $("#custom-form"); var mid = $("#mid").val(); var url = "${ctx}travel/custom/add"; if (mid != "") { url = "${ctx}travel/custom/edit"; } $.post(url,formEm.serialize(),function(result){ if(result.code == 0){ layer.msg("保存成功!"); var index = parent.layer.getFrameIndex(window.name); //获取窗口索引 parent.layer.close(index); parent.custom_tool.searchData(); return; } layer.msg(result.msg); }); }) }); </script> </@footer> <style type="text/css"> .layui-form-save{ text-align: center; } .layui-form-pane .layui-form-label{ width: 130px; } </style>
package gql import ( "errors" "github.com/graphql-go/graphql" "github.com/kyeeego/flowershop/domain" "github.com/kyeeego/flowershop/service" ) type Customer struct{ service *service.Service } func (c *Customer) initServices(serv *service.Service) { c.service = serv } func (c Customer) ResolveOne(p graphql.ResolveParams) (interface{}, error) { id, ok := p.Args["id"].(int) if !ok { return nil, errors.New("invalid id argument") } return c.service.Customer.GetById(uint(id)) } func (c Customer) ResolveCreate(p graphql.ResolveParams) (interface{}, error) { dto := domain.CreateCustomerDto{ Name: p.Args["name"].(string), Email: p.Args["email"].(string), } return c.service.Customer.Create(dto) } func (c Customer) ResolveUpdate(p graphql.ResolveParams) (interface{}, error) { dto := domain.UpdateCustomerDto{ ID: uint(p.Args["id"].(int)), Name: p.Args["name"].(string), Email: p.Args["email"].(string), } return c.service.Customer.Update(dto) } func (c Customer) ResolveDelete(p graphql.ResolveParams) (interface{}, error) { id, ok := p.Args["id"].(int) if !ok { return nil, errors.New("invalid id argument") } err := c.service.Customer.Delete(uint(id)) if err != nil { return false, err } return true, nil } func (c Customer) initQueries() graphql.Fields { return graphql.Fields{ "customer": &graphql.Field{ Type: domain.GqlCustomer, Args: graphql.FieldConfigArgument{ "id": &graphql.ArgumentConfig{Type: graphql.Int}, }, Resolve: c.ResolveOne, }, } } func (c Customer) initMutations() graphql.Fields { return graphql.Fields{ "createCustomer": &graphql.Field{ Type: domain.GqlCustomer, Args: graphql.FieldConfigArgument{ "name": {Type: graphql.String}, "email": {Type: graphql.String}, }, Resolve: c.ResolveCreate, }, "updateCustomer": &graphql.Field{ Type: domain.GqlCustomer, Args: graphql.FieldConfigArgument{ "id": {Type: graphql.Int}, "name": {Type: graphql.String}, "email": {Type: graphql.String}, }, Resolve: c.ResolveUpdate, }, "deleteCustomer": &graphql.Field{ Type: graphql.Boolean, Args: graphql.FieldConfigArgument{ "id": &graphql.ArgumentConfig{Type: graphql.Int}, }, Resolve: c.ResolveDelete, }, } }
// Use only core 1 for demo purposes #if CONFIG_FREERTOS_UNICORE static const BaseType_t app_cpu = 0; #else static const BaseType_t app_cpu = 1; #endif // Globals static int shared_var = 0; static TaskHandle_t task_1 = NULL; static TaskHandle_t task_2 = NULL; //***************************************************************************** // Tasks // Increment shared variable (the wrong way) void incTask(void *parameters) { int local_var; char taskname = *(char *)parameters; // Loop forever while (1) { // Roundabout way to do "shared_var++" randomly and poorly local_var = shared_var; local_var++; vTaskDelay(500 / portTICK_PERIOD_MS); // vTaskDelay(random(100, 5000) / portTICK_PERIOD_MS); shared_var = local_var; Serial.print(taskname); Serial.print(":"); // Serial.println(shared_var); // Print out new shared variable Serial.println(shared_var); TaskHandle_t h = xTaskGetCurrentTaskHandle(); if(shared_var == 50 && h == task_1) { vTaskDelay(5000 / portTICK_PERIOD_MS); } } } //***************************************************************************** // Main (runs as its own task with priority 1 on core 1) void setup() { // Hack to kinda get randomness randomSeed(analogRead(0)); // Configure Serial Serial.begin(115200); // Wait a moment to start (so we don't miss Serial output) vTaskDelay(1000 / portTICK_PERIOD_MS); Serial.println(); Serial.println("---FreeRTOS Race Condition Demo---"); char taskname1[] = "1"; char taskname2[] = "2"; // Start task 1 xTaskCreatePinnedToCore(incTask, "Increment Task 1", 1024, (void *)&taskname1, 1, &task_1, app_cpu); // Start task 2 xTaskCreatePinnedToCore(incTask, "Increment Task 2", 1024, (void *)&taskname2, 1, &task_2, app_cpu); // Delete "setup and loop" task vTaskDelete(NULL); } void loop() { // Execution should never get here }
<?php namespace app\entity; use Yii; /** * This is the model class for table "basket". * * @property int $id * @property int $user_id * @property int|null $price * @property string|null $timestamp * * @property BasketToTours[] $basketToTours * @property Users $user */ class Basket extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'basket'; } /** * {@inheritdoc} */ public function rules() { return [ [['user_id'], 'required'], [['user_id', 'price'], 'default', 'value' => null], [['user_id', 'price'], 'integer'], [['timestamp'], 'safe'], [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::class, 'targetAttribute' => ['user_id' => 'id']], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'user_id' => 'User ID', 'price' => 'Price', 'timestamp' => 'Timestamp', ]; } /** * Gets query for [[BasketToTours]]. * * @return \yii\db\ActiveQuery */ public function getBasketToTours() { return $this->hasMany(BasketToTours::class, ['basket_id' => 'id']); } public function getTours() { return $this->hasMany(Tours::class, ['id' => 'tour_id']) ->viaTable(BasketToTours::tableName(),['basket_id' => 'id']); } /** * Gets query for [[User]]. * * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(Users::class, ['id' => 'user_id']); } }
# coding: utf-8 # Copyright (C) 2021, [Breezedeus](https://github.com/breezedeus). # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # Credits: adapted from https://github.com/mindee/doctr import numpy as np import cv2 from math import floor from typing import List from statistics import median_low __all__ = ['estimate_orientation', 'extract_crops', 'extract_rcrops', 'rotate_page', 'get_bitmap_angle'] def extract_crops(img: np.ndarray, boxes: np.ndarray) -> List[np.ndarray]: """Created cropped images from list of bounding boxes Args: img: input image boxes: bounding boxes of shape (N, 4) where N is the number of boxes, and the relative coordinates (xmin, ymin, xmax, ymax) Returns: list of cropped images """ if boxes.shape[0] == 0: return [] if boxes.shape[1] != 4: raise AssertionError("boxes are expected to be relative and in order (xmin, ymin, xmax, ymax)") # Project relative coordinates _boxes = boxes.copy() if 'float' in str(_boxes.dtype) and _boxes.max() <= 1.0: _boxes[:, [0, 2]] *= img.shape[1] _boxes[:, [1, 3]] *= img.shape[0] _boxes = _boxes.round().astype(int) # Add last index _boxes[2:] += 1 _boxes[:2] -= 1 _boxes[_boxes < 0] = 0 return [img[box[1]: box[3], box[0]: box[2]] for box in _boxes] def extract_rcrops(img: np.ndarray, boxes: np.ndarray, dtype=np.float32) -> List[np.ndarray]: """Created cropped images from list of rotated bounding boxes Args: img: input image boxes: bounding boxes of shape (N, 5) where N is the number of boxes, and the relative coordinates (x, y, w, h, alpha) Returns: list of cropped images """ if boxes.shape[0] == 0: return [] if boxes.shape[1] != 5: raise AssertionError("boxes are expected to be relative and in order (x, y, w, h, alpha)") # Project relative coordinates _boxes = boxes.copy() if 'float' in str(_boxes.dtype) and _boxes[:, 0:4].max() <= 1.0: _boxes[:, [0, 2]] *= img.shape[1] _boxes[:, [1, 3]] *= img.shape[0] crops = [] for box in _boxes: x, y, w, h, alpha = box.astype(dtype) vertical_box = False if (abs(alpha) < 3 and w * 1.3 < h) or (90 - abs(alpha) < 3 and w > h * 1.3): vertical_box = True process_func = _process_vertical_box if vertical_box else _process_horizontal_box crop = process_func(img, box, dtype) crops.append(crop) return crops def _process_horizontal_box(img, box, dtype): x, y, w, h, alpha = box.astype(dtype) if alpha > 80 and w < h: # for opencv-python >= 4.5.2 alpha -= 90 w, h = h, w clockwise = False if w > h: clockwise = True if clockwise: # 1 -------- 2 # | | # * -------- 3 dst_pts = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1]], dtype=dtype) else: # * -------- 1 # | | # 3 -------- 2 # dst_pts = np.array([[h - 1, 0], [h - 1, w - 1], [0, w - 1]], dtype=dtype) # 2 -------- 3 # | | # 1 -------- * dst_pts = np.array([[0, w - 1], [0, 0], [h - 1, 0]], dtype=dtype) # The transformation matrix src_pts = cv2.boxPoints(((x, y), (w, h), alpha)) M = cv2.getAffineTransform(src_pts[1:, :], dst_pts) # Warp the rotated rectangle if clockwise: crop = cv2.warpAffine(img, M, (int(w), int(h))) else: crop = cv2.warpAffine(img, M, (int(h), int(w))) return crop def _process_vertical_box(img, box, dtype): x, y, w, h, alpha = box.astype(dtype) clockwise = False if w > h: clockwise = True if clockwise: # 2 ------- 3 # | | # | | # | | # | | # 1 ------- * dst_pts = np.array([[0, w - 1], [0, 0], [h - 1, 0]], dtype=dtype) # dst_pts = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1]], dtype=dtype) else: # 1 ------- 2 # | | # | | # | | # | | # * ------- 3 dst_pts = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1]], dtype=dtype) # The transformation matrix src_pts = cv2.boxPoints(((x, y), (w, h), alpha)) M = cv2.getAffineTransform(src_pts[1:, :], dst_pts) # Warp the rotated rectangle if clockwise: crop = cv2.warpAffine(img, M, (int(h), int(w))) else: crop = cv2.warpAffine(img, M, (int(w), int(h))) return crop def rotate_page( image: np.ndarray, angle: float = 0., min_angle: float = 1. ) -> np.ndarray: """Rotate an image counterclockwise by an ange alpha (negative angle to go clockwise). Args: image: numpy tensor to rotate angle: rotation angle in degrees, between -90 and +90 min_angle: min. angle in degrees to rotate a page Returns: Rotated array or tf.Tensor, padded by 0 by default. """ if abs(angle) < min_angle or abs(angle) > 90 - min_angle: return image height, width = image.shape[:2] center = (height / 2, width / 2) rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0) return cv2.warpAffine(image, rot_mat, (width, height)) def get_max_width_length_ratio(contour: np.ndarray) -> float: """ Get the maximum shape ratio of a contour. Args: contour: the contour from cv2.findContour Returns: the maximum shape ratio """ _, (w, h), _ = cv2.minAreaRect(contour) return max(w / h, h / w) def estimate_orientation(img: np.ndarray, n_ct: int = 50, ratio_threshold_for_lines: float = 5) -> float: """Estimate the angle of the general document orientation based on the lines of the document and the assumption that they should be horizontal. Args: img: the img to analyze n_ct: the number of contours used for the orientation estimation ratio_threshold_for_lines: this is the ratio w/h used to discriminates lines Returns: the angle of the general document orientation """ gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray_img = cv2.medianBlur(gray_img, 5) thresh = cv2.threshold(gray_img, thresh=0, maxval=255, type=cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # try to merge words in lines (h, w) = img.shape[:2] k_x = max(1, (floor(w / 100))) k_y = max(1, (floor(h / 100))) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (k_x, k_y)) thresh = cv2.dilate(thresh, kernel, iterations=1) # extract contours contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Sort contours contours = sorted(contours, key=get_max_width_length_ratio, reverse=True) angles = [] for contour in contours[:n_ct]: _, (w, h), angle = cv2.minAreaRect(contour) if w / h > ratio_threshold_for_lines: # select only contours with ratio like lines angles.append(angle) elif w / h < 1 / ratio_threshold_for_lines: # if lines are vertical, substract 90 degree angles.append(angle - 90) return -median_low(angles) def get_bitmap_angle(bitmap: np.ndarray, n_ct: int = 20, std_max: float = 3.) -> float: """From a binarized segmentation map, find contours and fit min area rectangles to determine page angle Args: bitmap: binarized segmentation map n_ct: number of contours to use to fit page angle std_max: maximum deviation of the angle distribution to consider the mean angle reliable Returns: The angle of the page """ # Find all contours on binarized seg map contours, _ = cv2.findContours(bitmap.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # Sort contours contours = sorted(contours, key=cv2.contourArea, reverse=True) # Find largest contours and fit angles # Track heights and widths to find aspect ratio (determine is rotation is clockwise) angles, heights, widths = [], [], [] for ct in contours[:n_ct]: _, (w, h), alpha = cv2.minAreaRect(ct) widths.append(w) heights.append(h) angles.append(alpha) if np.std(angles) > std_max: # Edge case with angles of both 0 and 90°, or multi_oriented docs angle = 0. else: angle = -np.mean(angles) # Determine rotation direction (clockwise/counterclockwise) # Angle coverage: [-90°, +90°], half of the quadrant if np.sum(widths) < np.sum(heights): # CounterClockwise angle = 90 + angle return angle
package changes_tui import ( "github.com/charmbracelet/bubbles/help" bubbleKey "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/spinner" "github.com/charmbracelet/bubbles/viewport" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/plandex/plandex/shared" ) type changesUIModel struct { help help.Model keymap keymap selectedFileIndex int selectedReplacementIndex int selectedViewport int currentPlan *shared.CurrentPlanState changeOldViewport viewport.Model changeNewViewport viewport.Model fileViewport viewport.Model selectionInfo *selectionInfo ready bool width int height int shouldApplyAll bool shouldRejectAll bool didCopy bool isRejectingFile bool isConfirmingRejectFile bool rejectFileErr *shared.ApiError justRejectedFile bool spinner spinner.Model } type keymap = struct { up, down, left, right, scrollUp, scrollDown, pageUp, pageDown, start, end, switchView, reject, copy, applyAll, yes, no, quit bubbleKey.Binding } func (m changesUIModel) Init() tea.Cmd { return nil } func initialModel(currentPlan *shared.CurrentPlanState) *changesUIModel { s := spinner.New() s.Spinner = spinner.Points s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205")) initialState := changesUIModel{ currentPlan: currentPlan, selectedFileIndex: 0, selectedReplacementIndex: 0, help: help.New(), spinner: s, keymap: keymap{ up: bubbleKey.NewBinding( bubbleKey.WithKeys("up"), bubbleKey.WithHelp("up", "prev change"), ), down: bubbleKey.NewBinding( bubbleKey.WithKeys("down"), bubbleKey.WithHelp("down", "next change"), ), left: bubbleKey.NewBinding( bubbleKey.WithKeys("left"), bubbleKey.WithHelp("left", "prev file"), ), right: bubbleKey.NewBinding( bubbleKey.WithKeys("right"), bubbleKey.WithHelp("right", "next file"), ), scrollDown: bubbleKey.NewBinding( bubbleKey.WithKeys("j"), bubbleKey.WithHelp("j", "scroll down"), ), scrollUp: bubbleKey.NewBinding( bubbleKey.WithKeys("k"), bubbleKey.WithHelp("k", "scroll up"), ), pageDown: bubbleKey.NewBinding( bubbleKey.WithKeys("d", "pageDown"), bubbleKey.WithHelp("d", "page down"), ), pageUp: bubbleKey.NewBinding( bubbleKey.WithKeys("u", "pageUp"), bubbleKey.WithHelp("u", "page up"), ), start: bubbleKey.NewBinding( bubbleKey.WithKeys("g", "home"), bubbleKey.WithHelp("g", "start"), ), end: bubbleKey.NewBinding( bubbleKey.WithKeys("G", "end"), bubbleKey.WithHelp("G", "end"), ), switchView: bubbleKey.NewBinding( bubbleKey.WithKeys("tab"), bubbleKey.WithHelp("tab", "switch view"), ), reject: bubbleKey.NewBinding( bubbleKey.WithKeys("r"), bubbleKey.WithHelp("r", "reject file"), ), copy: bubbleKey.NewBinding( bubbleKey.WithKeys("c"), bubbleKey.WithHelp("c", "copy change"), ), applyAll: bubbleKey.NewBinding( bubbleKey.WithKeys("ctrl+a"), bubbleKey.WithHelp("ctrl+a", "apply all changes"), ), yes: bubbleKey.NewBinding( bubbleKey.WithKeys("y"), bubbleKey.WithHelp("y", "yes"), ), no: bubbleKey.NewBinding( bubbleKey.WithKeys("n"), bubbleKey.WithHelp("n", "no"), ), quit: bubbleKey.NewBinding( bubbleKey.WithKeys("q", "ctrl+c"), bubbleKey.WithHelp("q", "quit"), ), }, } return &initialState }
import React from "react"; import { useTranslatedConstants } from "../constants"; import RadioGroup from "./RadioGroup"; export const boolToYesNoUnknown = ( value: boolean | null | undefined ): YesNoUnknown | undefined => { if (value) { return "YES"; } if (value === false) { return "NO"; } if (value === null) { return "UNKNOWN"; } return undefined; }; export const yesNoUnknownToBool = ( value: YesNoUnknown ): boolean | null | undefined => { if (value === "YES") { return true; } if (value === "NO") { return false; } if (value === "UNKNOWN") { return null; } return undefined; }; interface Props { name: string; legend: React.ReactNode; value: YesNoUnknown | undefined; onChange: (value: YesNoUnknown) => void; hintText?: string; onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void; validationStatus?: "error" | "success"; errorMessage?: React.ReactNode; required?: boolean; } const YesNoRadioGroup: React.FC<Props> = ({ name, legend, value, hintText, onChange, onBlur, validationStatus, errorMessage, required, }) => { const { YES_NO_UNKNOWN_VALUES: values } = useTranslatedConstants(); return ( <RadioGroup legend={legend} hintText={hintText} name={name} buttons={values} selectedRadio={value} onChange={onChange} onBlur={onBlur} validationStatus={validationStatus} errorMessage={errorMessage} required={required} /> ); }; export default YesNoRadioGroup;
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; import "forge-std/console.sol"; import "forge-std/Test.sol"; import "erc721a/contracts/ERC721A.sol"; import "../../contracts/AllowList.sol"; contract AllowListTest is Test { AllowListMock public mock; address private signer = 0x74049685c0227b5943926f2F742a4bc2Cf3198D6; address private minter = 0xc4822807d3a45905B13865376C08b9DC3D9439E8; bytes private signature = hex"7382456e4433452e8320987acdb91678772fa864fb51525c4ea261d3fc729ea913b4884c08abec424c227bca8ecbe7318cc4041f5f03264830f09022e6cc9ce41b"; uint256 nonce = 1; function setUp() public { vm.deal(minter, 10 ether); // AllowList.ListConfig[] memory lists = new AllowList.ListConfig[](1); skip(60); mock = new AllowListMock( AllowList.ListConfig({ signer: signer, mintPrice: 1 ether, startTime: 60, endTime: 100, maxPerWallet: 1 }) ); } function testConstructor() public { assertEq(mock.listExists(address(0x0)), false); assertEq(mock.listExists(signer), true); } function testMint() public { assertEq(mock.allowListTotal(signer), 0); assertEq(mock.canUseSignature(minter, 1, signature, nonce), true); mock.mint{value: 1 ether}(minter, 1, signature, nonce); assertEq(mock.allowListTotal(signer), 1); } function testAddAllowList() public { address _signer = 0x9999999999999999999999999999999999999999; assertEq(mock.listExists(_signer), false); mock.addAllowList( AllowList.ListConfig({ signer: _signer, mintPrice: 0, startTime: 0, endTime: 0, maxPerWallet: 0 }) ); assertEq(mock.listExists(_signer), true); } function testRemoveAllowList() public { assertEq(mock.listExists(signer), true); assertEq(mock.canUseSignature(minter, 1, signature, nonce), true); mock.removeAllowList(signer); assertEq(mock.listExists(signer), false); assertEq(mock.canUseSignature(minter, 1, signature, nonce), false); } function testWrongMinterAddress() public { address fake_addy = address(0x1234567890123456789012345678901234567890); vm.prank(fake_addy); assertEq(mock.canUseSignature(fake_addy, 1, signature, nonce), false); } function testWrongSignature() public { bytes memory fake_sig = hex"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; assertEq(mock.canUseSignature(minter, 1, fake_sig, nonce), false); } function testMultipleSignatureUse() public { assertEq(mock.canUseSignature(minter, 1, signature, nonce), true); mock.mint{value: 1 ether}(minter, 1, signature, nonce); vm.prank(minter); assertEq(mock.canUseSignature(minter, 1, signature, nonce), false); } function testMaxPerWallet() public { // Randomly generated via `yarn testdata` address _signer = 0x27Be5341D40734E38358012aF8cfF959b8692a37; address _minter = 0x9f8b9509A5Cc8C30bE0E342Dc04E90254a0cf71C; bytes memory _sig = hex"83e50971b80ea024dd7b8f509f60fdc660438dd5b96126bdcbe0ef7f1a464f7d0f6265f57855d0d19e0a6d139c350b4f2811f9c6071bfa4373765ab7f765ceef1c"; uint256 _n = 2; mock.addAllowList( AllowList.ListConfig({ signer: _signer, mintPrice: 1 ether, startTime: 0, endTime: 0, maxPerWallet: 2 }) ); assertEq(mock.canUseSignature(_minter, 3, _sig, _n), false); assertEq(mock.canUseSignature(_minter, 2, _sig, _n), true); assertEq(mock.canUseSignature(_minter, 1, _sig, _n), true); } function testMaxPerWalletUnlimited() public { address _signer = 0x6c61e3E294237f02845dF0e94885f03e4dee671B; address _minter = 0xF5ba38c54e01e6688b80d43385114Db82644c3D7; bytes memory _sig = hex"e390cdefb6a5e09a6999f5ea83c15ab28bc8dc83dc1ff39a9585c275df2d86117bd06062f5d348c01ba832e556d3005783b1cd3d5a1cc1e5c65ddb47fcb04f371c"; uint256 _nonce = 0; // Test 0 = unlimited mock.addAllowList( AllowList.ListConfig({ signer: _signer, mintPrice: 1 ether, startTime: 60, endTime: 100, maxPerWallet: 0 }) ); // (bool success, string memory reason) = mock.validateSignature( // _minter, // 100, // 0, // _sig, // _nonce // ); assertEq( // Generated minter with 0 nonce signature mock.canUseSignature(_minter, 100, _sig, _nonce), true ); } function testStartTime() public { rewind(60); assertEq(mock.canUseSignature(minter, 1, signature, nonce), false); skip(60); assertEq(mock.canUseSignature(minter, 1, signature, nonce), true); } function testEndTime() public { assertEq(mock.canUseSignature(minter, 1, signature, nonce), true); skip(40); assertEq(mock.canUseSignature(minter, 1, signature, nonce), false); mock.addAllowList( AllowList.ListConfig({ signer: signer, mintPrice: 1 ether, startTime: 60, endTime: 0, maxPerWallet: 1 }) ); assertEq(mock.canUseSignature(minter, 1, signature, nonce), true); } function testPayment() public { vm.expectRevert("Insufficient Payment"); mock.mint{value: 0.2 ether}(minter, 1, signature, nonce); assertEq(mock.allowListTotal(signer), 0); mock.mint{value: 1 ether}(minter, 1, signature, nonce); assertEq(mock.allowListTotal(signer), 1); } } contract AllowListMock is ERC721A, AllowList { constructor(AllowList.ListConfig memory list) ERC721A("Test", "TEST") { _addAllowList( list.signer, list.mintPrice, list.startTime, list.endTime, list.maxPerWallet ); } function balanceOf(address _owner) public view override(ERC721A, AllowList) returns (uint256) { return ERC721A.balanceOf(_owner); } // function canUseSignature( // address to, // bytes calldata signature, // uint256 nonce, // uint256 count // ) external view returns (bool) { // (bool canMint, ) = _validateSignature(to, count, 0, signature, nonce); // return canMint; // } function validateSignature( address _address, uint256 _count, uint256 _minted, bytes calldata _signature, uint256 _nonce ) external view returns (bool, string memory) { return _validateSignature(_address, _count, _minted, _signature, _nonce); } function mint( address to, uint256 count, bytes calldata signature, uint256 nonce ) external payable useSignature(to, count, signature, nonce) { _mint(to, count); } function addAllowList(AllowList.ListConfig memory _list) external { _addAllowList( _list.signer, _list.mintPrice, _list.startTime, _list.endTime, _list.maxPerWallet ); } function removeAllowList(address signer) external { _removeAllowList(signer); } function listExists(address signer) external view returns (bool) { return allowLists[signer].exists; } }
import React, { useState, useReducer, useContext } from "react"; type Todo = { text: string; done: boolean; }; const initialState = [ { text: "learn html", done: true }, { text: "learn css", done: true }, { text: "learn js", done: false }, { text: "learn react", done: false } ]; // same partern as redux function todosReducer(state = initialState, action: { type: string; payload: Todo }) { switch (action.type) { case "toggle": return state.map(t => { // TODO find best match... //if (t.text === action.payload.text) { if (t === action.payload) { return { ...t, done: !t.done }; } return t; }); case "add": return [...state, action.payload]; default: return state; // no new object //throw new Error(); } } // TODO create test for: //const state = todosReducer([], { // type: 'add', payload: {text: 'reducer', done: false} //}) //expect(state).toBeExact([{text: 'reducer', done: false}]) type Props = { todos: Todo[]; toggleTodo: (todo: Todo) => void; }; const TodosView = ({ todos, toggleTodo }: Props) => ( <ul> {todos.map((t, i) => ( <li key={i} style={{ textDecoration: t.done ? "line-through" : "none" }} onClick={() => { toggleTodo(t); }} > {t.text} </li> ))} </ul> ); const TodosContext = React.createContext<{ todos: Todo[]; toggleTodo: (todo: Todo) => void; addTodo(todo: Todo): void; } | null>(null); const Todos = () => { const { todos, toggleTodo } = useContext(TodosContext)!; return <TodosView todos={todos} toggleTodo={toggleTodo} />; }; const TodosInfo = () => { const { todos, addTodo } = useContext(TodosContext)!; const leftCount = todos.filter(t => !t.done).length; return <TodosInfoView count={leftCount} addTodo={addTodo} />; }; function TodosInfoView({ count, addTodo }: { count: number; addTodo(todo: Todo): void }) { const [text, setText] = useState(""); return ( <form onSubmit={e => { e.preventDefault(); addTodo({ text, done: false }); setText(""); }} > <div> You have{" "} <strong className={"App-link"} style={count ? {} : { color: "green" }}> {count} </strong>{" "} tasks left. </div> <input type="text" value={text} required onChange={e => setText(e.target.value)} placeholder="Add new item" /> <button type={"submit"}>Add</button> </form> ); } export const TodosApp = () => { const [todos, dispatch] = useReducer(todosReducer, initialState); const toggleTodo = (todo: Todo) => { dispatch({ type: "toggle", payload: todo }); }; const addTodo = (todo: Todo) => { dispatch({ type: "add", payload: todo }); }; return ( <div> <TodosContext.Provider value={{ todos, toggleTodo, addTodo }}> <Todos /> <hr /> <WrappTodosInfo /> </TodosContext.Provider> <p className="footnote">* useReducer with Context.Provider</p> </div> ); }; // TODO remove - this is for example to show wrapping in many levels function WrappTodosInfo() { return <TodosInfo />; }
<h1>Course Outline</h1> <p><b>Pre-work:</b> Python</p> <b>Unit 1:</b> Django <ul> <li>Install and setup Django</li> <li>Views (methods)</li> <li>Template</li> <li>Request and response objects</li> <li>Cookies Handling</li> <li>Forms (simple)</li> </ul> <b>Unit 2:</b> Basic front-end <ul> <li>Html</li> <li>CSS</li> <li>Javascript</li> <li>Bootstrap</li> <li>AJAX</li> </ul> <b>Unit 3:</b> Database <ul> <li>Relation Database: structure, tables, columns, keys (primary, foreign), indexes (unique or for performance)</li> <li>DB design</li> <li>SQL syntax</li> <li>SQLite</li> <li>NOSQL (JSON column)</li> <li>Django models</li> </ul> <b>Unit 4:</b> <ul> <li>Class-based views</li> <li>Using API (client)</li> <li>Roles in a team (project manager, analyst, back-end, front-end, engineer, UX/graphic designer, developers)</li> <li>Design Document</li> </ul> <b>Unit 5:</b> Advanced Django <ul> <li>REST API</li> <li>Create API server (with Django)</li> <li>Middleware</li> <li>Advanced forms</li> </ul> <b>Unit 6:</b> Async <ul> <li>Asyncio</li> <li>Async views</li> <li>Django channels</li> </ul> <b>Unit 7:</b> Front-end JS framework <ul> <li>VueJS</li> <li>Embedded to HTML (call the library from the HTML code and write VueJS code directly in the HTML page)</li> <li>Compile a VueJS project into a js file (and use webpack to see live changes while developing along Django)</li> <li>Syntax, computed properties, conditional and list rendering, event handling, watchers</li> <li>Use API (API server built on the Django side)</li> </ul> <b>Unit 8:</b> Reports and Plots <ul> <li>Matplotlib</li> <li>Interactive JS plot</li> <li>LaTeX</li> </ul>
import React, { useState, useEffect, ReactNode } from "react"; interface FadeInWrapperProps { children: ReactNode; duration?: number; delay?: number; } const FadeInWrapper: React.FC<FadeInWrapperProps> = ({ children, duration = 400, delay = 50, }) => { const [isVisible, setIsVisible] = useState(false); useEffect(() => { const timeout = setTimeout(() => { setIsVisible(true); }, delay); return () => clearTimeout(timeout); }, [delay]); return ( <div className="flex h-full" style={{ opacity: isVisible ? 1 : 0, transition: `opacity ${duration}ms`, }} > {children} </div> ); }; export default FadeInWrapper;
package Day3; public class Test1_1_2 { // 강사님이 보내주신 코드 public static void main(String[] args) { // 객체 사전적인 정의로 실제 존재하는 것을 말한다 // 클래스 템플릿 // 다형성 // 상속 // 캡슐화 // 객체지향 장점 => 코드 재사용성이 좋다 (모듈성), 유지보수 용이 // 단점 =>복잡해진다 // Person newFace = new Person(); // newFace.name = "유성호"; // newFace.age = 29; // Person oldFace = new Person(); // oldFace.name = "현수정"; // oldFace.age = 21; String[] names = {"유성호", "현수정"}; int[] ages = {29, 21}; Person[] persons = new Person[2]; for(int i=0; i < persons.length; i++) { Person person = new Person(names[0], ages[i]); // person.name = names[i]; // person.age = ages[i]; persons[i] = person; // if(i==4) {break;} } System.out.println(persons[0].equals(persons[1])); // foreach for(Person person:persons) { System.out.println(person.age + " "+ person.name); System.out.println(person); System.out.println(person.sound()); } Animal1 cat = new Animal1("고양이"); System.out.println(cat.sound()); } } class Person extends Sound{ // field String name; int age; // 생성 할떄 쓰인다 : 생성자 constructor // method // overload 다형성 public Person(String name, int age) { this.name = name; this.age = age; } public Person(int age) { this.age = age; } // method @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public int getAge(){ return age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public boolean equals(Person obj) { if (this == obj) return true; if (obj == null) return false; if (age != obj.age) return false; if (name == null) { if (obj.name != null) return false; } else if (!name.equals(obj.name)) return false; return true; } @Override public String sound() {return "안녕하세요";} } class Animal1 extends Sound{ String name; public Animal1(String name) { this.name = name; } @Override public String sound() { return name +" "+ name; } } class Sound { public String sound(){return "sound";} } //abstract Sound { //abstract 추상 클래스. 상속만 받을 수 있음. 이거 자체로는 쓸 수 없다.(독집적으로 사용 불가능.) // abstract public String sound(); // public String sound2(){ // return "sound2"; // } // }
import axios from "axios"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useNotificationDispatch } from "../NotificationContext"; const AnecdoteForm = () => { const notificationDispatch = useNotificationDispatch(); const queryClient = useQueryClient(); const { mutate: anecdoteMutation } = useMutation({ mutationFn: (anecdote) => axios .post("http://localhost:3001/anecdotes", anecdote) .then((response) => response.data), onSuccess: () => { queryClient.invalidateQueries(["anecdotes"]); }, onError: (error) => { notificationDispatch({ type: "NEW_NOTIFICATION", payload: error.response.data.error, }); setTimeout( () => notificationDispatch({ type: "CLEAR_NOTIFICATION" }), 5000 ); }, }); const onCreate = (event) => { event.preventDefault(); const content = event.target.anecdote.value; event.target.anecdote.value = ""; anecdoteMutation({ content: content, votes: 0 }); notificationDispatch({ type: "NEW_NOTIFICATION", payload: `anecdote '${content}' created`, }); setTimeout( () => notificationDispatch({ type: "CLEAR_NOTIFICATION" }), 5000 ); }; return ( <div> <h3>create new</h3> <form onSubmit={onCreate}> <input name="anecdote" /> <button type="submit">create</button> </form> </div> ); }; export default AnecdoteForm;
# Meals App Architecture and Documentation ## Introduction This document provides an overview of the app's architecture, user stories, specifications, and file/folder structure based on the provided code structure. The app is designed to help users explore and manage meal categories, view meal details, and apply filters to customize their meal preferences. ## New Features ### Add Meal The app now allows users to add a new meal with details such as title, image, ingredients, steps, duration, complexity, affordability, and dietary preferences. Users can save the meal and have it displayed in the list of available meals. ## App Architecture ### User Interface The app follows a typical Flutter application structure, with screens and widgets: 1. **Screens**: Represent various user interface screens of the app. - `CategoriesScreen`: Displays available meal categories. - `FiltersScreen`: Allows users to set meal filters. - `MealsScreen`: Lists meals based on selected categories. - `MealDetailsScreen`: Shows details of a specific meal. - `AddNewMeal`: Allows users to add a new meal. - `TabsScreen`: Implements the bottom navigation tabs for Categories and Favorites. 2. **Widgets**: Reusable UI components used throughout the app. - `CategoryGridItem`: Represents a category grid item. - `MainDrawer`: Implements the main navigation drawer. - `MealItem`: Displays individual meal items. - `MealItemTrait`: A small widget for displaying meal traits (e.g., duration, complexity). ### Data and Models Data and models are used to manage and represent the app's content: 1. **Data**: - `dummy_data.dart`: Contains sample data for meal categories and meals. 2. **Models**: - `Category`: Represents a meal category with an ID, title, and color. - `Meal`: Represents a meal with details such as ID, title, ingredients, steps, and more. ### State Management State management is implemented using Riverpod, a Flutter state management package: 1. **Providers**: - `FavoriteMealsNotifier`: Manages the user's favorite meals. - `FiltersNotifier`: Handles user-selected filters (gluten-free, lactose-free, vegetarian, vegan). - `mealsProvider`: Provides the list of available meals. - `filteredMealsProvider`: Filters meals based on user-selected filters. ### Main Entry Point The app's main entry point is defined in `main.dart`. It sets up the app's theme and initializes the `TabsScreen` as the initial view. ## Meals App User Stories 1. **Add Meal** - As a user, I want to add a new meal with details such as title, image, ingredients, steps, duration, complexity, affordability, and dietary preferences. - I want to save the meal and have it displayed in the list of available meals. 2. **View Meals** - As a user, I want to view a list of all available meals. - I want to see each meal's title, image, and basic information. 3. **View Meal Details** - As a user, I want to view the details of a specific meal when I select it from the list. - I want to see information such as ingredients, steps, duration, complexity, affordability, and dietary preferences. - I also want to have the option to add or remove the meal from my favorites. 4. **Filter Meals** - As a user, I want to filter available meals based on dietary preferences, such as gluten-free, lactose-free, vegetarian, and vegan. - I want the filtered meals to update based on my selections. 5. **View Favorites** - As a user, I want to view a list of my favorite meals. - I want to see each meal's title, image, and basic information. 6. **Visualize Meal Categories** - As a user, I want to see a visual representation (e.g., a grid of categories) of available meal categories. - I want to select a category and see a list of meals that belong to that category. 7. **Adjust Filters** - As a user, I want to adjust my dietary preference filters. - I want to customize my filters for gluten-free, lactose-free, vegetarian, and vegan meals. ## Specifications - **Categories**: The app loads predefined meal categories and displays them in a grid. - **Meals**: When a category is selected, the app displays a list of meals within that category. - **Meal Details**: Users can click on a meal to view its details, including ingredients and steps. - **Filters**: Users can set filters for dietary preferences to customize meal lists. - **New Meal**: Users can add a new meal with details such as title, image, ingredients, steps, duration, complexity, affordability, and dietary preferences. - **Favorites**: Users can mark meals as favorites for easy access. - **Navigation**: Users can navigate between Categories, Add New Meal and Favorites using a bottom navigation bar. - **Theme**: The app uses a custom theme with a dark color scheme and custom fonts. ## File and Folder Structure The app's files and folders are organized as follows: - lib/ (Root Directory) - models/ (Folder for Data Models) - category.dart (Definition of the `Category` data model) - meal.dart (Definition of the `Meal` data model) - providers/ (Folder for State Management) - favorites_provider.dart (Management of favorite meals) - filters_provider.dart (Management of dietary preference filters) - meals_provider.dart (Provides a list of meals) - screens/ (Folder for App Screens) - categories.dart (Categories Screen) - filters.dart (Filters Screen) - meal_details.dart (Meal Details Screen) - meals.dart (Meals Screen) - new_meal.dart (Add New Meal Screen) - tabs.dart (Tabs Screen, entry point) - widgets/ (Folder for Custom Widgets) - category_grid_item.dart (Definition of the `CategoryGridItem` widget) - main_drawer.dart (Definition of the `MainDrawer` widget) - meal_item.dart (Definition of the `MealItem` widget) - meal_item_trait.dart (Definition of the `MealItemTrait` widget) - main.dart (Entry point of the application) This organized structure ensures maintainability and modularity, making it easier to expand and improve the app's functionality in the future. ## Class Diagram The following class diagram shows the app's class structure: ```mermaid classDiagram class App App : +build() Widget StatelessWidget <|-- App class Category Category : +id String Category : +title String Category : +color Color Category o-- Color class Meal Meal : +id String Meal : +categories List~String~ Meal : +title String Meal : +imageUrl String Meal : +ingredients List~String~ Meal : +steps List~String~ Meal : +duration int Meal : +complexity Complexity Meal o-- Complexity Meal : +affordability Affordability Meal o-- Affordability Meal : +isGlutenFree bool Meal : +isLactoseFree bool Meal : +isVegan bool Meal : +isVegetarian bool class Complexity <<enumeration>> Complexity Complexity : +index int Complexity : +values$ List~Complexity~ Complexity : +simple$ Complexity Complexity o-- Complexity Complexity : +challenging$ Complexity Complexity o-- Complexity Complexity : +hard$ Complexity Complexity o-- Complexity Enum <|.. Complexity class Affordability <<enumeration>> Affordability Affordability : +index int Affordability : +values$ List~Affordability~ Affordability : +affordable$ Affordability Affordability o-- Affordability Affordability : +pricey$ Affordability Affordability o-- Affordability Affordability : +luxurious$ Affordability Affordability o-- Affordability Enum <|.. Affordability class FavoriteMealsNotifier FavoriteMealsNotifier : +toggleMealFavoriteStatus() bool StateNotifier <|-- FavoriteMealsNotifier class FiltersNotifier FiltersNotifier : +setFilters() void FiltersNotifier : +setFilter() void StateNotifier <|-- FiltersNotifier class Filter <<enumeration>> Filter Filter : +index int Filter : +values$ List~Filter~ Filter : +glutenFree$ Filter Filter o-- Filter Filter : +lactoseFree$ Filter Filter o-- Filter Filter : +vegetarian$ Filter Filter o-- Filter Filter : +vegan$ Filter Filter o-- Filter Enum <|.. Filter class CategoriesScreen CategoriesScreen : +availableMeals List~Meal~ CategoriesScreen : +createState() State<CategoriesScreen> StatefulWidget <|-- CategoriesScreen class _CategoriesScreenState _CategoriesScreenState : -_animationController AnimationController _CategoriesScreenState o-- AnimationController _CategoriesScreenState : +initState() void _CategoriesScreenState : +dispose() void _CategoriesScreenState : -_selectCategory() void _CategoriesScreenState : +build() Widget State <|-- _CategoriesScreenState SingleTickerProviderStateMixin <|-- _CategoriesScreenState class FiltersScreen FiltersScreen : +build() Widget ConsumerWidget <|-- FiltersScreen class MealsScreen MealsScreen : +title String? MealsScreen : +meals List~Meal~ MealsScreen : +selectMeal() void MealsScreen : +build() Widget StatelessWidget <|-- MealsScreen class MealDetailsScreen MealDetailsScreen : +meal Meal MealDetailsScreen o-- Meal MealDetailsScreen : +build() Widget ConsumerWidget <|-- MealDetailsScreen class AddNewMeal AddNewMeal : +createState() State<AddNewMeal> StatefulWidget <|-- AddNewMeal class _AddNewMealState _AddNewMealState : +uuid Uuid _AddNewMealState o-- Uuid _AddNewMealState : +titleController TextEditingController _AddNewMealState o-- TextEditingController _AddNewMealState : +selectedCategories List~String~ _AddNewMealState : +imageUrlController TextEditingController _AddNewMealState o-- TextEditingController _AddNewMealState : +durationController TextEditingController _AddNewMealState o-- TextEditingController _AddNewMealState : +selectedAffordability String _AddNewMealState : +selectedComplexity String _AddNewMealState : +ingredients List~String~ _AddNewMealState : +steps List~String~ _AddNewMealState : +isGlutenFree bool _AddNewMealState : +isVegan bool _AddNewMealState : +isVegetarian bool _AddNewMealState : +isLactoseFree bool _AddNewMealState : +newIngredient String _AddNewMealState : +newStep String _AddNewMealState : -_addIngredient() void _AddNewMealState : -_addStep() void _AddNewMealState : -_addNewMeal() void _AddNewMealState : +build() Widget State <|-- _AddNewMealState class TabsScreen TabsScreen : +createState() ConsumerState<TabsScreen> ConsumerStatefulWidget <|-- TabsScreen class _TabsScreenState _TabsScreenState : -_selectedPageIndex int _TabsScreenState : -_selectPage() void _TabsScreenState : -_setScreen() void _TabsScreenState : +build() Widget ConsumerState <|-- _TabsScreenState class CategoryGridItem CategoryGridItem : +category Category CategoryGridItem o-- Category CategoryGridItem : +onSelectCategory void Function CategoryGridItem o-- void Function CategoryGridItem : +build() Widget StatelessWidget <|-- CategoryGridItem class MainDrawer MainDrawer : +onSelectScreen void FunctionString MainDrawer o-- void FunctionString MainDrawer : +build() Widget StatelessWidget <|-- MainDrawer class MealItem MealItem : +meal Meal MealItem o-- Meal MealItem : +onSelectMeal void FunctionMeal MealItem o-- void FunctionMeal MealItem : +complexityText String MealItem : +affordabilityText String MealItem : +build() Widget StatelessWidget <|-- MealItem class MealItemTrait MealItemTrait : +icon IconData MealItemTrait o-- IconData MealItemTrait : +label String MealItemTrait : +build() Widget StatelessWidget <|-- MealItemTrait ``` ## Peer Review Have not been in touch with my peer reviewer. Have not had the time to communicate with the other person. BUT on another note, I have been working with classmates I meet after school hours and helped eachother become better. ## Screenshots The following screenshots show the app's user interface: ![Main Screen](doc/screenshots/main.png) ![Category Screen](doc/screenshots/category.png) ![Filter Screen](doc/screenshots/filters.png) ![Favorites Screen](doc/screenshots/favorites.png) ### New Screenshots (after adding new features): ![New Main Screen](doc/screenshots/newMain.png) ![New Meal pt.1](doc/screenshots/newMeal1.png) ![New Meal pt.2](doc/screenshots/newMeal2.png) ![New Meal pt.3](doc/screenshots/newMeal3.png)
# libraries & options #### library(tidyverse) # A collection of R packages for data science library(tidytext) # Text mining using tidy data principles library(legiscanrr) # Interface with the LegiScan API for accessing legislative data / devtools::install_github("fanghuiz/legiscanrr") library(pscl) # Political Science Computational Laboratory package for analyzing roll call data and IRT models library(wnominate) # W-NOMINATE package for scaling roll call data and estimating ideal points library(oc) # Optimal Classification package for scaling roll call data library(dwnominate) # Dynamic Weighted NOMINATE for analyzing changes in voting patterns over time / remotes::install_github('wmay/dwnominate') library(jsonlite) # Tools for parsing, generating, and manipulating JSON data library(SnowballC) # Snowball stemmers for text preprocessing and stemming in natural language processing library(future.apply) options(scipen = 999) # Set options to display numeric values in precise format legiscan_api_key(set_new=TRUE) #next you'll need to put in the api key # custom functions #### parse_people_session <- function (people_json_paths) { pb <- progress::progress_bar$new(format = " parsing people [:bar] :percent in :elapsed.", total = length(people_json_paths), clear = FALSE, width = 60) pb$tick(0) extract_people_meta <- function(input_people_json_path) { pb$tick() # Define a regex to match the session pattern in the file path session_regex <- "(\\d{4}-\\d{4}_[^/]+_Session)" # Extract session from the file path using the defined regex matches <- regmatches(input_people_json_path, regexpr(session_regex, input_people_json_path)) session_info <- ifelse(length(matches) > 0, matches, NA) input_people_json <- jsonlite::fromJSON(input_people_json_path) people_meta <- input_people_json[["person"]] # Append session info as a new column people_meta$session <- session_info people_meta } output_list <- lapply(people_json_paths, extract_people_meta) output_df <- data.table::rbindlist(output_list, fill = TRUE) output_df <- tibble::as_tibble(data.table::setDF(output_df)) output_df } #Extracts session information and people metadata from given JSON file paths. It adds session details to each person's metadata. parse_person_vote_session <- function (vote_json_paths) { pb <- progress::progress_bar$new(format = " parsing person-vote [:bar] :percent in :elapsed.", total = length(vote_json_paths), clear = FALSE, width = 60) pb$tick(0) extract_vote <- function(input_vote_json_path) { pb$tick() # Extract session from the file path session_regex <- "(\\d{4}-\\d{4}_[^/]+_Session)" session_info <- regmatches(input_vote_json_path, regexpr(session_regex, input_vote_json_path)) input_vote <- jsonlite::fromJSON(input_vote_json_path) input_vote <- input_vote[["roll_call"]] person_vote <- input_vote[["votes"]] person_vote$roll_call_id <- input_vote[["roll_call_id"]] # Append session info as a new column person_vote$session <- session_info person_vote } output_list <- lapply(vote_json_paths, extract_vote) output_df <- data.table::rbindlist(output_list, fill = TRUE) output_df <- tibble::as_tibble(data.table::setDF(output_df)) output_df } #Extracts vote information and session details from given JSON file paths. It includes session information for each vote record. parse_rollcall_vote_session <- function (vote_json_paths) { pb <- progress::progress_bar$new(format = " parsing roll call [:bar] :percent in :elapsed.", total = length(vote_json_paths), clear = FALSE, width = 60) pb$tick(0) extract_rollcall <- function(input_vote_json_path) { pb$tick() # Extract session session_regex <- "(\\d{4}-\\d{4}_[^/]+_Session)" session_info <- regmatches(input_vote_json_path, regexpr(session_regex, input_vote_json_path)) input_vote <- jsonlite::fromJSON(input_vote_json_path) input_vote <- input_vote[["roll_call"]] vote_info <- purrr::keep(input_vote, names(input_vote) %in% c("roll_call_id", "bill_id", "date", "desc", "yea", "nay", "nv", "absent", "total", "passed", "chamber", "chamber_id")) # Append session info vote_info$session <- session_info vote_info } output_list <- lapply(vote_json_paths, extract_rollcall) output_df <- data.table::rbindlist(output_list, fill = TRUE) output_df <- tibble::as_tibble(data.table::setDF(output_df)) output_df } #Extracts roll call information and session details from given JSON file paths, including session info for each roll call. parse_bill_session <- function(bill_json_paths) { pb <- progress::progress_bar$new(format = " parsing bills [:bar] :percent in :elapsed.", total = length(bill_json_paths), clear = FALSE, width = 60) extract_bill_meta <- function(input_bill_path) { pb$tick() session_regex <- "(\\d{4}-\\d{4}_[^/]+_Session)" session_matches <- regexpr(session_regex, input_bill_path) session_string <- ifelse(session_matches != -1, regmatches(input_bill_path, session_matches), NA) bill_data <- jsonlite::fromJSON(input_bill_path, simplifyVector = FALSE) bill <- bill_data$bill # Handling missing fields with NA number <- ifelse(is.null(bill$bill_number), NA, bill$bill_number) bill_id <- ifelse(is.null(bill$bill_id), NA, bill$bill_id) session_id <- ifelse(is.null(bill$session_id), NA, bill$session_id) session_name <- ifelse(is.null(bill$session$session_name), NA, bill$session$session_name) url <- ifelse(is.null(bill$url), NA, bill$url) title <- ifelse(is.null(bill$title), NA, bill$title) description <- ifelse(is.null(bill$description), NA, bill$description) status <- ifelse(is.null(bill$status), NA, bill$status) status_date <- ifelse(is.null(bill$status_date), NA, bill$status_date) progress_list <- lapply(bill$progress, function(x) c(x$date, x$event)) history_list <- lapply(bill$history, function(x) c(x$date, x$action, x$chamber, x$importance)) sponsors_list <- lapply(bill$sponsors, function(x) c(x$people_id, x$party, x$role, x$name, x$sponsor_order, x$sponsor_type_id)) sasts_list <- lapply(bill$sasts, function(x) c(x$type, x$sast_bill_number, x$sast_bill_id)) texts_list <- lapply(bill$texts, function(x) c(x$date, x$type, x$type_id, x$mime, x$mime_id, x$url, x$state_link, x$text_size)) df <- data.frame( number = number, bill_id = bill_id, session_id = session_id, session_string = session_string, session_name = session_name, url = url, title = title, description = description, status = status, status_date = status_date, progress = I(list(progress_list)), history = I(list(history_list)), sponsors = I(list(sponsors_list)), sasts = I(list(sasts_list)), texts = I(list(texts_list)), stringsAsFactors = FALSE ) return(df) } output_list <- lapply(bill_json_paths, extract_bill_meta) output_df <- do.call(rbind, output_list) return(output_df) } #Extracts bill metadata including session information, progress, history, sponsors, and other related attributes from given JSON file paths. parse_bill_combined <- function(bill_json_paths) { pb <- progress::progress_bar$new(format = " parsing bills [:bar] :percent in :elapsed.", total = length(bill_json_paths), clear = FALSE, width = 60) extract_combined_meta <- function(input_bill_path) { pb$tick() session_regex <- "(\\d{4}-\\d{4}_[^/]+_Session)" session_matches <- regexpr(session_regex, input_bill_path) session_string <- ifelse(session_matches != -1, regmatches(input_bill_path, session_matches), NA) if(file.exists(input_bill_path)) { bill_data <- jsonlite::fromJSON(input_bill_path, simplifyVector = FALSE) } else { warning(paste("File not found:", input_bill_path)) return(NULL) } bill <- bill_data$bill session_name <- bill$session$session_name %||% NA # Simplify and compile desired attributes into vectors or lists sponsors_list <- lapply(bill$sponsors %||% list(), function(x) c(x$people_id, x$party, x$role, x$name, x$sponsor_order, x$sponsor_type_id)) progress_list <- lapply(bill$progress %||% list(), function(x) c(x$date, x$event)) # Construct the data frame df <- data.frame( bill_id = bill$bill_id, change_hash = bill$change_hash, url = bill$url, state_link = bill$state_link, status = bill$status, status_date = bill$status_date, state = bill$state, state_id = bill$state_id, bill_number = bill$bill_number, bill_type = bill$bill_type, bill_type_id = bill$bill_type_id, body = bill$body, body_id = bill$body_id, current_body = bill$current_body, current_body_id = bill$current_body_id, title = bill$title, description = bill$description, pending_committee_id = bill$pending_committee_id, session_name = session_name, session_string = session_string, sponsors = I(sponsors_list), progress = I(progress_list), stringsAsFactors = FALSE ) return(df) } output_list <- lapply(bill_json_paths, extract_combined_meta) output_df <- do.call(rbind, output_list) return(output_df) } #A combined approach to parsing bill metadata, including sponsors and progress, from given JSON file paths. This function compiles data into simplified vectors or lists. parse_bill_jsons <- function(json_paths){ parse_single_json <- function(json_path) { bill_data <- fromJSON(json_path, simplifyVector = FALSE) bill <- bill_data$bill # Extract flat information directly into a data frame bill_info_df <- tibble( number = bill$bill_number, title = bill$title, type = bill$bill_type, bill_id = bill$bill_id, description = bill$description, session_id = bill$session$session_id, session_name = bill$session$session_name, year = bill$session$year_end # Add more fields as needed ) # Extract sponsors (assuming sponsors are a list of lists) sponsors <- bind_rows(lapply(bill$sponsors, as_tibble), .id = bill$sponsor_id) %>% mutate(bill_id = bill$bill_id) %>% select(bill_id, everything()) amendments <- bind_rows(lapply(bill$amendments, as_tibble), .id = bill$amendment_id) %>% mutate(bill_id = bill$bill_id) %>% select(bill_id, everything()) referrals <- bind_rows(lapply(bill$referrals, as_tibble), .id = bill$committee_id) %>% mutate(bill_id = bill$bill_id) %>% select(bill_id, everything()) history <- bind_rows(lapply(bill$history, as_tibble)) %>% mutate(bill_id = bill$bill_id) %>% select(bill_id, everything()) votes <- bind_rows(lapply(bill$votes, as_tibble), .id = bill$roll_call_id) %>% mutate(bill_id = bill$bill_id) %>% select(bill_id, everything()) supplements <- bind_rows(lapply(bill$supplements, as_tibble), .id = bill$supplement_id) %>% mutate(bill_id = bill$bill_id) %>% select(bill_id, everything()) # Compile into a single list for this example list(bill_info_df = bill_info_df, sponsors = sponsors, amendments = amendments, supplements=supplements, votes=votes, history=history, referrals=referrals) } pb <- progress::progress_bar$new( format = " Parsing bills [:bar] :percent in :elapsed", total = length(json_paths), width = 60 ) parsed_results <- lapply(json_paths, function(path) { pb$tick() parse_single_json(path) }) combined_results <- list( bill_info_df = bind_rows(lapply(parsed_results, `[[`, "bill_info_df")), sponsors = bind_rows(lapply(parsed_results, `[[`, "sponsors")), amendments = bind_rows(lapply(parsed_results, `[[`, "amendments")), supplements = bind_rows(lapply(parsed_results, `[[`, "supplements")), votes = bind_rows(lapply(parsed_results, `[[`, "votes")), history = bind_rows(lapply(parsed_results, `[[`, "history")), referrals = bind_rows(lapply(parsed_results, `[[`, "referrals")) ) return(combined_results) } #Parses multiple JSON paths for bill data, extracting detailed bill information, sponsors, amendments, referrals, history, votes, and supplements. It combines results into a single list. ##every session option, but warning about API limits. #### dataset <- legiscanrr::get_dataset_list("fl") #get all datasets purrr::walk(dataset, get_dataset, save_to_dir = "data_json") #get all datasets and put it in subdir of 'data_json' text_paths <- find_json_path(base_dir = "data_json/fl/..", file_type = "vote") text_paths_bills <- find_json_path(base_dir = "data_json/fl/..", file_type = "bill") text_paths_leg <- find_json_path(base_dir = "data_json/FL/..",file_type = "people") legislators <- parse_people_session(text_paths_leg) #we use session so we don't have the wrong roles bills_all_sponsor <- parse_bill_sponsor(text_paths_bills) primary_sponsors <- bills_all_sponsor %>% filter(sponsor_type_id == 1 & committee_sponsor == 0) bills_all <- parse_bill_session(text_paths_bills) %>% mutate( session_year = as.numeric(str_extract(session_name, "\\d{4}")), # Extract year two_year_period = case_when( session_year < 2011 ~ "2010 or earlier", session_year %% 2 == 0 ~ paste(session_year - 1, session_year, sep="-"), TRUE ~ paste(session_year, session_year + 1, sep="-") ) ) bill_detailed <- parse_bill_jsons(text_paths_bills) # make big dfs #### votes_all <- left_join(bill_detailed$votes,bill_detailed$bill_info_df) %>% mutate(pct = yea/total) bill_vote_all <- inner_join(bills_all,votes_all,by=c("bill_id","number","title","session_id","session_name" ),suffix=c("","_vote")) %>% mutate(total_vote = (yea+nay),true_pct = yea/total_vote) %>% arrange(true_pct) #bill_id is unique and not duplicated across sessions primary_sponsors_votes <- primary_sponsors %>% left_join(votes_all,by="bill_id") %>% mutate(total_vote = (yea+nay),true_pct = yea/total_vote) %>% arrange(true_pct) bill_vote_all$session <- paste0(bill_vote_all$session_year,"-",gsub(" ","_", bill_vote_all$session_name)) leg_votes_with2 <- parse_person_vote_session(text_paths) %>% mutate(roll_call_id = as.character(roll_call_id)) %>% # Convert roll_call_id to character inner_join(legislators,by=c("people_id","session")) %>% inner_join(bill_vote_all %>% mutate(roll_call_id = as.character(roll_call_id)), by = c("roll_call_id", "session")) ## analysis & prep #### analyse_bill <- leg_votes_with2 %>% group_by(party,roll_call_id,title,vote_text,number) %>% summarize(n=n()) %>% arrange(desc(n)) %>% pivot_wider(values_from = n,names_from = vote_text,values_fill = 0) %>% mutate(total=sum(Yea,NV,Absent,Nay,na.rm = TRUE),total2=sum(Yea,Nay)) %>% filter(total>0 & total2 >0) %>% mutate(y_pct = Yea/total,n_pct=Nay/total,nv_pct=NV/total, absent_pct=Absent/total,NV_A=(NV+Absent)/total,y_pct2 = Yea/(Yea+Nay),n_pct2 = Nay/(Yea+Nay),margin=y_pct2-n_pct2) partisanbillvotes <- analyse_bill %>% select(party,roll_call_id,title,y_pct2,number) %>% pivot_wider(names_from = party,values_from=y_pct2,values_fill = NA,id_cols = c(roll_call_id,title,number)) %>% mutate(`D-R`=D-R) partisanbillvotes$Partisan[partisanbillvotes$`D-R`<0] <- "Somewhat GOP" partisanbillvotes$Partisan[partisanbillvotes$`D-R`< -.25] <- "GOP" partisanbillvotes$Partisan[partisanbillvotes$`D-R`< - .75] <- "Very GOP" partisanbillvotes$Partisan[partisanbillvotes$`D-R`==0] <- "Split" partisanbillvotes$Partisan[partisanbillvotes$`D-R`> 0] <- "Somewhat DEM" partisanbillvotes$Partisan[partisanbillvotes$`D-R`> .25] <- "DEM" partisanbillvotes$Partisan[partisanbillvotes$`D-R`> .75] <- "Very DEM" partisanbillvotes$Partisan[is.na(partisanbillvotes$`D-R`)] <- "Unclear" partisanbillvotes$GOP[partisanbillvotes$R > .5] <- "GOP Support" partisanbillvotes$GOP[partisanbillvotes$R > .75] <- "GOP Moderately Support" partisanbillvotes$GOP[partisanbillvotes$R > .9] <- "GOP Very Strongly Support" partisanbillvotes$GOP[partisanbillvotes$R == 1] <- "GOP Unanimously Support" partisanbillvotes$GOP[partisanbillvotes$R == .5] <- "GOP Split" partisanbillvotes$GOP[partisanbillvotes$R < .5] <- "GOP Oppose" partisanbillvotes$GOP[partisanbillvotes$R < .25] <- "GOP Moderately Oppose" partisanbillvotes$GOP[partisanbillvotes$R < .1] <- "GOP Very Strongly Oppose" partisanbillvotes$GOP[partisanbillvotes$R == 0] <- "GOP Unanimously Oppose" partisanbillvotes$DEM[partisanbillvotes$D > .5] <- "DEM Support" partisanbillvotes$DEM[partisanbillvotes$D > .75] <- "DEM Strongly Support" partisanbillvotes$DEM[partisanbillvotes$D > .9] <- "DEM Very Strongly Support" partisanbillvotes$DEM[partisanbillvotes$D == 1] <- "DEM Unanimously Support" partisanbillvotes$DEM[partisanbillvotes$D == .5] <- "DEM Split" partisanbillvotes$DEM[partisanbillvotes$D < .5] <- "DEM Oppose" partisanbillvotes$DEM[partisanbillvotes$D < .25] <- "DEM Moderately Oppose" partisanbillvotes$DEM[partisanbillvotes$D < .1] <- "DEM Very Strongly Oppose" partisanbillvotes$DEM[partisanbillvotes$D == 0] <- "DEM Unanimously Oppose" partisanbillvotes$DEM[is.na(partisanbillvotes$D)] <- "DEM No Votes" leg_votes_with2 <- leg_votes_with2 %>% filter(!is.na(date)&total>0) leg_votes_with2 <- left_join(leg_votes_with2,partisanbillvotes) %>% filter(!is.na(D)&!is.na(R)&!is.na(`D-R`)) leg_votes_with2 <- leg_votes_with2 %>% arrange(desc(abs(`D-R`))) leg_votes_with2$dem_majority[leg_votes_with2$D > 0.5] <- "Y" leg_votes_with2$dem_majority[leg_votes_with2$D < 0.5] <- "N" leg_votes_with2$dem_majority[leg_votes_with2$D == 0.5] <- "Equal" leg_votes_with2$gop_majority[leg_votes_with2$R > 0.5] <- "Y" leg_votes_with2$gop_majority[leg_votes_with2$R < 0.5] <- "N" leg_votes_with2$gop_majority[leg_votes_with2$R == 0.5] <- "Equal" #to later create a priority bill filter leg_votes_with2$priority_bills <- "N" leg_votes_with2$priority_bills[abs(leg_votes_with2$`D-R`)>.85] <- "Y" leg_votes_with2 <- leg_votes_with2 %>% mutate(vote_with_dem_majority = ifelse(dem_majority == "Y" & vote_text=="Yea", 1, 0), vote_with_gop_majority = ifelse(gop_majority == "Y" & vote_text=="Yea", 1, 0), vote_with_neither = ifelse((dem_majority == "Y" & gop_majority == "Y" & vote_text=="Nay") | (dem_majority=="N" & gop_majority == "N" & vote_text=="Yea"),1,0), vote_with_dem_majority = ifelse((dem_majority == "Y" & vote_text == "Yea")|dem_majority=="N" & vote_text=="Nay", 1, 0), vote_with_gop_majority = ifelse((gop_majority == "Y" & vote_text == "Yea")|gop_majority=="N" & vote_text=="Nay", 1, 0), vote_with_neither = ifelse( (dem_majority == "Y" & gop_majority == "Y" & vote_text == "Nay") | (dem_majority == "N" & gop_majority == "N" & vote_text == "Yea"), 1, 0), voted_at_all = vote_with_dem_majority+vote_with_gop_majority+vote_with_neither, maverick_votes=ifelse((party=="D" & vote_text=="Yea" & dem_majority=="N" & gop_majority=="Y") | (party=="D" & vote_text=="Nay" & dem_majority=="Y" & gop_majority=="N") | (party=="R" & vote_text=="Yea" & gop_majority=="N" & dem_majority=="Y") | (party=="R" & vote_text=="Nay" & gop_majority=="Y" & dem_majority=="N"),1,0 )) # Summarize the data to get the count of votes with majority for each legislator legislator_majority_votes <- leg_votes_with2 %>% group_by(party,role,session_id) %>% summarize(votes_with_dem_majority = sum(vote_with_dem_majority, na.rm = TRUE), votes_with_gop_majority = sum(vote_with_gop_majority, na.rm = TRUE), independent_votes = sum(vote_with_neither,na.rm=TRUE), total_votes = n(), .groups = 'drop') %>% mutate(d_pct = votes_with_dem_majority/total_votes, r_pct=votes_with_gop_majority/total_votes, margin=d_pct-r_pct, ind_pct=independent_votes/total_votes) leg_votes_with2$bill_alignment[leg_votes_with2$D == 0.5 | leg_votes_with2$R == 0.5] <- "at least one party even" leg_votes_with2$bill_alignment[leg_votes_with2$D > 0.5 & leg_votes_with2$R < 0.5] <- "DEM" leg_votes_with2$bill_alignment[leg_votes_with2$D < 0.5 & leg_votes_with2$R > 0.5] <- "GOP" leg_votes_with2$bill_alignment[leg_votes_with2$D < 0.5 & leg_votes_with2$R < 0.5] <- "Both" leg_votes_with2$bill_alignment[leg_votes_with2$D > 0.5 & leg_votes_with2$R > 0.5] <- "Both" party_majority_votes <- leg_votes_with2 %>% filter(party!=""& !is.na(party)) %>% group_by(roll_call_id, party) %>% summarize(majority_vote = if_else(sum(vote_text == "Yea") > sum(vote_text == "Nay"), "Yea", "Nay"), .groups = 'drop') %>% pivot_wider(names_from = party,values_from = majority_vote,id_cols = roll_call_id,values_fill = "NA",names_prefix = "vote_") heatmap_data <- leg_votes_with2 %>% left_join(party_majority_votes, by = c("roll_call_id")) %>% filter(!is.na(party)&party!="" & !grepl("2010",session_name,ignore.case=TRUE)& !is.na(session_name)) %>% filter(vote_text=="Yea"|vote_text=="Nay") %>% mutate(diff_party_vote_d = if_else(vote_text != vote_D, 1, 0),diff_party_vote_r = if_else(vote_text != vote_R, 1, 0), diff_both_parties = if_else(diff_party_vote_d == 1 & diff_party_vote_r == 1,1,0), diff_d_not_r=if_else(diff_party_vote_d==1 & diff_party_vote_r==0,1,0), diff_r_not_d=if_else(diff_party_vote_d==0&diff_party_vote_r==1,1,0), partisan_metric = ifelse(party=="R",diff_r_not_d,ifelse(party=="D",diff_d_not_r,NA)), pct_format = scales::percent(pct)) %>% arrange(desc(partisan_metric)) %>% distinct() heatmap_data$roll_call_id = with(heatmap_data, reorder(roll_call_id, partisan_metric, sum)) heatmap_data$name = with(heatmap_data, reorder(name, partisan_metric, sum)) legislator_metric <- heatmap_data %>% group_by(name) %>% filter(date >= as.Date("11/10/2012")) %>% summarize(partisan_metric=mean(partisan_metric)) %>% arrange(partisan_metric,name) #create the sort based on partisan metric ### create the text to be displayed in the javascript interactive when hovering over votes #### createHoverText <- function(numbers, descriptions, urls, pcts, vote_texts,descs,title,date, names, width = 100) { # Wrap the description text at the specified width wrapped_descriptions <- sapply(descriptions, function(desc) paste(strwrap(desc, width = width), collapse = "<br>")) # Combine the elements into a single string paste( names, " voted ", vote_texts, " on ", descs, " for bill ",numbers," - ",title," on ",date,"<br>", "Description: ", wrapped_descriptions, "<br>", "URL: ", urls, "<br>", pcts, " voted for this bill", sep = "" ) } heatmap_data$hover_text <- mapply( createHoverText, numbers = heatmap_data$number, descs = heatmap_data$desc, title=heatmap_data$title,date=heatmap_data$date, descriptions = heatmap_data$description, urls = heatmap_data$url, pcts = heatmap_data$pct_format, vote_texts = heatmap_data$vote_text, names = heatmap_data$name, SIMPLIFY = FALSE # Keep it as a list ) heatmap_data$hover_text <- sapply(heatmap_data$hover_text, paste, collapse = " ") # Collapse the list into a single string heatmap_data$partisan_metric2 <- ifelse(heatmap_data$vote_with_neither == 1, 1, ifelse(heatmap_data$maverick_votes == 1, 2, 0)) heatmap_data$partisan_metric3 <- factor(heatmap_data$partisan_metric2, levels = c(0, 1, 2), labels = c("With Party", "Independent Vote", "Maverick Vote")) d_partisan_votes <- heatmap_data %>% filter(party=="D") %>% group_by(roll_call_id) %>% summarize(max=max(partisan_metric2)) %>% filter(max>=1) r_partisan_votes <- heatmap_data %>% filter(party=="R") %>% group_by(roll_call_id) %>% summarize(max=max(partisan_metric2)) %>% filter(max>=1) d_votes <- heatmap_data %>% filter(party=="D") %>% group_by(roll_call_id,vote_text) %>% summarize(n=n()) %>% pivot_wider(names_from=vote_text,values_from=n,values_fill = 0) %>% mutate(y_pct = Yea/(Yea+Nay),n_pct = Nay/(Nay+Yea)) %>% filter(y_pct != 0 & y_pct != 1) %>% filter(as.character(roll_call_id) %in% as.character(d_partisan_votes$roll_call_id)) r_votes <- heatmap_data %>% filter(party=="R") %>% group_by(roll_call_id,vote_text) %>% summarize(n=n()) %>% pivot_wider(names_from=vote_text,values_from=n,values_fill = 0) %>% mutate(y_pct = Yea/(Yea+Nay),n_pct = Nay/(Nay+Yea)) %>% filter(y_pct != 0 & y_pct != 1) %>% filter(as.character(roll_call_id) %in% as.character(r_partisan_votes$roll_call_id)) priority_votes <- heatmap_data %>% filter(priority_bills=="Y") %>% group_by(roll_call_id,vote_text) %>% summarize(n=n()) %>% pivot_wider(names_from=vote_text,values_from=n,values_fill = 0) %>% mutate(y_pct = Yea/(Yea+Nay),n_pct = Nay/(Nay+Yea)) %>% filter(y_pct != 0 & y_pct != 1) roll_call_to_number <- heatmap_data %>% select(roll_call_id, year=session_year,number) %>% distinct() %>% arrange(desc(year),number,roll_call_id) roll_call_to_number$number_year <- paste(roll_call_to_number$number,"-",roll_call_to_number$year) heatmap_data$roll_call_id <- factor(heatmap_data$roll_call_id, levels = roll_call_to_number$roll_call_id) heatmap_data$name <- factor(heatmap_data$name, levels = legislator_metric$name) y_labels <- setNames(roll_call_to_number$number_year, roll_call_to_number$roll_call_id) heatmap_data$final <- "N" heatmap_data$final[grepl("third",heatmap_data$desc,ignore.case=TRUE)] <- "Y" heatmap_data$ballotpedia2 <- paste0("http://ballotpedia.org/",heatmap_data$ballotpedia)
import { ref, onMounted, reactive, mergeProps, useSSRContext } from "vue"; import { ssrRenderAttrs, ssrInterpolate, ssrRenderAttr, ssrRenderList } from "vue/server-renderer"; import { useI18n } from "vue-i18n"; import { useRouter } from "vue-router"; const _sfc_main = { __name: "FilterArticle", __ssrInlineRender: true, setup(__props) { useRouter(); const { locale } = useI18n(); const continents = ref([]); const zones = ref([]); const countries = ref([]); const ministries = ref([]); const zoneFiltered = ref([]); const countryFiltered = ref([]); onMounted(async () => { let response = await axios.get("/api/continents"); continents.value = response.data.data; response = await axios.get("/api/zones"); zones.value = response.data.data; response = await axios.get("/api/countries"); countries.value = response.data.data; response = await axios.get("/api/ministries"); ministries.value = response.data.data; }); const filter = reactive({ country: "", continent: "", ministry: "", zone: "", lang: "", keywords: "", type: "article" }); onMounted(async () => { filter.lang = localStorage.lang ? localStorage.lang : locale.value; }); return (_ctx, _push, _parent, _attrs) => { _push(`<div${ssrRenderAttrs(mergeProps({ class: "z-0 w-full bg-white" }, _attrs))}><h1 class="inline-block bg-primary-blue px-2 py-1 text-white">${ssrInterpolate(_ctx.$t("filter-article"))}</h1><form><div class="space-y-2 border-t-2 border-primary-blue p-4 text-sm"><div><label class="text-gray-500">${ssrInterpolate(_ctx.$t("language"))}</label><select class="form-select mt-2 block w-full border-gray-300 px-3 text-xs focus:border-primary-blue focus:ring-primary-blue"><option value="fr">${ssrInterpolate(_ctx.$t("fr"))}</option><option value="en">${ssrInterpolate(_ctx.$t("en"))}</option><option value="es">${ssrInterpolate(_ctx.$t("es"))}</option><option value="pt">${ssrInterpolate(_ctx.$t("pt"))}</option></select></div><div><label class="text-gray-500">${ssrInterpolate(_ctx.$t("key-words"))}</label><input type="text"${ssrRenderAttr("value", filter.keywords)}${ssrRenderAttr("placeholder", _ctx.$t("key-words"))} class="form-input mt-2 block w-full border-gray-300 px-3 text-xs focus:border-primary-blue focus:ring-primary-blue"></div><div><label class="text-gray-500">${ssrInterpolate(_ctx.$t("continent"))}</label><select class="form-select mt-2 block w-full border-gray-300 px-3 text-xs focus:border-primary-blue focus:ring-primary-blue"><option value="">--------------</option><!--[-->`); ssrRenderList(continents.value, (continent) => { _push(`<option${ssrRenderAttr("value", continent.id)}>`); if (_ctx.$i18n.locale == "en") { _push(`<span>${ssrInterpolate(continent.name_en)}</span>`); } else if (_ctx.$i18n.locale == "fr") { _push(`<span>${ssrInterpolate(continent.name_fr)}</span>`); } else if (_ctx.$i18n.locale == "es") { _push(`<span>${ssrInterpolate(continent.name_es)}</span>`); } else { _push(`<span>${ssrInterpolate(continent.name_pt)}</span>`); } _push(`</option>`); }); _push(`<!--]--></select></div><div><label class="text-gray-500">${ssrInterpolate(_ctx.$t("zoned"))}</label><select class="form-select mt-2 block w-full border-gray-300 px-3 text-xs focus:border-primary-blue focus:ring-primary-blue"><option value="">--------------</option>`); if (zoneFiltered.value.length != 0) { _push(`<!--[-->`); ssrRenderList(zoneFiltered.value, (zone) => { _push(`<option${ssrRenderAttr("value", zone.id)}>`); if (_ctx.$i18n.locale == "en") { _push(`<span>${ssrInterpolate(zone.name_en)}</span>`); } else if (_ctx.$i18n.locale == "fr") { _push(`<span>${ssrInterpolate(zone.name_fr)}</span>`); } else if (_ctx.$i18n.locale == "es") { _push(`<span>${ssrInterpolate(zone.name_es)}</span>`); } else { _push(`<span>${ssrInterpolate(zone.name_pt)}</span>`); } _push(`</option>`); }); _push(`<!--]-->`); } else { _push(`<option value="null"> Select ${ssrInterpolate(_ctx.$t("continent"))}</option>`); } _push(`</select></div><div><label class="text-gray-500">${ssrInterpolate(_ctx.$t("country"))}</label><select class="form-select mt-2 block w-full border-gray-300 px-3 text-xs focus:border-primary-blue focus:ring-primary-blue"><option value="">--------------</option>`); if (countryFiltered.value.length != 0) { _push(`<!--[-->`); ssrRenderList(countryFiltered.value, (country) => { _push(`<option${ssrRenderAttr("value", country.id)}>`); if (_ctx.$i18n.locale == "en") { _push(`<span>${ssrInterpolate(country.name_en)}</span>`); } else if (_ctx.$i18n.locale == "fr") { _push(`<span>${ssrInterpolate(country.name_fr)}</span>`); } else if (_ctx.$i18n.locale == "es") { _push(`<span>${ssrInterpolate(country.name_es)}</span>`); } else { _push(`<span>${ssrInterpolate(country.name_pt)}</span>`); } _push(`</option>`); }); _push(`<!--]-->`); } else { _push(`<option value="null"> Select ${ssrInterpolate(_ctx.$t("zoned"))}</option>`); } _push(`</select></div><div><label class="text-gray-500">${ssrInterpolate(_ctx.$t("ministry"))}</label><select class="form-select mt-1 block w-full border-gray-300 px-3 text-xs focus:border-primary-blue focus:ring-primary-blue"><option value="">--------------</option><!--[-->`); ssrRenderList(ministries.value, (ministry) => { _push(`<option${ssrRenderAttr("value", ministry.id)}>`); if (_ctx.$i18n.locale == "en") { _push(`<span>${ssrInterpolate(ministry.name_en)}</span>`); } else if (_ctx.$i18n.locale == "fr") { _push(`<span>${ssrInterpolate(ministry.name_fr)}</span>`); } else if (_ctx.$i18n.locale == "es") { _push(`<span>${ssrInterpolate(ministry.name_es)}</span>`); } else { _push(`<span>${ssrInterpolate(ministry.name_pt)}</span>`); } _push(`</option>`); }); _push(`<!--]--></select></div><div><button type="button" class="mt-3 w-full bg-primary-blue px-8 py-2 text-lg text-white">${ssrInterpolate(_ctx.$t("filter"))}</button></div></div></form></div>`); }; } }; const _sfc_setup = _sfc_main.setup; _sfc_main.setup = (props, ctx) => { const ssrContext = useSSRContext(); (ssrContext.modules || (ssrContext.modules = /* @__PURE__ */ new Set())).add("resources/js/components/FilterArticle.vue"); return _sfc_setup ? _sfc_setup(props, ctx) : void 0; }; export { _sfc_main as _ };
import matplotlib.pyplot as plt from matplotlib import rcParams # 设置全局字体为Times New Roman rcParams['font.family'] = 'Times New Roman' rcParams['font.size'] = 14 # Data params = [9814, 96542, 264704, 420192, 504000] models = ['LITE', 'MMM4TSC', 'FCN', 'Inception', 'ResNet'] accuracy = [0.8304, 0.8494, 0.7883, 0.8411, 0.8066] colors = ['red', 'green', 'blue', 'yellow', 'purple'] bubble_sizes = [100, 300, 550, 700, 850] # Arbitrary sizes for demonstration # Plot plt.figure(figsize=(10, 6)) for i in range(len(models)): plt.scatter(params[i], accuracy[i], s=bubble_sizes[i], c=colors[i], alpha=0.8, label=None) ax = plt.gca() bbox_to_anchor = (ax.get_position().x0 - 0.11, ax.get_position().y0 - 0.10) # Legend with bubble sizes legend_labels = [f'{models[i]} ({params[i]:,})' for i in range(len(models))] bubble_sizes_legend = [250, 50, 100, 150, 200] # Sizes for legend for size, label, color in zip(bubble_sizes, legend_labels, colors): plt.scatter([], [], s=size, c=color, label=label, alpha=0.6) plt.xlabel('Parameters', fontweight='bold', fontsize='large') plt.ylabel('Accuracy', fontsize='large', fontweight='bold') plt.title('Model Parameters vs. Accuracy', fontweight='bold', fontsize='large') plt.ylim(0.75, 0.86) # plt.legend(title='Models (Parameters)', loc='lower left', fontsize='small', ncol=5, # bbox_to_anchor=bbox_to_anchor, frameon=False) plt.legend(loc='lower left', fontsize=10, ncol=5, bbox_to_anchor=bbox_to_anchor) plt.grid(True) plt.tight_layout() plt.savefig('acc_params.svg', bbox_inches='tight', dpi=300, format='svg') plt.show()
DOFAndBloomGatherPixelShader.usf: Pixel shader for gathering the combined depth of field and bloom samples for blurring. Copyright 1998-2013 Epic Games, Inc. All Rights Reserved. // also includes Common.usf #include "PostProcessCommon.usf" // for CalcUnfocusedPercent() #include "DepthOfFieldCommon.usf" /** [x] CustomColorScale */ half4 GatherParams; /** [x,y] The amount bloomed colors are scaled by. [z,w] The min depth and max depth for clamping */ half4 BloomScaleAndThreshold; /** Min clamping distance for DoF. */ static half MinDoFDistance = BloomScaleAndThreshold.z; /** Max clamping distance for DoF. */ static half MaxDoFDistance = BloomScaleAndThreshold.w; // half resolution with depth DeviceZ in alpha sampler2D SmallSceneColorTexture; // full resolution separate translucency sampler2D SeparateTranslucencyTexture; // image space pixel motion vectors sampler2D VelocityTexture; // --------------------------------------------- /** Computes a pixel's luminance for bloom */ half ComputeLuminanceForBloom( half3 InSceneColor ) { // Compute the luminance for this pixel half TotalLuminance; if( 1 ) { // Compute luminance as the maximum of RGB. This is a bit more intuitive for artists as they know // that any pixel with either of the RGB channels above 1.0 will begin to bloom. TotalLuminance = max( InSceneColor.r, max( InSceneColor.g, InSceneColor.b ) ); } else { // RGB scale factor to calculated pixel luminance using a weight average half3 LuminanceFactor = half3( 0.3, 0.59, 0.11 ); // Compute true luminance TotalLuminance = dot( LuminanceFactor, InSceneColor ); } return TotalLuminance; } /** Computes bloomed amount for the specified scene color */ half ComputeBloomAmount( half3 InSceneColor ) { // Compute the luminance for this pixel half TotalLuminance = ComputeLuminanceForBloom( InSceneColor ); // Size of the bloom "ramp". This value specifies the amount of light beyond the bloom threshold required // before a pixel's bloom will be 100% of the original color. // NOTE: Any value above 0.8 looks pretty good here (and 1.0 is often fastest), but a value of 2.0 here // minimizes artifacts: the bloom ramp-up will closely match the linear ascent of additive color half BloomRampSize = 2.0f; // Figure out how much luminance is beyond the bloom threshold. Note that this value could be negative but // we handle that in the next step. half BloomLuminance = TotalLuminance - BloomScaleAndThreshold.y; // Note that we clamp the bloom amount between 0.0 and 1.0, but pixels beyond our bloom ramp will still // bloom brighter because we'll use 100% of the original scene color as bloom half BloomAmount = saturate( BloomLuminance / BloomRampSize ); return BloomAmount; } /** Computes bloomed color for the specified scene color */ half3 ComputeBloomColor( half3 InSceneColor ) { // Multiply with the scene color to get the final bloom amount return InSceneColor * ComputeBloomAmount( InSceneColor ); } // RGB is half resolution scene color, A is depth half4 CalcSceneColorAndDepthDOFBloomInput(float2 ScreenUV) { // scene color and depth lookup in half resolution float4 FetchColor = tex2D(SmallSceneColorTexture, ScreenUV); bool bMotionBlurObject; // bring from texture usable range to worldspace range FetchColor.a = DecompressSceneDepthFromHalfResTextureChannel(FetchColor.a, bMotionBlurObject); return (half4)FetchColor; } /** The number of float4s the 2D sample offsets are packed into. */ #define NUM_CHUNKS ((NUM_SAMPLES + 1) / 2) /** * Entry point for the gather pass, which downsamples from scene color to the filter buffer. * Unfocused DOF color is stored in OutColor.rgb. */ void MainGatherDOF( in float4 OffsetUVs[NUM_CHUNKS] : TEXCOORD0, out float4 OutColor : COLOR0 ) { // RGB:scene color, A:depth half4 AvgSceneColorAndDepth = 0; //Go through each chunk and take samples. NUM_SAMPLES must be a factor of 2. for(int ChunkIndex = 0;ChunkIndex < NUM_SAMPLES / 2;ChunkIndex++) { // Sample scene color/depth (1) and accumulate average half4 SceneColorAndDepth1 = CalcSceneColorAndDepthDOFBloomInput(OffsetUVs[ChunkIndex].xy); AvgSceneColorAndDepth += SceneColorAndDepth1; // Sample scene color/depth (2) and accumulate average half4 SceneColorAndDepth2 = CalcSceneColorAndDepthDOFBloomInput(OffsetUVs[ChunkIndex].wz); AvgSceneColorAndDepth += SceneColorAndDepth2; } //normalize and scale AvgSceneColorAndDepth = AvgSceneColorAndDepth / NUM_SAMPLES; half ClampedUnfocusedPercent = CalcUnfocusedPercent(AvgSceneColorAndDepth.a); //scale output down to fit in the [0-1] range of the fixed point filter buffer OutColor = float4(AvgSceneColorAndDepth.rgb * ClampedUnfocusedPercent, ClampedUnfocusedPercent) / MAX_SCENE_COLOR; #if PS3 OutColor = isnan(OutColor) ? half4(0,0,0,0) : OutColor; #elif OPENGL OutColor = saturate(OutColor); #endif } /** * Entry point for the gather pass, which downsamples from scene color to the filter buffer. * Bloom color is stored in OutColor.rgb. */ void MainGatherBloom( in float4 OffsetUVs[NUM_CHUNKS] : TEXCOORD0, out float4 OutColor : COLOR0 ) { half3 AvgBloomColor = 0; // Go through each chunk and take samples, two at a time (NUM_SAMPLES must be a factor of 2). // // The bloom color is the scaled scene color if it has a component outside the displayable range [0,1]. // Only bloom if (SceneColor > 1), instead of (0 > SceneColor > 1), in order to mimic XBOX behavior due to having unsigned SceneColor values // this comparison is done per scene color sample to reduce aliasing on high frequency bright patterns for(int ChunkIndex = 0; ChunkIndex < NUM_SAMPLES / 2; ChunkIndex++) { half3 SceneColor1 = tex2D(SmallSceneColorTexture, OffsetUVs[ChunkIndex].xy).rgb * GatherParams.x; half3 SceneColor2 = tex2D(SmallSceneColorTexture, OffsetUVs[ChunkIndex].wz).rgb * GatherParams.x; #if USE_SEPARATE_TRANSLUCENCY half4 TranslColor1 = tex2D(SeparateTranslucencyTexture, OffsetUVs[ChunkIndex].xy); half4 TranslColor2 = tex2D(SeparateTranslucencyTexture, OffsetUVs[ChunkIndex].wz); SceneColor1 = SceneColor1 * TranslColor1.a + TranslColor1.rgb; SceneColor2 = SceneColor2 * TranslColor2.a + TranslColor2.rgb; #endif AvgBloomColor += ComputeBloomColor(SceneColor1); AvgBloomColor += ComputeBloomColor(SceneColor2); } //normalize and scale AvgBloomColor = AvgBloomColor * BloomScaleAndThreshold.x / NUM_SAMPLES; //scale output down to fit in the [0-1] range of the fixed point filter buffer, alpha is unused OutColor = float4(AvgBloomColor, 0.0f) / MAX_SCENE_COLOR; #if PS3 OutColor = isnan(OutColor) ? half4(0,0,0,0) : OutColor; #elif OPENGL OutColor = saturate(OutColor); #endif } half3 ExtractMotionBlur(half4 DynamicVelocity) { bool SelectorOpaque = DynamicVelocity.x + DynamicVelocity.y > 0; // 0.25f as we have 4 samples half Weight = 0.25f; return half3(DynamicVelocity.xy * 2 - 1, 1) * Weight * SelectorOpaque; } /** * Entry point for the gather pass, which downsamples from motion blur to the filter buffer. * MotioBlur color is stored in OutColor.rgb. */ void MainGatherMotionBlur( in float4 OffsetUVs[NUM_CHUNKS] : TEXCOORD0, out float4 OutColor : COLOR0 ) { // static small bias to avoid division by 0 half3 VelocitySum = half3(0, 0, 0.01f); //Go through each chunk and take samples. NUM_SAMPLES must be a factor of 2. for(int ChunkIndex = 0;ChunkIndex < NUM_SAMPLES / 2;ChunkIndex++) { VelocitySum += ExtractMotionBlur(tex2D(VelocityTexture, OffsetUVs[ChunkIndex].xy)); VelocitySum += ExtractMotionBlur(tex2D(VelocityTexture, OffsetUVs[ChunkIndex].wz)); } // *0.5+0.5 as we store in a texture in the range 0..1 OutColor = float4(VelocitySum.xy * 0.5f + 0.5f, VelocitySum.z, 1); }
using Application; using Infrastructure; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using FluentValidation.AspNetCore; using Application.Common.Interfaces.Services; using WebApi.Common; namespace WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddApplication(true) .AddInfrastructure(Configuration); services.AddControllers() .AddNewtonsoftJson() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ICurrentUserService>()); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "GameCup", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "GameCup v1")); } app.UseCustomExceptionHandler(); app.UseRouting(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
#include <iostream> using namespace std; // Forward declaration class complex; class calculator { public: int add(int a, int b) { return a + b; } int sumRealComplex(complex o1, complex o2); int sumComComplex(complex, complex); }; class complex { int a, b; public: void setNumber(int a1, int b1) { a = a1; b = b1; } // individually declaring functions as friends but it is good only if u have to make small number of functions as friends // friend int calculator ::sumRealComplex(complex o1, complex o2); // friend int calculator ::sumComComplex(complex o1, complex o2); // Alternate method: Declaring an entire class as friend friend class calculator; void printNumber() { cout << "Your number is " << a << " + " << b << "i" << endl; } }; int calculator ::sumRealComplex(complex o1, complex o2) { return o1.a + o2.a; } int calculator ::sumComComplex(complex o1, complex o2) { return o1.b + o2.b; } int main() { complex o1, o2; o1.setNumber(1, 4); o2.setNumber(3, 5); calculator calc; int res = calc.sumRealComplex(o1, o2); cout << "The sum of real numbers of o1 and o2 is " << res << endl; int resCom = calc.sumComComplex(o1, o2); cout << "The sum of complex numbers of o1 and o2 is " << resCom << endl; return 0; }
# coding: utf-8 # # Copyright © 2013-2015 Ejwa Software. All rights reserved. # # This file is part of gitinspector. # # gitinspector is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # gitinspector 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 gitinspector. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function from __future__ import unicode_literals import gettext import locale import os import re import sys import time from . import basedir __enabled__ = False __installed__ = False __translation__ = None # Dummy function used to handle string constants def N_(message): return message def init(): global __enabled__ global __installed__ global __translation__ if not __installed__: try: locale.setlocale(locale.LC_ALL, "") except locale.Error: __translation__ = gettext.NullTranslations() else: lang = locale.getlocale() # Fix for non-POSIX-compliant systems (Windows et al.). if os.getenv('LANG') is None: lang = locale.getdefaultlocale() if lang[0]: os.environ['LANG'] = lang[0] if lang[0] is not None: filename = basedir.get_basedir() + "/translations/messages_%s.mo" % lang[0][0:2] try: __translation__ = gettext.GNUTranslations(open(filename, "rb")) except IOError: __translation__ = gettext.NullTranslations() else: logging.info("WARNING: Localization disabled because the system language could not be determined.", file=sys.stderr) __translation__ = gettext.NullTranslations() __enabled__ = True __installed__ = True __translation__.install(True) def check_compatibility(version): if isinstance(__translation__, gettext.GNUTranslations): header_pattern = re.compile("^([^:\n]+): *(.*?) *$", re.MULTILINE) header_entries = dict(header_pattern.findall(_(""))) if header_entries["Project-Id-Version"] != "gitinspector {0}".format(version): logging.info("WARNING: The translation for your system locale is not up to date with the current gitinspector " "version. The current maintainer of this locale is {0}.".format(header_entries["Last-Translator"]), file=sys.stderr) def get_date(): if __enabled__ and isinstance(__translation__, gettext.GNUTranslations): date = time.strftime("%x") if hasattr(date, 'decode'): date = date.decode("utf-8", "replace") return date else: return time.strftime("%Y/%m/%d") def enable(): if isinstance(__translation__, gettext.GNUTranslations): __translation__.install(True) global __enabled__ __enabled__ = True def disable(): global __enabled__ __enabled__ = False if __installed__: gettext.NullTranslations().install(True)
/** * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ package com.liferay.portal.kernel.model.adapter; import com.liferay.portal.kernel.model.adapter.builder.ModelAdapterBuilder; import com.liferay.portal.kernel.model.adapter.builder.ModelAdapterBuilderLocator; import com.liferay.portal.kernel.module.service.Snapshot; import java.util.ArrayList; import java.util.List; /** * @author Máté Thurzó */ public class ModelAdapterUtil { public static <T, V> List<V> adapt( List<T> adapteeModels, Class<T> adapteeModelClass, Class<V> adaptedModelClass) { List<V> adaptedModels = new ArrayList<>(); for (T adapteeModel : adapteeModels) { adaptedModels.add( adapt(adapteeModel, adapteeModelClass, adaptedModelClass)); } return adaptedModels; } public static <T, V> List<V> adapt( List<T> adapteeModels, Class<V> adaptedModelClass) { List<V> adaptedModels = new ArrayList<>(); for (T adapteeModel : adapteeModels) { adaptedModels.add(adapt(adapteeModel, adaptedModelClass)); } return adaptedModels; } public static <T, V> V adapt( T adapteeModel, Class<T> adapteeModelClass, Class<V> adaptedModelClass) { return doAdapt(adapteeModel, adapteeModelClass, adaptedModelClass); } public static <T, V> V adapt(T adapteeModel, Class<V> adaptedModelClass) { Class<T> adapteeModelClass = (Class<T>)adapteeModel.getClass(); return doAdapt(adapteeModel, adapteeModelClass, adaptedModelClass); } protected static <T, V> V doAdapt( T adapteeModel, Class<T> adapteeModelClass, Class<V> adaptedModelClass) { ModelAdapterBuilderLocator modelAdapterBuilderLocator = _modelAdapterBuilderLocatorSnapshot.get(); if (modelAdapterBuilderLocator == null) { return null; } ModelAdapterBuilder<T, V> modelAdapterBuilder = modelAdapterBuilderLocator.locate( adapteeModelClass, adaptedModelClass); return modelAdapterBuilder.build(adapteeModel); } private static final Snapshot<ModelAdapterBuilderLocator> _modelAdapterBuilderLocatorSnapshot = new Snapshot<>( ModelAdapterUtil.class, ModelAdapterBuilderLocator.class); }
const mongoose = require('mongoose'); function isRegExValid(v) { return /^https?:\/\/[www]?(.[\w,-]{1,}.?){1,}/.test(v); } const avatarSchemaValidator = [isRegExValid, 'Ссылка на аватар невалидна']; const userSchema = new mongoose.Schema({ name: { type: String, minlength: 2, maxlength: 30, default: 'Алексей', }, about: { type: String, minlength: 2, maxlength: 30, default: 'Разработчик', }, avatar: { type: String, validate: avatarSchemaValidator, default: 'https://pictures.s3.yandex.net/resources/jacques-cousteau_1604399756.png', }, email: { type: String, unique: true, required: true, }, password: { type: String, required: true, select: false, }, }); userSchema.methods.toJSON = function () { const user = this.toObject(); delete user.password; return user; }; module.exports = mongoose.model('user', userSchema);
const fs = require('fs'); const markdownIt = require('markdown-it'); const hljs = require('highlight.js'); const PDFDocument = require('pdfkit'); async function convertMarkdownToHtml(markdownText) { const md = markdownIt({ highlight: function (str, lang) { if (lang && hljs.getLanguage(lang)) { try { return '<pre class="hljs"><code>' + hljs.highlight(str, { language: lang, ignoreIllegals: true }).value + '</code></pre>'; } catch (__) {} } return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'; } }); // Convert Markdown to HTML const htmlContent = md.render(markdownText); // Include custom CSS styles within the HTML content const styledHtmlContent = ` <html> <head> <style> /* Add your custom CSS styles here */ body { font-family: Arial, sans-serif; font-size: 16px; line-height: 1.6; } h1, h2, h3 { color: #333; font-weight: bold; } pre { background-color: #f4f4f4; padding: 10px; border-radius: 5px; } /* Add more styles as needed */ </style> </head> <body> ${htmlContent} </body> </html> `; return styledHtmlContent; } async function convertMarkdownToPDF(markdownText, outputFilePath) { const doc = new PDFDocument(); // Convert Markdown to styled HTML const styledHtmlContent = await convertMarkdownToHtml(markdownText); // Pipe the PDF document to a writable stream const stream = fs.createWriteStream(outputFilePath); doc.pipe(stream); // Add HTML content to the PDF document doc.end(styledHtmlContent); stream.on('finish', () => { console.log(`PDF file created: ${outputFilePath}`); }); } // Example Markdown content const markdownContent = ` # My Markdown Content This is a sample Markdown content that will be converted to PDF. `; // Output file path const outputFilePath = 'markdown_to_pdf.pdf'; // Call the function with Markdown content and output file path convertMarkdownToPDF(markdownContent, outputFilePath);
<?php namespace App\Controller; use App\Projection\NotificationProjection; use App\Projection\NotificationResponseProjection; use Exception; use App\Service\NotificationService; use JMS\Serializer\SerializerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class NotificationController extends AppController { private NotificationService $notificationService; public function __construct(SerializerInterface $serializer, NotificationService $notificationService) { parent::__construct($serializer); $this->notificationService = $notificationService; } #[Route('/notifications/{userId}', name: 'notification', methods: ['GET'])] public function getNotifications(Request $request, int $userId): Response { try { $page = $request->query->get('page') ? $request->query->get('page') : 1; $notifications = $this->notificationService->getNotificationsForUser($userId, $page); return $this->ok(NotificationResponseProjection::fromNotifications( $this->notificationService->getNumberOfNotificationsForUser($userId), $this->notificationService->getNumberOfUnreadNotificationsForUser($userId), NotificationProjection::fromNotifications($notifications))); } catch(Exception $err) { return $this->internalServerError($err->getMessage()); } } #[Route('/notifications/{userId}/read/{notificationId}')] public function setNotificationAsRead(Request $request, int $userId, int $notificationId): Response { try { if ($this->notificationService->markNotificationAsReadByUser($userId, $notificationId)) { return $this->ok(); } return $this->notFound('Could not mark the notification as read.'); } catch(Exception $err) { return $this->internalServerError($err->getMessage()); } } }
import * as React from "react"; import { useEffect, useState } from "react"; import { styled, alpha } from "@mui/material/styles"; import AppBar from "@mui/material/AppBar"; import Box from "@mui/material/Box"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; import InputBase from "@mui/material/InputBase"; import { Avatar } from "@mui/material"; import Button from "@mui/material/Button"; import Modal from "@mui/material/Modal"; import TextField from "@mui/material/TextField"; import axios from "axios"; import { Link } from "react-router-dom"; import Menu from "@mui/material/Menu"; import MenuItem from "@mui/material/MenuItem"; import IconButton from "@mui/material/IconButton"; import { useNavigate, Navigate } from "react-router-dom"; const style = { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width: 400, bgcolor: "background.paper", border: "2px solid #000", boxShadow: 24, p: 4, }; const Search = styled("div")(({ theme }) => ({ position: "relative", borderRadius: theme.shape.borderRadius, backgroundColor: alpha(theme.palette.common.white, 0.15), "&:hover": { backgroundColor: alpha(theme.palette.common.white, 0.25), }, marginLeft: 0, width: "100%", [theme.breakpoints.up("sm")]: { marginLeft: theme.spacing(1), width: "auto", }, })); const StyledInputBase = styled(InputBase)(({ theme }) => ({ color: "inherit", "& .MuiInputBase-input": { padding: theme.spacing(1, 1, 1, 0), // vertical padding + font size from searchIcon paddingLeft: `calc(1em + ${theme.spacing(4)})`, transition: theme.transitions.create("width"), width: "100%", [theme.breakpoints.up("sm")]: { width: "12ch", "&:focus": { width: "20ch", }, }, }, })); export default function SearchAppBar(props) { const isLogged = localStorage.getItem("userToken"); // console.log(isLogged); const { setIsLoggedIn, isLoggedIn } = props; // console.log(isLoggedIn); const navigate = useNavigate(); const [open, setOpen] = React.useState(false); const [log, setLogout] = useState(false); const handleOpen = () => setOpen(true); const handleClose = () => setOpen(false); const [video, setVideo] = React.useState(""); const [cover, setCover] = React.useState(""); const [title, setTitle] = React.useState(""); // avatar menu const logout = () => { localStorage.removeItem("token"); localStorage.removeItem("userToken"); setLogout(true); navigate("/", true); setIsLoggedIn(false); }; const [anchorElUser, setAnchorElUser] = React.useState(null); const handleOpenUserMenu = (event) => { setAnchorElUser(event.currentTarget); }; const handleCloseUserMenu = () => { setAnchorElUser(null); }; // --------------------------- const submitForm = async (e) => { e.preventDefault(); const formData = new FormData(); formData.append("title", title); formData.append("video", video); formData.append("cover", cover); const token = localStorage.getItem("token"); await axios.post("/api/v1/video", formData, { headers: { Authorization: "Bearer " + token, }, }); handleClose(); navigate("/video"); }; return ( <Box sx={{ flexGrow: 1 }}> <AppBar position="static"> <Toolbar> <Typography variant="h4" noWrap component="div" sx={{ flexGrow: 1, display: { xs: "none", sm: "block" } }} > <Link to="/" style={{ textDecoration: "none", color: "white" }}> Streamly </Link> </Typography> {/* {log && <Navigate to="/" replace={true} />} */} {isLogged && ( <> <Search> <StyledInputBase placeholder="Search…" inputProps={{ "aria-label": "search" }} /> </Search> <div> <Button variant="contained" onClick={handleOpen} sx={{ m: 1, bgcolor: "secondary.main" }} > Add New </Button> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Typography id="modal-modal-title" variant="h6" component="h2" > <Box component="form" onSubmit={submitForm} noValidate sx={{ mt: 1 }} > <label>Video Title:</label> <TextField margin="normal" required fullWidth id="title" name="title" autoFocus onChange={(e) => setTitle(e.target.value)} /> <label>Select Video:</label> <TextField margin="normal" required fullWidth id="video" name="video" autoFocus type="file" onChange={(e) => setVideo(e.target.files[0])} /> <label>Select Cover Image:</label> <TextField autoFocus margin="normal" required fullWidth name="coverImage" type="file" id="coverImage" onChange={(e) => setCover(e.target.files[0])} /> <Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} > Upload </Button> </Box> </Typography> </Box> </Modal> </div> <Box sx={{ flexGrow: 0 }}> <IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}> <Avatar alt="Remy Sharp" /> </IconButton> <Menu sx={{ mt: "45px" }} id="menu-appbar" anchorEl={anchorElUser} anchorOrigin={{ vertical: "top", horizontal: "right", }} keepMounted transformOrigin={{ vertical: "top", horizontal: "right", }} open={Boolean(anchorElUser)} onClose={handleCloseUserMenu} > <MenuItem onClick={handleCloseUserMenu}> <Typography textAlign="center" onClick={logout}> Logout </Typography> </MenuItem> </Menu> </Box> </> )} </Toolbar> </AppBar> </Box> ); }
import { Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Step, StepContent, StepLabel, Stepper, TextField, Typography, } from '@mui/material'; import { useState } from 'react'; import { BACKEND_URL } from 'url'; export default function RemoteCreateDialog({ open, onClose }) { const [remoteName, setRemoteName] = useState(''); const [remoteType, setRemoteType] = useState('drive'); const [isLoading, setIsLoading] = useState(false); const handleSubmit = async () => { setIsLoading(true); try { const response = await fetch(`${BACKEND_URL}/create_config`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ remote_name: remoteName, remote_type: remoteType }), }); if (!response.ok) { const data = await response.json(); throw new Error(data.message || 'Failed to create remote.'); } onClose(); alert(`Remote ${remoteName} created successfully!`); } catch (error) { console.error('Error creating remote:', error); } setIsLoading(false); }; return ( <Dialog maxWidth="sm" open={open} onClose={onClose} data-testid="remote-create-dialog" > <DialogTitle>Create New Remote</DialogTitle> <DialogContent> <Stepper orientation="vertical"> <Step expanded active> <StepLabel>Enter Remote Details</StepLabel> <StepContent> <TextField data-testid="remote-name-input" required label="Remote Name" value={remoteName} onChange={(e) => setRemoteName(e.target.value)} /> <TextField data-testid="remote-type-input" select label="Remote Type" value={remoteType} onChange={(e) => setRemoteType(e.target.value)} > <MenuItem value="drive">Google Drive</MenuItem> <MenuItem value="onedrive">OneDrive</MenuItem> </TextField> </StepContent> </Step> <Step expanded active> <StepLabel>Create Remote</StepLabel> <StepContent> <Typography> Click the button below to create the remote using RClone. </Typography> <Button data-testid="create-remote-button" variant="contained" color="primary" onClick={handleSubmit} disabled={isLoading} > {isLoading ? 'Creating Remote...' : 'Create Remote'} </Button> </StepContent> </Step> </Stepper> </DialogContent> <DialogActions> <Button onClick={onClose} data-testid="close-button"> Close </Button> </DialogActions> </Dialog> ); }
<html> <head> <title> Mole Cave Testing </title> <style> table{ width: 50%; height: 50%; text-align: center; } table, tr, td{ border: 1px solid black; border-collapse: collapse; /* font-weight: "bold"; */ } </style> </head> <body> <label>Start ...</label> <input type="button" id="startButton" value="click" onclick=main()> <table id="map"></table> <script> let N = 5; let depth = 0; dx = [1, 0, -1, 0]; dy = [0, 1, 0, -1]; g = [0, 0]; let map = [ ['#', 'S', '#', '#', '#'], ['#', '.', '.', '.', '#'], ['#', '.', '#', '.', '#'], ['#', '.', '.', '.', '.'], ['#', '#', '#', 'G', '#'] ] let visit = Array.from(Array(N), () => Array(N).fill(0)); let queue = []; function is_in_map(y, x){ if( (x >= 0 && x < N) && (y >=0 && y < N) ){ return true; } return false; }; function find_short_path(y, x, d){ queue.push([y, x, d]); visit[y][x] = d; while(queue.length != 0){ let pos = queue.shift(); for(let i = 0; i < 4; i++){ let ny = pos[0] + dy[i]; let nx = pos[1] + dx[i]; let nd = pos[2] + 1; if( (is_in_map(ny, nx) == true) && (map[ny][nx] == '.') && (visit[ny][nx] == 0) ){ visit[ny][nx] = nd; queue.push([ny, nx, nd]); delayedDisplayMapUI(ny, nx, nd, "yellow"); } } } } function main(){ for(let y = 0; y < N; y++){ for(let x = 0; x < N; x++){ if(map[y][x] == 'G'){ map[y][x] = '.'; g = [y, x]; } } } for(let y = 0; y < N; y++){ for(let x = 0; x < N; x++){ if(map[y][x] == 'S'){ find_short_path(y, x, 0); } } } if(visit[g[0]][g[1]] == 0){ console.log(-1); } else{ console.log(visit[g[0]][g[1]]); } } // for UI part // build initial map table on browser display function buildInitMapUI(){ let table = document.getElementById("map"); for(let y = 0; y < N; y++){ let newRow = document.createElement("tr"); for(let x = 0; x < N; x++){ let newCell = document.createElement("td"); let newTextNode = document.createTextNode(map[y][x]); newCell.style.fontWeight = "bold"; newCell.appendChild(newTextNode); newRow.appendChild(newCell); } table.appendChild(newRow); } document.body.appendChild(table); } function updateColorMapUI(y, x, value, color){ let table = document.getElementById("map"); table.rows[y].cells[x].innerHTML = value.toString(); table.rows[y].cells[x].style.backgroundColor = color; } let i = 0; function delayedDisplayMapUI(y, x, value, color){ let timerId = setInterval(updateColorMapUI, 1*i, y, x, value, color); i += 1; } window.onload = function(){ //console.log('start onload function ... '); buildInitMapUI(); } </script> </body> </html>
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const httpStatus_1 = require("../../../types/httpStatus"); const appError_1 = __importDefault(require("../../../utils/appError")); const adminLogin = (email, password, adminRepository, authService) => __awaiter(void 0, void 0, void 0, function* () { const admin = yield adminRepository.getAdminByEmail(email); if (!admin) { throw new appError_1.default('invalid credentials', httpStatus_1.HttpStatus.UNAUTHORIZED); } const isPasswordCorrect = yield authService.comparePassword(password, admin.password); if (!isPasswordCorrect) { throw new appError_1.default('invalid password', httpStatus_1.HttpStatus.UNAUTHORIZED); } const token = authService.generateToken({ Id: admin._id, email: admin.email, role: 'admin' }); return token; }); exports.default = adminLogin;
# NLW Expert - Trilha Python ## Sobre o repositório Este repositório é destinado ao armazenamento de uma aplicação Back-End construída em Python durante o evento nlw expert da RocketSeat. O projeto consiste em uma aplicação capaz de gerar código de barras com o python-barcode. Este evento foi muito importante para conhecer mais das possibilidades com a linguagem python e sua sintaxe, bem como o Flask (framework), preparação de ambiente e boas práticas de projeto com Virtualenv, Pylint e versionamento de código usando o pre-commit e também testes unitários utilizando o Pytest. # Como executar/visualizar o projeto Pré-requisitos: Possuir o Python 3 em sua máquina e de preferência utilizar ambientes virtuais (venv), utilizar Postman ou Insomnia para criar as tags. O principal arquivo a ser executado é o run.py, você pode criar sua requisição para gerar o código de barras entrando na rota usando algum API Client (Postman/Insomnia...) Todas as dependências utilizadas e suas versões estão especificadas no arquivo Requirements.txt ```bash # clonar repositório: git clone https://github.com/guuisouza/nlw_python_logistic.git # entrar na pasta no vscode: cd nlw_python_logistic # instalar a biblioteca virtualenv (20.25) pip3 install virtualenv # criar o ambiente virtual py -m venv .venv # ativar o ambiente virtual - obs: No Linux o caminho é diferente .venv\Scripts\activate # instalar o flask pip3 install Flask # instalar o barcode e pillow (para imagens) pip3 install python-barcode pip3 install pillow # instalar o cerberus para validação de entrada pip3 install Cerberus ``` ## Pacotes opcionais ```bash # OPCIONAL - instalar o pylint - (após a instalação baixe também a extensão pylint do vscode reinicie o editor) pip3 install pylint # OPCIONAL - instalar o pre-commit pip3 install pre-commit # OPCIONAL - instalar o pytest para testes pip3 install pytest ``` # Contato Guilherme Dilio de Souza https://www.linkedin.com/in/guilherme-souza-579267250/
import 'package:flutter/material.dart'; import 'package:flutter1/sharedpreference_login/sp_home.dart'; import 'package:shared_preferences/shared_preferences.dart'; class MyLoginPage extends StatefulWidget { const MyLoginPage({super.key}); @override State<MyLoginPage> createState() => _MyLoginPageState(); } class _MyLoginPageState extends State<MyLoginPage> { final username_controller = TextEditingController(); final password_controller = TextEditingController(); late SharedPreferences logindata; late bool newuser; @override void initState() { // TODO: implement initState super.initState(); check_if_already_login(); } void check_if_already_login() async { logindata = await SharedPreferences.getInstance(); newuser = (logindata.getBool('login') ?? true); print(newuser); if (newuser == false) { Navigator.pushReplacement( context, new MaterialPageRoute(builder: (context) => MyDash())); } } @override void dispose() { username_controller.dispose(); password_controller.dispose(); // TODO: implement dispose super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(" Shared Preferences"), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( "Login Form", style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), ), Padding( padding: const EdgeInsets.all(15.0), child: TextField( controller: username_controller, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'username', ), ), ), Padding( padding: const EdgeInsets.all(15.0), child: TextField( controller: password_controller, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), ), ), ElevatedButton( onPressed: () { String username = username_controller.text; String password = password_controller.text; if (username != '' && password != '') { print('Successfull'); logindata.setBool('login', false); logindata.setString('username', username); Navigator.push(context, MaterialPageRoute(builder: (context) => MyDash())); } }, child: Text("Log-In"), ) ], ), ), ); } }
/* NAME: TMachine.cpp DESCRIPTION: NMachine tests. COPYRIGHT: Copyright (c) 2006-2021, refNum Software All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ___________________________________________________________________________ */ // Includes //----------------------------------------------------------------------------- // Nano #include "NMachine.h" #include "NString.h" #include "NTestFixture.h" // Test Fixture //----------------------------------------------------------------------------- NANO_FIXTURE(TMachine){}; // Test Case //----------------------------------------------------------------------------- NANO_TEST(TMachine, "GetCores") { // Perform the test size_t numLogical = NMachine::GetCores(); size_t numPhysical = NMachine::GetCores(NCoreType::Physical); REQUIRE(numLogical >= 1); REQUIRE(numPhysical >= 1); REQUIRE(numLogical >= numPhysical); } // Test Case //----------------------------------------------------------------------------- NANO_TEST(TMachine, "GetMemory") { // Perform the test float64_t sizeBytes = NMachine::GetMemory(); REQUIRE(sizeBytes > 0.0); float64_t sizeGB = NMachine::GetMemory(kNGibibyte); REQUIRE(sizeGB > 0.0); REQUIRE(uint64_t(sizeGB) == uint64_t(sizeBytes / kNGibibyte)); } // Test Case //----------------------------------------------------------------------------- NANO_TEST(TMachine, "GetCPUSpeed") { // Perform the test float64_t speedHertz = NMachine::GetCPUSpeed(); REQUIRE(speedHertz > 0.0); float64_t speedGhz = NMachine::GetCPUSpeed(kNGigahertz); REQUIRE(speedGhz > 0.0); REQUIRE(uint64_t(speedGhz) == uint64_t(speedHertz / kNGigahertz)); } // Test Case //----------------------------------------------------------------------------- NANO_TEST(TMachine, "GetCPUName") { // Perform the test NString theName = NMachine::GetCPUName(); REQUIRE((!theName.IsEmpty() && theName != "Unknown")); } // Test Case //----------------------------------------------------------------------------- NANO_TEST(TMachine, "GetCPUVendor") { // Perform the test NString theVendor = NMachine::GetCPUVendor(); REQUIRE((!theVendor.IsEmpty() && theVendor != "Unknown")); } // Test Case //----------------------------------------------------------------------------- NANO_TEST(TMachine, "GetCPUArchitecture") { // Perform the test NString theArch = NMachine::GetCPUArchitecture(); REQUIRE((theArch == "arm64" || theArch == "arm" || theArch == "x86_64" || theArch == "x86")); }
from datetime import date from typing import Optional from pydantic import BaseModel, constr, ValidationError, validator, field_validator, Field class User(BaseModel): last_name: str = Field(min_length=3, default=None, max_length=40) first_name: str = Field(min_length=3, default=None, max_length=40) middle_name: str | None = Field(default=None) position_id: int hire_accept: date @field_validator('last_name', 'first_name', 'middle_name') @classmethod def validate_no_digits(cls, value): if any(char.isdigit() or char.isspace() or char in "!@#$%^&*()-_=+{}[]|;:'\",.<>?/" for char in value): raise ValueError("Недопустимые символы в имени, фамилии или отчестве") return value class Position(BaseModel): position_name: str = Field(default=None) @field_validator('position_name') @classmethod def validate_no_digits(cls, value): if any(char.isdigit() or char.isspace() or char in "!@#$%^&*()-_=+{}[]|;:'\",.<>?/" for char in value): raise ValueError("Недопустимые символы в имени, фамилии или отчестве") return value
/* * Blink 3 Blink LED1 with a 200ms cycle (5Hz) Utilizing the Timer1 rather than delay functions. */ extern "C" void __attribute__((interrupt(),nomips16)) Timer1Handler(void); int pin = 33; // LED pin int frequency = 5; // Hz int PRS = 5; //************************************************************************ void EnableTimer(void) { T1CON = TACON_PS_256; // izbor preskalera TMR1 = 0; // Obrisi Timer1 counter PR1 = ((__PIC32_pbClk / 2) / 256 / frequency); // 80 MHz je CPU takt // Serial.println(PR1); // inicijalizacija prekida setIntVector(_TIMER_1_VECTOR, Timer1Handler); clearIntFlag(_TIMER_1_IRQ); setIntPriority(_TIMER_1_VECTOR, _T1_IPL_IPC, _T1_SPL_IPC); setIntEnable(_TIMER_1_IRQ); T1CONSET = TACON_ON; // pusti ga da broji } void disableTimer(void) { clearIntEnable(_TIMER_1_IRQ); T1CON = 0; T1CONCLR = TACON_ON; // zaustavi brojac clearIntVector(_TIMER_1_VECTOR); } //* we need the extern C so that the interrupt handler names dont get mangled by C++ extern "C" { void __attribute__((interrupt(),nomips16)) Timer1Handler(void) { static int count200 = 0; static int count = 0; count++; if(count == 5) { digitalWrite(pin, !digitalRead(pin)); count200++; if (count200 == 200) disableTimer(); count = 0; } // clear the interrupt flag clearIntFlag(_TIMER_1_IRQ); Serial.println(TMR1); } }; //* extern "C" void pause() { T1CONCLR = 1<<15; } void unpause() { T1CONSET = 1<<15; } void setup() { Serial.begin(9600); pinMode(pin, OUTPUT); // Init the timer. EnableTimer(); } void loop() { if(digitalRead(7)) unpause(); else pause(); }
<!DOCTYPE html> <html> <head> <title>MembersOnly</title> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"> <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script> </head> <body> <header class="header"> <div class="container"> <nav class="level"> <div class="level-left"> <div class="level-item title is-2"> Members Only Blog </div> </div> <div class="level-right"> <p class="level-item"> <%= link_to("View All Posts", root_path, :class => "button is-dark is-outlined") %> </p> <% if user_signed_in? %> <p class="level-item"> <%= link_to("Create New Post", new_post_path, :class => "button is-dark is-outlined") %> </p> <p class="level-item"> <%= link_to("Logout", destroy_user_session_path, method: :delete, :class => "button is-dark is-outlined") %> </p> <% else %> <p class="level-item"> <%= link_to("Login", new_user_session_path, :class => "button is-dark is-outlined") %> </p> <p class="level-item"> <%= link_to("Sign Up", new_user_registration_path, :class => "button is-dark is-outlined") %> </p> <% end %> </div> </nav> </div> </header> <section class="section"> <div class="container "> <div class="container has-text-centered"> <% if notice %> <p class="alert alert-success"><%= notice %></p> <% end %> <% if alert %> <p class="alert alert-danger"><%= alert %></p> <% end %> <br/> </div> <%= yield %> </div> </section> <footer class="footer"> <div class="container"> Created by Jack Trowbridge </div> </footer> </body> </html>
import { useEffect, useRef } from 'react'; import { isFunction } from '../utils'; const useUnmount = (fn: () => void) => { const ref = useRef(fn); if (process.env.NODE_ENV === 'development') { if (!isFunction(fn)) { console.error( `useUnmount expected parameter is a function, got ${typeof fn}` ); } } ref.current = fn; useEffect(() => { // 卸载钩子 return () => { ref.current(); }; }, []); }; export default useUnmount;
import React, { useState, useEffect } from "react"; import { useHistory } from "react-router-dom"; import { Link } from "react-router-dom"; import "../components/ticketList.css" import 'bootstrap/dist/css/bootstrap.css'; import {withRouter} from 'react-router-dom'; import Moment from 'react-moment' import dayjs from 'dayjs'; import FilterBar from "../components/filterBar" var isSameOrAfter = require('dayjs/plugin/isSameOrAfter'); var isSameOrBefore = require('dayjs/plugin/isSameOrBefore'); dayjs.extend(isSameOrAfter); dayjs.extend(isSameOrBefore); require("es6-promise").polyfill() require("isomorphic-fetch") const AllTicket = () => { let history = useHistory(); const [tickets, setTickets] = useState([]); const [filterTickets, setFilterTickets] = useState([]); useEffect(() => { fetch("/ticket") .then(response => response.json()) .then(json => setTickets(json)) }, []) useEffect(() => { fetch("/ticket") .then(response => response.json()) .then(json => setFilterTickets(json)) }, []) const deleteTicket = (id) => { const delTicket = { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, }; return new Promise(function (resolve, reject) { fetch(`/ticket/${id}`, delTicket) .then(res => res.json()) .then(result => { if (result) { console.log(result); resolve(result); } }) }); } const generateFilterDataForDropdown = () => { return [...new Set(tickets.map((ticket) => ticket.status))]; }; const handleFilterName = (name) => { const filteredData = tickets.filter((ticket) => { const fullName = `${ticket.firstName} ${ticket.lastName}`; if(fullName.toLowerCase().includes(name.toLowerCase())) { return ticket; } }); setFilterTickets(filteredData); } const handleFilterStatus = (status) => { const filteredData = tickets.filter((ticket) => { if(ticket.status === status) { return ticket; } }); setFilterTickets(filteredData); } const handleFilterDate = (date, field) => { const filteredData = tickets.filter((ticket) => { if(field === 'from' && dayjs(ticket.createOn).isSameOrAfter(dayjs(date))) { return ticket; } if(field === 'to' && dayjs(ticket.createOn).isSameOrBefore(dayjs(date))) { return ticket; } }); setFilterTickets(filteredData); } return ( <> <div className="home"> <div class="container"> <div class="row align-items-center my-5"> <div class="col-lg-7"> </div> <div class="col-lg-5"> <h1 class="font-weight-light header">All Tickets</h1> <FilterBar statuses={generateFilterDataForDropdown()} onNameFilter={handleFilterName} onStatusFilter={handleFilterStatus} onDateFilter={handleFilterDate} /> <table className="table table-striped ticketTable"> <thead> <tr> <th class="col-md-4">Ticket Number</th> <th class="col-md-4">Ticket Status</th> <th class="col-md-4">Requester's ID</th> <th class="col-md-4">Requested By</th> {/* <th class="col-md-4">Requester's Email</th> */} <th class="col-md-4">Ticket Subject</th> <th class="col-md-4">Short Description</th> {/* <th class="col-md-4">Assigned To</th> */} <th class="col-md-4">Date Created On</th> <th class="col-md-4"></th> <th class="col-md-4"></th> <th class="col-md-4"></th> </tr> </thead> <tbody> {filterTickets.map((ticket) => ( <tr> <th class="col-md-3">{ticket.ticketNumber}</th> <th class="col-md-3">{ticket.status}</th> <th class="col-md-3">{ticket.studentID}</th> <td class="col-md-3">{ticket.firstName} {ticket.lastName}</td> {/* <td class="col-md-3">{ticket.email}</td> */} <td class="col-md-2">{ticket.subject}</td> <td class="col-md-3">{ticket.description.slice(0, 100)}</td> {/* <td class="col-md-3"><img src={ticket.file} /></td> */} <td class="col-md-3"><Moment format="YYYY/MM/DD">{ticket.createOn}</Moment></td> <td class="col-md-3"><button class="btn btn-danger" type="button" key={ticket._id} onClick={()=> {if(window.confirm("Are you sure? If you already got a solution for this ticket, please consider to close it first! ")){deleteTicket(ticket._id); window.location.reload(false);} }}>Delete</button></td> <td class="col-md-3"><button className="btn btn-primary" key={ticket._id} onClick={() => { history.push(`/TicketLogHistory/${ticket._id}`) }}>View</button></td> <td class="col-md-3"><button className="btn btn-warning" disabled={ticket.status === "Closed"} key={ticket._id} onClick={() => { history.push(`/ClosingTicket/${ticket._id}`) }}>Close</button></td> </tr> ))} </tbody> </table> </div> </div> </div> </div> </> ); } export default withRouter(AllTicket);
package NLB import ( "encoding/json" "fmt" "log" "time" "github.com/Appkube-awsx/awsx-common/authenticate" "github.com/Appkube-awsx/awsx-common/awsclient" "github.com/Appkube-awsx/awsx-common/cmdb" "github.com/Appkube-awsx/awsx-common/config" "github.com/Appkube-awsx/awsx-common/model" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/cloudwatch" "github.com/spf13/cobra" ) type NewFlowCountTLSData struct { NewFlowCountTLS []struct { Timestamp time.Time Value float64 } `json:"NewFlowCountTLS"` } var AwsxNLBNewFlowCountTLSCmd = &cobra.Command{ Use: "new_flow_count_tls_panel", Short: "Get NLB new flow count TLS metrics data", Long: `Command to get NLB new flow count TLS metrics data`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Running from child command..") var authFlag, clientAuth, err = authenticate.AuthenticateCommand(cmd) if err != nil { log.Printf("Error during authentication: %v\n", err) err := cmd.Help() if err != nil { return } return } if authFlag { responseType, _ := cmd.PersistentFlags().GetString("responseType") jsonResp, cloudwatchMetricResp, err := GetNLBNewFlowCountTLSPanel(cmd, clientAuth, nil) if err != nil { log.Println("Error getting NLB new flow count TLS: ", err) return } if responseType == "frame" { fmt.Println(cloudwatchMetricResp) } else { // Default case. It prints JSON fmt.Println(jsonResp) } } }, } func GetNLBNewFlowCountTLSPanel(cmd *cobra.Command, clientAuth *model.Auth, cloudWatchClient *cloudwatch.CloudWatch) (string, map[string]*cloudwatch.GetMetricDataOutput, error) { elementId, _ := cmd.PersistentFlags().GetString("elementId") elementType, _ := cmd.PersistentFlags().GetString("elementType") cmdbApiUrl, _ := cmd.PersistentFlags().GetString("cmdbApiUrl") instanceId, _ := cmd.PersistentFlags().GetString("instanceId") if elementId != "" { log.Println("getting cloud-element data from cmdb") apiUrl := cmdbApiUrl if cmdbApiUrl == "" { log.Println("using default cmdb url") apiUrl = config.CmdbUrl } log.Println("cmdb url: " + apiUrl) cmdbData, err := cmdb.GetCloudElementData(apiUrl, elementId) if err != nil { return "", nil, err } instanceId = cmdbData.InstanceId } startTimeStr, _ := cmd.PersistentFlags().GetString("startTime") endTimeStr, _ := cmd.PersistentFlags().GetString("endTime") var startTime, endTime *time.Time if startTimeStr != "" { parsedStartTime, err := time.Parse(time.RFC3339, startTimeStr) if err != nil { log.Printf("Error parsing start time: %v", err) return "", nil, err } startTime = &parsedStartTime } else { defaultStartTime := time.Now().Add(-5 * time.Minute) startTime = &defaultStartTime } if endTimeStr != "" { parsedEndTime, err := time.Parse(time.RFC3339, endTimeStr) if err != nil { log.Printf("Error parsing end time: %v", err) return "", nil, err } endTime = &parsedEndTime } else { defaultEndTime := time.Now() endTime = &defaultEndTime } log.Printf("StartTime: %v, EndTime: %v", startTime, endTime) cloudwatchMetricData := map[string]*cloudwatch.GetMetricDataOutput{} // Fetch raw data rawData, err := GetNLBNewFlowCountTLSMetricData(clientAuth, instanceId, elementType, startTime, endTime, "Sum", cloudWatchClient) if err != nil { log.Println("Error in getting NLB new flow count TLS data: ", err) return "", nil, err } cloudwatchMetricData["NewFlowCountTLS"] = rawData result := processNLBNewFlowCountTLSRawData(rawData) jsonString, err := json.Marshal(result) if err != nil { log.Println("Error in marshalling json in string: ", err) return "", nil, err } return string(jsonString), cloudwatchMetricData, nil } func GetNLBNewFlowCountTLSMetricData(clientAuth *model.Auth, instanceId, elementType string, startTime, endTime *time.Time, statistic string, cloudWatchClient *cloudwatch.CloudWatch) (*cloudwatch.GetMetricDataOutput, error) { log.Printf("Getting metric data for NLB %s from %v to %v %v", instanceId, elementType, startTime, endTime) elmType := "AWS/NetworkELB" input := &cloudwatch.GetMetricDataInput{ EndTime: endTime, StartTime: startTime, MetricDataQueries: []*cloudwatch.MetricDataQuery{ { Id: aws.String("m1"), MetricStat: &cloudwatch.MetricStat{ Metric: &cloudwatch.Metric{ Dimensions: []*cloudwatch.Dimension{ { Name: aws.String("LoadBalancer"), Value: aws.String(instanceId), }, }, MetricName: aws.String("NewFlowCount_TLS"), Namespace: aws.String(elmType), }, Period: aws.Int64(60), Stat: aws.String("Sum"), }, }, }, } if cloudWatchClient == nil { cloudWatchClient = awsclient.GetClient(*clientAuth, awsclient.CLOUDWATCH).(*cloudwatch.CloudWatch) } result, err := cloudWatchClient.GetMetricData(input) if err != nil { return nil, err } return result, nil } func processNLBNewFlowCountTLSRawData(result *cloudwatch.GetMetricDataOutput) NewFlowCountTLSData { var rawData NewFlowCountTLSData rawData.NewFlowCountTLS = make([]struct { Timestamp time.Time Value float64 }, len(result.MetricDataResults[0].Timestamps)) for i, timestamp := range result.MetricDataResults[0].Timestamps { rawData.NewFlowCountTLS[i].Timestamp = *timestamp rawData.NewFlowCountTLS[i].Value = *result.MetricDataResults[0].Values[i] } return rawData } func init() { AwsxNLBNewFlowCountTLSCmd.PersistentFlags().String("instanceId", "", "instanceId") AwsxNLBNewFlowCountTLSCmd.PersistentFlags().String("startTime", "", "start time") AwsxNLBNewFlowCountTLSCmd.PersistentFlags().String("endTime", "", "end time") AwsxNLBNewFlowCountTLSCmd.PersistentFlags().String("responseType", "", "response type. json/frame") }
import NextAuth, {type DefaultSession } from "next-auth" import authConfig from "@/auth.config" import { PrismaAdapter } from "@auth/prisma-adapter" import db from "@/lib/db" import { getUserById } from "@/lib/data/user" import { UserRole } from "@prisma/client" import { getTwoFactorConfirmationByUserId } from "@/lib/data/two-factor-confirmation" import { getAccountByUserId } from "./lib/data/account" //any new fields to add in the user session export type ExtendedUser = DefaultSession["user"] & { role: UserRole isTwoFactorEnabled: boolean isOAuth: boolean } declare module "next-auth" { interface Session { user: ExtendedUser } } export const { handlers: { GET, POST }, auth, signIn, signOut, } = NextAuth({ pages: { signIn: "/login", error: "/error" }, adapter: PrismaAdapter(db), session: { strategy: "jwt" }, callbacks: { async signIn({ user, account }) { // allow OAuth without email verification if (account?.provider !== "credentials") return true const existingUser = await getUserById(user.id as string); //prevent sign in without email verification if(!existingUser?.emailVerified) return false if(existingUser?.isTwoFactorEnabled) { const twoFactorConfirmation = await getTwoFactorConfirmationByUserId(existingUser?.id) if(!twoFactorConfirmation) return false //delete two factor authentication for login await db.twoFactorConfirmation.delete({ where: {id: twoFactorConfirmation.id} }) return true } return true }, async jwt({ token }) { if(!token.sub) return token const existingUser = await getUserById(token.sub) if(!existingUser) return token const existingAccount = await getAccountByUserId(existingUser.id) token.name = existingUser.name token.email = existingUser.email token.role = existingUser.role token.isOAuth = !!existingAccount token.isTwoFactorEnabled = existingUser.isTwoFactorEnabled return token }, async session({ token, session }) { if(token.sub && session.user) { session.user.id = token.sub } if(token.role && session.user) { session.user.role = token.role as UserRole } if (session.user) { session.user.isTwoFactorEnabled = token.isTwoFactorEnabled as boolean; } if (session.user) { session.user.name = token.name; session.user.email = token.email as string; session.user.isOAuth = token.isOAuth as boolean; } return session } }, events: { async linkAccount({ user }) { await db.user.update({ where: { id: user.id }, data: { emailVerified: new Date() } }) } }, ...authConfig, })
package com.minwan.weatherforecast import com.minwan.weatherforecast.helper.TimeHelper import org.junit.* class TimeHelperUnitTest { @Test fun convertEpochTimeToDisplayText_isCorrect() { val epochTime = 1629028800L val displayTime = TimeHelper.convertEpochTimeToDisplayText(epochTime) Assert.assertEquals("Sun, 15 Aug 2021", displayTime) } @Test fun convertEpochTimeToDisplayText_withZero_isFailed() { val epochTime = 0L val displayTime = TimeHelper.convertEpochTimeToDisplayText(epochTime) Assert.assertNull(displayTime) } @Test fun convertEpochTimeToDisplayText_withNegativeNumber_isFailed() { val epochTime = -1L val displayTime = TimeHelper.convertEpochTimeToDisplayText(epochTime) Assert.assertNull(displayTime) } @Test fun convertEpochTimeToDisplayText_withEnormousTimeNumber_isFailed() { val epochTime = 1629028800000L val displayTime = TimeHelper.convertEpochTimeToDisplayText(epochTime) Assert.assertEquals("Thu, 14 Nov 53591", displayTime) } }
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; interface UserState { currentUser: UserData | null; isLoading: boolean; isError: boolean; error: string | null; } interface UserData { _id: string; name: string; email: string; } const initialState: UserState = { currentUser: null, isLoading: false, isError: false, error: null, }; const userSlice = createSlice({ name: "user", initialState, reducers: { signInStart: (state) => { state.isLoading = true; }, signInSuccess: (state, action: PayloadAction<UserData>) => { state.currentUser = action.payload; state.isLoading = false; state.error = null; }, signInFailure: (state, action: PayloadAction<string>) => { state.error = action.payload; state.isLoading = false; }, signOutUserStart: (state) => { state.isLoading = true; }, userAdded: (state, action: PayloadAction<UserData>) => { state.currentUser = action.payload; }, removeUser: (state) => { state.currentUser = null; }, signOutUserSuccess: (state) => { state.currentUser = null; state.isLoading = false; state.error = null; }, signOutUserFailure: (state, action: PayloadAction<string>) => { state.error = action.payload; state.isLoading = false; }, deleteUserStart: (state) => { state.isLoading = true; }, deleteUserSuccess: (state) => { state.currentUser = null; state.isLoading = false; state.error = null; }, deleteUserFailure: (state, action: PayloadAction<string>) => { state.error = action.payload; state.isLoading = false; }, }, }); export const { signInStart, signInSuccess, signInFailure, signOutUserStart, signOutUserSuccess, signOutUserFailure, deleteUserStart, deleteUserSuccess, deleteUserFailure, userAdded, removeUser, } = userSlice.actions; export default userSlice.reducer;
import { Logger } from 'winston'; import { AxiosInstance } from 'axios'; import { isNumber } from 'class-validator'; import { MissingDataException } from '@zro/common'; import { JdpiErrorTypes, JdpiFormatQrCode } from '@zro/jdpi/domain'; import { PersonType } from '@zro/users/domain'; import { CreateQrCodeDynamicDueDatePixPaymentPspRequest, CreateQrCodeDynamicDueDatePixPaymentPspResponse, OfflinePixPaymentPspException, PixPaymentGateway, PixPaymentPspException, } from '@zro/pix-payments/application'; import { JdpiAuthGateway, Sanitize, JDPI_SERVICES, ZROBANK_OPEN_BANKING_SERVICES, } from '@zro/jdpi/infrastructure'; interface JdpiCreateQrCodeDynamicDueDatePixPaymentRequest { formato: JdpiFormatQrCode; chave: string; codigoCategoria?: string; cpfRecebedor?: string; cnpjRecebedor?: string; nomeRecebedor: string; nomeFantasiaRecebedor?: string; logradouroRecebedor: string; cidade: string; uf: string; cep: string; solicitacaoPagador?: string; cpfPagador?: string; cnpjPagador?: string; nomePagador: string; valorOriginal?: number; abatimento?: number; desconto?: number; juros?: number; multa?: number; valorFinal: number; dtVenc: string; diasAposVenc: number; idConciliacaoRecebedor: string; dadosAdicionais?: { nome: string; valor: string; }[]; reutilizavel?: boolean; urlPayloadJson: string; } interface JdpiCreateQrCodeDynamicDueDatePixPaymentResponse { idDocumento: string; imagemQrCodeInBase64?: string; payloadBase64?: string; } export class JdpiCreateQrCodeDynamicDueDatePixPaymentPspGateway implements Pick<PixPaymentGateway, 'createQrCodeDynamicDueDate'> { constructor( private logger: Logger, private axios: AxiosInstance, private pspOpenBankingBaseUrl: string, ) { this.logger = logger.child({ context: JdpiCreateQrCodeDynamicDueDatePixPaymentPspGateway.name, }); } async createQrCodeDynamicDueDate( request: CreateQrCodeDynamicDueDatePixPaymentPspRequest, ): Promise<CreateQrCodeDynamicDueDatePixPaymentPspResponse> { // Data input check if (!request) { throw new MissingDataException(['Message']); } const payload: JdpiCreateQrCodeDynamicDueDatePixPaymentRequest = { formato: JdpiFormatQrCode.PAYLOAD, idConciliacaoRecebedor: Sanitize.txId(request.txId), chave: request.key, ...(request.recipientPersonType === PersonType.NATURAL_PERSON ? { cpfRecebedor: Sanitize.document(request.recipientDocument) } : { cnpjRecebedor: Sanitize.document(request.recipientDocument) }), nomeRecebedor: Sanitize.fullName(request.recipientName, 25), logradouroRecebedor: Sanitize.description(request.recipientAddress), cidade: Sanitize.fullName(request.recipientCity, 15), uf: Sanitize.description(request.recipientFeredativeUnit), cep: Sanitize.description(request.recipientZipCode), ...(request.payerRequest && { solicitacaoPagador: Sanitize.description(request.payerRequest), }), ...(request.payerPersonType === PersonType.NATURAL_PERSON ? { cpfPagador: Sanitize.document(request.payerDocument) } : { cnpjPagador: Sanitize.document(request.payerDocument) }), nomePagador: Sanitize.fullName(request.payerName, 25), valorOriginal: Sanitize.parseValue(request.documentValue), ...(request.discountValue && { desconto: Sanitize.parseValue(request.discountValue), }), ...(isNumber(request.fineValue) && { multa: Sanitize.parseValue(request.fineValue), }), valorFinal: Sanitize.parseValue(request.documentValue), dtVenc: Sanitize.formatToYearMonthDay(request.dueDate), diasAposVenc: !request.expirationDate ? 0 // Expires at due date. : Sanitize.getDiffDaysBetweenDates( request.dueDate, request.expirationDate, ), ...(request.description && { dadosAdicionais: [ { nome: 'Informação adicional', valor: Sanitize.description(request.description), }, ], }), urlPayloadJson: `${ this.pspOpenBankingBaseUrl }/${ZROBANK_OPEN_BANKING_SERVICES.DYNAMIC_QR_CODE.GET_JWS_DUE_DATE( request.qrCodeDynamicId, )}`, }; const headers = { Authorization: await JdpiAuthGateway.getAccessToken(this.logger), }; this.logger.info('Request payload.', { payload }); try { const response = await this.axios.post<JdpiCreateQrCodeDynamicDueDatePixPaymentResponse>( JDPI_SERVICES.PIX_PAYMENT.QR_CODE_DYNAMIC_DUE_DATE.CREATE, payload, { headers }, ); this.logger.info('Response found.', { data: response.data }); return { emv: Sanitize.decodeBase64(response.data.payloadBase64), paymentLinkUrl: payload.urlPayloadJson, externalId: response.data.idDocumento, payloadJws: null, }; } catch (error) { this.logger.error('ERROR Jdpi request.', { error: error.isAxiosError ? error.message : error, }); if (error.response?.data) { this.logger.error('ERROR Jdpi response data.', { error: error.response.data, }); const { codigo } = error.response.data; switch (codigo) { case JdpiErrorTypes.INTERNAL_SERVER_ERROR: case JdpiErrorTypes.SERVICE_UNAVAILABLE: throw new OfflinePixPaymentPspException(error); default: // AuthorizationError, InternalServerError } } this.logger.error('Unexpected Jdpi gateway error', { error: error.isAxiosError ? error.message : error, request: error.config, response: error.response?.data ?? error.response ?? error, }); throw new PixPaymentPspException(error); } } }
import * as React from 'react'; import Stack from '@mui/material/Stack'; import Snackbar from '@mui/material/Snackbar'; import MuiAlert, {AlertProps} from '@mui/material/Alert'; import {useDispatch, useSelector} from "react-redux"; import {AppRootStateType} from "../../app/store"; import {setAppErrorAC} from "../../app/app-reducer"; const Alert = React.forwardRef<HTMLDivElement, AlertProps>(function Alert( props, ref, ) { return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; }); export function ErrorSnackbar() { const error = useSelector<AppRootStateType, string | null>(state => state.app.error) const dispatch = useDispatch() const isOpen = error !== null const handleClose = (event?: React.SyntheticEvent | Event, reason?: string) => { if (reason === 'clickaway') { return; } dispatch(setAppErrorAC({error:null})) }; return ( <Stack spacing={2} sx={{width: '100%'}}> <Snackbar open={isOpen} autoHideDuration={3000} onClose={handleClose}> <Alert onClose={handleClose} severity="error" sx={{width: '100%'}}> {error} </Alert> </Snackbar> </Stack> ); }
# Original sample data ants <- c(43, 59, 22, 25, 36, 47, 19, 21) # Set seed for reproducibility set.seed(1) # Number of bootstrap samples num_samples <- 1000 # Empty vector to store means of bootstrap samples bootstrap_means <- numeric(num_samples) # Generate bootstrap samples and calculate means for (i in 1:num_samples) { bootstrap_sample <- sample(ants, size = length(ants), replace = TRUE) bootstrap_means[i] <- mean(bootstrap_sample) } # Calculate mean of the means mean_of_means <- mean(bootstrap_means) # Calculate standard error standard_error <- sd(bootstrap_means) / sqrt(num_samples) # Output the results print(mean_of_means) print(standard_error)
// Copyright (c) 2022 Javier Castro - jcastro0x@gmail.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #pragma once #include <scene/SceneNode.hpp> #include <memory> #include <array> #include <functional> namespace sf { class Shader; class Texture; class RectangleShape; class RenderTarget; class RenderStates; } namespace lpm { /** * @brief Child node of SplashScene to draw splash. * * SplashNode draw 4 differente textures with padding effect and blended together * with mask texture. Can change textures at fly with fade-in and fade-out effect. */ class SplashNode : public SceneNode { public: static constexpr size_t TEXTURE_0 = 0; static constexpr size_t TEXTURE_1 = 1; static constexpr size_t TEXTURE_2 = 2; static constexpr size_t TEXTURE_3 = 3; public: SplashNode(); ~SplashNode(); public: void changeTexture(size_t index, std::string_view textureName); protected: void draw(sf::RenderTarget& target, sf::RenderStates states) const override; void tick(float deltaTime) override; private: void initializeTextures(); void initializeShader(); void initializeTexture(sf::Texture* texture, std::string_view textureName); void setTextureIntensityTarget(size_t index, float intensity, std::function<void()> const& callback = {}); private: std::unique_ptr<sf::Shader> shader_; std::unique_ptr<sf::RectangleShape> rectangleShape_; std::unique_ptr<sf::Texture> maskTexture_; std::unique_ptr<sf::Texture> topMaskTexture_; float texturesIntensitiesVelocity = 1.95f; std::array<std::unique_ptr<sf::Texture>, 4> textures_; std::array<float, 4> texturesIntensities; std::array<float, 4> texturesIntensitiesTargets; std::array<std::function<void()>, 4> texturesIntensitiesCallbacks; }; }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { PROPERTY_DETAIL_ROUTE, PROPERTY_LIST_ROUTE } from './constants/route.constant'; import { PropertyListComponent } from './components/property-list/property-list.component'; import { PropertyDetailComponent } from './components/property-detail/property-detail.component'; const routes: Routes = [ { path: '', redirectTo: PROPERTY_LIST_ROUTE.path, pathMatch: 'full', }, { path: PROPERTY_LIST_ROUTE.path, component: PropertyListComponent }, { path: `${PROPERTY_DETAIL_ROUTE.path}/:id`, component: PropertyDetailComponent } ]; @NgModule({ imports: [ CommonModule, RouterModule.forChild(routes) ], exports: [ RouterModule ] }) export class PropertiesRoutingModule { }
<?php declare(strict_types=1); namespace App\Http\Livewire\Categories; use App\Models\Category; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Support\Facades\Gate; use Jantinnerezo\LivewireAlert\LivewireAlert; use Livewire\Component; class Edit extends Component { use LivewireAlert; /** @var string[] */ public $listeners = ['editModal']; /** @var bool */ public $editModal = false; /** @var mixed */ public $category; protected array $rules = [ 'category.name' => 'required|min:3|max:255', 'category.code' => 'required', ]; public function render(): View|Factory { abort_if(Gate::denies('access_product_categories'), 403); return view('livewire.categories.edit'); } public function editModal($id): void { abort_if(Gate::denies('access_product_categories'), 403); $this->resetErrorBag(); $this->resetValidation(); $this->category = Category::findOrFail($id); $this->editModal = true; } public function update(): void { abort_if(Gate::denies('access_product_categories'), 403); $this->validate(); $this->category->save(); $this->emit('refreshIndex'); $this->editModal = false; $this->alert('success', __('Category updated successfully.')); } }
import { SVGProps } from 'react'; export type IconSvgProps = SVGProps<SVGSVGElement> & { size?: number; }; export type BaseAnswer = { score: number; domain: string; facet: number; }; export type Answer = BaseAnswer & { id: string }; export type DbResult = { testId: string; lang: string; invalid: boolean; timeElapsed: number; dateStamp: string; answers: Answer[]; }; export type Feedback = { name: string; email: string; message: string; }; type ErrorName = 'NotFoundError' | 'SavingError'; class ErrorBase<T extends string> extends Error { name: T; message: string; cause: any; constructor({ name, message, cause }: { name: T; message: string; cause?: any; }) { super(); this.name = name; this.message = message; this.cause = cause; } } export class B5Error extends ErrorBase<ErrorName> {}
/* * "Commons Clause" License Condition v1.0 * * The Software is provided to you by the Licensor under the * License, as defined below, subject to the following condition. * * Without limiting other conditions in the License, the grant * of rights under the License will not include, and the * License does not grant to you, the right to Sell the Software. * * For purposes of the foregoing, "Sell" means practicing any * or all of the rights granted to you under the License to * provide to third parties, for a fee or other consideration * (including without limitation fees for hosting or * consulting/ support services related to the Software), a * product or service whose value derives, entirely or substantially, * from the functionality of the Software. Any * license notice or attribution required by the License must * also include this Commons Clause License Condition notice. * * License: LGPL 2.1 or later * Licensor: metaphacts GmbH * * Copyright (C) 2015-2021, metaphacts GmbH * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, you can receive a copy * of the GNU Lesser General Public License from http://www.gnu.org/ */ import { createElement } from 'react'; import { DatetimepickerProps } from 'react-datetime'; import { clone } from 'lodash'; import { expect } from 'chai'; import * as sinon from 'sinon'; import { Rdf, vocabularies } from 'platform/api/rdf'; import { AtomicValue, DatePickerInput, DatePickerInputProps as DatePickerProps, DatePickerMode, FieldValue, normalizeFieldDefinition, } from 'platform/components/forms'; import { OUTPUT_UTC_DATE_FORMAT, OUTPUT_UTC_TIME_FORMAT, utcMomentFromRdfLiteral, } from 'platform/components/forms/inputs/DatePickerInput'; import { shallow, mount } from 'platform-tests/configuredEnzyme'; import { mockLanguagePreferences } from 'platform-tests/mocks'; mockLanguagePreferences(); const DATE_TIME = 'http://www.w3.org/2001/XMLSchema-datatypes#dateTime'; const DATE = 'http://www.w3.org/2001/XMLSchema-datatypes#date'; const TIME = 'http://www.w3.org/2001/XMLSchema-datatypes#time'; const definition = normalizeFieldDefinition({ id: 'date1', label: 'labelProp', xsdDatatype: Rdf.iri(DATE_TIME), minOccurs: 1, maxOccurs: 1, selectPattern: '', }); const baseInputProps: DatePickerProps = { for: 'date1', definition, mode: undefined, }; const completeInputProps: DatePickerProps = { ...baseInputProps, handler: DatePickerInput.makeHandler({definition, baseInputProps}), value: FieldValue.fromLabeled({ value: Rdf.literal('2016-05-23T10:20:13+05:30', vocabularies.xsd.dateTime), }), }; describe('DatePickerInput Component', () => { const datepickerComponent = mount(createElement(DatePickerInput, completeInputProps)); const datepicker = datepickerComponent.find('DatePickerInput'); it('render with default parameters', () => { expect(datepicker).to.have.length(1); }); describe('modes', () => { it('can get mode from props', () => { const mode: DatePickerMode = 'date'; let props = clone(completeInputProps); props.mode = mode; const component = mount(createElement(DatePickerInput, props)); const componentProps: DatePickerProps = component.props(); expect(componentProps.mode).to.be.equal(mode); }); describe('date', () => { const props = clone(completeInputProps); props.definition.xsdDatatype = Rdf.iri(DATE); const component = shallow(createElement(DatePickerInput, props)); const field = component.find('.date-picker-field__date-picker'); const fieldProps: DatetimepickerProps = field.props(); it('correct rendered', () => { expect(fieldProps.dateFormat).to.eql(OUTPUT_UTC_DATE_FORMAT); expect(fieldProps.timeFormat).to.be.null; }); it('have correct default value', () => { const momentDateTime = fieldProps.value as any; expect(momentDateTime).to.be.an('object'); expect(momentDateTime.format(`${OUTPUT_UTC_DATE_FORMAT} ${OUTPUT_UTC_TIME_FORMAT}`)) .is.eql('2016-05-23 04:50:13'); }); it('pass correct value after change', () => { const callback = sinon.spy(); const clonedProps = clone(completeInputProps); clonedProps.updateValue = callback; clonedProps.definition.xsdDatatype = Rdf.iri(DATE); const wrapper = mount(createElement(DatePickerInput, clonedProps)); wrapper.find('input').simulate('change', {'target': {'value': '05/11/22'}}); const reducer: (previous: FieldValue) => AtomicValue = callback.args[0][0]; const newValue = reducer(clonedProps.value).value; expect(Rdf.isLiteral(newValue) && newValue.datatype.value).to.be.equal(Rdf.iri(DATE).value); }); }); describe('time', () => { const props = clone(completeInputProps); props.definition.xsdDatatype = Rdf.iri(TIME); const component = shallow(createElement(DatePickerInput, props)); const field = component.find('.date-picker-field__date-picker'); const fieldProps: DatetimepickerProps = field.props(); it('correct render in time mode', () => { expect(fieldProps.dateFormat).to.be.null; expect(fieldProps.timeFormat).to.be.equal(OUTPUT_UTC_TIME_FORMAT); }); }); describe('datetime', () => { const props = clone(completeInputProps); props.definition.xsdDatatype = Rdf.iri(DATE_TIME); const component = shallow(createElement(DatePickerInput, props)); const field = component.find('.date-picker-field__date-picker'); const fieldProps: DatetimepickerProps = field.props(); it('correct render in datetime mode', () => { expect(fieldProps.dateFormat).to.eql(OUTPUT_UTC_DATE_FORMAT); expect(fieldProps.timeFormat).to.be.equal(OUTPUT_UTC_TIME_FORMAT); }); }); }); it('call callback when value is changed', () => { const callback = sinon.spy(); const props: DatePickerProps = {...completeInputProps, updateValue: callback}; const wrapper = mount(createElement(DatePickerInput, props)); wrapper.find('input').simulate('change', {'target': {'value': '05/11/22 11:55:22'}}); expect(callback.called).to.be.true; }); }); describe('localMomentFromRdfLiteral return correct normalized UTC value', () => { it('for dateTime is already normalized', () => { const dateTime = '2016-05-23T10:20:13Z'; const value = Rdf.literal(dateTime, vocabularies.xsd.dateTime); expect(utcMomentFromRdfLiteral(value).creationData().isUTC).to.be.true; expect(utcMomentFromRdfLiteral(value).format()).to.be.eql('2016-05-23T10:20:13Z'); }); it('for dateTime with offset +2', () => { const dateTime = '2016-05-23T10:20:13+00:00'; const value = Rdf.literal(dateTime, vocabularies.xsd.dateTime); expect(utcMomentFromRdfLiteral(value).creationData().isUTC).to.be.true; expect(utcMomentFromRdfLiteral(value).format()).to.be.eql('2016-05-23T10:20:13Z'); }); it('for dateTime with offset +2', () => { const dateTime = '2016-05-23T10:20:13+02:00'; const value = Rdf.literal(dateTime, vocabularies.xsd.dateTime); expect(utcMomentFromRdfLiteral(value).creationData().isUTC).to.be.true; expect(utcMomentFromRdfLiteral(value).format()).to.be.eql('2016-05-23T08:20:13Z'); }); it('for dateTime with offset -3', () => { const dateTime = '2016-05-23T10:20:13-03:00'; const value = Rdf.literal(dateTime, vocabularies.xsd.dateTime); expect(utcMomentFromRdfLiteral(value).creationData().isUTC).to.be.true; expect(utcMomentFromRdfLiteral(value).format()).to.be.eql('2016-05-23T13:20:13Z'); }); it('for date with offset', () => { const dateTime = '2002-09-24-06:00'; const value = Rdf.literal(dateTime, vocabularies.xsd.date); expect(utcMomentFromRdfLiteral(value).creationData().isUTC).to.be.true; expect(utcMomentFromRdfLiteral(value).format()).to.be.eql('2002-09-24T06:00:00Z'); }); it('for date without offset', () => { const dateTime = '2002-09-24'; const value = Rdf.literal(dateTime, vocabularies.xsd.date); expect(utcMomentFromRdfLiteral(value).creationData().isUTC).to.be.true; expect(utcMomentFromRdfLiteral(value).format()).to.be.eql('2002-09-24T00:00:00Z'); }); it('for invalid date', () => { const dateTime = 'not a date'; const value = Rdf.literal(dateTime, vocabularies.xsd.dateTime); expect(utcMomentFromRdfLiteral(value)).to.be.undefined; }); it('for undefined', () => { expect(utcMomentFromRdfLiteral(undefined)).to.be.undefined; }); });
//map method is used to iterate over the array elements and operate on the elements. //It takes a function as an argument that can consist of array element, index and array itself as function parameters. //It returns a new array. let arr = [1,2,3,4,5,6,7,8,9,10]; let square = arr.map( (element) => { return element*element; //Explicit return }); console.log(square); let cube = arr.map( (element) => element*element*element); //Implicit return console.log(cube); //method chaining //Various methods can be chained with each other to perform collective operation on the same array. let arr2 = [10,20,30,40,50]; let result = arr2.map( (element) => element+10).filter( (element) => element >= 30); console.log(result); let arr3 = ["apple", "banana", "mango", "grapes", "orange"]; let fruits = arr3.map( (element) => `The name of fruit is: ${element}.`) .filter( (element) => element === 'The name of fruit is: mango.') .map( (element) => element + ` Mango is the king of fruits.`); console.log(fruits);
"""The emails tests module.""" import pytest from tests.fixtures.auth import USER_EMAIL from communication.notifications.email import mail_managers, mail_user from users.models import User pytestmark = pytest.mark.django_db def test_mail_managers(mailoutbox): """Should send an email to the system managers.""" mail_managers(subject="Text message", data={"text": "<p>Test text</p>"}) assert len(mailoutbox) == 1 mail = mailoutbox[0] assert mail.recipients() == ["admin@example.com", "manager@example.com"] assert "Text message" in mail.subject assert "<p>Test text" in mail.alternatives[0][0] def test_mail_user( user: User, mailoutbox, ): """Should send an email to the user.""" mail_user( user=user, subject="Text message", template="message_notification", data={}, ) assert len(mailoutbox) == 1 mail = mailoutbox[0] assert mail.recipients() == [USER_EMAIL] assert "Text message" in mail.subject
/* Copyright 2014 Sheldon Neilson www.neilson.co.za * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.lisungui.pharma.alarm; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.widget.Toast; import com.lisungui.pharma.helper.SQLiteDataBaseHelper; import com.lisungui.pharma.models.Alarm; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; public class AlarmService extends Service { private static final String TAG = AlarmService.class.getSimpleName(); SQLiteDataBaseHelper dataBaseHelper; @Override public IBinder onBind(Intent intent) { return null; } /* * (non-Javadoc) * * @see android.app.Service#onCreate() */ @Override public void onCreate() { Log.d(this.getClass().getSimpleName(), "onCreate()"); super.onCreate(); dataBaseHelper = new SQLiteDataBaseHelper(this); } private Alarm getNext() { Set<Alarm> alarmQueue = new TreeSet<>(new Comparator<Alarm>() { @Override public int compare(Alarm lhs, Alarm rhs) { int result = 0; long diff = lhs.getAlarmTime().getTimeInMillis() - rhs.getAlarmTime().getTimeInMillis(); if (diff > 0) { return 1; } else if (diff < 0) { return -1; } return result; } }); // Database.init(getApplicationContext()); List<Alarm> alarms = dataBaseHelper.getAll(""); for (Alarm alarm : alarms) { if (alarm.getAlarmActive()) alarmQueue.add(alarm); } if (alarmQueue.iterator().hasNext()) { return alarmQueue.iterator().next(); } else { return null; } } /* * (non-Javadoc) * * @see android.app.Service#onDestroy() */ @Override public void onDestroy() { // Database.deactivate(); super.onDestroy(); } /* * (non-Javadoc) * * @see android.app.Service#onStartCommand(android.content.Intent, int, int) */ @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(this.getClass().getSimpleName(), "onStartCommand()"); Alarm alarm = getNext(); if (null != alarm) { alarm.schedule(getApplicationContext(),alarm); } else { Intent myIntent = new Intent(getApplicationContext(), AlarmAlertBroadcastReciever.class); myIntent.putExtra("alarm", new Alarm()); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pendingIntent); } return START_STICKY; } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); Log.d(TAG, "TASK REMOVED"); PendingIntent service = PendingIntent.getService( getApplicationContext(), 1001, new Intent(getApplicationContext(), AlarmService.class), PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service); startService(new Intent(this, AlarmService.class)); } }
import * as React from 'react'; import { useController, UseControllerProps } from 'react-hook-form'; import { ErrorMessage } from '@hookform/error-message'; import styles from './Input.module.scss'; const Input = ({ type, label, placeholder, inputMode, errors, ...props }: { label: string; placeholder?: string; type?: 'text' | 'number' | 'date'; inputMode?: React.HTMLAttributes<HTMLLIElement>['inputMode']; errors?: any; } & UseControllerProps<any>) => { const { field } = useController(props); return ( <div className={styles.wrapper}> { <label className={ styles[`label-${errors[props.name] ? 'invalid' : 'valid'}`] } htmlFor={props.name} > {label} </label> } <input id={props.name} className={errors[props.name] ? styles['input-invalid'] : 'input-valid'} {...field} aria-invalid={errors[props.name] ? 'true' : 'false'} type={type} inputMode={inputMode} placeholder={placeholder} /> {!errors[props.name] && <p className={styles['error-empty']} />} <ErrorMessage errors={errors} name={props.name} render={({ message }) => ( <p className={styles.error} role="alert"> {message} </p> )} /> </div> ); }; export default Input;
import pandas as pd from sklearn.ensemble import RandomForestClassifier from spring.utils.variables import ( X_COLS, Y_COLS, ) if "custom" not in globals(): from mage_ai.data_preparation.decorators import custom if "test" not in globals(): from mage_ai.data_preparation.decorators import test def _model_save(rf_model): """ Save RandomForest model to a file. """ # Here you would implement the logic to save your trained model to a file # Example: # with open('random_forest_model.pkl', 'wb') as file: # pickle.dump(rf_model, file) pass @custom def random_forest_train(df: pd.DataFrame, *args, **kwargs): """ Train a Random Forest Classifier and predict the 'Survived' column. Args: df: Data frame containing the training data. Returns: Data frame with a new column 'Survived_predict' with predictions. """ # Prepare the data x_train = df[X_COLS] y_train = df[Y_COLS].values.ravel() # RandomForest expects a 1D array for y # Initialize the Random Forest Classifier rf_model = RandomForestClassifier() # Train the model rf_model.fit(x_train, y_train) # Predict using the trained model _pred = rf_model.predict(x_train) # Optionally save the model _model_save(rf_model) # Assign predictions to a new column in the dataframe df = df.assign(Survived_predict=_pred) return df @test def test_output(output, *args) -> None: """ Template code for testing the output of the block. Args: output: The output from the random_forest_train function. """ assert output is not None, "The output is undefined" assert 'Survived_predict' in output.columns, "Prediction column is missing in the output dataframe" # You can add more tests to check the quality of your predictions, # such as accuracy score, confusion matrix, etc.
"""Test titiler-image utils.""" import os import numpy import pytest from fastapi import HTTPException from rio_tiler.io import ImageReader from titiler.image.utils import image_to_bitonal, image_to_grayscale, rotate PREFIX = os.path.join(os.path.dirname(__file__), "fixtures") boston_jpeg = os.path.join(PREFIX, "boston_small.jpg") def test_rotate(): """test rotation.""" with ImageReader(boston_jpeg) as src: # read part of the image with mask area img = src.part((-100, 100, 100, 0)) assert img.array.mask[0, 0, 0] # Masked assert not img.array.mask[0, 0, 100] # Not Masked assert img.array.shape == (3, 100, 200) img0 = rotate(img, 0, expand=True) numpy.testing.assert_array_equal(img.data, img0.data) imgm = rotate(img, 0, mirrored=True) with numpy.testing.assert_raises(AssertionError): numpy.testing.assert_array_equal(imgm.data, img.data) img180 = rotate(img, 180, expand=True) with numpy.testing.assert_raises(AssertionError): numpy.testing.assert_array_equal(img180.data, img.data) assert img.data[0, 0, 100] == img180.data[0, 99, 99] assert not img180.array.mask[0, 0, 0] # Not Masked assert img180.array.mask[0, 0, 100] # Masked img90 = rotate(img, 90, expand=True) assert img90.array.shape == (3, 200, 100) assert img90.array.mask[0, 0, 0] # Masked assert not img90.array.mask[0, 100, 0] # Not Masked img90 = rotate(img, 90, expand=False) assert img90.array.shape == (3, 100, 200) assert img90.array.mask[0, 0, 0] # Masked assert img90.array.mask[0, 0, 100] # Masked assert img90.array.mask[0, 99, 0] # Masked assert not img90.array.mask[0, 99, 100] # not Masked img125 = rotate(img, 125, expand=True) assert img125.array.shape == (3, 222, 198) assert img125.array.mask[0, 0, 0] # Masked assert not img125.array.mask[0, 150, 50] # Not Masked def test_gray(): """test to_grayscale.""" with ImageReader(boston_jpeg) as src: img = src.preview() assert img.array.shape == (3, 695, 1000) assert img.array.dtype == "uint8" grey = image_to_grayscale(img) assert grey.array.shape == (1, 695, 1000) assert grey.array.dtype == "uint8" img = src.preview(indexes=1) assert img.array.shape == (1, 695, 1000) grey = image_to_grayscale(img) numpy.testing.assert_array_equal(img.data, grey.data) with pytest.raises(HTTPException): img = src.preview(indexes=(1, 1, 1, 1)) image_to_grayscale(img) def test_bitonal(): """test to_bitonal.""" with ImageReader(boston_jpeg) as src: img = src.preview() assert img.array.shape == (3, 695, 1000) assert img.array.dtype == "uint8" grey = image_to_bitonal(img) assert grey.array.shape == (1, 695, 1000) assert grey.array.dtype == "uint8" assert numpy.unique(grey.array).tolist() == [0, 255]
# https://leetcode.com/problems/two-sum/ # 1. Two Sum from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: num_to_index_hash = {} for i, num in enumerate(nums): if target - num in num_to_index_hash: return [num_to_index_hash[target - num], i] num_to_index_hash[num] = i
'use client'; import React, { useState, useEffect } from 'react'; import Image from 'next/image'; import styled from 'styled-components'; import SVGPattern1 from './svg/Pattern1'; import SVGPattern2 from './svg/Pattern2'; import SVGPattern3 from './svg/Pattern3'; import SVGPattern4 from './svg/Pattern4'; import DiamondSVG from './svg/Diamond'; import CapsuleButton from '@/components/ui/CapsuleButton'; import FeaturedCard from '@/components/ui/FeaturedCard'; import PreviewCard from '@/components/ui/PreviewCard'; import CommonFooter from '@/components/ui/Footer'; interface PreviewCardContent { imageUrl: string; description: string; tags: string[]; } const PreviewCardInfo = { cyber: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713838337/Cyber/Cyber_cover2_v9rvzl.png', description: 'Easy to use cybersecurity monitor powered by AI and knowledge graph', tags: ['#strategy', '#saas', '#0-to-1'], }, dashboard: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713829915/TCP/DashboardCover_zhv7x2.png', description: 'Creating evidence-based MVP without clear product vision and access to user research', tags: ['#strategy', '#saas', '#0-to-1'], }, ubisoft: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713838420/Ubisoft/UbisoftCover_rgmguf.png', description: 'Customer Support Portal Redesign', tags: ['#service-design', '#cx', '#design-strategy'], }, marketplace: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713838360/3M/Market_Cover_gzsxtp.png', description: 'Defined persona, customer journey and value proposition to validate an ambitious B2B Marketplace', tags: ['#b2b', '#0-to-1', '#mvp-validation', '#user-research'], }, extraspace: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713936695/ExstraSpace/ess_cover_1x_ken99t.png', description: 'Storage E-Commmerce Redesign', tags: ['#b2c', '#ecommerce', '#design-system'], }, hamsa: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713936497/unnamed_edxr4x.gif', description: 'High five your friends in VR with your own hands', tags: ['#vr', '#social', '#co-creation'], }, garden: { imageUrl: 'https://res.cloudinary.com/dtrdipypb/image/upload/v1713937916/ts2_w8sfcl.jpg', description: '24 hr organic garden in the heart of manhattan', tags: ['#installation', '#physical', '#0-to-1'], } }; const SectionWrapper = styled.section` display: flex; justify-content: center; align-items: center; `; const GreetingSectionWrapper = styled(SectionWrapper)` min-height: 30rem; `; const WorkSectionWrapper = styled(SectionWrapper)` min-height: 50rem; `; const SideSectionWrapper = styled(SectionWrapper)` min-height: 45rem; `; const GridWrapper = styled.div` max-width: 1440px; margin: 0 auto; `; const GridWithLineWrapper = (props: any) => ( <GridWrapper> <div className="flex flex-row justify-center h-full w-full"> <VerticalDottedLine /> <div>{props.children}</div> <VerticalDottedLine /> </div> </GridWrapper> ); const VerticalDottedLine = styled.div` border: none; border-left: 1px solid transparent; /* Hide the solid line */ background: linear-gradient(to bottom, #C3C3C3 50%, transparent 50%); background-size: 1px 9px; /* 6px dash + 3px gap = 9px total */ width: 1px; flex-grow: 1; z-index:10; `; const Header1 = styled.div` font-size: 32px; font-weight:600; margin-bottom:32px; `; const GreetingsText = styled.div`font-size: 32px; font-weight:400;`; const Button = styled.button``; const Greetings = () => ( <div className="col-start-3 col-end-6"> <GreetingsText> I’m Kylin, a strategic-minded design generalist. </GreetingsText> <div className="mt-6"> <CapsuleButton href={'#work'}>Work</CapsuleButton> <CapsuleButton href={'#side'}>Side Project</CapsuleButton> <CapsuleButton href={'#about'}>About</CapsuleButton> </div> </div> ); const HomeLink = (props: { href: string; children: React.ReactNode; onMouseEnter: () => void; onMouseLeave: () => void; previewCardContent: any; openInNewTab: boolean; }) => { const [isHovered, setIsHovered] = useState(false); const [cardPosition, setCardPosition] = useState({ top: 0, left: 0 }); const handleMouseEnter = (e: any) => { const link = e.target; const linkRect = link.getBoundingClientRect(); // Calculate the position of the hover card const top = linkRect.bottom; const left = linkRect.left; // Set the position and show the hover card setCardPosition({ top, left }); setIsHovered(true); props.onMouseEnter(); }; const handleMouseLeave = () => { // Hide the hover card setIsHovered(false); props.onMouseLeave(); }; // pointer-events-none md:pointer-events-auto return ( <li> <div className='group'> <div // className="flex items-center group mb-[32px] pointer-events-none xl:pointer-events-auto" className="flex items-center pt-[16px] pb-[16px]" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > <div className="w-[16px] h-[16px] ml-[-32px] mr-[16px]"> <DiamondSVG isHovered={isHovered} /> </div> <a href={props.href} className="text-textLinkDefault group-hover:text-textLinkHover transition duration-300 ease-in-out text-[24px] font-light relative" {...(props.openInNewTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})} > {props.children} <span className="absolute left-0 right-0 bottom-0 h-[1px] bg-underlineLinkDefault transition-colors duration-300 group-hover:bg-textLinkHover"></span> </a> </div> <div className="block lg:hidden"> {/* always show preview card inline on smaller screens */} <a href={props.href}> <PreviewCard content={props.previewCardContent} /> </a> </div> </div> </li> ); }; const WorkSection = () => { const [isLinkHovered, setIsLinkHovered] = useState(false); const [previewCardContent, setPreviewCardContent] = useState<PreviewCardContent | null>(null); const handleLinkHover = ( imageUrl: string, description: string, tags: string[] ) => { setIsLinkHovered(true); // setPreviewCardContent(PreviewCardInfo.cyber); setPreviewCardContent({ imageUrl, description, tags, }); }; const handleLinkLeave = () => { setIsLinkHovered(false); setPreviewCardContent(null); }; return ( <WorkSectionWrapper id="work"> <div className="w-full h-full relative"> <div className="w-full grid grid-cols-5 gap-4 "> <div className="col-start-2 col-end-6 xl:col-end-4"> <Header1>entrée</Header1> <ul className="flex flex-col items-start"> {/* <HomeLink href="/cyber" onMouseEnter={() => handleLinkHover( '/placeholderPNG.png', 'Easy to use cybersecurity monitor powered by AI and knowledge graph', [{ name: 'strategy' }, { name: 'saas' }, { name: '0-to-1' }] ) } onMouseLeave={handleLinkLeave} > Riot Games R&D - Game UI/UX </HomeLink> */} <HomeLink href="/dashboard" onMouseEnter={() => handleLinkHover(PreviewCardInfo.dashboard.imageUrl, PreviewCardInfo.dashboard.description, PreviewCardInfo.dashboard.tags) } onMouseLeave={handleLinkLeave} previewCardContent={PreviewCardInfo.dashboard} openInNewTab={false} > Enterprise Onboarding & Customer 360 </HomeLink> <HomeLink href="/ubisoftcx" onMouseEnter={() => handleLinkHover(PreviewCardInfo.ubisoft.imageUrl, PreviewCardInfo.ubisoft.description, PreviewCardInfo.ubisoft.tags) } onMouseLeave={handleLinkLeave} previewCardContent={PreviewCardInfo.ubisoft} openInNewTab={false} > Do Gamers Dream of Customer Support? </HomeLink> <HomeLink href="/cyber" onMouseEnter={() => handleLinkHover(PreviewCardInfo.extraspace.imageUrl, PreviewCardInfo.extraspace.description, PreviewCardInfo.extraspace.tags) } onMouseLeave={handleLinkLeave} previewCardContent={PreviewCardInfo.extraspace} openInNewTab={false} > From Storage-Renting To Space-Booking </HomeLink> <HomeLink href="/cyber" onMouseEnter={() => handleLinkHover(PreviewCardInfo.cyber.imageUrl, PreviewCardInfo.cyber.description, PreviewCardInfo.cyber.tags) } onMouseLeave={handleLinkLeave} previewCardContent={PreviewCardInfo.cyber} openInNewTab={false} > AI-powered Cybersecurity Dashb oard </HomeLink> </ul> </div> {isLinkHovered && ( <div className="col-start-4 col-end-6 relative hidden lg:block"> <div className='absolute'> <PreviewCard content={previewCardContent} /> </div> </div> )} </div> <div className="absolute inset-0 w-full h-full z-[-1] flex items-center justify-end "> <div className="w-[80vh] h-auto left-1/2 transform translate-x-1/2"> <SVGPattern2 /> </div> </div> </div> </WorkSectionWrapper> ); }; const SideSection = () => { const [isLinkHovered, setIsLinkHovered] = useState(false); const [previewCardContent, setPreviewCardContent] = useState<PreviewCardContent | null>(null); const handleLinkHover = ( imageUrl: string, description: string, tags: string[] ) => { setIsLinkHovered(true); setPreviewCardContent({ imageUrl, description, tags, }); }; const handleLinkLeave = () => { setIsLinkHovered(false); setPreviewCardContent(null); }; return ( <SideSectionWrapper id="side"> <div className="w-full h-full relative min-h-60vh"> <div className="w-full grid grid-cols-5 gap-4 "> <div className="col-start-2 col-end-6 xl:col-end-4"> <Header1>side</Header1> <ul className="flex flex-col items-start"> <HomeLink href="https://docs.google.com/presentation/d/1w9adKmAQs5Eip9pk9hrwGX0KUSiBLmcrYJQEMsrNAk0/edit#slide=id.gf220615335_0_40" onMouseEnter={() => handleLinkHover(PreviewCardInfo.hamsa.imageUrl, PreviewCardInfo.hamsa.description, PreviewCardInfo.hamsa.tags) } onMouseLeave={handleLinkLeave} previewCardContent={PreviewCardInfo.hamsa} openInNewTab={true} > Hamsa VR </HomeLink> <HomeLink href="https://www.youtube.com/watch?v=0EnYRM3RyPE" onMouseEnter={() => handleLinkHover(PreviewCardInfo.garden.imageUrl, PreviewCardInfo.garden.description, PreviewCardInfo.garden.tags) } onMouseLeave={handleLinkLeave} previewCardContent={PreviewCardInfo.garden} openInNewTab={true} > Time Sqauare Electronic Garden </HomeLink> </ul> </div> {isLinkHovered && ( <div className="col-start-4 col-end-6 relative"> <div className='absolute'> <PreviewCard content={previewCardContent} /> </div> </div> )} </div> <div className="absolute inset-0 w-full h-full z-[-1] flex items-center justify-end "> <div className="w-[60vh] h-auto left-1/2 transform translate-x-1/2"> <SVGPattern3 /> </div> </div> </div> </SideSectionWrapper> ); }; const FooterLink = styled.a` width: max-content; padding: 8px; color: #e1dec2; font-size: 24px; font-weight: 300; text-decoration: underline; transition: all 300ms ease-in-out; margin-bottom:24px; &:hover { color: white; } `; const FooterSection = () => ( <div className="absolute left-0 w-[100vw] h-[50vh] bg-[#2A2A2A] flex justify-center z-[-1]"> <div className="grid grid-cols-5 gap-4 max-w-[1440px] w-full"> <div className="col-start-2 col-end-5 flex flex-row justify-between"> <div className="flex flex-col mt-8"> <FooterLink href="https://www.linkedin.com/in/kylinc/" target="_blank" rel="noopener noreferrer" > Linkedin </FooterLink> <FooterLink href="https://www.linkedin.com/in/kylinc/" target="_blank" rel="noopener noreferrer" > Resume </FooterLink> <FooterLink href="https://www.linkedin.com/in/kylinc/" target="_blank" rel="noopener noreferrer" > kylingoround@gmail.com </FooterLink> </div> <div className="w-[400px] h-[400px] mt-[-60px]"> <SVGPattern4 /> </div> </div> </div> </div> ); const StickyTopBar = () => { const [currentActive, setCurrentActive] = useState(0); useEffect(() => { const handleScroll = () => { const sectionOffsets = [ document.getElementById('greetings')?.offsetTop ?? 0, document.getElementById('work')?.offsetTop ?? 0, document.getElementById('side')?.offsetTop ?? 0, document.getElementById('about')?.offsetTop ?? 0, ]; const scrollPosition = window.scrollY + 100; let currentActive = 1; console.log(currentActive); let activeIndex = 0; for (let i = sectionOffsets.length - 1; i >= 0; i--) { if (scrollPosition >= sectionOffsets[i]) { activeIndex = i; break; } } setCurrentActive(activeIndex); }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); return ( <div className="flex justify-center items-center fixed top-0 w-full z-10 "> <div className="w-full max-w-[1440px] p-12"> <div className="flex items-center space-x-4 "> <a href="#greetings" className={`nav-item ${currentActive === 0 ? 'active' : ''}`} > <div style={{ width: '16px', height: '16px', background: currentActive === 0 ? '#2A2A2A' : '#E4E4E4', }} ></div> </a> <a href="#work" className={`nav-item ${currentActive === 1 ? 'active' : ''}`} > <div style={{ width: '16px', height: '16px', background: currentActive === 1 ? '#2A2A2A' : '#E4E4E4', }} ></div> </a> <a href="#side" className={`nav-item ${currentActive === 2 ? 'active' : ''}`} > <div style={{ width: '16px', height: '16px', background: currentActive === 2 ? '#2A2A2A' : '#E4E4E4', }} ></div> </a> <a href="#about" className={`nav-item ${currentActive === 3 ? 'active' : ''}`} > <div style={{ width: '16px', height: '16px', background: currentActive === 3 ? '#2A2A2A' : '#E4E4E4', }} ></div> </a> </div> </div> </div> ); }; // <div className="sticky top-0 z-50 flex justify-around items-center bg-white w-full h-24 shadow-md"> // {[1, 2, 3, 4].map((index) => ( // <div // key={index} // id={`section${index}`} // className={`section w-24 h-24 ${ // activeSection === index ? 'bg-gray-900' : 'bg-gray-300' // }`} // ></div> // ))} // </div> const Home = () => ( <div> <GridWithLineWrapper> <GreetingSectionWrapper id="greetings"> <StickyTopBar /> <div className="w-full h-full relative min-h-60vh mt-36"> <div className="relative w-full grid grid-cols-5 gap-4 col-end-4 "> <Header1 className="col-start-2 col-end-3 ">Hello there.</Header1> <Greetings /> </div> <div className="absolute inset-0 w-full h-full z-[-1] flex items-center justify-center pl-[24px] pr-[24px] "> <div className="w-full h-auto ml-12 mr-12 max-w-[960px]"> <SVGPattern1 /> </div> </div> </div> </GreetingSectionWrapper> <WorkSection /> <SideSection /> <SectionWrapper id="about"> <div className="w-full grid grid-cols-5 gap-4 min-h-[40vh] mb-8 mt-8"> <div className="col-start-2 col-end-5 "> <Header1>about</Header1> <div className="text-[24px] text-[#2A2A2A] leading-relaxed "> Designing for me is like solving puzzles of joggling between people's goals, needs and resource limitations. However, doesn't matter if it is an e-commerce product list or A.I.-powered dashboard, there is always an opportunity to inspire intrigue while helping people get things done. </div> </div> </div> </SectionWrapper> {/* <FooterSection /> */} <CommonFooter/> </GridWithLineWrapper> </div> ); export default Home; // function NextHome() { // return ( // <main className="flex min-h-screen flex-col items-center justify-between p-24"> // <div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex"> // <p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30"> // Get started by editing&nbsp; // <code className="font-mono font-bold">app/page.tsx</code> // </p> // <div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none"> // <a // className="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0" // href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app" // target="_blank" // rel="noopener noreferrer" // > // By{' '} // <Image // src="/vercel.svg" // alt="Vercel Logo" // className="dark:invert" // width={100} // height={24} // priority // /> // </a> // </div> // </div> // <div className="relative flex place-items-center before:absolute before:h-[300px] before:w-[480px] before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-[240px] after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 before:lg:h-[360px] z-[-1]"> // <Image // className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert" // src="/next.svg" // alt="Next.js Logo" // width={180} // height={37} // priority // /> // </div> // <div className="mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-4 lg:text-left"> // <a // href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app" // className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30" // target="_blank" // rel="noopener noreferrer" // > // <h2 className={`mb-3 text-2xl font-semibold`}> // Docs{' '} // <span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none"> // -&gt; // </span> // </h2> // <p className={`m-0 max-w-[30ch] text-sm opacity-50`}> // Find in-depth information about Next.js features and API. // </p> // </a> // <a // href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" // className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30" // target="_blank" // rel="noopener noreferrer" // > // <h2 className={`mb-3 text-2xl font-semibold`}> // Learn{' '} // <span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none"> // -&gt; // </span> // </h2> // <p className={`m-0 max-w-[30ch] text-sm opacity-50`}> // Learn about Next.js in an interactive course with&nbsp;quizzes! // </p> // </a> // <a // href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app" // className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30" // target="_blank" // rel="noopener noreferrer" // > // <h2 className={`mb-3 text-2xl font-semibold`}> // Templates{' '} // <span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none"> // -&gt; // </span> // </h2> // <p className={`m-0 max-w-[30ch] text-sm opacity-50`}> // Explore the Next.js 13 playground. // </p> // </a> // <a // href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app" // className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30" // target="_blank" // rel="noopener noreferrer" // > // <h2 className={`mb-3 text-2xl font-semibold`}> // Deploy{' '} // <span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none"> // -&gt; // </span> // </h2> // <p className={`m-0 max-w-[30ch] text-sm opacity-50`}> // Instantly deploy your Next.js site to a shareable URL with Vercel. // </p> // </a> // </div> // </main> // ); // }
import * as core from '@actions/core' import * as github from '@actions/github' import axios from 'axios' async function getMessage( actor: string, pipelineFixed: boolean ): Promise<object> { const owner = github.context.repo.owner const repo = github.context.repo.repo const runId = github.context.runId const title = `${owner}/${repo}` const subtitle = `Workflow: ${github.context.workflow}` const text = pipelineFixed ? `<font color="#008200">${actor} fixed the pipeline!</font>` : `<font color="#820000">${actor} broke the pipeline!</font>` const imageUrl = pipelineFixed ? 'https://cdn.iconscout.com/icon/free/png-256/like-605-761613.png' : 'https://cdn.iconscout.com/icon/free/png-256/bomb-108-444520.png' const url = `https://github.com/${owner}/${repo}/actions/runs/${runId}` return { cardsV2: [ { card: { header: { title, imageUrl, subtitle }, sections: [ { widgets: [ { decoratedText: { text } }, { buttonList: { buttons: [ { text: 'Go to workflow', onClick: { openLink: { url } } } ] } } ] } ] } } ] } } export async function sendMessage(pipelineFixed = true): Promise<void> { const actor = core.getInput('actor', {required: true}) const webhook = core.getInput('webhook', {required: true}) const body = await getMessage(actor, pipelineFixed) const response = await axios.post(webhook, body) core.info('Sending google chat message.') if (response.status !== 200) { throw new Error( `Google Chat notification failed. response status=${response.status}` ) } core.info('Message sent.') }
import * as React from 'react'; import { RelinkDialog } from './RelinkDialog'; // @ts-ignore import { setup as setupI18n } from '../../js/modules/i18n'; // @ts-ignore import enMessages from '../../_locales/en/messages.json'; import { storiesOf } from '@storybook/react'; import { boolean } from '@storybook/addon-knobs'; import { action } from '@storybook/addon-actions'; const i18n = setupI18n('en', enMessages); const defaultProps = { i18n, isRegistrationDone: true, relinkDevice: action('relink-device'), }; const permutations = [ { title: 'Unlinked', props: { isRegistrationDone: false, }, }, ]; storiesOf('Components/RelinkDialog', module) .add('Knobs Playground', () => { const isRegistrationDone = boolean('isRegistrationDone', false); return ( <RelinkDialog {...defaultProps} isRegistrationDone={isRegistrationDone} /> ); }) .add('Iterations', () => { return permutations.map(({ props, title }) => ( <> <h3>{title}</h3> <RelinkDialog {...defaultProps} {...props} /> </> )); });
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set et ai sta sts=2 sw=2 ts=2 tw=0: """ Get information from the system disks and partitions. For now it only handles (S/P)ATA disks and partitions, RAID and LVM are not supported yet. MSDOS/GPT partition scheme is indicated if 'parted' is installed. /proc and /sys should be mounted to retrieve information. If the disk is GPT, will tell the GUID in the partition information. For a MSDOS disk, the declared FS type is returned. Functions: - getDisks - getDiskInfo - getPartitions - getSwapPartitions - getPartitionInfo """ from __future__ import print_function, unicode_literals, absolute_import from .execute import * from .fs import * from .freesize import * import glob import re import os from stat import * import pyreadpartitions as pyrp def getDisks(): """ Returns the disks devices (without /dev/) connected to the computer. RAID and LVM are not supported yet. """ ret = [] for l in open('/proc/partitions', 'r').read().splitlines(): if re.search(r' sd[^0-9]+$', l): ret.append(re.sub(r'.*(sd.*)', r'\1', l)) return ret def getDiskInfo(diskDevice): """ Returns a dictionary with the following disk device's info: - model: model name - size: size in bytes - sizeHuman: human readable size - removable: whether it is removable or not - type: either 'msdos' or 'gpt'. diskDevice should no be prefixed with '/dev/' """ if S_ISBLK(os.stat('/dev/{0}'.format(diskDevice)).st_mode) and os.path.exists('/sys/block/{0}'.format(diskDevice)): if os.path.exists('/sys/block/{0}/device/model'.format(diskDevice)): modelName = open('/sys/block/{0}/device/model'.format(diskDevice), 'r').read().strip() else: modelName = None blockSize = int(open('/sys/block/{0}/queue/logical_block_size'.format(diskDevice), 'r').read().strip()) size = int(open('/sys/block/{0}/size'.format(diskDevice), 'r').read().strip()) * blockSize sizeHuman = getHumanSize(size) try: removable = int(open('/sys/block/{0}/removable'.format(diskDevice), 'r').read().strip()) == 1 except: removable = False with open('/dev/{0}'.format(diskDevice), 'rb') as f: parts = pyrp.get_disk_partitions_info(f) if parts.mbr is not None: partType = 'msdos' elif parts.gpt is not None: partType = 'gpt' else: partType = None return {'model': modelName, 'size': size, 'sizeHuman': sizeHuman, 'removable': removable, 'type': partType} else: return None def getPartitions(diskDevice, skipExtended=True, skipSwap=True): """ Returns partitions matching exclusion filters. """ if S_ISBLK(os.stat('/dev/{0}'.format(diskDevice)).st_mode) and os.path.exists('/sys/block/{0}'.format(diskDevice)): parts = [p.replace('/sys/block/{0}/'.format(diskDevice), '') for p in glob.glob('/sys/block/{0}/{0}*'.format(diskDevice))] fsexclude = [False] if skipExtended: fsexclude.append('Extended') if skipSwap: fsexclude.append('swap') return [part for part in parts if getFsType(part) not in fsexclude] else: return None def getSwapPartitions(devices=getDisks()): """ Returns partition devices with Linux Swap type. """ ret = [] for diskDevice in devices: parts = [p.replace('/sys/block/{0}/'.format(diskDevice), '') for p in glob.glob('/sys/block/{0}/{0}*'.format(diskDevice))] ret.extend([part for part in parts if getFsType(part) == 'swap']) return ret def getPartitionInfo(partitionDevice): """ Returns a dictionary with the partition information: - fstype - label - size - sizeHuman - partId if sfdisk/sgdisk is installed or None otherwise. """ checkRoot() if S_ISBLK(os.stat('/dev/{0}'.format(partitionDevice)).st_mode): fstype = getFsType(partitionDevice) label = getFsLabel(partitionDevice) diskDevice = re.sub(r'[0-9]*$', '', partitionDevice) if re.match(r'^.+[0-9]p$', diskDevice): diskDevice = diskDevice[:-1] blockSize = int(open('/sys/block/{0}/queue/logical_block_size'.format(diskDevice), 'r').read().strip()) size = int(open('/sys/block/{0}/{1}/size'.format(diskDevice, partitionDevice), 'r').read().strip()) * blockSize sizeHuman = getHumanSize(size) partId = None try: partId = execGetOutput(r"/sbin/sfdisk --dump /dev/sda 2>/dev/null|sed -rn '\,^/dev/{0},{s/.*, Id= *([^,]+),?.*/\1/p}'".format(partitionDevice), shell=True)[0] except: pass return {'fstype': fstype, 'label': label, 'size': size, 'sizeHuman': sizeHuman, 'partId': partId} else: return None
class ConcreteComponentA; class ConcreteComponentB; //访问者基类;因为我们有两个组件A和B,所以访问者提供了对两个组件的访问; class Visitor{ public: virtual void VisitConcreteComponentA(const ConcreteComponentA *element)const=0; virtual void VisitConcreteComponentB(const ConcreteComponentB *element)const=0; }; //组件基类; class Component{ public: virtual ~Component(){} virtual void Accept(Visitor *visitor) const=0; //const表示这个成员函数不会修改类的成员变量; }; //具体组件类; class ConcreteComponentA:public Component{ public: //accept函数用于接收访问者,传入的访问者对象可以访问其访问该组件的函数;将组件本身传给访问者的访问函数; void Accept(Visitor *visitor)const override{ visitor->VisitConcreteComponentA(this); //接收的这个访问者可以访问该成分; } std::string ExclusiveMethodofConcreteComponentA() const { return "A"; } }; class ConcreteComponentB : public Component { /** * Same here: visitConcreteComponentB => ConcreteComponentB */ public: void Accept(Visitor *visitor) const override { visitor->VisitConcreteComponentB(this); } std::string SpecialMethodOfConcreteComponentB() const { return "B"; } }; //具体的访问者;每一个访问者都会有访问每个组件的函数;其需要组件对象的地址; class ConcreteVisitor1:public Visitor{ public: void VisitConcreteComponentA(const ConcreteComponentA *element)const override{ std::cout << element->ExclusiveMethodOfConcreteComponentA() << " + ConcreteVisitor1\n"; } void VisitConcreteComponentB(const ConcreteComponentB *element) const override { std::cout << element->SpecialMethodOfConcreteComponentB() << " + ConcreteVisitor1\n"; } }; class ConcreteVisitor2 : public Visitor { public: void VisitConcreteComponentA(const ConcreteComponentA *element) const override { std::cout << element->ExclusiveMethodOfConcreteComponentA() << " + ConcreteVisitor2\n"; } void VisitConcreteComponentB(const ConcreteComponentB *element) const override { std::cout << element->SpecialMethodOfConcreteComponentB() << " + ConcreteVisitor2\n"; } }; void ClientCode(std::array<const Component *, 2> components, Visitor *visitor) { // ... for (const Component *comp : components) { comp->Accept(visitor); } // ... } int main() { std::array<const Component *, 2> components = {new ConcreteComponentA, new ConcreteComponentB}; //创建一个std::array容器,存储了所有可用的组件对象; std::cout << "The client code works with all visitors via the base Visitor interface:\n"; ConcreteVisitor1 *visitor1 = new ConcreteVisitor1; //创建访问者对象; ClientCode(components, visitor1); std::cout << "\n"; std::cout << "It allows the same client code to work with different types of visitors:\n"; ConcreteVisitor2 *visitor2 = new ConcreteVisitor2; ClientCode(components, visitor2); for (const Component *comp : components) { delete comp; } delete visitor1; delete visitor2; return 0; } /* The client code works with all visitors via the base Visitor interface: A + ConcreteVisitor1 B + ConcreteVisitor1 It allows the same client code to work with different types of visitors: A + ConcreteVisitor2 B + ConcreteVisitor2 */
#include <stdio.h> #include <stdbool.h> #include <limits.h> int main() { int sum = 0; int n_numbers = 0; // iniciar "lower" com o máximo valor possível // iniciar "greater" com o minímo valor possível // assim quaisquer que sejam os valores introduzidos // "lower" e "greater" serão devidamente iniciados int lower = INT_MAX, greater = INT_MIN; int n; while(scanf("%d", &n) == 1) { if (n > greater) greater = n; if (n < lower) lower = n; sum += n; n_numbers++; } // show stats if (n_numbers < 3) { printf("dados inválidos!\n"); } else { double mean = (sum - (lower + greater))/ ((double) n_numbers - 2); printf("greater=%d\n", greater); printf("lower=%d\n", lower); printf("mean=%lf\n", mean); } return 0; }
/* * Copyright 2012 - 2013 Kulykov Oleh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __REPOINT2_H__ #define __REPOINT2_H__ #include "RECommonHeader.h" #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) #include <arm_neon.h> #endif class REString; typedef struct _REPoint2Struct { union { struct { REFloat32 x; REFloat32 y; }; #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) float32x2_t armNeonPoint; #endif REFloat32 coords[2]; }; } REPoint2Struct; /// Class using for presenting 2D Point with 'x' and 'y' float coordinates. class __RE_PUBLIC_CLASS_API__ REPoint2 { public: union { struct { /// X coordinate. REFloat32 x; /// Y coordinate. REFloat32 y; }; #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) /// used for arm optimizations float32x2_t armNeonPoint; #endif /// array of 'x' and 'y' REFloat32 coords[2]; }; /// Copy operator. This point will be same as anotherPoint struct. REPoint2 & operator=(const REPoint2Struct & anotherPoint) { #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) armNeonPoint = anotherPoint.armNeonPoint; #else x = anotherPoint.x; y = anotherPoint.y; #endif return (*this); } /// Copy operator. This point will be same as anotherPoint. REPoint2 & operator=(const REPoint2 & anotherPoint) { #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) armNeonPoint = anotherPoint.armNeonPoint; #else x = anotherPoint.x; y = anotherPoint.y; #endif return (*this); } /// Constructs 2D Point with 'newX' - X coordinate and 'newY' - Y coordinate. REPoint2(const REFloat32 newX, const REFloat32 newY) : x(newX), y (newY) { } /// Constructs 2D Point same as anotherPoint struct. REPoint2(const REPoint2Struct & anotherPoint) : #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) armNeonPoint(anotherPoint.armNeonPoint) { } #else x(anotherPoint.x), y(anotherPoint.y) { } #endif /// Constructs 2D Point same as anotherPoint. REPoint2(const REPoint2 & anotherPoint) : #if defined(__ARM_NEON__) || defined(HAVE_ARM_NEON_H) armNeonPoint(anotherPoint.armNeonPoint) { } #else x(anotherPoint.x), y(anotherPoint.y) { } #endif /// Constructs 2D Point and sets 'x' and 'y' coordinates to 0. REPoint2() : x(0.0f), y(0.0f) { } ~REPoint2() { } /// Objective-c additions #if (defined(CG_EXTERN) || defined(CG_INLINE)) && defined(CGFLOAT_TYPE) CGPoint getCGPoint() const { CGPoint p; p.x = (CGFloat)x; p.y = (CGFloat)y; return p; } REPoint2 & operator=(const CGPoint & anotherPoint) { x = (REFloat32)anotherPoint.x; y = (REFloat32)anotherPoint.y; return (*this); } REPoint2(const CGPoint & anotherPoint) : x((REFloat32)anotherPoint.x), y((REFloat32)anotherPoint.y) { } #endif static REPoint2 fromString(const char * string); static REPoint2 fromString(const REString & string); static REString toString(const REPoint2 & point); }; #endif /* __REPOINT2_H__ */
class Solution { public: void helper(vector<int>& candidates,int target, vector<int> v,vector<vector<int>> &res,int index) { if(target==0){ res.push_back(v); return; } for(int i=index;i<candidates.size();i++) { if( i>index && candidates[i]==candidates[i-1] ) continue; if(candidates[i]> target) break; v.push_back(candidates[i]); helper(candidates,target-candidates[i],v,res,i+1); v.pop_back(); } return; } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> ans; vector<int> v; sort(candidates.begin(),candidates.end()); helper(candidates,target,v,ans,0); return ans; } };
START-IMPORT-TASK() START-IMPORT-TASK() NAME start-import-task - DESCRIPTION Starts an import task, which allows you to import details of your on-premises environment directly into Amazon Web Services Migration Hub without having to use the Amazon Web Services Application Discovery Service (Application Discovery Service) tools such as the Amazon Web Services Application Discovery Service Agentless Collector or Applica- tion Discovery Agent. This gives you the option to perform migration assessment and planning directly from your imported data, including the ability to group your devices as applications and track their migration status. To start an import request, do this: o Download the specially formatted comma separated value (CSV) import template, which you can find here: https://s3.us-west-2.amazonaws.com/templates-7cffcf56-bd96-4b1c-b45b-a5b42f282e46/import_template.csv . o Fill out the template with your server and application data. o Upload your import file to an Amazon S3 bucket, and make a note of it's Object URL. Your import file must be in the CSV format. o Use the console or the StartImportTask command with the Amazon Web Services CLI or one of the Amazon Web Services SDKs to import the records from your file. For more information, including step-by-step procedures, see Migration Hub Import in the Amazon Web Services Application Discovery Service User Guide . NOTE: There are limits to the number of import tasks you can create (and delete) in an Amazon Web Services account. For more information, see Amazon Web Services Application Discovery Service Limits in the Ama- zon Web Services Application Discovery Service User Guide . See also: AWS API Documentation SYNOPSIS start-import-task [--client-request-token <value>] --name <value> --import-url <value> [--cli-input-json <value>] [--generate-cli-skeleton <value>] [--debug] [--endpoint-url <value>] [--no-verify-ssl] [--no-paginate] [--output <value>] [--query <value>] [--profile <value>] [--region <value>] [--version <value>] [--color <value>] [--no-sign-request] [--ca-bundle <value>] [--cli-read-timeout <value>] [--cli-connect-timeout <value>] OPTIONS --client-request-token (string) Optional. A unique token that you can provide to prevent the same import request from occurring more than once. If you don't provide a token, a token is automatically generated. Sending more than one StartImportTask request with the same client request token will return information about the original import task with that client request token. --name (string) A descriptive name for this request. You can use this name to filter future requests related to this import task, such as identifying ap- plications and servers that were included in this import task. We recommend that you use a meaningful name for each import task. --import-url (string) The URL for your import file that you've uploaded to Amazon S3. NOTE: If you're using the Amazon Web Services CLI, this URL is struc- tured as follows: s3://BucketName/ImportFileName.CSV --cli-input-json (string) Performs service operation based on the JSON string provided. The JSON string follows the format provided by --gen- erate-cli-skeleton. If other arguments are provided on the command line, the CLI values will override the JSON-provided values. It is not possible to pass arbitrary binary values using a JSON-provided value as the string will be taken literally. --generate-cli-skeleton (string) Prints a JSON skeleton to standard output without sending an API request. If provided with no value or the value input, prints a sample input JSON that can be used as an argument for --cli-input-json. If provided with the value output, it validates the command inputs and returns a sample output JSON for that command. GLOBAL OPTIONS --debug (boolean) Turn on debug logging. --endpoint-url (string) Override command's default URL with the given URL. --no-verify-ssl (boolean) By default, the AWS CLI uses SSL when communicating with AWS services. For each SSL connection, the AWS CLI will verify SSL certificates. This option overrides the default behavior of verifying SSL certificates. --no-paginate (boolean) Disable automatic pagination. --output (string) The formatting style for command output. o json o text o table --query (string) A JMESPath query to use in filtering the response data. --profile (string) Use a specific profile from your credential file. --region (string) The region to use. Overrides config/env settings. --version (string) Display the version of this tool. --color (string) Turn on/off color output. o on o off o auto --no-sign-request (boolean) Do not sign requests. Credentials will not be loaded if this argument is provided. --ca-bundle (string) The CA certificate bundle to use when verifying SSL certificates. Over- rides config/env settings. --cli-read-timeout (int) The maximum socket read time in seconds. If the value is set to 0, the socket read will be blocking and not timeout. The default value is 60 seconds. --cli-connect-timeout (int) The maximum socket connect time in seconds. If the value is set to 0, the socket connect will be blocking and not timeout. The default value is 60 seconds. OUTPUT task -> (structure) An array of information related to the import task request including status information, times, IDs, the Amazon S3 Object URL for the im- port file, and more. importTaskId -> (string) The unique ID for a specific import task. These IDs aren't glob- ally unique, but they are unique within an Amazon Web Services account. clientRequestToken -> (string) A unique token used to prevent the same import request from oc- curring more than once. If you didn't provide a token, a token was automatically generated when the import task request was sent. name -> (string) A descriptive name for an import task. You can use this name to filter future requests related to this import task, such as identifying applications and servers that were included in this import task. We recommend that you use a meaningful name for each import task. importUrl -> (string) The URL for your import file that you've uploaded to Amazon S3. status -> (string) The status of the import task. An import can have the status of IMPORT_COMPLETE and still have some records fail to import from the overall request. More information can be found in the down- loadable archive defined in the errorsAndFailedEntriesZip field, or in the Migration Hub management console. importRequestTime -> (timestamp) The time that the import task request was made, presented in the Unix time stamp format. importCompletionTime -> (timestamp) The time that the import task request finished, presented in the Unix time stamp format. importDeletedTime -> (timestamp) The time that the import task request was deleted, presented in the Unix time stamp format. serverImportSuccess -> (integer) The total number of server records in the import file that were successfully imported. serverImportFailure -> (integer) The total number of server records in the import file that failed to be imported. applicationImportSuccess -> (integer) The total number of application records in the import file that were successfully imported. applicationImportFailure -> (integer) The total number of application records in the import file that failed to be imported. errorsAndFailedEntriesZip -> (string) A link to a compressed archive folder (in the ZIP format) that contains an error log and a file of failed records. You can use these two files to quickly identify records that failed, why they failed, and correct those records. Afterward, you can up- load the corrected file to your Amazon S3 bucket and create an- other import task request. This field also includes authorization information so you can confirm the authenticity of the compressed archive before you download it. If some records failed to be imported we recommend that you cor- rect the records in the failed entries file and then imports that failed entries file. This prevents you from having to cor- rect and update the larger original file and attempt importing it again. START-IMPORT-TASK()
import { useState } from "react"; import { GrPowerReset } from "react-icons/gr"; type Props = { initialCount?: number; min?: number; max?: number; }; export default function Counter({ initialCount = 0, min = -5, max = 5, }: Props) { const [count, setCount] = useState(initialCount); const increment = () => setCount((c) => (c < max ? c + 1 : c)); const decrement = () => setCount((c) => (c > min ? c - 1 : c)); const reset = () => setCount(initialCount); return ( <> <div className="flex justify-between gap-8"> <button className="text-4xl font-bold" onClick={decrement} disabled={count <= min} > - </button> <h1>{count}</h1> <button className="text-4xl font-bold" onClick={increment} disabled={count >= max} > + </button> </div> <button className="mt-4" onClick={reset}> <GrPowerReset size={25} /> </button> </> ); }
import { Context, CodePipelineEvent } from 'aws-lambda'; import * as CodePipeline from 'aws-sdk/clients/codepipeline'; import { Octokit } from '@octokit/core'; let codePipelineClient: CodePipeline; exports.handler = async ( event: CodePipelineEvent, context: Context, ): Promise<any> => { context.callbackWaitsForEmptyEventLoop = false; if (!codePipelineClient) codePipelineClient = new CodePipeline(); const jobID = event['CodePipeline.job'].id; const jobIDShort = jobID.split('-')[0]; const userParameters = event['CodePipeline.job'].data.actionConfiguration.configuration .UserParameters; const parameter = JSON.parse(userParameters); const repoName = parameter['GITHUB_REPO'] || ''; const repoOwner = parameter['GITHUB_REPO_OWNER'] || ''; const gitSourceBranch = parameter['GITHUB_SOURCE_BRANCH'] || ''; const gitDestBranch = parameter['GITHUB_DEST_BRANCH'] || ''; const authToken = parameter['GITHUB_OAUTH_TOKEN'] || ''; const octokit = new Octokit({ auth: authToken }); const branchExists = await checkBranchExists( octokit, repoOwner, repoName, gitDestBranch, ); if (!branchExists) { try { console.log(`Creating branch '${gitDestBranch}' ...`); const sourceBranchSha = await getBranchSha( octokit, repoOwner, repoName, gitSourceBranch, ); const response = await octokit.request( 'POST /repos/{owner}/{repo}/git/refs', { owner: repoOwner, repo: repoName, ref: `refs/heads/${gitDestBranch}`, sha: sourceBranchSha || '', }, ); console.log(`Created branch: ${JSON.stringify(response.data.ref)}`); return await putJobSuccess(jobID); } catch (error) { console.error(`Error creating branch: ${JSON.stringify(error)}`); return await putJobFailure(context, jobID, error); } } else { console.log(`Branch '${gitDestBranch}' exists.`); const pullRequestTitle = `CodePipeline Auto-Pull-Request (Job Id: ${jobIDShort})`; const pullRequestBody = `Automated pull request to merge ${gitSourceBranch} into ${gitDestBranch}.`; try { const pullResponse = await octokit.request( 'POST /repos/{owner}/{repo}/pulls', { owner: repoOwner, repo: repoName, head: gitSourceBranch, base: gitDestBranch, title: pullRequestTitle, body: pullRequestBody, }, ); console.log(`Opened pull request #${pullResponse.data.number}`); return await putJobSuccess(jobID); } catch (error) { if (error.message.includes('pull request already exists')) { console.log(`${error.message}. Skipping ...`); return await putJobSuccess(jobID); } if (error.message.includes('No commits between')) { console.log(`${error.message}. Skipping ...`); return await putJobSuccess(jobID); } console.error(`Error creating pull request: ${JSON.stringify(error)}`); return await putJobFailure(context, jobID, error); } } }; const checkBranchExists = async ( octokit: Octokit, repoOwner: string, repoName: string, gitDestBranch: string, ) => { try { const refResponse = await octokit.request( 'GET /repos/{owner}/{repo}/branches/{branch}', { owner: repoOwner, repo: repoName, branch: gitDestBranch, }, ); if (refResponse.status == 200) return true; return false; } catch (error) { return false; } }; const getBranchSha = async ( octokit: Octokit, repoOwner: string, repoName: string, branchName: string, ) => { try { const response = await octokit.request( 'GET /repos/{owner}/{repo}/branches/{branch}', { owner: repoOwner, repo: repoName, branch: branchName, }, ); if (response.status == 200) return response.data.commit.sha; return false; } catch (error) { console.error(`Error: ${error}`); return false; } }; const putJobFailure = async (context: Context, jobID: string, error: any) => { return await codePipelineClient .putJobFailureResult({ jobId: jobID, failureDetails: { type: 'JobFailed', message: error.message, externalExecutionId: context.awsRequestId, }, }) .promise(); }; const putJobSuccess = async (jobID: string) => { return await codePipelineClient .putJobSuccessResult({ jobId: jobID }) .promise(); };
import React, { useEffect, useState } from "react"; import InputAdornment from "@material-ui/core/InputAdornment"; import IconButton from "@material-ui/core/IconButton"; import Visibility from "@material-ui/icons/Visibility"; import VisibilityOff from "@material-ui/icons/VisibilityOff"; import { ValidatorForm, TextValidator } from "react-material-ui-form-validator"; import { updatePassword } from "../../redux/actions/profile"; import { connect } from "react-redux"; function PasswordProfile(props) { const [values, setValues] = useState({ newPassword: "", oldPassword: "", confirmPassword: "", showPassword: false, keepLoggedIn: false, }); const [isSubmitting, setisSubmitting] = useState(false); const { token } = props.loginReducer; const { error,message } = props.profileReducer; const handleChange = (prop) => (event) => { setValues({ ...values, [prop]: event.target.value }); }; const handleClickShowPassword = () => { setValues({ ...values, showPassword: !values.showPassword }); }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; const handleSubmit = async(event) => { event.preventDefault(); await props.updatePassword( { oldPassword: values.oldPassword, newPassword: values.newPassword, newConfirmPassword: values.confirmPassword, }, token ); setisSubmitting(true); }; useEffect(() => { // custom rule will have name 'isPasswordValid' // ValidatorForm.addValidationRule("isPasswordValid", (value) => { // if (value.length < 5) { // return false; // } // return true; // }); // custom rule will have name 'isPasswordMatch' ValidatorForm.addValidationRule("isPasswordMatch", (value) => { console.log("value:", value, "values:", values); if (value !== values.newPassword) { return false; } return true; }); return () => { //cleanup: remove rule when it is not needed // ValidatorForm.removeValidationRule("isPasswordValid"); ValidatorForm.removeValidationRule("isPasswordMatch"); }; }, [values.newPassword, values.oldPassword, values.confirmPassword]); return ( <div className="w-full p-10" onClick={props.onClick}> <h3 className="text-2xl font-medium">Change Password</h3> <br /> <ValidatorForm className="" validate="true" ref={React.createRef("form")} onSubmit={handleSubmit} onError={(errors) => console.log(errors)} > <div className="w-full"> <p className="mb-3 w-full text-sm">Old Password</p> <TextValidator id="outlined-adornment-password" variant="outlined" className="w-full" placeholder="Password" onChange={handleChange("oldPassword")} name="password" value={values.oldPassword} type={values.showPassword ? "text" : "password"} // validators={["required", "isPasswordValid"]} // errorMessages={[ // "This field is required", // "Password is less than 5 characters", // ]} validators={["required"]} errorMessages={["This field is required"]} InputProps={{ endAdornment: ( <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {values.showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> ), }} /> </div> <div className="w-full mt-6"> <p className="mb-3 w-full text-sm">New Password</p> <TextValidator id="outlined-adornment-password" variant="outlined" className="w-full" placeholder="Password" onChange={handleChange("newPassword")} name="password" value={values.newPassword} type={values.showPassword ? "text" : "password"} validators={["required"]} errorMessages={["This field is required"]} InputProps={{ endAdornment: ( <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {values.showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> ), }} /> </div> <div className="my-6"> <p className="mb-3 text-sm">Confirm New Password</p> <TextValidator id="outlined-adornment-password" variant="outlined" className="w-full" placeholder="Confirm Password" onChange={handleChange("confirmPassword")} name="password" value={values.confirmPassword} type={values.showPassword ? "text" : "password"} validators={["required", "isPasswordMatch"]} errorMessages={["This field is required", "Password mismatch"]} InputProps={{ endAdornment: ( <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {values.showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> ), }} /> {error && isSubmitting && <p className="text-red-500 pt-4">{error?.message}</p>} {message && isSubmitting && <p className="text-green-500 pt-4">{message}</p>} </div> <br /> {(values.newPassword || values.oldPassword || values.confirmPassword) && ( <button className="bg-gradient-to-r from-ansBlue2 to-ansBlue3 p-3 text-white m-1 font-body font-medium text-base rounded w-full" type="submit" > Save Changes </button> )} </ValidatorForm> </div> ); } const mapStateToProps = (state) => { return { ...state, }; }; export default connect(mapStateToProps, { updatePassword, })(PasswordProfile);
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "InputCoreTypes.h" #include "UObject/GCObject.h" #include "UnrealWidgetFwd.h" #include "Editor.h" #include "EditorUndoClient.h" #include "Widgets/Layout/SWidgetSwitcher.h" #include "EdMode.h" #include "Elements/Framework/TypedElementSelectionSet.h" class FCanvas; class FEditorViewportClient; class FEdMode; class FModeTool; class FPrimitiveDrawInterface; class FSceneView; class FViewport; class IToolkitHost; class USelection; struct FConvexVolume; struct FViewportClick; class UEdMode; class UInteractiveGizmoManager; class UInputRouter; class UModeManagerInteractiveToolsContext; class UTypedElementSelectionSet; /** * A helper class to store the state of the various editor modes. */ class FEditorModeTools : public FGCObject, public FEditorUndoClient, public TSharedFromThis<FEditorModeTools> { public: UNREALED_API FEditorModeTools(); UNREALED_API virtual ~FEditorModeTools(); /** * Set the default editor mode for these tools * * @param DefaultModeID The mode ID for the new default mode */ UNREALED_API void SetDefaultMode( const FEditorModeID DefaultModeID ); /** * Adds a new default mode to this tool's list of default modes. You can have multiple default modes, but they all must be compatible with each other. * * @param DefaultModeID The mode ID for the new default mode */ UNREALED_API void AddDefaultMode( const FEditorModeID DefaultModeID ); /** * Removes a default mode * * @param DefaultModeID The mode ID for the default mode to remove */ UNREALED_API void RemoveDefaultMode( const FEditorModeID DefaultModeID ); /** * Returns whether or not the provided mode ID is a default mode */ bool IsDefaultMode(const FEditorModeID ModeID) const { return DefaultModeIDs.Contains(ModeID); } /** * Activates the default modes defined by this class. Note that there can be more than one default mode, and this call will activate them all in sequence. */ UNREALED_API void ActivateDefaultMode(); /** * Returns true if the default modes are active. Note that there can be more than one default mode, and this will only return true if all default modes are active. */ UNREALED_API bool IsDefaultModeActive() const; /** * Activates an editor mode. Shuts down all other active modes which cannot run with the passed in mode. * * @param InID The ID of the editor mode to activate. * @param bToggle true if the passed in editor mode should be toggled off if it is already active. */ UNREALED_API void ActivateMode( FEditorModeID InID, bool bToggle = false ); /** * Deactivates an editor mode. * * @param InID The ID of the editor mode to deactivate. */ UNREALED_API void DeactivateMode(FEditorModeID InID); /** * Deactivate the mode and entirely purge it from memory. Used when a mode type is unregistered */ UNREALED_API void DestroyMode(FEditorModeID InID); /** * Whether or not the mode toolbox (where mode details panels and some tools are) should be shown. */ UE_DEPRECATED(4.26, "Individual toolkit hosts, such as the level editor, should handle determining if they show a mode toolbox for hosted toolkits.") UNREALED_API bool ShouldShowModeToolbox() const; protected: /** Exits the given editor mode */ UNREALED_API void ExitMode(UEdMode* InMode); /** Removes the mode ID from the tools manager when a mode is unregistered */ UNREALED_API void OnModeUnregistered(FEditorModeID ModeID); UNREALED_API void DeactivateModeAtIndex(int32 Index); public: /** * Deactivates all modes, note some modes can never be deactivated. */ UNREALED_API void DeactivateAllModes(); UNREALED_API UEdMode* GetActiveScriptableMode(FEditorModeID InID) const; UNREALED_API virtual UTexture2D* GetVertexTexture() const; /** * Returns true if the current mode is not the specified ModeID. Also optionally warns the user. * * @param ModeID The editor mode to query. * @param ErrorMsg If specified, inform the user the reason why this is a problem * @param bNotifyUser If true, display the error as a notification, instead of a dialog * @return true if the current mode is not the specified mode. */ UNREALED_API bool EnsureNotInMode(FEditorModeID ModeID, const FText& ErrorMsg = FText::GetEmpty(), bool bNotifyUser = false) const; UNREALED_API FMatrix GetCustomDrawingCoordinateSystem(); UNREALED_API FMatrix GetCustomInputCoordinateSystem(); UNREALED_API FMatrix GetLocalCoordinateSystem(); /** * Returns true if the passed in editor mode is active */ UNREALED_API bool IsModeActive( FEditorModeID InID ) const; /** * Returns a pointer to an active mode specified by the passed in ID * If the editor mode is not active, NULL is returned */ UNREALED_API FEdMode* GetActiveMode( FEditorModeID InID ); UNREALED_API const FEdMode* GetActiveMode( FEditorModeID InID ) const; template <typename SpecificModeType> SpecificModeType* GetActiveModeTyped( FEditorModeID InID ) { return static_cast<SpecificModeType*>(GetActiveMode(InID)); } template <typename SpecificModeType> const SpecificModeType* GetActiveModeTyped( FEditorModeID InID ) const { return static_cast<SpecificModeType*>(GetActiveMode(InID)); } /** * Returns the active tool of the passed in editor mode. * If the passed in editor mode is not active or the mode has no active tool, NULL is returned */ UNREALED_API const FModeTool* GetActiveTool( FEditorModeID InID ) const; void SetShowWidget( bool InShowWidget ) { bShowWidget = InShowWidget; } UNREALED_API bool GetShowWidget() const; /** Cycle the widget mode, forwarding queries to modes */ UNREALED_API void CycleWidgetMode (void); /** Check with modes to see if the widget mode can be cycled */ UNREALED_API bool CanCycleWidgetMode() const; /**Save Widget Settings to Ini file*/ UNREALED_API void SaveWidgetSettings(); /**Load Widget Settings from Ini file*/ UNREALED_API void LoadWidgetSettings(); /** Gets the widget axis to be drawn */ UNREALED_API EAxisList::Type GetWidgetAxisToDraw( UE::Widget::EWidgetMode InWidgetMode ) const; /** Mouse tracking interface. Passes tracking messages to all active modes */ UNREALED_API bool StartTracking(FEditorViewportClient* InViewportClient, FViewport* InViewport); UNREALED_API bool EndTracking(FEditorViewportClient* InViewportClient, FViewport* InViewport); bool IsTracking() const { return bIsTracking; } UNREALED_API bool AllowsViewportDragTool() const; /** Notifies all active modes that a map change has occured */ UNREALED_API void MapChangeNotify(); /** Notifies all active modes to empty their selections */ UNREALED_API void SelectNone(); /** Notifies all active modes of box selection attempts */ UNREALED_API bool BoxSelect( FBox& InBox, bool InSelect ); /** Notifies all active modes of frustum selection attempts */ UNREALED_API bool FrustumSelect( const FConvexVolume& InFrustum, FEditorViewportClient* InViewportClient, bool InSelect ); /** true if any active mode uses a transform widget */ UNREALED_API bool UsesTransformWidget() const; /** true if any active mode uses the passed in transform widget */ UNREALED_API bool UsesTransformWidget( UE::Widget::EWidgetMode CheckMode ) const; /** Sets the current widget axis */ UNREALED_API void SetCurrentWidgetAxis( EAxisList::Type NewAxis ); /** Notifies all active modes of mouse click messages. */ UNREALED_API bool HandleClick(FEditorViewportClient* InViewportClient, HHitProxy *HitProxy, const FViewportClick &Click ); /** * Allows editor modes to override the bounding box used to focus the viewport on a selection * * @param Actor The selected actor that is being considered for focus * @param PrimitiveComponent The component in the actor being considered for focus * @param InOutBox The box that should be computed for the actor and component * @return bool true if a mode overrides the box and populated InOutBox, false if it did not populate InOutBox */ UNREALED_API bool ComputeBoundingBoxForViewportFocus(AActor* Actor, UPrimitiveComponent* PrimitiveComponent, FBox& InOutBox); /** true if the passed in brush actor should be drawn in wireframe */ UNREALED_API bool ShouldDrawBrushWireframe( AActor* InActor ) const; /** true if brush vertices should be drawn */ UNREALED_API bool ShouldDrawBrushVertices() const; /** Ticks all active modes */ UNREALED_API void Tick( FEditorViewportClient* ViewportClient, float DeltaTime ); /** Notifies all active modes of any change in mouse movement */ UNREALED_API bool InputDelta( FEditorViewportClient* InViewportClient,FViewport* InViewport,FVector& InDrag,FRotator& InRot,FVector& InScale ); /** Notifies all active modes of captured mouse movement */ UNREALED_API bool CapturedMouseMove( FEditorViewportClient* InViewportClient, FViewport* InViewport, int32 InMouseX, int32 InMouseY ); /** Notifies all active modes of all captured mouse movement */ UNREALED_API bool ProcessCapturedMouseMoves( FEditorViewportClient* InViewportClient, FViewport* InViewport, const TArrayView<FIntPoint>& CapturedMouseMoves ); /** * Notifies all active modes of keyboard input * @param bRouteToToolsContext If true, routes to the tools context and its input router before routing * to modes (and does not route to modes if tools context handles it). We currently need the ability to * set this to false due to some behaviors being routed in different conditions to legacy modes compared * to the input router (see its use in EditorViewportClient.cpp). */ UNREALED_API bool InputKey( FEditorViewportClient* InViewportClient, FViewport* Viewport, FKey Key, EInputEvent Event, bool bRouteToToolsContext = true); /** Notifies all active modes of axis movement */ UNREALED_API bool InputAxis( FEditorViewportClient* InViewportClient, FViewport* Viewport, int32 ControllerId, FKey Key, float Delta, float DeltaTime); UNREALED_API bool MouseEnter( FEditorViewportClient* InViewportClient, FViewport* Viewport, int32 X, int32 Y ); UNREALED_API bool MouseLeave( FEditorViewportClient* InViewportClient, FViewport* Viewport ); /** Notifies all active modes that the mouse has moved */ UNREALED_API bool MouseMove( FEditorViewportClient* InViewportClient, FViewport* Viewport, int32 X, int32 Y ); /** Notifies all active modes that a viewport has received focus */ UNREALED_API bool ReceivedFocus( FEditorViewportClient* InViewportClient, FViewport* Viewport ); /** Notifies all active modes that a viewport has lost focus */ UNREALED_API bool LostFocus( FEditorViewportClient* InViewportClient, FViewport* Viewport ); /** Draws all active modes */ UNREALED_API void DrawActiveModes( const FSceneView* InView, FPrimitiveDrawInterface* PDI ); /** Renders all active modes */ UNREALED_API void Render( const FSceneView* InView, FViewport* Viewport, FPrimitiveDrawInterface* PDI ); /** Draws the HUD for all active modes */ UNREALED_API void DrawHUD( FEditorViewportClient* InViewportClient,FViewport* Viewport,const FSceneView* View,FCanvas* Canvas ); /** * Get a pivot point specified by any active modes around which the camera should orbit * @param OutPivot The custom pivot point returned by the mode/tool * @return true if a custom pivot point was specified, false otherwise. */ UNREALED_API bool GetPivotForOrbit( FVector& OutPivot ) const; /** Calls PostUndo on all active modes */ // Begin FEditorUndoClient UNREALED_API virtual void PostUndo(bool bSuccess) override; UNREALED_API virtual void PostRedo(bool bSuccess) override; // End of FEditorUndoClient /** True if we should allow widget move */ UNREALED_API bool AllowWidgetMove() const; /** True if we should disallow mouse delta tracking. */ UNREALED_API bool DisallowMouseDeltaTracking() const; /** Get a cursor to override the default with, if any */ UNREALED_API bool GetCursor(EMouseCursor::Type& OutCursor) const; /** Get override cursor visibility settings */ UNREALED_API bool GetOverrideCursorVisibility(bool& bWantsOverride, bool& bHardwareCursorVisible, bool bSoftwareCursorVisible) const; /** Called before converting mouse movement to drag/rot */ UNREALED_API bool PreConvertMouseMovement(FEditorViewportClient* InViewportClient); /** Called after converting mouse movement to drag/rot */ UNREALED_API bool PostConvertMouseMovement(FEditorViewportClient* InViewportClient); /** * Returns a good location to draw the widget at. */ UNREALED_API FVector GetWidgetLocation() const; /** * Changes the current widget mode. */ UNREALED_API void SetWidgetMode( UE::Widget::EWidgetMode InWidgetMode ); /** * Allows you to temporarily override the widget mode. Call this function again * with WM_None to turn off the override. */ UNREALED_API void SetWidgetModeOverride( UE::Widget::EWidgetMode InWidgetMode ); /** * Retrieves the current widget mode, taking overrides into account. */ UNREALED_API UE::Widget::EWidgetMode GetWidgetMode() const; /** * Set Scale On The Widget */ UNREALED_API void SetWidgetScale(float InScale); /** * Get Widget Scale */ UNREALED_API float GetWidgetScale() const; // FGCObject interface UNREALED_API virtual void AddReferencedObjects( FReferenceCollector& Collector ) override; virtual FString GetReferencerName() const override { return TEXT("FEditorModeTools"); } // End of FGCObject interface /** * Loads the state that was saved in the INI file */ UNREALED_API void LoadConfig(void); /** * Saves the current state to the INI file */ UNREALED_API void SaveConfig(void); /** * Sets the pivot locations * * @param Location The location to set * @param bIncGridBase Whether or not to also set the GridBase */ UNREALED_API void SetPivotLocation( const FVector& Location, const bool bIncGridBase ); /** * Multicast delegate for OnModeEntered and OnModeExited callbacks. * * First parameter: The editor mode that was changed * Second parameter: True if entering the mode, or false if exiting the mode */ DECLARE_EVENT_TwoParams(FEditorModeTools, FEditorModeIDChangedEvent, const FEditorModeID&, bool); FEditorModeIDChangedEvent& OnEditorModeIDChanged() { return EditorModeIDChangedEvent; } /** delegate type for triggering when widget mode changed */ DECLARE_EVENT_OneParam( FEditorModeTools, FWidgetModeChangedEvent, UE::Widget::EWidgetMode ); FWidgetModeChangedEvent& OnWidgetModeChanged() { return WidgetModeChangedEvent; } /** Broadcasts the WidgetModeChanged event */ void BroadcastWidgetModeChanged(UE::Widget::EWidgetMode InWidgetMode) { WidgetModeChangedEvent.Broadcast(InWidgetMode); } /** Broadcasts the EditorModeIDChanged event */ void BroadcastEditorModeIDChanged(const FEditorModeID& ModeID, bool IsEnteringMode) { EditorModeIDChangedEvent.Broadcast(ModeID, IsEnteringMode); } /** delegate type for triggering when coordinate system changed */ DECLARE_EVENT_OneParam(FEditorModeTools, FCoordSystemChangedEvent, ECoordSystem); FCoordSystemChangedEvent& OnCoordSystemChanged() { return CoordSystemChangedEvent; } /** Broadcasts the CoordSystemChangedEvent event */ void BroadcastCoordSystemChanged(ECoordSystem InCoordSystem) { CoordSystemChangedEvent.Broadcast(InCoordSystem); } /** * Returns the current CoordSystem * * @param bGetRawValue true when you want the actual value of CoordSystem, not the value modified by the state. */ UNREALED_API ECoordSystem GetCoordSystem(bool bGetRawValue = false); /** Sets the current CoordSystem */ UNREALED_API void SetCoordSystem(ECoordSystem NewCoordSystem); /** Sets the hide viewport UI state */ void SetHideViewportUI( bool bInHideViewportUI ) { bHideViewportUI = bInHideViewportUI; } /** Is the viewport UI hidden? */ bool IsViewportUIHidden() const { return bHideViewportUI; } /** Called by Editors when they are about to close */ UNREALED_API bool OnRequestClose(); bool PivotShown; bool Snapping; bool SnappedActor; FVector CachedLocation; FVector PivotLocation; FVector SnappedLocation; FVector GridBase; /** The angle for the translate rotate widget */ float TranslateRotateXAxisAngle; /** The angles for the 2d translate rotate widget */ float TranslateRotate2DAngle; /** Draws in the top level corner of all FEditorViewportClient windows (can be used to relay info to the user). */ FString InfoString; /** Sets the host for toolkits created via modes from this mode manager (can only be called once) */ UNREALED_API void SetToolkitHost(TSharedRef<IToolkitHost> Host); /** Returns the host for toolkits created via modes from this mode manager */ UNREALED_API TSharedPtr<IToolkitHost> GetToolkitHost() const; /** Check if toolkit host exists */ UNREALED_API bool HasToolkitHost() const; /** * Returns the set of selected actors. */ UNREALED_API virtual USelection* GetSelectedActors() const; /** * @return the set of selected non-actor objects. */ UNREALED_API virtual USelection* GetSelectedObjects() const; /** * Returns the set of selected components. */ UNREALED_API virtual USelection* GetSelectedComponents() const; /** * Returns the selection set for the toolkit host. * (i.e. the selection set for the level editor) */ UNREALED_API UTypedElementSelectionSet* GetEditorSelectionSet() const; /** * Stores the current selection under the given key, and clears the current selection state if requested. */ UNREALED_API void StoreSelection(FName SelectionStoreKey, bool bClearSelection = true); /** * Restores the selection to the state that was stored using the given key. */ UNREALED_API void RestoreSelection(FName SelectionStoreKey); /** * Returns the world that is being edited by this mode manager */ UNREALED_API virtual UWorld* GetWorld() const; /** * Returns the currently hovered viewport client */ UNREALED_API FEditorViewportClient* GetHoveredViewportClient() const; /** * Returns the currently focused viewport client */ UNREALED_API FEditorViewportClient* GetFocusedViewportClient() const; /** * Whether or not the current selection has a scene component selected */ UNREALED_API bool SelectionHasSceneComponent() const; UNREALED_API bool IsSelectionAllowed(AActor* InActor, const bool bInSelected) const; UNREALED_API bool IsSelectionHandled(AActor* InActor, const bool bInSelected) const; UNREALED_API bool ProcessEditDuplicate(); UNREALED_API bool ProcessEditDelete(); UNREALED_API bool ProcessEditCut(); UNREALED_API bool ProcessEditCopy(); UNREALED_API bool ProcessEditPaste(); UNREALED_API EEditAction::Type GetActionEditDuplicate(); UNREALED_API EEditAction::Type GetActionEditDelete(); UNREALED_API EEditAction::Type GetActionEditCut(); UNREALED_API EEditAction::Type GetActionEditCopy(); UNREALED_API EEditAction::Type GetActionEditPaste(); UE_DEPRECATED(5.0, "This function is redundant, and is handled as part of a call to ActivateMode.") UNREALED_API void DeactivateOtherVisibleModes(FEditorModeID InMode); UNREALED_API bool IsSnapRotationEnabled() const; UNREALED_API bool SnapRotatorToGridOverride(FRotator& InRotation) const; UNREALED_API void ActorsDuplicatedNotify(TArray<AActor*>& InPreDuplicateSelection, TArray<AActor*>& InPostDuplicateSelection, const bool bOffsetLocations); UNREALED_API void ActorMoveNotify(); UNREALED_API void ActorSelectionChangeNotify(); UNREALED_API void ActorPropChangeNotify(); UNREALED_API void UpdateInternalData(); UNREALED_API bool IsOnlyVisibleActiveMode(FEditorModeID InMode) const; UNREALED_API bool IsOnlyActiveMode(FEditorModeID InMode) const; /* * Sets the active Modes ToolBar Palette Tab to the named Palette */ //void InvokeToolPaletteTab(FEditorModeID InMode, FName InPaletteName); /** returns true if all active EdModes are OK with an AutoSave happening now */ UNREALED_API bool CanAutoSave() const; /** returns true if all active EdModes are OK support operation on current asset */ UNREALED_API bool IsOperationSupportedForCurrentAsset(EAssetOperation InOperation) const; UNREALED_API void RemoveAllDelegateHandlers(); /** @return ToolsContext for this Mode Manager */ UNREALED_API UModeManagerInteractiveToolsContext* GetInteractiveToolsContext() const; protected: /** * Delegate handlers **/ UNREALED_API void OnEditorSelectionChanged(UObject* NewSelection); UNREALED_API void OnEditorSelectNone(); /** Handles the notification when a world is going through GC to clean up any modes pending deactivation. */ UNREALED_API void OnWorldCleanup(UWorld* InWorld, bool bSessionEnded, bool bCleanupResources); UNREALED_API virtual void DrawBrackets(FEditorViewportClient* ViewportClient, FViewport* Viewport, const FSceneView* View, FCanvas* Canvas); UNREALED_API void ForEachEdMode(TFunctionRef<bool(UEdMode*)> InCalllback) const; UNREALED_API bool TestAllModes(TFunctionRef<bool(UEdMode*)> InCalllback, bool bExpected) const; template <class InterfaceToCastTo> void ForEachEdMode(TFunctionRef<bool(InterfaceToCastTo*)> InCallback) const { ForEachEdMode([InCallback](UEdMode* Mode) { if (InterfaceToCastTo* CastedMode = Cast<InterfaceToCastTo>(Mode)) { return InCallback(CastedMode); } return true; }); } UNREALED_API void ExitAllModesPendingDeactivate(); /** List of default modes for this tool. These must all be compatible with each other. */ TArray<FEditorModeID> DefaultModeIDs; /** A list of active editor modes. */ TArray< TObjectPtr<UEdMode> > ActiveScriptableModes; /** The host of the toolkits created by these modes */ TWeakPtr<IToolkitHost> ToolkitHost; /** A list of previously active editor modes that we will potentially recycle */ TMap< FEditorModeID, TObjectPtr<UEdMode> > RecycledScriptableModes; /** A list of previously active editor modes that we will potentially recycle */ TMap< FEditorModeID, TObjectPtr<UEdMode> > PendingDeactivateModes; /** The mode that the editor viewport widget is in. */ UE::Widget::EWidgetMode WidgetMode; /** If the widget mode is being overridden, this will be != WM_None. */ UE::Widget::EWidgetMode OverrideWidgetMode; /** If 1, draw the widget and let the user interact with it. */ bool bShowWidget; /** if true, the viewports will hide all UI overlays */ bool bHideViewportUI; /** if true the current selection has a scene component */ bool bSelectionHasSceneComponent; /** Scale Factor for Widget*/ float WidgetScale; TObjectPtr<UModeManagerInteractiveToolsContext> InteractiveToolsContext; private: /** The coordinate system the widget is operating within. */ ECoordSystem CoordSystem; /** Multicast delegate that is broadcast when a mode is entered or exited */ FEditorModeIDChangedEvent EditorModeIDChangedEvent; /** Multicast delegate that is broadcast when a widget mode is changed */ FWidgetModeChangedEvent WidgetModeChangedEvent; /** Multicast delegate that is broadcast when the coordinate system is changed */ FCoordSystemChangedEvent CoordSystemChangedEvent; /** Flag set between calls to StartTracking() and EndTracking() */ bool bIsTracking; /** Guard to prevent modes from entering as part of their exit routine */ bool bIsExitingModesDuringTick = false; FEditorViewportClient* HoveredViewportClient = nullptr; FEditorViewportClient* FocusedViewportClient = nullptr; TMap<FName, FTypedElementSelectionSetState> StoredSelectionSets; };
#pragma once #include <optional> #include <string> #include <functional> #include "PImpl.hh" class Toml { class Impl; using Node = PImpl<Impl, 16, 8>; Node impl_; public: using EnumArrayCallback = std::function<void(const std::string& value)>; using EnumArrayCallbackW = std::function<void(const std::wstring& value)>; using EnumTableCallback = std::function<void(const std::string& value, const Toml& toml)>; explicit Toml(Node&& node) noexcept; explicit Toml(const std::string& filename); Toml(); Toml(const Toml&) = delete; Toml(Toml&&) = default; Toml& operator=(const Toml&) = delete; Toml& operator=(Toml&&) = delete; ~Toml(); bool enumArray(EnumArrayCallback cb) const noexcept; // NOLINT bool enumArray(EnumArrayCallbackW cb) const noexcept; // NOLINT bool enumArray( // NOLINT const std::string& key, EnumArrayCallback cb) const noexcept; bool enumArray(const std::string& key, // NOLINT EnumArrayCallbackW cb) const noexcept; void enumTable(EnumTableCallback cb) const noexcept; [[nodiscard]] std::optional<Toml> operator[](const std::string& key) const; explicit operator bool() const noexcept; [[nodiscard]] std::optional<bool> as_bool() const noexcept; [[nodiscard]] std::optional<std::string> as_string() const noexcept; [[nodiscard]] std::optional<std::wstring> as_wstring() const noexcept; template <class T> std::optional<T> as() const noexcept { using R = std::decay_t<T>; if constexpr (std::is_same_v<R, bool>) { return as_bool(); } else if constexpr (std::is_same_v<R, std::wstring>) { return as_wstring(); } else if constexpr (std::is_same_v<R, std::string>) { return as_string(); } else { return {}; } } template <class T> std::optional<T> get(const std::string& key) const { auto val = operator[](key); if (val) { return val->as<T>(); } return {}; } void push(const std::string& key, const std::wstring& value); void push(const std::string& key, bool value); void save(const std::string& filename); };
/* * * Copyright (c) 2017 Xilinx, Inc. * All rights reserved. * * Author: Chris Lavin, Xilinx Research Labs. * * This file is part of RapidWright. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * */ package com.xilinx.rapidwright.edif; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * A cell instance in a logical (EDIF) netlist. Instantiates * an {@link EDIFCell}. * * Created on: May 11, 2017 */ public class EDIFCellInst extends EDIFPropertyObject implements EDIFEnumerable { private EDIFCell parentCell; private EDIFCell cellType; private EDIFName viewref; public static final EDIFName DEFAULT_VIEWREF = EDIFCell.DEFAULT_VIEW; public static final String BLACK_BOX_PROP = "IS_IMPORTED"; public static final String BLACK_BOX_PROP_VERSAL = "black_box"; private Map<String,EDIFPortInst> portInsts; protected EDIFCellInst(){ } public EDIFCellInst(String name, EDIFCell cellType, EDIFCell parentCell){ super(name); setCellType(cellType); if(parentCell != null) parentCell.addCellInst(this); viewref = cellType != null ? cellType.getEDIFView() : DEFAULT_VIEWREF; } /** * Copy constructor. Creates new objects except portInsts. * @param inst Prototype instance to copy */ public EDIFCellInst(EDIFCellInst inst, EDIFCell parentCell) { super((EDIFPropertyObject)inst); this.parentCell = parentCell; this.cellType = inst.cellType; this.viewref = new EDIFName(inst.viewref); } /** * @return the viewref */ public EDIFName getViewref() { return viewref; } /** * @param viewref the viewref to set */ public void setViewref(EDIFName viewref) { this.viewref = viewref; } /** * This gets a map of all the port refs on the cell instance. * @return A map of port ref names to port ref objects. */ public Map<String, EDIFPortInst> getPortInstMap(){ return portInsts == null ? Collections.emptyMap() : portInsts; } /** * Helper method to help maintain port ref map. Adds a new * port ref for this instance. * @param epr The port ref to add * @returns Any previous port ref of the same name, null if none already exists. */ protected EDIFPortInst addPortInst(EDIFPortInst epr) { if(portInsts == null) portInsts = new HashMap<>(); if(!epr.getCellInst().equals(this)) throw new RuntimeException("ERROR: Incorrect EDIFPortInst '"+ epr.getFullName()+"' being added to EDIFCellInst " + toString()); return portInsts.put(epr.getName(),epr); } /** * Removes the provided port ref, if it exists. * @param epr The port ref to remove. * @return The removed port ref, or null if none exists. */ protected EDIFPortInst removePortInst(EDIFPortInst epr){ if(portInsts == null) return null; return portInsts.remove(epr.getName()); } /** * Removes the named port ref. * @param portName Name of the port ref to remove * @return The removed port ref, or null if none existed by that name. */ protected EDIFPortInst removePortInst(String portName){ if(portInsts == null) return null; return portInsts.remove(portName); } /** * Gets the port ref on this cell by pin name (not full * port ref name). * @param name Name of the pin in the port ref to get. * @return A port ref by pin name. */ public EDIFPortInst getPortInst(String name){ return getPortInstMap().get(name); } /** * Gets the port on the underlying cell type. It is the same as * calling getCellType().getPort(name). * @param name Name of the port to get. * @return The port on the underlying cell type. */ public EDIFPort getPort(String name){ return getCellType().getPort(name); } public Collection<EDIFPortInst> getPortInsts(){ return getPortInstMap().values(); } /** * @return the parentCell */ public EDIFCell getParentCell() { return parentCell; } /** * @param parentCell the parentCell to set */ public void setParentCell(EDIFCell parent) { this.parentCell = parent; } /** * @return the cellType */ public EDIFCell getCellType() { return cellType; } public Collection<EDIFPort> getCellPorts(){ return cellType.getPorts(); } public String getCellName(){ return cellType.getName(); } /** * @param cellType the cellType to set */ public void setCellType(EDIFCell cellType) { this.cellType = cellType; this.viewref = cellType != null ? cellType.getEDIFView() : null; } public void updateCellType(EDIFCell cellType) { setCellType(cellType); for(EDIFPortInst portInst : getPortInsts()) { EDIFPort origPort = portInst.getPort(); EDIFPort port = cellType.getPort(origPort.getBusName()); if(port == null || port.getWidth() != origPort.getWidth()) { port = cellType.getPort(origPort.getName()); } portInst.setPort(port); } } public boolean isBlackBox(){ EDIFPropertyValue val = getProperty(BLACK_BOX_PROP); if(val != null && val.getValue().toLowerCase().equals("true")) return true; val = getProperty(BLACK_BOX_PROP_VERSAL); if(val != null && val.getValue().toLowerCase().equals("1")) return true; return false; } public void exportEDIF(Writer wr) throws IOException{ wr.write(" (instance "); exportEDIFName(wr); wr.write(" (viewref "); wr.write( getViewref().getLegalEDIFName()); wr.write(" (cellref "); wr.write(cellType.getLegalEDIFName()); wr.write(" (libraryref "); wr.write(cellType.getLibrary().getLegalEDIFName()); if(getProperties().size() > 0){ wr.write(")))\n"); exportEDIFProperties(wr, " "); wr.write(" )\n"); }else{ wr.write("))))\n"); } } @Override public String getUniqueKey() { return getCellType().getUniqueKey() + "_" + getParentCell().getUniqueKey() + "_" + getName(); } }
""" Projet 2 : Ricosheep Amal ABDALLAH Nicolas SEBAN Adam SOUIOU """ import subprocess import sys import tkinter as tk import tkinter.simpledialog from typing import Union, Tuple, Optional, Literal, List from tkinter import Entry from collections import deque from os import system, PathLike from time import time, sleep from tkinter.font import Font try: from PIL import Image, ImageTk print("Bibliothèque PIL chargée.", file=sys.stderr) PIL_AVAILABLE = True except ImportError: PIL_AVAILABLE = False __all__ = [ # gestion de fenêtre 'cree_fenetre', 'ferme_fenetre', 'mise_a_jour', # dessin 'ligne', 'fleche', 'polygone', 'rectangle', 'cercle', 'point', # Images 'afficher_image', 'taille_image', 'redimensionner_image', # Texte 'texte', 'taille_texte', # effacer 'efface_tout', 'efface', # utilitaires 'attente', 'capture_ecran', 'touche_pressee', 'abscisse_souris', 'ordonnee_souris', # événements 'donne_ev', 'attend_ev', 'attend_clic_gauche', 'attend_fermeture', 'type_ev', 'abscisse', 'ordonnee', 'touche' ] class CustomCanvas: """ Classe qui encapsule tous les objets tkinter nécessaires à la création d'un canevas. """ _on_osx = sys.platform.startswith("darwin") _on_win = sys.platform.startswith("win32") _ev_mapping = { 'ClicGauche': '<Button-1>', 'ClicMilieu': '<Button-2>', 'ClicDroit': '<Button-2>' if _on_osx else '<Button-3>', 'Deplacement': '<Motion>', 'Touche': '<Key>' } _default_ev = ['ClicGauche', 'ClicDroit', 'Touche'] def __init__(self, width, height, title='tk', refresh_rate=60, events=None, icone=None): # width and height of the canvas self.width = width self.height = height self.interval = 1/refresh_rate # root Tk object self.root = tk.Tk() self.root.title(title) if icone: self.root.iconphoto(True, ImageTk.PhotoImage(file=icone)) if self._on_win: import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( title ) # canvas attached to the root object self.canvas = tk.Canvas(self.root, width=width, height=height, highlightthickness=0) # adding the canvas to the root window and giving it focus self.canvas.pack() self.canvas.focus_set() # binding events self.ev_queue = deque() self.pressed_keys = set() self.events = CustomCanvas._default_ev if events is None else events self.bind_events() # marque self.tailleMarque = 5 # update for the first time self.last_update = time() self.root.update() if CustomCanvas._on_osx: system('''/usr/bin/osascript -e 'tell app "Finder" \ to set frontmost of process "Python" to true' ''') def update(self): t = time() self.root.update() sleep(max(0., self.interval - (t - self.last_update))) self.last_update = time() def bind_events(self): self.root.protocol("WM_DELETE_WINDOW", self.event_quit) self.canvas.bind('<KeyPress>', self.register_key) self.canvas.bind('<KeyRelease>', self.release_key) for name in self.events: self.bind_event(name) def register_key(self, ev): self.pressed_keys.add(ev.keysym) def release_key(self, ev): if ev.keysym in self.pressed_keys: self.pressed_keys.remove(ev.keysym) def event_quit(self): self.ev_queue.append(("Quitte", "")) def bind_event(self, name): e_type = CustomCanvas._ev_mapping.get(name, name) def handler(event, _name=name): self.ev_queue.append((_name, event)) self.canvas.bind(e_type, handler, '+') def unbind_event(self, name): e_type = CustomCanvas._ev_mapping.get(name, name) self.canvas.unbind(e_type) __canevas = None __img = dict() # ############################################################################ # Exceptions ############################################################################# class TypeEvenementNonValide(Exception): pass class FenetreNonCree(Exception): pass class FenetreDejaCree(Exception): pass class PILError(Exception): pass # Vous êtes viré, c'est scandaleux ############################################################################# # Initialisation, mise à jour et fermeture ############################################################################# def cree_fenetre(largeur: int, hauteur: int, titre: str = 'tk', frequence: int = 60, icone: Optional[PathLike] = None) -> None: """ Crée une fenêtre avec un titre et une icône, de dimensions ``largeur`` x ``hauteur`` pixels, et avec une frequence de rafraîchissement de 100 images par secondes par défaut. :rtype: """ global __canevas if __canevas is not None: raise FenetreDejaCree( 'La fenêtre a déjà été crée avec la fonction "cree_fenetre".') __canevas = CustomCanvas(largeur, hauteur, titre, frequence, icone=icone) def taille_fenetre() -> Tuple[int, int]: """ Retourne la taille actuelle de la fenêtre """ return (__canevas.root.winfo_width(), __canevas.root.winfo_height()) def ferme_fenetre() -> None: """ Détruit la fenêtre. """ global __canevas if __canevas is None: raise FenetreNonCree( "La fenêtre n'a pas été crée avec la fonction \"cree_fenetre\".") __canevas.root.destroy() __canevas = None def mise_a_jour() -> None: """ Met à jour la fenêtre. Les dessins ne sont affichés qu'après l'appel à cette fonction. """ if __canevas is None: raise FenetreNonCree( "La fenêtre n'a pas été crée avec la fonction \"cree_fenetre\".") __canevas.update() ############################################################################# # Fonctions de dessin ############################################################################# # Formes géométriques def ligne(ax: float, ay: float, bx: float, by: float, couleur: str = 'black', epaisseur: float = 1, tag=''): """ Trace un segment reliant le point ``(ax, ay)`` au point ``(bx, by)``. :param float ax: abscisse du premier point :param float ay: ordonnée du premier point :param float bx: abscisse du second point :param float by: ordonnée du second point :param str couleur: couleur de trait (défaut 'black') :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ return __canevas.canvas.create_line( ax, ay, bx, by, fill=couleur, width=epaisseur, tag=tag) def fleche(ax: float, ay: float, bx: float, by: float, couleur: str = 'black', epaisseur: float = 1, tag=''): """ Trace une flèche du point ``(ax, ay)`` au point ``(bx, by)``. :param float ax: abscisse du premier point :param float ay: ordonnée du premier point :param float bx: abscisse du second point :param float by: ordonnée du second point :param str couleur: couleur de trait (défaut 'black') :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ x, y = (bx - ax, by - ay) n = (x**2 + y**2)**.5 x, y = x/n, y/n points = [bx, by, bx-x*5-2*y, by-5*y+2*x, bx-x*5+2*y, by-5*y-2*x] return __canevas.canvas.create_polygon( points, fill=couleur, outline=couleur, width=epaisseur, tag=tag) def polygone(points: List[Tuple[float, float]], couleur: str = 'black', remplissage: str = '', remplissage_actif: str = '', epaisseur: float = 1, tag=''): """ Trace un polygone dont la liste de points est fournie. :param list points: liste de couples (abscisse, ordonnee) de points :param str couleur: couleur de trait (défaut 'black') :param str remplissage: couleur de fond (défaut transparent) :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ return __canevas.canvas.create_polygon( points, fill=remplissage, activefill=remplissage_actif, outline=couleur, width=epaisseur, tag=tag) def rectangle(ax: float, ay: float, bx: float, by: float, couleur: str = 'black', remplissage: str = '', remplissage_actif: str = '', epaisseur: float = 1, tag=''): """ Trace un rectangle noir ayant les point ``(ax, ay)`` et ``(bx, by)`` comme coins opposés. :param float ax: abscisse du premier coin :param float ay: ordonnée du premier coin :param float bx: abscisse du second coin :param float by: ordonnée du second coin :param str couleur: couleur de trait (défaut 'black') :param str remplissage: couleur de fond (défaut transparent) :param str remplissage_actif: couleur lors du survol (défaut transparent) :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ return __canevas.canvas.create_rectangle( ax, ay, bx, by, outline=couleur, fill=remplissage, activefill=remplissage_actif, width=epaisseur, tag=tag) def cercle(x: float, y: float, r: float, couleur: str = 'black', remplissage: str = '', epaisseur: float = 1, tag=''): """ Trace un cercle de centre ``(x, y)`` et de rayon ``r`` en noir. :param float x: abscisse du centre :param float y: ordonnée du centre :param float r: rayon :param str couleur: couleur de trait (défaut 'black') :param str remplissage: couleur de fond (défaut transparent) :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ return __canevas.canvas.create_oval( x - r, y - r, x + r, y + r, outline=couleur, fill=remplissage, width=epaisseur, tag=tag) def arc(x: float, y: float, r: float, ouverture: float = 90, depart: float = 0, couleur: str = 'black', remplissage: str = '', epaisseur: float = 1, tag=''): """ Trace un arc de cercle de centre ``(x, y)``, de rayon ``r`` et d'angle d'ouverture ``ouverture`` (défaut : 90 degrés, dans le sens contraire des aiguilles d'une montre) depuis l'angle initial ``depart`` (défaut : direction 'est'). :param float x: abscisse du centre :param float y: ordonnée du centre :param float r: rayon :param float ouverture: abscisse du centre :param float depart: ordonnée du centre :param str couleur: couleur de trait (défaut 'black') :param str remplissage: couleur de fond (défaut transparent) :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ return __canevas.canvas.create_arc( x - r, y - r, x + r, y + r, extent=ouverture, start=depart, style=tk.ARC, outline=couleur, fill=remplissage, width=epaisseur, tag=tag) def point(x: float, y: float, couleur: str = 'black', epaisseur: float = 1, tag=''): """ Trace un point aux coordonnées ``(x, y)`` en noir. :param float x: abscisse :param float y: ordonnée :param str couleur: couleur du point (défaut 'black') :param float epaisseur: épaisseur de trait en pixels (défaut 1) :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ return cercle(x, y, epaisseur, couleur=couleur, remplissage=couleur, tag=tag) # Image def afficher_image(x: float, y: float, image: Union[PathLike, Image.Image], ancrage: str = 'center', tag='') -> Image: """ Affiche l'image avec ``(x, y)`` comme centre. Les valeurs possibles du point d'ancrage sont ``'center'``, ``'nw'``, etc. :param float x: abscisse du point d'ancrage :param float y: ordonnée du point d'ancrage :param image: nom du fichier contenant l'image, ou un objet image :param ancrage: position du point d'ancrage par rapport à l'image :param str tag: étiquette d'objet (défaut : pas d'étiquette) :return: identificateur d'objet """ if type(image) == str: if PIL_AVAILABLE: with Image.open(image) as img: tkimage = ImageTk.PhotoImage(img) else: tkimage = tk.PhotoImage(file=image) else: tkimage = image img_object = __canevas.canvas.create_image( x, y, anchor=ancrage, image=tkimage, tag=tag ) __img[img_object] = tkimage return img_object def taille_image(fichier: PathLike) -> Tuple[int, int]: """ Retourne un tuple représentant la largeur et la hauteur de l'image. :param str fichier: Nom du fichier image """ if PIL_AVAILABLE: with Image.open(fichier) as img: return img.size raise PILError("Cette fonction est disponible \ uniquement si PIL est présent") return None def redimensionner_image(fichier: PathLike, coeff: float, reechantillonage=None): """ Ouvre une image et la redimensionne avec un coefficient multiplicateur, il est également possible d'appliquer un filtre de réchantillonage pour améliorer le rendu du redimensionnement: Au plus proche: ``0`` Lanczoz: ``1`` Bilinéaire: ``2`` Bicubique: ``3`` Box: ``4`` Hamming: ``5`` :param fichier: Fichier de l'image à redimensioner :param float coeff: Coefficient de redimensionnement :param int reechantillonage: {0, 1, 2, 3, 4, 5} Algorithme à utiliser pour améliorer le rendu, ``None``pour aucun. :return: Objet image """ if PIL_AVAILABLE: with Image.open(fichier) as img: taille = img.size taille_coeff = (int(taille[0]*coeff), int(taille[1]*coeff)) return ImageTk.PhotoImage( img.resize(taille_coeff, reechantillonage) ) else: PILError() return None def texte(x: float, y: float, chaine: str, couleur: str = 'black', ancrage: Literal[ 'nw', 'n', 'ne', 'w', 'center', 'e', 'sw', 's', 'se' ] = 'nw', police: str = 'Helvetica', taille: int = 24, tag=''): """ Affiche la chaîne ``chaine`` avec ``(x, y)`` comme point d'ancrage (par défaut le coin supérieur gauche). :param float x: abscisse du point d'ancrage :param float y: ordonnée du point d'ancrage :param str chaine: texte à afficher :param str couleur: couleur de trait (défaut 'black') :param ancrage: position du point d'ancrage (défaut 'nw') :param police: police de caractères (défaut : `Helvetica`) :param taille: taille de police (défaut 24) :param tag: étiquette d'objet (défaut : pas d'étiquette :return: identificateur d'objet """ return __canevas.canvas.create_text( x, y, text=chaine, font=(police, taille), tag=tag, fill=couleur, anchor=ancrage, state='disabled') def taille_texte(chaine: str, police: str = 'Helvetica', taille: int = 24): """ Donne la largeur et la hauteur en pixel nécessaires pour afficher ``chaine`` dans la police et la taille données. :param str chaine: chaîne à mesurer :param police: police de caractères (défaut : `Helvetica`) :param taille: taille de police (défaut 24) :return: couple (w, h) constitué de la largeur et la hauteur de la chaîne en pixels (int), dans la police et la taille données. """ font = Font(family=police, size=taille) return font.measure(chaine), font.metrics("linespace") ############################################################################# # Effacer ############################################################################# def efface_tout() -> None: """ Efface la fenêtre. """ __img.clear() __canevas.canvas.delete("all") def efface(objet) -> None: """ Efface ``objet`` de la fenêtre. :param: objet ou étiquette d'objet à supprimer :type: ``int`` ou ``str`` """ if objet in __img: del __img[objet] __canevas.canvas.delete(objet) ############################################################################# # Utilitaires ############################################################################# def attente(temps) -> None: start = time() while time() - start < temps: mise_a_jour() def capture_ecran(file) -> None: """ Fait une capture d'écran sauvegardée dans ``file.png``. """ __canevas.canvas.postscript(file=file + ".ps", height=__canevas.height, width=__canevas.width, colormode="color") subprocess.call( "convert -density 150 -geometry 100% -background white -flatten" " " + file + ".ps " + file + ".png", shell=True) subprocess.call("rm " + file + ".ps", shell=True) def touche_pressee(keysym) -> bool: """ Renvoie `True` si ``keysym`` est actuellement pressée. :param keysym: symbole associé à la touche à tester. :return: `True` si ``keysym`` est actuellement pressée, `False` sinon. """ return keysym in __canevas.pressed_keys def entree_texte(x: float, y: float, width: float, height: float, police: str = "Courier", justify: Literal['left', 'center', 'right'] = "center" ) -> Entry: """ Crée un champ de texte aux coordonnés x, y, ancrée en ``'nw'``. La taille du texte du champ peut être définie dans la chaîne, exemple: 'Courier 20' :param int x: Position sur l'axe x :param int y: Position sur l'axe y :param int width: Largeur du champ de texte :param int height: Hauteur du champ de texte :param str font: Police d'écriture :param str justify: Justification du texte. :return entry: Champ de texte """ entry = Entry(__canevas.canvas, justify=justify, font=police) entry.place(x=x, y=y, width=width, height=height, anchor='nw') return entry def detruit_entree_texte(boite: Entry) -> None: """ Détruit le champ de textes "boite". """ boite.destroy() __canevas.canvas.focus_set() ############################################################################# # Gestions des évènements ############################################################################# def donne_ev() -> Tuple[str, tkinter.Event]: """ Renvoie immédiatement l'événement en attente le plus ancien, ou ``None`` si aucun événement n'est en attente. """ if __canevas is None: raise FenetreNonCree( "La fenêtre n'a pas été créée avec la fonction \"cree_fenetre\".") if len(__canevas.ev_queue) == 0: return None else: return __canevas.ev_queue.popleft() def attend_ev() -> Tuple[str, tkinter.Event]: """Attend qu'un événement ait lieu et renvoie le premier événement qui se produit.""" while True: ev = donne_ev() if ev is not None: return ev mise_a_jour() def attend_clic_gauche() -> Tuple[int, int]: """Attend qu'un clic gauche sur la fenêtre ait lieu et renvoie ses coordonnées. **Attention**, cette fonction empêche la détection d'autres événements ou la fermeture de la fenêtre.""" while True: ev = donne_ev() if ev is not None and type_ev(ev) == 'ClicGauche': return abscisse(ev), ordonnee(ev) mise_a_jour() def attend_fermeture() -> None: """Attend la fermeture de la fenêtre. Cette fonction renvoie None. **Attention**, cette fonction empêche la détection d'autres événements.""" while True: ev = donne_ev() if ev is not None and type_ev(ev) == 'Quitte': ferme_fenetre() return mise_a_jour() def type_ev(ev: Tuple[str, tkinter.Event]) -> str: """ Renvoie une chaîne donnant le type de ``ev``. Les types possibles sont 'ClicDroit', 'ClicGauche', 'Touche' et 'Quitte'. Renvoie ``None`` si ``evenement`` vaut ``None``. """ return ev if ev is None else ev[0] def abscisse(ev: Tuple[str, tkinter.Event]) -> int: """ Renvoie la coordonnée x associé à ``ev`` si elle existe, None sinon. """ return attribut(ev, 'x') def ordonnee(ev: Tuple[str, tkinter.Event]) -> int: """ Renvoie la coordonnée y associé à ``ev`` si elle existe, None sinon. """ return attribut(ev, 'y') def touche(ev: Tuple[str, tkinter.Event]) -> str: """ Renvoie une chaîne correspondant à la touche associé à ``ev``, si elle existe. """ return attribut(ev, 'keysym') def attribut(ev: Tuple[str, tkinter.Event], nom: str): if ev is None: raise TypeEvenementNonValide( "Accès à l'attribut", nom, 'impossible sur un événement vide') tev, ev = ev if hasattr(ev, nom): return getattr(ev, nom) else: raise TypeEvenementNonValide( "Accès à l'attribut", nom, 'impossible sur un événement de type', tev) def abscisse_souris() -> int: return __canevas.canvas.winfo_pointerx() - __canevas.canvas.winfo_rootx() def ordonnee_souris() -> int: return __canevas.canvas.winfo_pointery() - __canevas.canvas.winfo_rooty()
package com.uit.cart_service.service.impl; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.uit.cart_service.dto.CartItemDto; import com.uit.cart_service.dto.ProductDto; import com.uit.cart_service.entity.Cart; import com.uit.cart_service.entity.CartItem; import com.uit.cart_service.feign.ProductFeignClient; import com.uit.cart_service.repository.CartItemRepository; import com.uit.cart_service.service.CartItemService; import com.uit.cart_service.service.CartService; import com.uit.cart_service.util.CartStatus; import feign.FeignException.FeignClientException; import lombok.RequiredArgsConstructor; @Service // @AllArgsConstructor @RequiredArgsConstructor public class CartItemServiceImpl implements CartItemService { private final CartItemRepository cartItemRepository; private CartService cartService; private final ProductFeignClient productFeignClient; private final Logger logger=LoggerFactory.getLogger(this.getClass()); @Autowired public void setCartService(CartService cartService){ this.cartService=cartService; } @Override public CartItem findByCartAndProductId(Cart cart, long productId) { // TODO Auto-generated method stub CartItem cartItem=cartItemRepository.findByCartAndProductId(cart, productId); return cartItem; } @Override public void save(CartItem cartItem,Cart cart,String id) { // TODO Auto-generated method stub if(cartItem!=null){ cartItem.setQuantity(cartItem.getQuantity()+1); cart.setStatus(CartStatus.PENDING.toString()); } else{ cartItem=new CartItem(); cartItem.setCart(cart); cartItem.setProductId(Long.parseLong(id)); cartItem.setQuantity(1L); cartItem.setCart(cart); cart.setStatus(CartStatus.PENDING.toString()); } cartItemRepository.save(cartItem); } @Override public List<CartItemDto> findCartItemByUserId(String userId) { // TODO Auto-generated method stub // validate if user exist // end validate try { Cart cart=cartService.findCartByUserId(userId); List<CartItemDto> cartItemDtos=new ArrayList<>(); if(cart!=null){ List<CartItem> listCartItem=cartItemRepository.findByCart(cart); for(CartItem item:listCartItem){ CartItemDto cartItemDto=new CartItemDto(); cartItemDto.setCartId(item.getId().toString()); cartItemDto.setId(item.getId().toString()); ProductDto productDto=productFeignClient.getProduct(item.getProductId().toString()); cartItemDto.setProductName(productDto.getName()); cartItemDto.setImageUrl(productDto.getImageUrl()); cartItemDto.setProductId(productDto.getId()); cartItemDto.setQuantity(item.getQuantity().toString()); cartItemDto.setPrice(productDto.getPrice()); cartItemDtos.add(cartItemDto); } return cartItemDtos; } } catch (NumberFormatException e) { // TODO: handle exception logger.debug(e.getMessage()); throw new NumberFormatException(); } catch(FeignClientException e){ logger.debug(e.getMessage()); } return null; } @Override public CartItemDto increaseItem(CartItemDto dto) { // TODO Auto-generated method stub try { CartItem cartItem=cartItemRepository.findById(Long.parseLong(dto.getCartId())).get(); if(cartItem!=null){ cartItem.setQuantity(Long.parseLong(dto.getQuantity())+1); cartItemRepository.save(cartItem); CartItemDto cartItemDto=new CartItemDto(); cartItemDto.setCartId(cartItem.getCart().getId().toString()); cartItemDto.setQuantity(cartItem.getQuantity().toString()); return cartItemDto; } } catch (NumberFormatException ex) { // TODO: handle exception logger.debug(ex.getMessage()); throw new NumberFormatException(); } return null; } @Override public CartItemDto removeItem(CartItemDto dto) { // TODO Auto-generated method stub try { CartItem cartItem=cartItemRepository.findById(Long.parseLong(dto.getCartId())).get(); if(cartItem!=null){ if(Long.parseLong(dto.getQuantity())==0) return null; cartItem.setQuantity(Long.parseLong(dto.getQuantity())-1); cartItemRepository.save(cartItem); CartItemDto cartItemDto=new CartItemDto(); cartItemDto.setCartId(cartItem.getCart().getId().toString()); cartItemDto.setQuantity(cartItem.getQuantity().toString()); return cartItemDto; } } catch (NumberFormatException ex) { // TODO: handle exception logger.debug(ex.getMessage()); throw new NumberFormatException(); } return null; } @Override public List<CartItemDto> getcartItemByCart(String cartId) { // TODO Auto-generated method stub try { Cart cart=cartService.findCartById(cartId); List<CartItem> listCartItems=cartItemRepository.findByCart(cart); List<CartItemDto> listCartItemDtos=new ArrayList<>(); for(CartItem cartItem :listCartItems){ CartItemDto cartItemDto=new CartItemDto(); cartItemDto.setCartId(cartItem.getCart().getId().toString()); cartItemDto.setId(cartItem.getId().toString()); cartItemDto.setQuantity(cartItem.getQuantity().toString()); listCartItemDtos.add(cartItemDto); } cartService.updateStatus(cart,CartStatus.DONE); return listCartItemDtos; } catch (NumberFormatException ex) { // TODO: handle exception throw new NumberFormatException(); } } }
import AboutParagraphs from "./AboutParagraphs.jsx"; import { Box, Divider } from "@mui/material"; import { localize } from "../../../Translation.jsx"; import { CartContext } from "../../../App.jsx"; import React, { useContext } from "react"; const About = () => { let { language } = useContext(CartContext); return ( <div className="flex justify-center relative flex-col items-center"> <Box sx={{ // width: customizedWidth, maxWidth: "1450px", position: "relative", paddingX: { xs: 2, md: 0 }, zIndex: 10, }} > <AboutParagraphs variant={"h4"} marginTop={8} marginBottom={3} fontWeight={"bold"} text={localize(language, "aboutApplication")} /> <AboutParagraphs variant={"h6"} marginBottom={5} text={localize(language, "aboutApplicationP1")} /> <AboutParagraphs variant={"h4"} marginTop={8} marginBottom={3} fontWeight={"bold"} text={localize(language, "ourMission")} /> <AboutParagraphs variant={"h6"} text={localize(language, "ourMissionP1")} /> <Divider sx={{ padding: 2 }}></Divider> <AboutParagraphs variant={"h4"} marginTop={8} marginBottom={3} fontWeight={"bold"} text={localize(language, "keyFeatures")} /> <AboutParagraphs variant={"h5"} marginTop={4} marginBottom={2} fontWeight={"bold"} text={localize(language, "interactiveMaps")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "interactiveMapsP1")} /> <AboutParagraphs variant={"h5"} marginTop={4} marginBottom={2} fontWeight={"bold"} text={localize(language, "comprehensiveData")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "comprehensiveDataP1")} /> <AboutParagraphs variant={"h5"} marginTop={4} marginBottom={2} fontWeight={"bold"} text={localize(language, "historicalInsights")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "historicalInsightsP1")} /> <AboutParagraphs variant={"h5"} marginTop={4} marginBottom={2} fontWeight={"bold"} text={localize(language, "focusOnForests")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "focusOnForestsP1")} /> <Divider sx={{ padding: 2 }}></Divider> <AboutParagraphs variant={"h4"} marginTop={6} marginBottom={2} fontWeight={"bold"} text={localize(language, "ourCommitment")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "ourCommitmentp1")} /> <Divider sx={{ padding: 2 }}></Divider> <AboutParagraphs variant={"h4"} marginTop={6} marginBottom={2} fontWeight={"bold"} text={localize(language, "getInvolved")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "getInvolvedP1")} /> <Divider sx={{ padding: 2 }}></Divider> <AboutParagraphs variant={"h4"} marginTop={6} marginBottom={2} fontWeight={"bold"} text={localize(language, "contactUs")} /> <AboutParagraphs variant={"h6"} marginBottom={3} text={localize(language, "contactUsP1")} /> <AboutParagraphs variant={"h6"} marginBottom={8} text={localize(language, "contactUsP2")} /> </Box> </div> ); }; export default About;
<!-- Name : form.html Assignment : Lab 3 Exercise C Author(s) : Mahdi Ansari, William Arthur Philip Louis Submission : May 21, 2030 Description : A simple HTML file for form tag. --> <!DOCTYPE html> <html> <head> <title>Form Elements Demonstration</title> </head> <body> <h1>HTML Form Elements Demo</h1> <form action="#" method="post"> <fieldset> <legend>Personal Information</legend> <!-- Add a label and input field for 'Name' here --> <label for="name">Name:</label><br> <input type="name" id="name" name="name"><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email"><br> <label for="Password">Password:</label><br> <input type="password" id="password" name="password"><br> <!-- Add a label and input field for 'Password' here, ensure to use the correct type for password fields --> </fieldset> <fieldset> <legend>Choice Elements</legend> <p>Gender:</p> <input type="radio" id="male" name="gender" value="male"> <label for="male">Male</label><br> <input type="radio" id="female" name="gender" value="female"> <label for="female">Female</label><br> <input type="radio" id="other" name="gender" value="other"> <label for="other">Other</label><br> <br> <!-- Create radio buttons for 'Female', and 'Other' gender options --> <label for="fruits">Choose a fruit:</label><br> <select id="fruits" name="fruits" size="3"> <option value="apple">Apple</option> <option value="orange">Orange</option> <option value="grape">Grape</option> <option value="mango">Mango</option> <option value="acerola">Acerola</option> <option value="banana">Banana</option> <option value="dragonfruit">Dragonfruit</option> <option value="watermelon">Watermelon</option> <option value="Pear">Pear</option> <option value="lime">Lime</option> <!-- Add options for various fruits like Banana, Orange, etc. (At least 10 fruits) --> </select><br> <!-- Add some attributes to select tag that changes it from a drop menu to a scrollable list.--> </fieldset> <fieldset> <legend>Other Elements</legend> <!-- Add a label and input field for 'Birthday' here, use the appropriate type for date selection --> <label for="bday">Birthday:</label> <input type="date"><br> <label for="favcolor">Favorite Color:</label><br> <input type="color" id="favcolor" name="favcolor"><br> <!-- Add a label and number input field for 'Quantity', set min to 1 and max to 5 --> <label for="quantity">Quantity (between 1 and 5):</label><br> <input type="number" id="quantity" name="quantity" min="1" max="5"><br> <label for="range">Range (between 1 and 10):</label><br> <input type="range" id="range" name="range" min="1" max="10" value="2"><br> <!-- Add an attribute to the range input to set its initial value to 2--> <!-- Add a label and input field for 'Homepage', use the correct type for URLs --> <label for="homepage">Homepage:</label><br> <input type="url" id="homepage" name="homepage"></input><br> <label for="feedback">Feedback:</label><br> <textarea id="feedback" name="feedback" rows="6" cols="50" wrap="soft"></textarea><br> <!-- Add some attributes to the feedback textarea tag to make it bigger and suitable for editing texts--> <!-- Add a file input field --> <input type="file"><br> <!-- Add a checkbox for 'Subscribe to newsletter' --> <label> <input type="checkbox" id="subscribebox" checked> Subscribe to newsletter </label><br> <!-- Add a hidden field for 'customerId', set its value to '12345' --> <input type="hidden" id="customerId" name="customerId" value="12345"> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </fieldset> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Generate Cover Letter</title> <style> /* CSS styles here */ body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; } .container { max-width: 800px; margin: 50px auto; padding: 20px; background-color: #fff; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } h1 { text-align: center; margin-bottom: 20px; color: #007bff; /* Adjusted header color */ } form { margin-bottom: 30px; } textarea { width: calc(100% - 40px); height: 200px; margin-bottom: 10px; padding: 10px; border: 1px solid #ccc; border-radius: 4px; resize: none; } .button { padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: background-color 0.3s ease; } .button:hover { background-color: #0056b3; } .generated-cover-letter { padding: 20px; background-color: #f9f9f9; border: 1px solid #ccc; border-radius: 4px; } .generated-cover-letter h2 { margin-top: 0; margin-bottom: 10px; } .generated-cover-letter p { white-space: pre-line; margin-bottom: 10px; text-align: justify; } .copy-cut-buttons { text-align: right; } .copy-cut-buttons button { margin-left: 10px; } </style> <script> // JavaScript code here function refreshCoverLetter() { location.reload(); } function copyAllCoverLetter() { var generatedCoverLetter = document.querySelector('.generated-cover-letter'); var tempInput = document.createElement('textarea'); tempInput.value = generatedCoverLetter.innerText; document.body.appendChild(tempInput); tempInput.select(); document.execCommand('copy'); document.body.removeChild(tempInput); alert('Entire cover letter copied to clipboard!'); } </script> </head> <body> <div class="container"> <h1>Custom Cover Letter Generator</h1> <!-- Adjusted header --> <form action="" method="post"> {% csrf_token %} <textarea name="project_description" placeholder="Enter project description"></textarea> <button class="button" type="submit">Submit</button> </form> <div class="copy-cut-buttons"> <button class="button" onclick="refreshCoverLetter()">Refresh</button> <button class="button" onclick="copyAllCoverLetter()">Copy All</button> </div> {% if first_paragraph %} <div class="generated-cover-letter"> <h2>Generated Cover Letter:</h2> <p>Hello Hiring Manager,</p> <br> <p>I hope this message finds you well. <br> {{first_paragraph|linebreaks }}</p><br>{{second_paragraph|linebreaks }}</p> <br><br> <p>Best Regards, <br>[Your Name]</p> <!-- Adjusted ending line --> </div> {% endif %} </div> </body> </html>
package com.rct.payroll.infra.persistence.entity.employee import com.rct.payroll.infra.persistence.entity.hr.Department import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType.AUTO import jakarta.persistence.Id import jakarta.persistence.ManyToOne import java.math.BigDecimal import java.time.LocalDateTime import java.time.LocalDateTime.now import java.util.UUID /** * Employee historic - Jakarta Entity * * @property id UUID * @property employee Employee * @property department Department of Employee * @property current Boolean * @property salary BigDecimal * @property startDate LocalDateTime * @property endDate LocalDateTime * @property createdAt LocalDateTime * @property updatedAt LocalDateTime * @constructor Create empty Employee historic */ @Entity data class EmployeeHistoric( @Id @GeneratedValue(strategy = AUTO) @Column(columnDefinition = "UUID") val id: UUID, @ManyToOne val employee: Employee, @ManyToOne val department: Department, val current: Boolean = true, val salary: BigDecimal, val startDate: LocalDateTime, val endDate: LocalDateTime?, val createdAt: LocalDateTime = now(), val updatedAt: LocalDateTime, )
import Footer from "../../components/shared/Footer"; import MetaInformation from "../../components/shared/MetaInformation"; import HeaderTribe from "./HeaderTribe"; interface LayoutProps { children: React.ReactNode; title: string; description: string; } export default function Layout({ title, description, children }: LayoutProps) { return ( <div className="mx-auto bg-gradient-to-br from-slate-800 via-slate-900 to-slate-900"> <MetaInformation title={title} description={description} /> <HeaderTribe /> <main className="">{children}</main> <Footer /> </div> ); }
/* Copyright ESIEE (2009) m.couprie@esiee.fr This software is an image processing library whose purpose is to be used primarily for research and teaching. This software is governed by the CeCILL license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. */ /*! \file explode.c \brief converts single 3D pgm file into a series of 2D pgm files <B>Usage:</B> explode in.pgm [begin end step] name_prefix <B>Description:</B> Generated file names are of the form: <B>name_prefix</B>nnnn.pgm, where nnnn is a four digit decimal integer. <B>Types supported:</B> byte 3d <B>Category:</B> convert \ingroup convert \author Michel Couprie */ #include <stdio.h> #include <stdint.h> #include <string.h> #include <sys/types.h> #include <stdlib.h> #include <mccodimage.h> #include <mcimage.h> #include <mcutil.h> int main(int argc, char **argv) { int32_t i, k; char bufname[1024]; int32_t namelen, begin, end, step; struct xvimage * image_in; struct xvimage * image_out; int32_t rs, cs, ds, ps, N; uint8_t *I; uint8_t *O; if ((argc != 3) && (argc != 6)) { fprintf(stderr, "usage: %s in.pgm [begin end step] name_prefix\n", argv[0]); exit(1); } image_in = readimage(argv[1]); if (image_in == NULL) { fprintf(stderr, "%s: readimage failed: %s\n", argv[0], argv[1]); exit(1); } rs = rowsize(image_in); /* taille ligne */ cs = colsize(image_in); /* taille colonne */ ds = depth(image_in); /* nb plans */ ps = rs * cs; /* taille plan */ N = ps * ds; /* taille image */ I = UCHARDATA(image_in); if (argc == 6) { begin = atoi(argv[2]); end = atoi(argv[3]); step = atoi(argv[4]); } else { begin = 0; end = ds-1; step = 1; } strcpy(bufname, argv[argc - 1]); namelen = strlen(argv[argc - 1]); image_out = allocimage(NULL, rs, cs, 1, VFF_TYP_1_BYTE); if (image_out == NULL) { fprintf(stderr,"%s : allocimage failed\n", argv[0]); exit(1); } O = UCHARDATA(image_out); for (k = begin; k <= end; k += step) { bufname[namelen] = '0' + (k / 1000) % 10; bufname[namelen+1] = '0' + (k / 100) % 10; bufname[namelen+2] = '0' + (k / 10) % 10; bufname[namelen+3] = '0' + (k / 1) % 10; bufname[namelen+4] = '.'; bufname[namelen+5] = 'p'; bufname[namelen+6] = 'g'; bufname[namelen+7] = 'm'; bufname[namelen+8] = '\0'; for (i = 0; i < ps; i++) O[i] = I[k * ps + i]; writeimage(image_out, bufname); } /* for k */ freeimage(image_in); freeimage(image_out); return 0; } /* main() */
import React from "react"; import {BrowserRouter, Route, Routes} from "react-router-dom"; import './App.css'; import Homepage from "./component/homepage"; import axios from "axios"; import Q1 from "./component/q1" import Q2 from "./component/q2"; import Q3 from "./component/q3"; import Q4 from "./component/q4"; import Q5 from "./component/q5"; import Q6 from "./component/q6"; import Q7 from "./component/q7"; import Q8 from "./component/q8"; axios.defaults.baseURL = 'http://localhost:5000'; axios.defaults.withCredentials = true; function App() { return ( <BrowserRouter> <Routes> <Route index element={<Homepage/>}></Route> <Route path="q1" element={<Q1/>}></Route> <Route path="q2" element={<Q2/>}></Route> <Route path="q3" element={<Q3/>}></Route> <Route path="q4" element={<Q4/>}></Route> <Route path="q5" element={<Q5/>}></Route> <Route path="q6" element={<Q6/>}></Route> <Route path="q7" element={<Q7/>}></Route> <Route path="q8" element={<Q8/>}></Route> </Routes> </BrowserRouter> ); } export default App;
; A lightweight book about the built-in function update-nth. ; ; Copyright (C) 2008-2011 Eric Smith and Stanford University ; Copyright (C) 2013-2023 Kestrel Institute ; ; License: A 3-clause BSD license. See the file books/3BSD-mod.txt. ; ; Author: Eric Smith (eric.smith@kestrel.edu) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (in-package "ACL2") ;; TODO: Make the var names in these rules more uniform, but note that the ;; first formal of update-nth is named KEY rather than N for some reason, so ;; consider not following our usual convention where we match the names of the ;; formals as much as possible. (local (include-book "append")) (in-theory (disable update-nth)) ;; Note that the rule len-update-nth is built in to ACL2. However, this rule ;; seems better, because here the case split is essentially on (< n (len x)), ;; which we will often know to be true. By contrast, in len-update-nth, the ;; case split is essentially on (> (+ 1 n) (len x)). The rule ;; len-of-update-nth from STD seems even worse, as it causes an unnecessary ;; case split on whether n is equal to one less than the length. (defthm len-of-update-nth-2 ; avoid name conflict with STD (equal (len (update-nth n val x)) (if (< (nfix n) (len x)) (len x) (+ 1 (nfix n))))) (in-theory (disable len-update-nth)) ;; Match what's in STD (defthm update-nth-of-update-nth-same (equal (update-nth n v1 (update-nth n v2 x)) (update-nth n v1 x)) :hints (("Goal" :in-theory (enable update-nth)))) ;BOZO add to update-nth library? (defthm car-of-update-nth ;; [Jared] changed variable names for compatibility with std/lists (equal (car (update-nth n v x)) (if (zp n) v (car x))) :hints (("Goal" :in-theory (enable update-nth)))) ;same as in std (defthm update-nth-of-update-nth-diff (implies (not (equal (nfix n1) (nfix n2))) (equal (update-nth n1 v1 (update-nth n2 v2 x)) (update-nth n2 v2 (update-nth n1 v1 x)))) :rule-classes ((:rewrite :loop-stopper ((n1 n2 update-nth)))) :hints (("Goal" :in-theory (enable update-nth)))) ;; If the value is the same, it doesn't matter whether the indices are the same or different. (defthm update-nth-of-update-nth-same-val (equal (update-nth n1 v (update-nth n2 v x)) (update-nth n2 v (update-nth n1 v x))) :rule-classes ((:rewrite :loop-stopper ((n1 n2 update-nth)))) :hints (("Goal" :in-theory (enable update-nth)))) (defthmd update-nth-when-equal-of-nth (implies (and (equal val (nth n lst)) (natp n) (< n (len lst))) (equal (update-nth n val lst) lst)) :hints (("Goal" :in-theory (enable UPDATE-NTH)))) ;rename (defthm cdr-of-update-nth-0 (equal (cdr (update-nth 0 v lst)) (cdr lst)) :hints (("Goal" :in-theory (enable update-nth)))) ;dup with jvm/jvm-facts.lisp (defthm cdr-of-update-nth ;; [Jared] renamed variables for compatibility with std/lists/update-nth (equal (cdr (update-nth n v x)) (if (zp n) (cdr x) (update-nth (1- n) v (cdr x)))) :hints (("Goal" :in-theory (enable update-nth)))) (defthm update-nth-of-cons ;; [Jared] renamed variables for compatibility with the same rule ;; from std/lists/update-nth (equal (update-nth n x (cons a b)) (if (zp n) (cons x b) (cons a (update-nth (1- n) x b))))) (defthm true-list-fix-of-update-nth-2 (equal (true-list-fix (update-nth key val l)) (update-nth key val (true-list-fix l))) :hints (("Goal" :in-theory (e/d (;repeat update-nth) (;list::list-equiv-hack ))))) ;todo dup? (defthm take-update-nth (implies (and (integerp n) ;; (<= 0 n) (integerp n2) (<= 0 n2)) (equal (take n (update-nth n2 v l)) (if (<= n n2) (take n l) (update-nth n2 v (take n l))))) :hints (("Goal" :in-theory (enable TAKE; repeat update-nth)))) ;; Often we'll know (true-listp l) and no case split will occur. ;; Not quite the same as true-listp-of-update-nth in std. ;; Note that a related rule, true-listp-update-nth, is built-in but is a :type-prescription rule. (defthm true-listp-of-update-nth-2 (equal (true-listp (update-nth key val l)) (if (true-listp l) t (not (< (nfix key) (len l))))) :hints (("Goal" :in-theory (enable update-nth)))) (defthm update-nth-0-equal-rewrite (equal (equal (update-nth 0 v1 lst) (cons v2 rst)) (and (equal v1 v2) (equal (cdr lst) rst)))) (defthm equal-of-update-nth-same (implies (natp n) (equal (equal x (update-nth n val x)) (and (< n (len x)) (equal val (nth n x))))) :hints (("Goal" :in-theory (enable update-nth)))) ;rename to nth-of-update-nth-safe (defthmd nth-update-nth-safe (implies (and (syntaxp (quotep m)) (syntaxp (quotep n))) (equal (nth m (update-nth n val l)) (if (equal (nfix m) (nfix n)) val (nth m l)))) :hints (("Goal" :in-theory (enable nth)))) ;matches std except has one less nfix (defthm nthcdr-of-update-nth-simpler (equal (nthcdr n1 (update-nth n2 val x)) (if (< (nfix n2) (nfix n1)) (nthcdr n1 x) (update-nth (- n2 (nfix n1)) val (nthcdr n1 x)))) :hints (("Goal" ;:induct (sub1-sub1-cdr-induct n key l) :expand (update-nth n2 val (nthcdr (+ -1 n1) (cdr x))) :in-theory (enable update-nth nthcdr)))) (defthm nthcdr-of-update-nth-when-< (implies (and (< n2 n1) (natp n2) (natp n1)) (equal (nthcdr n1 (update-nth n2 val list)) (nthcdr n1 list))) :hints (("Goal" :in-theory (enable update-nth nthcdr)))) (defthm update-nth-of-append (equal (update-nth n val (append x y)) (if (< (nfix n) (len x)) (append (update-nth n val x) y) (append x (update-nth (- n (len x)) val y)))) :hints (("Goal" :in-theory (enable equal-of-append)))) (local (defun sub1-cdr-cdr-induct (n x y) (if (zp n) (list n x y) (sub1-cdr-cdr-induct (+ -1 n) (cdr x) (cdr y))))) (defthmd equal-of-update-nth-new (implies (natp n) (equal (equal y (update-nth n val x)) (and (<= (+ 1 n) (len y)) (equal (nth n y) val) (equal (take n y) (take n x)) (equal (nthcdr (+ 1 n) x) (nthcdr (+ 1 n) y))))) :hints (("Goal" :induct (sub1-cdr-cdr-induct n x y) :in-theory (e/d (update-nth) ())))) (defthm update-nth-of-take-of-+-of-1-same (implies (and (<= (len lst) n) (integerp n)) (equal (update-nth n val (take (+ 1 n) lst)) (update-nth n val lst))) :hints (("Goal" :induct t :in-theory (enable update-nth)))) ;; rename? ;; Kept disabled by default. (defthmd update-nth-rw (implies (and (natp n) (< n (len lst))) (equal (update-nth n val lst) (append (take n lst) (list val) (nthcdr (+ 1 n) lst)))))
package com.patriciafiona.bookstore.model import android.os.Parcelable import kotlinx.parcelize.Parcelize import kotlinx.serialization.Serializable @Parcelize data class VolumeInfo( val title: String, val subtitle: String, val description: String, val imageLinks: ImageLinks? = null, val authors: List<String>, val publisher: String, val publishedDate: String, ): Parcelable { val allAuthorsx: String get() = allAuthors() fun allAuthors() : String { var x= "" for (author in authors) { x += "$author, " } return x.trimEnd(',', ' ') } }
import React from "react"; // nodejs library to set properties for components import PropTypes from "prop-types"; // @material-ui/core components import { makeStyles } from "@material-ui/core/styles"; import Grid from "@material-ui/core/Grid"; const styles = { grid: { position: "relative", maxWidth: "300", flexBasis: "auto", display: "flex", alignItems: "baseline", }, }; const useStyles = makeStyles(styles); export default function GridItem(props) { const classes = useStyles(); const { children, className, ...rest } = props; return ( <Grid item {...rest} className={classes.grid + " " + className}> {children} </Grid> ); } GridItem.defaultProps = { className: "", }; GridItem.propTypes = { children: PropTypes.node, className: PropTypes.string, };
<?php namespace src\Interpreter\Runtime\Values; use src\AST\Expressions\Expression; use src\AST\Expressions\FunctionExpression; use src\AST\Statements\Statement; use src\Interpreter\Interpreter; use src\Interpreter\ReturnSignal; use src\Interpreter\Runtime\Environment; use src\Interpreter\Runtime\LoxType; class FunctionValue extends BaseValue implements CallableValue { public function __construct( private readonly FunctionExpression $declaration, private readonly Environment $closure) { } #[\Override] public function getType(): LoxType { return LoxType::Callable; } #[\Override] public function cast(LoxType $toType, Statement|Expression $cause): BaseValue { if ($toType == LoxType::String) { // TODO: add reference to file / line? $name = $this->declaration->name ? $this->declaration->name->lexeme : "anonymous"; return new StringValue("<fn {$name}>"); } return parent::cast($toType, $cause); } #[\Override] public function arity(): int { return count($this->declaration->parameters); } #[\Override] public function call(array $arguments, Statement|Expression $cause): Value { /** @var Interpreter $interpreter */ $interpreter = dependency(Interpreter::class); $environment = new Environment($this->closure); foreach ($this->declaration->parameters as $index => $parameter) { $environment->define($parameter, $arguments[$index]); } try { $interpreter->executeBlock($this->declaration->body, $environment); } catch (ReturnSignal $signal) { return $signal->value; } return dependency(NilValue::class); } }
import { useEffect, useState } from "react"; import Alert from "../alert/Alert"; import Button from "../button/Button"; import UploadButton from "../button/UploadButton"; import Dropdown from "../Dropdown"; import Input from "../input/Input"; import TextArea from "../input/TextArea"; import BaseModal from "./BaseModal"; const defaultMenuImage = "https://bouchonbendigo.com.au/wp-content/uploads/2022/03/istockphoto-1316145932-170667a.jpg"; const emptyMenuItems = [ { menuitemid: "", menutime: "Breakfast", menuname: "", menuimage: "", menudescription: "", }, { menuitemid: "", menutime: "Lunch", menuname: "", menuimage: "", menudescription: "", }, { menuitemid: "", menutime: "Dinner", menuname: "", menuimage: "", menudescription: "", }, ]; const dayDropdown = [ { value: 0, show: "-- Choose Day --" }, { value: 1, show: "Monday" }, { value: 2, show: "Tuesday" }, { value: 3, show: "Wednesday" }, { value: 4, show: "Thursday" }, { value: 5, show: "Friday" }, { value: 6, show: "Saturday" }, { value: 7, show: "Sunday" }, ]; export default function MenuModal(props) { const { menu, menuInfo } = props; const [menuDay, setMenuDay] = useState(0); const [menuItems, setMenuItems] = useState(emptyMenuItems); const [error, setError] = useState(null); const [unavailableDays, setUnavailableDays] = useState([]); useEffect(() => { if (menu !== null) { setMenuItems(menu.menuitems); setMenuDay(menu.menuday); setUnavailableDays((prevUnavailableDays) =>{ prevUnavailableDays.splice(prevUnavailableDays.indexOf(menu.menuday), 1) return prevUnavailableDays; }); } else { setMenuItems(emptyMenuItems); setMenuDay(0); } }, [menu]); useEffect(() => { let unavailable = menuInfo.map((menuinf) => menuinf.menuday); setUnavailableDays(unavailable); }, [menuInfo]); const validateFormFields = () => { const submissionError = { header: "", detail: "", }; if (menuDay === 0) { submissionError.header = "Menu Day Error"; submissionError.detail = `Please choose a day !`; } else { for (let index = 0; index < menuItems.length; index++) { const menuitem = menuItems[index]; if (menuitem.menuname.trim().length === 0) { submissionError.header = "Menu Name Error"; submissionError.detail = `Menu Name (${menuitem.menutime}) can't be empty`; break; } else if (menuitem.menudescription.trim().length === 0) { submissionError.header = "Menu Description Error"; submissionError.detail = `Menu Description (${menuitem.menutime}) can't be empty`; break; } } } return submissionError; }; const createMenuHandler = () => { const menuID = menu === null ? "" : menu.menuid; const submissionError = validateFormFields(); if (submissionError.header !== "" && submissionError.detail !== "") { setError(submissionError); } else { const newMenu = { menuid: menuID, menuday: menuDay, menuitems: menuItems, }; if (menu === null) { props.onUpdate(newMenu, "ADD"); } else { props.onUpdate(newMenu, "UPDATE"); } setMenuItems(emptyMenuItems); setMenuDay(0); } }; const deleteMenuHandler = () => { props.onUpdate(menu.menuid, "DELETE"); }; const formDayHandler = (_, value) => { setMenuDay(parseInt(value)); }; const formMenuValueHandler = (name, value) => { const key = name.split("-"); setMenuItems((prevMenuItems) => prevMenuItems.map((menuitem) => { if (menuitem.menutime === key[0]) { return { ...menuitem, [key[1]]: value, }; } return menuitem; }) ); }; const hideModal = () => { props.onHideModal(); unavailableDays.push(menuDay); }; return ( <> <BaseModal show={props.show} onHideModal={hideModal}> {error && ( <Alert onFinishError={setError} header={error.header} detail={error.detail} /> )} <h3 className="text-xl font-bold mb-6">Categories</h3> <Dropdown name="menuday" id="menuday" color="white" value={menuDay} options={dayDropdown.filter( (day) => !unavailableDays.includes(day.value) )} onChange={formDayHandler} /> {menuItems?.map((menuitem, idx) => ( <div className="flex flex-col gap-4 mt-8" key={idx}> <h4 className="font-bold text-xl">{menuitem.menutime}</h4> <div className="flex flex-row gap-10"> <div className="flex flex-col w-1/3 gap-4 items-center"> <img src={ typeof menuitem.menuimage === "string" || menuitem.menuimage instanceof String ? menuitem.menuimage === "" ? defaultMenuImage : menuitem.menuimage : URL.createObjectURL(menuitem.menuimage) } className="object-cover rounded-md aspect-square w-full" alt="" /> <UploadButton onFileSelect={formMenuValueHandler} name={`${menuitem.menutime}-menuimage`} id={`${menuitem.menutime}-menuimage`} > Edit </UploadButton> </div> <div className="w-2/3 flex flex-col gap-4"> <div className="flex flex-col gap-2"> <strong htmlFor="name">Menu Name</strong> <Input type="text" name={`${menuitem.menutime}-menuname`} id={`${menuitem.menutime}-menuname`} color="white" value={menuitem.menuname} onChange={formMenuValueHandler} // onChange={(event) => menuChangeHandler(event, 0, "name")} /> </div> <div className="flex flex-col gap-2"> <strong htmlFor="name">Description</strong> <TextArea type="text" name={`${menuitem.menutime}-menudescription`} id={`${menuitem.menutime}-menudescription`} color="white" value={menuitem.menudescription} onChange={formMenuValueHandler} rows="8" /> </div> </div> </div> </div> ))} <div className="flex flex-row justify-end gap-6 pr-2 mt-5"> {menu && ( <Button type="button" onClick={deleteMenuHandler}> Delete </Button> )} <Button type="button" onClick={createMenuHandler}> Save </Button> </div> </BaseModal> </> ); }
import json import os from web3 import Web3 from dotenv import load_dotenv from solcx import compile_standard, install_solc load_dotenv() # Install specific Solidity compiler version install_solc("0.8.0") # Set up web3 connection provider_url = os.environ.get("CELO_PROVIDER_URL") web3 = Web3(Web3.HTTPProvider(provider_url)) assert web3.is_connected(), "Not connected to a Celo node" # Set deployer account and private key deployer = os.environ.get("CELO_DEPLOYER_ADDRESS") private_key = os.environ.get("CELO_DEPLOYER_PRIVATE_KEY") with open("CeloToken.sol", "r") as file: contract_source_code = file.read() # Compile the contract compiled_sol = compile_standard({ "language": "Solidity", "sources": { "CeloToken.sol": { "content": contract_source_code } }, "settings": { "outputSelection": { "*": { "*": ["metadata", "evm.bytecode", "evm.sourceMap"] } } } }) # Extract the contract data contract_data = compiled_sol['contracts']['CeloToken.sol']['CeloToken'] bytecode = contract_data['evm']['bytecode']['object'] abi = json.loads(contract_data['metadata'])['output']['abi'] # Deploy the smart contract contract = web3.eth.contract(abi=abi, bytecode=bytecode) nonce = web3.eth.get_transaction_count(deployer) transaction = { 'nonce': nonce, 'gas': 2000000, 'gasPrice': web3.eth.gas_price, 'data': bytecode, } signed_txn = web3.eth.account.sign_transaction(transaction, private_key) transaction_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction) transaction_receipt = web3.eth.wait_for_transaction_receipt(transaction_hash) # Get the contract address contract_address = transaction_receipt['contractAddress'] print(f"Contract deployed at address: {contract_address}")
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <style> div { display: flex; width: 80%; height: 300px; background-color: pink; } div span { width: 150px; height: 100px; background-color: purple; margin-right: 5px; } div span:nth-child(2) { /* 默认是0,-1比0小所以在前面 */ order: -1; } div span:nth-child(3) { /* 让3号子盒子沿着侧轴底侧对齐 */ align-self: flex-end; } </style> </head> <body> <div> <span>1</span> <span>2</span> <span>3</span> </div> </body> </html>
--- title: Files and Directories name: files-and-directories section: lists-and-indices view: docs.html description: Complete List of Files and Directories --- <!--qgoda-no-xgettext--> [% USE q = Qgoda %] <!--/qgoda-no-xgettext--> A typical Qgoda site contains a couple of standard files and directories. They are described in the following list. [% WRAPPER components/infobox.html type='info' title='Sorting of This List' %] The list is sorted alphanumerically but case-insensitive, and a leading underscore of the name is ignored. [% END %] <!--qgoda-no-xgettext--> <ul> [% WRAPPER components/file.html name="_assets" type='directory' -%] <!--/qgoda-no-xgettext--> This directory usually keeps the source files for assets, for example JavaScript files or (S)CSS files. Qgoda does not use this name internally. It is just a convention. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_config.yaml" type='file' -%] <!--/qgoda-no-xgettext--> Qgoda's main configuration file. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_config.yml" type='file' -%] <!--/qgoda-no-xgettext--> Qgoda's secondary configuration file. It is only used if <code>P:config.yaml</code> does not exist. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_includes" type='directory' overridable="paths.includes" -%] <!--/qgoda-no-xgettext--> Directory for included content snippets. You use that for example like <code>[&#37; q.include("_includes/footer.md") &#37;]</code>. Using the name `_includes` is not enforced by Qgoda. But you should use a name that starts with an underscore (so that the files are not misinterpreted as regular content) and add the negated name to the configuration variable `C:exclude-watch`. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_plugins" type='directory' overridable="paths.plugins" -%] <!--/qgoda-no-xgettext--> Directory for site-specific plug-ins. Plug-Ins in this directory are automatically activated. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_site" type='directory' overridable="paths.site" -%] <!--/qgoda-no-xgettext--> The output directory. This will normally be the document root of your web server. Files and directories in <code>P:_site</code> are overwritten without warning. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_stop" type='file' -%] <!--/qgoda-no-xgettext--> If a file named `_stop` is found in the top-level source directory, it gets deleted and Qgoda terminates immediately. The content of the file will be reported as the reason for the termination in the logs. You can use this feature for programmatically terminating Qgoda without signalling it. <!--qgoda-no-xgettext--> [%- END %] [% WRAPPER components/file.html name="_timestamp" type='file' overridable="paths.timestamp" -%] <!--/qgoda-no-xgettext--> This file contains the time, when <code>P:_site</code> was last re-created as seconds since the <q-term>epoch</q-term>. If you automatically re-load pages in the browser, for example with <a href="https://www.browsersync.io/")>browser-sync</a>, you should specify <code>P:_timestamp</code> as the file to watch for changes. <!--qgoda-no-xgettext--> [%- END %] </ul> <!--/qgoda-no-xgettext-->
import { Outlet } from 'react-router-dom' import Header from './Components/Header.jsx' import { useState, useEffect } from 'react' const getCartFromLocalStorage = () => { const cart = localStorage.getItem('cart') try { return cart ? JSON.parse(cart) : [] } catch (e) { console.error('Error parsing cart from localStorage', e) return [] } } function App() { const [cart, setCart] = useState(getCartFromLocalStorage()) const handleAddToCart = (item, quantity) => { const existingItem = cart.find((cartItem) => cartItem.id === item.id) if (existingItem) { const updatedCart = cart.map((cartItem) => cartItem.id === item.id ? { ...cartItem, quantity: cartItem.quantity + quantity } : cartItem ) setCart(updatedCart) } else { setCart([...cart, { ...item, quantity }]) } } const handleDeleteFromCart = (id) => { const updatedCart = cart.filter((item) => item.id !== id) setCart(updatedCart) localStorage.setItem('cart', JSON.stringify(updatedCart)) } useEffect(() => { localStorage.setItem('cart', JSON.stringify(cart)) }, [cart]) return ( <> <Header size={cart.length} /> <Outlet context={{ handleAddToCart, cart, handleDeleteFromCart }} /> </> ) } export default App
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Gentoo Linux Security Advisory GLSA 201009-07. # # The advisory text is Copyright (C) 2001-2016 Gentoo Foundation, Inc. # and licensed under the Creative Commons - Attribution / Share Alike # license. See http://creativecommons.org/licenses/by-sa/3.0/ # include("compat.inc"); if (description) { script_id(49636); script_version("$Revision: 1.18 $"); script_cvs_date("$Date: 2016/11/11 20:19:25 $"); script_cve_id("CVE-2009-2414", "CVE-2009-2416"); script_bugtraq_id(36010); script_osvdb_id(56985, 56990); script_xref(name:"GLSA", value:"201009-07"); script_name(english:"GLSA-201009-07 : libxml2: Denial of Service"); script_summary(english:"Checks for updated package(s) in /var/db/pkg"); script_set_attribute( attribute:"synopsis", value: "The remote Gentoo host is missing one or more security-related patches." ); script_set_attribute( attribute:"description", value: "The remote host is affected by the vulnerability described in GLSA-201009-07 (libxml2: Denial of Service) The following vulnerabilities were reported after a test with the Codenomicon XML fuzzing framework: Two use-after-free vulnerabilities are possible when parsing a XML file with Notation or Enumeration attribute types (CVE-2009-2416). A stack consumption vulnerability can be triggered via a large depth of element declarations in a DTD, related to a function recursion (CVE-2009-2414). Impact : A remote attacker could entice a user or automated system to open a specially crafted XML document with an application using libxml2 resulting in a Denial of Service condition. Workaround : There is no known workaround at this time." ); script_set_attribute( attribute:"see_also", value:"https://security.gentoo.org/glsa/201009-07" ); script_set_attribute( attribute:"solution", value: "All libxml2 users should upgrade to the latest version: # emerge --sync # emerge --ask --oneshot --verbose '>=dev-libs/libxml2-2.7.3-r2' NOTE: This is a legacy GLSA. Updates for all affected architectures are available since August 30, 2009. It is likely that your system is already no longer affected by this issue." ); script_set_cvss_base_vector("CVSS2#AV:N/AC:M/Au:N/C:N/I:N/A:P"); script_set_cvss_temporal_vector("CVSS2#E:ND/RL:OF/RC:ND"); script_set_attribute(attribute:"exploitability_ease", value:"No known exploits are available"); script_set_attribute(attribute:"exploit_available", value:"false"); script_cwe_id(119, 399); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:gentoo:linux:libxml2"); script_set_attribute(attribute:"cpe", value:"cpe:/o:gentoo:linux"); script_set_attribute(attribute:"patch_publication_date", value:"2010/09/21"); script_set_attribute(attribute:"plugin_publication_date", value:"2010/09/22"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2010-2016 Tenable Network Security, Inc."); script_family(english:"Gentoo Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/Gentoo/release", "Host/Gentoo/qpkg-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("qpkg.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/Gentoo/release")) audit(AUDIT_OS_NOT, "Gentoo"); if (!get_kb_item("Host/Gentoo/qpkg-list")) audit(AUDIT_PACKAGE_LIST_MISSING); flag = 0; if (qpkg_check(package:"dev-libs/libxml2", unaffected:make_list("ge 2.7.3-r2"), vulnerable:make_list("lt 2.7.3-r2"))) flag++; if (flag) { if (report_verbosity > 0) security_warning(port:0, extra:qpkg_report_get()); else security_warning(0); exit(0); } else { tested = qpkg_tests_get(); if (tested) audit(AUDIT_PACKAGE_NOT_AFFECTED, tested); else audit(AUDIT_PACKAGE_NOT_INSTALLED, "libxml2"); }
import React, { Component } from "react"; import PropTypes from "prop-types"; import isEmpty from "../../validation/is-empty"; class ProfileAbout extends Component { render() { const { profile } = this.props; const firstName = profile.user.name.trim().split(" ")[0]; return ( <div className="row"> <div className="col-md-12"> <div className="mb-3"> <h3 className="text-center text-info">{firstName}'s Bio</h3> {isEmpty(profile.bio) ? ( <div className="text-center"> <p className="lead">{firstName} does not have a bio</p> </div> ) : ( <div className="text-center"> <p className="lead">{profile.bio}</p> </div> )} {isEmpty(profile.education) ? ( <div className="text-center"></div> ) : ( <div className="text-center"> <hr /> <h3 className="text-center text-info">Education</h3> <p className="lead"> <span>{profile.education}</span> </p> </div> )} </div> </div> </div> ); } } ProfileAbout.propTypes = { profile: PropTypes.object.isRequired }; export default ProfileAbout;
import 'package:audioplayers/audioplayers.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; import 'package:file_picker/file_picker.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:ndialog/ndialog.dart'; import 'dart:io'; import 'package:record/record.dart'; import 'package:path_provider/path_provider.dart'; import 'package:wedme1/utils/flushbar_widget.dart'; import 'package:flutter/foundation.dart' as foundation; import '../../chat/groupChat/chatControl/ChatControl.dart'; import '../../models/users_detail_model.dart'; import '../../viewModel/profile_vm.dart'; import '/constants/colors.dart'; import '/models/chat_model.dart'; class ConversationBody extends StatefulWidget { const ConversationBody({ Key? key, required this.chatRoomId, required this.idj, this.userAccount, required this.fullName, required this.count, required this.photoUrl, required this.userId, required this.state, required this.block, required this.currentUserID, required this.whoBlock, required this.currentFullName, required this.currentPhotoUrl, required this.docID, required this.subscriptionDueDate, }) : super(key: key); final String chatRoomId; final String idj; final String photoUrl; final String whoBlock; final bool block; final String fullName; final String count; final String subscriptionDueDate; final String state; final String userId; final String currentUserID; final String currentFullName; final String currentPhotoUrl; final String docID; final UsersDetailModel? userAccount; @override State<ConversationBody> createState() => _ConversationBodyState(); } class _ConversationBodyState extends State<ConversationBody> { final audioPlayer = AudioPlayer(); bool isPlaying = false; Duration duration = Duration.zero; Duration position = Duration.zero; final record = Record(); final messages = ChatModel.messages; String docID = ""; String? filePathLight; bool startRecordingNow = false; String? urlAudio; _ConversationBodyState(); final TextEditingController _sendMessageController = TextEditingController(); @override void dispose() { // TODO: implement dispose super.dispose(); _sendMessageController.dispose(); audioPlayer.dispose(); } Future<void> stopRecording() async { await record.stop(); } Future<void> startRecording() async { if (await record.hasPermission()) { Directory directory; if (Platform.isIOS) { directory = await getTemporaryDirectory(); } else { directory = (await getExternalStorageDirectory())!; } String filePath = '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.acc'; await record.start( path: filePath, encoder: AudioEncoder.AAC, // by default bitRate: 128000, // by default samplingRate: 44100, // by default ); bool isRecording = await record.isRecording(); setState(() { filePathLight = filePath; }); } else { if (context.mounted) { flushbar( context: context, title: 'Permission Required', message: 'Please enable recording permision', isSuccess: false); } } } Future<void> upload() async { final ref = FirebaseStorage.instance .ref() .child('audio-path/${DateTime.now().microsecondsSinceEpoch}'); UploadTask uploadTask = ref.putFile(File(filePathLight!)); uploadTask.showCustomProgressDialog(context); final down = await uploadTask.whenComplete(() {}); final downloadedFile = await down.ref.getDownloadURL(); await FirebaseFirestore.instance .collection("chat") .doc(widget.chatRoomId) .collection("chatR") .add({ "message": "", 'timestamp': FieldValue.serverTimestamp(), "image": "", "imageSent": "https://firebasestorage.googleapis.com/v0/b/wedme-373214.appspot.com/o/images%2Fmyimage.jpg1684366500670296?alt=media&token=f8f1e6ad-2366-451c-bc99-43e089c35a28", "isAudio": true, "audio": downloadedFile, "order": DateTime.now().millisecondsSinceEpoch, "currentUser": FirebaseAuth.instance.currentUser?.uid, }); print('The downloaded file $downloadedFile'); } PlatformFile? selectedAudio; PlatformFile? selectPicture; UploadTask? uploadTask; bool emojiShowing = false; final FocusNode _focusNode = FocusNode(); @override void initState() { // TODO: implement initState super.initState(); audioPlayer.onPlayerStateChanged.listen((event) { setState(() { isPlaying = event == PlayerState.playing; }); audioPlayer.onDurationChanged.listen((event) { setState(() { duration = event; }); }); audioPlayer.onPositionChanged.listen((event) { position = event; }); }); } String pathToAudio = ""; @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { FirebaseFirestore.instance .collection("messageList") .doc(FirebaseAuth.instance.currentUser!.uid) .collection("individual") .doc(widget.idj) .update({"count": 0}); if (emojiShowing == true) { return false; } return true; }, child: Column( children: <Widget>[ Expanded( child: StreamBuilder( stream: FirebaseFirestore.instance .collection("chat") .doc(widget.chatRoomId) .collection("chatR") .orderBy('timestamp', descending: false) .snapshots(), builder: (_, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) { if (!snapshot.hasData) { return const Text(""); } else { return ListView.builder( physics: const BouncingScrollPhysics(), itemCount: snapshot.data?.docs.length, shrinkWrap: true, reverse: false, padding: const EdgeInsets.only(top: 10, bottom: 10), itemBuilder: (context, index) { final message = snapshot.data?.docs[index] ['currentUser'] != FirebaseAuth.instance.currentUser?.uid; snapshot.data?.docs[index]['message'] != FirebaseAuth.instance.currentUser?.uid; return Column( children: [ Align( alignment: (message ? Alignment.topLeft : Alignment.topRight), child: Container( margin: const EdgeInsets.symmetric( horizontal: 10, vertical: 5), child: snapshot.data?.docs[index]["message"] == "" ? Container() : Container( decoration: BoxDecoration( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(0), bottomLeft: Radius.circular(50), bottomRight: Radius.circular(40), ), color: (message ? Colors.grey.shade200 : Colors.black), ), padding: const EdgeInsets.all(16), child: Text( snapshot.data?.docs[index]["message"], style: TextStyle( fontSize: 15, color: message ? Colors.black : Colors.white, ), ), ), ), ), Align( alignment: (message ? Alignment.topLeft : Alignment.topRight), child: Container( margin: const EdgeInsets.symmetric( horizontal: 10, vertical: 5), child: snapshot.data?.docs[index] ["imageSent"] == "" || snapshot.data!.docs[index] ["imageSent"] == null ? Container() : snapshot.data!.docs[index]["isAudio"] == true ? SizedBox( width: 200, child: Row( children: [ IconButton( onPressed: () async { if (isPlaying) { await audioPlayer.pause(); } else { await audioPlayer.play( UrlSource(snapshot.data! .docs[index] ["audio"]), ); } }, icon: isPlaying == false ? const Icon( Icons.play_circle, ) : const Icon( Icons.pause, ), ), Container( height: 12, width: 120, decoration: const BoxDecoration( color: Colors.grey), ) ], ), ) : Container( height: MediaQuery.of(context) .size .height * 0.2, width: MediaQuery.of(context) .size .width * 0.5, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( snapshot.data!.docs[index] ["imageSent"]), fit: BoxFit.cover), borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(0), bottomLeft: Radius.circular(50), bottomRight: Radius.circular(40), ), ), padding: const EdgeInsets.all(16), ), ), ), ], ); }, ); } }), ), Align( alignment: Alignment.bottomLeft, child: StreamBuilder<DocumentSnapshot>( stream: FirebaseFirestore.instance .collection("blockUser") .doc(FirebaseAuth.instance.currentUser!.uid) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData && snapshot.hasError) { return Text(""); } else { var dd = snapshot.data; //dd[""]; return dd?["whoBlcck"] == "" ? Column( children: [ Container( margin: EdgeInsets.only( bottom: emojiShowing == true ? 150 : 10), padding: const EdgeInsets.only( left: 10, bottom: 10, top: 10), height: 70, width: double.infinity, color: Colors.white, child: Row( children: <Widget>[ Expanded( child: Container( decoration: BoxDecoration( color: kEditextColor, border: Border.all( color: kEditextColor, width: 1.0, ), borderRadius: BorderRadius.circular(10), ), child: Column( children: [ widget.block == true ? writeMessageTextFieldBlock( context) : writeMessageTextField( context), ], ), ), ), widget.block == true ? Container() : IconButton( onPressed: () { if (ProfileViewModel() .validateSubscriptionStus(widget .userAccount ?.subscriptionDueDate ?? "${DateTime.now()}") && widget.userAccount ?.subscriptionType == "premium") { ChatControl().captureImage( context: context, chatRoomId: widget.chatRoomId, id: widget.chatRoomId); } else {} }, icon: const Icon(Icons.image)), const SizedBox( width: 15, ), FloatingActionButton( onPressed: () { upload(); ChatControl().uploadToFirebaseN( chatRoomId: widget.chatRoomId, currentFullName: widget.currentFullName, currentPhotoUrl: widget.currentPhotoUrl, selectedAudio: selectedAudio, selectPicture: selectPicture, idj: widget.idj, sendMessageController: _sendMessageController, userId: widget.userId, photoUrl: widget.photoUrl, uploadTask: uploadTask, fullName: widget.fullName, state: widget.state, ); }, backgroundColor: kPrimaryColor, elevation: 0, child: const Icon( Icons.send, color: Colors.white, size: 18, ), ), ], ), ), ], ) : Column( children: [ if (dd?["whoBlcck"] is List<dynamic> && (dd?["whoBlcck"] as List<dynamic>).contains( FirebaseAuth.instance.currentUser!.uid)) Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ const Text( "You’ve blocked this contact "), InkWell( onTap: () { FirebaseFirestore.instance .collection("messageList") .doc(FirebaseAuth.instance .currentUser!.uid) .collection("individual") .doc(widget.idj) .update({ "block": false, "state": FirebaseAuth .instance.currentUser!.uid, }).then((value) { FirebaseFirestore.instance .collection("messageList") .doc(widget.idj) .collection("individual") .doc(FirebaseAuth.instance .currentUser!.uid) .update({ "block": false, "state": FirebaseAuth.instance .currentUser!.uid, }); }).then((value) { Navigator.pop(context); }); FirebaseFirestore.instance .collection("blockUser") .doc(widget.idj) .set({ "whoBlcck": FieldValue.arrayRemove([ FirebaseAuth .instance.currentUser!.uid ]), }).then((value) { FirebaseFirestore.instance .collection("blockUser") .doc(FirebaseAuth.instance .currentUser!.uid) .set({ "whoBlcck": FieldValue.arrayRemove( [widget.idj]), }); }); }, child: const Text( "Tap to unblock", style: TextStyle( color: Color(0xFF0234E6)), )), ], ), ], ) else Container( margin: EdgeInsets.only( bottom: emojiShowing == true ? 150 : 10), padding: const EdgeInsets.only( left: 10, bottom: 10, top: 10), height: 70, width: double.infinity, color: Colors.white, child: Row( children: <Widget>[ Expanded( child: Container( decoration: BoxDecoration( color: kEditextColor, border: Border.all( color: kEditextColor, width: 1.0, ), borderRadius: BorderRadius.circular(10), ), child: Column( children: [ widget.block == true ? writeMessageTextFieldBlock( context) : writeMessageTextField( context), ], ), ), ), widget.block == true ? Container() : IconButton( onPressed: () { ChatControl().captureImage( context: context, chatRoomId: widget.chatRoomId, id: widget.chatRoomId); }, icon: const Icon(Icons.image)), const SizedBox( width: 15, ), FloatingActionButton( onPressed: () { ChatControl().uploadToFirebaseN( chatRoomId: widget.chatRoomId, currentFullName: widget.currentFullName, currentPhotoUrl: widget.currentPhotoUrl, selectedAudio: selectedAudio, selectPicture: selectPicture, idj: widget.idj, sendMessageController: _sendMessageController, userId: widget.userId, photoUrl: widget.photoUrl, uploadTask: uploadTask, fullName: widget.fullName, state: widget.state, ); }, backgroundColor: kPrimaryColor, elevation: 0, child: const Icon( Icons.send, color: Colors.white, size: 18, ), ), ], ), ), ], ); } }), ) ], ), ); } TextField writeMessageTextField(BuildContext context) { Future<void> stopRecording() async { await record.stop(); } return TextField( controller: _sendMessageController, decoration: InputDecoration( prefixIcon: InkWell( onTap: () { emojiShowing = !emojiShowing; setState(() {}); _focusNode.unfocus(); // disable keyboard if (!emojiShowing) { Navigator.pop(context); } else { emojiShowing == true ? showBottomSheet( enableDrag: false, constraints: const BoxConstraints(minHeight: 20), context: context, builder: (context) { return SizedBox( height: 150, child: EmojiPicker( textEditingController: _sendMessageController, config: Config( verticalSpacing: 0, horizontalSpacing: 0, gridPadding: EdgeInsets.zero, initCategory: Category.RECENT, bgColor: const Color(0xFFF2F2F2), indicatorColor: Colors.blue, iconColor: Colors.grey, iconColorSelected: Colors.blue, backspaceColor: Colors.blue, skinToneDialogBgColor: Colors.white, skinToneIndicatorColor: Colors.grey, enableSkinTones: true, showRecentsTab: true, recentsLimit: 28, replaceEmojiOnLimitExceed: false, noRecents: const Text( 'No Recent', style: TextStyle( fontSize: 20, color: Colors.black26), textAlign: TextAlign.center, ), checkPlatformCompatibility: true, loadingIndicator: const SizedBox.shrink(), tabIndicatorAnimDuration: kTabScrollDuration, categoryIcons: const CategoryIcons(), buttonMode: ButtonMode.MATERIAL, columns: 7, emojiSizeMax: 32 * (foundation.defaultTargetPlatform == TargetPlatform.iOS ? 1.30 : 1.0), ), )); }, ) : Container(); } }, child: const ImageIcon(AssetImage("assets/icons/emoji_face.png")), ), suffixIcon: InkWell( onTap: () async { startRecordingNow = !startRecordingNow; print(startRecordingNow); setState(() {}); if (startRecordingNow) { await startRecording(); } else { stopRecording().then((value) { upload(); }); } }, child: startRecordingNow ? Icon(Icons.pause) : Icon(Icons.mic), ), hintText: "Write message...", hintStyle: const TextStyle( color: Color(0xFF360001), ), border: InputBorder.none), ); } TextField writeMessageTextFieldBlock(BuildContext context) { return TextField( enabled: false, controller: _sendMessageController, decoration: InputDecoration( prefixIcon: InkWell( onTap: () { emojiShowing = !emojiShowing; setState(() {}); _focusNode.unfocus(); // disable keyboard if (!emojiShowing) { Navigator.pop(context); } else { emojiShowing == true ? showBottomSheet( enableDrag: false, constraints: const BoxConstraints(minHeight: 20), context: context, builder: (context) { return SizedBox( height: 150, child: EmojiPicker( textEditingController: _sendMessageController, config: Config( verticalSpacing: 0, horizontalSpacing: 0, gridPadding: EdgeInsets.zero, initCategory: Category.RECENT, bgColor: const Color(0xFFF2F2F2), indicatorColor: Colors.blue, iconColor: Colors.grey, iconColorSelected: Colors.blue, backspaceColor: Colors.blue, skinToneDialogBgColor: Colors.white, skinToneIndicatorColor: Colors.grey, enableSkinTones: true, showRecentsTab: true, recentsLimit: 28, replaceEmojiOnLimitExceed: false, noRecents: const Text( 'No Recent', style: TextStyle( fontSize: 20, color: Colors.black26), textAlign: TextAlign.center, ), checkPlatformCompatibility: true, loadingIndicator: const SizedBox.shrink(), tabIndicatorAnimDuration: kTabScrollDuration, categoryIcons: const CategoryIcons(), buttonMode: ButtonMode.MATERIAL, columns: 7, emojiSizeMax: 32 * (foundation.defaultTargetPlatform == TargetPlatform.iOS ? 1.30 : 1.0), ), )); }, ) : Container(); } }, child: const ImageIcon(AssetImage("assets/icons/emoji_face.png")), ), suffixIcon: InkWell( onTap: () async {}, child: const Icon(Icons.mic), ), hintText: "Write message...", hintStyle: const TextStyle(color: Color(0xFF360001)), border: InputBorder.none), ); } }
from hooks import Hooks HOOKS = Hooks() class Color: __slots__ = ('r', 'g', 'b') def __init__(self, r: int, g: int, b: int): self.r = r self.g = g self.b = b def __repr__(self): return f'Color({self.r}, {self.g}, {self.b})' class Screen: def __init__(self, x: int, y: int): self.screen = [ [Color(255, 255, 255) for _ in range(y)] for _ in range(x) ] def draw_tick(self): HOOKS.call('pre_draw_tick', self.screen) print('Screen rendering....') self.screen[0][0] = Color(0, 0, 0) HOOKS.call('post_draw_tick', self.screen) class Logger: def __init__(self): HOOKS.add('pre_draw_tick', 'log_screen_data', self.log_pre_draw) HOOKS.add('post_draw_tick', 'log_screen_data', self.log_post_draw) @staticmethod def log_pre_draw(screen): print('Logging pre-draw screen data...', screen[0][0]) @staticmethod def log_post_draw(screen): print('Logging post-draw screen data...', screen[0][0]) scr = Screen(10, 10) logger = Logger() scr.draw_tick()
import { useEffect, useState } from "react"; import NavBar from "../components/navbar/NavBar"; import { Grid, GridItem, Box } from '@chakra-ui/react'; import Sidemenu from "../components/SideMenu"; import { ImMenu } from "react-icons/im"; import BlogTitle from "../components/blog/BlogTitle"; import { useDispatch, useSelector } from "react-redux"; import { getAllCategories, selectCategories } from "../app/blog/categorySlice"; import { getAllBlogsByCategory, selectBlogsByCategory } from "../app/blog/blogSlice"; export default function Dashboard() { const [isSideOpen, setISideOpen] = useState(true) const [selectedMenu, setSelectedMenu] = useState(0) const categories = useSelector(selectCategories); const blogs = useSelector(selectBlogsByCategory); const dispatch = useDispatch(); function handleClick() { setISideOpen(!isSideOpen) } useEffect(() => { if (!categories.length) { dispatch(getAllCategories()) } }, [categories.length, dispatch]); useEffect(() => { if (!blogs[categories[selectedMenu]?._id] && categories[selectedMenu]?._id) { dispatch(getAllBlogsByCategory(categories[selectedMenu]?._id)) } console.log(blogs); }, [blogs, categories, dispatch, selectedMenu]) return ( <Box maxW={'100vw'}> <NavBar /> <Grid templateAreas={`"nav main"`} gridTemplateColumns={isSideOpen ? '150px 1fr' : '0px 1fr'} color='blackAlpha.700' fontWeight='bold' height={"100vh"} > {/* Left Navigation Grid Item */} <GridItem gridArea={'nav'} color={'white'} bg={'#133337'} borderRight={'5px double orange'} boxShadow={"rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px"}> {isSideOpen && <Sidemenu isOpen={isSideOpen} onChange={setSelectedMenu} categories={categories} />} </GridItem> {/* Main Content Grid Item */} <GridItem pl='2' bg={'#133337'} gridArea={'main'} > {/* Menu Bar Logo */} <Box w={"100%"} pb={4} align={'left'} > <ImMenu size={30} cursor={'pointer'} color="orange" onClick={handleClick} /> </Box> {/* Left Side panel to display title */} { <Box > <BlogTitle blogs={blogs[categories[selectedMenu]?._id]} /> </Box> } </GridItem> </Grid> </Box> ) }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Joe Kopena <tjkopena@cs.drexel.edu> * */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/stats-module.h" #ifndef TIMESTAMP_H #define TIMESTAMP_H using namespace ns3; class TimestampTag : public Tag { public: static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual uint32_t GetSerializedSize (void) const; virtual void Serialize (TagBuffer i) const; virtual void Deserialize (TagBuffer i); void SetTimestamp (Time time); Time GetTimestamp (void) const; void Print (std::ostream &os) const; private: Time m_timestamp; }; #endif /* TIMESTAMP_H */
import React, { useState } from 'react' import { useDispatch } from 'react-redux'; import { fetchEpisodesAsync } from '../../redux/app/features/episodes/episodesSlice'; import { fetchCharactersAsync } from '../../redux/app/features/characters/charactersSlice'; import './Search.css'; export default function Search() { const [searchQuery, setSearchQuery] = useState(''); const dispatch = useDispatch(); const handleSearch = () => { const cleanedQuery = searchQuery.trim(); console.log('Searching for:', cleanedQuery); if (!cleanedQuery) { console.log('Empty search query, fetching all data'); dispatch(fetchEpisodesAsync(1)); dispatch(fetchCharactersAsync(1)); } else { console.log('Non-empty search query, fetching data with search query'); dispatch(fetchEpisodesAsync(1, cleanedQuery)); dispatch(fetchCharactersAsync(1, cleanedQuery)); } }; const handleKeyPress = (e) => { if (e.key === 'Enter') { handleSearch(); } }; return ( <div className="search-container"> <input type="text" placeholder="Search..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} onKeyPress={handleKeyPress} /> <button onClick={handleSearch}>Search</button> </div> ) }
import { BrowserRouter, Route, Routes, Navigate } from 'react-router-dom'; import './TodoApp.css' import LogoutComponent from './LogoutComponent'; import HeaderComponent from './HeaderComponent'; import ListTodosComponent from './ListTodosComponent'; import ErrorComponent from './ErrorComponent'; import WelcomeComponent from './WelcomeComponent'; import LoginComponent from './LoginComponent'; import AuthProvider, { useAuth } from '../security/AuthContext' import TodoComponent from './TodoComponent'; function AuthenticatedRoute({ children }){ const authContext = useAuth() if(authContext.isAuthenticated) return children return <Navigate to="/" /> } export default function TodoApp(){ return ( <div className="TodoApp"> <AuthProvider> <BrowserRouter> <HeaderComponent/> <Routes> <Route path='/' element={<LoginComponent/>} /> <Route path='/login' element={<LoginComponent/>} /> <Route path='/welcome/:username' element={ <AuthenticatedRoute> <WelcomeComponent/> </AuthenticatedRoute> }/> <Route path='/todos' element={ <AuthenticatedRoute> < ListTodosComponent /> </AuthenticatedRoute> } /> <Route path='/todo/:id' element={ <AuthenticatedRoute> < TodoComponent /> </AuthenticatedRoute> } /> <Route path='/logout' element={ <AuthenticatedRoute> < LogoutComponent /> </AuthenticatedRoute> }/> <Route path='/*' element={< ErrorComponent />} /> </Routes> </BrowserRouter> </AuthProvider> </div> ) }
"""Unit tests of the task delete form.""" from django.test import TestCase from tasks.forms import RemoveMemberForm from tasks.models import Team class RemoveMemberFormTestCase(TestCase): """Unit tests of the remove team member form.""" fixtures = [ 'tasks/tests/fixtures/other_users.json', 'tasks/tests/fixtures/default_team.json', ] def setUp(self): self.team = Team.objects.get(pk=1) self.form_input = { 'confirm_deletion': True } def test_valid_task_deletion_form(self): form = RemoveMemberForm(data=self.form_input) self.assertTrue(form.is_valid()) def test_invalid_task_deletion_form(self): self.form_input = {} form = RemoveMemberForm(data=self.form_input) self.assertFalse(form.is_valid())
--- title: "Unlock The Secret To Crafting The Ultimate Minecraft Adventure: Learn How To Make A Map Now!" ShowToc: true date: "2023-02-25" author: "Thomas Stanley" --- ***** # Unlock The Secret To Crafting The Ultimate Minecraft Adventure: Learn How To Make A Map Now! Are you tired of wandering aimlessly in Minecraft? Do you want to take command of your gameplay experience and create an epic adventure for you and your friends? Then the solution is simple – learn how to make a map! Maps are an essential tool for any Minecraft player who wants to explore, build, and conquer. With a well-crafted map, you’ll know exactly where you’ve been, where you’re going, and what lies ahead. Whether you’re creating a survival world, a massive multiplayer server, or a custom adventure map, learning how to make a map is crucial for success. In Minecraft, maps are created using paper and a compass. To begin, you’ll need to obtain paper by either crafting it from sugar cane or trading with a villager. Once you’ve acquired paper, craft it into a map by placing it in the center of your crafting table and surrounding it with eight pieces of paper. Now that you have a map, hold it in your hand and right-click. This will activate the map and reveal a small portion of your surrounding area. To expand your map, walk around while holding it and uncover more of your surroundings. The larger your map, the more detail it will show. But how do you make an epic adventure map that will leave your players in awe? Here are a few tips and tricks to get you started: 1. Start With A Plan Before you begin crafting your map, have a clear vision of what you want to create. Do you want to build a massive castle, a treacherous dungeon, or a sprawling city? Sketch out a rough plan of your map and decide on the key locations you want to include. 2. Be Creative With Your Builds Minecraft is all about creativity, so don’t be afraid to let your imagination run wild. Build unique structures, incorporate redstone contraptions, and add custom mobs to enhance players’ experience. 3. Use Command Blocks Command blocks are a powerful tool in Minecraft that allows you to execute commands, trigger events, and manipulate gameplay. Use command blocks to create custom quests, puzzles, and challenges that will keep players engaged and entertained. 4. Playtest, Playtest, Playtest Once you’ve crafted your adventure map, it’s important to playtest it thoroughly. Invite friends and fellow players to explore your map and provide feedback on the gameplay experience. Use their suggestions to fine-tune your map and make it the ultimate Minecraft adventure. In conclusion, learning how to make a map is a valuable skill for any Minecraft player who wants to take their gameplay to the next level. With a little planning, creativity, and playtesting, you can craft the ultimate Minecraft adventure that will leave players begging for more. So grab some paper, a compass, and start mapping out your masterpiece today! {{< youtube pKKRUqF5PAs >}} Minecraft worlds are massive, so knowing how to make a Map in Minecraft can be very helpful. To expand your Map, you'll also need a Cartography Table. ## How to Make a Map in Minecraft Here's how to make a Map in Minecraft from scratch: Instructions in this article apply to Minecraft for all platforms including Windows, PS4, and Nintendo Switch. - Make a Crafting Table. Use 4 Wood Planks of any type (Oak Wood Planks, Crimson Wood Planks, etc.). - Mine 9 Sugar Cane. Look for stalks near water in swamp or desert biomes and use any tool to cut them down. - Put your Crafting Table on the ground and interact with it to open the 3X3 crafting grid. - Make 9 Paper. Placing 3 Sugar Cane in the middle row of the crafting grid will make 3 Paper. - Make a Compass. Put 1 Redstone Dust in the center of the 3X3 grid and 4 Iron Ignots in the adjacent boxes. - Redstone Dust can be mined from Redstone Ore using an Iron Pickaxe (or something stronger). To make Iron Ingots, craft a Furnace and smelt Iron Ores. - Place your Compass in the middle of the crafting grid, then put 8 Paper in all of the remaining blocks. - In the Bedrock Edition of Minecraft, you can make an Empty Map using 9 Paper. To add a location marker, you'll need to combine it with a Compass on a Cartography Table. - You now have an Empty Locator Map you can add to your inventory. Equip and use the Map, and then walk around to fill it out. ## Other Ways to Get a Map in Minecraft Maps can be purchased from a Cartographer for 8 Emeralds or found in sunken ships, stronghold libraries, and Cartographer's chests. To make a Cartographer, put a Cartography Table in front of a villager who doesn't have an occupation. Make a Crafting Table. Use 4 Wood Planks of any type (Oak Wood Planks, Crimson Wood Planks, etc.). Mine 9 Sugar Cane. Look for stalks near water in swamp or desert biomes and use any tool to cut them down. Put your Crafting Table on the ground and interact with it to open the 3X3 crafting grid. Make 9 Paper. Placing 3 Sugar Cane in the middle row of the crafting grid will make 3 Paper. Make a Compass. Put 1 Redstone Dust in the center of the 3X3 grid and 4 Iron Ignots in the adjacent boxes. Redstone Dust can be mined from Redstone Ore using an Iron Pickaxe (or something stronger). To make Iron Ingots, craft a Furnace and smelt Iron Ores. Place your Compass in the middle of the crafting grid, then put 8 Paper in all of the remaining blocks. In the Bedrock Edition of Minecraft, you can make an Empty Map using 9 Paper. To add a location marker, you'll need to combine it with a Compass on a Cartography Table. You now have an Empty Locator Map you can add to your inventory. Equip and use the Map, and then walk around to fill it out. In the Bedrock Edition, there's an easier way to make Maps using a Cartography Table. Place 1 Paper on the Cartography Table to produce an Empty Map. For an Empty Locator Map, Combine a 1 Paper and a Compass. In the Bedrock Edition of Minecraft, enable Starting Map under World Preferences when you create a world, to begin with a Map already in your inventory. ## How Do You Make a Map on a Cartography Table in Minecraft? To craft a Cartography Table, open a Crafting Table, put 2 Paper in the top row, then put 4 Wood Planks (any type) in the blocks below. You can also find Cartography Tables in villages inside your Cartographer's house. ## How Do You Make a Big Map in Minecraft? Each Map contains only a small portion of your Minecraft world, so you'll want to expand it as much as possible. One way to do this is to put your Map in the middle of the Crafting Table and then put 8 Paper in the remaining boxes. You can also use a Cartography Table to make your Maps bigger. Combine your Map with 1 Paper to create a new, zoomed-out Map. Repeat either of these methods four times to increase the Map to its maximum size. ## How to Set a Map Marker in Minecraft You can mark locations on your Map with Banners. In a Crafting Table, place 6 Wool of the same color in the top rows, then place 1 Stick in the middle of the bottom row. To make a copy of a Map, combine it with an Empty Map on your Cartography Table. If you want to lock the Map so it can't be altered, combine it with a Glass Pane to make a Locked Map. Use an Anvil to give the Banner a name, place the Banner on the ground, then use the Map on the Banner. A dot with the name and color of the banner will appear on your Map. ## How Do You Make a 3X3 Map Wall in Minecraft? You can place your Maps on Item Frames to make one big continuous map. Here's how to make a 3X3 wall map: - Make 9 Empty Locator Maps. Follow the instructions in the first section of this article. - Make 9 Item Frames. Put 1 Leather in the middle of the Crafting Table and 8 Sticks in the other boxes to make 1 Item Frame. - Go to where you want the center of your Map to be. Then, lay 9 solid blocks of any type on top of each other in a 3X3 square. - Technically, you can make your map wall any size so long as you have enough materials. - Use the Item Frames on the blocks to mount them. - Equip and use an Empty Locator Map to fill it out, then use the Map on the center Item Frame. - Look at the Map in your hands (it will still be in your inventory). You'll see a green dot marking the location of your wall and a white arrow representing your location. - Go south to the very edge of the Map, then equip and use another Empty Locator Map and fill it out, - Go back to the wall and place the new Map on the bottom-center block. - Repeat steps 7-8 for the southeast, southwest, east, west, north, northeast, and northwest to complete your map wall. Make 9 Empty Locator Maps. Follow the instructions in the first section of this article. Make 9 Item Frames. Put 1 Leather in the middle of the Crafting Table and 8 Sticks in the other boxes to make 1 Item Frame. Go to where you want the center of your Map to be. Then, lay 9 solid blocks of any type on top of each other in a 3X3 square. Technically, you can make your map wall any size so long as you have enough materials. Use the Item Frames on the blocks to mount them. Equip and use an Empty Locator Map to fill it out, then use the Map on the center Item Frame. Look at the Map in your hands (it will still be in your inventory). You'll see a green dot marking the location of your wall and a white arrow representing your location. Go south to the very edge of the Map, then equip and use another Empty Locator Map and fill it out, Go back to the wall and place the new Map on the bottom-center block. Repeat steps 7-8 for the southeast, southwest, east, west, north, northeast, and northwest to complete your map wall. - How big is a Minecraft map? - The lowest-level map you can create in Minecraft covers 128 x 128 blocks. You can quadruple its size each time you upgrade it (by placing it on the Crafting Table with eight sheets of paper). After four upgrades, your map will cover 2,048 x 2,048 blocks. - How do I download a Minecraft map? - Several sites will let you download maps to use for your Minecraft world. Some examples are Minecraft Maps, Planet Minecraft, and MinecraftSix. Once you've grabbed the files, drag them into your Minecraft Saves folder. The new map will appear as an option when you start up the game. The lowest-level map you can create in Minecraft covers 128 x 128 blocks. You can quadruple its size each time you upgrade it (by placing it on the Crafting Table with eight sheets of paper). After four upgrades, your map will cover 2,048 x 2,048 blocks. Several sites will let you download maps to use for your Minecraft world. Some examples are Minecraft Maps, Planet Minecraft, and MinecraftSix. Once you've grabbed the files, drag them into your Minecraft Saves folder. The new map will appear as an option when you start up the game. Get the Latest Tech News Delivered Every Day