text
stringlengths
184
4.48M
## 何をしたかったか [lukeed/tsm](https://github.com/lukeed/tsm) と [esbuild-kit/esno](https://github.com/esbuild-kit/esno) と [esbuild-kit/tsx](https://github.com/esbuild-kit/tsx) の比較 環境: - Node v17.9.0 - GitHub Codespaces 4-core/8GB RAM/32GB サンプルコード: ```ts #!/usr/bin/env tsm // dummy import "typescript"; const message: string = "hello world"; console.log(message); ``` ```ts #!/usr/bin/env esno // dummy import "typescript"; const message: string = "hello world"; console.log(message); ``` ```ts #!/usr/bin/env esmo // dummy import "typescript"; const message: string = "hello world"; console.log(message); ``` ```ts #!/usr/bin/env tsx // dummy import "typescript"; const message: string = "hello world"; console.log(message); ``` ```ts // dummy import "typescript"; const message: string = "hello world"; console.log(message); ``` ```sh time npx --call 'bash -c "for i in {1..10}; do ./hello-world.tsm.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do ./hello-world.esno.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do ./hello-world.esmo.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do ./hello-world.tsx.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do node -r tsm hello-world.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do node --loader tsm hello-world.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do node --loader tsx hello-world.ts > /dev/null 2>&1; done"' time npx --call 'bash -c "for i in {1..10}; do node -r esbuild-register hello-world.ts > /dev/null 2>&1; done"' ``` ## 結果 サイズ: esno のほうが、依存関係が多いのでややサイズ大きいが esbuild 本体に比べれば誤差程度 パフォーマンス: tsm のほうがパフォーマンス高い ```console $ time npx --call 'bash -c "for i in {1..10}; do ./hello-world.tsm.ts > /dev/null 2>&1; done"' real 0m4.848s user 0m4.608s sys 0m0.695s $ time npx --call 'bash -c "for i in {1..10}; do ./hello-world.esno.ts > /dev/null 2>&1; done"' real 0m5.261s user 0m4.765s sys 0m0.856s $ time npx --call 'bash -c "for i in {1..10}; do ./hello-world.esmo.ts > /dev/null 2>&1; done"' real 0m6.468s user 0m6.321s sys 0m0.964s $ time npx --call 'bash -c "for i in {1..10}; do ./hello-world.tsx.ts > /dev/null 2>&1; done"' real 0m10.406s user 0m9.108s sys 0m2.192s $ time npx --call 'bash -c "for i in {1..10}; do node -r tsm hello-world.ts > /dev/null 2>&1; done"' real 0m3.804s user 0m3.430s sys 0m0.513s $ time npx --call 'bash -c "for i in {1..10}; do node --loader tsm hello-world.ts > /dev/null 2>&1; done"' real 0m4.162s user 0m3.971s sys 0m0.683s $ time npx --call 'bash -c "for i in {1..10}; do node --loader tsx hello-world.ts > /dev/null 2>&1; done"' real 0m9.209s user 0m8.049s sys 0m2.035s $ time npx --call 'bash -c "for i in {1..10}; do node -r esbuild-register hello-world.ts > /dev/null 2>&1; done"' real 0m4.422s user 0m4.113s sys 0m0.694s ``` ## 感想 ここまで見た範囲では tsm 優位か
import mongoose from 'mongoose'; import bcrypt from 'bcrypt'; const Schema = mongoose.Schema; // IMPORTANT: refresh token const UserSchema = new Schema({ userId: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, devices: { type: [String], required: true } }, {timestamps: true}); UserSchema.pre( 'save', async function(next) { if (this.isModified('password')) { const hashPwd = await bcrypt.hash(this.password, 10); this.password = hashPwd; } next(); } ); UserSchema.methods.isValidPassword = async function(password) { const user = this; const compare = await bcrypt.compare(password, user.password); return compare; } const UserModel = mongoose.model('user', UserSchema); export default UserModel;
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import React from "react"; import styled from "styled-components"; import { BrandLogo } from "../brandLogo"; import { Link } from "react-router-dom"; import { Marginer } from "../../components/marginer"; import { faFacebook, faTwitter } from "@fortawesome/free-brands-svg-icons"; import { faEnvelope, faEye } from '@fortawesome/free-solid-svg-icons'; import { deviceSize } from "../responsive"; import { useMediaQuery } from "react-responsive"; import FooterSectionBackgroundImg from "../../images/footer.png"; const FooterContainer = styled.div` width: 100%; min-height: 300px; background: url(${FooterSectionBackgroundImg}) no-repeat; display: flex; flex-direction: column; justify-content: space-between; padding: 2em 3em; padding-bottom: 0; border-top: 0.6px solid rgb(0, 0, 0, 0.3); @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0px 30px; } `; const TopContainer = styled.div` width: 100%; display: flex; margin-bottom: 1em; @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const LogoContainer = styled.div` display: flex; font-size: 10px; align-items: flex-start; flex-direction: column; line-height: 1.3; text-align: start; @media screen and (max-width: ${deviceSize.mobile}px) { align-items: left; font-size: 10px; } `; const ContentContainer = styled.div` display: flex; flex-direction: column; align-items: flex-start; &:not(:last-of-type) { margin-right: 3%; } @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const BottomContainer = styled.div` display: flex; justify-content: space-between; align-items: center; height: 70px; border-top: 0.6px solid rgb(0, 0, 0, 0.3); padding: 0 10px; @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const RightBottomContainer = styled.div` display: flex; @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const LeftBottomContainer = styled.div` display: flex; @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const Title = styled.h2` margin: 0; margin-bottom: 13px; color: #000; font-weight: 600; font-size: 20px; &:hover { color: #485412; @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const FLink = styled.a` text-decoration: none; color: #6f6f6f; font-weight: 500; font-size: 15px; cursor: pointer; &:not(:last-of-type) { margin-bottom: 8px; } @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const SloganText = styled.h3` margin: 0; line-height: 1.5; color: #fff; font-weight: bold; font-size: 15px; text-align: left; padding-top: 1em; &:hover { color: #0D2D19; } @media screen and (max-width: ${deviceSize.mobile}px) { font-size: 11px; font-weight: bold; } `; const PrivacyText = styled.h6` color: #F3F3F3; font-size: 11px; margin: 0; margin-left: 10px; display: flex; margin-top: 5px; align-items: center; text-align: left; &:hover { color: #0D2D19; } @media screen and (max-width: ${deviceSize.mobile}px) { font-size: 10px; } `; const PrivacyTextQ = styled.h6` color: #F3F3F3; font-size: 15px; margin: 0; margin-left: 10px; display: flex; margin-top: 5px; align-items: center; &:hover { color: #0D2D19; } @media screen and (max-width: ${deviceSize.mobile}px) { font-size: 10px; } `; const PrivacyTextQ1 = styled.h6` color: #F3F3F3; font-size: 14px; margin: 0; margin-left: 10px; display: flex; margin-top: 5px; align-items: center; &:hover { color: #0D2D19; } @media screen and (max-width: ${deviceSize.mobile}px) { font-size: 10px; } `; const AnchorLink = styled(Link)` font-size: 12px; color: #fff; cursor: pointer; text-decoration: none; outline: none; transition: all 200ms ease-in-out; &:hover { color: #0D2D19; } @media screen and (max-width: ${deviceSize.mobile}px) { padding: 0; } `; const SocialIcon = styled.div` color: #0D2D19; font-size: 20px; cursor: pointer; transition: background-color, 200ms ease-in-out; &:not(:last-of-type) { margin-right: 10px; } &:hover { color: #ffff; } @media screen and (max-width: ${deviceSize.mobile}px) { font-size: 15px; } `; export function Footer(props) { const isMobile = useMediaQuery({ maxWidth: deviceSize.mobile }); return ( <FooterContainer> <TopContainer> <ContentContainer> <LogoContainer> <BrandLogo logoSize={isMobile ? 33 : 40} textSize={isMobile ? 28 : 35} /> </LogoContainer> <SloganText> Trading and investing in digital options involves significant level of risk and is not suitable for all clients. Please make sure you carefully consider your investment your investment objectives, level of experience and risk appetite before buying or selling any digital option. Buying or selling digital options entails financial risks and could result in a partial or complete loss of your funds, therefore, you should not invest funds you cannot afford to lose. You should be aware of and fully understand all the risks associated with trading and investing in digital options, and seek advice from an independent financial advisor if you have any doubts. </SloganText> <Marginer direction="vertical" margin={8} /> </ContentContainer> <ContentContainer> <Title>Quick Links</Title> <AnchorLink to="/customer/access/signup"> <PrivacyTextQ>Home</PrivacyTextQ> </AnchorLink> <AnchorLink to="/customer/access/signup"> <PrivacyTextQ>Login</PrivacyTextQ> </AnchorLink> <AnchorLink to="/customer/access/signup"> <PrivacyTextQ>Join Us</PrivacyTextQ> </AnchorLink> <AnchorLink to="/customer/access/signup"> <PrivacyTextQ>FAQ</PrivacyTextQ> </AnchorLink> <AnchorLink to="/accountTypes"> <PrivacyTextQ1>AccountTypes</PrivacyTextQ1> </AnchorLink> </ContentContainer> <ContentContainer> <Title>Contact Us</Title> <SocialIcon> <FontAwesomeIcon icon={faEnvelope} /> <PrivacyText>bitchangetrading@gmail.com</PrivacyText> </SocialIcon> <SocialIcon> <FontAwesomeIcon icon={faEye} /> <PrivacyText>Door open</PrivacyText> <PrivacyText>Mon - Sun : 09:00 - 18:00</PrivacyText> </SocialIcon> </ContentContainer> </TopContainer> <BottomContainer> <LeftBottomContainer> {< hideLogo color="#F3F3F3" textSize={isMobile ? 20 : 25} />} <PrivacyText>bitchangetrading&#169; All Rights Reserved. 2021</PrivacyText> </LeftBottomContainer> <RightBottomContainer> <SocialIcon> <FontAwesomeIcon icon={faFacebook} /> </SocialIcon> <SocialIcon> <FontAwesomeIcon icon={faTwitter} /> </SocialIcon> </RightBottomContainer> </BottomContainer> </FooterContainer> ); }
# rm(list = ls()) # Read the fin\unction setwd("C:/MyTemp/myGitLab/windDamage") source("myFunctions.R") # Test new library # sf objects library(ggplot2) # for choropleth map plot library(spdep) # neighbours library(rgdal) library(rgeos) library(sf) library(raster) library(dplyr) library(spData) library(sf) # Read real data just to get crs # Set working directory setwd("U:/projects/2019_windthrowModel/Janita/outSimulated") # Read stand geometry df.geom = read_sf("MV_Korsnas.shp") # Test if the fuinction correctly loops over lit of data r1 <- raster(nrow=11, ncol=6, crs = crs(df.geom)) #"+init=epsg:2957" values(r1) <- matrix(data = c(20, NA, NA, NA, NA,20, NA, NA, NA, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20), nrow = 11, ncol = 6, byrow = TRUE) # Convert raster to polygon my.sf1<-st_as_sf(rasterToPolygons(r1)) names(my.sf1) <- c("treeHeight", "geometry") # make raster r2 r2 <- r1 values(r2) <- matrix(data = c(20, NA, NA, NA, NA,20, NA, NA, NA, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, NA, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 0, 0, 20, NA, 20, 20, 0, 0, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 20, 20, 20), nrow = 11, ncol = 6, byrow = TRUE) # Convert raster to polygon my.sf2<-st_as_sf(rasterToPolygons(r2)) names(my.sf2) <- c("treeHeight", "geometry") # Make raster 3 r3 <- r1 values(r3) <- matrix(data = c(20, NA, NA, NA, NA,20, NA, NA, NA, 20, 20, 20, NA, NA, 5, 8, 20, 20, NA, NA, 20, 10, 20, 20, NA, NA, 20, 20, 0, 20, NA, NA, 20, 20, 20, 20, NA, 20, 20, 20, 0, 20, NA, 20, 20, 20, 20, 20, NA, 20, 20, 0, 20, 20, NA, 20, 20, 20, 20, 20, NA, 20, 1, 0, 0, 20), nrow = 11, ncol = 6, byrow = TRUE) # Convert raster to polygon my.sf3<-st_as_sf(rasterToPolygons(r3)) names(my.sf3) <- c("treeHeight", "geometry") # list without open_edge calculated my.ls1<-list(my.sf1, my.sf2) my.ls2<-list(my.sf1, my.sf2, my.sf3) # Try ifg open_edge function works on both: sf1<-findOpenEdge_sf(sf = my.sf1, treeHeight=treeHeight, distance = 10, pixel.width = 16) sf2<-findOpenEdge_sf(sf = my.sf2, treeHeight=treeHeight, distance = 10, pixel.width = 16) plot(sf1) plot(sf2) # seems that individually algorith works # Put data together in a list of sfs objects, try again my.ls<-list(sf1, sf2) # run the function just on one of them my.ls[[2]] plot(my.ls[[2]]) # are teh files in a list and original identical?? identical(my.ls[[2]], sf2) # Does the function works on a element of a list? outLs1<-findOpenEdge_sf(sf = my.ls1[[2]], treeHeight=treeHeight, distance = 10, pixel.width = 16) # Lapply a function over the list out<-lapply(my.ls2, findOpenEdge_sf) plot(out[[3]]) #my.sf$open_edge <- FALSE # Create output: sf.open<- findOpenEdge_sf(sf = my.sf, treeHeight=treeHeight, distance = 10, pixel.width = 16) # Test data on true geometry # ----------------------------------------------- # Set working directory setwd("U:/projects/2019_windthrowModel/Janita/outSimulated") # read simulated data df <- read.csv("rsl_without_MV_Korsnas.csv", sep = ";") # without == climate change is not included # Read stand geometry df.geom = read_sf("MV_Korsnas.shp") #df.geom = readOGR(dsn = getwd(), # layer = "MV_Korsnas") # Test if the function works: create new H_dom variable, # fill in with pre-defined colours # make for multiple landscapes (time) # to see if the function works # clean up unnecessary columns out<- subset(df.geom, select = c("standid")) sf1<-out sf2<-out sf3<-out # Create new landscapes with different tree heights sf1$H_dom <- rep(20, nrow(sf1)) # CReate another landscape sf2$H_dom <- rep(c(20, 30), each = nrow(df.geom)/2) sf3$H_dom <- rep(c(20, 30), nrow(df.geom)/2) # Calculate open edge sf1.open = findOpenEdge_sf(sf = sf1, H_dom = H_dom, distance = 10, pixel.width = 16) sf2.open = findOpenEdge_sf(sf = sf2, H_dom = H_dom, distance = 10, pixel.width = 16) sf3.open = findOpenEdge_sf(sf = sf3, H_dom = H_dom, distance = 10, pixel.width = 16) plot(sf1.open["open_edge"]) plot(sf2.open["open_edge"]) plot(sf3.open["open_edge"]) # Load data shp = system.file("shape/nc.shp", package="sf") my.sf <- st_read(shp, quiet = TRUE) # Convert crs to projected system to make buffer my.sf.web<- st_transform(my.sf, 3857) # Subset the data to create two independent shps i = 10 # Split datasets in two files one = my.sf.web[i, ] left = my.sf.web[-i,] # Create buffer buff35 = st_buffer(one, 35000 ) # distance buff50 = st_buffer(one, 50000) # CHeck which polygons overlaps with my buffer out.overlap = st_overlaps(buff, left) # Subset the polygons that overlaps with the buffer nbrs.buff35 <- left[st_overlaps(buff35,left)[[1]],] nbrs.buff50 <- left[st_overlaps(buff50,left)[[1]],] # Merge together `neighbors`` and `one` u <- st_union(rbind(nbrs.buff, one)) int.buff.one = st_difference(buff, u) int.buff.one.area <- st_area(int.buff.one) library(gridExtra) p1 <- ggplot(nbrs.buff50) + geom_sf(fill = "lightblue") + geom_sf(data = buff50, fill = NA, col = "red", lwd = 1) p2 <- ggplot(nbrs.buff35) + geom_sf(fill = "grey") + geom_sf(data = buff35, fill = NA, col = "red", lwd = 1) grid.arrange(p1, p2, nrow = 1) # --------------------------------------------------- # Why overlay operation does not subset the completely overlapped features? # ---------------------------------------------------- # Load data shp = system.file("shape/nc.shp", package="sf") my.sf <- st_read(shp, quiet = TRUE) # Convert crs to projected system to make buffer my.sf.web<- st_transform(my.sf, 3857) # Subset the data to create two independent shps i = 10 # Split datasets in two files one = my.sf.web[i, ] #left = my.sf.web[-i,] # Create buffer #buff35 = st_buffer(one, 35000 ) # distance buff50 = st_buffer(one, 50000) # CHeck which polygons overlaps with my buffer out.overlap = st_overlaps(buff50, my.sf.web) out.overlap <- my.sf.web[st_intersects(buff50, my.sf.web, sparse = FALSE),] # Subset the polygons that overlaps with the buffer #nbrs.buff35 <- left[st_overlaps(buff35,left)[[1]],] nbrs.buff50 <- my.sf.web[st_overlaps(buff50,my.sf.web)[[1]],] #nbrs.buff50 <- my.sf.web[st_covers(buff50,my.sf.web)[[1]],] nbrs.buff50 <- my.sf.web[st_within(buff50,my.sf.web)[[1]],] library(gridExtra) ggplot(buff50) + geom_sf(data = my.sf.web, fill = "lightgrey") + geom_sf(data = nbrs.buff50, fill = "red") + geom_sf(fill = NA, col = "green", lwd = 2) + geom_sf(data = out.overlap, fill = "violet") ggplot(out.overlap) + geom_sf(data = out.overlap) + geom_sf(data = buff50, col = "red", fill = NA) p2 <- ggplot(nbrs.buff50) + geom_sf(fill = "lightgrey") + geom_sf(data = buff50, fill = NA, col = "red", lwd = 1) grid.arrange(p1, p2, nrow = 1)
# Dotfiles > This is the Dotfiles for personal usage. The current setup is base on `arcolinuxb-xfce-v23.05.04-x86_64.iso` Windows Manager: AwesomeWM Shell: ZSH Terminal: Kitty Editor: Lunarvim Theme: Catppuccin Macchiato ## Setup - pluggable authentication modules(PAM) - package manager - yay - mirror list - reflector - reflector-simple - locale - en_US.UTF-8 UTF-8 - zh_CN.UTF-8 UTF-8 - polkit - xfce-polkit - clipboard - xsel - copyq - flameshot - font - font-manager - ttf-font-awesome - ttf-jetbrains-mono - ttf-jetbrains-mono-nerd - ttf-roboto - ttf-liberation - noto-fonts - noto-fonts-cjk - noto-fonts-emoji - noto-fonts-extra - <https://wiki.archlinux.org/title/Help:I18n> - input method - fcitx5-im - fcitx5-rime - fcitx5-material-color - kill `ps -A | grep fcitx5 | awk '{print $1}'` && fcitx5 -d - <https://github.com/hosxy/Fcitx5-Material-Color> - external monitor - arandr - audio - pipewire (multimedia framework) - pipewire-audio (audio client) - pavucontrol (GUI controller) - wireplumber (session manager) - pacmixer - driver - xf86-video-amdgpu - display server - xorg - .xinitrc - .Xresources - xorg automation - xdotool - autokey - windows manager - awesomewm-git - twm - terminal emulator - wezterm - terminal multiplexers - zellij - backlight - ddcui - brightnessctl - xfce4-power-manager - shell - zsh - oh-my-zsh - theme: bira - plugins: - zsh-autosuggestions - z - <https://github.com/zsh-users/zsh-autosuggestions> - editor - neovim - lunarvim - neovide - status bar - polybar - xorg compositor - picom-git - application launcher - rofi - display manager - sddm - xinit-xsession - screenlocker - betterlockscreen - notification daemon - naughty - dunst - wallpaper - feh - python-pywal - swapfile - no swap on installation - ext4 format - use swapfile on later stage - setup swap for hibernation - bootloader - grub-install - utility - duf(df alternative) - duc(du with graph) - ncdu(disk usage) - difftastic(diff alternative) - lsd(ls alternative) - ripgrep(grep alternative) - fd(find alternative) - sd(sed alternative) - hyperfine(shell benchmark) - tokei(code language statistics) - tealdeer(tldr) - bandwhich(network traffic monitor) - zoxide(zsh z alternative) - grex(regex generator) - bottom(resource monitor) - htop(process monitor) - procs(process monitor) - fnm(nvm alternative) - stacer(system cleaning) - thunar(file manager, gui) - xplr(file manager, rust tui) - lf(file manager, golang tui) - xclock(default boot program from xinit) - arandr(xrandr gui) - inxi(hardware overview) ## FAQ - connect to wifi - nmcli device wifi connect <SSID> password <PW> - show all os in grub - install `os-prober`, `update-grub` - `sudo os-prober` - `sudo update-grub` - brightness control - internal monitor (e.g. laptop) - brightnessctl - external monitor - ddcutil - laptop optimize - touchpad - natural scrolling - single tap - [libinput](https://wiki.archlinux.org/title/Libinput#Via_Xorg_configuration_file) ## Reference [Best tool comparison](https://www.linuxlinks.com/ClipboardManagers/)<br> [LunarVim configuration](https://www.lunarvim.org/docs/faq#how-do-i-use-lunarvim-in-neovide)<br> [ZSH files](https://apple.stackexchange.com/questions/388622/zsh-zprofile-zshrc-zlogin-what-goes-where)<br> [Vim Search](https://thevaluable.dev/vim-search-find-replace/)<br> [AwesomeWM dotfiles](https://github.com/AlphaTechnolog/dotfiles)<br> [AwesomeWM customization](http://epsi-rns.github.io/desktop/2019/06/15/awesome-overview.html)<br> [Building Your Mouseless Development Environment](https://themouseless.dev/)<br> [Code strcuture in lang](https://github.com/epsi-rns/case-examples)<br> [ZSH keymap](https://thevaluable.dev/zsh-line-editor-configuration-mouseless/)<br> [Lua 101](https://epsi.bitbucket.io/lambda/2020/11/16/playing-with-records-lua-01/)<br> [Application list](https://wiki.archlinux.org/title/List_of_applications#top-page)<br> [EWW powermenu](https://dharmx.is-a.dev/eww-powermenu/)<br> [AwesomeWM example](https://github.com/muammar/awesome/blob/master/autostart.lua)<br> <http://epsi-rns.github.io/desktop/2019/06/15/awesome-overview.html><br> ## Change default editor for sudo <https://unix.stackexchange.com/questions/408413/change-default-editor-to-vim-for-sudo-systemctl-edit-unit-file>
import React, { useState } from 'react'; import AddFavourite from './AddFavourites'; const MovieList = (props) => { const [showPopup, setShowPopup] = useState(false); const [selectedMovie, setSelectedMovie] = useState(null); const [userRating, setUserRating] = useState(0); const handleMovieClick = (movie) => { setShowPopup(true); setSelectedMovie(movie); }; const handleRatingChange = (event) => { let value = parseFloat(event.target.value); // Check if the number is between 0 and 10 and has at most one decimal place if (value >= 0 && value <= 10 && !isNaN(value)) { value = Math.round(value * 10) / 10; // Round to one decimal place setUserRating(value); } }; const handleConfirmRating = () => { setShowPopup(false); props.handleFavouritesClick(selectedMovie, userRating); }; return ( <> {showPopup && ( <div className='modal-overlay'> <div className='modal-content'> <h4 className='popup-heading'>Set Rating for {selectedMovie?.Title}</h4> <span className='m-1'></span> <input className="popup-input" type="number" value={userRating} onChange={handleRatingChange} min="1" max="10" step="0.1" /> <span className='m-2'></span> <button className="popup-button" onClick={handleConfirmRating}>Confirm Rating</button> </div> </div> )} {props.movies.map((movie, index) => ( <div className='image-container d-flex justify-content-start m-3 poster-container'> <img src={movie.Poster} alt='movie'></img> <div onClick={() => handleMovieClick(movie)} className='overlay d-flex align-items-center justify-content-center add-favorite-container' > <AddFavourite /> </div> </div> ))} </> ); }; export default MovieList;
import { Link } from "react-router-dom"; import { useLoginValidation } from "./validation"; export function LoginForm() { const { errors, handleSubmit, isSubmitting, register, sendForm } = useLoginValidation(); return ( <form className="z-40 grid place-items-center gap-y-4" onSubmit={handleSubmit(sendForm)} > <fieldset className="w-full max-w-80 space-y-1 "> <label htmlFor="email" className="block pb-1 text-brown text-sm sm:text-base" > E-mail </label> <input type="text" id="email" className="bg-gow border border-[#7d2d0a4d] rounded-md w-full text-sm sm:text-base h-10 indent-2 text-darkBrown outline-none" placeholder="E-mail utilizado no cadastro" required {...register("email")} /> {errors.email && ( <small className="text-sm w-full text-red-700 ml-1"> *{errors.email.message} </small> )} </fieldset> <div className="flex items-center justify-between w-full max-w-80 "> <Link to={"/cadastrar"} className="z-40 text-center text-sm sm:text-base underline text-brown font-medium" > Não possuo cadastro </Link> <button className="space-y-1 w-36 h-10 text-sm sm:text-lg bg-brown rounded-md text-gold transition-all hover:scale-95 disabled:bg-opacity-80 disabled:pointer-events-none" disabled={isSubmitting} > {isSubmitting ? "Avançando..." : "Avançar"} </button> </div> </form> ); }
package se.umu.svke0008.thirty.domain.service import se.umu.svke0008.thirty.domain.model.Dice import se.umu.svke0008.thirty.domain.model.GameState import se.umu.svke0008.thirty.domain.model.ScoreChoice import se.umu.svke0008.thirty.domain.model.ScoreHistory import kotlinx.coroutines.flow.Flow /** * Interface that defines operations for the game-service. */ interface GameService { /** * Retrieves the current state of the game. */ fun getGameState(): Flow<GameState> /** * Retrieves the current list of dice. */ fun getDice(): Flow<List<Dice>> /** * Performs a dice throw action using the given list of dice. */ fun throwDice(diceList: List<Dice>) /** * Selects a die from the given list of dice. */ fun selectDice(die: Dice, diceList: List<Dice>) /** * Locks a die from the given list of dice. */ fun lockDice(die: Dice, diceList: List<Dice>) /** * Retrieves the total score of the game. */ fun getTotalScore(): Flow<Int> /** * Retrieves the calculated score from combinations. */ fun getCalculatedScore(): Flow<Int> /** * Retrieves the list of score choices. */ fun getScoreChoices(): Flow<List<ScoreChoice>> /** * Retrieves the history of scores choices. */ fun getScoreHistory(): Flow<List<ScoreHistory>> /** * Selects a score choice. */ fun selectScoreChoice(selectedScoreChoice: ScoreChoice) /** * Ends the current turn of the game. */ suspend fun endTurn() /** * Starts a new game. */ fun startNewGame() /** * Toggles the state of the help assist. */ fun toggleHelpAssist() /** * Restores the game state from a previously saved instance. * * @param gameState The previously saved GameState object that will be used to restore the game. * This should include all the necessary information to fully resume the game from the point it was saved. */ fun retrieveSavedGameState(gameState: GameState) /** * Retrieves the number of throws left. */ val throwsLeftFlow: Flow<Int> /** * Checks if there are no more throws left. */ val noMoreThrows: Flow<Boolean> /** * Checks if the game is over. */ val gameOver: Flow<Boolean> /** * Checks if the help assist is enabled. */ val helpAssistEnabled: Flow<Boolean> /** * Checks if ending the turn is allowed. */ val endTurnAllowed: Flow<Boolean> /** * Checks if a throw action has been performed. */ val hasThrown: Flow<Boolean> /** * Emits a string message every time a turn ends. */ val endTurnEventFlow: Flow<String> /** * Checks if a score choice has been selected. */ val hasSelectedChoice: Flow<Boolean> /** * Retrieves the number of rounds left. */ val roundsLeftFlow: Flow<Int> /** * Checks if a new game has started. */ val newGameFlow: Flow<Boolean> /** * Checks if the game has been won. */ val hasWon: Flow<Boolean> }
#pragma once #include <iostream> #include <string> #include <unordered_map> #include<glm/glm.hpp> struct ShaderProgramSource { std::string VertexSource; std::string FragmentSource; }; class Shader { private: std::string m_FilePath; unsigned int m_RendererID; std::unordered_map<std::string, int> m_LocationCache; public: Shader(const std::string& filepath); ~Shader(); void Bind() const; void Unbind() const; //Set Uniforms void SetUniform1i(const std::string& name, int value); void SetUniform1f(const std::string& name, float value); void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3); void SetUniformMat4f(const std::string& name, const glm::mat4& mat); bool CompileShader(); private: int GetUniformLocation(const std::string& name); unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader); unsigned int CompileShader(const std::string& source, unsigned int type); ShaderProgramSource parseShader(const std::string& filePath); };
<h2 mat-dialog-title style="text-align: center">{{ tituloForm }}</h2> <mat-dialog-content [formGroup]="frm"> <div> <mat-form-field> <input matInput placeholder="Ingrese la fecha" type="date" name="fecha" formControlName="fecha" /> </mat-form-field> <mat-form-field> <mat-label>Seleccione el cliente</mat-label> <mat-select formControlName="cliente" required> <mat-option>Ninguno</mat-option> <mat-option *ngFor="let clientes of _clienteData" [value]="clientes.id"> {{ clientes.nombre }} - {{ clientes.nit }} </mat-option> </mat-select> </mat-form-field> </div> <div> <h3 style="text-align: center">Detalle Del Ingreso</h3> </div> <div> <mat-form-field> <mat-label>Seleccione el producto</mat-label> <mat-select formControlName="producto" required> <mat-option>Ninguno</mat-option> <mat-option *ngFor="let productos of _productoData" [value]="productos.id" > {{ productos.descripcion }} </mat-option> </mat-select> </mat-form-field> <mat-form-field> <input matInput placeholder="Ingrese la cantidad" type="number" name="cantidad" formControlName="cantidad" /> </mat-form-field> <button mat-icon-button color="primary" (click)="addItem()"> <mat-icon>add</mat-icon> </button> </div> <div> <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="idSalidaDetalle"> <th mat-header-cell *matHeaderCellDef>ID</th> <td mat-cell *matCellDef="let element"> {{ element.idSalidaDetalle }} </td> </ng-container> <ng-container matColumnDef="producto"> <th mat-header-cell *matHeaderCellDef>Producto</th> <td mat-cell *matCellDef="let element"> {{ element.producto.descripcion }} </td> </ng-container> <ng-container matColumnDef="cantidad"> <th mat-header-cell *matHeaderCellDef>Cantidad</th> <td mat-cell *matCellDef="let element"> {{ element.cantidad }} </td> </ng-container> <ng-container matColumnDef="valor"> <th mat-header-cell *matHeaderCellDef>Valor</th> <td mat-cell *matCellDef="let element"> {{ element.valor }} </td> </ng-container> <ng-container matColumnDef="valorTotal"> <th mat-header-cell *matHeaderCellDef>Total</th> <td mat-cell *matCellDef="let element"> {{ element.valorTotal | number: "1.1-2" }} </td> </ng-container> <ng-container matColumnDef="opciones"> <th mat-header-cell *matHeaderCellDef [ngStyle]="{ display: localSave == true ? 'table-cell' : 'none' }" > Opciones </th> <td mat-cell *matCellDef="let element" [ngStyle]="{ display: localSave == true ? 'table-cell' : 'none' }" > <button type="button" mat-icon-button color="warn" (click)="eliminar(element)" > <mat-icon>delete</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> </table> </div> <br /> <button type="button" mat-raised-button color="primary" style="float: right" (click)="grabar()" [disabled]="!localSave ? 'isabled' : null" > <span>Finalizar</span> </button> <button type="button" mat-raised-button color="warn" style="float: left" (click)="cerrar()" > <span>Cancelar</span> </button> </mat-dialog-content>
import { useMemo } from 'react'; import { Navigate, useNavigate, useParams } from 'react-router-dom'; import { getHeroById } from '../helpers'; export const HeroPage = () => { const { id } = useParams(); const navigate = useNavigate(); // Hook de useMemo, cuando el 'id' cambié, se dispara el método // del primer parámetro. const hero = useMemo( () => getHeroById(id), [id]); const onNavigateBack = () => { // Regresar en el historial a la página anterior: navigate(-1); } if ( !hero ) { return <Navigate to="/marvel" /> } return ( <div className="row mt-5"> <div className="col-4"> <img src={`/assets/heroes/${id}.jpg`} alt={ hero.superhero } className="img-thumbnail animate__animated animate__fadeInLeft" /> </div> <div className="col-8"> <h3>{ hero.superhero }</h3> <ul className="list-group list-group-flush"> <li className="list-group-item"><b>Alter ego: </b>{ hero.alter_ego }</li> <li className="list-group-item"><b>Publisher: </b>{ hero.publisher }</li> <li className="list-group-item"><b>First Appearance: </b>{ hero.first_appearance }</li> </ul> <h5 className="mt-3">Characters</h5> <p>{ hero.characters }</p> <button className="btn btn-outline-primary" onClick={ onNavigateBack } > Regresar </button> </div> </div> ) }
// ** React Imports import {useEffect, useMemo, useState} from 'react' import useBoundStore from "../../../../../../stores"; import {useForm, Controller} from "react-hook-form"; import toast from "react-hot-toast"; import {Button, Form, Offcanvas} from "react-bootstrap"; import {Info, X} from "react-feather"; import Select , { createFilter } from "react-select"; import {Input, Label} from "reactstrap"; import {addFormRelation, createFormField, removeFormField, updateFormField} from "../../../../../../libs/axios"; import {useQueryClient} from "react-query"; import Swal from 'sweetalert2'; import withReactContent from "sweetalert2-react-content"; interface FieldTypeOption { value: string; label: string; fieldType: string; } const fieldTypeOptions: Array<FieldTypeOption> = [ // {value: 'row', label: 'Row'}, { value: 'text-input', label: 'Input Text', fieldType: 'string' }, { value: 'number-input', label: 'Input Number', fieldType: 'int' }, { value: 'float-input', label: 'Input Float', fieldType: 'float' }, { value: 'text-area', label: 'Text Area', fieldType: 'mediumtext' }, { value: 'radio', label: 'Radio (TEXT)', fieldType: 'string' }, { value: 'datetime', label: 'Date & Time', fieldType: 'datetime' }, { value: 'date', label: 'Date', fieldType: 'date' }, { value: 'time', label: 'Time', fieldType: 'time' }, { value: 'checkbox', label: 'Checkbox', fieldType: 'boolean' }, { value: 'select', label: 'Select (TEXT)', fieldType: 'string' }, ] const FieldConfigCanvas = (props: { show: boolean }) => { const swalController = withReactContent(Swal) const closeBoxConfig = useBoundStore(state => state.formEditor.closeFieldConfig); const formData = useBoundStore(state => state.formEditor.formData); const currentSelectedField = useBoundStore(state => state.formEditor.currentSelectedField); const removeField = removeFormField; const fieldConfigFormAction = useBoundStore(state => state.formEditor.fieldConfigFormAction); // Get QueryClient from the context const queryClient = useQueryClient() const [slugInit, setSlugInit] = useState(''); const defaultValues = useMemo(() => { return {name: currentSelectedField?.name ?? '', slug: currentSelectedField?.slug ?? '', selectedFieldType: fieldTypeOptions.find( ft => ft.value == currentSelectedField?.componentTemplate ) ?? undefined}; }, [currentSelectedField]); const { reset, control, setError, watch, handleSubmit, formState: {errors} } = useForm<{ name: string, slug: string, targetForm?: {value: number}, connectFromField?: number, connectToField?: number, selectedFieldType?: FieldTypeOption }>( { defaultValues: defaultValues }) const watchFieldTypeSelect = watch('selectedFieldType'); const [listFormData, setListFormData] = useState([]) useEffect(() => { reset(defaultValues) }, [currentSelectedField, defaultValues]) function onSubmit(data: any) { if (data.slug == null || data.slug === '') { data.slug = slugInit; } if (data.selectedFieldType === null) { setError('selectedFieldType', {type: 'custom', message: 'Please select fieldType'}) return; } if (fieldConfigFormAction == 'new') { switch (data.selectedFieldType.value) { case 'relation': case 'relation-multiple': addFormRelation(formData.id, { formId: formData.id, targetFormId: data.targetForm.value, ...data, }).then( r => console.log(r)) break; default: toast.promise( createFormField(formData.id, { slug: data.slug, name: data.name, componentTemplate: data.selectedFieldType.value, fieldType: data.selectedFieldType.fieldType, }), { loading: 'Updating component', success: 'Update component success', error: 'Update component fail' } ).then(action => { console.log(`/forms/${formData.id}`) queryClient.invalidateQueries({ queryKey:[`forms`, formData.id.toString()] }).then(() => {}) reset(); setSlugInit(''); }).catch(e => { console.error('createField fail', e) }) break; } } else { toast.promise( updateFormField(formData.id, currentSelectedField.id, { name: data.name, }), { loading: 'Updating component', success: 'Update component success', error: 'Update component fail' }).then(action => { reset(); setSlugInit(''); }).catch(e => { console.error('createComponent fail', e) }) } } return ( <Offcanvas style={{width: 560}} backdrop="static" onHide={() => { closeBoxConfig() }} show={props.show} scroll={true} placement={"end"}> <Offcanvas.Header closeButton> <Offcanvas.Title>{fieldConfigFormAction == 'edit' ? 'Update Field' : 'New Field'}</Offcanvas.Title> </Offcanvas.Header> <Offcanvas.Body> <div className='d-flex flex-wrap mb-0'> <div className={'me-auto'}> {currentSelectedField?.slug} </div> {(currentSelectedField != null) ? <Button variant={'outline-danger'} onClick={() => { removeField(formData.id, currentSelectedField.id).then( r => console.log(r)) }} size={'sm'} type='submit' className='ms-auto mb-2' > {/*TODO formData must valid*/} remove {formData.id} <X size={12}/> </Button> : null} </div> <Form onSubmit={handleSubmit(onSubmit)}> <div> <Label className='form-label' for='comp-name'> Field Name </Label> <a href={"https://docs.hypesdk.com/form#field"} style={{position: 'absolute', right: 20}} target={"_blank"} rel="noreferrer"><Info/></a> <Controller name='name' control={control} render={({field}) => (<Input {...field} id='comp-name' type='text' onChange={(e) => { setSlugInit(e.target.value.trim().toLowerCase().replace(/ /g, "_")); field.onChange(e) }} invalid={errors.name && true}/>)} /> </div> <div> <Label className='form-label' for='comp-slug'> Field Slug </Label> <Controller name='slug' control={control} render={({field}) => (<Input {...field} id='comp-slug' type='text' disabled={fieldConfigFormAction === 'edit'} placeholder={slugInit} invalid={errors.slug && true}/>)} /> </div> <div> <Label className='form-label' for='component'>Field for Component</Label> <Controller name='selectedFieldType' control={control} render={({field}) => (<Input {...field} type='select' value={watchFieldTypeSelect?.value} onChange={(e) => { field.onChange(fieldTypeOptions.find(c => c.value === e.target.value)) } } disabled={fieldConfigFormAction === 'edit'} > <option value={''}>None</option> {fieldTypeOptions.map((o, i) => { return <option key={o.value} value={o.value}>{o.label}</option> })} </Input>)} /> {errors.selectedFieldType && <p className={'text-danger'}>{errors.selectedFieldType.message} !</p>} </div> {watchFieldTypeSelect != null && (watchFieldTypeSelect.value === 'relation' || watchFieldTypeSelect.value === 'relation-multiple') ? <> <div> <Label className='form-label' for='targetForm'>Target Form</Label> <Controller name='targetForm' control={control} render={({field}) => ( <Select {...field} value={listFormData.length > 0 ? listFormData.filter((item: {value: number}) => item.value === (field.value ?? -1))[0] : field.value} options={listFormData} isClearable={false} filterOption={createFilter({trim: true})} className='react-select' classNamePrefix='select' />)} /> </div> <div> <Label className='form-label' for='connectFromComponent'>Migrate relation</Label> <Controller name='connectFromField' control={control} render={({field}) => ( <Input {...field} type='text' placeholder={'this form component slug'} invalid={errors.slug && true}/> )} /> <Controller name='connectToField' control={control} render={({field}) => ( <Input {...field} type='text' placeholder={'target form component slug'} invalid={errors.slug && true}/> )} /> </div> </> : null } <Button type={'submit'} className='ms-auto mt-2' color='primary'> Save </Button> </Form> </Offcanvas.Body> </Offcanvas> ) } export default FieldConfigCanvas
class PizzaEntry { constructor(diameter, price) { this.diameter = diameter; this.price = price; this.area = diameter * diameter * Math.PI / 4; this.pricePerArea = price / this.area; } } var elements = []; function sortElements() { elements.sort(function(a, b) { return a.diameter - b.diameter; }); } function updateTable() { var table = document.getElementById("myTable"); // clear table while (table.firstChild) { table.removeChild(table.firstChild); } // add header var header = table.createTHead(); var headerRow = header.insertRow(0); var j = 0; headerRow.insertCell(j++).innerHTML = "Diameter"; headerRow.insertCell(j++).innerHTML = "Price"; headerRow.insertCell(j++).innerHTML = "Area"; headerRow.insertCell(j++).innerHTML = "Price per area"; headerRow.insertCell(j++).innerHTML = ""; // add entries var body = table.createTBody(); for (var i = 0; i < elements.length; i++) { var row = body.insertRow(-1); var j = 0; row.insertCell(j++).innerHTML = elements[i].diameter; row.insertCell(j++).innerHTML = elements[i].price; row.insertCell(j++).innerHTML = elements[i].area.toFixed(2); row.insertCell(j++).innerHTML = elements[i].pricePerArea.toFixed(4); var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.appendChild(txt); span.onclick = function() { // remove from elements and update table var rowIndex = this.parentNode.parentNode.rowIndex; console.log(`now removing ${rowIndex}`); document.getElementById("myTable").deleteRow(rowIndex); elements.splice(rowIndex-1, 1); console.log('elements after removal:') console.log(elements); updateTable(); } row.insertCell(j++).appendChild(span); table.appendChild(row); } } // Create a new list item when clicking on the "Add" button function newElement() { var diameter = document.getElementById("diameterInput").value; var price = document.getElementById("priceInput").value; if (diameter === '' || price === '') { alert("Please fill in all fields"); return; } diameter = parseFloat(diameter); price = parseFloat(price); if (isNaN(diameter) || isNaN(price)) { alert("Please enter valid numbers"); return; } // clear input fields document.getElementById("diameterInput").value = ''; document.getElementById("priceInput").value = ''; const entry = new PizzaEntry(diameter, price); elements.push(entry); sortElements(); updateTable(); } updateTable();
use std::{fmt::Debug, ops::Mul}; use image::{Rgb, Rgba, RgbaImage}; use num_traits::{Float, NumCast, NumOps, One, Zero}; pub trait NumLike: PartialEq + NumOps + NumCast + Zero + One + Copy + Debug {} impl NumLike for f64 {} impl NumLike for f32 {} impl NumLike for i32 {} pub fn maxf<T: Float>(a: T, b: T) -> T { if a > b { a } else { b } } pub fn minf<T: Float>(a: T, b: T) -> T { if a < b { a } else { b } } pub fn splitext(filename: &str) -> (String, String) { let idx = filename.rfind('.'); match idx { Some(idx) => ( filename[..idx].to_string(), filename[idx..].to_string().to_lowercase(), ), None => (filename.to_string(), String::from("")), } } pub trait RgbaImageExt { fn flip_horizontal(&mut self); fn flip_vertical(&mut self); } impl RgbaImageExt for RgbaImage { fn flip_horizontal(&mut self) { let width = self.width(); let height = self.height(); let mut temp_row = vec![Rgba([0, 0, 0, 0]); width as usize]; for y in 0..height { for x in 0..width / 2 { let left = self.get_pixel(x, y); let right = self.get_pixel(width - x - 1, y); temp_row[x as usize] = *right; temp_row[(width - x - 1) as usize] = *left; } for x in 0..width { self.put_pixel(x, y, temp_row[x as usize]); } } } fn flip_vertical(&mut self) { let width = self.width(); let height = self.height(); let mut temp_col = vec![Rgba([0, 0, 0, 0]); height as usize]; for x in 0..width { for y in 0..height / 2 { let top = self.get_pixel(x, y); let bottom = self.get_pixel(x, height - y - 1); temp_col[y as usize] = *bottom; temp_col[(height - y - 1) as usize] = *top; } for y in 0..height { self.put_pixel(x, y, temp_col[y as usize]); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_splitext() { let filename = "example.png"; let (name, ext) = splitext(filename); assert_eq!(name, "example"); assert_eq!(ext, ".png"); let filename = "example.tar.gz"; let (name, ext) = splitext(filename); assert_eq!(name, "example.tar"); assert_eq!(ext, ".gz"); let filename = "example"; let (name, ext) = splitext(filename); assert_eq!(name, "example"); assert_eq!(ext, ""); let filename = ".hidden"; let (name, ext) = splitext(filename); assert_eq!(name, ""); assert_eq!(ext, ".hidden"); let filename = "example.PNG"; let (name, ext) = splitext(filename); assert_eq!(name, "example"); assert_eq!(ext, ".png"); } }
// // ImageView.swift // movies // // Created by Daniel Ferrer on 6/10/22. // import SwiftUI import Kingfisher struct ImageView: View { var urlImage: String? var placeholderImage: String = "placeholder" var body: some View { GeometryReader { geo in if let urlImage = urlImage, let image = URL(string: urlImage) { KFImage.url(image) .renderingMode(.original) .resizable() .placeholder { Image(placeholderImage) .resizable() .aspectRatio(contentMode: .fill) } .aspectRatio(contentMode: .fill) .frame(maxWidth: geo.size.width, maxHeight: geo.size.height) .clipped() } else { Image(placeholderImage) .resizable() .aspectRatio(contentMode: .fill) .frame(maxWidth: geo.size.width, maxHeight: geo.size.height) .clipped() } } } } struct ImageView_Previews: PreviewProvider { static var previews: some View { VStack { VStack { ImageView(urlImage: "https://image.tmdb.org/t/p/original/tVxDe01Zy3kZqaZRNiXFGDICdZk.jpg") }.frame(width: 100, height: 100) VStack { ImageView(urlImage: nil) }.frame(width: 100, height: 100) } } }
package ua.foxminded.warehouse.service.enums; /** * An enumeration representing the types of transactions that can occur in the * system. * Possible transaction types are: * PURCHASE: Represents a purchase transaction. * SALES: Represents a sales transaction. * RETURN: Represents a return transaction. * TRANSFER: Represents a transfer transaction. * * Each transaction type has a corresponding boolean variable to indicate whether * the transaction represents an income or an expense. * * This enumeration is used to categorize transactions and generate financial reports * based on income and expenses. * * @author Bohush Darya * @version 1.0 * */ public enum TransactionType { PURCHASE(true), SALES(false), RETURN(true), TRANSFER_FROM(true), TRANSFER_TO(false); private final boolean isIncome; TransactionType(boolean isIncome){ this.isIncome = isIncome; } public boolean isIncome() { return this.isIncome; } }
85.Maximal Rectangle Explanation: This code seems to implement a solution to the "Maximal Rectangle" problem, which involves finding the largest rectangular area containing only 1s in a binary matrix. Let's break down the code: - The `maximalRectangle` method takes a 2D list `matrix` representing the binary matrix as input and returns an integer representing the area of the largest rectangle. - It first checks if the matrix is empty. If it is, it returns 0. - It initializes variables `rows` and `cols` to store the number of rows and columns in the matrix, respectively. - It initializes `max_area` to store the maximum area found so far. - It iterates over each row in the matrix: - It initializes a `heights` array with zeros, where each element corresponds to the height of the rectangle ending at the current column in the current row. - It calculates the heights of rectangles for the current row based on consecutive '1's using a dynamic programming approach. - Within the loop over each row: - It uses a stack-based approach to calculate the maximum area. It iterates over each column index: - If the current height (`heights[i]`) is less than the height of the previous column (`heights[stack[-1]]`), it pops the index from the stack and calculates the area. - It updates `max_area` if the calculated area is greater than the current maximum. - Finally, it appends the current column index to the stack. - After the loop, it handles the case where the stack is not empty, calculating areas for the remaining indices. - It returns `max_area`, which holds the maximum area found. This algorithm efficiently finds the maximum area of a rectangle containing only 1s in the binary matrix. Solution: class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 rows, cols = len(matrix), len(matrix[0]) max_area = 0 for row in matrix: heights = [0] * cols # Initialize heights array with zeros for i in range(cols): heights[i] = heights[i] + 1 if row[i] == '1' else 0 # Calculate max area using stack stack = [] for i in range(cols): while stack and heights[stack[-1]] > heights[i]: height = heights[stack.pop()] width = i - stack[-1] if stack else i area = height * width max_area = max(max_area, area) stack.append(i) # Handle the case where the stack is not empty while stack: height = heights[stack.pop()] width = cols - stack[-1] if stack else cols area = height * width max_area = max(max_area, area) return max_area
function calcularDescontoPorLitro(preco, desconto, quantidade_litros) { let valor_litros_total = quantidade_litros * preco; let desconto_final = (valor_litros_total / 100) * desconto; return desconto_final; } // Função para calcular o valor total a ser pago function calcularValorTotal(litros, preco, tipoCombustivel) { let descontoTotal = 0; if (tipoCombustivel === "A") { descontoTotal += calcularDescontoPorLitro(preco, 5, litros); // 5% de desconto para álcool } else if (tipoCombustivel === "G") { descontoTotal += calcularDescontoPorLitro(preco, 6, litros); // 6% de desconto para gasolina } return (litros * preco) - descontoTotal; } function abastecer() { let litros = parseFloat(document.getElementById("litros").value); let preco = parseFloat(document.getElementById("preco").value); let tipoCombustivel; if (document.getElementById("alcool").checked) { tipoCombustivel = "A"; } else if (document.getElementById("gasolina").checked) { tipoCombustivel = "G"; } let valorTotal = calcularValorTotal(litros, preco, tipoCombustivel); document.getElementById("precoFinal").innerText = "Valor total a ser pago: R$ " + valorTotal.toFixed(2); } document.getElementById("btAbastecer").addEventListener("click", abastecer);
# 環境構築 ``` pyenv local 3.8 ``` ``` shell poetry install poetry run pre-commit install ``` # フォーマット ``` poetry run black . ``` # 開発ガイド 1. actions.py: 新たに定義するクエリの説明を記述します。 2. docs/api.md: actions.pyへの参照をドキュメントに反映します。 3. `_async`に非同期クエリを実装します(まずは仮の実装でよいでしょう)。あるいは、`_sync`に同期クエリを実装します(非同期クエリから自動生成できる互換性がない場合)。 4. `queryables.py`に非同期クエリへの参照(`_ait`)と同期クエリ(`_sit`)への参照を定義します。実装がない場合は、`no_implement`とします。 5. `make generate` を実行します。実行前に、これまでの作業内容をステージングし、どんな変更があるか確認してください。 6. `tests`にテストを追加します。 <!-- TODO: 1クエリを定義するのに手続きが多い。もっと簡略化したい。 TODO: actions.py が説明だけのモジュールなのでもっと一箇所に定義を集めたい TODO: docs/api.md への繁栄を自動にしたい --> ## 同期/非同期 同期クエリと非同期クエリをそれぞれ実装するコストが高いため、 非同期クエリを同期クエリへ変換するアプローチを取っています。 次のルールを参考にコードを実装します。 - `_async`: 非同期クエリを定義します。 - `_sync_generate`: 非同期クエリから自動生成される同期クエリ群。このモジュールは触らないでください。 - `_sync`: `_sync_generate`がインポートされる。自動生成できない、あるいは、最適化したいクエリをここでオーバーライドしてください。 - `generate_unasync.py`: 非同期から同期コードへの変換方法を定義する。このモジュールは触らないでください。 `generate_unasync.py` により、非同期コードは同期コードに変換されます。 `generate_unasync.py`には、次のようなルールが定義されます。 ``` fromdir=str(CODE_ROOT / "_async"), todir=str(CODE_ROOT / "_sync_generate"), ``` 次を実行するとコードが自動生成されます。 ```make unasync``` さらに詳しくは[unasync](https://github.com/python-trio/unasync)を参照してください。 ## ジェネリクステンプレート 本パッケージのジェネリクスは複雑です。 正しく型を伝えるため、あるいは、曖昧な型を吸収するためのテンプレートです。 主に、`Tuple[KEY, VALUE]`型の活用範囲を広げることを目的としています。 - `__queries__.py`: Queryクラスのテンプレートです。クエリを追加したらここへコードを追加します。 - `queries.py`: `__queries__.py`をテンプレートとして生成されるモジュールです。 次を実行するとコードが自動生成されます。 ```make generate```
#include "Json.h" #include "../../Logger.h" #include "Object.h" #include "Array.h" #include <algorithm> namespace r8ge { namespace utility { Json::Json() : m_type(Type::null) {} Json::Json(const object &o) : m_type(Type::object) { m_data.o = new object(o); } Json::Json(const std::initializer_list<std::pair<StringKey, Json>> &list) : m_type(Type::object) { m_data.o = new object(list); } Json::Json(const array &a) : m_type(Type::array) { m_data.a = new array(a); } Json::Json(const std::initializer_list<Json> &list) { m_type = Type::array; m_data.a = new array(list); } Json::~Json() { if (is_object()) delete m_data.o; if (is_array()) delete m_data.a; if (is_string()) delete m_data.s; } Json::Json(Json &&other) noexcept { m_data = other.m_data; m_type = other.m_type; other.m_data = {}; } Json &Json::operator=(Json &&other) noexcept { if (this == &other) return *this; m_data = other.m_data; m_type = other.m_type; other.m_data = {}; return *this; } Json::Json(const Json &other) { copy(other); } Json &Json::operator=(const Json &other) { copy(other); return *this; } void Json::copy(const Json &other) { if (this == &other) return; m_type = other.m_type; if (is_object()) m_data.o = new object(*other.m_data.o); else if (is_array()) m_data.a = new array(*other.m_data.a); else if (is_string()) m_data.s = new string(*other.m_data.s); else m_data = other.m_data; } std::string Json::to_string(bool format, size_t _tab_spaces, size_t _count_of_indent, bool _should_format) const { std::string str; if(_should_format) for (size_t c = 0; c < _count_of_indent * _tab_spaces; c++) str += format ? " " : ""; if (is_object()) str += m_data.o->to_string(format, _tab_spaces, _count_of_indent+1); if (is_array()) str += m_data.a->to_string(format, _tab_spaces, _count_of_indent+1); if (is_string()) str += "\"" + *m_data.s + "\""; if (is_boolean()) str += m_data.b ? "true" : "false"; if (is_integral())str += std::to_string(m_data.i); if (is_decimal()) str += std::to_string(m_data.d); if (is_null()) str += "null"; return str; } Type Json::type() const { return m_type; } bool Json::is_integral() const { return m_type == Type::integral; } bool Json::is_decimal() const { return m_type == Type::decimal; } bool Json::is_boolean() const { return m_type == Type::boolean; } bool Json::is_string() const { return m_type == Type::string; } bool Json::is_object() const { return m_type == Type::object; } bool Json::is_array() const { return m_type == Type::array; } bool Json::is_null() const { return m_type == Type::null; } Json &Json::operator[](const StringKey &key) { if (!is_object()) { if (is_null()) { m_type = Type::object; m_data.o = new object; } else { R8GE_LOG_ERROR("Cannot use operator[StringKey:key] on non-object value"); return *this; } } return (*m_data.o)[key]; } Json &Json::operator[](size_t index) { if (!is_array()) { if (is_null()) { m_type = Type::array; m_data.a = new array; } else { R8GE_LOG_ERROR("Cannot use operator[size_t:index] on non-array value"); return *this; } } return (*m_data.a)[index]; } Json &Json::operator+=(const Json &other) { if (is_array()) { m_data.a->add(other); } return *this; } Json &Json::operator+=(const std::pair<StringKey, Json> &p) { if (!is_object()) { if (is_null()) { m_type = Type::object; m_data.o = new object; } else { R8GE_LOG_ERROR("Cannot use operator[std::pair<StringKey, Value>] on non-object value"); return *this; } } else (*m_data.o)[p.first] = p.second; return *this; } //TODO: change error function integral Json::as_integral() const { if (is_integral()) return m_data.i; else R8GE_LOG_ERROR("Cannot convert value [{}] to integral", to_string(m_type)); return 0; } decimal Json::as_decimal() const { if (is_decimal()) return m_data.d; else R8GE_LOG_ERROR("Cannot convert value [{}] to decimal", to_string(m_type)); return 0.0; } boolean Json::as_boolean() const { if (is_boolean()) return m_data.b; else R8GE_LOG_ERROR("Cannot convert value [{}] to boolean", to_string(m_type)); return 0.0; } string Json::as_string(bool format) const { if (is_string()) return *m_data.s; else return to_string(format); } Json::Convertor Json::operator()() const { return {*this}; } std::string Json::to_string(Type t) const { switch (t) { case Type::integral: return "integral"; case Type::decimal: return "decimal"; case Type::boolean: return "boolean"; case Type::string: return "string"; case Type::object: return "object"; case Type::array: return "array"; case Type::null: return "null"; } return "unknown"; } size_t Json::from_string(std::string_view str, size_t _index) { // Remove all spaces, tabs, newlines std::string s{str}; s.erase(std::remove_if(s.begin(), s.end(), [](unsigned char x) { return std::isspace(x); }), s.end()); if (s.empty()) { m_type = Type::null; return _index; } if (s[_index] == '{') { m_type = Type::object; m_data.o = new object; return m_data.o->from_string(s, _index); } else if (s[_index] == '[') { m_type = Type::array; m_data.a = new array; return m_data.a->from_string(s, _index); } else if (s[_index] == '"') { m_type = Type::string; size_t last_index = s.find('"', _index + 1); auto str = s.substr(_index + 1, last_index - _index - 1); m_data.s = new string(str); return last_index + 1; } else if (s[_index] == 't' || s[_index] == 'f') { m_type = Type::boolean; m_data.b = s[_index] == 't'; return _index + (s[_index] == 't' ? 5 : 6); } else if (s == "null") { m_type = Type::null; return _index; } else { size_t last_index_c = s.find(',', _index); size_t last_index_b = s.find('}', _index); size_t last_index_s = s.find(']', _index); size_t last_index = std::min(last_index_c, std::min(last_index_b, last_index_s)); std::string num = s.substr(_index, last_index - _index); if (num.find('.') != std::string::npos) { m_type = Type::decimal; m_data.d = std::stod(num); } else { m_type = Type::integral; m_data.i = std::stoi(num); } return last_index; } } std::vector<Json> Json::as_vector() const { if (is_array()) return m_data.a->as_vector(); else R8GE_LOG_ERROR("Cannot convert value [{}] to vector", to_string(m_type)); return {}; } Json::Convertor::Convertor(const Json &value) : m_value(value) {} Json::Convertor::operator int() const { return static_cast<int>(m_value.as_integral()); } Json::Convertor::operator long() const { return static_cast<long>(m_value.as_integral()); } Json::Convertor::operator long long() const { return static_cast<long long>(m_value.as_integral()); } Json::Convertor::operator float() const { return static_cast<float>(m_value.as_decimal()); } Json::Convertor::operator double() const { return static_cast<double>(m_value.as_decimal()); } Json::Convertor::operator long double() const { return static_cast<long double>(m_value.as_decimal()); } Json::Convertor::operator bool() const { return m_value.as_boolean(); } Json::Convertor::operator std::string() const { return m_value.as_string(false); } } }
package ar.edu.itba.game.backend.logic; import java.io.Serializable; import java.util.Observable; import ar.edu.itba.game.frontend.observers.BaseObserver; public class Base extends Observable implements Attackable, Serializable { private static final long serialVersionUID = -4883608043561346759L; static int HEIGHT = 282; static int WIDTH = 180; private int maxHP; private int HP; private Element element; private Side side; private transient BaseObserver observer; public Base(Side side, BaseObserver baseObserver){ int X; this.side = side; if(side==Side.LEFT){ X = -10 + 76/2; }else{ X = Game.WIDTH * Game.SCALE - WIDTH + 10 + 76/2; } element = new Element(X, Game.GROUND_HEIGHT, WIDTH, HEIGHT); this.maxHP = GameStats.BASE_MAX_HP; this.HP = GameStats.BASE_MAX_HP; this.observer = baseObserver; } public int getHP() { return HP; } //TODO: ADD THROWS ENDGAMEEXCEPTION A LA INTERFAZ /** * Reduces the base hp and ends the game in case the base hp runs out */ @Override public void receiveDamage(int damage){ this.HP -=damage; this.observer.update(this); if(this.HP <= 0){ this.observer.setLooser(this.side); WorldManager.getInstance().endGame(); } } public int getMaxHP() { return maxHP; } @Override public Element getElement() { return this.element; } @Override public boolean doesFly() { return false; } public float getX() { if(this.side == Side.LEFT) return this.element.getX() -38; return this.element.getX() - 3 * 38; } public float getY() { return this.element.getY() - 2; } public int getHeight() { return this.element.getHeight(); } public int getWidth() { return this.element.getWidth(); } public Side getSide() { return this.side; } public void setObserver(BaseObserver baseObserver) { this.observer = baseObserver; this.observer.update(this); } }
#include <stdio.h> #include <strings.h> #include <stdlib.h> #include <string.h> #define MAX_LENGTH 256 #define MAX_PAGES 100 // variaveis de controle de escopo global int pagina_atual; typedef struct noLista { char termo[MAX_LENGTH]; struct noLista *prox; }noLista; typedef struct Lista { int qtd; noLista *primeiro; }Lista; typedef struct noArvore { char palavra[MAX_LENGTH]; int paginas[MAX_PAGES]; int quantidade_paginas; struct noArvore *esquerda; struct noArvore *direita; }noArvore; // funcao de controle para verificar se a pagina ja foi inserida na lista de paginas da palavra int verifica_paginas(noArvore **no) { int i; for(i=0; i < (*no)->quantidade_paginas; i++) { if((*no)->paginas[i] == pagina_atual) return 1; } return 0; } // codigos lista ordenada // inicializando lista ordenada void iniciar_lista(Lista *l) { l->qtd = 0; l->primeiro = NULL; } // fazendo verificacao se lista esta vazia atraves da variavel quantidade int lista_vazia(Lista *l) { return l->qtd == 0 ? 1 : 0; } // inserindo termos na lista ordenada int inserir_termo(Lista *l, char termo[]) { // comparacao entre strings em uppercase para garantir case insensitive if(strcasecmp(termo, l->primeiro->termo) == 0) { return 0; } // alocando memoria para novo termo noLista *novo_termo = (noLista *) malloc (sizeof(noLista)); strcpy(novo_termo->termo, termo); novo_termo->prox = NULL; // caso lista de termos esteja vazia, insere na primeira posicao if(lista_vazia(l)) { l->primeiro = novo_termo; } else if(strcasecmp(termo, l->primeiro->termo) < 0) { novo_termo->prox = l->primeiro; l->primeiro = novo_termo; } else // se nao, insere na posicao adequada, seguindo a ordem alfabetica { noLista *aux = l->primeiro; while(aux->prox != NULL && strcasecmp(termo, aux->prox->termo) > 0) { aux = aux->prox; } novo_termo->prox = aux->prox; aux->prox = novo_termo; } l->qtd++; return 1; } // codigos arvore binaria // iniciando arvore void iniciar_arvore(noArvore **no) { (*no) = NULL; } // inserindo valores dentro da arvore int inserir_arvore(noArvore **no, char palavra[]) { // se nao existe a palavra, sera inserido em um novo no e inicializado seu vetor de paginas com a pagina atual if((*no) == NULL) { *no = malloc (sizeof(noArvore)); strcpy((*no)->palavra, palavra); (*no)->quantidade_paginas = 1; (*no)->paginas[(*no)->quantidade_paginas - 1] = pagina_atual; (*no)->direita = NULL; (*no)->esquerda = NULL; return 1; } else if(strcasecmp(palavra, (*no)->palavra) == 0) { // se palavra ja existe, pagina atual sera inserido no vetor if(verifica_paginas(&(*no)) == 0) { (*no)->quantidade_paginas++; (*no)->paginas[(*no)->quantidade_paginas -1] = pagina_atual; return 1; } } // se palavra for "menor" do que palavra no no atual, vai para a esquerda, se nao, vai para a direita else if(strcasecmp(palavra, (*no)->palavra) < 0) { return inserir_arvore(&(*no)->esquerda, palavra); } else { return inserir_arvore(&(*no)->direita, palavra); } } // procura o no no qual a palavra pesquisada se encontra e retorna um ponteiro para o no pesquisado noArvore **pesquisar_palavra(noArvore **no, char palavra[]) { if((*no) == NULL) { return NULL; } else if(strcasecmp(palavra, (*no)->palavra) == 0) { strcpy((*no)->palavra, palavra); return no; } else if(strcasecmp(palavra, (*no)->palavra) < 0) { pesquisar_palavra(&(*no)->esquerda, palavra); } else { pesquisar_palavra(&(*no)->direita, palavra); } } // printando no no console e arquivo de saida valores recebidos do no correspondente ao termo pesquisado void printar_arvore(FILE *s, noArvore **no) { if(no == NULL) { return; } printf("%s %d", (*no)->palavra, (*no)->paginas[0]); fprintf(s, "%s %d", (*no)->palavra, (*no)->paginas[0]); int i; for(i=1; i<(*no)->quantidade_paginas; i++) { printf(", %d", (*no)->paginas[i]); fprintf(s, ", %d", (*no)->paginas[i]); } fprintf(s, "\n"); printf("\n"); } // parte da juncao das estruturas //para cada elemento na lista de termos, sera pesquisado na arvore e printado no console/arquivo de saida. void get_termos(Lista *l, char termos[]) { char palavra[MAX_LENGTH]; int i = 8, j = 0; while(termos[i] != '>') { if(termos[i] == ',') { palavra[j] = '\0'; j=0; i++; inserir_termo(l, palavra); continue; } palavra[j] = termos[i]; j++; i++; } palavra[j] = '\0'; inserir_termo(l, palavra); } int get_pagina(char *str) { int i, j = 0, tamanho = strlen(str); char *numero; // removendo caracteres da string e deixando apenas o numero numero = strtok(str, "<page:"); numero = strtok(numero, ">"); return atoi(numero); // retorno da conversao do numero restante da string em inteiro } // tratando string, tirando caracteres desnecessarios e dividindo palavras em multiplas strings conforme os separadores void trata_string(noArvore **no, char str[]) { int tamanho = strlen(str); if(str[tamanho - 1] == ',' || str[tamanho - 1] == '.' || str[tamanho - 1] == ';') { str[tamanho - 1] = '\0'; } str = strtok(str, "()."); while(str != NULL) { inserir_arvore(&(*no), str); str = strtok(NULL, "()."); } } // pegando os termos da lista de termos, pesquisando e printando void mostrar_termos(FILE *s, Lista *l, noArvore **no) { noLista *aux = l->primeiro; while(aux != NULL) { printar_arvore(s, pesquisar_palavra(&(*no), aux->termo)); aux = aux->prox; } } // lendo arquivo, localizando numero da pagina e termos void ler_arquivo(FILE *e, noArvore **no, Lista *l) { char palavra[MAX_LENGTH]; while(fscanf(e, "%s", palavra) != EOF) { if(strncmp(palavra, "<termos:", 8) == 0) // se linha contem termos, sera inserido na lista { get_termos(l, palavra); continue; } else if(strncmp(palavra, "<page:", 6) == 0) // se linha contem pagina, sera atualizado a variavel de controle global { pagina_atual = get_pagina(palavra); continue; } else { trata_string(&(*no), palavra); } } } // funcoes de tratamento de erro // verifica se o arquivo esta vazio a partir da posicao do ponteiro do arquivo int estaVazioArquivo(FILE *f) { fseek(f, 0, SEEK_END); int tamanhoArquivo = ftell(f); rewind(f); // reiniciando ponteiro do arquivo if(tamanhoArquivo == 0) return 1; else return 0; } // verifica se houve erro na criacao dos ponteiros para os arquvios correspondentes void verificaArquivos(FILE *e, FILE *s) { if(e == NULL && s != NULL) { printf("ERRO\n"); printf("Arquivo de entrada nao encontrado!\n"); exit(1); } else if(e != NULL && s == NULL) { printf("Erro na criacao do arquivo de saida!\n"); exit(1); } else if(e != NULL && s == NULL) { printf("Erro na criacao de ambos arquivos!\n"); exit(1); } } // faz tratamento de erro nos arquivos caso arquivo de entrada esteja vazio ou nao seja encontrado void trataArquivos(FILE *e, FILE *s) { verificaArquivos(e, s); if(estaVazioArquivo(e)) { // caso arquivo esteja vazio, o programa sera encerrado printf("ERRO: Arquivo de entrada vazio!\n"); exit(1); } else { return; } } // verifica quantidade de argumentos passados na chamada da execucao do programa. Se igual a 3, segue sua execucao normalmente void verificaArgumentos(int arg) { if(arg == 3) return; else if(arg < 3) { printf("Numero de argumentos insuficientes, insira tres argumentos seguindo a seguinte ordem:\n"); printf("./main 'arquivo_de_entrada.txt 'arquivo_de_saida.txt'\n"); exit(1); } else { printf("Numero de argumentos nao esta de acordo com o necessario, insira tres argumentos seguindo a seguinte ordem:\n"); printf("./main 'arquivo_de_entrada.txt 'arquivo_de_saida.txt'\n"); exit(1); } } int main(int argc, const char *argv[]) { FILE *entrada = fopen(argv[1], "r"); FILE *saida = fopen(argv[2], "w"); verificaArgumentos(argc); trataArquivos(entrada, saida); Lista *termos = malloc (sizeof(Lista)); noArvore *raiz; iniciar_lista(termos); iniciar_arvore(&raiz); ler_arquivo(entrada, &raiz, termos); mostrar_termos(saida, termos, &raiz); return 0; }
// // SignInModel.swift // CarPool // // Created by Himanshu on 5/10/23. // import Foundation import UIKit /// model struct containing /// properties for signup and /// login /// - email : string value for email address /// - password : string value for password /// - reEnterPassword : string value for re entered password (used in sign up onlly) struct SignInModel { // MARK: - properties var email: String var password: String var reEnterPassword: String // MARK: - initializers /// default initializer to assign values to properties init() { self.email = "" self.password = "" self.reEnterPassword = "" } // MARK: - methods /// method to get the textFieldValues with input value, placeholder value, /// input field identifier, and keyboard type /// - Parameter isNewUser: bool to check if the user is new or existing /// - Returns: return an array containg all the data of input fields func getInputFields(isNewUser: Bool) -> Constants.TypeAliases.InputFieldArrayType { // initialize the array with necessary // values of input fields var textFieldValues = [ ( email, Constants.Placeholders.email, InputFieldIdentifier.email, UIKeyboardType.emailAddress ), ( password, Constants.Placeholders.password, InputFieldIdentifier.password, UIKeyboardType.twitter ) ] // if user is new / creating account // then append the confirm password field if isNewUser { textFieldValues .append( ( reEnterPassword, Constants.Placeholders.reEnterPassword, InputFieldIdentifier.confirmPassword, UIKeyboardType.twitter ) ) } // return the array return textFieldValues } }
package sap.ui.unified.calendar; @:native("sap.ui.unified.calendar.Month") /** * renders a month with ItemNavigation This is used inside the calendar. Not for stand alone usage If used inside the calendar the properties and aggregation are directly taken from the parent (To not duplicate and sync DateRanges and so on...) */ extern class Month extends sap.ui.core.Control { @:overload(function(?sId:String, ?mSettings:MonthArgs):Void {}) public function new(?mSettings:MonthArgs):Void; @:overload( function(vAriaLabelledBy:sap.ui.core.ID):sap.ui.unified.calendar.Month{ }) /** * Adds some ariaLabelledBy into the association {@link #getAriaLabelledBy ariaLabelledBy}. * @param vAriaLabelledBy The ariaLabelledBy to add; if empty, nothing is inserted * @return Reference to <code>this</code> in order to allow method chaining */ public function addAriaLabelledBy( vAriaLabelledBy:sap.ui.core.Control):sap.ui.unified.calendar.Month; /** * Adds some disabledDate to the aggregation {@link #getDisabledDates disabledDates}. * @param oDisabledDate The disabledDate to add; if empty, nothing is inserted * @return Reference to <code>this</code> in order to allow method chaining */ public function addDisabledDate( oDisabledDate:sap.ui.unified.DateRange):sap.ui.unified.calendar.Month; /** * Adds some selectedDate to the aggregation {@link #getSelectedDates selectedDates}. * @param oSelectedDate The selectedDate to add; if empty, nothing is inserted * @return Reference to <code>this</code> in order to allow method chaining */ public function addSelectedDate( oSelectedDate:sap.ui.unified.DateRange):sap.ui.unified.calendar.Month; /** * Adds some specialDate to the aggregation {@link #getSpecialDates specialDates}. * @param oSpecialDate The specialDate to add; if empty, nothing is inserted * @return Reference to <code>this</code> in order to allow method chaining */ public function addSpecialDate( oSpecialDate:sap.ui.unified.DateTypeRange):sap.ui.unified.calendar.Month; /** * Attaches event handler <code>fnFunction</code> to the {@link #event:focus focus} event of this <code>sap.ui.unified.calendar.Month</code>. When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener</code> if specified, otherwise it will be bound to this <code>sap.ui.unified.calendar.Month</code> itself. Date focus changed * @param oData An application-specific payload object that will be passed to the event handler along with the event object when firing the event * @param fnFunction The function to be called when the event occurs * @param oListener Context object to call the event handler with. Defaults to this <code>sap.ui.unified.calendar.Month</code> itself * @return Reference to <code>this</code> in order to allow method chaining */ public function attachFocus( ?oData:Dynamic, fnFunction:(Dynamic)->Void, ?oListener:Dynamic):sap.ui.unified.calendar.Month; /** * Attaches event handler <code>fnFunction</code> to the {@link #event:select select} event of this <code>sap.ui.unified.calendar.Month</code>. When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener</code> if specified, otherwise it will be bound to this <code>sap.ui.unified.calendar.Month</code> itself. Date selection changed * @param oData An application-specific payload object that will be passed to the event handler along with the event object when firing the event * @param fnFunction The function to be called when the event occurs * @param oListener Context object to call the event handler with. Defaults to this <code>sap.ui.unified.calendar.Month</code> itself * @return Reference to <code>this</code> in order to allow method chaining */ public function attachSelect( ?oData:Dynamic, fnFunction:(Dynamic)->Void, ?oListener:Dynamic):sap.ui.unified.calendar.Month; /** * Attaches event handler <code>fnFunction</code> to the {@link #event:weekNumberSelect weekNumberSelect} event of this <code>sap.ui.unified.calendar.Month</code>. When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener</code> if specified, otherwise it will be bound to this <code>sap.ui.unified.calendar.Month</code> itself. Fired when a week number selection is changed. By default, choosing the week number will select the corresponding week. If the week has already been selected, choosing the week number will deselect it. The default behavior can be prevented using the <code>preventDefault</code> method. <b>Note:</b> Works for Gregorian calendars only and when <code>intervalSelection</code> is set to <code>true</code>. * @param oData An application-specific payload object that will be passed to the event handler along with the event object when firing the event * @param fnFunction The function to be called when the event occurs * @param oListener Context object to call the event handler with. Defaults to this <code>sap.ui.unified.calendar.Month</code> itself * @return Reference to <code>this</code> in order to allow method chaining */ public function attachWeekNumberSelect( ?oData:Dynamic, fnFunction:(Dynamic)->Void, ?oListener:Dynamic):sap.ui.unified.calendar.Month; /** * checks if a date is focusable in the current rendered output. So if not rendered or in other month it is not focusable. * @param oDate JavaScript date object for focused date. * @return flag if focusable */ public function checkDateFocusable( oDate:Dynamic):Bool; /** * Destroys all the disabledDates in the aggregation {@link #getDisabledDates disabledDates}. * @return Reference to <code>this</code> in order to allow method chaining */ public function destroyDisabledDates( ):sap.ui.unified.calendar.Month; /** * Destroys all the selectedDates in the aggregation {@link #getSelectedDates selectedDates}. * @return Reference to <code>this</code> in order to allow method chaining */ public function destroySelectedDates( ):sap.ui.unified.calendar.Month; /** * Destroys all the specialDates in the aggregation {@link #getSpecialDates specialDates}. * @return Reference to <code>this</code> in order to allow method chaining */ public function destroySpecialDates( ):sap.ui.unified.calendar.Month; /** * Detaches event handler <code>fnFunction</code> from the {@link #event:focus focus} event of this <code>sap.ui.unified.calendar.Month</code>. The passed function and listener object must match the ones used for event registration. * @param fnFunction The function to be called, when the event occurs * @param oListener Context object on which the given function had to be called * @return Reference to <code>this</code> in order to allow method chaining */ public function detachFocus( fnFunction:(Dynamic)->Void, ?oListener:Dynamic):sap.ui.unified.calendar.Month; /** * Detaches event handler <code>fnFunction</code> from the {@link #event:select select} event of this <code>sap.ui.unified.calendar.Month</code>. The passed function and listener object must match the ones used for event registration. * @param fnFunction The function to be called, when the event occurs * @param oListener Context object on which the given function had to be called * @return Reference to <code>this</code> in order to allow method chaining */ public function detachSelect( fnFunction:(Dynamic)->Void, ?oListener:Dynamic):sap.ui.unified.calendar.Month; /** * Detaches event handler <code>fnFunction</code> from the {@link #event:weekNumberSelect weekNumberSelect} event of this <code>sap.ui.unified.calendar.Month</code>. The passed function and listener object must match the ones used for event registration. * @param fnFunction The function to be called, when the event occurs * @param oListener Context object on which the given function had to be called * @return Reference to <code>this</code> in order to allow method chaining */ public function detachWeekNumberSelect( fnFunction:(Dynamic)->Void, ?oListener:Dynamic):sap.ui.unified.calendar.Month; /** * displays the month of a given date without setting the focus * @param oDate JavaScript date object for focused date. * @return <code>this</code> to allow method chaining */ public function displayDate( oDate:Dynamic):sap.ui.unified.calendar.Month; /** * Creates a new subclass of class sap.ui.unified.calendar.Month with name <code>sClassName</code> and enriches it with the information contained in <code>oClassInfo</code>. <code>oClassInfo</code> might contain the same kind of information as described in {@link sap.ui.core.Control.extend}. * @param sClassName Name of the class being created * @param oClassInfo Object literal with information about the class * @param FNMetaImpl Constructor function for the metadata object; if not given, it defaults to the metadata implementation used by this class * @return Created class / constructor function */ public static function extend( sClassName:String, ?oClassInfo:Dynamic, ?FNMetaImpl:(Dynamic)->Void):(Dynamic)->Void; /** * Returns array of IDs of the elements which are the current targets of the association {@link #getAriaLabelledBy ariaLabelledBy}. * @return null */ public function getAriaLabelledBy( ):Array<sap.ui.core.ID>; /** * Gets current value of property {@link #getDate date}. A date as JavaScript Date object. The month including this date is rendered and this date is focused initially (if no other focus is set). * @return Value of property <code>date</code> */ public function getDate( ):Dynamic; /** * Gets content of aggregation {@link #getDisabledDates disabledDates}. Date Ranges for disabled dates * @return null */ public function getDisabledDates( ):Array<sap.ui.unified.DateRange>; /** * Gets current value of property {@link #getFirstDayOfWeek firstDayOfWeek}. If set, the first day of the displayed week is this day. Valid values are 0 to 6. If not a valid value is set, the default of the used locale is used. Default value is <code>-1</code>. * @return Value of property <code>firstDayOfWeek</code> */ public function getFirstDayOfWeek( ):Int; /** * Gets current value of property {@link #getIntervalSelection intervalSelection}. If set, interval selection is allowed Default value is <code>false</code>. * @return Value of property <code>intervalSelection</code> */ public function getIntervalSelection( ):Bool; /** * ID of the element which is the current target of the association {@link #getLegend legend}, or <code>null</code>. * @return null */ public function getLegend( ):sap.ui.core.ID; /** * Returns a metadata object for class sap.ui.unified.calendar.Month. * @return Metadata object describing this class */ public static function getMetadata( ):sap.ui.core.ElementMetadata; /** * Gets current value of property {@link #getNonWorkingDays nonWorkingDays}. If set, the provided weekdays are displayed as non-working days. Valid values inside the array are 0 to 6. If not set, the weekend defined in the locale settings is displayed as non-working days. * @return Value of property <code>nonWorkingDays</code> */ public function getNonWorkingDays( ):Array<Int>; /** * Gets current value of property {@link #getPrimaryCalendarType primaryCalendarType}. If set, the calendar type is used for display. If not set, the calendar type of the global configuration is used. * @return Value of property <code>primaryCalendarType</code> */ public function getPrimaryCalendarType( ):sap.ui.core.CalendarType; /** * Gets current value of property {@link #getSecondaryCalendarType secondaryCalendarType}. If set, the days are also displayed in this calendar type If not set, the dates are only displayed in the primary calendar type * @return Value of property <code>secondaryCalendarType</code> */ public function getSecondaryCalendarType( ):sap.ui.core.CalendarType; /** * Gets content of aggregation {@link #getSelectedDates selectedDates}. Date Ranges for selected dates of the DatePicker * @return null */ public function getSelectedDates( ):Array<sap.ui.unified.DateRange>; /** * Gets current value of property {@link #getShowHeader showHeader}. If set, a header with the month name is shown Default value is <code>false</code>. * @return Value of property <code>showHeader</code> */ public function getShowHeader( ):Bool; /** * Gets current value of property {@link #getShowWeekNumbers showWeekNumbers}. Determines whether the week numbers in the months are displayed. <b>Note:</b> For Islamic calendars, the week numbers are not displayed regardless of what is set to this property. Default value is <code>true</code>. * @return Value of property <code>showWeekNumbers</code> */ public function getShowWeekNumbers( ):Bool; /** * Gets current value of property {@link #getSingleSelection singleSelection}. If set, only a single date or interval, if intervalSelection is enabled, can be selected Default value is <code>true</code>. * @return Value of property <code>singleSelection</code> */ public function getSingleSelection( ):Bool; /** * Gets content of aggregation {@link #getSpecialDates specialDates}. <code>DateRange</code> with type to visualize special days in the Calendar. <b>Note:</b> If one day is assigned to more than one DateTypeRange, only the first one will be used. The only exception is when one of the types is <code>NonWorking</code>, then you can have both <code>NonWorking</code> and the other type. For example, you can have <code>NonWorking</code> + <code>Type01</code> but you can't have <code>Type01</code> + <code>Type02</code>. * @return null */ public function getSpecialDates( ):Array<sap.ui.unified.DateTypeRange>; /** * Gets current value of property {@link #getWidth width}. Width of Month * @return Value of property <code>width</code> */ public function getWidth( ):sap.ui.core.CSSSize; /** * Checks for the provided <code>sap.ui.unified.DateRange</code> in the aggregation {@link #getDisabledDates disabledDates}. and returns its index if found or -1 otherwise. * @param oDisabledDate The disabledDate whose index is looked for * @return The index of the provided control in the aggregation if found, or -1 otherwise */ public function indexOfDisabledDate( oDisabledDate:sap.ui.unified.DateRange):Int; /** * Checks for the provided <code>sap.ui.unified.DateRange</code> in the aggregation {@link #getSelectedDates selectedDates}. and returns its index if found or -1 otherwise. * @param oSelectedDate The selectedDate whose index is looked for * @return The index of the provided control in the aggregation if found, or -1 otherwise */ public function indexOfSelectedDate( oSelectedDate:sap.ui.unified.DateRange):Int; /** * Checks for the provided <code>sap.ui.unified.DateTypeRange</code> in the aggregation {@link #getSpecialDates specialDates}. and returns its index if found or -1 otherwise. * @param oSpecialDate The specialDate whose index is looked for * @return The index of the provided control in the aggregation if found, or -1 otherwise */ public function indexOfSpecialDate( oSpecialDate:sap.ui.unified.DateTypeRange):Int; /** * Inserts a disabledDate into the aggregation {@link #getDisabledDates disabledDates}. * @param oDisabledDate The disabledDate to insert; if empty, nothing is inserted * @param iIndex The <code>0</code>-based index the disabledDate should be inserted at; for a negative value of <code>iIndex</code>, the disabledDate is inserted at position 0; for a value greater than the current size of the aggregation, the disabledDate is inserted at the last position * @return Reference to <code>this</code> in order to allow method chaining */ public function insertDisabledDate( oDisabledDate:sap.ui.unified.DateRange, iIndex:Int):sap.ui.unified.calendar.Month; /** * Inserts a selectedDate into the aggregation {@link #getSelectedDates selectedDates}. * @param oSelectedDate The selectedDate to insert; if empty, nothing is inserted * @param iIndex The <code>0</code>-based index the selectedDate should be inserted at; for a negative value of <code>iIndex</code>, the selectedDate is inserted at position 0; for a value greater than the current size of the aggregation, the selectedDate is inserted at the last position * @return Reference to <code>this</code> in order to allow method chaining */ public function insertSelectedDate( oSelectedDate:sap.ui.unified.DateRange, iIndex:Int):sap.ui.unified.calendar.Month; /** * Inserts a specialDate into the aggregation {@link #getSpecialDates specialDates}. * @param oSpecialDate The specialDate to insert; if empty, nothing is inserted * @param iIndex The <code>0</code>-based index the specialDate should be inserted at; for a negative value of <code>iIndex</code>, the specialDate is inserted at position 0; for a value greater than the current size of the aggregation, the specialDate is inserted at the last position * @return Reference to <code>this</code> in order to allow method chaining */ public function insertSpecialDate( oSpecialDate:sap.ui.unified.DateTypeRange, iIndex:Int):sap.ui.unified.calendar.Month; /** * Removes all the controls in the association named {@link #getAriaLabelledBy ariaLabelledBy}. * @return An array of the removed elements (might be empty) */ public function removeAllAriaLabelledBy( ):Array<sap.ui.core.ID>; /** * Removes all the controls from the aggregation {@link #getDisabledDates disabledDates}. Additionally, it unregisters them from the hosting UIArea. * @return An array of the removed elements (might be empty) */ public function removeAllDisabledDates( ):Array<sap.ui.unified.DateRange>; /** * Removes all the controls from the aggregation {@link #getSelectedDates selectedDates}. Additionally, it unregisters them from the hosting UIArea. * @return An array of the removed elements (might be empty) */ public function removeAllSelectedDates( ):Array<sap.ui.unified.DateRange>; /** * Removes all the controls from the aggregation {@link #getSpecialDates specialDates}. Additionally, it unregisters them from the hosting UIArea. * @return An array of the removed elements (might be empty) */ public function removeAllSpecialDates( ):Array<sap.ui.unified.DateTypeRange>; @:overload( function(vAriaLabelledBy:Int):sap.ui.core.ID{ }) @:overload( function(vAriaLabelledBy:sap.ui.core.ID):sap.ui.core.ID{ }) /** * Removes an ariaLabelledBy from the association named {@link #getAriaLabelledBy ariaLabelledBy}. * @param vAriaLabelledBy The ariaLabelledBy to be removed or its index or ID * @return The removed ariaLabelledBy or <code>null</code> */ public function removeAriaLabelledBy( vAriaLabelledBy:sap.ui.core.Control):sap.ui.core.ID; @:overload( function(vDisabledDate:Int):sap.ui.unified.DateRange{ }) @:overload( function(vDisabledDate:String):sap.ui.unified.DateRange{ }) /** * Removes a disabledDate from the aggregation {@link #getDisabledDates disabledDates}. * @param vDisabledDate The disabledDate to remove or its index or id * @return The removed disabledDate or <code>null</code> */ public function removeDisabledDate( vDisabledDate:sap.ui.unified.DateRange):sap.ui.unified.DateRange; @:overload( function(vSelectedDate:Int):sap.ui.unified.DateRange{ }) @:overload( function(vSelectedDate:String):sap.ui.unified.DateRange{ }) /** * Removes a selectedDate from the aggregation {@link #getSelectedDates selectedDates}. * @param vSelectedDate The selectedDate to remove or its index or id * @return The removed selectedDate or <code>null</code> */ public function removeSelectedDate( vSelectedDate:sap.ui.unified.DateRange):sap.ui.unified.DateRange; @:overload( function(vSpecialDate:Int):sap.ui.unified.DateTypeRange{ }) @:overload( function(vSpecialDate:String):sap.ui.unified.DateTypeRange{ }) /** * Removes a specialDate from the aggregation {@link #getSpecialDates specialDates}. * @param vSpecialDate The specialDate to remove or its index or id * @return The removed specialDate or <code>null</code> */ public function removeSpecialDate( vSpecialDate:sap.ui.unified.DateTypeRange):sap.ui.unified.DateTypeRange; /** * Sets a new value for property {@link #getDate date}. A date as JavaScript Date object. The month including this date is rendered and this date is focused initially (if no other focus is set). When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. * @param oDate New value for property <code>date</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setDate( oDate:Dynamic):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getFirstDayOfWeek firstDayOfWeek}. If set, the first day of the displayed week is this day. Valid values are 0 to 6. If not a valid value is set, the default of the used locale is used. When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. Default value is <code>-1</code>. * @param iFirstDayOfWeek New value for property <code>firstDayOfWeek</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setFirstDayOfWeek( ?iFirstDayOfWeek:Int):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getIntervalSelection intervalSelection}. If set, interval selection is allowed When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. Default value is <code>false</code>. * @param bIntervalSelection New value for property <code>intervalSelection</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setIntervalSelection( ?bIntervalSelection:Bool):sap.ui.unified.calendar.Month; @:overload( function(oLegend:sap.ui.core.ID):sap.ui.unified.calendar.Month{ }) /** * Sets the associated {@link #getLegend legend}. * @param oLegend ID of an element which becomes the new target of this legend association; alternatively, an element instance may be given * @return Reference to <code>this</code> in order to allow method chaining */ public function setLegend( oLegend:sap.ui.unified.CalendarLegend):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getNonWorkingDays nonWorkingDays}. If set, the provided weekdays are displayed as non-working days. Valid values inside the array are 0 to 6. If not set, the weekend defined in the locale settings is displayed as non-working days. When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. * @param sNonWorkingDays New value for property <code>nonWorkingDays</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setNonWorkingDays( ?sNonWorkingDays:Array<Int>):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getPrimaryCalendarType primaryCalendarType}. If set, the calendar type is used for display. If not set, the calendar type of the global configuration is used. When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. * @param sPrimaryCalendarType New value for property <code>primaryCalendarType</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setPrimaryCalendarType( sPrimaryCalendarType:sap.ui.core.CalendarType):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getSecondaryCalendarType secondaryCalendarType}. If set, the days are also displayed in this calendar type If not set, the dates are only displayed in the primary calendar type When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. * @param sSecondaryCalendarType New value for property <code>secondaryCalendarType</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setSecondaryCalendarType( sSecondaryCalendarType:sap.ui.core.CalendarType):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getShowHeader showHeader}. If set, a header with the month name is shown When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. Default value is <code>false</code>. * @param bShowHeader New value for property <code>showHeader</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setShowHeader( ?bShowHeader:Bool):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getShowWeekNumbers showWeekNumbers}. Determines whether the week numbers in the months are displayed. <b>Note:</b> For Islamic calendars, the week numbers are not displayed regardless of what is set to this property. When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. Default value is <code>true</code>. * @param bShowWeekNumbers New value for property <code>showWeekNumbers</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setShowWeekNumbers( ?bShowWeekNumbers:Bool):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getSingleSelection singleSelection}. If set, only a single date or interval, if intervalSelection is enabled, can be selected When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. Default value is <code>true</code>. * @param bSingleSelection New value for property <code>singleSelection</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setSingleSelection( ?bSingleSelection:Bool):sap.ui.unified.calendar.Month; /** * Sets a new value for property {@link #getWidth width}. Width of Month When called with a value of <code>null</code> or <code>undefined</code>, the default value of the property will be restored. * @param sWidth New value for property <code>width</code> * @return Reference to <code>this</code> in order to allow method chaining */ public function setWidth( ?sWidth:sap.ui.core.CSSSize):sap.ui.unified.calendar.Month; } typedef MonthArgs = sap.ui.core.Control.ControlArgs & { /** * A date as JavaScript Date object. The month including this date is rendered and this date is focused initially (if no other focus is set). */ @:optional var date:haxe.extern.EitherType<String,Dynamic>; /** * If set, interval selection is allowed */ @:optional var intervalSelection:haxe.extern.EitherType<String,Bool>; /** * If set, only a single date or interval, if intervalSelection is enabled, can be selected */ @:optional var singleSelection:haxe.extern.EitherType<String,Bool>; /** * If set, a header with the month name is shown */ @:optional var showHeader:haxe.extern.EitherType<String,Bool>; /** * If set, the first day of the displayed week is this day. Valid values are 0 to 6. If not a valid value is set, the default of the used locale is used. */ @:optional var firstDayOfWeek:haxe.extern.EitherType<String,Int>; /** * If set, the provided weekdays are displayed as non-working days. Valid values inside the array are 0 to 6. If not set, the weekend defined in the locale settings is displayed as non-working days. */ @:optional var nonWorkingDays:Array<haxe.extern.EitherType<String,Int>>; /** * If set, the calendar type is used for display. If not set, the calendar type of the global configuration is used. */ @:optional var primaryCalendarType:haxe.extern.EitherType<String,sap.ui.core.CalendarType>; /** * If set, the days are also displayed in this calendar type If not set, the dates are only displayed in the primary calendar type */ @:optional var secondaryCalendarType:haxe.extern.EitherType<String,sap.ui.core.CalendarType>; /** * Width of Month */ @:optional var width:haxe.extern.EitherType<String,sap.ui.core.CSSSize>; /** * Determines whether the week numbers in the months are displayed. <b>Note:</b> For Islamic calendars, the week numbers are not displayed regardless of what is set to this property. */ @:optional var showWeekNumbers:haxe.extern.EitherType<String,Bool>; /** * Date Ranges for selected dates of the DatePicker */ @:optional var selectedDates:Array<haxe.extern.EitherType<String,sap.ui.unified.DateRange>>; /** * <code>DateRange</code> with type to visualize special days in the Calendar. <b>Note:</b> If one day is assigned to more than one DateTypeRange, only the first one will be used. The only exception is when one of the types is <code>NonWorking</code>, then you can have both <code>NonWorking</code> and the other type. For example, you can have <code>NonWorking</code> + <code>Type01</code> but you can't have <code>Type01</code> + <code>Type02</code>. */ @:optional var specialDates:Array<haxe.extern.EitherType<String,sap.ui.unified.DateTypeRange>>; /** * Date Ranges for disabled dates */ @:optional var disabledDates:Array<haxe.extern.EitherType<String,sap.ui.unified.DateRange>>; /** * Association to controls / ids which label this control (see WAI-ARIA attribute aria-labelledby). */ @:optional var ariaLabelledBy:Array<haxe.extern.EitherType<String,sap.ui.core.Control>>; /** * Association to the <code>CalendarLegend</code> explaining the colors of the <code>specialDates</code>. <b>Note</b> The legend does not have to be rendered but must exist, and all required types must be assigned. */ @:optional var legend:haxe.extern.EitherType<String,sap.ui.unified.CalendarLegend>; /** * Date focus changed */ @:optional var focus:(oControlEvent:haxe.extern.EitherType<String,sap.ui.base.Event>)->Void; /** * Date selection changed */ @:optional var select:(oControlEvent:haxe.extern.EitherType<String,sap.ui.base.Event>)->Void; /** * Fired when a week number selection is changed. By default, choosing the week number will select the corresponding week. If the week has already been selected, choosing the week number will deselect it. The default behavior can be prevented using the <code>preventDefault</code> method. <b>Note:</b> Works for Gregorian calendars only and when <code>intervalSelection</code> is set to <code>true</code>. */ @:optional var weekNumberSelect:(oControlEvent:haxe.extern.EitherType<String,sap.ui.base.Event>)->Void; }
import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { ShopItem } from "./ShopItem"; import { ShoppingBasketContextProvider } from "context/ShoppingBasketContext"; describe("ShopItem", () => { it("should display item name", () => { renderScreen(); expect(screen.getByText("Doritos")).toBeInTheDocument(); }); it('should increment when "Add" is clicked', () => { renderScreen(); clickAdd(); expect(screen.getByText("1")).toBeInTheDocument(); }); it('should decrement when "Remove" is clicked', () => { renderScreen(); clickAdd(); clickAdd(); clickRemove(); expect(screen.getByText("1")).toBeInTheDocument(); }); }); const clickAdd = () => { userEvent.click(screen.getByText("+")); }; const clickRemove = () => { userEvent.click(screen.getByText("-")); }; const renderScreen = ({ itemName = "Doritos" } = {}) => { render( <ShoppingBasketContextProvider> <ShopItem item={{ name: itemName, price: "3.00", id: "5" }} /> </ShoppingBasketContextProvider> ); };
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of the ERIS tool (https://github.com/telina/eris). * Copyright (c) 2023 Rhea Rinaldo (Rhea@Odlanir.de). * * Authors: * - 2021-2021 Mohammed Hussam Al Turjman (Mohammed_Hussam.Al_Turjman@dfki.de) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef ERIS_WIDGETS_EDITOR_WIDGET_H #define ERIS_WIDGETS_EDITOR_WIDGET_H #include <QObject> #include <QPlainTextEdit> #include "syntax_highlighting.h" QT_BEGIN_NAMESPACE class QPaintEvent; class QResizeEvent; class QSize; class QWidget; QT_END_NAMESPACE namespace widgets { class HighlighterWidget; class LineNumberArea; // // Evaluation settings editor (properties editor). // From this widget a user can edit the later used by prism "experiment.pctl" file. // class EditorWidget : public QPlainTextEdit { Q_OBJECT public: explicit EditorWidget(QWidget* parent = nullptr); // These functions are to view line numbers alongside // the content of the editor. void lineNumberAreaPaintEvent(QPaintEvent* event); int lineNumberAreaWidth(); // This function is to mark a predefined property. // To add or remove properties you should go to the // highlighterWidget. // Notice that specifying random properties has no effect. void markAsUnchecked(const QString&, bool mark = true); public slots: // Can be used to clean the editor widget. void clean(); protected: void resizeEvent(QResizeEvent* event) override; private slots: void updateLineNumberAreaWidth(int newBlockCount); void highlightCurrentLine(); void updateLineNumberArea(const QRect&, int); private: QWidget* lineNumberArea; int currentLine = 0; HighlighterWidget* highlighterWidget; }; // Very basic numbering area for the editor class LineNumberArea : public QWidget { Q_OBJECT public: explicit LineNumberArea(EditorWidget* editor) : QWidget(editor) { codeEditor = editor; } QSize sizeHint() const override { return QSize(codeEditor->lineNumberAreaWidth(), 0); } protected: void paintEvent(QPaintEvent* event) override { codeEditor->lineNumberAreaPaintEvent(event); } private: EditorWidget* codeEditor; }; } // namespace widgets #endif // ERIS_WIDGETS_EDITOR_WIDGET_H
/** * Copyright 2013 SyncWise International SARL * All rights reserved. * * The text, images, audio and video files herein are the copyrighted works of SyncWise International SARL. * Reproduction in whole or in part, whether on paper, on the Internet, on CD-ROM, or any other medium, * including utilization in machines capable of reproduction or without the express permission of SyncWise * International SARL is prohibited. * */ package me.SyncWise.Android; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Date; import android.content.Context; /** * Helper Class used to provide date and time utilities. * * @author Elias * */ public class DateTime { /** * Constant integer holding the starting working hour. */ public static final int WORKING_HOUR_START = 8; /** * Constant integer holding the ending working hour. */ public static final int WORKING_HOUR_END = 18; /** * Returns the string representation of the day, retrieved from the provided calendar. * * @param context The application context. * @param calendar The calendar object holding the required day. * @return String holding the day label. * @see #getDayAbbreviation(Context, Calendar) * @see #getMonth(Context, Calendar) */ public static String getDay ( final Context context , final Calendar calendar ) { // Determine if the content and/or the calendar objects are valid if ( context == null || calendar == null ) // Invalid arguments return null; // Compute and return the corresponding day label switch ( calendar.get ( Calendar.DAY_OF_WEEK ) ) { case Calendar.MONDAY: return AppResources.getInstance ( context ).getString ( context , R.string.monday_label ); case Calendar.TUESDAY: return AppResources.getInstance ( context ).getString ( context , R.string.tuesday_label ); case Calendar.WEDNESDAY: return AppResources.getInstance ( context ).getString ( context , R.string.wednesday_label ); case Calendar.THURSDAY: return AppResources.getInstance ( context ).getString ( context , R.string.thursday_label ); case Calendar.FRIDAY: return AppResources.getInstance ( context ).getString ( context , R.string.friday_label ); case Calendar.SATURDAY: return AppResources.getInstance ( context ).getString ( context , R.string.saturday_label ); case Calendar.SUNDAY: return AppResources.getInstance ( context ).getString ( context , R.string.sunday_label ); } // End switch // Never reached return null; } /** * Returns the abbreviation string representation of the day, retrieved from the provided calendar. * * @param context The application context. * @param calendar The calendar object holding the required day. * @return String holding the abbreviation day label. * @see #getDay(Context, Calendar) * @see #getMonth(Context, Calendar) */ public static String getDayAbbreviation ( final Context context , final Calendar calendar ) { // Determine if the content and/or the calendar objects are valid if ( context == null || calendar == null ) // Invalid arguments return null; // Compute and return the corresponding abbreviation day label switch ( calendar.get ( Calendar.DAY_OF_WEEK ) ) { case Calendar.MONDAY: return AppResources.getInstance ( context ).getString ( context , R.string.monday_abbreviation ); case Calendar.TUESDAY: return AppResources.getInstance ( context ).getString ( context , R.string.tuesday_abbreviation ); case Calendar.WEDNESDAY: return AppResources.getInstance ( context ).getString ( context , R.string.wednesday_abbreviation ); case Calendar.THURSDAY: return AppResources.getInstance ( context ).getString ( context , R.string.thursday_abbreviation ); case Calendar.FRIDAY: return AppResources.getInstance ( context ).getString ( context , R.string.friday_abbreviation ); case Calendar.SATURDAY: return AppResources.getInstance ( context ).getString ( context , R.string.saturday_abbreviation ); case Calendar.SUNDAY: return AppResources.getInstance ( context ).getString ( context , R.string.sunday_abbreviation ); } // End switch // Never reached return null; } /** * Returns the string representation of the month, retrieved from the provided calendar. * * @param context The application context. * @param calendar The calendar object holding the required month. * @return String holding the month label. * @see #getDay(Context, Calendar) */ public static String getMonth ( final Context context , final Calendar calendar ) { // Determine if the content and/or the calendar objects are valid if ( context == null || calendar == null ) // Invalid arguments return null; // Compute and return the corresponding month label switch ( calendar.get ( Calendar.MONTH ) ) { case Calendar.JANUARY: return AppResources.getInstance ( context ).getString ( context , R.string.january_label ); case Calendar.FEBRUARY: return AppResources.getInstance ( context ).getString ( context , R.string.february_label ); case Calendar.MARCH: return AppResources.getInstance ( context ).getString ( context , R.string.march_label ); case Calendar.APRIL: return AppResources.getInstance ( context ).getString ( context , R.string.april_label ); case Calendar.MAY: return AppResources.getInstance ( context ).getString ( context , R.string.may_label ); case Calendar.JUNE: return AppResources.getInstance ( context ).getString ( context , R.string.june_label ); case Calendar.JULY: return AppResources.getInstance ( context ).getString ( context , R.string.july_label ); case Calendar.AUGUST: return AppResources.getInstance ( context ).getString ( context , R.string.august_label ); case Calendar.SEPTEMBER: return AppResources.getInstance ( context ).getString ( context , R.string.september_label ); case Calendar.OCTOBER: return AppResources.getInstance ( context ).getString ( context , R.string.october_label ); case Calendar.NOVEMBER: return AppResources.getInstance ( context ).getString ( context , R.string.november_label ); case Calendar.DECEMBER: return AppResources.getInstance ( context ).getString ( context , R.string.december_label ); } // End switch // Never reached return null; } /** * Returns the string representation of the full date, retrieved from the provided calendar.<br> * The format used is as follows : <br> * <b>DAY, MONTH DD YYYY</b> * * @param context The application context. * @param calendar The calendar object holding the required date. * @return String holding the full date label. * @see #getBriefDate(Context, Calendar) * @see #getBriefDate(Context, Date) * @see #getFullTime(Context, Calendar, boolean, boolean) * @see #getFullTime(Context, Calendar) * @see #getFullDateTime(Context, Calendar, boolean, boolean) * @see #getFullDateTime(Context, Calendar) */ public static String getFullDate ( final Context context , final Calendar calendar ) { // Declare and initialize a two digits string formatter DecimalFormat twoDigits = new DecimalFormat ( "00" ); // Compute the full date StringBuilder date = new StringBuilder (); date.append ( getDay ( context , calendar ) ); date.append ( ", " ); date.append ( getMonth ( context , calendar ) ); date.append ( " " ); date.append ( twoDigits.format ( calendar.get ( Calendar.DAY_OF_MONTH ) ) ); date.append ( ", " ); date.append ( String.valueOf ( calendar.get ( Calendar.YEAR ) ) ); // Return the full date return date.toString (); } /** * Returns the string representation of the brief date, retrieved from the provided calendar.<br> * The format used is as follows : <br> * <b>DD-MM-YYYY</b> * * @param context The application context. * @param calendar The calendar object holding the required date. * @return String holding the brief date label. * @see #getBriefDate(Context, Calendar) * @see #getFullTime(Context, Calendar, boolean, boolean) * @see #getFullTime(Context, Calendar) * @see #getFullDateTime(Context, Calendar, boolean, boolean) * @see #getFullDateTime(Context, Calendar) */ public static String getBriefDate ( final Context context , final Date date ) { // Declare and initialize a calendar object Calendar calendar = Calendar.getInstance (); // Set the time calendar.setTime ( date ); // Compute and return the brief date return getBriefDate ( context , calendar ); } /** * Returns the string representation of the brief date, retrieved from the provided calendar.<br> * The format used is as follows : <br> * <b>DD-MM-YYYY</b> * * @param context The application context. * @param calendar The calendar object holding the required date. * @return String holding the brief date label. * @see #getBriefDate(Context, Date) * @see #getFullTime(Context, Calendar, boolean, boolean) * @see #getFullTime(Context, Calendar) * @see #getFullDateTime(Context, Calendar, boolean, boolean) * @see #getFullDateTime(Context, Calendar) */ public static String getBriefDate ( final Context context , final Calendar calendar ) { // Declare and initialize a two digits string formatter DecimalFormat twoDigits = new DecimalFormat ( "00" ); // Compute the brief date StringBuilder date = new StringBuilder (); date.append ( twoDigits.format ( calendar.get ( Calendar.DAY_OF_MONTH ) ) ); date.append ( "-" ); date.append ( twoDigits.format ( calendar.get ( Calendar.MONTH ) + 1 ) ); date.append ( "-" ); date.append ( String.valueOf ( calendar.get ( Calendar.YEAR ) ) ); // Return the brief date return date.toString (); } /** * Returns the string representation of the full time, retrieved from the provided calendar.<br> * The format used is as follows : <br> * <b>HH:MM:SS.SSS</b><br> * The seconds (<b>SS</b>) and / or milliseconds (<b>SSS</b>) values may be omitted. * * @param context The application context. * @param calendar The calendar object holding the required date. * @param seconds Boolean indicating whether to add the seconds value or not. * @param milliseconds Boolean indicating whether to add the milliseconds value or not. * @return String holding the full time label. * @see #getBriefDate(Context, Calendar) * @see #getBriefDate(Context, Date) * @see #getFullDate(Context, Calendar) * @see #getFullTime(Context, Calendar) * @see #getFullDateTime(Context, Calendar, boolean, boolean) * @see #getFullDateTime(Context, Calendar) */ public static String getFullTime ( final Context context , final Calendar calendar , boolean seconds , boolean milliseconds ) { // Declare and initialize a two digits string formatter DecimalFormat twoDigits = new DecimalFormat ( "00" ); // Compute the full time StringBuilder time = new StringBuilder (); time.append ( twoDigits.format ( calendar.get ( Calendar.HOUR_OF_DAY ) ) ); time.append ( ":" ); time.append ( twoDigits.format ( calendar.get ( Calendar.MINUTE ) ) ); if ( seconds ) { time.append ( ":" ); time.append ( twoDigits.format ( calendar.get ( Calendar.SECOND ) ) ); } // End if if ( milliseconds ) { time.append ( "." ); time.append ( twoDigits.format ( calendar.get ( Calendar.MILLISECOND ) ) ); } // End if // Return the full time return time.toString (); } /** * Same as {@link #getFullTime(Context, Calendar, boolean, boolean)} with no seconds nor milliseconds values (flags are {@code false}). * * @param context The application context. * @param calendar The calendar object holding the required date. * @return String holding the full time label. * @see #getBriefDate(Context, Calendar) * @see #getBriefDate(Context, Date) * @see #getFullDate(Context, Calendar) * @see #getFullTime(Context, Calendar, boolean, boolean) * @see #getFullDateTime(Context, Calendar, boolean, boolean) * @see #getFullDateTime(Context, Calendar) */ public static String getFullTime ( final Context context , final Calendar calendar ) { // Compute and return the full time without the seconds and milliseconds values return getFullTime ( context , calendar , false , false ); } /** * Returns the string representation of the full date and time, retrieved from the provided calendar.<br> * Same as {@link #getFullDate(Context, Calendar)} and {@link #getFullTime(Context, Calendar, boolean, boolean)} combined. * * @param context The application context. * @param calendar The calendar object holding the required date. * @param seconds Boolean indicating whether to add the seconds value or not. * @param milliseconds Boolean indicating whether to add the milliseconds value or not. * @return String holding the full date time label. * @see #getBriefDate(Context, Calendar) * @see #getBriefDate(Context, Date) * @see #getFullDate(Context, Calendar) * @see #getFullTime(Context, Calendar, boolean, boolean) * @see #getFullTime(Context, Calendar) * @see #getFullDateTime(Context, Calendar) */ public static String getFullDateTime ( final Context context , final Calendar calendar , boolean seconds , boolean milliseconds ) { // Compute the full date and time StringBuilder dateTime = new StringBuilder (); dateTime.append ( getFullDate ( context , calendar ) ); dateTime.append ( " " ); dateTime.append ( AppResources.getInstance ( context ).getString ( context , R.string.at_label ) ); dateTime.append ( " " ); dateTime.append ( getFullTime ( context , calendar , seconds , milliseconds ) ); // Return the full date and time return dateTime.toString (); } /** * Same as {@link #getFullDateTime(Context, Calendar, boolean, boolean)} with no seconds nor milliseconds values (flags are {@code false}). * * @param context The application context. * @param calendar The calendar object holding the required date. * @return String holding the full date time label. * @see #getBriefDate(Context, Calendar) * @see #getBriefDate(Context, Date) * @see #getFullDate(Context, Calendar) * @see #getFullTime(Context, Calendar, boolean, boolean) * @see #getFullTime(Context, Calendar) * @see #getFullDateTime(Context, Calendar, boolean, boolean) */ public static String getFullDateTime ( final Context context , final Calendar calendar ) { // Compute and return the full date and time without the seconds and milliseconds values return getFullDateTime ( context , calendar , false , false ); } }
package com.group12.carrierpigeon.threading; /** * A Future class regulates return value calls from asynchronous sources. It will block calling threads if a return value is not ready. * @param <T> */ public class Future<T> extends Publisher<T> { private T returnObject = null; private String whoIs; /** * Gets the returned object from a Worker class. If the return is not valid yet, this method will block until such return is valid. Method is thread-safe. * If the caller does not want to risk being blocked, subscribe to the class via a call to {@link Publisher#subscribe(Subscriber)}. {@link Subscriber} class will be notified via execution * on the main (UI) thread * @return the given Object from a Worker class * @throws InterruptedException if the thread becomes blocked and is interrupted */ public synchronized T getReturnObject() throws InterruptedException { while(this.returnObject == null) { this.wait(); } return this.returnObject; } /** * Sets the return object. Typically performed by the {@link Worker} object which issued this Future object. * Once the object is set, all blocked threads on {@link Future#getReturnObject()} will become unblocked. This will also invoke {@link Subscriber#update(Object)} to any * subscribers of the {@link Future} object within the main (UI) thread * @param returnObject the given object to allow other threads to obtain. */ public synchronized void setReturnObject(T returnObject) { this.returnObject = returnObject; this.notifyAll(); this.notifySubscribers(returnObject,this.whoIs); } public void setWhoIs(String whoIs) { this.whoIs = whoIs; } }
// // SelectUselessFactView.swift // UselessFactsProject // // Created by Emilly Maia on 19/10/22. // // import Foundation import UIKit class SelectUselessFactView: UIView { weak var delegate: GeratorUselessFactDelegate? lazy var favoriteButton: UIButton = { let favoriteButton = UIButton(type: .system) favoriteButton.translatesAutoresizingMaskIntoConstraints = false favoriteButton.setTitle(" favoritos", for: .normal) favoriteButton.setImage(UIImage(systemName: "heart.circle.fill"), for: .normal) favoriteButton.layer.cornerRadius = 8 favoriteButton.tintColor = .gray favoriteButton.backgroundColor = .systemBackground favoriteButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) favoriteButton.clipsToBounds = true return favoriteButton }() lazy var subTitleLabel: UILabel = { let descriptionlabel = UILabel() descriptionlabel.translatesAutoresizingMaskIntoConstraints = false descriptionlabel.text = "Hey you! Discover useless facts to impress your friends and family with our app!" descriptionlabel.textAlignment = .left descriptionlabel.font = UIFont.systemFont(ofSize: 24) descriptionlabel.textColor = .gray descriptionlabel.numberOfLines = 0 return descriptionlabel }() lazy var titleLabel: UILabel = { let description = UILabel() description.translatesAutoresizingMaskIntoConstraints = false description.text = "Select the fact type:" description.textAlignment = .left description.font = UIFont.boldSystemFont(ofSize: 36) description.numberOfLines = 0 return description }() lazy var randomFactCardView: CardView = { let cardView = CardView(title: "Random useless fact", imageName: "RandomUselessFactImage") cardView.translatesAutoresizingMaskIntoConstraints = false cardView.backgroundColor = .init(red: 0.62, green: 0.66, blue: 1.00, alpha: 1.00) return cardView }() lazy var todayFactCardView: CardView = { let cardView = CardView(title: "Today useless fact", imageName: "TodayUselessFactImage") cardView.translatesAutoresizingMaskIntoConstraints = false cardView.backgroundColor = .init(red: 1.00, green: 0.78, blue: 0.62, alpha: 1.00) return cardView }() // MARK: - Call button action (show the favorites screen) @objc func buttonAction(sender: UIButton) { delegate?.didTapFavorite() } override init(frame: CGRect) { super.init(frame: frame) setupView() configConstrainsts() randomFactCardView.didTapCard = { self.delegate?.didTapCard(type: .random) } todayFactCardView.didTapCard = { self.delegate?.didTapCard(type: .today) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup constraints private func configConstrainsts() { NSLayoutConstraint.activate([ self.favoriteButton.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 32), self.favoriteButton.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 250), self.favoriteButton.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 16), self.favoriteButton.bottomAnchor.constraint(equalTo: subTitleLabel.topAnchor, constant: -32) ]) NSLayoutConstraint.activate([ self.subTitleLabel.topAnchor.constraint(equalTo: favoriteButton.bottomAnchor, constant: 32), self.subTitleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), self.subTitleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16), self.subTitleLabel.bottomAnchor.constraint(equalTo: titleLabel.topAnchor, constant: -32) ]) NSLayoutConstraint.activate([ self.titleLabel.topAnchor.constraint(equalTo: subTitleLabel.bottomAnchor, constant: 32), self.titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), self.titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16) ]) NSLayoutConstraint.activate([ self.randomFactCardView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 32), self.randomFactCardView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), self.randomFactCardView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16), self.randomFactCardView.heightAnchor.constraint(equalToConstant: 150) ]) NSLayoutConstraint.activate([ self.todayFactCardView.topAnchor.constraint(equalTo: randomFactCardView.bottomAnchor, constant: 16), self.todayFactCardView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), self.todayFactCardView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16), self.todayFactCardView.heightAnchor.constraint(equalToConstant: 150) ]) } private func setupView() { addSubview(favoriteButton) addSubview(subTitleLabel) addSubview(titleLabel) addSubview(randomFactCardView) addSubview(todayFactCardView) } }
#include "Clove/Graphics/Vulkan/MemoryAllocator.hpp" #include "Clove/Graphics/Vulkan/VulkanLog.hpp" namespace clove { namespace { uint32_t getMemoryTypeIndex(uint32_t typeBits, VkMemoryPropertyFlags properties, VkPhysicalDevice physicalDevice) { VkPhysicalDeviceMemoryProperties memoryType{}; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memoryType); for(uint32_t i = 0; i < memoryType.memoryTypeCount; ++i) { if((typeBits & (1 << i)) != 0 && (memoryType.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } CLOVE_ASSERT_MSG(false, "{0}: Failed to find the specified index", CLOVE_FUNCTION_NAME); return -1; } } MemoryAllocator::Block::Block(VkDevice device, VkDeviceMemory memory, VkDeviceSize size, uint32_t memoryTypeIndex) : device{ device } , memory{ memory } , size{ size } , memoryTypeIndex{ memoryTypeIndex } { chunks.emplace_back(0, size, memory); } MemoryAllocator::Block::Block(Block &&other) noexcept : device{ other.device } , memory{ other.memory } , size{ other.size } , memoryTypeIndex{ other.memoryTypeIndex } , chunks{ std::move(other.chunks) } { other.memory = VK_NULL_HANDLE;//Make sure the moved block no longer points to our memory } MemoryAllocator::Block &MemoryAllocator::Block::operator=(Block &&other) noexcept { device = other.device; memory = other.memory; size = other.size; memoryTypeIndex = other.memoryTypeIndex; chunks = std::move(other.chunks); other.memory = VK_NULL_HANDLE;//Make sure the moved block no longer points to our memory return *this; } MemoryAllocator::Block::~Block() { vkFreeMemory(device, memory, nullptr); } MemoryAllocator::Chunk const *MemoryAllocator::Block::allocate(VkDeviceSize const size, VkDeviceSize const alignment) { for(auto chunk = std::begin(chunks); chunk != std::end(chunks); ++chunk) { if(chunk->free) { VkDeviceSize const remainingAlignment{ chunk->offset % alignment }; //How much we're off from the alignment VkDeviceSize const alignmentCorrection{ remainingAlignment != 0 ? alignment - remainingAlignment : 0 };//How much we compensate for to achieve a multiple of alignment if(VkDeviceSize const chunkSize = chunk->size - alignmentCorrection; chunkSize >= size) { auto const prevOffset = chunk->offset; chunk->offset += alignmentCorrection; chunk->size = chunkSize; chunk->free = false; //Add back the extra bits to the chunk to the left if(auto const extraBits{ chunk->offset - prevOffset }; extraBits > 0) { std::prev(chunk)->size += extraBits; } //If we have room left in the chunk, split it and put the excess back in the list. if(VkDeviceSize const remainingSize{ chunk->size - size }; remainingSize > 0) { chunks.insert(std::next(chunk), Chunk(chunk->offset + size, remainingSize, memory)); chunk->size = size; } return &*chunk; } } } return nullptr; } bool MemoryAllocator::Block::free(Chunk const *&chunkPtr) { for(auto chunk = std::begin(chunks); chunk != std::end(chunks); ++chunk) { if(*chunk == *chunkPtr) { chunk->free = true; bool removeIndex{ false }; bool removeRight{ false }; //Merge neighbouring chunks if(auto rightChunk = std::next(chunk); rightChunk != std::end(chunks) && rightChunk->free) { //Merge right into us chunk->size += rightChunk->size; removeRight = true; } if(chunk != std::begin(chunks)) { if(auto leftChunk = std::prev(chunk); leftChunk->free) { //Merge ourselves into left leftChunk->size += chunk->size; removeIndex = true; } } //Remove the right most first to preserve indices if(removeRight) { chunks.erase(std::next(chunk)); } if(removeIndex) { chunks.erase(chunk); } chunkPtr = nullptr; return true; } } return false; } MemoryAllocator::MemoryAllocator(DevicePointer device) : device{ std::move(device) } { } MemoryAllocator::MemoryAllocator(MemoryAllocator &&other) noexcept = default; MemoryAllocator &MemoryAllocator::operator=(MemoryAllocator &&other) noexcept = default; MemoryAllocator::~MemoryAllocator() = default; MemoryAllocator::Chunk const *MemoryAllocator::allocate(VkMemoryRequirements const &memoryRequirements, VkMemoryPropertyFlags properties) { uint32_t const memoryTypeIndex{ getMemoryTypeIndex(memoryRequirements.memoryTypeBits, properties, device.getPhysical()) }; Chunk const *freeChunk{ nullptr }; for(auto &block : memoryBlocks) { if(block.getMemoryTypeIndex() == memoryTypeIndex) { freeChunk = block.allocate(memoryRequirements.size, memoryRequirements.alignment); if(freeChunk != nullptr) { break; } } } if(freeChunk == nullptr) { //Make sure if allocate a new block that's big enough VkDeviceSize const size{ std::max(memoryRequirements.size, blockSize) }; VkMemoryAllocateInfo const info{ .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = nullptr, .allocationSize = size, .memoryTypeIndex = memoryTypeIndex, }; VkDeviceMemory memory{ VK_NULL_HANDLE }; if(VkResult const result{ vkAllocateMemory(device.get(), &info, nullptr, &memory) }; result != VK_SUCCESS) { switch(result) { case VK_ERROR_OUT_OF_HOST_MEMORY: CLOVE_LOG(CloveGhaVulkan, LogLevel::Error, "Could not allocate memory. Out of host memory."); break; case VK_ERROR_OUT_OF_DEVICE_MEMORY: CLOVE_LOG(CloveGhaVulkan, LogLevel::Error, "Could not allocate memory. Out of device memory."); break; case VK_ERROR_INVALID_EXTERNAL_HANDLE: CLOVE_LOG(CloveGhaVulkan, LogLevel::Error, "Could not allocate memory. Invalid External handle."); break; case VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR: CLOVE_LOG(CloveGhaVulkan, LogLevel::Error, "Could not allocate memory. Invalid opaque capture address."); break; default: CLOVE_LOG(CloveGhaVulkan, LogLevel::Error, "Could not allocate memory. Reason Unknown."); break; } return nullptr; } #if CLOVE_GHA_MEMORY_DEBUG VkPhysicalDeviceMemoryBudgetPropertiesEXT memoryBudgetProperties{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT, }; VkPhysicalDeviceMemoryProperties2 properties{ .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, .pNext = &memoryBudgetProperties, }; vkGetPhysicalDeviceMemoryProperties2(device.getPhysical(), &properties); uint32_t const heapIndex{ properties.memoryProperties.memoryTypes[memoryTypeIndex].heapIndex }; CLOVE_LOG(CloveGhaVulkan, LogLevel::Trace, "Allocated block of {0} bytes from heap {1}. Current heap usage: {2} / {3}", size, heapIndex, memoryBudgetProperties.heapUsage[heapIndex], memoryBudgetProperties.heapBudget[heapIndex]); #endif memoryBlocks.emplace_back(device.get(), memory, size, memoryTypeIndex); freeChunk = memoryBlocks.back().allocate(memoryRequirements.size, memoryRequirements.alignment); CLOVE_ASSERT_MSG(freeChunk != nullptr, "{0}: Newly allocated Block does not have enough room", CLOVE_FUNCTION_NAME_PRETTY); } return freeChunk; } void MemoryAllocator::free(Chunk const *&chunk) { for(auto &block : memoryBlocks) { if(block.free(chunk)) { break; } } } }
// // Movie.swift // PictarineTest // // Created by Benjamin Duhieu on 17/01/2024. // import Foundation struct Movie: Identifiable { let id: Int let title: String let overview: String let posterPath: String? var posterURL: URL? { posterPath.map { URL(string: "https://image.tmdb.org/t/p/w400/\($0)")! } } let popularity: Double let voteAverage: Double let releaseDate: String? func retrieveYearDate() -> String { guard let date = releaseDate else { return "" } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" if let date = dateFormatter.date(from: date) { let calendar = Calendar.current return "\(calendar.component(.year, from: date))" } return "" } } extension Movie: Equatable { static func == (lhs: Movie, rhs: Movie) -> Bool { return lhs.id == rhs.id } } extension Movie: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(id) } }
const mongoose = require('mongoose') const mongooseUniqueValidator = require('mongoose-unique-validator') const subredditSchema = new mongoose.Schema({ name: { type: String, required: true, unique: true }, description: { type: String, required: true }, date_created: { type: Date, required: true }, moderators: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }], subscribers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }], posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }] }) subredditSchema.plugin(mongooseUniqueValidator) subredditSchema.set('toJSON', { transform: (document, returnedObject) => { returnedObject.id = returnedObject._id.toString() delete returnedObject._id delete returnedObject.__v } }) const subredditModel = mongoose.model('Subreddit', subredditSchema) module.exports = subredditModel
<?php /** * Created by PhpStorm. * User: hirai * Date: 2015/09/11 * Time: 15:09 */ namespace MiscBundle\Command; use MiscBundle\Entity\SymfonyUsers; use MiscBundle\Util\BatchLogger; use MiscBundle\Util\FileUtil; use MiscBundle\Util\WebAccessUtil; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\BrowserKit\Response; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\BrowserKit\Cookie; use Symfony\Component\DomCrawler\Field\InputFormField; use Symfony\Component\Filesystem\Filesystem; class YabuyoshiLoginTestCommand extends ContainerAwareCommand { /** @var SymfonyUsers */ private $account; protected function configure() { $this ->setName('misc:yabuyoshi-login-test') ->setDescription('RMSログインの確認') ->addOption('account', null, InputOption::VALUE_OPTIONAL, '実行アカウント symfony_users.id') ; } protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); /** @var BatchLogger $logger */ $logger = $container->get('misc.util.batch_logger'); $logger->initLogTimer(); // 実行アカウントの取得 (ログ記録PC, NEログインアカウント) if ($accountId = $input->getOption('account')) { /** @var SymfonyUsers $account */ $account = $container->get('doctrine')->getRepository('MiscBundle:SymfonyUsers')->find($accountId); if ($account) { $this->account = $account; $logger->setAccount($account); } } $doctrine = $container->get('doctrine'); /** @var WebAccessUtil $webAccessUtil */ $webAccessUtil = $container->get('misc.util.web_access'); if ($this->account) { $webAccessUtil->setAccount($this->account); } // 藪吉 ログイン $client = $webAccessUtil->getWebClient(); $url = 'https://web01.lisa-c.jp/yabuyoshi/logininit.html'; $crawler = $client->request('get', $url); $output->writeln($crawler->html()); $response = $client->getResponse(); $request = $client->getRequest(); $logger->info(print_r($response->getHeaders(), true)); $logger->info(print_r($response->getStatus(), true)); $logger->info(print_r($request->getUri(), true)); $logger->info(print_r($request->getCookies(), true)); // ログイン処理 $form = $crawler->selectButton('ログイン')->form(); $form['userId'] = 'plusnao'; $form['userPass'] = '1622'; $form['accountId'] = ''; $form['url'] = ''; $form['loginSubmit'] = 'true'; $crawler = $client->submit($form); // Login 実行 /** @var Response $response */ $response = $client->getResponse(); $request = $client->getRequest(); $logger->info(print_r($response->getHeaders(), true)); $logger->info(print_r($response->getStatus(), true)); $logger->info(print_r($request->getUri(), true)); $logger->info(print_r($request->getCookies(), true)); if ($response->getStatus() !== 200 || $request->getUri() !== 'https://web01.lisa-c.jp/yabuyoshi/menuItem.html') { throw new \RuntimeException(sprintf('ログインに失敗しました。[%s][%s][%s]', $response->getStatus(), $request->getUri(), $response->getContent())); } // 在庫情報ダウンロード画面 遷移 $url = 'https://web01.lisa-c.jp/yabuyoshi/Wst051.html'; $crawler = $client->request('get', $url); /** @var Response $response */ $response = $client->getResponse(); $request = $client->getRequest(); $logger->info(print_r($response->getHeaders(), true)); $logger->info(print_r($response->getStatus(), true)); $logger->info(print_r($request->getUri(), true)); $logger->info(print_r($request->getCookies(), true)); $output->writeln($crawler->html()); $form = $crawler->filter('#Wst051'); if (!$form || $form->count() === 0) { throw new \RuntimeException('no csv download form'); } $form = $form->form(); // キー類 捜索&追加 $oFwSessKey = $crawler->filter('[name=fwSessKey]'); $oFwActId = $crawler->filter('[name=fwReqId]'); $oFwCldId = $crawler->filter('[name=fwCldId]'); $url = '/yabuyoshi/Wst051!download.html'; if ($oFwSessKey->count()) { $url .= ';jsessionid=' . $oFwSessKey->attr('value'); } // action 差し替え $form->getFormNode()->setAttribute('action', $url); $logger->info(sprintf('sess: %d', $oFwSessKey->count())); $logger->info(sprintf('req: %d', $oFwActId->count())); $logger->info(sprintf('cld: %d', $oFwCldId->count())); if ($oFwActId->count()) { $domDocument = new \DOMDocument; $input = $domDocument->createElement('input'); $input->setAttribute('name', 'fwReqId'); $input->setAttribute('value', $oFwActId->attr('value')); $input = new InputFormField($input); $form->set($input); } if ($oFwCldId->count()) { $domDocument = new \DOMDocument; $input = $domDocument->createElement('input'); $input->setAttribute('name', 'fwCldId'); $input->setAttribute('value', $oFwCldId->attr('value')); $input = new InputFormField($input); $form->set($input); } $form['outputType'] = '2'; // 「在庫リスト(商品順)」 // $form['downloadFlg'] = 'true'; foreach($form->all() as $field) { $logger->info(sprintf('%s : %s', $field->getName(), $field->getValue())); } $crawler = $client->submit($form); // ダウンロード実行 /** @var Response $response */ $response = $client->getResponse(); $request = $client->getRequest(); $headers = $response->getHeaders(); $status = $response->getStatus(); $uri = $request->getUri(); $logger->info(print_r($headers, true)); $logger->info(print_r($status, true)); $logger->info(print_r($uri, true)); $logger->info(print_r($request->getCookies(), true)); if ($status !== 200 || $uri !== 'https://web01.lisa-c.jp/yabuyoshi/Wst051!download.html') { throw new \RuntimeException('ダウンロードの実行に失敗しました。'); } if (!isset($headers['Content-Disposition'])) { throw new \RuntimeException('ダウンロード時のレスポンスではありませんでした。(Content-Disposition)', print_r($headers, true)); } $fileName = null; foreach($headers['Content-Disposition'] as $header) { if (preg_match('/^attachment;filename="([^"]+)"/', $header, $match)) { $fileName = $match[1]; } } if (!$fileName) { throw new \RuntimeException('ダウンロードのレスポンスではありませんでした。', print_r($headers, true)); } $fs = new FileSystem(); /** @var FileUtil $fileUtil */ $fileUtil = $this->getContainer()->get('misc.util.file'); $exportDir = sprintf('%s/Yabuyoshi/Import/', $fileUtil->getWebCsvDir()); if (!$fs->exists($exportDir)) { $fs->mkdir($exportDir, 0755); } $exportPath = sprintf('%s/stock_%s.csv', $exportDir, (new \DateTime())->format('YmdHis')); $fp = new \SplFileObject($exportPath,'wb'); $fp->fwrite($response->getContent()); unset($fp); $logger->info('output csv: ' . $exportPath . ' ... done.'); return 1; } }
import enum from sqlalchemy import Boolean, Column, Integer, String, DateTime, func, Enum, ForeignKey, Float, Date, Numeric from sqlalchemy.orm import declarative_base, relationship Base = declarative_base() class UserRole(enum.Enum): admin: str = 'admin' user: str = 'user' # class CompanyRole(enum.Enum): # buyer: str = 'buyer' # supplier: str = 'supplier' # partner: str = 'partner' # other: str = 'other' # class AccountingType(enum.Enum): # GR: str = "GR" # OFFICIAL: str = "OFFICIAL" # # # class TransactionType(enum.Enum): # D: str = "Debit" # C: str = "Credit" # # # class DocumentType(enum.Enum): # invoice: str = "invoice" # payment: str = "payment" # # # class OperationRegion(enum.Enum): # domestic: str = "domestic" # export: str = "export" # _import: str = "import" # # # class AccountName(enum.Enum): # QNB: str = "QNB" # VAKIF: str = "VAKIF" # ZIRAAT: str = "ZIRAAT" # KUVEYT: str = "KUVEYT" # TRY_CASA: str = "TRY_CASA" # USD_CASA: str = "USD_CASA" # EUR_CASA: str = "EUR_CASA" # BGN_CASA: str = "BGN_CASA" # # # class PaymentMethod(enum.Enum): # CASH: str = "CASH" # BANK_ACCOUNT: str = "BANK_ACCOUNT" # CREDIT_CARD: str = "CREDIT_CARD" # # # class Currency(enum.Enum): # TL: str = "TL" # USD: str = "USD" # EUR: str = "EUR" # BGN: str = "BGN" # # # class ExpensesType(enum.Enum): # buyer = "buyer" # capital = "capital" # fixed = "fixed" # interest = "interest" # investments = "investments" # invoice_job = "invoice_job" # old_debt = "old_debt" # settlements = "settlements" # variable = "variable" # other = "other" class Company(Base): __tablename__ = "companies" id = Column(Integer, primary_key=True) company_name = Column(String(150), index=True, nullable=False, unique=True) additional_info = Column(String(150), nullable=True) favorite_role = Column(String, index=True, nullable=True) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), default=1) user = relationship('User', backref='companies') class Contact(Base): __tablename__ = "contacts" id = Column(Integer, primary_key=True) firstname = Column(String(50), index=True, nullable=False) lastname = Column(String(50), index=True) email = Column(String, unique=True, index=True, nullable=False) phone = Column(String(15), unique=True, index=True, nullable=False) additional_info = Column(String(150), nullable=True) # is_favorite = Column(Boolean, default=False) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), default=1) user = relationship('User', backref='contacts') class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) username = Column(String(50)) email = Column(String(150), nullable=False, unique=True) password = Column(String(255), nullable=False) refresh_token = Column(String(255), nullable=True) password_reset_token = Column(String(255), nullable=True) avatar = Column(String(255), nullable=True) roles = Column('user_roles', Enum(UserRole), default=UserRole.user) # roles = Column(Enum(UserRole), default=UserRole.user) confirmed = Column(Boolean, default=False) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) # class Invoice(Base): # __tablename__ = "documents" # id = Column(Integer, primary_key=True) # document_number = Column(String(50), nullable=False) # document_date = Column(DateTime, nullable=False) # document_type = Column('document_type', Enum(DocumentType), default=DocumentType.invoice) # company_id = Column('company_id', ForeignKey('companies.id', ondelete='CASCADE'), default=1) # company = relationship('Company', backref='documents') # created_at = Column(DateTime, default=func.now()) # updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) # deleted_at = Column(DateTime, default=func.now(), onupdate=func.now()) # is_deleted = Column(Boolean, default=False) # user_id = Column('user_id', ForeignKey('users.id', ondelete='CASCADE'), default=1) # user = relationship('User', backref='documents') # # class Transaction(Base): __tablename__ = "transactions" id = Column(Integer, primary_key=True) date = Column(DateTime) expenses_category = Column(Enum("buyer", "capital", "fixed", "interest", "investments", "invoice_job", "old_debt", "settlements", "variable", "other", name='expensestype'), nullable=False) # Column(String(255), nullable=False) company_id = Column('company_id', ForeignKey('companies.id', ondelete='CASCADE'), default=1) company = relationship('Company', backref='transactions') description = Column(String(255), nullable=True) accounting_type = Column(Enum('GR Baris', 'ProOil', name='accounting_type'), nullable=False) operation_type = Column(Enum('debit', 'credit', name='operation_type'), nullable=False) document_type = Column(Enum('payment', 'invoice', 'changes', "undefined", name='document_types'), nullable=True) operation_region = Column(Enum('domestic', 'export', 'import', name='operation_region'), nullable=False) currency = Column(Enum('tl', 'eur', 'usd', name='currency_type'), nullable=False) sum = Column(Float, nullable=False) usd_tl_rate = Column(Numeric(precision=18, scale=4), nullable=False) eur_usd_rate = Column(Numeric(precision=18, scale=4), nullable=False) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) deleted_at = Column(DateTime, default=func.now()) is_deleted = Column(Boolean, default=False) user_id = Column('user_id', ForeignKey('users.id', ondelete='SET NULL'), default=1) user = relationship('User', backref='transactions') class DailyStockReports(Base): __tablename__ = "DailyStockReports" id = Column(Integer, primary_key=True) date = Column(Date, default=func.now(), index=True) product_id = Column(Integer, ForeignKey('products.id', ondelete='SET NULL'), index=True) quantity = Column(Float, default=0.0) created_at = Column(DateTime, default=func.now(), nullable=True) updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=True) class Products(Base): __tablename__ = "products" id = Column(Integer, primary_key=True) english_name = Column(String(100), nullable=False) ukrainian_name = Column(String(100), nullable=False) russian_name = Column(String(100), nullable=False) turkish_name = Column(String(100), nullable=False) created_at = Column(DateTime, default=func.now(), nullable=True) updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=True) user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL')) user = relationship('User', backref='products') class Purchase(Base): __tablename__ = "purchases" id = Column(Integer, primary_key=True) date = Column(DateTime, nullable=False) operation_type = Column(Enum('income', 'outcome', name='operation_types'), nullable=False) quantity = Column(Float, nullable=False) company_id = Column(Integer, ForeignKey('companies.id', ondelete='SET NULL')) company = relationship('Company', backref='purchases') product_id = Column(Integer, ForeignKey('products.id')) product = relationship('Products', backref='purchases') price_tl = Column(Numeric(precision=18, scale=2), nullable=False) transfer_cost = Column(Numeric(precision=18, scale=2), nullable=True) commission_duties = Column(Numeric(precision=18, scale=2), nullable=True) sum_total_tl = Column(Numeric(precision=18, scale=2), nullable=False) appr_ex_rate = Column(Numeric(precision=18, scale=4), nullable=False) sum_total_usd = Column(Numeric(precision=18, scale=2), nullable=False) account_type = Column(String(50), nullable=False) cost_per_mt_tl = Column(Numeric(precision=18, scale=2), nullable=False) cost_per_mt_usd = Column(Numeric(precision=18, scale=2), nullable=False) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL')) user = relationship('User', backref='purchases') class ExchRate(Base): __tablename__ = "exchrates" id = Column(Integer, primary_key=True) date = Column(DateTime) usd_tl_rate = Column(Numeric(precision=18, scale=4), nullable=False) eur_usd_rate = Column(Numeric(precision=18, scale=4), nullable=False) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) user_id = Column('user_id', ForeignKey('users.id', ondelete='SET NULL'), default=1) user = relationship('User', backref='exch_rates') class AccountName(Base): __tablename__ = "accounts" id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) user_id = Column('user_id', ForeignKey('users.id', ondelete='SET NULL'), nullable=True) user = relationship('User', backref='accounts') class Movements(Base): __tablename__ = "movements" id = Column(Integer, primary_key=True) date = Column(DateTime) company_id = Column('company_id', ForeignKey('companies.id', ondelete='SET NULL'), nullable=True) company = relationship('Company', backref='movements') description = Column(String(255), default="payment", nullable=True) account_type = Column(String(50), nullable=False) operation_type = Column(String(50), nullable=False) currency = Column(String(50), nullable=False) sum = Column(Float, nullable=False) payment_way = Column('payment_way', ForeignKey('accounts.id', ondelete='SET NULL'), nullable=True) account = relationship('AccountName', backref='movements') created_at = Column(DateTime, default=func.now()) updated_at = Column(DateTime, default=func.now(), onupdate=func.now()) user_id = Column('user_id', ForeignKey('users.id', ondelete='SET NULL'), nullable=True) user = relationship('User', backref='movements') # @event.listens_for(Company, 'before_insert') # def updated_favorite(mapper, conn, target): # # if target.firstname.startswith('My'): # target.is_favorite = True # # # @event.listens_for(Company, 'before_update') # def updated_favorite(mapper, conn, target): # # if target.firstname.startswith('My'): # target.is_favorite = True
'use strict'; /** * Utility function to validate Error Objects * @param val The value to be evaluated. * @returns {boolean} */ var isError = function (val) { return (!!val && typeof val === 'object') && typeof val.message === 'string' && Object.prototype.toString.call(val) === '[object Error]'; }; /** * Main object used to communicate with the platform. * @returns {Platform} * @constructor */ function Platform() { if (!(this instanceof Platform)) return new Platform(); require('events').EventEmitter.call(this); Platform.init.call(this); } require('util').inherits(Platform, require('events').EventEmitter); /** * Init function for Platform. */ Platform.init = function () { ['SIGHUP', 'SIGINT', 'SIGTERM'].forEach((signal) => { process.on(signal, () => { console.log(`Executing ${signal} listener...`); this.emit('close'); setTimeout(() => { this.removeAllListeners(); process.exit(); }, 2000); }); }); ['unhandledRejection', 'uncaughtException'].forEach((exceptionEvent) => { process.on(exceptionEvent, (error) => { console.error(exceptionEvent, error); this.handleException(error); this.emit('close'); setTimeout(() => { this.removeAllListeners(); process.exit(1); }, 2000); }); }); process.on('message', (m) => { if (m.type === 'ready') this.emit('ready', m.data.options); else if (m.type === 'log') this.emit('log', m.data); else if (m.type === 'close') this.emit('close'); }); }; /** * Needs to be called once in order to notify the platform that the plugin has already finished the init process. * @param {function} [callback] Optional callback to be called once the ready signal has been sent. */ Platform.prototype.notifyReady = function (callback) { callback = callback || function () { }; setImmediate(() => { process.send({ type: 'ready' }, callback); }); }; /** * Notifies the platform that resources have been released and this plugin can shutdown gracefully. * @param {function} [callback] Optional callback to be called once the close signal has been sent. */ Platform.prototype.notifyClose = function (callback) { callback = callback || function () { }; setImmediate(() => { process.send({ type: 'close' }, callback); }); }; /** * Logs errors to all the attached exception handlers in the topology. * @param {error} error The error to be handled/logged * @param {function} callback Optional callback to be called once the error has been sent. */ Platform.prototype.handleException = function (error, callback) { callback = callback || function () { }; setImmediate(() => { if (!isError(error)) return callback(new Error('A valid error object is required.')); process.send({ type: 'error', data: { name: error.name, message: error.message, stack: error.stack } }, callback); }); }; module.exports = new Platform();
// // PostViewModel.swift // Insta_Swift // // Created by baegteun on 2021/07/23. // import Foundation struct PostViewModel{ let post: Post var imageUrl: URL?{ return URL(string: post.imageUrl) } var userProfileImageUrl: URL? { return URL(string: post.ownerImageUrl) } var username: String { return post.ownerUsername } var captions: String{ return post.caption } var likes: Int{ return post.likes } var likesLabelText: String{ if post.likes != 1 { return "\(post.likes) likes" }else{ return "\(post.likes) like" } } init(post: Post){ self.post = post } }
import React, { useRef, useState } from 'react'; import firebase from 'firebase/app'; import 'firebase/firestore'; import 'firebase/auth'; import { useAuthState } from 'react-firebase-hooks/auth'; import { useCollectionData } from 'react-firebase-hooks/firestore'; firebase.initializeApp({ apiKey: "AIzaSyBdHa-wyQlI3fKe9XqykLmTmB_xrtUV4fs", authDomain: "chat-app-5bc3b.firebaseapp.com", projectId: "chat-app-5bc3b", storageBucket: "chat-app-5bc3b.appspot.com", messagingSenderId: "1086732838113", appId: "1:1086732838113:web:7fc771e8e39da3965303a0" }) const auth = firebase.auth() const firestore = firebase.firestore() function trialpage(props) { const [user] = useAuthState(auth) return ( <div> <header> <h1>⚛️🔥💬</h1> <SignOut /> </header> <section> {user ? <ChatRoom /> : <SignIn />} </section> </div> ); } function SignIn() { const signInWithGoogle = () => { const provider = new firebase.auth.GoogleAuthProvider() auth.signInWithPopup(provider) } return ( <> <button onClick={signInWithGoogle}>Sign in with Google</button> </> ) } function SignOut() { return auth.currentUser && ( <button onClick={() => auth.signOut()}>Sign Out</button> ) } function ChatRoom() { const dummy = useRef(); const messagesRef = firestore.collection('messages'); const query = messagesRef.orderBy('createdAt').limit(25); const [messages] = useCollectionData(query, { idField: 'id' }); const [formValue, setFormValue] = useState(''); const sendMessage = async (e) => { e.preventDefault(); const { uid, photoURL } = auth.currentUser; await messagesRef.add({ text: formValue, createdAt: firebase.firestore.FieldValue.serverTimestamp(), uid, photoURL }) setFormValue(''); dummy.current.scrollIntoView({ behavior: 'smooth' }); } return (<> <main> {messages && messages.map(msg => <ChatMessage key={msg.id} message={msg} />)} <span ref={dummy}></span> </main> <form onSubmit={sendMessage}> <input value={formValue} onChange={(e) => setFormValue(e.target.value)} placeholder="say something nice" /> <button>SEND🕊️</button> </form> </>) } function ChatMessage(props) { const { text, uid, photoURL } = props.message; const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received'; return (<> <div> <img src={photoURL || 'https://api.adorable.io/avatars/23/abott@adorable.png'} /> <p>{text}</p> </div> </>) } export default trialpage;
import { PlusOutlined } from "@ant-design/icons"; import { Input, Tag, Tooltip } from "antd"; import _ from "lodash"; import { useEffect, useRef, useState } from "react"; import RenderIf from "@/utils/RenderIf/renderIf"; interface IInputWithTagComponentProps { tags: any; setTags: any; } const InputWithTagComponent = (props: IInputWithTagComponentProps) => { const { tags, setTags } = props; // State & constants const [inputVisible, setInputVisible] = useState(false); const [inputValue, setInputValue] = useState(""); const [editInputIndex, setEditInputIndex] = useState<number>(); const [editInputValue, setEditInputValue] = useState(""); const inputRef = useRef<any>(null); const editInputRef = useRef<any>(null); // Life cycle methods useEffect(() => { if (inputVisible) { inputRef.current?.focus(); } }, [inputVisible]); useEffect(() => { editInputRef.current?.focus(); }, [inputValue]); // Event methods const handleClose = (removedTag: string) => { const newTagsArr = tags.filter((tag: string) => tag !== removedTag); setTags(newTagsArr); }; const showInput = () => { setInputVisible(true); }; const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => { setInputValue((e.target as HTMLInputElement).value); }; const handleInputConfirm = () => { if (inputValue && tags.indexOf(inputValue) === -1) { setTags([...tags, inputValue as string]); } setInputVisible(false); setInputValue(""); }; const handleEditInputChange = (e: React.FormEvent<HTMLInputElement>) => { setEditInputValue((e.target as HTMLInputElement).value); }; const handleEditInputConfirm = () => { const newTags = [...tags]; if (editInputIndex) { newTags[editInputIndex] = editInputValue; setTags(newTags); setEditInputIndex(-1); setInputValue(""); } }; return ( <> {tags.map((tag: string, index: number) => { if (editInputIndex === index) { return ( <Input ref={editInputRef} key={tag} size="small" className="tag-input" value={editInputValue} onChange={handleEditInputChange} onBlur={handleEditInputConfirm} onPressEnter={handleEditInputConfirm} /> ); } const isLongTag = tag.length > 20; const tagElem = _.size(tag) > 0 ? ( <Tag className="edit-tag" key={tag} closable onClose={() => handleClose(tag)}> <span onDoubleClick={(e) => { if (index !== 0) { setEditInputIndex(index); setEditInputValue(tag); e.preventDefault(); } }} > {isLongTag ? `${tag.slice(0, 20)}...` : tag} </span> </Tag> ) : ( "" ); return isLongTag ? ( <Tooltip title={tag} key={tag}> {tagElem} </Tooltip> ) : ( tagElem ); })} <RenderIf isTrue={inputVisible === true}> <Input ref={inputRef} type="text" size="small" className="tag-input" value={inputValue} onChange={handleInputChange} onBlur={handleInputConfirm} onPressEnter={handleInputConfirm} /> </RenderIf> <RenderIf isTrue={inputVisible === false}> <Tag className="site-tag-plus" onClick={showInput}> <PlusOutlined /> Add skills </Tag> </RenderIf> </> ); }; export default InputWithTagComponent;
/* * Copyright 2020 Thomas Plougsgaard * * 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. */ import { handleVersion } from '../handlers' import { sendNotification } from '../server' import javaVersion from '../util/javaVersion' import { ChildProcess, spawn } from 'child_process' import { getPortPromise } from 'portfinder' import * as _ from 'lodash' import * as jobs from './jobs' import * as queue from './queue' import * as socket from './socket' import { USER_MESSAGE } from '../util/userMessages' export interface CompileOnSave { enabled: boolean } export interface CompileOnChange { enabled: boolean delay: number } export interface Explain { enabled: boolean } export interface UserConfiguration { compileOnSave: CompileOnSave compileOnChange: CompileOnChange explain: Explain extraJvmArgs: string extraFlixArgs: string } export interface StartEngineInput { flixFilename: string workspaceFolders: [string] extensionPath: string extensionVersion: string globalStoragePath: string workspaceFiles: [string] workspacePkgs: [string] workspaceJars: [string] userConfiguration: UserConfiguration } let flixInstance: ChildProcess | undefined = undefined let startEngineInput: StartEngineInput let flixRunning: boolean = false export function isRunning() { return flixRunning } export function getFlixFilename() { return startEngineInput.flixFilename } export function getExtensionVersion() { return _.get(startEngineInput, 'extensionVersion', '(unknown version)') } export function getProjectRootUri() { return _.first(startEngineInput.workspaceFolders) } export function updateUserConfiguration(userConfiguration: UserConfiguration) { _.set(userConfiguration, 'userConfiguration', startEngineInput) queue.resetEnqueueDebounced() } export function compileOnSaveEnabled() { return startEngineInput?.userConfiguration.compileOnSave.enabled ?? true } export function compileOnChangeEnabled() { return startEngineInput?.userConfiguration.compileOnChange.enabled ?? true } export function compileOnChangeDelay() { return startEngineInput?.userConfiguration.compileOnChange.delay ?? 300 } export async function start(input: StartEngineInput) { if (flixInstance || socket.isOpen()) { await stop() } // copy input to local var for later use startEngineInput = _.clone(input) const { flixFilename, extensionPath, workspaceFiles, workspacePkgs, workspaceJars } = input // Check for valid Java version const { majorVersion, versionString } = await javaVersion(extensionPath) if (versionString === undefined) { // This happends when we are not able to run a java statement or get a java version sendNotification(jobs.Request.internalError, { message: USER_MESSAGE.JAVA_NOT_FOUND(), actions: [], }) return } if (majorVersion! < 11) { sendNotification(jobs.Request.internalError, { message: USER_MESSAGE.JAVA_WRONG_VERSION(versionString), actions: [], }) return } // get a port starting from 8888 const port = await getPortPromise({ port: 8888 }) // build the Java args from the user configuration // TODO split respecting "" const args = [] args.push(...parseArgs(startEngineInput.userConfiguration.extraJvmArgs)) args.push('-jar', flixFilename, 'lsp', `${port}`) args.push(...parseArgs(startEngineInput.userConfiguration.extraFlixArgs)) if (startEngineInput?.userConfiguration.explain.enabled ?? false) { args.push('--explain') } // // WARNING: WE MUST CONNECT TO 127.0.0.1 AND NOT LOCALHOST. // // SEE https://github.com/microsoft/vscode/issues/192545 // const instance = (flixInstance = spawn('java', args)) const webSocketUrl = `ws://127.0.0.1:${port}` // forward flix to own stdout & stderr instance.stdout.pipe(process.stdout) instance.stderr.pipe(process.stderr) const connectToSocket = (data: any) => { const str = data .toString() .split(/(\r?\n)/g) .join('') if (str.includes(`:${port}`)) { // initialise websocket, listening to messages and what not socket.initialiseSocket({ uri: webSocketUrl, onOpen: function handleOpen() { flixRunning = true const addUriJobs = _.map(workspaceFiles, uri => ({ uri, request: jobs.Request.apiAddUri })) const addPkgJobs = _.map(workspacePkgs, uri => ({ uri, request: jobs.Request.apiAddPkg })) const addJarJobs = _.map(workspaceJars, uri => ({ uri, request: jobs.Request.apiAddJar })) const Jobs: jobs.Job[] = [...addUriJobs, ...addPkgJobs, ...addJarJobs] queue.initialiseQueues(Jobs) handleVersion() sendNotification(jobs.Request.internalFinishedJob) }, onClose: function handleClose() { flixRunning = false }, }) // now that the connection is established, there's no reason to listen for new messages instance.stdout.removeListener('data', connectToSocket) } } instance.stdout.addListener('data', connectToSocket) } /** * Parses the argument string into a list of arguments. */ function parseArgs(args: string): Array<string> { const trimmed = args.trim() if (trimmed === '') { return [] } else { return args.split(' ') } } export async function stop() { queue.terminateQueue() await socket.closeSocket() if (flixInstance) { flixInstance.kill() } } export function addUri(uri: string) { const job: jobs.Job = { request: jobs.Request.apiAddUri, uri, } queue.enqueue(job) } export function remUri(uri: string) { const job: jobs.Job = { request: jobs.Request.apiRemUri, uri, } queue.enqueue(job) } export function addPkg(uri: string) { const job: jobs.Job = { request: jobs.Request.apiAddPkg, uri, } queue.enqueue(job) } export function remPkg(uri: string) { const job: jobs.Job = { request: jobs.Request.apiRemPkg, uri, } queue.enqueue(job) } export function addJar(uri: string) { const job: jobs.Job = { request: jobs.Request.apiAddJar, uri, } queue.enqueue(job) } export function remJar(uri: string) { const job: jobs.Job = { request: jobs.Request.apiRemJar, uri, } queue.enqueue(job) } export function enqueueJobWithFlattenedParams(request: jobs.Request, params?: any) { const job: jobs.Job = { request, ...(params || {}), } return queue.enqueue(job) }
// // DiceView.swift // DiceRoll // // Created by Or Israeli on 09/06/2023. // import SwiftUI struct Dots: View { var body: some View { HStack { //left column VStack { Circle() .frame(width: 20) .padding(.top, 4) Spacer() Circle() .frame(width: 20) .padding(.bottom, 4) } //mid column Circle() .frame(width: 20) //right column VStack { Circle() .frame(width: 20) .padding(.top, 4) Spacer() Circle() .frame(width: 20) .padding(.bottom, 4) } } .foregroundColor(.black) } } struct Dice: View { var number: Int? var body: some View { RoundedRectangle(cornerRadius: 10, style: .continuous) .foregroundColor(.black) .overlay { ZStack { RoundedRectangle(cornerRadius: 10, style: .continuous) .foregroundColor(.white) .frame(width: 90, height: 90) .overlay { if let number = number { Text(String(number)) .font(.largeTitle) .foregroundColor(.black) } else { Dots() } } } } .frame(width: 100, height: 100) } } struct DiceView: View { var roll: Roll? var body: some View { HStack { Dice(number: roll?.num1) Dice(number: roll?.num2) } } } struct DiceView_Previews: PreviewProvider { static var previews: some View { DiceView(roll: Roll()) } }
class Solution { public: int maxSubArray(vector<int> &nums) { // TLE // int max_sum = INT_MIN; // for(int i = 0; i < nums.size(); i++){ // int currsum = 0; // for(int j = i; j < nums.size();j++){ // currsum += nums[j]; // max_sum = max(max_sum, currsum); // } // } // return max_sum; // Kadane's Algorithm // int Max = INT_MIN; // int sum = 0; // int n = nums.size(); // for(int i = 0; i < n; i++){ // sum += nums[i]; // Max = max(sum,Max); // if(sum < 0) // sum = 0; // } // return Max; // This Question can be done using Maximum sum subarray. // In this we always take in account till we are positive we can always // take the prev_sum. Otherwise start a new subarray from the Current Position. int local_max = 0; int global_max = -1e4; int n = nums.size(); for (int i = 0; i < n; i++) { local_max += (nums[i]); global_max = max(global_max, local_max); if (local_max < 0) { local_max = 0; } } return global_max; } };
import '../styles/globals.css'; import '@rainbow-me/rainbowkit/styles.css'; import { getDefaultWallets, RainbowKitProvider, Chain } from '@rainbow-me/rainbowkit'; import type { AppProps } from 'next/app'; import { configureChains, createConfig, WagmiConfig } from 'wagmi'; import { arbitrum, goerli, mainnet, optimism, polygon, base, zora, sepolia, } from 'wagmi/chains'; import { publicProvider } from 'wagmi/providers/public'; const nordek: Chain = { id: 81041, name: 'Nordek', network: 'nordek', iconUrl:`https://pbs.twimg.com/profile_images/1721104975164751872/DTsj6Zth_400x400.jpg`, nativeCurrency: { decimals: 18, name: 'Nordek', symbol: 'NRK', }, rpcUrls: { public: { http: ['https://mainnet-rpc.nordekscan.com'] }, default: { http: ['https://mainnet-rpc.nordekscan.com'] }, }, blockExplorers: { default: { name: 'Nordekscan', url: 'https://nordekscan.com:443' }, }, testnet: false, }; const { chains, publicClient, webSocketPublicClient } = configureChains( [ mainnet, polygon, optimism, arbitrum, base, zora, goerli, sepolia, nordek ], [ publicProvider()] ); const { connectors } = getDefaultWallets({ appName: 'RainbowKit App', projectId: process.env.NEXT_PUBLIC_PROJECT_ID?process.env.NEXT_PUBLIC_PROJECT_ID:'YOUR_PROJECT_ID', chains, }); const wagmiConfig = createConfig({ autoConnect: true, connectors, publicClient, webSocketPublicClient, }); function MyApp({ Component, pageProps }: AppProps) { return ( <WagmiConfig config={wagmiConfig}> <RainbowKitProvider chains={chains}> <Component {...pageProps} /> </RainbowKitProvider> </WagmiConfig> ); } export default MyApp;
import React, {useCallback} from 'react'; import {useQueryClient} from 'react-query'; import {ErrorRounded} from '@mui/icons-material'; import {Button, Stack, Typography} from '@mui/material'; interface IProps { queryKey: string; } export const ErrorPage: React.FC<IProps> = ({queryKey}) => { const queryClient = useQueryClient(); const handleReset = useCallback(() => { queryClient.invalidateQueries(queryKey); }, [queryClient, queryKey]); return ( <Stack width="100%" height="80vh" justifyContent="center" alignItems="center"> <Stack width="80%" display="flex" justifyContent="space-between" alignItems="center" spacing={3}> <ErrorRounded color="secondary" sx={{fontSize: 100}} /> <Typography variant="h4" align="center"> Error loading data! </Typography> <Button variant="outlined" onClick={handleReset}> Reset Page </Button> </Stack> </Stack> ); };
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os from functools import reduce from multiprocessing.pool import ThreadPool as Pool from time import perf_counter from typing import cast, Dict, List, Optional, Tuple, Union import numpy import torch import torch.distributed as dist from torch import nn from torchrec.distributed.collective_utils import invoke_on_rank_and_broadcast_result from torchrec.distributed.planner.constants import BATCH_SIZE, MAX_SIZE from torchrec.distributed.planner.enumerators import EmbeddingEnumerator from torchrec.distributed.planner.partitioners import GreedyPerfPartitioner from torchrec.distributed.planner.perf_models import NoopPerfModel from torchrec.distributed.planner.proposers import ( GreedyProposer, GridSearchProposer, proposers_to_proposals_list, UniformProposer, ) from torchrec.distributed.planner.stats import EmbeddingStats from torchrec.distributed.planner.storage_reservations import ( HeuristicalStorageReservation, ) from torchrec.distributed.planner.types import ( Enumerator, ParameterConstraints, Partitioner, PerfModel, PlannerError, Proposer, ShardingOption, Stats, Storage, StorageReservation, Topology, ) from torchrec.distributed.types import ( EnumerableShardingSpec, ModuleSharder, ParameterSharding, ShardingPlan, ShardingPlanner, ShardingType, ShardMetadata, ) def _to_sharding_plan( sharding_options: List[ShardingOption], topology: Topology, ) -> ShardingPlan: def _placement( compute_device: str, rank: int, local_size: int, ) -> str: param_device = compute_device if compute_device == "cuda": param_device = torch.device("cuda", rank % local_size) return f"rank:{rank}/{param_device}" compute_device = topology.compute_device local_size = topology.local_world_size plan = {} for sharding_option in sharding_options: shards = sharding_option.shards sharding_type = sharding_option.sharding_type module_plan = plan.get(sharding_option.path, {}) module_plan[sharding_option.name] = ParameterSharding( sharding_spec=None if sharding_type == ShardingType.DATA_PARALLEL.value else EnumerableShardingSpec( [ ShardMetadata( shard_sizes=shard.size, shard_offsets=shard.offset, placement=_placement( compute_device, cast(int, shard.rank), local_size ), ) for shard in shards ] ), sharding_type=sharding_type, compute_kernel=sharding_option.compute_kernel, ranks=[cast(int, shard.rank) for shard in shards], ) plan[sharding_option.path] = module_plan return ShardingPlan(plan) class ParallelizedEmbeddingShardingPlanner(ShardingPlanner): """ Provides an optimized sharding plan for a given module with shardable parameters according to the provided sharders, topology, and constraints using multiprocessing to improve runtime and scalability. """ def __init__( self, topology: Topology, batch_size: Optional[int] = None, enumerator: Optional[Enumerator] = None, storage_reservation: Optional[StorageReservation] = None, proposer: Optional[Union[Proposer, List[Proposer]]] = None, custom_cpu_count: Optional[int] = None, partitioner: Optional[Partitioner] = None, performance_model: Optional[PerfModel] = None, stats: Optional[Union[Stats, List[Stats]]] = None, constraints: Optional[Dict[str, ParameterConstraints]] = None, debug: bool = True, ) -> None: self._topology = topology self._batch_size: int = batch_size if batch_size else BATCH_SIZE self._constraints = constraints self._enumerator: Enumerator = ( enumerator if enumerator else EmbeddingEnumerator( topology=topology, batch_size=self._batch_size, constraints=constraints, ) ) self._storage_reservation: StorageReservation = ( storage_reservation if storage_reservation else HeuristicalStorageReservation(percentage=0.15) ) self._partitioner: Partitioner = ( partitioner if partitioner else GreedyPerfPartitioner() ) if proposer: self._proposers: List[Proposer] = ( [proposer] if not isinstance(proposer, list) else proposer ) else: self._proposers = [ GridSearchProposer(), GreedyProposer(), GreedyProposer(use_depth=False), UniformProposer(), ] self._perf_model: PerfModel = ( performance_model if performance_model else NoopPerfModel(topology=topology) ) if stats: self._stats: List[Stats] = [stats] if not isinstance(stats, list) else stats else: self._stats = [EmbeddingStats()] self._debug = debug self._num_proposals: int = 0 self._num_plans: int = 0 self._cpu_count: Optional[int] = ( custom_cpu_count if custom_cpu_count else os.cpu_count() ) def collective_plan( self, module: nn.Module, sharders: List[ModuleSharder[nn.Module]], pg: dist.ProcessGroup, ) -> ShardingPlan: """ Call self.plan(...) on rank 0 and broadcast """ return invoke_on_rank_and_broadcast_result( pg, 0, self.plan, module, sharders, ) def plan( self, module: nn.Module, sharders: List[ModuleSharder[nn.Module]], ) -> ShardingPlan: self._num_proposals = 0 self._num_plans = 0 start_time = perf_counter() storage_constraint: Topology = self._storage_reservation.reserve( topology=self._topology, batch_size=self._batch_size, module=module, sharders=sharders, constraints=self._constraints, ) search_space = self._enumerator.enumerate( module=module, sharders=sharders, ) if not search_space: # No shardable parameters return ShardingPlan({}) proposals_list = proposers_to_proposals_list( self._proposers, search_space=search_space ) self._num_proposals = len(proposals_list) def get_best_plan( proposal_group: List[List[ShardingOption]], ) -> Tuple[Optional[List[ShardingOption]], float, Storage, int]: group_plans_num = 0 lowest_storage = Storage(MAX_SIZE, MAX_SIZE) best_perf_rating = MAX_SIZE best_plan = None for proposal in proposal_group: try: plan = self._partitioner.partition( proposal=proposal, storage_constraint=storage_constraint, ) group_plans_num += 1 perf_rating = self._perf_model.rate(plan=plan) if perf_rating < best_perf_rating: best_perf_rating = perf_rating best_plan = plan except PlannerError: current_storage = cast( Storage, reduce( lambda x, y: x + y, [ shard.storage for option in proposal for shard in option.shards ], ), ) if current_storage < lowest_storage: lowest_storage = current_storage return (best_plan, best_perf_rating, lowest_storage, group_plans_num) grouped_proposals = numpy.array_split(proposals_list, self._cpu_count) pool = Pool(self._cpu_count) group_best_plans = pool.map(get_best_plan, grouped_proposals) pool.close() pool.join() lowest_storage = Storage(MAX_SIZE, MAX_SIZE) best_perf_rating = MAX_SIZE best_plan = None for plan_info in group_best_plans: current_plan = plan_info[0] plan_perf_rating = plan_info[1] plan_storage = plan_info[2] self._num_plans += plan_info[3] if plan_perf_rating < best_perf_rating: best_plan = current_plan best_perf_rating = plan_perf_rating if plan_storage < lowest_storage: lowest_storage = plan_storage if best_plan is not None: sharding_plan = _to_sharding_plan(best_plan, self._topology) end_time = perf_counter() for stats in self._stats: stats.log( sharding_plan=sharding_plan, topology=self._topology, batch_size=self._batch_size, storage_reservation=self._storage_reservation, num_proposals=self._num_proposals, num_plans=self._num_plans, run_time=end_time - start_time, best_plan=best_plan, constraints=self._constraints, debug=self._debug, ) return sharding_plan else: global_storage_capacity = reduce( lambda x, y: x + y, [device.storage for device in self._topology.devices], ) global_storage_constraints = reduce( lambda x, y: x + y, [device.storage for device in storage_constraint.devices], ) raise PlannerError( f"Unable to find a plan for this model that evaluates {self._num_proposals} proposals." "\nPossible solutions:" f"\n 1) Increase the number of devices ({self._topology.world_size})" f"\n 2) Reduce the model size (" f"\n\t Global storage: {global_storage_capacity.hbm}, " f"\n\t Available for model parallel: {global_storage_constraints}," f"\n\t Requirement for model parallel: {lowest_storage})" f"\n 3) Reduce local batch size ({self._batch_size})" "\n 4) Remove planner constraints that might be reducing search space or available storage\n" )
use std::str::FromStr; #[derive(Debug)] enum Operation { Noop, Add } #[derive(Debug)] struct Instruction { cycles: u8, operation: Operation, operand: Option<i32> } struct Device { acc: isize, cycles: usize, signal_strength: isize } impl Default for Device { fn default() -> Self { Device { acc: 1, cycles: 0, signal_strength: 0 } } } impl Device { fn execute(&mut self, instruction: Instruction) { match instruction.operation { Operation::Noop => { self.cycles += 1; self.check_cycle(); } Operation::Add => { for _ in 0..instruction.cycles { self.cycles += 1; self.check_cycle(); } self.acc += instruction.operand.unwrap() as isize; }, } } fn check_cycle(&mut self) { if [20, 60, 100, 140, 180, 220].contains(&self.cycles) { self.signal_strength += self.acc * self.cycles as isize; } } } impl FromStr for Instruction { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { let mut splitted = s.split_whitespace(); match splitted.next().unwrap() { "noop" => { return Ok(Instruction { cycles: 1, operation: Operation::Noop, operand: None }); } "addx" => { let opp = splitted.next().unwrap(); return Ok(Instruction { cycles: 2, operation: Operation::Add, operand: Some(opp.parse().unwrap()) }); } _ => todo!() } } } pub fn sovle() { let mut device = Device::default(); include_str!("test") .lines() .for_each(|l| { let i = l.parse::<Instruction>().unwrap(); device.execute(i); }); println!("{:?}", device.signal_strength); }
// app/page.js 'use client'; import React, { useState } from 'react'; import Header from '../components/Header'; import Menu from '../components/Menu'; import CharacterStats from '../components/CharacterStats'; import Modal from '../components/Modal'; import SocialMedia from '../components/SocialMedia'; import SkillMeter from '../components/SkillMeter'; // Import SkillMeter component import Blog from '../components/Blog'; // Import Blog component import ContactInfo from '../pages/ContactInfo'; import Objective from '../pages/Objective'; import ProfessionalExperience from '../pages/ProfessionalExperience'; import Education from '../pages/Education'; import Certifications from '../pages/Certifications'; import TechnicalSkills from '../pages/TechnicalSkills'; // Import other page components as needed export default function Home() { const [isModalOpen, setIsModalOpen] = useState(false); const [modalContent, setModalContent] = useState(null); const openModal = (content) => { setModalContent(content); setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); setModalContent(null); }; const renderModalContent = () => { switch (modalContent) { case 'ContactInfo': return <ContactInfo />; case 'Objective': return <Objective />; case 'ProfessionalExperience': return <ProfessionalExperience />; case 'Education': return <Education />; case 'Certifications': return <Certifications />; case 'TechnicalSkills': return <TechnicalSkills />; default: return null; } }; // Define your skills and levels const skills = [ { name: 'HTML', level: 90 }, { name: 'CSS', level: 85 }, { name: 'JavaScript', level: 75 }, // ... add more skills as needed ]; const skillsData = { labels: ['JavaScript', 'HTML & CSS', 'Java', 'Python', 'React', 'Data'], datasets: [{ label: 'Years of Experience', data: [8, 10, 3, 4, 5, 6], // Data for the radar chart backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1, pointBackgroundColor: 'rgba(255, 99, 132, 1)', }], }; const skillsColor = 'rgba(255, 99, 132, 0.2)'; return ( <div> <Header onClose={closeModal} /> <Menu openModal={openModal} /> {isModalOpen && ( <Modal onClose={closeModal}> {renderModalContent()} </Modal> )} <CharacterStats /> <SocialMedia /> {/* Render the radar chart SkillMeter */} <SkillMeter dataPoints={[10, 10, 6, 4, 10, 8]} labels={['JavaScript', 'HTML & CSS', 'Advertising', 'Python', 'Design', 'Data']} /> <Blog /> {/* Added Blog component here */} {/* ... other components ... */} </div> ); }
<?php namespace App\Http\Controllers; use App\Http\Requests\StoreCategoryRequest; use App\Http\Requests\UpdateCategoryRequest; use App\Models\Category; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; class CategoryController extends Controller { /** * Display a listing of the resource. */ public function index() { $categories = Category::latest("id")->get(); return view("category.index",compact("categories")); } /** * Show the form for creating a new resource. */ public function create() { return view("category.create"); } /** * Store a newly created resource in storage. */ public function store(StoreCategoryRequest $request) { Category::create([ "title" => $request->title, "slug" => Str::slug($request->title), "user_id" => Auth::id() ]); return redirect()->route("category.index"); } /** * Display the specified resource. */ public function show(Category $category) { return abort(404); } /** * Show the form for editing the specified resource. */ public function edit(Category $category) { // $this->authorize("update",$category); return view("category.edit",compact("category")); } /** * Update the specified resource in storage. */ public function update(UpdateCategoryRequest $request, Category $category) { $this->authorize("update",$category); $category->update([ "title" => $request->title ]); return redirect()->route("category.index");; } /** * Remove the specified resource from storage. */ public function destroy(Category $category) { $this->authorize("delete",$category); $category->delete(); return redirect()->back(); } }
import { Controller, Get, Post, Delete, Body, Query, UseGuards, Param, Patch, ParseIntPipe } from '@nestjs/common'; import { MoviesService } from './movies.service'; import { GetUser } from 'src/decorator'; import { JwtGuard } from 'src/auth/guard'; import { CreateMovieDto, MovieDto } from './movies.dto'; import { EditMovieDto } from './dto'; @UseGuards(JwtGuard) @Controller('movies') export class MoviesController { PrismaService: any; constructor(private readonly movieService:MoviesService) {} @Get() async findAll(@Query("page") page:number,@Query("perPage") perPage:number, @Query("name") name?:string): Promise<MovieDto[]> { page = page && page > 0 ? page : 1 perPage = perPage && perPage > 0 ? perPage : 10 return await this.movieService.findMany(page,perPage,name) } @Post() async create( @Body() data: CreateMovieDto, @GetUser("id") userId:number ){ return await this.movieService.createMovie(data,userId) } @Delete(':id') async delete(@Param('id',ParseIntPipe) id: number,@GetUser("id") userId:number): Promise<String> { return await this.movieService.deleteMovie(id,userId); } @Patch(':id') async update(@Param('id',ParseIntPipe) id: number, @Body() data: EditMovieDto, @GetUser("id") userId:number): Promise<MovieDto> { return await this.movieService.editMovie(userId,id, data); } }
import { Injectable, NotFoundException, Logger, InternalServerErrorException, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { ETaskStatus } from './interface/tasks.interface'; import { GetTasksFilterDto } from './dto/get-tasks-filter.dto'; import { CreateTaskDto } from './dto/create-task.dto'; import { Task } from './task.entity'; import { User } from '../auth/user.entity'; @Injectable() export class TasksService { private logger = new Logger('TasksService', { timestamp: true }); constructor( @InjectRepository(Task) private tasksRepository: Repository<Task> ) {} async createTask(createTaskDto: CreateTaskDto, user: User): Promise<Task> { const { title, description } = createTaskDto; const task = this.tasksRepository.create({ title, description, status: ETaskStatus.OPEN, user, }); await this.tasksRepository.save(task); return task; } async getTasks(filterDto: GetTasksFilterDto, user: User): Promise<Task[]> { const { status, search } = filterDto; const query = this.tasksRepository.createQueryBuilder('task'); query.where({ user }); if (status) { query.andWhere('task.status = :status', { status }); } if (search) { query.andWhere( '(LOWER(task.title) LIKE LOWER(:search) OR LOWER(task.description) LIKE LOWER(:search))', { search: `%${search}%`, } ); } try { const tasks = await query.getMany(); return tasks; } catch (err) { this.logger.error(`Filed to get tasks fro user "${user.username}".`, err.stack); throw new InternalServerErrorException(); } } async getTaskById(id: string, user: User): Promise<Task> { const foundTask = await this.tasksRepository.findOne({ where: { id, user } }); if (!foundTask) { throw new NotFoundException(`Task with ID '${id}' not found`); } return foundTask; } async updateTaskById(id: string, status: ETaskStatus, user: User): Promise<Task> { const task = await this.getTaskById(id, user); task.status = status; await this.tasksRepository.save(task); return task; } async deleteTaskById(id: string, user: User): Promise<void> { const result = await this.tasksRepository.delete({ id, user }); if (result.affected === 0) { throw new NotFoundException(`Task with ID '${id}' not found`); } } }
<?php declare(strict_types=1); namespace App\Modules\Invoices\Domain\Models; use App\Domain\Enums\StatusEnum; use App\Domain\Models\CompanyModel; use Ramsey\Uuid\UuidInterface; readonly class InvoiceModel { public function __construct( private UuidInterface $id, private string $number, private string $date, private string $dueDate, private StatusEnum $status, private string $updatedAt, private CompanyModel $billToCompany, private CompanyModel $shipToCompany, /** @var InvoiceProductLineModel[] */ private array $productLines, ) { } public function getId(): UuidInterface { return $this->id; } public function getNumber(): string { return $this->number; } public function getDate(): string { return $this->date; } public function getDueDate(): string { return $this->dueDate; } public function getBillToCompany(): CompanyModel { return $this->billToCompany; } public function getShipToCompany(): CompanyModel { return $this->shipToCompany; } /** @return InvoiceProductLineModel[] */ public function getProductLines(): array { return $this->productLines; } public function getTotalPrice(): int { return array_reduce( $this->productLines, fn (int $total, InvoiceProductLineModel $productLine) => $total + $productLine->getTotal(), 0 ); } public function getStatus(): StatusEnum { return $this->status; } public function getUpdatedAt(): string { return $this->updatedAt; } }
import { Meta, StoryObj } from "@storybook/react"; import { CustomMantineSelect } from "./CustomMantineSelect"; const meta = { title: "Example/CustomMantineSelect", component: CustomMantineSelect, parameters: { layout: "centered", }, args: { label: "Label", placeholder: "Pick something...", emptyLabel: "Nothing found", data: [ { label: "Item 1", value: 1 }, { label: "Item 2", value: 2 }, { label: "Item 3", value: 3 }, ], classNames: { root: "w-full", }, }, tags: ["autodocs"], } satisfies Meta<typeof CustomMantineSelect>; export default meta; type Story = StoryObj<typeof meta>; export const Default: Story = { name: "Single", args: { value: 1, }, }; export const Multiple: Story = { args: { value: [1, 2], multiple: true, renderValueOutside: true, }, }; export const MultipleSearchable: Story = { args: { value: [1, 2], multiple: true, renderValueOutside: true, searchable: true, }, };
package com.zmr.login.controller; import com.zmr.login.entity.User; import com.zmr.login.entity.UserAccount; import com.zmr.login.entity.UserInfo; import com.zmr.login.mapper.UserMapper; import com.zmr.login.service.IUserService; import com.zmr.main.exception.InsertException; import com.zmr.main.exception.UserNotFoundException; import com.zmr.main.exception.UsernameDuplicatedException; import com.zmr.main.response.ResponseResult; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * @author franciszmr * @version 1.0 * @date 2023/11/15 20:18 * @description */ @RestController @RequestMapping("/user") public class UserController { @Resource private UserMapper userMapper; @Resource private IUserService userService; @GetMapping("/{userName}") public ResponseResult findByUserName(@PathVariable String userName) { return ResponseResult.success(userMapper.findByUserName(userName)); } @PostMapping("/register") public ResponseResult register(@RequestBody User user) { try { userService.register(user); System.out.println(ResponseResult.success("register successfully!")); return ResponseResult.success("register successfully!"); } catch (UsernameDuplicatedException e) { return ResponseResult.fail(400, "user name has occupied!"); } catch (InsertException e) { return ResponseResult.fail(502, "register with exception!"); } } @PostMapping("/login") public ResponseResult login(@RequestBody User user) { try { userService.login(user); System.out.println("login success!"); // redirect to index page //return "redirect:/index"; return ResponseResult.success("Login success!"); } catch (UserNotFoundException e) { return ResponseResult.fail(400, "Login failed!"); //return "redirect:/myLogin"; } } @PostMapping("/getUserInfo") public ResponseResult getUserInfo(@RequestBody UserAccount userAccount) { UserInfo userInfo = userService.getUserInfo(userAccount); return ResponseResult.success(userInfo); } }
class Intcode: def __init__(self, code: list[int]): self.code = code self.crs = 0 self.input = 0 self.output = 0 self.opcode = 0 self.mode = '000' self.should_return_output = False def parse_mode(self, mode): mode_as_string = str(mode).zfill(5) return int(mode_as_string[-2:]), mode_as_string[0:3] def parse_io_parameters(self): pos = self.crs + 1 return self.code[pos] if self.mode[2] == '0' else pos def parse_jmp_parameters(self): tst_pos = self.code[self.crs + 1] jmp_pos = self.code[self.crs + 2] tst = self.code[tst_pos] if self.mode[2] == '0' else tst_pos jmp = self.code[jmp_pos] if self.mode[1] == '0' else jmp_pos return tst, jmp def parse_op_parameters(self): lhs_pos = self.code[self.crs + 1] rhs_pos = self.code[self.crs + 2] res_pos = self.crs + 3 lhs = self.code[lhs_pos] if self.mode[2] == '0' else lhs_pos rhs = self.code[rhs_pos] if self.mode[1] == '0' else rhs_pos out_pos = self.code[res_pos] if self.mode[0] == '0' else res_pos return lhs, rhs, out_pos def handle_addition(self): lhs, rhs, res = self.parse_op_parameters() result = lhs + rhs self.code[res] = result self.crs += 4 def handle_multiplication(self): lhs, rhs, res = self.parse_op_parameters() result = lhs * rhs self.code[res] = result self.crs += 4 def handle_input(self): res_pos = self.parse_io_parameters() self.code[res_pos] = self.input self.crs += 2 def handle_output(self): res_pos = self.parse_io_parameters() out = self.code[res_pos] self.output = out if self.output != 0: print("error") self.crs += 2 def handle_jump_if_true(self): tst, jmp = self.parse_jmp_parameters() if tst != 0: self.crs = jmp else: self.crs += 3 def handle_jump_if_false(self): tst, jmp = self.parse_jmp_parameters() if tst == 0: self.crs = jmp else: self.crs += 3 def handle_less_than(self): lhs, rhs, pos = self.parse_op_parameters() if lhs < rhs: self.code[pos] = 1 else: self.code[pos] = 0 self.crs += 4 def handle_equals(self): lhs, rhs, pos = self.parse_op_parameters() if lhs == rhs: self.code[pos] = 1 else: self.code[pos] = 0 self.crs += 4 def modify(self, pos, val): self.code[pos] = val def load(self, code: list[int]): self.code = code def return_output(self): self.should_return_output = True def run(self): self.crs = 0 while self.code[self.crs] != 99: self.opcode, self.mode = self.parse_mode(self.code[self.crs]) match self.opcode: case 1: self.handle_addition() case 2: self.handle_multiplication() case 3: self.handle_input() case 4: self.handle_output() case 5: self.handle_jump_if_true() case 6: self.handle_jump_if_false() case 7: self.handle_less_than() case 8: self.handle_equals() case 99: break if self.should_return_output: return self.output else: return self.code[0]
#!/usr/bin/perl -w use Test::More tests => 19; use strict; BEGIN { $| = 1; unshift @INC, '../blib/lib'; unshift @INC, '../blib/arch'; unshift @INC, '.'; chdir 't' if -d 't'; use_ok ('Games::Resource'); } can_ok ('Games::Resource', qw/ open config /); my $cfg = Games::Resource::config(); is (ref($cfg), 'HASH', 'config returns hash'); is ($cfg->{language}, 'en', 'en is default'); Games::Resource::config( { resource_files => [ 'books' ] } ); $cfg = Games::Resource::config(); is (join(", ", @{$cfg->{resource_files}}), 'books', 'set books'); ############################################################################## # open() tests my $FILE = Games::Resource::open ( 'test.txt' ); cmp_file($FILE,'test.txt'); $FILE = Games::Resource::open ( 'book1.txt' ); cmp_file($FILE,'book1.txt'); $FILE = Games::Resource::open ( 'books', 'book2.txt' ); # just so cmp_file($FILE,'books/book2.txt'); $FILE = Games::Resource::open ( 'books', 'book3.txt' ); # w/ lang=en cmp_file($FILE,'books/book2.txt'); $FILE = Games::Resource::open ( 'books/book4.txt' ); # in zipfile cmp_file($FILE,'books/book4.txt'); ############################################################################## sub cmp_file { my $file = shift; my $name = shift; is (ref($file), 'Games::Resource'); if (defined $file) { my $FILE = $file->handle(); my $doc = ''; if (ref($FILE) eq 'GLOB') { binmode $FILE; while (<$FILE>) { $doc .= $_; } is ($doc, "Test\ntest\n", "$name opened and read"); } $doc = $file->contents(); is ($doc, "Test\ntest\n", "$name contents()"); } else { isnt ($file ||'undef', 'undef', "$name not found?"); } }
--- title: 工作流过程参考 seo-title: Workflow Process Reference description: 工作流过程参考 seo-description: null uuid: de367aa8-4580-4810-b665-2a7b521e36ca contentOwner: User products: SG_EXPERIENCEMANAGER/6.4/SITES topic-tags: extending-aem content-type: reference discoiquuid: dbdf981f-791b-4ff7-8ca8-039d0bdc9c92 exl-id: c828302c-54ad-4171-89d1-f77f4d836277 source-git-commit: c5b816d74c6f02f85476d16868844f39b4c47996 workflow-type: tm+mt source-wordcount: '1175' ht-degree: 2% --- # 工作流过程参考{#workflow-process-reference} >[!CAUTION] > >AEM 6.4已结束扩展支持,本文档将不再更新。 有关更多详细信息,请参阅 [技术支助期](https://helpx.adobe.com/cn/support/programs/eol-matrix.html). 查找支持的版本 [此处](https://experienceleague.adobe.com/docs/). AEM提供了几个可用于创建工作流模型的流程步骤。 对于内置步骤未涵盖的任务,还可以添加自定义流程步骤(请参阅 [创建工作流模型](/help/sites-developing/workflows-models.md))。 ## 过程特性 {#process-characteristics} 对于每个过程步骤,描述了以下特征。 ### Java类或ECMA路径 {#java-class-or-ecma-path} 流程步骤由Java类或ECMAScript定义。 * 对于Java类进程,提供完全限定的类名称。 * 对于ECMAScript,会提供脚本的路径。 ### 有效负荷 {#payload} 有效负载是工作流实例对其执行操作的实体。 有效负载由启动工作流实例的上下文隐式选择。 例如,如果将工作流应用于AEM页面 *P* then *P* 会随着工作流的进行逐步传递,每个步骤都可以选择在执行时执行 *P* 在某种程度上。 在最常见的情况下,有效负载是存储库中的JCR节点(例如,AEM页面或资产)。 JCR节点有效负载作为JCR路径或JCR标识符(UUID)的字符串传递。 在某些情况下,有效负载可能是JCR属性(作为JCR路径传递)、URL、二进制对象或通用Java对象。 对有效负载采取行动的单个进程步骤通常期望有特定类型的有效负载,或根据有效负载类型采取不同的行动。 对于下面描述的每个流程,都描述了预期的有效负载类型(如果有)。 ### 参数 {#arguments} 某些工作流会处理接受管理员在设置工作流步骤时指定的参数。 参数在 **进程参数** 属性 **属性** 工作流编辑器窗格。 对于下面描述的每个过程,参数字符串的格式以简单的EBNF语法进行描述。 例如,以下表示参数字符串由一个或多个以逗号分隔的对组成,其中每对都由名称(即字符串)和值(用双冒号分隔)组成: ``` args := name '::' value [',' name '::' value]* name := /* A string */ value := /* A string */ ``` ### 超时 {#timeout} 在此超时时间段后,工作流步骤不再可操作。 某些工作流进程会遵守超时,而对于其他工作流进程,则不会应用超时,因此会被忽略。 ### 权限 {#permissions} 传递给的会话 `WorkflowProcess` 由服务用户为工作流进程服务提供支持,该服务在存储库的根下具有以下权限: * `jcr:read` * `rep:write` * `jcr:versionManagement` * `jcr:lockManagement` * `crx:replicate` 如果这组权限不足以满足您的 `WorkflowProcess` 实施,则必须使用具有所需权限的会话。 要实现此目的,建议使用创建的具有所需权限子集的必要(但最小)服务用户。 >[!CAUTION] > >如果您从AEM 6.2之前的版本升级,则可能需要更新实施。 > >在以前的版本中,管理员会话被传递到 `WorkflowProcess` 实施和之后可以拥有对存储库的完全访问权限,而无需定义特定的ACL。 > >权限现在定义如下([权限](#permissions))。 与更新实施的推荐方法相同。 > >当代码更改不可行时,还会出于向后兼容性目的提供短期解决方案: > >* 使用Web控制台( `/system/console/configMgr` 找到 **AdobeGranite工作流配置服务** > >* 启用 **工作流进程旧版模式** > >这将还原为向提供管理员会话的旧行为 `WorkflowProcess` 实施,并再次提供对整个存储库的无限制访问。 ## 工作流控制流程 {#workflow-control-processes} 以下进程不会对内容执行任何操作。 它们用于控制工作流本身的行为。 ### AbsoluteTimeAutoAdvancer(绝对时间自动提前器) {#absolutetimeautoadvancer-absolute-time-auto-advancer} 的 `AbsoluteTimeAutoAdvancer` (绝对时间自动提前器)进程的行为与 **AutoAdvancer**,但是它会在给定的时间和日期超时,而不是在给定的时长后超时。 * **Java类**: `com.adobe.granite.workflow.console.timeout.autoadvance.AbsoluteTimeAutoAdvancer` * **负载**:无。 * **参数**:无。 * **超时**:达到设置的时间和日期后,处理超时。 ### AutoAdvancer(Auto Advancer) {#autoadvancer-auto-advancer} 的 `AutoAdvancer` 进程会自动将工作流推进到下一步。 如果有多个可能的下一步(例如,如果存在OR拆分),则此流程将沿 *默认路线*,如果已指定,则不会高级工作流。 * **Java类**: `com.adobe.granite.workflow.console.timeout.autoadvance.AutoAdvancer` * **负载**:无。 * **参数**:无。 * **超时**:在设置的时长后,处理超时。 ### ProcessAssembler(进程汇编程序) {#processassembler-process-assembler} 的 `ProcessAssembler` 进程在单个工作流步骤中按顺序执行多个子进程。 使用 `ProcessAssembler`,在工作流中创建此类型的单个步骤,并设置其参数以指示要执行的子进程的名称和参数。 * **Java类**: `com.day.cq.workflow.impl.process.ProcessAssembler` * **负载**:DAM资产、AEM页面或无有效负载(取决于子流程的要求)。 * **参数**: ``` args := arg [',' arg] arg := processname ['::' processargs] processname := /* A fully qualified Java Class or absolute repository path to an ECMAScript */ processargs := processarg [';' processarg]* processarg := '[' nobracketprocessarg ']' | nobracketprocessarg nobracketprocessarg := listitem [':' listitem]* listitem := /* A string */ ``` * **超时**:尊重。 例如: * 从资产中提取元数据。 * 创建三个指定大小的缩略图。 * 从资产创建JPEG图像,假定资产最初既不是GIF也不是PNG(在这种情况下,不会创建JPEG)。 * 设置资产的上次修改日期。 ```shell com.day.cq.dam.core.process.ExtractMetadataProcess, com.day.cq.dam.core.process.CreateThumbnailProcess::[140:100];[48:48];[319:319:false], com.day.cq.dam.core.process.CreateWebEnabledImageProcess::dimension:1280:1280;mimetype:image/jpeg, com.day.cq.dam.core.process.AssetSetLastModifiedProcess ``` ## 基本流程 {#basic-processes} 以下流程执行简单任务或作为示例。 >[!CAUTION] > >您 ***必须*** 不会更改 `/libs` 路径。 > >这是因为 `/libs` 在下次升级实例时被覆盖(在应用修补程序或功能包时可能会被覆盖)。 ### 删除 {#delete} 将删除给定路径上的项目。 * **ECMAScript路径**: `/libs/workflow/scripts/delete.ecma` * **负载**:JCR路径 * **参数**:无 * **超时**:已忽略 ### noop {#noop} 这是空进程。 它不执行任何操作,但会记录调试消息。 * **ECMAScript路径**: `/libs/workflow/scripts/noop.ecma` * **负载**:无 * **参数**:无 * **超时**:已忽略 ### rule-false {#rule-false} 这是一个返回的空进程 `false` 在 `check()` 方法。 * **ECMAScript路径**: `/libs/workflow/scripts/rule-false.ecma` * **负载**:无 * **参数**:无 * **超时**:已忽略 ### 样本 {#sample} 这是ECMAScript过程示例。 * **ECMAScript路径**: `/libs/workflow/scripts/sample.ecma` * **负载**:无 * **参数**:无 * **超时**:已忽略 ### urlcaller {#urlcaller} 这是一个调用给定URL的简单工作流流程。 通常,URL将是对执行简单任务的JSP(或其他Servlet等效项)的引用。 此过程仅应在开发和演示期间使用,而不应在生产环境中使用。 参数指定URL、登录名和密码。 * **ECMAScript路径**: `/libs/workflow/scripts/urlcaller.ecma` * **负载**:无 * **参数**: ``` args := url [',' login ',' password] url := /* The URL to be called */ login := /* The login to access the URL */ password := /* The password to access the URL */ ``` 例如:`http://localhost:4502/my.jsp, mylogin, mypassword` * **超时**:已忽略 ### LockProcess {#lockprocess} 锁定工作流的有效负载。 * **Java类:** `com.day.cq.workflow.impl.process.LockProcess` * **负载:** JCR_PATH和JCR_UUID * **参数:** 无 * **超时:** 已忽略 该步骤在下列情况下无效: * 负载已锁定 * 有效负荷节点不包含jcr:content子节点 ### UnlockProcess {#unlockprocess} 解锁工作流的有效负载。 * **Java类:** `com.day.cq.workflow.impl.process.UnlockProcess` * **负载:** JCR_PATH和JCR_UUID * **参数:** 无 * **超时:** 已忽略 该步骤在下列情况下无效: * 有效负载已解锁 * 有效负荷节点不包含jcr:content子节点 ## 版本控制流程 {#versioning-processes} 以下进程将执行与版本相关的任务。 ### CreateVersionProcess {#createversionprocess} 创建工作流有效负载的新版本(AEM页面或DAM资产)。 * **Java类**: `com.day.cq.wcm.workflow.process.CreateVersionProcess` * **负载**:引用页面或DAM资产的JCR路径或UUID * **参数**:无 * **超时**:受尊重
package com.uteev.convertorusdtobtc.presentation import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.ListAdapter import com.squareup.picasso.Picasso import com.uteev.convertorusdtobtc.R import com.uteev.convertorusdtobtc.domain.pojo.coininfo.ListOfDatum import com.uteev.convertorusdtobtc.domain.pojo.coinprice.CoinPriceInfo class CoinListAdapter : ListAdapter<CoinPriceInfo, CoinItemViewHolder>(CoinItemDiffCallBack()) { var onCoinItemClick : ((CoinPriceInfo) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CoinItemViewHolder { val layout = R.layout.item_coin val view = LayoutInflater.from(parent.context).inflate(layout, parent, false) return CoinItemViewHolder(view) } override fun onBindViewHolder(viewHolder: CoinItemViewHolder, position: Int) { val item = getItem(position) viewHolder.view.setOnClickListener { onCoinItemClick?.invoke(item) } viewHolder.tvFsTs.text = item.fromSymbol + " / " + item.toSymbol viewHolder.tvPrice.text = item.price.toString() viewHolder.tvTimeLastUpdate.text = item.getFormattedTime() Picasso.get().load(item.getFullImageUrl()).into(viewHolder.iLogoCoin) } companion object { const val MAX_SIZE_POOL = 15 } }
package face import ( "bytes" "compress/gzip" "encoding/base64" "encoding/json" "io" "log" "sync" ) /* * face for data zip * @author <AndyZhou> * @mail <diudiu8848@163.com> */ //global variable for single instance var ( _zip *Zip _zipOnce sync.Once ) //face info type Zip struct { } //get single instance func GetZip() *Zip { _zipOnce.Do(func() { _zip = NewZip() }) return _zip } //construct func NewZip() *Zip { //self init this := &Zip{ } return this } //un compress data func (f *Zip) UnZipData(resp []byte) (bool, map[string]interface{}) { var ( outBytes bytes.Buffer ) //base64 decode respStr := string(resp) byteData, err := base64.StdEncoding.DecodeString(respStr) if err != nil { return false, nil } //zip un compress byteReader := bytes.NewReader(byteData) gzipReader, err := gzip.NewReader(byteReader) if err != nil { return false, nil } _, err = io.Copy(&outBytes, gzipReader) if err != nil { return false, nil } //json decode result := make(map[string]interface{}) err = json.Unmarshal(outBytes.Bytes(), &result) if err != nil { return false, nil } return true, result } //compress data func (f *Zip) ZipData(req map[string]interface{}) (bool, []byte) { var ( in bytes.Buffer ) //basic check if req == nil || len(req) <= 0 { return false, nil } //json encode jsonByte, err := json.Marshal(req) if err != nil { return false, nil } //zip compress zipWriter := gzip.NewWriter(&in) _, err = zipWriter.Write(jsonByte) if err != nil { zipWriter.Close() return false, nil } err = zipWriter.Close() if err != nil { log.Println("err:", err.Error()) } //base64 encode out := make([]byte, 2048) base64.StdEncoding.Encode(out, in.Bytes()) return true, out }
import { Task } from "../entities/Task"; import { Arg, Int, Mutation, Query, Resolver } from "type-graphql"; import { UserInputError } from "apollo-server-express"; @Resolver() export class TaskResolver { @Query(() => String) hello(): string { return "Hello World!"; } @Query(() => [Task]) tasks(): Promise<Task[]> { return Task.find({}); } @Query(() => Task, { nullable: true }) task( @Arg("id", () => Int) id: number ): Promise<Task | null> { return Task.findOne({ where: { id } }); } @Mutation(() => Task) createTask( @Arg("title", () => String) title: string ): Promise<Task> { return Task.create({ title, isComplete: false }).save(); } @Mutation(() => Task) async deleteTask( @Arg("id", () => Int) id: number ): Promise<Task> { const task = await Task.findOne({ where: { id } }); if (!task) { throw new UserInputError(`Task with id ${id} not found`); } try { Task.delete({ id }); return task; } catch { throw new Error("Error deleting task"); } } @Mutation(() => Task, { nullable: true }) async updateTask( @Arg("id", () => Int) id: number, @Arg("isComplete", () => Boolean) isComplete: boolean ): Promise<Task> { const task = await Task.findOne({ where: { id } }); if (!task) { throw new UserInputError(`Task with id ${id} not found`); } try { Task.update({ id }, { isComplete }); return task; } catch { throw new Error("Error updating task"); } } }
import java.util.ArrayList; import java.util.List; /** * There are n kids with candies. You are given an integer array candies, * where each candies[i] represents the number of candies the ith kid has, * and an integer extraCandies, denoting the number of extra candies that you have. * * Return a boolean array result of length n, where result[i] is true if, * after giving the ith kid all the extraCandies, they will have the greatest * number of candies among all the kids, or false otherwise. * * Note that multiple kids can have the greatest number of candies. * * * * Example 1: * * Input: candies = [2,3,5,1,3], extraCandies = 3 * Output: [true,true,true,false,true] * Explanation: If you give all extraCandies to: * - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. * - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. * - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. * - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. * - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. * Example 2: * * Input: candies = [4,2,1,1,2], extraCandies = 1 * Output: [true,false,false,false,false] * Explanation: There is only 1 extra candy. * Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. * Example 3: * * Input: candies = [12,1,12], extraCandies = 10 * Output: [true,false,true] * * * Constraints: * * n == candies.length * 2 <= n <= 100 * 1 <= candies[i] <= 100 * 1 <= extraCandies <= 50 */ public class KidsWithGreatestCandies { public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) { int maxCandies = 0; for (int i =0; i< candies.length; i++) { maxCandies = Math.max(maxCandies, candies[i]); } List<Boolean> results = new ArrayList<>(); for (int i =0; i< candies.length; i++) { results.add(candies[i]+extraCandies>=maxCandies); } return results; } }
// Copyright 2022 Google LLC // // 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. import { doc, getDocs, getDoc, collection, query, startAfter, orderBy, limit, where, endBefore, collectionGroup, limitToLast } from "firebase/firestore"; import VALUES from './values.js' import React from 'react'; import { createRoot } from 'react-dom/client'; import Jobs from './components/Jobs'; // For the jobs table const container = document.querySelector('#render-content'); const tableRoot = createRoot(container); // build the table using the query passed export async function makeTable(db, thequery, first, status) { // show loader let jobs; // check if it is a status sort if not do a normal query if(status != null && status != "") { if (status == "failed") { jobs = await getFailedJobs(thequery); } else if(status == "search") { if(VALUES.searchTerm.trim() == "") { thequery = query(collectionGroup(VALUES.db, VALUES.collection), orderBy('created', 'desc'), limit(10)); jobs = await getNormalJobs(db, thequery, true); } else { jobs = await getSearchJobs(); } } else { jobs = await getOtherJobs(status, thequery); } } else { jobs = await getNormalJobs(db, thequery, first); } // check if the user can go to the next page canAdvance(jobs.length) // set the html of the table setHtml(jobs) } // go to next page export function nextPage() { let nextQuery = null; // make sure that the last query is not null and user can advance if(VALUES.last != null && VALUES.canAdvance) { // get the specific query and start after the last value in the current table nextQuery = getQuery(startAfter(VALUES.last)) VALUES.direction = 0; // if query is found then make the table if(nextQuery != false) { $('#p2').show(); makeTable(VALUES.db, nextQuery, false, VALUES.status) // increment the span holding the page number $('.pages span').html(parseInt($('.pages span').html()) + 1); } } } export function prevPage() { let prevQuery = null; // make sure that prevFirst exists and that the page number is not 1 if(VALUES.first != null && parseInt($('.pages span').html()) != 1) { // get the query, but this time start at the prev first prevQuery = getQuery(endBefore(VALUES.first), limitToLast(10)) VALUES.direction = 1; // if the query is found, then make the table if(prevQuery != false) { $('#p2').show(); makeTable(VALUES.db, prevQuery, false, VALUES.status) // increment the span holding the page number $('.pages span').html(parseInt($('.pages span').html()) - 1); } } } export function filterJobs() { let status = $('#status').val(); let created = $('#created').val(); let updated = $('#updated').val(); if (status == "" && created == "" && updated == "") { // reset the table to original values $('.pages span').html(0); $('#p2').show(); makeTable(VALUES.db, query(collection(VALUES.db, VALUES.collection), orderBy('created', 'desc'), limit(10))) $('.filter-side-holder').hide() } else { let filterQuery = null; let createdTimestamp = null; let updatedTimestamp = null; if(created != "") { // get the firebase timestamp so it can compare dates let date = new Date(); date.setHours(date.getHours() - created) createdTimestamp = Timestamp.fromDate(date) } if(updated != "") { // get the firebase timestamp so it can compare dates let date = new Date(); date.setHours(date.getHours() - updated) updatedTimestamp = Timestamp.fromDate(date) } VALUES.status = status; VALUES.createdTimestamp = createdTimestamp; VALUES.updatedTimestamp = updatedTimestamp; VALUES.direction = 0; // the different ways the query can be made if(status != "" && created == "" && updated == "") { filterQuery = query(collectionGroup(VALUES.db, "levels"), where("status", "==", status), orderBy('created', 'desc'), limit(10)) } else if (status != "" && created != "") { filterQuery = query(collectionGroup(VALUES.db, "levels"), where("status", "==", status), where("created", ">=", createdTimestamp), orderBy('created', 'desc'), limit(10)) } else if (status != "" && updated != "") { filterQuery = query(collectionGroup(VALUES.db, "levels"), where("status", "==", status), where("updated", ">=", updatedTimestamp), orderBy('updated', 'desc'), limit(10)) } else if (updated != "" && created == "") { filterQuery = query(collection(VALUES.db, VALUES.collection), where("updated", ">=", updatedTimestamp), orderBy('updated', 'desc'), limit(10)) } else if (created != "" && updated == "") { filterQuery = query(collection(VALUES.db, VALUES.collection), where("created", ">=", createdTimestamp), orderBy('created', 'desc'), limit(10)) } // make the table if(filterQuery != null) { $('.pages span').html(1); $('#p2').show(); makeTable(VALUES.db, filterQuery, true, status) } } } // get the specific query for either prevPage or nextPage and startAt or startAfter marker function getQuery(marker, limitMarker=limit(10)) { // cleans the code later on const status = VALUES.status; const createdTimestamp = VALUES.createdTimestamp; const updatedTimestamp = VALUES.updatedTimestamp; const searchTerm = VALUES.searchTerm; const db = VALUES.db if(searchTerm == "") { if (status == "" && createdTimestamp == null && updatedTimestamp == null) { return query(collection(db, VALUES.collection), orderBy('created', 'desc'), marker, limitMarker) } else if(status != "" && createdTimestamp == null && updatedTimestamp == null) { return query(collectionGroup(db, "levels"), where("status", "==", status), orderBy('created', 'desc'), marker, limitMarker) } else if (status != "" && createdTimestamp != null) { return query(collectionGroup(db, "levels"), where("status", "==", status), where("created", ">=", createdTimestamp), orderBy('created', 'desc'), marker, limitMarker) } else if (status != "" && updatedTimestamp != null) { return query(collectionGroup(db, "levels"), where("status", "==", status), where("updated", ">=", updatedTimestamp), orderBy('updated', 'desc'), marker, limitMarker) } else if (updatedTimestamp != null && createdTimestamp == null) { return query(collection(db, VALUES.collection), where("updated", ">=", updatedTimestamp), orderBy('updated', 'desc'), marker, limitMarker) } else if (createdTimestamp != null && updatedTimestamp == null) { return query(collection(db, VALUES.collection), where("created", ">=", createdTimestamp), orderBy('created', 'desc'), marker, limitMarker) } return false } else { return query(collection(db, VALUES.collection), where('name', ">=", searchTerm), where("name", "<", searchTerm + 'z'), orderBy('name', 'desc'), marker, limitMarker) } } function getOverrallStatus(subjobs) { const statusCount = { "running": 0, "scheduled": 0, "finished": 0 }; for(let i=0; i < subjobs.length; i++) { statusCount[subjobs[i].status.toLowerCase()] += 1; if(subjobs[i].status.toLowerCase() == "failed") { return "failed"; } } return decideStatus(statusCount); } function decideStatus(statusCount) { if (statusCount['running'] == 0 && statusCount['scheduled'] == 0 && statusCount['finished'] > 0) { // if all of them are finished, job is done return "finished"; } else if (statusCount['running'] > 0) { // if any of the jobs are running, then the job is running return "running"; } else if (statusCount['running'] == 0 && statusCount['scheduled'] > 0) { // if no jobs running, then the status is scheduled return "scheduled"; } // return scheduled if not in any of these return "scheduled"; } // a nice function to calculate how long ago the last update was export function timeSince(date) { const seconds = Math.floor((new Date() - date) / 1000); let interval = seconds / 31536000; if (interval > 1) { return Math.floor(interval) + " years"; } interval = seconds / 2592000; if (interval > 1) { return Math.floor(interval) + " months"; } interval = seconds / 86400; if (interval > 1) { return Math.floor(interval) + " days"; } interval = seconds / 3600; if (interval > 1) { return Math.floor(interval) + " hours"; } interval = seconds / 60; if (interval > 1) { return Math.floor(interval) + " minutes"; } return Math.floor(seconds) + " seconds"; } async function getNormalJobs(db, thequery, first) { // get all the jobs returned from the query let values = await getJobs(db, thequery) // values[0] is the jobs, values[1] is the last job, values[2] is the first job let jobs = values[0]; // set values for pagination setValues(values[1], values[2], first) return jobs; } async function getSearchJobs() { let jobs = [] let docIds = VALUES.searchTerm.split(";") for(var i = 0; i < docIds.length; i++) { const document = await getDoc(doc(VALUES.db, VALUES.collection, docIds[i])) if(document.exists) { jobs.push(await populateJob(VALUES.db, document)) } } return jobs; } async function getOtherJobs(status, thequery) { let filled = false; let jobs = []; let levelDocs = []; let completedDocs = []; // top level jobs that have already been checked let lastDoc; while(!filled) { let response = await getOtherDocs(jobs, levelDocs, completedDocs, lastDoc, thequery, status); jobs = response[0]; levelDocs = response[1]; completedDocs = response[2]; filled = response[3]; lastDoc = response[4]; } return jobs; } async function getOtherDocs(jobs, levelDocs, completedDocs, lastDoc, thequery, status) { let numberOfDocs = jobs.length; if(lastDoc != null) { if(VALUES.direction != null && VALUES.direction == 1) { thequery = getQuery(endBefore(VALUES.first), limitToLast(10)) } else { thequery = getQuery(startAfter(lastDoc)); } } const querySnapshot = await getDocs(thequery); let filled = false; let last; if(querySnapshot.empty) { return [jobs, [], [], true] } else { filled = await Promise.all(querySnapshot.docs.map(async (document) => { let parentDoc = document.ref.parent.path.split('/')[1] // get top level document if(completedDocs.includes(parentDoc) != true) { completedDocs.push(parentDoc); const aggregators = await getAggregators(VALUES.db, parentDoc, []); let subjobs = []; // fill in the subjobs field with the jobs logs subjobs = await getLevels(VALUES.db, parentDoc, aggregators[0], subjobs) subjobs = await getLevels(VALUES.db, parentDoc, aggregators[1], subjobs) if(getOverrallStatus(subjobs) == status) { numberOfDocs += 1; // when # of docs goes over amount stop it if(numberOfDocs > 10) { VALUES.last = document; VALUES.first = levelDocs[0]; return true; } let job = {}; job.logs = subjobs; job.status = status; job.id = parentDoc; const topLevelDoc = await getDoc(doc(VALUES.db, VALUES.collection, parentDoc)); let vals = topLevelDoc.data(); job.created = vals.created; job.updated = vals.updated; if(vals.updated == null) { job.updated = job.created; } jobs.push(job); levelDocs.push(document); } } })); filled = filled.at(-1) if(filled == undefined) { filled = false; } if(!filled) { last = querySnapshot.docs[querySnapshot.docs.length-1]; VALUES.last = last; if(levelDocs.length >= 1) { VALUES.first = levelDocs[0]; } } } return [jobs, levelDocs, completedDocs, filled, last]; } async function getFailedJobs(thequery) { let filled = false let docs = []; let levelDocs = []; let lastDoc; while(!filled) { let response = await getFailedDocs(docs, levelDocs, lastDoc, thequery); docs = response[0]; levelDocs = response[1]; filled = response[2]; lastDoc = response[3]; } let jobs = []; for(var i = 0; i < docs.length; i++) { const document = await getDoc(doc(VALUES.db, VALUES.collection, docs[i])) jobs.push(await populateJob(VALUES.db, document)); } return jobs; } async function getFailedDocs(failedDocs, levelDocs, lastDoc, thequery) { let numberOfFailedDocs = failedDocs.length; if(lastDoc != null){ if(VALUES.direction != null && VALUES.direction == 1) { thequery = getQuery(endBefore(VALUES.first), limitToLast(10)) } else { thequery = getQuery(startAfter(lastDoc)); } } const querySnapshot = await getDocs(thequery); let filled = false; let last; if(querySnapshot.empty) { return [failedDocs, [], true] } else { filled = await Promise.all(querySnapshot.docs.map(async (document) => { let parentDoc = document.ref.parent.path.split('/')[1] // get top level document if(failedDocs.includes(parentDoc) != true) { failedDocs.push(parentDoc); levelDocs.push(document); numberOfFailedDocs += 1; // when # of failed docs reaches ten, exit promise and save position if(numberOfFailedDocs >= 10) { VALUES.last = document; VALUES.first = levelDocs[0]; return true; } } })); filled = filled.at(-1) if(filled == undefined) { filled = false; } if(!filled) { last = querySnapshot.docs[querySnapshot.docs.length-1]; VALUES.last = last; VALUES.first = levelDocs[0]; } } return [failedDocs, levelDocs, filled, last]; } // get the 10 jobs that are requested and the last document async function getJobs(db, thequery) { let jobs = []; const querySnapshot = await getDocs(thequery); // populate the jobs array jobs = await populateJobs(db, jobs, querySnapshot); // get the last document. used for pagination const last = querySnapshot.docs[querySnapshot.docs.length-1]; // get the first document. used for pagination const first = querySnapshot.docs[0] return [jobs, last, first]; } // populate the jobs variable using an async method and in parallel async function populateJobs(db, jobs, querySnapshot) { await Promise.all(querySnapshot.docs.map(async (doc) => { jobs.push(await populateJob(db, doc)); })); return jobs; } async function populateJob(db, doc) { let job = {}; job.id = doc.id; let vals = doc.data(); job.created = vals.created; job.updated = vals.updated; if(vals.updated == null) { job.updated = job.created; } // fill in the aggregators field with the aggregators const aggregators = await getAggregators(db, doc.id, []); let subjobs = []; // fill in the subjobs field with the jobs logs subjobs = await getLevels(db, doc.id, aggregators[0], subjobs) subjobs = await getLevels(db, doc.id, aggregators[1], subjobs) job.logs = subjobs; if(vals.overrallStatus != null) { // job finished or failed job.status = vals.overrallStatus; } else { // job scheduled or running or top level document hasn't been updated job.status = getOverrallStatus(subjobs) } return job; } // function to get the logs for a given document and aggregator // and fill in the subjobs array and return it back async function getLevels(db, docId, aggregator, subjobs) { const levelSnapshot = await getDocs(collection(db, VALUES.collection, docId, "aggregators", aggregator, "levels")); levelSnapshot.forEach((doc) => { let log = {}; log.level = aggregator+"-"+doc.id; let vals = doc.data(); log.created = vals.created; log.message = vals.message; log.result = vals.result; log.status = vals.status; log.total_levels = vals.total_levels; log.updated = vals.updated; subjobs.push(log) }); return subjobs; } async function getAggregators(db, docId, aggregators) { const aggregatorSnapshot = await getDocs(collection(db, VALUES.collection, docId, "aggregators")); aggregatorSnapshot.forEach((doc) => { aggregators.push(doc.id); }) return aggregators; } // change a firestore timestamp to a date and then format it export function formatTime(timestamp, updated) { let date = timestamp.toDate(); // if updated get the amount of time it has been since the timestamp if (updated) { return timeSince(date) + " ago"; } let day = date.getDate(); let month = date.getMonth() + 1; let year = date.getFullYear(); let hour = date.getHours(); let minute = date.getMinutes(); let seconds = date.getSeconds(); return month + "/" + day + "/" + year + " at " + hour + ":" + minute + ":" + seconds } function setValues(last, first, set) { VALUES.last = last; // if it is the very first page then prevfirst is equal to first if(set) { VALUES.prevFirst = first } else { VALUES.prevFirst = VALUES.first; } VALUES.first = first; } function canAdvance(length) { // if it is less than 10, that means that there are no more jobs left in query // so pagination should stop if(length < 10) { VALUES.canAdvance = false; } else { VALUES.canAdvance = true; } } function setHtml(jobs) { if(window.jobsTable == undefined) { tableRoot.render(<Jobs jobs={jobs} />); } else { window.jobsTable.updateJobs(jobs) } }
class Solution: def maxProfit(self, prices: list[int]) -> int: # O(n) time compexity # O(1) space complexity l,r = 0,1 profit = 0 while r < len(prices): profit = max(profit,prices[r]-prices[l]) if prices[l] < prices[r]: r+=1 elif prices[l] >= prices[r]: l = r r += 1 return profit s = Solution() print(s.maxProfit([7,1,5,3,6,4])) print(s.maxProfit([7,6,4,3,1])) print(s.maxProfit([1,2]))
#pragma once #include "AABB.h" #include "BroadphaseOutput.h" #include <vector> #include <unordered_map> #include <cassert> #include <stack> namespace phyz { template <typename T> class AABBTree { public: enum CostFunction { VOLUME, SURFACE_AREA }; AABBTree(double aabb_margin_size, CostFunction cost_type=VOLUME) : aabb_margin_size(aabb_margin_size), root(nullptr), cost_type(cost_type) {} ~AABBTree() { if (root == nullptr) return; std::vector<Node*> delete_queue{ root }; while (!delete_queue.empty()) { Node* to_delete = delete_queue.back(); delete_queue.pop_back(); if (!to_delete->is_leaf) { assert(to_delete->left != nullptr && to_delete->right != nullptr); delete_queue.push_back(to_delete->left); delete_queue.push_back(to_delete->right); } delete to_delete; } } void add(T object, bool object_static, int object_id, const AABB& object_bounds) { Node* new_leaf = new Node(object, object_static, object_id, object_bounds, aabb_margin_size, cost_type); object_node_map[object_id] = new_leaf; if (root == nullptr) { root = new_leaf; return; } Node* best_candidate = nullptr; AABB best_candidate_aabb; double best_candidate_cost = std::numeric_limits<double>::infinity(); std::vector<InsertionCandidate> candidates = { InsertionCandidate{root, 0} }; while (!candidates.empty()) { InsertionCandidate c = candidates.back(); candidates.pop_back(); //impossible to be better if (c.inherited_cost >= best_candidate_cost) continue; AABB candidate_aabb = AABB::combine(new_leaf->node_aabb, c.node->node_aabb); double direct_cost = cost_type == VOLUME ? AABB::volume(candidate_aabb) : AABB::surfaceArea(candidate_aabb); double candidate_cost = c.inherited_cost + direct_cost; if (candidate_cost < best_candidate_cost) { best_candidate = c.node; best_candidate_aabb = candidate_aabb; best_candidate_cost = candidate_cost; } if (!c.node->is_leaf) { assert(c.node->left != nullptr && c.node->right != nullptr); double child_inherited_cost = c.inherited_cost + direct_cost - c.node->cost_value; candidates.push_back({ c.node->left, child_inherited_cost }); candidates.push_back({ c.node->right, child_inherited_cost }); } } assert(best_candidate != nullptr); Node* new_parent = new Node(); if (best_candidate == root) { root = new_parent; } else { Node* old_parent = best_candidate->parent; Node** old_parent_child_slot = (old_parent->left == best_candidate) ? &old_parent->left : &old_parent->right; //replace new_parent in slot where best_canditate was new_parent->parent = old_parent; *old_parent_child_slot = new_parent; } //attach new_leaf and best_candidate as children of new_parent new_parent->left = best_candidate; best_candidate->parent = new_parent; new_parent->right = new_leaf; new_leaf->parent = new_parent; //propogate AABB changes that result from this haveAncestorsRecalculateAABB(new_leaf); //rebalance tree as necessary rebalanceAncestors(new_leaf); } void remove(unsigned int object_id) { assert(object_node_map.find(object_id) != object_node_map.end()); Node* to_remove_leaf = object_node_map[object_id]; object_node_map.erase(object_id); if (to_remove_leaf == root) { root = nullptr; //edge case 1 } else { Node* parent = to_remove_leaf->parent; Node* sibling = (parent->left == to_remove_leaf) ? parent->right : parent->left; if (parent == root) { root = sibling; sibling->parent = nullptr; //edge case 2 } else { Node* grandparent = parent->parent; Node** grandparent_child_slot = (grandparent->left == parent) ? &grandparent->left : &grandparent->right; sibling->parent = grandparent; *grandparent_child_slot = sibling; haveAncestorsRecalculateAABB(sibling); //general case } delete parent; } delete to_remove_leaf; } void update(T object, bool object_static, int object_id, const AABB& updated_object_bounds) { assert(object_node_map.find(object_id) != object_node_map.end()); Node* object_leaf = object_node_map[object_id]; if (!AABB::isAABBContained(updated_object_bounds, object_leaf->node_aabb)) { remove(object_id); add(object, object_static, object_id, updated_object_bounds); } else { object_leaf->leaf_object_true_aabb = updated_object_bounds; } } std::vector<Pair<T>> getAllCollisionCandidates() const { static int prev_colpair_size = 0; if (root == nullptr || root->is_leaf) return std::vector<Pair<T>>(); std::vector<Pair<T>> col_pairs; col_pairs.reserve(prev_colpair_size); std::vector<TreePair> search_candidates = { {root->left, root->right} }; while (!search_candidates.empty()) { TreePair tp = search_candidates.back(); search_candidates.pop_back(); if (!tp.n1->is_leaf && !tp.n1->internal_collision_checked_flag) { search_candidates.push_back({ tp.n1->left, tp.n1->right }); tp.n1->internal_collision_checked_flag = true; } if (!tp.n2->is_leaf && !tp.n2->internal_collision_checked_flag) { search_candidates.push_back({ tp.n2->left, tp.n2->right }); tp.n2->internal_collision_checked_flag = true; } if (!tp.n1->is_leaf && !tp.n2->is_leaf) { //non-leaf x non-leaf if (AABB::intersects(tp.n1->node_aabb, tp.n2->node_aabb)) { search_candidates.push_back({ tp.n1->left, tp.n2->left }); search_candidates.push_back({ tp.n1->left, tp.n2->right }); search_candidates.push_back({ tp.n1->right, tp.n2->left }); search_candidates.push_back({ tp.n1->right, tp.n2->right }); } } else if (tp.n1->is_leaf && !tp.n2->is_leaf) { //leaf x non-leaf if (AABB::intersects(tp.n1->leaf_object_true_aabb, tp.n2->node_aabb)) { search_candidates.push_back({ tp.n1, tp.n2->left }); search_candidates.push_back({ tp.n1, tp.n2->right }); } } else if (!tp.n1->is_leaf && tp.n2->is_leaf) { //non-leaf x leaf if (AABB::intersects(tp.n1->node_aabb, tp.n2->leaf_object_true_aabb)) { search_candidates.push_back({ tp.n1->left, tp.n2 }); search_candidates.push_back({ tp.n1->right, tp.n2 }); } } else { //leaf x leaf if (AABB::intersects(tp.n1->leaf_object_true_aabb, tp.n2->leaf_object_true_aabb)) { col_pairs.push_back(Pair<T>(tp.n1->leaf_object, tp.n1->leaf_object_id, tp.n2->leaf_object, tp.n2->leaf_object_id)); } } } //reset internal_collision_checked_flags if (root != nullptr && !root->is_leaf) { std::vector<Node*> queue{ root }; while (!queue.empty()) { Node* n = queue.back(); queue.pop_back(); assert(!n->is_leaf); n->internal_collision_checked_flag = false; if (!n->left->is_leaf) queue.push_back(n->left); if (!n->right->is_leaf) queue.push_back(n->right); } } prev_colpair_size = col_pairs.size(); return col_pairs; } std::vector<T> getCollisionCandidatesWith(AABB target) const { if (root == nullptr) return std::vector<T>(); std::vector<T> out; std::vector<Node*> node_candidates = { root }; while (!node_candidates.empty()) { Node* n = node_candidates.back(); node_candidates.pop_back(); if (n->is_leaf) { if (AABB::intersects(n->leaf_object_true_aabb, target)) out.push_back(n->leaf_object); } else { if (AABB::intersects(n->node_aabb, target)) { node_candidates.push_back(n->left); node_candidates.push_back(n->right); } } } return out; } std::vector<T> raycastHitCandidates(mthz::Vec3 ray_origin, mthz::Vec3 ray_dir) const { if (root == nullptr) return std::vector<T>(); std::vector<T> out; std::vector<Node*> node_candidates = { root }; while (!node_candidates.empty()) { Node* n = node_candidates.back(); node_candidates.pop_back(); if (n->is_leaf) { if (AABB::rayIntersectsAABB(n->leaf_object_true_aabb, ray_origin, ray_dir)) out.push_back(n->leaf_object); } else { if (AABB::rayIntersectsAABB(n->node_aabb, ray_origin, ray_dir)) { node_candidates.push_back(n->left); node_candidates.push_back(n->right); } } } return out; } private: class Node { public: Node() : parent(nullptr), left(nullptr), right(nullptr), is_leaf(false), leaf_object_id(-1), cost_value(0) {} Node(T object, bool object_static, int object_id, const AABB& object_aabb, double aabb_margin_size, CostFunction cost_type) : parent(nullptr), left(nullptr), right(nullptr), is_leaf(true), leaf_object(object), leaf_object_id(object_id), leaf_object_true_aabb(object_aabb) { double margin = object_static ? 0 : aabb_margin_size; setAABB(AABB{ object_aabb.min - mthz::Vec3(margin, margin, margin), object_aabb.max + mthz::Vec3(margin, margin, margin) }, cost_type); } void setAABB(const AABB& aabb, CostFunction cost_type, double aabb_cost = -1) { node_aabb = aabb; if (aabb_cost == -1) { cost_value = cost_type == VOLUME ? AABB::volume(aabb) : AABB::surfaceArea(aabb); } else { cost_value = aabb_cost; } } void calculateAndUpdateAABB(CostFunction cost_type) { //there is no reason this function should be used with leaf nodes. Probably implies a bug assert(!is_leaf); //non-leaf nodes should always have two children assert(left != nullptr && right != nullptr); setAABB(AABB::combine(left->node_aabb, right->node_aabb), cost_type); } static void swpNodes(Node* n1, Node* n2) { Node* n1_og_parent = n1->parent; Node* n2_og_parent = n2->parent; assert(n1_og_parent != nullptr && n2_og_parent != nullptr); Node** n1_child_slot = (n1_og_parent->left == n1) ? &n1_og_parent->left : &n1_og_parent->right; Node** n2_child_slot = (n2_og_parent->left == n2) ? &n2_og_parent->left : &n2_og_parent->right; *n1_child_slot = n2; *n2_child_slot = n1; n1->parent = n2_og_parent; n2->parent = n1_og_parent; } Node* parent; Node* left; Node* right; //in case of non-leaf is the merged bounding box of the two children nodes //in case of leaf node, is the enlarged bounding box of the object AABB node_aabb; double cost_value; //for use in checking all collisions bool internal_collision_checked_flag = false; bool is_leaf; T leaf_object; int leaf_object_id; AABB leaf_object_true_aabb; }; //structs used in some functions struct InsertionCandidate { Node* node; double inherited_cost; }; struct TreePair { Node* n1; Node* n2; }; CostFunction cost_type; double aabb_margin_size; std::unordered_map<unsigned int, Node*> object_node_map; Node* root; void haveAncestorsRecalculateAABB(Node* altered_node) { Node* current = altered_node->parent; while (current != nullptr) { current->calculateAndUpdateAABB(cost_type); current = current->parent; } } void rebalanceAncestors(Node* altered_leaf) { assert(altered_leaf->is_leaf); Node* current = altered_leaf->parent; while (current != nullptr && current->parent != nullptr) { Node* sibling = (current->parent->left == current) ? current->parent->right : current->parent->left; if (sibling != nullptr) { //cl: swap current with sibling->left //sr: swap sibling with current->right AABB cl_aabb, cr_aabb, sl_aabb, sr_aabb; double cl_cost, cr_cost, sl_cost, sr_cost; //current cannot be a leaf as we are following parent pointers sl_aabb = AABB::combine(current->right->node_aabb, sibling->node_aabb); sr_aabb = AABB::combine(current->left->node_aabb, sibling->node_aabb); sl_cost = cost_type == VOLUME ? AABB::volume(sl_aabb) : AABB::surfaceArea(sl_aabb); sr_cost = cost_type == VOLUME ? AABB::volume(sr_aabb) : AABB::surfaceArea(sr_aabb); if (sibling->is_leaf) { //inf worst possible, disqualifies the nodes cl_cost = std::numeric_limits<double>::infinity(); cr_cost = std::numeric_limits<double>::infinity(); } else { cl_aabb = AABB::combine(sibling->right->node_aabb, current->node_aabb); cr_aabb = AABB::combine(sibling->left->node_aabb, current->node_aabb); cl_cost = cost_type == VOLUME ? AABB::volume(cl_aabb) : AABB::surfaceArea(cl_aabb); cr_cost = cost_type == VOLUME ? AABB::volume(cr_aabb) : AABB::surfaceArea(cr_aabb); } double cl_cost_change = cl_cost - sibling->cost_value; double cr_cost_change = cr_cost - sibling->cost_value; double sl_cost_change = sl_cost - current->cost_value; double sr_cost_change = sr_cost - current->cost_value; double min = std::min<double>(cl_cost_change, std::min<double>(cr_cost_change, std::min<double>(sl_cost_change, sr_cost_change))); if (min >= 0) { /*no swap is best*/ } else if (min == cl_cost_change) { Node::swpNodes(current, sibling->left); sibling->setAABB(cl_aabb, cost_type, cl_cost); } else if (min == cr_cost_change) { Node::swpNodes(current, sibling->right); sibling->setAABB(cr_aabb, cost_type, cr_cost); } else if (min == sl_cost_change) { Node::swpNodes(sibling, current->left); current->setAABB(sl_aabb, cost_type, sl_cost); } else { Node::swpNodes(sibling, current->right); current->setAABB(sr_aabb, cost_type, sr_cost); } } current = current->parent; } } }; }
import React, { useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { CircularProgressbar, buildStyles } from "react-circular-progressbar"; import { updateFail, updateSucess, clearError, } from "../../../redux/function/userSlice.js"; import { getStorage, ref, uploadBytesResumable, getDownloadURL, } from "firebase/storage"; import { useNavigate } from "react-router-dom"; import { app } from "../../../firebase/firebase.js"; import { set } from "mongoose"; function CreateItems() { const [imageData, setImageData] = useState(null); const [imageFileURL, setImageFileURL] = useState(null); const [updateMessage, setUpdateMessage] = useState(""); const [error, setError] = useState(null); const [imageUploadError, setImageUploadError] = useState(null); const [formData, setFormData] = useState({}); const [successMessage, setsuccessMessage] = useState(null); const [imageUploadProgres, setImageUploadProgress] = useState(0); const dispatch = useDispatch(); const navigate = useNavigate(); const { currentUser } = useSelector((state) => state.user); const handleImageChange = (e) => { const imageFile = e.target.files[0]; if (imageFile) { setImageData(imageFile); } }; const handleImageUpload = async (e) => { e.preventDefault(); try { if (!imageData) { setImageUploadError("Please select Menu image"); setTimeout(() => { setImageUploadError(null); }, 3000); return; } const storage = getStorage(app); const fileName = new Date().getTime() + imageData.name; const storageRef = ref(storage, fileName); const uploadTask = uploadBytesResumable(storageRef, imageData); uploadTask.on( "state_changed", (snapshot) => { const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; setImageUploadProgress(progress.toFixed(0)); }, (error) => { setImageUploadError("Could not upload image (image < 2mb)"); setTimeout(() => { setImageUploadError(null); setImageUploadProgress(0); }, 3000); }, () => { getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { setUpdateMessage("Image uploaded successfully"); setFormData({ ...formData, menuImage: downloadURL }); setImageUploadProgress(0); setImageFileURL(downloadURL); setTimeout(() => { setImageUploadError(null); setUpdateMessage(null); }, 3000); }); } ); } catch (error) { setError("Error in uploading image (image_size < 2mb)"); } }; const handleChange = (e) => { setFormData({ ...formData, [e.target.id]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); if (Object.keys(formData).length === 0) { return; } try { const res = await fetch(`/api/menu/createMenu`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }); const data = await res.json(); if (!res.ok) { setError(data.message); } setsuccessMessage(data.message.message); setTimeout(() => { setError(null); setsuccessMessage(null); navigate(`/menu/${data.status.menu.slug}`); }, 4000); } catch (error) { setError(error.message); setTimeout(() => { setError(null); }, 4000); } }; return ( <div className="overflow-hidden p-3 dark:glass-container md:w-2/4 md:px-14 min-h-screen mx-auto bg-gray-100 dark:bg-[#131315] rounded-lg shadow-md "> <div className="mb-4 flex items-center justify-center rounded-lg py-2"> <h1 className="text-center font-heading_font text-3xl my-4 text-[#27374D] dark:text-[#DDE6ED]"> Item Details </h1> </div> <form onSubmit={handleSubmit}> <div> {/* Item Name */} <div className="mt-4 gap-6 dark:text-gray-500 font-body_font space-y-4 md:grid md:grid-cols-2 md:space-y-0"> <div className="w-full"> <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" htmlFor="firstName" > Item Name<span className="text-red-700">*</span> </label> <input id="menuName" type="text" className="flex h-10 w-full rounded-md border border-black/30 bg-transparent px-3 py-2 text-sm dark:border-gray-600 dark:placeholder:text-gray-700 text-gray-400 focus:outline-none focus:ring-1 focus:ring-black/30 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50" placeholder="Item Name" onChange={handleChange} /> </div> {/* Item Price */} <div className="w-full"> <label htmlFor="menuPrice" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Price </label> <input id="menuPrice" type="text" inputMode="numeric" pattern="[0-9]*" className="flex h-10 w-full rounded-md border border-black/30 bg-transparent text-gray-400 px-3 py-2 text-sm dark:border-gray-600 dark:placeholder:text-gray-700 focus:outline-none focus:ring-1 focus:ring-black/30 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50" placeholder="Item Price" onChange={handleChange} /> </div> {/* Item Category */} <div className="w-full"> <label htmlFor="menuCategory" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Category </label> <input id="menuCategory" type="text" className="flex h-10 w-full rounded-md border border-black/30 bg-transparent px-3 py-2 text-sm dark:border-gray-600 dark:placeholder:text-gray-700 text-gray-400 focus:outline-none focus:ring-1 focus:ring-black/30 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50" placeholder="Item Category" onChange={handleChange} /> </div> {/* Item type */} <div className="w-full"> <label htmlFor="menuType" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Type </label> <select id="menuType" className="input-field border hover:shadow-md hover:rounded-xl px-4 py-2 rounded-md w-full focus:outline-none text-gray-600" onChange={handleChange} > <option value="">Select Item Type</option> <option value="Outdoor">OutDoor</option> <option value="Indoor">InDoor</option> <option value="E-Sports">E-Sports</option> </select> </div> {/* Item Discount */} <div className="w-full"> <label htmlFor="itemDiscount" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Discount </label> <input id="menuDiscount" type="text" className="flex h-10 w-full rounded-md border border-black/30 bg-transparent px-3 py-2 text-sm dark:border-gray-600 dark:placeholder:text-gray-700 text-gray-400 focus:outline-none focus:ring-1 focus:ring-black/30 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50" placeholder="Item Discount" onChange={handleChange} /> </div> {/*Item Status */} <div className="w-full"> <label htmlFor="menuType" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Status </label> <select id="menuStatus" className="flex h-10 w-full rounded-md border border-black/30 bg-transparent px-3 py-2 text-sm dark:border-gray-600 dark:placeholder:text-gray-700 text-gray-400 focus:outline-none focus:ring-1 focus:ring-black/30 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50" onChange={handleChange} > <option value="">Select Item Status</option> <option value="In Stock">In Stock</option> <option value="Out of Stock">Out of Stock</option> </select> </div> {/* Description */} <div className="col-span-2 grid"> <div className="w-full"> <label htmlFor="itemDescription" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Description </label> <input id="menuDescription" type="text" className="flex h-10 w-full rounded-md border border-black/30 bg-transparent px-3 py-2 text-sm dark:border-gray-600 dark:placeholder:text-gray-700 text-gray-400 focus:outline-none focus:ring-1 focus:ring-black/30 focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50" placeholder="Item Description" onChange={handleChange} /> </div> </div> {/* Image */} <div className="col-span-2 grid"> <label htmlFor="menuType" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" > Item Image </label> <div className="flex flex-col md:flex-row md:gap-8"> <div className="flex md:gap-8"> <div> <input id="menuImage" type="file" accept="image/*" className="input-field border hover:shadow-md hover:rounded-xl px-4 rounded-md w-full focus:outline-none text-gray-600" placeholder="Item Image" onChange={handleImageChange} /> </div> <div className="mx-4 px-6 border rounded bg-black text-gray-200 flex items-center"> <button type="submit" className="" onClick={handleImageUpload} > {imageUploadProgres ? ( <div className="w-14 h-14 "> <CircularProgressbar value={imageUploadProgres} text={`${imageUploadProgres || 0} % `} styles={buildStyles({ pathColor: "#00ff00", textColor: "#00ff00", trailColor: "#E52A3D", rotation: 0.25, })} /> </div> ) : ( " Upload" )} </button> </div> </div> </div> {imageUploadError && ( <div className="text-center text-red-600 p-3 rounded-md"> {imageUploadError} </div> )} {updateMessage && ( <div className="text-center text-green-500 p-3 font-bold rounded-md"> {updateMessage} </div> )} </div> </div> </div> <div className="pt-6 flex gap-4"> <button type="submit" className="bg-[#27374D] form-box text-white font-semibold py-2 px-4 rounded-md w-full" > Create Item </button> </div> </form> </div> ); } export default CreateItems;
import router from './routers' import useStore from '@/store' import { logOut } from '@/store/modules/user' import Config from '@/settings' import NProgress from 'nprogress' // progress bar import 'nprogress/nprogress.css' // progress bar style import { getToken } from '@/utils/auth' // getToken from cookie // import { buildMenus } from '@/api/system/menu' import { filterAsyncRouter } from '@/store/modules/permission' import { generatorDynamicRouter } from '@/router/formatterRouer' // import { asyncRouter } from './routers' // import { getComponentName } from '@/router/formatterRouer' NProgress.configure({ showSpinner: false }) // NProgress Configuration const whiteList = ['/login', '/download'] // no redirect whitelist router.beforeEach((to, from, next) => { const { user } = useStore() if (to.meta.title) { document.title = to.meta.title + ' - ' + Config.title } NProgress.start() if (getToken()) { // 已登录且要跳转的页面是登录页 if (to.path === '/login') { next({ path: '/' }) NProgress.done() } else { if (user.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息 let flag = user.GetInfo() if (flag) { // 动态路由,拉取菜单 loadMenus(next, to) } else { user.LogOut().then(() => { logOut() }) } // user // .GetInfo() // .then(() => { // // 拉取user_info // // 动态路由,拉取菜单 // loadMenus(next, to) // }) // .catch(() => { // user.LogOut().then(() => { // // location.reload() // 为了重新实例化vue-router对象 避免bug // logOut() // }) // }) } else if (user.loadMenus) { // 登录时未拉取菜单,在此处拉取 // 修改成false,防止死循环 user.updateLoadMenus() loadMenus(next, to) } else { next() } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入 next() } else { next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页 NProgress.done() } } }) export const loadMenus = (next: any, to: any) => { const { user, permission } = useStore() // 保存菜单(下面会 改变路由的配置,所以要深拷贝) let _menus1 = JSON.parse(JSON.stringify(user.menus)) // 刷新页面,根据缓存的activeApps 显示对应的菜单 let currentService = sessionStorage.getItem('activeApps') if (currentService) { _menus1.map((item: any) => { if (item.application === currentService || item.application === undefined) { item.hidden = false } else { item.hidden = true } }) } new Promise((resolve) => { generatorDynamicRouter(_menus1).then((routers: any) => { user.homeMenus = routers const sdata = JSON.parse(JSON.stringify(routers)) const rdata = JSON.parse(JSON.stringify(routers)) const sidebarRoutes = filterAsyncRouter(sdata) const rewriteRoutes = filterAsyncRouter(rdata, false) // console.log(rewriteRoutes) permission.GenerateRoutes(rewriteRoutes).then(() => { rewriteRoutes.forEach((item) => { router.addRoute(item) // 动态添加可访问路由表 }) // 这句不能放到上面,会导致页面加载不到,空白 rewriteRoutes.push({ path: '*', redirect: '/404', meta: { hidden: true } }) next({ ...to, replace: true }) permission.SetSidebarRouters(sidebarRoutes) resolve }) }) }) // }) } router.afterEach(() => { NProgress.done() // finish progress bar })
<style lang="less"> </style> <template> <view class="page"> <head></head> <button @tap="startRecord">{{isStart === 0 ? '点击开始录音' : isStart === 1 ? '正在录音' : isStart === 2 ? '暂停录音' : isStart === 3 ? '继续录音' : '录音完成'}}</button> <button @tap="playRecording" v-show="isStart === 4">播放录音</button> </view> </template> <script> import wepy from '@wepy/core' wepy.page({ data: { recorderManager: '', // 创建录音 innerAudioContext: '', // 创建音频 isStart: 0, // 0没有开始录音,1开始录音,2暂停录音,3继续录音,4录音完成 option: { duration: 10000, frameSize: 50 }, isRecordingPlay: false }, methods: { startRecord () { let that = this if (that.isStart === 1) { that.recorderManager.pause() } else { wx.getSetting({ success (res) { // 已授权 if (res.authSetting['scope.record']) { that.isStart = 1 that.recorderManager.start(that.option) } else { // 未授权 wx.authorize({ scope: 'scope.record', success: res => { // 授权成功 console.log(res) }, fail: error => { // 拒绝授权 wx.showModal({ title: '温馨提示', content: `若点击不授权,将无法使用录音`, cancelText: '不授权', cancelColor: '#999', confirmText: '授权', confirmColor: '#00c6ff', success(res) { if (res.confirm) { wx.openSetting({ // 确定再次授权 success(res) { console.log(res.authSetting) } }) } else if (res.cancel) { console.log('用户点击取消') } } }) } }) } } }) } }, playRecording () { if (this.isRecordingPlay) { this.isRecordingPlay = false this.innerAudioContext.pause() } else { this.isRecordingPlay = true this.innerAudioContext.play() } } }, onLoad () { this.recorderManager = wx.getRecorderManager() this.innerAudioContext = wx.createInnerAudioContext() // 监听录音暂停事件 this.recorderManager.onPause(() => { this.isStart = 3 }) // 监听录音继续录制 this.recorderManager.onResume(res => { this.isStart = 3 console.log(res + 'resume') }) // 监听录音结束事件 this.recorderManager.onStop(res => { this.isStart = 4 console.log(res) this.innerAudioContext.src = res.tempFilePath }) // 监听录音完成指定帧大小文件事件 this.recorderManager.onFrameRecorded(res => { const { frameBuffer } = res console.log('frameBuffer.byteLength', frameBuffer.byteLength) }) this.innerAudioContext.onPlay(() => { console.log('播放录音') }) } }) </script> <config> { navigationBarTitleText: '录音', navigationStyle: 'custom', usingComponents: { head: '~@/components/test-head' } } </config>
import React, { useEffect, useState } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faThumbsUp, faShare, faComment } from '@fortawesome/free-solid-svg-icons'; import '../css/posts.css'; function PostCard({ post }) { return ( <div className="post-card"> <div className="post-header"> <div className="user-info"> {post.AuthorProfileImgUrl ? (<img src={post.AuthorProfileImgUrl} alt={`shashi's Icon`} className="profile-image-small" />): (<img src="https://upload.wikimedia.org/wikipedia/commons/2/2c/Default_pfp.svg" alt={`shashi's Icon`} className="profile-image-small" />)} <div className="user-details"> <h2 className="user-name">{post.AuthorName}</h2> <p className="user-handle">@{post.AuthorHandle}</p> </div> </div> </div> <div className="post-content"> <p>{post.writeUp}</p> {post.post && ( <img src={post.imageUrl} alt="Post" className="post-image" /> )} {/* Display other post details as needed */} </div> <div className="post-actions"> <button> <FontAwesomeIcon icon={faThumbsUp} /> Like </button> <button> <FontAwesomeIcon icon={faComment} /> Comment </button> <button> <FontAwesomeIcon icon={faShare} /> Share </button> </div> </div> ); } export default PostCard;
import http from 'http'; import { postgraphile, PostGraphileOptions } from 'postgraphile'; import { NodePlugin } from 'graphile-build'; import SimplifyInflectorPlugin from '@graphile-contrib/pg-simplify-inflector'; import ManyToManyPlugin from '@graphile-contrib/pg-many-to-many'; import FilterPlugin from 'postgraphile-plugin-connection-filter'; // import FederationPlugin from 'postgraphile-federation-plugin'; // import InflectorPlugin from './plugins/InflectorPlugin'; // import TimeoutPlugin from './plugins/TimeoutPlugin'; // import ExtendSchemaPlugin from './plugins/ExtendSchemaPlugin'; import DefaultOrderPlugin from './plugins/DefaultOrderPlugin'; const isDevelopment = process.env.NODE_ENV !== 'production'; const config = { port: process.env.BIND_PORT || '3000', } const logger = console; async function run() { const provideGraphiql = true; // isDevelopment // see https://www.graphile.org/postgraphile/usage-library/#recommended-options const options: PostGraphileOptions = { graphiql: provideGraphiql, enhanceGraphiql: true, dynamicJson: true, setofFunctionsContainNulls: false, ignoreRBAC: false, ignoreIndexes: true, enableQueryBatching: true, legacyRelations: 'omit', showErrorStack: 'json', // regular Plugins appendPlugins: [ SimplifyInflectorPlugin, FilterPlugin, ManyToManyPlugin, // InflectorPlugin, ExtendSchemaPlugin, DefaultOrderPlugin ], skipPlugins: [ NodePlugin ], simpleCollections: 'only', graphileBuildOptions: { // https://github.com/graphile-contrib/postgraphile-plugin-connection-filter#performance-and-security connectionFilterComputedColumns: false, connectionFilterSetofFunctions: false, connectionFilterLists: false, pgOmitListSuffix: true, }, /* pluginHook: makePluginHook([ TimeoutPlugin({ timeout: config.requestTimeout }) ]), */ // see watchPg at https://www.graphile.org/postgraphile/usage-library/#api-postgraphilepgconfig-schemaname-options // https://github.com/graphile/graphile-engine/blob/master/packages/graphile-build-pg/res/watch-fixtures.sql watchPg: isDevelopment || process.env.WATCH_PG === 'true', disableQueryLog: !isDevelopment, allowExplain: isDevelopment, extendedErrors: isDevelopment ? ['hint', 'detail', 'errcode'] : ['errcode'], disableDefaultMutations: true, // pgDefaultRole: 'viewer', exportGqlSchemaPath: isDevelopment ? 'schema.graphql' : undefined, // eslint-disable-line no-undefined pgSettings: { timezone: process.env.TZ || 'Europe/Amsterdam' } } http .createServer(postgraphile( process.env.DATABASE_URL || 'postgres:///openstreetmap' || 'postgres://user:pass@host:5432/dbname', "public", options )) .listen(config.port || 3000); const endpoint = `http://localhost:${config.port}`; logger.info(`🚀 GraphQL server running on port ${config.port}`); logger.info(`GraphQL running at: ${endpoint}/graphql`); logger.info( `GraphiQL running at: ${provideGraphiql ? `${endpoint}/graphiql` : 'DISABLED'}` ); } run();
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>Virgo V</title> <meta charset="ISO-8859-1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <header th:insert="~{fragments/general :: header(authentication=${authentication})}"></header> <div class="container mt-5 pt-4"> <h1 class="text-center"> Category List</h1> <div> <table class="table table-hover table-responsive-xl"> <thead> <tr> <th>Name</th> <th>Description</th> <th>Update</th> <th>Delete</th> </tr> </thead> <tbody> <tr th:each="category : ${categories}"> <td th:text="${category.name}"></td> <td th:text="${category.description}"></td> <td><a th:href="@{/admin/category/showFormForUpdateCategory/{id}(id=${category._id})}" class="btn btn-info">Update</a></td> <td><a th:href="@{/admin/category/deleteCategory/{id}(id=${category._id})}" th:data-confirm-delete="|Are you sure you want to delete ${category.name} category?|" onclick="if (!confirm(this.getAttribute('data-confirm-delete'))) return false" class="btn btn-danger">Delete</a></td> </tr> </tbody> </table> <div class=" p-2 float-right"><a th:href="@{/admin/category/showFormForCreatingCategory}" class="btn btn-info"> Add Category </a></div> </div> </div> </body> </html>
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('tg_users_datas', function (Blueprint $table) { # Habilitar unicamente valores positivos $table->bigInteger('az_identifier')->unsigned()->primary(); # Campos informativos para auditorias $table->timestamp('az_created_at'); $table->bigInteger('az_created_by'); $table->timestamp('az_modified_at'); $table->bigInteger('az_modified_by'); # Campos relevantes para almacenacmiento $table->string('cd_email')->nullable(); $table->string('cd_login')->nullable(); $table->string('cd_password')->nullable(); # Habilitar unicamente valores positivos $table->bigInteger('sy_authentication')->unsigned(); $table->bigInteger('sy_session_time')->unsigned(); $table->bigInteger('tg_role_data')->unsigned(); # Relaciones de llaves foraneas con otras tablas de la base de datos $table->foreign('tg_role_data')->references('az_identifier')->on('tg_roles_datas'); //$table->foreign('sy_authentication')->references('az_identifier')->on('sy_authentications'); //$table->foreign('sy_session_time')->references('az_identifier')->on('sy_sessions_times'); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('tg_users_datas'); } };
# MIT License # Copyright (c) 2021 Izhar Ahmad # 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 NONINFRINGEMENT. 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. from __future__ import annotations from neocord.dataclasses.flags.base import BaseFlags, flag class UserFlags(BaseFlags): """ Represents the public flags of a user that appear on the user accounts. They are often referred as "badges" in the UI and are shown on the profile of users. This class is not generally created manually. Attributes ---------- value: :class:`int` The raw integer value of flags. discord_employee: :class:`bool` Returns ``True`` if the user is a Discord staff. partnered_server_owner: :class:`bool` Returns ``True`` if the user has the partnered server owner badge. hypesquad_events: :class:`bool` Returns ``True`` if the user has Hypesquad events badge. bug_hunter_level_1: :class:`bool` Returns ``True`` if the user has the level one of bug hunter badge. house_bravery: :class:`bool` Returns ``True`` if the user's house is HypeSquad Bravery. house_brilliance: :class:`bool` Returns ``True`` if the user's house is HypeSquad Brilliance. house_balance: :class:`bool` Returns ``True`` if the user's house is HypeSquad Balance. early_supporter: :class:`bool` Returns ``True`` if the user has the "Early Supporter" badge. team_user: :class:`bool` Returns ``True`` if user is a "team user". bug_hunter_level_2: :class:`bool` Returns ``True`` if the has the user level two on bug hunter badge. verified_bot: :class:`bool` Returns ``True`` if the has the user is a verified bot. early_verified_bot_developer: :class:`bool` Returns ``True`` if the has the "Early Verified Bot Developer" badge. discord_certified_moderator: :class:`bool` Returns ``True`` if the has the "Certified Discord Moderator" badge. """ VALID_FLAGS = { 'discord_employee', 'partnered_server_owner', 'hypesquad_events', 'bug_hunter_level_1', 'house_bravery', 'house_brilliance', 'house_balance', 'early_supporter', 'team_user', 'bug_hunter_level_2', 'verified_bot', 'early_verified_bot_developer', 'discord_certified_moderator' } def __init__(self, value: int): super().__init__(value=value) @flag def discord_employee(self) -> int: return 1 << 0 @flag def partnered_server_owner(self) -> int: return 1 << 1 @flag def hypesquad_events(self) -> int: return 1 << 2 @flag def bug_hunter_level_1(self) -> int: return 1 << 3 @flag def house_bravery(self) -> int: return 1 << 6 @flag def house_brilliance(self) -> int: return 1 << 7 @flag def house_balance(self) -> int: return 1 << 8 @flag def early_supporter(self) -> int: return 1 << 9 @flag def team_user(self) -> int: return 1 << 10 @flag def bug_hunter_level_2(self) -> int: return 1 << 14 @flag def verified_bot(self) -> int: return 1 << 16 @flag def early_verified_bot_developer(self) -> int: return 1 << 17 @flag def discord_certified_moderator(self) -> int: return 1 << 18
{% extends 'base.html' %} {% block title %}Blog Post{% endblock title %} {% block style %}{% endblock style %} {% block body %} <div class="container pb50 my-3"> <div class="row"> <div class="col-md-9 mb40"> <article> <img src="https://images.unsplash.com/photo-1455734729978-db1ae4f687fc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=80" alt="" class="img-fluid mb30"> <div class="post-content"> <h3>{{post.post_title}}</h3> <ul class="post-meta list-inline"> <li class="list-inline-item"> <i class="fa fa-user-circle-o"></i> <a href="#">{{post.post_author}}</a> </li> <li class="list-inline-item"> <i class="fa fa-calendar-o"></i> <a href="#">{{post.post_publish_date}}</a> </li> <li class="list-inline-item"> <i class="fa fa-tags"></i> <a href="#">{{post.post_category}}</a> </li> </ul> {{post.post_content}} <ul class="list-inline share-buttons"> <li class="list-inline-item">Share Post:</li> <li class="list-inline-item"> <a href="#" class="social-icon-sm si-dark si-colored-facebook si-gray-round"> <i class="fa fa-facebook"></i> <i class="fa fa-facebook"></i> </a> </li> <li class="list-inline-item"> <a href="#" class="social-icon-sm si-dark si-colored-twitter si-gray-round"> <i class="fa fa-twitter"></i> <i class="fa fa-twitter"></i> </a> </li> <li class="list-inline-item"> <a href="#" class="social-icon-sm si-dark si-colored-linkedin si-gray-round"> <i class="fa fa-linkedin"></i> <i class="fa fa-linkedin"></i> </a> </li> </ul> <hr class="mb40"> <h4 class="mb40 text-uppercase font500">About Author</h4> <div class="media mb40"> <i class="d-flex mr-3 fa fa-user-circle fa-5x text-primary"></i> <div class="media-body"> <h5 class="mt-0 font700">Jane Doe</h5> Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus. </div> </div> <hr class="mb40"> <h4 class="mb40 text-uppercase font500">Comments</h4> </div> </article> <!-- post article--> </div> <div class="col-md-3 mb40"> <!--/col--> <div class="mb40"> <h4 class="sidebar-title">Categories</h4> <ul class="list-unstyled categories"> <li><a href="#">Rent</a></li> <li><a href="#">Sale</a></li> <li class="active"><a href="#">Apartment</a> <ul class="list-unstyled"> <li><a href="#">Office</a></li> <li><a href="#">Godown</a></li> <li><a href="#">Gerage</a></li> </ul> </li> <li><a href="#">Top Rating</a></li> <li><a href="#">Trending</a></li> <li><a href="#">Newest Properties</a></li> </ul> </div> <!--/col--> <div> <h4 class="sidebar-title">Latest News</h4> <ul class="list-unstyled"> <li class="media"> <img class="d-flex mr-3 img-fluid" width="64" src="https://bootdey.com/img/Content/avatar/avatar1.png" alt="Generic placeholder image"> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="#">Lorem ipsum dolor sit amet</a></h5> April 05, 2017 </div> </li> <li class="media my-4"> <img class="d-flex mr-3 img-fluid" width="64" src="https://bootdey.com/img/Content/avatar/avatar2.png" alt="Generic placeholder image"> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="#">Lorem ipsum dolor sit amet</a></h5> Jan 05, 2017 </div> </li> <li class="media"> <img class="d-flex mr-3 img-fluid" width="64" src="https://bootdey.com/img/Content/avatar/avatar3.png" alt="Generic placeholder image"> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="#">Lorem ipsum dolor sit amet</a></h5> March 15, 2017 </div> </li> </ul> </div> </div> </div> </div> {% endblock body %}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" /> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" href="task2.css"> </head> <body> <div class="container-fluid c1"> <div class="container"> <div class="row"> <div class="col-md-8"> <div class="first"> <i class="fas fa-map-marker-alt"></i> <p> 9051 Constra Incorporate, USA</p> </div> </div> <div class="col-md-4"> <div class="second d-flex justify-content-lg-end justify-content-md-end justify-content-sm-center "> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> <i class="fab fa-github"></i> </div> </div> </div> </div> </div> <!-- end of top nav --> <div class="container-fluid c2"> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light sticky-top"> <div class="container-fluid"> <a class="navbar-brand" href="#"><img class="img-fluid" src="images/logo.png" alt=""></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ms-auto mb-2 mb-lg-0"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> HOME </a> <ul> <li><a class="dropdown-item" href="#">Home One</a></li> <hr> <li><a class="dropdown-item" href="#">Home Two</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> COMPANY </a> <ul> <li><a class="dropdown-item" href="#">About Us</a></li> <hr> <li><a class="dropdown-item" href="#">Our People</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> PROJECTS </a> <ul> <li><a class="dropdown-item" href="#">Projets All</a></li> <hr> <li><a class="dropdown-item" href="#">Project Single</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> SERVICES </a> <ul> <li><a class="dropdown-item" href="#">Services All</a></li> <hr> <li><a class="dropdown-item" href="#">Services Single</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> FEATURES </a> <ul> <li><a class="dropdown-item" href="#">TypoGraphy</a></li> <hr> <li><a class="dropdown-item" href="#"> 404</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> NEWS </a> <ul> <li><a class="dropdown-item" href="#">News Left</a></li> <hr> <li><a class="dropdown-item" href="#">News Right</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link"> CONTACT </a> </li> <button class="btn" type="submit">GET FREE QUOTE</button> </ul> </div> </div> </nav> </div> </div> <!-- end of nav --> <div class="container-fluid c3"> <!-- <div class="container"> <div class="row"> <div class="col-md-6"> <div class="only"> <h5>17 year of excellent</h5> <h2>Construction Industry</h2> <p>You have ideas, goals, and dreams. We have a culturally diverse, forward thinking team looking for talent like.</p> <button class="btn"> Know Us</button> </div> </div> </div> </div> --> <div id="carouselExampleIndicators" class="carousel slide position-relative" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="images/1.jpg" class="d-block w-100" alt="..."> <div class="only"> <h5>17 year of excellent</h5> <h2>Construction Industry</h2> <p>You have ideas, goals, and dreams. We have a culturally diverse, forward thinking <br> team looking for talent like.</p> <button class="btn"> Know Us</button> </div> </div> <div class="carousel-item"> <img src="images/bg.jpg" class="d-block w-100" alt="..."> <div class="only"> <h5>17 year of excellent</h5> <h2>Construction Industry</h2> <p>You have ideas, goals, and dreams. We have a culturally diverse, forward thinking <br> team looking for talent like.</p> <button class="btn"> Know Us</button> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> </div> <!-- end of c3 --> <div class="container-fluid c4"> <div class="container"> <div class="row"> <div class="col-md-6"> <p> WE UNDERSTAND YOUR NEEDS ON CONSTRUCTION</p> </div> <div class="col-md-6"> <div class="d-flex justify-content-sm-center justify-content-lg-end forend"> <button class="btn"> Know Us</button> </div> </div> </div> </div> </div> <!-- ------end of c4---- --> <div class="container-fluid c5"> <div class="container"> <div class="row"> <div class="col-lg-4"> <div class="img1"> <img src="images/i1.jpg" alt=""> </div> <div class="con"> <div class="img"> <img src="images/ii1.png" alt=""> </div> <div class="txt"> <h3>ZERO HARM EVERYDAY</h3> <p>You have ideas, goals, and dreams. <br> We have a culturally diverse, forward <br> thinking team looking for talent like. <br> Lorem ipsum dolor suscipit.</p> <a href="">&#8250; Learn More </a> </div> </div> </div> <div class="col-lg-4"> <div class="img1"> <img src="images/i2.jpg" alt=""> </div> <div class="con"> <div class="img"> <img src="images/ii2.png" alt=""> </div> <div class="txt"> <h3>VIRTUAL CONSTRUCTION</h3> <p>You have ideas, goals, and dreams. <br> We have a culturally diverse, forward <br> thinking team looking for talent like. <br> Lorem ipsum dolor suscipit.</p> <a href="">&#8250; Learn More </a> </div> </div> </div> <div class="col-lg-4"> <div class="img1"> <img src="images/i3.jpg" alt=""> </div> <div class="con"> <div class="img"> <img src="images/ii3.png" alt=""> </div> <div class="txt"> <h3>BUILD TO LAST</h3> <p>You have ideas, goals, and dreams. <br> We have a culturally diverse, forward <br> thinking team looking for talent like. <br> Lorem ipsum dolor suscipit.</p> <a href="">&#8250; Learn More </a> </div> </div> </div> </div> </div> </div> <!-- end of c5 --> <div class="container-fluid c6"> <div class="container"> <div class="row"> <div class="col-md-3 text-center"> <div class="al"> <img src="images/i1.png" alt=""> <h2>1789</h2> <h5>TOTAL PROJECTS</h5> </div> </div> <div class="col-md-3 text-center"> <div class="al"> <img src="images/i2.png" alt=""> <h2>647</h2> <h5>STAFF MEMBERS</h5> </div> </div> <div class="col-md-3 text-center"> <div class="al"> <img src="images/i3.png" alt=""> <h2>4000</h2> <h5>HOURS OF WORK</h5> </div> </div> <div class="col-md-3 text-center"> <div class="al"> <img src="images/i4.png" alt=""> <h2>44</h2> <h5>COUNTRIES EXPERIENCE</h5> </div> </div> </div> </div> </div> <!-- ----end of c6 --> <div class="container-fluid c7"> <div class="container"> <div class="bef text-center"> <h5>WE ARE SPECIALISTS IN</h5> <h2>WHAT WE DO</h2> </div> <div class="row"> <div class="col-lg-4 col-md-12"> <div class="con d-flex justify-content-lg-center justify-content-md-center"> <div class="img"> <img src="images/ii1.png" alt=""> </div> <div class="txt"> <h3>HOME CONSTRUCTION</h3> <p>Lorem ipsum dolor sit amet <br> consectetur adipiscing elit Integer <br> adipiscing erat </p> </div> </div> <div class="con d-flex justify-content-lg-center justify-content-md-center"> <div class="img"> <img src="images/ii2.png" alt=""> </div> <div class="txt"> <h3>BUILDING REMODELS</h3> <p>Lorem ipsum dolor sit amet <br> consectetur adipiscing elit Integer <br> adipiscing erat </p> </div> </div> <div class="con d-flex justify-content-lg-center justify-content-md-center"> <div class="img"> <img src="images/ii3.png" alt=""> </div> <div class="txt"> <h3>INTERIOR DESIGN</h3> <p>Lorem ipsum dolor sit amet <br> consectetur adipiscing elit Integer <br> adipiscing erat </p> </div> </div> </div> <div class="col-lg-4 text-center"> <img class="img-fluid im" src="images/man.jpg" alt=""> </div> <div class="col-lg-4"> <div class="con d-flex justify-content-lg-center justify-content-md-center"> <div class="img"> <img src="images/ii1.png" alt=""> </div> <div class="txt"> <h3>EXTERIOR DESIGN</h3> <p>Lorem ipsum dolor sit amet <br> consectetur adipiscing elit Integer <br> adipiscing erat </p> </div> </div> <div class="con d-flex justify-content-lg-center justify-content-md-center"> <div class="img"> <img src="images/ii2.png" alt=""> </div> <div class="txt"> <h3>RENOVATION</h3> <p>Lorem ipsum dolor sit amet <br> consectetur adipiscing elit Integer <br> adipiscing erat </p> </div> </div> <div class="con d-flex justify-content-lg-center justify-content-md-center"> <div class="img"> <img src="images/ii3.png" alt=""> </div> <div class="txt"> <h3>SAFETY MANAGEMENT</h3> <p>Lorem ipsum dolor sit amet <br> consectetur adipiscing elit Integer <br> adipiscing erat </p> </div> </div> </div> </div> </div> </div> <!-- end of c7 --> <div class="container-fluid c8"> <div class="befo text-center"> <h5>WORK OF EXCELLENCE</h5> <h2>RECENT PROJECTS</h2> </div> <div class="container"> <div class="list"> <ul class="d-lg-flex justify-content-lg-between"> <li class="one">Show All</li> <li>COMMERCIAL</li> <li>EDUCATION</li> <li>GOVENMENT</li> <li>INFRASTRUCTURE</li> <li>RESIDENTIAL</li> <li>HEATHCARE</li> </ul> </div> <div class="row"> <div class="col-lg-4 main p-0"> <img class="img-fluid" src="images/11.jpg" alt=""> <div class="onhov"> <div class="inside"> <h3>CAPITAL TELTWAY BUILDING</h3> <button class="btn">COMMERCIAL, INTERIORS</button> </div> </div> <button class="out">+</button> </div> <div class="col-lg-4 main p-0"> <img class="img-fluid" src="images/22.jpg" alt=""> <div class="onhov"> <div class="inside"> <h3>CAPITAL TELTWAY BUILDING</h3> <button class="btn">COMMERCIAL, INTERIORS</button> </div> </div> <button class="out">+</button> </div> <div class="col-lg-4 main p-0"> <img class="img-fluid" src="images/33.jpg" alt=""> <div class="onhov"> <div class="inside"> <h3>CAPITAL TELTWAY BUILDING</h3> <button class="btn">COMMERCIAL, INTERIORS</button> </div> </div> <button class="out">+</button> </div> </div> <div class="row"> <div class="col-lg-4 main p-0"> <img class="img-fluid" src="images/44.jpg" alt=""> <div class="onhov"> <div class="inside"> <h3>CAPITAL TELTWAY BUILDING</h3> <button class="btn">COMMERCIAL, INTERIORS</button> </div> </div> <button class="out">+</button> </div> <div class="col-lg-4 main p-0"> <img class="img-fluid" src="images/55.jpg" alt=""> <div class="onhov"> <div class="inside"> <h3>CAPITAL TELTWAY BUILDING</h3> <button class="btn">COMMERCIAL, INTERIORS</button> </div> </div> <button class="out">+</button> </div> <div class="col-lg-4 main p-0"> <img class="img-fluid" src="images/66.jpg" alt=""> <div class="onhov"> <div class="inside"> <h3>CAPITAL TELTWAY BUILDING</h3> <button class="btn">COMMERCIAL, INTERIORS</button> </div> </div> <button class="out">+</button> </div> <div class="outof d-flex justify-content-lg-center"> <button class="btn">View All Projects</button> </div> </div> </div> </div> <!-- end of c8 --> <div class="container-fluid c9"> <div class="container"> <div class="row"> <div class="col-md-12 col-lg-6"> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <div class="cap1"> <p> Question ran over her cheek When she reached the first hills <br> of the Italic Mountains, she had a last view back on the skyline <br> of her hometown Bookmarksgrove, the headline of Alphabet <br> Village and the subline of her own road. </p> <div class="ico"> <i class="fas fa-quote-left"></i> </div> </div> <div class="slide-con d-flex"> <img src="images/f1.png" alt="..."> <div class="slide-info"> <h3 class="quote-author">Gabriel Denis</h3> <span class="quote-subtext">Chairman, OKT</span> </div> </div> </div> <div class="carousel-item "> <div class="cap1"> <p> Question ran over her cheek When she reached the first hills <br> of the Italic Mountains, she had a last view back on the skyline <br> of her hometown Bookmarksgrove, the headline of Alphabet <br> Village and the subline of her own road. </p> <div class="ico"> <i class="fas fa-quote-left"></i> </div> </div> <div class="slide-con d-flex"> <img src="images/ff2.png" alt="..."> <div class="slide-info"> <h3 class="quote-author">Gabriel Denis</h3> <span class="quote-subtext">Chairman, OKT</span> </div> </div> </div> <div class="carousel-item "> <div class="cap1"> <p> Question ran over her cheek When she reached the first hills <br> of the Italic Mountains, she had a last view back on the skyline <br> of her hometown Bookmarksgrove, the headline of Alphabet <br> Village and the subline of her own road. </p> <div class="ico"> <i class="fas fa-quote-left"></i> </div> </div> <div class="slide-con d-flex"> <img src="images/ff3.png" alt="..."> <div class="slide-info"> <h3 class="quote-author">Gabriel Denis</h3> <span class="quote-subtext">Chairman, OKT</span> </div> </div> </div> </div> <div class="carousel-indicators position-relative"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> </div> </div> <div class="col-md-6"> <div class="row"> <div class="col-md-12 col-lg-4 text-center"> <img class="img-fluid" src="images/f2.png" alt=""> </div> <div class="col-md-12 col-lg-4 text-center"> <img class="img-fluid" src="images/f3.png" alt=""> </div> <div class="col-md-12 col-lg-4 text-center"> <img class="img-fluid" src="images/f4.png" alt=""> </div> </div> <div class="row"> <div class="col-md-12 col-lg-4 text-center"> <img class="img-fluid" src="images/f5.png" alt=""> </div> <div class="col-md-12 col-lg-4 text-center"> <img class="img-fluid" src="images/f6.png" alt=""> </div> <div class="col-md-12 col-lg-4 text-center"> <img class="img-fluid" src="images/f7.png" alt=""> </div> </div> </div> </div> </div> </div> <!-- ---------end of c9----------- --> <div class="c10"> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="con1 "> <h3>CAN WE HELP?</h3> <p>(+9) 847-291-4353</p> </div> </div> <div class="col-md-8"> <div class="apove"> <div class="row align-items-center"> <div class="col-md-4"> <div class="inside"> <h3>NEWSLETTER SIGN-UP</h3> <p>Latest updates and news</p> </div> </div> <div class="col-md-8 "> <div class="elinput"> <input type="text"> </div> </div> </div> </div> </div> </div> </div> </div> <!-- ---- --> <!-- -------end of c10------- --> <div class="container-fluid c11"> <div class="container"> <div class="bef text-center"> <h5>WORK OF EXCELLENCE</h5> <h2>RECENT PROJECTS</h2> </div> <div class="row"> <div class="col-lg-4"> <div class="new"> <img class="img-fluid" src="images/n1.jpg" alt=""> <h3>WE JUST COMPLETES $17.6 MILLION <br> MEDICAL CLINIC IN MID-MISSOURI</h3> <span> JULY 20, 2017</span> </div> </div> <div class="col-lg-4"> <div class="new"> <img class="img-fluid" src="images/n2.jpg" alt=""> <h3> THANDLER AIRPORT WATER <br> RECLAMATION FACILITY EXPANSION <br> PROJECT NAMED</h3> <span> JULY 18, 2017</span> </div> </div> <div class="col-lg-4"> <div class="new"> <img class="img-fluid" src="images/n3.jpg" alt=""> <h3>SILICON BENCH AND CORNIKE BEGIN <br> CONSTRUCTION SOLAR FACILITIES</h3> <span> JULY 13, 2017</span> </div> </div> <div class="outof text-center"> <button class="btn">SEE ALL POSTS</button> </div> </div> </div> </div> <!-- ----end of c11---- --> <div class="container-fluid c12"> <div class="container"> <div class="row"> <div class="col-lg-4"> <div class="foothead"> <span>ABOUT US</span> </div> <img class="img-fluid" src="images/logo2.png" alt=""> <p>Lorem ipsum dolor sit amet, consectetur <br> adipisicing elit, sed do eiusmod tempor inci done <br> idunt ut labore et dolore magna aliqua.</p> <div class="second d-flex "> <i class="fab fa-facebook-f"></i> <i class="fab fa-twitter"></i> <i class="fab fa-instagram"></i> <i class="fab fa-github"></i> </div> </div> <div class="col-lg-4"> <div class="foothead"> <span>WORKING HOURS</span> </div> <p>We work 7 days a week, every day excluding <br> major holidays. Contact us if you have an <br> emergency, with our Hotline and Contact form.</p> <div class="cen d-flex justify-content-start"> <div class="fst"> <ul> <li>Monday - Friday:</li> <li>Saturday:</li> <li>Sunday and holidays:</li> </ul> </div> <div class="second"> <ul> <li>10:00 - 16:00</li> <li>12:00 - 15:00</li> <li>09:00 - 12:00</li> </ul> </div> </div> </div> <div class="col-lg-4"> <div class="foothead"> <span>SERVICES</span> </div> <div class="lista"> <ul> <li>Pre-Construction</li> <hr> <li>General Contracting</li> <hr> <li>Construction Management</li> <hr> <li>Design and Build</li> <hr> <li>Self-Perform Construction</li> </ul> </div> </div> </div> </div> </div> <!-- end of c12 --> <div class="container-fluid final text-center"> <p>Copyright © 2022, Designed & Developed by Themefisher </p> <span>Distributed by Themewagon</span> <div class="list "> <ul class="d-flex justify-content-center"> <li>About</li> <li>Our People</li> <li>Faq</li> <li>Blog</li> <li>Pricing</li> </ul> </div> </div> <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Response; use Illuminate\Http\RedirectResponse; use App\Models\Ticket; use Illuminate\Http\Request; use Illuminate\View\View; class TicketController extends Controller { /** * Display a listing of the resource. */ public function index():View { $userTickets = Auth::user()->tickets; return view('tickets.index', ['tickets' => $userTickets]); } /** * Show the form for creating a new resource. */ public function create() { // } /** * Store a newly created resource in storage. */ public function store(Request $request): RedirectResponse { $validated = $request->validate([ 'message' => 'required|string|max:255', 'category' => 'required|in:Desenvolvimento Web,Programação Embarcada,Inteligência Artificial,Banco de Dados,Outros', ]); $request->user()->tickets()->create($validated); return redirect(route('tickets.index')); } /** * Display the specified resource. */ public function show(Ticket $ticket) { // } /** * Show the form for editing the specified resource. */ public function edit(Ticket $ticket): View { $this->authorize('update', $ticket); return view('tickets.edit', [ 'ticket' => $ticket, ]); } /** * Update the specified resource in storage. */ public function update(Request $request, Ticket $ticket): RedirectResponse { $this->authorize('update', $ticket); $validated = $request->validate([ 'message' => 'required|string|max:255', 'category' => 'required|in:Desenvolvimento Web,Programação Embarcada,Inteligência Artificial,Banco de Dados,Outros', ]); $ticket->update($validated); return redirect(route('tickets.index')); } /** * Remove the specified resource from storage. */ public function destroy(Ticket $ticket): RedirectResponse { $this->authorize('delete', $ticket); $ticket->delete(); return redirect(route('tickets.index')); } }
컴퓨터 과학이 무엇인지 알아 보자. 사람이 정보를 어떻게 표현하는지 생각해 보고, 컴퓨터는 정보를 어떻게 표현할 수 있는지 그 방법에 대해 알아 보자. <br><br> ### 📌 컴퓨터 과학(Computer Science) 강의에서 교수님은 컴퓨터 과학에 대해 아래와 같이 설명했다. > What is computer science? It's just a process of solving problem. > > 컴퓨터 과학(Computer science)은 무엇일까? 이것은 문제를 해결하는 과정(a process of solving problem)일 뿐이다. 그렇다면 문제를 해결하는 것은 무엇일까? ![image of input, process and output](https://computersciencewiki.org/images/a/a9/Ipo.png?20170722115047) [Inputs and outputs - Computer Science Wiki](https://computersciencewiki.org/index.php/Inputs_and_outputs) 바로 문제를 입력(input) 받아 적절한 답안의 출력(output)을 구하는 문제 해결 과정(a process of solving problem)이라 할 수 있다. <br><br> ### 📌 숫자를 나타내는 체계 이제 컴퓨터를 통하여 문제를 해결하기에 앞서, 컴퓨터가 정보를 표현 방법에 대해 알아 보자. #### 1\. 컴퓨터의 언어: 이진법(binary) > 주어진 데이터를 숫자 0과 1로만 표현하는 것을 **이진법(binary)**이라고 한다. #### 2\. 사람의 언어: 십진법(decimal) 사람에게 정보의 표현은 숫자를 세는 걸로 시작한다. 이를 '단일 표기법(unary notation)'이라 한다. 너무 자연스럽게 이해할 수 있는 숫자 _123_은 왜 _123_일까? 아래와 같은 약속을 통해 이루어진다. ``` 123 = (100 * 1) + (10 * 2) + (1 * 3) = 100 + 20 + 3 ``` 즉,100의 자리, 10의 자리, 1의 자리를 나누어 각각의 자리에 곱셈을 더해서 나타낸다. 이를 십진법(decimal)이라 한다. <br><br> ### 📌이진법을 통한 정보의 표현 ![an image of two lightbulbs, turned on means 1 and turned off means 0](https://sandbox.mc.edu/~bennet/cs110/textbook/bulbs.gif) [CSC 110 MODULE 1.3](http://sandbox.mc.edu/~bennet/cs110/textbook/module1_3.html) 0과 1로만 표현하는 이진법을 이용해 전구가 켜지거나 꺼지는(전기가 있거나 없는, 1이거나 0을, 참이거나 거짓인) 상태를 나타낼 수 있다. <br> 이진수 011 또한 십진법의 약속처럼 아래와 같이 나타낼 수 있다. ```c 011 = (4 * 0) + (2 * 1) + (1 * 1) ``` <br><br> ### 📌 비트(bit)와 바이트(byte) ![비트는 0과 1을 나타내는 이진수를, 바이트는 8개의 비트를 나타낸다.](https://learnworthy.net/wp-content/uploads/2020/03/The-amazing-history-of-the-Data-Byte.png?ezimgfmt=ng%3Awebp%2Fngcb12%2Frs%3Adevice%2Frscb12-1) [The amazing history of the Data Byte | Learnworthy.net](https://learnworthy.net/the-amazing-history-of-the-data-byte/) > 비트(bit)는 이진수(binary digit)을 요약한 단어이며, 0과 1로만 값을 나타내는 측정 단위이다. <br> 하나의 비트로는 수많은 양의 데이터를 표현하기에 많이 부족해 보인다. 따라서 몇 개의 비트를 하나로 묶어 어느 정도 가짓수를 가진 새로운 단위를 만들었다. 그게 바로 바이트(byte)이다. <br> > 바이트(byte)는 8개의 비트가 모여 이진수 00000000부터 이진수 11111111까지 나타낼 수 있는 8자리의 이진수이다. 1 byte는 십진법으로 0부터 255까지 나타낼 수 있다. ![바이트는 8개의 전구를 각각 끄거나 키는 방식으로 숫자를 표현한다.](https://sandbox.mc.edu/~bennet/cs110/textbook/significance.gif) [CSC 110 MODULE 1.3](http://sandbox.mc.edu/~bennet/cs110/textbook/module1_3.html) - 강의에서 나온 8개의 전구는 1 바이트를 나타내며, 전구를 끄거나 켜서 주어진 숫자를 표현한다. - 교수님은 트랜지스터 또한 이러한 방식으로 전기를 저장하거나 저장하지 않음으로써 데이터를 표현한다고 설명한다.
<template> <div class="autocomplete"> <input type="text" class="form-control" :id="inputElementId" v-model="search" @focus="open" @keydown.down="arrowDown" @keydown.up="arrowUp" @keydown.enter="enter" @keydown.esc="close" @keydown.tab="close" /> <div class="results" v-show="isOpen" :id="'results' + inputElementId"> <div class="result" :id="'result' + i" :class="{'active': i === selectedItemIndex}" v-for="(result, i) in results" :key="i" @click="selectItem(result)" v-html="result"> </div> <div v-if="results.length < 1" class="text-center text-muted bg-light p-2"> There are no items matching your input. </div> </div> </div> </template> <script lang="ts"> import {Component, Emit, Prop, Vue, Watch} from 'vue-property-decorator'; import {matchAndMark, removeHtml} from '@/util/StringUtils'; import uuid from 'uuid/v4'; @Component export default class Autocomplete extends Vue { @Prop({required: true}) public items: string[]; private search: string; private isOpen: boolean; private selectedItemIndex: number; private inputElementId: string; constructor() { super(); this.search = ''; this.isOpen = false; this.selectedItemIndex = -1; this.inputElementId = uuid(); } private mounted() { document.addEventListener('click', this.handleClickOutside); } private destroyed() { document.removeEventListener('click', this.handleClickOutside); } @Watch('search') @Emit('item-changed') private onItemChange(item: string): string { return item; } @Emit('item-selected') private selectItem(item: string): string { this.search = removeHtml(item); this.close(); return this.search; } get results(): string[] { if (!/\S/.test(this.search)) { return this.items; } return matchAndMark(this.search, this.items); } private handleClickOutside(event: Event) { if (!this.$el.contains(event.target as Node)) { this.close(); } } private open(): void { this.isOpen = true; const inputElement = document.getElementById(this.inputElementId); const height = null != inputElement ? inputElement.offsetHeight - 1 : 0; const resultsElement = this.resultsElement; if (null != resultsElement && null != resultsElement.style) { resultsElement.style.top = height + 'px'; } } private close(): void { this.isOpen = false; this.selectedItemIndex = -1; } private arrowDown() { if (!this.isOpen) { this.open(); this.selectedItemIndex = 0; return; } if (this.selectedItemIndex < (this.results.length - 1)) { this.selectedItemIndex = this.selectedItemIndex + 1; return; } this.selectedItemIndex = 0; } private arrowUp() { if (this.selectedItemIndex > 0) { this.selectedItemIndex = this.selectedItemIndex - 1; return; } this.selectedItemIndex = this.results.length - 1; } get resultsElement(): HTMLElement|null { return document.getElementById('results' + this.inputElementId); } @Watch('selectedItemIndex') private scroll(index: number): void { const activeElement: HTMLElement|null = document.getElementById('result' + index); const resultsElement = this.resultsElement; if (null == resultsElement) { return; } if (index <= 0 || null == activeElement) { resultsElement.scrollTop = 0; return; } if (index === this.results.length - 1) { resultsElement.scrollTop = activeElement.offsetTop; } const scrollZoneTopOffset = resultsElement.scrollTop + activeElement.clientHeight; if (activeElement.offsetTop < scrollZoneTopOffset) { resultsElement.scrollTop = activeElement.offsetTop - activeElement.clientHeight; } const scrollZoneBottomOffset = resultsElement.scrollTop + resultsElement.clientHeight - activeElement.clientHeight; if ((activeElement.offsetTop + activeElement.offsetHeight) > scrollZoneBottomOffset) { resultsElement.scrollTop = resultsElement.scrollTop + activeElement.clientHeight; } } private enter() { if (this.selectedItemIndex < 0) { return; } this.selectItem(this.results[this.selectedItemIndex]); } } </script> <style lang="scss" scoped> div.autocomplete { position: relative; font-family: Inconsolata, monospace; } div.results { position: absolute; top: 2rem; left: 0; border: 1px solid #ced4da; border-top-color: #80bdff; border-radius: .2rem; padding: .2rem; z-index: 1000; background: #fff; min-width: 100%; max-height: 24.5rem; overflow-y: scroll; } div.result { cursor: pointer; padding: 4px .3rem; z-index: 0; &:hover, &.active { background: #F4DBFF; } } div.autocomplete.br-0 input.form-control { border-radius: 0; } div.autocomplete.br-r-0 input.form-control { border-top-right-radius: 0; border-bottom-right-radius: 0; } input[type=text] { outline:0; -webkit-box-shadow:none; box-shadow:none; outline:0; -webkit-box-shadow:none; box-shadow:none; border-radius: 0; padding: .5em 1em; height: auto; } </style>
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider def plot_normal_distribution(ax, std_deviation): ax.clear() mean = 0 x = np.linspace(mean - 3*max_std_deviation, mean + 3*max_std_deviation, 100) y = (1/(std_deviation * np.sqrt(2*np.pi))) * np.exp(-0.5*((x - mean)/std_deviation)**2) ax.plot(x, y, label=f'Standard Deviation = {std_deviation}') ax.set_title('Intuitive understanding of Standard devation\n Change values of SD with yellow slider, observe the Normal curve') ax.set_xlabel('x') ax.set_ylabel('Probability Density') ax.legend() # Customize the grid style ax.grid(True, linestyle='dotted', linewidth=0.5, color='gray') # Mark the x-axis with standard deviation values ax.set_xticks([ mean - 3 *std_deviation, mean - 2* std_deviation, mean - std_deviation, mean, mean + std_deviation, mean + 2*std_deviation, mean + 3*std_deviation]) ax.set_xticklabels(['-3 × SD', '-2 × SD', '-1 × SD', 'Mean', '1 × SD', '2 × SD', '3 × SD']) # Add a thick marker line at the mean ax.axvline(x=mean, color='blue', linewidth=1) ax.axvline(x=mean - 2* std_deviation, color='green', linewidth=0.4) ax.axvline(x=mean + 2* std_deviation, color='red', linewidth=0.4) plt.draw() fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) # Adjust the bottom margin for the slider max_std_deviation = 5.0 # Set the maximum value for standard deviation initial_std_deviation = 2.0 # Initial value for standard deviation std_deviation_slider_ax = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='yellow') #(0.2, 0.7, 0.2, 0.5)) #'lightgoldenrodyellow') std_deviation_slider = Slider(std_deviation_slider_ax, 'Std Deviation', valmin=0.1, valmax=max_std_deviation, valinit=initial_std_deviation) plot_normal_distribution(ax, initial_std_deviation) # Initial plot def update(val): std_deviation = std_deviation_slider.val plot_normal_distribution(ax, std_deviation) std_deviation_slider.on_changed(update) plt.show()
#!/usr/bin/python3 def matrix_divided(matrix, div): """ Divide all elements of a matrix by a divisor. Args: matrix (list): A list of lists containing integers or floats. div (int or float): The divisor. Returns: list: new matrix divided by div, rounded to 2 decimal places. Raises: TypeError: If the input is not a list of lists of integers or floats, or if each row of the matrix does not have the same size, or if div is not a number (integer or float). ZeroDivisionError: If div is equal to 0. """ # Check if matrix is a list of lists of integers or floats if not all(isinstance(row, list) and all(isinstance( elem, (int, float)) for elem in row) for row in matrix): raise TypeError( "matrix must be a matrix (list of lists) of integers/floats") # Check if each row of the matrix has the same size if not all(len(row) == len(matrix[0]) for row in matrix): raise TypeError("Each row of the matrix must have the same size") # Check if div is a number (integer or float) if not isinstance(div, (int, float)): raise TypeError("div must be a number") # Check if div is not equal to 0 if div == 0: raise ZeroDivisionError("division by zero") # Divide all elements of the matrix by div, rounded to 2 decimal places result_matrix = [[round(elem / div, 2) for elem in row] for row in matrix] return result_matrix
<h1 class="mt-4">Latest Posts</h1> <div class="row"> <% @posts.each do |post| %> <div class="col-md-4 mb-4"> <div class="card"> <%= image_tag post.image, class: 'card-img-top' if post.image.attached? %> <div class="card-body"> <h5 class="card-title"><%= post.user.email %></h5> <p class="card-text"><%= post.content %></p> <p class="card-text"> <small class="text-muted"><%= post.created_at.strftime('%B %d, %Y') %></small> </p> </div> <div class="card-footer"> <%= link_to 'View', post, class: 'btn btn-primary' %> <!-- Display Like Count --> <span class="btn btn-secondary disabled"><%= post.likes.count %> Likes</span> <%= link_to 'Like', like_post_path(post), method: :post, class: 'btn btn-success' if user_signed_in? %> </div> </div> </div> <% end %> </div> <%= link_to 'New Post', new_post_path, class: 'btn btn-primary' if user_signed_in? %>
<template> <view> <view id="_drag_button" :class="{ transition: isDock && !isMove, left: isLeft }" :style="'left: ' + left + 'px; top:' + top + 'px;'" class="drag" @touchend="touchend" @touchstart="touchstart" @touchmove.stop.prevent="touchmove" @click.stop.prevent="click" > <!-- <text>{{ text }}</text> --> <block v-if="isLeft"> <view class="fz-24 color-white lh-126 m-r-10"> <view v-if="isPlatform===1">平台</view> <view v-else-if="isPlatform===2">售后</view> <view v-else-if="isPlatform===3">投诉</view> <view>客服</view> </view> <VoIcon :size="30" name="qimo-phone" /> </block> <block v-else> <VoIcon :size="30" name="qimo-phone" /> <view class="fz-24 color-white lh-126 m-l-10"> <view v-if="isPlatform===1">平台</view> <view v-else-if="isPlatform===2">售后</view> <view v-else-if="isPlatform===3">投诉</view> <view>客服</view> </view> </block> </view> </view> </template> <script> export default { name: 'VoDragButton', props: { /** * @description 1售前 2售后 3投诉客服 */ isPlatform:{ type:Number, default:1 }, isDock: { type: Boolean, default: false, }, existTabBar: { type: Boolean, default: true, }, }, data() { return { sys: {}, top: -120, left: -120, width: 0, height: 0, offsetWidth: 0, offsetHeight: 0, windowWidth: 0, windowHeight: 0, isMove: true, edge: 0, text: '按钮', isLeft: false, } }, mounted() { const sys = uni.getSystemInfoSync() this.sys = sys this.windowWidth = sys.windowWidth this.windowHeight = sys.windowHeight const bottomNum = sys.safeAreaInsets.bottom this.existTabBar && (this.windowHeight -= 180 + bottomNum) // if (sys.windowTop) { // this.windowHeight += sys.windowTop // } const query = uni.createSelectorQuery().in(this) query .select('#_drag_button') .boundingClientRect((data) => { this.width = data.width this.height = data.height this.offsetWidth = data.width / 2 this.offsetHeight = data.height / 2 this.left = this.windowWidth - this.width - this.edge // this.top = this.windowHeight - this.height - this.edge this.top = 350 }) .exec() }, methods: { click() { this.$emit('btnClick', { left: this.left, top: this.top }) }, touchstart(e) { this.$emit('btnTouchstart') }, touchmove(e) { // 单指触摸 if (e.touches.length !== 1) { return false } this.isMove = true this.left = e.touches[0].clientX - this.offsetWidth let clientY = e.touches[0].clientY - this.offsetHeight // #ifdef H5 clientY += this.height // #endif let edgeBottom = this.windowHeight - this.height - this.edge // 上下触及边界 if (clientY < this.sys.statusBarHeight) { this.top = this.sys.statusBarHeight } else if (clientY > edgeBottom) { this.top = edgeBottom } else { this.top = clientY } }, touchend(e) { if (this.isDock) { let edgeRigth = this.windowWidth - this.width - this.edge if (this.left < this.windowWidth / 2 - this.offsetWidth) { this.left = this.edge } else { this.left = edgeRigth } } this.isMove = false if (this.left === 0) { this.isLeft = true } else { this.isLeft = false } this.$emit('btnTouchend') }, }, } </script> <style lang="scss"> .drag { display: flex; justify-content: center; align-items: center; // background-color: rgba(0, 0, 0, 0.5); // box-shadow: 0 0 6upx rgba(0, 0, 0, 0.4); // color: $uni-text-color-inverse; width: 144rpx; height: 80rpx; // border-radius: 50%; // font-size: $uni-font-size-sm; // position: fixed; // z-index: 999999; //background: linear-gradient(270deg, #161825 -8.54%, #404773 100%); background: linear-gradient(89.93deg, #ff8640 0.06%, #ff5622 99.94%); mix-blend-mode: normal; position: fixed; // right: 0; // bottom: 330rpx; z-index: 99; border-top-left-radius: 100rpx; border-bottom-left-radius: 100rpx; border-top-right-radius: 0; border-bottom-right-radius: 0; &.transition { transition: left 0.3s ease, top 0.3s ease; } &.left { border-top-right-radius: 100rpx; border-bottom-right-radius: 100rpx; border-top-left-radius: 0; border-bottom-left-radius: 0; } } .lh-126{ line-height: 126%; } </style>
const { promisify } = require("util"); const jwt = require("jsonwebtoken"); const catchAsync = require("./../util/catchAsync"); const AppError = require("./../util/appError"); const sendEmail = require("./../util/email"); const User = require("../models/userModel"); const bcrypt = require("bcryptjs"); const crypto = require("crypto"); const Profile = require("../models/profileModel"); // Make JWT token const createToken = (id) => { return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN.toString(), }); }; const createSendToken = (user, statusCode, res) => { const myToken = createToken(user._id); res.status(statusCode).json({ success: "true", status: statusCode, token: myToken, data: { user, }, }); }; // Function to handle error responses const sendErrorResponse = (res, errorMessage, statusCode, error) => { if (error) { res.status(statusCode).json({ success: "false", status: statusCode, errorMessage: errorMessage, error: error, }); } else { res.status(statusCode).json({ success: "false", status: statusCode, errorMessage: errorMessage, }); } }; exports.signUp = catchAsync(async (req, res, next) => { const email = req.body.email; const user = await User.findOne({ email }); if (user) { sendErrorResponse( res, "Email already has an account. Either log in or use another email", 400 ); return; } let createUser = null; try { createUser = await User.create({ email: req.body.email, password: req.body.password, passwordConfirm: req.body.passwordConfirm, phone: req.body.phone, role: req.body?.role, fullName: req.body.fullName, }); } catch (error) { console.log(error, "error from sign up"); sendErrorResponse(res, "Internal Server error", 500, error); } try { if (!createUser) return; // Email data pass to email.js await sendEmail({ email: createUser.email, subject: "Sign-Up Notification", message: `Welcome to join us, ${createUser.username}!!!`, }); // response data createUser.password = undefined; // hide pass from response createSendToken(createUser, 201, res); } catch (error) { // sendErrorResponse(res, "Error sending email confirmation", 500, error); return next(new AppError("Somthing problem here!!!", 500)); } }); exports.logIn = catchAsync(async (req, res, next) => { const { email, password } = req.body; // Check if email exist if (!email) { sendErrorResponse(res, "You cannot log in without an email", 401); return next(new AppError("provide email", 400)); } // Check if email exist if (!password) { sendErrorResponse(res, "Please provide password", 401); return next(new AppError("provide password", 400)); } // Check if user exists & password is correct const user = await User.findOne({ email }).select("+password"); if (!user || !(await user.comparePassword(password, user.password))) { sendErrorResponse(res, "Incorrect Email or Password", 401); return next(new AppError("Incorrect email or password", 401)); } try { // Email data pass to email.js await sendEmail({ email: user.email, subject: "LogIn Notification", message: `Login successful, ${user.fullName}!!!`, }); let data = null; let profile = await Profile.findOne({ user: user._id }); if (!profile) { data = { ...user, }; } else { data = { _id: user._id, role: user.role, email: user.email, phone: user.phone, fullName: user.fullName, title: profile.title, photo: profile.photo, about: profile.about, }; } // response data user.password = undefined; // hide pass from response if (data === null) return; console.log(user, "login response"); createSendToken(data, 200, res); } catch (error) { // sendErrorResponse(res, "Error sending email confirmation", 500, error); return next(new AppError("Somthing problem here!!!", 500)); } }); exports.getUserById = catchAsync(async (req, res, next) => { // Retrieve the user ID from the request parameters const userId = req.params.id; // Use Mongoose to find the user by ID const user = await User.findOne({ _id: userId }); // Check if the user exists if (!user) { res.status(404).json({ success: false, message: "User not found", }); return next(new AppError("User not found", 404)); } const profile = await Profile.findOne({ user: userId }); // Respond with the user data (excluding sensitive information like the password) res.status(200).json({ success: true, data: { user, profile, }, }); }); exports.getAllUser = catchAsync(async (req, res, next) => { const users = await User.find(); res.status(200).json({ success: "ok", length: users.length, data: { users, }, }); }); exports.forgotPassword = catchAsync(async (req, res, next) => { const clientUrl = req.rawHeaders[req.rawHeaders.length - 5]; console.log(req.rawHeaders[req.rawHeaders.length - 5], "this is the email"); let user = await User.findOne({ email: req.body.email }); if (!user) { sendErrorResponse(res, "There is no user with this email", 404); return next(new AppError("There is no user with this email address", 404)); } let resetToken = user.createPasswordResetToken(); await user.save({ validateBeforeSave: false }); let resetURL = `${clientUrl}reset-password/${resetToken}`; let message = `Forget your password ? click the link below to reset it. \n${resetURL}.\nIf you didn't forget your password, please ignore this email !!!`; try { await sendEmail({ email: user.email, subject: "Your password reset token (valid for 10 minutes)", message, }); res.status(200).json({ status: "ok", message: "Token send to your email!", }); } catch (error) { user.passwordResetToken = undefined; user.passwordResetExpires = undefined; await user.save({ validateBeforeSave: false }); // sendErrorResponse(res, "Internal Server error", 500, error); return next( new AppError( "There was an error sending the email. Try again later !!!", 500 ) ); } }); exports.resetPassword = catchAsync(async (req, res, next) => { try { let hashedToken = crypto .createHash("sha256") .update(req.params.token) .digest("hex"); console.log(hashedToken.toString()); let user = await User.findOne({ passwordResetToken: hashedToken, passwordResetExpires: { $gt: Date.now() }, }); console.log(user); if (!user) { sendErrorResponse(res, "Token is invalid or has expired", 400); return next(new AppError("Token is invalid or has expired", 400)); } user.password = req.body.password; user.passwordConfirm = req.body.passwordConfirm; user.passwordResetToken = undefined; user.passwordResetExpires = undefined; await user.save(); createSendToken(user, 200, res); } catch (error) { sendErrorResponse(res, "Internal Server error", 500, error); console.log(error); return next(new AppError("Internal server error", 500)); } }); exports.updatePassword = catchAsync(async (req, res, next) => { try { let user = await User.findById(req.user.id).select("+password"); console.log(user); if ( !(await user.comparePassword(req.body.passwordCurrent, user.password)) ) { sendErrorResponse(res, "Your current password is wrong", 400); return next(new AppError("Your current password is wrong", 401)); } user.password = req.body.password; user.passwordConfirm = req.body.passwordConfirm; await user.save(); user.password = undefined; createSendToken(user, 200, res); } catch (error) { sendErrorResponse(res, "Internal Server error", 500, error); return next(new AppError("Internal server error", 500)); } }); // Restrict user route exports.restrictTo = (...roles) => { return (req, res, next) => { if (!roles.includes(req.user.role)) { next( new AppError("You do not have permission to perform this action", 403) ); } next(); }; }; // Get current user Info from JWT token exports.protect = catchAsync(async (req, res, next) => { // Getting token and check of it's there let token, reqHeader = req.headers.authorization; if (reqHeader && reqHeader.startsWith("Bearer")) { token = reqHeader.split(" ")[1]; } console.log(token); if (!token) { next( new AppError("You are not logged in! Please log in to get access", 401) ); } // Verification token const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET); const currentUser = await User.findById(decoded.id); if (!currentUser) { next( new AppError("User recently changed password! Please login again", 401) ); } // assign current user data on (req.user) req.user = currentUser; next(); });
<x-layout title="Register"> <div class="container p-5"> <x-alert /> <form action="{{ route('user.store') }}" method="POST" id="formRegister" enctype="multipart/form-data"> @csrf <div class="row"> <div class="form-group col-12"> <label for="name">Função:</label> <select name="type" id="type" class="form-control" onchange="handleSelectChange(this)"> @foreach ($tipoUser as $key => $value) <option value="{{ $value->id }}">{{ $value->nome }}</option> @endforeach <optgroup label="----------------"> <option value="addNew"><button class="btn btn-success" id="addFuncao">+ Cadastrar Nova Função</button></option> </optgroup> </select> </div> <div class="form-group col-12"> <label for="name">Nome:</label> <input type="text" class="form-control" id="name" name="name" placeholder="Nome: Felipe Silva" value="{{ old('name') }}"> @if ($errors->has('name')) <span class="help-block text-danger "> <strong>{{ $errors->first('name') }}</strong> </span> @endif </div> <div class="form-group col-12"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" name="email" placeholder="Email" value="{{ old('email') }}"> @if ($errors->has('email')) <span class="help-block text-danger"> <strong>{{ $errors->first('email') }}</strong> </span> @endif </div> <div class="form-group col-12"> <label for="telefone">Telefone:</label> <input type="text" class="form-control" id="telefone" name="telefone" placeholder="9999-9999" value="{{ old('telefone') }}"> @if ($errors->has('telefone')) <span class="help-block text-danger"> <strong>{{ $errors->first('telefone') }}</strong> </span> @endif </div> <div class="form-group col-12"> <label for="password">Senha:</label> <input type="password" class="form-control" id="password" name="password"> @if ($errors->has('password')) <span class="help-block text-danger"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> <div class="form-group col-12"> <label for="confirm_password">Confirmar Senha:</label> <input type="password" class="form-control" id="confirm_password" name="confirm_password"> @if ($errors->has('confirm_password')) <span class="help-block text-danger"> <strong>{{ $errors->first('confirm_password') }}</strong> </span> @endif </div> <div class="form-group col-12"> <label for="foto">Foto</label> <input type="file" name='avatar' id="avatar" class="form-control"> </div> </div> <div class="form-group"> <button class="buttons login_btn register_btn" name="login" value="Login"> Continue </button> </div> </form> </div> </x-layout>
/* istanbul ignore file: don't test the test. */ import expect from "expect"; import invariant from "invariant"; import sample from "lodash/sample"; import BigNumber from "bignumber.js"; import { AppSpec, MutationSpec, TransactionDestinationTestInput, TransactionRes, } from "@ledgerhq/coin-framework/bot/types"; import { DeviceModelId } from "@ledgerhq/devices"; import { getCryptoCurrencyById, parseCurrencyUnit, } from "@ledgerhq/coin-framework/currencies/index"; import { CryptoCurrency } from "@ledgerhq/types-cryptoassets"; import { cryptocurrenciesById } from "@ledgerhq/cryptoassets/currencies"; import { botTest, genericTestDestination, pickSiblings } from "@ledgerhq/coin-framework/bot/specs"; import { acceptTransaction, avalancheSpeculosDeviceAction } from "./speculos-deviceActions"; import { Transaction as EvmTransaction } from "./types"; import { getEstimatedFees } from "./logic"; const testTimeout = 10 * 60 * 1000; const minBalancePerCurrencyId: Partial<Record<CryptoCurrency["id"], number>> = { arbitrum: 0.001, arbitrum_goerli: 0.001, optimism: 0.001, optimism_goerli: 0.001, boba: 0.001, metis: 0.01, moonriver: 0.1, rsk: 0.05, polygon_zk_evm: 0.001, polygon_zk_evm_testnet: 0.001, base: 0.001, base_goerli: 0.001, avalanche_c_chain: 0.001, bsc: 0.005, polygon: 0.005, ethereum: 0.001, ethereum_goerli: 0.001, ethereum_classic: 0.05, }; /** * Method in charge of verifying that both the recipient and sender of a *coin* transaction * have received/lost the expected amount and have now the right balances * * ⚠️ Some blockchains specific rules are included */ const testCoinDestination = (args: TransactionDestinationTestInput<EvmTransaction>): void => { const { sendingAccount } = args; const { currency } = sendingAccount; // Because Arbitrum is an L2, gas is used in a specific way to ensure both the L2 and the L1 are getting paid. // But as of right now the `arbiscan.io` API is only returning the proposed gas price of // the transaction and not the effectively used gas price, which might differ. // This leads to not being able to correctly cost an operation and // therefore makes it impossible infer the sender's balance if (["arbitrum", "arbitrum_goerli"].includes(currency.id)) { return; } return genericTestDestination(args); }; /** * Method in charge of verifying the balance of a coin account after * the transaction has been confirmed * * ⚠️ Some blockchains specific rules are included */ const testCoinBalance: MutationSpec<EvmTransaction>["test"] = ({ account, accountBeforeTransaction, operation, }) => { // Optimism works in a way where a transaction as a L2 cost and a L1 settlement cost // The explorer API is not capable of returning the L1 cost, therefore // the operation value will always be less than what // has been removed from the account balance // // Remark is also true for Abritrum but because of the arbiscan API not returning the // effectively used gas but the "bid"/proposition of gas of the transaction // resulting in inconsistencies regarding the cumulated value of a tx. // value + gasLimit * gasPrice <-- gasPrice can be wrong here. // // Klaytn is not providing the right gasPrice either at the moment // and their explorers are using the transaction gasPrice // instead of the effectiveGasPrice from the receipt const underValuedFeesCurrencies = ["optimism", "optimism_goerli", "base", "base_goerli"]; const overValuedFeesCurrencies = ["arbitrum", "arbitrum_goerli", "klaytn"]; const currenciesWithFlakyBehaviour = [...underValuedFeesCurrencies, ...overValuedFeesCurrencies]; // Classic test verifying exactly the balance if (!currenciesWithFlakyBehaviour.includes(account.currency.id)) { botTest("account balance moved with operation value", () => expect(account.balance.toString()).toBe( accountBeforeTransaction.balance.minus(operation.value).toString(), ), ); } else { // fallback test verifying the balance moved between the maximum and minimum possible values of the operation botTest( "account balance moved at least operation value and less than operation value plus fees", () => { // If the fee is undervalued like it is for optimism for example // the only doable check is to verify that the account // has lost *at least* the operation value + fee if (underValuedFeesCurrencies.includes(account.currency.id)) { const maxBalance = accountBeforeTransaction.balance.minus( operation.value.minus(operation.fee), // type OUT operations value includes fees so we remove it ); expect({ lessThanMaxBalance: account.balance.lte(maxBalance), }).toEqual({ lessThanMaxBalance: true, }); } // If the fee is overvalue like it is for arbitrum for example // we make sure the account has now a balance between // previous balance minus only operation value & // previous balance minus operation value + fee if (overValuedFeesCurrencies.includes(account.currency.id)) { const minBalance = accountBeforeTransaction.balance.minus( operation.value, // type OUT operations value includes fees ); const maxBalance = accountBeforeTransaction.balance.minus( operation.value.minus(operation.fee), ); expect({ greaterThanMinBalance: account.balance.gte(minBalance), lessThanMaxBalance: account.balance.lte(maxBalance), }).toEqual({ greaterThanMinBalance: true, lessThanMaxBalance: true, }); } }, ); } }; const transactionCheck = (currencyId: string) => ({ maxSpendable }: { maxSpendable: BigNumber }): void => { const currency = getCryptoCurrencyById(currencyId); const minBalance = parseCurrencyUnit( currency.units[0], `${minBalancePerCurrencyId[currency.id] || 1}`, ); invariant(maxSpendable.gt(minBalance), `${currencyId} balance is too low`); }; const evmBasicMutations: ({ maxAccount, }: { maxAccount: number; }) => MutationSpec<EvmTransaction>[] = ({ maxAccount }) => [ { name: "move 50%", maxRun: 2, testDestination: testCoinDestination, transaction: ({ account, siblings, bridge, maxSpendable }): TransactionRes<EvmTransaction> => { const sibling = pickSiblings(siblings, maxAccount); const recipient = sibling.freshAddress; const amount = maxSpendable.div(2).integerValue(); return { transaction: bridge.createTransaction(account), updates: [ { recipient, amount, }, ], }; }, test: ({ account, accountBeforeTransaction, operation, transaction, status, optimisticOperation, }): void => { const estimatedGas = getEstimatedFees(transaction); botTest("operation fee is not exceeding estimated gas", () => expect(operation.fee.toNumber()).toBeLessThanOrEqual(estimatedGas.toNumber()), ); testCoinBalance({ account, accountBeforeTransaction, operation, transaction, status, optimisticOperation, }); }, }, { name: "send max", maxRun: 1, testDestination: testCoinDestination, transaction: ({ account, siblings, bridge }): TransactionRes<EvmTransaction> => { const sibling = pickSiblings(siblings, maxAccount); const recipient = sibling.freshAddress; return { transaction: bridge.createTransaction(account), updates: [ { recipient, }, { useAllAmount: true, }, ], }; }, test: ({ account, accountBeforeTransaction, operation, transaction, status, optimisticOperation, }): void => { const estimatedGas = getEstimatedFees(transaction); botTest("operation fee is not exceeding estimated gas", () => expect(operation.fee.toNumber()).toBeLessThanOrEqual(estimatedGas.toNumber()), ); testCoinBalance({ account, accountBeforeTransaction, operation, transaction, status, optimisticOperation, }); }, }, ]; const moveErc20Mutation: MutationSpec<EvmTransaction> = { name: "move some ERC20 like (ERC20, BEP20, etc...)", maxRun: 1, testDestination: testCoinDestination, transaction: ({ account, siblings, bridge }): TransactionRes<EvmTransaction> => { const erc20Account = sample((account.subAccounts || []).filter(a => a.balance.gt(0))); invariant(erc20Account, "no erc20 account"); const sibling = pickSiblings(siblings, 3); const recipient = sibling.freshAddress; return { transaction: bridge.createTransaction(account), updates: [ { recipient, subAccountId: erc20Account!.id, }, Math.random() < 0.5 ? { useAllAmount: true, } : { amount: erc20Account!.balance.times(Math.random()).integerValue(), }, ], }; }, test: ({ accountBeforeTransaction, account, transaction }): void => { invariant(accountBeforeTransaction.subAccounts, "sub accounts before"); const erc20accountBefore = accountBeforeTransaction.subAccounts?.find( s => s.id === transaction.subAccountId, ); invariant(erc20accountBefore, "erc20 acc was here before"); invariant(account.subAccounts, "sub accounts"); const erc20account = account.subAccounts!.find(s => s.id === transaction.subAccountId); invariant(erc20account, "erc20 acc is still here"); if (transaction.useAllAmount) { botTest("erc20 account is empty", () => expect(erc20account!.balance.toString()).toBe("0")); } else { botTest("account balance moved with tx amount", () => expect(erc20account!.balance.toString()).toBe( erc20accountBefore!.balance.minus(transaction.amount).toString(), ), ); } }, }; const getAppQuery = (currencyId: CryptoCurrency["id"]): AppSpec<EvmTransaction>["appQuery"] => { switch (currencyId) { case "avalanche_c_chain": return { model: DeviceModelId.nanoS, appName: "Avalanche" }; case "polygon": return { model: DeviceModelId.nanoS, appName: "Polygon" }; case "bsc": return { model: DeviceModelId.nanoS, appName: "Binance Smart Chain" }; case "ethereum_classic": return { model: DeviceModelId.nanoS, appName: "Ethereum Classic" }; default: return { model: DeviceModelId.nanoS, appName: "Ethereum", appVersion: "1.10.3", }; } }; const getGenericDeviceAction = ( currencyId: CryptoCurrency["id"], ): AppSpec<EvmTransaction>["genericDeviceAction"] => { if (currencyId === "avalanche_c_chain") { return avalancheSpeculosDeviceAction; } return acceptTransaction; }; const getDependency = (currencyId: CryptoCurrency["id"]): AppSpec<EvmTransaction>["dependency"] => { switch (currencyId) { case "bsc": case "polygon": case "ethereum_classic": return "Ethereum"; default: return undefined; } }; const getMutations = (currencyId: CryptoCurrency["id"]): AppSpec<EvmTransaction>["mutations"] => { switch (currencyId) { case "avalanche_c_chain": return evmBasicMutations({ maxAccount: 8 }); case "polygon": case "bsc": return evmBasicMutations({ maxAccount: 8 }).concat(moveErc20Mutation); case "ethereum_classic": return evmBasicMutations({ maxAccount: 4 }); case "ethereum": return evmBasicMutations({ maxAccount: 7 }).concat(moveErc20Mutation); case "telos_evm": case "polygon_zk_evm": case "polygon_zk_evm_testnet": return evmBasicMutations({ maxAccount: 3 }); default: return evmBasicMutations({ maxAccount: 4 }).concat(moveErc20Mutation); } }; export default Object.values(cryptocurrenciesById) .filter(currency => currency.family === "evm") .reduce<Partial<Record<CryptoCurrency["id"], AppSpec<EvmTransaction>>>>((acc, currency) => { acc[currency.id] = { name: currency.name, currency, appQuery: getAppQuery(currency.id), dependency: getDependency(currency.id), testTimeout, transactionCheck: transactionCheck(currency.id), mutations: getMutations(currency.id), genericDeviceAction: getGenericDeviceAction(currency.id), }; return acc; }, {});
<script setup lang="ts"> import DefaultLayout from '@/layouts/DefaultLayout.vue'; import ProfileHeader from '../components/ProfileHeader.vue'; import ProfileFeed from '../components/ProfileFeed.vue'; import { Topic, User, getCurrentUser } from '@/lib/domain'; import { useRoute } from 'vue-router'; import { onMounted } from 'vue'; const route = useRoute(); function getUserId() { return route.params['id'] ? Number(route.params['id']) : getCurrentUser().id; } onMounted(() => { const userId = getUserId(); console.log('Component mounted', userId); }); // TODO: Load profile const profile: { user: User; topics: Topic[] } = { user: { id: 1, username: 'topicql', name: 'TopicQL', bio: 'A GraphQL study', avatarUrl: 'https://vectorseek.com/wp-content/uploads/2023/02/GraphQL-Logo-Vector.jpg', }, topics: [ { id: 1, author: { id: 1, username: 'topicql', avatarUrl: 'https://vectorseek.com/wp-content/uploads/2023/02/GraphQL-Logo-Vector.jpg', }, content: 'Lorem ipsum', replies: [], createdAt: new Date(new Date().getTime() - 1000 * 60 * 10), }, ], }; </script> <template> <DefaultLayout> <template #title> <ProfileHeader :user="profile.user"></ProfileHeader> </template> <template #default> <ProfileFeed :topics="profile.topics"></ProfileFeed> </template> </DefaultLayout> </template>
import {HttpClient} from "@angular/common/http"; import {CurrencyService} from "./currency.service"; import {of} from "rxjs"; describe('CurrencyService', () => { let httpClientMock: jasmine.SpyObj<HttpClient>; let service: CurrencyService; beforeEach(() => { httpClientMock = jasmine.createSpyObj('HttpClient', ['get']); service = new CurrencyService(httpClientMock); }); it('should return exchange rate for valid currencies', (done) => { const baseCurrency = 'USD'; const targetCurrency = 'EUR'; const mockResponse = {base: baseCurrency, rates: {[targetCurrency]: 0.9}}; httpClientMock.get.and.returnValue(of(mockResponse)); service.getExchangeRate(baseCurrency, targetCurrency) .subscribe(response => { expect(response.base).toEqual(baseCurrency); expect(response.rates[targetCurrency]).toEqual(0.9); done(); }); }); it('should return available currencies from response', (done) => { const url = `${service.API_URL}?api_key=${service.API_KEY}&base=USD`; const mockResponse = {exchange_rates: {EUR: 0.9, GBP: 0.8}}; httpClientMock.get.and.returnValue(of(mockResponse)); service.getAvailableCurrencies() .subscribe(currencies => { expect(currencies).toEqual(['EUR', 'GBP']); done(); }); }); it('should return available currencies from response', (done) => { const url = `${service.API_URL}?api_key=${service.API_KEY}&base=USD`; const mockResponse = {exchange_rates: {EUR: 0.9, GBP: 0.8}}; httpClientMock.get.and.returnValue(of(mockResponse)); service.getAvailableCurrencies() .subscribe(currencies => { expect(currencies).toEqual(['EUR', 'GBP']); done(); }); }); });
import React from "react"; import { render, fireEvent, act } from "@testing-library/react-native"; import { Provider } from "react-redux"; import { Store, createStore } from "redux"; import * as _ from "lodash"; import type { IOPictograms } from "@pagopa/io-app-design-system"; import AskUserInteractionScreen, { Props } from "../AskUserInterarctionScreen"; import { GlobalState } from "../../../../store/reducers/types"; import { appReducer } from "../../../../store/reducers"; import { applicationChangeState } from "../../../../store/actions/application"; jest.useFakeTimers(); const globalState = appReducer(undefined, applicationChangeState("active")); const store = createStore(appReducer, globalState as any); const defaultProps = { title: "Test title", subtitle: "Test subtitle", pictogramName: "timeout" as IOPictograms, onSubmit: jest.fn(), onClose: jest.fn(), onCancel: jest.fn(), onTimerExpired: jest.fn(), timerDurationInSeconds: 10 }; describe("AskUserInteractionScreen component", () => { it("should render properly", () => { const { getByText, getByTestId } = renderComponent(defaultProps, store); expect(getByText(defaultProps.title)).toBeTruthy(); expect(getByText(defaultProps.subtitle)).toBeTruthy(); const continueButton = getByText("Continue"); const cancelButton = getByText("Cancel"); const headerCloseButton = getByTestId("header-close-button"); const countdownTimer = getByText("00:10"); expect(continueButton).toBeTruthy(); expect(cancelButton).toBeTruthy(); expect(headerCloseButton).toBeTruthy(); expect(countdownTimer).toBeTruthy(); expect(getByTestId("countdown-timer")).toBeTruthy(); }); it("should call onSubmit when the continue button is pressed", () => { const { getByText } = renderComponent(defaultProps, store); const button = getByText("Continue"); fireEvent.press(button); expect(defaultProps.onSubmit).toHaveBeenCalled(); }); it("should call onCancel when the exit button is pressed", () => { const { getByText } = renderComponent(defaultProps, store); const button = getByText("Cancel"); fireEvent.press(button); expect(defaultProps.onCancel).toHaveBeenCalled(); }); it("should call onClose when the close button is pressed", () => { const { getByTestId } = renderComponent(defaultProps, store); const button = getByTestId("header-close-button"); fireEvent.press(button); expect(defaultProps.onClose).toHaveBeenCalled(); }); it("does not render exit button if onExit prop is not provided", () => { const { queryByText } = renderComponent( _.omit(defaultProps, "onCancel"), store ); expect(queryByText("Cancel")).toBeNull(); }); it("does not render close button if onExit prop is not provided", () => { const { queryByTestId } = renderComponent( _.omit(defaultProps, "onClose"), store ); expect(queryByTestId("header-close-button")).toBeNull(); }); it("does not render timer if onTimerExpired prop is not provided", () => { const { queryByTestId } = renderComponent( _.omit(defaultProps, "onTimerExpired"), store ); expect(queryByTestId("countdown-timer")).toBeNull(); }); it("should call onTimerExpired when the timer expires", async () => { renderComponent(defaultProps, store); await act(() => { jest.advanceTimersByTime(10 * 1000); }); expect(defaultProps.onTimerExpired).toHaveBeenCalled(); }); }); const renderComponent = (props: Props, store: Store<GlobalState>) => render( <Provider store={store}> <AskUserInteractionScreen {...props} /> </Provider> );
package org.ageage.githubclient.data.api.di import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.ageage.githubclient.data.api.GitHubApiClient import org.ageage.githubclient.data.api.impl.ApiExceptionMapper import org.ageage.githubclient.data.api.impl.ApiExceptionMapperImpl import org.ageage.githubclient.data.api.impl.GitHubApiClientImpl import org.ageage.githubclient.data.api.interceptor.AccessTokenInterceptor import org.ageage.githubclient.data.api.service.GitHubApiService import retrofit2.Retrofit import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal object ApiModule { @Provides @Singleton fun provideAccessTokenInterceptor(): AccessTokenInterceptor { return AccessTokenInterceptor() } @Provides @Singleton fun provideOkHttpClient(accessTokenInterceptor: AccessTokenInterceptor): OkHttpClient { return OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .addInterceptor(accessTokenInterceptor) .build() } @Provides @Singleton fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { val json = Json { ignoreUnknownKeys = true } return Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .client(okHttpClient) .build() } @Provides fun provideGitHubApiService(retrofit: Retrofit): GitHubApiService { return retrofit.create(GitHubApiService::class.java) } @Provides fun providesSearchApiClient( gitHubApiService: GitHubApiService, apiExceptionMapper: ApiExceptionMapper ): GitHubApiClient { return GitHubApiClientImpl(gitHubApiService, apiExceptionMapper) } @Provides fun provideApiExceptionMapper(): ApiExceptionMapper { return ApiExceptionMapperImpl() } }
import { Form, Formik } from "formik"; import React, { useEffect } from "react"; import Button from "../app/components/button/Button"; import Input from "../app/components/input/Input"; import LabelText from "../app/components/labelText/LabelText"; import { loginValidate } from "../app/utils/validation"; import styles from "../styles/login.module.css"; import { FaFacebook } from "react-icons/fa"; import { FcGoogle } from "react-icons/fc"; import Link from "next/link"; import { RootState, useAppDispatch, useAppSelector } from "../app/store/store"; import { authFacebookLogin, authGoogleLogin, authLogin } from "../app/redux/auth/authSlice"; import Loader from "../app/components/loader/Loader"; import { useRouter } from "next/router"; import { useSelector } from "react-redux"; import Meta from "../app/components/meta/Meta"; const Login = () => { const dispatch = useAppDispatch(); const { loading } = useAppSelector((state: RootState) => state.auth); const router = useRouter(); const { user } = useSelector((state: RootState) => state.auth) useEffect(() =>{ if(user) router.push("/") }, [router, user]) return ( <> <Meta title="Firebase Image - Login" description="Firebase" keyword="Razu Islam" /> {loading ? ( <Loader /> ) : ( <section className={styles.login}> <div className={`${styles.container} container`}> <div className={styles.wrapper}> <Formik initialValues={{ email: "", password: "", }} validationSchema={loginValidate} onSubmit={(values: any) => { dispatch(authLogin(values)); router.push("/") }} > {(formik) => ( <> <h1 style={{ textAlign: "center", color: "#333", }} > Welcome to login firebase </h1> <Form> <LabelText htmlFor="email">Email</LabelText> <Input type="email" name="email" placeholder="Enter Email" className="form_control_input" id="email" /> <LabelText htmlFor="password">Password</LabelText> <Input type="password" name="password" placeholder="Enter password" className="form_control_input" id="password" /> <Button type="submit" className={`app_btn fill ${styles.btn}`} > Login </Button> </Form> </> )} </Formik> {/* Forgot Password */} <div className={styles.forgotPassword}> <p> <Link href="/forgot_password"> Forgot your password? </Link> </p> </div> <p className={styles.logintext}> if you don't have an account please <Link href="/register"> Register</Link> </p> {/* Google With Google */} <div className="flex i_center j_center" style={{ width: "100%", }} > <div className="flex i_center j_center" style={{ width: "100%", marginTop: "0.6em", }} > <Button className={styles.google} onClick={() => dispatch(authGoogleLogin())}> <FcGoogle /> Login With Google </Button> </div> </div> {/* Login With Facebook Button */} <div className="flex i_center j_center" style={{ width: "100%", marginTop: "0.6em", }} > <Button className={styles.facebook} onClick={() => dispatch(authFacebookLogin())}> <FaFacebook /> Login With Facebook </Button> </div> </div> </div> </section> )} </> ); }; export default Login;
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:paradise/core/constants/color_palatte.dart'; import 'package:paradise/core/constants/dimension_constants.dart'; import 'package:paradise/core/helpers/assets_helper.dart'; import 'package:paradise/core/helpers/text_styles.dart'; import 'package:paradise/core/helpers/AuthFunctions.dart'; import 'package:paradise/presentations/screens/Staffs/register_form_screen.dart'; import 'package:paradise/presentations/screens/forgot_password_screen.dart'; import 'package:paradise/presentations/widgets/button_widget.dart'; import 'package:paradise/presentations/widgets/input_password.dart'; import 'package:paradise/presentations/widgets/input_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../widgets/dialog.dart'; import 'home_screen.dart'; class LoginScreen extends StatefulWidget { static String routeName = 'login_screen'; const LoginScreen({super.key}); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { Color getColor(Set<MaterialState> states) { const Set<MaterialState> interactiveStates = <MaterialState>{ MaterialState.pressed, MaterialState.hovered, MaterialState.focused, }; if (states.any(interactiveStates.contains)) { return ColorPalette.primaryColor; } return ColorPalette.primaryColor; } bool isChecked = true; TextEditingController _emailController = TextEditingController(); TextEditingController _passwordController = TextEditingController(); final formSignInKey = GlobalKey<FormState>(); late SharedPreferences pref; bool _passwordVisible = false; @override void initState() { // TODO: implement initState super.initState(); Pref(); } void Pref() async { pref = await SharedPreferences.getInstance(); _emailController.text = pref.getString("email").toString(); _passwordController.text = pref.getString("password").toString(); } @override Widget build(BuildContext context) { return GestureDetector( child: Scaffold( body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(vertical: kMaxPadding * 4), child: Form( key: formSignInKey, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: kItemPadding), child: Image.asset( AssetHelper.icoLogin, ), ), Padding( padding: const EdgeInsets.symmetric(vertical: kItemPadding), child: Text('Login', style: TextStyles.h1.setColor(ColorPalette.darkBlueText)), ), Padding( padding: const EdgeInsets.symmetric( horizontal: kMaxPadding, vertical: kItemPadding), child: InputWidget( controller: _emailController, labelText: 'Enter your email', icon: AssetHelper.icoUser, validator: (input) { final bool emailValid = RegExp( r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?") .hasMatch(input!); if (input.isEmpty) { return "Please enter username"; } else if (!emailValid) { return "Email is not Invalid"; } }), ), Padding( padding: const EdgeInsets.symmetric( horizontal: kMaxPadding, vertical: kItemPadding), child: TextFormField( validator: (input) { if (input == "") { return "Please enter your password!"; } else if (input != null && input.length <= 6) { return "Password is too short!"; } else return null; }, obscureText: !_passwordVisible, controller: _passwordController, decoration: InputDecoration( suffixIcon: IconButton( icon: Icon( // Based on passwordVisible state choose the icon _passwordVisible ? Icons.visibility : Icons.visibility_off, ), onPressed: () { setState(() { _passwordVisible = !_passwordVisible; }); }, ), labelText: 'Enter your password', labelStyle: TextStyles.h6.setColor(ColorPalette.grayText), contentPadding: const EdgeInsets.only(bottom: 14), floatingLabelBehavior: FloatingLabelBehavior.never, prefixIcon: Container( child: Image.asset(AssetHelper.icoLock), padding: const EdgeInsets.only(right: 16), ), prefixIconConstraints: BoxConstraints( minWidth: 24, ), ), ), // InputWidget( // controller: _passwordController, // isPassword: true, // labelText: 'Password', // icon: AssetHelper.icoLock, // validator: (input) { // if (input == "") { // return "Please enter your password!"; // } else if (input != null && input.length <= 6) { // return "Password is too short!"; // } else // return null; // }, // ), ), Container( width: double.infinity, margin: const EdgeInsets.symmetric( horizontal: 33, vertical: kItemPadding), child: Row( children: [ StatefulBuilder( builder: (context, setState) { return Checkbox( checkColor: Colors.white, fillColor: MaterialStateColor.resolveWith( (states) => getColor(states)), value: isChecked, onChanged: (value) { setState(() { isChecked = !isChecked; }); }, ); }, ), Text( 'Remember me', style: TextStyles.h6.italic .setColor(ColorPalette.primaryColor), ), ], ), ), Container( padding: const EdgeInsets.symmetric( horizontal: kMaxPadding, vertical: kItemPadding), child: ButtonWidget( label: 'Log in', color: ColorPalette.primaryColor, onTap: () async { if (formSignInKey.currentState!.validate()) { if (isChecked) { pref.setString('email', _emailController.text); pref.setString( "password", _passwordController.text); } else { pref.setString('email', ""); pref.setString("password", ""); } await AuthServices.signinUser(_emailController.text, _passwordController.text, context); // await FirebaseFirestore.instance // .collection("Users") // .get() // .then((value) { // int check = 0; // for (var doc in value.docs) { // if (doc.get("Email") == _emailController.text) { // check++; // } // } // if (check > 0) { // } else { // ScaffoldMessenger.of(context).showSnackBar( // SnackBar( // content: Text( // 'No user Found with this Email'))); // } // }); } }, ), ), TextButton( onPressed: () { Navigator.of(context) .pushNamed(ForgotPasswordScreen.routeName); }, child: Text( 'Forgot password?', style: TextStyles.h6.bold.setColor(ColorPalette.greenText), ), ), ], ), ), ), ), ), onTap: () { FocusManager.instance.primaryFocus?.unfocus(); }, ); } }
/* 문제 정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오. 명령은 총 여섯 가지이다. push X: 정수 X를 큐에 넣는 연산이다. pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. size: 큐에 들어있는 정수의 개수를 출력한다. empty: 큐가 비어있으면 1, 아니면 0을 출력한다. front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다. 입력 첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다. 출력 출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다. */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by WOOSERK. * User: WOOSERK * Date: 2020-10-05 * Time: 오후 10:33 */ public class Q10845 { private final static int SIZE = 10001; static class MyQueue { private int[] data; private int front; private int rear; public MyQueue() { data = new int[SIZE]; front = 0; rear = -1; } void push(int X) { data[++rear] = X; } int pop() { return (front == rear + 1)? -1 : data[front++]; } int size() { return rear - front + 1; } int empty() { return (front == rear + 1) ? 1 : 0; } int front() { return (front == rear + 1) ? -1 : data[front]; } int back() { return (front == rear + 1 ? -1 : data[rear]); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); MyQueue queue = new MyQueue(); while(N-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); String command = st.nextToken(); switch(command) { case "push": queue.push(Integer.parseInt(st.nextToken())); break; case "pop": System.out.println(queue.pop()); break; case "size": System.out.println(queue.size()); break; case "empty": System.out.println(queue.empty()); break; case "front": System.out.println(queue.front()); break; case "back": System.out.println(queue.back()); break; } } } }
import { ICar, ICars, IGarageClient } from '../models/garage.model'; class Garage implements IGarageClient { private url; private limitCar; constructor() { this.url = 'http://127.0.0.1:3000/garage'; this.limitCar = 7; } public async getAll(page: number, limit = this.limitCar): Promise<ICars> { const response = await fetch(`${this.url}?_page=${page}&_limit=${limit}`); return { data: await response.json(), count: Number(response.headers.get('X-Total-Count')), }; } public async get(id: number): Promise<ICar> { const response = await fetch(`${this.url}/${id}`); return response.json(); } public async create(body: Omit<ICar, 'id'>): Promise<ICar> { const response = await fetch(this.url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); return response.json(); } public async remove(id: number): Promise<void> { await fetch(`${this.url}/${id}`, { method: 'DELETE' }); } public async update(id: number, body: Omit<ICar, 'id'>): Promise<ICar> { const response = await fetch(`${this.url}/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); return response.json(); } } export default new Garage();
package com.example.l12.L12.service; import com.example.l12.L12.models.UserInfo; import com.example.l12.L12.repository.UserRepository; import com.example.l12.L12.requests.CreateUserRequestDto; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service @Slf4j public class UserService { @Autowired UserRepository userRepository; /** * <p> * This method is used to create / persist new user object * </p> * @param userRequestDto * @return - userInfo without Id */ public UserInfo createUser(CreateUserRequestDto userRequestDto) { UserInfo userInfo = userRequestDto.toUser(); userRepository.save(userInfo); return userInfo; } /** * 10000 of records * --> (0,20) (21,40) * * limit 20 * limit 21 40 * * @return */ public List<UserInfo> fetchAllUsers(int pageNumber) { Pageable pageable = PageRequest.of(pageNumber, 20); return userRepository.findAll(pageable).getContent(); } public Optional<UserInfo> fetchOneById(Integer id) { return userRepository.findById(id); } }
// ---------------------------------------- Importar import {urlProducto, urlCarpetaImg, urlBuscador, urlCarrito, urlFavoritos, urlInicio, urlPagar} from "../modules/urls.mjs"; import {todosLosProductos, copiaTodosLosProductos, favoritos, carrito} from "../modules/arrays.mjs"; import {showMenu} from "./menu.mjs"; // ---------------------------------------- Exportar export function formatearNumero(numero) { let formatoNumero = new Intl.NumberFormat('es-AR'); return '$' + formatoNumero.format(numero); } export function mostrarBanners(lugar) { let section = document.createElement('section'); section.id = 'banners'; section.innerHTML = ` <!-- Slider main container --> <div class="swiper"> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> <div class="swiper-slide"> <img src="img/primerBanner.png" alt="50% de descuento en consolas y videojuegos"> </div> <div class="swiper-slide segundo-banner"> <img src="img/segundoBanner.png" alt="Las mejores notebooks en un solo lugar"> </div> <div class="swiper-slide"> <img src="img/tercerBanner.jpg" alt="necesitamos diseñador gráfico"> </div> </div> <!-- Pagination --> <div class="swiper-pagination"></div> <!-- Navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> `; lugar.appendChild(section); // Iniciar swiper new Swiper('.swiper', { // Optional parameters direction: 'horizontal', loop: true, // If we need pagination pagination: { el: '.swiper-pagination', }, // Navigation arrows navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, autoplay: { delay: 5000, }, }); } export function mostrarProductos(id, titulo, array, cantidad, dom) { let section = document.createElement('section'); section.classList = 'container text-center mh-500 py-3'; section.id = id; section.innerHTML = ` <h2 class="times">${titulo}</h2> <section class="row align-items-start justify-content-center mt-4 arial"> </section> `; // Si no hay la cantida de productos requeridos para mostrar, mostrar todos los que haya cantidad > array.length && (cantidad = array.length); for (let i = 0; i < cantidad; i++) { // Variable para mostrar envio gratis let h5EnvioGratis = ''; // Variable para saber donde esta el texto oculto que se va a mostrar luego let numeroChildren = 3; // Si hay envio gratis cambiar variable y sumar array[i].envioGratis && (h5EnvioGratis = '<h5 class="text-success">Envío Gratis!</h5>', numeroChildren++); let article = document.createElement('article'); article.classList = 'col-12 col-md-3 p-2 articulo position-relative'; article.innerHTML = ` <div class="rounded border bg-white p-3 articulo-principal"> <div class="contenedor-img"> <img src="${`${urlCarpetaImg}${array[i].id}-1.png`}" alt="${array[i].nombre}"> </div> <hr class="w-100"> <h5>${formatearNumero(array[i].precio)}</h5> ${h5EnvioGratis} <h5 class="d-md-none" id="${array[i].id}">${array[i].nombre}</h5> </div> `; let estadoFavorito = document.createElement('div'); estadoFavorito.classList = 'addFavourite'; mostrarEstadoFavorito(array[i].id - 1, estadoFavorito); article.appendChild(estadoFavorito) // Agrear a dom section.children[1].appendChild(article); // Eventos article.children[0].onmouseover = () => {article.children[0].children[numeroChildren].classList.toggle('d-md-none')}; article.children[0].onmouseout = () => {article.children[0].children[numeroChildren].classList.toggle('d-md-none')}; // Guardar id en variable porque cambia let arrayID = array[i].id; // Click en el cuerpo -> redirigir a pagina del producto article.children[0].onclick = () => {window.location.href = `${urlProducto}?id=${arrayID}`}; // Click en la estrella article.children[1].onclick = () => { // Agregar o quitar de favoritos agregarOQuitarFavoritos(arrayID - 1, estadoFavorito); // Si esta en la pagina de favoritos, recargar pagina para que no muestre el producto quitado window.location.href.includes(urlFavoritos) && window.location.reload(); }; } dom.appendChild(section); } export function mostrarError(main, error) { // Limpiar DOM main.innerHTML = ''; let section = document.createElement('section'); section.classList = 'text-center mh-700 pt-5'; section.innerHTML = ` <h1>Ha ocurrido un error</h1> <h5 class="pt-5">Por favor intente mas tarde</h5> <p>Si el problema persiste, por favor comuniquese con el administrador</p> <p class="pt-5">${error}</p> `; main.appendChild(section); } export function mostrarCategorias(dom, array) { dom.innerHTML = ''; let section = document.createElement('section'); section.classList = 'container'; let div = document.createElement('div'); div.classList = 'row align-items-center justify-content-center text-center verdana'; array.forEach(element => { let article = document.createElement('article'); article.classList = 'col-12 col-md-4 p-3'; article.innerHTML = ` <div class="bg-white px-2 py-4 rounded border categoria"> <h5>${element}</h5> </div> `; article.onclick = () => { sessionStorage.setItem('categorias', element); window.location.href = `${urlBuscador}?categoria=${element}`; } div.appendChild(article); }); section.appendChild(div); dom.appendChild(section); } export function obtenerCategorias() { let listaCategorias = []; // Recorro todos los productos todosLosProductos.forEach(element => { // Si el producto no se encuentra en la lista de productos lo agrego listaCategorias.indexOf(element.categoria) === -1 && listaCategorias.push(element.categoria); }); return listaCategorias; } export function noHayFavoritos(dom) { let section = document.createElement('section'); section.classList = 'text-center mt-5'; section.innerHTML = ` <div class="my-5"> <h3>No se encontraron favoritos agregados!</h3> <h5>Podés agregar productos a favoritos para poder verlos o comprarlos más tarde.</h5> </div> <a href="${urlBuscador}"> <button class="btn btn-primary arial">Buscar productos</button> </a> `; dom.appendChild(section); } export function copiarArray(arrayDeseado, arrayDestino) { // Limpiar arrayDestino.splice(0, arrayDestino.length); // Por cada elemento del array deseado, mandar a destino arrayDeseado.forEach(element => { arrayDestino.push(element) }); } function agregarParrafoFiltro(idDOM, nombre, cantidad) { // DOM const dom = document.getElementById(idDOM); // Crear parrafo let p = document.createElement('p'); p.classList = 'm-1'; p.innerHTML = ` <a class="text-decoration-none text-dark">${nombre} <span class="text-secondary">(${cantidad})</span></a> `; p.onclick = () => { // Actualizar filtro en storage sessionStorage.setItem(idDOM, nombre); // Recargar pagina correrBusqueda(); } // Agregarlo dom.appendChild(p); } export function mostrarCategoria(copiaTodosLosProductos) { // Ordenar por categoria copiaTodosLosProductos.sort((a, b) => { if (a.categoria > b.categoria) { return 1; } if (a.categoria < b.categoria) { return -1; } // a es igual a b return 0; }) let contador = 0; // Copiar categorias a array for (let i = 0; i < copiaTodosLosProductos.length; i++) { // Contar un producto mas de la categoria contador++; // Si es el ultimo numero del array o si el nombre de la categoria actual es diferente a la siguiente, agregar if (i === (copiaTodosLosProductos.length - 1) || (copiaTodosLosProductos[i].categoria !== copiaTodosLosProductos[i+1].categoria)) { agregarParrafoFiltro('categorias', copiaTodosLosProductos[i].categoria, contador); contador = 0; } } } export function mostrarMarca(copiaTodosLosProductos) { // Ordenar por marca copiaTodosLosProductos.sort((a, b) => { if (a.marca > b.marca) { return 1; } if (a.marca < b.marca) { return -1; } // a es igual a b return 0; }) let contador = 0; // Copiar categorias a array for (let i = 0; i < copiaTodosLosProductos.length; i++) { // Contar un producto mas de la categoria contador++; // Si es el ultimo numero del array o si el nombre de la categoria actual es diferente a la siguiente, agregar if (i === (copiaTodosLosProductos.length - 1) || (copiaTodosLosProductos[i].marca !== copiaTodosLosProductos[i+1].marca)) { agregarParrafoFiltro('marcas', copiaTodosLosProductos[i].marca, contador); contador = 0; } } } export function mostrarFiltrosActivos(dom) { // DOM const filtrosActivos = document.getElementById(dom); const divFiltros = filtrosActivos.children[1]; // Limpiar filtros divFiltros.innerHTML = ''; // Variables let busqueda = sessionStorage.getItem('busqueda'); let categorias = sessionStorage.getItem('categorias'); let marcas = sessionStorage.getItem('marcas'); // Si hay algun filtro, mostrar seccion if (busqueda || categorias || marcas) { filtrosActivos.classList.remove('d-none'); }else{ filtrosActivos.classList.add('d-none'); } // Si hay un filtro de busqueda, mostrar busqueda && mostrarFiltro(busqueda, 'busqueda', divFiltros); // Si hay un filtro de categoria, mostrar categorias && mostrarFiltro(categorias, 'categorias', divFiltros); // Si hay un filtro de marca, mostrar marcas && mostrarFiltro(marcas, 'marcas', divFiltros); } function mostrarFiltro(valor, remover, dom) { let div = document.createElement('div'); div.classList = 'col-auto bg-primary rounded px-4 py-1 m-1 position-relative'; div.innerHTML = ` <a class="text-decoration-none text-white">${valor}<span class="cross">x</span></a> `; div.onclick = () => { sessionStorage.removeItem(remover); correrBusqueda(); } dom.appendChild(div); } export function correrBusqueda() { // Dom - ubicar donde poner los productos const resultadosDOM = document.getElementById('resultados'); // Copiar array original copiarArray(todosLosProductos, copiaTodosLosProductos); // Mostrar filtros activos mostrarFiltrosActivos('filtros-activos'); // Almacenar resultados del filtrado const arrayFiltrado = aplicarFiltros(copiaTodosLosProductos); // Limpiar limpiar('categorias'); limpiar('marcas'); limpiar('resultados'); // Manejar opciones orden opcionesOrden(); // Ordenar ordenar(arrayFiltrado); // Mostrar productos encontrados, si no hay, mostrar no se encontraron arrayFiltrado.length > 0 ? mostrarProductos('resultados','Resultados', arrayFiltrado, arrayFiltrado.length, resultadosDOM) : resultadosDOM.innerHTML = `<h3 class="text-center pt-5">No se encontraron resultados</h3>`; // Mostrar categorias para filtrar mostrarCategoria(arrayFiltrado); // Mostrar marcas para filtrar mostrarMarca(arrayFiltrado); } function aplicarFiltros(copiaTodosLosProductos) { // Variables let busqueda = sessionStorage.getItem('busqueda') || ''; let categorias = sessionStorage.getItem('categorias') || ''; let marcas = sessionStorage.getItem('marcas') || ''; busqueda = busqueda.toLowerCase(); // Filtrar copiaTodosLosProductos = copiaTodosLosProductos.filter((el) => el.nombre.toLowerCase().includes(busqueda) || el.categoria.toLowerCase().includes(busqueda) || el.marca.toLowerCase().includes(busqueda)); copiaTodosLosProductos = copiaTodosLosProductos.filter((el) => el.categoria.includes(categorias)); copiaTodosLosProductos = copiaTodosLosProductos.filter((el) => el.marca.includes(marcas)); return copiaTodosLosProductos; } function limpiar(idElemento) { const dom = document.getElementById(idElemento); dom.innerHTML = ''; } function ordenarMenorPrecio(arrayAOrdenar) { arrayAOrdenar.sort((a, b) => a.precio - b.precio); } function ordenarMayorPrecio(arrayAOrdenar) { arrayAOrdenar.sort((a, b) => b.precio - a.precio); } function ordenarRandom(arrayAOrdenar) { arrayAOrdenar.sort(() => Math.random(1) - Math.random(1)); } function ordenar(arrayAOrdenar) { let orden = sessionStorage.getItem('orden'); orden === 'Menor Precio' && ordenarMenorPrecio(arrayAOrdenar); orden === 'Mayor Precio' && ordenarMayorPrecio(arrayAOrdenar); (orden === 'Random' || orden === null) && ordenarRandom(arrayAOrdenar); } function opcionesOrden() { const ordenActual = document.getElementById('abrirOpcionesOrden'); const contenedorOpciones = document.getElementById('opcionesOrden'); const listaOpciones = contenedorOpciones.children[0].children; // Poner valor actual ordenActual.children[0].innerText = sessionStorage.getItem('orden') || 'Random'; // Mostrar opciones de orden ordenActual.onclick = () => {contenedorOpciones.classList.toggle('d-none')}; // Por cada orden listado for (let i = 0; i < listaOpciones.length; i++) { listaOpciones[i].onclick = () => { // Cambiar opcion orden en storage sessionStorage.setItem('orden', listaOpciones[i].innerText); // Correr busqueda para actualizar correrBusqueda(); // Cerrar lista contenedorOpciones.classList.toggle('d-none'); // Cambiar orden actual ordenActual.children[0].innerText = listaOpciones[i].innerText; } } } export function manejarImagesProducto(id, numeroImagenPrincipal) { mostrarImagenesPreview(id, numeroImagenPrincipal); mostrarImagenPricipal(id, numeroImagenPrincipal); } function mostrarImagenesPreview(id, numeroImagenPrincipal) { const imagenesPreviewDom = document.getElementById('imagenes').children[0].children[0]; // Limpiar DOM para no acumular imagenes imagenesPreviewDom.innerHTML = ''; for (let i = 1; i < todosLosProductos[id].imagenesDisponibles + 1; i++) { let imagen = document.createElement('div'); imagen.classList = 'my-2 border rounded previewImg'; imagen.innerHTML = ` <img src="${urlCarpetaImg}${parseInt(id)+1}-${i}.png" alt="Imagen previa numero ${i} del producto" class="w-100"> `; // Si es la imagen actual, agregar borde azul if (i === numeroImagenPrincipal) { imagen.classList.add('border-primary'); } imagenesPreviewDom.appendChild(imagen); imagen.onclick = () => {manejarImagesProducto(id, i)} } } function mostrarImagenPricipal(id, numeroImagen) { const imagenPrincipalDom = document.getElementById('imagenes').children[0].children[1]; imagenPrincipalDom.innerHTML = ` <img src="${urlCarpetaImg}${parseInt(id)+1}-${numeroImagen}.png" alt="Imagen ${numeroImagen} del producto" class="w-75"> `; } export function mostrarNombreProducto(id, dom) { dom.innerText = todosLosProductos[id].nombre; } export function mostrarColores(id, dom) { todosLosProductos[id].coloresDisponibles.forEach(element => { let contenedor = document.createElement('div'); contenedor.classList = 'col-4 mb-3'; contenedor.innerHTML = `<div class="border w-100 rounded bg-${element.toLowerCase()}">${element}</div>`; dom.appendChild(contenedor); }); } export function mostrarDescripcion(id, dom) { dom.innerText = todosLosProductos[id].descripcion; } function mostrarPrecio(id, dom, cantidad) { dom.innerText = formatearNumero(todosLosProductos[id].precio * cantidad); } export function manejarCantidades(id) { // DOM const precioDom = document.getElementById('opciones').children[0]; const domSeleccionar = document.getElementById('opciones').children[1].children[0].children[0]; const domCantidadDisp = document.getElementById('opciones').children[1].children[1].children[0].children[0]; const botonComprar = document.getElementById('opciones').children[2].children[0]; const botonAgregar = document.getElementById('opciones').children[3].children[0]; // Abrir lista cantidades domSeleccionar.children[1].onclick = () => {domSeleccionar.children[2].classList.toggle('d-none')} // Al hacer click en la lista de opciones cantidad domSeleccionar.children[2].onclick = (e) => { // Cambiar valor arriba domSeleccionar.children[1].children[0].innerText = e.target.innerText; // Cerrar lista domSeleccionar.children[2].classList.toggle('d-none'); // Volver a correr funcion manejarCantidades(id); } // Mostrar disponibles menos seleccionados cantidadesDisponibles(id, domCantidadDisp); // Cantidad seleccionada es igual a el texto en Dom como numero let cantidadSeleccionada = parseInt(domSeleccionar.children[1].innerText); // MostrarPrecio mostrarPrecio(id, precioDom, cantidadSeleccionada); // Si la cantidad seleccionada es mayor a la disponible if (todosLosProductos[id].cantidadDisponible - cantidadSeleccionada < 0) { // Deshabilitar botones botonComprar.classList.add('disabled'); botonAgregar.classList.add('disabled'); // Mostrar advertencia Toastify({ text: `Solo hay ${todosLosProductos[id].cantidadDisponible} disponibles`, duration: 5000, close: true, gravity: "top", // `top` or `bottom` position: "right", // `left`, `center` or `right` style: { background: "#ff8800", color: "white" }, onClick: function(){} // Callback after click }).showToast(); }else{ // Habilitar botones botonComprar.classList.remove('disabled'); botonAgregar.classList.remove('disabled'); } // Boton comprar botonComprar.onclick = () => { // Agregar producto a canasta agregarProducto(id, cantidadSeleccionada); // Redirigir a carrito window.location.href = urlCarrito; } // Boton agregar a carrito botonAgregar.onclick = () => { // Agregar producto a canasta agregarProducto(id, cantidadSeleccionada); showMenu(); // Mostrar mensaje Toastify({ text: 'Producto agregado', duration: 3000, gravity: "top", // `top` or `bottom` position: "right", // `left`, `center` or `right` style: { background: "#1cb81c", color: "white" }, onClick: function(){} // Callback after click }).showToast(); } } function cantidadesDisponibles(id, domDisponibles) { // Mostrar disponible domDisponibles.innerText = todosLosProductos[id].cantidadDisponible; } function agregarProducto(id, cantidad) { // Buscar si el producto que se quiere agregar esta en el carrito let auxiliar = carrito.find( (el) => el.producto.id === (id+1) ); // Si está, sumar cantidades y borrar original if (auxiliar !== undefined) { cantidad += auxiliar.cantidad; carrito.splice(carrito.indexOf(auxiliar)); } // Agregar un objeto con el producto a comprar y la cantidad carrito.push({producto: todosLosProductos[id], cantidad: cantidad}); // Almacenar localStorage.setItem('carrito', JSON.stringify(carrito)); } export function agregarOQuitarFavoritos(productId, dom) { // Variable let mensaje = ''; let color = ''; let estaAgregado = buscarFavorito(productId); if (estaAgregado.length === 0) { // Agregar favoritos.push(todosLosProductos[productId]); // Cambiar mensaje mensaje = 'Agregado a favoritos'; color = '#1cb81c'; } else { // Buscar producto en favoritos const resultado = favoritos.find((el) => el.id === productId + 1); // Borrar producto de favoritos favoritos.splice(favoritos.indexOf(resultado), 1); // Cambiar mensaje mensaje = 'Quitado de favoritos'; color = '#ff8800'; } // Actualizar localStorage.setItem('favoritos',JSON.stringify(favoritos)); // Mostrar mensaje Toastify({ text: mensaje, duration: 3000, gravity: "top", // `top` or `bottom` position: "right", // `left`, `center` or `right` style: { background: color, color: "white" }, onClick: function(){} // Callback after click }).showToast(); // Mostrar estado actual mostrarEstadoFavorito(productId, dom) } function buscarFavorito(productId) { // Buscar y retornar array return favoritos.filter( (el) => el.id === productId + 1 ); } export function mostrarEstadoFavorito(productId, dom) { let estaAgregado = buscarFavorito(productId); if (estaAgregado.length === 0) { // Mostrar estrella vacia dom.innerHTML = ` <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="blue" class="bi bi-star" viewBox="0 0 16 16"> <path d="M2.866 14.85c-.078.444.36.791.746.593l4.39-2.256 4.389 2.256c.386.198.824-.149.746-.592l-.83-4.73 3.522-3.356c.33-.314.16-.888-.282-.95l-4.898-.696L8.465.792a.513.513 0 0 0-.927 0L5.354 5.12l-4.898.696c-.441.062-.612.636-.283.95l3.523 3.356-.83 4.73zm4.905-2.767-3.686 1.894.694-3.957a.565.565 0 0 0-.163-.505L1.71 6.745l4.052-.576a.525.525 0 0 0 .393-.288L8 2.223l1.847 3.658a.525.525 0 0 0 .393.288l4.052.575-2.906 2.77a.565.565 0 0 0-.163.506l.694 3.957-3.686-1.894a.503.503 0 0 0-.461 0z"/> </svg> `; }else{ // Mostrar estrella llena dom.innerHTML = ` <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="blue" class="bi bi-star-fill" viewBox="0 0 16 16"> <path d="M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z"/> </svg> `; } } export function mostrarCarrito(dom) { dom.innerHTML = ''; if (carrito.length > 0) { carrito.forEach(element => { let precio = element.cantidad * element.producto.precio; let article = document.createElement('article'); article.classList = 'container p-3 position-relative bg-white border-top prodCart'; article.innerHTML = ` <div class="row align-items-center justify-content-center"> <section class="col-12 col-md-2 my-3 my-md-0" id="imagen"> <img src="${urlCarpetaImg}${element.producto.id}-1.png" alt="Imagen ${element.producto.nombre}"> </section> <section class="col-12 col-md-4 my-3 my-md-0" id="detalles"> <h4>${element.producto.nombre}</h4> </section> <section class="col-12 col-md-5 my-3 my-md-0" id="precio"> <div class="row align-items-center justify-content-center"> <div class="col-12 col-md-6 my-3 my-md-0"> <p class="text-secondary">Cantidad:</p> <h4>${element.cantidad}</h4> </div> <div class="col-12 col-md-6 my-3 my-md-0"> <p class="text-secondary">Subtotal:</p> <h4>${formatearNumero(precio)}</h4> </div> </div> </section> </div> `; // Agregar boton para quitar let divButton = document.createElement('div'); divButton.id = 'quitar'; divButton.innerHTML = '<button class="btn btn-sm btn-danger">x</button>'; divButton.onclick = () => { // Borrar de array carrito carrito.splice(carrito.indexOf(element),1); // Acutalizar en local localStorage.setItem('carrito', JSON.stringify(carrito)); // Recargar menu y productos en carrito showMenu(); mostrarCarrito(dom); }; article.appendChild(divButton); // Añadir articulo al dom dom.appendChild(article); }); let total = carrito.reduce((acc,el) => acc + el.producto.precio * el.cantidad, 0); let section = document.createElement('section'); section.classList = 'container px-3 py-5 border-top bg-white'; section.innerHTML = ` <div class="row align-items-center justify-content-center"> <div class="col-12 col-md-3"> <h5>Total:</h5> </div> <div class="col-12 col-md-3"> <h5 id="total">${formatearNumero(total)}</h5> </div> </div> <a href="${urlPagar}"> <button class="btn btn-primary w-75 mt-5 arial" id="pagar"><h5>Pasar a pago</h5></button> </a> `; dom.appendChild(section) }else{ dom.innerHTML = ` <h3 class="mt-5">No se encontraror productos en la canasta<h3> <a href="${urlInicio}"> <button class="btn btn-primary mt-4 px-5 arial"><h5>Ir a inicio</h5></button> </a> `; } } export function borrarCarritoYCargarMenu() { // Remover del local storage localStorage.removeItem('carrito'); // Resetear variable carrito.length = 0; // Recargar menu showMenu(); }
import React from "react"; import "./Styles/Dashboard.css"; import BarChart from "./Chart"; function Dashboard() { let label1 = [ "Everett", "Seattle", "Lynnwood", "Bothell", "Mukilteo", "Edmonds", ]; let data1 = [ 90000, 80000, 50000,45000, 40000, 35000, ]; let data2 = [ 160000, 130000,80000,77000, 42000, 41000, 10000, ]; let label2 = [ "Service Plumbing", "Bid Work HVAC", "Service HVAC", "Bid Work Plumbing", "HWT Replacement", "Maintenance", "Material Scale", ]; let maxi1=90000; let maxi2=180000; const companyM = [ { money: "$406,411.29", title: "Total Revenue", }, { money: "$620", title: "Total Jobs Avg", }, { money: "655", title: "Tickets Created", }, { money: "735", title: "Tickets Scheduled", }, { money: "$110,448.8", title: "Outstanding Amount", }, { money: "105", title: "Membership Sold", }, { money: "436", title: "Jobs Completed", }, { money: "65", title: "Total Canceled", }, ]; return ( <div className="mainDashboard"> <div style={{textAlign:"left",width:"90%",height:"90% "}}> <h2>Company Metrics</h2> <div className="allMetrics"> {companyM.map((item, index) => { return ( <CompanyMetrics key={index} title={item.title} money={item.money} /> ); })} </div> </div> <div className="allCharts"> <div className="bar"> <BarChart labels={label1} data={data1} heading={"Revenue By Job Location"} max={maxi1} /> </div> <div className="bar"> <BarChart labels={label2} data={data2} heading={"Revenue By Job Type"} ax={maxi2} /> </div> </div> </div> ); } function CompanyMetrics({ title, money }) { return ( <div className="metrics"> <h3>{money}</h3> <p>{title}</p> </div> ); } export default Dashboard;
import React, { useState, useRef } from 'react' import { SendMessageManager } from '../../controller/send_message' import formatRelativeTime from '../../../../utils/format_time'; import { IoIosArrowRoundBack } from "react-icons/io"; const Chat = ({ messages, channel, userId, setChannel }) => { // console.log(messages, userId) const inputRef = useRef(null); const { sendMessageController } = SendMessageManager() const [text, setText] = useState('') const handleMessage = (e) => { inputRef.current.value = '' const data = { "channel_id": channel?._id, "type": "text", "message": text } sendMessageController(data) } return ( <div className='flex flex-col justify-between h-full'> <div> <div className='flex gap-x-[11px] items-center mb-[11px] bg-white rounded-[10px] p-[14px]'> <div className='flex gap-x-3 items-center'> <div className='md:hidden block' onClick={() => { setChannel(null) }}> <IoIosArrowRoundBack size={30} /> </div> <div className='flex-shrink-0'> <img src={channel?.initiator?.user_id !== userId ? ( channel?.initiator?.profile_picture.length > 0 ? channel?.initiator?.profile_picture : 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png' ) : ( channel?.receiver?.profile_picture.length > 0 ? channel?.receiver?.profile_picture : 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png')} className='h-[40px] w-[40px] rounded-full object-cover' /> </div> </div> <h3 className='text-black text-[15px] font-semibold'>{channel?.initiator?.user_id !== userId ? channel?.initiator?.full_name : channel?.receiver?.full_name}</h3> </div> </div> <div className='h-full overflow-scroll mt-[24px]'> <div className="flex flex-col-reverse"> { messages?.map(el => <div className={`mb-2 ${el?.sender?.user_id === userId ? 'self-end text-right' : '' }`}> <div key={el?._id} className={`p-2 rounded-lg mb-1 shadow-md ${el?.sender?.user_id === userId ? 'bg-brandPrimary self-end' : 'bg-white p-2 max-w-[230px]' }`}> {el?.message} </div> <p className='text-[10px] font-light '>{formatRelativeTime(el?.createdAt)}</p> </div> ) } </div> </div> <div className="flex mt-auto flex-end w-full bg-white p-[11px] rounded-[10px]"> <input id='message' type="text" className="flex-1 border p-2 mr-2 rounded-[50px] bg-[#f2f2f2] p-[15px] outline-none focus:outline-none" placeholder="Type your message..." ref={inputRef} onChange={(e) => { setText(e.target.value) }} /> <button className="bg-brandPrimary text-white p-2 rounded-[50px]" disabled={!text.length > 0} onClick={() => { handleMessage() }}> <svg xmlns="http://www.w3.org/2000/svg" width="60" height="45" viewBox="0 0 60 45" fill="none"> <rect width="60" height="45" rx="22.5" fill="#FFF112" /> <path d="M41.5261 22.1223L23.5936 13.106C22.6919 12.7053 21.6901 13.5067 22.0908 14.4083L24.5954 21.1205L36.0161 23.0239L24.5954 24.9274L22.0908 31.6396C21.7903 32.5412 22.6919 33.3426 23.5936 32.8417L41.5261 23.8254C42.2273 23.5249 42.2273 22.523 41.5261 22.1223Z" fill="black" /> </svg> </button> </div> </div> ) } export default Chat
--- title: Tagging Docker images sidebar_position: 1 --- How to set registry, repository and tag names on your images --- ## Configuring registries A `docker_image` target takes an optional `registries` field, whose value is a list of registry endpoints: ```python title="src/example/BUILD" docker_image( name="demo", registries=[ "reg.company.internal", ] ) ``` Images built from this target will be published to these registries. If you push many images to the same registries, and you don't want to repeat the endpoint information, you can name the registries in your `pants.toml` config file, and then refer to them by name in the target, using a `@` prefix. You can also designate one or more registries as the default for your repo, and images with no explicit `registries` field will use those default registries. ```toml tab={"label":"pants.toml"} [docker.registries.company-registry1] address = "reg1.company.internal" default = true [docker.registries.company-registry2] address = "reg2.company.internal" ``` ```python tab={"label":"src/example/BUILD"} docker_image(name="demo") # This is equivalent to the previous target, # since company-registry1 is the default registry: docker_image( name="demo", registries=["@company-registry1"], ) # You can mix named and direct registry references. docker_image( name="demo2", registries=[ "@company-registry2", "ext-registry.company-b.net:8443", ] ) ``` ## Setting a repository name In Docker parlance, an image is identified by a _repository_ and one or more _tags_ within that repository. You set a repository name using the `repository` field on `docker_image`: ```python title="src/example/BUILD" docker_image( name="demo", repository="example/demo", ) ``` ```shell $ ./pants package src/example:demo # Will build the image: example/demo:latest ``` You can also specify a default repository name in config, and this name can contain placeholders in curly braces that will be interpolated for each `docker_image`: ```toml tab={"label":"pants.toml"} [docker] default_repository = "{directory}/{name}" ``` ```python tab={"label":"src/example/BUILD"} docker_image( name="demo", ) ``` The default placeholders are: - `{directory}`: The directory the docker_image's BUILD file is in. - `{parent_directory}`: The parent directory of `{directory}`. - `{name}`: The name of the docker_image target. - `{build_args.ARG_NAME}`: Each defined Docker build arg is available for interpolation under the `build_args.` prefix. Since repository names often conform to patterns like these, this can save you on some boilerplate by allowing you to omit the `repository` field on each `docker_image`. But you can always override this field on specific `docker_image` targets, of course. In fact, you can use these placeholders in the `repository` field as well, if you find that helpful. See [String interpolation using placeholder values](./tagging-docker-images.mdx#string-interpolation-using-placeholder-values) for more information. ## Tagging images When Docker builds images, it can tag them with a set of tags. Pants will apply the tags listed in the `image_tags` field of `docker_image`. (Note that the field is named `image_tags` and not just `tags`, because Pants has [its own tags concept](../../reference/targets/target.mdx#tags), which is unrelated.) ```python title="src/example/BUILD" docker_image( name="demo", repository="example/demo", image_tags=["1.2", "example"] ) ``` When pants builds the `src/example:demo` target, a single image will be built, with two tags applied: - `example/demo:1.2` - `example/demo:example` It's often useful to keep versions of derived images and their base images in sync. Pants helps you out with this by interpolating tags referenced in `FROM` commands in your Dockerfile into the `image_tags` in the corresponding `docker_image`: ```python tab={"label":"src/example/BUILD"} # These three are equivalent docker_image(name="demo1", image_tags=["{tags.upstream}"]) docker_image(name="demo1", image_tags=["{tags.stage0}"]) # The first FROM may also be referred to as "baseimage" docker_image(name="demo1", image_tags=["{tags.baseimage}"]) # Any stage my be used, and being a format string, you may add extra text as well. docker_image(name="demo1", image_tags=["{tags.stage1}-custom-suffix"]) ``` ```dockerfile tab={"label":"src/example/Dockerfile"} FROM upstream:1.2 as upstream # ... FROM scratch # ... ``` This way you can specify a version just once, on the base image, and the derived images will automatically acquire the same version. You may also use any Docker build arguments (when configured as described in [Docker build arguments](./overview.mdx#build-arguments)) for interpolation into the `image_tags` in the corresponding `docker_image`: ```python title="src/example/BUILD" docker_image(image_tags=["{build_args.ARG_NAME}"]) ``` ## Using env vars to include dynamic data in tags You can interpolate dynamic data, such as the current Git commit sha, in an image tag, using environment variables and Docker build args. For example, you can declare a custom build arg, either in `extra_build_args` for a specific `docker_image` target, or for all `docker_image` targets in `pants.toml`: ```python # pants.toml [docker] build_args = ["GIT_COMMIT"] ``` and use this build arg in the image tag: ```python # src/example/BUILD docker_image(name="demo", image_tags=["1.2-{build_args.GIT_COMMIT}"]) ``` Then, if you run Pants with the data set in an environment variable of the same name: ``` $ GIT_COMMIT=$(git rev-parse HEAD) ./pants package src/example:demo ``` the value from the environment will be used. :::note Generating dynamic tags in a plugin If you don't want to use the environment variable method described above, you'll need to write some custom plugin code. Don't hesitate to [reach out](/community/getting-help) for help with this. We are looking into making some common dynamic data, such as the git sha, automatically available in the core Docker plugin in the future. ::: ## All together: Registries, Repositories and Tags To illustrate how all the above work together, this target: ```python title="src/example/BUILD" docker_image( name="demo", repository="example/demo", registries=["reg1", "reg2"], image_tags=["1.0", "latest"] ) ``` Will create a single image with these full names: ``` reg1/example/demo:1.0 reg1/example/demo:latest reg2/example/demo:1.0 reg2/example/demo:latest ``` ## String interpolation using placeholder values As we've seen above, some fields of the `docker_image` support replacing placeholder values in curly braces with variable text, such as a build arg or base image tag for instance. The interpolation context (the available placeholder values) depends on which field it is used in. These are the common values available for all fields: - `{tags.<stage>}`: The tag of a base image (the `FROM` instruction) for a particular stage in the `Dockerfile`. The `<stage>` is either `stageN` where `N` is the numeric index of the stage, starting at `0`. The first stage, `stage0`, is also available under the pseudonym `baseimage`. If the stage is named (`FROM image AS my_stage`), then the tag value is also available under that name: `{tags.my_stage}`. - `{build_args.ARG_NAME}`: Each defined Docker build arg is available for interpolation under the `build_args.` prefix. - `{pants.hash}`: This is a unique hash value calculated from all input sources and the `Dockerfile`. It is effectively a hash of the Docker build context. See note below regarding its stability guarantee. See [Setting a repository name](./tagging-docker-images.mdx#setting-a-repository-name) for placeholders specific to the `repository` field. :::note The `{pants.hash}` stability guarantee The calculated hash value _may_ change between stable versions of Pants for the otherwise same input sources. :::
import os import logging from dotenv import load_dotenv from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler from opentelemetry.sdk._logs.export import BatchLogRecordProcessor from opentelemetry._logs import set_logger_provider from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter load_dotenv() logger_proiver = LoggerProvider() set_logger_provider(logger_proiver) log_exporter = AzureMonitorLogExporter( connection_string=os.getenv('APP_CONNECTION') ) logger_proiver.add_log_record_processor( BatchLogRecordProcessor(log_exporter) ) handler = LoggingHandler() logger = logging.getLogger(__name__) logger.addHandler(handler) logger.setLevel(logging.INFO) # Info logger.info("Hello, World!") # warning logger.warning("This is a warning message.") # Error logger.error("This is an error message.") # Exception properties = {'custom_dimensions': str({'key_1': 'value_1', 'key_2': 'value_2'})} # Use properties in exception logs try: pass except Exception: logger.exception('Capture an exception.', extra=properties) logger_proiver.force_flush()
package com.anamika.test; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.anamika.demo.MyDivide; import com.anamika.exception.NegativeNoNotAllowedException; public class MyDivideTest { private MyDivide myDivide; @Before public void setUp(){ myDivide=new MyDivide(); } @After public void tearDown() { myDivide=null; } @Test public void t001(){ assertEquals(2,myDivide.divide(10, 5)); } @Test(expected= NegativeNoNotAllowedException.class) public void t002(){ myDivide.divide(-10, 5); } @Test(expected= NegativeNoNotAllowedException.class) public void t003(){ myDivide.divide(10, -5); } @Test(expected=NegativeNoNotAllowedException.class) public void t004(){ myDivide.divide(-7, -2); } @Test(expected=ArithmeticException.class) public void t005(){ myDivide.divide(20, 0); } @Test public void t006(){ assertEquals(0,myDivide.divide(0, 20)); } }
<template> <div class="relevance-form-tree"> <a-input :value="text" :readonly="true" :placeholder="placeholder" @click="onClick" @mouseover="onMouseenter" @mouseout="onMouseleave"> <a-icon v-show="hover" slot="suffix" type="close-circle" @click="clear" @mouseenter="onMouseenter" /> <a-icon v-show="!hover" slot="suffix" type="file" /> </a-input> <a-modal :title="formTitle" :visible="visibleTreeDig" :width="full ? '100%' : '950px'" :destroyOnClose="true" :maskClosable="false" :keyboard="false" :class="{ 'full-modal': full, 'relevance-form': true }" :closable="!full" @ok="onModalOkTree" @cancel="onModalCancelTree" > <a-tooltip placement="top" v-show="!full"> <template slot="title"> <span>{{ $t("cloudpivot.form.runtime.biz.fullScreen") }}</span> </template> <span @click="fullScreen(true)" class="fullscreen icon aufontAll">&#xe8e5;</span> </a-tooltip> <a-tooltip placement="top" v-show="full"> <template slot="title"> <span>{{ $t("cloudpivot.form.runtime.biz.smallScreen") }}</span> </template> <span @click="fullScreen(false)" class="fullscreen icon aufontAll">&#xe8e7;</span> </a-tooltip> <a-tree :loadData="onLoadData" :defaultExpandedKeys="defaultExpandedKeys" :key="num" :treeData="treeData" :loadedKeys="loadedKeys" :replaceFields="replaceFields" @select="onSelect"> </a-tree> </a-modal> </div> </template> <script lang="ts"> import {Component, Vue, Watch, Prop, InjectReactive} from "vue-property-decorator"; import { RelevanceFormControl } from "@cloudpivot/form/src/common/controls/relevance-form-control"; import cloneDeep from "lodash/cloneDeep"; import { DataItemType, RelevanceFormSelectMode, convertDataItemExp, RendererFormControl, FormControlType, } from "@cloudpivot/form/schema"; import { // TreeSelect, Modal, Tooltip, Icon, Spin, Input, Tree } from "@h3/antd-vue"; import axios from "axios"; import env from "../../../../../../../../entries/portal/src/config/env"; import * as Type from "../../../../../../../../entries/portal/extends/type"; import {treeArrFilter} from "../../../../../utils"; @Component({ name: "relevance-form-tree", components: { ATooltip: Tooltip, AModal: Modal, AInput: Input, AIcon: Icon, ASpin: Spin, ATree: Tree }, }) export default class RelevanceFormTree extends RelevanceFormControl{ @InjectReactive("project") projectCode?: string; @InjectReactive('projectConfig') projectConfig?: Type.ProjectConfig; query = {}; hover = false; full = false; //树控件 visibleTreeDig: boolean = false; //树控件弹窗 formConfigTree:{columnCode:string|null,dicName:string|null,id:string|null,mainTree:number|null,schemaCode:string|null,sequenceStatus:string|null}[] = []; currentDicName: string = ''; treeData: Array<any> = []; replaceFields = { key: "id", title: "taskName", }; selectedTree: string = ''; currentNode: any; defaultExpandedKeys: Array<string> = []; num: number = 0; loadedKeys: Array<string> = []; get text() { //不用显示字段控制 if (!this.ctrl.value) { return ""; } if (!this.ctrl.value[this.getDisplayField]) { this.setLinkageValue(); } return this.parseDisplayFieldValue( this.ctrl.value[this.getDisplayField], this.getDisplayField ); } async onClick() { let item = this.formConfigTree.filter((i)=> this.control.key === i.columnCode); if(item.length) { this.visibleTreeDig = true; this.currentDicName = item[0]?.dicName??''; this.getTreeData(); return } } fullScreen(full: boolean) { this.full = full; } onMouseenter() { this.hover = true; } onMouseleave() { this.hover = false; } clear() { this.ctrl.value = null; } //获取已配置的树形组件 getTreeConfig() { axios.get(`${env.apiHost}/dataManage/treeComponet/getTreeConfig`,{ params: { appCode: this.projectCode, schemaCode: this.$route.query.schemaCode } }).then((res:any)=> { if(res.errcode === 0) { this.formConfigTree = res?.data?? []; } }) } getTreeData() { axios.get(`${env.apiHost}/dataManage/treeComponet/getTreeData`,{ params: { appCode: this.projectCode, dicName: this.currentDicName, currentId: '', projectName: this.projectConfig?.projectName ?? '' } }).then((res:any)=> { if(res.errcode === 0) { this.treeData = res?.data?? []; this.defaultExpandedKeys = treeArrFilter(this.treeData,'children','children',(obj:{children:any[]})=> { return obj['children'] && obj['children'].length }); this.loadedKeys = treeArrFilter(this.treeData,'children','children',(obj:{children:any[],childCount:number})=> { return obj['children'] && !obj['children'].length && !obj['childCount'] }) ++this.num; } }) } onLoadData(treeNode:any) { this.loadedKeys.push(treeNode.$vnode.data.key); return new Promise(resolve => { if (treeNode.dataRef.children != undefined && treeNode.dataRef.children.length > 0) { // 有值了直接渲染 //@ts-ignore resolve(); return; } axios.get(`${env.apiHost}/dataManage/treeComponet/getTreeData`,{ params: { appCode: this.projectCode, dicName: this.currentDicName, currentId: treeNode.$vnode.data.key, projectName: this.projectConfig?.projectName ?? '' } }).then((res:any)=> { if(res.errcode === 0) { treeNode.dataRef.children = res.data; } }) //@ts-ignore resolve(); }); } onSelect(key:string,e:any) { this.currentNode = e.selectedNodes[0].data.props.dataRef } async onModalOkTree() { if(this.currentNode) this.setValue(cloneDeep({ name: this.currentNode.taskName, id: this.currentNode.id, task_name: this.currentNode.taskName, code_name: this.currentNode.taskName })); this.visibleTreeDig = false; } onModalCancelTree() { this.visibleTreeDig = false; } mounted() { this.getTreeConfig() } } </script> <style scoped lang="less"> .ant-input-suffix > i { color: #ccc; } .relevance-form-tree { height: 100%; .anticon-close-circle { cursor: pointer; transition: color 0.3s; font-size: 12px; &:hover { color: #999; } &:active { color: #666; } } } .fullscreen { position: absolute; top: 16px; right: 60px; cursor: pointer; } .full-modal .fullscreen { right: 16px; } .full-modal { /deep/ .ant-modal { height: 100%; top: 0; padding-bottom: 0; .ant-modal-content { height: 100%; } } } /deep/ .ant-modal-body { height: 400px; overflow: auto; } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Web page CSS --> <link rel="stylesheet" href="assets/css/styles.css" /> <!-- Simple lightbox CSS --> <link rel="stylesheet" href="assets/css/simple-lightbox.min.css" /> <!-- Favicons --> <link rel="apple-touch-icon" sizes="180x180" href="assets/icons/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="assets/icons/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="assets/icons/favicon-16x16.png" /> <!-- Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Caveat:wght@400..700&display=swap" rel="stylesheet"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Rock+Salt&display=swap" rel="stylesheet"> <title>Landing Page</title> </head> <body> <!-- Navbar --> <nav> <a> <h1 id="nav-title">perfect blues</h1> </a> <ul> <li class="nav-item"> <a href="#perfect" class="nav-link" id="nav-link">Perfect</a> </li> <li class="nav-item"> <a href="#pictures" class="nav-link" id="nav-link">Pictures</a> </li> <li class="nav-item"> <a href="#albums" class="nav-link" id="nav-link">Albums</a> </li> <li class="nav-item"> <a href="#sub" class="nav-link" id="nav-link">Contact us</a> </li> </ul> <!-- Dark/light theme switcher --> <div class="theme-switch"> <input type="checkbox" class="checkbox" id="checkbox" /> <label for="checkbox" class="label"> <ion-icon name="partly-sunny-outline" class="sun"></ion-icon> <ion-icon name="moon-outline" class="moon"></ion-icon> <div class="switcher"></div> </label> </div> <!-- Bars --> <div class="hamburger" id="hamburger"> <div class="bar"></div> <div class="bar"></div> <div class="bar"></div> </div> </nav> <!-- Hero section --> <section class="hero"> <div class="intro-text"> <h1> <span class="hear">Playing the perfect blues</span> <br /> <span class="connecting">Happy moments, take a breath</span> </h1> <h3 class="sub">Singing a perfect tune</h3> <a class="btn black" href="#">Feeling creatures</a> <a class="btn blue" href="#">in the depth</a> </div> <div class="i-frame"> <iframe width="560" height="315" src="https://www.youtube.com/embed/M-9PLDrC_vQ?si=FhA4hS-BRNRNuoy1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> <div class="stand-1"></div> <div class="stand-2"></div> </div> </section> <!-- More lyrics section --> <section class="about" id="perfect"> <h3 class="hear">Perfect background, perfect light.</h3> <p class="connecting">Perfect scenery, perfect sight</p> <h3 class="hear">Perfect sunshine, perfect night</h3> <p class="connecting">Perfect everything, perfect life</p> </section> <!-- Lightbox image gallery --> <section class="stars" id="pictures"> <div class="stars-gallery"> <a class="big"> <img src="assets/images/cover.jpeg" alt="album cover" title="Album Cover" /> </a> <a class="big"> <img src="assets/images/hannah1.jpeg" alt="Hannah on a surf boat" title="Hannah Bahng" /> </a> <a class="big"> <img src="assets/images/hannah2.png" alt="Hannah with waves behind her" title="Hannah Bahng" /> </a> <a class="big"> <img src="assets/images/hannah3.jpeg" alt="Hannah taking a selfie at the beach" title="Hannah Bahng" /> </a> <a class="big"> <img src="assets/images/hannah4.webp" alt="Hannah looking straight at the camera" title="Hannah Bahng" /> </a> </div> </section> <!-- album cover --> <section class="album" id="albums"> <div class="albums"> <div class="music"> <div class="album-1"> <img src="assets/images/cover.jpeg" alt="John Doe" /> <p class="album-name">perfect blues</p> <p class="name">By Hannah Bahng</p> </div> <div class="album-2"> <img src="assets/images/the-abysmal-ep.png" alt="Jane Doe" /> <p class="album-name">The Abysmal EP</p> <p class="name">By Hannah Bahng</p> </div> </div> </div> </section> <!-- Email subscription --> <section class="sub" id="sub"> <h3>Subscribe to our newsletter for updates</h3> <form action="#"> <input type="email" name="email" id="email-sub" class="email-sub" required /> <input type="submit" value="Subscribe" id="submit-btn" class="submit-btn" /> </form> </section> <!-- Social icons --> <section class="social"> <h3>Connect with us on Social Media</h3> <div class="socicons"> <a href="#"><ion-icon name="logo-twitter"></ion-icon></a> <a href="#"><ion-icon name="logo-instagram"></ion-icon></a> <a href="#"><ion-icon name="logo-facebook"></ion-icon></a> </div> </section> <footer>&copy;2024. All Rights Reserved</footer> <!-- Scroll to top button --> <i class="scroll-up" id="scroll-up"> <img src="assets/icons/up-arrow.png" class="socicon up-arrow" alt="up-arrow" /> </i> <!-- Web page script --> <script src="assets/js/app.js"></script> <!-- Ion icons CDN --> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <!-- Simple lightbox --> <script src="assets/js/simple-lightbox.min.js"></script> <script> var lightbox = new SimpleLightbox(".stars-gallery a"); </script> </body> </html>
import { createSlice } from "@reduxjs/toolkit"; import { SearchAlarm } from '@/types/Alarm'; import previewBtn from '@/assets/images/btn/preview.png'; import previewBtnActive from '@/assets/images/btn/preview_active.png'; import analysis from '@/assets/images/btn/analysis.png'; import analysisActive from '@/assets/images/btn/analysis_active.png'; import alarm from '@/assets/images/btn/alarm.png'; import alarmActive from '@/assets/images/btn/alarm_active.png'; import calc from '@/assets/images/btn/calc.png'; import calcActive from '@/assets/images/btn/calc_active.png'; import app from '@/assets/images/btn/app.png'; import appActive from '@/assets/images/btn/app_active.png'; import setting from '@/assets/images/btn/setting.png'; import settingActive from '@/assets/images/btn/setting_active.png'; interface menuState { menu: Array<{ key: string; btn: string; activeBtn: string; }>; } export interface State { menu: menuState; } export const menuSlice = createSlice({ name: "menu", initialState: { menu: [ { key: '/home/preview', btn: previewBtn, activeBtn: previewBtnActive }, { key: '/home/analysis', btn: analysis, activeBtn: analysisActive }, { key: '/home/alarm', btn: alarm, activeBtn: alarmActive }, { key: '/home/calc', btn: calc, activeBtn: calcActive }, { key: '/home/app', btn: app, activeBtn: appActive }, { key: '/home/setting', btn: setting, activeBtn: settingActive }, ], }, reducers: { changeMenu(state: menuState, action) { state = Object.assign(state, { ...action.payload}); }, } }); export const { changeMenu, } = menuSlice.actions;