text
stringlengths
184
4.48M
<!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>Online Portfolio</title> <!-- Link To CSS --> <link rel="stylesheet" href="./css/style.css"> <!-- Box Icons --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css"> </head> <body> <!-- Navbar --> <header> <a href="#" class="logo">Brijesh Upadhyay</a> <div class="bx bx-menu" id="menu-icon"></div> <ul class="navbar"> <li><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#skills">Skills</a></li> <!-- <li><a href="#services">Services</a></li> --> <li><a href="#portfolio">Projects</a></li> <li><a href="#contact">Contact</a></li> <div class="bx bx-moon" id="darkmode"></div> </ul> </header> <!-- Home --> <section class="home" id="home"> <div class="social"> <!-- <a href="#"><i class='bx bxl-github'></i></a> <a href="#"><i class='bx bxl-dribbble' ></i></a> <a href="#"><i class='bx bxl-behance' ></i></a> --> </div> <div class="home-img"> <img src="xxx.png" alt=""> </div> <div class="home-text"> <span>Namaste, I'm</span> <h1>Brijesh Upadhyay</h1> <h2>Frontend Developer</h2> <p>I would love to hear from you. Whether it's a project, job, opportunity, or just a chat.<br><br> Feel free to.......</p> <a href="#contact" class="btn">Contact Me</a> </div> </section> <!-- About --> <section class="about" id="about"> <div class="heading"> <h2>About Me</h2> <span>Introduction</span> </div> <!-- About Content --> <div class="about-container"> <div class="about-img"> <img src="about.png" alt=""> </div> <div class="about-text"> <p>I am a passtionate Front-End Web Developer using web technologies to build amazing products and focusing on solving problems for differnt niches and industries using power of technology.</p> <div class="information"> <!-- Box 1 --> <div class="info-box"> <i class='bx bxs-user' ></i> <span>Brijesh Upadhyay</span> </div> <!-- Box 2 --> <div class="info-box"> <i class='bx bxs-phone' ></i> <span>+69 420 666 000</span> </div> <!-- Box 3 --> <div class="info-box"> <i class='bx bxs-envelope' ></i> <span>highcash69@gmail.com</span> </div> </div> <a href="#" class="btn">Resume</a> </div> </div> </section> <!-- Skills --> <section class="skills" id="skills"> <div class="heading"> <h2>Skills</h2> <span>My Skills</span> </div> <!-- Skills Content --> <div class="skills-container"> <div class="bars"> <!-- Box 1 --> <div class="bars-box"> <h3>HTML</h3> <span>94%</span> <div class="light-bar"></div> <div class="percent-bar html-bar"></div> </div> <!-- Box 2 --> <div class="bars-box"> <h3>CSS</h3> <span>84%</span> <div class="light-bar"></div> <div class="percent-bar css-bar"></div> </div> <!-- Box 3 --> <div class="bars-box"> <h3>JavaScript</h3> <span>74%</span> <div class="light-bar"></div> <div class="percent-bar js-bar"></div> </div> <!-- Box 4 --> <div class="bars-box"> <h3>React</h3> <span>80%</span> <div class="light-bar"></div> <div class="percent-bar react-bar"></div> </div> </div> <div class="skills-img"> <img src="123.png" alt=""> </div> </div> </section> <!-- Services --> <!-- <section class="services" id="services"> <div class="heading"> <h2>Services</h2> <span>Our Services</span> </div> <div class="services-content"> <div class="services-box"> <i class='bx bx-code-alt' ></i> <h3>Web Development</h3> <a href="#">Learn More</a> </div> <div class="services-box"> <i class='bx bx-server' ></i> <h3>Backend Development</h3> <a href="#">Learn More</a> </div> <div class="services-box"> <i class='bx bx-brush' ></i> <h3>UI/UX Design</h3> <a href="#">Learn More</a> </div> <div class="services-box"> <i class='bx bxl-wordpress' ></i> <h3>Wordpress Developer</h3> <a href="#">Learn More</a> </div> </div> </section> --> <!-- Portfolio --> <section class="portfolio" id="portfolio"> <div class="heading"> <h2>Projects</h2> <span>My recent Work</span> </div> <div class="portfolio-content"> <div class="portfolio-img"> <img src="proj1.png" alt=""> </div> <div class="portfolio-img"> <img src="proj2.png" alt=""> </div> <div class="portfolio-img"> <img src="proj3.png" alt=""> </div> <div class="portfolio-img"> <img src="proj4.png" alt=""> </div> <div class="portfolio-img"> <img src="proj5.png" alt=""> </div> <div class="portfolio-img"> <img src="proj6.png" alt=""> </div> </div> </section> <!-- Contact --> <section class="contact" id="contact"> <div class="heading"> <h2>Contact</h2> <span>Connect with me</span> </div> <div class="contact-form"> <form action="http://localhost:8000/get-info" method="post"> <input type="text" name="name" placeholder="Your Name"> <input type="email" name="email" id="" placeholder="Your Email"> <textarea name="data" id="" cols="30" rows="10" placeholder="Write Your Message Here..."></textarea> <input type="submit" value="Send" class="contact-button"> </form> </div> </section> <!-- Footer --> <div class="footer"> <h2>Socials</h2> <div class="footer-social"> <a href="#"><i class='bx bxl-facebook' ></i></a> <a href="#"><i class='bx bxl-twitter' ></i></a> <a href="#"><i class='bx bxl-instagram' ></i></a> <a href="#"><i class='bx bxl-youtube' ></i></a> </div> </div> <!-- Copyright --> <!-- <div class="copyright"> <p>Create By <a href="">Foolish Developer</a> | All Right Reserved.</p> </div> --> <!-- Link To JS --> <script src="./js/script.js"></script> </body> </html>
import { useEffect, useState } from "react"; import pokeApi from "../../api/pokeApi"; import Spinner from "../Spinner"; import PokemonCard from "../PokemonCard/PokemonCard"; import SearchBar from "../SearchBar/SearchBar"; import PokemonModal from "../PokemonModal/PokemonModal"; import noImg from '../../assets/images/noImg.png'; const URL = import.meta.env.VITE_API_URL; const PokeApi = () => { // hooks const [pokemons, setPokemons] = useState([]); const [loading, setLoading] = useState(true); const [originalPokemonsArray, setOriginalPokemonsArray] = useState([]); const [selectedPokemon, setSelectedPokemon] = useState({}); const [isModalOpen, setIsModalOpen] = useState(false); const [offset, setOffset] = useState(0) // functs const handleDelete = (id) => { const updatePokemons = pokemons.filter((pokemon) => pokemon.id !== id); setPokemons(updatePokemons); }; const openModal = (pokemon) => { setIsModalOpen(true); setSelectedPokemon(pokemon); }; const closeModal = () => { setIsModalOpen(false); setSelectedPokemon(null); }; const handleClickOffset = (num) => { setLoading(true); setOffset((prev) => prev + num); }; // effects useEffect(() => { const fetchData = async () => { const data = await pokeApi(URL + `&offset=${offset}`); // console.log(data); // creamos una variable que contenga la info // que necesito de todos los pokemons // Será una promesa que consumiré // cuando todas las promesas hagan resolve const pokemonsData = await Promise.all( data.map(async ({ url }) => { try { const resp = await fetch(url); if (!resp.ok) throw new Error("Error map fetching"); const pokemonDetails = await resp.json(); const pokemonObject = { id: pokemonDetails.id, name: pokemonDetails.name, image: pokemonDetails.sprites.other.dream_world.front_default || pokemonDetails.sprites.other["official-artwork"].front_default || pokemonDetails.sprites.other.home.front_default || pokemonDetails.sprites.front_default || noImg, image2: pokemonDetails.sprites.other["official-artwork"].front_default || noImg, image3: pokemonDetails.sprites.other.home.front_default || noImg, imageAnimFront: pokemonDetails.sprites.other.showdown.front_default || noImg, imageAnimBack: pokemonDetails.sprites.other.showdown.back_default || noImg, abilities: pokemonDetails.abilities, stats: pokemonDetails.stats, type: pokemonDetails.types, height: pokemonDetails.height, weight: pokemonDetails.weight, media: ( pokemonDetails.stats.reduce((a, b) => a + b.base_stat, 0) / pokemonDetails.stats.length ).toFixed(2), }; return pokemonObject; } catch (error) { console.error(error); } }), ); setPokemons(pokemonsData); setOriginalPokemonsArray(pokemonsData); // console.log(pokemonsData); // como hemos terminado de cargar ... setLoading(false); }; fetchData(); }, [offset]); return ( <> <SearchBar pokemons={originalPokemonsArray} setPokemons={setPokemons} /> <div className="mx-auto w-1/2 flex justify-between"> {offset > 0 ? ( <button className="mt-4 p-2 bg-blue-500 text-white rounded" onClick={() => handleClickOffset(-100)} > -100 </button> ) : ( <><div className="mt-4 p-2 bg-red-500 text-white rounded line-through">-100</div></> )} <div className="mt-4 p-2 bg-slate-200 text-gray-800 font-semibold rounded"> {offset} - {offset+99} </div> {offset < 1300 ? ( <button className="mt-4 p-2 bg-blue-500 text-white rounded" onClick={() => handleClickOffset(+100)} > +100 </button> ) : ( <><div className="mt-4 p-2 bg-red-500 text-white rounded line-through">+100</div></> )} </div> <div className="flex flex-wrap flex-grow justify-center mb-10"> {loading ? ( <Spinner /> ) : ( pokemons.map((pokemon) => ( <PokemonCard pokemon={pokemon} key={pokemon.id} handleDelete={handleDelete} openModal={openModal} /> )) )} </div> <PokemonModal isOpen={isModalOpen} selectedPokemon={selectedPokemon} onClose={closeModal} /> </> ); }; export default PokeApi;
const Discord = require('discord.js'); module.exports = { name: 'kick', alias: [], desc: "Expulsa a alguien del servidor", usage: "kick <@miembro> [%razon]", userPerms: ["ADMINISTRATOR", "KICK_MEMBERS"], botPerms: ["MANAGE_SERVERS"], cooldown: 1000 * 5, owner: false, async execute(client, message, args, prefix){ let usuario = message.mentions.members.first() || message.guild.members.cache.get(args[0]); if (!usuario) return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle('❌ `|` Error') .setDescription('❌ `|` Debes mencionar un miembro!') .setColor('RED') .setTimestamp() ] }) let razon = args.slice(1).join(" ") || "No se ha especificado ninguna razón!"; if(usuario.id == message.guild.ownerId) return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle('❌ `|` Error') .setDescription('❌ `|` No puedes expulsar al DUEÑO del Servidor!') .setColor('RED') .setTimestamp() ] }) if (message.guild.me.roles.highest.position > usuario.roles.highest.position) { if (message.member.roles.highest.position > usuario.roles.highest.position) { usuario.send({ embeds: [ new Discord.MessageEmbed() .setTitle(`📰 \`|\` Has sido expulsado`) .setDescription(`🛠 \`|\` Has sido expulsado de __${message.guild.name}__\n**Razón:** \n\`\`\`yml\n${razon}\`\`\``) .setColor('DARK_GREY') .setTimestamp() ] }).catch(() => { return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle('❌ `|` Error') .setDescription('❌ `|` No se le ha podido enviar el DM al miembro!') .setColor('RED') .setTimestamp() ] }) }); usuario.kick([razon]).then(message => { return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle(`✅ \`|\` Usuario expulsado`) .setDescription(`✔ \`|\` Se ha expulsado exitosamente a \`${usuario.user.tag}\` *(\`${usuario.id}\`)* del servidor!**`) .addField(`❓ Razón`, `\n\`\`\`yml\n${razon}\`\`\``) .setColor('PURPLE') .setTimestamp() ] }) }).catch(() => { return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle('❌ `|` Error') .setDescription('❌ `|` No he podido expulsar al miembro!') .setColor('RED') .setTimestamp() ] }) }); } else { return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle('❌ `|` Error') .setDescription('❌ `|` Tu Rol está por __debajo__ del miembro que quieres expulsar!') .setColor('RED') .setTimestamp() ] }) } } else { return message.reply({ embeds: [ new Discord.MessageEmbed() .setTitle('❌ `|` Error') .setDescription('❌ `|` Mi Rol está por __debajo__ del miembro que quieres expulsar!') .setColor('RED') .setTimestamp() ] }) } } } /** * ____ _ _ _ _ * / ___| __ _| |_ ___ | | | |___ _ _ __ _| | * | | _ / _` | __/ _ \| | | / __| | | |/ _` | | * | |_| | (_| | || (_) | |_| \__ \ |_| | (_| | | * \____|\__,_|\__\___/ \___/|___/\__,_|\__,_|_| * */
library(R.utils) library(data.table) library(ggplot2) library(Hmisc) library(dplyr) #download.file("https://storage.googleapis.com/gtex_analysis_v8/rna_seq_data/GTEx_Analysis_2017-06-05_v8_RNASeQCv1.1.9_gene_reads.gct.gz", destfile = "gtex_read_counts.gct.gz") #gunzip("gtex_read_counts.gct.gz", remove= T) data <- fread("gtex_read_counts.gct",data.table = FALSE) View(data) #Separate to skin and combine skin dataframe and read data frames library(readr) sample <- read_delim("GTEx_Analysis_v8_Annotations_SampleAttributesDS.txt") sample1 <- as.data.frame(sample) skin1 <- sample1[which(sample1$SMTSD== 'Skin - Not Sun Exposed (Suprapubic)'), ] View(skin1) columns_rows <- colnames(data) %in% skin1$SAMPID skin_data <- data[,columns_rows] dat <- skin1[columns_rows,] #Isolate gene Id from read data and combine to skin_data Gene_ID <- data$Description gene_id <- as.data.frame(Gene_ID) View(gene_id) final_skin <- cbind(gene_id, skin_data) View(final_skin) #Generate histogram of rows hist(as.numeric(skin_data[2,]), xlab= "WASH7P", main= "WASH7P Histogram Read Count") hist(as.numeric(skin_data[18,]), xlab= "RP11-34P13.18", main= "RP11-34P13.18 Histogram Read Count") #Get mean of all rows means <- rowMeans(skin_data) means_column <- as.data.frame(means) means_column #append final_skin1 <- cbind(means_column, final_skin) View(final_skin1) #Histogram Visualization hist(log10(means), breaks=100, xlab = "Read Counts", main= "") density <- density(log10(means)) #Filters all data nrow(final_skin) skincounts <- as.numeric(final_skin) filter <- rowSums(skin_data) > 650000 skincounts <- skin_data[filter,] View(skincounts) #Another way to filter with gene names filter1 <- rowSums(skin_data[, 2:604]) > 650000 skincounts1 <- final_skin[filter1, ] View(skincounts1) class(skincounts1) write.csv(skincounts1,"C:\\Users\\cdima\\OneDrive\\Desktop\\Project\\Batch Effect\\skincounts.csv", row.names = FALSE) #Correlation cor2 <- cor(t(skincounts1[, 2:605]), method= "spearman") cor2 <- as.data.frame(cor2) class(cor2) #pastes row on top and column on end skin_gene <- rbind(skincounts1$Gene_ID, cor2) cor2$gene_id <- paste(skincounts1$Gene_ID) #Pastes column on left skin_gene1 <- cbind(skincounts1$Gene_ID, cor2) skin_gene2 <- rbind(skincounts1$Gene_ID, cor2) View(cor2) cor1 <- cor(t(skincounts), method="spearman") as.data.frame(cor1) View(cor1) skin_gene3 <- cbind(skincounts1$Gene_ID, skin_gene2) cor2 <- cor1 cor2 <- as.data.frame(cor2) write.csv(cor1,"C:\\Users\\cdima\\OneDrive\\Desktop\\Project\\newcor.csv", row.names = FALSE) write.csv(skin_gene1,"C:\\Users\\cdima\\OneDrive\\Desktop\\Project\\Batch Effect\\genecorr.csv", row.names = FALSE) #plot correlations Smad2 and smad4 plot(cor2$`46675`, cor2$`46742`, xlab = "SMAD2", ylab= "SMAD4") cor(cor2$`46675`, cor2$`46742`) summary(lm(cor2$`46675`~cor2$`46742`)) abline(lm(cor2$`46675`~cor2$`46742`)) #Merge the correlation data and geneid cor2$Gene_ID <- NA merge <- merge(gene_id, cor2, all.y=TRUE) merge1 <- cor2[gene_id$Gene_ID,] #12687 POLR2B TSHB 2490 #BIRC5 AURKB cor(final_skin$Gene_ID== "POLR2B", final_skin$Gene_ID== "TSHB") cor(final_skin$Gene_ID== "BIRC5", final_skin$Gene_ID == "AURKB") row12687 <- skincounts[12687, ] row2490 <- skincounts[2490, 1] #Histogram filtered data filtered_means <- rowMeans(skincounts) hist(log10(filtered_means), breaks=100, xlab = "Filtered Read Counts", main= "") filtered_density <- density(log10(filtered_means)) #Plot Density graphs plot(density, col=1) lines(filtered_density, col=2) #Regression by gene plot(row12687, row2490) #Load in pos and neg corr genes library(readr) pos_corr <- read_delim("skin_pos_corr_genes.txt", delim = "\t", escape_double = FALSE, col_names = FALSE, trim_ws = TRUE) pos_corr <- as.data.frame(pos_corr) new_pos <- pos_corr[pos_corr$X5 > 0.90,] View(new_pos) #Correlation Matrix and Corrleation matrix of pvalues cor <- cor(skincounts) spearman <- cor(skincounts, method = "pearson") skincount <- as.matrix(skincounts) pval <- rcorr(skincount, type = c("spearman")) cor <-as.matrix(cor) cor <- as.data.frame(cor) class(cor) write.csv(cor,"C:\\Users\\cdima\\OneDrive\\Desktop\\Project\\cor.csv", row.names = FALSE) write.csv(spearman,"C:\\Users\\cdima\\OneDrive\\Desktop\\Project\\spearman.csv", row.names = FALSE) #Correlation matrix of raw readss library(corrplot) source("http://www.sthda.com/upload/rquery_cormat.r") cormat<-rquery.cormat(skincounts, graphType="heatmap") skin2 <- skin_data for(i in 1:nrow(skin_data)) { hist(as.numeric(skin_data[i,])) } for(i in 1:5){ print(i) } #Remove unused samples filter_data <- dplyr::filter(.data = skin1, SAMPID %in% colnames(data)) View(filter_data) filt <- filter_data[columns_rows,] #Normalization normal <- DESeqDataSetFromMatrix(countData = skin_data, colData = filter_data, design = ~ 1) results <- DESeq(normal) #Volcano Plot with(results, plot(log2FoldChange, -log10(pvalue), pch=20, main="Volcano plot", xlim=c(-3,3))) #Load phenotype data and merge with Ischemic time phenotype <- read.csv("gtex_phenotypes_v8.csv") GTEx_SAMPID_to_SUBJID <- function(sampids){ stringr::str_extract(string = sampids, pattern = "GTEX-[[:alnum:]]*") } phenotype_SUBJID <- GTEx_SAMPID_to_SUBJID(phenotype$SUBJID) phenotype_SUBJID skincounts2 <- skincounts new <- GTEx_SAMPID_to_SUBJID(colnames(skincounts2)) colnames(skincounts2) <- new View(skincounts2) sampleid <-GTEx_SAMPID_to_SUBJID(colnames(skincounts)) class(sampleid) col <- colnames(skincounts2) %in% phenotype$SUBJID new_skincounts <- skincounts2[,col] join <- left_join(new_skincounts, phenotype, by= "SUBJID") #Remove first column and then get all samples from read count data into phenotype data phenotype <- phenotype[,-1 ] row <- colnames(skincounts2) %in% phenotype$SUBJID row1 <- phenotype$SUBJID %in% colnames(skincounts2) df2 <- phenotype[row1, ] #Now have a dataframe saved as df2 which has the skin count data phenotypes ischemic <- df2$TRISCHD pca <- princomp(df2$TRISCHD, cor= TRUE, score= TRUE) summary(pca) biplot(pca)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="comlib.js"></script> <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js" integrity="sha256-QvgynZibb2U53SsVu98NggJXYqwRL7tg3FeyfXvPOUY=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body> <table border="1" class="table table-bordered table-hover table-sm table-striped mt-5" style="text-align:center"> <thead class="table-dark"> <tr> <td colspan="10"><h3>學生成績測試資料產生</h3></td> </tr> <tr> <td>姓名</td> <td>國文</td> <td>英文</td> <td>數學</td> <td>計算機概論</td> <td>工廠實習</td> <td>微積分</td> <td>體育</td> <td>平均成績</td> <td>排名</td> </tr> </thead> <tbody id="scoreList"> </tbody> </table> <hr> <div id="main" style="width:800px; height:600px;"></div> <hr> <div id="main1" style="width:800px; height:600px;"></div> <hr> <div id="main2" style="width:800px; height:600px;"></div> <script> var scoreSheet = new Array(); var fail = new Array(0, 0, 0, 0, 0, 0, 0); //var rank = new Array(); var avg = 0; var rank = 0; var rankArray = []; var statistics = new Array(); // 統計各科成績分布圖 for (let i = 0; i < 7; i++) { statistics[i] = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } var scoreData = []; for (let i = 0; i < 30; i++) { scoreData = Array("Student" + (i + 1), rand(1, 100), rand(1, 100), rand(1, 100), rand(1, 100), rand(1, 100), rand(1, 100), rand(1, 100), avg, rank) let total = 0; scoreSheet.push(scoreData); // average let sum = 0; for (let j = 1; j < scoreData.length - 2; j++) { //console.log('i: ' + i + " j: " + j); //console.log(scoreSheet[i][j]); sum += scoreSheet[i][j]; scoreSheet[i][scoreData.length - 2] = (sum / (scoreData.length - 3)).toFixed(2); } rankArray[i] = (sum / (scoreData.length - 3)).toFixed(2); //計算各科不及格人數 for (let j = 1; j < 8; j++) { if (scoreSheet[i][j] < 60) { fail[j - 1]++; } statistics[j - 1][scoreAssign(scoreSheet[i][j])]++; total = total + scoreSheet[i][j]; } } //console.log(statistics); // ***RANKING*** *** indexOf*** let tempArray = []; // 排序rankArray 大 to 小 rankArray.sort(function (a, b) { return b - a; }); for (let i = 0; i < 30; i++) { scoreSheet[i][9] = (rankArray.indexOf(scoreSheet[i][8]) + 1); } //console.log(scoreSheet); //console.log(fail); render(); function render() { const scoreList = document.querySelector('#scoreList'); for (let i = 0; i < 30; i++) { const tr = document.createElement('tr'); for (let j = 0; j < 10; j++) { const td = document.createElement('td'); td.textContent = scoreSheet[i][j]; if (j == 9) { td.classList.add('rank'); td.style.color = "black" } tr.append(td); } scoreList.append(tr); } // set background-color const tds = document.querySelectorAll('td'); for (let i = 0; i < tds.length; i++) { if (parseInt(tds[i].textContent) < 60) { tds[i].style.color = "red"; } else if (parseInt(tds[i].textContent) > 95) { tds[i].style.color = "green"; tds[i].textContent = '*' + tds[i].textContent; tds[i].style.fontWeight = "bolder"; } else if (((parseInt(tds[i].textContent) > 90) && (parseInt(tds[i].textContent) < 95))) { tds[i].style.color = "green"; } // reset rank field's bgc const rankTd = document.querySelectorAll('.rank'); for (let i = 0; i < 30; i++) { rankTd[i].style.color = "black" } } // failed counts const tr = document.createElement('tr'); const td = document.createElement('td') td.textContent = '不及格人數'; tr.append(td); for (let i = 0; i < 9; i++) { const td = document.createElement('td'); if (i > 6) { td.textContent = '---'; td.classList.add('none'); } else { td.textContent = fail[i]; } tr.append(td); } scoreList.append(tr); } function scoreAssign(data = 0) { if (data == 100) { return (10); } else if (data >= 90) { return (9); } else if (data >= 80) { return (8); } else if (data >= 70) { return (7); } else if (data >= 60) { return (6); } else if (data >= 50) { return (5); } else if (data >= 40) { return (4); } else if (data >= 30) { return (3); } else if (data >= 20) { return (2); } else if (data >= 10) { return (1); } else { return (0); } } console.log('1.23' + '23'); console.log(scoreSheet); // setting avg data array let avgArrayStastic = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for (let i = 0; i < 30; i++) { let avg = parseFloat(scoreSheet[i][8]); let assign = scoreAssign(avg); avgArrayStastic[assign]++; } console.log(avgArrayStastic); </script> <script> var myChart = echarts.init(document.getElementById('main')); var clist = ['國文', '英文', '數學', '計算機概論', '工廠實習', '微積分', '體育'] </script> <script> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 指定图表的配置项和数据 var option = { title: { text: '班級成績統計圖' }, tooltip: {}, legend: { data: ['不及格人數'] }, xAxis: { data: clist//['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] }, yAxis: {}, series: [ { name: '不及格人數', type: 'bar', //data: [5, 20, 36, 10, 10, 20] data: [{ value: fail[0], itemStyle: { color: '#5470c6' } }, { value: fail[1], itemStyle: { color: '#91cc75' } }, { value: fail[2], itemStyle: { color: '#fac858' } }, { value: fail[3], itemStyle: { color: '#eee666' } }, { value: fail[4], itemStyle: { color: '#73c0de' } }, { value: fail[5], itemStyle: { color: '#3ba272' } }, { value: fail[6], itemStyle: { color: '#fc8452' } }] } ] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); </script> <hr> <script> var myChart = echarts.init(document.getElementById('main1')); var option1 = { title: { text: '各科成績分布圖' }, tooltip: { trigger: 'axis' }, legend: { //data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine'] data: clist }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { feature: { saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: ['0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80-89', '90-99', '100'] }, yAxis: { }, series: [ { name: clist[0], type: 'line', stack: 'Total', data: statistics[0] }, { name: clist[1], type: 'line', stack: 'Total', data: statistics[1] }, { name: clist[2], type: 'line', stack: 'Total', data: statistics[2] }, { name: clist[3], type: 'line', stack: 'Total', data: statistics[3] }, { name: clist[4], type: 'line', stack: 'Total', data: statistics[4] }, { name: clist[5], type: 'line', stack: 'Total', data: statistics[5] }, { name: clist[6], type: 'line', stack: 'Total', data: statistics[6] } ] }; myChart.setOption(option1); </script> <hr> <script> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main2')); // 指定图表的配置项和数据 var option2 = { title: { text: '平均成績分布', subtext: '圓餅圖', left: 'center' }, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: 'left' }, series: [ { name: '平均成績', type: 'pie', radius: '50%', data: [ { value: avgArrayStastic[0], name: '0-9分: ' + avgArrayStastic[0] + '人' }, { value: avgArrayStastic[1], name: '10-19分: ' + avgArrayStastic[1] + '人' }, { value: avgArrayStastic[2], name: '20-29分: ' + avgArrayStastic[2] + '人' }, { value: avgArrayStastic[3], name: '30-39分: ' + avgArrayStastic[3] + '人' }, { value: avgArrayStastic[4], name: '40-49分: ' + avgArrayStastic[4] + '人' }, { value: avgArrayStastic[5], name: '50-59分: ' + avgArrayStastic[5] + '人' }, { value: avgArrayStastic[6], name: '60-69分: ' + avgArrayStastic[6] + '人' }, { value: avgArrayStastic[7], name: '70-79分: ' + avgArrayStastic[7] + '人' }, { value: avgArrayStastic[8], name: '80-89分: ' + avgArrayStastic[8] + '人' }, { value: avgArrayStastic[9], name: '90-99分: ' + avgArrayStastic[9] + '人' }, { value: avgArrayStastic[10], name: '100分: ' + avgArrayStastic[10] + '人' }, ], emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option2); </script> </body> </html>
import { ButtonPropsColorOverrides, ColorPaletteProp, ModalDialog, Typography } from '@mui/joy'; import Button from '@mui/joy/Button'; import Modal from '@mui/joy/Modal'; import { OverridableStringUnion } from '@mui/types'; interface ConfirmModalProps { isOpen: boolean; close: () => void; title: string; description: string; onConfirm: () => void; confirmLabel?: string; cancelLabel?: string; confirmColor?: OverridableStringUnion<ColorPaletteProp, ButtonPropsColorOverrides>; cancelColor?: OverridableStringUnion<ColorPaletteProp, ButtonPropsColorOverrides>; } const ConfirmModal = (props: ConfirmModalProps) => { return ( <Modal open={props.isOpen} onClose={props.close}> <ModalDialog aria-labelledby="basic-modal-dialog-title" aria-describedby="basic-modal-dialog-description" sx={{ maxWidth: 500 }} > <Typography id="basic-modal-dialog-title" component="h2"> {props.title} </Typography> <Typography id="basic-modal-dialog-description" textColor="text.tertiary"> {props.description} </Typography> <div style={{ width: '100%', display: 'flex', flexDirection: 'row', }} > <Button onClick={() => { props.onConfirm(); props.close(); }} style={{ marginRight: '0.5rem' }} color={props.confirmColor || 'primary'} > {props.confirmLabel || 'Bekræft'} </Button> <Button onClick={props.close} color={props.cancelColor || 'danger'}> {props.cancelLabel || 'Annuller'} </Button> </div> </ModalDialog> </Modal> ); }; export default ConfirmModal;
/* * Copyright (C) 2010-2012 Dmitry Marakasov * * This file is part of glosm. * * glosm is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * glosm 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with glosm. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef TILEMANAGER_HH #define TILEMANAGER_HH #include <glosm/BBox.hh> #include <glosm/Projection.hh> #include <pthread.h> #include <list> #include <map> #include <set> class Geometry; class GeometryDatasource; class Viewer; class Tile; /** * Generic quadtree tile manager * * This class is serves as a base class for layers and manages tile * loading, displaying and disposal. * * @todo this class is planned to handle multilayer tile hierarchies, * however for now level is fixed */ class TileManager { public: enum RequestFlags { SYNC = 0x01, BLOB = 0x02, }; protected: /** * Tile identifier */ struct TileId { int level; int x; int y; TileId(int lev, int xx, int yy) : level(lev), x(xx), y(yy) { } inline bool operator==(const TileId& other) const { return x == other.x && y == other.y && level == other.level; } inline bool operator!=(const TileId& other) const { return x != other.x || y != other.y || level != other.level; } }; /** * Single node of a quadtree */ struct QuadNode { Tile* tile; int generation; BBoxi bbox; QuadNode* childs[4]; QuadNode() : tile(NULL), generation(0), bbox(BBoxi::ForGeoTile(0, 0, 0)) { childs[0] = childs[1] = childs[2] = childs[3] = NULL; } }; /** * Single tile loading request */ struct TileTask { TileId id; BBoxi bbox; TileTask(const TileId& i, const BBoxi& b) : id(i), bbox(b) { } }; /** * Holder of data for LoadLocality request */ struct RecLoadTilesInfo { enum Modes { BBOX, LOCALITY }; union { const Viewer* viewer; const BBoxi* bbox; }; int mode; int flags; Vector3i viewer_pos; float closest_distance; int queue_size; RecLoadTilesInfo() : queue_size(0) { } }; protected: typedef std::list<TileTask> TilesQueue; typedef std::vector<QuadNode**> GCQueue; protected: /* @todo it would be optimal to delegate these to layer via either * virtual methods or templates */ int level_; float range_; volatile int flags_; bool height_effect_; size_t size_limit_; const Projection projection_; mutable pthread_mutex_t tiles_mutex_; /* protected by tiles_mutex_ */ QuadNode root_; int generation_; size_t total_size_; int tile_count_; /* /protected by tiles_mutex_ */ mutable pthread_mutex_t queue_mutex_; pthread_cond_t queue_cond_; /* protected by queue_mutex_ */ TilesQueue queue_; TileId loading_; /* /protected by queue_mutex_ */ pthread_t loading_thread_; volatile bool thread_die_flag_; protected: /** * Constructs Tile */ TileManager(const Projection projection); /** * Destructor */ virtual ~TileManager(); /** * Spawns a single tile with specified bbox */ virtual Tile* SpawnTile(const BBoxi& bbox, int flags) const = 0; /** * Recursive tile loading function for viewer's locality * * @todo remove code duplication with RecLoadTilesBBox */ void RecLoadTilesLocality(RecLoadTilesInfo& info, QuadNode** pnode, int level = 0, int x = 0, int y = 0); /** * Recursive tile loading function for given bbox * * @todo remove code duplication with RecLoadTilesLocality */ void RecLoadTilesBBox(RecLoadTilesInfo& info, QuadNode** pnode, int level = 0, int x = 0, int y = 0); /** * Recursive function that places tile into specified quadtree point */ void RecPlaceTile(QuadNode* node, Tile* tile, int level = 0, int x = 0, int y = 0); /** * Recursive function for tile rendering * * @return 1 if whole tile was rendered, 0 otherwise */ int RecRenderTiles(QuadNode* node, const Viewer& viewer); /** * Recursive function for destroying tiles and quadtree nodes */ void RecDestroyTiles(QuadNode* node); /** * Recursive function for garbage collecting unneeded tiles */ void RecGarbageCollectTiles(QuadNode* node, GCQueue& gcqueue); /** * Thread function for tile loading */ void LoadingThreadFunc(); /** * Static wrapper for thread function */ static void* LoadingThreadFuncWrapper(void* arg); /** * Loads tiles */ void Load(RecLoadTilesInfo& info); protected: /** * Renders visible tiles */ void Render(const Viewer& viewer); protected: static bool GenerationCompare(QuadNode** x, QuadNode** y); public: /** * Loads square area of tiles */ void LoadArea(const BBoxi& bbox, int flags = 0); /** * Loads tiles in locality of Viewer */ void LoadLocality(const Viewer& viewer, int flags = 0); /** * Destroys unneeded tiles */ void GarbageCollect(); /** * Destroys all tiles */ void Clear(); /** * Sets designated tile level * * @param level desired level */ void SetLevel(int level); /** * Sets range in which tiles are visible * * @param range range in meters */ void SetRange(float range); /** * Sets flags for tile spawinig * * @param flags flags * @see GeometryGenerator::GetGeometry */ void SetFlags(int flags); /** * Sets mode of taking viewer height into account * * @param enabled if true, height is taken into account * when calculating distance from viewer to tile */ void SetHeightEffect(bool enabled); /** * Sets limit on cumulative tiles size * * @param limit size limit in bytes */ void SetSizeLimit(size_t limit); }; #endif
import React, { useRef } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { useDrop, useDrag } from 'react-dnd'; import PropTypes from 'prop-types'; import Card from './Card'; import AddButton from './AddButton'; import EditableText from './EditableText'; import actions from '../store/actions'; import combineClassNames from '@chalarangelo/combine-class-names'; const { createCard, addCardToColumn, moveCardInsideColumn, setHoveredCard, setDraggedCard, setColumnTitle } = actions; /** * Renders a column on the board, containing the provided cards. */ const Column = ({ id, index, cards, title, tags, hoveredCardId = null, hoveredCardState = false, draggedCard = null, createCard, addCardToColumn, setHoveredCard, setDraggedCard, moveCardInsideColumn, previewHeight = 0, isHovered = false, setIsHovered, isDragging = false, setDraggedColumn, handleDrop, setColumnTitle }) => { const ref = useRef(null); const [{ isOver }, drop] = useDrop({ accept: ['card', 'column'], canDrop: item => (item.type === 'column' && item.index !== isHovered.index) || (item.type === 'card' && item.sourceColumnId !== id), hover: (item, monitor) => { if (!ref.current || item.type !== 'column' || item.index === index) return; const { left, right } = ref.current.querySelector('.column').getBoundingClientRect(); const hoverMiddleX = (right - left) / 2 + left; const clientOffsetX = monitor.getClientOffset().x; if (clientOffsetX < hoverMiddleX) setIsHovered({ position: 'before', index }); else if (clientOffsetX > hoverMiddleX) setIsHovered({ position: 'after', index: index + 1 }); }, drop: (item, monitor) => { if(item.type === 'card') { if (!monitor.canDrop()) return; const hasBeenHandled = monitor.didDrop() && monitor.getDropResult().handled; if (!hasBeenHandled) addCardToColumn(item.id, id, hoveredCardState.index); } if(item.type === 'column' && item.index !== isHovered.index) { handleDrop(item.id, isHovered.index); setIsHovered(false); return { handled: true }; } }, collect: monitor => { if (!ref.current) return { isOver: monitor.isOver() }; if (monitor.didDrop() || !isDragging) setIsHovered(false); return { isOver: monitor.isOver() }; }, }); const [style, drag] = useDrag({ item: { id, type: 'column', index }, collect: monitor => ({ opacity: monitor.isDragging() ? 0 : 1, display: monitor.isDragging() ? 'none' : 'block' }), begin: () => { if (!ref.current) return; const { height } = ref.current.getBoundingClientRect(); setDraggedColumn({ id, height }); }, end: () => { setDraggedColumn(null); } }); drag(drop(ref)); const isEmptyHovered = !cards.length && isOver && draggedCard !== null; return ( <div className={combineClassNames`column-wrapper ${isHovered ? 'with-previews' : ''}`} ref={ref} style={{ ...style, display: isHovered ? 'flex' : style.display }} > { isHovered && isHovered.position === 'before' && <div className="column-preview" style={{ height: previewHeight }}/> } <div className="column"> <div className="column-title"> <h3> <EditableText id={`column-name-${id}`} name={`column-name-${id}`} value={title} onChange={val => { setColumnTitle(id, val); }} /> </h3> <button className="btn btn-column-menu icon icon-more-horizontal" /> </div> <ul className={combineClassNames`column-content ${isEmptyHovered ? 'hover' : ''}`} ref={ref} style={{ height: isEmptyHovered ? draggedCard.height : '' }} > {cards.filter(card => !card.archived).map((card, i) => ( <Card key={card.id} card={{ ...card, tags: card.tags.map(t => tags[t]) }} columnId={id} index={i} previewHeight={draggedCard !== null ? draggedCard.height : 0} isHovered={hoveredCardId === card.id ? hoveredCardState : false} setIsHovered={hovered => setHoveredCard(card.id, hovered)} setDraggedCard={setDraggedCard} isDragging={draggedCard !== null} handleDrop={moveCardInsideColumn} /> ))} </ul> <AddButton id={`btn-${id}`} name={`btn-${id}`} onSubmit={cardTitle => createCard({ title: cardTitle }, id)} buttonText="Add a card" submitText="Add Card" wrapperClassName="column-action-add" buttonClassName="btn-column-add" inputClassName="input-column-add" /> </div> { isHovered && isHovered.position === 'after' && <div className="column-preview" style={{ height: previewHeight }}/> } </div> ); }; Column.propTypes = { id: PropTypes.string.isRequired, index: PropTypes.number.isRequired, cards: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired })).isRequired, title: PropTypes.string.isRequired, tags: PropTypes.shape({}).isRequired, hoveredCardId: PropTypes.string, hoveredCardState: PropTypes.oneOfType([ PropTypes.shape({ position: PropTypes.string, index: PropTypes.number }), PropTypes.bool ]), draggedCard: PropTypes.oneOfType([ PropTypes.shape({ id: PropTypes.string, height: PropTypes.number }), PropTypes.bool ]), createCard: PropTypes.func.isRequired, addCardToColumn: PropTypes.func.isRequired, setHoveredCard: PropTypes.func.isRequired, setDraggedCard: PropTypes.func.isRequired, moveCardInsideColumn: PropTypes.func.isRequired, setColumnTitle: PropTypes.func.isRequired }; const mapStateToProps = state => { return { hoveredCardId: state.interface.hoveredCardId, draggedCard: state.interface.draggedCard, hoveredCardState: state.interface.hoveredCardState }; }; const mapDispatchToProps = dispatch => { return { createCard: bindActionCreators(createCard, dispatch), addCardToColumn: bindActionCreators(addCardToColumn, dispatch), setHoveredCard: bindActionCreators(setHoveredCard, dispatch), setDraggedCard: bindActionCreators(setDraggedCard, dispatch), moveCardInsideColumn: bindActionCreators(moveCardInsideColumn, dispatch), setColumnTitle: bindActionCreators(setColumnTitle, dispatch) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Column);
import React, { useState } from 'react' const Lesson72 = () => { const [workers, setWorkers] = useState({ employees: [ { name: 'Serioga', surname: 'Bryk', salary: 800, checked: true }, { name: 'Grigory', surname: 'Pipka', salary: 1000, checked: true }, { name: 'Valera', surname: 'Groznyi', salary: 2000, checked: true }, { name: 'Ludmila', surname: 'Voznik', salary: 500, checked: true }], sumSalaries: 4300 }); const Table = ({ data, funcSumm }) => { return ( <table> <tbody> {data.map((item, index) => ( <tr > <td width="40%">{item.name}</td> <td width="20%">{item.surname}</td> <td width="40%">{item.salary}</td> <td><input type="checkbox" key={index} checked={item.checked} onChange={() => funcSumm(index)} /></td> </tr> ))} </tbody> </table> ); }; const sumSal = (index) => { const copy = { ...workers }; copy.employees[index].checked = !copy.employees[index].checked; copy.employees[index].checked === true ? (copy.sumSalaries += copy.employees[index].salary) : (copy.sumSalaries -= copy.employees[index].salary); setWorkers(copy); }; return <div> <Table data={workers.employees} funcSumm={sumSal} /> <p>{workers.sumSalaries}</p> </div> } export default Lesson72
// React import React from 'react'; // React router dom import { useNavigate, Link } from 'react-router-dom'; // Sweet alert import Swal from 'sweetalert2'; // Mis importaciones import { elementosPrueba } from '../../data/elements'; export const CollectionDetail = () => { const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; const collection = elementosPrueba[0]; const navigate = useNavigate(); const deleteCollection = () => { Swal.fire({ title: 'Quieres eliminar la colección y todos sus elementos?', showDenyButton: true, confirmButtonText: '<i className="fa-solid fa-check"></i> Si, eliminar', denyButtonText: '<i className="fa-solid fa-ban"></i> No, conservar', }).then((result) => { if (result.isConfirmed) { Swal.fire('Colección eliminada!', '', 'success').then(() => { navigate('/'); }); } else if (result.isDenied) { Swal.fire('No se ha eliminado la colección', '', 'error'); } }) } return ( <div className='collectionDetail'> <div className="detail"> <img style={{width: '250px'}} src={collection.cover} alt={collection.title} /> <div className="container"> <h2>{collection.autor} | {collection.title}</h2> <p>Categoría: {collection.category}</p> <p>{collection.date.toLocaleDateString('es-ES', options)}</p> <p>{collection.text}</p> <div className="btns"> <Link to='edit' className='btn'> <span><i className="fa-solid fa-pen-to-square"></i> Editar</span> <span><i className="fa-solid fa-pen-to-square"></i> Editar</span> </Link> <a className='btn' onClick={deleteCollection}> <span><i className="fa-solid fa-trash"></i> Eliminar</span> <span><i className="fa-solid fa-trash"></i> Eliminar</span> </a> </div> </div> </div> <div className="gallery container"> <ul className="image-gallery"> { collection.elements.map((element, idx) => ( <li key={idx}> <img src={element.image} alt="" /> <div className="overlay"><span>{element.description}</span></div> </li> )) } </ul> </div> </div> ) }
import Link from 'next/link'; import ThemeToggler from './ThemeToggler'; import { usePathname } from 'next/navigation'; const navigationLinks = [ { path: '/blog', label: 'Blog', }, { path: '/projects', label: 'Projects', }, { path: 'https://github.com/cakegod', label: 'Github', }, { path: '/contact', label: 'Contact', }, ]; function Header() { const pathname = usePathname(); const underlineNavLink = (path: string) => pathname === `${path}` ? 'dark text-red-600 dark:text-red-400 underline decoration-1' : ''; return ( <header className='border-b border-zinc-300 pb-12 dark:border-zinc-700'> <div className='flex items-center justify-between pb-10'> <Link href='/' className='cursor-pointer text-4xl font-bold text-pink-800 dark:text-pink-400 md:text-5xl' > Cake&apos;s Blog </Link> <ThemeToggler /> </div> <nav className='flex justify-between text-lg font-medium dark:text-zinc-300 md:text-xl [&>*]:transition-colors hover:[&>*]:text-red-600 dark:[&>*]:transition-colors dark:hover:[&>*]:text-red-400'> {navigationLinks.map(({ path, label }) => ( <Link key={path} href={path} className={underlineNavLink(path)}> {label} </Link> ))} </nav> </header> ); } export default Header;
namespace ScreenSound.Modelos { // O termo internal está relacionado a visibilidade de classes. Apenas o projeto consegue enxergar esta classe. internal class Avaliacao { public Avaliacao(int nota) { Nota = nota; } public int Nota { get; } // Os métodos static são funções que não depende de nenhuma variável de instância (new), quando invocados executam uma função sem a dependência do conteúdo de um objeto. // Veremos que as instruções dentro do método Avaliacao Parse() não utilizam nada de fora da instância do objeto, como, por exemplo, nota. // Neste tipo de cenário, podemos marcar este método como estático. Dessa forma, ele se tornará apenas uma função com elementos autocontidos. // O static informa que o conteúdo executado não utiliza nenhuma informação da instância desta classe — no caso, Avaliacao. Podemos chamar o método diretamente pelo tipo. public static Avaliacao Parse(string texto) { int nota = int.Parse(texto); return new Avaliacao(nota); } } }
import React from "react"; import { Solver } from "../solver/Solver"; export const ShowSolutions: ({ solver, }: { solver: Solver | undefined; }) => JSX.Element = ({ solver }) => { if (solver === undefined) return <></>; const solutions = solver.solve().map((s) => s.prettyPrint); return ( <div data-cy="solutions-display" data-testid="solutions-display"> {solutions.length === 0 ? ( <NoSolutions /> ) : ( <Solutions solutions={solutions} /> )} </div> ); }; const Solutions: ({ solutions }: { solutions: string[] }) => JSX.Element = ({ solutions, }) => { return ( <div data-testid="solutions-list"> <ul> {solutions.map((s) => { return <li key={s}>{s}</li>; })} </ul> </div> ); }; const NoSolutions: () => JSX.Element = () => { return <p data-testid="no-solutions">This one was impossible</p>; };
import React, { useState } from "react"; import AttendedLecture from "./Components/AttendedLecture"; import TotalLectures from "./Components/TotalLectures"; import Button from "./Components/Button"; import Percentage from "./Components/Percentage"; const Attendence = () => { const [attendedLecture, setAttendedLecture] = useState(); const [totalLectures, setTotalLectures] = useState(); const [percentage, setPercentage] = useState(0); const [needLecture, setNeedLecture] = useState('😊'); const [emoji,setEmoji]=useState(null) const calculatePercentage = () => { if(Number(totalLectures)>=Number(attendedLecture)){ const percent = (attendedLecture / totalLectures) * 100; setPercentage(`${percent.toFixed(2)}`); if (percent >= 75) { setNeedLecture("WOW !!🤩 You have reached 75% attendence"); setEmoji('🥳') } else { const needAttendence = Math.ceil(0.75 * totalLectures - attendedLecture); setNeedLecture(`Oh No!! ☹️ You are required to attend ${needAttendence} lectures`); setEmoji('😮') } } else{ alert("Attend lectures should be less than or equal to total lectures") } }; return ( <div className="w-full h-screen flex flex-col justify-center items-center gap-10 tracking-wider"> <div className="text-3xl font-extrabold text animate-pulse"> Attendence Tracker App </div> <TotalLectures totalLectures={totalLectures} setTotalLectures={setTotalLectures} /> <AttendedLecture attendedLecture={attendedLecture} setAttendedLecture={setAttendedLecture} /> <Button calculatePercentage={calculatePercentage} /> <Percentage percent={percentage} needLecture={needLecture} emoji={emoji} /> <footer className="bg-sky-700 w-full h-10 text-white items-center flex justify-center my-0 absolute bottom-0"> Made By Aastha Kalra &#10084; </footer> </div> ); }; export default Attendence;
import { useState } from "react"; import { Button, Grid, TextField, Box, Typography, IconButton, } from "@mui/material"; import RemoveCircleIcon from "@mui/icons-material/RemoveCircle"; import AddCircleIcon from "@mui/icons-material/AddCircle"; import { useMembers } from "../hooks/useMembers"; import shuffle from "lodash.shuffle"; type divideTeamProps = { backgroundColors: string[]; }; function DivideTeam({ backgroundColors }: divideTeamProps) { const [members] = useMembers(); const [teamNum, setTeamNum] = useState(1); const [teamUsers, setTeamUsers] = useState<string[]>([]); const handleIncrement = () => { if (teamNum === 4) return; setTeamNum(teamNum + 1); }; const handleDecrement = () => { if (teamNum === 1) return; setTeamNum(teamNum - 1); }; const shuffleList = () => { setTeamUsers(shuffle(members.map((v) => v.option))); }; return ( <> <Grid container direction="column" alignItems="center" justifyContent="center" spacing={2} > <Grid item> <Grid container spacing={1} alignItems="center"> <Grid item> <IconButton onClick={handleDecrement}> <RemoveCircleIcon color="primary" /> </IconButton> </Grid> <Grid item> <TextField id="standard-number" label="チーム数(最大4)" value={teamNum} type="number" defaultValue={1} inputProps={{ style: { textAlign: "center" }, inputMode: "numeric", pattern: "[0-9]*", min: 1, // 最小値 max: 4, // 最大値 }} variant="standard" style={{ width: 100 }} onChange={(event) => setTeamNum(Number(event.target.value))} /> </Grid> <Grid item> <IconButton onClick={handleIncrement}> <AddCircleIcon color="primary" /> </IconButton> </Grid> </Grid> </Grid> <Grid item xs={12}> <Button variant="contained" onClick={shuffleList}> Go! </Button> </Grid> </Grid> {teamUsers.length !== 0 && [...Array(teamNum)].map((_, i) => ( <Grid container alignItems="center" justifyContent="center" direction="column" spacing={1} mt={2} > <Grid item xs={12} key={i}> <Typography variant="h6" color="inherit" noWrap> チーム{i + 1} </Typography> </Grid> {teamUsers.map( (user: string, index) => i === index % teamNum && ( <Grid item xs={12} key={user}> <Box key={user} sx={{ borderRadius: 2, backgroundColor: backgroundColors[i % 4], color: "white", textAlign: "center", whiteSpace: "nowrap", width: 160, height: 40, lineHeight: "40px", }} > {user} </Box> </Grid> ) )} </Grid> ))} </> ); } export default DivideTeam;
/* mpfr_get_ld, mpfr_get_ld_2exp -- convert a multiple precision floating-point number to a machine long double Copyright 2002-2015 Free Software Foundation, Inc. Contributed by the AriC and Caramel projects, INRIA. This file is part of the GNU MPFR Library. The GNU MPFR Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MPFR Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <float.h> #include "mpfr-impl.h" #if defined(HAVE_LDOUBLE_IS_DOUBLE) /* special code when "long double" is the same format as "double" */ long double mpfr_get_ld (mpfr_srcptr x, mpfr_rnd_t rnd_mode) { return (long double) mpfr_get_d (x, rnd_mode); } #elif defined(HAVE_LDOUBLE_IEEE_EXT_LITTLE) /* special code for IEEE 754 little-endian extended format */ long double mpfr_get_ld (mpfr_srcptr x, mpfr_rnd_t rnd_mode) { mpfr_long_double_t ld; mpfr_t tmp; int inex; MPFR_SAVE_EXPO_DECL (expo); MPFR_SAVE_EXPO_MARK (expo); mpfr_init2 (tmp, MPFR_LDBL_MANT_DIG); inex = mpfr_set (tmp, x, rnd_mode); mpfr_set_emin (-16382-63); mpfr_set_emax (16384); mpfr_subnormalize (tmp, mpfr_check_range (tmp, inex, rnd_mode), rnd_mode); mpfr_prec_round (tmp, 64, MPFR_RNDZ); /* exact */ if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (tmp))) ld.ld = (long double) mpfr_get_d (tmp, rnd_mode); else { mp_limb_t *tmpmant; mpfr_exp_t e, denorm; tmpmant = MPFR_MANT (tmp); e = MPFR_GET_EXP (tmp); /* The smallest positive normal number is 2^(-16382), which is 0.5*2^(-16381) in MPFR, thus any exponent <= -16382 corresponds to a subnormal number. The smallest positive subnormal number is 2^(-16445) which is 0.5*2^(-16444) in MPFR thus 0 <= denorm <= 63. */ denorm = MPFR_UNLIKELY (e <= -16382) ? - e - 16382 + 1 : 0; MPFR_ASSERTD (0 <= denorm && denorm < 64); #if GMP_NUMB_BITS >= 64 ld.s.manl = (tmpmant[0] >> denorm); ld.s.manh = (tmpmant[0] >> denorm) >> 32; #elif GMP_NUMB_BITS == 32 if (MPFR_LIKELY (denorm == 0)) { ld.s.manl = tmpmant[0]; ld.s.manh = tmpmant[1]; } else if (denorm < 32) { ld.s.manl = (tmpmant[0] >> denorm) | (tmpmant[1] << (32 - denorm)); ld.s.manh = tmpmant[1] >> denorm; } else /* 32 <= denorm < 64 */ { ld.s.manl = tmpmant[1] >> (denorm - 32); ld.s.manh = 0; } #else # error "GMP_NUMB_BITS must be 32 or >= 64" /* Other values have never been supported anyway. */ #endif if (MPFR_LIKELY (denorm == 0)) { ld.s.exph = (e + 0x3FFE) >> 8; ld.s.expl = (e + 0x3FFE); } else ld.s.exph = ld.s.expl = 0; ld.s.sign = MPFR_IS_NEG (x); } mpfr_clear (tmp); MPFR_SAVE_EXPO_FREE (expo); return ld.ld; } #else /* generic code */ long double mpfr_get_ld (mpfr_srcptr x, mpfr_rnd_t rnd_mode) { if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (x))) return (long double) mpfr_get_d (x, rnd_mode); else /* now x is a normal non-zero number */ { long double r; /* result */ long double m; double s; /* part of result */ mpfr_exp_t sh; /* exponent shift, so that x/2^sh is in the double range */ mpfr_t y, z; int sign; #if defined(HAVE_LDOUBLE_MAYBE_DOUBLE_DOUBLE) if (MPFR_LDBL_MANT_DIG == 106) { /* Assume double-double format (as found with the PowerPC ABI). The generic code below isn't used because numbers with precision > 106 would not be supported. */ sh = 0; /* force sh to 0 otherwise if say x = 2^1023 + 2^(-1074) then after shifting mpfr_get_d (y, rnd_mode) will underflow to 0 */ mpfr_init2 (y, mpfr_get_prec (x)); mpfr_init2 (z, IEEE_DBL_MANT_DIG); /* keep the precision small */ mpfr_set (y, x, rnd_mode); /* exact */ s = mpfr_get_d (x, MPFR_RNDN); /* high part of x */ mpfr_set_d (z, s, MPFR_RNDN); /* exact */ mpfr_sub (y, x, z, MPFR_RNDN); /* exact */ /* Add the second part of y (in the correct rounding mode). */ r = (long double) s + (long double) mpfr_get_d (y, rnd_mode); } else #endif { /* First round x to the target long double precision, so that all subsequent operations are exact (this avoids double rounding problems). However if the format contains numbers that have more precision, MPFR won't be able to generate such numbers. */ mpfr_init2 (y, MPFR_LDBL_MANT_DIG); mpfr_init2 (z, MPFR_LDBL_MANT_DIG); /* Note about the precision of z: even though IEEE_DBL_MANT_DIG is sufficient, z has been set to the same precision as y so that the mpfr_sub below calls mpfr_sub1sp, which is faster than the generic subtraction, even in this particular case (from tests done by Patrick Pelissier on a 64-bit Core2 Duo against r7285). But here there is an important cancellation in the subtraction. TODO: get more information about what has been tested. */ mpfr_set (y, x, rnd_mode); sh = MPFR_GET_EXP (y); sign = MPFR_SIGN (y); MPFR_SET_EXP (y, 0); MPFR_SET_POS (y); r = 0.0; do { s = mpfr_get_d (y, MPFR_RNDN); /* high part of y */ r += (long double) s; mpfr_set_d (z, s, MPFR_RNDN); /* exact */ mpfr_sub (y, y, z, MPFR_RNDN); /* exact */ } while (!MPFR_IS_ZERO (y)); } mpfr_clear (z); mpfr_clear (y); /* we now have to multiply back by 2^sh */ MPFR_ASSERTD (r > 0); if (sh != 0) { /* An overflow may occur (example: 0.5*2^1024) */ while (r < 1.0) { r += r; sh--; } if (sh > 0) m = 2.0; else { m = 0.5; sh = -sh; } for (;;) { if (sh % 2) r = r * m; sh >>= 1; if (sh == 0) break; m = m * m; } } if (sign < 0) r = -r; return r; } } #endif /* contributed by Damien Stehle */ long double mpfr_get_ld_2exp (long *expptr, mpfr_srcptr src, mpfr_rnd_t rnd_mode) { long double ret; mpfr_exp_t exp; mpfr_t tmp; if (MPFR_UNLIKELY (MPFR_IS_SINGULAR (src))) return (long double) mpfr_get_d_2exp (expptr, src, rnd_mode); tmp[0] = *src; /* Hack copy mpfr_t */ MPFR_SET_EXP (tmp, 0); ret = mpfr_get_ld (tmp, rnd_mode); if (MPFR_IS_PURE_FP(src)) { exp = MPFR_GET_EXP (src); /* rounding can give 1.0, adjust back to 0.5 <= abs(ret) < 1.0 */ if (ret == 1.0) { ret = 0.5; exp ++; } else if (ret == -1.0) { ret = -0.5; exp ++; } MPFR_ASSERTN ((ret >= 0.5 && ret < 1.0) || (ret <= -0.5 && ret > -1.0)); MPFR_ASSERTN (exp >= LONG_MIN && exp <= LONG_MAX); } else exp = 0; *expptr = exp; return ret; }
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*- ;;; copyright (c) 2017 David D. McDonald -- all rights reserved ;;; ;;; File: "gloss-interpretations" ;;; Module: "interface;mumble;" ;;; Version: October 2017 ;; initiated 10/12/17 for the code that takes an sexp representing the ;; interpretation of an utterance by the BA and renders it into Engish. (in-package :sparser) #| Given a s-exp lifted from the capability of a method or in general any ECI restatement of the results of a TRIPS parse, translate it to the corresponding Krisp individual. The entry point gloss-BA-interpretation does all of the coarse, across the board changes operating over the s-expression. This includes renaming role keywords that are always different in the Krisp ontology (rename-roles-as-needed), and renaming symbols that are different between the two ontologies (rename-eci-terms-as-needed). Then it calls gloss-interpretation, which recursively walks through the s-exp, which is structured as a plist. The :isa tag is used to lookup the Krisp category to use (corresponding-krisp-category) which is usually a direct symbol-names-category relationship but can also use a stipulated mapping like the role and symbols do. From the category we get an individual and bind its variables by walking through the rest of the expression. Identifiers in the sub-expressions can identify specific, already created entities (find-individual-for-gloss) or will make a fresh one given the category. Given the individual that has been retrieved or made using the description lattice, the next step would be to apply any needed default information (tense, mood, definiteness) and produce a text. |# ;;--- examples to start from (defparameter capability-1 '(a ?g :isa put :agent SYS :theme (a ?blk :isa block) :final-location (a ?loc :isa on :ground (a ?shelf :isa shelf))) "From cwc-integ/spire/data/executive-structured-goals.lisp") ;; (gloss-BA-interpretation capability-1) (defparameter interp-to-gloss-1 '(a goal0 :isa put :agent SYS :theme (a b1 :isa block) :final-location (a * :isa on :ground (a the-shelf :isa shelf))) "From cwc-integ/spire/test/test/lisp") ;; (gloss-BA-interpretation interp-to-gloss-1) ;;--- driver and minions (defun gloss-BA-interpretation (raw-sexp) "Entry point for the interpretation expression. Does rote massaging of data types and values that aren't knowledge-based then calls gloss interpretation to do the converstion to Krisp." (let* ((sexp (reintern-symbols raw-sexp (find-package :sparser)))) (rename-roles-as-needed sexp) (rename-eci-terms-as-needed sexp) (gloss-interpretation sexp))) (defun gloss-interpretation (sexp) "Fixed point in the recursive walk through the sexp. First it decodes the sexp, e.g. (a b1 :isa block) by picking out the specifier ('a') and identifier ('b1'), plus the remaining role/value information in the sexp. Then it determines the Krisp category to use and get the base individual ('i'). The walk through the remainder of the expression (the role / value pairs) binds the appropriate variables on the individual, which we return as the value of the function." (cond ((symbolp sexp) (find-individual-for-gloss sexp nil)) (t (let* ((specifier (first sexp)) (identifier (second sexp)) (name-of-predicate (cadr (memq :isa sexp))) (arg-plist (cdr (memq name-of-predicate sexp))) (role-names (loop for term in arg-plist when (keywordp term) collect term))) (assert (eq specifier 'a) (sexp) "Dont' know how to understand a Spire expression like this ~a" sexp) (let ((category (corresponding-krisp-category name-of-predicate role-names))) ;; need a fallback strategy for when we can't get a category (let ((i (individual-for-gloss identifier category))) (do ((var-name (car arg-plist) (car rest)) (value-exp (cadr arg-plist) (cadr rest)) (rest (cddr arg-plist) (cddr rest))) ((null var-name)) (let ((var (find-variable-for-category var-name category)) (j (gloss-interpretation value-exp))) (setq i (bind-variable var j i)))) i)))))) ;;--- Find or make individual (defun individual-for-gloss (identifier category) "Return an individual of that category that we can retrieve from that indentifier if there is one, otherwise we'll make a new one" (or (find-individual-for-gloss identifier category) (individual-for-ref category))) (defun find-individual-for-gloss (identifier category) ;; a set of unfortunately specific cases (declare (ignore category)) (let* ((id-string (symbol-name identifier)) (id-in-mumble (intern id-string (find-package :mumble)))) (cond ((eq identifier '*) nil) ;; placeholder case ((eql (elt id-string 0) #\?) ;; it's a variable (formulate-individual-for-variable identifier category)) ((and (or (eql (elt id-string 0) #\b) ;; name of a block (eql (elt id-string 0) #\B)) (= 2 (length id-string))) (let ((block-name (string-append "B" (elt id-string 1)))) (find-individual 'block :name block-name))) ((boundp id-in-mumble) ;; *the-table* (eval id-in-mumble)) ((boundp identifier) ;; *me* (eval identifier))))) (defun formulate-individual-for-variable (identifier category) ;;TO-DO e.g. 'a block', 'a gene' ) ;;--- translate roles (defparameter *spire-to-krisp-role-renaming* '((:final-location . :location)) "Substitutions to make between Spire ECIs and Krisp") (defun rename-roles-as-needed (sexp) "Runs for side-effects. Works on the entire tree at once to all levels." (nsublis *spire-to-krisp-role-renaming* sexp)) ;;--- translate stray symbols (defparameter *eci-term-names-to-krisp* '((SYS . *me*) ;; see model/core/mid-level/interlocutor.lisp (the-shelf . *the-shelf*) ;; see blocks-world/entities.lisp ) "For swapping the names for things that aren't the same between ECI and Krisp models (for no good reason probably). Note that a symbol like *me* is a global that's bound to an individual.") (defun rename-eci-terms-as-needed (sexp) (nsublis *eci-term-names-to-krisp* sexp)) ;;--- translate category #| We could just do this as an in-line table in the ECIs like we note related concepts in VerbNet or TRIPS. Question is whether the mapping would vary according to which roles get values. |# (defparameter *eci-names-to-krisp-category-names* `((put . put-something-somewhere)) "Correspondence of symbol naming ECI (via :isa) to name of equivalent Krisp category.") (defun corresponding-krisp-category (eci-name role-names) (declare (ignore role-names)) (or (category-named eci-name) (let* ((cat-name (cdr (assq eci-name *eci-names-to-krisp-category-names*))) (category (category-named cat-name))) (assert category (eci-name) "No corresponding Krisp category defined for ECI ~a" eci-name) category)))
--- title: '2.4.4 - Directory Tree' --- For relatively small websites, ad-hoc side-loading is available directly from a folder structure on the hard drive. This is intended for loading manuals, documentation and similar data sets that are large and slowly changing. A website can be archived with wget, like this ```bash wget -nc -x --continue -w 1 -r -A "html" "docs.marginalia.nu" ``` After doing this to a bunch of websites, create a YAML file in the upload directory, with contents something like this: ```yaml sources: - name: jdk-20 dir: "jdk-20/" domainName: "docs.oracle.com" baseUrl: "https://docs.oracle.com/en/java/javase/20/docs" keywords: - "java" - "docs" - "documentation" - "javadoc" - name: python3 dir: "python-3.11.5/" domainName: "docs.python.org" baseUrl: "https://docs.python.org/3/" keywords: - "python" - "docs" - "documentation" - name: mariadb.com dir: "mariadb.com/" domainName: "mariadb.com" baseUrl: "https://mariadb.com/" keywords: - "sql" - "docs" - "mariadb" - "mysql" ``` The fields in the above are |parameter|description| |----|----| |name|Purely informative| |dir|Path of website contents relative to the location of the yaml file| |domainName|The domain name of the website| |baseUrl|This URL will be prefixed to the contents of `dir`| |keywords|These supplemental keywords will be injected in each document| The directory structure corresponding to the above might look like this: ``` docs-index.yaml jdk-20/ jdk-20/resources/ jdk-20/api/ jdk-20/api/[...] jdk-20/specs/ jdk-20/specs/[...] jdk-20/index.html mariadb.com mariadb.com/kb/ mariadb.com/kb/[...] python-3.11.5 python-3.11.5/genindex-B.html python-3.11.5/library/ python-3.11.5/distutils/ python-3.11.5/[...] [...] ``` So e.g. the file `jdk-20/api/java.base/java/lang/Thread.html` would refer to the URL `https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/Thread.html`. After creating the directory structure, go to the `Index Nodes -> Node N -> Actions -> Sideload Dirtree`, and select the directory containing the structure. Then click 'Sideload Dirtree`. This will process the data, so that it can be loaded. <figure> <img src="load-dirtree.webp"> <figcaption>Sideload Dirtree form</figcaption> </figure> As usual with sideloaded data, after the data has been processed it can be loaded by going to `Index Nodes -> Node N -> Actions -> Load Processed Data`.
<html ng-app="rtfclusterdemo"> <head> <title>MuleSoft Training</title> <!-- Load JS libraries --> <script src="/js/angular-1.4.8.min.js"></script> <script src="/js/bootstrap-3.3.1.min.js"></script> <script src="/js/commons.js"></script> <script src="/js/pagination.min.js"></script> <script src="/js/jquery-3.1.1.min.js"></script> <!-- CSS files --> <link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" media="all"> <link rel="stylesheet" type="text/css" href="/css/bootstrap-theme.min.css" media="all"> <link rel="stylesheet" type="text/css" href="/css/mu.css" media="all"> </head> <body class="grey-bg"> <script> function showElement(id) { document.getElementById(id).style.visibility = 'visible'; } function hideElement(id) { document.getElementById(id).style.visibility = 'hidden'; } function removeElement(id) { document.getElementById(id).remove(); } var app = angular.module("rtfclusterdemo", []); app.controller("memstatsController", function($scope, $http) { $scope.results = []; $scope.sortKey = 'applicationID'; $scope.reverse = false; $http.get("/api/memory").success(function (response) { $scope.results = response; removeElement('loadingView'); showElement('statsResultsView'); }); $scope.parJson = function (json) { return angular.fromJson(json); } }); </script> <div id="title-bar"> <img src="https://www.mulesoft.com/sites/default/files/training.png" class="title-bar-logo"> MuleSoft Training </div> <div id="sub-title-bar"> <table> <tr> <td><a href="http://www.mulesoft.com">MuleSoft Home</a></td> <td><a href="https://anypoint.mulesoft.com/login/">Anypoint Platform Login</a></td> <td><a href="http://training.mulesoft.com">MuleSoft Training</a></td> <td><a href="https://docs.mulesoft.com/general/">Documentation</a></td> <td><a href="https://forums.mulesoft.com/index.html">Community Forum</a></td> </tr> </table> </div> <div class="container" id="mainContent"> <div class="contentHeading"> <h4>Anypoint Platform Operations: Runtime Fabric</h4> <hr /> </div> <!-- Temporary view "Loading data" --> <div id="loadingView" class="container"> <table class="dialog"> <tr class="dialogheader"><td>Info</td></tr> <tr><td>Gathering statistics. Please wait...</td></tr> </table> </div> <!-- Processing results view --> <div id="statsResultsView" class="container" ng-controller="memstatsController" style="visibility: hidden"> <div> <h4>JVM Memory Statistics</h4> </div> <table id="statsResultsTable" class="table table-striped table-condensed"> <thead> <tr class="thead"> <th align="center" width="200" ><font color='#ffffff'>Parameter</font></th> <th align="center"><font color='#ffffff'>Value</font></th> </tr> </thead> <tbody> <tr> <td class="line">JVM Total Memory</td> <td class="line">{{results['JVM total memory']}}</td> </tr> <tr> <td class="line">JVM Used Memory</td> <td class="line">{{results['JVM used memory']}}</td> </tr> <tr> <td class="line">JVM Free Memory</td> <td class="line">{{results['JVM free memory']}}</td> </tr> <tr> <td class="line">Heap Max Size</td> <td class="line">{{results['Heap max size']}}</td> </tr> <tr> <td class="line">Heap Init Size</td> <td class="line">{{results['Heap init size']}}</td> </tr> <tr> <td class="line">Heap Committed</td> <td class="line">{{results['Heap commited']}}</td> </tr> <tr> <td class="line">Heap Used Size</td> <td class="line">{{results['Heap used size']}}</td> </tr> </tbody> </table> </div> </div> </body> </html>
document.addEventListener("DOMContentLoaded", function() { // Sample data for the Bar Chart and Line Graph const barChartCanvas = document.getElementById("barChart").getContext("2d"); const barChart = new Chart(barChartCanvas, { type: "bar", data: { labels: ["A", "B", "C", "D", "E"], datasets: [{ label: "Bar Chart Data", data: [30, 45, 22, 60, 12], backgroundColor: "#3498db", }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } } } }); const lineGraphCanvas = document.getElementById("lineGraph").getContext("2d"); const lineGraph = new Chart(lineGraphCanvas, { type: "line", data: { labels: ["Jan", "Feb", "Mar", "Apr", "May"], datasets: [{ label: "Line Graph Data", data: [10, 25, 18, 40, 32], borderColor: "#e74c3c", fill: false, }] }, options: { responsive: true, maintainAspectRatio: false, scales: { y: { beginAtZero: true } } } }); });
<template> <div class="top"> <div class="content"> <div class="left" @click="$router.push('/home')"> <img src="@/assets/images/desktop_1.jpg" alt="logo" /> <p>预约挂号统一平台</p> </div> <div class="right"> <div class="help">帮助中心</div> <div class="login" @click="handleLogin" v-if="!UserStore.userInfo.token">登录 / 注册</div> <div class="userInfo" v-else> <el-dropdown> <span class="el-dropdown-link"> {{ UserStore.userInfo.name }} <el-icon class="el-icon--right"> <arrow-down /> </el-icon> </span> <template #dropdown> <el-dropdown-menu> <el-dropdown-item @click="$router.push('/user/certification')" >实名认证</el-dropdown-item > <el-dropdown-item @click="$router.push('/user/order')">挂号订单</el-dropdown-item> <el-dropdown-item @click="$router.push('/user/infomation')" >就诊人管理</el-dropdown-item > <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item> </el-dropdown-menu> </template> </el-dropdown> </div> </div> </div> </div> </template> <script lang="ts" setup> import { ArrowDown } from '@element-plus/icons-vue' import useUserStore from '@/stores/modules/user' const UserStore = useUserStore() import router from '@/router' //登录 const handleLogin = () => { UserStore.LoginShow = true } //退出登录 const handleLogout = () => { UserStore.logout() router.replace('/home') } </script> <style scoped lang="scss"> .top { position: fixed; z-index: 2; width: 100%; height: 90px; display: flex; justify-content: center; background-color: #fff; border-bottom: 1px solid #ccc; } .content { width: 1200px; height: 90px; display: flex; justify-content: space-between; align-items: center; background-color: #fff; } .left { display: flex; align-items: center; img { display: block; width: 60px; height: 60px; border-radius: 50%; margin-right: 10px; } p { font-size: 20px; color: rgb(92, 185, 231); } } .right { display: flex; align-items: center; font-size: 14px; color: #aaa; .help { margin-right: 10px; } } .login, .userInfo { cursor: pointer; &:hover { color: #4fadeb; } } </style>
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "huffman.h" // Intermediate form for trees (gets converted to tables) typedef struct huffman_node { short value; long freq; struct huffman_node *left, *right; } huffman_node; void build_tree(huffman_node *pos, long prefix, short length, hufftable *table); void print_tree(huffman_node *pos, const char *parent_prefix, const char *postfix); //{{{ huffman_node *make_tree(long *char_frequencies) { int i, j; int num_top_nodes = 256; int lowest, lowest2, lowest_val; huffman_node *nodes[256]; huffman_node *node_buf; for(i=0; i<256; i++) { nodes[i] = (huffman_node*)malloc(sizeof(huffman_node)); nodes[i]->value = i; nodes[i]->freq = char_frequencies[i]; nodes[i]->left = NULL; nodes[i]->right = NULL; } // Do combinations do { lowest = 0; lowest_val = LONG_MAX; // Find lowest freq for(j=0; j<num_top_nodes; j++) { if(nodes[j]->freq < lowest_val) { lowest = j; lowest_val = nodes[j]->freq; } } lowest2 = 0; lowest_val = LONG_MAX; // Find second-lowest freq for(j=0; j<num_top_nodes; j++) { if(nodes[j]->freq < lowest_val && j != lowest) { lowest2 = j; lowest_val = nodes[j]->freq; } } // Set representations node_buf = (huffman_node*)malloc(sizeof(huffman_node)); node_buf->value = 0; node_buf->freq = nodes[lowest]->freq + nodes[lowest2]->freq; node_buf->left = nodes[lowest]; node_buf->right = nodes[lowest2]; nodes[lowest] = node_buf; nodes[lowest2] = nodes[--num_top_nodes]; } while(num_top_nodes > 1); return nodes[0]; } //}}} //{{{ void make_table(huffman_node *root, hufftable *table) { build_tree(root->left, 0, 1, table); build_tree(root->right, 1, 1, table); } //}}} //{{{ int compare_hufftab_entry(const huffdecompresstable_entry *one, const huffdecompresstable_entry *two) { if(one->binrep > two->binrep) return 1; else if(one->binrep == two->binrep) return 0; else return -1; } //}}} //{{{ void make_decompress_table(hufftable *table, huffdecompresstable *decompress_table) { int i; for(i=0; i<256; i++) { decompress_table->entries[i].binrep = table->rep[i] << (16 - table->replen[i]); // Move data to most significant bits decompress_table->entries[i].binreplen = table->replen[i]; decompress_table->entries[i].byterep = i; } qsort(decompress_table, 256, sizeof(huffdecompresstable_entry), &compare_hufftab_entry); } //}}} //{{{ void build_tree(huffman_node *pos, long prefix, short length, hufftable *table) { if(pos->left && pos->right) { build_tree(pos->left, prefix<<1, length+1, table); build_tree(pos->right, (prefix<<1)|1, length+1, table); } else { table->replen[pos->value] = length; table->rep[pos->value] = prefix; } } //}}} //{{{ void print_tree(huffman_node *pos, const char *parent_prefix, const char *postfix) { char prefix[32]; strcpy(prefix, parent_prefix); strcat(prefix, postfix); if(pos->left && pos->right) { print_tree(pos->left, prefix, "0"); print_tree(pos->right, prefix, "1"); } else { printf("%3i(%3li)=%s\n", pos->value, pos->freq, prefix); } } //}}} //{{{ void count_frequencies(long *char_frequencies, unsigned char *buf, int length) { int i; for(i=0; i<256; i++) char_frequencies[i] = 0; for(i=0; i<length; i++) char_frequencies[ buf[i] ]++; for(i=0; i<256; i++) // Don't allow for zero frequencies if(char_frequencies[i] == 0) char_frequencies[i]++; } //}}} //{{{ void huffify(char *filename) { unsigned char *buf = malloc(65536); // GENERALIZEME int size, i; long frequencies[256]; hufftable table; huffdecompresstable decompress_table; FILE *fin = fopen(filename, "rb"); FILE *fout; huffman_node *hufftree; size = fread(buf, 1, 65536, fin); count_frequencies(frequencies, buf, size); hufftree = make_tree(frequencies); make_table(hufftree, &table); make_decompress_table(&table, &decompress_table); // Write tables in C header form to file fout = fopen("hufftable.h", "w"); if(fout) { fprintf(fout, "/* Generated file - Do not edit. */\n" "#include \"huffman.h\"\n"); fprintf(fout, "const hufftable huff_compress = {\n" "\t{\n" "\t\t0x%lX", (long)table.rep[0]); for(i=1; i<256; i++) fprintf(fout, ", 0x%lX", (long)table.rep[i]); fprintf(fout, "},\n\t{ %i", (int)table.replen[0]); for(i=1; i<256; i++) fprintf(fout, ", %i", (int)table.replen[i]); fprintf(fout, " }\n};\n\n"); fprintf(fout, "const huffdecompresstable huff_decompress = {\n" "\t{\n" "\t\t{0x%X, %i, 0x%X}", (int)decompress_table.entries[0].binrep, (int)decompress_table.entries[0].binreplen, (int)decompress_table.entries[0].byterep); for(i=1; i<256; i++) fprintf(fout, ",\n\t\t" "{0x%X, %i, 0x%X}", (int)decompress_table.entries[i].binrep, (int)decompress_table.entries[i].binreplen, (int)decompress_table.entries[i].byterep); fprintf(fout, "\n\t}\n};\n"); fclose(fout); } } //}}} //{{{ int main(int argc, char **argv) { int i; for(i=1; i<argc; i++) huffify(argv[i]); return 0; } //}}}
/* eslint-disable react/prop-types */ /* eslint-disable react/no-unstable-nested-components */ import React, { useState } from 'react'; import { Box, Paper, Tab, Tabs, Typography } from '@mui/material'; import Login from './Login/Login'; import Signup from './Signup/Signup'; import './auth.css'; function SignInOutContainer() { const [value, setValue] = useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; const paperStyle = { width: 340, margin: "20px auto", backgroundColor: 'rgba(78, 66, 92, 0.4)', color: "gold" }; function TabPanel(props) { const { children, index, } = props; return ( <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} > {value === index && ( <Box> <Typography>{children}</Typography> </Box> )} </div> ); } return ( <div className="authContainer"> <Paper elevation={20} style={paperStyle} > <Tabs value={value} indicatorColor="primary" textColor="primary" onChange={handleChange} aria-label="disabled tabs example" > <Tab sx={{ fontFamily: 'Montserrat sans-serif', color: "gold" }} label="Вход" /> <Tab sx={{ fontFamily: 'Montserrat sans-serif', color: "gold" }} label="Регистрация" /> </Tabs> <TabPanel value={value} index={0}> <Login /> </TabPanel> <TabPanel value={value} index={1}> <Signup /> </TabPanel> </Paper> </div> ); } export default SignInOutContainer;
// import 'dart:convert'; // import 'dart:math'; // import 'package:firebase_core/firebase_core.dart'; // import 'package:firebase_messaging/firebase_messaging.dart'; // import 'package:flutter/material.dart'; // import 'package:flutter_local_notifications/flutter_local_notifications.dart'; // import 'package:http/http.dart' as http; // import 'package:provider/provider.dart'; // import 'package:rafu_store_app/GenericHelpers/common_helpers.dart'; // import 'package:rafu_store_app/Home/features/notifications/notification_provider.dart'; // import 'package:rafu_store_app/Utils/print_debug.dart'; // import '../../../GenericHelpers/petite_storage.dart'; // import '../../../main.dart'; // final FirebaseMessaging messaging = // FirebaseMessaging.instance; // @pragma('vm:entry-point') // Future<void> backgroundMessageHandler( // RemoteMessage message) async { // print("Handling a background message: ${message.data}"); // await Firebase.initializeApp(); // LocalNotificationService.initialize(); // await StorageUtil.getInstance(); // await showNotification(message); // print( // "Handling a background message: ${message.messageId}"); // } // void registerBackgroundMessageHandler() { // FirebaseMessaging.onBackgroundMessage( // backgroundMessageHandler); // } // Future<void> myBackgroundMessageHandler( // RemoteMessage message) async { // // Handle background message // await showNotification(message); // } // final FlutterLocalNotificationsPlugin // flutterLocalNotificationsPlugin = // FlutterLocalNotificationsPlugin(); // const AndroidNotificationChannel channel = // AndroidNotificationChannel( // 'high_importance_channel', // id // 'High Importance Notifications', // title // importance: Importance.high, // ); // Future<void> showNotification(RemoteMessage message) async { // logg("Remote message ${message}"); // // RemoteNotification? notification = message.notification; // // AndroidNotification? android = // // message.notification != null ? message.notification!.android : null; // if (message.data != null) { // // Create a new AndroidNotificationDetails object // final AndroidNotificationDetails // androidPlatformChannelSpecifics = // AndroidNotificationDetails(channel.id, channel.name, // channelDescription: channel.description, // importance: Importance.max, // priority: Priority.high, // ticker: 'ticker'); // // Create a new NotificationDetails object // final NotificationDetails platformChannelSpecifics = // NotificationDetails( // android: androidPlatformChannelSpecifics); // Random random = new Random(); // int id = random.nextInt(1000); // // Show the notification // await flutterLocalNotificationsPlugin.show( // id, // getStringFromMap(message.data, 'title'), // getStringFromMap(message.data, 'message') // .toString(), // platformChannelSpecifics, // payload: getStringFromMap(message.data, 'body')); // } // } // // click action // Future selectNotification(String? payload) { // // Handle notification tap // if (payload != null) { // logg('notification payload: $payload'); // } // return Future.value(true); // } // class LocalNotificationService { // static final FlutterLocalNotificationsPlugin // _flutterLocalNotificationsPlugin = // FlutterLocalNotificationsPlugin(); // static void initialize() { // final InitializationSettings initializationSettings = // InitializationSettings( // android: AndroidInitializationSettings( // "@mipmap/launcher_icon")); // _flutterLocalNotificationsPlugin.initialize( // initializationSettings, // onDidReceiveNotificationResponse: // (NotificationResponse // notificationResponse) async { // logg("From Res"); // if (notificationResponse.payload != null) { // StorageUtil.resetpreferencedata( // key: 'from_notification'); // StorageUtil.resetpreferencedata(key: 'payload'); // StorageUtil.putString( // key: 'from_notification', value: 'true'); // StorageUtil.putString( // key: 'payload', // value: // jsonEncode(notificationResponse.payload)); // } // // final String? payload = notificationResponse.payload; // // if (notificationResponse.payload != null) { // // debugPrint('notification payload: $payload'); // // } // // await Navigator.push( // // context, // // MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)), // // ); // }, // // onDidReceiveBackgroundNotificationResponse: notificationTapBackground, // ); // } // static void display(RemoteMessage message) async { // try { // print("In Notification method"); // // int id = DateTime.now().microsecondsSinceEpoch ~/1000000; // Random random = new Random(); // int id = random.nextInt(1000); // final NotificationDetails notificationDetails = // const NotificationDetails( // android: AndroidNotificationDetails( // "mychanel", // "my chanel", // importance: Importance.max, // enableVibration: true, // playSound: true, // priority: Priority.high, // styleInformation: BigTextStyleInformation(''), // )); // print("my id is ${id.toString()}"); // await _flutterLocalNotificationsPlugin.show( // id, // message.notification!.title, // message.notification!.body, // notificationDetails, // ); // } on Exception catch (e) { // print('Error>>>$e'); // } // } // } // RemoteNotification getNoteFrom(String title, String body) { // return RemoteNotification( // title: title, // titleLocArgs: ['', ''], // titleLocKey: '', // body: body, // bodyLocArgs: ['', ''], // bodyLocKey: null, // ); // }
import { StyleSheet, View } from "react-native"; import React, { useState, useLayoutEffect } from "react"; import { KeyboardAvoidingView } from "react-native"; import { StatusBar } from "expo-status-bar"; import { Button, Input, Text } from "react-native-elements"; import { auth } from "../firebase"; export default function RegisterScreen({ navigation }) { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [imageUrl, setImageUrl] = useState(""); useLayoutEffect(() => { navigation.setOptions({ headerBackTitle: "Login", }); }, [navigation]); const register = () => { auth .createUserWithEmailAndPassword(email, password) .then((authUser) => { authUser.user.updateProfile({ displayName: name, photoURL: imageUrl || "https://www.kindpng.com/picc/m/24-248253_user-profile-default-image-png-clipart-png-download.png", }); }) .catch((error) => alert(error.message)); }; return ( <KeyboardAvoidingView behavior="padding" style={styles.container}> <StatusBar style="light" /> <Text h3 style={{ marginBottom: 50 }}> Create a Signal Account </Text> <View style={styles.inputContainer}> <Input placeholder="Full Name" autoFocus type="text" value={name} onChangeText={(text) => setName(text)} /> <Input placeholder="Email" type="text" value={email} onChangeText={(text) => setEmail(text)} /> <Input placeholder="Password" secureTextEntry type="text" value={password} onChangeText={(text) => setPassword(text)} /> <Input placeholder="Profile Picture URL(optional) " type="text" value={imageUrl} onChangeText={(text) => setImageUrl(text)} onSubmitEditing={register} /> </View> <Button style={styles.button} title="Register" onPress={register} raised /> <View style={{ height: 100 }} /> </KeyboardAvoidingView> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#fff", }, button: { width: 200, }, inputContainer: { width: 350, marginBottom: 10, }, });
<script> import { ArrowUpIcon, HelpCircleIcon } from "vue-feather-icons"; import { Carousel, Slide } from "vue-carousel"; import Navbar from "@/components/navbar"; import Switcher from "@/components/switcher"; import Footer from "@/components/footer"; import Testimonial from "@/components/testimonial"; import Pricing from "@/components/pricing"; import Pricing1 from "@/components/pricing2"; /** * Page-pricing component */ export default { data() { return { pricingData: [ { title: "Free", price: 0, feature: [ "Full Access", "Enhanced Security", "Source Files", "1 Domain Free", ], button: "Buy Now", }, { title: "Starter", price: 39, feature: [ "Full Access", "Source Files", "Free Appointments", "Enhanced Security", ], button: "Get Started", isBest: true, }, { title: "Professional", price: 59, feature: [ "Full Access", "Enhanced Security", "Source Files", "1 Domain Free", ], button: "Try it Now", }, ], testimonialData: [ { id: 1, profile: "images/client/01.jpg", message: "It seems that only fragments of the original text remain in the Lorem Ipsum texts used today.", name: "Thomas Israel", designation: "C.E.O", }, { id: 2, profile: "images/client/02.jpg", message: "One disadvantage of Lorum Ipsum is that in Latin certain letters appear more frequently than others.", name: "Barbara McIntosh", designation: "M.D", }, { id: 3, profile: "images/client/03.jpg", message: "The most well-known dummy text is the 'Lorem Ipsum', which is said to have originated in the 16th century.", name: "Carl Oliver", designation: "P.A", }, { id: 4, profile: "images/client/04.jpg", message: "According to most sources, Lorum Ipsum can be traced back to a text composed by Cicero.", name: "Christa Smith", designation: "Manager", }, { id: 5, profile: "images/client/05.jpg", message: "There is now an abundance of readable dummy texts. These are usually used when a text is required.", name: "Dean Tolle", designation: "Developer", }, { id: 6, profile: "images/client/05.jpg", message: "Thus, Lorem Ipsum has only limited suitability as a visual filler for German texts.", name: "Jill Webb", designation: "Designer", }, ], }; }, components: { Navbar, Switcher, Footer, Carousel, Slide, Pricing, Pricing1, ArrowUpIcon, HelpCircleIcon, Testimonial, }, }; </script> <template> <div> <Navbar /> <!-- Hero Start --> <section class="bg-half bg-light d-table w-100"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-12 text-center"> <div class="page-next-level"> <h4 class="title">Pricing</h4> <div class="page-next"> <nav aria-label="breadcrumb" class="d-inline-block"> <ul class="breadcrumb bg-white rounded shadow mb-0"> <li class="breadcrumb-item"> <router-link to="/">Landrick</router-link> </li> <li class="breadcrumb-item"><a href="#">Page</a></li> <li class="breadcrumb-item active" aria-current="page"> Pricing </li> </ul> </nav> </div> </div> </div> <!--end col--> </div> <!--end row--> </div> <!--end container--> </section> <!--end section--> <!-- Hero End --> <!-- Shape Start --> <div class="position-relative"> <div class="shape overflow-hidden text-white"> <svg viewBox="0 0 2880 48" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M0 48H1437.5H2880V0H2160C1442.5 52 720 0 720 0H0V48Z" fill="currentColor" ></path> </svg> </div> </div> <!--Shape End--> <!-- Price Start --> <section class="section"> <div class="container"> <div class="row justify-content-center"> <div class="col-12 text-center"> <div class="section-title mb-4 pb-2"> <h4 class="title mb-4">Pricing #1</h4> <p class="text-muted para-desc mb-0 mx-auto"> Start working with <span class="text-primary font-weight-bold">Landrick</span> that can provide everything you need to generate awareness, drive traffic, connect. </p> </div> </div> <!--end col--> </div> <!--end row--> <Pricing1 :pricingData="pricingData" /> <!--end row--> </div> <!--end container--> <div class="container mt-100 mt-60"> <div class="row justify-content-center"> <div class="col-12 text-center"> <div class="section-title mb-4 pb-2"> <h4 class="title mb-4">Pricing #2</h4> <p class="text-muted para-desc mb-0 mx-auto"> Start working with <span class="text-primary font-weight-bold">Landrick</span> that can provide everything you need to generate awareness, drive traffic, connect. </p> </div> </div> <!--end col--> </div> <!--end row--> <div class="row align-items-center"> <div class="col-12 mt-4 pt-2"> <div class="text-center"> <b-tabs pills justified nav-class="justify-content-center d-inline-block border py-1 px-2 rounded-pill" > <b-tab title-item-class="d-inline-block" title-link-class="px-3 rounded-pill" > <template v-slot:title> Monthly </template> <Pricing /> <!--end row--> </b-tab> <b-tab title-item-class="d-inline-block" title-link-class="px-3 rounded-pill" > <template v-slot:title> Yearly <span class="badge badge-pill badge-success">15% Off </span> </template> <Pricing /> <!--end row--> </b-tab> </b-tabs> </div> </div> <!--end col--> </div> <!--end row--> </div> <!--end container--> <!-- Price End --> <!-- Testi Start --> <div class="container mt-100 mt-60"> <div class="row justify-content-center"> <div class="col-12 text-center"> <div class="section-title mb-4 pb-2"> <h4 class="title mb-4">Client Reviews</h4> <p class="text-muted para-desc mx-auto mb-0"> Start working with <span class="text-primary font-weight-bold">Landrick</span> that can provide everything you need to generate awareness, drive traffic, connect. </p> </div> </div> <!--end col--> </div> <!--end row--> <div class="row justify-content-center"> <div class="col-lg-12 mt-4"> <Testimonial :testimonialData="testimonialData" /> </div> <!--end col--> </div> <!--end row--> </div> <!--end container--> </section> <!--end section--> <!-- Testi End --> <!-- FAQ n Contact Start --> <section class="section bg-light"> <div class="container"> <div class="row"> <div class="col-md-6 col-12"> <div class="media"> <help-circle-icon class="fea icon-ex-md text-primary mr-2 mt-1" ></help-circle-icon> <div class="media-body"> <h5 class="mt-0"> How our <span class="text-primary">Landrick</span> work ? </h5> <p class="answer text-muted mb-0"> Due to its widespread use as filler text for layouts, non-readability is of great importance: human perception is tuned to recognize certain patterns and repetitions in texts. </p> </div> </div> </div> <!--end col--> <div class="col-md-6 col-12 mt-4 mt-sm-0 pt-2 pt-sm-0"> <div class="media"> <help-circle-icon class="fea icon-ex-md text-primary mr-2 mt-1" ></help-circle-icon> <div class="media-body"> <h5 class="mt-0">What is the main process open account ?</h5> <p class="answer text-muted mb-0"> If the distribution of letters and 'words' is random, the reader will not be distracted from making a neutral judgement on the visual impact </p> </div> </div> </div> <!--end col--> <div class="col-md-6 col-12 mt-4 pt-2"> <div class="media"> <help-circle-icon class="fea icon-ex-md text-primary mr-2 mt-1" ></help-circle-icon> <div class="media-body"> <h5 class="mt-0">How to make unlimited data entry ?</h5> <p class="answer text-muted mb-0"> Furthermore, it is advantageous when the dummy text is relatively realistic so that the layout impression of the final publication is not compromised. </p> </div> </div> </div> <!--end col--> <div class="col-md-6 col-12 mt-4 pt-2"> <div class="media"> <help-circle-icon class="fea icon-ex-md text-primary mr-2 mt-1" ></help-circle-icon> <div class="media-body"> <h5 class="mt-0"> Is <span class="text-primary">Landrick</span> safer to use with my account ? </h5> <p class="answer text-muted mb-0"> The most well-known dummy text is the 'Lorem Ipsum', which is said to have originated in the 16th century. Lorem Ipsum is composed in a pseudo-Latin language which more or less corresponds to 'proper' Latin. </p> </div> </div> </div> <!--end col--> </div> <!--end row--> <div class="row mt-md-5 pt-md-3 mt-4 pt-2 mt-sm-0 pt-sm-0 justify-content-center" > <div class="col-12 text-center"> <div class="section-title"> <h4 class="title mb-4">Have Question ? Get in touch!</h4> <p class="text-muted para-desc mx-auto"> Start working with <span class="text-primary font-weight-bold">Landrick</span> that can provide everything you need to generate awareness, drive traffic, connect. </p> <div class="mt-4 pt-2"> <router-link to="/page-contact-two" class="btn btn-primary" >Contact us <i class="mdi mdi-arrow-right"></i ></router-link> </div> </div> </div> <!--end col--> </div> <!--end row--> </div> <!--end container--> </section> <!--end section--> <!-- FAQ n Contact End --> <!--end section--> <Footer /> <!-- Footer End --> <Switcher /> <!-- Back to top --> <a href="javascript: void(0);" class="btn btn-icon btn-primary back-to-top" id="back-to-top" v-scroll-to="'#topnav'" > <arrow-up-icon class="icons"></arrow-up-icon> </a> <!-- Back to top --> </div> </template>
import {NgModule} from "@angular/core"; import {CommonModule} from "@angular/common"; import {RouterModule, Routes} from "@angular/router"; import {ReactiveFormsModule} from "@angular/forms"; import { RegisterComponent } from './components/register/register.component'; import {StoreModule} from "@ngrx/store"; import {reducers} from "./store/reducers"; import {AuthService} from "./services/auth.service"; import {EffectsModule} from "@ngrx/effects"; import {RegisterEffect} from "./store/effects/register.effect"; import {BackendErrorMessagesModule} from "../shared/modules/backendErrorMassages/backendErrorMessages.module"; import {PersistanseService} from "../shared/services/persistanse.service"; import {LoginEffect} from "./store/effects/login.effect"; import {LoginComponent} from "./components/login/login.component"; import {GetCurrentUserEffect} from "./store/effects/getCurrentUser.effect"; const routes: Routes = [ { path: 'register', component: RegisterComponent }, { path: 'login', component: LoginComponent } ] @NgModule({ imports: [ CommonModule, RouterModule.forChild(routes), ReactiveFormsModule, StoreModule.forFeature('auth', reducers), EffectsModule.forFeature([RegisterEffect, LoginEffect, GetCurrentUserEffect]), BackendErrorMessagesModule ], declarations: [ RegisterComponent, LoginComponent ], providers: [ AuthService, PersistanseService ] }) export class AuthModule {}
# Center Point Tracking Project This project focuses on tracking people, through center points, detected in videos using YOLOv3 and OpenCV. It counts the number of center points that enter or leave a specified rectangular region and calculates the time each center point spends inside the region. The original source code was centered around simply detecting vehicles that either go up or down, which is applicable for one specific video. I changed the class to focus on identifying people instead. I also removed the lines and developed a random rectangular region of interest in the middle of the video. I adjusted the original "count_vehicle" function into a "count_person" function that has a live of counter of how many people are in the region of interest per frame. Furthermore, I also added a feature that can inform you how long each person spends within the region. ## Features - Real-time video processing using YOLOv3 and OpenCV. - Tracks center points of people. - Counts center points entering or leaving a designated rectangular region. - Calculates and displays time spent by each center point inside the region. ## Getting Started To run this project on your local machine, follow these steps: 1. Download source code from https://techvidvan.com/tutorials/opencv-vehicle-detection-classification-counting/ 2. Install dependencies from link above. 3. Replace main script with: `python center_point_timer.py` Make sure to customize the region coordinates and other settings according to your requirements. ## Dependencies - OpenCV: `pip install opencv-python` - pytube: `pip install pytube` ## Usage - Adjust the `top_left_x`, `top_left_y`, `bottom_right_x`, and `bottom_right_y` variables in the `center_point_timer.py` script to define the rectangular region of interest. - Run the script using a Python interpreter. The video feed will open, and you'll see the center points being tracked along with their stay duration in the region. ## Acknowledgements - YOLOv3: [YOLO: Real-Time Object Detection](https://pjreddie.com/darknet/yolo/) - OpenCV: [Open Source Computer Vision Library](https://opencv.org/) - Source code from: https://techvidvan.com/tutorials/opencv-vehicle-detection-classification-counting/
package org.stadium.adminapi.service.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.NotBlank; import java.math.BigDecimal; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class StadiumDto { private Long id; @NotBlank(message = "name is required") private String name; @NotBlank(message = "description is required") private String description; //Long address info @NotBlank(message = "address is required") private String address; @NotBlank(message = "shortAddress is required") private String shortAddress; @NotBlank(message = "phone1 is required") private String phone1; @NotBlank(message = "phone2 is required") private String phone2; @NotBlank(message = "email is required") private String email; private BigDecimal price; }
using eventRadar.Controllers; using eventRadar.Data.Dtos; using eventRadar.Data.Repositories; using eventRadar.Helpers; using eventRadar.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace eventRadarUnitTests { [TestClass] public class WebsiteControllerTests { private Mock<IEventRepository> _eventRepositoryMock; private EventController _controller; [TestInitialize] public void Setup() { _eventRepositoryMock = new Mock<IEventRepository>(); _controller = new EventController(_eventRepositoryMock.Object, null, null, null, null, null); } private WebsiteController SetupControllerWithMockRepo(Mock<IWebsiteRepository> mockRepo) { return new WebsiteController(mockRepo.Object); } [TestMethod] public async Task GetMany_ReturnsListOfWebsites() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); var websites = new List<Website> { new Website { Id = 1, Url = "https://example1.com" }, new Website { Id = 2, Url = "https://example2.com" } }; mockRepo.Setup(repo => repo.GetManyAsync()).ReturnsAsync(websites); var result = await controller.GetMany(); Assert.IsNotNull(result); Assert.AreEqual(2, result.Count()); } [TestMethod] public async Task Get_ReturnsNotFoundResult_WhenWebsiteDoesNotExist() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); int nonExistingWebsiteId = 3; mockRepo.Setup(repo => repo.GetAsync(nonExistingWebsiteId)).ReturnsAsync((Website)null); var result = await controller.Get(nonExistingWebsiteId); Assert.IsInstanceOfType(result.Result, typeof(NotFoundResult)); } [TestMethod] public async Task Get_ReturnsOkObjectResult_WhenWebsiteExists() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); int existingWebsiteId = 1; var existingWebsite = new Website { Id = existingWebsiteId, Url = "https://example1.com" }; mockRepo.Setup(repo => repo.GetAsync(existingWebsiteId)).ReturnsAsync(existingWebsite); var result = await controller.Get(existingWebsiteId); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(ActionResult<WebsiteDto>)); var okResult = result; Assert.IsNotNull(okResult); var websiteDto = okResult.Value as WebsiteDto; Assert.AreEqual(existingWebsite.Id, websiteDto.Id); Assert.AreEqual(existingWebsite.Url, websiteDto.Url); } [TestMethod] public async Task Create_ReturnsCreatedResult_WithWebsiteDto() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); var createWebsiteDto = new CreateWebsiteDto("https://example3.com", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath"); var createdWebsite = new Website { Id = 3, Url = "https://example3.com" }; mockRepo.Setup(repo => repo.CreateAsync(It.IsAny<Website>())).Returns(Task.CompletedTask).Callback<Website>(w => w.Id = 3); var result = await controller.Create(createWebsiteDto); Assert.IsNotNull(result); Assert.IsInstanceOfType(result.Result, typeof(CreatedResult)); var createdResult = result.Result as CreatedResult; Assert.IsNotNull(createdResult); var websiteDto = createdResult.Value as WebsiteDto; Assert.AreEqual(createdWebsite.Id, websiteDto.Id); Assert.AreEqual(createdWebsite.Url, websiteDto.Url); } [TestMethod] public async Task Create_CallsCreateAsyncOnRepository_Once() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); var createWebsiteDto = new CreateWebsiteDto("https://example4.com", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath", "testpath"); mockRepo.Setup(repo => repo.CreateAsync(It.IsAny<Website>())).Returns(Task.CompletedTask).Callback<Website>(w => w.Id = 4); var result = await controller.Create(createWebsiteDto); mockRepo.Verify(repo => repo.CreateAsync(It.IsAny<Website>()), Times.Once()); } [TestMethod] public async Task Update_ReturnsNotFoundResult_WhenWebsiteDoesNotExist() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); int websiteId = 1; var updateWebsiteDto = new UpdateWebsiteDto ("https://example5.com", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2"); mockRepo.Setup(repo => repo.GetAsync(websiteId)).ReturnsAsync((Website)null); var result = await controller.Update(websiteId, updateWebsiteDto); Assert.IsNotNull(result); Assert.IsInstanceOfType(result.Result, typeof(NotFoundResult)); } [TestMethod] public async Task Update_ReturnsOkObjectResult_WithUpdatedWebsiteDto() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); int websiteId = 1; var existingWebsite = new Website { Id = websiteId, Url = "https://example6.com" }; var updateWebsiteDto = new UpdateWebsiteDto ("https://example7.com", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2", "testpath2"); mockRepo.Setup(repo => repo.GetAsync(websiteId)).ReturnsAsync(existingWebsite); mockRepo.Setup(repo => repo.UpdateAsync(It.IsAny<Website>())).Returns(Task.CompletedTask); var result = await controller.Update(websiteId, updateWebsiteDto); Assert.IsNotNull(result); Assert.IsInstanceOfType(result.Result, typeof(OkObjectResult)); var okResult = result.Result as OkObjectResult; Assert.IsNotNull(okResult); var updatedWebsiteDto = okResult.Value as WebsiteDto; Assert.AreEqual(websiteId, updatedWebsiteDto.Id); Assert.AreEqual(updateWebsiteDto.Url, updatedWebsiteDto.Url); } [TestMethod] public async Task Remove_ReturnsNotFoundResult_WhenWebsiteDoesNotExist() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); int websiteId = 1; mockRepo.Setup(repo => repo.GetAsync(websiteId)).ReturnsAsync((Website)null); var result = await controller.Remove(websiteId); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(NotFoundResult)); } [TestMethod] public async Task Remove_ReturnsNoContentResult_WhenWebsiteIsDeleted() { var mockRepo = new Mock<IWebsiteRepository>(); var controller = SetupControllerWithMockRepo(mockRepo); int websiteId = 1; var existingWebsite = new Website { Id = websiteId, Url = "https://example8.com" }; mockRepo.Setup(repo => repo.GetAsync(websiteId)).ReturnsAsync(existingWebsite); mockRepo.Setup(repo => repo.DeleteAsync(It.IsAny<Website>())).Returns(Task.CompletedTask); var result = await controller.Remove(websiteId); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(NoContentResult)); } } }
**AFNI** ```bash to3d -prefix outDataset.nii -session ./ DICOM/* 3dcopy outDataset.nii output.mnc ``` **ANTs** There is no native DICOM to MINC conversion in ANTs. Therefore, a common practice is to convert DICOM to NIfTI with dcm2niix, then converting NIfTI to MINC with nii2mnc. **FSL** ```bash fslchfiletype ANALYZE input.dcm output.img dcm2mnc output.img output.mnc ``` **FreeSurfer** FreeSurfer doesn't allow MINC file creation. A common solution is to convert DICOM to NIfTI using FreeSurfer's mri_convert, then NIfTI to MINC. **MRtrix** ```bash mrconvert input.dcm output.nii nii2mnc output.nii output.mnc ``` **R** R packages do not directly provide DICOM to MINC conversion. Usually, the conversion involves dealing with DICOM to NIfTI and then NIfTI to MINC. **Workbench Command** There isn't native DICOM to MINC conversion for Workbench. A workaround is to use other tools like dcm2niix, and then convert NIfTI to MINC using nii2mnc. **SPM (via a MATLAB script)** ```matlab matlabbatch{1}.spm.util.import.dicom.data = {'C:/Users/User/Desktop/DICOM'}; matlabbatch{1}.spm.util.import.dicom.root = 'flat'; matlabbatch{1}.spm.util.import.dicom.outdir = {'C:/Users/User/Desktop/NIfTI'}; matlabbatch{1}.spm.util.import.dicom.prototype = fullfile(spm('dir'), 'toolbox/DICOM/Analyze.nii'); spm_jobman('run', matlabbatch); cd('C:/Users/User/Desktop/NIfTI'); !nii2mnc YourNIfTIFile.nii YourMINCFile.mnc ``` **Pure Python** ```python import pydicom import nibabel as nib import numpy as np from pyminc.volumes.factory import * # Read DICOM file ds = pydicom.read_file("input.dcm") # Create Numpy array array_np = ds.pixel_array # Create new MINC file volumeOut = volumeFromFile('output.mnc', dtype=np.int16, volume=volumeIn) # Write numpy array to MINC file volumeOut.data[:,:,:] = array_np ``` Please note: DICOM to MINC conversion is not commonly performed directly in many of these platforms, thus certain conversions involve intermediate steps such as achieving NIfTI format. Please ensure the necessary tools like dcm2niix, nii2mnc are installed and remember to replace filenames accordingly.
import { UyeDialogComponent } from './../../dialogs/uye-dialog/uye-dialog.component'; import { MyAlertService } from './../../../services/myAlert.service'; import { Sonuc } from './../../../models/Sonuc'; import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialogRef, MatDialog } from '@angular/material/dialog'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { Uye } from 'src/app/models/Uye'; import { ApiService } from 'src/app/services/api.service'; import { ConfirmDialogComponent } from '../../dialogs/confirm-dialog/confirm-dialog.component'; @Component({ selector: 'app-admin-uye', templateUrl: './admin-uye.component.html', styleUrls: ['./admin-uye.component.css'] }) export class AdminUyeComponent implements OnInit { dataSource: any; kayitlar: Uye[]; displayedColumns = ['uyeAdsoyad', 'uyeMail','uyeDersSayisi', 'uyeAdmin', 'islemler']; @ViewChild(MatSort) sort: MatSort; @ViewChild(MatPaginator) paginator: MatPaginator; confirmDialogRef: MatDialogRef<ConfirmDialogComponent>; dialogRef: MatDialogRef<UyeDialogComponent>; constructor( public apiServis: ApiService, public matDialog: MatDialog, public alert: MyAlertService ) { } ngOnInit() { this.KayitGetir(); } KayitGetir() { this.apiServis.UyeListe().subscribe(d => { this.kayitlar = d; this.dataSource = new MatTableDataSource(d); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; }); } UyeEkle() { var yeniKayit = new Uye(); this.dialogRef = this.matDialog.open(UyeDialogComponent, { width: "400px", data: { islem: 'ekle', kayit: yeniKayit } }); this.dialogRef.afterClosed().subscribe(d => { if (d) { d.uyeFoto = "profil.jpg"; this.apiServis.UyeEkle(d).subscribe((s:Sonuc) => { this.alert.AlertUygula(s); if (s.islem) { this.KayitGetir(); } }); } }); } UyeDuzenle(uye: Uye) { this.dialogRef = this.matDialog.open(UyeDialogComponent, { width: "400px", data: { islem: 'duzenle', kayit: uye } }); this.dialogRef.afterClosed().subscribe((d: Uye) => { if (d) { uye.uyeMail = d.uyeMail; uye.uyeAdsoyad = d.uyeAdsoyad; this.apiServis.UyeDuzenle(uye).subscribe((s:Sonuc) => { this.alert.AlertUygula(s); if (s.islem) { this.KayitGetir(); } }); } }); } UyeSil(uye: Uye) { this.confirmDialogRef = this.matDialog.open(ConfirmDialogComponent, { width: "400px" }); this.confirmDialogRef.componentInstance.dialogMesaj = uye.uyeAdsoyad + " isimli Üye Silinecektir Onaylıyor musunuz?"; { } this.confirmDialogRef.afterClosed().subscribe(d => { if (d) { this.apiServis.UyeSil(uye.uyeId).subscribe((s:Sonuc) => { this.alert.AlertUygula(s); if (s.islem) { this.KayitGetir(); } }); } }); } Filtrele(e: any) { var deger = e.target.value; this.dataSource.filter = deger.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } }
import "./UpdateActor.css" import Button from '@mui/material/Button'; import { TextField } from "@mui/material"; import { useNavigate, useParams } from "react-router-dom"; import * as yup from "yup" import{useFormik} from "formik" import { useDispatch, useSelector } from 'react-redux'; import { fetchUpdateActor } from "../../../redux/Actors/actorAction"; import KeyboardBackspaceIcon from "@mui/icons-material/KeyboardBackspace"; import { useContext } from "react"; import { IMDBContext } from "../../../Context"; import Carousel from 'react-bootstrap/Carousel'; const producerValidationSchema=yup.object({ name:yup.string().required("please fill the name"), gender:yup.string().required("please fill the Gender of the Producer"), image:yup.string().required("please fill the image of the Producer"), dob:yup.string().required("please fill the Date of Birth of the Producer"), Bio:yup.string().required("please fill the bio of the Producer"), }) function UpdateActor() { const {id}=useParams() const{baseUrl,pics,handleSuccess,handleFailure}=useContext(IMDBContext) const navigate=useNavigate(); const dispatch=useDispatch() let actor=useSelector((prod)=>prod.actors.actors.filter((ele)=>ele._id===id)) console.log(actor) const{values,handleChange, handleSubmit,handleBlur,errors,touched}=useFormik({ initialValues:{ _id:actor[0]._id, name:actor[0].name, gender:actor[0].gender, image:actor[0].image, dob:actor[0].dob, Bio:actor[0].Bio }, validationSchema:producerValidationSchema, onSubmit:(updateProducer)=>{ console.log("onSubmit triggered",updateProducer) dispatch(fetchUpdateActor(baseUrl,updateProducer,handleSuccess,handleFailure)); navigate("/actor") } }) return( <div className="containers addProducerPage "> <div className='carousel-land'> <Carousel > { pics.map((img,idx)=>( <Carousel.Item key={idx} > <img className="d-block" src={img} alt="First slide" style={{width:"100vw",height:"40vh"}}></img> </Carousel.Item> )) } </Carousel> </div> <div className='heading'><h1>Update Actor</h1></div> <div className="input-section"> <form onSubmit={handleSubmit} className='form-addPage'> <TextField label={touched.name && errors.name?<p style={{color:"red"}}>{errors.name} </p>:"Enter The Name of the Actor"} id="filled" variant="filled" style={{marginLeft:"1rem", marginTop:"1rem", width: '50ch'}} onChange={handleChange} value={values.name} onBlur={handleBlur} name= "name" /> <TextField label= {touched.gender && errors.gender? <p style={{color:"red"}}>{errors.gender}</p>:"Enter Gender of the Producer"} id="filled" variant="filled" style={{marginLeft:"1rem", marginTop:"1rem", width: '50ch'}} onChange={handleChange} value={values.gender} onBlur={handleBlur} name= "gender" /> <TextField label={touched.image && errors.image?<p style={{color:"red"}}>{errors.image}</p>: "Enter The image of the Actor" } id="filled" variant="filled" style={{marginLeft:"1rem", marginTop:"1rem", width: '50ch'}} onChange={handleChange} value={values.image} onBlur={handleBlur} name= "image" /> <TextField label={touched.dob && errors.dob?<p style={{color:"red"}}>{errors.dob}</p>: "Enter Date of Birth of Actor" } id="filled" variant="filled" style={{marginLeft:"1rem", marginTop:"1rem", width: '50ch'}} onChange={handleChange} value={values.dob} onBlur={handleBlur} name= "dob" /> <TextField label={touched.Bio && errors.Bio?<p style={{color:"red"}}>{errors.Bio}</p>: "Enter Bio of Producer" } id="filled" variant="filled" style={{marginLeft:"1rem", marginTop:"1rem", width: '50ch'}} onChange={handleChange} value={values.Bio} onBlur={handleBlur} name= "Bio" /> <Button className="add-btn" color="success" type="submit" variant="contained" style={{display:"block",textAlign:"center", marginLeft:"25%",width:"50%", marginTop:"1rem"}} > Update Actor </Button> </form> </div> <Button startIcon={<KeyboardBackspaceIcon />} variant="contained" onClick={() => { navigate(-1); }} > Back </Button> </div> ) } export default UpdateActor
package com.optima.gerai_pay.Activity; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.optima.gerai_pay.Helper.SessionManager; import com.optima.gerai_pay.Helper.Utils; import com.optima.gerai_pay.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class DetailTopUpHistory extends AppCompatActivity { private TextView trxDate, orderID, trxStatus, paymentType, paymentSite, paymentCode, totalTopUp; String getToken; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_top_up_history); SessionManager sessionManager = new SessionManager(this); sessionManager.checkLogin(); HashMap<String, String> user = sessionManager.getUserDetail(); getToken = user.get(SessionManager.TOKEN); ImageView backButton = findViewById(R.id.backBtn); trxDate = findViewById(R.id. trxDate); orderID = findViewById(R.id.orderID); trxStatus = findViewById(R.id.trxStatus); paymentType = findViewById(R.id.paymentType); paymentSite = findViewById(R.id.paymentSite); paymentCode = findViewById(R.id.paymentCode); totalTopUp = findViewById(R.id.totalTopUp); getData(); backButton.setOnClickListener(view -> finish()); } private void getData(){ final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.show(); Intent intent = getIntent(); final String getOrderID = intent.getStringExtra("orderId"); String url = Utils.BASE_URL + "depositbyid"; RequestQueue requestQueue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> { progressDialog.dismiss(); try{ JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("history"); for (int k = 0; k < jsonArray.length(); k++) { JSONObject object = jsonArray.getJSONObject(k); trxDate.setText(object.getString("tgl")); orderID.setText(object.getString("order_id")); paymentType.setText(object.getString("payment_type")); paymentSite.setText(object.getString("bank")); paymentCode.setText(object.getString("va_number")); Utils formatRupiah = new Utils(); totalTopUp.setText(formatRupiah.formatRupiah(Double.parseDouble(object.getString("total")))); trxStatus.setText(object.getString("status")); if (object.getString("status").equals("sukses")) { trxStatus.setTextColor(getResources().getColor(R.color.green_forest_primary)); trxStatus.setText(object.getString("status")); } else if (object.getString("status").equals("proses")) { trxStatus.setTextColor(getResources().getColor(R.color.colorAccent)); trxStatus.setText(object.getString("status")); } else if (object.getString("status").equals("gagal")) { trxStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark)); trxStatus.setText(object.getString("status")); } } } catch (JSONException e) { e.printStackTrace(); progressDialog.dismiss(); toastIcon("Jaringan Bermasalah, Coba Lagi !", R.drawable.ic_close, android.R.color.holo_red_dark); } }, error -> { progressDialog.dismiss(); toastIcon("Jaringan Bermasalah, Coba Lagi !", R.drawable.ic_close, android.R.color.holo_red_dark); }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("order_id", getOrderID); return params; } @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<String, String>(); params.put("Accept", "application/json"); params.put("Authorization", "Bearer " + getToken); return params; } }; requestQueue.add(stringRequest); } private void toastIcon(final String message, final int image, final int color) { Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_LONG); @SuppressLint("InflateParams") View custom_view = getLayoutInflater().inflate(R.layout.toast_icon_text, null); ((TextView) custom_view.findViewById(R.id.message)).setText(message); ((ImageView) custom_view.findViewById(R.id.icon)).setImageResource(image); ((ImageView) custom_view.findViewById(R.id.icon)).setColorFilter(android.R.color.white); ((CardView) custom_view.findViewById(R.id.parent_view)).setCardBackgroundColor(getResources().getColor(color)); toast.setView(custom_view); toast.show(); } @Override public void onBackPressed() { super.onBackPressed(); finish(); } }
from django.db import models from django.contrib.auth.models import User # Create your models here. # Create a custom profile to go with the user class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Change were images are stored in setting.py (add base directories) image = models.ImageField(default='blank-user-profile.jpg', upload_to='profile_pictures') location = models.CharField(max_length=100) def __str__(self) -> str: return self.user.username
import { useContext, useRef } from 'react' import { useDispatch } from 'react-redux' import { ValueContext } from '..' import { addnewtask } from '../../../redux/features/stateSlice' import { AreaElement } from './children-component/area/AreaElement' import { CalenderElement } from './children-component/calender/CalenderElement' import { InputElement } from './children-component/input/InputElement' import { PiorityElement } from './children-component/piority/PiorityElement' import styles from './content.module.css' export const Content = () => { const value = useContext(ValueContext) const dispatch = useDispatch() let taskValue = { input: value.input, desc: value.desc, calc: value.calc, piority: value.piority } let currentDate = new Date().toDateInputValue() const ref = useRef(null) //click button Add const handleSubmit = (e) => { e.preventDefault() let task = [] if (value.input && value.desc) { task.push(taskValue) dispatch(addnewtask(task)) value.setInput('') value.setDesc('') value.setCalc(currentDate) value.setPiority('Normal') value.toast('Add success') ref.current && ref.current.focus() } else { alert('Please check the fields') } } return ( <form className={styles.content}> <InputElement ref={ref} value={value} /> <AreaElement /> <div className={styles.selectContent}> <CalenderElement /> <PiorityElement /> </div> <button type='submit' onClick={handleSubmit} className={styles.buttonAdd}>Add</button> </form> ) }
import React from "react"; import { Link } from "react-router-dom"; // MUI import { Avatar, Box, Card, CardContent, Chip, Grid, Stack, Typography, } from "@mui/material"; // types import { TProduct } from "../@types/product"; // component props type type ProductProps = { product: TProduct }; function Product({ product }: ProductProps) { return ( <Grid item xs={12} sm={6} md={4} lg={3}> <Box sx={{ height: "412px" }}> <Link to={`/product-detail/${product._id}`}> <Card> <CardContent sx={{ padding: 0 }}> <Avatar src={product.image} alt={product.name} variant="square" sx={{ height: 250, width: "auto" }} /> <Box sx={{ display: "flex", justifyContent: "space-between", marginTop: "1rem", paddingLeft: 2, }} > <Box sx={{ width: "100%" }}> <Typography variant="body1" noWrap overflow={"hidden"} textOverflow={"ellipsis"} width={"90%"} > {product.name} </Typography> <Stack direction={"row"} alignItems={"center"} justifyContent={"space-between"} marginRight={1} > <Typography variant="body2" color={"text.secondary"}> {product.category?.name} </Typography> <Chip label={product.size.name} size="small" sx={{ fontSize: 12 }} /> </Stack> <Typography variant="subtitle1">${product.price}</Typography> </Box> </Box> </CardContent> </Card> </Link> </Box> </Grid> ); } export default Product;
# GPT-3.5 Chat Assistant with Flask This is a simple Flask web application that utilizes OpenAI's GPT-3.5 model to create a chat assistant. Users can interact with the chat assistant by entering text prompts, and the assistant will respond based on the input. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ### Prerequisites Before you begin, make sure you have the following installed on your system: - Python 3 - Flask - OpenAI Python package ### Installation 1. Clone the repository to your local machine: ``` git clone https://github.com/irohanrajput/pybot.git ``` 2. Navigate into the project directory: ``` cd pybot ``` 3. Install the required Python packages: ``` pip install -r requirements.txt ``` ### Usage 1. Obtain an API key from OpenAI and save it in a file named `apikey.json` in the root directory of the project where your 'main.py' file exists. The format should be: ```json {"key": "YOUR_API_KEY_HERE"} ``` 2. Run the Flask application: ``` python app.py ``` 3. Open your web browser and navigate to `http://localhost:5000` to access the chat interface. 4. Enter text prompts in the input field and press Enter or click on the submit button to interact with the chat assistant. ## Acknowledgments - This project utilizes OpenAI's GPT-3.5 model for natural language processing. - The Flask web framework is used to create the web interface.
import { Body, Controller, Get, Param } from '@nestjs/common'; import { ApiResponse, CreateRoleDto, UpdateRoleDto, } from '@myexperiment/domain'; import { RoleService } from '@myexperiment/infrastructure'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class AppController { constructor(private readonly roleService: RoleService) {} @Get('/') hello(): string { return 'hello'; } @MessagePattern({ cmd: 'create_role' }) create(@Body() createRole: CreateRoleDto): Promise<ApiResponse> { return this.roleService.createRole(createRole); } @MessagePattern({ cmd: 'get_roles' }) findAll(): Promise<ApiResponse> { return this.roleService.findAll(); } @MessagePattern({ cmd: 'get_role' }) findById(id: number): Promise<ApiResponse> { return this.roleService.findById(id); } @MessagePattern({ cmd: 'update_role' }) updateById(id: number, updateRole: UpdateRoleDto) { return this.roleService.updateById(id, updateRole); } @MessagePattern({ cmd: 'delete_role' }) deleteById(id: number) { return this.roleService.deleteById(id); } }
import { csrfFetch } from "./csrf"; const SET_USER = 'session/SET_USER'; const REMOVE_USER = 'session/REMOVE_USER'; // Action Creators const setUser = (user) => ({ type: SET_USER, user }); const removeUser = () => ({ type: REMOVE_USER, }); // Thunk Actions export const login = (user) => async dispatch => { const { credential, password } = user; const response = await csrfFetch('/api/session', { method: 'POST', body: JSON.stringify({ credential, password, }), }); const data = await response.json(); dispatch(setUser(data.user)); return response; }; export const restoreUser = () => async dispatch => { const response = await csrfFetch('/api/session'); const data = await response.json(); dispatch(setUser(data.user)); return response; } export const signup = (user) => async dispatch => { const { username, firstName, lastName, email, password } = user; const response = await csrfFetch('/api/users', { method: 'POST', body: JSON.stringify({ username, firstName, lastName, email, password, }), }); const data = await response.json(); dispatch(setUser(data.user)); return response; }; export const logout = () => async dispatch => { const response = await csrfFetch('/api/session', { method: 'DELETE', }); dispatch(removeUser()); return response; }; export const demoLogin = () => async dispatch => { const res = await csrfFetch(`/api/session/demo`, { method: 'POST', }) const user = await res.json() if (res.ok) { dispatch(setUser(user.user)) return res } else { return Promise.reject(user) } } // Session Reducer const initialState = { user: null }; const sessionReducer = (state = initialState, action) => { let newState; switch (action.type) { case SET_USER: newState = Object.assign({}, state); newState.user = action.user; return newState; case REMOVE_USER: newState = Object.assign({}, state); newState.user = null; return newState; default: return state; } }; export default sessionReducer;
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:ptnet_plugin/data.dart'; import 'package:ptnet_plugin/permission.dart'; import 'package:ptnet_plugin/ptnet_plugin.dart'; import 'package:flutter_testapp/widget.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String _result = ''; final _plugin = PtnetPlugin(); // Controller - UI final inputServer = TextEditingController(); final inputAddress = TextEditingController(); // TTL - Port - Server - Address - Progress - Execute var visibleUI = [false, false, false, false, false, true]; var editEnable = false; var executeEnable = false; var timeLabel = false; // Realtime - update Timer? _timer; static const int delayMillis = 30000; // Change the delay as needed // Unchanged Values final _initAddress = 'zing.vn'; final String _dnsServer = "8.8.8.8"; // Changed Values String actionValue = 'Ping'; var actionValues = [ 'Ping', 'PageLoad', 'DnsLookup', 'PortScan', 'TraceRoute', 'WifiScan', 'WifiInfo' ]; final ValueNotifier<int?> selectedTTL = ValueNotifier<int?>(null); final ValueNotifier<int?> selectedPortType = ValueNotifier<int?>(null); @override void dispose() { _timer?.cancel(); selectedTTL.dispose(); // Don't forget to dispose of the ValueNotifier selectedPortType.dispose(); super.dispose(); } @override void initState() { super.initState(); PermissionResquest().requestPermission(); initAction(); } void initValue() { _result = ""; visibleUI.fillRange( 0, 6, false); // Initialize all elements of visibleUI to false visibleUI[3] = true; // Address visibleUI[5] = true; // Execute executeEnable = true; selectedTTL.value = 1; selectedPortType.value = 0; inputAddress.text = _initAddress; } void initAction() { _timer?.cancel(); initValue(); switch (actionValue) { case "DnsLookup": visibleUI[2] = true; inputServer.text = "8.8.8.8"; break; case "PortScan": visibleUI[0] = true; // TTL visibleUI[1] = true; // Port timeLabel = false; break; case "WifiScan": visibleUI[3] = false; visibleUI[5] = false; break; case "WifiInfo": visibleUI[3] = false; break; default: break; } } // Act use by Execute void callState(String act) { Map<String, Function> stateFunctions = { "Ping": pingState, "PageLoad": pageLoadState, "DnsLookup": dnsLookupState, "TraceRoute": traceRouteState, "PortScan": portScanState, "WifiInfo": wifiInfoState, }; stateFunctions[act]?.call(); } // UI processor void executeHandle(bool status) { setState(() { executeEnable = status; }); } void editableHandle(bool status) { setState(() { editEnable = status; }); } void resultHandle(String result) { setState(() { _result = result; }); } void setInputAddress(String address) { inputAddress.text = address; } String getInputAddress() { return (inputAddress.text.isNotEmpty) ? inputAddress.text : _initAddress; } void setInputServer(String server) { inputAddress.text = server; } String getInputServer() { return (inputServer.text.isNotEmpty) ? inputServer.text : _dnsServer; } void visibleControl(int index, bool status) { setState(() { visibleUI[index] = status; }); } Future<void> pingState() async { String error = ""; String address = getInputAddress(); PingDTO pingResult = PingDTO(address: "", ip: "", time: -1.0); // Start process ------------------------------------------- resultHandle(""); executeHandle(false); setInputAddress(address); // Execute try { pingResult = await _plugin.getPingResult(address) ?? pingResult; } on Exception catch (e) { error = e.toString(); } // End process ------------------------------------------- if (!mounted) return; if (error.isNotEmpty) { resultHandle("\n${pingResult.toString()}"); } else { resultHandle('\nFailed to get ping result'); } executeHandle(true); } Future<void> pageLoadState() async { int time = 10; String pageLoadResult = ""; String address = getInputAddress(); // Start process ------------------------------------------- resultHandle(""); executeHandle(false); editableHandle(false); setInputAddress(address); // Execute while (time > 0) { if (executeEnable) { break; } else { try { pageLoadResult = await _plugin.getPageLoadResult(address) ?? ""; } on Exception { pageLoadResult = "Fail to get page load result"; } resultHandle("$_result\nTime: $pageLoadResult ms"); time--; } } // End process ------------------------------------------- if (!mounted) return; executeHandle(true); editableHandle(true); } Future<void> dnsLookupState() async { String error = ""; List<String> dnsLookupResult = []; String address = getInputAddress(); String server = getInputServer(); // Start process ------------------------------------------- resultHandle(""); setInputAddress(address); setInputServer(server); executeHandle(false); // Execute try { dnsLookupResult = await _plugin.getDnsLookupResult(address, server) ?? []; } on Exception { error = "Fail to get page load result"; } // End process ------------------------------------------- if (!mounted) return; if (error.isNotEmpty) { resultHandle("\n$error"); } else { for (var element in dnsLookupResult) { resultHandle("$_result\n$element"); } executeHandle(true); } } int _currentPort = 0; int _endPort = 0; int _rootPort = 0; void selectedPortRange() { int portType = int.tryParse(selectedPortType.value.toString()) ?? 1; switch (portType) { case 0: _currentPort = 1; _endPort = 1023; break; case 1: _currentPort = 1024; _endPort = 49151; break; case 2: _currentPort = 49152; _endPort = 65565; break; default: _currentPort = 1; _endPort = 65565; break; } _rootPort = _currentPort; } Future<void> portScanState() async { String error = ""; String address = getInputAddress(); int timeout = int.tryParse(selectedTTL.value.toString()) ?? 1; PortDTO portDTO = PortDTO(address: "", port: -1, open: false); selectedPortRange(); // Start process ------------------------------------------- resultHandle(""); executeHandle(false); visibleControl(4, true); setInputAddress(address); // Execute for (var port = _rootPort; port <= _endPort; port++) { portDTO = PortDTO(address: "", port: -1, open: false); if (!executeEnable) { try { portDTO = await _plugin.getPortScanResult(address, port, timeout) ?? portDTO; setState(() { _currentPort = port; }); if (portDTO.port != -1 && portDTO.open) { resultHandle("$_result\n$portDTO"); } } on Exception { error = "Fail to get port scan result"; } } } // End process ------------------------------------------- if (!mounted) return; if (error.isNotEmpty) { resultHandle("\n$error"); } else { executeHandle(true); if (_currentPort == _endPort) { visibleControl(4, false); } } } Future<void> traceRouteState() async { String error = ""; String address = getInputAddress(); List<TraceHopDTO> traceList = []; var hop1 = TraceHopDTO( hopNumber: 0, domain: "", ipAddress: "", time: -1, status: false); var hop2 = TraceHopDTO( hopNumber: 0, domain: "", ipAddress: "", time: -1, status: false); var traceResult = TraceHopDTO( hopNumber: 0, domain: "", ipAddress: "", time: -1, status: false); var endpoint = TraceHopDTO( hopNumber: 0, domain: "", ipAddress: "", time: -1, status: false); // Start process ------------------------------------------- resultHandle(""); executeHandle(false); setInputAddress(address); // Execute try { endpoint = await _plugin.getTraceRouteEndpoint(address) ?? endpoint; } on Exception { error = "Fail to get endpoint"; } var ttl = 1; while (traceResult.ipAddress != endpoint.ipAddress || ttl <= 255) { traceResult = TraceHopDTO( hopNumber: 0, domain: "", ipAddress: "", time: -1, status: false); // Stop / Run if (!executeEnable) { try { traceResult = await _plugin.getTraceRouteResult(address, ttl) ?? traceResult; if (traceResult.hopNumber != 0) { traceList.add(traceResult); } } on Exception { error = "Fail to get trace route result"; } if (error.isEmpty) { resultHandle("$_result\n${traceResult.toString()}"); } else { resultHandle("$_result\nRequest timeout!!!"); } if (traceList.length == 2) { hop1 = traceList[0]; hop2 = traceList[1]; } if (traceList.length > 2) { hop1 = traceList[traceList.length - 2]; hop2 = traceList[traceList.length - 1]; } if (traceResult.ipAddress == endpoint.ipAddress) { break; } else { if (hop1.ipAddress == hop2.ipAddress && hop1.ipAddress.isNotEmpty) { break; } } ttl++; } else { break; } } // End process ------------------------------------------- if (!mounted) return; executeHandle(true); } void wifiScanHandle() { wifiScanState(); _timer = Timer.periodic(const Duration(milliseconds: delayMillis), (Timer t) => wifiScanState()); } Future<void> wifiScanState() async { String error = ""; List<WifiScanResultDTO> scanResult = []; // Start process resultHandle(_result); // Execute if (actionValue == 'WifiScan') { // Attempt to rescan Wi-Fi networks try { // Get the Wi-Fi scan results scanResult = await _plugin.getWifiScanResult() ?? scanResult; } catch (e) { error = "Failed to get Wi-Fi scan result: $e"; // Update error message } } else { _timer?.cancel(); } // End process ------------------------------------------- if (!mounted) return; if (error.isEmpty) { if (scanResult.isNotEmpty) { _result = ""; for (var element in scanResult) { resultHandle("$_result\n${element.toString()}"); } } else { _result = _result; } } else { resultHandle("\n$error"); } } Future<void> wifiInfoState() async { String error = ""; WifiInfoDTO wifiInfo = WifiInfoDTO( SSID: "", BSSID: "", gateWay: "", subnetMask: "", deviceMAC: "", ipAddress: ""); // Start process ------------------------------------------- resultHandle(""); executeHandle(false); // Execute try { wifiInfo = await _plugin.getWifiInfo() ?? wifiInfo; } on Exception { error = "Fail to get wifi info"; } // End process ------------------------------------------- if (!mounted) return; executeHandle(true); if (error.isNotEmpty) { resultHandle("\n$error"); } else { resultHandle("\n${wifiInfo.toString()}"); } } void onChanged(String? newValue) { setState(() { actionValue = newValue!; // Update the actionValue variable with the newly selected value // Call any other methods or update any other variables as needed initAction(); // Example: Call initAction method switch (actionValue) { case "WifiScan": wifiScanHandle(); break; default: break; } }); } void stopExecute(String? p1) { setState(() { executeEnable = true; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Center( // child: Text('Running on: $_platformVersion\n'), child: Column( children: [ CustomDropdownButton( enabled: executeEnable, actionValue: actionValue, actionValues: actionValues, onChanged: onChanged, ), IpForm( controller: inputAddress, enabled: executeEnable, visible: visibleUI[3]), DNSServerForm( visible: visibleUI[2], enabled: executeEnable, inputServer: inputServer), PortRangeForm( visible: visibleUI[1], enabled: executeEnable, selectedPortType: selectedPortType), TimeOutForm( visible: visibleUI[0], enabled: executeEnable, selectedValue: selectedTTL, ), const SizedBox(height: 30), ExecuteButton( visible: visibleUI[5], enabled: executeEnable, actionValue: actionValue, onPressed: callState, stopPressed: stopExecute), const SizedBox(height: 12), CustomResultWidget( visible: visibleUI[4], currentPort: _currentPort - _rootPort + 1, endPort: _endPort - _rootPort + 1, actionValue: actionValue, result: _result, ), ], ), ), ), ); } }
//TypeScript adds types and visibility modifiers to JavaScript classes. //Members: Types //TypeScript adds types to class members, including properties and methods. class Person { name: string; } const person = new Person(); person.name = "Jane"; console.log(person); //Members: Visibility Modifiers //TypeScript adds visibility modifiers to class members, including properties and methods. // Class members also be given special modifiers which affect visibility. // There are three main visibility modifiers in TypeScript. // public - (default) allows access to the class member from anywhere // private - only allows access to the class member from within the class // protected - allows access to the class member from itself and any classes that inherit it, which is covered in the inheritance section below class Person { private name: string;//this property is private public constructor(name: string) {//this constructor is public this.name = name; } public getName(): string {//this method is public return this.name; } } const person = new Person("Jane"); console.log(person.getName()); // person.name isn't accessible from outside the class since it's private //Parameter Properties // TypeScript provides a convenient way to define class members in the constructor, by adding a visibility modifiers to the parameter. class Person { // name is a private member variable public constructor(private name: string) {} public getName(): string { return this.name; } } const person = new Person("Jane"); console.log(person.getName()); //Inheritance // TypeScript supports class inheritance // A class can inherit from another class by using the extends keyword. // The derived class can access the properties and methods of the base class. // The derived class can override the properties and methods of the base class. // The derived class can call the constructor of the base class using the super keyword. class Person { protected name: string; public constructor(name: string) { this.name = name; } public getName(): string { return this.name; } } class Employee extends Person { private department: string; public constructor(name: string, department: string) { super(name); this.department = department; } public getElevatorPitch(): string { return `Hello, my name is ${this.name} and I work in ${this.department}`; } } const employee = new Employee("Jane", "Sales"); console.log(employee.getElevatorPitch()); console.log(employee.getName()); // Override // When a class extends another class, it can replace the members of the parent class with the same name. // Newer versions of TypeScript allow explicitly marking this with the override keyword. interface Shape { getArea: () => number; } class Rectangle implements Shape { // using protected for these members allows access from classes that extend from this class, such as Square public constructor(protected readonly width: number, protected readonly height: number) {} public getArea(): number { return this.width * this.height; } public toString(): string { return `Rectangle[width=${this.width}, height=${this.height}]`; } } class Square extends Rectangle { public constructor(width: number) { super(width, width); } // this toString replaces the toString from Rectangle public override toString(): string { return `Square[width=${this.width}]`; } } const mySq = new Square(20); console.log(mySq.toString()); // Abstract Classes // Classes can be written in a way that allows them to be used as a base class for other classes without having to implement all the members. This is done by using the abstract keyword. Members that are left unimplemented also use the abstract keyword. abstract class Polygon { public abstract getArea(): number; public toString(): string { return `Polygon[area=${this.getArea()}]`; } } class Rectangle extends Polygon { public constructor(protected readonly width: number, protected readonly height: number) { super(); } public getArea(): number { return this.width * this.height; } } const myRect = new Rectangle(10,20); console.log(myRect.getArea());
# Copyright 2022 The Nerfstudio Team. All rights reserved. # # 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. """Utility functions to allow easy re-use of common operations across dataloaders""" from pathlib import Path from typing import List, Tuple, Union import json import cv2 import numpy as np import torch from PIL import Image def get_image_mask_tensor_from_path(filepath: Path, scale_factor: float = 1.0) -> torch.Tensor: """ Utility function to read a mask image from the given path and return a boolean tensor """ pil_mask = Image.open(filepath) if scale_factor != 1.0: width, height = pil_mask.size newsize = (int(width * scale_factor), int(height * scale_factor)) pil_mask = pil_mask.resize(newsize, resample=Image.NEAREST) mask_tensor = torch.from_numpy(np.array(pil_mask)).unsqueeze(-1).bool() if len(mask_tensor.shape) != 3: raise ValueError("The mask image should have 1 channel") return mask_tensor def get_scannet_image_mask_tensor_from_path( filepath: Path, instance_id: int, all_instances: List[int], scale_factor: float = 1.0 ) -> torch.Tensor: """ Utility function to read a mask image from the given path and return a boolean tensor """ assert instance_id in all_instances or instance_id == 0 # instance mask or background mask mask = cv2.imread(filepath.as_posix(), cv2.IMREAD_GRAYSCALE) if instance_id != 0: binary_mask = (mask == instance_id).astype(np.uint8) else: # return all values in mask that do not belong to any instance binary_mask = np.isin(mask, all_instances, invert=True).astype(np.uint8) if scale_factor != 1.0: width, height = binary_mask.size newsize = (int(width * scale_factor), int(height * scale_factor)) binary_mask = cv2.resize(binary_mask, newsize, interpolation=cv2.INTER_NEAREST) structuring_element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) binary_mask = cv2.dilate(binary_mask, structuring_element, iterations=6) mask_tensor = torch.from_numpy(binary_mask).unsqueeze(-1).bool() if len(mask_tensor.shape) != 3: raise ValueError("The mask image should have 1 channel") return mask_tensor def get_obj_poseBox_tensor_from_path(filepath: Path): with open(filepath,'r') as f: lines = f.readlines() line = lines[0].split(' ') dim = np.array([float(line[8]),float(line[9]),float(line[10])]) assert(dim.min()>=0) location = np.array([float(line[11]),float(line[12]),float(line[13])]) box = torch.tensor([[location[0]-dim[0],location[1]-dim[1],location[2]-dim[2]], [location[0]+dim[0],location[1]+dim[1],location[2]+dim[2]]]) return box def get_obj_poseBox_tensor_from_json(filepath: Path, frame_index: int, instance_id: int): if instance_id == 0: return torch.zeros((2, 3)) # dummy pose, include whole scene with open(filepath,'r') as f: data = json.load(f) object_pose = data[str(frame_index)][str(instance_id)] center = object_pose[:3] dim = object_pose[3:6] rotation = np.array(object_pose[6:]).reshape((3,3)) center = rotation @ np.array(center).T box = torch.tensor([[center[0]-dim[0],center[1]-dim[1],center[2]-dim[2]], [center[0]+dim[0],center[1]+dim[1],center[2]+dim[2]]]) return box def get_semantics_and_mask_tensors_from_path( filepath: Path, mask_indices: Union[List, torch.Tensor], scale_factor: float = 1.0 ) -> Tuple[torch.Tensor, torch.Tensor]: """ Utility function to read segmentation from the given filepath If no mask is required - use mask_indices = [] """ if isinstance(mask_indices, List): mask_indices = torch.tensor(mask_indices, dtype="int64").view(1, 1, -1) pil_image = Image.open(filepath) if scale_factor != 1.0: width, height = pil_image.size newsize = (int(width * scale_factor), int(height * scale_factor)) pil_image = pil_image.resize(newsize, resample=Image.NEAREST) semantics = torch.from_numpy(np.array(pil_image, dtype="int64"))[..., None] mask = torch.sum(semantics == mask_indices, dim=-1, keepdim=True) == 0 return semantics, mask def get_depth_image_from_path( filepath: Path, height: int, width: int, scale_factor: float, interpolation: int = cv2.INTER_NEAREST, ) -> torch.Tensor: """Loads, rescales and resizes depth images. Filepath points to a 16-bit or 32-bit depth image, or a numpy array `*.npy`. Args: filepath: Path to depth image. height: Target depth image height. width: Target depth image width. scale_factor: Factor by which to scale depth image. interpolation: Depth value interpolation for resizing. Returns: Depth image torch tensor with shape [width, height, 1]. """ if filepath.suffix == ".npy": image = np.load(filepath) * scale_factor image = cv2.resize(image, (width, height), interpolation=interpolation) else: image = cv2.imread(str(filepath.absolute()), cv2.IMREAD_ANYDEPTH) image = image.astype(np.float64) * scale_factor image = cv2.resize(image, (width, height), interpolation=interpolation) return torch.from_numpy(image[:, :, np.newaxis])
import pandas as pd titanic = pd.read_csv("titanic.csv") # select specific rows pd_series = titanic["age"] print(pd_series) # output -> pandas series print(type(pd_series)) # output: class 'pandas.core.series.Series' # select multiple columns (create a list) # most methods are available for both series and dataframes print(type(titanic["age"])) # datatype: series print(type(titanic[["age", "sex"]])) # datatype: dataframe print(titanic[["age", "sex", "fare"]]) # alternative method select one column with dot notation print(titanic.age) # equals test whether to objects have same elements # some people think should NOT use dot notation but can perform with less code print(titanic.age.equals(titanic["age"])) print(titanic.embarked)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css"> <link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet' /> <link rel="stylesheet" href="style.css"> <title>Frontend Bootcamp</title> </head> <body> <!--Navbar--> <nav class="navbar navbar-expand-lg bg-dark navbar-dark py-3 fixed-top"> <div class="container"> <a href="#" class="navbar-brand">Bootstrap 5</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navmenu"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navmenu"> <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a href="#learn" class="nav-link">L. F ANJI</a> </li> <li class="nav-item"> <a href="#questions" class="nav-link">Questions</a> </li> <li class="nav-item"> <a href="#instructors" class="nav-link">Instructors</a> </li> </ul> </div> </div> </nav> <!--Showcase--> <section class="bg-dark text-light p-5 p-lg-0 pt-lg-5 text-center text-sm-start"> <div class="container"> <div class="d-md-flex align-items-center justify-content-between"> <div> <h1>Become a <span class="text-warning">Web Developer</span></h1> <p class="lead my-4">Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, iste neque error cum ullam itaque adipisci numquam exercitationem aperiam quas, illum quod.</p> <button class="btn btn-primary btn-lg" data-bs-toggle="modal" data-bs-target="#enroll">Start Now!</button> </div> <img class="img-fluid w-50 d-none d-sm-block" src="img/lionel.jpg" alt=""> </div> </div> </section> <!--Newsletter--> <section class="bg-primary text-light p-5"> <div class="container d-md-flex"> <div class="justify-content-between align-items-center"> <h3 class="mb-3 mb-md-0">Sign Up For Our Newsletter</h3> </div> <div class="input-group news-input"> <input type="text" class="form-control" placeholder="Enter Email"> <button class="btn btn-dark btn-lg" type="button">Button</button> </div> </div> </section> <!--Boxes--> <section class="p-5"> <div class="container"> <div class="row text-center g-4"> <div class="col-md"> <div class="card bg-light text-dark"> <div class="card-body text-center"> <div class="h1 mb-3"> <i class="bi bi-laptop"></i> </div> <h3 class="card-title mb-3"> Virtual </h3> <p class="card-text"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, quo! Maxime similique autem quas quod? </p> <a href="#" class="btn btn-primary">Read More</a> </div> </div> </div> <div class="col-md"> <div class="card bg-secondary text-dark"> <div class="card-body text-center"> <div class="h1 mb-3"> <i class="bi bi-person-square"></i> </div> <h3 class="card-title mb-3"> Hybrid </h3> <p class="card-text"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, quo! Maxime similique autem quas quod? </p> <a href="#" class="btn btn-dark">Read More</a> </div> </div> </div> <div class="col-md"> <div class="card bg-light text-dark"> <div class="card-body text-center"> <div class="h1 mb-3"> <i class="bi bi-people"></i> </div> <h3 class="card-title mb-3"> In Person </h3> <p class="card-text"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, quo! Maxime similique autem quas quod? </p> <a href="#" class="btn btn-primary">Read More</a> </div> </div> </div> </div> </div> </section> <!--Learn Section--> <section id="learn" class="p-5 bg-light"> <div class="container"> <div class="row align-items-center justify-content-between"> <div class="col-md"> <img src="img/user7.jpg" class="img-fluid" alt=""> </div> <div class="col-md p-5"> <h2>Code Like ANJI</h2> <p class="lead">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam quod, minus blanditiis dolorum magni aliquid labore perferendis sed facilis nam sit quidem aliquam deleniti porro itaque, quae ratione quis quos.</p> <a href="" class="btn btn-primary"> <i class="bi bi-chevron-right"></i> Read More </a> </div> </div> </div> </section> <section id="questions" class="p-5 bg-dark"> <div class="container"> <div class="row align-items-center justify-content-between"> <div class="col-md p-5"> <h2>Learn From ANJI</h2> <p class="lead text-light">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Eius excepturi facilis officia, delectus quam similique corporis hic perferendis laborum veritatis? Nemo earum at, recusandae ad accusantium ab deserunt iste minima.</p> <a href="" class="btn btn-primary"> <i class="bi bi-chevron-right"></i> Read More </a> </div> <div class="col-md"> <img src="img/carousel2.jpg" class="img-fluid w-50" alt=""> </div> </div> </div> </section> <!--Question Accordion--> <section class="p-5"> <div class="container"> <h2 class="text-center mb-4">Frequently Asked Questions</h2> <div class="accordion accordion-flush" id="questions"> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingOne"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne"> Where Are You Located? </button> </h2> <div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample"> <div class="accordion-body">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Qui consequuntur cumque minus ipsum natus distinctio. Neque sint, repudiandae minima et sed tempore exercitationem suscipit explicabo. Amet corporis, culpa voluptatibus ut dolores, consequuntur aliquid eligendi vitae eveniet, recusandae incidunt esse unde error possimus voluptas nam animi natus quo consectetur. Quia, reiciendis.</div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseTwo" aria-expanded="false" aria-controls="flush-collapseTwo"> How much does it cost to attend? </button> </h2> <div id="flush-collapseTwo" class="accordion-collapse collapse" aria-labelledby="flush-headingTwo" data-bs-parent="#accordionFlushExample"> <div class="accordion-body">Lorem ipsum dolor sit amet consectetur adipisicing elit. Soluta facere, rerum earum id et necessitatibus voluptate nobis sint esse velit veniam dolor optio laborum, non quibusdam consequatur maiores est? Odit ducimus minima optio repudiandae repellat porro qui reiciendis, rem blanditiis praesentium corporis eligendi, ipsa repellendus, eius veritatis cupiditate dolorem labore!</div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header" id="flush-headingThree"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseThree" aria-expanded="false" aria-controls="flush-collapseThree"> What Do I Need To Know? </button> </h2> <div id="flush-collapseThree" class="accordion-collapse collapse" aria-labelledby="flush-headingThree" data-bs-parent="#accordionFlushExample"> <div class="accordion-body">Lorem ipsum dolor sit amet consectetur adipisicing elit. Sapiente, laboriosam explicabo aliquid alias vel sequi dignissimos illo consequatur nostrum rerum, mollitia reprehenderit? Libero at minima modi voluptas, optio quibusdam fuga.</div> </div> </div> </div> </div> </section> <section id="instructors" class="p-5 bg-primary"> <div class="container"> <h2 class="text-center text-white">Our Instructors</h2> <p class="lead text-center text-white mb-5"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Cum, voluptatum? </p> <div class="row g-4"> <div class="col-md-6 col-lg-3"> <div class="card bg-light"> <div class="card-body text-center"> <img src="img/favicon.ico" class="rounded-circle mb-3" alt=""> <h3 class="card-title mb-3">Bro Enoch</h3> <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Pariatur ipsam delectus, qui consequatur cumque eligendi.</p> <a href="#"><i class="bi bi-twitter text-dark mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-dark mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-dark mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-dark mx-1"></i></a> </div> </div> </div> <div class="col-md-6 col-lg-3"> <div class="card bg-light"> <div class="card-body text-center"> <img src="img/favicon.ico" class="rounded-circle mb-3" alt=""> <h3 class="card-title mb-3">FelAnji</h3> <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Pariatur ipsam delectus, qui consequatur cumque eligendi.</p> <a href="#"><i class="bi bi-twitter text-dark mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-dark mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-dark mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-dark mx-1"></i></a> </div> </div> </div> <div class="col-md-6 col-lg-3"> <div class="card bg-light"> <div class="card-body text-center"> <img src="img/favicon.ico" class="rounded-circle mb-3" alt=""> <h3 class="card-title mb-3">Qudus</h3> <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Pariatur ipsam delectus, qui consequatur cumque eligendi.</p> <a href="#"><i class="bi bi-twitter text-dark mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-dark mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-dark mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-dark mx-1"></i></a> </div> </div> </div> <div class="col-md-6 col-lg-3"> <div class="card bg-light"> <div class="card-body text-center"> <img src="img/favicon.ico" class="rounded-circle mb-3" alt=""> <h3 class="card-title mb-3">Ikeoluwa</h3> <p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Pariatur ipsam delectus, qui consequatur cumque eligendi.</p> <a href="#"><i class="bi bi-twitter text-dark mx-1"></i></a> <a href="#"><i class="bi bi-facebook text-dark mx-1"></i></a> <a href="#"><i class="bi bi-linkedin text-dark mx-1"></i></a> <a href="#"><i class="bi bi-instagram text-dark mx-1"></i></a> </div> </div> </div> </div> </div> </section> <!--Contact and Map--> <section class="p-5"> <div class="container"> <div class="row g-4"> <div class="col-md"> <h2 class="text-center mb-4">Contact Info</h2> <ul class="list-group list-group-flush lead"> <li class="list-group-item"> <span class="fw-bold">Main Location</span> 15, Babalola Street, Odoguyan, Ikorodu Lagos </li> <li class="list-group-item"> <span class="fw-bold">Student Phone:</span>+234 907 285 6771 </li> <li class="list-group-item"> <span class="fw-bold">Enrollment Email:</span>oniyeleanjola@gmail.com </li> <li class="list-group-item"> <span class="fw-bold">Student Email:</span>anjiboss33@gmail.com </li> </ul> </div> <div class="col-md"> <div id="map"></div> </div> </div> </div> </section> <!--Footer--> <footer class="p-4 bg-dark text-white text-center position-relative"> <div class="container"> <p class="lead">Copyrigth &copy; 2021 FelAnji</p> <a href="#" class="position-absolute bottom-0 end-0 p-4"> <i class="bi bi-arrow-up-circle h1"></i> </a> </div> </footer> <!-- Modal --> <div class="modal fade" id="enroll" tabindex="-1" aria-labelledby="enrollLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="enrollLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p class="lead">Fill this form and ANJI will get back to you</p> <form> <div class="mb-3"> <label for="first-name" class="col-form-label">First Name</label> <input type="text" class="form-control" id="first-name"> </div> <div class="mb-3"> <label for="last-name" class="col-form-label">Last Name</label> <input type="text" class="form-control" id="first-name"> </div> <div class="mb-3"> <label for="email" class="col-form-label">Email</label> <input type="email" class="form-control" id="first-name"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Submit</button> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> <script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js'></script> <script> mapboxgl.accessToken = 'pk.eyJ1IjoiZmVsYW5qaSIsImEiOiJja3R2NXFmbmcwaGFzMnVtcG81ZHpsdGpnIn0.sl5ni0euT792b2LCrn7H-g'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11' }); </script> </script> </body> </html>
type Message = { id: number; content: string; }; type Conversation = { id: number; title: string; messages: Message[]; }; let conversations: Conversation[] = [ { id: 1, title: 'Conversation 1', messages: [{ id: 1, content: 'Message 1' }] }, { id: 2, title: 'Conversation 2', messages: [{ id: 1, content: 'Message 2' }] }, ]; export const getConversations = (): Promise<Conversation[]> => { return new Promise((resolve) => { setTimeout(() => resolve(conversations), 500); }); }; export const getConversationMessages = (id: number): Promise<Message[]> => { return new Promise((resolve) => { const conversation = conversations.find((c) => c.id === id); setTimeout(() => resolve(conversation ? conversation.messages : []), 500); }); }; export const createMessage = (conversationId: number, content: string): Promise<Message> => { return new Promise((resolve) => { const conversation = conversations.find((c) => c.id === conversationId); if (conversation) { const newMessage = { id: Date.now(), content }; conversation.messages.push(newMessage); setTimeout(() => resolve(newMessage), 500); } }); }; export const createConversation = (title: string): Promise<Conversation> => { return new Promise((resolve) => { const newConversation = { id: Date.now(), title, messages: [] }; conversations.push(newConversation); setTimeout(() => resolve(newConversation), 500); }); };
package com.google.android.material.progressindicator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.view.ViewParent; import android.widget.ProgressBar; import androidx.annotation.AttrRes; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.Px; import androidx.annotation.RestrictTo; import androidx.annotation.StyleRes; import androidx.annotation.VisibleForTesting; import androidx.core.view.ViewCompat; import androidx.vectordrawable.graphics.drawable.Animatable2Compat; import com.google.android.material.R; import com.google.android.material.color.MaterialColors; import com.google.android.material.internal.ThemeEnforcement; import com.google.android.material.progressindicator.BaseProgressIndicatorSpec; import com.google.android.material.theme.overlay.MaterialThemeOverlay; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; /* loaded from: classes5.dex */ public abstract class BaseProgressIndicator<S extends BaseProgressIndicatorSpec> extends ProgressBar { public static final int HIDE_INWARD = 2; public static final int HIDE_NONE = 0; public static final int HIDE_OUTWARD = 1; public static final int SHOW_INWARD = 2; public static final int SHOW_NONE = 0; public static final int SHOW_OUTWARD = 1; /* renamed from: o reason: collision with root package name */ static final int f24026o = R.style.Widget_MaterialComponents_ProgressIndicator; /* renamed from: a reason: collision with root package name */ S f24027a; /* renamed from: b reason: collision with root package name */ private int f24028b; /* renamed from: c reason: collision with root package name */ private boolean f24029c; /* renamed from: d reason: collision with root package name */ private boolean f24030d; /* renamed from: e reason: collision with root package name */ private final int f24031e; /* renamed from: f reason: collision with root package name */ private final int f24032f; /* renamed from: g reason: collision with root package name */ private long f24033g; /* renamed from: h reason: collision with root package name */ AnimatorDurationScaleProvider f24034h; /* renamed from: i reason: collision with root package name */ private boolean f24035i; /* renamed from: j reason: collision with root package name */ private int f24036j; /* renamed from: k reason: collision with root package name */ private final Runnable f24037k; /* renamed from: l reason: collision with root package name */ private final Runnable f24038l; /* renamed from: m reason: collision with root package name */ private final Animatable2Compat.AnimationCallback f24039m; /* renamed from: n reason: collision with root package name */ private final Animatable2Compat.AnimationCallback f24040n; @Retention(RetentionPolicy.SOURCE) @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP}) /* loaded from: classes5.dex */ public @interface HideAnimationBehavior { } @Retention(RetentionPolicy.SOURCE) @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP}) /* loaded from: classes5.dex */ public @interface ShowAnimationBehavior { } /* JADX INFO: Access modifiers changed from: protected */ public BaseProgressIndicator(@NonNull Context context, @Nullable AttributeSet attributeSet, @AttrRes int i4, @StyleRes int i5) { super(MaterialThemeOverlay.wrap(context, attributeSet, i4, f24026o), attributeSet, i4); this.f24033g = -1L; this.f24035i = false; this.f24036j = 4; this.f24037k = new Runnable() { // from class: com.google.android.material.progressindicator.BaseProgressIndicator.1 @Override // java.lang.Runnable public void run() { BaseProgressIndicator.this.k(); } }; this.f24038l = new Runnable() { // from class: com.google.android.material.progressindicator.BaseProgressIndicator.2 @Override // java.lang.Runnable public void run() { BaseProgressIndicator.this.j(); BaseProgressIndicator.this.f24033g = -1L; } }; this.f24039m = new Animatable2Compat.AnimationCallback() { // from class: com.google.android.material.progressindicator.BaseProgressIndicator.3 @Override // androidx.vectordrawable.graphics.drawable.Animatable2Compat.AnimationCallback public void onAnimationEnd(Drawable drawable) { BaseProgressIndicator.this.setIndeterminate(false); BaseProgressIndicator baseProgressIndicator = BaseProgressIndicator.this; baseProgressIndicator.setProgressCompat(baseProgressIndicator.f24028b, BaseProgressIndicator.this.f24029c); } }; this.f24040n = new Animatable2Compat.AnimationCallback() { // from class: com.google.android.material.progressindicator.BaseProgressIndicator.4 @Override // androidx.vectordrawable.graphics.drawable.Animatable2Compat.AnimationCallback public void onAnimationEnd(Drawable drawable) { super.onAnimationEnd(drawable); if (!BaseProgressIndicator.this.f24035i) { BaseProgressIndicator baseProgressIndicator = BaseProgressIndicator.this; baseProgressIndicator.setVisibility(baseProgressIndicator.f24036j); } } }; Context context2 = getContext(); this.f24027a = i(context2, attributeSet); TypedArray obtainStyledAttributes = ThemeEnforcement.obtainStyledAttributes(context2, attributeSet, R.styleable.BaseProgressIndicator, i4, i5, new int[0]); this.f24031e = obtainStyledAttributes.getInt(R.styleable.BaseProgressIndicator_showDelay, -1); this.f24032f = Math.min(obtainStyledAttributes.getInt(R.styleable.BaseProgressIndicator_minHideDelay, -1), 1000); obtainStyledAttributes.recycle(); this.f24034h = new AnimatorDurationScaleProvider(); this.f24030d = true; } @Nullable private DrawingDelegate<S> getCurrentDrawingDelegate() { if (isIndeterminate()) { if (getIndeterminateDrawable() == null) { return null; } return getIndeterminateDrawable().n(); } else if (getProgressDrawable() == null) { return null; } else { return getProgressDrawable().o(); } } /* JADX INFO: Access modifiers changed from: private */ public void j() { ((DrawableWithAnimatedVisibilityChange) getCurrentDrawable()).setVisible(false, false, true); if (m()) { setVisibility(4); } } /* JADX INFO: Access modifiers changed from: private */ public void k() { if (this.f24032f > 0) { this.f24033g = SystemClock.uptimeMillis(); } setVisibility(0); } private boolean m() { if ((getProgressDrawable() != null && getProgressDrawable().isVisible()) || (getIndeterminateDrawable() != null && getIndeterminateDrawable().isVisible())) { return false; } return true; } private void n() { if (getProgressDrawable() != null && getIndeterminateDrawable() != null) { getIndeterminateDrawable().m().d(this.f24039m); } if (getProgressDrawable() != null) { getProgressDrawable().registerAnimationCallback(this.f24040n); } if (getIndeterminateDrawable() != null) { getIndeterminateDrawable().registerAnimationCallback(this.f24040n); } } private void o() { if (getIndeterminateDrawable() != null) { getIndeterminateDrawable().unregisterAnimationCallback(this.f24040n); getIndeterminateDrawable().m().h(); } if (getProgressDrawable() != null) { getProgressDrawable().unregisterAnimationCallback(this.f24040n); } } @Override // android.widget.ProgressBar @Nullable public Drawable getCurrentDrawable() { if (isIndeterminate()) { return getIndeterminateDrawable(); } return getProgressDrawable(); } public int getHideAnimationBehavior() { return this.f24027a.hideAnimationBehavior; } @NonNull public int[] getIndicatorColor() { return this.f24027a.indicatorColors; } public int getShowAnimationBehavior() { return this.f24027a.showAnimationBehavior; } @ColorInt public int getTrackColor() { return this.f24027a.trackColor; } @Px public int getTrackCornerRadius() { return this.f24027a.trackCornerRadius; } @Px public int getTrackThickness() { return this.f24027a.trackThickness; } protected void h(boolean z3) { if (!this.f24030d) { return; } ((DrawableWithAnimatedVisibilityChange) getCurrentDrawable()).setVisible(p(), false, z3); } public void hide() { boolean z3; if (getVisibility() != 0) { removeCallbacks(this.f24037k); return; } removeCallbacks(this.f24038l); long uptimeMillis = SystemClock.uptimeMillis() - this.f24033g; int i4 = this.f24032f; if (uptimeMillis >= i4) { z3 = true; } else { z3 = false; } if (z3) { this.f24038l.run(); } else { postDelayed(this.f24038l, i4 - uptimeMillis); } } abstract S i(@NonNull Context context, @NonNull AttributeSet attributeSet); @Override // android.view.View public void invalidate() { super.invalidate(); if (getCurrentDrawable() != null) { getCurrentDrawable().invalidateSelf(); } } boolean l() { View view = this; while (view.getVisibility() == 0) { ViewParent parent = view.getParent(); if (parent == null) { if (getWindowVisibility() != 0) { return false; } return true; } else if (!(parent instanceof View)) { return true; } else { view = (View) parent; } } return false; } @Override // android.widget.ProgressBar, android.view.View protected void onAttachedToWindow() { super.onAttachedToWindow(); n(); if (p()) { k(); } } @Override // android.widget.ProgressBar, android.view.View protected void onDetachedFromWindow() { removeCallbacks(this.f24038l); removeCallbacks(this.f24037k); ((DrawableWithAnimatedVisibilityChange) getCurrentDrawable()).hideNow(); o(); super.onDetachedFromWindow(); } @Override // android.widget.ProgressBar, android.view.View protected synchronized void onDraw(@NonNull Canvas canvas) { int save = canvas.save(); if (getPaddingLeft() != 0 || getPaddingTop() != 0) { canvas.translate(getPaddingLeft(), getPaddingTop()); } if (getPaddingRight() != 0 || getPaddingBottom() != 0) { canvas.clipRect(0, 0, getWidth() - (getPaddingLeft() + getPaddingRight()), getHeight() - (getPaddingTop() + getPaddingBottom())); } getCurrentDrawable().draw(canvas); canvas.restoreToCount(save); } @Override // android.widget.ProgressBar, android.view.View protected synchronized void onMeasure(int i4, int i5) { int paddingLeft; int paddingTop; super.onMeasure(i4, i5); DrawingDelegate<S> currentDrawingDelegate = getCurrentDrawingDelegate(); if (currentDrawingDelegate == null) { return; } int e4 = currentDrawingDelegate.e(); int d4 = currentDrawingDelegate.d(); if (e4 < 0) { paddingLeft = getMeasuredWidth(); } else { paddingLeft = e4 + getPaddingLeft() + getPaddingRight(); } if (d4 < 0) { paddingTop = getMeasuredHeight(); } else { paddingTop = d4 + getPaddingTop() + getPaddingBottom(); } setMeasuredDimension(paddingLeft, paddingTop); } @Override // android.view.View protected void onVisibilityChanged(@NonNull View view, int i4) { boolean z3; super.onVisibilityChanged(view, i4); if (i4 == 0) { z3 = true; } else { z3 = false; } h(z3); } @Override // android.view.View protected void onWindowVisibilityChanged(int i4) { super.onWindowVisibilityChanged(i4); h(false); } /* JADX INFO: Access modifiers changed from: package-private */ public boolean p() { if (ViewCompat.isAttachedToWindow(this) && getWindowVisibility() == 0 && l()) { return true; } return false; } @RestrictTo({RestrictTo.Scope.LIBRARY_GROUP}) @VisibleForTesting public void setAnimatorDurationScaleProvider(@NonNull AnimatorDurationScaleProvider animatorDurationScaleProvider) { this.f24034h = animatorDurationScaleProvider; if (getProgressDrawable() != null) { getProgressDrawable().f24073c = animatorDurationScaleProvider; } if (getIndeterminateDrawable() != null) { getIndeterminateDrawable().f24073c = animatorDurationScaleProvider; } } public void setHideAnimationBehavior(int i4) { this.f24027a.hideAnimationBehavior = i4; invalidate(); } @Override // android.widget.ProgressBar public synchronized void setIndeterminate(boolean z3) { if (z3 == isIndeterminate()) { return; } DrawableWithAnimatedVisibilityChange drawableWithAnimatedVisibilityChange = (DrawableWithAnimatedVisibilityChange) getCurrentDrawable(); if (drawableWithAnimatedVisibilityChange != null) { drawableWithAnimatedVisibilityChange.hideNow(); } super.setIndeterminate(z3); DrawableWithAnimatedVisibilityChange drawableWithAnimatedVisibilityChange2 = (DrawableWithAnimatedVisibilityChange) getCurrentDrawable(); if (drawableWithAnimatedVisibilityChange2 != null) { drawableWithAnimatedVisibilityChange2.setVisible(p(), false, false); } if ((drawableWithAnimatedVisibilityChange2 instanceof IndeterminateDrawable) && p()) { ((IndeterminateDrawable) drawableWithAnimatedVisibilityChange2).m().g(); } this.f24035i = false; } @Override // android.widget.ProgressBar public void setIndeterminateDrawable(@Nullable Drawable drawable) { if (drawable == null) { super.setIndeterminateDrawable(null); } else if (drawable instanceof IndeterminateDrawable) { ((DrawableWithAnimatedVisibilityChange) drawable).hideNow(); super.setIndeterminateDrawable(drawable); } else { throw new IllegalArgumentException("Cannot set framework drawable as indeterminate drawable."); } } public void setIndicatorColor(@ColorInt int... iArr) { if (iArr.length == 0) { iArr = new int[]{MaterialColors.getColor(getContext(), R.attr.colorPrimary, -1)}; } if (!Arrays.equals(getIndicatorColor(), iArr)) { this.f24027a.indicatorColors = iArr; getIndeterminateDrawable().m().c(); invalidate(); } } @Override // android.widget.ProgressBar public synchronized void setProgress(int i4) { if (isIndeterminate()) { return; } setProgressCompat(i4, false); } public void setProgressCompat(int i4, boolean z3) { if (isIndeterminate()) { if (getProgressDrawable() != null) { this.f24028b = i4; this.f24029c = z3; this.f24035i = true; if (getIndeterminateDrawable().isVisible() && this.f24034h.getSystemAnimatorDurationScale(getContext().getContentResolver()) != 0.0f) { getIndeterminateDrawable().m().f(); return; } else { this.f24039m.onAnimationEnd(getIndeterminateDrawable()); return; } } return; } super.setProgress(i4); if (getProgressDrawable() != null && !z3) { getProgressDrawable().jumpToCurrentState(); } } @Override // android.widget.ProgressBar public void setProgressDrawable(@Nullable Drawable drawable) { if (drawable == null) { super.setProgressDrawable(null); } else if (drawable instanceof DeterminateDrawable) { DeterminateDrawable determinateDrawable = (DeterminateDrawable) drawable; determinateDrawable.hideNow(); super.setProgressDrawable(determinateDrawable); determinateDrawable.s(getProgress() / getMax()); } else { throw new IllegalArgumentException("Cannot set framework drawable as progress drawable."); } } public void setShowAnimationBehavior(int i4) { this.f24027a.showAnimationBehavior = i4; invalidate(); } public void setTrackColor(@ColorInt int i4) { S s3 = this.f24027a; if (s3.trackColor != i4) { s3.trackColor = i4; invalidate(); } } public void setTrackCornerRadius(@Px int i4) { S s3 = this.f24027a; if (s3.trackCornerRadius != i4) { s3.trackCornerRadius = Math.min(i4, s3.trackThickness / 2); } } public void setTrackThickness(@Px int i4) { S s3 = this.f24027a; if (s3.trackThickness != i4) { s3.trackThickness = i4; requestLayout(); } } public void setVisibilityAfterHide(int i4) { if (i4 != 0 && i4 != 4 && i4 != 8) { throw new IllegalArgumentException("The component's visibility must be one of VISIBLE, INVISIBLE, and GONE defined in View."); } this.f24036j = i4; } public void show() { if (this.f24031e > 0) { removeCallbacks(this.f24037k); postDelayed(this.f24037k, this.f24031e); return; } this.f24037k.run(); } @Override // android.widget.ProgressBar @Nullable public IndeterminateDrawable<S> getIndeterminateDrawable() { return (IndeterminateDrawable) super.getIndeterminateDrawable(); } @Override // android.widget.ProgressBar @Nullable public DeterminateDrawable<S> getProgressDrawable() { return (DeterminateDrawable) super.getProgressDrawable(); } }
import React, {useState, useEffect, useRef} from "react"; import Blog from "./components/Blog"; import Notification from "./components/Notification"; import LoginForm from "./components/LoginForm"; import BlogForm from "./components/BlogForm"; import Togglable from "./components/Togglable"; import blogService from "./services/blogs"; import loginService from "./services/login"; const App = () => { const [blogs, setBlogs] = useState([]); const [message, setMessage] = useState(null); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [update, setUpdate] = useState(null); const [user, setUser] = useState(null); const blogRef = useRef(); useEffect(() => { blogService.getAll().then((blogs) => setBlogs(blogs)); }, [update]); useEffect(() => { const loggedUserJSON = window.localStorage.getItem("loggedUser"); if (loggedUserJSON) { const user = JSON.parse(loggedUserJSON); setUser(user); blogService.setToken(user.token); } }, []); useEffect(() => { setTimeout(() => { setMessage(null); }, 5000); }, [message]); // LOGIN const handleLogin = async (event) => { event.preventDefault(); try { const user = await loginService.login({ username, password, }); blogService.setToken(user.token); window.localStorage.setItem("loggedUser", JSON.stringify(user)); setUser(user); setUsername(""); setPassword(""); setMessage({ text: `${user.name} logged in.`, type: "success", }); } catch (exception) { setMessage({ text: "Wrong username or password. Please try again.", type: "error", }); } }; // LOGOUT const handleLogout = async () => { window.localStorage.removeItem("loggedUser"); setMessage({ text: "Logout successful.", type: "success", }); setUser(null); }; // CREATE BLOG const createBlog = async (blogObject) => { try { blogRef.current.toggleVisibility(); const response = await blogService.create(blogObject); setBlogs(blogs.concat(response)); setMessage({ text: `A new blog ${response.title} by ${response.author} added.`, type: "success", }); } catch (exception) { // simply show exception from backend as error setMessage({ text: `${exception}`, type: "error", }); } }; // DELETE BLOG const deleteBlog = async (blog) => { const result = window.confirm(`Remove a blog ${blog.title} by ${blog.author}.`); if (result) { await blogService.remove({ id: blog.id, }); setUpdate(Math.floor(Math.random() * 1000)); } }; // LIKE BLOG const likeBlog = async (id, likes) => { await blogService.update({ id: id, likes: likes + 1, }); setUpdate(Math.floor(Math.random() * 1000)); }; // LOGIN FORM const loginForm = () => ( <Togglable buttonLabel="Log in"> <LoginForm handleSubmit={handleLogin} username={username} password={password} handleUsernameChange={({target}) => setUsername(target.value)} handlePasswordChange={({target}) => setPassword(target.value)} /> </Togglable> ); const userInfo = () => ( <div> {user.name} logged in <button onClick={handleLogout}>Logout</button> </div> ); // BLOG FORM const blogForm = () => ( <Togglable buttonLabel="Create Blog" ref={blogRef}> <BlogForm createBlog={createBlog} /> </Togglable> ); return ( <div> <Notification message={message} /> {user === null ? ( <div> <h2>Log in.</h2> {loginForm()} </div> ) : ( <div> <h2>Blogs</h2> {userInfo()} {blogForm()} {blogs.sort((a, b) => (a.likes > b.likes ? -1 : 1)) && blogs.map((blog) => ( <Blog blog={blog} likeBlog={likeBlog} deleteBlog={deleteBlog} key={blog.id} /> ))} </div> )} </div> ); }; export default App;
#! /usr/bin/env bash # Patch: -pro_powerpc_4xx_use_default_nand_oob # Date: Fri Aug 15 13:07:03 2008 # MR: 27840 # Source: MontaVista Software, Inc. # Type: Enhancement # Disposition: local # Signed-off-by: Valentine Barshak <vbarshak@ru.mvista.com> # Description: # Use default NAND OOB layout for kilauea and canyonlands. # Based on the powerpc git warp-nand changes # from 4ebef31fa6e013e5cd3d4522e6018eb6d55046be # PATCHNUM=1473 LSPINFO=include/linux/lsppatchlevel.h TMPFILE=/tmp/mvl_patch_$$ function dopatch() { patch $* >${TMPFILE} 2>&1 <<"EOF" MR: 27840 Source: MontaVista Software, Inc. Type: Enhancement Disposition: local Signed-off-by: Valentine Barshak <vbarshak@ru.mvista.com> Description: Use default NAND OOB layout for kilauea and canyonlands. Based on the powerpc git warp-nand changes from 4ebef31fa6e013e5cd3d4522e6018eb6d55046be Index: linux-2.6.18/arch/powerpc/platforms/40x/kilauea-nand.c --- linux-2.6.18.orig/arch/powerpc/platforms/40x/kilauea-nand.c +++ linux-2.6.18/arch/powerpc/platforms/40x/kilauea-nand.c @@ -71,19 +71,12 @@ static struct platform_device kilauea_nd .resource = &kilauea_ndfc, }; -static struct nand_ecclayout nand_oob_16 = { - .eccbytes = 3, - .eccpos = { 0, 1, 2, 3, 6, 7 }, - .oobfree = { {.offset = 8, .length = 16} } -}; - static struct platform_nand_chip kilauea_nand_chip0 = { .nr_chips = 1, .chip_offset = CS_NAND_0, .nr_partitions = ARRAY_SIZE(nand_parts), .partitions = nand_parts, .chip_delay = 50, - .ecclayout = &nand_oob_16, .priv = &kilauea_chip0_settings, }; Index: linux-2.6.18/arch/powerpc/platforms/44x/canyonlands-nand.c --- linux-2.6.18.orig/arch/powerpc/platforms/44x/canyonlands-nand.c +++ linux-2.6.18/arch/powerpc/platforms/44x/canyonlands-nand.c @@ -71,19 +71,12 @@ static struct platform_device canyonland .resource = &canyonlands_ndfc, }; -static struct nand_ecclayout nand_oob_16 = { - .eccbytes = 3, - .eccpos = { 0, 1, 2, 3, 6, 7 }, - .oobfree = { {.offset = 8, .length = 16} } -}; - static struct platform_nand_chip canyonlands_nand_chip0 = { .nr_chips = 1, .chip_offset = CS_NAND_0, .nr_partitions = ARRAY_SIZE(nand_parts), .partitions = nand_parts, .chip_delay = 50, - .ecclayout = &nand_oob_16, .priv = &canyonlands_chip0_settings, }; Index: linux-2.6.18/mvl_patches/pro50-1473.c --- /dev/null +++ linux-2.6.18/mvl_patches/pro50-1473.c @@ -0,0 +1,16 @@ +/* + * Author: MontaVista Software, Inc. <source@mvista.com> + * + * 2008 (c) MontaVista Software, Inc. This file is licensed under + * the terms of the GNU General Public License version 2. This program + * is licensed "as is" without any warranty of any kind, whether express + * or implied. + */ +#include <linux/init.h> +#include <linux/mvl_patch.h> + +static __init int regpatch(void) +{ + return mvl_register_patch(1473); +} +module_init(regpatch); EOF rv=0 cat /tmp/mvl_patch_$$ if [ "$?" != "0" ]; then # Patch had a hard error, return 2 rv=2 elif grep '^Hunk' ${TMPFILE}; then rv=1 fi rm -f ${TMPFILE} return $rv } function options() { echo "Options are:" echo " --force-unsupported - Force the patch to be applied even if the" echo " patch is out of order or the current kernel is unsupported." echo " Use of this option is strongly discouraged." echo " --force-apply-fuzz - If the patch has fuzz, go ahead and apply" echo " it anyway. This can occur if the patch is applied to an" echo " unsupported kernel or applied out of order or if you have" echo " made your own modifications to the kernel. Use with" echo " caution." echo " --remove - Remove the patch" } function checkpatchnum() { local level; if [ ! -e ${1} ]; then echo "${1} does not exist, make sure you are in the kernel" 1>&2 echo "base directory" 1>&2 exit 1; fi # Extract the current patch number from the lsp info file. level=`grep '#define LSP_.*PATCH_LEVEL' ${1} | sed 's/^.*\"\\(.*\\)\".*\$/\\1/'` if [ "a$level" = "a" ]; then echo "No patch level defined in ${1}, are you sure this is" 1>&2 echo "a valid MVL kernel LSP?" 1>&2 exit 1; fi expr $level + 0 >/dev/null 2>&1 isnum=$? # Check if the kernel is supported if [ "$level" = "unsupported" ]; then echo "**Current kernel is unsupported by MontaVista due to patches" echo " begin applied out of order." if [ $force_unsupported == 't' ]; then echo " Application is forced, applying patch anyway" unsupported=t fix_patch_level=f else echo " Patch application aborted. Use --force-unsupported to" echo " force the patch to be applied, but the kernel will not" echo " be supported by MontaVista." exit 1; fi # Check the patch number from the lspinfo file to make sure it is # a valid number elif [ $isnum = 2 ]; then echo "**Patch level from ${1} was not a valid number, " 1>&2 echo " are you sure this is a valid MVL kernel LSP?" 1>&2 exit 1; # Check that this is the right patch number to be applied. elif [ `expr $level $3` ${4} ${2} ]; then echo "**Application of this patch is out of order and will cause the" echo " kernel to be unsupported by MontaVista." if [ $force_unsupported == 't' ]; then echo " application is forced, applying patch anyway" unsupported=t else echo " Patch application aborted. Please get all the patches in" echo " proper order from MontaVista Zone and apply them in order" echo " If you really want to apply this patch, use" echo " --force-unsupported to force the patch to be applied, but" echo " the kernel will not be supported by MontaVista." exit 1; fi fi } # # Update the patch level in the file. Note that we use patch to do # this. Certain weak version control systems don't take kindly to # arbitrary changes directly to files, but do have a special version # of "patch" that understands this. # function setpatchnum() { sed "s/^#define LSP_\(.*\)PATCH_LEVEL[ \t*]\"[0-9]*\".*$/#define LSP_\1PATCH_LEVEL \"${2}\"/" <${1} >/tmp/$$.tmp1 diff -u ${1} /tmp/$$.tmp1 >/tmp/$$.tmp2 rm /tmp/$$.tmp1 sed "s/^+++ \/tmp\/$$.tmp1/+++ include\/linux\/lsppatchlevel.h/" </tmp/$$.tmp2 >/tmp/$$.tmp1 rm /tmp/$$.tmp2 patch -p0 </tmp/$$.tmp1 rm /tmp/$$.tmp1 } force_unsupported=f force_apply_fuzz="" unsupported=f fix_patch_level=t reverse=f common_patchnum_diff='+ 1' common_patchnum=$PATCHNUM patch_extraopts='' # Extract command line parameters. while [ $# -gt 0 ]; do if [ "a$1" == 'a--force-unsupported' ]; then force_unsupported=t elif [ "a$1" == 'a--force-apply-fuzz' ]; then force_apply_fuzz=y elif [ "a$1" == 'a--remove' ]; then reverse=t common_patchnum_diff='' common_patchnum=`expr $PATCHNUM - 1` patch_extraopts='--reverse' else echo "'$1' is an invalid command line parameter." options exit 1 fi shift done echo "Checking patch level" checkpatchnum ${LSPINFO} ${PATCHNUM} "${common_patchnum_diff}" "-ne" if ! dopatch -p1 --dry-run --force $patch_extraopts; then if [ $? = 2 ]; then echo -n "**Patch had errors, application aborted" 1>&2 exit 1; fi # Patch has warnings clean_apply=${force_apply_fuzz} while [ "a$clean_apply" != 'ay' -a "a$clean_apply" != 'an' ]; do echo -n "**Patch did not apply cleanly. Do you still want to apply? (y/n) > " read clean_apply clean_apply=`echo "$clean_apply" | tr '[:upper:]' '[:lower:]'` done if [ $clean_apply = 'n' ]; then exit 1; fi fi dopatch -p1 --force $patch_extraopts if [ $fix_patch_level = 't' ]; then if [ $unsupported = 't' ]; then common_patchnum="unsupported" fi setpatchnum ${LSPINFO} ${common_patchnum} fi # Move the patch file into the mvl_patches directory if we are not reversing if [ $reverse != 't' ]; then if echo $0 | grep '/' >/dev/null; then # Filename is a path, either absolute or from the current directory. srcfile=$0 else # Filename is from the path for i in `echo $PATH | tr ':;' ' '`; do if [ -e ${i}/$0 ]; then srcfile=${i}/$0 fi done fi fname=`basename ${srcfile}` diff -uN mvl_patches/${fname} ${srcfile} | (cd mvl_patches; patch) fi
using LMS.Application.Interfaces; using LMS.Application.Services; using LMS.CoreBusiness.Entities.Accounts; using LMS.CoreBusiness.Interfaces; using LMS.CoreBusiness.UnitsOfWork; using LMS.Infrastructure.Data; using LMS.Infrastructure.Repositories; using LMS.Infrastructure.UnitsOfWork; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System.Text; namespace LMS.Infrastructure.Extensions { public static class DependencyInjection { public static IServiceCollection AddInfrastructure(this IServiceCollection services) { const string environmentVariable = "ConnectionStrings:LmsDefaultConnection"; services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Environment.GetEnvironmentVariable(environmentVariable))); services.AddDbContext<UsersDbContext>(options => options.UseSqlServer( Environment.GetEnvironmentVariable(environmentVariable))); services.AddIdentity<AspNetUsers, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<UsersDbContext>() .AddDefaultTokenProviders(); services.AddScoped<IAuthorRepository, AuthorRepository>(); services.AddScoped<IAuthorService, AuthorService>(); services.AddScoped<ICategoryRepository, CategoryRepository>(); services.AddScoped<ICategoryService, CategoryService>(); services.AddScoped<IBookRepository, BookRepository>(); services.AddScoped<IBookService, BookService>(); services.AddScoped<IAuthorshipRepository, AuthorshipRepository>(); services.AddScoped<IAuthorshipService, AuthorshipService>(); services.AddScoped<ILibrarianRepository, LibrarianRepository>(); services.AddScoped<ILibrarianService, LibrarianService>(); services.AddScoped<IPurchaseRepository, PurchaseRepository>(); services.AddScoped<IPurchaseService, PurchaseService>(); services.AddScoped<IAcquisitionRepository, AcquisitionRepository>(); services.AddScoped<IAcquisitionService, AcquisitionService>(); services.AddScoped<IStockRepository, StockRepository>(); services.AddScoped<IStockService, StockService>(); services.AddScoped<IAccountRepository, AccountRepository>(); services.AddScoped<IAccountService, AccountService>(); return services; } public static IServiceCollection AddUnitsOfWork(this IServiceCollection services) { services.AddScoped<IAcquisitionUnitOfWork, AcquisitionUnitOfWork>(); services.AddScoped<IPurchaseUnitOfWork, PurchaseUnitOfWork>(); return services; } public static IServiceCollection ConfigureJwtAuthentication(this IServiceCollection services, IConfiguration configuration) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = configuration.GetSection("JwtKeys:Issuer").Value, ValidAudience = configuration.GetSection("JwtKeys:Audience").Value, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("JwtKeys:Secret").Value)) }; }); return services; } public static IServiceCollection ConfigureCors(this IServiceCollection services) { var MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, policy => { policy.WithOrigins("https://localhost:7078/api/"); }); }); return services; } } }
<html> <head> <meta charset="utf-8"> <script src="js/jquery-1.10.2.js"></script> <script> var url = "/PersonaCXF/service/personas"; var obtenerTodos = function() { $.ajax(url, { type : "GET", dataType : "json" }).done(function(json) { $("#resultado").html(JSON.stringify(json)); // stringify convierte un JSON a String }); }; var obtener = function() { var id = $("#mensaje").val(); $.ajax(url + "/" + id, { type : "GET", dataType : "json" }).done(function(json) { $("#resultado").html(JSON.stringify(json)); }); }; var agregar = function() { var mensaje = $("#mensaje").val(); $.ajax(url, { type : "POST", data : mensaje, contentType : "application/json" }).done(function() { $("#resultado").html("Elemento agregado..."); }); }; var modificar = function() { var mensaje = $("#mensaje").val(); $.ajax(url, { type : "PUT", data : mensaje, contentType : "application/json" }).done(function() { $("#resultado").html("Elemento modificado..."); }); }; var eliminar = function() { var id = $("#mensaje").val(); $.ajax(url + "/" + id, { type : "DELETE" }).done(function() { $("#resultado").html("Elemento eliminado..."); }); }; $(document).ready(function() { $("#btnObtenerTodos").click(obtenerTodos); $("#btnObtener").click(obtener); $("#btnAgregar").click(agregar); $("#btnModificar").click(modificar); $("#btnEliminar").click(eliminar); }); </script> </head> <body> <p>En caso de que la operación sea agregar o modificar el mensaje debe ser un JSON, por ejemplo: { "id": "6", "nombre": "Mio", "apellido": "Otro Otro" }. Si desea agregar puede omitir el "id". Para obtener y eliminar debe especificar un número, por ejemplo: 2</p> <textarea id="mensaje"></textarea> <br /> <br /> <input type="button" id="btnObtenerTodos" value="obtenerTodos" /> <input type="button" id="btnObtener" value="obtener" /> <input type="button" id="btnAgregar" value="agregar" /> <input type="button" id="btnModificar" value="modificar" /> <input type="button" id="btnEliminar" value="eliminar" /> <br /> <br /> <div id="resultado"></div> </body> </html>
<?php declare(strict_types=1); /* * This file is part of the drewlabs namespace. * * (c) Sidoine Azandrew <azandrewdevelopper@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Drewlabs\Soap; use Drewlabs\Soap\Contracts\RequestInterface; class SoapInterpreter { /** * @var SoapClient */ private $client; /** * The request class that is binded to the SoapClient * That request class can be used to modify the actual request string. * * @var string */ private $requestClass; public function __construct(SoapClient $client, string $requestClass = null) { $this->client = $client; $requestClass = $requestClass ?? DefaultSoapRequest::class; $this->bindRequest($requestClass); } public function bindRequest(string $class) { $this->requestClass = $class; return $this; } /** * Interpret the given method and arguments to a SOAP request message. * * @param string $action the name of the SOAP function to interpret * @param array $args an array of the arguments to $func * @param array $options An associative array of options. * The location option is the URL of the remote Web service. * The uri option is the target namespace of the SOAP service. * The soapaction option is the action to call. * @param mixed $headers an array of headers to be interpreted along with the SOAP request * * @return RequestInterface */ public function request($action, array $args = [], array $options = null, $headers = null) { if (null !== $this->requestClass) { $this->client = $this->client->withRequestClass($this->requestClass); } return $this->client->withHeaders($headers)->request($action, $args, $options); } /** * Interpret a SOAP response message to PHP values. * * @param string $response the SOAP response message * @param string $action the name of the SOAP function to interpret * @param array $output_headers if supplied, this array will be filled with the headers from the SOAP response * * @throws \SoapFault * * @return mixed */ public function response($response, $action, array &$output_headers = null) { return $this->client->response($response, $action, $output_headers); } }
import { MAX_ENTRY_LENGTH } from "../config/constants.js"; /** * Represents an error for a missing or malformed changelog heading in a PR description. */ export class InvalidChangelogHeadingError extends Error { /** * Constructs the InvalidChangelogHeadingError instance. */ constructor() { const message = "The '## Changelog' heading in your PR description is either missing or malformed. Please make sure that your PR description includes a '## Changelog' heading with proper spelling, capitalization, spacing, and Markdown syntax."; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error for an empty changelog section in a PR description. */ export class EmptyChangelogSectionError extends Error { /** * Constructs the EmptyChangelogSectionError instance. */ constructor() { const message = "The Changelog section in your PR description is empty. Please add a valid changelog entry or entries. If you did add a changelog entry, check to make sure that it was not accidentally included inside the comment block in the Changelog section."; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error when a changelog entry exceeds the maximum allowed length. */ export class EntryTooLongError extends Error { /** * Constructs the EntryTooLongError instance. * @param {string} entryLength - The length of the entry provided by the user. */ constructor(entryLength) { const characterOverage = entryLength - MAX_ENTRY_LENGTH; const message = `Entry is ${entryLength} characters long, which is ${characterOverage} ${ characterOverage === 1 ? "character" : "characters" } longer than the maximum allowed length of ${MAX_ENTRY_LENGTH} characters. Please revise your entry to be within the maximum length.`; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error when a specified category does not exist. */ export class InvalidPrefixError extends Error { /** * Constructs the InvalidPrefixError instance. * @param {string} foundPrefix - The prefix provided by the user. */ constructor(foundPrefix) { const message = `Invalid description prefix. Found "${foundPrefix}". Expected "breaking", "deprecate", "feat", "fix", "infra", "doc", "chore", "refactor", "security", "skip", or "test".`; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error when a specified prefix is not "skip" in manual mode. */ export class InvalidPrefixForManualChangesetCreationError extends Error { /** * Constructs the InvalidPrefixForManualChangesetCreationError instance. * @param {string} foundPrefix - The prefix provided by the user. */ constructor(foundPrefix) { const message = `Invalid description prefix. Found "${foundPrefix}". Only "skip" entry option is permitted for manual commit of changeset files.` + `\n\n` + `If you were trying to skip the changelog entry, please use the "skip" entry option in the ##Changelog section of your PR description.`; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error when a category is incorrectly included with a 'skip' option. */ export class InvalidAdditionalPrefixWithSkipEntryOptionError extends Error { /** * Constructs the CategoryWithSkipError instance. */ constructor() { const message = "If your Changelog section includes the 'skip' entry option, it cannot also include other changelog entry prefixes. The option 'skip' must be alone when used. Please review your Changelog section again."; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error when a changelog entry does not start with a '-' character. */ export class ChangelogEntryMissingHyphenError extends Error { /** * Constructs the ChangelogEntryMissingHyphenError instance. */ constructor() { const message = "Changelog entries must begin with a hyphen (-)."; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } } /** * Represents an error when a description is empty. */ export class EmptyEntryDescriptionError extends Error { /** * Constructs the EmptyDescriptionError instance. * @param {string} foundPrefix - The prefix provided by the user. */ constructor(foundPrefix) { const message = `Description for "${foundPrefix}" entry cannot be empty.`; super(message); this.name = this.constructor.name; this.shouldResultInPRComment = true; } }
\begin{enumerate} \item[1.7] Give state diagrams of NFAs with the specified number of states recognizing each of the following languages. In all parts, the alphabet is {0,1}. \begin{enumerate} \item The language $\{w|w~ \text{ends with }00\}$ with three states \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, accepting, right of=q2] (q3) {}; \draw (q1) edge[above] node{$0$} (q2) (q2) edge[above] node{$0$} (q3) (q1) edge[loop above] node{$0,1$} (q1); \end{tikzpicture} \end{figure} \item The language of Exercise 1.6c with five states \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, right of=q2] (q3) {}; \node[state, right of=q3] (q4) {}; \node[state, accepting, right of=q4] (q5) {}; \draw (q1) edge[loop above] node{$1$} (q1) (q1) edge[above] node{$0$} (q2) (q2) edge[loop above] node{$0$} (q2) (q2) edge[above] node{$1$} (q3) (q3) edge[above] node{$0$} (q4) (q4) edge[above] node{$1$} (q5) (q5) edge[loop above] node{$0,1$} (q5) (q3) edge[bend left, below] node{$1$} (q1) (q4) edge[bend right, above] node{$0$} (q2); \end{tikzpicture} \end{figure} \item The language of Exercise 1.6l with six states \begin{figure}[H] \centering \begin{tikzpicture} \node[state, accepting, initial] (q1) {}; \node[state, above right of=q1] (q2) {}; \node[state, accepting, below right of=q1] (q3) {}; \node[state, right of=q3] (q4) {}; \node[state, right of=q2] (q5) {}; \node[state, accepting, right of=q5] (q6) {}; \draw (q1) edge[right] node{$\epsilon$} (q2) (q1) edge[above] node{$1$} (q3) (q3) edge[above] node{$1$} (q4) (q1) edge[loop above] node{$0$} (q1) (q3) edge[loop above] node{$0$} (q3) (q4) edge[loop above] node{$0$} (q4) (q2) edge[loop above] node{$0,1$} (q2) (q5) edge[loop above] node{$1$} (q5) (q6) edge[loop above] node{$0,1$} (q6) (q2) edge[right, below] node{$0$} (q5) (q5) edge[right, below] node{$0$} (q6); \end{tikzpicture} \end{figure} \item The language $\{0\}$ with two states \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q1) {}; \node[state, accepting, right of=q1] (q2) {}; \draw (q1) edge[above] node{$0$} (q2); \end{tikzpicture} \end{figure} \item The language $0^\ast1^\ast0+$ with three states \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, accepting, right of=q2] (q3) {}; \draw (q1) edge[above] node{$\epsilon$} (q2) (q2) edge[above] node{$0$} (q3) (q1) edge[loop above] node{$0$} (q1) (q2) edge[loop above] node{$1$} (q2) (q3) edge[loop above] node{$0$} (q3); \end{tikzpicture} \end{figure} \item The language $1^\ast(001+)^\ast$ with three states \begin{figure}[H] \centering \begin{tikzpicture} \node[state, accepting, initial] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, below right of=q1] (q3) {}; \draw (q1) edge[above] node{$0$} (q2) (q2) edge[right] node{$0$} (q3) (q3) edge[left] node{$1$} (q1) (q1) edge[loop above] node{$1$} (q1); \end{tikzpicture} \end{figure} \item The language ${\epsilon}$ with one state \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial, accepting] (q1) {}; \end{tikzpicture} \end{figure} \item The language $0^\ast$ with one state \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial, accepting] (q1) {}; \draw (q1) edge[loop above] node{$0$} (q1); \end{tikzpicture} \end{figure} \end{enumerate} \item[1.8] Use the construction in the proof of Theorem 1.45 to give the state diagrams of NFAs recognizing the union of the languages described in: \begin{enumerate} \item Exercises 1.6a and 1.6b \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q0) {}; \node[state, above right of=q0] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, accepting, right of=q2] (q3) {}; \node[state, right of=q3] (q4) {}; \node[state, below right of=q0] (bq1) {}; \node[state, right of=bq1] (bq2) {}; \node[state, right of=bq2] (bq3) {}; \node[state, accepting, right of=bq3] (bq4) {}; \draw (q0) edge[above, blue] node{$\epsilon$} (q1) (q0) edge[above, blue] node{$\epsilon$} (bq1) (q1) edge[above] node{$1$} (q2) (q2) edge[loop above] node{$1$} (q2) (q2) edge[bend left, above] node{$0$} (q3) (q3) edge[loop above] node{$0$} (q3) (q3) edge[bend left, below] node{$1$} (q2) (q1) edge[bend right, below] node{$0$} (q4) (q4) edge[loop above] node{$0,1$} (q4) (q1) edge[loop above] node{$0$} (q1) (bq1) edge[above] node{$1$} (bq2) (bq2) edge[loop above] node{$0$} (bq2) (bq2) edge[above] node{$1$} (bq3) (bq3) edge[loop above] node{$0$} (bq3) (bq3) edge[above] node{$1$} (bq4) (bq4) edge[loop above] node{$0,1$} (bq4); \end{tikzpicture} \end{figure} \item Exercises 1.6c and 1.6f \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q0) {}; \node[state, above right of=q0] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, right of=q2] (q3) {}; \node[state, right of=q3] (q4) {}; \node[state, accepting, right of=q4] (q5) {}; \node[state, accepting, below right of=q0] (bq1) {}; \node[state, accepting, right of=bq1] (bq2) {}; \node[state, accepting, right of=bq2] (bq3) {}; \node[state, right of=bq3] (bq4) {}; \draw (q0) edge[above, blue] node{$\epsilon$} (q1) (q0) edge[above, blue] node{$\epsilon$} (bq1) (q1) edge[loop above] node{$1$} (q1) (q1) edge[above] node{$0$} (q2) (q2) edge[loop above] node{$0$} (q2) (q2) edge[above] node{$1$} (q3) (q3) edge[above] node{$0$} (q4) (q4) edge[above] node{$1$} (q5) (q5) edge[loop above] node{$0,1$} (q5) (q3) edge[bend left, below] node{$1$} (q1) (q4) edge[bend right, above] node{$0$} (q2) (bq1) edge[above] node{$1$} (bq2) (bq1) edge[loop above] node{$0$} (bq1) (bq2) edge[above] node{$1$} (bq3) (bq2) edge[bend right, above] node{$0$} (bq1) (bq3) edge[above] node{$0$} (bq4) (bq3) edge[loop above] node{$1$} (bq3) (bq4) edge[loop above] node{$0,1$} (bq4); \end{tikzpicture} \end{figure} \end{enumerate} \item[1.9] Use the construction in the proof of Theorem 1.47 to give the state diagrams of NFAs recognizing the concatenation of the languages described in \begin{enumerate} \item Exercises 1.6g and 1.6i. \begin{figure}[H] \centering \begin{tikzpicture} \node[state, accepting, initial] (q1) {}; \node[state, accepting, below of=q1] (q2) {}; \node[state, accepting, right of=q2] (q3) {}; \node[state, accepting, above of=q3] (q4) {}; \node[state, accepting, right of=q4] (q5) {}; \node[state, accepting, below of=q5] (q6) {}; \node[state, right of=q6] (q7) {}; \node[state, below of=q7] (bq1) {}; \node[state, above right of=bq1] (bq2) {}; \node[state, accepting, below right of=bq1] (bq3) {}; \node[state, accepting, right of=bq3] (bq5) {}; \draw (q7) edge[loop above] node{$0,1$} (q7) (q1) edge[left] node{$0,1$} (q2) (q2) edge[above] node{$0,1$} (q3) (q3) edge[left] node{$0,1$} (q4) (q4) edge[above] node{$0,1$} (q5) (q5) edge[left] node{$0,1$} (q6) (q6) edge[above] node{$0,1$} (q7) (bq1) edge[above] node{$0$} (bq2) (bq1) edge[above] node{$1$} (bq3) (bq2) edge[loop above] node{$0,1$} (bq2) (bq3) edge[bend left, above] node{$0,1$} (bq5) (bq5) edge[bend left, above] node{$1$} (bq3) (bq5) edge[bend right, above] node{$0$} (bq2) (q1) edge[left, below, blue] node{$\epsilon$} (bq1) (q2) edge[left, below, blue] node{$\epsilon$} (bq1) (q3) edge[left, below, blue] node{$\epsilon$} (bq1) (q4) edge[left, below, blue] node{$\epsilon$} (bq1) (q5) edge[left, below, blue] node{$\epsilon$} (bq1); \end{tikzpicture} \end{figure} \item Exercises 1.6b and 1.6m. \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, right of=q2] (q3) {}; \node[state, accepting, right of=q3] (q4) {}; \node[state, right of=q4] (bq1) {}; \draw (q1) edge[loop above] node{$0$} (q1) (q1) edge[above] node{$1$} (q2) (q2) edge[loop above] node{$0$} (q2) (q2) edge[above] node{$1$} (q3) (q3) edge[loop above] node{$0$} (q3) (q3) edge[above] node{$1$} (q4) (q4) edge[loop above] node{$0,1$} (q4) (q4) edge[above, blue] node{$\epsilon$} (bq1) (bq1) edge[loop right] node{$0,1$} (bq1); \end{tikzpicture} \end{figure} \end{enumerate} \item [1.10] Use the construction in the proof of Theorem 1.49 to give the state diagrams of NFAs recognizing the star of the languages described in \begin{enumerate} \item Exercise 1.6b. \begin{figure}[H] \centering \begin{tikzpicture} \node[state, accepting, initial] (q0) {}; \node[state, right of=q0] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, right of=q2] (q3) {}; \node[state, accepting, right of=q3] (q4) {}; \draw (q0) edge[above] node{$\epsilon$} (q1) (q1) edge[loop above] node{$0$} (q1) (q1) edge[above] node{$1$} (q2) (q2) edge[loop above] node{$0$} (q2) (q2) edge[above] node{$1$} (q3) (q3) edge[loop above] node{$0$} (q3) (q3) edge[above] node{$1$} (q4) (q4) edge[loop above] node{$0,1$} (q4) (q4) edge[bend left, below] node{$\epsilon$} (q1); \end{tikzpicture} \end{figure} \item Exercise 1.6j. \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q0) {}; \node[state, right of=q0] (q1) {}; \node[state, above right of=q1] (q2) {}; \node[state, below right of=q1] (q3) {}; \node[state, below right of=q2] (q4) {}; \node[state, accepting, above right of=q2] (q5) {}; \node[state, below right of=q3] (q8) {}; \node[state, accepting, right of=q4] (q6) {}; \draw (q0) edge[above] node{$\epsilon$} (q1) (q1) edge[above] node{$0$} (q2) (q1) edge[above] node{$1$} (q3) (q2) edge[above] node{$0$} (q5) (q2) edge[above] node{$1$} (q4) (q3) edge[above] node{$0$} (q4) (q3) edge[above] node{$1$} (q8) (q4) edge[above] node{$0$} (q6) (q4) edge[right] node{$1$} (q8) (q5) edge[above] node{$1$} (q6) (q5) edge[loop right] node{$0$} (q5) (q6) edge[loop above] node{$0$} (q6) (q8) edge[loop right] node{$0,1$} (q8) (q6) edge[above] node{$1$} (q8) (q5) edge[bend left, below] node{$\epsilon$} (q1) (q6) edge[bend left, below] node{$\epsilon$} (q1); \end{tikzpicture} \end{figure} \item Exercise 1.6m. \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial, accepting] (q0) {}; \node[state, right of=q0] (q1) {}; \draw (q0) edge[above] node{$\epsilon$} (q1) (q1) edge[loop right] node{$0,1$} (q1); \end{tikzpicture} \end{figure} \end{enumerate} \item [1.11] Prove that every NFA can be converted to an equivalent one that has a single accept state. It is enough to show that every NFA can be converted to an equivalent one that has a single accept state and no transitions into the accept state. Let $N = (Q, \Sigma, \delta, q_0, F)$ be an NFA. We construct an NFA $N' = (Q \cup \{q_f\}, \Sigma, \delta', q_0, \{q_f\})$ where $\delta'$ is the same as $\delta$ with additional transitions: for each $q \in F$ $\delta'(q, \epsilon) = \{q_f\}$. It is clear that $L(N) = L(N')$ and that $N'$ has a single accept state. Therefore, every NFA can be converted to an equivalent one that has a single accept state. \item [1.12] Let \[D = \{w|w~ \text{contains an even number of }a\text{’s and an odd number of }b\text{’s}\] \[ \text{and does not contain the substring }ab\}\] Give a DFA with five states that recognizes $D$ and a regular expression that generates $D$. (Suggestion: Describe $D$ more simply.) $$D = \{w|w~ \text{contains odd number of }b\text{'s followed by even number of }a\text{'s} \}$$ \begin{figure}[H] \centering \begin{tikzpicture} \node[state, initial] (q0) {}; \node[state, accepting, right of=q0] (q1) {}; \node[state, right of=q1] (q2) {}; \node[state, right of=q2] (q3) {}; \node[state, above of=q1] (q5) {}; \draw (q0) edge[above] node{$b$} (q1) (q0) edge[bend right, below] node{$a$} (q2) (q1) edge[bend left, left] node{$b$} (q5) (q5) edge[bend left, left] node{$b$} (q1) (q1) edge[bend left, below] node{$a$} (q2) (q2) edge[bend left, above] node{$a$} (q1) (q2) edge[below] node{$b$} (q3) (q5) edge[below] node{$a$} (q3) (q3) edge[loop above] node{$a,b$} (q3); \end{tikzpicture} \end{figure} The regular expression that generates $D$ is $b(bb)^{\ast}(aa)^{\ast}$. \end{enumerate}
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Accueil</title> <link rel="stylesheet" href="/css/produitList.css" th:href="@{/css/produitList.css}" /> <link rel="stylesheet" href="/css/index.css" th:href="@{/css/index.css}" /> <link rel="stylesheet" href="/css/form.css" th:href="@{/css/form.css}" /> <script src="/js/index.js" th:src="@{/js/index.js}" type="text/javascript" ></script> </head> <body> <header class="absolute inset-x-0 top-0 z-50"> <div th:replace="~{navbar :: navbar}"></div> </header> <div class="mb-0 rounded-t border-0 pr-4_4 pl-4 pt-24"> <div class="flex flex-wrap items-center"> <div class="relative w-full max-w-full flex-1 flex-grow px-4"> <h3 class="text-blueGray-700 text-base font-semibold">Produits</h3> </div> <div class="relative w-full max-w-full flex-1 flex-grow px-4 text-right" > <a th:if="${isUserLoggedIn != null && isAdmin}" th:href="@{'/addProduit'}"> <button class="mb-1 mr-1 rounded bg-indigo-500 px-3 py-0_80 text-xs font-bold uppercase text-white outline-none transition-all duration-150 ease-linear focus:outline-none active:bg-indigo-500 hover:bg-indigo-600" type="button" > Ajouter un produit </button> </a> </div> </div> </div> <div class="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8 pt-10" > <div th:each="produit : ${produits}" class="mb-6 flex flex-col items-center justify-center" > <a th:href="@{/produit/perso/{id}(id=${produit.id})}" class="group"> <div class="aspect-h-1 aspect-w-1 xl:aspect-h-8 xl:aspect-w-7 h-52 w-52 overflow-hidden rounded-lg" > <img th:src="@{/displayImage/{id}(id=${produit.id})}" alt="image" class="h-full w-full object-cover object-center group-hover:opacity-75" /> </div> <h3 class="mt-4 text-sm text-gray-700" th:text="${produit.name}"></h3 ></a> <div class="pt-4"> <a th:if="${isUserLoggedIn != null && isAdmin}" th:href="@{/deleteProduct/{id}(id=${produit.id})}" onclick="return confirm('Are you sure you want to delete this product?')" ><button class="mr-3 py-1 mb-1 rounded bg-indigo-500 px-3 text-xs font-bold uppercase text-white outline-none transition-all duration-150 ease-linear hover:bg-indigo-600 focus:outline-none active:bg-indigo-500" type="button" > Supprimer </button></a > <a th:if="${isUserLoggedIn != null && isAdmin}" th:href="@{/editProduct/{id}(id=${produit.id})}"><button class="py-1 mb-1 mr-1 ml-3 rounded bg-indigo-500 px-3 text-xs font-bold uppercase text-white outline-none transition-all duration-150 ease-linear hover:bg-indigo-600 focus:outline-none active:bg-indigo-500" type="button" > Modifier </button></a> </div> </div> </div> </body> <script> function changeQuantity(element, operation) { var productId = element.getAttribute("data-product-id"); var stock = element.getAttribute("data-stock"); var quantityInput = document.getElementById("quantity" + productId); var currentQuantity = parseInt(quantityInput.value); if (operation === "plus" && currentQuantity < stock) { quantityInput.value = currentQuantity + 1; } else if (operation === "minus" && currentQuantity > 0) { quantityInput.value = currentQuantity - 1; } } function addToCart(element) { var productId = element.getAttribute("data-product-id"); var productPrix = element.getAttribute("data-product-prix"); var quantity = document.getElementById("quantity" + productId).value; console.log( "Produit ID:", productId, "Quantité:", quantity, "Prix", productPrix ); } </script> </html>
library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use IEEE.math_real.all; -- Test bench para el filtro FIR implementado en VHDL que incluye la generacion de la senal de entrada -- Autor: Estanislao Crivos -- Fecha: Junio 2024 -- Trabajo Final - Microarquitecturas y Softcores - CESE CO20 - FI UBA entity FIR_Filter_Full_System_TB is end; architecture FIR_Filter_Full_System_TB_Architecture of FIR_Filter_Full_System_TB is component FIR_Filter_Full_System is port ( filter_clk : in STD_LOGIC; -- Filter clock input filter_reset : in STD_LOGIC; -- Filter reset input (0 is operative) filter_A_0 : in STD_LOGIC; -- Filer coeff. selector bit 0 filter_A_1 : in STD_LOGIC; -- Filer coeff. selector bit 1 filter_output_data : out UNSIGNED(31 downto 0) -- Filter output ); end component; -- Call NCO component component nco is generic( DATA_W: natural := 11; -- cantidad de bits del dato ADDR_W: natural := 9; -- cantidad de bits de las direcciones de la LUT modulo: natural := 32767; -- cantidad de puntos PASO_W: natural := 11 -- cantidad de bits del paso ); port( clk: in std_logic; rst: in std_logic; paso: in unsigned(PASO_W-1 downto 0); -- valor de entrada (paso) salida_cos: out unsigned(DATA_W-2 downto 0); salida_sen: out unsigned(DATA_W-2 downto 0) ); end component; -- Declare Test Bench signals signal clock_TB : std_logic := '0'; signal reset_TB : std_logic := '0'; signal A_0_TB : std_logic := '0'; signal A_1_TB : std_logic := '0'; signal filter_output_TB : unsigned(31 downto 0) := (others => '0'); signal filter_output_logic_vector_TB : std_logic_vector(31 downto 0); begin test_process : process begin -- Switch to A = 01 wait for 450 us; -- reset_TB <= '1'; -- wait for 5 us; A_0_TB <= '1'; A_1_TB <= '0'; -- wait for 10 us; -- reset_TB <= '0'; -- Switch to A = 10 wait for 450 us; -- reset_TB <= '1'; -- wait for 5 us; A_0_TB <= '0'; A_1_TB <= '1'; -- wait for 10 us; -- reset_TB <= '0'; -- Switch to A = 11 wait for 450 us; -- reset_TB <= '1'; -- wait for 5 us; A_0_TB <= '1'; A_1_TB <= '1'; -- wait for 10 us; -- reset_TB <= '0'; end process test_process; -- Clocking process (1MHz clock) clock_process : process begin wait for 0.5 us; clock_TB <= not clock_TB; end process clock_process; -- Instatiate filter FILTER: FIR_Filter_Full_System port map ( filter_clk => clock_TB, filter_reset => reset_TB, filter_A_0 => A_0_TB, filter_A_1 => A_1_TB, filter_output_data => filter_output_TB ); filter_output_logic_vector_TB <= std_logic_vector(filter_output_TB); end;
import { Field, ObjectType } from '@nestjs/graphql'; import { IsNotEmpty, IsString, IsUUID } from 'class-validator'; import { Answer } from 'src/apis/answer/entities/answer.entity'; import { CompletedSurvey } from 'src/apis/completed-survey/entities/completed-survey.entity'; import { CommonEntity } from 'src/common/entity/common.entity'; import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; @Entity({ name: 'participant' }) @ObjectType() export class Participant extends CommonEntity { @IsUUID() @PrimaryGeneratedColumn('uuid') @Field(() => String) participant_id: string; @IsNotEmpty() @IsString() @Column({ type: 'varchar' }) @Field(() => String) participant_name: string; @IsNotEmpty() @IsString() @Column({ type: 'varchar' }) @Field(() => String) participant_birth: string; @IsNotEmpty() @IsString() @Column({ type: 'varchar' }) @Field(() => String) participant_sex: string; @OneToMany(() => Answer, (answer) => answer.participant) @Field(() => [Answer]) answer: Answer[]; @OneToMany( () => CompletedSurvey, (completedSurvey) => completedSurvey.participant, ) @Field(() => [CompletedSurvey]) completedSurvey: CompletedSurvey[]; @Field(() => Date) created_at: Date; @Field(() => Date) updated_at: Date; @Field(() => Date, { nullable: true }) deleted_at: Date; }
import { createSlice } from "@reduxjs/toolkit"; import { produce } from "immer"; const initialState = { item: '', currentItems: [] } export const itemSlice = createSlice({ name: 'item', initialState, reducers: { addItem: (state, action) => { const newItem = action.payload; const newArr = state.currentItems; document.getElementById('itemName').value = ''; newArr.push({ name: newItem, quantity: 1, grabbed: false }); state.numItems++; }, incrementQuantity: (state, action) => { for(let i = 0; i < state.currentItems.length; i++) { if(state.currentItems[i].name === action.payload) { state.currentItems[i].quantity += 1; } } }, decrementQuantity: (state, action) => { for(let i = 0; i < state.currentItems.length; i++) { if(state.currentItems[i].name === action.payload) { if(state.currentItems[i].quantity === 1) { state.currentItems.splice(i, 1) } else { state.currentItems[i].quantity -= 1; } } } } } }) export const { addItem, incrementQuantity, decrementQuantity } = itemSlice.actions; export default itemSlice.reducer;
<div class="page-content"> <div class="container-fluid"> <!-- start page title --> <!-- <app-breadcrumb></app-breadcrumb> --> <app-progress-bar></app-progress-bar> <!-- end page title --> <div class="row justify-content-center"> <div class="col-xxl-9"> <div class="card"> <div class="card-body"> <form #myForm="ngForm"> <div class="row mb-3"> <div class="col-lg-3"> <label for="quizNm" class="form-label-inline">{{ "course0104.quiz.quizDetail.quizNm" | translate }}<span class="text-danger"> *</span></label> </div> <div class="col-lg-9"> <input type="text" required class="form-control " id="quizNm" name="quizNm" placeholder="{{'course0104.quiz.quizDetail.placeholderQuizNm' | translate}}" [(ngModel)]="quiz.quizNm" #quizNm="ngModel" [ngClass]="{ 'is-invalid': (quizNm.invalid && submitted) || (quizNm.invalid && (quizNm.dirty || quizNm.touched))}" /> <div class="invalid-error" *ngIf="(quizNm.invalid && submitted) || quizNm.invalid && (quizNm.dirty || quizNm.touched)"> <span *ngIf="quizNm.errors?.['required']">{{ 'message.requiredQuizName' | translate }}</span> </div> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="quizTime" class="form-label-inline">{{ "course0104.quiz.quizDetail.quizTime" | translate }} {{ "course0104.quiz.quizDetail.minute" | translate }}<span class="text-danger"> *</span></label> </div> <div class="col-lg-9"> <input type="number" required class="form-control " id="quizTime" name="quizTime" placeholder="{{'course0104.quiz.quizDetail.placeholderQuizTime' | translate}}" [(ngModel)]="quiz.quizTime" #quizTime="ngModel" [ngClass]="{ 'is-invalid': (quizTime.invalid && submitted) || (quizTime.invalid && (quizTime.dirty || quizTime.touched))}" /> <div class="invalid-error" *ngIf="(quizTime.invalid && submitted) || quizTime.invalid && (quizTime.dirty || quizTime.touched)"> <span *ngIf="quizTime.errors?.['required']">{{ 'message.requiredQuizName' | translate }}</span> </div> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="quizContent" class="form-label-inline">{{ "course0104.quiz.quizDetail.quizContent" | translate }}<span class="text-danger"> *</span></label> </div> <div class="col-lg-9"> <textarea required class="form-control " id="quizContent" name="quizContent" placeholder="{{'course0104.quiz.quizDetail.placeholderQuizContent' | translate}}" [(ngModel)]="quiz.quizContent" #quizContent="ngModel" [ngClass]="{ 'is-invalid': (quizContent.invalid && submitted) || (quizContent.invalid && (quizContent.dirty || quizContent.touched))}"></textarea> <div class="invalid-error" *ngIf="(quizContent.invalid && submitted) || quizContent.invalid && (quizContent.dirty || quizContent.touched)"> <span *ngIf="quizContent.errors?.['required']">{{ 'message.requiredQuizContent' | translate }}</span> </div> </div> </div> <div class="row mb-3" style="display: none;"> <div class="col-lg-3"> <label for="quizType" class="form-label-inline">{{ "course0104.quiz.quizDetail.quizType" | translate }}<span class="text-danger"> *</span></label> </div> <div class="col-lg-9"> <p-dropdown appendTo="body" placeholder="{{'course0104.quiz.quizDetail.placeholderQuizType' | translate}}" [required]="true" [options]="quizTypes" [(ngModel)]="quiz.quizType" optionLabel="commNm" optionValue="commCd" [ngModelOptions]="{ standalone: true }" #quizType="ngModel" [ngClass]="{ 'ng-invalid ng-dirty': (quizType.invalid && submitted) || quizType.invalid && (quizType.dirty || quizType.touched)}"> </p-dropdown> <div class="invalid-error" *ngIf="(quizType.invalid && submitted) || quizType.invalid && (quizType.dirty || quizType.touched)"> <span *ngIf="quizType.errors?.['required']">{{ 'course0104.quiz.quizDetail.quizTypeRequired' | translate }}</span> </div> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="ordNo" class="form-label-inline">{{ "course0101.lectureDetail.ordNo" | translate }}</label> </div> <div class="col-lg-9"> <input type="number" class="form-control " id="ordNo" name="ordNo" placeholder="{{'course0101.lectureDetail.placeholderOrdNo' | translate}}" [(ngModel)]="quiz.ordNo" #url="ngModel" /> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="status-user" class="form-label-inline">{{ "sys3.userDetail.status" | translate }}<span class="text-danger"> *</span></label> </div> <div class="col-lg-9"> <span class="form-check form-check-inline"> <label class="form-check-label" for="active"> {{"sys.sys0103.status.active" | translate }} </label> <input class="form-check-input" type="radio" name="status" id="active" (change)="quiz.status=true" [checked]="quiz.status == true"> </span> <span class="form-check form-check-inline"> <label class="form-check-label" for="disable"> {{"sys.sys0103.status.blocked" | translate }} </label> <input class="form-check-input" type="radio" name="status" id="disable" (change)="quiz.status=false" [checked]="quiz.status == false"> </span> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" (click)="goList()"> {{ "button.back.title2" | translate }} </button> <button *ngIf="!quiz.cannotCRUD" type="button" class="btn btn-primary" (click)="onSave(myForm.invalid)"> {{ "sys3.userDetail.buttonSave" | translate }} </button> </div> <!-- end card-body --> </div> <!-- end card --> </div> <!-- end col --> </div> <div class="row justify-content-center"> <div class="col-xxl-9"> <div class="card"> <div class="card-body"> <div class="modal-footer"> <a *ngIf="!quiz.cannotCRUD" href="assets/file/templateQuiz.xls" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "course0104.quiz.quizDetail.downloadTemplate" | translate }} </a> <input #inputFile hidden type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onclick="this.value = null" (change)="importExcel($event)" /> <button (click)="exportPDF(quizId)" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "course0104.quiz.quizDetail.exportPDF" | translate }} </button> <button *ngIf="!quiz.cannotCRUD" (click)="inputFile.click()" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "course0104.quiz.quizDetail.importExcel" | translate }} </button> <button *ngIf="!quiz.cannotCRUD" (click)="addNewQuestion(0)" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "button.add.title" | translate }} </button> </div> </div> </div> </div> </div> <div class="row justify-content-center"> <ng-container *ngFor="let quizItem of listQuizItem; let index = index;"> <div *ngIf="quizItem.crudType != 'D'" class="col-xxl-8" id="quizItem{{index}}"> <div class="card"> <div class="card-header align-items-center"> <h4 class="card-title mb-0 flex-grow-1">{{ "course0104.quiz.quizDetail.question" | translate }}{{quizItem.index}}</h4> </div><!-- end card header --> <div class="card-body"> <div class="live-preview"> <!-- <form #quizItemForm="ngForm"> --> <div class="row mb-3"> <div class="col-lg-3"> <label for="quizType" class="form-label-inline">{{ "course0104.quiz.quizDetail.quizType" | translate }}</label> </div> <div class="col-lg-9"> <p-dropdown appendTo="body" placeholder="{{'course0104.quiz.quizDetail.placeholderQuizType' | translate}}" [required]="true" [options]="quizItemTypes" [(ngModel)]="quizItem.quizItemType" optionLabel="commNm" optionValue="commCd" [ngModelOptions]="{ standalone: true }" #quizType="ngModel"> </p-dropdown> </div> </div> <ng-container *ngIf="quizItem.quizItemType == '08-03'"> <div class="row mb-3"> <div class="col-lg-3"> <label for="meassageInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.questionContent" | translate }}</label> </div> <div class="col-lg-9"> <textarea [(ngModel)]="quizItem.quizItemContent" name="quizItemContent" class="form-control" id="meassageInput" rows="3" placeholder="Enter your message"></textarea> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.answerContent" | translate }} A</label> </div> <div class="col-lg-9"> <input [(ngModel)]="quizItem.answerA" name="answerA" type="text" class="form-control" id="nameInput" placeholder="Enter your content"> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.answerContent" | translate }} B</label> </div> <div class="col-lg-9"> <input [(ngModel)]="quizItem.answerB" name="answerB" type="text" class="form-control" id="nameInput" placeholder="Enter your content"> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.answerContent" | translate }} C</label> </div> <div class="col-lg-9"> <input [(ngModel)]="quizItem.answerC" name="answerC" type="text" class="form-control" id="nameInput" placeholder="Enter your content"> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.answerContent" | translate }} D</label> </div> <div class="col-lg-9"> <input [(ngModel)]="quizItem.answerD" name="answerD" type="text" class="form-control" id="nameInput" placeholder="Enter your content"> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.correctAnswer" | translate }}</label> </div> <div class="col-lg-9"> <p-multiSelect required #listClassCheckedvalid="ngModel" [options]="listCorrectAnswer" [(ngModel)]="quizItem.answerCorrect" name="answerCorrect" defaultLabel="Chọn Đáp Án" optionLabel="label" [style]="{'width':'100%'}"></p-multiSelect> </div> </div> </ng-container> <ng-container *ngIf="quizItem.quizItemType == '08-01'"> <div class="row mb-3"> <div class="col-lg-3"> <label for="meassageInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.questionContent" | translate }}</label> </div> <div class="col-lg-9"> <textarea [(ngModel)]="quizItem.quizItemContent" name="quizItemContent" class="form-control" id="meassageInput" rows="3" placeholder="{{ 'course0104.quiz.quizDetail.enterQuestion' | translate }}"></textarea> </div> </div> <div class="row mb-3" *ngFor="let answer of quizItem.listAnswer; let answerIndex = index"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.answerContent" | translate }} {{answerIndex+1}}</label> </div> <div class="col-lg-7"> <input [(ngModel)]="answer.answerContent" name="answerC" type="text" class="form-control" id="nameInput" placeholder="{{ 'course0104.quiz.quizDetail.enterAnswer' | translate }}"> </div> <div class="col-lg-2"> <button (click)="removeAnswer(quizItem.listAnswer, answerIndex)" *ngIf="quizItem.listAnswer.length > 1" type="button" class="btn btn-light waves-effect"><i class="ri-checkbox-indeterminate-line"></i></button> <button (click)="addAnswer(quizItem.listAnswer)" *ngIf="answerIndex == quizItem.listAnswer.length - 1" type="button" class="btn btn-light waves-effect"><i class="ri-add-box-line"></i></button> </div> </div> <div class="row mb-3"> <div class="col-lg-3"> <label for="nameInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.correctAnswer" | translate }}</label> </div> <div class="col-lg-9"> <p-multiSelect (onChange)="setCorrectAnswer(quizItem)" required #listClassCheckedvalid="ngModel" [options]="createMultiSelect(quizItem)" [(ngModel)]="quizItem.listAnswerCorrect" name="answerCorrectFlex" defaultLabel="{{ 'iqTest.iqQues.iqQuesDetail.selectCorrectAnswer' | translate }}" optionLabel="label" [style]="{'width':'100%'}"></p-multiSelect> </div> </div> </ng-container> <ng-container *ngIf="quizItem.quizItemType == '08-02'"> <div class="row mb-3"> <div class="col-lg-3"> <label for="meassageInput" class="form-label-inline">{{ "course0104.quiz.quizDetail.questionContent" | translate }}</label> </div> <div class="col-lg-9"> <textarea [(ngModel)]="quizItem.quizItemContent" name="quizItemContent" class="form-control" id="meassageInput" rows="3" placeholder="{{ 'course0104.quiz.quizDetail.enterQuestion' | translate }}"></textarea> </div> </div> </ng-container> <div class="modal-footer"> <button *ngIf="!quiz.cannotCRUD" (click)="removeQuestion(index)" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light rounded-pill"> <i class="bx bx-trash label-icon align-middle rounded-pill fs-16 ms-2"></i> {{ "button.delete.title" | translate }} </button> </div> <!-- </form> --> </div> </div> </div> </div> </ng-container> </div> <div class="row justify-content-center" *ngIf="listQuizItem.length >1"> <div class="col-xxl-9"> <div class="card"> <div class="card-body"> <div class="modal-footer"> <!-- <a *ngIf="!quiz.cannotCRUD" href="assets/file/templateQuiz.xls" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "course0104.quiz.quizDetail.downloadTemplate" | translate }} </a> <input #inputFile hidden type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onclick="this.value = null" (change)="importExcel($event)" /> <button (click)="exportPDF(quizId)" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "course0104.quiz.quizDetail.exportPDF" | translate }} </button> <button *ngIf="!quiz.cannotCRUD" (click)="inputFile.click()" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "course0104.quiz.quizDetail.importExcel" | translate }} </button> --> <button *ngIf="!quiz.cannotCRUD" type="button" class="btn btn-primary" (click)="onSave(myForm.invalid)"> {{ "sys3.userDetail.buttonSave" | translate }} </button> <button *ngIf="!quiz.cannotCRUD" (click)="addNewQuestion(0)" type="button" class="btn rounded-pill btn-primary btn-label waves-effect right waves-light"> <i class="ri-file-add-line label-icon align-middle fs-16 ms-2"></i> {{ "button.add.title" | translate }} </button> </div> </div> </div> </div> </div> </div> <!-- container-fluid --> </div> <p-confirmDialog> </p-confirmDialog>
#include <stdio.h> #include "function_pointers.h" /** * print_name - Prints a name using the given function * @name: Name to print * @f: Function pointer to the printing function * * Return: None */ void print_name(char *name, void (*f)(char *)) { if (name != NULL && f != NULL) f(name); }
import itertools import ipywidgets as widgets import matplotlib.pylab as plt import numpy as np from ipywidgets import GridspecLayout from src.lib.VizUtils import plot_solutions_together def visualize_intuition(sm, diffusion_contrast_lower, diffusion_contrast_upper, num_points_per_dim_to_plot=50, axes_xy_proportions=(3, 3)): grid = GridspecLayout(*sm.blocks_geometry) cells = list(itertools.product(*list(map(range, sm.blocks_geometry)))) coefs_sliders = dict() for i, j in cells: key = f"a{i}{j}" coefs_sliders[key] = widgets.FloatSlider(value=50, min=diffusion_contrast_lower, max=diffusion_contrast_upper, step=0.5, description=f'a[{i},{j}]:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f') grid[i, j] = coefs_sliders[key] def show_solution(**kwargs): diffusion_coefficients = np.array([list(kwargs.values())]).reshape((1,) + sm.blocks_geometry) solutions_intuition = sm.generate_solutions(diffusion_coefficients[:, ::-1]) plot_solutions_together( sm, diffusion_coefficients=diffusion_coefficients, solutions=solutions_intuition, num_points_per_dim_to_plot=num_points_per_dim_to_plot, contour_levels=7, axes_xy_proportions=axes_xy_proportions ) plt.show() out = widgets.interactive_output(show_solution, coefs_sliders) display(grid, out) def vizualize_approximations(sm, measurements_sampling_method_dict, reduced_basis_dict, state_estimation_method_dict, diffusion_contrast_lower, diffusion_contrast_upper, max_vn_dim, num_points_per_dim_to_plot=50, axes_xy_proportions=(3, 3)): def show_approx(n_dim, rb_methods, m, measurements_sampling_method, state_estimation_method, **kwargs): approximate_solutions = [] for rb_method in rb_methods: rb = reduced_basis_dict[rb_method][:n_dim] measurement_points = measurements_sampling_method_dict[measurements_sampling_method](m, sm.x_domain, sm.y_domain, basis=rb, sm=sm) diffusion_coefficients = np.array([list(kwargs.values())]).reshape((1,) + sm.blocks_geometry) solution = sm.generate_solutions(diffusion_coefficients[:, ::-1]) measurements_online = sm.evaluate_solutions(measurement_points, solutions=solution) approximate_solutions.append( state_estimation_method_dict[state_estimation_method](measurement_points, measurements_online, rb)) plot_solutions_together( sm, None, [solution] + approximate_solutions, num_points_per_dim_to_plot=num_points_per_dim_to_plot, contour_levels=7, axes_xy_proportions=axes_xy_proportions, titles=["True solution"] + list(rb_methods), colorbar=False, measurement_points=measurement_points) plt.show() style = {'description_width': 'initial'} global_grid = GridspecLayout(4, 2) available_widgets = dict() grid = GridspecLayout(*sm.blocks_geometry) cells = list(itertools.product(*list(map(range, sm.blocks_geometry)))) for i, j in cells: key = f"a{i}{j}" available_widgets[key] = widgets.FloatSlider( value=50, min=diffusion_contrast_lower, max=diffusion_contrast_upper, step=0.5, description=f'a[{i},{j}]:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', style=style) grid[i, j] = available_widgets[key] global_grid[0, :] = grid global_grid[1, 0] = available_widgets["rb_methods"] = widgets.SelectMultiple( options=list(reduced_basis_dict.keys()), value=list(reduced_basis_dict.keys()), description="Reduced Basis: ", disabled=False, style=style) global_grid[1, 1] = available_widgets["n_dim"] = widgets.IntSlider( value=1, min=1, max=50, step=1, description='RB dim n:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, style=style) global_grid[2, 0] = available_widgets["measurements_sampling_method"] = widgets.Dropdown( options=list(measurements_sampling_method_dict.keys()), description="Measurements sampling method: ", disabled=False, style=style) global_grid[2, 1] = available_widgets["m"] = widgets.IntSlider( value=50, min=max_vn_dim, max=10 * max_vn_dim, step=1, description='Number of measurements:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, style=style) global_grid[3, :] = available_widgets["state_estimation_method"] = widgets.Dropdown( options=list(state_estimation_method_dict.keys()), description="State estimation method: ", disabled=False, style=style) out = widgets.interactive_output(show_approx, available_widgets) display(global_grid, out) error_metrics_dict = { "L2": lambda x: np.mean(np.sqrt(np.mean(x ** 2, axis=-1))), "Linf": lambda x: np.max(np.sqrt(np.mean(x ** 2, axis=-1))) } def visualize_convergence(sm, solutions, measurements_sampling_method_dict, reduced_basis_dict, state_estimation_method_dict, max_vn_dim): # n_per_dim = int(refinement*np.sqrt(sm.vspace_dim)) # x, y = np.meshgrid(*[np.linspace(*sm.y_domain, num=n_per_dim), np.linspace(*sm.x_domain, num=n_per_dim)]) # quadrature_points = np.concatenate([x.reshape((-1, 1)), y.reshape((-1, 1))], axis=1) def show_convergence(rb_methods, measurements_sampling_method, m, state_estimation_method, error_metric, noise): for rb_method in rb_methods: errors = [] for n in range(1, max_vn_dim): basis = reduced_basis_dict[rb_method][:n] if measurements_sampling_method == "Optim" or len(errors) == 0: measurement_points = measurements_sampling_method_dict[measurements_sampling_method](m, sm.x_domain, sm.y_domain, basis=basis, sm=sm) measurements = sm.evaluate_solutions(measurement_points, solutions) + np.random.normal(scale=noise) v = solutions - \ state_estimation_method_dict[state_estimation_method]( measurement_points, measurements, np.reshape(basis, (n, -1))) errors.append(error_metrics_dict[error_metric](v)) # errors.append(error_metrics_dict[error_metric](sm.evaluate_solutions(points=quadrature_points, solutions=v))) plt.plot(np.arange(1, max_vn_dim, dtype=int), errors, ".-", label=rb_method) plt.xticks(np.arange(1, max_vn_dim, dtype=int)) plt.yscale("log") plt.grid() plt.legend() plt.show() style = {'description_width': 'initial'} global_grid = GridspecLayout(4, 2) available_widgets = dict() global_grid[0, 0] = available_widgets["error_metric"] = widgets.Dropdown( options=list(error_metrics_dict.keys()), description="Error metric: ", disabled=False, style=style) global_grid[0, 1] = available_widgets["noise"] = widgets.FloatSlider( value=0, min=0, max=1, step=0.01, description="Noise: ", disabled=False, style=style) global_grid[1, :] = available_widgets["rb_methods"] = widgets.SelectMultiple( options=list(reduced_basis_dict.keys()), value=list(reduced_basis_dict.keys()), description="Reduced Basis: ", disabled=False, style=style) global_grid[2, 0] = available_widgets["measurements_sampling_method"] = widgets.Dropdown( options=list(measurements_sampling_method_dict.keys()), description="Measurements sampling method: ", disabled=False, style=style) global_grid[2, 1] = available_widgets["m"] = widgets.IntSlider( value=50, min=max_vn_dim, max=10 * max_vn_dim, step=1, description='Number of measurements:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, style=style) global_grid[3, :] = available_widgets["state_estimation_method"] = widgets.Dropdown( options=list(state_estimation_method_dict.keys()), description="State estimation method: ", disabled=False, style=style) out = widgets.interactive_output(show_convergence, available_widgets) display(global_grid, out) def visualize_state_estimation_methods(sm, solutions, measurements_sampling_method_dict, reduced_basis_dict, state_estimation_method_dict, max_vn_dim): def show_semethod(rb_method, measurements_sampling_method, m, state_estimation_methods, error_metric, noise, vn_range): # measurement_points = measurements_sampling_method_dict[measurements_sampling_method](m, sm.x_domain, # sm.y_domain) # measurements = sm.evaluate_solutions(measurement_points, solutions) + np.random.normal(scale=noise) for state_estimation_method in state_estimation_methods: errors = [] for n in range(*vn_range): basis = reduced_basis_dict[rb_method][:n] if measurements_sampling_method == "Optim" or len(errors) == 0: measurement_points = measurements_sampling_method_dict[measurements_sampling_method](m, sm.x_domain, sm.y_domain, basis=basis, sm=sm) measurements = sm.evaluate_solutions(measurement_points, solutions) + np.random.normal(scale=noise) v = solutions - \ state_estimation_method_dict[state_estimation_method]( measurement_points, measurements, np.reshape(basis, (n, -1))) errors.append(error_metrics_dict[error_metric](v)) # errors = [error_metrics_dict[error_metric]( # solutions - state_estimation_method_dict[state_estimation_method](measurement_points, measurements, # np.reshape( # reduced_basis_dict[rb_method][:n], # (n, -1))) # ) for n in range(*vn_range)] plt.plot(np.arange(*vn_range), errors, ".-", label=state_estimation_method) plt.xticks(np.arange(*vn_range, dtype=int)) plt.grid() plt.yscale("log") plt.ylim((None, 1e-1)) plt.legend() plt.show() style = {'description_width': 'initial'} global_grid = GridspecLayout(4, 2) available_widgets = dict() global_grid[0, 0] = available_widgets["error_metric"] = widgets.Dropdown( options=list(error_metrics_dict.keys()), description="Error metric: ", disabled=False, style=style) global_grid[0, 1] = available_widgets["noise"] = widgets.FloatText( value=0, min=0, max=1, # step=0.01, description="Noise: ", disabled=False, style=style) global_grid[1, :] = available_widgets["rb_method"] = widgets.Dropdown( options=list(reduced_basis_dict.keys()), value=list(reduced_basis_dict.keys())[0], description="Reduced Basis: ", disabled=False, style=style) global_grid[2, 0] = available_widgets["measurements_sampling_method"] = widgets.Dropdown( options=list(measurements_sampling_method_dict.keys()), # value=list(measurements_sampling_method_dict.keys()), description="Measurements sampling method: ", disabled=False, style=style) global_grid[2, 1] = available_widgets["m"] = widgets.IntText( value=50, min=max_vn_dim, # max=10 * max_vn_dim, # step=1, description='Number of measurements:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, style=style) global_grid[3, 0] = available_widgets["state_estimation_methods"] = widgets.SelectMultiple( options=list(state_estimation_method_dict.keys()), value=list(state_estimation_method_dict.keys()), description="State estimation method: ", disabled=False, style=style) global_grid[3, 1] = available_widgets["vn_range"] = widgets.IntRangeSlider( min=0, max=max_vn_dim, value=(1, max_vn_dim), step=1, description="dim(Vn) range: ", disabled=False, style=style) out = widgets.interactive_output(show_semethod, available_widgets) display(global_grid, out) def visualize_samplers(sm, solutions, measurements_sampling_method_dict, reduced_basis_dict, state_estimation_method_dict, max_vn_dim): def show_smethod(rb_method, measurements_sampling_methods, m, state_estimation_method, error_metric, noise, vn_range): for measurements_sampling_method in measurements_sampling_methods: errors = [] for n in range(*vn_range): basis = reduced_basis_dict[rb_method][:n] if measurements_sampling_method == "Optim" or len(errors) == 0: measurement_points = measurements_sampling_method_dict[measurements_sampling_method](m, sm.x_domain, sm.y_domain, basis=basis, sm=sm) measurements = sm.evaluate_solutions(measurement_points, solutions) + np.random.normal(scale=noise) v = solutions - \ state_estimation_method_dict[state_estimation_method]( measurement_points, measurements, np.reshape(basis, (n, -1))) errors.append(error_metrics_dict[error_metric](v)) plt.plot(np.arange(*vn_range), errors, ".-", label=measurements_sampling_method) plt.xticks(np.arange(*vn_range, dtype=int)) plt.grid() plt.yscale("log") plt.ylim((None, 1e-1)) plt.legend() plt.show() style = {'description_width': 'initial'} global_grid = GridspecLayout(4, 2) available_widgets = dict() global_grid[0, 0] = available_widgets["error_metric"] = widgets.Dropdown( options=list(error_metrics_dict.keys()), description="Error metric: ", disabled=False, style=style) global_grid[0, 1] = available_widgets["noise"] = widgets.FloatText( value=0, min=0, max=1, # step=0.01, description="Noise: ", disabled=False, style=style) global_grid[1, :] = available_widgets["rb_method"] = widgets.Dropdown( options=list(reduced_basis_dict.keys()), value=list(reduced_basis_dict.keys())[0], description="Reduced Basis: ", disabled=False, style=style) global_grid[2, 0] = available_widgets["measurements_sampling_methods"] = widgets.SelectMultiple( options=list(measurements_sampling_method_dict.keys()), value=list(measurements_sampling_method_dict.keys()), description="Measurements sampling method: ", disabled=False, style=style) global_grid[2, 1] = available_widgets["m"] = widgets.IntText( value=50, min=max_vn_dim, # max=10 * max_vn_dim, # step=1, description='Number of measurements:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, style=style) global_grid[3, 0] = available_widgets["state_estimation_method"] = widgets.Dropdown( options=list(state_estimation_method_dict.keys()), # value=list(state_estimation_method_dict.keys()), description="State estimation method: ", disabled=False, style=style) global_grid[3, 1] = available_widgets["vn_range"] = widgets.IntRangeSlider( min=0, max=max_vn_dim, value=(1, max_vn_dim), step=1, description="dim(Vn) range: ", disabled=False, style=style) out = widgets.interactive_output(show_smethod, available_widgets) display(global_grid, out) def visualize_all(sm, solutions, measurements_sampling_method_dict, reduced_basis_dict, state_estimation_method_dict, max_vn_dim): def show(rb_method, measurements_sampling_method, m, state_estimation_methods, error_metric, noise, vn_range): measurement_points = measurements_sampling_method_dict[measurements_sampling_method](m, sm.x_domain, sm.y_domain) measurements = sm.evaluate_solutions(measurement_points, solutions) + np.random.normal(scale=noise) for state_estimation_method in state_estimation_methods: errors = [error_metrics_dict[error_metric]( solutions - state_estimation_method_dict[state_estimation_method](measurement_points, measurements, np.reshape( reduced_basis_dict[rb_method][:n], (n, -1))) ) for n in range(*vn_range)] plt.plot(np.arange(*vn_range), errors, ".-", label=state_estimation_method) plt.xticks(np.arange(*vn_range, dtype=int)) plt.grid() plt.yscale("log") plt.ylim((None, 1e-1)) plt.legend() plt.show() style = {'description_width': 'initial'} global_grid = GridspecLayout(4, 2) available_widgets = dict() global_grid[0, 0] = available_widgets["error_metric"] = widgets.Dropdown( options=list(error_metrics_dict.keys()), description="Error metric: ", disabled=False, style=style) global_grid[0, 1] = available_widgets["noise"] = widgets.FloatText( value=0, min=0, max=1, # step=0.01, description="Noise: ", disabled=False, style=style) global_grid[1, :] = available_widgets["rb_method"] = widgets.Dropdown( options=list(reduced_basis_dict.keys()), value=list(reduced_basis_dict.keys())[0], description="Reduced Basis: ", disabled=False, style=style) global_grid[2, 0] = available_widgets["measurements_sampling_method"] = widgets.Dropdown( options=list(measurements_sampling_method_dict.keys()), # value=list(measurements_sampling_method_dict.keys()), description="Measurements sampling method: ", disabled=False, style=style) global_grid[2, 1] = available_widgets["m"] = widgets.IntText( value=50, min=max_vn_dim, # max=10 * max_vn_dim, # step=1, description='Number of measurements:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, style=style) global_grid[3, 0] = available_widgets["state_estimation_methods"] = widgets.SelectMultiple( options=list(state_estimation_method_dict.keys()), value=list(state_estimation_method_dict.keys()), description="State estimation method: ", disabled=False, style=style) global_grid[3, 1] = available_widgets["vn_range"] = widgets.IntRangeSlider( min=0, max=max_vn_dim, value=(1, max_vn_dim), step=1, description="dim(Vn) range: ", disabled=False, style=style) out = widgets.interactive_output(show_semethod, available_widgets) display(global_grid, out)
/* V0.3 */ /* Mixins for standard functions Array, Math, Sting... */ import "./mixins.js" /* Chance RNG */ import "../lib/chance.slim.js" const chance = new Chance() /* Storage - localforage https://localforage.github.io/localForage/ */ import "../lib/localforage.min.js" const DB = {} DB.games = localforage.createInstance({ name: "Outlands.Games" }); DB.state = localforage.createInstance({ name: "Outlands.State" }); /* SVG https://svgjs.dev/docs/3.0/getting-started/ */ /* UI Resources */ //Preact import {h, Component, render} from 'https://unpkg.com/preact?module'; import htm from 'https://unpkg.com/htm?module'; // Initialize htm with Preact const html = _.html = htm.bind(h); /* App Sub UI */ import*as UI from './UI.js'; import {Functions} from './functions.js'; import {Planes} from './setting.js'; import * as Scenarios from '../scenarios/index.js'; import*as Gen from './generate.js'; /* Game Object */ let Game = { "id": "", "name": "", "fame" : {}, //items bought "bought" : {}, /* knowledge of Regions and sites key = region id value = { siteId : # knowledge } An empty Region means the party knows of it - useful for travel A site with knowledge means that it is known */ "knowledge" : new Map(), //ways between varions regions : [regionId, regionId] "ways" : new Set(), //store for ids - quests, parties, characters, and created regions "toSave": new Set(), //log for information "log": [], //what is active "active" : { time : 1 } } let GameState = {} /* Declare the main App */ class App extends Component { constructor() { super(); this.state = { show: "AllPlanes", reveal: [], dialog: "", iframe: null, saveName: "", savedGames: new Set(), generated: [], toGenerate: "", tick : 0, }; //functions this.functions = Functions //Scenarios this.scenarios = Scenarios //keep generator functions this.gen = Gen //keep poi this.poi = Gen.POI //global store for generated areas / factions this.activeState = {} } // Lifecycle: Called whenever our component is created async componentDidMount() { let id = await DB.games.getItem("lastGame") if(id) { this.load(id) } else { id = Game.id = chance.natural() this.generate(id) Gen.Scene.enter(this,"") //Gen.Scene.enter(this,"Intro.Begin") } //updated saved game list let sG = this.state.savedGames DB.games.iterate((g,id)=>{ id != "lastGame" ? sG.add([g.name, id]) : null } ) setInterval(()=> { this.updateState("tick",this.state.tick+1) if(this.activeRegion && this.state.tick%3 == 0){ this.activeRegion.display() } }, 1000) } // Lifecycle: Called just before our component will be destroyed componentWillUnmount() {} /* Core Save Load and Generate */ generate(id=chance.hash()) { //reset GameState = {} this.activeState = {} let RNG = new Chance(id) //core region maker for planes Object.keys(Planes).forEach(p=> { let n = RNG.sumDice("2d3+1") _.fromN(n,()=>{ new Gen.Region(this,{ id : RNG.hash(), plane : p }) }) }) //update game Game.id = id let _animals = [Gen.Encounter({what:"Animal"}),Gen.Encounter({what:"Animal"})] let name = [RNG.randBetween(1,1000),_animals[0].essence[1],_animals[0].tags[1],_animals[1].tags[1]] Game.name = name.join(" ") console.log(this.activeState, this.game) this.refresh() } save() { //first save to game DB.games.setItem("lastGame",Game.id) DB.games.setItem(Game.id, Game) //now save individual state Game.toSave.forEach(id => DB.state.setItem(id,GameState[id])) //refresh this.refresh() } async load(id) { //pull game let game = await DB.games.getItem(id) if (!game) { return } //first generate this.generate(id) //write state let sets = ["toSave","ways"] Object.keys(Game).forEach(k=> Game[k] = sets.includes(k) ? new Set(game[k]) : game[k]) //load saved let nl = 0 await Game.toSave.forEach(async id => { GameState[id] = await DB.state.getItem(id) this.activeState[id] = new Gen[GameState[id].w](this,GameState[id]) await this.refresh() nl++ //go to scene after load nl == Game.toSave.size ? game.active.scene == "freeplay" ? null : Gen.Scene.enter(this,game.active.scene,null) : null }) } /* Game Functions */ act(f, opts) { //call the function f(opts) //save //refresh this.refresh() } /* Get functions */ get game() { return Object.assign({state:GameState},Game) } get planes() { return Object.values(Planes).map(p => { p.children = this.regions.filter(r => r.plane == p.name) p.parties = p.children.map(r=> r.parties).flat() return p }) } get regions() { return Object.values(this.activeState).filter(p=>p.what == "Region") } get parties () { return Object.values(this.activeState).filter(p=>p.what == "Party") } get quests() { return Object.values(this.activeState).filter(p=>p.what == "Quest") } get activeParty() { return this.activeState[Game.active.party] } get activeRegion() { let [w,id] = this.state.show.split(".") return w== "Plane" ? this.regions.find(r=> r.id==id) : null } /* Render functions */ //main function for updating state async updateState(what, val) { let s = {} s[what] = val await this.setState(s) //check for view if(what == "show" && val.includes("Plane") && this.activeRegion){ this.activeRegion.display() } } //main functions for setting view - usine set/get of show refresh() { this.show = this.state.show } set show(what) { this.updateState("show", what) } get show() { let[what,id] = this.state.show.split(".") return UI[what] ? UI[what](this) : this[what][id].UI ? this[what][id].UI() : "" } set dialog(what) { this.updateState("dialog", what) } get dialog() { let[what,id] = this.state.dialog.split(".") return what == "" ? "" : UI.Dialog(this) } /* Render */ //main page render render(props, {show, savedGames}) { let view = show.split(".")[0] let rids = this.regions.map(r=>r.id) //final layout return html` <div class="fixed left-0 pa2 z-2"> <h1 class="pointer underline-hover ma0" onClick=${()=>this.show = "AllPlanes"}>Outlands</h1> </div> <div class="fixed right-0 pa2 z-2"> <div class="flex items-center"> <div class="f5 b i mh2">${Game.name}</div> <div class="dropdown rtl"> <div class="f4 b pointer link dim bg-light-gray br2 pa2">⚙</div> <div class="f4 rtl w-100 dropdown-content bg-white-70 db ba bw1 pa1"> <div class="tc link pointer dim underline-hover hover-orange pa1" onClick=${()=>this.save()}>Save</div> <div class="tc link pointer dim underline-hover hover-orange pa1" onClick=${()=>this.generate()}>Generate New</div> ${[...savedGames].map(sg=> sg[1] == Game.id ? "" : html`<div class="tc link pointer dim underline-hover hover-orange pa1" onClick=${()=>this.load(sg[1])}>Load ${sg[0]}</div>`)} </div> </div> </div> <div>${this.parties.map(p=> html`<div class="pointer dim bg-lightest-blue mv1 pa1" onClick=${()=>this.show = ["Plane", p.region.id].join(".")}>${p.characters.map(c=>c.name).join(", ")}</div>`)}</div> <div>${[...this.quests].map(q=> q.state.done ? "" : html`<div class="pointer dim bg-light-yellow mv1 pa1">${q.text}</div>`)}</div> </div> <div class="absolute z-1 w-100 mt5 pa2"> ${this.show} </div> ${this.dialog} ` } } render(html`<${App}/>`, document.getElementById("app"));
import { Entity, BaseEntity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, OneToMany } from 'typeorm'; import {User} from './user' import {Comment} from './comment' @Entity({ name: 'articles' }) export class Article extends BaseEntity { @PrimaryGeneratedColumn() readonly id!: number @Column() title!: string @Column() content!: string @Column() views!: number @Column() create_time!: Date @Column() update_time!: Date @Column() is_delete!: number @ManyToOne(() => User) @JoinColumn({name: 'user_id'}) user!: User @OneToMany(() => Comment, (comment) => comment.article) comments!: Comment[] }
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:io'; class AdaptativeButton extends StatelessWidget { final String label; final Function() onPressed; const AdaptativeButton( this.label, this.onPressed, { Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Platform.isIOS ? CupertinoButton( onPressed: onPressed(), color: Theme.of(context).primaryColor, padding: const EdgeInsets.symmetric(horizontal: 20), child: Text(label), ) : ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).primaryColor, foregroundColor: Theme.of(context).textTheme.labelLarge?.color, ), onPressed: onPressed(), child: Text(label), ); } }
<?php /** * Blog-layout template. * * @author ThemeFusion * @copyright (c) Copyright by ThemeFusion * @link http://theme-fusion.com * @package Avada * @subpackage Core * @since 1.0.0 */ // Do not allow directly accessing this file. if ( ! defined( 'ABSPATH' ) ) { exit( 'Direct script access denied.' ); } global $wp_query; // Set the correct post container layout classes. $blog_layout_custom = 'grid'; $blog_layout = avada_get_blog_layout(); $pagination_type = Avada()->settings->get( 'blog_pagination_type' ); $post_class = 'fusion-post-' . $blog_layout; // Masonry needs additional grid class. if ( 'masonry' === $blog_layout ) { $post_class .= ' fusion-post-grid'; } $container_class = 'fusion-posts-container '; $wrapper_class = 'fusion-blog-layout-' . $blog_layout . '-wrapper '; if ( 'grid' === $blog_layout || 'masonry' === $blog_layout ) { $container_class .= 'fusion-blog-layout-grid fusion-blog-layout-grid-' . Avada()->settings->get( 'blog_archive_grid_columns' ) . ' isotope '; if ( 'masonry' === $blog_layout ) { $container_class .= 'fusion-blog-layout-' . $blog_layout . ' '; } } else if ( 'timeline' !== $blog_layout ) { $container_class .= 'fusion-blog-layout-' . $blog_layout . ' '; } if ( ! Avada()->settings->get( 'post_meta' ) || ( ! Avada()->settings->get( 'post_meta_author' ) && ! Avada()->settings->get( 'post_meta_date' ) && ! Avada()->settings->get( 'post_meta_cats' ) && ! Avada()->settings->get( 'post_meta_tags' ) && ! Avada()->settings->get( 'post_meta_comments' ) && ! Avada()->settings->get( 'post_meta_read' ) ) ) { $container_class .= 'fusion-no-meta-info '; } if ( Avada()->settings->get( 'blog_equal_heights' ) && 'grid' === $blog_layout ) { $container_class .= 'fusion-blog-equal-heights '; } // Set class for scrolling type. if ( 'Infinite Scroll' === $pagination_type ) { $container_class .= 'fusion-posts-container-infinite '; $wrapper_class .= 'fusion-blog-infinite '; } else if ( 'load_more_button' === $pagination_type ) { $container_class .= 'fusion-posts-container-infinite fusion-posts-container-load-more '; } else { $container_class .= 'fusion-blog-pagination '; } if ( ! Avada()->settings->get( 'featured_images' ) ) { $container_class .= 'fusion-blog-no-images '; } // Add class if rollover is enabled. if ( Avada()->settings->get( 'image_rollover' ) && Avada()->settings->get( 'featured_images' ) ) { $container_class .= ' fusion-blog-rollover'; } $content_align = Avada()->settings->get( 'blog_layout_alignment' ); if ( $content_align && ( 'grid' === $blog_layout || 'masonry' === $blog_layout || 'timeline' === $blog_layout ) ) { $container_class .= ' fusion-blog-layout-' . $content_align; } $number_of_pages = $wp_query->max_num_pages; if ( is_search() && Avada()->settings->get( 'search_results_per_page' ) ) { $number_of_pages = ceil( $wp_query->found_posts / Avada()->settings->get( 'search_results_per_page' ) ); } ?> <div id="posts-container" class="fusion-blog-archive <?php echo esc_attr( $wrapper_class ); ?>fusion-clearfix"> <div class="all-wraper"> <h4 class="core-blog-title">Blog</h4> </div> <div class="<?php echo esc_attr( $container_class ); ?>" data-pages="<?php echo (int) $number_of_pages; ?>"> <?php if ( 'timeline' === $blog_layout ) : ?> <?php // Add the timeline icon. ?> <div class="fusion-timeline-icon"><i class="fusion-icon-bubbles"></i></div> <div class="fusion-blog-layout-timeline fusion-clearfix"> <?php // Initialize the time stamps for timeline month/year check. $post_count = 1; $prev_post_timestamp = null; $prev_post_month = null; $prev_post_year = null; $first_timeline_loop = false; ?> <?php // Add the container that holds the actual timeline line. ?> <div class="fusion-timeline-line"></div> <?php endif; ?> <?php if ( 'masonry' === $blog_layout ) : ?> <article class="fusion-post-grid fusion-post-masonry post fusion-grid-sizer"></article> <?php endif; ?> <?php // Start the main loop. $argsQuery = array( 'post_type' => 'blog', // only query post type 'tax_query' => array( array( 'taxonomy' => 'qcore', 'field' => 'slug', 'terms' => 'our-values', 'operator' => 'NOT IN') // seems that's what you're missing ), ); $custom_query = new WP_Query( $argsQuery ); ?> <?php while ( $custom_query->have_posts() ) : ?> <?php $custom_query->the_post(); ?> <?php //$thumbnail_img_url = get_the_post_thumbnail_url(get_the_ID(),'thumbnail'); $thumbnail_img_url = get_the_post_thumbnail_url(get_the_ID(),'medium'); $permalink_url = get_permalink( $post->ID ); // Set the time stamps for timeline month/year check. $alignment_class = ''; if ( 'timeline' === $blog_layout ) { $post_timestamp = get_the_time( 'U' ); $post_month = date( 'n', $post_timestamp ); $post_year = get_the_date( 'Y' ); $current_date = get_the_date( 'Y-n' ); // Set the correct column class for every post. if ( $post_count % 2 ) { $alignment_class = 'fusion-left-column'; } else { $alignment_class = 'fusion-right-column'; } // Set the timeline month label. if ( $prev_post_month != $post_month || $prev_post_year != $post_year ) { if ( $post_count > 1 ) { echo '</div>'; } echo '<h3 class="fusion-timeline-date">' . get_the_date( Avada()->settings->get( 'timeline_date_format' ) ) . '</h3>'; echo '<div class="fusion-collapse-month">'; } } // Set the has-post-thumbnail if a video is used. This is needed if no featured image is present. $thumb_class = ''; if ( get_post_meta( get_the_ID(), 'pyre_video', true ) ) { $thumb_class = ' has-post-thumbnail'; } // Masonry layout, get the element orientation class. $element_orientation_class = ''; if ( 'masonry' === $blog_layout ) { $masonry_cloumns = Avada()->settings->get( 'blog_archive_grid_columns' ); $masonry_columns_spacing = Avada()->settings->get( 'blog_archive_grid_column_spacing' ); $responsive_images_columns = $masonry_cloumns; $masonry_attributes = array(); $element_base_padding = 0.8; // Set image or placeholder and correct corresponding styling. if ( has_post_thumbnail() ) { $post_thumbnail_attachment = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' ); $masonry_attribute_style = 'background-image:url(' . $post_thumbnail_attachment[0] . ');'; } else { $post_thumbnail_attachment = array(); $masonry_attribute_style = 'background-color:#f6f6f6;'; } // Get the correct image orientation class. $element_orientation_class = Avada()->images->get_element_orientation_class( get_post_thumbnail_id() ); $element_base_padding = Avada()->images->get_element_base_padding( $element_orientation_class ); $masonry_column_offset = ' - ' . ( (int) $masonry_columns_spacing / 2 ) . 'px'; if ( false !== strpos( $element_orientation_class, 'fusion-element-portrait' ) ) { $masonry_column_offset = ''; } $masonry_column_spacing = ( (int) $masonry_columns_spacing ) . 'px'; if ( class_exists( 'Fusion_Sanitize' ) && class_exists( 'Fusion_Color' ) && 'transparent' !== Fusion_Sanitize::color( Avada()->settings->get( 'timeline_color' ) ) && '0' != Fusion_Color::new_color( Avada()->settings->get( 'timeline_color' ) )->alpha ) { $masonry_column_offset = ' - ' . ( (int) $masonry_columns_spacing / 2 ) . 'px'; if ( false !== strpos( $element_orientation_class, 'fusion-element-portrait' ) ) { $masonry_column_offset = ' + 4px'; } $masonry_column_spacing = ( (int) $masonry_columns_spacing - 2 ) . 'px'; if ( false !== strpos( $element_orientation_class, 'fusion-element-landscape' ) ) { $masonry_column_spacing = ( (int) $masonry_columns_spacing - 6 ) . 'px'; } } // Check if a featured image is set and also that not a video with no featured image. $post_video = get_post_meta( get_the_ID(), 'pyre_video', true ); if ( ! empty( $post_thumbnail_attachment ) || ! $post_video ) { // Calculate the correct size of the image wrapper container, based on orientation and column spacing. $masonry_attribute_style .= 'padding-top:calc((100% + ' . $masonry_column_spacing . ') * ' . $element_base_padding . $masonry_column_offset . ');'; } // Check if we have a landscape image, then it has to stretch over 2 cols. if ( false !== strpos( $element_orientation_class, 'fusion-element-landscape' ) ) { $responsive_images_columns = $masonry_cloumns / 2; } // Set the masonry attributes to use them in the first featured image function. $masonry_attributes = array( 'class' => 'fusion-masonry-element-container', 'style' => $masonry_attribute_style, ); // Get the post image. Avada()->images->set_grid_image_meta( array( 'layout' => 'portfolio_full', 'columns' => $responsive_images_columns, 'gutter_width' => $masonry_columns_spacing, ) ); $permalink = get_permalink( $post->ID ); $image = fusion_render_first_featured_image_markup( $post->ID, 'full', $permalink, false, false, false, 'default', 'default', '', '', 'yes', false, $masonry_attributes ); Avada()->images->set_grid_image_meta( array() ); } // End if(). $post_classes = array( $post_class, $alignment_class, $thumb_class, $element_orientation_class, 'post', 'fusion-clearfix', ); ?> <article id="post-<?php the_ID(); ?>" <?php post_class( $post_classes ); ?>> <?php if ( 'grid' === $blog_layout_custom ) : ?> <?php // Add an additional wrapper for grid layout border. ?> <div class="fusion-post-wrapper archieve-page-div"> <ul style="padding: 0;"> <li style="background-image: url('<?php echo $thumbnail_img_url; ?>')"> </li> <div class="text"> <a href="<?php echo $permalink_url; ?>"> <h4><?php the_title();?></h4> </a> <?php if(has_excerpt()) { ?> <p><?php echo get_the_excerpt(); ?></p> <?php }else{ ?> <p> <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 95, '...'); ?> </p> <?php } ?> </div> </ul> </ul> <?php endif; ?> </article> <?php // Adjust the timestamp settings for next loop. if ( 'timeline' === $blog_layout ) { $prev_post_timestamp = $post_timestamp; $prev_post_month = $post_month; $prev_post_year = $post_year; $post_count++; } ?> <?php endwhile; ?> <?php if ( 'timeline' === $blog_layout && 1 < $post_count ) : ?> </div> <?php endif; ?> </div> <?php // If infinite scroll with "load more" button is used. ?> <?php if ( 'load_more_button' === $pagination_type && 1 < $number_of_pages ) : ?> <div class="fusion-load-more-button fusion-blog-button fusion-clearfix"> <?php echo esc_textarea( apply_filters( 'avada_load_more_posts_name', esc_attr__( 'Load More Posts', 'Avada' ) ) ); ?> </div> <?php endif; ?> <?php if ( 'timeline' === $blog_layout ) : ?> </div> <?php endif; ?> <?php // Get the pagination. ?> <?php echo fusion_pagination( '', apply_filters( 'fusion_pagination_size', 1 ) ); // WPCS: XSS ok. ?> </div> <?php wp_reset_postdata(); /* Omit closing PHP tag to avoid "Headers already sent" issues. */
import { Tab, TableCell, Typography } from "@mui/material"; import React, { useEffect, useState } from "react"; const TimerCell = ({ startTime }) => { const [timeRemaining, setTimeRemaining] = useState(calculateTimeRemaining()); function calculateTimeRemaining() { const now = new Date(); const start = new Date(startTime); const timeDiff = start - now; if (timeDiff <= 0) { return { hours: 0, minutes: 0, seconds: 0 }; } const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24)); const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000); return { days, hours, minutes, seconds }; } useEffect(() => { const timerInterval = setInterval(() => { const remainingTime = calculateTimeRemaining(); setTimeRemaining(remainingTime); if (remainingTime.days === 0 && remainingTime.hours === 0 && remainingTime.minutes === 0 && remainingTime.seconds === 0) { window.location.reload(); } }, 1000); return () => { clearInterval(timerInterval); }; }, [startTime]); return ( <TableCell> <Typography> {timeRemaining.days !== 0 ? `${timeRemaining.days}days` : `${timeRemaining.hours}h ${timeRemaining.minutes}m ${timeRemaining.seconds}s` } </Typography> </TableCell> ); }; export default TimerCell;
package routes import ( rblx "rblx/api" "rblx/database" "rblx/structs" "strconv" "time" "github.com/labstack/echo/v4" ) var ( ValidSizes = []int16{30, 48, 60, 75, 100, 110, 140, 150, 352, 420, 720} ) var ( InMemoryCache = true; // If this is set to true the images will be stored in memory. ) func PrimaryRoute(av *structs.Storage, hs *structs.Storage) echo.HandlerFunc { return func(c echo.Context) error { return c.JSON(200, structs.Response{ Success: true, Message: "Welcome - Roblox Cache Server By github.com/jub0t/RoCDN", Data: structs.DatabaseInfo{ Avatars: len(av.Data), Headshots: len(hs.Data), }, }) } } func NotFound(c echo.Context) error { return c.Redirect(302, `https://github.com/jub0t/RoCDN`) } func Headshot(db *structs.Storage) echo.HandlerFunc { return func(c echo.Context) error { user_id, err := strconv.ParseInt(c.Param("userId"), 0, 64) if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "Unable to parse user_id", }) } size, err := strconv.ParseInt(c.QueryParam("size"), 0, 64) if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "Invalid size", }) } image := database.Get(db, int(user_id), int(size)) if image.TargetId > 0 { if (InMemoryCache) { c.Response().Header().Set("Content-Type", "image/png") c.Response().Header().Set("Content-Length", strconv.Itoa(len(image.Data))) c.Response().Header().Set("Cache-Control", "max-age=31536000") // Cache for 1 year c.Response().Write(image.Data) c.Response().Flush() return nil; } else { return c.Redirect(302, image.ImageUrl) } } else { r_image, err := rblx.GetHeadshot(int(user_id), int(size), "png", false) if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "User not found", }) } image_data, err := rblx.GetImageDataFromURL(r_image.ImageUrl); if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "Image data could not be retreived", }) } database.Insert(db, structs.Image{ Data: image_data, Size: int(size), TargetId: r_image.TargetId, ImageUrl: r_image.ImageUrl, Timestamp: time.Now().UnixMilli() + time.Hour.Milliseconds()*6, }) if len(r_image.ImageUrl) > 0 { c.Response().Header().Set("Content-Type", "image/png") c.Response().Header().Set("Content-Length", strconv.Itoa(len(image_data))) c.Response().Header().Set("Cache-Control", "max-age=31536000") // Cache for 1 year c.Response().Write(image.Data) c.Response().Flush() return nil; } else { return c.JSON(400, structs.Response{ Success: true, Message: "ImageURL Is Not Valid", }) } } } } func Avatar(db *structs.Storage) echo.HandlerFunc { return func(c echo.Context) error { user_id, err := strconv.ParseInt(c.Param("userId"), 0, 64) if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "Unable to parse user_id", }) } size, err := strconv.ParseInt(c.QueryParam("size"), 0, 64) if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "Invalid size", }) } image := database.Get(db, int(user_id), int(size)) if image.TargetId > 0 { return c.Redirect(302, image.ImageUrl) } else { r_image, err := rblx.GetAvatar(int(user_id), int(size), "png", false) if err != nil { return c.JSON(400, structs.Response{ Success: true, Message: "User not found", }) } database.Insert(db, structs.Image{ Size: int(size), TargetId: r_image.TargetId, ImageUrl: r_image.ImageUrl, Timestamp: time.Now().UnixMilli() + time.Hour.Milliseconds()*6, }) if len(r_image.ImageUrl) > 0 { return c.Redirect(302, r_image.ImageUrl) } else { return c.JSON(400, structs.Response{ Success: true, Message: "ImageURL Is Not Valid", }) } } } }
#ifndef STEP_WRITER_ROW_H #define STEP_WRITER_ROW_H #include <cstdint> #include <string> #include <utility> #include <vector> #include "ftxui/component/component.hpp" enum class highlight_type { Keyword, Operator, Identifier, Number, String, Comment, Unknown }; struct highlight_item { std::pair<uint32_t, uint32_t> h_idx; highlight_type h_type; }; class Row { public: Row(std::string s); Row(); std::string getText(); int getLen(); void insertText(int idx, char c); void removeString(int idx); void deleteChar(int idx); void appendRow(Row r); ftxui::Element Render(); void add_highlight_item(highlight_item item); void clear_highlights(); std::vector<highlight_item> getHighlights(); private: std::string text; int len; std::vector<highlight_item> highlight_items; }; #endif //STEP_WRITER_ROW_H
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entities.DataTransferObjects { public abstract record BookDtoForManipulation { [Required(ErrorMessage ="Title is a required field.")] [MinLength(2,ErrorMessage ="Title must consist of at least 2 characters")] [MaxLength(50,ErrorMessage ="Title must consist of at maximum 50 characters")] public string Title { get; init; } [Required] [Range(10,1000)] public decimal Price { get; init; } } }
#include <algorithm> #include <iostream> #include <bits/stdc++.h> using namespace std; struct Segment { int start, end; }; bool compare(Segment &a, Segment &b) { return a.end < b.end; } vector<int> optimal_points(vector<Segment> &segments) { sort(segments.begin(), segments.end(), compare); vector<int> points; int point = segments[0].end; points.push_back(point); for (int i = 1; i < segments.size(); ++i) { if (point < segments[i].start || point > segments[i].end) { point = segments[i].end; points.push_back(point); } } return points; } int main() { unsigned int n; cin >> n; vector<Segment> segments(n); for (size_t i = 0; i < segments.size(); ++i) { cin >> segments[i].start >> segments[i].end; } vector<int> points = optimal_points(segments); cout << points.size() << "\n"; for (size_t i = 0; i < points.size(); ++i) { cout << points[i] << " "; } }
package Model; import java.util.Objects; import java.util.UUID; /** * This is the Authorization Token Model class */ public class AuthToken { /** * This is the authorization token for the authToken object * */ private String authToken; /** * This is the username for the authToken object * */ private String username; /** * This is the Constructor for the Authorization Token Model class */ public AuthToken(String authToken, String username) { this.authToken = authToken; this.username = username; } public AuthToken() { authToken = UUID.randomUUID().toString().substring(0,13); username = null; } // getters and setters public String getAuthToken() { return authToken; } public void setAuthToken(String authToken) { this.authToken = authToken; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AuthToken token = (AuthToken) o; return Objects.equals(authToken, token.authToken) && Objects.equals(username, token.username); } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using AcquiringBank.Data.Models; using MongoDB.Driver; namespace AcquiringBank.Data.Repositories.Abstractions; public abstract class BaseRepository<TModel> : IBaseRepository<TModel> where TModel : ModelBase { protected readonly IMongoCollection<TModel> _mongoCollection; protected BaseRepository(IMongoDatabase mongoDatabase, string collectionName = "") { if (mongoDatabase is null) throw new ArgumentException("MongoDatabase could not be null"); _mongoCollection = mongoDatabase.GetCollection<TModel>(collectionName == string.Empty ? nameof(TModel) : collectionName); } public async Task AddAsync(TModel model) { model.Id = Guid.NewGuid(); model.CreatedAt = DateTime.UtcNow; await _mongoCollection.InsertOneAsync(model); } public async Task DeleteByIdAsync(Guid id) { await _mongoCollection.DeleteOneAsync(px => px.Id.Equals(id)); } public async Task<TModel> FindByPredicateAsync(Expression<Func<TModel, bool>> predicate) { var cursor = await _mongoCollection.FindAsync(predicate); return await cursor.FirstOrDefaultAsync(); } public async Task<IEnumerable<TModel>> ListByPredicateAsync(Expression<Func<TModel, bool>> predicate) { var cursor = await _mongoCollection.FindAsync(predicate); return await cursor.ToListAsync(); } public async Task<(int pageNumber, int pageSize, int lastPage, IEnumerable<TModel>)> ListPaginateAsync( Expression<Func<TModel, bool>> predicate, int pageNumber, int pageSize) { var count = await _mongoCollection.CountDocumentsAsync(predicate); var elements = await _mongoCollection .Find(predicate) .Skip((pageNumber - 1) * pageSize) .Limit(pageSize).ToListAsync(); var totalPages = (int)count / pageSize; if (count % pageSize != 0) totalPages++; return (pageNumber, pageSize, totalPages, elements); } }
/** TreeNode: node for a general tree. */ class TreeNode { constructor(val, children = []) { this.val = val; this.children = children; } } class Tree { constructor(root = null) { this.root = root; } /** sumValues(): add up all of the values in the tree. */ sumValues() { let toSum = [this.root]; let sum = 0 while (toSum.length && toSum[0]) { let current = toSum.pop(); sum += current.val; for (let child of current.children) { toSum.push(child) } } return sum; } /** countEvens(): count all of the nodes in the tree with even values. */ countEvens() { let toCheck = [this.root]; let numEvens = 0 while (toCheck.length && toCheck[0]) { let current = toCheck.pop(); if (current.val % 2 === 0) { numEvens++; }; if (current.children) { for (let child of current.children) { toCheck.push(child) } } } return numEvens; } /** numGreater(lowerBound): return a count of the number of nodes * whose value is greater than lowerBound. */ numGreater(lowerBound) { let toCheck = [this.root]; let numHigher = 0 while (toCheck.length && toCheck[0]) { let current = toCheck.pop(); if (current.val > lowerBound) { numHigher++; }; if (current.children) { for (let child of current.children) { toCheck.push(child) } } } return numHigher; } } module.exports = { Tree, TreeNode };
import { useState } from "react"; import { signInWithGooglePopup, signInAuthUserWithEmailAndPassword, } from "../../utilities/firebase/firebase.utility"; import FormInput from "../form-input/form-input.component"; import Button from "../button/button.component"; import "./sign-in-form.styles.scss"; import "./sign-in-form.styles.scss"; const defaultFormFields = { email: "", password: "", }; const SignInForm = () => { const [formFields, setFormFields] = useState(defaultFormFields); const { email, password } = formFields; const handleChange = (event) => { const { name, value } = event.target; setFormFields({ ...formFields, [name]: value }); }; const handleSubmit = async (event) => { event.preventDefault(); try { await signInAuthUserWithEmailAndPassword(email, password); setFormFields(defaultFormFields); } catch (error) { console.log(error); } }; const logGoogleUser = async () => { await signInWithGooglePopup(); }; return ( <div className="sign-in-form-container"> <h2>Already have an account?</h2> <span>Sign Up with email and password</span> <form onSubmit={(event) => { handleSubmit(event); }} > <FormInput label="Email Address" type="email" required onChange={handleChange} name="email" value={email} /> <FormInput label="Password" type="password" required onChange={handleChange} name="password" value={password} /> <div className="sign-in-buttons-container"> <Button type="submit">Sign in</Button> <Button buttonType="google" onClick={logGoogleUser}> Google Sign in </Button> </div> </form> </div> ); }; export default SignInForm;
import React, { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Route, Routes } from 'react-router-dom'; import LoadingBar from 'react-redux-loading-bar'; import Header from './component/Header'; import CreateThread from './page/CreateThread'; import Home from './page/Home'; import Leaderboard from './page/Leaderboard'; import Login from './page/Login'; import Register from './page/Register'; import ThreadDetail from './page/ThreadDetail'; import { preloadState } from './redux/preload/action'; import { logoutUser } from './redux/user/action'; import AlertMessage from './component/AlertMessage'; function App() { const dispatch = useDispatch(); const { message, user, isPreload } = useSelector((state) => state); useEffect(() => { dispatch(preloadState()); }, [dispatch]); if (isPreload) { return null; } const handleLogout = () => { dispatch(logoutUser()); }; return ( <div className="mx-auto h-screen w-full pb-10"> <div className="sticky top-0 z-50"> <Header user={user} onLogout={handleLogout} /> </div> <div> <LoadingBar style={{ backgroundColor: 'green' }} showFastActions /> </div> <div className="p-4"> {message != null && ( <AlertMessage type={message.type} text={message.text} /> )} <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/register" element={<Register />} /> <Route path="/thread/:id" element={<ThreadDetail />} /> <Route path="/thread/new" element={<CreateThread />} /> <Route path="/leaderboard" element={<Leaderboard />} /> </Routes> </div> </div> ); } export default App;
<?php // Paso 1: Crear una variable llamada $edad y asignarle un valor numérico. $edad = 25; // Paso 2: Crear una expresión que calcule la edad que tendrás en 10 años y guardarla en una variable llamada $edad_futura. $edad_futura = $edad + 10; // Paso 3: Utilizar condicionales para mostrar un mensaje según la edad. if ($edad >= 18) { echo "Eres mayor de edad"; } else { echo "Eres menor de edad"; } echo "<br>"; // Paso 4: Utilizar un bucle para imprimir los números del 1 al 10 en orden ascendente. for ($i = 1; $i <= 10; $i++) { echo $i . " "; } echo "<br>"; // Paso 5: Crear una función que determine si un número es par o impar. function esPar($numero) { if ($numero % 2 == 0) { return true; } else { return false; } } // Paso 6: Utilizar un bucle para imprimir una lista de números pares del 20 al 40. echo "Números pares del 20 al 40: "; for ($i = 20; $i <= 40; $i++) { if (esPar($i)) { echo $i . " "; } } ?>
'use client' import styles from "./signin.module.css" import React from 'react' import Image from "next/image" import Link from "next/link" import * as Yup from 'yup' import { useFormik } from 'formik'; import Nft from "@/assets/Images/nft.jpg" import { Button, Checkbox, Form, Input } from 'antd'; export default function SignIn() { const formItemLayout = { labelCol: { span: 24 }, wrapperCol: { span: 24 }, }; const initialValues = { email : "", password: "" } const validationSchema = Yup.object().shape({ email: Yup.string() .email('Invalid email address') .required('Email is required') .matches( /^[A-Za-z0-9._%-]+@gmail\.com$/, 'Invalid email domain. Only gmail.com emails are allowed.' ), password: Yup.string() .required('Password is required') .min(6, 'Password must be at least 6 characters') }) const formik = useFormik({ initialValues, validationSchema, onSubmit :(values)=> { console.log(values) } }) return ( <> <Form onFinish={formik.handleSubmit} name="normal_login" className={styles.form}> <Image src = {Nft} alt = "nft" width={60} height={60} className="block mx-auto rounded-full"/> <h2 className="font-bold mb-7 text-[34px] text-center text-white break-words">MonkeyChat</h2> <Form.Item label = {<span style = {{color:"white", fontWeight:"900"}}>Email</span>} name="email" {...formItemLayout} validateStatus={formik.touched.email && formik.errors.email ? 'error' : ''} help={formik.touched.email && formik.errors.email ? formik.errors.email : null} > <Input placeholder="Email" {...formik.getFieldProps('email')}/> </Form.Item> <Form.Item label={<span className="text-white font-bold">Password</span>} name="password" {...formItemLayout} validateStatus={formik.touched.password && formik.errors.password ? 'error' : ''} help={formik.touched.password && formik.errors.password ? formik.errors.password : null} > <Input.Password {...formik.getFieldProps('password')}/> </Form.Item> <Form.Item> <Link className={styles.forgot} href="#"> Forgot password </Link> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" className={styles.btn}> Log in </Button> <span className="text-white">Or</span> <Link href="/" className={styles.signuptext}>Sign up!</Link> </Form.Item> <button className="w-[100%] block mx-auto bg-[grey] font-bold py-3 rounded-xl text-white" type="button">Sign In With Google</button> </Form> </> ) }
import { Component } from '@angular/core'; import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; import { Store } from '@ngrx/store'; import { AppState } from '../app.reducer'; import * as actions from './todoStore/todo.actions'; @Component({ selector: 'app-todo-add', standalone: true, imports: [ReactiveFormsModule], template: ` <header class="header"> <h1>TodoApp</h1> <input class="new-todo" placeholder="que quieres hacer?" autofocus [formControl]="txtInput" (keyup.enter)="agregar()" > </header> `, styles: `` }) export class TodoAddComponent { txtInput: FormControl; constructor(private store: Store<AppState>){ this.txtInput = new FormControl('', Validators.required) } agregar(){ if(this.txtInput.invalid){ return; } this.store.dispatch(actions.crear({texto: this.txtInput.value})); this.txtInput.reset(); } }
# Logging volunteer hours Staff can log actual hours worked by each volunteer on a regular basis which can be useful to track for funder reports. ## How to Log hours as follows: 1. Go to **Volunteers > Manage Volunteer Projects** 1. Find your project 1. Click **Log Hours** 1. Fill out the **Actual Duration** and **Status** columns. !!! bug As of version 2.2.1, a known [bug]( https://issues.civicrm.org/jira/browse/VOL-245) prevents you from logging *some* hours unless you log *all* hours for all assigned volunteers at once. "Hours worked" are stored within the activity for the [assignment](./assignments.md). See [reporting](./reporting.md) for more info about viewing this data after it's logged. ## Commending volunteers Within the **Log hours** screen, you can also click the star icon to write a "commendation" for the volunteer's performance within the project. It just gets stored in CiviCRM &mdash; it doesn't get emailed to them. Commendations are stored as separate activities (with the type "Volunteer Commendation"). Once made, you can see them on the **Activities** tab for a contact. !!! caution "Caveat" Commendations are associated with *projects* not with *assignments*. If you have a volunteer who worked the "Set up" assignment and the "Clean up" assignment for an event, you will only be able to write *one* commendation for them, as a summary of their performance throughout the entire project.
--- marp: true theme: default class: invert paginate: true --- <style> .icon img { border-radius: 50%; /* 丸く切り抜く */ } </style> # RailsからReactを剥がした話 --- ![bg](../../images/5a6819c5a9e9ad/top.png) --- <!-- _class: icon --> # 自己紹介 - GMOメディア所属 - 西悠太 - フロントエンドエンジニア - X: Riya31377928 ![bg left 100%](../../images/5a6819c5a9e9ad/icon.jpeg) --- # なぜ移行したのか ReactからRailsのERBに移行しました。 多くの方が「なぜ?」と思うかもしれません。 RailsからReactに移行するのはよくある話ですが、逆はあまり聞きません。 --- # 移行した理由は以下の通りです - 移行したページはlpなのでReactのメリットがあまりない - Reactのコードが負債になっている - 自分以外にReactを書ける人がいない --- # 移行したページはlpなのでReactのメリットがあまりない 移行したページはlpで、インタラクティブな要素はほとんどありません。 また、CSRを利用しているのでSEOにもあまりメリットがありません。 そのため、Reactを使うメリットがあまりないと考えました。 --- # Reactのコードが負債になっている 外部の会社に委託して作成したため、Reactのコードが負債になっていました。 TypeScriptだけど型がない、コンポーネントが分割されていない、コードが複雑、などなど。 --- # 自分以外にReactを書ける人がいない 私以外のチームメンバーはRailsをメインで書いているため、Reactを書ける人がいません。 たった数ページのためにReactを書ける人を育成するのは難しいと考えました。 以上の理由から、ReactからRailsのERB移行を決めました。 --- # 移行した手順 --- # 1. ロジックを整理する まず始めに、どんな工程を踏んで画面が表示されているのかを整理しました。 --- ## 画面が表示されるまでの工程は以下の通りです 1. Railsのコントローラーでデータを取得する 2. RailsのコントローラーでReactのコンポーネントにデータを渡す 3. Reactのコンポーネントでデータを加工する 4. 必要に応じてReactからAPIを叩く 5. Reactのコンポーネントでデータを表示する --- 特にネックになっていたのが、4の「必要に応じてReactからAPIを叩く」でした。 Railsのコントローラーでデータを取得しているのに、Reactから不足分のデータを取得していました。 そのため、何度も再レンダリングが発生していました。 --- # 2. コンポーネントを整理する 次に、移行対象のコンポーネントを整理しました。 コンポーネントAはBに依存していて、BはCに依存しているというような複雑な依存関係がありました。 それらを整理し、移行対象のコンポーネントを特定しました。 --- # 3. コンポーネントを一個ずつ移行する コンポーネントを一個ずつ移行していきました 1. if文をRubyのコードに変換 2. 共通関数をヘルパーに移植 3. propsをlocal_assignsに変換 4. コードを整理して可読性を上げる 5. JSを可能な限り削除する --- # 苦労した点 --- # 見た目の互換性を完璧にReactと合わせないといけない lp作成部分がReactで作成されていたため、見た目の互換性を完璧に合わせるのは大変でした。 React独自の機能をバニラJSで実装し直したり、CSSを修正したりしました。 ピクセル単位で見ると誤差はありますが、人間の目では全く分からないレベルになりました。 --- # 流れてくるデータが多次元配列 DBから取得したデータが多次元配列で流れていました。 ```txt [ ["id", 1], ["title", "Title"], ["description", "Description"], ["is_public", true], ["page_url", "hoge"], ["name_param", "hoge"], ["school_id", 1], ["tpl_image", {"id"=>1, "image_url"=>"http://res.cloudinary.com/hoge, "image_smart_url"=>nil}], ... ] ``` --- 本当はちゃんとしたデータ構造に直したかったのですが、他のページでも参照しているため、今回は直さずに移行しました。 必要なデータには `position` というキーがあるので、それを使ってソートしました。 ```ruby items.map { |item| item.deep_transform_keys(&:to_sym) }.each_with_index.sort_by { |item, index| [item[:position], index] }.map(&:first) # mapで配列の中身をシンボルに変換 # each_with_indexで配列の中身とインデックスを取得 # sort_byでpositionでソートし、positionが同じ場合はインデックスでソート # mapでインデックスを削除 ``` --- # if文をRubyのコードに変換 私は普段からReactを書いているので、Rubyの真偽値の扱いに手間取りました。 JSでは、`''` や `0` などの値が `false` として扱われますが、Rubyでは `''` や `0` は `true` として扱われます。 --- # ERBとReactの改行、空白の違い ERBでは改行や空白がそのまま出力されますが、Reactでは改行や空白が無視されます。 これになかなか気づけず、苦労しました。 --- ## ERB ```erb <p> <%= text %> </p> ``` ```html <p> こんにちは </p> ``` --- ## React ```jsx const Hoge = () => { const text = "こんにちは" return ( <p> {text} </p> ) } ``` ```html <p>こんにちは</p> ``` --- # コードを整理して可読性を上げる React側でデータを加工していたため、コードが複雑になっていました。 そのため、コードを整理して可読性を上げるのに苦労しました。 Railsのコントローラーで整形してからデータを渡すように変更したり、必要なデータを一括で取得するように変更したりしました。 バグ検証に時間がかかりましたが、コードが整理されていくのは楽しかったです。 --- # JSを可能な限り削除する Reactで無駄にJSを書いていた部分があったので、可能な限り削除しました。 例えば、ホバー時にスタイルを変更するという処理は、`onmouseover` と `onmouseout` を使って実装しました。 --- # まとめ そんなこんなで、ReactからRailsのERBに移行しました。 移行には苦労しましたが、コードが整理されていくのは楽しかったです。 React好きとしては、少し寂しい気持ちもありますが、移行してよかったと思っています。 適材適所で使うことが大切だと思います。 --- # おまけ ![](../../images/5a6819c5a9e9ad/QR_337957.png) https://zenn.dev/gmomedia/articles/5a6819c5a9e9ad
> Name 双重强力指标策略Double-Strong-Indicators-Strategy > Author ChaoZhang > Strategy Description ![IMG](https://www.fmz.com/upload/asset/f34fda5b45509d9f7c.png) [trans] ### 概述 本策略综合运用移动平均线聚散指标(MACD)和相对强弱指数(RSI)两个强力指标,设定买入和卖出条件,以捕捉股价的反转机会。 ### 策略原理 1. 计算MACD指标,包括快线、慢线和信号线。快线和慢线交叉为买卖信号。 2. 计算RSI指标,设置超买区和超卖区阈值。RSI指标可以判断超买超卖情况。 3. 结合MACD指标的金叉死叉信号和RSI指标的超买超卖区判断,制定买入和卖出条件: - 买入条件:MACD快线上穿慢线形成金叉,同时RSI指标刚刚从超卖区回落,具有反转信号; - 卖出条件:MACD快线下穿慢线形成死叉,同时RSI指标进入超买区,具有反转信号。 4. 这样可以同时利用两个强力指标的优势,在反转点位精确买入卖出。 ### 优势分析 1. MACD指标可以判断股价趋势和买卖时机。RSI指标可以判断超买超卖情况。两者结合可以提高买卖精准度。 2. 同时利用两个指标过滤信号,可以避免因单一指标产生的假信号。 3. MACD结合RSI,可以在反转点前买入,反转点后卖出,捕捉反转机会。 4. 该策略操作频率适中,既可以跟踪趋势,也可以捕捉反转,灵活运用。 ### 风险分析 1. MACD指标在震荡行情中容易产生假信号。RSI指标参数设置需要优化,否则也会出现假信号。 2. 股价短期内可能存在剧烈波动,跌破策略的止损点造成损失。 3. 需要优化RSI和MACD的参数设置,否则可能出现过多信号或信号不足。 4. 实盘交易中需要严格把控资金管理和风险控制。 ### 优化方向 1. 优化MACD参数的快慢均线设置,寻找最佳的参数组合。 2. 优化RSI的超买超卖阈值,防止假信号的产生。 3. 加入止损机制,以控制单笔损失。 4. 可以考虑加入其他指标,如布林带、KDJ等,形成多重过滤。 5. 可以测试不同的买卖策略,如突破策略、趋势跟踪策略等。 ### 总结 本策略同时运用MACD和RSI两个强力指标,在反转点买入卖出,具有较强的实战价值。但需要持续优化参数设置,严格做好资金管理,才能在实盘中取得好的效果。该策略整体较为灵活,可适应不同行情,值得实盘验证与长期跟踪。 || ## Overview This strategy combines the Moving Average Convergence Divergence (MACD) indicator and the Relative Strength Index (RSI) indicator to set buy and sell conditions for catching reversal opportunities. ### Strategy Logic 1. Calculate the MACD indicator, including the fast line, slow line and signal line. Crossovers between the fast line and slow line are trading signals. 2. Calculate the RSI indicator and set overbought and oversold threshold values. The RSI indicator can determine overbought and oversold conditions. 3. Combine the crossover signals from the MACD and the overbought/oversold readings from the RSI to formulate the buy and sell conditions: - Buy condition: The MACD fast line crosses above the slow line (golden cross) while the RSI indicator just fell back from the overbought zone, signaling a reversal. - Sell condition: The MACD fast line crosses below the slow line (death cross) while the RSI indicator enters the overbought zone, signaling a reversal. 4. This allows utilizing the strengths of both powerful indicators to accurately buy and sell at reversal points. ### Advantage Analysis 1. MACD can identify trends and trading opportunities. RSI gauges overbought/oversold conditions. Using both improves accuracy. 2. Using two indicators filters out false signals that can occur with a single indicator. 3. MACD combined with RSI allows buying before reversals and selling after reversals to capture turns. 4. The strategy has a moderate frequency, tracking trends and catching reversals flexibly. ### Risk Analysis 1. MACD can give false signals in choppy markets. RSI parameters need optimization to avoid false signals. 2. Short-term volatility may stop out positions, causing losses. 3. RSI and MACD parameters need optimization to avoid too many or too few signals. 4. Strict risk and money management are crucial for live trading. ### Optimization Directions 1. Optimize MACD fast/slow line parameters for best combinations. 2. Optimize RSI overbought/oversold thresholds to prevent false signals. 3. Add a stop loss to control single trade risk. 4. Consider adding filters like Bollinger Bands or KDJ for extra confirmation. 5. Test various entry/exit strategies like breakouts or trend following. ### Summary This strategy combines the strengths of MACD and RSI for reversals. But parameter tuning, risk control and money management are key for live performance. The flexibility makes it suitable for different market conditions and worth live testing and tracking. [/trans] > Strategy Arguments |Argument|Default|Description| |----|----|----| |v_input_int_1|12|Fast moving average| |v_input_int_2|26|Slow moving average| |v_input_int_3|9|signalLength| |v_input_int_4|35|RSIOverSold| |v_input_int_5|80|RSIOverBought| |v_input_int_6|14|Length| > Source (PineScript) ``` javascript /*backtest start: 2022-11-13 00:00:00 end: 2023-11-19 00:00:00 period: 1d basePeriod: 1h exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ //@version=5 // © sabirt strategy(title='MACD and RSI', overlay=true, shorttitle='MACD&RSI') //MACD Settings fastMA = input.int(title='Fast moving average', defval=12, minval=1) slowMA = input.int(title='Slow moving average', defval=26, minval=1) signalLength = input.int(9, minval=1) //RSI settings RSIOverSold = input.int(35, minval=1) RSIOverBought = input.int(80, minval=1) src = close len = input.int(14, minval=1, title='Length') up = ta.rma(math.max(ta.change(src), 0), len) down = ta.rma(-math.min(ta.change(src), 0), len) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down) wasOversold = rsi[0] <= RSIOverSold or rsi[1] <= RSIOverSold or rsi[2] <= RSIOverSold or rsi[3] <= RSIOverSold or rsi[4] <= RSIOverSold or rsi[5] <= RSIOverSold wasOverbought = rsi[0] >= RSIOverBought or rsi[1] >= RSIOverBought or rsi[2] >= RSIOverBought or rsi[3] >= RSIOverBought or rsi[4] >= RSIOverBought or rsi[5] >= RSIOverBought [currMacd, _, _] = ta.macd(close[0], fastMA, slowMA, signalLength) [prevMacd, _, _] = ta.macd(close[1], fastMA, slowMA, signalLength) signal = ta.ema(currMacd, signalLength) avg_1 = math.avg(currMacd, signal) crossoverBear = ta.cross(currMacd, signal) and currMacd < signal ? avg_1 : na avg_2 = math.avg(currMacd, signal) crossoverBull = ta.cross(currMacd, signal) and currMacd > signal ? avg_2 : na strategy.entry('buy', strategy.long, when=crossoverBull and wasOversold) strategy.close('buy', when=crossoverBear and wasOverbought) ``` > Detail https://www.fmz.com/strategy/432657 > Last Modified 2023-11-20 09:47:41
# 给你一个整数数组 nums 。nums 中,子数组的 范围 是子数组中最大元素和最小元素的差值。 # # 返回 nums 中 所有 子数组范围的 和 。 # # 子数组是数组中一个连续 非空 的元素序列。 # # # # 示例 1: # # # 输入:nums = [1,2,3] # 输出:4 # 解释:nums 的 6 个子数组如下所示: # [1],范围 = 最大 - 最小 = 1 - 1 = 0 # [2],范围 = 2 - 2 = 0 # [3],范围 = 3 - 3 = 0 # [1,2],范围 = 2 - 1 = 1 # [2,3],范围 = 3 - 2 = 1 # [1,2,3],范围 = 3 - 1 = 2 # 所有范围的和是 0 + 0 + 0 + 1 + 1 + 2 = 4 # # 示例 2: # # # 输入:nums = [1,3,3] # 输出:4 # 解释:nums 的 6 个子数组如下所示: # [1],范围 = 最大 - 最小 = 1 - 1 = 0 # [3],范围 = 3 - 3 = 0 # [3],范围 = 3 - 3 = 0 # [1,3],范围 = 3 - 1 = 2 # [3,3],范围 = 3 - 3 = 0 # [1,3,3],范围 = 3 - 1 = 2 # 所有范围的和是 0 + 0 + 0 + 2 + 0 + 2 = 4 # # # 示例 3: # # # 输入:nums = [4,-2,-3,4,1] # 输出:59 # 解释:nums 中所有子数组范围的和是 59 # # # # # 提示: # # # 1 <= nums.length <= 1000 # -10⁹ <= nums[i] <= 10⁹ # # # # # 进阶:你可以设计一种时间复杂度为 O(n) 的解决方案吗? # Related Topics 栈 数组 单调栈 👍 130 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def subArrayRanges(self, nums: List[int]) -> int: stack, ans = [], 0 # 利用单调递减栈,得到pop出来的下标i左右最近的比nums[i]更大的位置jk,nums[i]作为区域(j, k)的最大值 for k, v in enumerate(nums + [float('inf')]): while stack and nums[stack[-1]] <= v: i, j = stack.pop(), stack[-1] if stack else -1 ans += (i - j) * (k - i) * nums[i] stack.append(k) # 利用单调递增栈,得到pop出来的下标i左右最近的比nums[i]更小的位置jk,nums[i]作为区域(j,k)的最小值 stack = [] for k, v in enumerate(nums + [float("-inf")]): while stack and nums[stack[-1]] > v: i, j = stack.pop(), stack[-1] if stack else -1 ans -= (i - j) * (k - i) * nums[i] stack.append(k) return ans # leetcode submit region end(Prohibit modification and deletion) nums = [30,20,10,20] print(Solution().subArrayRanges(nums))
import { Component, OnDestroy, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators, } from '@angular/forms'; import { IonicModule, LoadingController, NavController, ToastController, } from '@ionic/angular'; import { AccessoriesSubTypes, ClothingSubTypes, ClothingTypes, FootwearSubTypes, Settings, UndergarmentsSubTypes, } from 'src/app/constants/constants'; import { WardrobeService } from 'src/app/services/wardrobe/wardrobe.service'; import { ClothingItem } from 'src/app/models/clothing-item/clothing-item.model'; import { Subscription } from 'rxjs'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-edit-clothing-item', templateUrl: './edit-clothing-item.page.html', styleUrls: ['./edit-clothing-item.page.scss'], standalone: true, imports: [IonicModule, CommonModule, FormsModule, ReactiveFormsModule], }) export class EditClothingItemPage implements OnInit, OnDestroy { clothingItem: ClothingItem | undefined; form!: FormGroup; clothingTypes: string[] = ClothingTypes; clothingSubTypes: string[] = ClothingSubTypes; accessoriesSubTypes: string[] = AccessoriesSubTypes; footwearSubTypes: string[] = FootwearSubTypes; undergarmentsSubTypes: string[] = UndergarmentsSubTypes; clothingSettings: string[] = Settings; otherSubTypes: string[] = ['Other']; private _subscriptions: Subscription[] = []; thumbnailError: boolean = true; constructor( private loadingCtrl: LoadingController, private wardrobeService: WardrobeService, private toastCtrl: ToastController, private navCtrl: NavController, private activatedRoute: ActivatedRoute ) {} ngOnInit() { this.form = new FormGroup({ clothingSetting: new FormControl(null, { updateOn: 'change', validators: [Validators.required], }), clothingType: new FormControl(null, { updateOn: 'change', validators: [Validators.required], }), clothingSubType: new FormControl(null, { updateOn: 'change', validators: [Validators.required], }), color: new FormControl(null, { updateOn: 'change', validators: [Validators.required], }), imageUrl: new FormControl(null, { updateOn: 'change', validators: [Validators.required], }), isFavorite: new FormControl(null, { updateOn: 'change', validators: [], }), }); this._subscriptions.push( this.activatedRoute?.paramMap?.subscribe((paramMap) => { if (!paramMap?.has('clothingItemId')) { this.navCtrl.navigateBack('/home/tabs/feed'); return; } this.loadingCtrl .create({ message: 'Fetching Item data...', }) .then((loadingEl) => { loadingEl.present(); this.wardrobeService .getClothingItemsById(<string>paramMap?.get('clothingItemId')) .subscribe((itemArray) => { if (!itemArray || !itemArray.length) { this.navCtrl.navigateBack('/wardrobe'); } this.clothingItem = itemArray[0]; this.form.patchValue({ clothingSetting: this.clothingItem.setting, clothingType: this.clothingItem.type, clothingSubType: this.clothingItem.subType, imageUrl: this.clothingItem.imageUrl, color: this.clothingItem.color, }); loadingEl.dismiss(); }); }); }) ); } onThumbnailError() { console.log('onThumbnailError'); this.thumbnailError = true; } onIonImgDidLoad(event: any) { console.log('onIonImgDidLoad'); this.thumbnailError = false; } onCreateClothingItem() { const newClothingItem = new ClothingItem( this.form.value.clothingSetting, this.form.value.clothingType, this.form.value.clothingSubType, this.form.value.imageUrl, <string>this.clothingItem?.id, this.form.value.color ); this.loadingCtrl .create({ message: 'UpdatingItem...', }) .then((loadingEl) => { loadingEl.present(); this.wardrobeService .updateClothingItem(newClothingItem) .subscribe((res) => { if (res) { this.toastCtrl .create({ message: 'Item updated Successfully!', duration: 1500, position: 'bottom', icon: 'checkmark-circle-outline', color: 'success', }) .then((toastEl) => { toastEl.present(); loadingEl.dismiss(); this.navCtrl.navigateBack('/wardrobe'); }); } else { this.toastCtrl .create({ message: 'Cold not update item!', duration: 1500, position: 'bottom', icon: 'close-circle-outline', color: 'danger', }) .then((toastEl) => { toastEl.present(); }); } }); }); } ngOnDestroy() { this._subscriptions.forEach((subscription) => subscription.unsubscribe()); } }
# -*- coding: utf-8 -*- """ Created on Fri Nov 24 14:26:55 2023 @author: Asus """ import pandas as pd import numpy as np import matplotlib.pyplot as plt # visualization import seaborn as sns # Importing the dataset dataset = pd.read_csv(r"C:\Users\Asus\Downloads\electronics.csv") # list of first five rows dataset.head() dataset.tail() # shape dataset.shape # It is also a good practice to know the columns and their corresponding data types # along with finding whether they contain null values or not. dataset.info() # We can see that the dataset contains 5 columns and 10000 rows. # The columns are as follows: # 1. User ID # 2. Product ID # 3. Rating # 4. Timestamp # 5. Category # The data types of the columns are as follows: # 1. User ID - int64 # 2. Product ID - object # 3. Rating - int64 # 4. Timestamp - int64 # 5. Category - object # We can see that the columns User ID and Rating are of int64 data type, while the columns Product ID and Category are of object data type. # We can also see that there are no null values in the dataset. # We can also see that the column Timestamp is of int64 data type, but it is actually a timestamp. # We can convert it to a timestamp using the following code: from datetime import datetime pd.to_datetime(dataset['timestamp']) # We can also see that the column Product ID is of object data type, but it is actually a string. # We can convert it to a string using the following code: dataset['brand'] = dataset['brand'].astype(str) # We can also see that the column Category is of object data type, but it is actually a string. # We can convert it to a string using the following code: dataset['category'] = dataset['category'].astype(str) # We can also see that the column Timestamp is of int64 data type, but it is actually a timestamp. # We can convert it to a timestamp using the following code: dataset['timestamp'] = pd.to_datetime(dataset['timestamp']) # We can also see that the column Rating is of int64 data type, but it is actually a float. # We can convert it to a float using the following code: dataset['rating'] = dataset['rating'].astype(float) # We can also see that the column User ID is of int64 data type, but it is actually a string. # We can convert it to a string using the following code: dataset['user_id'] = dataset['user_id'].astype(str) # We can also see that the column Product ID is of object data type, but it is actually a string. # We can convert it to a string using the following code: dataset['item_id'] = dataset['item_id'].astype(str) # to get a better understanding of the dataset, # we can also see the statistical summary of the dataset. dataset.describe() # 1. The mean rating is 4. # 2. The minimum rating is 1. # 3. The maximum rating is 5. # 4. The standard deviation of the ratings is 1.4. # 5. The 25th percentile of the ratings is 4. # 6. The 50th percentile of the ratings is 5. # 7. The 75th percentile of the ratings is 5. # We can also see the number of unique users and items in the dataset. dataset.nunique() # check for duplicates dataset.duplicated().sum() # check for missing values dataset.isnull().sum() # the distribution of ratings dataset['rating'].value_counts() # most of the ratings are 5 # what was the best year of sales dataset['year'] = pd.DatetimeIndex(dataset['timestamp']).year dataset['year'].value_counts() # 2015 was the best year of sales # what was the best month of sales dataset['month'] = pd.DatetimeIndex(dataset['timestamp']).month dataset['month'].value_counts() # January was the best month of sales # drop all null values dataset.dropna(inplace=True) # check for missing values # FINDING ANSWERS WITH THE DATA WE HAVE WITH VISUALIZATIONS # the distribution of ratings sns.countplot(x='rating', data=dataset) # the distribution of ratings # The distribution of ratings is as follows: # most of the ratings are 5 dataset['rating'].value_counts() # the distribution of sales by year sns.countplot(x='year', data=dataset) # the distribution of sales by year # The distribution of sales by year is as follows: # 2015 was the best year of sales <AxesSubplot:xlabel='year', ylabel='count'> # brands with the most sales sns.countplot(x='brand', data=dataset, order=dataset['brand'].value_counts().iloc[1:10].index) # What brand name sold the least? sns.countplot(x='brand', data=dataset, order=dataset['brand'].value_counts().iloc[-10:].index) # We can see that the brand name of EINCAR sold the least followed closely with DURAGADGET. # Logitech & Bose had the most sales followed by Sony. # brands with the most sales in 2016 sns.countplot(x='brand', data=dataset[dataset['year'] == 2016], order=dataset['brand'].value_counts().iloc[1:10].index) # in 2016 Bose overtook Logitech to have the most sales. # TaoTronics had the third most sales that year # brands with the most sales in 2017 sns.countplot(x='brand', data=dataset[dataset['year'] == 2017], order=dataset['brand'].value_counts().iloc[1:10].index) # the top 3 products sold in 2017 were Bose, Logitech and Mpow. # brands with the most sales in 2018 sns.countplot(x='brand', data=dataset[dataset['year'] == 2018], order=dataset['brand'].value_counts().iloc[1:10].index) # For 2018, Bose was the most sold for a third year in a row followed by Logitech while Mpow was the third most sold. # month with most sales sns.countplot(x='month', data=dataset) # January[#1] was the month with the most sales # What products by category were sold the most in January sns.countplot(x='category', data=dataset[dataset['month'] == 1], order=dataset['category'].value_counts().iloc[1:10].index) # The top 3 products sold in January were Computers & Accesories, Camera & Photo and Accesories & Supplies. # Category with the least sales sns.countplot(x='category', data=dataset, order=dataset['category'].value_counts().iloc[-10:].index) # The category with the least sales was Security & Surveillance while the most sales were Headphones. # distribution of sales presented in a pie chart dataset['category'].value_counts(normalize=True) dataset.groupby('category')['rating'].count().sort_values(ascending=False).head(10).plot(kind='pie') # white background sns.set_style('white') # conclusion of our analysis # We can see that the year 2015 had the best sales. # The month of January had the best sales. # We can see that the brands Bose and Logitech sold the most # We can see that the category of Headphones sold the most. # We can see that the brand name of EINCAR sold the least followed closely with DURAGADGET. # We can see that the category of Security and Surveillance sold the least.
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace DuplicatorPro\Symfony\Component\EventDispatcher; /** * An EventSubscriber knows himself what events he is interested in. * If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes * {@link getSubscribedEvents} and registers the subscriber as a listener for all * returned events. * * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> * @author Bernhard Schussek <bschussek@gmail.com> * * @api */ interface EventSubscriberInterface { /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array The event names to listen to * * @api */ public static function getSubscribedEvents(); }
// server.js const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express(); const port = 3300; app.use(cors()); app.use(bodyParser.json()); let issues = []; app.post('/create', (req, res) => { const newIssue = req.body; issues.push(newIssue); console.log('Created Issue:', newIssue); res.json(newIssue); }); app.get('/read', (req, res) => { res.json(issues); }); app.put('/update', (req, res) => { const updatedIssue = req.body; console.log('Updated Issue:', updatedIssue); res.json(updatedIssue); }); // Update delete endpoint to expect the issue ID as a parameter app.delete('/delete/:id', (req, res) => { const issueId = req.params.id; const deletedIssueIndex = issues.findIndex((issue) => issue.id == issueId); if (deletedIssueIndex !== -1) { const deletedIssue = issues.splice(deletedIssueIndex, 1)[0]; console.log('Deleted Issue:', deletedIssue); res.json(deletedIssue); } else { res.status(404).json({ error: 'Issue not found' }); } }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });
import { useState } from "react"; import { useNavigate } from "react-router-dom"; import classes from "./AboutPage.module.scss"; import Privacy from "./content-section/Privacy"; import Terms from "./content-section/Terms"; import Introduction from "./content-section/Introduction"; import Objectives from "./content-section/Objectives"; import RoundArrowRightSvg from "../../Shared/svgs/RoundArrowRightSvg"; import RoundArrowLeftSvg from "../../Shared/svgs/RoundArrowLeftSvg"; function AboutPage() { const pageOptions = [ { title: "Introduction", component: <Introduction /> }, { title: "Objectives", component: <Objectives /> }, { title: "Terms", component: <Terms /> }, { title: "Privacy", component: <Privacy /> }, ]; const navigate = useNavigate(); const [selectedContent, setSelectedContent] = useState(0); const onSetSelectedContent = (pageNumber) => { setSelectedContent(pageNumber); }; return ( <div className={classes.container}> <div className={classes["container__column"]}> <div className={classes["container__column__nav"]}> <ul> {pageOptions.map((element, index) => ( <li key={index} onClick={() => { onSetSelectedContent(index); }} > <RoundArrowRightSvg /> {element.title} </li> ))} </ul> <ul> <li onClick={() => { navigate("/"); }} > <RoundArrowLeftSvg /> Home Page </li> </ul> </div> </div> <div className={classes["container__column"]}> <div className={classes["container__column__content"]}> {pageOptions[selectedContent].component} </div> </div> </div> ); } export default AboutPage;
import React, { useContext, useState } from "react"; import DataContext from "../../context/DataContext"; import { ToastContainer, Zoom } from "react-toastify"; import { Formik, Form, ErrorMessage } from "formik"; import TextField from "../../components/textField/TextField"; import TextAreaField from "../../components/textField/TextAreaField"; import SelectField from "../../components/textField/SelectField"; import * as Yup from "yup"; const AddProduct = () => { const { isLoading, handleAddProduct } = useContext(DataContext); const itemCode = (category) => { const letter = category.slice(0, 3).toUpperCase(); const number = Date.now(); const output = letter + "-" + number; return output; }; const validate = Yup.object({ name: Yup.string() .max(25, "Must be less than 15 Characters") .min(3, "Must be at least 6 Characters") .required("Required"), category: Yup.string().required("Required"), quantity: Yup.number() .max(100, "Must be less than 100") .min(0, "Must be at least 1") .required("Required"), price: Yup.number().min(0, "Must be at least 1").required("Required"), description: Yup.string() .max(250, "Must be less than 10 Characters") .min(3, "Must be at least 1 Characters") .required("Required"), file: Yup.mixed().nullable().required(), }); const saveProduct = async (values) => { const formData = new FormData(); formData.append("name", values.name); formData.append("category", values.category); formData.append("quantity", values.quantity); formData.append("price", values.price); formData.append("description", values.description); formData.append("itemCode", itemCode(values.category)); formData.append("image", values.file); handleAddProduct(formData); }; return ( <section className='productEdit'> <div className='container mt-5 update__profile'> <Formik initialValues={{ name: "", category: "", quantity: "", price: "", description: "", file: null, }} validationSchema={validate} onSubmit={(values, { resetForm }) => { saveProduct(values); resetForm({ values: "" }); values.file = null; }} > {({ values, setFieldValue }) => ( <Form> <div className='detailCards'> <h3 style={{ color: "var(--theme" }}>Add Items :</h3> <TextField label='Item Name' name='name' id='name' type='text' placeholder='Enter Item Name' /> <div className='form-group mb-3 '> <label htmlFor='file' className='label__style mb-0' > Item Photo </label> <div> <input className={`form-control shadow-none`} autoComplete='off' type='file' name='file' accept='image/png, image/gif, image/jpeg' onChange={(e) => { setFieldValue("file", e.target.files[0]); }} /> <ErrorMessage name='file' component='p' className='errorMessage' /> </div> </div> {values.file != null && ( <div className='image__preview rounded'> <img src={URL.createObjectURL(values.file)} alt='product' className='rounded' width={200} height={200} /> </div> )} <SelectField label='Category' name='category' id='category' /> <TextField label='Quantity' name='quantity' id='quantity' type='number' placeholder='Enter the Quantity' /> <TextField label='Price' name='price' id='price' type='number' placeholder='Enter Price' /> <TextAreaField label='Description' name='description' id='description' type='text' placeholder='Enter Description' /> <div className='text-center mt-3'> <button className='text-white button rounded' type='submit' > {isLoading ? ( <span className='spinner-border spinner-border-sm text-warning'></span> ) : ( "Add Items" )} </button> </div> </div> </Form> )} </Formik> </div> <ToastContainer position='top-right' autoClose={1000} transition={Zoom} draggable={false} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss pauseOnHover theme='dark' /> </section> ); }; export default AddProduct;
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSavedBlogsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('saved_blogs', function (Blueprint $table) { $table->increments('saved_blog_id'); $table->integer('blog_post_id')->unsigned()->nullable(); $table->integer('blog_category_id')->unsigned()->nullable(); $table->integer('user_id')->unsigned()->nullable(); $table->timestamps(); $table->foreign('blog_post_id')->references('blog_post_id')->on('blog_posts')->onDelete('cascade'); $table->foreign('blog_category_id')->references('blog_category_id')->on('blog_categories')->onDelete('cascade'); $table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('saved_blogs'); } }
(ns yolk.macros) (defmacro defbus [name args value-args & body] `(defn ~name ~args (fn ~value-args ~@body))) (defmacro defnotice [name] `(defn ~name [] (fn [x#] x#))) (defn log-sexp [sexp] `(yolk.bacon/do-action (yolk.bacon/log-action '~sexp))) (defmacro ->logi "Skips the fist expression. Useful for using inside a '->" [& body] `(-> ~(first body) ~@(interleave (rest body) (map log-sexp (rest body))))) (defmacro ->log [& body] `(-> ~@(interleave body (map log-sexp body)))) (comment (->log a (b/map true)) (defn my-function [value] (do stuff ...) value) (->with my-function ) (-> a (b/do-action (log-action 'a)) (b/map true) (b/do-action (log-action '(b/map true)))) )
# class Employee: # def __init__(self, name, id,salary): # self.name = name # self.id = id # self.salary = salary # def showDetails(self): # print(f"Details about {self.name}:\n I 'm {self.name}. My id is {self.id} and my salary is {self.salary}\n\n") # # inheritance # class Programmer(Employee): # def progrmmer(self): # print("The default programming language is Python!") # e1 = Employee("Md. Sultan Mahmud", "0001", 30500) # e2 = Employee("Md. Rahul Islam", "0002", 50000) # e3 = Employee("Md. Kabir Khan", "0003", 20000) # e4 = Programmer("Mst. Nilima Akter", "0004", 15000) # e1.showDetails() # e2.showDetails() # e3.showDetails() # e4.showDetails() # e4.progrmmer() class Student: def __init__(self, name,age): self.name = name self.age = age def show(self): print(f"My name is {self.name} and i'm in {self.age} years old!!") class Profession(Student ): def __init__(self,name, age, prof): super().__init__(name, age) self.prof = prof def profession(self): print(f"I'm working as {self.prof}") s1 = Student("Sultan", 20 ) s2 = Profession("Rahul Islam", 25,"Programmer") s2.show() s2.profession() # s1.show()
const mysqlExecute = require("../../util/mysqlConnexion"); const fs = require("fs"); const fs2 = require("fs").promises; const bcrypt = require("bcrypt"); const sharp = require("sharp"); const GeneralDAO = require("./generalDAO"); const { response } = require("express"); // Esta función envuelve la función fs.readFile en una promesa para uso asíncrono const readFileAsync = async (path) => { try { return await fs2.readFile(path); } catch (error) { throw error; } }; const { error } = require("console"); const hashPassword = async (password) => { const saltRounds = 10; // Número de rondas de salado const hashedPassword = await bcrypt.hash(password, saltRounds); return hashedPassword; }; const comparePassword = async (password, hashedPassword, cb) => { try { const match = await bcrypt.compare(password, hashedPassword); cb(match); } catch (error) { // Manejar el error, si ocurre console.error("Error al comparar contraseñas:", error); return false; } }; class FreelancerDAO { static async createFreelancer(free, cb) { let sql = "INSERT INTO freelancer (idFreelancer, `name`, phoneNumber,cellphone,adress, email, `password`, idCity, `description`, profilePhoto) VALUES (?,?,?,?,?,?,?,?,?,?);"; const password = await hashPassword(free.password); const knowledge = free.technickKnowledge; let link = free.profilePhoto; const values = [ free.idCard, free.name, free.telphone, free.cellphone, free.adress, free.email, password, parseFloat(free.idCity), free.description, ]; let fileContent = null; try { if (link !== null) { fileContent = await sharp(link) .resize({ width: 800 }) .jpeg({ quality: 80 }) .toBuffer(); } values.push(fileContent); const results = await mysqlExecute(sql, values); cb({ result: true, user: {} }); GeneralDAO.insertKnowledge(knowledge, free.idCard); } catch (err) { console.log(err); cb({ result: false }); } if (link !== null) { fs.unlink(link, (error) => { if (error) { console.error("Error deleting file:", error); } else { console.log("File deleted successfully."); } }); } } static async fetchAll(p, cb) { let sql = p.city !== "00" ? "select f.idFreelancer, f.name , t.name city, f.description, f.profilePhoto, f.url from freelancer f left join town t using (idCity) where f.idCity=?" : "select f.idFreelancer, f.name , t.name city, f.description, f.profilePhoto, f.url from freelancer f left join town t using (idCity)"; try { const results = p.city !== "00" ? await mysqlExecute(sql, [parseFloat(p.city)]) : await mysqlExecute(sql); results.map((freelancer) => { if (freelancer.profilePhoto) { let photo = freelancer.profilePhoto.toString("base64"); freelancer["profilePhoto"] = photo; } }); cb(results); } catch (err) { console.log(error) cb({ result: false }); } } static async fetchAll(p, cb) { let sql = p.city !== "00" ? "select f.idFreelancer, f.name , t.name city, f.description, f.profilePhoto from freelancer f left join town t using (idCity) where f.idCity=?" : "select f.idFreelancer, f.name , t.name city, f.description, f.profilePhoto from freelancer f left join town t using (idCity)"; try { const results = p.city !== "00" ? await mysqlExecute(sql, [parseFloat(p.city)]) : await mysqlExecute(sql); results.map((freelancer) => { if (freelancer.profilePhoto) { let photo = freelancer.profilePhoto.toString("base64"); freelancer["profilePhoto"] = photo; } }); cb(results); } catch (err) { console.log(err); cb({ result: false }); } } static async fetchByKeyword(p, cb) { let sql = p.city !== "00" ? "select f.idFreelancer, f.name name, t.name city, f.description, f.profilePhoto FROM freelancer f left join town t using (idCity) WHERE idCity=? and description LIKE ? or f.name like ? " : "select f.idFreelancer, f.name name, t.name city, f.description, f.profilePhoto FROM freelancer f left join town t using (idCity) WHERE description LIKE ? or f.name like ? "; try { const results = p.city !== "00" ? await mysqlExecute(sql, [ parseFloat(p.city), `%${p.keyword}%`, `%${p.keyword}%`, ]) : await mysqlExecute(sql, [`%${p.keyword}%`, `%${p.keyword}%`]); results.map((freelancer) => { if (freelancer.profilePhoto) { let photo = freelancer.profilePhoto.toString("base64"); freelancer["profilePhoto"] = photo; } }); cb(results); } catch (err) { console.log(err); cb({ result: false }); } } static async userExist(json, cb) { let sql = "select * from freelancer where idFreelancer=?"; try { const res = await mysqlExecute(sql, [json.idCard]); this.emailExist(json, (e) => { if (e.length === 0 && res.length === 0) { cb({ result: true }); } else { if (e.length !== 0) { cb({ result: false, error: "Email registrada anteriormente." }); } else { cb({ result: false, error: "Cedula registrada anteriormente." }); } } }); } catch (error) { console.log(error); } } static async emailExist(json, cb) { let sql = "select * from freelancer where email=?"; try { const res = await mysqlExecute(sql, [json.email]); cb(res); } catch (error) { console.log(error); } } static async fetchById(id, cb) { let sql = "SELECT idFreelancer, name, description, cellphone, email, importantInfo, profilePhoto, rut, curriculum, eps FROM freelancer WHERE idFreelancer = ?"; try { const response = await mysqlExecute(sql, [id]); const user = response[0]; // Convertir blobs a URLs de datos base64 si existen if (user.profilePhoto) { user.profilePhoto = user.profilePhoto.toString("base64"); } if (user.rut) { user.rut = user.rut.toString("base64"); } if (user.curriculum) { user.curriculum = user.curriculum.toString("base64"); } if (user.eps) { user.eps = user.eps.toString("base64"); } // Obtener títulos de conocimientos académicos y agregarlos a la respuesta sql = "SELECT title FROM academicdegrees JOIN technicalknowledge USING(idTechnicalKnowledge) WHERE idFreelancer = ?"; const knowledge = await mysqlExecute(sql, [id]); const knowledgeList = knowledge.map((e) => e.title).join(", "); user["knowledge"] = knowledgeList; cb(user); } catch (error) { console.log(error); } } static async updateById(formData) { const { id, name, description, cellphone, email, importantInfo, profilePhoto, curriculum, rut, eps, password, } = formData; let fileContents = {}; // Verificar y procesar los archivos adjuntos if (profilePhoto) { fileContents.profilePhoto = await sharp(profilePhoto) .resize({ width: 800 }) .jpeg({ quality: 80 }) .toBuffer(); } if (curriculum) { fileContents.curriculum = await readFileAsync(curriculum); } if (rut) { fileContents.rut = await readFileAsync(rut); } if (eps) { fileContents.eps = await readFileAsync(eps); } // Consulta SQL para actualizar el perfil let sql = `UPDATE freelancer SET name = ?, description = ?, cellphone = ?, email = ?, importantInfo = ?`; const params = [ name, description, cellphone, email, importantInfo, ]; // Agregar campos de archivos al SQL y parámetros if (profilePhoto) { sql += ", profilePhoto = ?"; params.push(fileContents.profilePhoto); } if (curriculum) { sql += ", curriculum = ?"; params.push(fileContents.curriculum); } if (rut) { sql += ", rut = ?"; params.push(fileContents.rut); } if (eps) { sql += ", eps = ?"; params.push(fileContents.eps); } sql += " WHERE idFreelancer = ?"; params.push(id); try { // Ejecutar la consulta SQL await mysqlExecute(sql, params); // Eliminar archivos temporales if (profilePhoto) { fs.unlink(profilePhoto, (error) => { if (error) { console.error("Error deleting profile photo file:", error); } else { console.log("Profile photo file deleted successfully."); } }); } if (curriculum) { fs.unlink(curriculum, (error) => { if (error) { console.error("Error deleting curriculum file:", error); } else { console.log("Curriculum file deleted successfully."); } }); } if (rut) { fs.unlink(rut, (error) => { if (error) { console.error("Error deleting rut file:", error); } else { console.log("Rut file deleted successfully."); } }); } if (eps) { fs.unlink(eps, (error) => { if (error) { console.error("Error deleting eps file:", error); } else { console.log("Eps file deleted successfully."); } }); } // Actualización de la contraseña si es necesario if (password) { const hashedPassword = hashPassword(password); sql = "UPDATE freelancer SET password = ? WHERE idFreelancer = ?"; await mysqlExecute(sql, [hashedPassword, id]); } console.log("Perfil actualizado correctamente."); } catch (error) { console.error("Error al actualizar el perfil:", error); } } static async logIn(json, cb){ let sql = "SELECT name, idFreelancer idCard, email, idCity, adress, password from freelancer where email = ?"; try{ const response = await mysqlExecute(sql, [ json.email]); if (response.length === 0) { cb({login: false}); } else{ comparePassword(json.password, response[0]["password"], (match)=>{ if(match) { let user = response[0]; user["user"]="1"; user["password"]=null; cb({login : true, user : user}) } else { cb({login: false}); } }); } } catch (error){ console.log(error); } } static async logIn(json, cb) { let sql = "SELECT name, idFreelancer idCard, email, idCity, adress, password from freelancer where email = ?"; try { const response = await mysqlExecute(sql, [json.email]); if (response.length === 0) { cb({ login: false }); } else { comparePassword(json.password, response[0]["password"], (match) => { if (match) { let user = response[0]; user["user"] = "1"; user["password"] = null; cb({ login: true, user: user }); } else { cb({ login: false }); } }); } } catch (error) { console.log(error); } } static async getProfilephotoById(id, cb) { let sql = "select profilePhoto from freelancer where idFreelancer=?"; try { const res = await mysqlExecute(sql, [id]); if (res[0].profilePhoto) { let photo = res[0].profilePhoto.toString("base64"); cb({ profilePhoto: photo, response: true }); } else { cb({ response: false }); } } catch (error) { console.log(error); } } static async progressiveProfiling(json, cb) { const values = [json.tools, json.preferredBrands, json.id]; let sql = "UPDATE freelancer SET tools = ?, preferredBrands = ? WHERE idFreelancer = ?"; try { const res = await mysqlExecute(sql, values); const updatedRows = res.affectedRows; const success = updatedRows > 0; cb({ success }); } catch (error) { console.log(error); cb({ success: false }); } } static async checkPreferences(id, cb) { let sql = "SELECT tools, preferredBrands FROM freelancer WHERE idFreelancer =?"; try { const res = await mysqlExecute(sql, [id]); if(res[0].tools && res[0].preferredBrands){ cb({response: true}); }else{ cb({response: false}); } } catch (error) { console.log(error); } } static async addPreviousWork(formValues, cb) { const { idFreelancer, title, description, date, img } = formValues; let fileContent = {}; try { let sql = `INSERT INTO previouswork (idFreelancer, title, description, date) VALUES (?, ?, ?, ?)`; let params = [idFreelancer, title, description, date]; const res = await mysqlExecute(sql, params); // Obtener el idPreviousWork asignado automáticamente const idPreviousWork = res.insertId; if (img) { fileContent.img = await sharp(img) .resize({ width: 800 }) .jpeg({ quality: 80 }) .toBuffer(); let imgSql = `INSERT INTO imagespw (idPreviousWork, image) VALUES (?, ?)`; let imgParams = [idPreviousWork, fileContent.img]; await mysqlExecute(imgSql, imgParams); if (img) { fs.unlink(img, (error) => { if (error) { console.error("Error deleting profile photo file:", error); } else { console.log("Profile photo file deleted successfully."); } }); } } cb({response: true}); }catch (error) { console.log(error); cb({response: false}); } } static async fetchPortfolio(id, cb) { try { let sql = "SELECT * FROM previouswork WHERE idFreelancer = ?"; const previousWorks = await mysqlExecute(sql, [id]); let portfolio = []; for (let work of previousWorks) { sql = "SELECT image FROM imagespw WHERE idPreviousWork = ?"; const images = await mysqlExecute(sql, [work.idPreviousWork]); let portfolioItem = { idPreviousWork: work.idPreviousWork, title: work.title, description: work.description, date: work.date, img: null }; // Si hay una imagen, convertirla a base64 if (images.length > 0) { const imageBlob = images[0].image; const base64Image = imageBlob.toString('base64'); portfolioItem.img = base64Image; } // Añadir el objeto al array de trabajos previos con imágenes portfolio.push(portfolioItem); } cb(portfolio); } catch (error) { console.log(error); cb(error, null); } } static async editPreviousWork(formValues, cb) { const { idPreviousWork, title, description, date, img } = formValues; let fileContent = {}; try { // Verificar si ya existe una imagen para el trabajo previo let imgSql = `SELECT COUNT(*) AS count FROM imagespw WHERE idPreviousWork = ?`; let imgParams = [idPreviousWork]; let imgResult = await mysqlExecute(imgSql, imgParams); let imgExists = imgResult[0].count > 0; if (imgExists) { // Si existe una imagen, actualizarla fileContent.img = await sharp(img) .resize({ width: 800 }) .jpeg({ quality: 80 }) .toBuffer(); let updateImgSql = `UPDATE imagespw SET image = ? WHERE idPreviousWork = ?`; let updateImgParams = [fileContent.img, idPreviousWork]; await mysqlExecute(updateImgSql, updateImgParams); } else { // Si no existe una imagen, insertarla fileContent.img = await sharp(img) .resize({ width: 800 }) .jpeg({ quality: 80 }) .toBuffer(); let insertImgSql = `INSERT INTO imagespw (idPreviousWork, image) VALUES (?, ?)`; let insertImgParams = [idPreviousWork, fileContent.img]; await mysqlExecute(insertImgSql, insertImgParams); } // Actualizar la información del trabajo previo let sql = `UPDATE previouswork SET title = ?, description = ?, date = ? WHERE idPreviousWork = ?`; let params = [title, description, date, idPreviousWork]; await mysqlExecute(sql, params); cb({ response: true }); } catch (error) { console.error("Error al editar el trabajo previo:", error); cb({ response: false }); } } } module.exports = FreelancerDAO;
package com.codedifferently.lesson9.library; import java.util.List; /** Represents a Marvel comic in the library. */ public class Book { private String title; private String isbn; private List<String> authors; private int numPages; private boolean checkedOut; public Book(String title, String isbn, List<String> authors, int numPages) { this.title = title; this.isbn = isbn; this.authors = authors; this.numPages = numPages; this.checkedOut = false; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public List<String> getAuthors() { return authors; } public void setAuthors(List<String> authors) { this.authors = authors; } public int getNumPages() { return numPages; } public void setNumPages(int numPages) { this.numPages = numPages; } public boolean isCheckedOut() { return checkedOut; } public void setCheckedOut(boolean checkedOut) { this.checkedOut = checkedOut; } }
<template> <div class="flex flex-col md:flex-row"> <div class="main-content flex-1 mt-12 md:mt-2 pb-24 md:pb-5"> <div class="flex flex-row flex-wrap flex-grow mt-2"> <div class="w-full p-3"> <div class="bg-white border-transparent rounded-lg shadow-lg"> <div class="p-5"> <JSCharting :options="options"></JSCharting> </div> </div> </div> </div> </div> </div> </template> <script> import JSCharting from 'jscharting-vue' import moment from 'moment-timezone' export default { name: 'ProjectChart', data () { return { project: this.$attrs.project, options: { debug: false, type: 'horizontal column', zAxisScaleType: 'stacked', yAxis_scale_type: 'time', legend_position: 'bottom', title_label_text: 'Project Beta from %min to %max', yAxis: { markers: this.$attrs.project.transactions.flatMap(transaction => [ { value: moment(new Date(transaction.date)).format('l'), label_text: transaction.transaction_type + ' ' + transaction.amount } ]) }, defaultSeries: { defaultPoint: { legendEntry: { value: '{days(%max-%min):number n0} days' }, tooltip: '<b>%name</b> <br/>%low - %high<br/>{days(%high-%low)} days', marker_type: 'diamond' }, firstPoint: { visible: true, xAxisTick: { label: { text: '<b>%name</b>', style: { fontSize: '14px' } } }, outline: { color: 'darkenMore', width: 3 } } }, series: [] } } }, created () { function toPoints (segment, parent) { var points = [] if (segment.parent_id === null) { console.log(moment(Date(segment.started_date)).format('l')) points = [{ name: segment.name, y: [moment(new Date(segment.started_date)).format('l'), moment(new Date(segment.due_date)).format('l')] }] } else { points = [{ name: parent.name, y: [moment(new Date(parent.started_date)).format('l'), moment(new Date(parent.due_date)).format('l')] }] } if (segment.children) { points.concat([ segment.children.flatMap(s => [ toPoints(s) ]) ]) } return points } this.options.series = this.project.segments.flatMap(segment => [ { name: segment.name, points: toPoints(segment) } ]) }, components: { JSCharting, moment } } </script>
<?php namespace App\Http\Livewire\Admin\User; use App\Models\User; use Illuminate\Support\Facades\Hash; use Livewire\Component; class NewUser extends Component { public $name, $lastname, $email, $matricula, $dni, $password, $password_confirmation; public function render() { return view('livewire.admin.user.new-user'); } public function createUser() { $validatedData = $this->validate([ 'name' => 'required|string|max:255', 'lastname' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'matricula' => ['required_without:dni'], // requerido si no se proporciona el DNI 'dni' => ['required_without:matricula'], // requerido si no se proporciona la matrícula 'password' => 'required|string|min:8|confirmed', ], [ 'name.required' => 'El campo nombre es obligatorio.', 'lastname.required' => 'El campo apellido es obligatorio.', 'email.required' => 'El campo email es obligatorio.', 'email.email' => 'El campo email debe ser una dirección de correo electrónico válida.', ]); $user = User::create([ 'name' => $validatedData['name'], 'lastname' => $validatedData['lastname'], 'email' => $validatedData['email'], 'matricula' => $validatedData['matricula'], 'dni' => $validatedData['dni'], 'password' => Hash::make($validatedData['password']), ]); return redirect()->route('admin.users.index')->with('message', 'Usuario creado correctamente.'); } }
import { Body, Controller, Delete, Get, NotFoundException, Param, Post, Put, Query, } from '@nestjs/common'; import { ApiOperation, ApiTags } from '@nestjs/swagger'; import { QueryLimitDto } from 'src/common/queryLimit.dto'; import { customResponse } from 'src/common/response'; import { EvidenciaDto, ReportadoDto, SearchEvidenceDto, UpdateEvidenciaDto, } from '../../dto/evidencia/evidencia.dto'; import { EvidenciasService } from '../../services/evidencias/evidencias.service'; @ApiTags('Evidencias') @Controller('document/evidencias') export class EvidenciasController { constructor(private readonly evidenciasService: EvidenciasService) {} @Get() @ApiOperation({ summary: 'Obtener todas las evidencias', }) async findAll(@Query() query: QueryLimitDto) { const model = await this.evidenciasService.findAll(query); const total = await this.evidenciasService.count(); return customResponse('Evidencia', model, 200, total); } @Get('/delivery') @ApiOperation({ summary: 'Obtener todas las evidencias por ID de folio y responsable', }) async findOneByFolioAndResponsable(@Query() query: SearchEvidenceDto) { const model = await this.evidenciasService.findOneByFolioAndResponsable(query); return customResponse('Evidencia', model); } @Get('/folio/:id') @ApiOperation({ summary: 'Obtener todas las evidencias por ID de folio', }) async findAllByFolio(@Param('id') id: string) { const model = await this.evidenciasService.findAllByFolio(id); return customResponse('Evidencia', model); } @Get('/:id') @ApiOperation({ summary: 'Obtener una evidencia por ID', }) async findOne(@Param('id') id: string) { const model = await this.evidenciasService.findOne(id); return customResponse('Evidencia', model); } @Post('/reportar') @ApiOperation({ summary: 'Crear un reporte', }) async createReporte(@Body() body: ReportadoDto) { const model = await this.evidenciasService.createReporte(body); return customResponse('Reporte creado', model, 201); } @Post() @ApiOperation({ summary: 'Crear una evidencia', }) async create(@Body() body: EvidenciaDto) { const model = await this.evidenciasService.create(body); return customResponse('Evidencia creada', model, 201); } @Put('/:id') @ApiOperation({ summary: 'Actualizar una evidencia', }) async update(@Param('id') id: string, @Body() body: UpdateEvidenciaDto) { const model = await this.evidenciasService.update(id, body); return customResponse('Evidencia actualizada', model); } @Delete('/:id') @ApiOperation({ summary: 'Eliminar una evidencia', }) async delete(@Param('id') id: string) { const model = await this.evidenciasService.delete(id); if (model) { return customResponse('Evidencia eliminada'); } throw new NotFoundException('Evidencia no encontrada'); } }
/*Develop an object oriented program in C++ to create a database of student information system containing the following information: Name, Roll number, Class, division, Date of Birth, Blood group, Contact address, telephone number, driving license no. and other. Construct the database with suitable member functions for initializing and destroying the data viz constructor, default constructor, Copy constructor, destructor, static member functions, friend class, this pointer, inline code and dynamic memory allocation operators-new and delete. */ include<iostream> #include<string.h> // header file declares a set of functions to work strings. using namespace std; class db { int roll; char name[20]; char Class[10]; char Div[10]; char dob[12]; char bg[5],city[10]; char phone[12],license[12]; public: static int stdno; // declaration of static variable static void count() // defination of static function { cout<<"\n No.of objects created: "<<stdno; } void fin(){cout<<"\nInline Function!";} db() // default constructor { roll=7; strcpy(name,"Sachin"); strcpy(Class,"SE"); strcpy(Div,"A"); strcpy(dob,"13/08/1992"); strcpy(bg,"B+"); strcpy(city,"Pune"); strcpy(phone,"9123456789"); strcpy(license,"A1010"); ++stdno; } void getdata()// defining member function { cout<<"Enter name: "<<endl; cin>>name; cout<<"rollno: "<<endl; cin>>roll; cout<<"Class: "<<endl; cin>>Class; cout<<"Div: "<<endl; cin>>Div; cout<<"DOB: "<<endl; cin>>dob; cout<<"bg: "<<endl; cin>>bg; cout<<"City: "<<endl; cin>>city; cout<<"Phone: "<<endl; cin>>phone; cout<<"license: "<<endl; cin>>license; /cin>>name>>roll>>Class>>Div>>dob>>bg>>city>>phone>>license;/ } friend void display(db d); // declaration of friend function ~db() // destructor { cout<<"\n\n"<<this->name<<"(Object) is destroyed!\n"; } }; void display(db d) // defination of friend function { cout<<"\n Name:"<<d.name; cout<<"\n Roll_No:"<<d.roll; cout<<"\n Class:"<<d.Class; cout<<"\n Div:"<<d.Div; cout<<"\n DOB:"<<d.dob; cout<<"\n Blood group:"<<d.bg; cout<<"\n City:"<<d.city; cout<<"\n Phone_No:"<<d.phone; cout<<" \n License_No:"<<d.license; } int db::stdno; // Define static data member stdno outside the class; int main() { int n,i; db d1,*ptr[5]; cout<<"\nDefault values:"; display(d1); d1.getdata(); display(d1); cout<<"\nHow many objects u want to create?:"; cin>>n; for(i=0;i<n;i++) { ptr[i]=new db(); //new operator use to dynamic memory(run time) allocation ptr[i]->getdata(); } cout<<"\n"<<"name"<<"roll"<<"Class"<<"Div"<<"dob"<<"bg"<<"contact"<<"phone"<<"license"; for(i=0;i<n;i++) display(*ptr[i]); db::count(); // calling of static function for(i=0;i<n;i++) { delete(ptr[i]); //delete operator use to deallocation of memory } cout<<"\nObjects deleted!" ; }
import {Modal} from "react-bootstrap"; import React, {useEffect, useState} from "react"; import CustomButton from "../../../user/components/CustomButton"; import FormFieldError from "../../../global/components/FormFieldError"; import LoadingScreen from "../../../user/components/LoadingScreen"; import AdminProductSizesComp from "../AdminProductSizesComp"; import AdminMultipleImageUpload from "../AdminMultipleImageUpload"; export default function AdminProductUpdateModal({ showUpdateModal, setShowUpdateModal, handleUpdateData, clickedData, categoriesMapped, detailData }) { const [newData, setNewData] = useState({...clickedData}); const [selectedFiles, setSelectedFiles] = useState([]); const [validationErrors, setValidationErrors] = useState({}); //functions returns changed images like, new images, deleted images, order changed images const parseUpdatedImages = (data) => { const newImages = data.new_images; let updatedImages = []; let uploadedFiles = []; let deletedImages = []; newImages.forEach((image, index) => { //files in the database if (image.id !== undefined) { //if order is changed and is_deleted is undefined if (image.order !== data.images.find((file) => file.id === image.id).order && image.is_deleted === undefined) { updatedImages.push(image) } else if (image.is_deleted === true) { //if file is deleted deletedImages.push(image) } } else if (image.is_deleted === undefined) { //id is undefined and is_deleted is undefined //file in format of {order: 0, file: File} //uploaded files are the files that are not in the database uploadedFiles.push(image) } }) return { new_images: uploadedFiles, updated_images: updatedImages, deleted_images: deletedImages }; } const parseUpdatedSizes = (data) => { const groupSizes = data.sizes //group sizes are the sizes that are already in the database const newSizes = data.new_sizes; //new sizes are the sizes that are added by the user let updatedSizes = []; let deletedSizes = []; let addedSizes = []; newSizes.forEach((size, index) => { if (size.id !== undefined) { if (size.is_deleted === true) { deletedSizes.push(size) } else if (size.is_deleted === undefined) { const groundSize = groupSizes.find((groupSize) => groupSize.id === size.id) if (size.value !== groundSize.value || size.quantity !== groundSize.quantity) { //giving old_quantity and quantity values to the updated sizes updatedSizes.push({...size, old_value: groundSize.value, old_quantity: groundSize.quantity}) } } } else if (size.is_deleted === undefined) { addedSizes.push(size) } }) return { new_sizes: addedSizes, updated_sizes: updatedSizes, deleted_sizes: deletedSizes } } const handleOnClick = async ({event, data}) => { event.preventDefault(); const images = parseUpdatedImages(data); const sizes = parseUpdatedSizes(data); handleUpdateData({newData: {...newData, images, sizes}, setValidationErrors}) } useEffect(() => { setNewData({...clickedData}) }, [clickedData]); useEffect(() => { const localForm = []; selectedFiles.forEach((file, index) => { localForm.push(file); }); setNewData({...newData, new_images: localForm}); }, [selectedFiles]); useEffect(() => { if (detailData.isLoaded) { setNewData({ ...newData, images: detailData?.images || [], sizes: detailData?.sizes ? [...detailData?.sizes.map((size) => { return {...size} })] : [], new_sizes: detailData?.sizes ? [...detailData?.sizes] : [], description: detailData?.description || '', }) setSelectedFiles(detailData?.images || []) } }, [detailData.isLoaded]); useEffect(() => { if (Object.keys(newData).length === 0 || newData === clickedData) { return; } if (Object.keys(validationErrors).length === 0) { setShowUpdateModal(false); //setNewData({}); } }, [validationErrors]) return ( <> <Modal show={showUpdateModal} onHide={() => { setShowUpdateModal(false); setValidationErrors({}) }} className={"modal-lg"} > <Modal.Header closeButton> <Modal.Title>Ürün Güncelle</Modal.Title> </Modal.Header> <Modal.Body> {!detailData.isLoaded ? (<LoadingScreen></LoadingScreen>) : <div className="container"> <div className="row"> <div className="col"> <div className="col-sm-3">Ürün Adı</div> <div className=""> <input type="text" className={"form-control " + (validationErrors.title ? "is-invalid" : "")} id="name" value={newData?.title || ''} onChange={(e) => { setNewData({...newData, title: e.target.value}) }} /> <FormFieldError errorMessage={validationErrors.title}/> </div> </div> <div className="col"> <div className="col-sm-3">Kategori</div> <div className=""> <select className={"form-control " + (validationErrors.category_id ? "is-invalid" : "")} onChange={(e) => { setNewData({...newData, category_id: e.target.value}) }} > <option value={-1}>Kategori Seç</option> {categoriesMapped.map((category, index) => ( <option value={category.id} selected={category.id === newData?.category_id} >{category.title}</option> ))} </select> <FormFieldError errorMessage={validationErrors.category_id}/> </div> </div> </div> <br/> <div className="row"> <div className="col"> <div className="">Eski Fiyat</div> <div className=""> <input type="text" className={"form-control " + (validationErrors.old_price ? "is-invalid" : "")} id="name" value={newData?.old_price || ''} onChange={(e) => { setNewData({...newData, old_price: e.target.value}) }} /> <FormFieldError errorMessage={validationErrors.old_price}/> </div> </div> <div className="col"> <div className="">Yeni Fiyat</div> <div className=""> <input type="text" className={"form-control " + (validationErrors.new_price ? "is-invalid" : "")} id="name" value={newData?.new_price || ''} onChange={(e) => { setNewData({...newData, new_price: e.target.value}) }} /> <FormFieldError errorMessage={validationErrors.new_price}/> </div> </div> <div className="col"> <div className="">İndirim Oranı</div> <div className=""> <input type="number" className="form-control" id="discount_product" value={(((newData?.old_price - newData?.new_price) / newData?.old_price) * 100).toFixed(2) || 0} onChange={(e) => { const percent = e.target.value setNewData({ ...newData, new_price: newData.old_price - (newData.old_price * percent / 100) }) }} /> </div> </div> </div> <br/> <div className="row"> <div className="col"> <div className="col-sm-3">Açıklama</div> <div className=""> <textarea className={"form-control " + (validationErrors.description ? "is-invalid" : "")} id="name" value={newData?.description || ''} onChange={(e) => { setNewData({...newData, description: e.target.value}) }} /> <FormFieldError errorMessage={validationErrors.description}/> </div> </div> </div> <br/> <AdminProductSizesComp validationErrors={validationErrors} newData={newData} setNewData={setNewData} /> <br/> <AdminMultipleImageUpload validationErrors={validationErrors} selectedFiles={selectedFiles} setSelectedFiles={setSelectedFiles} /> </div> } </Modal.Body> <Modal.Footer> <CustomButton text="Kapat" onClick={() => { setShowUpdateModal(false); setValidationErrors({}) }} /> <CustomButton text="Kaydet" status="success" onClick={async (event) => { await handleOnClick({event, data: newData}); }} /> </Modal.Footer> </Modal> </> ); }
:toc: macro toc::[] :doctype: book :reproducible: :source-highlighter: rouge :listing-caption: Listing == Integrating Spring Data in OASP4J === Introduction This chapter specifies a possible solution for integrating the Spring Data module in devonfw. It is possible to have some services using the Spring Data module while some services use JPA/Hibernate. To integrate Spring Data in devonfw, there can be two approaches as stated below: . Create a new module for spring data . Integrate Spring Data in an existing core project The more feasible approach will be option 2 i.e to integrate it into an existing core project instead of creating a new module. Below are the reasons for not preferring a creation of a different module supporting spring data: * It does not follow KISS (Keep it simple, stupid) principle. In the existing structure of sample application, Entity classes along with some abstract implementation classes are included in oasp4j-samples-core project. You need to refer these classes while implementing spring-data. If you try to refer it in different module, it will become complex to compare it to the first approach. * If you integrate Spring Data in oasp4j, you need to annotate SpringBootApp.java class with @Enablejparepositories. If you create a different module, it will not be possible, as SpringBootApp class is in the core module. === Existing Structure of Data Access Layer Consider TableEntity as an example. image::images/Integrating-Spring-Data/Existing_Dataaccess_Structure.JPG[, width="450", link="images/Integrating-Spring-Data/Existing_Dataaccess_Structure.JPG"] image::images/Integrating-Spring-Data/TableDaoImpl_Structure.JPG[, width="450", link="images/Integrating-Spring-Data/TableDaoImpl_Structure.JPG"] === Structure of Data Access Layer with Spring Data image::images/Integrating-Spring-Data/Structure_With_Spring_Data.JPG[, width="450", link="images/Integrating-Spring-Data/Structure_With_Spring_Data.JPG"] Below are the steps, to integrate Spring Data in the data access layer: * Add dependency for Spring Data in pom.xml of oasp4j-samples-core project [source,xml] -------- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> -------- * Create Spring data Repository - Create interface which extends spring data repositories such as CRUDRepository or PagingAndSortingRepository and annotate it with @Repository annotation. Spring data have repositories such as CRUDRepository which provide the default CRUD functionality. [source,java] -------- @Repository Public interface TableRepo extends CrudRepository<TableEntity, Serializable>{ } -------- * Create the class, annotate it with @Component annotation and autowire spring data repository created above. [source,java] -------- @Component public class RegistrationBean { @Inject private TableRepo tableRepo; /** * The constructor. */ public RegistrationBean() { } /** * @return tableRepo */ public TableRepo getTableRepo() { return this.tableRepo; } /** * @param tableRepo the tableRepo to set */ public void setTableRepo(TableRepo tableRepo) { this.tableRepo = tableRepo; } } -------- * Here, you are ready to test the functionality. Create a test class to test above changes. [source,java] -------- @SpringApplicationConfiguration(classes = { SpringBootApp.class }) @WebAppConfiguration @EnableJpaRepositories(basePackages = { "io.oasp.gastronomy.restaurant.tablemanagement.dataaccess.api.repo" }) @ComponentScan(basePackages = { "io.oasp.gastronomy.restaurant.tablemanagement.dataaccess.api.dao" }) public class TestClass extends ComponentTest { @Inject RegistrationBean registrationBean; /** * @return registerationBean */ public RegistrationBean getRegisterationBean() { return this.registrationBean; } /** * @param registerationBean the registerationBean to set */ public void setRegisterationBean(RegistrationBean registerationBean) { this.registrationBean = registerationBean; } /** * @param args */ @Test public void saveTable() { TableEntity table = new TableEntity(); table.setId(106L); table.setModificationCounter(1); table.setNumber(6L); table.setState(TableState.FREE); table.setWaiterId(2L); System.out .println("TableRepo instance *************************************************** " + getRegisterationBean()); TableEntity entity = getRegisterationBean().getTableRepo().save(table); System.out.println("entity id " + entity); } } -------- Note: If you get DataIntegrityViolationExceptions while saving an object in a database, modify the script to auto_increment column id. The database should be able to auto increment column id as you have @GeneratedValue annotation in ApplicationPersistenceEntity. * Modify SpringBootApp.java class to scan the JPA repositories. [source,java] -------- @SpringBootApplication(exclude = { EndpointAutoConfiguration.class }) @EntityScan(basePackages = { "io.oasp.gastronomy.restaurant" }, basePackageClasses = { AdvancedRevisionEntity.class }) @EnableGlobalMethodSecurity(securedEnabled = true) public class SpringBootApp { /** * Entry point for spring-boot based app * * @param args - arguments */ public static void main(String[] args) { SpringApplication.run(SpringBootApp.class, args); } } -------- The above example shows how you can implement default functionalities. If you want to add custom functionalities, then you need to add custom repository and provide its implementation class. Also, you need to modify TableRepo to extend the custom repository. Below are the steps. Make note that, this is in continuation with previous example: Add custom repository as below in a repo package itself: [source,java] -------- public interface TableRepoCustom { /** * @param number * @return */ List<TableEntity> findByTableState(int number); } -------- * Create an implementation class for the above custom repository in a repo package itself. You have not annotated repository with any annotation, still Spring data will consider it as a custom repository. This is because spring data scan the repository package to search for any class and if it found one, then spring data consider it as a custom repository. [source,java] -------- public class TableRepoImpl implements TableRepoCustom { @PersistenceContext private EntityManager entityManager; /** * {@inheritDoc} */ @Override public List<TableEntity> findByTableState(int state) { String query = "select table from TableEntity table where table.state= " + state; System.out.println("Query " + query); List<TableEntity> tableList = this.entityManager.createQuery(query).getResultList(); return tableList; } } -------- * Modify test class to include above functionality [source,java] -------- @SpringApplicationConfiguration(classes = { SpringBootApp.class }) @WebAppConfiguration @EnableJpaRepositories(basePackages = { "io.oasp.gastronomy.restaurant.tablemanagement.dataaccess.api.repo" }) @ComponentScan(basePackages = { "io.oasp.gastronomy.restaurant.tablemanagement.dataaccess.api.dao" }) public class TestClass extends ComponentTest { @Inject RegistrationBean registrationBean; /** * @return registerationBean */ public RegistrationBean getRegisterationBean() { return this.registrationBean; } /** * @param registerationBean the registerationBean to set */ public void setRegisterationBean(RegistrationBean registerationBean) { this.registrationBean = registerationBean; } /** * @param args */ @Test public void saveTable() { TableEntity table = new TableEntity(); table.setId(106L); table.setModificationCounter(1); table.setNumber(6L); table.setState(TableState.FREE); table.setWaiterId(2L); System.out .println("TableRepo instance *************************************************** " + getRegisterationBean()); TableEntity entity = getRegisterationBean().getTableRepo().save(table); System.out.println("entity id " + entity); } @Test public void testFindByTableState() { List<TableEntity> tableList = getRegisterationBean().getTableRepoImpl().findByTableState(0); System.out.println("tableList size ***************************** " + tableList.size()); } } -------- With custom repository, you can implement functionality such as getrevisionHistory(). Additionally, spring data support @Query annotatio and derived query. Here, samples are attached for 2 entities (DrinkEntity, TableEntity) which are later implemented with spring data. === Query Creation in Spring Data JPA Below are the ways to create a query in Spring Data JPA: * Query creation by method names: List<User> findByEmailAddressAndLastname(String emailAddress, String lastname); Above method is equivalent to the below query: select u from User u where u.emailAddress = ?1 and u.lastname = ?2 This is explained in the next section. * Using JPA Named Queries Example: @NamedQuery(name = "Drink.nonalcholic", query = "select drink from DrinkEntity drink where drink.alcoholic=false") * Using @Query annotation [source,java] -------- @Query(name = "table.query1", value = "select table from TableEntity table where table.state= :#{#criteria.state}") public Page<TableEntity> findTablesDummy(@Param("criteria") TableSearchCriteriaTo criteria, Pageable pageable); -------- Include above method in repository i.e TableRepo. * Native Queries - This Queries can be created using @Query annotation and setting nativeQuery=true * Similar to the criteria, you have Predicate from QueryDsl. This is explained in below section. === Query creation by method names Consider tablemanagement as an example. First, you will create a TableEntity class with attribute number, waiterId and state. To test query creation by method names, you will create new method findByState(TableState state) in TableRepo. This method will find table based on TableState provided. Follow below steps: * Create TableEntity class as below: [source,java] -------- @Entity // Table is a reserved word in SQL/RDBMS and can not be used as table name @javax.persistence.Table(name = "RestaurantTable") public class TableEntity extends ApplicationPersistenceEntity implements Table { private static final long serialVersionUID = 1L; private Long number; private Long waiterId; private TableState state; @Override @Column(unique = true) public Long getNumber() { return this.number; } @Override public void setNumber(Long number) { this.number = number; } @Override @Column(name = "waiter_id") public Long getWaiterId() { return this.waiterId; } @Override public void setWaiterId(Long waiterId) { this.waiterId = waiterId; } @Override public TableState getState() { return this.state; } @Override public void setState(TableState state) { this.state = state; } } -------- * In TableRepo create findByState(TableState state) method as below: [source,java] -------- @Repository public interface TableRepo extends JpaRepository<TableEntity, Long>, TableRepoCustom { // Query Creation By method names List<TableEntity> findByState(TableState state); } -------- * You will have RegistrationBean class as shown in the previous example. Now, you are ready to test the method findByState(TableState state). In test class, include below test method: [source,java] -------- @Test public void testFindTableByState() { List<TableEntity> tableList = getRegisterationBean().getTableRepo().findByState(TableState.FREE); System.out.println("tableList size " + tableList.size()); } -------- === Implementing Query with QueryDsl Like the JPA Criteria API, it uses a Java 6 annotation processor to generate meta-model objects and produces a much more approachable API. Another good thing about the project is that, it not only has the support for JPA but also allows querying Hibernate, JDO, Lucene, JDBC and even plain collections. * To start with QueryDsl add below plugin in a pom.xml: [source,java] -------- <plugin> <groupId>com.mysema.maven</groupId> <artifactId>apt-maven-plugin</artifactId> <version>1.1.1</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>process</goal> </goals> <configuration> <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> </plugin> -------- * Execute _mvn clean install_ on the project. This will create special query classes e.g for DrinkEntity class generated will be QDrinkEntity. * To execute Querydsl predicates, you simply let your repository extend QueryDslPredicateExecutor<T> Example: [source,java] -------- @Repository public interface DrinkRepo extends JpaRepository<DrinkEntity, Long>, QueryDslPredicateExecutor<DrinkEntity>, DrinkRepoCustom { /** * {@inheritDoc} */ @Override <S extends DrinkEntity> S save(S entity); } -------- * You will have registrationBean class, which have above repository autowired in it. * Create test class and below method. [source,java] -------- @Test public void testFindNonAlcoholicDrinks() { QDrinkEntity drinkEntityEqu = QDrinkEntity.drinkEntity; BooleanExpression drink = drinkEntityEqu.alcoholic.isFalse(); List<DrinkEntity> drinkList = (List<DrinkEntity>) getDrinkEntityRegistrationBean().getDrinkRepo().findAll(drink); for (DrinkEntity drink1 : drinkList) { System.out.println("drink id " + drink1.getId() + " description: " + drink1.getDescription()); } } -------- This will return list of drink entities which are nonalcoholic. === Paging and Sorting Support * For Paging and Sorting support in Spring Data JPA, you should implement PagingAndSortingRepository. Create an interface as shown below: [source,java] -------- @Repository public interface TableRepo extends JpaRepository<TableEntity, Long>, TableRepoCustom { /** * {@inheritDoc} */ @Override <S extends TableEntity> S save(S table); TableEntity findByNumber(long number); /** * {@inheritDoc} */ @Override Page<TableEntity> findAll(Pageable pageable); @Query(name = "table.query", value = "select table from TableEntity table where table.state= ?1") Page<TableEntity> findByTableState1(TableState state, Pageable pageable); } -------- * Create test method as below: [source,java] -------- @Test public void testFindTableByState1() { PageRequest pageRequest = new PageRequest(0, 2, Direction.DESC, "state"); Page<TableEntity> pageEntity = getRegisterationBean().getTableRepo().findByTableState1(TableState.FREE, pageRequest); List<TableEntity> tableList = pageEntity.getContent(); for (TableEntity table : tableList) { System.out.println("Table details: " + table.getId() + " , " + table.getWaiterId() + " , " + table.getState()); } } -------- In the above example, you are extending JpaRepository which in turn extends PagingAndSortingRepository. So, you will get paging and sorting functionality. For Paging and Sorting support, you need to pass Pageable as method Parameter. [source,java] -------- PageRequest pageRequest = new PageRequest(0, 2, Direction.DESC, "state"); //Here 0 - indicate page number. //2 - object on a page //Direction Desc or ASC- Sorting sequence Desc or Asc //State - this is a property based on which query gets sorted -------- For creating pageRequest object, you have different constructors available as below: [source,java] -------- PageRequest(int page,int size) PageRequest(int page,int size,int sort) PageRequest(int page,int size,Direction direction) PageRequest(int page, int size, Direction direction, String... properties) -------- === References https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/ http://docs.spring.io/spring-data/jpa/docs/1.4.1.RELEASE/reference/html/jpa.repositories.html http://javabeat.net/spring-data-jpa-querydsl-integration/
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing; using MedicalClinicApp.DatabaseHandler; using MedicalClinicApp.Repositories.Classes; using MedicalClinicApp.Repositories.Interfaces; using MedicalClinicApp.Services.Classes; using MedicalClinicApp.Services.Interfaces; using Microsoft.EntityFrameworkCore; namespace MedicalClinicApp { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Database connection builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("connectionString"))); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // Dependency Injection builder.Services.AddScoped<IPatientRepository, PatientRepository>(); builder.Services.AddScoped<IPatientSortRepository, PatientSortRepository>(); builder.Services.AddScoped<IPatientSearchRepository, PatientSearchRepository>(); builder.Services.AddScoped<IPatientExportService, PatientExportService>(); // CORS policy builder.Services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("http://localhost:3000") .AllowAnyMethod() .AllowAnyHeader()); }); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); // Using CORS policy app.UseCors("AllowSpecificOrigin"); app.MapControllers(); app.Run(); } } }