text
stringlengths
184
4.48M
// var realAge = 30; // let person = { // name: "cheems", // surname: "doge", // realAge: "12", // normalAge: function () { // // console.log("this in normal is", this); // console.log(`doge is ${this.realAge} years old `); // }, // /** // * the difference between normal and arrow fucntion is that the pointer to this keyword pints to global obect in arrowAge // * function // * // * but in cause the this keyword is pointed to the scope // */ // // arrow function // arrowAge: () => { // console.log("this in arrow is ", this); // console.log(`doge is ${this.realAge} years old `); // }, // }; // // console.log("this is ", this, global); // // person.normalAge(); // // person.arrowAge(); // const anObject = { // aValue: "example value", // aMethod: function () { // console.log("aMethod", this.aValue); // const arrow = () => { // console.log("arrow", this.aValue); // }; // //arrow(); // }, // }; // // anObject.aMethod(); // const copyOfAMethod = anObject.aMethod; // copyOfAMethod(); // let Person = function (name) { // this.name = name; // this.normal = function () { // console.log("HEY THERE FROM ", this.name); // }; // this.abNormal = () => { // console.log("HEY THERE FROM ABORNAL ", this.name); // }; // }; // let dave = new Person("dave"); // let mac = new Person("Mac"); // // here in case of arrow function it will always point to the object initialized and wont change the poinitng // dave.normal(); // dave.abNormal(); // dave.normal.call(mac); // dave.abNormal.call(mac); // dave.normal.apply(mac); // dave.abNormal.apply(mac); // dave.normal.bind(mac)(); // dave.abNormal.bind(mac)(); function add(a, b, c) { console.log("haha curryied", a + b + c); return a + b + c; } add(10, 20, 30); function curriedAdd(a) { return function (b) { return function (c) { console.log("haha curryied", a + b + c); return a + b + c; }; }; } curriedAdd(10)(20)(30);
import React, { useState, useEffect } from 'react'; import Backdrop from '@mui/material/Backdrop'; import Box from '@mui/material/Box'; import Modal from '@mui/material/Modal'; import Fade from '@mui/material/Fade'; import Button from '@mui/material/Button'; import YouTubeIcon from '@mui/icons-material/YouTube'; // import Typography from '@mui/material/Typography'; import './ContentModal.css'; import axios from 'axios'; import { img_500, unavailable } from '../../Config/config'; const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: "70%", height: "500px", bgcolor: 'background.paper', border: '2px solid #000', boxShadow: 24, overflowY:"scroll", p: 4, '&::-webkit-scrollbar': { display: "none" } }; export default function ContentModal({ children, media_type, id }) { const [open, setOpen] = React.useState(false); const [content, setContent] = useState(); const [video, setVideo] = useState(); const handleOpen = () => setOpen(true); const handleClose = () => setOpen(false); const getData = async () => { const { data } = await axios.get(`https://api.themoviedb.org/3/${media_type}/${id}?api_key=${process.env.REACT_APP_API_KEY}&language=en-US`); setContent(data); // console.log("data",data); } const getVideo = async () => { const { data } = await axios.get(`https://api.themoviedb.org/3/${media_type}/${id}/videos?api_key=${process.env.REACT_APP_API_KEY}&language=en-US`); // console.log(data); setVideo(data.results[0]?.key); } useEffect(() => { getData(); getVideo(); //eslint-disable-next-line }, []); return ( <div> <div className="media" onClick={handleOpen}> {children} </div> <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" open={open} onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <Box sx={style}> {/* <Typography id="transition-modal-title" variant="h6" component="h2"> Text in a modal </Typography> <Typography id="transition-modal-description" sx={{ mt: 2 }}> Duis mollis, est non commodo luctus, nisi erat porttitor ligula. </Typography> */} { content && (<div > <div className="ContentModal"> <img className='ContentModal_portrait' alt={content.name || content.title} src={content.poster_path ? `${img_500}/${content.poster_path}` : unavailable} /> <img className='ContentModal_landscape' alt={content.name || content.title} src={content.backdrop_path ? `${img_500}/${content.backdrop_path}` : unavailable} /> <div className="ContentModal_about"> <span className="ContentModal_title"> {content.name || content.title} ( {( content.first_air_date || content.release_date || "-------" ).substring(0, 7)} ) </span> <br /> {content.tagline && ( <i className='tagline'>{content.tagline}</i> )} <br /> <span className="ContentModal_description"> {content.overview} </span> <div></div> <Button variant="contained" startIcon={<YouTubeIcon />} color="error" target="_blank" href={`https://www.youtube.com/watch?v=${video}`} > WATCH thE TRAILER </Button> </div> </div> </div> ) } </Box> </Fade> </Modal> </div> ); }
install.packages("CausalImpact") install.packages('tidyr') install.packages('lubridate') library(CausalImpact) library(tidyr) library(dplyr) library(lubridate) setwd('C:/Users/dmz38/Downloads/1654157067295-데멘토_지원신청서_및_개인정보활용동의서') # 2018-03을 시작으로 월을 기준으로 2022-05-01까지의 Date형태의 변수 생성 time.points <- seq.Date(as.Date('2018-03-01'),by='month', length.out = 52) str(time.points) # 코로나 영향을 받기전과 코로나 영향을 받고 난뒤의 날짜를 분리 지정 pre.period <- as.Date(c("2018-03-01", "2020-01-01")) post.period <- as.Date(c("2020-02-01", "2022-05-01")) # 지역별 제곱미터당 권리금(이상치 제거) df11 <- read.csv('제곱 권리금(이상치).csv') df11 df_11 <- df11[,c(2:17)] # 날짜 컬럼을 제외한 사용할 컬럼 추출 df_1_9 <- zoo(df_11, time.points) # 예측할 데이터와 Date 변수 합치기 impact <- CausalImpact(df_1_9, pre.period, post.period) # causalimpact 실행 plot(impact) summary(impact) # 지역별 권리금(이상치 제거) df12 <- read.csv('지역별 권리금(이상치).csv') df12 df_12 <- df12[,c(2:17)] df_1_10 <- zoo(df_12, time.points) impact <- CausalImpact(df_1_10, pre.period, post.period) plot(impact) summary(impact) # 지역별 유동인구(이상치 제거) df14 <- read.csv('지역별 유동인구(이상치).csv') df14 df_14 <- df14[,c(2:17)] df_1_12 <- zoo(df_14, time.points) impact <- CausalImpact(df_1_12, pre.period, post.period) plot(impact) summary(impact) # 업종별 제곱미터당 권리금 df15 <- read.csv('업종별 제곱 지원금(이상치).csv') df15 df_15 <- df15[,c(2:9)] df_1_13 <- zoo(df_15, time.points) impact <- CausalImpact(df_1_13, pre.period, post.period) plot(impact) summary(impact) # 업종별 권리금(이상치) df16 <- read.csv('업종별 권리금(이상치).csv') df16 df_16 <- df16[,c(2:9)] df_1_14 <- zoo(df_16, time.points) impact <- CausalImpact(df_1_14, pre.period, post.period) plot(impact) summary(impact) # 업종별 매매가(이상치) df17 <- read.csv('업종별 매매가(이상치).csv') df_17 <- df17[,c(2:9)] df_1_15 <- zoo(df_17, time.points) impact <- CausalImpact(df_1_15, pre.period, post.period) plot(impact) summary(impact)
using System.Text; using gettmail_final.services.acctSession; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.WebUtilities; using Microsoft.EntityFrameworkCore; using RandomStringCreator; public class RegisterController : Controller { private readonly UserManager<AppUser> _userManager; private readonly ApplicationDbContext _db; private readonly ILogger<RegisterController> _log; private readonly IEmailSender _emailSender; private readonly SignInManager<AppUser> _signinManager; public RegisterController(UserManager<AppUser> manager, SignInManager<AppUser> signinManager, ApplicationDbContext db, ILogger<RegisterController> log, IEmailSender emailSender, SignInManager<AppUser> signin) { _userManager = manager; _db = db; _log = log; _emailSender = emailSender; _signinManager = signin; } public async Task<IActionResult> Index() { AccountSession acctSession = new AccountSession(); AppUser? userData = await acctSession.IsUserSignedIn(User, _signinManager, _userManager); if (userData != null) { return Redirect("/account"); } else { RegisterViewModel viewM = new RegisterViewModel(userData); return View(viewM); } } [HttpPost] public async Task<IActionResult> Index(RegisterFormModel form) { if (!ModelState.IsValid) { TempData["status"] = "error"; TempData["message"] = "Form invalid"; return View(new RegisterViewModel(null)); } try { AccountSession acctSession = new AccountSession(); AppUser? userData = await acctSession.IsUserSignedIn(User, _signinManager, _userManager); //see if email is already confirmed in database var emailsInUse = await _db.Users.Where(u => u.Email == form.Email.Trim()).ToArrayAsync(); if (emailsInUse.Length > 0) { foreach (var x in emailsInUse) { if (x.EmailConfirmed) { TempData["status"] = "error"; TempData["message"] = "Email already in use"; return View(new RegisterViewModel(null)); } } } //generate unqiue api key bool l = true; string apiKey = ""; while (l) { string key = new StringCreator().Get(20); bool exists = await _db.Users.AnyAsync(u => u.ApiKey == key); if (!exists) { l = false; apiKey = key; } } AppUser newUser = new AppUser { UserName = form.Username.Trim(), Email = form.Email.Trim(), AccountCreatedOn = DateTime.Now.ToUniversalTime(), ApiKey = apiKey, RemainingApiCalls = 100 //default value }; var newUserResult = await _userManager.CreateAsync(newUser, form.Password.Trim()); if (!newUserResult.Succeeded) { TempData["status"] = "error"; TempData["message"] = "There was an error while creating new user"; return View(new RegisterViewModel(null)); } var userId = await _userManager.GetUserIdAsync(newUser); var code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Action("ConfirmEmail", "Register", new { userId = userId, code = code, returnUrl = "/register/confirmemail" }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(form.Email.Trim(), "Confirm your account", $"Please confirm your account by clicking this link - {callbackUrl}"); TempData["status"] = "success"; TempData["message"] = "A confirmation email was sent to your inbox"; return View(new RegisterViewModel(null)); } catch (Exception ex) { TempData["status"] = "error"; TempData["message"] = ex.ToString(); return View(new RegisterViewModel(null)); } } [HttpGet] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return RedirectToPage("/register"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return NotFound($"Unable to load user with ID '{userId}'."); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await _userManager.ConfirmEmailAsync(user, code); if (!result.Succeeded) { TempData["message"] = "Error while confirming account"; return View(new RegisterViewModel(null)); } //if there are any email addresses that match the one just confirmed //delete from database //...this will prevent error while user is attempting to log in and linq query finds //multiple records with same email address (throws error, wont let user log in) var sameEmailAddresses = _db.Users.Where(e => e.Email == user.Email && !e.EmailConfirmed); if (sameEmailAddresses.Any()) { _db.RemoveRange(sameEmailAddresses); await _db.SaveChangesAsync(); } TempData["message"] = "Successfully confirmed account!"; await _signinManager.SignInAsync(user, true); return View(new RegisterViewModel(new AppUser())); } }
import { Entity, Column, PrimaryGeneratedColumn, BeforeInsert, BeforeUpdate, AfterLoad, } from "typeorm"; import {IsEmail, IsOptional} from "class-validator"; import { hashSync } from "bcrypt"; import {JoinTable, ManyToMany, OneToMany} from "typeorm/index"; import {Team} from "./Team"; import {Goal} from "./Goal"; import {UserGoal} from "./UserGoal"; @Entity({ name: "usuario" }) export class User { @PrimaryGeneratedColumn("increment", { name: "ID" }) id: number; @Column({ name: "nome" }) name: string; @Column({ name: "sobrenome" }) lastName: string; @Column({ unique: true, name: "email" }) @IsEmail() email: string; @Column({ name: "matricula" }) registration: string; @Column({ name: "senha" }) password: string; @Column({ name: "admin", default: false }) admin: boolean; @ManyToMany(() => Team, (team) => team.users) @JoinTable({ name: "usuario_turma", joinColumn: { name: "usuario_id", }, inverseJoinColumn: { name: "turma_id", }, }) @IsOptional() teams?: Team[]; @AfterLoad() loadTempPassword() { this.tempPassword = this.password; } @BeforeInsert() @BeforeUpdate() hashPassword() { if (this.password !== this.tempPassword) this.password = hashSync(this.password, 8); } @OneToMany(() => UserGoal, (userGoal) => userGoal.user) public userGoal?: UserGoal; public token?: string; public tempPassword?: string; }
library(lubridate) library(stringr) library(tidyverse) library(ggplot2) library(viridis) library(geojsonio) library(RColorBrewer) library(rgdal) incidents <- read.csv("./inputs/incidents_state.txt") states <- read.csv("./inputs/wildfire_states.txt") incidents$FireDiscov <- mdy(word(incidents$FireDiscov,1)) incidents$year <- year(incidents$FireDiscov) #5 years 2018 to 2022 incidents <- incidents%>%filter(year >= 2018 & year < 2023 ) #merge state incidents$POOFips <- floor(incidents$POOFips/1000) #summarize by year and state incidents_year_state <- incidents%>% group_by(year,POOFips)%>% summarise(n = n()) incidents_year_state <- incidents_year_state[!is.na(incidents_year_state$POOFips),] incidents_year_state <- incidents_year_state%>% group_by(POOFips)%>% summarise(avg = mean(n)) incidents_year_state <- incidents_year_state%>% left_join(.,states,by = c("POOFips" = "STATEFP")) spdf <- geojson_read("inputs/us_states_hexgrid.geojson", what = "sp") spdf@data = spdf@data %>% mutate(google_name = gsub(" \\(United States\\)", "", google_name)) plot(spdf) # I need to 'fortify' the data to be able to show it with ggplot2 (we need a data frame format) library(broom) spdf@data = spdf@data %>% mutate(google_name = gsub(" \\(United States\\)", "", google_name)) spdf_fortified <- tidy(spdf, region = "google_name") spdf_fortified <- spdf_fortified%>%filter(!id %in% c("Alaska","Hawaii")) # Calculate the centroid of each hexagon to add the label: library(rgeos) centers <- cbind.data.frame(data.frame(gCentroid(spdf, byid=TRUE), id=spdf@data$iso3166_2)) # Now I can plot this shape easily as described before: ggplot() + geom_polygon(data = spdf_fortified, aes( x = long, y = lat, group = group), fill="skyblue", color="white") + geom_text(data=centers, aes(x=x, y=y, label=id)) + theme_void() + coord_map() # Merge geospatial and numerical information spdf_fortified <- spdf_fortified %>% left_join(. , states, by=c("id"="NAME")) # Make a first chloropleth map ggplot() + geom_polygon(data = spdf_fortified, aes(fill = Join_Count, x = long, y = lat, group = group)) + scale_fill_gradient(trans = "log") + theme_void() + coord_map() ##hexbin map # Prepare binning spdf_fortified$Join_Count[is.na(spdf_fortified$Join_Count)] <- 0 spdf_fortified$bin <- cut(spdf_fortified$Join_Count , breaks=c(0,1,5,10,50,100,200, Inf), labels=c("0-1", "1-5","5-10","10-50","50-100", "100-200","200+" ), include.lowest = TRUE ) # Prepare a color scale coming from the viridis color palette library(viridis) my_palette <- rev(magma(8))[c(-1,-9)] # plot png("./outputs/hexbin.png", width = 5, height = 5, units="in",res = 1200) ggplot() + geom_polygon(data = spdf_fortified, aes(fill = bin, x = long, y = lat, group = group) , size=0, alpha=0.9) + geom_text(data=centers, aes(x=x, y=y, label=id), color="white", size=3, alpha=0.6) + theme_void() + scale_fill_manual( values=my_palette, name="Total large wildfire incidents, by state (2011-2020)", guide = guide_legend( keyheight = unit(2.5, units = "mm"), keywidth=unit(8, units = "mm"), label.position = "bottom", title.position = 'top', nrow=1) ) + ggtitle( "" ) + theme( legend.position = c(0.5, 0.95), text = element_text(color = "#22211d"), plot.background = element_rect(fill = "#f5f5f2", color = NA), panel.background = element_rect(fill = "#f5f5f2", color = NA), legend.background = element_rect(fill = "#f5f5f2", color = NA), plot.title = element_text(size= 17, hjust=0.5, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")), ) dev.off() rm(spdf,spdf_fortified,my_palette,centers)
--- title: Kapitel 9. Einen FreeBSD-Kernel bauen und installieren prev: books/developers-handbook/partiii next: books/developers-handbook/kerneldebug showBookMenu: true weight: 12 path: "/books/developers-handbook/" --- [[kernelbuild]] = Einen FreeBSD-Kernel bauen und installieren :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 9 :partnums: :source-highlighter: rouge :experimental: :images-path: books/developers-handbook/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] Ein Kernelentwickler muss wissen, wie der Bau eines angepassten Kernels funktioniert, da das Debuggen des FreeBSD-Kernels nur durch den Bau eines neuen Kernels möglich ist. Es gibt zwei Wege, einen angepassten Kernel zu bauen: * Den "traditionellen" Weg * Den "neuen" Weg [NOTE] ==== Die folgenden Ausführungen setzen voraus, dass Sie den Abschnitt extref:{handbook}kernelconfig/[Erstellen und Installation eines angepassten Kernels, kernelconfig-building] des FreeBSD-Handbuchs gelesen haben und daher wissen, wie man einen FreeBSD-Kernel baut. ==== [[kernelbuild-traditional]] == Einen Kernel auf die "traditionelle" Art und Weise bauen Bis FreeBSD 4.X wurde dieser Weg zum Bau eines angepassten Kernels empfohlen. Sie können Ihren Kernel nach wie vor auf diese Art und Weise bauen (anstatt das Target "buildkernel" der Makefiles im Verzeichnis [.filename]#/usr/src/# zu verwenden). Dies kann beispielsweise sinnvoll sein, wenn Sie am Kernel-Quellcode arbeiten. Haben Sie nur ein oder zwei Optionen der Kernelkonfigurationsdatei geändert, ist dieser Weg in der Regel schneller als der "neue" Weg. Andererseits kann es aber auch zu unerwarteten Fehlern beim Bau des Kernels kommen, wenn Sie Ihren Kernel unter aktuellen FreeBSD-Versionen auf diese Art und Weise bauen. [.procedure] ==== . Erzeugen Sie den Kernel-Quellcode mit man:config[8]: + [source,shell] .... # /usr/sbin/config MYKERNEL .... + . Wechseln Sie in das Build-Verzeichnis. man:config[8] gibt den Namen dieses Verzeichnisses aus, wenn die Erzeugung des Kernel-Quellcodes im vorherigen Schritt erfolgreich abgeschlossen wurde. + [source,shell] .... # cd ../compile/MYKERNEL .... + . Kompilieren Sie den neuen Kernel: + [source,shell] .... # make depend # make .... + . Installieren Sie den neuen Kernel: + [source,shell] .... # make install .... ==== [[kernelbuild-new]] == Einen Kernel auf die "neue" Art und Weise bauen Dieser Weg wird für alle aktuellen FreeBSD-Versionen empfohlen. Lesen Sie bitte den Abschnitt extref:{handbook}kernelconfig/[Erstellen und Installation eines angepassten Kernels, kernelconfig-building] des FreeBSD-Handbuchs, wenn Sie Ihren Kernel auf diese Art und Weise bauen wollen.
package com.example.jetpackcomposecatalog.components import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Image import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.outlined.AccountCircle import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.Info import androidx.compose.material.icons.outlined.Settings import androidx.compose.material.icons.rounded.Menu import androidx.compose.material.icons.rounded.Search import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FabPosition import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.NavigationDrawerItemDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch data class NavigationItem( val title: String, val selectedIcon: ImageVector, val unselectedIcon: ImageVector, val badgeCount: Int? = null ) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun ScaffoldComponent() { val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) var selectedItemIndex by rememberSaveable { mutableStateOf(0) } ModalNavigationDrawer( drawerContent = { ModalDrawerSheet { Spacer(modifier = Modifier.height(16.dp)) getItemsDrawer().forEachIndexed { index, item -> NavigationDrawerItem( label = { Text(text = item.title) }, selected = index == selectedItemIndex, onClick = { // navController.navigate(item.route) selectedItemIndex = index scope.launch { drawerState.close() } }, icon = { Icon( imageVector = if (index == selectedItemIndex) { item.selectedIcon } else item.unselectedIcon, contentDescription = item.title ) }, badge = { item.badgeCount?.let { Text(text = item.badgeCount.toString()) } }, modifier = Modifier .padding(NavigationDrawerItemDefaults.ItemPadding) ) } } }, drawerState = drawerState ) { Scaffold( snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, topBar = { TopAppBarSample(onClick = { scope.launch { snackbarHostState.showSnackbar("OnClick $it") } }, onClickDrawer = { scope.launch { drawerState.open() } }) }, bottomBar = { MyBottomNavigationCustom() }, floatingActionButton = { FloatingActionButtonExample() }, floatingActionButtonPosition = FabPosition.End, ) { Box( Modifier .height(50.dp) .fillMaxWidth() .background(Color.Red) ) { } } } } fun getItemsDrawer(): List<NavigationItem> { return listOf( NavigationItem( title = "All", selectedIcon = Icons.Filled.Home, unselectedIcon = Icons.Outlined.Home, ), NavigationItem( title = "Urgent", selectedIcon = Icons.Filled.Info, unselectedIcon = Icons.Outlined.Info, badgeCount = 45 ), NavigationItem( title = "Settings", selectedIcon = Icons.Filled.Settings, unselectedIcon = Icons.Outlined.Settings, ), ) } @Composable fun MyDrawer() { // Material2 Column(Modifier.padding(8.dp)) { Text( text = "Option 1", modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) HorizontalDivider( modifier = Modifier.fillMaxWidth() ) Text( text = "Option 2", modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) HorizontalDivider( modifier = Modifier.fillMaxWidth() ) Text( text = "Option 3", modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) HorizontalDivider( modifier = Modifier.fillMaxWidth() ) Text( text = "Option 4", modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) } } @Composable fun MyBottomNavigationCustom() { var index by remember { mutableStateOf(0) } NavigationBar(contentColor = Color.White, containerColor = Color.Gray, tonalElevation = 20.dp) { NavigationBarItem(selected = index == 0, onClick = { index = 0 }, icon = { Icon( imageVector = Icons.Default.Search, contentDescription = "" ) }, label = { Text(text = "Search") }) NavigationBarItem(selected = index == 1, onClick = { index = 1 }, icon = { Icon( imageVector = Icons.Default.Image, contentDescription = "" ) }, label = { Text(text = "Image") }) NavigationBarItem(selected = index == 2, onClick = { index = 2 }, icon = { Icon( imageVector = Icons.Default.Home, contentDescription = "" ) }, label = { Text(text = "Home") }) } } @Composable fun FloatingActionButtonExample() { FloatingActionButton( onClick = { print("Hello") }, contentColor = Color.White, containerColor = Color.Black, shape = FloatingActionButtonDefaults.extendedFabShape ) { Icon(Icons.Filled.Favorite, "Floating action button.") } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun TopAppBarSample(onClick: (String) -> Unit, onClickDrawer:()->Unit) { TopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = Color.Gray, titleContentColor = Color.White, actionIconContentColor = Color.Red, navigationIconContentColor = Color.Green, ), navigationIcon = { IconButton(onClick = { onClickDrawer() }) { Icon(imageVector = Icons.Rounded.Menu, contentDescription = null) } }, title = { Text(text = "Sample Title") }, actions = { IconButton(onClick = { onClick("Search") }) { Icon( imageVector = Icons.Rounded.Search, contentDescription = null ) } IconButton(onClick = { onClick("AccountCircle") }) { Icon( imageVector = Icons.Outlined.AccountCircle, contentDescription = null ) } } ) }
/* * Copyright 2021-2022 the original author and authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.edu.tjnu.tutor.common.locale; import org.springframework.context.i18n.LocaleContextHolder; import java.io.Serializable; import java.util.Locale; /** * 可获取国际化字符串消息的接口。 * * @author 王帅 * @since 2.0 */ public interface Localizable extends Serializable { /** * 通过 {@link LocaleContextHolder#getLocale()} 方法获得区域信息, * 解析返回消息。 * * @param args 格式化参数 * @return 默认消息 * @implSpec 对于国际化接口,该默认实现为: * <pre>{@code * return getLocalizedMessage(LocaleContextHolder.getLocale(), args); * }</pre> */ default String getMessage(Object... args) { return getLocalizedMessage(LocaleContextHolder.getLocale(), args); } /** * 通过指定的区域信息解析返回消息。 * * @param locale 区域信息 * @param args 格式化参数 * @return 默认消息 */ String getLocalizedMessage(Locale locale, Object... args); }
document.addEventListener('DOMContentLoaded', (event) => { let movieNameRef = document.getElementById("movie-name"); let searchBtn = document.getElementById("search-btn"); let result = document.getElementById("result"); let pagination = document.getElementById("pagination"); let currentPage = 1; let totalResults = 0; const resultsPerPage = 10; // Assuming 10 results per page const maxVisiblePages = 5; // Maximum number of visible pages at once // Event listener for Enter key press on the movie name input field movieNameRef.addEventListener("keypress", function (event) { if (event.key === "Enter") { getMovie(currentPage); } }); // Event listener for Enter key press on the search button searchBtn.addEventListener("keypress", function (event) { if (event.key === "Enter") { getMovie(currentPage); } }); // Function to fetch and display movies based on the current page and search term let getMovie = (page) => { result.innerHTML = `<h3 class="loading-message">Loading movies...</h3>`; result.classList.add('fadeIn'); let movieName = movieNameRef.value.trim(); let url = `https://www.omdbapi.com/?s=${encodeURIComponent(movieName)}&apikey=${key}&page=${page}`; if (movieName.length <= 0) { result.innerHTML = `<h3 class="msg">Please enter a movie name.</h3>`; pagination.innerHTML = ''; return; } fetch(url).then((resp) => resp.json()).then((data) => { if (data.Response == "True") { totalResults = parseInt(data.totalResults); let movieDetailsPromises = data.Search.map(movie => fetch(`https://www.omdbapi.com/?i=${movie.imdbID}&apikey=${key}`) .then(response => response.json())); Promise.all(movieDetailsPromises).then(details => { let sortedDetails = details.sort((a, b) => parseInt(b.Year) - parseInt(a.Year)); result.innerHTML = sortedDetails.map(detail => ` <div class="info"> <img src="${detail.Poster}" class="poster"> <div class="info-movie"> <h2>${detail.Title}</h2> <div class="rating"> <img src="star-icon.svg" alt="Star icon"> <h4>${detail.imdbRating}</h4> </div> <div class="details"> <span>${detail.Rated}</span> <span>${detail.Year}</span> <span>${detail.Runtime}</span> </div> <div class="genre">${detail.Genre.split(',').map(genre => `<div>${genre.trim()}</div>`).join('')}</div> <h3>Plot:</h3> <p>${detail.Plot}</p> <h3>Cast:</h3> <p>${detail.Actors}</p> </div> </div> `).join(''); setupPagination(totalResults); result.classList.add('fadeIn'); }); } else { result.innerHTML = `<h3 class="msg">${data.Error}</h3>`; pagination.innerHTML = ''; } }).catch((error) => { result.innerHTML = `<h3 class="msg">Error Occurred: ${error.message}</h3>`; pagination.innerHTML = ''; }); }; // Function to set up pagination based on the total number of movies function setupPagination(totalMovies) { const pageCount = Math.ceil(totalMovies / resultsPerPage); pagination.innerHTML = ''; let startPage = Math.max(currentPage - Math.floor(maxVisiblePages / 2), 1); let endPage = Math.min(startPage + maxVisiblePages - 1, pageCount); if (endPage - startPage < maxVisiblePages - 1) { startPage = Math.max(endPage - maxVisiblePages + 1, 1); } if (startPage > 1) { addPaginationItem(pagination, 1, '<<'); } if (currentPage > 1) { addPaginationItem(pagination, currentPage - 1, '<'); } for (let i = startPage; i <= endPage; i++) { addPaginationItem(pagination, i, i); } if (currentPage < pageCount) { addPaginationItem(pagination, currentPage + 1, '>'); } if (endPage < pageCount) { addPaginationItem(pagination, pageCount, '>>'); } } // Function to add an individual pagination item function addPaginationItem(container, page, text) { const button = document.createElement('button'); button.textContent = text; button.addEventListener('click', function (e) { e.preventDefault(); currentPage = page; getMovie(currentPage); }); if (page === currentPage) { button.classList.add('active'); // Add an 'active' class or disable the button } container.appendChild(button); } // Click event listener for the search button searchBtn.addEventListener("click", () => getMovie(currentPage)); });
# تكبير الشفاه - اليكم كافة الطرق! __شارك __غرد علاج تكبير الشفاه هي عملية تتطلّب من الطبيب معرفة تشريحية, معرفة دقيقة لمواد التعبئة المختلفة وميزاتها, معرفة تقنيات حقن مختلفة والقدرة على التعامل مع المضاعفات التي ممكن أن تظهر. منذ قدم الزمان، كانت تعتبر الشفاه جزءا هاما من سحر وجمال الشخص. وكان الرسامون في عصر النهضة يظهرون (يشددون) شفاه النساء بلوحاتهم. المثال الواضح على ذلك هو لوحة الموناليزا للرسام دافينشي، فيها تظهر ابتسامتها الخفية مع شفاهها الضيقة والثابتة والتي لا تكشف سرها ولا حتى أسنانها. بالرغم من جاذبية الشفاه إلا انه مع تقدم العمر تحدث بهما عمليات تنكسية كجزء من التقدم بالعمر التي تحدث أيضاً للعظام والعضلات المحيطة بها. الطبقة السطحية للجلد، البشرة (Epidermis) تصبح أكثر غلظه (كثافة)، والطبقة الأكثر عمقاً بالجلد، الأدمة (dermis)، أيضاً تمر بعمليات تنكسية: الجزيئات التي من شأنها أن تحافظ على رطوبة وحجم الشفاه مثل حمض الهيالورونيك (Hyaluronic acid) الذي يتواجد بالشفاه بكمية اخذه بالنقصان، وهنالك تغييرات أيضاً بكمية وحجم الجلد حول الفم الأمر الذي يؤدي إلى مظهر مجعد وتعب. قسم من العضلات تصبح متشنجة، وتكون النتيجة لذلك فقدان الشفاه لحجمها وتحولها إلى شفاه رقيقة، باهتة وتظهر بقع حول وعلى أطراف الفم. علاج تكبير الشفاه مناسب للأشخاص فوق جيل 18 سنة المعنيون بشفاه جذابة وممتلئة ولصاحبات الشفاه الرقيقة اللاتي يرغبن بمظهر ممتلئ وجذاب. لتحسين مظهر الشفاه بالطب التجميلي فإنه مع** تكبير الشفاه** يجب الأخذ بالحسبان تفاصيل هامه: رغبة المرأة، عمرها، وضع الشفتين الحالي ووضع وجهها. بالإضافة لذلك، يجب الأخذ بالحسبان • وضع الحنك • الأسنان • مبنى عظام الوجه • وضع الجلد، بقع الوجه. • الوضع الصحي العام • امكانية حدوث التهابات مثل الهربس • مرض السكري وغيرها يجب علينا الاهتمام بهذه الأمور من أجل النصيحة بنوع العلاج المناسب. من أجل رفع نسبة الرضا يجب ملائمة التوقعات مع المعالج، شرح الامكانيات الموجودة للعلاج والنتائج المتوقعة. الكثير من النساء اللاتي يخترن إجراء تكبير للشفاه يطلبن تنسيق شفاه معين. الشفاه الأكثر طلباً اليوم هي شفاه تسمى HOLYWOOD STYLE، بحسب SCALFANI، والتي تعرضها انجلينا جولي، الحديث هو عن شفاه ممتلئة جزئها المركزي غير ظاهر إنما مكبر بشكل متجانس مع كل الشفه. هنالك نوع اخر مطلوب من الشفاه هو PARIS STYLE، بهذا النوع من التنسيق يشدد خط الشفاه المركزي يشمل القوس. هذا النوع مناسب للنساء النحيفات أو المتقدمات بالسن أو النساء اللاتي لا يرغبن بأن يظهر التغيير الحاصل بشكل بارز. ينقسم علاج تنسيق الشفاه إلى قسمين، بداية بالتخدير الموضعي من أجل تمكين علاج سهل بدون أوجاع. يتم التخدير بواسطة الجليد، موجه موضعية أو حقنة. تتواجد بالحقن الجديدة مادة تخدير مع مادة التعبئة بنفس الحقنة. بعدها يتم العلاج. يتم العلاج بعيادة الطبيب. من غير المحبذ إجراء هذه العمليات بمعاهد التجميل، معاهد الرياضة أو حفلات تكبير الشفاه. وهذا في أعقاب التخوف من حدوث التهاب وتأثيرات جانبية مصاحبة للعلاج. **هنالك مجموعتين أساسيتين من المواد لتنسيق الشفاه:** المجموعة الأولى من مواد تنسيق الشفتين عبارة عن مواد طبيعية، تصنع بطرق بيو- تكنولوجية للهندسة الجينية. الحديث يدور حول مواد موجودة بشكل عام بالجسم ومع البلوغ، تقل كميتها، مثل حمض الهيالورونيك وهو مركب هام بالحفاظ على رطوبة الجلد والمحافظة على حجم النسيج بأعقاب امتصاص السوائل. مثال اخر هو الكولاجين المركب من بروتينات ويمر تغييرات مختلفة بالجسم خلال البلوغ والتقدم بالعمر. هذه المواد تصنع بظروف مخبرية، تباع كهلام تختلف درجة لزوجتها من منتج لاخر من أجل مساعدة الطبيب على تنسيق وترتيب الشفاه بالصورة الأكثر دقة وراحة. هذه المواد لا يتعرف عليها الجسم كمواد غريبة ولذلك فان تأثيراتها الجانبية مثل التحسس أو ردود الفعل الالتهابية بالإضافة إلى تكون الحبوب (نتوءات على شكل حبيبات) هي تأثيرات نادرة الحدوث جداً. بعد الحقن ممكن رؤية نتائج حالية أيضاً بعد علاج حقن واحد. هذا الأمر مناسب جداً للنساء والرجال المعنيين بإجراء اختلاف تجميلي قبل مناسبة أو خلال وقت قصير. سلبيات هذه المواد تكمن بأنها مواد تمتص وتتحلل عن طريق الجسم مع الوقت، لذلك فان تأثير علاج تكبير الشفاه يختفي. فترة الامتصاص ممكن أن تتراوح بين 3 أشهر حتى سنة ونصف، الأمر الذي يستلزم تكرار العملية كل عدة أشهر من أجل المحافظة على التأثير المطلوب. المجموعة الثانية من مواد تكبير الشفاه هي مواد اصطناعية. الحديث عن مواد بيولوجية لا يتم امتصاصها بالجسم إنما تؤدي إلى إنتاج نسيج حول منطقة الحقن الذي يملأ الشفاه ببطء: يتواجد السيليكون السائل بين هذه المواد، وهو يستعمل أيضاً للحقن بشبكية العيون بحالة انفصال الشبكية. تستعمل هذه المادة اليوم أيضاً لأهداف تجميلية أخرى غير تنسيق الشفاه. التقنية التي تحقن بها المادة تسمى MICRO-DROPLET، أي حقن قطرات إلى داخل الشفاه من أجل إحداث تحفيز لنسيج الشفة لإنتاج الكولاجين الذي يملأ الشفة مع الوقت. النتائج الحاصلة بهذا العلاج تكون جميلة جداً وتمنح الشفتين منظرا طبيعيا وجذابا. من أجل تحقيق التأثير المطلوب يجب حقن كميات صغيرة جداً من مادة السيليكون الطبيعي للشفتين مرة بالشهر، مدة العلاج حتى تحقيق النتائج المطلوبة يتراوح بين 3-8 أشهر. مادة اصطناعية أخرى هي ارطفيل أو أرتيكول التي تحتوي على جسيمات صغيرة (Microsphere) من مادة مصنعة تسمى polymethacrylate المستعملة كمادة تعبئة فورية وأيضاً كمادة مسببة لإنتاج نسيج يزيد من كثافة الشفتين. التأثيرات الجانبية الفورية لعلاج تنسيق الشفتين هو الانتفاخ والأورام الدموية ( Hematoma ) من أجل تقليل هذه المضاعفات إلى الحد الأدنى الممكن يجب تحديد عدد الحقنات عند القيام بالأمر واستعمال إبر رفيعة المناسبة لهذه الغاية. كما أنه من المعتاد وضع ثلج فوراً بعد العلاج لتقليل الانتفاخ وتشنج الاوعية الدموية. التأثيرات الجانبية التي تظهر لاحقاً هي الالتهابات. إنما هذا الأمر هو نادر جداً بحالة أن العملية أجريت بظروف معقمة على يد طبيب ماهر. يتم العلاج ضد هذه المضاعفات عن طريق إعطاء مضادات حيوية وأحياناً نادرة يتطلب الأمر أيضاً تصريف جراحي. هنالك نوع اخر من المضاعفات لكنه نادر هو رد فعل ذاتي التحساس (idiosyncratic)، وهو عبارة عن رد فعل تحسسي للمادة المحقونة وتكوين نتوءات بداخل الشفة، ممكن لرد الفعل أن يظهر أيضاً بعد مرور سنين. انتشار هذا الأمر هو 1 من كل ألف حالة. والعلاج ضد هذا النوع من المضاعفات يكون بحقن موضعي للستيروئيدات بجرعات دنيا تؤدي بشكل عام إلى اختفاء هذا الظهور. خلاصة الأمر، علاج تكبير الشفاه هو عملية تتطلب من الطبيب معرفة تشريحية، معرفة دقيقة لمواد التعبئة المختلفة وميزاتها، معرفة تقنيات حقن مختلفة والقدرة على التعامل مع المضاعفات التي ممكن أن تظهر. إجراء علاج تنسيق الشفتين على أيدي محترفة ممكن أن يحسن من مظهر الشفاه ويمنحهم مظهر جميل وجذاب. من قبل ويب طب - الأحد ، 9 ديسمبر 2012 آخر تعديل - الأحد ، 23 أبريل 2017 __شارك __غرد
<!DOCTYPE html> <html> <head> <title>Blogger</title> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= stylesheet_link_tag 'application', 'http://fonts.googleapis.com/css?family=Titillium+Web:600' %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> </head> <body> <div id="sidebar"> <div id="logo"> <%= link_to root_path do %> <%= image_tag "logo.png" %> <% end %> </div> <ul> <li class="category">Website</li> <li><%= link_to "Blog", root_path %></li> </ul> <ul> <li class="category">Links</li> <li><%= link_to "Blog", root_path %></li> <li><%= link_to "About", root_path %></li> </ul> </div> <div id="main_content"> <div id="header"> <%= link_to "All Posts", root_path %> <% if user_signed_in? %> <div class="buttons"> <%= link_to "New Post", new_post_path %> | <%= link_to "Settings", edit_user_registration_path %> | <%= link_to "Log out", destroy_user_session_path, method: "delete" %> </div> <%else%> <div class="buttons"> <%= link_to "Sign In", new_user_session_path %> | <%= link_to "Sign Up", new_user_registration_path %> </div> <% end %> </div> <% flash.each do |name, msg| %> <%= content_tag(:div, msg, class: "alert") %> <% end %> <%= yield %> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>展示星期数</title> </head> <body> <script> // 写一个函数 getWeekDay(date) 来显示一个日期的星期数, // 用简写表示:‘ MO’、‘ TU’、‘ WE’、‘ TH’、‘ FR’、‘ SA’、‘ SU’。 function getWeekDay(date) { let week = date.getDay(); switch (week) { case 0: return 'SU'; break; case 1: return 'MO'; break; case 2: return 'TU'; break; case 3: return 'WE'; break; case 4: return 'TH'; break; case 5: return 'FR'; break; case 6: return 'SA'; break; } } function getWeekDay1(date) { // date.getDay() 方法返回星期数, 从星期日开始。 // 我们创建一个星期数组, 这样可以通过它的序号得到名称: let days = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']; return days[date.getDay()]; } let date = new Date(2012, 0, 3); // 3 Jan 2012 console.log(getWeekDay(date)); // 应该输出 "TU" console.log(getWeekDay1(date)); // 应该输出 "TU" </script> </body> </html>
<?php /* * Copyright 2014 Google Inc. * * 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. */ namespace Google\Service\Script; class Project extends \Google\Model { /** * @var string */ public $createTime; protected $creatorType = GoogleAppsScriptTypeUser::class; protected $creatorDataType = ''; protected $lastModifyUserType = GoogleAppsScriptTypeUser::class; protected $lastModifyUserDataType = ''; /** * @var string */ public $parentId; /** * @var string */ public $scriptId; /** * @var string */ public $title; /** * @var string */ public $updateTime; /** * @param string */ public function setCreateTime($createTime) { $this->createTime = $createTime; } /** * @return string */ public function getCreateTime() { return $this->createTime; } /** * @param GoogleAppsScriptTypeUser */ public function setCreator(GoogleAppsScriptTypeUser $creator) { $this->creator = $creator; } /** * @return GoogleAppsScriptTypeUser */ public function getCreator() { return $this->creator; } /** * @param GoogleAppsScriptTypeUser */ public function setLastModifyUser(GoogleAppsScriptTypeUser $lastModifyUser) { $this->lastModifyUser = $lastModifyUser; } /** * @return GoogleAppsScriptTypeUser */ public function getLastModifyUser() { return $this->lastModifyUser; } /** * @param string */ public function setParentId($parentId) { $this->parentId = $parentId; } /** * @return string */ public function getParentId() { return $this->parentId; } /** * @param string */ public function setScriptId($scriptId) { $this->scriptId = $scriptId; } /** * @return string */ public function getScriptId() { return $this->scriptId; } /** * @param string */ public function setTitle($title) { $this->title = $title; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param string */ public function setUpdateTime($updateTime) { $this->updateTime = $updateTime; } /** * @return string */ public function getUpdateTime() { return $this->updateTime; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(Project::class, 'Google_Service_Script_Project');
import React, { useEffect, useState } from 'react'; import Categoriesloaded from './Categoriesloaded'; const AllCategories = () => { const [categories, setCategories] = useState([]); const [isLoading, setIsLoading] = useState(true); // Add loading state useEffect(() => { fetch('https://reread-server.vercel.app/categories') .then((res) => res.json()) .then((data) => { setCategories(data); setIsLoading(false); // Update loading state when data is fetched }) .catch((error) => { console.error('Error fetching data:', error); setIsLoading(false); // Handle error and update loading state }); }, []); return ( <div className='my-24' id='cat' > <h2 className='text-4xl font-bold text-center'>Categories</h2> <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mx-10 my-10'> { isLoading ? ( // Display skeleton loaders while data is being fetched <> <div className="flex basis-1/3 flex-col m-8 rounded shadow-md sm:w-80 animate-pulse h-96"> <div className="h-48 rounded-t dark:bg-[#d8d8d8]"></div> <div className="flex-1 px-4 py-8 space-y-4 sm:p-8 "> <div className="w-full h-6 rounded dark:bg-[#d8d8d8]"></div> <div className="w-full h-6 rounded dark:bg-[#d8d8d8]"></div> <div className="w-3/4 h-6 rounded dark:bg-[#d8d8d8]"></div> </div></div> <div className="flex-2 basis-1/3 flex-col m-8 rounded shadow-md sm:w-80 animate-pulse h-96"> <div className="h-48 rounded-t dark:bg-[#d8d8d8]"></div> <div className="flex-1 px-4 py-8 space-y-4 sm:p-8 "> <div className="w-full h-6 rounded dark:bg-[#d8d8d8]"></div> <div className="w-full h-6 rounded dark:bg-[#d8d8d8]"></div> <div className="w-3/4 h-6 rounded dark:bg-[#d8d8d8]"></div> </div></div> <div className="flex-2 basis-1/3 flex-col m-8 rounded shadow-md sm:w-80 animate-pulse h-96"> <div className="h-48 rounded-t dark:bg-[#d8d8d8]"></div> <div className="flex-1 px-4 py-8 space-y-4 sm:p-8 "> <div className="w-full h-6 rounded dark:bg-[#d8d8d8]"></div> <div className="w-full h-6 rounded dark:bg-[#d8d8d8]"></div> <div className="w-3/4 h-6 rounded dark:bg-[#d8d8d8]"></div> </div></div> </> ) : ( // Display fetched categories when loading is complete categories.map((category) => ( <Categoriesloaded key={category.category_id} category={category} /> )) )} </div> </div> ); }; export default AllCategories; // import Categoriesloaded from './Categoriesloaded'; // const AllCategories = () => { // const [categories,setCategories] = useState([]) // useEffect(()=>{ // fetch('https://reread-server.vercel.app/categories') // .then(res=>res.json()) // .then(data=>{ // setCategories(data); // }) // },[]) // return ( // <div className=' my-24' id='cat'> // <h2 className='text-4xl font-bold text-center'>Categories</h2> // <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10 mx-10 my-10 '> // { // categories?.map(category =><Categoriesloaded key={category.category_id} // category={category} // ></Categoriesloaded>) // } // </div> // </div> // ); // }; // export default AllCategories;
<script> import axios from 'axios' import { mapState } from 'vuex' export default { name: 'PlaylistCategories', components: {}, data() { return { pageId: 'PlaylistCategories', isOpen: false, playlistFeatures: [], } }, async created() { try { const response = await axios.get('https://api.spotify.com/v1/browse/featured-playlists', { headers: { 'Authorization': `Bearer ${localStorage.getItem('spotify_access_token')}`, }, }) const playlists = response.data.playlists.items for (let i = 0; i < 6; i++) { const randomIndex = Math.floor(Math.random() * playlists.length) this.playlistFeatures.push(playlists[randomIndex]) playlists.splice(randomIndex, 1) } } catch (error) { console.error(error) } }, methods: { selectPlaylist(playlist) { this.$router.push({ name: 'playlist', params: { id: playlist.id } }) }, }, computed: { ...mapState(['isLogin']), } } </script> <template> <div :class="pageId" v-if="isLogin"> <h2 class="text-white mb-3">Featured Playlists</h2> <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 3xl:grid-cols-7 gap-4"> <router-link v-for="playlist in playlistFeatures" :key="playlist.id" :to="`/playlist/${playlist.id}`" class="card p-2 rounded-md hover:bg-[#424242] cursor-pointer relative group"> <div class="relative"> <img v-if="playlist.images && playlist.images.length > 0" :src="playlist.images[0].url" alt="Playlist cover" class="card-img-top object-fit rounded-md bg-white mb-2 w-auto h-auto"> <div class="absolute right-0 bottom-0 mb-2 mr-2 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200"> <button class="bg-green-500 text-black rounded-full h-14 w-14 flex items-center justify-center"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-8 h-8"> <path fill-Rule="evenodd" d="M4.5 5.653c0-1.427 1.529-2.33 2.779-1.643l11.54 6.347c1.295.712 1.295 2.573 0 3.286L7.28 19.99c-1.25.687-2.779-.217-2.779-1.643V5.653Z" clipRule="evenodd" /> </svg> </button> </div> </div> <div class="card-body"> <p class="md:block">{{ playlist.name }}</p> </div> </router-link> </div> </div> </template>
// // File.swift // // // Copyright 2022 Oliver Letterer // import Foundation import CheckedScanner public struct MethodDefinition: Hashable { public var name: String public var isImpure: Bool public var arguments: [FunctionDefinition.FunctionArgumentDefinition] public var returns: TypeId? init(name: String, isImpure: Bool, arguments: [FunctionDefinition.FunctionArgumentDefinition], returns: TypeId?) { self.name = name self.isImpure = isImpure self.arguments = arguments self.returns = returns } public func inferredReturnType(in context: Context) -> TypeId { if returns == nil { return context.moduleContext.typechecker!.buildIn.Void } else { return returns! } } public var equals: (MethodDefinition) -> Bool { return { name == $0.name && arguments == $0.arguments && returns == $0.returns } } } public struct MethodDeclaration: AST { public var name: FunctionDeclaration.NameDeclaration public var isImpure: Bool public var arguments: [FunctionDeclaration.FunctionArgumentDeclaration] public var returns: TypeReference? public var openAngleBracket: OpenAngleBracketToken public var statements: [Statement] public var closeAngleBracket: CloseAngleBracketToken public var checked: InferredType<MethodId> public var file: URL public var location: Range<Int> init(name: FunctionDeclaration.NameDeclaration, isImpure: Bool, arguments: [FunctionDeclaration.FunctionArgumentDeclaration], returns: TypeReference?, openAngleBracket: OpenAngleBracketToken, statements: [Statement], closeAngleBracket: CloseAngleBracketToken, checked: InferredType<MethodId>, file: URL, location: Range<Int>) { self.name = name self.isImpure = isImpure self.arguments = arguments self.returns = returns self.openAngleBracket = openAngleBracket self.statements = statements self.closeAngleBracket = closeAngleBracket self.checked = checked self.file = file self.location = location } public var functionDefinition: MethodDefinition { return MethodDefinition(name: name.name, isImpure: isImpure, arguments: arguments.map(\.argumentDefinition), returns: returns?.checked.typeId) } public var description: String { return """ \(type(of: self)) - name: \(name.name) - isImpure: \(isImpure) - arguments: \(arguments.map(\.description).map({ $0.withIndent(4) }).joined(separator: "\n")) - returns: \(returns?.description ?? "Void") - statements: \(statements.map(\.description).map({ $0.withIndent(4) }).joined(separator: "\n")) """ } } extension MethodDeclaration { public static func canParse(parser: Parser) -> Bool { return parser.matches(optional: [ .impure ], required: .func) } public static func parse(parser: Parser) throws -> MethodDeclaration { var modifiers: Set<KeywordToken.Keyword> = [] while let keyword = parser.peek() as? KeywordToken, keyword.keyword != .func { guard !modifiers.contains(keyword.keyword) else { throw ParserError.modifierRedeclaration(keyword: keyword) } modifiers.insert(keyword.keyword) try! parser.drop() } let first = try parser.accept(.func) guard let name = parser.peek() else { throw ParserError.unexpectedEndOfFile(parser: parser) } guard let name = name as? IdentifierToken else { throw ParserError.unexpectedToken(parser: parser, token: name) } try! parser.drop() try parser.accept(.openParan) var arguments: [FunctionDeclaration.FunctionArgumentDeclaration] = [] while let argumentsStart = parser.peek() { if arguments.count > 0 { if argumentsStart is CloseParanToken { break } else if argumentsStart is CommaToken { try! parser.drop() arguments.append(try FunctionDeclaration.FunctionArgumentDeclaration.parse(parser: parser)) } else { throw ParserError.unexpectedToken(parser: parser, token: argumentsStart) } } else { if argumentsStart is CloseParanToken { break } arguments.append(try FunctionDeclaration.FunctionArgumentDeclaration.parse(parser: parser)) } } try parser.accept(.closeParan) let returns: TypeReference? if parser.matches(required: .arrow) { try! parser.accept(.arrow) returns = try TypeReference.parse(parser: parser) } else { returns = nil } let openAngleBracket = try parser.accept(.openAngleBracket) let statements: [Statement] = try [Statement].parse(parser: parser) let closeAngleBracket = try parser.accept(.closeAngleBracket) return MethodDeclaration(name: FunctionDeclaration.NameDeclaration(name: name.identifier, file: parser.file, location: name.location), isImpure: modifiers.contains(.impure), arguments: arguments, returns: returns, openAngleBracket: openAngleBracket, statements: statements, closeAngleBracket: closeAngleBracket, checked: .unresolved, file: parser.file, location: first.location.lowerBound..<closeAngleBracket.location.upperBound) } }
# This file is part of The Family's treasure tale. # The Family's treasure tale is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # The Family's treasure tale is distributed in the hope that it will # be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with The Family's treasure tale. If not, see # <http://www.gnu.org/licenses/>. from geometry import Positionable from graphics import Renderable, Colorable from animation import Animable, ColorAnimation day_color = (12, 32, 139, 0) night_color = (12, 32, 139, 128) duration = 15 class Sky: pass class SkyHelper: """Helper class for sky transitions. """ def __init__(self, entity): self.entity = entity def to_night(self): animable = self.entity.get_component(Animable) animable.add_animation(ColorAnimation(night_color, duration)) def to_day(self): animable = self.entity.get_component(Animable) animable.add_animation(ColorAnimation(day_color, duration)) def create_sky_effect(world, pos, size, layer): """Setup a sky entity and return its helper. """ sky = world.entity() sky.add_components( Positionable(pos[0], pos[1], size[0], size[1]), Colorable(day_color), Renderable( lambda brush, color: brush.draw_rect(color, (0, 0), size), layer ), Animable(), Sky() ) return SkyHelper(sky)
<template> <div class="demo-form-mobile"> <div class="page__hd"> <h1 class="page__title">Form</h1> <p class="page__desc">表单(纯展示)</p> </div> <div class="demo-form-mobile-hide-padds"> <tiny-form ref="ruleForm" :model="createData" :rules="rules" :hide-required-asterisk="false" :inline="false"> <tiny-form-item label="优秀" prop="users" vertical> <tiny-input v-model="createData.users" placeholder="请输入内容" type="form"></tiny-input> </tiny-form-item> <tiny-form-item label="优秀" vertical> <tiny-input v-model="createData.user" is-select :select-menu="menus" placeholder="请输入内容" type="form" ></tiny-input> </tiny-form-item> <tiny-form-item class="demo-form-mobile-item"> <tiny-button type="primary" @click="handleSubmit('ruleForm')">提交</tiny-button> </tiny-form-item> </tiny-form> </div> <tiny-dialog-box :visible="boxVisibility" @update:visible="boxVisibility = $event" :modal-append-to-body="false" title="消息提示" > <span>提交成功!</span> </tiny-dialog-box> </div> </template> <script lang="jsx"> import { Form, FormItem, Input, Button, DialogBox } from '@opentiny/vue' export default { components: { TinyForm: Form, TinyFormItem: FormItem, TinyInput: Input, TinyButton: Button, TinyDialogBox: DialogBox }, data() { return { menus: [ { id: 1, label: '我是小花,我是小花,我是小花,我是小花,我是小花,我是小花,我是小花' }, { id: 2, label: '我是小树' }, { id: 3, label: '我是小草' }, { id: 4, label: '我是小叶', warn: true } ], createData: { users: '', user: '' }, rules: { users: [{ required: true, message: '必填', trigger: 'change' }] }, boxVisibility: false } }, methods: { handleSubmit(formName) { this.$refs[formName].validate((valid) => { if (valid) { this.boxVisibility = true } }) } } } </script> <style scoped> .demo-form-mobile-hide-padds { padding: 15px; background: white; margin-bottom: 15px; } .page__hd { padding: 40px; } .page__title { font-weight: 400; font-size: 21px; text-align: left; } .page__desc { margin-top: 5px; color: #888; font-size: 14px; text-align: left; } .demo-form-mobile { height: 100%; background: #f4f4f4; } .demo-form-mobile-item { margin-top: 12px; } </style> <style> .demo-form-mobile .tiny-mobile-form-item__label { background: #fff; } .demo-form-mobile-hide-padds .tiny-mobile-input-form__input { text-align: right; } </style>
// Roar Source Code // Wasim Abbas // http://www.waZim.com // Copyright (c) 2008-2019 // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the 'Software'), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Version: 1.0.0 #pragma once #include "math/rorvector.hpp" namespace ror { /** * Forward declaration for Matrix2 class used within Matrix3 class */ template <class _type> class Matrix2; /** * Forward declaration for Matrix4 class used within Matrix3 class */ template <class _type> class Matrix4; /** * Forward declaration for Matrix3x4 class used within Matrix3 class */ template <class _type> class Matrix3x4; /** * Forward declaration for AxisAngle class used within Matrix3 class */ template <class _type> class AxisAngle; /** * Forward declaration for EulerAngle class used within Matrix3 class */ template <class _type> class EulerAngle; /** * Forward declaration for Quaternion class used within Matrix3 class */ template <class _type> class Quaternion; /** * Class for 3x3 matrix storage and manipulation. * A Template version of the Matrix3 is provided but OpenGL ES only supports (_type == float32_t) matrices. * This is a column-major matrix implementation. * To transform a vector you will need to post-multiply it * Matrix3 mat; * Vector3 vec; * auto result = mat * vec; * Reference: https://www.scratchapixel.com/lessons/mathematics-physics-for-computer-graphics/geometry/row-major-vs-column-major-vector * +X points right and +Y points up, Z+ point "out of the screen" for the right hand system. Camera looking down the -Z @ingroup RoarMath */ template <class _type> class ROAR_ENGINE_ITEM Matrix3 final { public: _type m_values[9]; //!< Matrix data in a C array Column-Major FORCE_INLINE Matrix3(_type a_scale = 1); //! Default constructor FORCE_INLINE Matrix3(const Matrix3 &a_other) = default; //! Copy constructor FORCE_INLINE Matrix3(Matrix3 &&a_other) noexcept = default; //! Move constructor FORCE_INLINE Matrix3 &operator=(const Matrix3 &a_other) = default; //! Copy assignment operator FORCE_INLINE Matrix3 &operator=(Matrix3 &&a_other) noexcept = default; //! Move assignment operator FORCE_INLINE ~Matrix3() noexcept = default; //! Destructor // TODO: Add constructors from axis angle and euler angles FORCE_INLINE explicit Matrix3(const Matrix4<_type> &a_other); FORCE_INLINE explicit Matrix3(const Matrix3x4<_type> &a_other); FORCE_INLINE explicit Matrix3(const _type *a_elements); FORCE_INLINE Matrix3(const Quaternion<_type> &a_quaternion); FORCE_INLINE Matrix3(_type a_0, _type a_1, _type a_2, //!< Don't use in normal usage never provide a hand written matrix _type a_3, _type a_4, _type a_5, //!< If ever used make sure rows and colums are correct _type a_6, _type a_7, _type a_8); //!< a_0, a_1, a_2 is the first column not the first row FORCE_INLINE _type &get(uint32_t a_row, uint32_t a_column) noexcept; FORCE_INLINE void set(const Matrix3 &a_matrix) noexcept; FORCE_INLINE void set(const _type *a_elements) noexcept; FORCE_INLINE void set(const Quaternion<_type> &a_quaternion); FORCE_INLINE void set(_type a_0, _type a_1, _type a_2, //!< Don't use in normal usage never provide a hand written matrix _type a_3, _type a_4, _type a_5, //!< If ever used make sure rows and colums are correct _type a_6, _type a_7, _type a_8) noexcept; //!< a_0, a_1, a_2 is the first column not the first row FORCE_INLINE void set_axis(uint32_t a_axis_index, const Vector3<_type> &a_axis) noexcept; FORCE_INLINE void set_x_axis(const Vector3<_type> &a_axis) noexcept; FORCE_INLINE void set_y_axis(const Vector3<_type> &a_axis) noexcept; FORCE_INLINE void set_z_axis(const Vector3<_type> &a_axis) noexcept; FORCE_INLINE void set_column(uint32_t a_index, const Vector3<_type> &a_column) noexcept; FORCE_INLINE Vector3<_type> x_axis() const; FORCE_INLINE Vector3<_type> y_axis() const; FORCE_INLINE Vector3<_type> z_axis() const; FORCE_INLINE Vector3<_type> column(uint32_t a_index) const; FORCE_INLINE explicit operator const _type *() const; //!< Only bind to const arrays or const pointers type FORCE_INLINE Matrix3 &operator+=(const Matrix3 &a_matrix); FORCE_INLINE Matrix3 &operator-=(const Matrix3 &a_matrix); FORCE_INLINE Matrix3 &operator*=(const Matrix3 &a_matrix); FORCE_INLINE Matrix3 &operator*=(_type a_value); FORCE_INLINE Matrix3 operator-() const; FORCE_INLINE void identity() noexcept; FORCE_INLINE _type determinant() const noexcept; FORCE_INLINE bool invert(); //!< Inverts the matrix and returns true. If inverse is not possile returns false FORCE_INLINE bool inverse(Matrix3 &a_output_matrix) const; //!< Sets a_output_matrix to inverse if its possible and returns true otherwise returns false FORCE_INLINE void transpose() noexcept; //!< Transposes the matrix FORCE_INLINE Matrix3 transposed() const; //!< Returns transpose of the matrix unchanged FORCE_INLINE void normalize(); //!< Normalizes the matrix x, y, z axis FORCE_INLINE void orthogonalize(); //!< Orthogonalizes the basis axis using Gram–Schmidt process, //!< it can fail if the axis are co-linear. It doesn't normalize the basis FORCE_INLINE bool is_orthogonal() const; }; using Matrix3i = Matrix3<int32_t>; using Matrix3f = Matrix3<float32_t>; using Matrix3d = Matrix3<double64_t>; const Matrix3f identity_matrix3i( 1, 0, 0, 0, 1, 0, 0, 0, 1); const Matrix3f identity_matrix3f( 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); const Matrix3f identity_matrix3d( 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); const Matrix3f zero_matrix3f( 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f); } // namespace ror #include "rormatrix3.hh"
import React from "react"; import { useState, useEffect } from "react"; import { useParams, Outlet, Link, useNavigate } from "react-router-dom"; import { getMovieInfo } from "services/api"; import { Wrapper, Paragraph, Button, MovieImage } from "./MoviesInfo.styled"; const MovieInfo = () => { const { movieId } = useParams() const [movieInfo, setMovieInfo] = useState({}) const [genres, setGenres] = useState([]) let nav = useNavigate() useEffect(() => { const asyncFunc = async () => { try { const movieInfo = await getMovieInfo(movieId) setMovieInfo(movieInfo) setGenres(movieInfo.genres) } catch (error) { console.log(error) } } asyncFunc() }, [movieId]) return ( <> <Button onClick={() => nav(-1)}>Go back</Button> {movieInfo && ( <> <Wrapper> <MovieImage> <img src={`https://image.tmdb.org/t/p/w500${movieInfo?.poster_path}`} alt={movieInfo?.title} width={250} /> </MovieImage> <div> <h2>{movieInfo?.title}</h2> <div>User score: {movieInfo?.vote_average}</div> <h3>Overview</h3> <p>{movieInfo?.overview}</p> <h4>Genres</h4> {genres.map(genre => ( <p key={genre.id}>{genre.name}</p> ))} </div> </Wrapper> <Paragraph>Additional information</Paragraph> <ul> <li> <Link to="cast">Cast</Link> </li> <li> <Link to="reviews">Reviews</Link> </li> </ul> <Outlet /> </> )} </> ) } export default MovieInfo;
<template> <section class="bill" v-if="this.$store.state.car.length > 0"> <article class="bill-create"> <h2>Factura a pagar</h2> <form action="" class="bill-form mt-3"> <select class="bill-form-select" v-model="selected"> <option v-for="(address, index) in registeredAddress" v-bind:value="address.value" :key="index" > {{ address.text }} </option> </select> <figure> <div v-if="this.currentCar.carType === 'Camión'" class="bill-car-type" > <i class="fas fa-truck-moving"></i> </div> <div v-else class="bill-car-type"> <i class="fas fa-car-side"></i> </div> <p> <span> Este auto es de tipo: </span> <span> {{ currentCar.carType }} </span> </p> <p> <span> Ingreso a la hora: {{ currentCar.getInHour }} </span> <span> Ingreso la fecha: {{ currentCar.getInDate }} </span> </p> <p v-if="currentCar.deposite">Se le aplica descuento</p> <p v-else>No tiene descuentos</p> <button class="create-bill" @click="getBill($event)"> Generar factura </button> </figure> </form> </article> <article class="bill-preview"> <h2>Vista previa del recibo</h2> <hr class="bill-divider mt-3" /> <div class="preview"> <h3 class="center">Black Car Parking</h3> <p> <span> Minutos de uso: </span> <span> {{ usedFor }} </span> </p> <p> <span> Tarifa de cobro: </span> <span> {{ carType }} </span> </p> <p> <span> Subtotal: </span> <span> {{ subtotal }} </span> </p> <hr class="bill-divider center" /> <p> <span> Total a pagar: </span> <span> {{ total }} </span> </p> <cite> Gracias por confiar la seguridad de su auto a Black Car, vuelva pronto </cite> </div> </article> </section> <section v-else> <article class="no-cars"> <hr class="bill-divider mt-3" /> <h2>No hay autos aún</h2> <hr class="bill-divider mt-3" /> </article> </section> </template> <script> export default { name: "Bill", data() { return { currentCar: Object, selected: "", usedFor: "", carType: "", subtotal: "", total: "", }; }, methods: { getCar() { this.$store.state.car.forEach((item) => { if (item.address === this.selected) { this.currentCar = item; } }); }, getUsedHour(flag = true) { const today = new Date(); const checkin = this.currentCar.getInHour; const usedSince = this.currentCar.getInDate; let hour = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); let date = today.getDate() + "/" + (today.getMonth() + 1) + "/" + today.getFullYear(); let usedHour, usedMin, usedSec; usedSec = parseInt(hour.substring(hour.lastIndexOf(":") + 1, hour.length)) - parseInt( checkin.substring(checkin.lastIndexOf(":") + 1, checkin.length) ); if (usedSec < 0) { usedHour + 1; usedSec += 60; } usedMin = parseInt(hour.substring(hour.indexOf(":") + 1, hour.lastIndexOf(":"))) - parseInt( checkin.substring(checkin.indexOf(":") + 1, checkin.lastIndexOf(":")) ); if (usedMin < 0) { usedMin + 1; usedMin += 60; } usedHour = parseInt(hour.substring(0, hour.indexOf(":"))) - parseInt(checkin.substring(0, checkin.indexOf(":"))); if (flag) { return usedMin + usedHour * 60 + "min " + usedSec + "sec "; } else { return usedMin + usedHour * 60 + usedSec / 60; } }, getSubtotal() { switch (this.currentCar.carType) { case "Turismo": { return (this.getUsedHour(false) * 1.5) / 60; } case "Todo terreno": { return (this.getUsedHour(false) * 2.5) / 60; } case "Furgoneta": { return (this.getUsedHour(false) * 3.5) / 60; } case "Camión": { if (this.currentCar.axis <= 3) { return (this.getUsedHour(false) * 4.5) / 60; } else { return (this.getUsedHour(false) * 6.5) / 60; } } } }, getTotal() { let subtotal = this.getSubtotal(); if (this.currentCar.deposite) { return (subtotal -= subtotal * 0.4); } else { return subtotal; } }, getBill(event) { event.preventDefault(); this.usedFor = this.getUsedHour(); this.carType = this.currentCar.carType; this.subtotal = "$" + Math.ceil(this.getSubtotal()) + ".00"; this.total = "$" + Math.ceil(this.getTotal()) + ".00"; this.$store.dispatch("removeCar", this.currentCar) this.$store.dispatch("addSlot"); }, }, computed: { registeredAddress() { let addressList = []; this.$store.state.car.forEach((item) => { addressList.push({ text: item.address, value: item.address, }); }); this.selected = addressList[0].value; return addressList; }, }, watch: { selected() { this.getCar(); }, }, }; </script> <style lang="css" scoped> cite { padding: 3% 1.2%; display: flex; justify-content: flex-end; } p { display: grid; padding: 2% 5%; grid-template-columns: auto auto; } p span:nth-child(2) { text-align: end; } .mt-3 { margin: 3% 0%; } .center { margin: 1.8% auto; text-align: center; } .no-cars { display: flex; flex-direction: column; justify-items: center; align-items: center; } .bill { display: grid; grid-template-columns: auto auto; padding: 2.5% 2.5% 0; } .bill-divider { width: 80%; height: 1px; border: none; background-color: #2c3e50; } .bill-create { padding: 0% 4%; } .bill-form { display: flex; border-radius: 8px; flex-direction: column; border: 1px solid #2c3e50; background-color: aliceblue; } .bill-form-select { width: 90%; border: none; margin: 2% auto; border-radius: 8px; background-color: aliceblue; } .bill-car-type { font-size: 14em; text-align: center; } .preview { width: 90%; padding: 2% 0% 0%; margin: 0% auto; border: 1px solid lightgray; } .create-bill { border: none; color: white; padding: 1.5%; border-radius: 8px; background-color: darkblue; display: flex; margin: 0 auto 5px; justify-self: center; } </style>
import { RefObject } from "react"; import { vec3, mat4 } from "wgpu-matrix"; import mesh from "./mesh.ts"; import vertexShaderCode from "./shaders/vert.wgsl?raw"; import fragmentShaderCode from "./shaders/frag.wgsl?raw"; import computeShaderCode from "./shaders/compute.wgsl?raw"; let canvas: HTMLCanvasElement | null; let bInitialized = false; let bMousePressed = false; let angleYaw: number = 0; let anglePitch: number = -0.7; let mouseLastX: number; let mouseLastY: number; let armLength: number = 2.5; let currSubdiv: number = 0; let newSubdiv: number = 10; const vertexBuffer: GPUBuffer[] = new Array(2); const vertexBindGroup: GPUBindGroup[] = new Array(2); let indexBuffer: GPUBuffer; let numToDraw: number; let p = 0; let lastFrameTime: number = 0; let gravity: number = 0; let centerOffset: number = 0; async function init( canvasRef: RefObject<HTMLCanvasElement>, props: { width: number; height: number }, ) { // react dev double load workaround if (bInitialized) { return; } bInitialized = true; canvas = canvasRef.current; if (!canvas) { console.log("Null canvas ref"); return; } const context = canvas.getContext("webgpu"); if (!context) { console.log("WebGPU not supported - failed to get webgpu context"); return; } //@TODO get performance/low-power, handle device lost const adapter = await navigator.gpu?.requestAdapter(); const device = await adapter?.requestDevice(); if (!device) { console.log("WebGPU not supported - failed to get webgpu device"); return; } //@TODO devicePixelRatio and window.matchMedia() changes canvas.width = props.width; canvas.height = props.height; const presentationFormat = navigator.gpu.getPreferredCanvasFormat(); const swapChainDesc: GPUCanvasConfiguration = { device, format: presentationFormat, }; context.configure(swapChainDesc); const computePipeline = device.createComputePipeline({ layout: "auto", compute: { module: device.createShaderModule({ code: computeShaderCode, }), entryPoint: "main", }, }); const computePassDescriptor: GPUComputePassDescriptor = {}; const simParamBufferSize = 4 * 4; const simParamBuffer = device.createBuffer({ size: simParamBufferSize, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, }); createVertexIndexBuffer(); const vertexShader = device?.createShaderModule({ code: vertexShaderCode }); const fragmentShader = device?.createShaderModule({ code: fragmentShaderCode, }); const vertexBufferLayout: GPUVertexBufferLayout = { // arrayStride: 4 * 4, arrayStride: 8 * 4, stepMode: "vertex", attributes: [ { shaderLocation: 0, offset: 0, format: "float32x4", }, ], }; const pipelineDesc: GPURenderPipelineDescriptor = { layout: "auto", //@TODO replace for explicit declaration vertex: { module: vertexShader, entryPoint: "vert_main", buffers: [vertexBufferLayout], }, primitive: { topology: "line-list", }, fragment: { module: fragmentShader, entryPoint: "frag_main", targets: [ { format: presentationFormat, }, ], }, }; const pipeline = device.createRenderPipeline(pipelineDesc); const uniformBufferSize = 4 * 16; // 4x4 matrix const uniformBuffer = device.createBuffer({ size: uniformBufferSize, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, }); const bindGroupDesc: GPUBindGroupDescriptor = { layout: pipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: uniformBuffer, }, }, ], }; const uniformBindGroup = device.createBindGroup(bindGroupDesc); function createVertexIndexBuffer() { const { vertices, indices, numVerticesToDraw } = mesh.getMeshData(currSubdiv); const vertexData = new Float32Array(vertices); const bufferDesc: GPUBufferDescriptor = { size: vertexData.byteLength, // usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.STORAGE, mappedAtCreation: true, }; for (let i = 0; i < 2; i += 1) { vertexBuffer[i] = device!.createBuffer(bufferDesc); new Float32Array(vertexBuffer[i].getMappedRange()).set(vertexData); vertexBuffer[i].unmap(); } const indexData = new Uint32Array(indices); indexBuffer = device!.createBuffer({ size: indexData.byteLength, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST, }); device!.queue.writeBuffer(indexBuffer, 0, indexData); numToDraw = numVerticesToDraw; for (let i = 0; i < 2; i += 1) { vertexBindGroup[i] = device!.createBindGroup({ layout: computePipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: simParamBuffer, }, }, { binding: 1, resource: { buffer: vertexBuffer[i], offset: 0, size: vertexData.byteLength, }, }, { binding: 2, resource: { buffer: vertexBuffer[1 - i], offset: 0, size: vertexData.byteLength, }, }, ], }); } } function updateSimParams(deltaTime: number) { const s = new ArrayBuffer(4 * 4); const d = new Float32Array(s); d[1] = gravity; d[2] = centerOffset; d[3] = (deltaTime / 1000) * 2; const d2 = new Uint32Array(s); d2[0] = currSubdiv; device!.queue.writeBuffer(simParamBuffer, 0, s); } function renderFrame(timeStamp: number) { if (newSubdiv !== currSubdiv) { currSubdiv = newSubdiv; createVertexIndexBuffer(); } const elapsed = timeStamp - lastFrameTime; lastFrameTime = timeStamp; updateSimParams(elapsed); const transformationMatrix = getTransformationMatrix( armLength, angleYaw, anglePitch, ); device!.queue.writeBuffer( uniformBuffer, 0, transformationMatrix.buffer, transformationMatrix.byteOffset, transformationMatrix.byteLength, ); const renderPassDesc: GPURenderPassDescriptor = { colorAttachments: [ { view: context!.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: { r: 0.3, g: 0.3, b: 0.3, a: 1.0 }, }, ], }; const commandEncoder = device!.createCommandEncoder(); { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[1 - p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[1 - p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[1 - p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[1 - p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const passEncoder = commandEncoder.beginComputePass( computePassDescriptor, ); passEncoder.setPipeline(computePipeline); passEncoder.setBindGroup(0, vertexBindGroup[p]); passEncoder.dispatchWorkgroups(Math.ceil(numToDraw / 64)); passEncoder.end(); } { const renderPass = commandEncoder.beginRenderPass(renderPassDesc); renderPass.setPipeline(pipeline); renderPass.setBindGroup(0, uniformBindGroup); renderPass.setVertexBuffer(0, vertexBuffer[1 - p]); renderPass.setIndexBuffer(indexBuffer, "uint32"); renderPass.drawIndexed(numToDraw); renderPass.end(); } device!.queue.submit([commandEncoder.finish()]); p = 1 - p; requestAnimationFrame(renderFrame); } canvas.addEventListener("mousedown", mousePressed); canvas.addEventListener("mouseup", mouseUnpressed); canvas.addEventListener("mousemove", mouseMove); canvas.addEventListener("wheel", mouseWheel); lastFrameTime = document.timeline.currentTime as number; requestAnimationFrame(renderFrame); } function getTransformationMatrix( armLength: number, yaw: number, pitch: number, ) { const aspect = canvas!.width / canvas!.height; const projectionMatrix = mat4.perspective( (2 * Math.PI) / 6, aspect, 0.001, 100.0, ); const modelViewProjectionMatrix = mat4.create(); const viewMatrix = mat4.identity(); mat4.translate(viewMatrix, vec3.fromValues(0, 0, -1 * armLength), viewMatrix); mat4.rotate(viewMatrix, vec3.fromValues(-1, 0, 0), pitch, viewMatrix); mat4.rotate(viewMatrix, vec3.fromValues(0, -1, 0), yaw, viewMatrix); mat4.multiply(projectionMatrix, viewMatrix, modelViewProjectionMatrix); return modelViewProjectionMatrix as Float32Array; } function mousePressed(mouseEvent: MouseEvent) { mouseLastX = mouseEvent.clientX; mouseLastY = mouseEvent.clientY; bMousePressed = true; } function mouseUnpressed() { bMousePressed = false; } function mouseMove(mouseEvent: MouseEvent) { if (bMousePressed) { anglePitch += 0.007 * (mouseLastY - mouseEvent.clientY); angleYaw += 0.007 * (mouseLastX - mouseEvent.clientX); anglePitch = Math.min(Math.PI / 2 - 1, anglePitch); anglePitch = Math.max(-Math.PI / 2 + 0.1, anglePitch); mouseLastX = mouseEvent.clientX; mouseLastY = mouseEvent.clientY; } } function mouseWheel(mouseEvent: WheelEvent) { if (mouseEvent.deltaY > 0) { armLength *= 1.4; } else { armLength *= 0.71; } armLength = Math.max(armLength, 1); armLength = Math.min(armLength, 10); } function updateSubdiv(subdiv: number) { newSubdiv = subdiv; } function updateCenterOffset(c: number) { centerOffset = c; } function toggleGravity() { gravity = -9.8 - gravity; } export default { init, updateSubdiv, updateCenterOffset, toggleGravity };
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, type CarouselApi, } from "@/components/ui/carousel"; import React from "react"; import { CarouselContentData } from "@/utils/mock/data"; export default function CarouselSection() { const [api, setApi] = React.useState<CarouselApi>(); const [current, setCurrent] = React.useState(0); const [count, setCount] = React.useState(0); React.useEffect(() => { if (!api) { return; } setCount(api.scrollSnapList().length); setCurrent(api.selectedScrollSnap() + 1); api.on("select", () => { setCurrent(api.selectedScrollSnap() + 1); }); }, [api]); return ( <div className="w-full bg-primary px-8 py-16 text-primary-foreground "> <div className="container mx-auto"> <Carousel setApi={setApi} className="w-full max-w-6xl mx-auto"> <CarouselContent> {CarouselContentData.map((item) => ( <CarouselItem key={item.id}> <div className="flex items-start flex-col lg:flex-row lg:items-center gap-6 lg:gap-16"> <div className={` p-6 w-full lg:w-[600px] lg:h-[280px] h-[200px] flex lg:justify-center justify-start items-center ${ item.id === 1 ? "bg-[#B4DC19]" : item.id === 2 ? "bg-[#9B0032]" : item.id === 3 ? "bg-[#9B0032]" : item.id === 4 ? "bg-[#B4C8E1]" : item.id === 5 ? "bg-[#14C8EB]" : item.id === 6 ? "bg-[#FA551E]" : "" } `} > <img src={item.logo} alt="uf" /> </div> <div className="flex flex-col gap-4"> <span className="text-base">“{item.desc}”</span> <div> <h4 className="font-title text-primary-foreground text-lg leading-8"> {item.owner} </h4> <p className="text-muted-foreground font-semibold"> {item.position} </p> </div> </div> </div> </CarouselItem> ))} </CarouselContent> <CarouselPrevious className="text-black" /> <CarouselNext className="text-black" /> </Carousel> <div className="py-2 text-center text-sm text-muted-foreground"> {current} / {count} </div> </div> </div> ); } { /** [&:nth-child(1)]:bg-[#B4DC19] [&:nth-child(2)]:bg-[#9B0032] [&:nth-child(3)]:bg-[#9B0032] [&:nth-child(4)]:bg-[#B4C8E1] [&:nth-child(5)]:bg-[#14C8EB] [&:nth-child(6)]:bg-[#FA551E] */ }
<template> <div> <!-- 面包屑导航 --> <el-breadcrumb separator-class="el-icon-arrow-right"> <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item> <el-breadcrumb-item>权限管理</el-breadcrumb-item> <el-breadcrumb-item>权限列表</el-breadcrumb-item> </el-breadcrumb> <!-- 卡片区 --> <el-card> <!-- 权限列表渲染 --> <el-table :data="rightsList" style="width: 100%" border stripe> <el-table-column type="index" label="#"></el-table-column> <el-table-column prop="authName" label="权限名称"> </el-table-column> <el-table-column prop="path" label="路径"> </el-table-column> <el-table-column prop="level" label="权限等级"> <template slot-scope="scope"> <el-tag v-if="scope.row.level == 0">一级</el-tag> <el-tag type="success" v-else-if="scope.row.level == 1" >二级</el-tag > <el-tag type="warning" v-else>三级</el-tag> </template> </el-table-column> </el-table> </el-card> </div> </template> <script> export default { created() { // 渲染列表 this.getrightsList(); }, data() { return { rightsList: [], }; }, methods: { // 渲染列表 async getrightsList() { const { data: res } = await this.$http.get("rights/list"); console.log(res); this.rightsList = res.data; }, }, }; </script> <style lang="less" scoped> .el-card { margin-top: 30px; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important; } </style>
# Задача 4 # Задана натуральная степень k. Сформировать случайным образом список # коэффициентов (значения от 1 до 100, можно создать свой генератор # случайных чисел или использовать готовый) многочлена и записать в файл # многочлен степени k. # Пример: # k=2 => 2*x² + 4*x + 5 = 0 from random import randint import itertools k = randint(2, 8) def get_ratios(k): ratios = [randint(0, 100) for i in range (k + 1)] while ratios[0] == 0: ratios[0] = randint(1, 100) return ratios def get_polynomial(k, ratios): var = ['*x^']*(k-1) + ['*x'] polynomial = [[a, b, c] for a, b, c in itertools.zip_longest(ratios, var, range(k, 1, -1), fillvalue = '') if a !=0] for x in polynomial: x.append(' + ') polynomial = list(itertools.chain(*polynomial)) polynomial[-1] = ' = 0' return "".join(map(str, polynomial)).replace(' 1*x',' x') ratios = get_ratios(k) polynom1 = get_polynomial(k, ratios) print(polynom1) with open('task_4.txt', 'w') as data: data.write(polynom1)
import { Link, useNavigate } from "react-router-dom"; import { useState } from "react"; import { BiCameraMovie, BiSearchAlt2 } from 'react-icons/bi'; import "./Navbar.css"; const Navbar = () => { const [search, setSearch] = useState(""); const navigate = useNavigate(); // Criando função de submit do formulário const handleSubmit = (e) => { e.preventDefault(); // Verificando se algo foi digitado no campo de pesquisa if (!search) { return; } navigate(`/search?filme=${search}`); setSearch(""); }; return ( <nav id="navbar"> <h2> <BiCameraMovie /> <Link to="/"> Infiniflix </Link> </h2> <form onSubmit={handleSubmit}> <input type="text" placeholder="Busque um filme" onChange={(e) => setSearch(e.target.value)} value={search} /> <button type="submit"> <BiSearchAlt2 /> </button> </form> </nav> ); }; export default Navbar;
import { RequestHandler, compose } from "@hattip/compose"; import { once } from "@hiogawa/utils"; import { loggerMiddleware } from "@hiogawa/utils-experimental"; import { globApiRoutes } from "@hiogawa/vite-glob-routes/dist/hattip"; import { importIndexHtml } from "@hiogawa/vite-import-index-html/dist/runtime"; import { rpcHandler } from "../trpc/server"; import { initializeOpentelemetry, traceForceFlushHandler, traceRequestHandler, } from "../utils/opentelemetry"; import { initializeServerHandler } from "../utils/server-utils"; import { WORKER_ASSET_URLS } from "../utils/worker-client"; import { WORKER_ASSET_URLS_LIBWEBM } from "../utils/worker-client-libwebm"; import { initailizeWorkerEnv } from "../utils/worker-env"; export function createHattipEntry() { return compose( loggerMiddleware(), bootstrapHandler(), // bootstrap includes opentelemetry initialization traceForceFlushHandler(), traceRequestHandler(), initializeServerHandler(), rpcHandler(), globApiRoutes(), htmlHandler() ); } function htmlHandler(): RequestHandler { return async () => { let html = await importIndexHtml(); html = html.replace("<!--@INJECT_HEAD@-->", injectToHead()); return new Response(html, { headers: { "content-type": "text/html" } }); }; } function injectToHead(): string { return [ [...WORKER_ASSET_URLS, ...WORKER_ASSET_URLS_LIBWEBM].map( (href) => `<link rel="prefetch" href="${href}" />` ), ] .flat() .join("\n"); } function bootstrapHandler() { return once(async () => { await initailizeWorkerEnv(); await initializeOpentelemetry(); }); }
// This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/03/a/PC.hdl /** * A 16-bit counter with load and reset control bits. * if (reset[t] == 1) out[t+1] = 0 * else if (load[t] == 1) out[t+1] = in[t] * else if (inc[t] == 1) out[t+1] = out[t] + 1 (integer addition) * else out[t+1] = out[t] */ CHIP PC { IN in[16],load,inc,reset; OUT out[16]; PARTS: // Put your code here: Inc16(in=outT, out=outTPlus1); // out[t] + 1 Mux16(a=outT, b=outTPlus1, sel=inc, out=isInc); //if (inc[t] == 1)out[t+1] = out[t] + 1 Mux16(a=isInc, b=in, sel=load, out=tPlus1OrInc); //if (load[t] == 1) out[t+1] = in[t] Mux16(a=tPlus1OrInc, b=false, sel=reset, out=t); //if (reset[t] == 1) out[t+1] = 0 Or(a=load, b=inc, out=loadOrInc); Or(a=loadOrInc, b=reset, out=loadReg); Register(in=t, load=loadReg, out=out, out=outT); }
// Time complexity can only be calculated on same programming device //Notation for different type of complexity --> Omega, Theta, Big O /* 1. Big oh Notation --> upper bound [Time Complexity] a. for(int i=0;i<n;i++){ cout<<"MoniChaurasiya\n"; --> n time loop will execute } Ans- O(n) b. for(int i=0;i<n;i+=2){ cout<<"MoniChaurasiya\n"; --> n/2 time loop will execute } Ans- O(n/2) ~ O(n) ______________________________________________ | formula --> O(kn) = O(n) (k is constant) | |______________________________________________| __________________________________________________ | formula --> O(n +- k) = O(n) (k is constant) | |__________________________________________________| ________________________________________________________________________________ | formula --> O(k1n^m +- k2n^(m-1) +- k3n^(m-2) ... = O(n^m) (k is constant) | |________________________________________________________________________________| Example --> O(5n^3 + 3) = O(n^3) O(6n^2 - 8) = O(n^2) O(6n^2 + n) = O(n^2) int a[n], b[m]; for(int i=0; i<n; i++){ a[i]++; --> n time loop will execute } Ans- O(n) for(int i=0; i<m; i++){ b[i]++; --> m time loop will execute } Ans- O(m) Answer -->Time Complexity is O(n+m) a. for(int i=0;i<n;i++){ --> n time loop will execute for(int j=0;j<n;j++){ cout<<"MoniChaurasiya\n"; --> n time loop will execute } } Time Compexity is O(n*n) = O(n^2) b. for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ cout<<"MoniChaurasiya\n"; } } Time Compexity is O(n(n+1)/2) = O(n^2) c. for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cout<<"MoniChaurasiya\n"; } for(int j=0;j<m;j++){ cout<<"MoniChaurasiya\n"; } for(int j=0;j<m;j++){ cout<<"MoniChaurasiya\n"; } } Time Compexity is O(n*(m+m+m) = O(n*3m) =O(nm) d. int c=0; for(int i=0; i<=n; i+=k){ c++; } i = 1, k^2, k^3, k^4, k^5, ... k^x This loop will end when k^x > n Time complexity is O(x) =O(log k n) =O(log n) e. int c=0; for(int i=0;i<n;i++){ for(int j=i+1;j<m;j++){ c++; } } total no : (m-1)+ (m-2)+ (m-3)+ (m-4)+ ... (m-(n+1)) --> no of term is n+1 sum = n/2 [first Term + last Term] = n/2 [m-1+m-n-1] = n/2 [2m-2-n] Time Compexity is O(n/2 [2m-2-n]) = O(n*m -n^2) = O(m*n) because m>n 2. Big oh Notation --> upper bound [Space Complexity] a. int c=0; for(int i=0;i<n; i++){ c++; --> Space Complexity is O(1) & Time Complexity is O(n) } b. int c[n]; for(int i=0;i<n; i++){ c[i]++; --> Space Complexity is O(n) & Time Complexity is O(n) } c. vector<int> a; vector<int> b; for(int i=0;i<n; i++){ for(int j=0;j<m; j++){ a.push_back(10); --> Space Complexity is O(n*m) & Time Complexity is O(n*m) b.push_back(5); } } d. vector<int> a[n]; vector<int> b[m]; for(int i=0;i<n; i++){ for(int j=0;j<m; j++){ a[i]=i; --> Space Complexity is O(n*m) & Time Complexity is O(n+m) b[j]=j; } } e. Space complexity of creating 2D matrix int arr[m][n]; --> space complexity is O(m*n) f. int a[n], b[n], c[n]; for(int i=0;i<n; i++){ c++; --> Space Complexity is O(3n)=O(n) & Time Complexity is O(n) } g. int a[n][n/2]; for(int i=1;i<n; i*=2){ for(int j=0;j<n/2; j++){ a[i][j]++; --> Space Complexity is O(n * n/2)=O(n^2) & Time Complexity is O(n/2 * log 2 n) = O(n.logn) } } h. int c=0; for(i=0;i<n; i+=i){ c++; } i= 1,2,4,8,16,32... i= 1, 2^1, 2^2, 2^3, 2^4, 2^5...2^x --> x+1 term Time Complexity is O(x+1) =O(x)= O(log 2 n) = O(log n ) -->Ignore base we can write (log 2 n) instead of (log 3 n) --> O(log 3 n)= O(log 2 n/log 2 3) = O(log 3 2 . log 2 n) = O(k.log 2 n) = O(log n ) i. int c=0; for(i=0;i<n; i+=i){ for(j=0;j<i; j++){ c++; } } i=0, j=0 -->1 i=2, j=0,1 -->2 i=4, j=0,1,2,3 -->4 i=8, j=0,1,2,3,4,5,6,7 -->8 = 1 + 2^1 + 2^2 + 2^3 + 2^4 + 2^5...+ 2^x --> x+1 term [ sum of n term = a[r^T-1]/r-1 ] = 1[2^(n+1)-1]/ 2-1 = 2^(n+1)-1 = O(2^(n+1)-1) = O(2.2^n) = O(kn) = O(n) 1+2+4+8+16...n/2 + n (1+1)+2+4+8+16...n/2 + n -1 (2+2)+4+8+16...n/2 + n -1 (4+4)+8+16...n/2 + n -1 (8+8)+16...n/2 + n -1 (16+16)...n/2 + n -1 32...n/2 + n -1 Time Complexity = O(2n-1) = O(n) j. int c=0; for(int i=1;i<=n;i++){ Time Complexity = O(logn) for(int j=n;j>=0;j--){ Time Complexity = O(n) c++; } } Total Time Complexity = O(n.logn) k. int c=0; for(int i=1;i*i<=n;i*=2){ Time Complexity = O(2^x * 2^x)= O(n) for(int j=0;j<i;j++){ c++; } } i=1,2,4,8,16...2^x [2^x=root n] 2^x * 2^x = n total iterations = 1+2+3+4+ ...2^x = 2^(x-1) -1 Time Complexity = O(2^x) = O(root n) k. int c=0; for(int i=1;i*i<=n;i*=2){ Time Complexity = O(2^x * 2^x)= O(n) for(int j=n;j>i;j--){ c++; } } i=1,2,4,8,16...2^x [2^x=root n] 2^x * 2^x = n total j iterations = n-root n total number of iterations = (n-1)+(n-2)+(n-4)+(n-8)+ ...(n-2^x) = (n+n+n+n...)-(1+2+4+8+...2^x) =n(x+1)+[2^(x+1)-1)] = n.x+n - 2.2^x -1 Time Complexity = O(n.log 2 rootn + n - rootn) = O(n.log root n) = O(n.(1/2)log n) = O(n.logn) l. int c=0; for(int i=1;i*i<n;i*=2){ for(int j=0;j<i;j++){ c++; } } i= 1,2,4,8,16...2^x [2^x=root n] total iterations =1+2+3+4+...2^x =2^(x+1)-1 Time complexity = O(2^x)=O(root n) m. int c=0; for(int i=1;i*i<n;i+=i){ for(int j=n;j>i;j--){ -->[n-i] c++; } } i= 1,2,4,8,16...2^x [2^x=root n] --> x=log root n total iterations =(n-1)+(n-2)+(n-3)+(n-4)+...(n-2^x) = (n+n+n+n...) - (1+2+4+8+...2^x) --> both term is x+1 term =n(x+1)-2^(x+1)-1 =n.x + n - 2.2^x + 1 Time complexity = O(n.log 2 root n + n- root n)=O(n.log root n) = O(n.1/2 .log n) = O(n.logn) n. int c=0; for(int i=1;i*i<n;i*=i){ c++; } } i=2,4,16,256,256*256... i=2,2^2,2^4,2^8,2^16... i=2^1,2^2^1,2^2^2,2^2^3,2^2^4... [x+1 term] 2^(2^x)=root n x=log(log root n)= log((1/2).log n)=log 1/2 + log(log n) time complexity = O(log(log n)) o. Time Complexity of fibonacci number int fibo(int n){ if(n==1 || n==2) return 1; return fibo (n-1)+ fibo (n-2); } for n 1+2^1+2^2+2^3+2^4...2^(n-1) = 1(2^n-1)/(2-1) = 2^n-1 Time Complexity of fibonacci series is O(2^n) p. Time Complexity of GCD(a,b) is O(log(a+b)) */
import { NextApiRequest, NextApiResponse } from "next"; import { sesClient } from "../../lib/aws/sesClient"; import sanitizeHtml from 'sanitize-html'; import { randomUUID } from "crypto"; import { isPossiblePhoneNumber } from "react-phone-number-input"; import isEmail from "validator/lib/isEmail"; import IContact from "../../types/IContact"; import { initialContactState } from "../../lib/helpers/contactReducer"; import { createSendContactEmailTemplateCommand } from "../../lib/aws/createSendContactEmailTemplateCommand"; export default async function contactHandler ( req: NextApiRequest, res: NextApiResponse) { if (req.method === "POST") { /* Check if user has passed the Captcha */ try { const result = await fetch("https://www.google.com/recaptcha/api/siteverify", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: `secret=${process.env.GOOG_CAPTCHA_SECRET_KEY}&response=${req.body.gRecaptchaToken}`, }) const reCaptchaRes = await result.json() console.log(reCaptchaRes) if (reCaptchaRes?.score > 0.5) { /* Passed recaptcha */ /* Check if user has Consented */ if(!req.body.hasConsented) { res.status(500).send({error: 'User has not consented to our Privacy Policy'}); res.end(); } /* Sanitize Input */ let sanitzedContact : IContact = {...initialContactState} for(const [key, value] of Object.entries(req.body)) { if(typeof value === 'string') { sanitzedContact = {...sanitzedContact, [key]: sanitizeHtml(value) } } else { sanitzedContact = {...sanitzedContact, [key]: value } } } /* Validate Input */ if(!isEmail(sanitzedContact.email)) { res.status(500).send({error: 'Invalid email address'}) res.end(); } if(sanitzedContact.phone) { if(!isPossiblePhoneNumber(sanitzedContact.phone.toString())) { res.status(500).send({error: 'Invalid phone number'}) res.end(); } } else { res.status(500).send({error: 'Phone number required'}) res.end(); } /* Create a Ref Number */ const date = new Date() const refId = `${randomUUID().slice(0,5)}-${req.body.name.slice(0,3)}-${date.getFullYear()}` sanitzedContact = {...sanitzedContact, refId} /* Create SES Command */ const sendEmailCommand = createSendContactEmailTemplateCommand( sanitzedContact ); /* Send Email and return response */ try { const response = await sesClient.send(sendEmailCommand); return res.status(200).json(response) } catch (e) { return res.status(500).send(e); } } else { // Failed captcha res.status(200).json({ status: "failure", message: "Google ReCaptcha Failure", }); } } catch (err) { res.status(405).json({ status: "failure", message: "Error submitting the contact form", }); } } else { res.status(405); res.end(); } };
import 'dart:convert'; import 'dart:io'; import 'package:event/data/controllers/limit_query_controller.dart'; import 'package:event/data/models/event_model.dart'; import 'package:event/data/models/filter_model.dart'; import 'package:event/data/repositories/repository.dart'; class EventRepository extends Repository { Future<List<Event>> getEvents( int offset, int limit, { Filter? filter, // String? query, // List<String>? services, // double? distance, bool isAuth = false, Coord? geo, }) async { String servicesArray = ""; if (filter != null && filter.services.isNotEmpty) { for (var element in filter.services) { servicesArray = servicesArray + "services=$element&"; } } ResponseData _res = await getRequest( "events", "${isAuth ? "user" : "public"}/events?type=ACTIVITY${geo != null && filter != null && filter.distance != double.infinity ? '&area={"lat": ${geo.lat}, "lng": ${geo.lng}, "radius": ${filter.distance}}' : ""}&limit=$limit&offset=$offset&name=${filter?.query ?? ''}&${servicesArray}archive=false", headers: { 'accept': 'application/json', "Authorization": Repository.token }, ); if (_res.status == 200) { List excursions = jsonDecode(_res.data); return excursions.map((e) => Event.fromJson(e)).toList(); } return []; } Future<Event?> getEvent(int id) async { ResponseData _res = await getRequest( "events", "public/events/$id", headers: { "accept": "*/*", "Content-Type": "application/json", "Authorization": Repository.token }, ); if (_res.status == 200) { return Event.fromJson(jsonDecode(_res.data)); } return null; } Future<List<Event>> getUserEvents( ActivityStatus status, int offset, { int? userId, }) async { ResponseData _res = userId != null ? await getRequest( "events", "public/events?type=ACTIVITY&limit=$indexOffsetLimit&offset=$offset&userId=$userId&archive=${status == ActivityStatus.archive}", headers: { "accept": "application/json", "Authorization": Repository.token }, ) : await getRequest( "events", "user/events/my?status=${Event.getTypeName(status, toJson: true)}&type=ACTIVITY&limit=$indexOffsetLimit&offset=$offset${status == ActivityStatus.published ? "&published=true" : ""}", headers: { "accept": "application/json", "Authorization": Repository.token }, ); if (_res.status == 200) { List excursions = jsonDecode(_res.data); return excursions.map((e) => Event.fromJson(e)).toList(); } return []; } Future<List<Event>> getFavoriteEvents(int offset) async { ResponseData _res = await getRequest( "events", "user/events/favorite?type=ACTIVITY&limit=$indexOffsetLimit&offset=$offset", headers: { 'accept': 'application/json', "Authorization": Repository.token }, ); if (_res.status == 200) { List events = jsonDecode(_res.data); return events.map((e) => Event.fromJson(e, isFavorite: true)).toList(); } return []; } Future<ResponseData> addToFavorite(int id) async { ResponseData _res = await postRequest( service: "events", url: "user/events/$id/favorite", parametrs: "", headers: { 'accept': '*/*', "Authorization": Repository.token, "Content-Type": "application/json" }, ); if (_res.status == 204) { return ResponseData( data: _res.data, status: _res.status, isSuccesful: true, ); } return _res; } Future<ResponseData> daleteFromFavorite(int id) async { ResponseData _res = await deleteRequest( service: "events", url: "user/events/$id/favorite", headers: {'accept': '*/*', "Authorization": Repository.token}, ); if (_res.status == 204) { return ResponseData( data: _res.data, status: _res.status, isSuccesful: true, ); } return _res; } Future<ResponseData> deleteEvent(int id) async { ResponseData _res = await deleteRequest( service: "events", url: "user/events/$id", headers: {"accept": "*/*", "Authorization": Repository.token}, ); if (_res.status == 204) { return ResponseData( data: "Экскурсия удалена", status: _res.status, isSuccesful: true, ); } return _res; } Future<ResponseData> editEvent(Event event, List<File> files) async { List<String> imageIds = []; for (var element in files) { imageIds.add((await uploadFile(element)).data); } event.images.addAll(imageIds); //log(jsonEncode(event.toJson())); ResponseData _res = await putRequest( url: "user/events/${event.id}", service: "events", parametrs: jsonEncode(event.toJson()), headers: { "accept": "*/*", "Content-Type": "application/json", "Authorization": Repository.token }, ); if (_res.status == 204) { return ResponseData( data: "Изменения сохранены", status: _res.status, isSuccesful: true, ); } return _res; } Future<ResponseData> addEvent(Event event, List<File> files) async { List<String> imageIds = []; for (var element in files) { imageIds.add((await uploadFile(element)).data); } event.images.clear(); event.images.addAll(imageIds); ResponseData _res = await postRequest( url: "user/events", service: "events", parametrs: jsonEncode(event.toJson()), headers: { "accept": "*/*", "Content-Type": "application/json", "Authorization": Repository.token }, ); return ResponseData( data: _res.data, status: _res.status, isSuccesful: _res.status == 200, ); } }
pragma solidity 0.4.24; // File: contracts\lib\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "only owner is able to call this function"); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts\lib\Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts\lib\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts\lib\Crowdsale.sol /** * @title Crowdsale - modified from zeppelin-solidity library * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; // event for token purchase logging // purchaser who paid for the tokens // beneficiary who got the tokens // value weis paid for purchase // amount amount of tokens purchased event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function initCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require( startTime == 0 && endTime == 0 && rate == 0 && wallet == address(0), "Global variables must be empty when initializing crowdsale!" ); require(_startTime >= now, "_startTime must be more than current time!"); require(_endTime >= _startTime, "_endTime must be more than _startTime!"); require(_wallet != address(0), "_wallet parameter must not be empty!"); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } } // File: contracts\lib\FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts\lib\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts\Whitelist.sol /** * @title Whitelist - crowdsale whitelist contract * @author Gustavo Guimaraes - <gustavo@starbase.co> */ contract Whitelist is Ownable { mapping(address => bool) public allowedAddresses; event WhitelistUpdated(uint256 timestamp, string operation, address indexed member); /** * @dev Adds single address to whitelist. * @param _address Address to be added to the whitelist */ function addToWhitelist(address _address) external onlyOwner { allowedAddresses[_address] = true; emit WhitelistUpdated(now, "Added", _address); } /** * @dev add various whitelist addresses * @param _addresses Array of ethereum addresses */ function addManyToWhitelist(address[] _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { allowedAddresses[_addresses[i]] = true; emit WhitelistUpdated(now, "Added", _addresses[i]); } } /** * @dev remove whitelist addresses * @param _addresses Array of ethereum addresses */ function removeManyFromWhitelist(address[] _addresses) public onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { allowedAddresses[_addresses[i]] = false; emit WhitelistUpdated(now, "Removed", _addresses[i]); } } } // File: contracts\TokenSaleInterface.sol /** * @title TokenSale contract interface */ interface TokenSaleInterface { function init ( uint256 _startTime, uint256 _endTime, address _whitelist, address _starToken, address _companyToken, uint256 _rate, uint256 _starRate, address _wallet, uint256 _crowdsaleCap, bool _isWeiAccepted ) external; } // File: contracts\TokenSaleForAlreadyDeployedERC20Tokens.sol /** * @title Token Sale contract - crowdsale of company tokens. * @author Gustavo Guimaraes - <gustavo@starbase.co> */ contract TokenSaleForAlreadyDeployedERC20Tokens is FinalizableCrowdsale, Pausable { uint256 public crowdsaleCap; // amount of raised money in STAR uint256 public starRaised; uint256 public starRate; bool public isWeiAccepted; // external contracts Whitelist public whitelist; ERC20 public starToken; // The token being sold ERC20 public tokenOnSale; event TokenRateChanged(uint256 previousRate, uint256 newRate); event TokenStarRateChanged(uint256 previousStarRate, uint256 newStarRate); event TokenPurchaseWithStar(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev initialization function * @param _startTime The timestamp of the beginning of the crowdsale * @param _endTime Timestamp when the crowdsale will finish * @param _whitelist contract containing the whitelisted addresses * @param _starToken STAR token contract address * @param _tokenOnSale ERC20 token for sale * @param _rate The token rate per ETH * @param _starRate The token rate per STAR * @param _wallet Multisig wallet that will hold the crowdsale funds. * @param _crowdsaleCap Cap for the token sale * @param _isWeiAccepted Bool for acceptance of ether in token sale */ function init( uint256 _startTime, uint256 _endTime, address _whitelist, address _starToken, address _tokenOnSale, uint256 _rate, uint256 _starRate, address _wallet, uint256 _crowdsaleCap, bool _isWeiAccepted ) external { require( whitelist == address(0) && starToken == address(0) && rate == 0 && starRate == 0 && tokenOnSale == address(0) && crowdsaleCap == 0, "Global variables should not have been set before!" ); require( _whitelist != address(0) && _starToken != address(0) && !(_rate == 0 && _starRate == 0) && _tokenOnSale != address(0) && _crowdsaleCap != 0, "Parameter variables cannot be empty!" ); initCrowdsale(_startTime, _endTime, _rate, _wallet); tokenOnSale = ERC20(_tokenOnSale); whitelist = Whitelist(_whitelist); starToken = ERC20(_starToken); starRate = _starRate; isWeiAccepted = _isWeiAccepted; owner = tx.origin; crowdsaleCap = _crowdsaleCap; } modifier isWhitelisted(address beneficiary) { require(whitelist.allowedAddresses(beneficiary), "Beneficiary not whitelisted!"); _; } /** * @dev override fallback function. cannot use it */ function () external payable { revert("No fallback function defined!"); } /** * @dev change crowdsale ETH rate * @param newRate Figure that corresponds to the new ETH rate per token */ function setRate(uint256 newRate) external onlyOwner { require(newRate != 0, "ETH rate must be more than 0"); emit TokenRateChanged(rate, newRate); rate = newRate; } /** * @dev change crowdsale STAR rate * @param newStarRate Figure that corresponds to the new STAR rate per token */ function setStarRate(uint256 newStarRate) external onlyOwner { require(newStarRate != 0, "Star rate must be more than 0!"); emit TokenStarRateChanged(starRate, newStarRate); starRate = newStarRate; } /** * @dev allows sale to receive wei or not */ function setIsWeiAccepted(bool _isWeiAccepted) external onlyOwner { require(rate != 0, "When accepting Wei you need to set a conversion rate!"); isWeiAccepted = _isWeiAccepted; } /** * @dev function that allows token purchases with STAR * @param beneficiary Address of the purchaser */ function buyTokens(address beneficiary) public payable whenNotPaused isWhitelisted(beneficiary) { require(beneficiary != address(0)); require(validPurchase() && tokenOnSale.balanceOf(address(this)) > 0); if (!isWeiAccepted) { require(msg.value == 0); } else if (msg.value > 0) { buyTokensWithWei(beneficiary); } // beneficiary must allow TokenSale address to transfer star tokens on its behalf uint256 starAllocationToTokenSale = starToken.allowance(beneficiary, address(this)); if (starAllocationToTokenSale > 0) { // calculate token amount to be created uint256 tokens = starAllocationToTokenSale.mul(starRate); //remainder logic if (tokens > tokenOnSale.balanceOf(address(this))) { tokens = tokenOnSale.balanceOf(address(this)); starAllocationToTokenSale = tokens.div(starRate); } // update state starRaised = starRaised.add(starAllocationToTokenSale); tokenOnSale.transfer(beneficiary, tokens); emit TokenPurchaseWithStar(msg.sender, beneficiary, starAllocationToTokenSale, tokens); // forward funds starToken.transferFrom(beneficiary, wallet, starAllocationToTokenSale); } } /** * @dev function that allows token purchases with Wei * @param beneficiary Address of the purchaser */ function buyTokensWithWei(address beneficiary) internal { uint256 weiAmount = msg.value; uint256 weiRefund = 0; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); //remainder logic if (tokens > tokenOnSale.balanceOf(address(this))) { tokens = tokenOnSale.balanceOf(address(this)); weiAmount = tokens.div(rate); weiRefund = msg.value.sub(weiAmount); } // update state weiRaised = weiRaised.add(weiAmount); tokenOnSale.transfer(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); wallet.transfer(weiAmount); if (weiRefund > 0) { msg.sender.transfer(weiRefund); } } // override Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (tokenOnSale.balanceOf(address(this)) == uint(0) && (starRaised > 0 || weiRaised > 0)) { return true; } return super.hasEnded(); } /** * @dev override Crowdsale#validPurchase * @return true if the transaction can buy tokens */ function validPurchase() internal view returns (bool) { return now >= startTime && now <= endTime; } /** * @dev finalizes crowdsale */ function finalization() internal { if (tokenOnSale.balanceOf(address(this)) > 0) { uint256 remainingTokens = tokenOnSale.balanceOf(address(this)); tokenOnSale.transfer(wallet, remainingTokens); } super.finalization(); } }
import React, { useState, useEffect } from "react"; import { useNavigate, useParams } from "react-router-dom"; import axios from "axios"; import Navbar from "../components/navbar"; import { Link } from "react-router-dom"; const EditBook = () => { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const { id } = useParams(); const navigate = useNavigate(); const [title, setTitle] = useState(""); const [author, setAuthor] = useState(""); const [publishYear, setPublishYear] = useState(""); // console.log("Id : " , id); useEffect(() => { axios .get(`http://localhost:5555/books/${id}`) .then((response) => { setTitle(response.data.title); setAuthor(response.data.author); setPublishYear(response.data.publishYear); setLoading(false); // Set loading to false when data is received successfully }) .catch((error) => { setError(error); // Set error state if the request fails setLoading(false); // Set loading to false even if there is an error }); }, []); // The empty dependency array means this effect runs once after the initial render if (loading) { return <div>Loading...</div>; } if (error) { return <div>Error occurred: {error.message}</div>; } const handleEditBook = () => { const data = { title, author, publishYear, }; setLoading(true); axios .put(`http://localhost:5555/books/${id}`, data) .then((response) => { console.log('Data updated successfully:', response.data); setLoading(false); navigate("/"); }) .catch((error) => { setError(error); // Set error state if the request fails setLoading(false); }); }; return ( <> <Navbar /> <Link to="/" class="btn btn-primary "> Go Back </Link> <div className="container mw-50 mt-5" style={{ maxWidth: "700px" }}> <div> <h1 className="text-center">Edit details</h1> <div className="mb-3"> <label class="form-label">Title</label> <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} class="form-control" /> </div> <div className="mb-3"> <label class="form-label">Author</label> <input class="form-control" type="text" value={author} onChange={(e) => setAuthor(e.target.value)} /> </div> <div className="mb-3"> <label class="form-label">Publish Year</label> <input class="form-control" type="text" value={publishYear} onChange={(e) => setPublishYear(e.target.value)} /> </div> <button onClick={handleEditBook} class="btn btn-primary"> Save </button> </div> </div> </> ); }; export default EditBook;
<script setup> import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'; import { Head, usePage, router } from '@inertiajs/vue3'; import StatusEnum from '../enums/StatusEnum' import TypeEnum from '../enums/TypeEnum' import PrimaryButton from '@/Components/PrimaryButton.vue'; import Trash from '@/Components/Trash.vue'; import View from '@/Components/View.vue'; import Pencil from '@/Components/Pencil.vue'; </script> <template> <AuthenticatedLayout> <template #header> <div class="header"> <h2 class="font-semibold text-xl text-gray-800 leading-tight">Dashboard</h2> <PrimaryButton class="ml-4" @click="create()"> Novo Imóvel </PrimaryButton> </div> </template> <div class="wrapper"> <div class="card offset-3"> <div class="table-responsive"> <table class="table table-bordered table-hover"> <thead> <tr> <th scope="col">Endereço</th> <th scope="col">Preço</th> <th scope="col">Tipo</th> <th scope="col">Status</th> <th scope="col"></th> </tr> </thead> <tbody> <tr v-for="imovel in imoveis"> <td>{{ imovel.endereco }}</td> <td class="price">{{ formatPrice(imovel.preco) }}</td> <td>{{ getTipoLabel(imovel.tipo) }}</td> <td>{{ getStatusLabel(imovel.status) }}</td> <td class="actions"> <button class="btn btn-outline-info" @click="view(imovel.id)"> <View/> </button> <button class="btn btn-outline-primary" @click="edit(imovel.id)"> <Pencil/> </button> <button class="btn btn-outline-danger" @click="destroy(imovel.id)"> <Trash/> </button> </td> </tr> </tbody> </table> </div> </div> </div> </AuthenticatedLayout> </template> <script> const BASE_ROUTE = '/imoveis' export default { name: 'ImoveisList', props: { imoveis: { type: Object, } }, data() { return { page: usePage(), showMessage: false, showError: false, message: '', error: '', } }, watch: { page() { this.flash(this.page.props.flash.message, this.page.props.flash.error) } }, methods: { destroy(id) { router.delete(`${BASE_ROUTE}/${id}`) }, edit(id) { router.get(`${BASE_ROUTE}/${id}/edit`) }, create() { router.get(`${BASE_ROUTE}/create`) }, view(id) { router.get(`${BASE_ROUTE}/${id}/view`) }, flash(message = null, error = null) { if (message) this.showMessage = true if (error) this.showError = true this.message = message this.error = error setTimeout(() => { this.hide() },4000) }, hide() { this.page.props.flash.message = '' this.page.props.flash.error = '' this.showMessage = false this.showError = false }, checkFlash() { if(this.page.props.flash.message || this.page.props.flash.error) { this.flash(this.page.props.flash.message, this.page.props.flash.error) } }, formatPrice(preco) { return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 }).format(preco) }, getTipoLabel(status) { switch (status) { case TypeEnum.CASA: return 'Casa' case TypeEnum.APARTAMENTO: return 'Apartamento' case TypeEnum.TERRENO: return 'Terreno' default: break; } }, getStatusLabel(status) { switch (status) { case StatusEnum.DISPONIVEL: return 'Disponível' case StatusEnum.ALUGADO: return 'Alugado' case StatusEnum.VENDIDO: return 'Vendido' default: break; } } }, updated() { this.checkFlash() }, created() { this.checkFlash() }, } </script> <style scoped> .header { display: flex; align-items: center; justify-content: space-between; } .wrapper { display: flex; flex-direction: column; gap: 32px; padding-top: 50px; } .card { margin-left: 0; background-color: #edf2fb; } .table-responsive { max-height: 700px; } th { background-color: #c1d4f9; } tbody { width: 700px; overflow-y: scroll; } thead { position: sticky; top: -1px; } .actions { display: flex; justify-content: space-evenly; } .my-btn { max-width: 150px; align-self: flex-end; } .price { font-family: 'Montserrat', sans-serif; } /* width */ ::-webkit-scrollbar { width: 8px; } /* Track */ ::-webkit-scrollbar-track { background: #edf2fb; border-radius: 10px; } /* Handle */ ::-webkit-scrollbar-thumb { background: #c1d4f9; border-radius: 10px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #3e7cf9; } </style>
const data = [ { id: 1, title: "The Lord of the Rings", publicationDate: "1954-07-29", author: "J. R. R. Tolkien", genres: [ "fantasy", "high-fantasy", "adventure", "fiction", "novels", "literature", ], hasMovieAdaptation: true, pages: 1216, translations: { spanish: "El señor de los anillos", chinese: "魔戒", french: "Le Seigneur des anneaux", }, reviews: { goodreads: { rating: 4.52, ratingsCount: 630994, reviewsCount: 13417, }, librarything: { rating: 4.53, ratingsCount: 47166, reviewsCount: 452, }, }, }, { id: 2, title: "The Cyberiad", publicationDate: "1965-01-01", author: "Stanislaw Lem", genres: [ "science fiction", "humor", "speculative fiction", "short stories", "fantasy", ], hasMovieAdaptation: false, pages: 295, translations: {}, reviews: { goodreads: { rating: 4.16, ratingsCount: 11663, reviewsCount: 812, }, librarything: { rating: 4.13, ratingsCount: 2434, reviewsCount: 0, }, }, }, { id: 3, title: "Dune", publicationDate: "1965-01-01", author: "Frank Herbert", genres: ["science fiction", "novel", "adventure"], hasMovieAdaptation: true, pages: 658, translations: { spanish: "", }, reviews: { goodreads: { rating: 4.25, ratingsCount: 1142893, reviewsCount: 49701, }, }, }, { id: 4, title: "Harry Potter and the Philosopher's Stone", publicationDate: "1997-06-26", author: "J. K. Rowling", genres: ["fantasy", "adventure"], hasMovieAdaptation: true, pages: 223, translations: { spanish: "Harry Potter y la piedra filosofal", korean: "해리 포터와 마법사의 돌", bengali: "হ্যারি পটার এন্ড দ্য ফিলোসফার্স স্টোন", portuguese: "Harry Potter e a Pedra Filosofal", }, reviews: { goodreads: { rating: 4.47, ratingsCount: 8910059, reviewsCount: 140625, }, librarything: { rating: 4.29, ratingsCount: 120941, reviewsCount: 1960, }, }, }, { id: 5, title: "A Game of Thrones", publicationDate: "1996-08-01", author: "George R. R. Martin", genres: ["fantasy", "high-fantasy", "novel", "fantasy fiction"], hasMovieAdaptation: true, pages: 835, translations: { korean: "왕좌의 게임", polish: "Gra o tron", portuguese: "A Guerra dos Tronos", spanish: "Juego de tronos", }, reviews: { goodreads: { rating: 4.44, ratingsCount: 2295233, reviewsCount: 59058, }, librarything: { rating: 4.36, ratingsCount: 38358, reviewsCount: 1095, }, }, }, ]; function getBooks() { return data; } function getBook(id) { return data.find((d) => d.id === id); } /* // destructuring const book = getBook(3); //const author = book.author; const { title, author, pages, publicationDate, genres, hasMovieAdaptation } = book; console.log(title, author, genres); //const primaryGenre = genres[0]; //const secondaryGenre = genres[1]; const [primaryGenre, secondaryGenre, ...otherGenres] = genres; console.log(primaryGenre, secondaryGenre, otherGenres); const newGenres = [...genres, "epic fantasy"]; newGenres; //-------------------------------------------------------------------------------------------------------------------------------- const updatedBook = { ...book, //Adding new property moviesPublicationDate: "2001-11-16", //Overwrittingan existing property pages: 1210, }; updatedBook; //function getYear(str) { // return str.split("-")[0]; //} const getYear = (str) => str.split("-")[0]; console.log(getYear(publicationDate)); const summary = `${title},a ${pages} -page long book ,was written by ${author} and published in ${getYear( publicationDate )} . The book has ${hasMovieAdaptation ? "" : "not"} been adapted as a movie`; summary; const pagesRange = pages > 1000 ? "over a thousand" : "less than 1000"; pagesRange; console.log(`our book is ${pagesRange} page long `); console.log(true && "some string"); console.log(false && "some string"); console.log(hasMovieAdaptation && "this book has a movie"); //falsy : 0,'',null,undefined console.log(0 && "some string"); console.log(true || "some string"); console.log(false || "some string"); console.log(book.translations.spanish); const spanishTranslation = book.translations.spanish || "not translated"; spanishTranslation; //console.log(); //const countWrong = book.reviews.librarything.reviewsCount || "no data"; //countWrong; //const count = book.reviews.librarything.reviewsCount ?? "no data"; //count; console.log(getTotoalReviwCount(book)); */ /* function getTotoalReviwCount(book) { const goodreads = book.reviews.goodreads.reviewsCount; const librarything = book.reviews.librarything?.reviewsCount ?? 0; return goodreads + librarything; } const books = getBooks(); books; const x = [1, 2, 3, 4, 5].map((el) => el * 2); console.log(x); const titles = books.map((book) => book.title); titles; const essentialData = books.map((book) => ({ title: book.title, author: book.author, reviewsCount: getTotoalReviwCount(book), })); essentialData; const longBooks = books .filter((book) => book.pages > 500) .filter((book) => book.hasMovieAdaptation); longBooks; const adventureBooks = books .filter((book) => book.genres.includes("adventure")) .map((book) => book.title); adventureBooks; const allBooksPages = books.reduce((sum, book) => sum + book.pages, 0); allBooksPages; const arr = [3, 5, 7, 2, 1, 6, 9, 4, 8]; const sorted = arr.slice().sort((a, b) => b - a); sorted; arr; const sortedByPages = books.sort((a, b) => a.pages - b.pages); sortedByPages; //---add object const newBook = { id: 6, title: "Harry Potter and the Chamber of Secrets", author: "J. K. Rowling", }; const booksAfterAdd = [...books, newBook]; booksAfterAdd; //----------- delete object const booksAfterDelete = booksAfterAdd.filter((book) => book.id !== 3); booksAfterDelete; const booksAfterUpdate = booksAfterDelete.map((book) => book.id === 1 ? { ...book, pages: 1 } : book ); booksAfterUpdate; */ // //.then((res) => res.json()) // .then((data) => console.log(data)); async function getTodos() { const res = await fetch("https://jsonplaceholder.typicode.com/todos"); const data = await res.json(); console.log(data); } getTodos();
def find_longest_tubes(tube_lengths, L1, L2): # Sort the tube lengths in descending order tube_lengths.sort(reverse=True) # Initialize the longest tube lengths as the first two tubes longest_tubes = [tube_lengths[0], tube_lengths[1]] # Initialize the total length of the longest tubes as the sum of the first two tubes longest_length = sum(longest_tubes) # Iterate through the remaining tubes for tube in tube_lengths[2:]: # If the sum of the longest tubes and the current tube is less than or equal to L1, add the current tube to the longest tubes if longest_length + tube <= L1: longest_tubes.append(tube) longest_length += tube # If the sum of the longest tubes is greater than L2, return impossible if longest_length > L2: return "Impossible" # Return the sum of the longest tubes return longest_length def main(): L1, L2, N = map(int, input().split()) tube_lengths = list(map(int, input().split())) print(find_longest_tubes(tube_lengths, L1, L2)) if __name__ == '__main__': main()
<mat-card elevation="5" fxFlex class="content"> <mat-card-title> <h2>Calculate BMI</h2> </mat-card-title> <mat-card-content id="form-content"> <form (ngSubmit)="onSubmit()" *ngIf="!submitted" [formGroup]="form" id="form1-content"> <mat-form-field> <label>Tezina(kg): </label> <input formControlName="tezina" matInput type="number" id="tezina" name="tezina" min="20" max="300"> </mat-form-field> <mat-form-field> <label>Visina(cm): </label> <input formControlName="visina" matInput type="number" id="visina" name="visina" min="20" max="300"> </mat-form-field> <mat-form-field> <label>Godine: </label> <input formControlName="godine" matInput type="number" id="godine" name="godine" min="1" max="120"> </mat-form-field> <!-- <mat-form-field> <label>Role</label> <mat-select formControlName="role"> <mat-option *ngFor="let role1 of roles" [value]="role1"> {{role1}} </mat-option> </mat-select> </mat-form-field> --> <button [disabled]="!form.valid" color="primary" mat-raised-button type="submit">Submit</button> <br> <button color="primary" mat-raised-button (click) = "this.router.navigate(['/'])" >Go Back</button> </form> <p *ngIf="notification" [class]="notification.msgType">{{notification.msgBody}}</p> <br> <mat-spinner *ngIf="submitted" mode="indeterminate"></mat-spinner> <br> <hr> </mat-card-content> </mat-card>
import { useState, useEffect } from 'react'; export default function useFetch(url, options) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchData = async () => { setLoading(true); try { const res = await fetch(url, options); if(res.status != 200) { setError({ 'message': `Failed to fetch ${url}`, 'status': `${res.status} ${res.statusText}`, }); setLoading(false); return; } const json = await res.json(); setData(json); setLoading(false) } catch (error) { setError(error); setLoading(false) } }; fetchData(); }, []); return { data, error, loading }; }; function useFetchListen(url, token, options) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchData = async () => { setLoading(true); try { let fetchUrl; if (!url.includes("?")) { fetchUrl = url + "?token=" + token } else { fetchUrl = url + "&token=" + token } const res = await fetch(fetchUrl, options); if(res.status != 200) { setError({ 'message': `Failed to fetch ${fetchUrl}`, 'status': `${res.status} ${res.statusText}`, }); setLoading(false); return; } const json = await res.json(); setData(json); setLoading(false) } catch (error) { setError(error); setLoading(false) } }; fetchData(); }, [url]); return { data, error, loading }; }; function useFetchGoogleAnalyticsIntegration(url, options, accountId, propertyId) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchData = async () => { if (url.includes('properties') && !accountId) { setData(null); return { data, loading, error } } if (url.includes('views') && !(accountId && propertyId)) { setData(null); return { data, loading, error } } setLoading(true); try { let endpoint = url; if (accountId) { endpoint += `&accountId=${accountId}` } if (propertyId) { endpoint += `&propertyId=${propertyId}` } const res = await fetch(endpoint, options); const json = await res.json(); setData(json); setLoading(false) } catch (error) { setError(error); setLoading(false) } }; fetchData(); }, [accountId, propertyId]); return { data, error, loading }; }; function useFetchGoogleAnalyticsFourIntegration(url, options, accountId) { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchData = async () => { if (url.includes('properties') && !accountId) { setData(null); return { data, loading, error } } setLoading(true); try { let endpoint = url; if (accountId) { endpoint += `&accountId=${accountId}` } const res = await fetch(endpoint, options); const json = await res.json(); setData(json); setLoading(false) } catch (error) { setError(error); setLoading(false) } }; fetchData(); }, [accountId]); return { data, error, loading }; }; export { useFetchGoogleAnalyticsIntegration, useFetchGoogleAnalyticsFourIntegration, useFetchListen };
import { useDispatch, useSelector } from "react-redux"; import { useEffect } from "react"; import { END } from "redux-saga"; import axios from "axios"; import AppLayout from "../components/AppLayout"; import PostForm from "../components/PostForm"; import PostCard from "../components/PostCard"; import { LOAD_POSTS_REQUEST } from "../reducers/post"; import { LOAD_MY_INFO_REQUEST } from "../reducers/user"; import wrapper from "../store/configureStore"; const Home = () => { const { me } = useSelector((state) => state.user); const { mainPosts, hasMorePost, loadPostsLoading, retweetError } = useSelector((state) => state.post); const dispatch = useDispatch(); useEffect(() => { if (retweetError) { alert(retweetError); } }, [retweetError]); useEffect(() => { function onScroll() { if (window.scrollY > document.documentElement.scrollHeight - document.documentElement.clientHeight - 1200) { if (hasMorePost && !loadPostsLoading) { const lastId = mainPosts[mainPosts.length - 1]?.id; dispatch({ type: LOAD_POSTS_REQUEST, data: lastId, }); } } } window.addEventListener("scroll", onScroll); return () => { window.removeEventListener("scroll", onScroll); }; }, [hasMorePost, loadPostsLoading, mainPosts]); return ( <AppLayout> {me && <PostForm />} {mainPosts.map((post) => ( <PostCard key={post.id} post={post} /> ))} </AppLayout> ); }; // 이게 있으면 화면그리기 전에 먼저 실행을 함. export const getServerSideProps = wrapper.getServerSideProps(async (context) => { console.log("getServerSideProps Start"); console.log(context); const cookie = context.req ? context.req.headers.cookie : ""; axios.defaults.headers.Cookie = ""; if (context.req && cookie) { axios.defaults.headers.Cookie = cookie; } context.store.dispatch({ type: LOAD_MY_INFO_REQUEST, }); context.store.dispatch({ type: LOAD_POSTS_REQUEST, }); // success 까지 기다리기 위해서 하는 조치 context.store.dispatch(END); //store.sagaTask 는 기존에 configStore.js 에서 처리함 await context.store.sagaTask.toPromise(); }); export default Home;
var crypto = require("crypto"); const axios = require("axios"); var db = require("../../models"); var RoleService = require("../../services/RoleService"); var roleService = new RoleService(db); var MembershipService = require("../../services/MembershipService"); var membershipService = new MembershipService(db); var UserService = require("../../services/UserService"); var userService = new UserService(db); var BrandService = require("../../services/BrandService"); var brandService = new BrandService(db); var db = require("../../models"); var CategoryService = require("../../services/CategoryService"); var categoryService = new CategoryService(db); var ProductService = require("../../services/ProductService"); var productService = new ProductService(db); var StatusService = require("../../services/StatusService"); var statusService = new StatusService(db); module.exports = { getProducts: async function () { try { const response = await axios.get( "http://143.42.108.232:8888/items/products" ); let products = response.data.data; const brandsArray = products.reduce((brands, product) => { if (!brands.includes(product.brand)) { brands.push(product.brand); } return brands; }, []); const categoriesArray = products.reduce((categories, product) => { if (!categories.includes(product.category)) { categories.push(product.category); } return categories; }, []); return { response: { brandsArray, categoriesArray, products }, statusCode: 200, }; } catch (error) { return { message: error?.message, statusCode: 500 }; } }, createBrands: async function (brandsArray) { for (brand of brandsArray) { try { const isExist = await brandService.getOneByName(brand); if (!(isExist instanceof db.Brand)) { const result = await brandService.createBrand(brand); if (!(result instanceof db.Brand)) { return { message: result?.errors[0].message, statusCode: 400, }; } } } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; }, createCategories: async function (categoriesArray) { for (category of categoriesArray) { try { const isExist = await categoryService.getOneByName(category); if (!(isExist instanceof db.Category)) { const result = await categoryService.createCategory( category ); if (!(result instanceof db.Category)) { return { message: result?.errors[0].message, statusCode: 400, }; } } } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; }, createProducts: async function (products) { let category; let brand; for (const product of products) { let temp = { name: product.name, imgUrl: product.imgurl, description: product.description, price: product.price, countInStock: product.quantity, brandName: product.brand, categoryName: product.category, }; try { category = await categoryService.getOneByName( temp.categoryName ); if (category === null) { return { message: `There is no ${product.category} category`, statusCode: 400, }; } brand = await brandService.getOneByName(temp.brandName); if (brand === null) { return { message: `There is no ${temp.brandName} brand`, statusCode: 400, }; } } catch (error) { return { message: error.message, statusCode: 500 }; } try { const isExist = await productService.checkIfExists( temp.name, ); if (!(isExist instanceof db.Product)) { const result = await productService.createProduct( temp.name, temp.imgUrl, temp.description, temp.price, temp.countInStock, brand.id, category.id ); if (!(result instanceof db.Product)) { return { message: result?.errors[0].message, statusCode: 400, }; } } } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; }, createRoles: async function () { const roles = ["Admin", "User"]; for (const role of roles) { try { const isRoleExist = await roleService.getOneByName(role); if (isRoleExist instanceof db.Role) { if (isRoleExist.isDeleted){ isRoleExist.isDeleted = false; await isRoleExist.save() } }else { const result = await roleService.createRole(role); if (!(result instanceof db.Role)) { return { message: `role ${role} could not be created. Error from server`, statusCode: 500, }; } } } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; }, createStatuses: async function () { const statuses = [ "Not-checkout", "In-progress", "Ordered", "Completed", ]; for (const status of statuses) { try { const existStatus = await statusService.getOneByName(status); if (existStatus instanceof db.Status) { if (existStatus.isDeleted){ existStatus.isDeleted = false; await existStatus.save() } }else { const result = await statusService.createStatus(status); if (!(result instanceof db.Status)) { return { message: `Status ${status} could not be created. Error from server`, statusCode: 500, }; } } } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; }, createMemberships: async function () { const memeberships = [ ["Bronze", 0], ["Silver", 15], ["Gold", 30], ]; for (const membership of memeberships) { try { const isMembershipExist = await membershipService.getOneByName( membership[0] ); if (isMembershipExist instanceof db.Membership) { if (isMembershipExist.isDeleted){ isMembershipExist.isDeleted = false; await isMembershipExist.save() } }else { const result = await membershipService.createMembership( membership[0], membership[1] ); if (!(result instanceof db.Membership)) { return { message: `${membership[0]} membership could not be created. Error from server`, statusCode: 500, }; } } } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; }, createUserAdmin: async function () { const adminObject = { firstName: process.env.ADMIN_FIRSTNAME_INIT, lastName: process.env.ADMIN_LASTNAME_INIT, username: process.env.ADMIN_USERNAME_INIT, email: process.env.ADMIN_EMAIL_INIT, password: process.env.ADMIN_PASSWORD_INIT, address: process.env.ADMIN_ADDRESS_INIT, phoneNumber: process.env.ADMIN_PHONENUMBER_INIT, }; try { const adminRole = await roleService.getOneNotDeletedById(1); const membershipBronze = await membershipService.getOneNotDeletedById(1); if ( adminRole instanceof db.Role && membershipBronze instanceof db.Membership ) { adminObject.roleId = adminRole.id; adminObject.membershipId = membershipBronze.id; try { const emailIsUsed = await userService.getOneByEmail( adminObject.email ); if (emailIsUsed != null) { return { message: "Provided email is already in use. Admin could not be created!", statusCode: 400, }; } const usernameIsUsed = await userService.getOneByUsername( adminObject.username ); if (usernameIsUsed != null) { return { message: "Provided username is already in use. Admin could not be created!", statusCode: 400, }; } const salt = crypto.randomBytes(16); crypto.pbkdf2( adminObject.password, salt, 310000, 32, "sha256", async (err, hashedPassword) => { if (err) { return { message: err?.message, statusCode: 500, }; } const result = await userService.createUser( adminObject.firstName, adminObject.lastName, adminObject.username, adminObject.email, hashedPassword, salt, adminObject.address, adminObject.phoneNumber, adminObject.membershipId, adminObject.roleId ); if (!(result instanceof db.User)) { return { message: result?.errors[0].message, statusCode: 400, }; } } ); } catch (error) { return { message: error?.message, statusCode: 500, }; } } return { message: "ok", statusCode: 200 }; } catch (error) { return { message: error?.message, statusCode: 500, }; } }, };
package com.albertojr.practicaandroidavanzado.Data.Remote import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteDataSourceImpl @Inject constructor( // private val moshi : // private val okHttpClient = // private val retrofit = private val api: DragonBallApi ) : RemoteDataSource { //The token is set to public to facilitate testing. public lateinit var token: String override suspend fun performLogin(loginData:String): String{ this.token = api.performLogin(loginData) return token } override suspend fun getHeroes(): List<GetHeroesResponse>{ token?.let { if(token.isNotEmpty()){ val requestData = "Bearer $token" return api.retrieveHeroes(requestData, GetHeroesRequestBody()) }else{ return mutableListOf() } //TODO Fix this method. I'm not sure which refactorization would be the best. } return mutableListOf() } override suspend fun updateHeroeFavStateRemote(id: String, isFav: Boolean) { token?.let { if(token.isNotEmpty()){ val requestData = "Bearer $token" api.updateHeroeFavStateRemote(requestData, GetFavRequestBody(id)) } } } override suspend fun retrieveHeroeLocations(id: String): List<GetLocationsResponse> { token?.let { if(token.isNotEmpty()){ val requestData = "Bearer $token" return api.retrieveHeroeLocations(requestData, GetLocationRequestBody(id)) } //TODO Fix this method. } return mutableListOf() } }
/* * Copyright (c) 2021 Talent Beyond Boundaries. * * This program 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 any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. */ import {Injectable} from '@angular/core'; import {environment} from "../../environments/environment"; import {HttpClient} from "@angular/common/http"; import {Observable} from "rxjs"; import {CandidateEducation} from "../model/candidate-education"; @Injectable({ providedIn: 'root' }) export class CandidateEducationService { private apiUrl: string = environment.apiUrl + '/candidate-education'; constructor(private http: HttpClient) { } createCandidateEducation(request): Observable<CandidateEducation> { return this.http.post<CandidateEducation>(`${this.apiUrl}`, request); } updateCandidateEducation(request): Observable<CandidateEducation> { return this.http.post<CandidateEducation>(`${this.apiUrl}/update`, request); } deleteCandidateEducation(id: number) { return this.http.delete<CandidateEducation>(`${this.apiUrl}/${id}`); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML5 Canvas</title> </head> <body> <canvas id="draw" width="800" height="800"></canvas> <script> var canvasContainer = document.querySelector("#draw"); var ctx = canvasContainer.getContext("2d"); canvasContainer.width = window.innerWidth; canvasContainer.height = window.innerHeight * .8; ctx.strokeStyle = 'blue'; ctx.lineJoin = 'round'; ctx.lineCap = 'round'; ctx.lineWidth = 10; let isDrawing = false; let lastX = 0; let lastY = 0; let hue = 0; let direction = true; function draw(e) { if (!isDrawing) { return } ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; ctx.beginPath(); ctx.moveTo(lastX, lastY); ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); [lastX, lastY] = [e.offsetX, e.offsetY]; hue++ if (hue >=360) { hue = 0; } if (ctx.lineWidth >= 100 || ctx.lineWidth <= 5) { direction = !direction; } if (direction) { ctx.lineWidth++; } else { ctx.lineWidth--; } } canvasContainer.addEventListener('mousemove', draw); canvasContainer.addEventListener('mousedown', (e) => { isDrawing = true; lastX = e.offsetX; lastY = e.offsetY; }); canvasContainer.addEventListener('mouseup', (e) => { isDrawing = false; }); </script> <style> html, body { margin: 0; } </style> <footer style="display: flex; flex-flow: column; justify-content: center; align-items:center; margin-top: 10px; margin-bottom: 10px;"> <span>Click and Drag to Draw</span> <span>Source code available on <a href="https://github.com/Dewiidar/CSSVariables">Github.</a> </span> <br> <span style="font-size: 20px;">Reach me out at <a href="https://www.linkedin.com/in/mohamed-dewidar-331252153/">Linkedin</a> </span> </footer> </body> </html>
<template> <CheckableGroup id="closed_with_solutions" :label="labels.closed_with_solutions" :info="info" validationName="Est-ce que ce site a été résorbé définitivement ?" > <span class="mb-4" >Un site est considéré comme résorbé si une solution pérenne en logement ou hébergement est mise en place pour 66% des habitants du site. </span> <Radio :value="true" label="Oui" variant="card" class="mr-1" name="closed_with_solutions" /> <Radio :value="false" label="Non" variant="card" name="closed_with_solutions" /> </CheckableGroup> </template> <script setup> import { computed, defineProps, toRefs } from "vue"; import { CheckableGroup, Radio } from "@resorptionbidonvilles/ui"; import labels from "../FormFermetureDeSite.labels"; const props = defineProps({ peopleWithSolutions: { type: Number, required: false, }, }); const { peopleWithSolutions } = toRefs(props); const info = computed(() => { if ( peopleWithSolutions.value === undefined || peopleWithSolutions.value === null ) { return ""; } return `D'après les informations renseignées, environ ${peopleWithSolutions.value}% des habitants du site ont été orientées vers une solution longue durée d’hébergement ou de logement adapté avec accompagnement, dont espace temporaire d'accompagnement`; }); </script>
import * as firebase from 'firebase/compat' import 'firebase/auth' import 'firebase/firestore' import 'firebase/storage' import { getAuth, onAuthStateChanged, sendEmailVerification } from 'firebase/auth'; import { getFirestore, setDoc, doc, arrayUnion, getDoc, } from 'firebase/firestore'; import { Alert } from 'react-native'; import { getDownloadURL, getStorage, ref } from 'firebase/storage'; import { updateLoginLogs } from './authentication/update-logs'; const firebaseConfig = { apiKey: 'AIzaSyCiSQj_UOC68vVNT64QIKZoZy0o0iKZpiQ', authDomain: 'pbms-7591f.firebaseapp.com', projectId: 'pbms-7591f', storageBucket: 'pbms-7591f.appspot.com', messagingSenderId: '1019923690377', appId: '1:1019923690377:web:5aaaa62242a54f1459e758', measurementId: 'G-7ETCGS7KN7', }; let app; if (firebase.apps.length === 0) { app = firebase.initializeApp(firebaseConfig); } else { app = firebase.app(); } const auth = firebase.auth(); const db = firebase.firestore(); const firestoreDB = getFirestore(app); const firebaseAuth = getAuth(app); const storageDB = getStorage(app) let authResponse; let user = auth.currentUser let activeBusinessAccount; let inventory; export function createaccount(email, password, businessName, navigation) { if (!email || !password || !businessName) { Alert.alert('Missing Fields', 'Some fields were missing please check the form') } else { auth.createUserWithEmailAndPassword(email, password) .then((userCredential) => { const user = userCredential.user; console.log('welcome ' + businessName) authResponse = true auth.updateCurrentUser(user, { displayName: businessName }) navigation.navigate('signin'); try { sendEmailVerification(user) console.log(authResponse) } catch (e) { console.log({ name: "email verification", message: e.message, code: e.code }) } }) .catch((error) => { const errorCode = error.code; const errorMessage = error.message; console.log({ name: 'authentication', errorCode: errorCode, errorMessage: errorMessage }) }); } } export async function createstorageaccount(config, navigation) { if (config) { console.log('connecting to firestore'); const business_reference = config const user = firebaseAuth.currentUser const doc_ref = doc(firestoreDB, 'clients', user.uid); const mock_storage = { "id": "item_id", "name": "Item Name", "description": "Item Description", "category": "Item Category", "barcode": "Item Barcode", "quantity": 10, "price": 19.99, "location": { "aisle": "Aisle Number", "shelf": "Shelf Number" }, "notes": "Additional Notes", "createdAt": "timestamp", "updatedAt": "timestamp" } activeBusinessAccount = user db.collection('clients') .doc(user.uid) .get() .then(documentSnapshot => { if (documentSnapshot.exists) { return Alert.alert( `${business_reference.name} already exists`, 'A business with the name ' + business_reference.name + 'already exists in our database', ); } else { setDoc(doc_ref, business_reference).then(() => { console.log('user firestore account created !'); setDoc(doc(firestoreDB, 'storage', user.uid), mock_storage).then(() => { navigation.navigate('home') }) }); } }); } else { business_reference = undefined; console.log( `${Date().toLowerCase().substring(0, 21)}: No user info was retrieved, please try again`, ); } } export function signin(email, password, navigation) { auth.signInWithEmailAndPassword(email, password).then((userCredential) => { const user = userCredential.user updateLoginLogs(user.uid) db.collection('clients').doc(user.uid).get().then((documentSnapshot) => { if (documentSnapshot.exists) { activeBusinessAccount = documentSnapshot.data() if (activeBusinessAccount !== null || undefined) { navigation.navigate('home') } else { console.error('error - username not found'); } } else { navigation.navigate('configure') } }).catch(error => { if (error.code === 'auth/email-already-in-use') { Alert.alert('Warning', 'the email already exists with an account'); } else if (error.code === 'auth/invalid-email') { Alert.alert('Invalid Email', 'please check your email formatting'); } else { console.error(error); } }); }) } export async function configure_store(id, config, navigation) { const reference = doc(db, 'clients', id) await updateDoc(reference, { stores: arrayUnion(config) }).then(() => { navigation.navigate('home') }).catch((e) => { console.error(e); }) } export async function get_inventory() { const docRef = doc(db, "storage", firebaseAuth.currentUser.uid); const docSnap = await getDoc(docRef); if (docSnap.exists()) { inventory = docSnap.data() } else { console.error('error - document does not exist'); } } export function uuid() { var dt = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (dt + Math.random() * 16) % 16 | 0; dt = Math.floor(dt / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); // console.log(uuid) return uuid; } export async function get_stores() { const uid = firebaseAuth.currentUser.uid const reference = doc(db, "clients", uid) getDoc(reference).then((snapshot) => { const stores = [] if (snapshot.exists()) { stores.push(snapshot.data()) const s = stores[0].stores; return s.length; } else { console.log('error collecting the stores'); return; } }) } export function is_logged_in(navigation) { onAuthStateChanged(auth, (user) => { if (user) { const uid = user.uid; db.collection('clients').doc(uid).get().then((documentSnapshot) => { console.log({ " account existance ": documentSnapshot.exists }) if (documentSnapshot.exists) { activeBusinessAccount = documentSnapshot.data() if (activeBusinessAccount !== null || undefined) { navigation.navigate('home') } else { console.log('Sorry Cant Find The User From Database'); } } else { navigation.navigate('configure') } }) } else { // User is signed out // ... } }); } export function signOut(navigation) { firebaseAuth.signOut().then(() => { navigation.navigate('signin') activeBusinessAccount = null }) } export function getActiveAccount() { const user = firebaseAuth.currentUser try { db.collection('clients').doc(user.uid).get().then((documentSnapshot) => { console.log({ " account existance ": documentSnapshot.exists }) if (documentSnapshot.exists) { activeBusinessAccount = documentSnapshot.data() } else { signOut() Alert.alert('Session Expired', 'Please sign in again to continue') navigation.navigate('signin') } }) } catch (error) { signOut() Alert.alert('Session Expired', 'Please sign in again to continue') navigation.navigate('signin') } } /** * @return a snapshot parameter for the store app in a then() method */ export async function getAccount() { await db.collection('clients').doc(firebaseAuth.currentUser.uid).get() } export async function firebaseUploadProductImage(uri, branch) { // const product_image_upload_path = `stores/${firebaseAuth.currentUser.uid}/${branch}` if (uri) { const filename = uri.substring(uri.lastIndexOf('/') + 1); console.log(filename) ref(storageDB, filename) } else { console.log('no image uploaded ke kodak black - versatile'); } console.log('image added.') }; /** * @param {*} imageUri contains a uri to the location where the image is situated */ export async function upload_store_product_image(imageUri) { if (imageUri) { const response = await fetch(imageUri); const blob = await response.blob(); const filename = imageUri.substring(imageUri.lastIndexOf('/') + 1); const ref = firebase.storage(app).ref().child(`inventory/${Date.now()}${filename}`); await ref.put(blob); // Get the image download URL const imageUrl = await ref.getDownloadURL(); console.log('Image URL:', imageUrl); // You can save the imageURL to a database or use it in your app } }; export { authResponse, user, firebaseAuth, auth, activeBusinessAccount, inventory, db, storageDB }
--- title: "Lab 9: Baby Names" format: html: self-contained: true editor: visual code-fold: true execute: warning: false theme: mint --- ## ```{r} #| include: false library(tidyverse) bb_names <- read_csv(here::here("supporting_artifacts", "ref.work", "lab9", "StateNames_A.csv")) bb_names <- bb_names |> rename("Sex" = "Gender") ``` ## DT Datatable Table ```{r} bb_clean <- bb_names |> filter( Name == "Allan" | Name == "Allen" | Name == "Alan", State == "CA" | State == "PA", Year == 2000, Sex == "M" ) bb_clean <- bb_clean |> group_by(State, Name) |> summarize(n = sum(Count)) prob <- bb_clean |> group_by(State) |> mutate(percent = n/sum(n)*100) |> select(Name, State, percent) |> pivot_wider(names_from = Name, values_from = percent, values_fill = 0) prob |> DT::datatable(class = 'cell-border stripe', filter = 'top', options = list(autoWidth = TRUE, dom = 'tip'), rownames = FALSE, caption = "Percent of Each Spelling for Babies Assigned Male at Birth and Born in 2000" ) ``` ## Kable Tables ```{r} bb_clean |> pivot_wider(names_from = Name, values_from = n, names_prefix = "Frequency of spelling ", values_fill = 0) |> knitr::kable() prob |> knitr::kable() ``` ```{r table} bb_clean <- bb_names |> filter(Name == "Allison") |> group_by(Year, Sex) |> summarize(n = sum(Count)) bb_clean |> pivot_wider(names_from = Sex, values_from = n, values_fill = 0) |> rename("Female" = "F", "Male" = "M") |> knitr::kable() ```
<template> <div class="file-list" > <form class="file-list__form" @submit.prevent> <select v-model="selectedValue" class="file-list__select" > <option v-for="(file, index) in fileList" :key="index" :value="file.id" >{{ file.project.name }}</option> </select> </form> <component :is="'template'" class="file-list__footer-template"> <div class="file-list__footer"> <button is="ui-button" :disabled="!selectedValue" @click.prevent="handleConfirm(selectedValue)" >Open</button> <button is="ui-button" @click.prevent="handleCancel()" >Cancel</button> </div> </component> </div> </template> <script lang="ts" setup> import { ref } from 'vue' import { fileStorage } from '@/plugins/db' import { ProjectFile } from '@/schema/ProjectFile' defineProps({ handleConfirm: { type: Function, required: true }, handleCancel: { type: Function, required: true } }) const fileList = ref<ProjectFile[]>([]) const selectedValue = ref('') const getFilterFileListFromDb = async() => { return await fileStorage.toArray() } getFilterFileListFromDb().then((res) => { fileList.value = res }) </script> <style lang="scss" scoped> .file-list__select { width: 100%; height: 3em; } .file-list__footer { > button + button { margin-left: 10px; } } </style>
import hashlib import os from parso._compatibility import FileNotFoundError, is_pypy from parso.pgen2 import generate_grammar from parso.utils import split_lines, python_bytes_to_unicode, parse_version_string from parso.python.diff import DiffParser from parso.python.tokenize import tokenize_lines, tokenize from parso.python.token import PythonTokenTypes from parso.cache import parser_cache, load_module, save_module from parso.parser import BaseParser from parso.python.parser import Parser as PythonParser from parso.python.errors import ErrorFinderConfig from parso.python import pep8 _loaded_grammars = {} class Grammar(object): """ :py:func:`parso.load_grammar` returns instances of this class. Creating custom none-python grammars by calling this is not supported, yet. """ #:param text: A BNF representation of your grammar. _error_normalizer_config = None _token_namespace = None _default_normalizer_config = pep8.PEP8NormalizerConfig() def __init__(self, text, tokenizer, parser=BaseParser, diff_parser=None): self._pgen_grammar = generate_grammar( text, token_namespace=self._get_token_namespace() ) self._parser = parser self._tokenizer = tokenizer self._diff_parser = diff_parser self._hashed = hashlib.sha256(text.encode("utf-8")).hexdigest() def parse(self, code=None, **kwargs): """ If you want to parse a Python file you want to start here, most likely. If you need finer grained control over the parsed instance, there will be other ways to access it. :param str code: A unicode or bytes string. When it's not possible to decode bytes to a string, returns a :py:class:`UnicodeDecodeError`. :param bool error_recovery: If enabled, any code will be returned. If it is invalid, it will be returned as an error node. If disabled, you will get a ParseError when encountering syntax errors in your code. :param str start_symbol: The grammar rule (nonterminal) that you want to parse. Only allowed to be used when error_recovery is False. :param str path: The path to the file you want to open. Only needed for caching. :param bool cache: Keeps a copy of the parser tree in RAM and on disk if a path is given. Returns the cached trees if the corresponding files on disk have not changed. :param bool diff_cache: Diffs the cached python module against the new code and tries to parse only the parts that have changed. Returns the same (changed) module that is found in cache. Using this option requires you to not do anything anymore with the cached modules under that path, because the contents of it might change. This option is still somewhat experimental. If you want stability, please don't use it. :param bool cache_path: If given saves the parso cache in this directory. If not given, defaults to the default cache places on each platform. :return: A subclass of :py:class:`parso.tree.NodeOrLeaf`. Typically a :py:class:`parso.python.tree.Module`. """ if 'start_pos' in kwargs: raise TypeError("parse() got an unexpected keyword argument.") return self._parse(code=code, **kwargs) def _parse(self, code=None, error_recovery=True, path=None, start_symbol=None, cache=False, diff_cache=False, cache_path=None, start_pos=(1, 0)): """ Wanted python3.5 * operator and keyword only arguments. Therefore just wrap it all. start_pos here is just a parameter internally used. Might be public sometime in the future. """ if code is None and path is None: raise TypeError("Please provide either code or a path.") if start_symbol is None: start_symbol = self._start_nonterminal if error_recovery and start_symbol != 'file_input': raise NotImplementedError("This is currently not implemented.") if cache and path is not None: module_node = load_module(self._hashed, path, cache_path=cache_path) if module_node is not None: return module_node if code is None: with open(path, 'rb') as f: code = f.read() code = python_bytes_to_unicode(code) lines = split_lines(code, keepends=True) if diff_cache: if self._diff_parser is None: raise TypeError("You have to define a diff parser to be able " "to use this option.") try: module_cache_item = parser_cache[self._hashed][path] except KeyError: pass else: module_node = module_cache_item.node old_lines = module_cache_item.lines if old_lines == lines: return module_node new_node = self._diff_parser( self._pgen_grammar, self._tokenizer, module_node ).update( old_lines=old_lines, new_lines=lines ) save_module(self._hashed, path, new_node, lines, # Never pickle in pypy, it's slow as hell. pickling=cache and not is_pypy, cache_path=cache_path) return new_node tokens = self._tokenizer(lines, start_pos) p = self._parser( self._pgen_grammar, error_recovery=error_recovery, start_nonterminal=start_symbol ) root_node = p.parse(tokens=tokens) if cache or diff_cache: save_module(self._hashed, path, root_node, lines, # Never pickle in pypy, it's slow as hell. pickling=cache and not is_pypy, cache_path=cache_path) return root_node def _get_token_namespace(self): ns = self._token_namespace if ns is None: raise ValueError("The token namespace should be set.") return ns def iter_errors(self, node): """ Given a :py:class:`parso.tree.NodeOrLeaf` returns a generator of :py:class:`parso.normalizer.Issue` objects. For Python this is a list of syntax/indentation errors. """ if self._error_normalizer_config is None: raise ValueError("No error normalizer specified for this grammar.") return self._get_normalizer_issues(node, self._error_normalizer_config) def _get_normalizer(self, normalizer_config): if normalizer_config is None: normalizer_config = self._default_normalizer_config if normalizer_config is None: raise ValueError("You need to specify a normalizer, because " "there's no default normalizer for this tree.") return normalizer_config.create_normalizer(self) def _normalize(self, node, normalizer_config=None): """ TODO this is not public, yet. The returned code will be normalized, e.g. PEP8 for Python. """ normalizer = self._get_normalizer(normalizer_config) return normalizer.walk(node) def _get_normalizer_issues(self, node, normalizer_config=None): normalizer = self._get_normalizer(normalizer_config) normalizer.walk(node) return normalizer.issues def __repr__(self): nonterminals = self._pgen_grammar._nonterminal_to_dfas.keys() txt = ' '.join(list(nonterminals)[:3]) + ' ...' return '<%s:%s>' % (self.__class__.__name__, txt) class PythonGrammar(Grammar): _error_normalizer_config = ErrorFinderConfig() _token_namespace = PythonTokenTypes _start_nonterminal = 'file_input' def __init__(self, version_info, bnf_text): super(PythonGrammar, self).__init__( bnf_text, tokenizer=self._tokenize_lines, parser=PythonParser, diff_parser=DiffParser ) self.version_info = version_info def _tokenize_lines(self, lines, start_pos): return tokenize_lines(lines, self.version_info, start_pos=start_pos) def _tokenize(self, code): # Used by Jedi. return tokenize(code, self.version_info) def load_grammar(**kwargs): """ Loads a :py:class:`parso.Grammar`. The default version is the current Python version. :param str version: A python version string, e.g. ``version='3.3'``. :param str path: A path to a grammar file """ def load_grammar(language='python', version=None, path=None): if language == 'python': version_info = parse_version_string(version) file = path or os.path.join( 'python', 'grammar%s%s.txt' % (version_info.major, version_info.minor) ) global _loaded_grammars path = os.path.join(os.path.dirname(__file__), file) try: return _loaded_grammars[path] except KeyError: try: with open(path) as f: bnf_text = f.read() grammar = PythonGrammar(version_info, bnf_text) return _loaded_grammars.setdefault(path, grammar) except FileNotFoundError: message = "Python version %s is currently not supported." % version raise NotImplementedError(message) else: raise NotImplementedError("No support for language %s." % language) return load_grammar(**kwargs)
import React, { useEffect, useState } from "react"; import Chart from 'react-apexcharts'; import axios from "axios"; const PieChart = ({ selectedDateTime }) => { const [checkinCount, setCheckinCount] = useState(0); const [borrowedBooksCount, setBorrowedBooksCount] = useState(0); const [loading, setLoading] = useState(true); const [dataAvailable, setDataAvailable] = useState(false); // State để kiểm tra dữ liệu có sẵn hay không useEffect(() => { const fetchData = async () => { try { setLoading(true); // Đánh dấu đang tải dữ liệu const checkinResponse = await axios.get("http://127.0.0.1:8000/user_checking_data", { params: { date: selectedDateTime } }); const borrowedBooksResponse = await axios.get("http://127.0.0.1:8000/get_borrow_book_count", { params: { date: selectedDateTime } }); setCheckinCount(checkinResponse.data.row_count); setBorrowedBooksCount(borrowedBooksResponse.data.total_borrow_book); setLoading(false); // Đánh dấu đã tải xong dữ liệu if (checkinResponse.data.row_count > 0 || borrowedBooksResponse.data.total_borrow_book > 0) { setDataAvailable(true); // Nếu có ít nhất một giá trị khác 0, đặt state là true } } catch (error) { console.error("Error fetching data:", error); setLoading(false); // Đánh dấu đã tải xong dù có lỗi xảy ra } }; fetchData(); }, [selectedDateTime]); // Thêm selectedDateTime vào mảng dependency của useEffect // Kiểm tra nếu không có dữ liệu if (!dataAvailable) { return <div>No data</div>; } const remainingBorrowedBooks = borrowedBooksCount - checkinCount; const data = { Late: checkinCount, Intime: remainingBorrowedBooks, }; const options = { labels: Object.keys(data), colors: ["#FF4560", "#008FFB"], legend: { position: "bottom", }, }; const series = Object.values(data); // Kiểm tra nếu đang tải dữ liệu if (loading) { return <div>Loading...</div>; } return ( <div className="chart sales-chart"> <h3 className="chart-title">Pie Chart</h3> <Chart options={options} series={series} type="pie" height={350} /> <p>Total Borrowed Books: {borrowedBooksCount}</p> <p>Total late Check-in: {checkinCount}</p> <p>Remaining On-time Check-ins: {remainingBorrowedBooks}</p> </div> ); }; export default PieChart;
// composables/useInvoiceStorage.js import { ref, onMounted } from 'vue'; import { Invoice } from '~/types/Invoice'; // Save the invoices to localStorage // Save the invoices to localStorage function saveInvoices(invoices: Invoice[]) { if (process.client) { localStorage.setItem('invoices', JSON.stringify(invoices)); } } // Get the invoices from localStorage function getInvoices(): Invoice[] { if (process.client) { const storedInvoices = localStorage.getItem('invoices'); if (storedInvoices) { return JSON.parse(storedInvoices); } } return []; } // Generate a random 5-digit ID function generateRandomId(): string { return Math.floor(Math.random() * 90000) + 10000 + ''; // Generate a random 5-digit number as string } export function useInvoiceStorage() { const invoices = ref<Invoice[]>(getInvoices()); function saveInvoice(invoice: Invoice) { invoice.id = generateRandomId(); // Set the ID to the generated random 5-digit number invoices.value.push(invoice); saveInvoices(invoices.value); } function getInvoiceById(invoiceId: string): Invoice | undefined { return invoices.value.find((invoice) => invoice.id === invoiceId); } function updateInvoice(updatedInvoice: Invoice, id: string): Invoice | null { const index = invoices.value.findIndex((invoice) => invoice.id === id); console.log("🌍 updatedInvoice", updatedInvoice); console.log("🌍 index updateInvoice", index); if (index !== -1) { Object.assign(invoices.value[index], updatedInvoice); saveInvoices(invoices.value); return invoices.value[index]; // Return the updated invoice } else { return null; // Return null if invoice with the specified ID is not found } } function deleteInvoice(invoiceId: string) { invoices.value = invoices.value.filter((invoice) => invoice.id !== invoiceId); saveInvoices(invoices.value); } // Save the invoices to localStorage when the component is mounted onMounted(() => { saveInvoices(invoices.value); }); return { invoices, saveInvoice, getInvoiceById, updateInvoice, deleteInvoice, }; }
/* * Copyright (C) 2015 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <gmock/gmock.h> #include <ac/dbus/controllerskeleton.h> namespace { struct MockController : public ac::Controller { MOCK_METHOD1(SetDelegate, void(const std::weak_ptr<ac::Controller::Delegate> &)); MOCK_METHOD0(ResetDelegate, void()); MOCK_METHOD2(Connect, void(const ac::NetworkDevice::Ptr &, ac::ResultCallback)); MOCK_METHOD2(Disconnect, void(const ac::NetworkDevice::Ptr &, ac::ResultCallback)); MOCK_METHOD1(DisconnectAll, void(ac::ResultCallback)); MOCK_METHOD1(Scan, ac::Error(const std::chrono::seconds &)); MOCK_CONST_METHOD0(State, ac::NetworkDeviceState()); MOCK_CONST_METHOD0(Capabilities, std::vector<ac::NetworkManager::Capability>()); MOCK_CONST_METHOD0(Scanning, bool()); MOCK_CONST_METHOD0(Enabled, bool()); MOCK_METHOD1(SetEnabled, ac::Error(bool)); }; } TEST(ControllerSkeleton, ThrowsForNullptrOnConstruction) { EXPECT_THROW(ac::dbus::ControllerSkeleton::Create(ac::Controller::Ptr{}), std::logic_error); } TEST(ControllerSkeleton, ForwardsCallsToImpl) { using namespace testing; auto impl = std::make_shared<MockController>(); // Times(AtLeast(1)) as ControllerSkeleton::create(...) already calls it. // In addition, we have to account for the case where we encounter issues during // construction of ac::dbus::ControllerSkeleton (such that a WPA supplicant connection // is never set up. EXPECT_CALL(*impl, SetDelegate(_)).Times(AtLeast(1)); EXPECT_CALL(*impl, ResetDelegate()).Times(1); EXPECT_CALL(*impl, Connect(_,_)).Times(1); EXPECT_CALL(*impl, Disconnect(_,_)).Times(1); EXPECT_CALL(*impl, DisconnectAll(_)).Times(1); EXPECT_CALL(*impl, Scan(_)).Times(1).WillRepeatedly(Return(ac::Error::kNone)); EXPECT_CALL(*impl, State()).Times(1).WillRepeatedly(Return(ac::NetworkDeviceState::kConnected)); EXPECT_CALL(*impl, Capabilities()).Times(1).WillRepeatedly(Return(std::vector<ac::NetworkManager::Capability>{ac::NetworkManager::Capability::kSource})); EXPECT_CALL(*impl, Scanning()).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*impl, Enabled()).Times(1).WillRepeatedly(Return(true)); EXPECT_CALL(*impl, SetEnabled(false)).Times(1).WillRepeatedly(Return(ac::Error::kNone)); auto fmc = ac::dbus::ControllerSkeleton::Create(impl); fmc->SetDelegate(std::shared_ptr<ac::Controller::Delegate>{}); fmc->ResetDelegate(); fmc->Connect(ac::NetworkDevice::Ptr{}, ac::ResultCallback{}); fmc->Disconnect(ac::NetworkDevice::Ptr{}, ac::ResultCallback{}); fmc->DisconnectAll(ac::ResultCallback{}); fmc->Scan(std::chrono::seconds{10}); fmc->State(); fmc->Capabilities(); fmc->Scanning(); fmc->Enabled(); fmc->SetEnabled(false); Mock::AllowLeak(impl.get()); }
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; import { ValidationPipe } from '@src/validation.pipe'; import { FakultasService } from './fakultas.service'; import { UpdateFakultaDto } from './dto/update-fakultas.dto'; import { CreateFakultasDto } from './dto/create-fakultas.dto'; @Controller('fakultas') export class FakultasController { constructor(private readonly fakultasService: FakultasService) {} @Post() create(@Body(new ValidationPipe()) createFakultasDto: CreateFakultasDto) { return this.fakultasService.create(createFakultasDto); } @Get() findAll() { return this.fakultasService.findAll(); } @Get(':kode') findOne(@Param('kode') kode: string) { return this.fakultasService.findOne(kode); } @Patch(':kode') update(@Param('kode') kode: string, @Body() updateFakultaDto: UpdateFakultaDto) { return this.fakultasService.update(kode, updateFakultaDto); } @Delete(':kode') remove(@Param('kode') kode: string) { return this.fakultasService.remove(kode); } }
package com.shubham.blog.services.impl; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.shubham.blog.entities.Comment; import com.shubham.blog.entities.Post; import com.shubham.blog.entities.User; import com.shubham.blog.exceptions.ResourceNotFoundException; import com.shubham.blog.payloads.CommentDto; import com.shubham.blog.repositories.CommentRepository; import com.shubham.blog.repositories.PostRepository; import com.shubham.blog.repositories.UserRepository; import com.shubham.blog.services.CommentService; @Service public class CommentServiceImpl implements CommentService { @Autowired private PostRepository postRespository; @Autowired private UserRepository userRepository; @Autowired private CommentRepository commentRepository; @Autowired private ModelMapper modelMapper; @Override public CommentDto createComment(CommentDto commentDto, Integer id) { Post post=this.postRespository.findById(id) .orElseThrow(()->new ResourceNotFoundException("Post","id",id)); User user=this.userRepository.findById(id) .orElseThrow(()->new ResourceNotFoundException("User","id",id)); Comment comment=this.modelMapper.map(commentDto,Comment.class); comment.setPost(post); comment.setUser(user); Comment newComment=this.commentRepository.save(comment); return this.modelMapper.map(newComment, CommentDto.class); } @Override public void deleteComment(Integer id) { // TODO Auto-generated method stub Comment comment=this.commentRepository.findById(id) .orElseThrow(()->new ResourceNotFoundException("Comment","id",id)); this.commentRepository.delete(comment); } }
using AutoMapper; using Cursus.Constants; using Cursus.DTO; using Cursus.DTO.Assignment; using Cursus.Entities; using Cursus.Services.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Cursus.Controllers { [Route("api/[controller]")] [ApiController] public class AssignmentController : ControllerBase { private readonly IAssignmentService _assignmentService; private readonly ISectionService _sectionService; private readonly IInstructorService _instructorService; private readonly IRedisService _cacheService; public AssignmentController(IAssignmentService assignmentService, ISectionService sectionService, IInstructorService instructorService, IRedisService cacheService) { _assignmentService = assignmentService; _sectionService = sectionService; _instructorService = instructorService; _cacheService = cacheService; } [HttpPost] [Authorize(Roles = "Instructor")] public async Task<IActionResult> CreateAsync(Guid sectionId, CreateAssignmentDTO createAssignmentDTO) { ResultDTO result; result = createAssignmentDTO.Validate(); if (!result.IsSuccess) return StatusCode(result.StatusCode, result); var instructor = await _instructorService.GetCurrentInstructor(); if (instructor is null) { result = ResultDTO.Fail(new[] { "Fail to create assignment" }); return StatusCode(result.StatusCode, result); } var section = await _sectionService.GetAsync(sectionId, instructor.ID); if (section is null) { result = ResultDTO.Fail(new[] { "Section not found" }, 404); return StatusCode(result.StatusCode, result); } var assignment = new Assignment() { Title = createAssignmentDTO.Title, Description = createAssignmentDTO.Description, TimeTaken = createAssignmentDTO.TimeTaken, SectionID = sectionId, CourseID = section.CourseID, InstructorID = instructor.ID }; var createdAssignment = await _assignmentService.CreateAsync(assignment); if (createdAssignment is not null) { await _cacheService.RemoveDataAsync(CacheKeyPatterns.CourseDetail + createdAssignment.CourseID); result = ResultDTO.Success(createdAssignment); return StatusCode(result.StatusCode, result); } result = ResultDTO.Fail(new[] { "Fail to create assignment" }); return StatusCode(result.StatusCode, result); } [HttpPut] [Authorize(Roles = "Instructor")] public async Task<IActionResult> UpdateAsync(Guid id, UpdateAssignmentDTO updateAssignmentDTO) { ResultDTO result; result = updateAssignmentDTO.Validate(); if (!result.IsSuccess) return StatusCode(result.StatusCode, result); var instructor = await _instructorService.GetCurrentInstructor(); if (instructor is null) { result = ResultDTO.Fail(new[] { "Fail to update assignment" }); return StatusCode(result.StatusCode, result); } var assignment = await _assignmentService.GetAsync(id, instructor.ID); if (assignment is null) { result = ResultDTO.Fail(new[] { "Assignment not found" }, 404); return StatusCode(result.StatusCode, result); } assignment.Title = updateAssignmentDTO.Title; assignment.Description = updateAssignmentDTO.Description; assignment.TimeTaken = updateAssignmentDTO.TimeTaken; var updatedAssignment = await _assignmentService.UpdateAsync(assignment); if (updatedAssignment is not null) { await _cacheService.RemoveDataAsync(CacheKeyPatterns.CourseDetail + updatedAssignment.CourseID); result = ResultDTO.Success(updatedAssignment); return StatusCode(result.StatusCode, result); } result = ResultDTO.Fail(new[] { "Fail to update assignment" }); return StatusCode(result.StatusCode, result); } [HttpDelete] [Authorize(Roles = "Instructor")] public async Task<IActionResult> DeleteAsync(Guid id) { ResultDTO result; var instructor = await _instructorService.GetCurrentInstructor(); if (instructor is null) { result = ResultDTO.Fail(new[] { "Fail to delete assignment" }); return StatusCode(result.StatusCode, result); } var assignment = await _assignmentService.GetAsync(id, instructor.ID); if (assignment is null) { result = ResultDTO.Fail(new[] { "Assignment not found" }, 404); return StatusCode(result.StatusCode, result); } var deletedAssignment = await _assignmentService.DeleteAsync(assignment); if (deletedAssignment is not null) { await _cacheService.RemoveDataAsync(CacheKeyPatterns.CourseDetail + deletedAssignment.CourseID); result = ResultDTO.Success(deletedAssignment); return StatusCode(result.StatusCode, result); } result = ResultDTO.Fail(new[] { "Fail to delete assignment" }); return StatusCode(result.StatusCode, result); } } }
# Electronic Items Management Please copy this markdown and use [markdownlivepreview.com](https://markdownlivepreview.com) to view it. ## Software Requirements - NodeJS - Postman - Installed NPM Packages: `express, Joi, fs` ## How to run 1. Install [NodeJS](https://nodejs.org/en/download) 2. Go to the NodeJS app folder. Run the following command on Unix/Linux shell/Windows Powershell: ``` node script.js ``` 3. This will run on `localhost`, port `8080` Example: ![run](https://i.imgur.com/82h85c9.png) > On Windows, you need to run Powershell as Administrator. ## How to send request 1. Open Postman desktop application. 2. Create a new HTTP. 3. Set the METHOD to the desired request method. 4. Put the URL to the desired API url. 5. Press SEND button to run. Example: ![postman](https://i.imgur.com/8IEBZjW.png) ## Features ### Display the list of all products 1. In Postman, set METHOD to `GET` 2. Set URL to: ``` localhost:8080/api/products ``` 3. Click SEND button 4. **This will return a JSON of products, each product has id, name, and quantity.** Example: ![getall](https://imgur.com/iv6VKtb.png) ### Display the information of a specific product when the request contains an ID 1. In Postman, set METHOD to `GET` 2. Set URL to: ``` localhost:8080/api/products/PRODUCT_ID ``` where the `PRODUCT_ID` is the product ID you're looking for. 3. Click SEND button 4. **This will return an information of the product ID you're looking for (inlude product id, name, and quantity)** Example: ![getid](https://i.imgur.com/p7PGxWE.png) ### Create a new product with information 1. In Postman, set METHOD to `POST` 2. Set URL to `localhost:8080/api/products` 3. Select the `Body` tab under the URL. 4. Fill the text box with the new product information: ``` json { "name": "PRODUCT_NAME", "quantity": PRODUCT_QUANTITY } ``` where `PRODUCT_NAME` is a string, in double-quote, must at least 2 characters; and `PRODUCT_QUANTITY` is an integer number. 5. **This will return the information of product you just added with a new assigned `ID`** Example: ![postid](https://i.imgur.com/wvrxxSX.png) ### Update the details of an existing product 1. In Postman, set METHOD to `PUT` 2. Set URL to `localhost:8080/api/products/PRODUCT_ID` 3. Select the `Body` tab under the URL. 4. Fill the text box with the new product information: ``` json { "name": "NEW_PRODUCT_NAME", "quantity": NEW_PRODUCT_QUANTITY } ``` where `PRODUCT_NAME` is a string, in double-quote, and `PRODUCT_QUANTITY` is an integer number. If `NEW_PRODUCT_NAME` is `NA` or `na`, the `PRODUCT_NAME` will not be modified. If `NEW_PRODUCT_QUANTITY` is `-1`, the `PRODUCT_QUANTITY` will not be modified. 5. **This will return the information of product you just modified with an `ID`** Example: ![putid](https://i.imgur.com/j73YmAA.png) ### Delete a product from the database 1. In Postman, set METHOD to `DELETE` 2. Set URL to: ``` localhost:8080/api/products/PRODUCT_ID ``` where the `PRODUCT_ID` is the product ID you're deleting. 3. Click SEND button 4. **This will return an information of the product ID you deleted.** Example: ![deleteid](https://i.imgur.com/7sUiv1r.png)
/* * MIT License * * Copyright (c) 2022-2023 Alexis Jehan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.alexisjehan.mavencheck.core.component.build.resolver; import com.github.alexisjehan.mavencheck.core.component.artifact.Artifact; import com.github.alexisjehan.mavencheck.core.component.artifact.ArtifactIdentifier; import com.github.alexisjehan.mavencheck.core.component.artifact.type.MavenArtifactType; import com.github.alexisjehan.mavencheck.core.component.build.file.BuildFile; import com.github.alexisjehan.mavencheck.core.component.build.file.BuildFileType; import com.github.alexisjehan.mavencheck.core.component.repository.Repository; import com.github.alexisjehan.mavencheck.core.component.repository.RepositoryType; import com.github.alexisjehan.mavencheck.core.component.session.MavenSession; import org.junit.jupiter.api.Test; import java.nio.file.Path; import static org.assertj.core.api.Assertions.assertThat; final class MavenBuildResolverIT { private final MavenBuildResolver mavenBuildResolver = new MavenBuildResolver(new MavenSession()); @Test void testResolve() { final var buildFile = new BuildFile( BuildFileType.MAVEN, Path.of("src", "test", "resources", "pom_it.xml") ); final var build = mavenBuildResolver.resolve(buildFile); assertThat(build.getFile()).isSameAs(buildFile); assertThat(build.getRepositories()).containsExactly( new Repository( RepositoryType.NORMAL, "google", "https://maven.google.com" ), new Repository( RepositoryType.NORMAL, "central", "https://repo.maven.apache.org/maven2" ), new Repository( RepositoryType.PLUGIN, "central", "https://repo.maven.apache.org/maven2" ) ); assertThat(build.getArtifacts()).containsExactly( new Artifact<>( MavenArtifactType.DEPENDENCY, new ArtifactIdentifier("com.google.android.material", "material"), "1.0.0" ), new Artifact<>( MavenArtifactType.DEPENDENCY, new ArtifactIdentifier("com.google.guava", "guava"), "10.0" ), new Artifact<>( MavenArtifactType.DEPENDENCY, new ArtifactIdentifier("org.springframework", "spring-core"), "3.0.0.RELEASE" ), new Artifact<>( MavenArtifactType.PROFILE_DEPENDENCY, new ArtifactIdentifier("com.google.guava", "guava"), "23.1-jre" ), new Artifact<>( MavenArtifactType.PROFILE_DEPENDENCY, new ArtifactIdentifier("com.google.guava", "guava"), "23.1-android" ) ); } }
package christmas.domain; import christmas.view.input.dto.InputMenuDto; import christmas.view.input.error.InputError; import christmas.view.input.error.InputIllegalException; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public enum MenuBoard { MUSHROOM_SOUP(MenuType.APPETIZER, "양송이수프", 6000), TAPAS(MenuType.APPETIZER, "타파스", 5500), CAESAR_SALAD(MenuType.APPETIZER, "시저샐러드", 8000), CHOCOLATE_CAKE(MenuType.DESSERT, "초코케이크", 15000), ICE_CREAM(MenuType.DESSERT, "아이스크림", 5000), ZERO_COLA(MenuType.DRINK, "제로콜라", 3000), RED_WINE(MenuType.DRINK, "레드와인", 60000), CHAMPAGNE(MenuType.DRINK, "샴페인", 25000), T_BONE_STEAK(MenuType.MAIN, "티본스테이크", 55000), BBQ_RIBS(MenuType.MAIN, "바비큐립", 54000), SEAFOOD_PASTA(MenuType.MAIN, "해산물파스타", 35000), CHRISTMAS_PASTA(MenuType.MAIN, "크리스마스파스타", 25000); final MenuType menuType; final String menuName; final int menuPrice; MenuBoard(MenuType menuType, String menuName, int menuPrice) { this.menuType = menuType; this.menuName = menuName; this.menuPrice = menuPrice; } private String getMenuName() { return this.menuName; } private MenuType getMenuType() { return this.menuType; } private int getMenuPrice() { return this.menuPrice; } private static boolean containsMenuName(MenuBoard menuBoard, String menuName) { return menuBoard.getMenuName().equals(menuName); } private static MenuBoard getMenuBoardByName(String name) { return Arrays.stream(values()) .filter(menu -> containsMenuName(menu, name)) .findFirst() .orElseThrow(() -> new InputIllegalException(InputError.NOT_POSSIBLE_ORDER)); } public static InputMenuDto getDtoByName(String name, int count) { return new InputMenuDto(getMenuBoardByName(name), count); } public static String toMenuEventString(EnumMap<MenuBoard, Integer> menus) { final String BLANK = " "; final String COUNT = "개"; final String NEW_LINE = "\n"; return menus.entrySet().stream() .map(menu -> menu.getKey().getMenuName() + BLANK + menu.getValue() + COUNT) .collect(Collectors.joining(NEW_LINE)); } public static String toChampagneAmountString(int amount) { final String COUNT = "개"; final String BLANK = " "; final String NOTING = "없음"; String name = CHAMPAGNE.getMenuName(); if (amount == 0) { return NOTING; } return name + BLANK + amount + COUNT; } public static boolean isAllMenuTypesDrink(Set<MenuBoard> menus) { return menus.stream() .allMatch(menu -> menu.getMenuType() == MenuType.DRINK); } public static int calculateTotalPrice(MenuBoard menu, int quantity) { return menu.getMenuPrice() * quantity; } public static int calculateTotalDessertCount(EnumMap<MenuBoard, Integer> menus) { return menus.entrySet().stream() .filter(menu -> menu.getKey().getMenuType() == MenuType.DESSERT) .mapToInt(Map.Entry::getValue) .sum(); } public static int calculateTotalMainCount(EnumMap<MenuBoard, Integer> menus) { return menus.entrySet().stream() .filter(menu -> menu.getKey().getMenuType() == MenuType.MAIN) .mapToInt(Map.Entry::getValue) .sum(); } public static int calculateTotalChampagnePrice(int amount) { return CHAMPAGNE.menuPrice * amount; } }
import { MongoClient } from 'mongodb' import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import axios from 'axios'; const execFilePromise = promisify(execFile); async function provision(uri) { console.log('Provisioning', uri) const client = new MongoClient(uri); await client.connect(); const db = client.db('expenses'); const col = db.collection('expenses'); await col.deleteMany({}); const count = Math.round(Math.random() * 100); const entries = []; for (let i = 0; i < count; i++) { entries.push({ i: i, amount: Math.round(Math.random() * 100000) / 100 }); } await col.insertMany(entries); await client.close(); console.log('Finished provisioning', uri); return entries; } async function main() { const collections = await Promise.all([ provision('mongodb://expenses-central'), // Central provision('mongodb://expenses-surf'), // surf provision('mongodb://expenses-uva') // UvA ]); const amounts = { 'central': collections[0].map((doc) => doc.amount), 'surf': collections[1].map((doc) => doc.amount), 'uva': collections[2].map((doc) => doc.amount), }; const correctResult = { 'central': { sum: amounts['central'].reduce((sum, amount) => sum + amount, 0), avg: amounts['central'].reduce((sum, amount) => sum + amount, 0) / amounts['central'].length, }, 'surf': { sum: amounts['surf'].reduce((sum, amount) => sum + amount, 0), avg: amounts['surf'].reduce((sum, amount) => sum + amount, 0) / amounts['surf'].length, }, 'uva': { sum: amounts['uva'].reduce((sum, amount) => sum + amount, 0), avg: amounts['uva'].reduce((sum, amount) => sum + amount, 0) / amounts['uva'].length, }, } // Deploy architecture console.log('Compiling') await execFilePromise('python', ['../../../blocks/userStoryCompiler/src/run.py', '../multi-env.yml']) console.log('Deploying') await Promise.all([ 'https://central.thesis.dev.qrcsoftware.nl', 'https://uva.thesis.dev.qrcsoftware.nl', 'https://surf.thesis.dev.qrcsoftware.nl' ].map((url) => execFilePromise('node', ['../../../cli/cli.js', 'clear', url]))); await execFilePromise('node', ['../../../cli/cli.js', 'push', './compiled.yml']); console.log('Deployed') // Get result const res = (await axios.get('https://gateway.central.thesis.dev.qrcsoftware.nl/get')).data; console.log('Results:'); console.log(res); // Validate results console.log('Correct results:'); console.log(correctResult); } main();
/* Copyright (C) 2017 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */ #include "test_helpers.h" #include "nmod_mpoly.h" TEST_FUNCTION_START(nmod_mpoly_mul_johnson, state) { slong tmul = 8; int i, j, result; /* Check f*(g + h) = f*g + f*h */ for (i = 0; i < tmul * flint_test_multiplier(); i++) { nmod_mpoly_ctx_t ctx; nmod_mpoly_t f, g, h, k1, k2, t1, t2; slong len, len1, len2; flint_bitcnt_t exp_bits, exp_bits1, exp_bits2; mp_limb_t modulus; modulus = n_randint(state, FLINT_BITS - 1) + 1; modulus = n_randbits(state, modulus); modulus = n_nextprime(modulus, 1); nmod_mpoly_ctx_init_rand(ctx, state, 20, modulus); nmod_mpoly_init(f, ctx); nmod_mpoly_init(g, ctx); nmod_mpoly_init(h, ctx); nmod_mpoly_init(k1, ctx); nmod_mpoly_init(k2, ctx); nmod_mpoly_init(t1, ctx); nmod_mpoly_init(t2, ctx); len = n_randint(state, 100); len1 = n_randint(state, 100); len2 = n_randint(state, 100); exp_bits = n_randint(state, 200) + 2; exp_bits1 = n_randint(state, 200) + 2; exp_bits2 = n_randint(state, 200) + 2; nmod_mpoly_randtest_bits(k1, state, len, exp_bits, ctx); nmod_mpoly_randtest_bits(k2, state, len, exp_bits, ctx); for (j = 0; j < 4; j++) { nmod_mpoly_randtest_bits(f, state, len1, exp_bits1, ctx); nmod_mpoly_randtest_bits(g, state, len2, exp_bits2, ctx); nmod_mpoly_randtest_bits(h, state, len2, exp_bits2, ctx); nmod_mpoly_add(t1, g, h, ctx); nmod_mpoly_assert_canonical(t1, ctx); nmod_mpoly_mul_johnson(k1, f, t1, ctx); nmod_mpoly_assert_canonical(k1, ctx); nmod_mpoly_mul_johnson(t1, f, g, ctx); nmod_mpoly_assert_canonical(t1, ctx); nmod_mpoly_mul_johnson(t2, f, h, ctx); nmod_mpoly_assert_canonical(t2, ctx); nmod_mpoly_add(k2, t1, t2, ctx); nmod_mpoly_assert_canonical(k2, ctx); result = nmod_mpoly_equal(k1, k2, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check f*(g + h) = f*g + f*h\ni = %wd, j = %wd\n", i ,j); fflush(stdout); flint_abort(); } } nmod_mpoly_clear(f, ctx); nmod_mpoly_clear(g, ctx); nmod_mpoly_clear(h, ctx); nmod_mpoly_clear(k1, ctx); nmod_mpoly_clear(k2, ctx); nmod_mpoly_clear(t1, ctx); nmod_mpoly_clear(t2, ctx); nmod_mpoly_ctx_clear(ctx); } /* Check aliasing first argument */ for (i = 0; i < tmul * flint_test_multiplier(); i++) { nmod_mpoly_ctx_t ctx; nmod_mpoly_t f, g, h; slong len, len1, len2; flint_bitcnt_t exp_bits, exp_bits1, exp_bits2; mp_limb_t modulus; modulus = n_randint(state, FLINT_BITS - 1) + 1; modulus = n_randbits(state, modulus); modulus = n_nextprime(modulus, 1); nmod_mpoly_ctx_init_rand(ctx, state, 20, modulus); nmod_mpoly_init(f, ctx); nmod_mpoly_init(g, ctx); nmod_mpoly_init(h, ctx); len = n_randint(state, 100); len1 = n_randint(state, 100); len2 = n_randint(state, 100); exp_bits = n_randint(state, 200) + 2; exp_bits1 = n_randint(state, 200) + 2; exp_bits2 = n_randint(state, 200) + 2; for (j = 0; j < 4; j++) { nmod_mpoly_randtest_bits(f, state, len1, exp_bits1, ctx); nmod_mpoly_randtest_bits(g, state, len2, exp_bits2, ctx); nmod_mpoly_randtest_bits(h, state, len, exp_bits, ctx); nmod_mpoly_mul_johnson(h, f, g, ctx); nmod_mpoly_assert_canonical(h, ctx); nmod_mpoly_mul_johnson(f, f, g, ctx); nmod_mpoly_assert_canonical(f, ctx); result = nmod_mpoly_equal(h, f, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check aliasing second arg\ni = %wd, j = %wd\n", i ,j); fflush(stdout); flint_abort(); } } nmod_mpoly_clear(f, ctx); nmod_mpoly_clear(g, ctx); nmod_mpoly_clear(h, ctx); nmod_mpoly_ctx_clear(ctx); } /* Check aliasing second argument */ for (i = 0; i < tmul * flint_test_multiplier(); i++) { nmod_mpoly_ctx_t ctx; nmod_mpoly_t f, g, h; slong len, len1, len2; flint_bitcnt_t exp_bits, exp_bits1, exp_bits2; mp_limb_t modulus; modulus = n_randint(state, FLINT_BITS - 1) + 1; modulus = n_randbits(state, modulus); modulus = n_nextprime(modulus, 1); nmod_mpoly_ctx_init_rand(ctx, state, 20, modulus); nmod_mpoly_init(f, ctx); nmod_mpoly_init(g, ctx); nmod_mpoly_init(h, ctx); len = n_randint(state, 100); len1 = n_randint(state, 100); len2 = n_randint(state, 100); exp_bits = n_randint(state, 200) + 2; exp_bits1 = n_randint(state, 200) + 2; exp_bits2 = n_randint(state, 200) + 2; for (j = 0; j < 4; j++) { nmod_mpoly_randtest_bits(f, state, len1, exp_bits1, ctx); nmod_mpoly_randtest_bits(g, state, len2, exp_bits2, ctx); nmod_mpoly_randtest_bits(h, state, len, exp_bits, ctx); nmod_mpoly_mul_johnson(h, f, g, ctx); nmod_mpoly_assert_canonical(h, ctx); nmod_mpoly_mul_johnson(g, f, g, ctx); nmod_mpoly_assert_canonical(g, ctx); result = nmod_mpoly_equal(h, g, ctx); if (!result) { printf("FAIL\n"); flint_printf("Check aliasing second arg\ni = %wd, j = %wd\n", i ,j); fflush(stdout); flint_abort(); } } nmod_mpoly_clear(f, ctx); nmod_mpoly_clear(g, ctx); nmod_mpoly_clear(h, ctx); nmod_mpoly_ctx_clear(ctx); } TEST_FUNCTION_END(state); }
<template> <div class="section fp-auto-height"> <div class="content" id="open-source-content"> <b-row> <b-col> <p class="content-header">🌱 Open Source Projects</p> </b-col> <b-col style="text-align:right"> <b-button size="lg" id="github-btn" href="https://github.com/hyeminnoh" target="_blank"> <font-awesome-icon :icon="faGithub" /> More... </b-button> </b-col> </b-row> <hr> <div class="repo-cards-main-div"> <b-row class="repo-cards-row" v-for="n in cardlength" :key="n" v-bind="pinnedRepo"> <b-col> <div class="repo-card-div" @click="togithub(pinnedRepo[n].node.url)"> <div class="repo-name-div"> <p class="repo-name">{{ pinnedRepo[n].node.name }}</p> </div> <p class="repo-description">{{ pinnedRepo[n].node.description }}</p> <div class="repo-stats"> <div class="repo-left-stat"> <span> <p><font-awesome-icon :icon="faStar" color="#808080"/> {{ pinnedRepo[n].node.stargazers.totalCount }}</p> </span> <span v-if="pinnedRepo[n].node.primaryLanguage"> <p><font-awesome-icon :icon="faCircle" :color="pinnedRepo[n].node.primaryLanguage.color"/> {{ pinnedRepo[n].node.primaryLanguage.name }}</p> </span> <span> <p><font-awesome-icon :icon="faCodeBranch" color="#808080"/> {{ pinnedRepo[n].node.forkCount }}</p> </span> </div> <div class="repo-right-stat"> <p>{{ pinnedRepo[n].node.diskUsage }} KB</p> </div> </div> </div> </b-col> <b-col> <div class="repo-card-div" @click="togithub(pinnedRepo[n+1].node.url)"> <div class="repo-name-div"> <p class="repo-name">{{ pinnedRepo[n+1].node.name }}</p> </div> <p class="repo-description">{{ pinnedRepo[n+1].node.description }}</p> <div class="repo-stats"> <div class="repo-left-stat"> <span> <p><font-awesome-icon :icon="faStar" color="#808080"/> {{ pinnedRepo[n+1].node.stargazers.totalCount }}</p> </span> <span v-if="pinnedRepo[n+1].node.primaryLanguage"> <p><font-awesome-icon :icon="faCircle" :color="pinnedRepo[n+1].node.primaryLanguage.color"/> {{ pinnedRepo[n+1].node.primaryLanguage.name }}</p> </span> <span> <p><font-awesome-icon :icon="faCodeBranch" color="#808080"/> {{ pinnedRepo[n+1].node.forkCount }}</p> </span> </div> <div class="repo-right-stat"> <p>{{ pinnedRepo[n+1].node.diskUsage }} KB</p> </div> </div> </div> </b-col> </b-row> </div> </div> </div> </template> <script> import ApolloClient from "apollo-boost"; import { gql } from "apollo-boost"; import { faGithub } from "@fortawesome/free-brands-svg-icons"; import { faCircle, faStar, faCodeBranch } from "@fortawesome/free-solid-svg-icons"; export default { name: "OpenSource", methods: { togithub(url) { window.open(url,'_blank'); } }, data() { return { faGithub, faCircle, faStar, faCodeBranch, pinnedRepo: [], cardlength: [] }; }, created: function() { const client = new ApolloClient({ uri: "https://api.github.com/graphql", request: operation => { operation.setContext({ headers: { authorization: `Bearer ${atob('MjU5NWFhM2NiYjcyNjZjZTZiN2YxMTA1Yzk0YjJhZGYxNjU1NmM0Nw==')}` } }); } }); client .query({ query: gql` { user(login: "HyeminNoh") { pinnedItems(first: 6, types: [REPOSITORY]) { totalCount edges { node { ... on Repository { name description forkCount stargazers { totalCount } url id diskUsage primaryLanguage { name color } } } } } } } ` }) .then(result => { var repos = result.data.user.pinnedItems.edges; console.log(repos) this.pinnedRepo = repos; this.repolength = repos.length; if (repos.length % 2 == 0) { for (var i = 0; i < repos.length / 2; i++) { this.cardlength.push(i * 2); } } else { for (var j = 0; j < repos.length / 2 + 1; j++) { this.cardlength.push(j * 2); } } }); } }; </script> <style> #open-source-content{ height: auto; } @media all and (max-width: 959px) and (min-width: 600px) { #open-source-content{ height: auto; } } @media all and (max-width: 599px) and (min-width: 320px) { #open-source-content{ height: auto !important; padding-bottom: 30%; } } .repo-card-div { color: rgb(88, 96, 105); background-color: rgb(255, 255, 255); box-shadow: rgba(0, 0, 0, 0.2) 0px 10px 30px -15px; padding: 2rem; cursor: pointer; margin: 1%; } .repo-card-div:hover { box-shadow: rgba(0, 0, 0, 0.2) 0px 20px 30px -10px; } .repo-stats { display: flex; -webkit-box-pack: justify; justify-content: space-between; font-size: 13px; color: rgb(106, 115, 125); } .repo-left-stat { -webkit-box-flex: 1; flex-grow: 1; display: flex; } .language-color { width: 10px; height: 10px; background-color: blue; margin-right: 0.25rem; border-radius: 100%; } .repo-left-stat span { display: flex; -webkit-box-align: center; align-items: center; margin-right: 0.75rem; } .repo-name-div { display: flex; align-items: center; } .repo-svg { margin-right: 0.5rem; min-width: 16px; } .repo-name { white-space: nowrap; text-overflow: ellipsis; color: rgb(36, 41, 46); margin-bottom: 0.75rem; font-size: 25px; font-weight: 700; letter-spacing: -0.5px; overflow: hidden; margin: 0px; } .repo-star-svg { margin-right: 0.3rem; } .repo-description { overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } </style>
from django.core.exceptions import ValidationError from django.db import transaction from rest_framework import serializers from ..common import validators from ..common.clean import sanitize_html from ..common.helper import SerializerHelper from ..riskofbias.serializers import AssessmentRiskOfBiasSerializer from . import constants, models class CollectionDataPivotSerializer(serializers.ModelSerializer): url = serializers.CharField(source="get_absolute_url") visual_type = serializers.CharField(source="get_visual_type_display") class Meta: model = models.DataPivot fields = ( "id", "slug", "title", "url", "visual_type", "caption", "published", "created", "last_updated", ) class DataPivotSerializer(serializers.ModelSerializer): url = serializers.CharField(source="get_absolute_url", read_only=True) data_url = serializers.CharField(source="get_data_url", read_only=True) download_url = serializers.CharField(source="get_download_url", read_only=True) def to_representation(self, instance): ret = super().to_representation(instance) ret["visual_type"] = instance.get_visual_type_display() return ret class Meta: model = models.DataPivot fields = "__all__" class DataPivotQuerySerializer(DataPivotSerializer): preferred_units = serializers.ListField( allow_empty=True, child=serializers.IntegerField(min_value=0) ) class Meta: model = models.DataPivotQuery fields = "__all__" class CollectionVisualSerializer(serializers.ModelSerializer): url = serializers.CharField(source="get_absolute_url") visual_type = serializers.CharField(source="get_visual_type_display") data_url = serializers.CharField(source="get_data_url") class Meta: model = models.Visual exclude = ("endpoints",) class VisualSerializer(serializers.ModelSerializer): def to_representation(self, instance): ret = super().to_representation(instance) if instance.id != instance.FAKE_INITIAL_ID: ret["url"] = instance.get_absolute_url() ret["url_update"] = instance.get_update_url() ret["url_delete"] = instance.get_delete_url() ret["data_url"] = instance.get_data_url() if instance.visual_type in [ constants.VisualType.ROB_HEATMAP, constants.VisualType.ROB_BARCHART, ]: ret["rob_settings"] = AssessmentRiskOfBiasSerializer(instance.assessment).data ret["visual_type"] = instance.get_visual_type_display() ret["endpoints"] = [ SerializerHelper.get_serialized(d, json=False) for d in instance.get_endpoints() ] ret["studies"] = [ SerializerHelper.get_serialized(d, json=False) for d in instance.get_studies() ] ret["assessment_rob_name"] = instance.assessment.get_rob_name_display() ret["assessment_name"] = str(instance.assessment) return ret def validate(self, data): visual_type = data["visual_type"] evidence_type = data["evidence_type"] if evidence_type not in constants.VISUAL_EVIDENCE_CHOICES[visual_type]: raise serializers.ValidationError( { "evidence_type": f"Invalid evidence type {evidence_type} for visual {visual_type}." } ) return data class Meta: model = models.Visual exclude = ("endpoints",) class SummaryTextSerializer(serializers.ModelSerializer): parent = serializers.PrimaryKeyRelatedField( queryset=models.SummaryText.objects.all(), write_only=True ) sibling = serializers.PrimaryKeyRelatedField( queryset=models.SummaryText.objects.all(), write_only=True, required=False, allow_null=True ) class Meta: model = models.SummaryText fields = "__all__" read_only_fields = ("depth", "path") def validate_text(self, value): validators.validate_hyperlinks(value) return sanitize_html.clean_html(value) def validate(self, data): assessment = data["assessment"] parent = data.get("parent") if parent and parent.assessment != assessment: raise ValidationError({"parent": "Parent must be from the same assessment"}) sibling = data.get("sibling") if sibling and sibling.assessment != assessment: raise ValidationError({"sibling": "Sibling must be from the same assessment"}) return data def create(self, validated_data): parent = validated_data.pop("parent", None) sibling = validated_data.pop("sibling", None) instance = models.SummaryText(**validated_data) if sibling: return sibling.add_sibling(pos="right", instance=instance) else: sibling = parent.get_first_child() if sibling: return sibling.add_sibling(pos="first-sibling", instance=instance) else: return parent.add_child(instance=instance) @transaction.atomic def update(self, instance, validated_data): instance.title = validated_data["title"] instance.slug = validated_data["slug"] instance.text = validated_data["text"] instance.save() parent = validated_data.get("parent") sibling = validated_data.get("sibling", None) if sibling: if instance.get_prev_sibling() != sibling: instance.move(sibling, pos="right") elif parent: instance.move(parent, pos="first-child") return instance class SummaryTableSerializer(serializers.ModelSerializer): class Meta: model = models.SummaryTable fields = "__all__" def to_representation(self, instance): ret = super().to_representation(instance) if instance.id: ret["url"] = instance.get_absolute_url() return ret def validate(self, data): # check model level validation models.SummaryTable(**data).clean() return data SerializerHelper.add_serializer(models.Visual, VisualSerializer)
# Copyright 2023 Efabless Corporation # # 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. from typing import List, Type from ..steps import ( Step, ) from ..steps import ( Yosys, OpenROAD, Magic, Misc, KLayout, Odb, Netgen, Checker, ) from .flow import Flow from .sequential import SequentialFlow @Flow.factory.register() class Classic(SequentialFlow): """ A flow of type :class:`openlane.flows.SequentialFlow` that is the most similar to the original OpenLane 1.0 flow, running the Verilog RTL through Yosys, OpenROAD, KLayout and Magic to produce a valid GDSII for simpler designs. This is the default when using OpenLane via the command-line. """ Steps: List[Type[Step]] = [ Yosys.JsonHeader, Yosys.Synthesis, Checker.YosysUnmappedCells, Checker.YosysSynthChecks, Misc.LoadBaseSDC, OpenROAD.STAPrePNR, OpenROAD.Floorplan, Odb.SetPowerConnections, Odb.ManualMacroPlacement, OpenROAD.TapEndcapInsertion, OpenROAD.IOPlacement, Odb.CustomIOPlacement, Odb.ApplyDEFTemplate, OpenROAD.GeneratePDN, OpenROAD.GlobalPlacement, OpenROAD.STAMidPNR, Odb.DiodesOnPorts, Odb.HeuristicDiodeInsertion, OpenROAD.RepairDesign, OpenROAD.DetailedPlacement, OpenROAD.CTS, OpenROAD.STAMidPNR, OpenROAD.ResizerTimingPostCTS, OpenROAD.STAMidPNR, OpenROAD.GlobalRouting, OpenROAD.ResizerTimingPostGRT, OpenROAD.STAMidPNR, OpenROAD.DetailedRouting, Checker.TrDRC, Odb.ReportDisconnectedPins, Checker.DisconnectedPins, Odb.ReportWireLength, Checker.WireLength, OpenROAD.FillInsertion, OpenROAD.RCX, OpenROAD.STAPostPNR, OpenROAD.IRDropReport, Magic.StreamOut, KLayout.StreamOut, Magic.WriteLEF, KLayout.XOR, Checker.XOR, Magic.DRC, Checker.MagicDRC, Magic.SpiceExtraction, Checker.IllegalOverlap, Netgen.LVS, Checker.LVS, ]
// Copyright 2023 Northern.tech AS // // 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. #include <common/http_resumer.hpp> #include <regex> #include <common/common.hpp> #include <common/expected.hpp> namespace mender { namespace common { namespace http { namespace resumer { namespace common = mender::common; namespace expected = mender::common::expected; namespace http = mender::common::http; // Represents the parts of a Content-Range HTTP header // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range struct RangeHeader { long long int range_start {0}; long long int range_end {0}; long long int size {0}; }; using ExpectedRangeHeader = expected::expected<RangeHeader, error::Error>; // Parses the HTTP Content-Range header // For an alternative implementation without regex dependency see: // https://github.com/mendersoftware/mender/pull/1372/commits/ea711fc4dafa943266e9013fd6704da3d4518a27 ExpectedRangeHeader ParseRangeHeader(string header) { RangeHeader range_header {}; std::regex content_range_regexp {R"(bytes\s+(\d+)\s?-\s?(\d+)\s?\/?\s?(\d+|\*)?)"}; std::smatch range_matches; if (!regex_match(header, range_matches, content_range_regexp)) { return expected::unexpected(http::MakeError( http::NoSuchHeaderError, "Invalid Content-Range returned from server: " + header)); } auto exp_range_start = common::StringToLongLong(range_matches[1].str()); auto exp_range_end = common::StringToLongLong(range_matches[2].str()); if (!exp_range_start || !exp_range_end) { return expected::unexpected(http::MakeError( http::NoSuchHeaderError, "Content-Range contains invalid number: " + header)); } range_header.range_start = exp_range_start.value(); range_header.range_end = exp_range_end.value(); if (range_header.range_start > range_header.range_end) { return expected::unexpected(http::MakeError( http::NoSuchHeaderError, "Invalid Content-Range returned from server: " + header)); } if ((range_matches[3].matched) && (range_matches[3].str() != "*")) { auto exp_size = common::StringToLongLong(range_matches[3].str()); if (!exp_size) { return expected::unexpected(http::MakeError( http::NoSuchHeaderError, "Content-Range contains invalid number: " + header)); } range_header.size = exp_size.value(); } return range_header; } class HeaderHandlerFunctor { public: HeaderHandlerFunctor(weak_ptr<DownloadResumerClient> resumer) : resumer_client_ {resumer} {}; void operator()(http::ExpectedIncomingResponsePtr exp_resp); private: void HandleFirstResponse( const shared_ptr<DownloadResumerClient> &resumer_client, http::ExpectedIncomingResponsePtr exp_resp); void HandleNextResponse( const shared_ptr<DownloadResumerClient> &resumer_client, http::ExpectedIncomingResponsePtr exp_resp); weak_ptr<DownloadResumerClient> resumer_client_; }; class BodyHandlerFunctor { public: BodyHandlerFunctor(weak_ptr<DownloadResumerClient> resumer) : resumer_client_ {resumer} {}; void operator()(http::ExpectedIncomingResponsePtr exp_resp); private: weak_ptr<DownloadResumerClient> resumer_client_; }; void HeaderHandlerFunctor::operator()(http::ExpectedIncomingResponsePtr exp_resp) { auto resumer_client = resumer_client_.lock(); if (resumer_client) { // If an error has already occurred, schedule the next AsyncCall directly if (!exp_resp) { resumer_client->logger_.Warning(exp_resp.error().String()); auto err = resumer_client->ScheduleNextResumeRequest(); if (err != error::NoError) { resumer_client->logger_.Error(err.String()); resumer_client->CallUserHandler(expected::unexpected(err)); } return; } if (resumer_client->resumer_state_->active_state == DownloadResumerActiveStatus::Resuming) { HandleNextResponse(resumer_client, exp_resp); } else { HandleFirstResponse(resumer_client, exp_resp); } } } void HeaderHandlerFunctor::HandleFirstResponse( const shared_ptr<DownloadResumerClient> &resumer_client, http::ExpectedIncomingResponsePtr exp_resp) { // The first response shall always call the user header callback. On resumable responses, we // create a our own incoming response and call the user header handler. On errors, we log a // warning and call the user handler with the original response auto resp = exp_resp.value(); if (resp->GetStatusCode() != mender::common::http::StatusOK) { // Non-resumable response resumer_client->CallUserHandler(exp_resp); return; } auto exp_header = resp->GetHeader("Content-Length"); if (!exp_header || exp_header.value() == "0") { resumer_client->logger_.Warning("Response does not contain Content-Length header"); resumer_client->CallUserHandler(exp_resp); return; } auto exp_length = common::StringToLongLong(exp_header.value()); if (!exp_length || exp_length.value() < 0) { resumer_client->logger_.Warning( "Content-Length contains invalid number: " + exp_header.value()); resumer_client->CallUserHandler(exp_resp); return; } // Resumable response resumer_client->resumer_state_->active_state = DownloadResumerActiveStatus::Resuming; resumer_client->resumer_state_->offset = 0; resumer_client->resumer_state_->content_length = exp_length.value(); // Prepare a modified response and call user handler resumer_client->response_.reset(new http::IncomingResponse(*resumer_client, resp->cancelled_)); resumer_client->response_->status_code_ = resp->GetStatusCode(); resumer_client->response_->status_message_ = resp->GetStatusMessage(); resumer_client->response_->headers_ = resp->GetHeaders(); resumer_client->CallUserHandler(resumer_client->response_); } void HeaderHandlerFunctor::HandleNextResponse( const shared_ptr<DownloadResumerClient> &resumer_client, http::ExpectedIncomingResponsePtr exp_resp) { // If an error occurs during handling here, cancel the resuming and call the user handler. auto resp = exp_resp.value(); auto resumer_reader = resumer_client->resumer_reader_.lock(); if (!resumer_reader) { // Errors should already have been handled as part of the Cancel() inside the // destructor of the reader. return; } auto exp_content_range = resp->GetHeader("Content-Range").and_then(ParseRangeHeader); if (!exp_content_range) { resumer_client->logger_.Error(exp_content_range.error().String()); resumer_client->CallUserHandler(expected::unexpected(exp_content_range.error())); return; } auto content_range = exp_content_range.value(); if (content_range.size != 0 && content_range.size != resumer_client->resumer_state_->content_length) { auto size_changed_err = http::MakeError( http::DownloadResumerError, "Size of artifact changed after download was resumed (expected " + to_string(resumer_client->resumer_state_->content_length) + ", got " + to_string(content_range.size) + ")"); resumer_client->logger_.Error(size_changed_err.String()); resumer_client->CallUserHandler(expected::unexpected(size_changed_err)); return; } if ((content_range.range_end != resumer_client->resumer_state_->content_length - 1) || (content_range.range_start != resumer_client->resumer_state_->offset)) { auto bad_range_err = http::MakeError( http::DownloadResumerError, "HTTP server returned an different range than requested. Requested " + to_string(resumer_client->resumer_state_->offset) + "-" + to_string(resumer_client->resumer_state_->content_length - 1) + ", got " + to_string(content_range.range_start) + "-" + to_string(content_range.range_end)); resumer_client->logger_.Error(bad_range_err.String()); resumer_client->CallUserHandler(expected::unexpected(bad_range_err)); return; } // Get the reader for the new response auto exp_reader = resumer_client->client_.MakeBodyAsyncReader(resp); if (!exp_reader) { auto bad_range_err = exp_reader.error().WithContext("cannot get the reader after resume"); resumer_client->logger_.Error(bad_range_err.String()); resumer_client->CallUserHandler(expected::unexpected(bad_range_err)); return; } // Update the inner reader of the user reader resumer_reader->inner_reader_ = exp_reader.value(); // Resume reading reusing last user data (start, end, handler) auto err = resumer_reader->AsyncReadResume(); if (err != error::NoError) { auto bad_read_err = err.WithContext("error reading after resume"); resumer_client->logger_.Error(bad_read_err.String()); resumer_client->CallUserHandler(expected::unexpected(bad_read_err)); return; } } void BodyHandlerFunctor::operator()(http::ExpectedIncomingResponsePtr exp_resp) { auto resumer_client = resumer_client_.lock(); if (!resumer_client) { return; } if (*resumer_client->cancelled_) { resumer_client->CallUserHandler(exp_resp); return; } if (resumer_client->resumer_state_->active_state == DownloadResumerActiveStatus::Inactive) { resumer_client->CallUserHandler(exp_resp); return; } // We resume the download if either: // * there is any error or // * successful read with status code Partial Content and there is still data missing const bool is_range_response = exp_resp && exp_resp.value()->GetStatusCode() == mender::common::http::StatusPartialContent; const bool is_data_missing = resumer_client->resumer_state_->offset < resumer_client->resumer_state_->content_length; if (!exp_resp || (is_range_response && is_data_missing)) { if (!exp_resp) { auto resumer_reader = resumer_client->resumer_reader_.lock(); if (resumer_reader) { resumer_reader->inner_reader_.reset(); } if (exp_resp.error().code == make_error_condition(errc::operation_canceled)) { // We don't want to resume cancelled requests, as these were // cancelled for a reason. resumer_client->CallUserHandler(exp_resp); return; } resumer_client->logger_.Info( "Will try to resume after error " + exp_resp.error().String()); } auto err = resumer_client->ScheduleNextResumeRequest(); if (err != error::NoError) { resumer_client->logger_.Error(err.String()); resumer_client->CallUserHandler(expected::unexpected(err)); return; } } else { // Update headers with the last received server response. When resuming has taken place, // the user will get different headers on header and body handlers, representing (somehow) // what the resumer has been doing in its behalf. auto resp = exp_resp.value(); resumer_client->response_->status_code_ = resp->GetStatusCode(); resumer_client->response_->status_message_ = resp->GetStatusMessage(); resumer_client->response_->headers_ = resp->GetHeaders(); // Finished, call the user handler \o/ resumer_client->logger_.Debug("Download resumed and completed successfully"); resumer_client->CallUserHandler(resumer_client->response_); } } DownloadResumerAsyncReader::~DownloadResumerAsyncReader() { Cancel(); } void DownloadResumerAsyncReader::Cancel() { auto resumer_client = resumer_client_.lock(); if (!*cancelled_ && resumer_client) { resumer_client->Cancel(); } } error::Error DownloadResumerAsyncReader::AsyncRead( vector<uint8_t>::iterator start, vector<uint8_t>::iterator end, io::AsyncIoHandler handler) { if (eof_) { handler(0); return error::NoError; } auto resumer_client = resumer_client_.lock(); if (!resumer_client || *cancelled_) { return error::MakeError( error::ProgrammingError, "DownloadResumerAsyncReader::AsyncRead called after stream is destroyed"); } // Save user parameters for further resumes of the body read resumer_client->last_read_ = {.start = start, .end = end, .handler = handler}; return AsyncReadResume(); } error::Error DownloadResumerAsyncReader::AsyncReadResume() { auto resumer_client = resumer_client_.lock(); if (!resumer_client) { return error::MakeError( error::ProgrammingError, "DownloadResumerAsyncReader::AsyncReadResume called after client is destroyed"); } return inner_reader_->AsyncRead( resumer_client->last_read_.start, resumer_client->last_read_.end, [this](io::ExpectedSize result) { if (!result) { logger_.Warning( "Reading error, a new request will be re-scheduled. " + result.error().String()); } else { if (result.value() == 0) { eof_ = true; } resumer_state_->offset += result.value(); logger_.Debug("read " + to_string(result.value()) + " bytes"); auto resumer_client = resumer_client_.lock(); if (resumer_client) { resumer_client->last_read_.handler(result); } else { logger_.Error( "AsyncRead finish handler called after resumer client has been destroyed."); } } }); } DownloadResumerClient::DownloadResumerClient( const http::ClientConfig &config, events::EventLoop &event_loop) : resumer_state_ {make_shared<DownloadResumerClientState>()}, client_(config, event_loop, "http_resumer:client"), logger_ {"http_resumer:client"}, cancelled_ {make_shared<bool>(true)}, retry_ { .backoff = http::ExponentialBackoff(chrono::minutes(1), 10), .wait_timer = events::Timer(event_loop)} { } DownloadResumerClient::~DownloadResumerClient() { if (!*cancelled_) { logger_.Warning("DownloadResumerClient destroyed while request is still active!"); } client_.Cancel(); } error::Error DownloadResumerClient::AsyncCall( http::OutgoingRequestPtr req, http::ResponseHandler user_header_handler, http::ResponseHandler user_body_handler) { HeaderHandlerFunctor resumer_header_handler {shared_from_this()}; BodyHandlerFunctor resumer_body_handler {shared_from_this()}; user_request_ = req; user_header_handler_ = user_header_handler; user_body_handler_ = user_body_handler; if (!*cancelled_) { return error::Error( make_error_condition(errc::operation_in_progress), "HTTP resumer call already ongoing"); } *cancelled_ = false; retry_.backoff.Reset(); resumer_state_->active_state = DownloadResumerActiveStatus::Inactive; resumer_state_->user_handlers_state = DownloadResumerUserHandlersStatus::None; return client_.AsyncCall(req, resumer_header_handler, resumer_body_handler); } io::ExpectedAsyncReaderPtr DownloadResumerClient::MakeBodyAsyncReader( http::IncomingResponsePtr resp) { auto exp_reader = client_.MakeBodyAsyncReader(resp); if (!exp_reader) { return exp_reader; } auto resumer_reader = make_shared<DownloadResumerAsyncReader>( exp_reader.value(), resumer_state_, cancelled_, shared_from_this()); resumer_reader_ = resumer_reader; return resumer_reader; } http::OutgoingRequestPtr DownloadResumerClient::RemainingRangeRequest() const { auto range_req = make_shared<http::OutgoingRequest>(*user_request_); range_req->SetHeader( "Range", "bytes=" + to_string(resumer_state_->offset) + "-" + to_string(resumer_state_->content_length - 1)); return range_req; }; error::Error DownloadResumerClient::ScheduleNextResumeRequest() { auto exp_interval = retry_.backoff.NextInterval(); if (!exp_interval) { return http::MakeError( http::DownloadResumerError, "Giving up on resuming the download: " + exp_interval.error().String()); } auto interval = exp_interval.value(); logger_.Info( "Resuming download after " + to_string(chrono::duration_cast<chrono::seconds>(interval).count()) + " seconds"); HeaderHandlerFunctor resumer_next_header_handler {shared_from_this()}; BodyHandlerFunctor resumer_next_body_handler {shared_from_this()}; retry_.wait_timer.AsyncWait( interval, [this, resumer_next_header_handler, resumer_next_body_handler](error::Error err) { if (err != error::NoError) { auto err_user = http::MakeError( http::DownloadResumerError, "Unexpected error in wait timer: " + err.String()); logger_.Error(err_user.String()); CallUserHandler(expected::unexpected(err_user)); return; } auto next_call_err = client_.AsyncCall( RemainingRangeRequest(), resumer_next_header_handler, resumer_next_body_handler); if (next_call_err != error::NoError) { // Schedule once more auto err = ScheduleNextResumeRequest(); if (err != error::NoError) { logger_.Error(err.String()); CallUserHandler(expected::unexpected(err)); } } }); return error::NoError; } void DownloadResumerClient::CallUserHandler(http::ExpectedIncomingResponsePtr exp_resp) { if (!exp_resp) { DoCancel(); } if (resumer_state_->user_handlers_state == DownloadResumerUserHandlersStatus::None) { resumer_state_->user_handlers_state = DownloadResumerUserHandlersStatus::HeaderHandlerCalled; user_header_handler_(exp_resp); } else if ( resumer_state_->user_handlers_state == DownloadResumerUserHandlersStatus::HeaderHandlerCalled) { resumer_state_->user_handlers_state = DownloadResumerUserHandlersStatus::BodyHandlerCalled; DoCancel(); user_body_handler_(exp_resp); } else { string msg; if (!exp_resp) { msg = "error: " + exp_resp.error().String(); } else { auto &resp = exp_resp.value(); msg = "response: " + to_string(resp->GetStatusCode()) + " " + resp->GetStatusMessage(); } logger_.Warning("Cannot call any user handler with " + msg); } } void DownloadResumerClient::Cancel() { DoCancel(); client_.Cancel(); }; void DownloadResumerClient::DoCancel() { // Set cancel state and then make a new one. Those who are interested should have their own // pointer to the old one. *cancelled_ = true; cancelled_ = make_shared<bool>(true); }; } // namespace resumer } // namespace http } // namespace common } // namespace mender
package main import ( "bytes" "fmt" "os" "strconv" ) func parseInput(filename string) [][]int { buff, _ := os.ReadFile(filename) buff = bytes.TrimSpace(buff) lines := bytes.Split(buff, []byte("\n")) sequences := make([][]int, len(lines)) for i, line := range lines { fields := bytes.Fields(line) sequence := make([]int, len(fields)) for j, f := range fields { sequence[j], _ = strconv.Atoi(string(f)) } sequences[i] = sequence } return sequences } func isAllZeros(seq []int) bool { for _, num := range seq { if num != 0 { return false } } return true } func getPairwiseDiffs(seq []int) []int { diff := make([]int, len(seq)-1) for i := range diff { diff[i] = seq[i+1] - seq[i] } return diff } func predictNextNum(seq []int) (num int) { diffs := make([][]int, 0) diffs = append(diffs, seq) latestDiff := seq // Find Pairwise differences, util all are zero for !isAllZeros(latestDiff) { nextLayer := getPairwiseDiffs(latestDiff) diffs = append(diffs, nextLayer) latestDiff = nextLayer } // Add a `0` to the end of each layer for i, d := range diffs { diffs[i] = append(d, 0) } // Find sums between layers to predict the next num for i := len(diffs) - 2; i >= 0; i-- { lastIdx := len(diffs[i]) - 1 diffs[i][lastIdx] = diffs[i][lastIdx-1] + diffs[i+1][lastIdx-1] } num = diffs[0][len(diffs[0])-1] return } func solveA(seqs [][]int) (acc int) { for _, seq := range seqs { num := predictNextNum(seq) fmt.Println(seq, "->", num) acc += num } return } func predictPrevNum(seq []int) (num int) { diffs := make([][]int, 0) diffs = append(diffs, seq) latestDiff := seq // Find Pairwise differences, util all are zero for !isAllZeros(latestDiff) { nextLayer := getPairwiseDiffs(latestDiff) diffs = append(diffs, nextLayer) latestDiff = nextLayer } // Add a `0` to the START of each layer for i, d := range diffs { diffs[i] = append([]int{0}, d...) } // Find sums between layers to predict the next num for i := len(diffs) - 2; i >= 0; i-- { diffs[i][0] = diffs[i][1] - diffs[i+1][0] } num = diffs[0][0] return } func solveB(seqs [][]int) (acc int) { for _, seq := range seqs { num := predictPrevNum(seq) fmt.Println(seq, "->", num) acc += num } return } func main() { seqs := parseInput("day9/in.txt") solnA := solveA(seqs) fmt.Println("Solution A:", solnA) solnB := solveB(seqs) fmt.Println("Solution B:", solnB) }
Background HIV infection among women in the United States has increased significantly over the last fifteen years, and recent estimates suggest that as many as 160,000 adult and adolescent women are living with HIV infection and/or AIDS [ 1 ] . Women accounted for almost one fourth of the new AIDS cases reported in 1999, and most of these women were infected with HIV through heterosexual contact. HIV prevention interventions can reduce risky sexual behaviour of women [ 2 ] , and numerous studies have documented the effectiveness of various cognitive-behavioural group intervention models [ 3 4 5 6 7 8 9 10 ] . For example, persons who participated in a 30-minute condom use skills educational session in a Los Angeles waiting room were less likely to return to the sexually transmitted disease (STD) clinic with a new STD than those who did not participate in the educational session [ 11 ] . Many interventions have been successful in increasing condom usage by supplementing condom use education and/or general HIV/AIDS education with training in other areas, such as negotiation skills (how to suggest condom use with a new partner), assertiveness skills (how to resist unwanted sexual advances) and cognitive coping skills (such as sexual self-control) and by improving self-esteem [ 4 5 6 9 12 ] . Policy- and decision-makers who plan HIV prevention programs need information about the cost-effectiveness of these programs in order to maximize the benefits of limited HIV prevention resources [ 7 13 ] . Here, we evaluated the cost-effectiveness of the Women in Group Support (WINGS) project, a six-session group-based intervention that offered training in condom use skills (using condoms correctly) and in communication skills (such as talking to sex partners about condom usage) for urban heterosexual women at high risk of acquiring HIV and other STDs. Methods Intervention content, delivery, and efficacy The methods of the WINGS intervention trial have been described previously [ 10 14 15 ] . A total of 604 HIV-uninfected women at high risk for STD/HIV were recruited from Baltimore, New York, and Seattle from May 1995 through July 1997. After completing baseline interviews, the women were randomly assigned to the intervention or to the control group. The intervention group sessions included components on reducing HIV and STD risk identified by Fisher and Fisher [ 16 ] , specifically training in the proper use of male and female condoms and building skills in communication to sex partners to encourage condom use (Table 1). Participants in the control group attended a 1-hour session on nutrition. Condom usage by the women in the WINGS intervention increased substantially, and at least part of this increase was attributable to intervention's effect on condom use skills and communication skills [ 10 15 ] . A model-based evaluation of the efficacy of the WINGS intervention [ 10 ] demonstrated that most of the intervention's effect on increasing condom usage was attributable to the condom use skills component of the intervention. This analysis focussed on the cost-effectiveness of the intervention. We evaluated the cost-effectiveness of the complete six-session intervention and the two sessions of the intervention that addressed condom use skills. For brevity, we refer to the complete, six-session WINGS intervention as the "complete intervention" and we refer to the two sessions that addressed condom skills training as the "condom use skills component" of the intervention. The condom use skills component was part of (not an alternative to) the complete intervention. To evaluate the cost-effectiveness of the condom use skills component of the intervention, we estimated the increase in condom usage attributable to the condom use skills component. We examined cost-effectiveness from the societal perspective, in which relevant costs and benefits were included in the analysis without regard to who might actually pay the costs or receive the benefits [ 17 ] . We calculated intervention costs for the period during which the intervention was delivered. Benefits of the intervention (averted HIV infections) were assumed to accrue in the 6 months following the intervention. The societal cost per HIV infection included the future medical care costs and indirect costs such as lost productivity, discounted at 3% annually. The cost-effectiveness analysis comprised four main steps: (1) retrospective analysis of the intervention's cost, (2) estimation of the number of HIV infections averted by the intervention, (3) calculation of the cost-effectiveness ratios, and (4) sensitivity analyses to examine how the cost-effectiveness ratios would change over a range of assumptions about cost and effectiveness. We present the methods to evaluate the cost-effectiveness of the complete intervention. Except where noted, the methods to evaluate the "condom use skills component" were identical. Estimating the intervention's cost Cost estimates (in 1996 dollars) were based primarily on cost information provided by the WINGS principal investigators, who estimated the various resources required to deliver the intervention. We obtained additional information from budget proposals of the WINGS project and from cost estimates of an earlier intervention of similar duration and intensity [ 13 ] . Because women attended sessions in small groups, costs were calculated per group of six women. Our assessment of intervention costs included the cost of rent for participant meeting spaces (including overhead and miscellaneous costs), facilitator wages and training, senior staff time for quality assurance, recruitment, client costs (incentive payments, child care and transportation compensation, and meals), and materials (such as condoms, anatomic models, and information pamphlets). The child care compensation, travel compensation, and incentive payments were assumed to cover all costs (direct and indirect) borne by the participants, such as travel expenses and foregone time for work or leisure. In calculating recruitment costs, we assumed that 75% of the total recruitment costs could be attributed to the randomized control nature of the study and not to the intervention itself. In assessing the cost of the condom use skills component of the intervention, we divided each cost item included in the complete intervention (except recruitment and materials) by three, as the condom use skills component had one-third the number of sessions as the complete intervention. Recruitment and materials costs in the condom use skills component were assumed to be the same as the complete intervention, since recruitment would still be necessary regardless of the duration of the intervention and since most of the materials cost in the complete intervention were attributable to the two sessions of the intervention focussing on condom use skills. HIV cases averted The number of HIV infections averted (A) by the intervention was estimated according to Equation 1: where the intervention is assumed to increase the percentage of sexual encounters protected by condoms from ρ b to ρ i , ε is condom effectiveness per act of intercourse, R is the probability of acquiring HIV in the absence of the intervention, and N is the number of women in the intervention. This approximation is derived from a model-based evaluation of the benefits of increases in occasional condom usage, which suggested that under conditions that prevail in many at-risk heterosexual populations the relationship between increased condom usage and HIV risk reduction is essentially linear [ 18 ] . For example, if condoms were 95% effective in preventing HIV transmission, then an increase in condom usage from 0% to 100% would reduce the risk of acquiring HIV by about 95%. Smaller increases in condom usage would yield smaller reductions in risk. Parameter values for equation 1 are summarized in Table 2. Values for ρ b and ρ i were obtained from the structural equation model estimates in a previous study of the efficacy of the WINGS intervention [ 10 ] . Based on these model estimates (see appendix), we applied the following base case values for condom usage following the intervention: 53.2% for the control group, 57.7% for the complete intervention, and 56.8% for the condom use skills component. Based on data from several sources, we assumed 0.019 as the base case annual probability of acquiring HIV in the absence of the intervention. Recent studies of high-risk urban women from several cities in the United States suggest HIV incidence rates in the range of 0.018 to more than 7 new infections per 100 person-years [ 19 20 21 22 23 24 ] , with the highest rates observed among women who reported exchanging sex for money or drugs and women with a recent history of acquiring other STDs such as syphilis. Of the women initially recruited for the WINGS trial, about one-fourth reported trading sex for money or drugs and almost one-third reported having an STD in the previous year [ 14 ] . Condom effectiveness (ε), the reduction in the per-act probability of HIV transmission when a condom is used, was set to 95% [ 25 ] . We assumed the increase in condom usage attributable to the intervention would last 6 months (range: 3 to 9) as the increases in condom usage attributable to the intervention were found to diminish by the six-month follow-up interviews [ 10 ] . The value of R was calculated from the annual probability of HIV infection (P) and the assumed duration of the intervention in months (D) as follows: R = 1 - (1 - P) D/12. Thus R represents the base case probability of acquiring HIV (in the absence of the intervention) during the D months following the intervention. Cost-effectiveness ratios Using standard methods of cost-effectiveness analysis, we calculated the average cost per HIV case averted as the net cost of the intervention divided by the estimated number of HIV infections averted, where net cost refers to the intervention's cost minus the societal costs of HIV averted by the intervention [ 26 ] . Averted HIV costs were calculated by multiplying the estimated number of averted HIV cases by the cost per case of HIV. Our baseline estimate of the societal cost of HIV was $337,000 per case, which includes the lifetime medical care costs ($195,000, with future costs discounted at 3% annually) and indirect costs ($142,000) such as lost economic productivity [ 27 28 ] . This estimate of the indirect costs per case of HIV was based on a recent report that indirect costs of HIV in England comprised between 45% to 102% of the direct treatment costs of HIV [ 28 ] . We used the midpoint of this range and assumed that indirect costs would be 73% of the direct medical costs ($195,000 × 73% = $142,000). This estimate of the indirect costs is quite conservative compared to other studies which suggest the indirect costs of HIV exceed the direct medical care costs [ 29 30 ] . We did not calculate the cost per quality-adjusted life year (QALY) gained when indirect costs of HIV were included in the cost per case of HIV, because these indirect costs might be "double counted" if included in the numerator (as averted HIV costs) and the denominator (as part of the QALY measure) [ 31 32 ] . For completeness, we repeated the analysis excluding the indirect costs of HIV from the numerator, focussing solely on the direct medical care costs ($195,000). The cost per QALY saved was calculated as the net cost of the intervention (the intervention's cost minus the direct medical care costs of HIV averted) divided by the number of QALYs saved. The number of QALYs saved was calculated by multiplying the estimated number of averted HIV cases by published estimates of the number of QALYs saved per HIV case averted [ 27 ] . To assess the cost-effectiveness of the complete intervention and the condom use skills component, we compared these interventions to the alternative of no intervention, which we assumed would have $0 in program cost and would not avert any new cases of HIV. For the complete intervention, we also calculated the incremental cost-effectiveness ratios, which compare the complete intervention to the condom use skills component. The incremental cost per case averted was calculated as difference in net cost (the net cost of the complete intervention minus that of the condom use skills component) divided by the difference in HIV cases averted (HIV cases averted by the complete intervention minus the HIV cases averted by the condom use skills component) [ 26 ] . The incremental cost per QALY saved was calculated in an analogous manner. Sensitivity analyses We conducted univariate and multivariate sensitivity analyses. In the univariate analysis, we examined how the estimated cost per case averted changed when we varied one parameter at a time, holding other parameters at their base case values. The parameters we varied were the cost of the intervention, the effectiveness of the intervention (as measured by condom usage after the intervention), condom efficacy, the annual probability of acquiring HIV, the duration of the effectiveness of the intervention, and the cost per case of HIV. In the multivariate analysis we varied all of the parameters listed above simultaneously. Specifically, we chose values for each parameter under the assumption that these values were uniformly distributed between their respective lower and upper bounds. We then estimated the cost per case averted using these random values. We repeated this procedure 20,000 times (a "Monte Carlo" simulation [ 33 ] ) to obtain a distribution of the estimated cost-effectiveness ratios. Ranges (upper and lower bounds) of all of the parameters (except condom use, condom effectiveness, and the number of QALYs saved per HIV case averted) were chosen as ± 50% of the parameter's base case value to allow for a wide variance in the values we applied in our sensitivity analyses. The selection of ranges for condom usage among intervention participants is described in the appendix. An analysis of HIV seroconversion studies indicated that condom usage decrease the per-act risk of HIV infection by 90% to 95% [ 25 ] . We applied a slightly wider range (85% to 98%) of possible values for condom effectiveness. The range for the number of QALYs saved per HIV case averted was obtained from a previously published study [ 27 ] . Results Sensitivity analyses In the univariate sensitivity analysis (Table 5), the cost per case averted for the complete intervention ranged from cost-saving (a negative cost per case averted) to more than $750,000. The cost per case averted for the condom use skills component ranged from cost-saving to almost $250,000. The results were most sensitive to changes in the annual probability of acquiring HIV, the effectiveness of the intervention (as measured by condom use among intervention participants), the duration of the intervention's effect on condom usage, and the cost of the intervention. When indirect costs of HIV were excluded, the cost per case averted ranged from $81,345 to more than $900,000 for the complete intervention and from cost-saving to almost $400,000 for the condom use skills component. In the multivariate sensitivity analysis (Table 6), the cost per case averted for the complete intervention ranged from cost-saving to more than $1.5 million, with a median value of $302,254. The cost per case averted for the condom use skills component ranged from cost-saving to more than $600,000 per case of HIV averted, with a median value of $13,504. When considering only the direct medical care costs of HIV, the median cost per case averted was $444,409 (range: $27,506 to $1.6 million) for the complete intervention and $150,201 (range: cost-saving to $783,820) for the condom use skills component. Discussion Improving the cost-effectiveness of HIV prevention interventions The finding that the condom use skills component was more cost-effective than the complete intervention is consistent with previous studies demonstrating the effectiveness of brief STD/HIV counselling sessions for persons at high risk for HIV and STDs [ 8 36 ] . These findings suggest the possibility that for a given budget, more HIV infections could be prevented by providing brief interventions to a larger number of people at risk for HIV rather than providing more intensive and lengthy interventions to a smaller number of people at risk for HIV. Our analysis also illustrated the importance of targeting the intervention to those at the highest risk for HIV. The cost-effectiveness ratios improved substantially when we assumed an annual probability of acquiring HIV of 3% per year (Table 5), a probability consistent with HIV incidence rates in some populations of high-risk urban women [ 19 20 21 22 ] . Reductions in the cost of the intervention would improve the program's cost-effectiveness (Table 5). The WINGS intervention might be delivered in a more cost-effective manner in other settings. For example, if incorporated into existing programs such as drug treatment or into corrections settings, additional recruitment expenses, incentive payments, transportation, meals, and child care would not be required. Limitations Our analysis is subject to at least four main limitations, the most important of which is the uncertainty in quantifying the effectiveness of the WINGS intervention. Intervention participants showed a significant increase in use of the female condom as compared to the control group [ 15 ] . Condom usage, as measured by the odds of condom use (male and female condoms), increased substantially for women in the intervention and for women in the control group [ 10 ] . Although this increase in condom usage for women in the intervention was not statistically different from the (lesser) increase shown by women in the control group, the WINGS intervention did increase condom use skills and communication skills, and these improved skills were linked to increases in the probability of condom usage [ 10 ] (see appendix). A second limitation is that the condom use skills component was not actually offered as separate, brief intervention, but was part of the six-session intervention required of all of the WINGS participants. As a result, we based our analysis of the effectiveness of the condom use skills component and the complete intervention on estimates of the efficacy of individual components of the intervention suggested by a structural equation model of the complete intervention's efficacy (see appendix). If we incorrectly attributed some of the effect of the complete intervention to the condom use skills component, our estimates will understate the incremental cost-effectiveness of the complete intervention and overstate the average cost-effectiveness of the condom use skills component. Further, because the effects of the condom use skills component may be different when provided alone than when provided in the context of a longer, multifaceted intervention, the estimated cost-effectiveness of the condom use skills component may be biased. A third limitation is the uncertainty in estimating the number of HIV infections averted by the increase in condom use. Our simple approximation was based on an application [ 18 ] of a Bernoulli model of HIV transmission which found that the relationship between increased condom usage and HIV risk reduction is essentially linear for most heterosexuals at risk for HIV. In our simplified model we applied the estimated annual probability of acquiring HIV among high-risk urban women. This average annual probability reflects an average of the various epidemiological and behavioural factors which affect the annual probability of acquiring HIV, such as per-act HIV transmission probabilities, number of sex partners, and HIV prevalence rates in the sex partners. The annual probability of acquiring HIV was the only key input required for our model to provide an estimate of the number of HIV cases averted through an increase in condom usage. Precise values for annual probability of acquiring HIV were difficult to obtain. Our base case probability of acquiring HIV for the WINGSparticipants (0.019) was higher than suggested by the incidence rates reported in some studies of women at high risk for acquiring HIV (0.018 to 1.2 new infections per 100 person-years [ 23 24 ] ), but substantially lower than others (3 or more new infections per 100 person-years [ 19 20 21 22 ] ). A fourth limitation is that we collected cost information retrospectively from the WINGS intervention principal investigators. The cost estimates they provided, however, were reasonably consistent with the detailed budget proposals they submitted prior to the delivery of the intervention. Furthermore, the estimated cost of the WINGS intervention ($456 per participant) is consistent with that of other small-group HIV prevention interventions for women ($450 per participant in a seven-session intervention [ 35 ] and $300 per participant in a five-session intervention [ 13 ] ). Potential underestimation of cost-effectiveness Unlike the WINGS intervention, many HIV interventions have been found to be cost-saving [ 7 34 ] , which occurs when the costs of HIV averted by the intervention outweighs the cost of implementing the intervention. We note that the condom skills component of the intervention, however, did appear to be cost-saving when indirect costs of HIV were included in the analysis. Under many scenarios explored in the sensitivity analyses the WINGS intervention and the condom use skills component were cost-saving. Furthermore, additional limitations of our analysis may have caused a substantial underestimation of the cost-effectiveness of the WINGS intervention. First, our analysis focussed on the prevention of the acquisition of HIV among women in the intervention and ignored the possibility of preventing HIV infection among the women's sex partners. Second, in focussing only on HIV prevention we ignored other potential benefits of the intervention such as reductions in STDs and unintended pregnancies. Third, although the intervention participants reported a substantial increase in condom usage, we only attributed a small part of this increase to the effects of the intervention. The increase in condom usage we did attribute to the intervention was the increase above and beyond the increase in condom usage reported by the control group, and it is possible that part of the increase in condom usage by the control group was attributable to participation in the WINGS trial. For example, measures of condom use skills were obtained for women in the control group on several occasions, requiring the women to perform such tasks as opening the condom package, unrolling the condom, and placing the condom on an anatomical model. If participation in these tasks contributed to the increase in condom usage by the women in the control group, then the actual effectiveness of the WINGS intervention would be understated in our analysis. Conclusions In sum, both the complete intervention and the two-session condom use skills component appeared to be at least moderately cost-effective in preventing HIV among at-risk urban women, using published cost-effectiveness standards for HIV prevention interventions. Our analysis indicated that group interventions consisting of two sessions may be more cost-effective than six sessions and suggested that, for a given HIV prevention budget, offering brief interventions for a large number of at-risk women may be more cost-effective in some cases than longer, more intensive and multifaceted interventions for a smaller number of at-risk women. Appendix The efficacy of the WINGS intervention was based on a previously published evaluation which used a structural equation model [ 10 ] . To estimate ρ b , the probability of condom use without the intervention, we used the probability of condom use for the control group. At three month followup, the (log) odds ratio of protected sex in the control group was 0.13. Thus, log(ρ b / 1 - ρ b ) = .13, or ρ b / (1 - ρ b ) = 1.1388, or ρ b = 0.5324. To estimate ρ i , the probability of condom use with the intervention, we estimated the increase in condom usage associated with the intervention. The structural equation model estimates suggested that the intervention increased the log (odds) of condom use by 0.1818. This value was estimated as the appropriate product of the unstandardized path coefficients connecting the intervention variable to the odds ratio of condom use outcome. A simplified version of the model at 3 months after the intervention is provided in Figure 1. Through recursive substitutions [ 37 ] , it can be shown that the regression coefficient linking the Treatment or Control Group Status variable and the Odds of Condom Usage is: (A*B)+(C*E*F)+(A*D*F), where A,B,C,D,E, and F are all coefficients to be estimated. Applying the published estimates (Table 3in Greenberg et al. 2000 [ 10 ] ) of these coefficients yielded an estimated 0.1818 increase in the (log) odds of condom usage attributable to the intervention. Thus, for the complete intervention, log (ρ i / 1 - ρ i ) = 0.13 + 0.1818, or ρ i / (1 - ρ i ) = 1.3659, or ρ i = 0.5773. Similarly, we calculated the effect of increased condom use skills by calculating (A*B) + (A*D*F), which yielded an estimated 0.1436 increase in the log (odds) of condom usage attributable to the condom use skills component. Thus, for the condom use skills component, log (ρ i / 1 - ρ i ) = 0.13 + 0.1436, or ρ i / (1 - ρ i ) = 1.3147, or ρ i = 0.5680. In sum, the estimated probability of condom usage for a given act of sexual intercourse is 53.2% without the intervention, 57.7% for the complete intervention and 56.8% for the condom use skills component. Using these baseline probabilities, condom usage is increased by 4.5 percentage points (in absolute terms) among women in the complete intervention, of which 3.6 percentage points could be attributed to the condom use skills component. To generate ranges (to be used in the sensitivity analysis) for the estimated condom usage among intervention participants, we varied these increases by ± 50%. Competing interests None declared. Authors' contributions HWC conducted the cost and cost-effectiveness analyses and drafted the manuscript. JBG initiated the study and contributed to the cost and cost-effectiveness analyses. MH contributed to the cost-effectiveness analysis and drafted the appendix. All authors contributed to the writing and reviewing of the manuscript and have read and approved the final version.
import { useDispatch } from "react-redux"; import { useHistory } from "react-router-dom"; //actions import { signin } from "../../store/actions/authActions"; import React from "react"; import IconButton from "@material-ui/core/IconButton"; import InputLabel from "@material-ui/core/InputLabel"; import Visibility from "@material-ui/icons/Visibility"; import InputAdornment from "@material-ui/core/InputAdornment"; import VisibilityOff from "@material-ui/icons/VisibilityOff"; import Input from "@material-ui/core/Input"; const Signin = () => { const [user, setUser] = React.useState({ username: "", password: "", showPassword: false, }); const dispatch = useDispatch(); const history = useHistory(); const handleClickShowPassword = () => { setUser({ ...user, showPassword: !user.showPassword }); }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; const handlePasswordChange = (prop) => (event) => { setUser({ ...user, [prop]: event.target.value }); }; const handleChange = (event) => { setUser({ ...user, [event.target.name]: event.target.value }); }; const handleSubmit = (event) => { event.preventDefault(); dispatch(signin(user, history)); // history.push("/"); }; return ( <form onSubmit={handleSubmit}> <div style={{ marginLeft: "30%", }} > <div class="mb-3"> <label for="formGroupExampleInput" class="form-label"> Username </label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Enter your username" name="username" onChange={handleChange} value={user.username} /> </div> <InputLabel htmlFor="standard-adornment-password"> Enter your Password </InputLabel> <Input type={user.showPassword ? "text" : "password"} onChange={handlePasswordChange("password")} value={user.password} endAdornment={ <InputAdornment position="end"> <IconButton onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} > {user.showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> } /> </div> <button type="submit">Signin</button> </form> ); }; export default Signin;
# coding=utf-8 # RUBEM Hydrological is a QGIS plugin that assists in setup the RUBEM model: # Copyright (C) 2021-2024 LabSid PHA EPUSP # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # # Contact: rubem.hydrological@labsid.eng.br """RUBEM Hydrological plugin user input validation code.""" from os.path import isdir, isfile try: from qgis.PyQt.QtGui import QValidator except ImportError: from PyQt5.QtGui import QValidator DEFAULT_STYLESHEET = "" INVALID_LINEEDIT_STYLESHEET = "border: 1px solid red; color: red;" # ACCEPTABLE_LINEEDIT_STYLESHEET = "border: 1px solid green; color: green;" ACCEPTABLE_LINEEDIT_STYLESHEET = DEFAULT_STYLESHEET # INTERMEDIATE_LINEEDIT_STYLESHEET = "border: 1px solid gold; color: gold;" INTERMEDIATE_LINEEDIT_STYLESHEET = INVALID_LINEEDIT_STYLESHEET INVALID_LABEL_STYLESHEET = "color: red;" # ACCEPTABLE_LABEL_STYLESHEET = "color: green;" ACCEPTABLE_LABEL_STYLESHEET = DEFAULT_STYLESHEET # INTERMEDIATE_LABEL_STYLESHEET = "color: gold;" INTERMEDIATE_LABEL_STYLESHEET = INVALID_LABEL_STYLESHEET class DirectoryPathValidator(QValidator): def __init__(self, parent=None, parentLabel=None): self.lineEdit = parent self.label = parentLabel super().__init__() def validate(self, input: str, pos: int): if not input: self.lineEdit.setStyleSheet(ACCEPTABLE_LINEEDIT_STYLESHEET) return QValidator.Acceptable, input, pos # elif not exists(input): # self.lineEdit.setStyleSheet(INVALID_STYLESHEET) # return QValidator.Invalid, input, pos elif isfile(input): self.lineEdit.setStyleSheet(INTERMEDIATE_LINEEDIT_STYLESHEET) return QValidator.Intermediate, input, pos elif isdir(input): self.lineEdit.setStyleSheet(ACCEPTABLE_LINEEDIT_STYLESHEET) return QValidator.Acceptable, input, pos elif input: self.lineEdit.setStyleSheet(INTERMEDIATE_LINEEDIT_STYLESHEET) return QValidator.Intermediate, input, pos else: self.lineEdit.setStyleSheet(INVALID_LINEEDIT_STYLESHEET) return QValidator.Invalid, input, pos class FilePathValidator(QValidator): def __init__(self, parent=None, parentLabel=None, parentExtension=None): self.lineEdit = parent self.label = parentLabel self.extension = parentExtension super().__init__() def validate(self, input: str, pos: int): if not input: self.lineEdit.setStyleSheet(ACCEPTABLE_LINEEDIT_STYLESHEET) self.label.setStyleSheet(ACCEPTABLE_LABEL_STYLESHEET) return QValidator.Acceptable, input, pos # elif not exists(input): # self.lineEdit.setStyleSheet(INVALID_STYLESHEET) # return QValidator.Invalid, input, pos elif isfile(input) and input.lower().endswith(self.extension): self.lineEdit.setStyleSheet(ACCEPTABLE_LINEEDIT_STYLESHEET) self.label.setStyleSheet(ACCEPTABLE_LABEL_STYLESHEET) return QValidator.Intermediate, input, pos elif isdir(input): self.lineEdit.setStyleSheet(INTERMEDIATE_LINEEDIT_STYLESHEET) self.label.setStyleSheet(INTERMEDIATE_LABEL_STYLESHEET) return QValidator.Acceptable, input, pos elif input: self.lineEdit.setStyleSheet(INTERMEDIATE_LINEEDIT_STYLESHEET) self.label.setStyleSheet(INTERMEDIATE_LABEL_STYLESHEET) return QValidator.Intermediate, input, pos else: self.lineEdit.setStyleSheet(INVALID_LINEEDIT_STYLESHEET) self.label.setStyleSheet(INVALID_LABEL_STYLESHEET) return QValidator.Invalid, input, pos
import { Field, FieldValue, FieldValues, useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import categories from "./categories"; const schema = z.object({ name: z.string().min(3, { message: "Require at least 3 characters" }), amount: z .number({ invalid_type_error: "amount needs to be specified" }) .min(1, { message: "require at least 1 item" }), category: z.enum(categories, { errorMap: () => ({ message: "Category is required" }), }), }); type FormData = z.infer<typeof schema>; interface Props { onSubmit: (data: FormData) => void; } const Form = ({ onSubmit }: Props) => { const { register, handleSubmit, reset, formState: { errors }, } = useForm<FormData>({ resolver: zodResolver(schema) }); return ( <form onSubmit={handleSubmit((data) => { onSubmit(data); reset(); })} > <div className="mb-3"> <label htmlFor="name" className="form-label"> Name </label> <input {...register("name")} id="name" type="text" className="form-control" /> {errors.name && <p className="text-danger">{errors.name.message}</p>} </div> <div className="mb-3"> <label htmlFor="amount" className="form-label"> Amount </label> <input {...register("amount", { valueAsNumber: true })} id="amount" type="number" className="form-control" /> {errors.amount && ( <p className="text-danger">{errors.amount.message}</p> )} </div> <div className="mb-3"> <label htmlFor="category" className="form-label"> Category </label> <select {...register("category")} id="category" className="form-control" > <option value=""></option> {categories.map((category) => ( <option key={category} value={category}> {category} </option> ))} </select> {errors.category && ( <p className="text-danger">{errors.category.message}</p> )} </div> <button className="btn btn-primary" type="submit"> Add to list </button> </form> ); }; export default Form;
% This demo script reproduces the analysis reported in the user guidebook % Junpeng Lao, 2015 March, University of Fribourg %-------------------------------------------------------------------------- % Copyright (C) iMap Team 2015 %% load data file p = userpath; addpath(genpath([ p(1:end-1) '/Apps/iMAP'])); clear all cd('./Data_sample_DEMO/') datafile = 'data_subset.txt'; % data structure % column 1 : subject % column 2 : TRIAL % column 3 : xfix % column 4 : yfix % column 5 : FIX_START % column 6 : FIX_END % column 7 : fixdur % column 8 : Spotlight % column 9 : Rating % column 10: IMAGE % column 11: Position % column 12: EYE_USED filetxt = fopen(datafile); data = textscan(filetxt,'%s%n%n%n%n%n%n%s%n%s%s%s%s'); subject = (data{1}); TRIAL = (data{2}); xfix = (data{3}); yfix = (data{4}); FIX_START = (data{5}); FIX_END = (data{6}); fixdur = (data{7}); Spotlight = (data{8}); Rating = (data{9}); stimli = (data{10}); Position = (data{11}); %% experiment parameters dist = 83; yScreen = 30; xScreen = 37; ySize = 1024; xSize = 1280; % rescale scale = 1/5; [ySize2, xSize2] = size(imresize(ones(ySize,xSize),scale,'nearest')); % create Gaussian for smoothing smoothingpic = 20; [x, y] = meshgrid(-floor(xSize/2)+.5:floor(xSize/2)-.5,... -floor(ySize/2)+.5:floor(ySize/2)-.5); gaussienne = exp(- (x .^2 / smoothingpic ^2) - (y .^2 / smoothingpic ^2)); gaussienne = (gaussienne - min(gaussienne(:))) ... / (max(gaussienne(:)) - min(gaussienne(:))); % f_fil = fft2(gaussienne); subjlist = unique(subject); Ns = length(subjlist);% number of subject Nc = 3;%number of condition (Natural viewing, 100, 300) Nsti = length(unique(stimli));% number of image %% prepare fixation matrix SLname = unique(Spotlight); Nc1 = length(SLname); PSname = unique(Position); Nc2 = length(PSname); Nitem = Nc1*Nc2*Ns; FixMap = zeros(Nitem, ySize2, xSize2); RawMap = zeros(Nitem, ySize2, xSize2); indx = zeros(Nitem, 1); ii = 0; for is = 1:Ns disp(is) % read individual data indSbj = strcmp(subject, subjlist{is}); seyex = xfix(indSbj); seyey = yfix(indSbj); sfixs = FIX_START(indSbj); sfixd = fixdur(indSbj); strial = TRIAL(indSbj); scondi = Spotlight(indSbj); srate = Rating(indSbj); simag = stimli(indSbj); spost = Position(indSbj); tbl = dataset(seyex,seyey,sfixs,sfixd,strial,scondi,srate,simag,spost); % figure;plot(seyex,ySize-seyey,'.r');axis([0 xSize 0 ySize]) %% convolution with Gaussian kernel for ic1 = 1:Nc1 for ic2 = 1:Nc2 %% ii = ii+1; selected = strcmp(scondi, SLname(ic1)) & strcmp(spost, PSname(ic2)); if sum(selected) ~= 0 trialid = unique(strial(selected)); isfixmap = zeros(size(trialid,1), ySize2, xSize2); israwmap = isfixmap; stDur = zeros(size(trialid,1), 1); stRate = stDur; for it = 1:size(trialid,1) % fixation matrix selected2 = find(strial == trialid(it)); seyext = seyex(selected2); seyeyt = seyey(selected2); intv = sfixd(selected2); rawmap = zeros(ySize, xSize); coordX = round(seyeyt);%switch matrix coordinate here coordY = round(seyext); indx1=coordX>0 & coordY>0 & coordX<ySize & coordY<xSize; if isempty(indx1) indx(ii) = 1; else rawmap = full(sparse(coordX(indx1), coordY(indx1), intv(indx1), ySize, xSize)); % f_mat = fft2(rawmap); % 2D fourrier transform on the points matrix % filtered_mat = f_mat .* f_fil; % % smoothpic = real(fftshift(ifft2(filtered_mat))); smoothpic = conv2(rawmap, gaussienne,'same'); isfixmap(it,:,:) = imresize(smoothpic, scale, 'nearest'); israwmap(it,:,:) = imresize(rawmap, scale, 'nearest'); stDur (it) = sum(intv(indx1)); stRate(it) = srate(selected2(1)); end end Subject{ii,1} = subjlist{is}; spotlight(ii,1) = SLname(ic1); position(ii,1) = PSname(ic2); rating(ii,1) = nanmean(stRate); fixDur(ii,1) = nanmean(stDur); FixMap(ii,:,:) = nanmean(isfixmap,1); RawMap(ii,:,:) = nanmean(israwmap,1); else indx(ii) = 1; end end end end %% matrix for inputing into imapLMM PredictorM = dataset(Subject,spotlight,position,rating,fixDur); indx2 = isnan(FixMap(:,1,1)); FixMap (logical(indx+indx2),:,:) = []; RawMap (logical(indx+indx2),:,:) = []; PredictorM(logical(indx+indx2),:) = []; Mask = squeeze(nanmean(FixMap))>(min(fixdur)/2); PredictorM.Subject = nominal(PredictorM.Subject); PredictorM.spotlight = nominal(PredictorM.spotlight); PredictorM.position = nominal(PredictorM.position); %% mean fixation map figure('NumberTitle','off','Name','Mean fixation bias'); Spotlightsize = unique(PredictorM.spotlight); Position = unique(PredictorM.position); ord = [1 3 5 2 4 6]; io = 0; for isp = 1:3 for ipp = 1:2 indxtmp = PredictorM.spotlight == Spotlightsize(isp) ... & PredictorM.position == Position(ipp); TempMap = squeeze(nanmean(FixMap(indxtmp,:,:), 1)); subplot(2,3,(ipp-1)*3+isp); imagesc(TempMap); axis off,axis equal; title(char([Position(ipp) Spotlightsize(isp)])); io = io+1; end end % figure;imagesc(Mask) % title('mask') % axis off,axis equal CondiVec = PredictorM.position .* PredictorM.spotlight; SbjVec = PredictorM.Subject; [RDM, stRDM] = rdmfixmap(FixMap, Mask, CondiVec, SbjVec); %% Linear Mixed Modeling with imapLMM tic opt.singlepredi = 1; [LMMmap,lmexample] = imapLMM(FixMap,PredictorM,Mask,opt, ... 'PixelIntensity ~ spotlight + position + spotlight:position + (fixDur|Subject)', ... 'DummyVarCoding','effect','FitMethod','REML'); toc %% LMMmap structure % imapLMM will output a structure called LMMmap with all the information % from the linear mixed model fitting: % LMMmap = % % runopt: [1x1 struct] % VariableInfo: [6x4 dataset] % Variables: [118x6 dataset] % FitMethod: 'REML' % Formula: [1x1 classreg.regr.LinearMixedFormula] % modelX: [118x6 double] % FitOptions: {'DummyVarCoding' 'effect' 'Fitmethod' 'REML'} % modelDFE: 112 % CoefficientNames: {1x6 cell} % Anova: [1x1 struct] % SinglePred: [1x1 struct] % RandomEffects: [1x1 struct] % CoefficientCovariance: [4-D double] % MSE: [256x320 double] % SSE: [256x320 double] % SST: [256x320 double] % SSR: [256x320 double] % Rsquared: [2x256x320 double] % ModelCriterion: [4x256x320 double] % Coefficients: [4-D double] %% show result %% plot model fitting close all opt1.type = 'model'; % perform contrast [StatMapm] = imapLMMcontrast(LMMmap,opt1); % output figure; imapLMMdisplay(StatMapm,0,'front.jpg'); %% plot fixed effec(anova result) % close all opt = struct;% clear structure opt.type = 'fixed'; opt.alpha = 0.05; % perform contrast [StatMap] = imapLMMcontrast(LMMmap,opt); mccopt = struct; mccopt.methods = 'bootstrap'; mccopt.nboot = 1000; mccopt.bootopt = 1; mccopt.tfce = 0; % perform multiple comparison correction [StatMap_c] = imapLMMmcc(StatMap,LMMmap,mccopt,FixMap); % output figure; imapLMMdisplay(StatMap_c,1,'front.jpg',[]) %% post-hoc [PostHoc] = imapLMMposthoc(StatMap_c,RawMap,LMMmap,'mean'); %% Linear Contrast % close all opt = struct;% clear structure opt.type = 'predictor beta'; opt.alpha = 2e-07; opt.c{1} = [1 0 0 0 -1 0]; opt.name = {'back 100-NV'}; % perform contrast [StatMap] = imapLMMcontrast(LMMmap,opt); mccopt = struct; mccopt.methods = 'bootstrap'; mccopt.nboot = 1000; mccopt.bootopt = 1; mccopt.tfce = 0; % multiple comparison correction [StatMap_c] = imapLMMmcc(StatMap,LMMmap,mccopt,FixMap); % output figure; imapLMMdisplay(StatMap_c,0,'back.jpg') %% One-tail t-test % close all opt = struct;% clear structure opt.type = 'predictor beta'; opt.alpha = 0.05; opt.onetail = '>'; opt.h = mean(mean(FixMap(:,Mask))); opt.c{1} = [0 1 0 0 0 0]; opt.name = {'front 100'}; % perform contrast [StatMap] = imapLMMcontrast(LMMmap,opt); mccopt = struct; mccopt.methods = 'bootstrap'; mccopt.nboot = 1000; mccopt.bootopt = 1; mccopt.tfce = 0; % multiple comparison correction [StatMap_c] = imapLMMmcc(StatMap,LMMmap,mccopt,FixMap); % output figure; imapLMMdisplay(StatMap_c,0,'front.jpg')
import { RESUME_DATA } from "@/data/resume-data"; import { GlobeIcon, MailIcon } from "lucide-react"; import { Button } from "./ui/button"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import Link from "next/link"; export default function Hero() { return ( <div className="block md:flex print:flex items-center justify-between"> <div className="flex-1 space-y-8"> <h1 className="text-medium font-medium -mb-4">{RESUME_DATA.name}</h1> <p className="text-medium text-muted-foreground dark:text-font-dark-mode max-w-md"> {RESUME_DATA.about} </p> <p className="max-w-md items-center"> <Link className="inline-flex gap-x-1.5 font-light text-muted-foreground dark:text-font-dark-mode align-baseline leading-none hover:underline" href={RESUME_DATA.locationLink} aria-label="Location" target="_blank" > <GlobeIcon className="size-4" /> {RESUME_DATA.location} </Link> </p> <div className="flex gap-x-1 pt-1 print:hidden"> {RESUME_DATA.contact.email ? ( <Button variant="outline" size="sm" asChild > <Link href={`mailto:${RESUME_DATA.contact.email}`} aria-label="Email"> <MailIcon className="size-4" /> </Link> </Button> ) : null} {RESUME_DATA.contact.social.map((social) => ( <Button key={social.name} variant="outline" size="sm" asChild > <Link href={social.url} aria-label={social.name}> <social.icon className="size-4" /> </Link> </Button> ))} <Button variant="outline" size={"sm"}> <a href="/pdf/cv_2024_eng.pdf" aria-label="Resume">Download Resume </a> </Button> </div> <div className="hidden flex-col gap-x-1 print:flex"> {RESUME_DATA.contact.email ? ( <Link href={`mailto:${RESUME_DATA.contact.email}`} aria-label="Print_email"> <span className="underline">{RESUME_DATA.contact.email}</span> </Link> ) : null} {RESUME_DATA.contact.tel ? ( <Link href={`tel:${RESUME_DATA.contact.tel}`} aria-label="Print_telp"> <span className="underline">{RESUME_DATA.contact.tel}</span> </Link> ) : null} </div> </div> <Avatar className="size-28 mx-auto max-sm:w-1/2 max-sm:h-1/2 max-sm:mt-6"> <AvatarImage alt={RESUME_DATA.name} src={RESUME_DATA.avatarUrl} rel="dns-prefetch" /> <AvatarFallback>{RESUME_DATA.initials}</AvatarFallback> </Avatar> </div> ); }
import { Star, StarOutline, GitHub } from "@mui/icons-material"; import React, { useEffect, useState } from "react"; import "./Explore.css"; import image from "../../assets/image.jpg"; import avatar from "../../assets/avatars/4.png"; import Modal from "../Modal/Modal"; import ProjectInfo from "./ProjectInfo"; export default function ExplorePage() { const [project, setproject] = useState([]); const [overview, setOverview] = useState(false); const [id, setId] = useState(); useEffect(() => { fetch("/api/project").then((response) => { response.json().then((e) => { setproject(e); console.log(e); }); }); }, []); function handleClick(id) { setId(id); setOverview(true); } return ( <div className="explore-section-hero"> <h3>Explore Projects</h3> <hr /> <div className="projects-grid"> {project.map((p) => ( <div className="data-list"> <div className="star--project"> <StarOutline /> </div> <div className="image-data"> <img onClick={() => handleClick(p.projectId)} src={image} alt="" /> </div> <div className="info"> <GitHub /> <p className="name">{p.projectTitle}</p> <div className="members"> {p.members.map((member) => ( <span> <img src={avatar} alt="" /> <p className="hide">{member.name}</p> </span> ))} </div> </div> </div> ))} </div> {/* <Modal open={overview} close={() => setOverview(false)}> <ProjectInfo projectId={id} /> </Modal> */} </div> ); }
<section> <header> <h2 class="text-lg font-medium text-gray-900"> {{ __('Update Password') }} </h2> <p class="mt-1 text-sm text-gray-600"> {{ __('Ensure your account is using a long, random password to stay secure.') }} </p> </header> <form method="post" action="{{ route('password.update') }}" class="mt-6 space-y-6 w-50 mx-auto"> @csrf @method('put') <div> <x-input-label for="update_password_current_password" :value="__('Current Password')" /> <x-text-input id="update_password_current_password" name="current_password" type="password" class="form-control mt-1 mx-auto block w-50" autocomplete="current-password" /> <x-input-error :messages="$errors->updatePassword->get('current_password')" class="mt-2" /> </div> <div> <x-input-label for="update_password_password" :value="__('New Password')" /> <x-text-input id="update_password_password" name="password" type="password" class="form-control mt-1 mx-auto block w-50" autocomplete="new-password" /> <x-input-error :messages="$errors->updatePassword->get('password')" class="mt-2" /> </div> <div> <x-input-label for="update_password_password_confirmation" :value="__('Confirm Password')" /> <x-text-input id="update_password_password_confirmation" name="password_confirmation" type="password" class="form-control mt-1 mx-auto block w-50" autocomplete="new-password" /> <x-input-error :messages="$errors->updatePassword->get('password_confirmation')" class="mt-2 text-danger" /> </div> <div class="flex items-center gap-4"> <x-primary-button class="btn btn-primary my-2">{{ __('Save') }}</x-primary-button> @if (session('status') === 'password-updated') <p x-data="{ show: true }" x-show="show" x-transition x-init="setTimeout(() => show = false, 2000)" class="text-sm text-gray-600" >{{ __('Saved.') }}</p> @endif </div> </form> </section>
# Gestione delle Priorità nelle Interruzioni Ci potrebbe essere la necessità di stabilire un grado di importanza per gli interrupt che si manifestano, in modo da far gestire alla CPU quello più prioritario. Ogni sistema che si rispetti ha gli interrupt prioritarizzati. Generalmente gli interrupt di I/O hanno meno priorità degli interrupt di eccezione. E anche tra gli interrupt I/O c'è una distinzione, le periferiche più veloci hanno priorità più alta (ovviamente è necessario gestirle per prima visto che più tempo passa più lavoro perdono). ## Registro Status Inanzitutto nel MIPS abbiamo lo Status register, esso stabilisce chi può interrompere il processore. Il primo filtro che attua questo registro è attraverso il bit di enable, se è 0 il processore non verrà mai interrotto. Inoltre una sezione di questo registro è utilizzata per definire quali interrupt precisi possono verificarsi, 8 bit (dal 15 all' 8). Se voglio rendere triggerabile un interrupt mi basterà mettere i bit corrispondenti a 1. ## Registro Cause Quando si verifica un'eccezione o un interrupt è nel registro Cause che troviamo tutte le informazioni necessarie per gestirla. Ad esempio nei bit da 6 a 2 troviamo l'exception code e dal 15 all'8 i pending interrupts. ## Gestione dell'interrupt + Fare l'AND logico tra la interrupt mask del registro status e i pending interrupt del registro cause. In questo modo avremmo tutti gli interrupt che si sono manifestati e che sono abilitati ad essere gestiti. + Selezionare l'interrupt con la priorità più alta, generalmente quello più a sinistra. + Salvare la maschera degli interrupt + Cambiare la maschera degli interrupt disabilitando gli interrupt con priorità minore o uguale a quella che si sta gestendo + Salvare lo stato del processore + Settare Interrupt Enable dello Status Register a 1 + Chiamare la routine di gestione dell'interrupt + Prima di restorare lo stato, settare il bit di interrupt enable del registro Cause a 0. Per fare il restore della maschera di interrupt.
2806. Account Balance After Rounded Purchase Easy Topics Companies Initially, you have a bank account balance of 100 dollars. You are given an integer purchaseAmount representing the amount you will spend on a purchase in dollars. At the store where you will make the purchase, the purchase amount is rounded to the nearest multiple of 10. In other words, you pay a non-negative amount, roundedAmount, such that roundedAmount is a multiple of 10 and abs(roundedAmount - purchaseAmount) is minimized. If there is more than one nearest multiple of 10, the largest multiple is chosen. Return an integer denoting your account balance after making a purchase worth purchaseAmount dollars from the store. Note: 0 is considered to be a multiple of 10 in this problem. Example 1: Input: purchaseAmount = 9 Output: 90 Explanation: In this example, the nearest multiple of 10 to 9 is 10. Hence, your account balance becomes 100 - 10 = 90. Example 2: Input: purchaseAmount = 15 Output: 80 Explanation: In this example, there are two nearest multiples of 10 to 15: 10 and 20. So, the larger multiple, 20, is chosen. Hence, your account balance becomes 100 - 20 = 80. Constraints: 0 <= purchaseAmount <= 100
using System; using System.IO; using System.Text; using System.Collections.Generic; namespace NAudio.Midi { /// <summary> /// Represents a MIDI sysex message /// </summary> public class SysexEvent : MidiEvent { private byte[] data; //private int length; /// <summary> /// Reads a sysex message from a MIDI stream /// </summary> /// <param name="br">Stream of MIDI data</param> /// <returns>a new sysex message</returns> public static SysexEvent ReadSysexEvent(BinaryReader br) { SysexEvent se = new SysexEvent(); //se.length = ReadVarInt(br); //se.data = br.ReadBytes(se.length); List<byte> sysexData = new List<byte>(); bool loop = true; while(loop) { byte b = br.ReadByte(); if(b == 0xF7) { loop = false; } else { sysexData.Add(b); } } se.data = sysexData.ToArray(); return se; } /// <summary> /// Creates a deep clone of this MIDI event. /// </summary> public override MidiEvent Clone() { object retData = null; if (data != null) retData = data.Clone(); return new SysexEvent { data = (byte[])retData }; } /// <summary> /// Describes this sysex message /// </summary> /// <returns>A string describing the sysex message</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (byte b in data) { sb.AppendFormat("{0:X2} ", b); } return String.Format("{0} Sysex: {1} bytes\r\n{2}",this.AbsoluteTime,data.Length,sb.ToString()); } /// <summary> /// Calls base class export first, then exports the data /// specific to this event /// <seealso cref="MidiEvent.Export">MidiEvent.Export</seealso> /// </summary> public override void Export(ref long absoluteTime, BinaryWriter writer) { base.Export(ref absoluteTime, writer); //WriteVarInt(writer,length); //writer.Write(data, 0, data.Length); writer.Write(data, 0, data.Length); writer.Write((byte)0xF7); } } }
<!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 rel="stylesheet" href="{{ url_for('static',filename='css/style.css') }}" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> <title>Register</title> </head> <body> <div class="container-md"> <nav class="navbar navbar-expand-lg navbar-light bg-warning"> <div class="container"> <a class="navbar-brand" href="/"> <img class="music" src="{{ url_for('static', filename='img/music.jpg') }}"> <span class="navbar-brand mb-0 h1">AlbumStash</span> </a> <div> <a href="/user_login" class="link-primary">Already Registered? Log In</a> </div> </div> </nav> <main> <div class="intro"> <h2 class="text-primary">Create Account</h2> </div> </main> <section class="vh-80 gradient-custom text-dark"> <div class="container py-5 h-80"> <div class="row justify-content-center align-items-center h-100"> <div class="col-12 col-lg-9 col-xl-7"> <div class="card shadow-2-strong card-registration" style="border-radius: 15px"> <div class="card-body p-4 p-md-5"> <h3 class="mb-4 pb-2 pb-md-0 mb-md-5">New Account</h3> {% with messages = get_flashed_messages() %} <!-- declare a variable called messages --> {% if messages %} <!-- check if there are any messages --> {% for message in messages %} <!-- loop through the messages --> <p class="2.5rem">{{message}}</p> <!-- display each message in a paragraph tag --> {% endfor %} <!-- --> {% endif %} <!-- --> {% endwith %} <form action="/register" method="POST"> <!-- **********************First and Last Name--> <div class="row"> <div class="col-md-6 mb-4"> <div class="form-outline"> <input type="text" name="first_name" class="form-control form-control-lg" /> <label class="form-label" for="first_name">First Name</label> </div> </div> <div class="col-md-6 mb-4"> <div class="form-outline"> <input type="text" name="last_name" class="form-control form-control-lg" /> <label class="form-label" for="last_name">Last Name</label> </div> </div> </div> <!-- ********************Email--> <div class="row"> <div class="col-md-6 mb-4 pb-2"> <div class="form-outline"> <input type="email" name="email" class="form-control form-control-lg" /> <label class="form-label" for="email">Email</label> </div> </div> </div> <!-- **********************Password--> <div class="row"> <div class="col-md-6 mb-4 d-flex align-items-center"> <div class="form-outline datepicker w-100"> <input type="password" class="form-control form-control-lg" name="password" /> <label for="password" class="form-label">Password</label> </div> </div> <div class="col-md-6 mb-4 d-flex align-items-center"> <div class="form-outline datepicker w-100"> <input type="password" class="form-control form-control-lg" name="password_c" /> <label for="password_c" class="form-label">Confirm Password</label> </div> </div> </div> <!-- **********************Submit--> <div class="mt-4 pt-2"> <input class="btn btn-success btn-lg" type="submit" value="Register" /> </div> </form> </div> </div> </div> </div> </div> </section> </div> </body> </html>
import Image from "next/image"; import React from "react"; import { useDispatch } from "react-redux"; import { decreaseQTY, increaseQTY, removeFromCart } from "../slices/cartSlice"; import { MinusIcon, PlusIcon } from "@heroicons/react/24/outline"; import Link from "next/link"; const CartItem = ({ item }: any) => { const dispatch = useDispatch(); const id = item.id; const removeItemToCart = () => { dispatch(removeFromCart(id)); }; const handleIncreaseQuantity = () => { dispatch(increaseQTY(id)); }; const handleDecreaseQuantity = () => { dispatch(decreaseQTY(id)); }; return ( <div className="flex border-b pb-5"> <div className="w-[30%]"> <Image src={item.image} alt={item.name} width={200} height={200} className="object-contain" /> </div> <div className="mx-5 sm:flex justify-between space-y-5 gap-y-5 place-content-start w-[70%]"> <div className="space-y-5"> <Link href={`/product/${item.id}`} className="text-black"> {item.name} </Link> <div className="flex space-x-5 items-center"> <div className="flex space-x-2 items-center"> <button className="button w-8 h-8 p-1" onClick={handleDecreaseQuantity} > <MinusIcon /> </button> <p className="text-black">{item.qty}</p> <button className="button w-8 h-8 p-1 " onClick={handleIncreaseQuantity} > <PlusIcon /> </button> </div> <button onClick={() => removeItemToCart()} className="mt-auto button w-max h-max" > Remove </button> </div> </div> <p className="text-black"> ₹ <span>{item.price * 80}</span> </p> </div> <div className="flex justify-center"></div> </div> ); }; export default CartItem;
package Zadanie3; import java.util.Random; public class Zadanie3 { private static final int ARRAY_SIZE = 100000000; private static final int THREAD_COUNT = 2; private static int[] generateArray(int size) { Random rand = new Random(); int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = rand.nextInt(10); } return arr; } private static long sum(int[] arr) { long result = 0; for (int i = 0; i < arr.length; i++) { result += arr[i]; } return result; } private static class SumThread implements Runnable { private int[] arr; private int startIndex; private int endIndex; private long result; public SumThread(int[] arr, int startIndex, int endIndex) { this.arr = arr; this.startIndex = startIndex; this.endIndex = endIndex; this.result = 0; } public long getResult() { return result; } @Override public void run() { for (int i = startIndex; i < endIndex; i++) { result += arr[i]; } } } public static void main(String[] args) throws InterruptedException { int[] arr1 = generateArray(ARRAY_SIZE); // Single-threaded sum long startTime = System.currentTimeMillis(); long result1 = sum(arr1); long elapsedTime1 = System.currentTimeMillis() - startTime; System.out.println("Elapsed time with one thread: " + elapsedTime1 + "ms"); System.out.println("Result with one thread: " + result1); // Multi-threaded sum startTime = System.currentTimeMillis(); SumThread[] sumThreads = new SumThread[THREAD_COUNT]; Thread[] threads = new Thread[THREAD_COUNT]; int chunkSize = ARRAY_SIZE / THREAD_COUNT; for (int i = 0; i < THREAD_COUNT; i++) { int startIndex = i * chunkSize; int endIndex = (i == THREAD_COUNT - 1) ? ARRAY_SIZE : startIndex + chunkSize; sumThreads[i] = new SumThread(arr1, startIndex, endIndex); threads[i] = new Thread(sumThreads[i]); threads[i].start(); } long result2 = 0; for (int i = 0; i < THREAD_COUNT; i++) { threads[i].join(); result2 += sumThreads[i].getResult(); } long elapsedTime2 = System.currentTimeMillis() - startTime; System.out.println("Elapsed time with " + THREAD_COUNT + " threads: " + elapsedTime2 + "ms"); System.out.println("Result with " + THREAD_COUNT + " threads: " + result2); // Multi-threaded sum using available processors int availableProcessors = Runtime.getRuntime().availableProcessors(); startTime = System.currentTimeMillis(); sumThreads = new SumThread[availableProcessors]; threads = new Thread[availableProcessors]; chunkSize = ARRAY_SIZE / availableProcessors; for (int i = 0; i < availableProcessors; i++) { int startIndex = i * chunkSize; int endIndex = (i == availableProcessors - 1) ? ARRAY_SIZE : startIndex + chunkSize; sumThreads[i] = new SumThread(arr1, startIndex, endIndex); threads[i] = new Thread(sumThreads[i]); threads[i].start(); } long result3 = 0; for (int i = 0; i < availableProcessors; i++) { threads[i].join(); result3 += sumThreads[i].getResult(); } long elapsedTime3 = System.currentTimeMillis() - startTime; System.out.println("Elapsed time with " + availableProcessors + " threads: " + elapsedTime3 + "ms"); System.out.println("Result with " + availableProcessors + " threads: " + result3); } }
const Koa = require("koa"); const Router = require("koa-router"); const koaStatic = require("koa-static"); const VueServerRenderer = require('vue-server-renderer'); const fs = require('fs') const path = require('path') const router = new Router(); const app = new Koa(); const serverBundle = fs.readFileSync(path.resolve(__dirname, 'dist/server.bundle.js'), 'utf8') const template = fs.readFileSync(path.resolve(__dirname, 'dist/server.html'), 'utf8') const render = VueServerRenderer.createBundleRenderer(serverBundle, { template }) router.get('/(.*)', async (ctx) => { ctx.set("Content-Type", "text/html"); ctx.body = await new Promise((resolve, reject) => { render.renderToString({url: ctx.url}, (err, html) => { if (err && err.code === 404) resolve("not found"); resolve(html) }) }); }) app.use(koaStatic(path.resolve(__dirname, 'dist'))) app.use(router.routes()); app.listen(3000);
package com.enigma.tokopedia.Entity; import com.fasterxml.jackson.annotation.JsonBackReference; import jakarta.persistence.*; import lombok.*; @Entity @Table(name = "m_product_price") @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Builder(toBuilder = true) public class ProductPrice { @Id @GeneratedValue(strategy = GenerationType.UUID) private String id; @Column(name = "stock" ,columnDefinition = "int check (stock > 0)" ,length = 100) private Integer stock; @Column(name = "is_active") private Boolean isActive; @Column(name = "price" ,columnDefinition = "bigint check (price > 8)" ,length = 100) private Long price; @ManyToOne @JoinColumn(name = "store_id") private Store store; // Harus di buat JsonBackRefrence supaya tidak stack overflow(saling memanggil) @ManyToOne @JsonBackReference @JoinColumn(name = "product_id") private Product product; @Override public String toString() { return "ProductPrice{" + "id='" + id + '\'' + ", stock=" + stock + ", isActive=" + isActive + ", price=" + price + ", store=" + store + ", product=" + product + '}'; } }
##Libraries library(arules) library(arulesViz) library(dplyr) library(twitteR) library(ROAuth) library(ggplot2) library(tokenizers) library(stopwords) library(rtweet) library(plyr) library(stringr) library(rtweet) library(networkD3) ##Setting Twitter authorization keys consumer_key<-'klef9rsiaHCjKuU0RJUKTPsY9' consumer_secret<- 'yZyTEAm70kPYsFo1X2xmQR1wc87Eavapnfhp9rp8jIMIUMgxzh' access_token<- '1409604349538492419-nEOthOigmEiE5lGUjOkHj7JWTkPOrG' access_secret<- 'lmUKRmRb0VT09LIZr4mlUptx7vGAyPLtGHYvxgGzVPYJy' ##Accessing the twitter api directly twitter_token <- create_token( consumer_key = consumer_key, consumer_secret = consumer_secret, access_token = access_token, access_secret = access_secret) ##Setting a masterile to store all searches and cluster1 file to ##store allstar, legend, superstar searches Masterfile<-'Twitter_csv_files/all_searches.csv' Cluster1<-'Twitter_csv_files/allstar_legend_superstar.csv' ##Performing a series of searches based on key terms and ##Writing the outuput of each to a distinct file Search<-rtweet::search_tweets('nba allstar',n=1000, lang = 'en', include_rts = FALSE,retryonratelimit = TRUE) Search_DF<-as.data.frame(Search) filename<-'Twitter_csv_files/nba_allstar.csv' MyFile<-file(filename) File1<-file(Cluster1) File2<-file(Masterfile) for (i in 1:nrow(Search_DF)){ ##Tokenizing words and removing unnecessary numbers,punctuation, ans ##stop words Tokens<-tokenizers::tokenize_words(Search_DF$text[i], stopwords=stopwords::stopwords('en'), lowercase=TRUE,strip_punct=TRUE, strip_numeric=TRUE,simplify=TRUE) ##Writing words to csv files cat(unlist(str_squish(Tokens)),'\n',file=filename,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Cluster1,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Masterfile,sep=',',append=TRUE) } close(MyFile) close(File1) close(File2) Search<-rtweet::search_tweets('nba star',n=1000,lang='en',include_rts = FALSE, retryonratelimit = TRUE) filename<-'Twitter_csv_files/nba_star.csv' MyFile<-file(filename) File2<-file(Masterfile) Search_DF<-as.data.frame(Search) for (i in 1:nrow(Search_DF)){ Tokens<-tokenizers::tokenize_words(Search_DF$text[i], stopwords=stopwords::stopwords('en'), lowercase=TRUE,strip_punct=TRUE, strip_numeric=TRUE,simplify=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=filename,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Masterfile,sep=',',append=TRUE) } close(MyFile) close(File2) Search<-rtweet::search_tweets('nba mvp',n=1000,lang='en',include_rts = FALSE, retryonratelimit = TRUE) filename<-'Twitter_csv_files/nba_mvp.csv' MyFile<-file(filename) File2<-file(Masterfile) Search_DF<-as.data.frame(Search) for (i in 1:nrow(Search_DF)){ Tokens<-tokenizers::tokenize_words(Search_DF$text[i], stopwords=stopwords::stopwords('en'), lowercase=TRUE,strip_punct=TRUE, strip_numeric=TRUE,simplify=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=filename,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Masterfile,sep=',',append=TRUE) } close(MyFile) close(File2) Search<-rtweet::search_tweets('nba superstar',n=1000,lang='en', include_rts = FALSE,retryonratelimit = TRUE) filename<-'Twitter_csv_files/nba_superstar.csv' MyFile<-file(filename) File1<-file(Cluster1) File2<-file(Masterfile) Search_DF<-as.data.frame(Search) for (i in 1:nrow(Search_DF)){ Tokens<-tokenizers::tokenize_words(Search_DF$text[i], stopwords=stopwords::stopwords('en'), lowercase=TRUE,strip_punct=TRUE, strip_numeric=TRUE,simplify=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=filename,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Cluster1,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Masterfile,sep=',',append=TRUE) } close(MyFile) close(File1) close(File2) Search<-rtweet::search_tweets('nba legend',n=1000,lang='en',include_rts = FALSE, retryonratelimit = TRUE) filename<-'Twitter_csv_files/nba_legend.csv' MyFile<-file(filename) Search_DF<-as.data.frame(Search) File1<-file(Cluster1) File2<-file(Masterfile) for (i in 1:nrow(Search_DF)){ Tokens<-tokenizers::tokenize_words(Search_DF$text[i], stopwords=stopwords::stopwords('en'), lowercase=TRUE,strip_punct=TRUE, strip_numeric=TRUE,simplify=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=filename,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Cluster1,sep=',',append=TRUE) cat(unlist(str_squish(Tokens)),'\n',file=Masterfile,sep=',',append=TRUE) } close(MyFile) close(File1) close(File2) ##Cleaning the CSV files Allstar_legend_superstar<-read.csv('Twitter_csv_files/allstar_legend_superstar.csv',header=FALSE) All_searches<-read.csv('Twitter_csv_files/all_searches.csv',header=FALSE) Allstar<-read.csv('Twitter_csv_files/nba_allstar.csv',header=FALSE) Legend<-read.csv('Twitter_csv_files/nba_legend.csv',header=FALSE) MVP<-read.csv('Twitter_csv_files/nba_mvp.csv',header=FALSE) star<-read.csv('Twitter_csv_files/nba_star.csv',header=FALSE) superstar<-read.csv('Twitter_csv_files/nba_star.csv',header=FALSE) #Storing all the files in a list so they can be looped through DataList<-list(Allstar_legend_superstar,All_searches, Allstar,Legend,MVP,star,superstar) ##Empty list to store cleaned Data NewDataList<-list() ##Removing specific words that are unnecessary and show up often for (i in 1:length(DataList)){ DF<-as.data.frame(DataList[[i]]) ##Setting empty dataframes No_numbers<-NULL Short_words<-NULL Long_words<-NULL ##Replacing 4 unnecessary words DF[DF=='t.co']<-'' DF[DF=='rt']<-'' DF[DF=='http']<-'' DF[DF=='https']<-'' ##Looping through each column for (a in 1:ncol(DF)){ ##lists to be filled with logicals numbers<-c() numbers<-c(numbers,grepl("[[:digit:]]",DF[[a]])) ##removing digits shortwords<-c() shortwords<-c(shortwords,grepl("[A-z]{4,}",DF[[a]]))##for short words longwords<-c() longwords<-c(longwords,grepl("[A-z]{12,}",DF[[a]]))##for long words ##Appending lists to create dataframes full of logicals No_numbers<-cbind(No_numbers,numbers) Short_words<-cbind(Short_words,shortwords) Long_words<-cbind(Long_words,longwords) } ##Replacing 'appropriate'TRUE' entries with blanks DF[No_numbers]<-'' DF[!Short_words]<-'' DF[Long_words]<-'' NewDataList[[i]]<-DF } ##Reassingning names to the clean DataFrames Allstar_legend_superstar<-NewDataList[[1]] All_searches<-NewDataList[[2]] Allstar<-NewDataList[[3]] Legend<-NewDataList[[4]] MVP<-NewDataList[[5]] star<-NewDataList[[6]] superstar<-NewDataList[[7]] ##Writing to csv files write.csv(Allstar_legend_superstar,'Twitter_csv_files/allstar_legend_superstar_clean.csv',row.names = FALSE) write.csv(All_searches,'Twitter_csv_files/all_searches_clean.csv',row.names = FALSE) write.csv(Allstar,'Twitter_csv_files/nba_allstar_clean.csv',row.names = FALSE) write.csv(Legend,'Twitter_csv_files/nba_legend_clean.csv',row.names = FALSE) write.csv(MVP,'Twitter_csv_files/nba_mvp_clean.csv',row.names = FALSE) write.csv(star,'Twitter_csv_files/nba_star_clean.csv',row.names = FALSE) write.csv(superstar,'Twitter_csv_files/nba_superstar_clean.csv',row.names = FALSE)
#include <iostream> #include <vector> using namespace std; vector<bool> che(int n) { // 1부터 n까지 사용할거라 n+1 크기의 true로 초기화 한 벡터 vector<bool> isPrime(n + 1, true); // 0과 1은 일단 소수가 아니다. isPrime[0] = isPrime[1] = false; for (int p = 2; p * p <= n; p++) { if (isPrime[p]) { for (int i = p * p; i <= n; i += p) { isPrime[i] = false; } } } return isPrime; } int main() { ios::sync_with_stdio(0); cin.tie(0); int N; cin >> N; vector<bool> result; result = che(1000); int count = 0; while (N--) { int n; cin >> n; if(result[n]) { count++; } } cout << count; return 0; }
import 'package:flutter/material.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:notes/services/notes_database.dart'; import 'package:notes/model/notes.dart'; import 'package:notes/widgets/note_list_widget.dart'; import 'note_edit_page.dart'; import 'note_detail_page.dart'; import '../widgets/note_card_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; class NotesPage extends StatefulWidget { @override _NotesPageState createState() => _NotesPageState(); } class _NotesPageState extends State<NotesPage> { List<Note> notes; List<Note> importantNotes; bool isLoading = false; bool isGrid = true; // TextEditingController _controller = new TextEditingController(); @override void initState() { super.initState(); refreshNotes(); } @override void dispose() { NotesDatabase.instance.close(); super.dispose(); } Future refreshNotes() async { setState(() => isLoading = true); SharedPreferences prefs = await SharedPreferences.getInstance(); isGrid = (prefs.getBool('grid') ?? true); this.notes = await NotesDatabase.instance.readAllNotes(); this.importantNotes = await NotesDatabase.instance.readAllFavorite(); setState(() => isLoading = false); } void onGridIconTap() async { setState(() { isGrid ? isGrid = false : isGrid = true; }); SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setBool('grid', isGrid); refreshNotes(); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text( 'Notes', style: TextStyle(fontSize: 24, color: Colors.white), ), actions: [ IconButton( icon: Icon( isGrid ? Icons.list : Icons.grid_view, color: Colors.white, ), onPressed: onGridIconTap, ), SizedBox(width: 12) ], ), body: SafeArea( child: Center( child: isLoading ? CircularProgressIndicator() : notes.isEmpty ? Text( 'No Notes', style: TextStyle(fontSize: 24, color: Colors.white), ) : buildNotes(), ), ), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () async { await Navigator.of(context).push( MaterialPageRoute(builder: (context) => AddEditNotePage()), ); refreshNotes(); }, ), ); Widget buildNotes() => isGrid ? StaggeredGridView.countBuilder( padding: EdgeInsets.all(8), itemCount: notes.length, staggeredTileBuilder: (index) => StaggeredTile.fit(2), crossAxisCount: 4, mainAxisSpacing: 4, crossAxisSpacing: 4, itemBuilder: (context, index) { final note = notes[index]; return GestureDetector( onTap: () async { await Navigator.of(context).push(MaterialPageRoute( builder: (context) => NoteDetailPage(noteId: note.id), )); refreshNotes(); }, child: NoteCardWidget(note: note, index: index), ); }, ) : ListView.builder( itemCount: notes.length, itemBuilder: (context, index) { final note = notes[index]; return GestureDetector( onTap: () async { await Navigator.of(context).push( MaterialPageRoute( builder: (context) => NoteDetailPage(noteId: note.id), ), ); refreshNotes(); }, child: NoteListCardWidget(note: note, index: index), ); }, ); }
<template> <main> <Link href="/2">Link to other page</Link> <Link href="/" :only="['lazy_prop']">Partial reload (only lazy prop)</Link> <button @click="counter++"> Reactive button (clicked {{ counter }} times) </button> <div class="props"> <h1>Props</h1> <span> Message: {{ message }} </span> <span> Flashed messages: {{ $page.props.messages }} </span> <span> Lazy prop: {{ $page.props.lazy_prop }} </span> </div> </main> </template> <script setup> import { Link } from "@inertiajs/vue3"; import { ref } from "vue"; defineProps({ message: String, }); const counter = ref(0); </script> <script> import MainLayout from '@/layouts/Main.vue'; export default { layout: MainLayout, }; </script> <style scoped> main { min-height: 100dvh; width: 100%; display: flex; gap: 1rem; place-items: center; place-content: center; flex-direction: column; >* { max-width: 50%; } .props { display: flex; flex-direction: column; gap: 1rem; h1 { font-weight: bold; width: 100%; text-align: center; } } } </style>
package com.example.Final_Project_9team.service; import com.example.Final_Project_9team.dto.InvitationResponseDto; import com.example.Final_Project_9team.dto.ResponseDto; import com.example.Final_Project_9team.dto.user.UserResponseDto; import com.example.Final_Project_9team.entity.Mates; import com.example.Final_Project_9team.entity.Schedule; import com.example.Final_Project_9team.entity.User; import com.example.Final_Project_9team.exception.CustomException; import com.example.Final_Project_9team.exception.ErrorCode; import com.example.Final_Project_9team.repository.MatesRepository; import com.example.Final_Project_9team.repository.ScheduleRepository; import com.example.Final_Project_9team.repository.UserRepository; import com.example.Final_Project_9team.utils.UserUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Slf4j @Service @RequiredArgsConstructor public class MatesService { private final MatesRepository matesRepository; private final UserRepository userRepository; private final ScheduleRepository scheduleRepository; private final UserUtils userUtils; // 유저가 다른 유저를 초대 public ResponseEntity<ResponseDto> inviteUserToSchedule(String userEmail, String invitedUsername, Long scheduleId) { log.info("invitedUser"+invitedUsername); User user = userUtils.getUser(userEmail); User invitedUser = userRepository.findByNickname(invitedUsername).orElseThrow( () -> new CustomException(ErrorCode.USER_NOT_FOUND)); Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow( () -> new CustomException(ErrorCode.SCHEDULE_NOT_FOUND)); // 유저가 일정의 멤버인지 검사 if(!matesRepository.existsByScheduleIdAndUserId(scheduleId,user.getId())) throw new CustomException(ErrorCode.USER_NOT_INCLUDED_SCHEDULE); Optional<Mates> optionalMates = matesRepository.findByScheduleIdAndUserId(scheduleId, invitedUser.getId()); // 이미 메이트가 존재하는 경우(이전에 초대된 적이 있다.) if (optionalMates.isPresent()) { Mates mates = optionalMates.get(); if (mates.getIsDeleted() == true) { // 1. 탈퇴했던 경우 mates.setDeleted(false); matesRepository.save(mates); } else { // 2. 이미 초대한 경우 throw new CustomException(ErrorCode.ALREADY_INVITED_MATES); } } else { Mates mate = Mates.builder() .user(invitedUser) .schedule(schedule) .isDeleted(false) .isAccepted(false) .isHost(false) .build(); matesRepository.save(mate); } return ResponseEntity.ok(ResponseDto.getMessage("초대가 정상적으로 되었습니다.")); } // 메이트에 추가로 초대할 리스트 조회(기존 메이트 제외) public List<UserResponseDto> findInvitationList(String keyword, String userEmail, Long scheduleId) { User user = userUtils.getUser(userEmail); List<User> findByEmail = userRepository.findAllByEmailContainingAndIsDeletedIsFalseAndEmailNot(keyword, userEmail); List<User> findByNickname = userRepository.findAllByNicknameContainingAndIsDeletedIsFalseAndEmailNot(keyword, userEmail); List<User> mergedList = new ArrayList<>(); mergedList.addAll(findByEmail); mergedList.addAll(findByNickname); //추가 // 내가 속한 일정의 멤버들 조회하여 리스트에서 제외하기 List<Mates> matesList = matesRepository.findAllByScheduleIdAndIsAcceptedTrue(scheduleId); for (Mates mates : matesList) { // log.info("mates.getuserid="+mates.getUser().getId()); User matesUser = userRepository.findById(mates.getUser().getId()).orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND)); while (mergedList.contains(matesUser)) { // 닉네임과 이메일이 중복되는 경우 모두 제거 mergedList.remove(matesUser); } } // 중복제거 후 닉네임 기준으로 정렬 List<UserResponseDto> userResponseDtoList = mergedList.stream() .distinct() .sorted(Comparator.comparing(User::getNickname)) .map(UserResponseDto::fromEntity) .collect(Collectors.toList()); // 초대된 이력이 있는 메이트의 dto 정보에 초대 정보 넣기. // List<Mates> invitedMates = matesRepository.findAllByUserIdAndIsAcceptedFalseAndIsDeletedFalse(scheduleId); // for (Mates invitedMate : invitedMates) { // for (UserResponseDto userResponseDto : userResponseDtoList) { // if (invitedMate.getUser().getNickname().equals(userResponseDto.getNickname())) { // userResponseDto.setIsInvited(true); // } // } // } return userResponseDtoList; } // 초대받은 리스트 조회(수락대기중인 리스트) public ResponseEntity<List<InvitationResponseDto>> readInvitations(String userEmail) { User user = userUtils.getUser(userEmail); List<Mates> matesList = matesRepository.findAllByUserIdAndIsAcceptedFalseAndIsDeletedFalse(user.getId()); List<InvitationResponseDto> invitationResponseDtos = new ArrayList<>(); for (Mates mates : matesList) { String time; if (mates.getModifiedAt() == null) { time = mates.getCreatedAt().toString().substring(0, 16).replace("T", " ").replaceAll("-", "."); } else { time = mates.getModifiedAt().toString().substring(0, 16).replace("T", " ").replaceAll("-", "."); } log.info("mates.id="+mates.getId()); log.info("time="+time); InvitationResponseDto invitationResponseDto = InvitationResponseDto.builder() .scheduleHost(mates.getSchedule().getUser().getNickname()) .invitedTime(time) .scheduleTitle(mates.getSchedule().getTitle()) .scheduleId(mates.getSchedule().getId()) .matesId(mates.getId()) .build(); log.info("mates.getId()="+mates.getId()); log.info("mates.getSchedule().getId()="+mates.getSchedule().getId()); invitationResponseDtos.add(invitationResponseDto); } // if(invitationResponseDtos.isEmpty()) // throw new CustomException(ErrorCode.INVITATION_NOT_FOUND); return ResponseEntity.ok(invitationResponseDtos); } // 초대 승낙 시 public ResponseEntity<ResponseDto> acceptInvitation(String userEmail, Long scheduleId, Long matesId) { User invitedUser = userUtils.getUser(userEmail); // User invitedUser = userRepository.findByEmail(userEmail).orElseThrow( // () -> new CustomException(ErrorCode.USER_NOT_FOUND)); Mates mates = matesRepository.findById(matesId).orElseThrow( () -> new CustomException(ErrorCode.MATES_NOT_FOUND)); Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow( () -> new CustomException(ErrorCode.SCHEDULE_NOT_FOUND)); // matesId의 유저정보와 맞는지 확인하기 isMatchedUserAndMates(invitedUser, mates); // 이미 초대를 수락한 경우 isAcceptedMates(mates); // 이미 탈퇴한 경우 isLeftMates(mates); mates.setAccepted(true); matesRepository.save(mates); return ResponseEntity.ok(ResponseDto.getMessage("초대가 정상적으로 수락되었습니다.")); } // 초대 거절 시 public ResponseEntity<ResponseDto> rejectInvitation(String userEmail, Long scheduleId, Long matesId) { log.info("rejectInvitation() 실행"); User invitedUser = userUtils.getUser(userEmail); // User invitedUser = userRepository.findByEmail(userEmail).orElseThrow( // () -> new CustomException(ErrorCode.USER_NOT_FOUND)); Mates mates = matesRepository.findById(matesId).orElseThrow( () -> new CustomException(ErrorCode.MATES_NOT_FOUND)); Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow( () -> new CustomException(ErrorCode.SCHEDULE_NOT_FOUND)); isMatchedUserAndMates(invitedUser, mates); isAcceptedMates(mates); isLeftMates(mates); matesRepository.delete(mates); return ResponseEntity.ok(ResponseDto.getMessage("초대가 정상적으로 거절되었습니다.")); } // 소속된 일정(메이트)에서 나가기(탈퇴) public ResponseEntity<ResponseDto> leaveMates(String userEmail, Long scheduleId, Long matesId) { User user = userUtils.getUser(userEmail); // User user = userRepository.findByEmail(userEmail).orElseThrow( // () -> new CustomException(ErrorCode.USER_NOT_FOUND)); Mates mates = matesRepository.findById(matesId).orElseThrow( () -> new CustomException(ErrorCode.MATES_NOT_FOUND)); Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow( () -> new CustomException(ErrorCode.SCHEDULE_NOT_FOUND)); isMatchedUserAndMates(user, mates); isLeftMates(mates); mates.setDeleted(true); mates.setAccepted(false); matesRepository.save(mates); return ResponseEntity.ok(ResponseDto.getMessage("해당 일정에서 나갔습니다.")); } public void isMatchedUserAndMates(User invitedUser, Mates mates) { if (!mates.getUser().equals(invitedUser)) throw new CustomException(ErrorCode.MATES_NOT_MATCHED_USER); } public void isAcceptedMates(Mates mates) { if (mates.getIsAccepted() == true) throw new CustomException(ErrorCode.ALREADY_ACCEPTED_MATES); } public void isLeftMates(Mates mates) { log.info(mates.getIsDeleted().toString()); if (mates.getIsDeleted() == true) throw new CustomException(ErrorCode.ALREADY_LEFT_MATES); } // 현재 회원이 포함된 메이트 모두 삭제 public void deleteMateAll(User user) { // isDeleted == false인 일정 찾아오기 List<Mates> matesList = matesRepository.findAllByUserIdAndIsDeletedIsFalse(user.getId()); for (Mates mates : matesList) { mates.setDeleted(true); matesRepository.save(mates); } } }
# Music Representing Corpus Virtual (MRCV) At the same time that MRCV is the title of the musical work, it is the name of the code repository that accompanies said musical work. The main purpose of this work is to introduce the non-technical &| non-machine-learning-ai people to AI/ML (artificial intelligence/machine learning [used interchangeably in this case]). We present a number of use cases that is encompassed within the scope/remit of this codebase. As a first-pass, we will describe the use-cases before going in depth in further sections. - **Music Generation** - Done through MIDI (currently, MUSIC-TO-SCORE is still underconstruction) - **Sampler Instrument Procedural Generation (Sound Design)** - Two choices here, the first being the ability to generate 128 different sounds to fill up the sampler instrument. - The second choice is to fill up the sampler instrument by pitch-shifting one sound in order to get 127 different notes. - The sampler instrument generated is a [Decent Sampler Instrument](https://www.decentsamples.com/product/decent-sampler-plugin/). - **Realtime Audio-to-Audio Generation (VST/AU plugin)** - In this case, the user is able to train a REALTIME-CAPABLE (audio rate inferencing) to be used in a plugin. (cf. `waveform-gen-plugin`) - **Neural Wavetable Generation through frequency features** - We generate a wavetable using frequency information. - This is then used as a wavetable/granular synthesiser and pitchshifted to fit 127 notes. - **Procedural Score Generation** - This is done through the `./genere/` part of the codebase. Feel free to read the [paper](https://tinyurl.com/3adsxybz) for further formal clarification on any of the topics within. Also feel free to watch the workshop/mini-showcase at on [Youtube](https://www.youtube.com/watch?v=VjuqjSp21Nw) ## Table of Contents * **[Starting from Absolute Zero](#starting-from-absolute-zero)** * **[Mac OS](#mac-os)** * **[Post VSCode Install](#post-vscode-install)** * **[Verify Pyenv Install](#verify-pyenv-install)** * **[After Installing Pyenv](#after-installing-pyenv)** * **[Post Python Install](#post-python-install)** * **[Time to Set Up VSCODE](#time-to-set-up-vscode)** * **[Dependencies](#dependencies)** * **[Building the Audio Plugin](#building-the-audio-plugin-to-run-json-neural-network-files)** * **[Using a Virtual Environment](#using-a-virtual-environment)** ## Starting from Absolute Zero ### Mac OS This project is made under the full understanding that people will not have had any programming experience whatsoever. This section of the `README.md` will serve as a guide for setting everything up. We recommend using [VSCode](https://code.visualstudio.com/) as the code executor. ##### Post VSCode Install After installing VSCode, download [Homebrew](https://brew.sh/) in order to manage certain packages you will need to maintain some neatness in your computer. We recommend pyenv and graphviz. First, install Homebrew, open the Terminal application (under Applications >> Terminal) and type these commands: ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` After installing Homebrew, you will be able to install packages from your Terminal application, for example: ```bash brew install <package-name> ``` Next, install pyenv and graphviz (for intel Macs, there seems to be a problem which can be easily fixed by installing xz) ```bash brew install pyenv brew install graphviz brew install xz (if needed) ``` After this, you will need to type a few simple commands into the terminal. Type this command to see which shell you are running. Usually it will be bash or zsh. ```bash echo $SHELL ``` Follow the steps below for the necessary shell (bash or zsh). ##### bash (taken from the pyenv github README.md) For **bash**, type these commands: ```bash echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc echo 'eval "$(pyenv init -)"' >> ~/.bashrc ``` Then, if you have `~/.profile`, `~/.bash_profile` or `~/.bash_login`, add the commands there as well. If you have none of these, add them to `~/.profile`. to add to `~/.profile`: ```bash echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.profile echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.profile echo 'eval "$(pyenv init -)"' >> ~/.profile ``` to add to `~/.bash_profile`: ```bash echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile echo 'eval "$(pyenv init -)"' >> ~/.bash_profile ``` Restart your terminal after typing these commands. ##### zsh (taken from the pyenv github README.md) For **zsh**, type these commands: ```zsh echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc echo 'eval "$(pyenv init -)"' >> ~/.zshrc ``` Restart your terminal after typing these commands. ##### Verify pyenv install Type this line to check if you have done everything right: ```bash pyenv --version ``` If correct, it should output something like: ```bash pyenv 2.3.7 ``` Your numbers may vary a little but in general it should not say pyenv can not be found or something along those lines. ##### After installing pyenv Next, we will want to set up the proper python versions for your system. Python versions can be installed with pyenv using this command. This command installs python version 3.10.10, which is the most stable version for this library. However, we have tested it on 3.10.8 and it works as well. ```bash pyenv install 3.10.10 ``` If you run into an error such as this: ```bash python-build: definition not found See all available versions with `pyenv install --list`. ... ``` Try to install versions by reducing the last number (first attempt from 3.10.10 to 3.10.9) until it allows you to install: ```bash pyenv install 3.10.9 ... pyenv install 3.10.8 ... (you get the idea) ``` ##### Post-python install Change our global version of python to the one we installed (the following command assumes 3.10.10, but yours might differ, it could be 3.10.8): ```bash pyenv global 3.10.10 ``` Restart your terminal application. After restarting, you should be able to type in `python -V` and see that your current version is 3.10.10. ##### Time to set up VSCode - Once you have installed the correct pyenv version, open VSCode and install the relevant python extensions by searching "Python" under the extensions (4 square logo with one square slightly lifted off). - After clicking the small "Install" button next to it, it should install a couple of other extensions for you like Pylance etc. Wait for that to complete. Once that is complete, it should ask you to do a few things, ignore that and click on "Mark Done" for everything. - When that is done, open a new file File >> New File ..., and call it something like test.py. Open that file. - Once that file is open, there should be a small button on the bottom right corner of the screen that says something along the lines of "Select Python Interpreter", or "3.10.10 64-bit ...". If it says something like "... ('3.10.10':pyenv)", you are in luck and will not need the next step however, if it says anything else, click on it and choose the option that has pyenv in the name. - If there are no options with pyenv in the name, select the option to type in the path, and type in `~/.pyenv/versions/3.10.10/bin/python`, replacing 3.10.10 with whichever version you installed. ## Dependencies Because this project is not currently in production yet (version no. < 0.0.0), the some dependencies will need to be installed separately from the `requirements.txt` file. First we install `requirements.txt`: ```bash pip install --upgrade pip pip install -r requirements.txt ``` After this, depending on which OS: ##### Windows/Intel Macs/Linux ```bash pip install tensorflow ``` ##### M1 Macs ```bash pip install tensorflow-macos tensorflow-metal ``` ## Building the Audio Plugin to run `.json` neural network files ### Configuring ```bash cd waveform-gen-plugin ``` ```bash cmake -Bbuild -DCMAKE_BUILD_TYPE=Release ``` <!-- cmake -Bbuild-xcode -GXcode -D"CMAKE_OSX_ARCHITECTURES=arm64;x86_64" --> ### Building Plugin <!-- ### If you want VST3, change AU to VST3 --> ##### AU ```bash cmake --build build --config Release --target waveform_gen_plugin_AU --parallel ``` ##### VST3 ```bash cmake --build build --config Release --target waveform_gen_plugin_VST3 --parallel ``` The plugin will be located in build/plugin/waveform_gen_plugin_artefacts. ### Building CLI Tool ```bash cmake --build build --config Release --target waveform_gen_cli --parallel ``` Then you can run the CLI tool like: ```bash ./build/cli/Debug/waveform_gen_cli --model-file="/Users/jatin/ChowDSP/Research/RTNeural/RTNeural/models/dense.json" --out-file=test.wav --samples=100000 ``` ## Using a virtual environment You may choose to run the library from a virtual environment. Should you wish to do so, this is an example using virtualenv `pip install virtualenv`. ```bash virtualenv --python=python3.10.10 env ``` ```bash pip install --upgrade pip ``` ```bash source env/bin/activate ``` ```bash pip install -r requirements.txt ``` After doing what you need to do: ```bash deactivate ``` # LICENSE BSD 3-Clause License Copyright (c) 2023, Christopher Johann Clarke Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Copyright (C) 2021 Greenbone Networks GmbH # Some text descriptions might be excerpted from (a) referenced # source(s), and are Copyright (C) by the respective right holder(s). # # SPDX-License-Identifier: GPL-2.0-or-later # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. if(description) { script_oid("1.3.6.1.4.1.25623.1.1.2.2021.1904"); script_cve_id("CVE-2017-18216", "CVE-2020-0465", "CVE-2020-0466", "CVE-2021-20261", "CVE-2021-27363", "CVE-2021-27364", "CVE-2021-27365", "CVE-2021-3178"); script_tag(name:"creation_date", value:"2021-05-19 06:22:15 +0000 (Wed, 19 May 2021)"); script_version("2022-04-07T14:39:39+0000"); script_tag(name:"last_modification", value:"2022-04-07 14:39:39 +0000 (Thu, 07 Apr 2022)"); script_tag(name:"cvss_base", value:"7.2"); script_tag(name:"cvss_base_vector", value:"AV:L/AC:L/Au:N/C:C/I:C/A:C"); script_tag(name:"severity_vector", value:"CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H"); script_tag(name:"severity_origin", value:"NVD"); script_tag(name:"severity_date", value:"2021-04-09 09:15:00 +0000 (Fri, 09 Apr 2021)"); script_name("Huawei EulerOS: Security Advisory for kernel (EulerOS-SA-2021-1904)"); script_category(ACT_GATHER_INFO); script_copyright("Copyright (C) 2021 Greenbone Networks GmbH"); script_family("Huawei EulerOS Local Security Checks"); script_dependencies("gb_huawei_euleros_consolidation.nasl"); script_mandatory_keys("ssh/login/euleros", "ssh/login/rpms", re:"ssh/login/release=EULEROS\-2\.0SP5"); script_xref(name:"Advisory-ID", value:"EulerOS-SA-2021-1904"); script_xref(name:"URL", value:"https://developer.huaweicloud.com/ict/en/site-euleros/euleros/security-advisories/EulerOS-SA-2021-1904"); script_tag(name:"summary", value:"The remote host is missing an update for the Huawei EulerOS 'kernel' package(s) announced via the EulerOS-SA-2021-1904 advisory."); script_tag(name:"vuldetect", value:"Checks if a vulnerable package version is present on the target host."); script_tag(name:"insight", value:"In various methods of hid-multitouch.c, there is a possible out of bounds write due to a missing bounds check. This could lead to local escalation of privilege with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android kernelAndroid ID: A-162844689References: Upstream kernel(CVE-2020-0465) fs/nfsd/nfs3xdr.c in the Linux kernel through 5.10.8, when there is an NFS export of a subdirectory of a filesystem, allows remote attackers to traverse to other parts of the filesystem via READDIRPLUS. NOTE: some parties argue that such a subdirectory export is not intended to prevent this attack, see also the exports(5) no_subtree_check default behavior.(CVE-2021-3178) In do_epoll_ctl and ep_loop_check_proc of eventpoll.c, there is a possible use after free due to a logic error. This could lead to local escalation of privilege with no additional execution privileges needed. User interaction is not needed for exploitation.Product: AndroidVersions: Android kernelAndroid ID: A-147802478References: Upstream kernel(CVE-2020-0466) In fs/ocfs2/cluster/nodemanager.c in the Linux kernel before 4.15, local users can cause a denial of service (NULL pointer dereference and BUG) because a required mutex is not used.(CVE-2017-18216) An issue was discovered in the Linux kernel through 5.11.3. A kernel pointer leak can be used to determine the address of the iscsi_transport structure. When an iSCSI transport is registered with the iSCSI subsystem, the transport's handle is available to unprivileged users via the sysfs file system, at /sys/class/iscsi_transport/$TRANSPORT_NAME/handle. When read, the show_transport_handle function (in drivers/scsi/scsi_transport_iscsi.c) is called, which leaks the handle. This handle is actually the pointer to an iscsi_transport struct in the kernel module's global variables.(CVE-2021-27363) An issue was discovered in the Linux kernel through 5.11.3. drivers/scsi/scsi_transport_iscsi.c is adversely affected by the ability of an unprivileged user to craft Netlink messages.(CVE-2021-27364) An issue was discovered in the Linux kernel through 5.11.3. Certain iSCSI data structures do not have appropriate length constraints or checks, and can exceed the PAGE_SIZE value. An unprivileged user can send a Netlink message that is associated with iSCSI, and has a length up to the maximum length of a Netlink message.(CVE-2021-27365) A race condition was found in the Linux kernels implementation of the floppy disk drive controller driver software. The impact of this issue is lessened by the fact that the default permissions on the floppy device (/dev/fd0) are restricted to root. If the permissions on the device have changed the impact changes greatly. In the default configuration root (or equivalent) permissions are required to attack this flaw.(CVE-2021-20261)"); script_tag(name:"affected", value:"'kernel' package(s) on Huawei EulerOS V2.0SP5."); script_tag(name:"solution", value:"Please install the updated package(s)."); script_tag(name:"solution_type", value:"VendorFix"); script_tag(name:"qod_type", value:"package"); exit(0); } include("revisions-lib.inc"); include("pkg-lib-rpm.inc"); release = rpm_get_ssh_release(); if(!release) exit(0); res = ""; report = ""; if(release == "EULEROS-2.0SP5") { if(!isnull(res = isrpmvuln(pkg:"kernel", rpm:"kernel~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(!isnull(res = isrpmvuln(pkg:"kernel-devel", rpm:"kernel-devel~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(!isnull(res = isrpmvuln(pkg:"kernel-headers", rpm:"kernel-headers~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(!isnull(res = isrpmvuln(pkg:"kernel-tools", rpm:"kernel-tools~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(!isnull(res = isrpmvuln(pkg:"kernel-tools-libs", rpm:"kernel-tools-libs~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(!isnull(res = isrpmvuln(pkg:"perf", rpm:"perf~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(!isnull(res = isrpmvuln(pkg:"python-perf", rpm:"python-perf~3.10.0~862.14.1.5.h547.eulerosv2r7", rls:"EULEROS-2.0SP5"))) { report += res; } if(report != "") { security_message(data:report); } else if(__pkg_match) { exit(99); } exit(0); } exit(0);
import { View, Text, TouchableOpacity, Image } from "react-native"; import BouncyCheckbox from "react-native-bouncy-checkbox"; import trash from "../../assets/trash.png"; import { styles } from "./styles"; type TaskProps = { text: string; isComplete: boolean; handleCompleteTask: () => void; handleRemoveTask: () => void; }; export function Task({ text, isComplete, handleCompleteTask, handleRemoveTask, }: TaskProps) { const style = styles({ isComplete }); return ( <View style={style.container}> <BouncyCheckbox size={25} fillColor="#5E60CE" textComponent={ <Text style={style.text} numberOfLines={2} ellipsizeMode="tail"> {text} </Text> } innerIconStyle={{ borderWidth: 2, borderColor: isComplete ? "#5E60CE" : "#4EA8DE", }} onPress={handleCompleteTask} /> <TouchableOpacity style={style.button} onPress={handleRemoveTask}> <Image source={trash} /> </TouchableOpacity> </View> ); }
import { existsSync, promises as fs } from 'node:fs' import { join } from 'node:path' import { dir } from './meta.mjs' const sizes = [ 'sm', 'lg', 'xl', ] const colors = map( [ 'red', 'orange', 'blue', ], [ '200', '400', ], ) const variants = [ 'hover', 'first', 'active', 'dark', 'dark:hover:focus:first:active', ...sizes, ...map(sizes, ['dark:hover:focus:first:active'], ':'), ] const names = [ ...map( ['p', 'pt', 'm', 'mx', 'top'], [ ...Array.from({ length: 10 }, (_, i) => i.toString()), '[1px]', '[3vh]', '[3.555em]', ], ), ...map( ['text', 'bg', 'border'], [ ...colors, ...map(colors, ['10', '20'], '/'), '[#525343]', '[#124453]', '[#942]', ], ), ...map( ['text', 'rounded'], [ ...sizes, ], ), ...map([ 'grid-cols', ], [ '1', '2', '[1fr_3em]', '[20px_min-content_1fr]', ]), ] function map(a, b, join = '-') { const classes = [] for (const n of a) { for (const t of b) classes.push(n + join + t) } return classes } export const classes = [ ...names, ...map(variants, names, ':'), ] export async function writeMock() { const content = () => `document.getElementById('app').innerHTML = \`${chunk(shuffle(classes)).map(c => `<div class="${c.join(' ')}" />`).join('\n')}\`` if (!existsSync(join(dir, 'source'))) await fs.mkdir(join(dir, 'source')) await fs.writeFile(join(dir, 'source/gen1.js'), content(), 'utf-8') await fs.writeFile(join(dir, 'source/gen2.js'), content(), 'utf-8') await fs.writeFile(join(dir, 'source/gen3.js'), content(), 'utf-8') await fs.writeFile(join(dir, 'source/gen.js'), 'import "./gen1";import "./gen2";import "./gen3";', 'utf-8') return classes } export function shuffle(array) { array = Array.from(array) let curr = array.length let idx // While there remain elements to shuffle... while (curr !== 0) { // Pick a remaining element... idx = Math.floor(Math.random() * curr) curr--; // And swap it with the current element. [array[curr], array[idx]] = [array[idx], array[curr]] } return array } export function chunk(array, size = 15) { const chunks = [] for (let i = 0; i < array.length; i += size) chunks.push(array.slice(i, i + size)) return chunks }
import React, { useState } from 'react'; const IterationSample = () => { //const names = ['눈사람','얼음','눈','바람']; //const nameList = names.map((name,index) => <li key={index}>{name}</li>) //return <ul>{nameList}</ul>; const [names, setNames] = useState([ { id : 1, text: '눈사람'}, { id : 2, text: '얼음' }, { id : 3, text: '눈' }, { id : 4, text: '바람'} ]); const [inputText, setInputText] = useState(''); const [nextId, setNextId] = useState(5); const onChange = e => setInputText(e.target.value); const onClick = () => { const nextNames = names.concat({ id: nextId, text:inputText }); setNextId(nextId + 1); setNames(nextNames); setInputText(''); } const onRemove = id => { const nextNames = names.filter(name => name.id !== id); setNames(nextNames); } const namesList = names.map(name => ( <li key={name.id} onDoubleClick={() => onRemove(name.id)}> {name.text} </li> )); return ( <> <input value={inputText} onChange={onChange} /> <button onClick={onClick}>추가</button> <ul>{namesList}</ul> </> ); }; export default IterationSample;
import { points } from './points.ts' type Props = { tenbou :number honba :number oya: string rival: string tsumo: boolean ron: boolean ron_direct: boolean } type HData = { method: string tensa : number aka: string rate: number ex1: string ex2: string ex3: string ex4: string } // 入力された条件から点数表を生成する export const Hyou : React.FC<Props> = ({tenbou, honba, oya, rival, tsumo, ron, ron_direct}: Props) => { const hheader = [ '和了方法', '相手とつく点差', '和了点数', '確率', '門前ツモ,平和ロン, 鳴き(30符)', '平和ツモ(20符)', '門前ロン、テンパネ(40符)', '七対子(25符)' ] const hheader2 = [ '和了方法', '相手とつく点差', '和了点数', '確率', '門前ツモ, 鳴き(30符)', '平和ツモ(20符)', 'テンパネ(40符)', '七対子(25符)' ] // スタイル const st_rate = (rate :number) => { return { backgroundColor: 'aliceblue', } } const st_method = (method :string) => { if (method === 'ロン'){ return { backgroundColor: 'aliceblue', } } else if (method === 'ロン(直撃)'){ return { backgroundColor: 'tomato' } } else if (method === 'ツモ'){ return { backgroundColor: 'khaki' } } } // スタイル(翻数によってhsl指定による色分けを行う。) const st_agari = (agari :string) => { const hon = Number(agari[0]) return { backgroundColor: `hsl(${hon * 30}, 70%, 80%)` } } let hdata: HData[] = [] // ロンの場合の点数表 if (ron_direct) { hdata.push(...points.map(p => { let tensa = 0 if (oya === '親') { tensa = p.parent_ron * 2 + tenbou * 1000 + honba * 600 } else{ tensa = p.child_ron * 2 + tenbou * 1000 + honba * 600 } return { method: 'ロン(直撃)', tensa: tensa, aka: oya === '親' ? `${p.parent_ron}` : `${p.child_ron}`, rate: p.rate * 100, ex1: p.ex1, ex2: p.ex2, ex3: p.ex3, ex4: p.ex4 } })) } if (ron) { hdata.push(...points.map(p => { let tensa = 0 if (oya === '親') { tensa = p.parent_ron + tenbou * 1000 + honba * 600 } else{ tensa = p.child_ron + tenbou * 1000 + honba * 600 } return { method: 'ロン', tensa: tensa, aka: oya === '親' ? `${p.parent_ron}` : `${p.child_ron}`, rate: p.rate * 100, ex1: p.ex1, ex2: p.ex2, ex3: p.ex3, ex4: p.ex4 } })) } if (tsumo) { // ツモの場合の点数表 hdata.push(...points.map(p => { let tensa = 0 let aka = '' if (oya === '親') { tensa = p.parent_tsumo * 4 + tenbou * 1000 + honba * 400 aka = `${p.parent_tsumo * 3}(${p.parent_tsumo}オール)` } else{ if (rival==='子'){ tensa = p.child_tsumo_from_child * 3 + p.child_tsumo_from_parent + tenbou * 1000 + honba * 400 } else{ tensa = p.child_tsumo_from_child * 2 + p.child_tsumo_from_parent * 2 + tenbou * 1000 + honba * 400 } aka = `${p.child_tsumo_from_child * 2 + p.child_tsumo_from_parent + honba * 300 + tenbou * 1000}(${p.child_tsumo_from_child + honba * 100}-${p.child_tsumo_from_parent + honba * 100})` } return { method: 'ツモ', tensa: tensa, aka: aka, rate: p.rate * 100, ex1: p.ex1, ex2: p.ex2, ex3: p.ex3, ex4: p.ex4 } })) } // 点数順にソートを行う hdata.sort((a, b) => { if( a.tensa < b.tensa ) return -1; if( a.tensa > b.tensa ) return 1; return 0; }) // 絞り込みによって取得する情報を変化させる return <> { hdata.length > 0 ? <div className="table-responsive"> <table className="table table-sm mt-3 text-center"> <thead> <tr className="table-secondary"> {hheader.map((h, i) => <th key={i}>{h}</th>)} </tr> </thead> <tbody> {hdata.map((h, i) => { return ( <tr key={h.tensa + i}> <td style={st_method(h.method)}>{h.method}</td> <td className="text-danger">{h.tensa}</td> <td>{h.aka}</td> <td style={st_rate(h.rate)}>{h.rate} %</td> <td style={st_agari(h.ex2)} className={h.ex2 === "" ? "table-secondary" : ""}>{h.ex2}</td> <td style={st_agari(h.ex1)} className={h.ex1 === "" ? "table-secondary" : ""}>{h.ex1}</td> <td style={st_agari(h.ex3)} className={h.ex3 === "" ? "table-secondary" : ""}>{h.ex3}</td> <td style={st_agari(h.ex4)} className={h.ex4 === "" ? "table-secondary" : ""}>{h.ex4}</td> </tr> ); })} </tbody> </table> </div> : <p>データが無いにゃ…(絞り込みを選択してにゃ)</p>} </> }
package com.ericsson.swot.messaging.bus; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; import java.util.logging.Logger; import com.ericsson.swot.messaging.common.Constants; public class Config { private Logger log = Logger.getLogger(this.getClass().getSimpleName()); /** * toggle this boolean is Oauth needs to be enabled/disabled */ public static boolean OAUTH_ENABLED = false; public static String CONFIG_FILE_PATH = "config"; private String OAUTH_SERVER_VALIDATION_URI = "http://localhost:8080/oauth" + Constants.VALIDATE_PATH;; private String TOPIC_SCHEMA_XML_FILE_PATH = "./swot_messaging_schema/topicSchema.xml"; private String PROPERTY_SCHEMA_XML_FILE_PATH = "./swot_messaging_schema/propertySchema.xml"; private boolean PUSH_RECORD_KEEPING = false; private Properties configFile; private static Config config = null; private static Config getConfig() { if (config == null) config = new Config(); return config; } private Config() { configFile = new java.util.Properties(); try { //InputStream is = new FileInputStream(CONFIG_FILE_PATH); // InputStream is = this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE_PATH); URL resourceUrl = this.getClass().getClassLoader().getResource(CONFIG_FILE_PATH); if (resourceUrl == null) throw new Exception(); log.info("config file found. Loading..."); File resourceFile = new File(resourceUrl.toURI()); InputStream is = new FileInputStream(resourceFile); // if (is == null); // throw new Exception(); configFile.load(is); if (this.configFile.getProperty("oauth_server_validate_uri") != null) { OAUTH_SERVER_VALIDATION_URI = this.configFile.getProperty("oauth_server_validate_uri"); log.info("oauth_server_validate_uri = " + OAUTH_SERVER_VALIDATION_URI); } if (this.configFile.getProperty("topic_schema_file_path") != null) { TOPIC_SCHEMA_XML_FILE_PATH = this.configFile.getProperty("topic_schema_file_path"); log.info("topic_schema_file_path = " + TOPIC_SCHEMA_XML_FILE_PATH); } if (this.configFile.getProperty("property_schema_file_path") != null) { PROPERTY_SCHEMA_XML_FILE_PATH = this.configFile.getProperty("property_schema_file_path"); log.info("property_schema_file_path = " + PROPERTY_SCHEMA_XML_FILE_PATH); } if (this.configFile.getProperty("push_record_keeping") != null) { PUSH_RECORD_KEEPING = Boolean.valueOf(this.configFile.getProperty("push_record_keeping")); log.info("push_record_keeping = " + PUSH_RECORD_KEEPING); } } catch(Exception e) { log.info("config file not found. Loading default property values."); e.printStackTrace(); } } public static String getOauthServerValidateUri() { return Config.getConfig().OAUTH_SERVER_VALIDATION_URI; } public static String getTopicSchemaXmlFilePath() { return Config.getConfig().TOPIC_SCHEMA_XML_FILE_PATH; } public static String getPropertySchemaXmlFilePath() { return Config.getConfig().PROPERTY_SCHEMA_XML_FILE_PATH; } public static boolean getPushRecordKeeping() { return Config.getConfig().PUSH_RECORD_KEEPING; } }
import React from "react"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import WorkProgress from "../sections/WorkProgress"; import Services from "../sections/Services"; import Pictures from "../sections/Pictures"; import Footer from "../sections/Footer"; import Navbar from "../components/Navbar"; import Cover from "../sections/Cover"; import { motion } from "framer-motion"; const Home = () => { return ( <> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.5, ease: "easeOut" }} > <Navbar /> <Cover /> <Services /> <WorkProgress /> <Pictures /> <Footer /> </motion.div> </> ); }; export async function getStaticProps({ locale }) { return { props: { ...(await serverSideTranslations(locale, [ "about", "workprogress", "services", "footer", "navbar", ])), }, }; } export default Home;
// // Write a function in C to find the sum of rows and columns of a Matrix. // // Header Files #include <stdio.h> #include <conio.h> #include <stdlib.h> #define MAX_ROWS 10 #define MAX_COLS 10 // // Functions Declarations (Prototypes) void input2DArray(int (*)[], int, int); void print2DArray(int (*)[], int, int); void printRowsColsSum(int (*)[], int, int); // // Main Function Start int main() { const int ROWS, COLS; printf("\nEnter Order of Matrix-A (Rows x Cols) (MAX %d x %d) => ", MAX_ROWS, MAX_COLS); scanf("%d%d", &ROWS, &COLS); // // Check Invalid Input for Matrix Order if (ROWS < 1 || ROWS > MAX_ROWS || COLS < 1 || COLS > MAX_COLS) { puts("\n!!! Invalid order of Matrix, Plz Enter Appropriate Order...\n"); exit(0); } // // Declare 2-d Array of Entered Order int matrixA[ROWS][COLS], sumOfRows = 0, sumOfCols = 0; // // Input Elements of Matrix-A printf("\n>>>>>> Enter Elements of Matrix-A of Order %d x %d <<<<<<<\n", ROWS, COLS); input2DArray(matrixA, ROWS, COLS); // // Print Matrix-A printf("\n\n>>>>>>>> Matrix-A of %d x %d <<<<<<<<<\n", ROWS, COLS); print2DArray(matrixA, ROWS, COLS); // // Print Sum of Rows and Cols puts("\n>>>>>>>> Sum of Rows and Columns <<<<<<<<<"); printRowsColsSum(matrixA, ROWS, COLS); putch('\n'); getch(); return 0; } // // Main Function End // // Functions Definitions 👇👇 // // Function to Input Elements of 2D Array void input2DArray(int (*arr)[], int rows, int cols) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("\nEnter element[%d][%d] => ", i + 1, j + 1); scanf("%d", &*((int *)arr + i * cols + j)); } } } // // Function to Print 2D Array void print2DArray(int (*arr)[], int rows, int cols) { putch(10); // // Add new line for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) printf("%-4d ", *((int *)arr + i * cols + j)); putch(10); // // Add new line } putch(10); // // Add new line } // // Function to Print Sum of Each Row and Column void printRowsColsSum(int (*mat)[], int rows, int cols) { int sumOfRows, sumOfCols; // // Find Sum of Rows and Cols and Print if (rows == cols) { // // Find Sum of Rows and Cols for (int i = 0; i < rows; i++) { sumOfRows = sumOfCols = 0; for (int j = 0; j < cols; j++) { sumOfRows += *((int *)mat + i * cols + j); sumOfCols += *((int *)mat + j * cols + i); } printf("\nSum of Row-%d => %d", i + 1, sumOfRows); printf("\nSum of Col-%d => %d", i + 1, sumOfCols); } } else { // // Find Sum of Rows for (int i = 0; i < rows; i++) { sumOfRows = 0; for (int j = 0; j < cols; j++) sumOfRows += *((int *)mat + i * cols + j); printf("\nSum of Row-%d => %d", i + 1, sumOfRows); } // // Find Sum of Cols for (int i = 0; i < cols; i++) { sumOfCols = 0; for (int j = 0; j < rows; j++) sumOfCols += *((int *)mat + j * cols + i); printf("\nSum of Col-%d => %d", i + 1, sumOfCols); } } }
import React from "react"; import { Search } from "@mui/icons-material"; import { IconButton,InputBase } from "@mui/material"; import { GridToolbarDensitySelector, GridToolbarContainer, GridToolbarExport, GridToolbarColumnsButton, } from "@mui/x-data-grid"; import FlexBetween from "./FlexBetween"; const DataGridCustomerToolbar = ({ searchText, setSearchText }) => { const handleSearchChange = (event) => { setSearchText(event.target.value); }; return ( <GridToolbarContainer> <FlexBetween width="100%"> <FlexBetween> <GridToolbarColumnsButton /> <GridToolbarDensitySelector /> <GridToolbarExport /> </FlexBetween> <InputBase placeholder="Search..." value={searchText} onChange={handleSearchChange} /> <IconButton> <Search /> </IconButton> </FlexBetween> </GridToolbarContainer> ); }; export default DataGridCustomerToolbar;
package heman.redis; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyStore; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.json.JSONArray; import org.json.JSONObject; public class TestCreateListUsers { public static void main(String[] args) { // Users API URLs String usersApiUrl = "https://172.16.22.21:9443/v1/users"; // Authentication String encodedAuth = "YWRtaW5Acmwub3JnOm5GYmlRbE8="; try { // Setup custom truststore setupCustomTruststore(); // Display all users displayAllUsers(usersApiUrl, encodedAuth); } catch (Exception e) { e.printStackTrace(); } } private static void setupCustomTruststore() throws Exception { // Load your custom truststore String truststoreFile = "/home/coder/hemantruststore.jks"; // Adjust this path String truststorePassword = "heman007"; // Adjust this password KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream inputStream = new FileInputStream(truststoreFile)) { trustStore.load(inputStream, truststorePassword.toCharArray()); } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } private static void displayAllUsers(String apiUrl, String encodedAuth) { try { URL url = new URL(apiUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", "Basic " + encodedAuth); // Get the response int responseCode = connection.getResponseCode(); System.out.println("Display users list " + "Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { StringBuilder usersData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { // Append each line to the usersData StringBuilder usersData.append(line); } // Parse JSON array of users JSONArray usersArray = new JSONArray(usersData.toString()); // Iterate through the users and print required fields for (int i = 0; i < usersArray.length(); i++) { JSONObject user = usersArray.getJSONObject(i); String name = user.getString("name"); String role = user.getString("role"); String email = user.getString("email"); // Print user details in the specified format System.out.println("Name: " + name + ", Role: " + role + ", Email: " + email); } } } else { System.out.println("Failed to fetch users. Response code: " + responseCode); try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } } connection.disconnect(); // Close the connection } catch (IOException e) { e.printStackTrace(); } } }
using DinoTrans.Shared.Contracts; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DinoTrans.Shared.DTOs { public class UserDTO { //new user [Required] public string FirstName { get; set; } = string.Empty; [Required] public string LastName { get; set; } = string.Empty; [Required] [EmailAddress] [DataType(DataType.EmailAddress)] public string Email { get; set; } = string.Empty; [Required] [DataType(DataType.Password)] public string Password { get; set; } = string.Empty; [Required] [DataType(DataType.Password)] [Compare(nameof(Password))] public string ConfirmPassword { get; set; } = string.Empty; [Required] [DataType(DataType.PhoneNumber)] public string PhoneNumber { get; set; } = string.Empty; public string? Address { get; set; } = string.Empty; [Required] public string Role { get; set; } //new company [Required] public string CompanyName { get; set; } = string.Empty; [DataType(DataType.EmailAddress)] [Required] public string CompanyEmail { get; set; } = string.Empty; [Required] public string CompanyPhoneNumber { get; set; } = string.Empty; [Required] public CompanyRoleEnum CompanyRole { get; set; } [Required] public string CompanyAddress { get; set; } = string.Empty; /* //new Location [Required] public string LocationName { get; set; } = string.Empty; */ } }
from typing import Tuple, Union, List, Optional import time import itertools from random import Random from CL.Interface.ModularCL.EvalCache import EvalCache from CL.Interface.ModularCL.ModularCLAlgorithm import ModularCLAlg from CL.Interface.Problem import Problem from CL.Interface.NNEvaluator import NNEvaluator from CL.Interface.NNTrainer import NNTrainer from CL.Interface.ModularCL.Library import Library class HOUDINI(ModularCLAlg): # Since we assume the architecture is given, HOUDINI is equal to exhaustive search def get_name(self): return "HOUDINI" def get_should_limit_evaluations_by_number_of_paths(self): return True def get_new_library(self, device) -> Library: return Library(device) def _get_modules_names_list_of_lists(self, problem: Problem) -> List[List[str]]: """ retrieves the relevant module names from the library and organises them into a list of lists, grouping them by module types. """ modules_types_list = problem.architecture_class.get_module_types() modules_names_list_of_lists = [] for c_module_type in modules_types_list: if c_module_type not in self.lib.items_by_module_type.keys(): # there are not library items of this type. c_module_names_list = [] else: c_module_names_list = [lib_item.name for lib_item in self.lib.items_by_module_type[c_module_type]] modules_names_list_of_lists.append(c_module_names_list) return modules_names_list_of_lists @staticmethod def exh_search_iteration_bottom_up(items_lists, LLT=False): if len(items_lists) == 0: return [tuple()] return_list_tuples = [] c_item_list = items_lists[0] for item in c_item_list: if LLT and item is None: c_tuple = (None,) * len(items_lists) return_list_tuples.append(c_tuple) continue for following_items_tuple in HOUDINI.exh_search_iteration_bottom_up(items_lists[1:], LLT=LLT): c_tuple = (item,) + following_items_tuple return_list_tuples.append(c_tuple) return return_list_tuples def _get_all_module_combinations(self, problem: Problem, random_obj: Random): modules_names_list_of_lists = self._get_modules_names_list_of_lists(problem) for mnl in modules_names_list_of_lists: mnl.append(None) all_module_combinations = self.exh_search_iteration_bottom_up(modules_names_list_of_lists) standalone_prog = (None,) * problem.architecture_class.get_num_modules() all_module_combinations.remove(standalone_prog) all_module_combinations.insert(0, standalone_prog) return all_module_combinations def iterate_programs(self, problem: Problem, trainer: NNTrainer, evaluator: NNEvaluator, eval_cache: Union[None, EvalCache], random_obj: Random, random_init_random_seed): """ yield program_str, loss, acc, exploration_time, newly_trained_modules """ c_suggestion_time_start = time.time() all_module_combinations = self._get_all_module_combinations(problem, random_obj) for p in all_module_combinations: if self._debug_include_suggestion_time: suggestion_time = time.time() - c_suggestion_time_start else: suggestion_time = 0. c_prog_exploration_res = self.explore_program(p, problem, trainer, evaluator, eval_cache, random_init_random_seed) c_prog_exploration_res.exploration_time += suggestion_time yield c_prog_exploration_res c_suggestion_time_start = time.time()
import React from 'react'; import { render, screen } from '@testing-library/react'; import { Brand } from 'src/types/brand'; import DevOverlay from '../index'; describe('The DevOverlay Component', () => { it('renders the dev overlay', () => { render( <DevOverlay variables={[]} hideDevOverlay={jest.fn()} toggleTheme={jest.fn()} toggleTranslation={jest.fn()} activeTheme={Brand.AutoScout24} displayTranslationKeys={false} />, ); expect(screen.getByText('Dev Overlay')).toBeInTheDocument(); }); it('renders the passed variables', () => { render( <DevOverlay variables={[ { name: 'Dummy', value: 'Find me', }, ]} hideDevOverlay={jest.fn()} toggleTheme={jest.fn()} activeTheme={Brand.AutoScout24} toggleTranslation={jest.fn()} displayTranslationKeys={false} />, ); expect(screen.getByText('Dummy')).toBeInTheDocument(); expect(screen.getByText('Find me')).toBeInTheDocument(); }); });