branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>//Progression 1 - create a Manager array and return it
let managerName = "<NAME>";
let managerAge = 78;
let currentTeam = "Manchester FC";
let trophiesWon = 27;
//Write your function here
function createManager(managerName, managerAge, currentTeam, trophiesWon) {
return [managerName, managerAge, currentTeam, trophiesWon];
}
// Don't edit the following code
try {
var manager = createManager(
managerName,
managerAge,
currentTeam,
trophiesWon
);
} catch (e) {
// do nothing - expected error
}
//Progression 2 - create a formation object and return it
var formation = [4, 4, 3];
//write your function here
function createFormation(arr) {
let expectedResult = {};
if (arr.length == 0) {
expectedResult = null;
} else if (arr.length == 2) {
expectedResult = {
defender: arr[0],
midfield: arr[1],
forward: undefined,
};
} else {
expectedResult = {
defender: arr[0],
midfield: arr[1],
forward: arr[2],
};
}
return expectedResult;
}
// Dont edit the following code
try {
var formationObject = createFormation(formation);
} catch (e) {
//do nothing
}
//Progression 3 - Filter players that debuted in ___ year
function filterByDebut(year) {
let expectedResult = players.filter(function (player) {
return player.debut == year;
});
return expectedResult;
}
//Progression 4 - Filter players that play at the position _______
function filterByPosition(position) {
let expectedResult = players.filter(function (player) {
return player.position == position;
});
return expectedResult;
}
//Progression 5 - Filter players that have won ______ award
function filterByAward(awardg) {
let expectedResult = players.filter(function (player) {
for (let i = 0; i < player.awards.length; i++) {
if (player.awards[i].name == awardg) {
return player;
}
}
});
return expectedResult;
}
//Progression 6 - Filter players that won ______ award ____ times
function filterByAwardxTimes(awardg, times) {
let expectedResult = players.filter(function (player) {
let timesDup = times;
for (let i = 0; i < player.awards.length; i++) {
if (player.awards[i].name == awardg) {
timesDup -= 1;
}
}
if (timesDup == 0) {
return player;
}
});
return expectedResult;
}
//Progression 7 - Filter players that won ______ award and belong to ______ country
function filterByAwardxCountry(awardg, count) {
let expectedResult = players.filter(function (player) {
if (player.country == count) {
for (let i = 0; i < player.awards.length; i++) {
if (player.awards[i].name == awardg) {
return player;
}
}
}
});
return expectedResult;
}
//Progression 8 - Filter players that won atleast ______ awards, belong to ______ team and are younger than ____
function filterByNoOfAwardsxTeamxAge(awa, tea, ag) {
let expectedResult = players.filter(function (player) {
if (player.awards.length >= awa && player.team == tea && player.age <= ag) {
return player;
}
});
return expectedResult;
}
//Progression 9 - Sort players in descending order of their age
//Progression 10 - Sort players beloging to _____ team in descending order of awards won
//Challenge 1 - Sort players that have won _______ award _____ times and belong to _______ country in alphabetical order of their names
//Challenge 2 - Sort players that are older than _____ years in alphabetical order
//Sort the awards won by them in reverse chronological order
| d7b3d1a7fdeb9d0cf4f0bd9f31a6f332b4cb85d1 | [
"JavaScript"
] | 1 | JavaScript | Sowji064/lab-prograd-premier-league | 656bc1f31c37aa519552eaf41bfce6dd181927ee | 909fe4759384b2dfa84655d64a9a98f4cfff49f4 |
refs/heads/master | <repo_name>Park-MinSoo/R<file_sep>/Rstudy/treemap_lab.R
#๋ฌธ์ 1
data(GNI2014)
str(GNI2014)
View(GNI2014)
windowsFonts(lett=windowsFont("ํด๋จผ์์ฒด"))
png(filename="treemap.png",height = 400, width=700)
treemap(GNI2014, vSize="population", index=c("continent", "iso3"), title="์ ์ธ๊ณ ์ธ๊ตฌ ์ ๋ณด", fontfamily.title ="lett", fontsize.title =30)
dev.off()
<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-20031A84/4027C589-contents
#1๋ถํฐ 26์ฌ์ด์ ๊ฐ๋ค ์ค์์ 10๊ฐ๋ฅผ ์ถ์ถํ์ฌ v๋ผ๋ ๋ณ์์ ์ ์ฅํํ์
#์ถ์ถ๋ ์ซ์์ ํด๋นํ๋ ์ํ๋ฒณ ๋๋ฌธ์๋ฅผ ์์๊ฐ์ผ๋ก ๋ฒกํฐ๋ฅผ ์์ฑํ๋ ์ฝ๋๋ฅผ ์์ฑํ์์ค.
v <- sample(1:26, 10)
sapply(v,function(d) return(LETTERS[d]))
<file_sep>/jQuery ํ์ต ๋ด์ฉ.md
# [ jQuery ํ์ต ๋ด์ฉ ]
- $(์๋ฐ์คํฌ๋ฆฝํธ)
- $('CSS์ ํ์') ---> $('h1'), $('div>p'), $('#target')
- $('HTMLํ๊ทธ๋ฌธ์์ด') - ์์ฑ --> $('<div>ใ
ใ
ใ
</div>').append('#target')
- $(ํจ์)
- $('CSS์ ํ์', DOM๊ฐ์ฒด)
- attr(), css()
```javascript
attr('HTML์์ฑ๋ช
') ---> getter
attr('HTML์์ฑ๋ช
','HTML์์ฑ๊ฐ')
attr('HTML์์ฑ๋ช
',ํจ์)
attr({'HTML์์ฑ๋ช
':'HTML์์ฑ๊ฐ','HTML์์ฑ๋ช
':'HTML์์ฑ๊ฐ',...}) ---> setter
css('css์์ฑ๋ช
') ---> getter
css('css์์ฑ๋ช
','css์์ฑ๊ฐ')
css('css์์ฑ๋ช
',ํจ์)
css({'css์์ฑ๋ช
':'css์์ฑ๊ฐ','css์์ฑ๋ช
':'css์์ฑ๊ฐ',...}) ---> setter
```
- html(), text()
```javascript
html() ---> innerHTML
text() ---> textContent
html() ---> getter
html('ํ๊ทธ๋ฌธ์์ด') ---> setter
html(ํจ์) ---> setter
```
- avax()
```javascript
jQuery.ajax()
$.ajax(), $.get(), $.post(), $.getJSON
$(....).load() // ์๋ต์ด ํ
์คํธ๋ HTML์ผ๋ ๋ฑ ๋ง๋๋ค.
// default๋ get์ด๋ค.
```
- each()
```javascript
$(...).each(ํจ์)
```
<file_sep>/Rstudy/JavaConnectNews.R
library(rvest)
library(dplyr)
text<- NULL
url<- "http://media.daum.net/ranking/popular/"
text <- read_html(url)
text
# newstitle
nodes <- html_nodes(text,"#mArticle > div.rank_news > ul.list_news2 > li > div.cont_thumb > strong > a.link_txt")
newstitle <- html_text(nodes)
newstitle <- newstitle %>% head(5)
newstitle <- gsub(",","",newstitle)
newstitle
# newspapername
nodes <- html_nodes(text, "span.info_news")
newspapername <- html_text(nodes, trim=TRUE)
newspapername <- newspapername %>% head(5)
newspapername
page <- data.frame(newstitle, newspapername)
<file_sep>/Rstudy/dplyr_lab3.R
str(ggplot2::mpg)
mpg <- as.data.frame(ggplot2::mpg)
#7-1
mpg %>% mutate(sum_t = cty + hwy) -> mpg
#7-2
mpg %>% mutate(avg_t = sum_t/2) -> mpg
#7-3
mpg %>% arrange(desc(avg_t)) %>% head(3)
#7-4
mpg %>%
mutate(sum_t = cty + hwy,
avg_t = sum_t/2) %>%
arrange(desc(avg_t)) %>%
head(3)
#8-1
mpg %>%
group_by(class) %>%
summarise(cty_mean = mean(cty))
#8-2
mpg %>%
group_by(class) %>%
summarise(cty_mean = mean(cty)) %>%
arrange(desc(cty_mean))
#8-3
mpg %>%
group_by(manufacturer) %>%
summarise(hwy_mean = mean(hwy,na.rm = T)) %>%
arrange(desc(hwy_mean)) %>%
head(3)
#8-4
mpg %>%
group_by(manufacturer) %>%
filter(class == 'compact') %>%
count(class) %>%
arrange(desc(n))
#9
fuel <- data.frame(fl = c("c", "d", "e", "p", "r"),
price_fl = c(2.35, 2.38, 2.11, 2.76, 2.22),
stringsAsFactors = F)
fuel
#9-1
mpg <- full_join(mpg, fuel, by = "fl")
#9-2
mpg %>% select(model, fl, price_fl) %>%
head(5)
#10-1
str(ggplot2::midwest)
midwest <- as.data.frame(ggplot2::midwest)
View(midwest)
midwest %>% mutate(percent_m = (poptotal - popadults)*100 / poptotal) -> midwest
#10-2
midwest %>%
group_by(county) %>%
arrange(desc(percent_m)) %>%
select(percent_m) %>%
head(5)
#10-3
midwest %>%
mutate(grade = ifelse(percent_m >= 40, "large",
ifelse(percent_m >= 30, "middle", "small")
)) %>%
group_by(grade) %>%
select(grade, county) %>%
count(grade)
#10-4
midwest %>%
mutate(percent_a = popasian*100 / poptotal) %>%
arrange(percent_a) %>%
select(state, county, percent_a) %>%
head(10)
#11
mpg <- as.data.frame(ggplot2::mpg)
mpg[c(65, 124, 131, 153, 212), "hwy"] <- NA
#11-1
table(is.na(mpg$drv))
table(is.na(mpg$hwy))
#11-2
mpg %>%
filter(!is.na(hwy)) %>%
group_by(drv) %>%
summarize(hwy_mean = mean(hwy))
#12
mpg <- as.data.frame(ggplot2::mpg)
mpg[c(10, 14, 58, 93), "drv"] <- "k"
mpg[c(29, 43, 129, 203), "cty"] <- c(3, 4, 39, 42)
#12-1
table(mpg$drv)
mpg$drv <- ifelse(mpg$drv %in% c('k'), NA, mpg$drv)
table(mpg$drv)
#12-2
boxplot(mpg$cty)$stats
mpg$cty <- ifelse(mpg$cty < 9 | mpg$cty > 26, NA, mpg$cty)
boxplot(mpg$cty)
#12-3
mpg %>%
filter(!is.na(drv)) %>%
group_by(drv) %>%
summarise(cty_mean = mean(cty,na.rm = T))
<file_sep>/R ํ์ต๋ด์ฉ.md
# [ R ํ์ต๋ด์ฉ ]
R ์ค์น URL : www.r-project.org
R ์คํ๋์ค ์ค์น URL : www.rstudio.com
## R
- ์์ ํ ์ดํฐํ๋ฆฌํฐ ์ธ์ด์ด๋ค.
- ํ๋ซํผ์ ์ํฅ์ ๋ฐ์ง ์์ง๋ง ์๋๊ฐ ์ข ๋๋ฆฌ๋ค.
- Java ์ฒ๋ผ API๋ฅผ Pacakge ๋ผ๊ณ ๋ถ๋ฅธ๋ค.
- R_GUI ๋ผ๋ ๊ธฐ๋ณธ ํด์ ๋ด์ฅํ๊ณ ์๋ค.
- ์ฅ์ : ๊ฐ๋ณ๋ค.
- Java๋ ๊ธฐ๋ณธ๊ตฌ์กฐ๋ฅผ ์๋ฒฝํ ๋ง๋ ๋ค์(๋ฐ๋์ ํ๋์ ํด๋์ค, ๋ฉ์๋ ๋ฑ) ์ปดํ์ผ์ ํด์ผ ์คํ์ด ๋์ง๋ง R์ ๊ทธ๋ฅ ํ์ํ ์ฝ๋๋ง ๋ฃ์ด๋ ์ํ ๊ฐ๋ฅํ๋ค.
- ์ด๋ฐ๊ฒ์ ์คํฌ๋ฆฝํธ ์ธ์ด(์๋ฐ์คํฌ๋ฆฝํธ, ํ์ด์ฌ ,R ๋ฑ)๋ผ๊ณ ํ๋ค.
- R์ Index๊ฐ 0๋ถํฐ๊ฐ ์๋ 1๋ถํฐ ์์ํ๋ค.
- +๊ธฐํธ๊ฐ ์๋ค๋ฉด ์ด์ ๋ฌธ์ฅ์ ์ด์ด์ prompt๊ฐ ์งํ๋๋ค๋๊ฒ์ด๋ค.
- ์์ ๋ช
๋ น์ด ์์ ํ๊ฒ ๋๋ด์ง ์๊ณ Enter๋ฅผ ์ณค์ ๊ฒฝ์ฐ ์๋์ผ๋ก +๋ก ๋ค์ํ์ด ์ถ๋ ฅ๋์ด ์ง๋ค.
- c๋์
์ฐ์ฐ์ : <-
- c๋ ํจ์๋ฅผ ์์ฑํด์ค๋ค.
- c:\hardy\Rstudy
- ์๋ ์ฃผ์์ด #์ด๋ค.'
- R์ ์ค์นผ๋ผ๊ฐ ์๋ค. ex) 10 => ์์ 1๊ฐ ์ง๋ฆฌ ๋ฒกํฐ์ ๊ฐ์ผ๋ก ์๋ค.
- *์ค์นผ๋ผ : ํ๋์ ๊ฐ
if)
```R
c(10,"A") ----> c("10", "A")
c(10,T) ----> c(10,1)
```
- ์ ๊ทํํ์
```R
? ---> 0, 1
+ ---> 1 ์ด์
* ---> 0 ์ด์
```
- R์
๋ ๋์ bin ๊ฒฝ๋ก
C:\hardy\Rstudy\selenium-server-standalone-master\bin
- R์
๋ ๋์ ํฌํธ๋๋ฒ
java -jar selenium-server-standalone.jar -port 4445
# [ ๋ฉํ ๋ง ๋ด์ฉ ์ ๋ฆฌ ]
- ํ์ฃผ์ฉ ๋ฉํ ๋
- ์์ ๋ง์ ํค์๋๋ฅผ ์ ํด์ ๋์ ธ์ค ๊ฒ.
- similarWeb
- ์์ด๋์ด ๋งคํธ๋ฆญ์ค
- ๋ฐ์์ง ๋ฉํ ๋
- ๋ฐ์ดํฐ๋ ์ ์ฒ๋ฆฌ ๊ณผ์ ์ด ๊ต์ฅํ ์ค์ํ๋ค.
- ์์
์ ํนํ ์์จ์ผํ๋ค. Hlookup ๋ฑ
- 2~3 ๊ตฐ๋ฐ์์์ ๋ฐ์ดํฐ๋ฅผ ๋ชจ์์์ผํ๋ค.
- ๊ตฌ๊ธ ์ค์นผ๋ผ (๋
ผ๋ฌธ๋ง ๊ฒ์ํ ์ ์์)
- What would you like to show? (ํํํ๊ธฐ ์ ํฉํ ๊ทธ๋ํ ์ฐจํธ ๋์)
- https://www.nsuchaud.fr/wp-content/uploads/2019/08/analysis-type-of-chart-1024x960.jpg
- <EMAIL>
- ์ต์ข
์ ๋ฉํ ๋
- Data Visualiztion
- ๋์ ๋ณด์ด์ง ์์ ๊ฒ์ ํ
์ดํฐ๋ก ๋์ ๋ณด์ด๋๋ก ํ๋ ๊ฒ
- ํ ์์๊ณผ์ ์ตํฉ (Mash Up)
- ์์ฐ์ด ์ฒ๋ฆฌ
- ํํ์ ๋ถ์ -> ์ฐ๊ด์ด ์ถ์ถ, ๊ฒ์/ ๋น๋
- ๊ตฌ๋ฌธ ๋ถ์ -> ์ฐ๊ด์ด ์ถ์ถ, ๊ฒ์/ ๋น๋
- ์๋ฏธ ๋ถ์ -> ๋ฌธ์์ ๊ธ๋ถ์ , ์ธ์ฌ์ดํธ ์ถ์ถ
- ๋ดํ ๋ถ์ -> ์ฑ๋ด
- oracle sql ๋ฐฑ์
- [ ๊ณ์ ์ ๋ชจ๋ ํ
์ด๋ธ ๋ฐฑ์
] - cmd ์ฐฝ์ ์ํ์ํค๊ณ ์ค๋ผํด์ bin ๋๋ ํ ๋ฆฌ์์ ์ํ
exp userid=jdbctest/jdbctest file=c:/unico/backup.bak
[ ๋ณต๊ตฌ]
imp userid=jdbctest/jdbctest file=c:/..../backup.bak full=y ignore=y
## [ Rserve ๊ฒฝ๋ก]
- C:\Program Files\R\R-3.6.3\bin\x64
- Rserve --RS-encoding utf8<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-A7F92100/D886FAFE-contents
text<- NULL
url<- "http://media.daum.net/ranking/popular/"
text <- read_html(url)
text
# newstitle
nodes <- html_nodes(text,"#mArticle > div.rank_news > ul.list_news2 > li > div.cont_thumb > strong > a.link_txt")
newstitle <- html_text(nodes)
newstitle
# newspapername
nodes <- html_nodes(text, "span.info_news")
newspapername <- html_text(nodes, trim=TRUE)
newspapername
page <- data.frame(newstitle, newspapername)
write.csv(page, "daumnews.csv")
<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-DEAE371D/66121AF2-contents
library(rvest)
text<- NULL
url<- "https://movie.daum.net/moviedb/grade?movieId=131576"
text <- read_html(url)
text
# ์ํํ์
nodes <- html_nodes(text,".emph_grade")
point <- html_text(nodes)
point
# ์ํ๋ฆฌ๋ทฐ
nodes <- html_nodes(text, "p.desc_review")
imsi <- html_text(nodes, trim=TRUE)
review <- imsi[nchar(imsi) > 0]
review
page <- cbind(point, review)
write.csv(page, "daummovie1.csv")
<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-32DEB4AB/1C83BF18-contents
#๋ฌธ์ 2
lib <- read.csv("data/์ง์ญ๋ณ์ฅ์ ์ธ๋์๊ด์ ๋ณด.csv",stringsAsFactors=F)
View(lib)
lib_add <- lib[,c(2, 9, 10)]
names(lib_add) <- c("libName", "lat", "lon")
View(lib_add)
map_seoul <- get_map(location="seoul", zoom=11, maptype="roadmap")
ggmap(map_seoul)+geom_point(data=lib_add, aes(x=lon, y=lat), alpha=0.7, size=5, color="red") +
geom_text(data=lib_add,
aes(x=lon,y=lat),
size=3,
label=lib_add$libName, vjust=0, hjust=-0.1) + guides(color=F)
ggsave("library.png")
<file_sep>/Rstudy/rjavatest.R
#install.packages("Rserve")
library(dplyr)
library(Rserve)
pdf <- read.table("C:/hardy/Rstudy/data/product_click.log")
names(pdf) <- c("logdate", "product")
pdf <- pdf %>% select(product) %>% group_by(product) %>% summarise(clickcount = n()) %>% arrange(desc(clickcount)) %>% head(1)
pdf <- as.data.frame(pdf)
pdf<file_sep>/Rstudy/naverhotel.R
# [ ๋ค์ด๋ฒ ํธํ
์ ๋ํ ์ ์ฒด ํ์ด์ง ๋๊ธ ์ฝ๊ธฐ ]
remDr <- remoteDriver(remoteServerAddr = "localhost" , port = 4445, browserName = "chrome")
remDr$open()
url<-'https://hotel.naver.com/hotels/item?hotelId=hotel:Shilla_Stay_Yeoksam&destination_kor=%EC%8B%A0%EB%9D%BC%EC%8A%A4%ED%85%8C%EC%9D%B4%20%EC%97%AD%EC%82%BC&rooms=2'
remDr$navigate(url)
Sys.sleep(3)
pageLink <- NULL
pageLink2 <- NULL
reple <- NULL
repeat{
doms <- remDr$findElements(using = "css", "body > div > div.ng-scope > div.container.ng-scope > div.content > div.hotel_used_review.ng-isolate-scope > div.review_ta.ng-scope > ul > li > div.review_desc > p")
Sys.sleep(1)
reple_v <- sapply(doms, function (x) {x$getElementText()})
print(reple_v)
reple <- append(reple, unlist(reple_v))
cat(length(reple), "\n")
pageLink <- remDr$findElements(using='css',"body > div > div.ng-scope > div.container.ng-scope > div.content > div.hotel_used_review.ng-isolate-scope > div.review_ta.ng-scope > div.paginate > a.direction.next")
remDr$executeScript("arguments[0].click();",pageLink)
if(length(pageLink2) == 1) break;
try(pageLink2<-remDr$findElement(using='css',
"body > div > div.ng-scope > div.container.ng-scope > div.content > div.hotel_used_review.ng-isolate-scope > div.review_ta.ng-scope > div.paginate > a.direction.next.disabled"), silent = T)
}
cat(length(reple), "๊ฐ์ ๋๊ธ ์ถ์ถ\n")
write(reple,"naverhotel.txt")
<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-DEAE371D/CD77EE1A-contents
library(rvest)
url <- "http://unico2013.dothome.co.kr/crawling/exercise_bs.html"
text <- read_html(url)
text
#<h1> ํ๊ทธ์ ์ปจํ
์ธ
nodes <- html_nodes(text, "h1")
title <- html_text(nodes)
title
#<a> ํ๊ทธ์ ์ปจํ
์ธ ์ href ์์ฑ๊ฐ
node1 <- html_nodes(text, "a")
aaa <- html_text(node1)
bbb <- html_attr(node1, "href")
aaa; bbb
#<img> ํ๊ทธ์ src ์์ฑ๊ฐ
nodeimg <- html_nodes(text, "img")
img <- html_attr(nodeimg, "src")
img
#์ฒซ ๋ฒ์งธ <h2> ํ๊ทธ์ ์ปจํ
์ธ
nodeh2 <- html_nodes(text, "h2:nth-of-type(1)")
h2a <- html_text(nodeh2)
h2a
#<ul> ํ๊ทธ์ ์์ ํ๊ทธ๋ค ์ค style ์์ฑ์ ๊ฐ์ด green์ผ๋ก ๋๋๋ ํ๊ทธ์ ์ปจํ
์ธ
nodeul <- html_nodes(text, "ul>*[style $= green]") # $= ์์ฑ์ ๋์ ๊ฐ์ ์ฐพ์๋ธ๋ค.
green <- html_text(nodeul)
green
#๋ ๋ฒ์งธ <h2> ํ๊ทธ์ ์ปจํ
์ธ
nodeh22 <- html_nodes(text, "h2:nth-of-type(2)")
h2b <- html_text(nodeh22)
h2b
#<ol> ํ๊ทธ์ ๋ชจ๋ ์์ ํ๊ทธ๋ค์ ์ปจํ
์ธ
nodeol <- html_nodes(text, "ol>*")
food <- html_text(nodeol)
food
#<table> ํ๊ทธ์ ๋ชจ๋ ์์ ํ๊ทธ๋ค์ ์ปจํ
์ธ
nodetable <- html_nodes(text, "table>*>*")
tb <- html_text(nodetable)
tb
#name ์ด๋ผ๋ ํด๋์ค ์์ฑ์ ๊ฐ๋ <tr> ํ๊ทธ์ ์ปจํ
์ธ
nodetr <- html_nodes(text, "tr[class = name]")
trrr <- html_text(nodetr)
trrr
#target ์ด๋ผ๋ ์์ด๋ ์์ฑ์ ๊ฐ๋ <td> ํ๊ทธ์ ์ปจํ
์ธ
nodetd <- html_nodes(text, "td[id = target]")
tddd <- html_text(nodetd)
tddd
<file_sep>/redu/src/main/java/service/ScrapingScheduler.java
package service;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScrapingScheduler {
@Scheduled(fixedDelay=300000) //5๋ถ์ ํ๋ฒ ์ํ
public void scheduleRun() {
Calendar calendar=Calendar.getInstance();
SimpleDateFormat dateFormat=new SimpleDateFormat(
"yyyy-MM-dd");
try {
RConnection rc = new RConnection();
FileWriter fw = new FileWriter("C:/hardy/daumnews_schedule.csv",true); //true ์ผ๋ ์ด์ด ์ฐ๊ธฐ
REXP x = rc.eval("imsi<-source('C:/hardy/Rstudy/JavaConnectNews.R'); imsi$value");
RList list = x.asList();
System.out.println(list);
for (int row = 0; row <= 4; row++ ) {
String newstitle = list.at("newstitle").asStrings()[row];
System.out.println(newstitle);
String newspapername = list.at("newspapername").asStrings()[row];
System.out.println(newspapername);
System.out.println(newstitle +","+ newspapername +"," +dateFormat.format(calendar.getTime()));
fw.write(newstitle +","+ newspapername +"," +dateFormat.format(calendar.getTime())+"\n");
}
rc.close();
fw.close();
}catch(Exception e) {
System.out.println("์ค๋ฅ ๋ฐ์");
e.printStackTrace();
}
}
}
<file_sep>/Linux ํ์ต ๋ด์ฉ.md
# [ Linux ]
## [ ๋ช
๋ น์ด ]
- pwd -> ํ์ฌ working directory๋ฅผ ์๋ ค์ค๋ค.
- ls -> ๊ฐ์ง๊ณ ์๋ ํด๋๋ฅผ ์๋ ค์ฃผ๋ฉฐ, ํด๋๋ ํ๋์์ผ๋ก ํ์๋์ด์ง๋ค.
- ls -l -> ์ข ๋ ์์ธํ๊ฒ ๋ฌธ์๋ฅผ ๋์ดํด ์ค๋ค.
- = ll ์ผ๋ก๋ ์ ๊ทผ ๊ฐ๋ฅ.
- l ์ long์ ์๋ฏธ์ด๋ค.
- ls -a -> ๋ ์์ธํ๊ฒ ๋ชจ๋ ๋ณด์ฌ์ค๋ค.
- a ๋ all์ ์๋ฏธ์ด๋ค.
- ls -al -> root ๊น์ง ์ ๋ถ ๋ณด์ฌ์ฃผ๋ฉด์ ์์ธํ๊ฒ ๋ณด์ฌ์ค๋ค.
- cd .. -> ํ๋ ์์ ํด๋๋ก ์ฌ๋ผ๊ฐ๋ค.
- cd centos -> centos ๋ก ๊ฐ๋ค.
- cd -> ๊ทธ๋ฅ ์ด๋์ ์์๋ ๊ฐ์ ํ directory๋ก ์ฎ๊ฒจ์ฌ์์๋ค.
- mkdir -> ํด๋๋ฅผ ์์ฑํ๋ค.
- ํ ํ ์์ฒด๋ฅผ ์ญ์ ํ ๋ -> dd
- ์ปค์ ์์น๋ง ์ญ์ ํ ๋ -> x
- ํ ํ ๋ณต์ฌ -> yy
- 3 ํ ๋ณต์ฌ -> 3yy
- (์ปค์ ํ ๋ฐ์ผ๋ก) ๋ถ์ฌ๋ฃ๊ธฐ -> p
- : -> ex๋ชจ๋๋ก ๊ฐ๋ค.
- : wq -> writeํ๊ณ quitํด๋ผ.
- :1 -> 1๋ฒ์งธ ํ์ผ๋ก ์ปค์๋ฅผ ์ฎ๊ฒจ๋ผ.
- q! -> (์ ์ฅํ์ง ๋ง๊ณ ) ๋ฌด์กฐ๊ฑด ๋๊ฐ๋ผ.
- cat ํ์ผ๋ช
-> "ํ์ผ๋ช
" ๋ด์ฉ์ ์ฝ์ด์ค๋ผ.
- head ํ์ผ๋ช
-> ์์์ ๋ถํฐ 10ํ ๋ด์ฉ์ ์ฝ์ด์ค๋ผ.
- tail ํ์ผ๋ช
-> ๋ค์์ ๋ถํฐ 10ํ ๋ด์ฉ์ ์ฝ์ด์ค๋ผ.
- vi e+TAB -> vi์์ e๋ก ์์ํ๋ ํ์ผ์ ์ฐพ์์ ์๋ ์์ฑ ํด์ค๋ค.
- **๊ตฌ๋ถ ๊ฐ๋ฅํ ํ์ผ๋ช
๊น์ง ์์ฑํ๊ณ TAB ํด์ฃผ์ด์ผ ํ๋ค.
- Shift + G -> ๋งจ ๋ง์ง๋ง ํ์ผ๋ก ์ปค์ ์์น๋ฅผ ์ฎ๊ฒจ ์ค๋ค.
- ^ -> ํ์ฌ ํ์ ์ฒ์์ผ๋ก ์ด๋
- $-> ํ์ฌ ํ์ ๋ง์ง๋ง์ผ๋ก ์ด๋
- cp ํ์ผ๋ช
์์ฑํ ํ์ผ
### ๋ช
๋ น > ํ์ผ๋ช
-> ๋ช
๋ น์ ๋ํ ๊ฒฐ๊ณผ๋ฅผ ํ์ผ๋ช
์ ๊ฐ์ง ๊ฒ์ ๋ง๋ค์ด์ ๊ทธ๊ณณ์ ์ ์ฅํ๊ฒ ๋ค.
### ๋ช
๋ น>>ํ์ผ๋ช
=> ์ด๋ฏธ ์กด์ฌํ๋ ํ์ผ๋ช
์ appendํ์ฌ ๋ช
๋ น์ ๋ด์ฉ์ ์ ์ฅํ๋ค.
### -๋ช
๋ น1 | ๋ช
๋ น2
- Space๋ฅผ ๋๋ฅด๋ฉด ํ ํ์ด์ง ์ฉ ๋์ด๊ฐ.
- Enter๋ฅผ ๋๋ฅด๋ฉด ํ ํ ์ฉ ๋์ด๊ฐ
- ps : process status -> ํ์ฌ (ํฐ๋ฏธ๋์์) ์ํ์ค์ธ ํ๋ก์ธ์ค๋ฅผ ๋ณด์ฌ์ค๋ค.
- ํ๋ก์ธ์ค : ํ์ฌ ์ํ์ค์ธ ํ๋ก๊ทธ๋จ
<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-20031A84/40811B95-contents
gong <- readLines("data/๊ณต๊ตฌ.txt", encoding = "UTF-8")
gong_n <- extractNoun(gong)
undata <- unlist(gong_n)
undata2 <- gsub("[[:lower:]]","",undata)
undata3 <- gsub("[[:upper:]]","",undata2)
undata4 <- gsub("[[:punct:]]","",undata3)
undata5 <- gsub("[[:digit:]]","",undata4)
undata6 <- gsub("โฅ","",undata5)
undata7 <- gsub("๊ณต๊ตฌ.*","",undata6)
undata8 <- gsub("ํด์ฃผ.*","",undata7)
undata9 <- Filter(function(x) {nchar(x) >= 2}, undata8)
undata9
bindo <- table(undata9)
final <- sort(bindo, decreasing = T)
head(final)
gong9 <- as.data.frame(final)
gong9
View(gong9)
png("wc.png",width=500, height=500)
windowsFonts(lett=windowsFont("ํด๋จผ์์ฒด"))
final <- wordcloud(gong9$undata9, gong9$Freq,
min.freq = 2,
random.order = FALSE,
rot.per = 0.3, scale = c(4, 1),
colors = rainbow(7),random.color = T,
family="lett")
dev.off()<file_sep>/Rstudy/.Rproj.user/7571EE4A/sources/s-1C178BEE/AF30B905-contents
yes24 <- readLines("yes24.txt")
yes24_n <- extractNoun(yes24)
undata <- unlist(yes24_n)
undata2 <- gsub("[[:lower:]]","",undata)
undata3 <- gsub("[[:upper:]]","",undata2)
undata4 <- gsub("[[:punct:]]","",undata3)
undata5 <- gsub("[[:digit:]]","",undata4)
undata6 <- Filter(function(x) {nchar(x) >= 2 & nchar(x) <= 4}, undata5)
undata6
bindo <- table(undata6)
result <- sort(bindo, decreasing = T)
result <- wordcloud2(result, fontFamily = "ํด๋จผ์์ฒด")
saveWidget(result,"wc.html",title="WORDCLOUD2 ์ค์ต",selfcontained = F)
| 866f449f7db9f5781f70a57ce50cf108a3c4ebe9 | [
"Markdown",
"Java",
"R"
] | 16 | R | Park-MinSoo/R | 67a2088de79cb0036fe582e5d9aff85a899aba7e | 00c3cf6cfce6b9b7b220a1efcdf4336a7204ca71 |
refs/heads/master | <repo_name>renatavillegas/wheelchair-control<file_sep>/build/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project( Main )
find_package( OpenCV REQUIRED)
add_executable(Main ../main.cpp)
include_directories(../lib)
add_definitions (-DNON_MATLAB_PARSING)
add_definitions (-DMAX_EXT_API_CONNECTIONS=255)
add_definitions (-D__linux)
target_link_libraries(Main ${OpenCV_LIBS})
set (CMAKE_CXX_FLAGS "-std=gnu++11 -pthread")
set (CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} -lrt")<file_sep>/lib/manipulator.h
#ifndef MANIPULATOR_H // include guard
#define MANIPULATOR_H
#define GLM_ENABLE_EXPERIMENTAL
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <opencv/cv.h>
#include <vector>
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApi.h"
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApiPlatform.h"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include "cameraCalibration.h"
#include "marker.h"
using namespace cv;
using namespace std;
using namespace glm;
class Manipulator
{
private:
int clientID;
int jacoHandle;
int ikTarget;
int ikTip;
int ikGroup;
int target0;
int target1;
int target2;
int rmlHandle;
int jh[6];
int jt[6];
float jointsUpperVelocityLimits[6];
public:
Manipulator(int id);
Manipulator();
void getHandPosition();
void getHandOrientation();
void setKnobPosition(simxFloat doorPosition[3]);
void setKnobOrientation(simxFloat doorOrientation[3]);
void exec();
int get_JacoHandle();
int get_target1Handle();
//motion planning related methods
void motion_planning();
float get_simStepTime();
void get_jointsUpperVelocityLimits(float jointsUpperVelocityLimits[6]);
int execute_rmlStep(float posVelAccel[3], int rmlHandle);
void execute_motion();
int get_rmlHandle(float velCorrection);
int get_lengthSize();
int get_pathSize(int pathID);
void follow_path(int pathID);
void approach();
void close_hand();
void open_door();
void push();
void open_hand();
void return_to_start_position();
void cross();
};
#endif /* MANIPULATOR_H */<file_sep>/lib/manipulator.cpp
#include "manipulator.h"
using namespace cv;
using namespace std;
using namespace glm;
Manipulator::Manipulator()
{
clientID = -1;
for(int i =0; i<6;i++)
{
jh[i] =-1;
jt[i]=-1;
jointsUpperVelocityLimits[i]=-1;
}
jacoHandle= -1;
ikTarget=-1;
ikTip=-1;
ikGroup= -1;
target0= -1;
target1=-1;
target2=-1;
rmlHandle = -1;
}
Manipulator::Manipulator(int ID)
{
clientID = ID;
for(int i =0; i<6;i++)
{
jh[i] =-1;
jt[i]=-1;
jointsUpperVelocityLimits[i]=-1;
}
// inputs: None
// outputs: joint handles, joint types,
// jacoHandle, ikTarget, ikTip, ikGroup, target0, target1;
int outIntCount = 19;
int *outInt;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "initializeJaco",
0, NULL,0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
for(int i=0; i<6; i++)
{
//joint handles
jh[i] = outInt[i];
jt[i] = outInt[i+6]; // joint type
cout << "Joint Connected " << jh[i]<<endl;
}
jacoHandle= outInt[12];
ikTarget=outInt[13];
ikTip=outInt[14];
ikGroup= outInt[15];
target0= outInt[16];
target1=outInt[17];
target2=outInt[18];
rmlHandle = -1;
}
int Manipulator::get_JacoHandle()
{
return jacoHandle;
}
int Manipulator::get_target1Handle()
{
return target1;
}
void Manipulator::setKnobPosition(simxFloat doorPos[3])
{
// set the targets position to do the planning
simxFloat target1Pos[3];
simxFloat target2Pos[3];
//experimental shift;
if (doorPos!=NULL)
{
target1Pos[0]= doorPos[0] - 0.08;
target1Pos[1]= doorPos[1] - 0.1;
target1Pos[2]= doorPos[2] -0.1;
target2Pos[0]= target1Pos[0]+ 0.01;
target2Pos[1]= target1Pos[1];
target2Pos[2]= target1Pos[2] - 0.07;
int result = simxSetObjectPosition(clientID, target1, -1, target1Pos,simx_opmode_oneshot_wait);
if (result!=simx_return_ok)
cout<< "ERROR: setKnobPosition target 1 Failed"<< endl;
result = simxSetObjectPosition(clientID, target2, -1, target2Pos,simx_opmode_oneshot_wait);
if (result!=simx_return_ok)
cout<< "ERROR: setKnobPosition target 2 Failed"<< endl;
}
else
cout << "ERROR: setKnobPosition:: doorPos is null"<< endl;
}
void Manipulator::setKnobOrientation(simxFloat doorOri[3])
{
if (doorOri!=NULL)
{
simxFloat target1Ori[3];
simxFloat target2Ori[3];
target1Ori[0]=doorOri[0];
target1Ori[1]= doorOri[1];
target1Ori[2]= doorOri[2] - 1.57;
target2Ori[0]=target1Ori[0];
target2Ori[1]=target1Ori[1]+ 0.03;
target2Ori[2]=target1Ori[2];
int result = simxSetObjectOrientation(clientID, target1, -1, target1Ori,simx_opmode_oneshot_wait);
if (result!=simx_return_ok)
cout<< "ERROR: setKnobOrientation target1 Failed"<< endl;
result = simxSetObjectOrientation(clientID, target2, -1, target2Ori,simx_opmode_oneshot_wait);
if (result!=simx_return_ok)
cout<< "ERROR: setKnobOrientation target2 Failed"<< endl;
}
else
cout << "ERROR: setKnobOrientation:: doorOri is null"<< endl;
}
// Motion planning remote API related methods:
// calculate path.
void Manipulator::motion_planning()
{
//inputs: None
//outPuts: pathFound - 0=true, 1=false ;
int outIntCount=1;
int *outInt;
outInt=NULL;
int found;
// int outStringCount = 2;
// simxChar *outString;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "motionPlanning",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result==simx_return_ok && outInt!=NULL)
{
found = *outInt;
if(found == 1)
cout << "Motion path found."<< endl;
}
}
// get simulation step time to use on motion execution.
float Manipulator::get_simStepTime()
{
int outFloatCount = 1;
float *outFloat;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "getSimStep",
0, NULL, 0, NULL, 0, NULL,0,NULL,
NULL, NULL, &outFloatCount , &outFloat, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok && outFloat!=NULL)
return *outFloat;
cout << "ERROR: get_simStepTime failed."<<endl;
}
// get the max vel of each joint
void Manipulator::get_jointsUpperVelocityLimits(float jointsUpperVelocityLimits[6])
{
//inputs: joint handles;
//outputs: joitUpperVelocityLimits, sucess;
int inIntCount = 1;
int *inInt;
int outIntCount = 1;
int *outInt;
int outFloatCount= 1;
float *outFloat = NULL;
int result;
int i =0;
do
{
*inInt = jh[i];
result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "getJointsUpperVelocityLimits",
inIntCount, inInt, 0, NULL, 0, NULL,0,NULL,
&outIntCount,&outInt, &outFloatCount , &outFloat, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok && outFloat!=NULL && *outInt ==1)
{
jointsUpperVelocityLimits[i] = *outFloat;
cout << "joitUpperVelocityLimits= " << jointsUpperVelocityLimits[i]<<endl;
}
else
cout << "ERROR: get_jointsUpperVelocityLimits failed." << endl;
i++;
}
while(i<6);
}
// get rml handle to calculate the steps of the motion
int Manipulator::get_rmlHandle(float velCorrection)
{
//inputs: velCorrection
//outputs: rml handle
int inIntCount =1;
int *inInt;
*inInt = 1;
int outIntCount = 1;
int *outInt;
int handle;
outInt = NULL;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "getRmlHandle",
inIntCount, inInt, 0, NULL, 0, NULL,0,NULL,
&outIntCount,&outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok && outInt !=NULL)
{
cout << "rmlHandle = " << *outInt << endl;
handle = *outInt;
return handle;
}
cout << "ERROR: get_rmlHandle failed. "<< endl;
return -1;
}
// execute a rmlStep
int Manipulator:: execute_rmlStep(float posVelAccel[3], int rmlHandle)
{
//inputs: rmlHandle
//output: res(0: Final state not reached yet; 1: final state reached)
int inIntCount = 1;
int *inInt;
inInt[0]= rmlHandle;
int outIntCount = 1;
int *outInt;
int outFloatCount = 3;
float *outFloat;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "executeRmlStep",
inIntCount, inInt, 0, NULL, 0, NULL,0,NULL,
&outIntCount,&outInt, &outFloatCount , &outFloat, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok && outInt !=NULL && outFloat !=NULL)
{
cout << "res = " << outInt[0] << endl;
for(int i=0; i<outFloatCount;i++)
{
posVelAccel[i]=outFloat[i];
cout << posVelAccel[i] << endl;
}
return outInt[0];
}
cout << "ERROR: execute_rmlStep failed."<< endl;
return -1;
}
//get legths size
int Manipulator::get_lengthSize()
{
//inputs: None
//Outputs: #length
int outIntCount=1;
int *outInt;
outInt = NULL;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "getLengthSize",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount,&outInt, 0 , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok && outInt!=NULL && *outInt !=-1)
return *outInt;
cout <<("ERROR: get_lengthSize failed.")<< endl;
return -1;
}
// get path size
int Manipulator::get_pathSize(int pathID)
{
//inputs: pathID
int inIntCount =1;
int inInt = pathID;
//outputs: path size
int outIntCount=1;
int *outInt;
int size = -1;
outInt = NULL;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "getPathSize",
inIntCount, &inInt, 0, NULL, 0, NULL,0,NULL,
&outIntCount,&outInt, 0 , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok && outInt!=NULL && *outInt !=-1)
size = *outInt;
else
cout <<("ERROR: get_pathSize failed.")<< endl;
return size;
}
void Manipulator::follow_path(int pathID)
{
//Each path point is a robot configuration.
int l = get_pathSize(pathID);
cout << "path size = " << l;
//get the config of all of the joints on the path position
int j = 0;
//inputs: point on path (j)
//outputs: config of all joints in this point
int inIntCount = 2;
int outFloatCount = 6;
int inInt[2] = {j,pathID};
float *outFloat;
outFloat=NULL;
float configs[6]= {-1,-1,-1,-1,-1,-1};
int result;
do
{
result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "followPath",
inIntCount, inInt, 0, NULL, 0, NULL,0,NULL,
0, NULL, &outFloatCount , &outFloat, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result== simx_return_ok && outFloat != NULL)
{
for(int i =0;i<outFloatCount-1;i++)
{
configs[i]= outFloat[i];
//cout << "config " << i << " = " << configs[i] << endl;
//cout << "jh " << i << jh[i] << endl;
if (configs[i]!=-111)
result = simxSetJointTargetPosition(clientID, jh[i],configs[i],simx_opmode_oneshot);
if(result != simx_return_ok)
cout<< "something wrong on SetJointTargetVelocity" <<endl;
}
}
inInt[0]++;
}
while(inInt[0]<l/6);
}
void Manipulator::approach()
{
//inputs: None
//outPuts: pathFound - 0=true, 1=false ;
int outIntCount=1;
int *outInt;
outInt=NULL;
int found;
// int outStringCount = 2;
// simxChar *outString;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "approach",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result==simx_return_ok && outInt!=NULL)
{
found = *outInt;
if(found == 1)
cout << "Approach path found."<< endl;
}
}
void Manipulator::close_hand()
{
//inputs: None
//output: None
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "closeHand",
0, NULL, 0, NULL, 0, NULL,0,NULL,
NULL, NULL, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok)
cout << "Hand closed." << endl;
}
void Manipulator::open_door()
{
//inputs: None
//outPuts: pathFound - 0=true, 1=false ;
int outIntCount=1;
int *outInt;
outInt=NULL;
int found=0;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "openDoorMotionPlanning",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result==simx_return_ok && outInt!=NULL)
{
found = *outInt;
if(found == 1)
cout << "Open door path found."<< endl;
}
}
void Manipulator::push()
{
//inputs: None
//outPuts: pathFound - 0=true, 1=false ;
int outIntCount=1;
int *outInt;
outInt=NULL;
int found=0;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "pushMotionPlanning",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result==simx_return_ok && outInt!=NULL)
{
found = *outInt;
if(found == 1)
cout << "Push door path found."<< endl;
}
}
void Manipulator::open_hand()
{
//inputs: None
//output: None
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "openHand",
0, NULL, 0, NULL, 0, NULL,0,NULL,
NULL, NULL, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result == simx_return_ok)
cout << "Hand opened." << endl;
}
void Manipulator::return_to_start_position()
{
//We have a target0 that holds the initial position and orientation.
//When the open movement is finished, return to that position and orientation.
//inputs: None
//outPuts: pathFound - 0=true, 1=false ;
int outIntCount=1;
int *outInt;
outInt=NULL;
int found;
// int outStringCount = 2;
// simxChar *outString;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "returnToStartPosition",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result==simx_return_ok && outInt!=NULL)
{
found = *outInt;
if(found == 1)
cout << "Return to start position path found."<< endl;
}
}
void Manipulator::cross()
{
//put the arm where the arTag is.
//inputs: None
//outPuts: pathFound - 0=true, 1=false ;
int outIntCount=1;
int *outInt;
outInt=NULL;
int found;
// int outStringCount = 2;
// simxChar *outString;
int result = simxCallScriptFunction(clientID, "Jaco", sim_scripttype_childscript, "cross",
0, NULL, 0, NULL, 0, NULL,0,NULL,
&outIntCount, &outInt, NULL , NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(result==simx_return_ok && outInt!=NULL)
{
found = *outInt;
if(found == 1)
cout << "Cross path found."<< endl;
}
}<file_sep>/lib/remoteapi.h
#ifndef REMOTEAPI_H // include guard
#define REMOTEAPI_H
#define GLM_ENABLE_EXPERIMENTAL
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <opencv/cv.h>
#include <vector>
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApi.h"
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApiPlatform.h"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include "cameraCalibration.h"
#include "marker.h"
#include "manipulator.h"
#include "manipulator.cpp"
using namespace cv;
using namespace std;
using namespace glm;
extern "C" {
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApi.c"
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApiPlatform.c"
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/common/shared_memory.c"
}
class RemoteApi
{
private:
int clientID;
int robotHandle;
int rightMotorHandle;
int leftMotorHandle;
int pathHandle;
int startDummyHandle;
int goalHandle;
int arTagHandle;
int doorHandle;
int cameraDummyHandle;
int goalCameraDummyHandle;
int collidableForPathPlanningHandle;
int obstaclesHandle;
int planningTaskHandle;
int doorJointHandle;
simxFloat TagQuaternion[4];
simxFloat TagPosition[3];
Marker realTag;
Manipulator jaco;
public:
//getter- setter
RemoteApi();
int get_clientID();
void connect();
void initialize_objects();
void set_tag_position(Marker realTag);
void path_planning();
void check_collision();
void path_following();
void adjust_orientation();
void preapre_motion();
void motion_planning();
void execute_motion();
void cross();
void return_to_initial_position();
};
#endif /* REMOTEAPI_H */<file_sep>/lib/marker.cpp
#include "marker.h"
int ID;
Vec3d position, angle;
quat quaternion;
//getters-setters
int Marker::get_id()
{
return ID;
}
void Marker::set_id(int id)
{
ID = id;
}
Vec3d Marker::get_position()
{
return position;
}
void Marker::set_position(Vec3d pos)
{
position = pos;
}
Vec3d Marker::get_angle()
{
return angle;
}
void Marker::set_angle(Vec3d orientation)
{
angle = orientation;
}
quat Marker::get_quaternion()
{
return quaternion;
}
void Marker::set_quaternion(quat q)
{
quaternion = q;
}
void Marker::set_quaternion(Vec3d angle)
{
vec3 eulerAngles = Vec3dtoVec3(angle);
quaternion = quat(eulerAngles);
}
vec3 Marker::Vec3dtoVec3 (Vec3d source)
{
vec3 dest;
for (int i=0; i<3; i++)
{
dest[i] = source(i);
}
return dest;
}
bool Marker::is_in_list(vector<Marker> marker_list, int markerID)
{
for(int i =0; i<marker_list.size(); i++)
{
if (markerID == marker_list[i].get_id())
return true;
}
return false;
}
Marker Marker::get_marker_in_list(vector<Marker> marker_list, int markerID)
{
Marker tag;
if (is_in_list(marker_list, markerID))
{
for(int i =0; i < marker_list.size(); i++)
{
tag = marker_list[i];
if (tag.get_id()==markerID)
break;
}
}
else
{
cout << "ERROR: This ID is not in the list\n";
}
return tag;
}
void Marker::print()
{
cout <<"Marker ID = " << ID <<endl
<< "DistanceVector = " << position << endl
<< "AngleVector=" << angle << endl;
}<file_sep>/Mywheelchair.lua
function sysCall_threadmain()
-- initialize objects
motorR = sim.getObjectHandle('motorRight')
motorL = sim.getObjectHandle('motorLeft')
robot = sim.getObjectHandle('wheelchair_shape')
path_handle = sim.getObjectHandle('Path')
path_plan_handle=simGetPathPlanningHandle('PathPlanningTask0')
start_dummy_handle = sim.getObjectHandle('wheelchairFrame')
--some constants
MPI=math.pi
rad2deg=180/MPI
deg2rad=MPI/180
--model related measures and constants definitions
L = 0.6403 -- m (distance between wheels)
maxLinVel=0.5 --linear velocity in m/s
maxAngVel=220 --deg/sec (3.876?rad/sec)
wheelHandle=sim.getObjectHandle('bigWheelLeft_respondable')
res,zMin=sim.getObjectFloatParameter(wheelHandle,17)
res,zMax=sim.getObjectFloatParameter(wheelHandle,20)
R=(zMax-zMin)/2-- m (wheel radius)
pos_on_path =0
dist = 0 -- dist from the robot to the point on the path
planstate=simSearchPath(path_plan_handle,5)
m= sim.buildMatrixQ(sim.getObjectPosition(robot, -1), sim.getObjectQuaternion(robot,-1))
while (sim.getSimulationState()~=sim.simulation_advancing_abouttostop) do
robot_pos= sim.getObjectPosition(robot, -1)
path_pos = sim.getPositionOnPath(path_handle, pos_on_path)
sim.setObjectPosition(start_dummy_handle, -1, path_pos)
sim.setObjectOrientation(start_dummy_handle, -1, path_pos)
print("path_pos before: " .. path_pos[1] ..", ".. path_pos[2] .. ", " .. path_pos[3])
m= sim.getObjectMatrix(robot, -1)
a = sim.invertMatrix(m)
if(a == -1)then
print("Could not invert matrix")
end
path_pos= sim.multiplyVector(m, path_pos)
print ("Path pos after changing: " .. path_pos[1] ..", ".. path_pos[2] .. ", " .. path_pos[3])
dist = math.sqrt((path_pos[1])^2 + (path_pos[2])^2)
print("Dist = " ..dist)
phi = math.atan2(path_pos[2], path_pos[1])
v_des= maxLinVel
om_des= maxAngVel
vl = v_des/10 - (L/2*om_des/10*MPI/180)/(R);
vr = v_des/10 + (L/2*om_des/10*MPI/180)/(R);
sim.setJointTargetVelocity(motorR,vr)
sim.setJointTargetVelocity(motorL,vl)
if(dist<0.1) then
pos_on_path = pos_on_path +0.1
else
sim.setJointTargetVelocity(motorR,0)
sim.setJointTargetVelocity(motorL,0)
end
sim.wait(0.025, true)
end
end
function sysCall_cleanup()
-- Put some clean-up code here
end
-- ADDITIONAL DETAILS:
-- -------------------------------------------------------------------------
-- If you wish to synchronize a threaded loop with each simulation pass,
-- enable the explicit thread switching with
--
-- sim.setThreadAutomaticSwitch(false)
--
-- then use
--
-- sim.switchThread()
--
-- When you want to resume execution in next simulation step (i.e. at t=t+dt)
--
-- sim.switchThread() can also be used normally, in order to not waste too much
-- computation time in a given simulation step
-- -------------------------------------------------------------------------
--backup
while (sim.getSimulationState()~=sim.simulation_advancing_abouttostop
and planstate ~=0) do
-- follow the path
robot_pos= sim.getObjectPosition(robot, -1)
robot_ori= sim.getObjectOrientation(robot, -1)
path_pos = sim.getPositionOnPath(path_handle, pos_on_path) -- pos_on_path [0-1]
path_ori = sim.getObjectOrientation(path_handle, -1)
-- print("path_pos before: " .. path_pos[1] ..", ".. path_pos[2] .. ", " .. path_pos[3])
m= sim.buildMatrix(robot_pos, robot_ori)
-- print("m before =" .. m[5])
a = sim.invertMatrix(m)
-- print("m after"..m[5])
if(a == -1)then
print("Could not invert matrix")
break
end
path_pos= sim.multiplyVector(m, path_pos) -- now pos is relative to the robot.
-- print ("Path pos after changing: " .. path_pos[1] ..", ".. path_pos[2] .. ", " .. path_pos[3])
dist = math.sqrt((path_pos[1])^2 + (path_pos[2])^2) -- distance between the robot and the point on path
print("Dist = " ..dist)
phi = math.atan2(path_pos[2], path_pos[1]) -- angular position of the path in relation to the robot
v_des= maxLinVel
om_des= maxAngVel
--v_r= (v_des + L*om_des)
--v_l = (v_des -L*om_des)
-- vl = v_des/10 - (L/15*om_des*MPI/180)/(R);
-- vr = v_des/10 + (L/15*om_des*MPI/180)/(R);
-- sim.setJointTargetVelocity(motorR,vr)
-- sim.setJointTargetVelocity(motorL,vl)
-- Moviment control. The ideia is applying the differential robot control definition.
if(dist<0.1) then
pos_on_path = pos_on_path +0.5
else
-- by knowing the angle, we know how to update the velocities.
a=math.atan2(path_pos[2],path_pos[1])
print("ang = " ..a)
if (a>=0)and(a<math.pi*0.5) then -- [0-90]: turn the robot clockwise
vr=nominalVelocity
vl=nominalVelocity*(1-2*a/(math.pi*0.5))
print('[0-90]: turn the robot clockwise')
end
if (a>=math.pi*0.5) then --[90-180]: turn the robot anticlockwise
vl=-nominalVelocity
vr=nominalVelocity*(1-2*(a-math.pi*0.5)/(math.pi*0.5))
print('[90-180]: turn the robot anticlockwise')
end
if (a<0)and(a>-math.pi*0.5) then --[-90-0]: turn the robot anticlockwise
vl=nominalVelocity
vr=nominalVelocity*(1+2*a/(math.pi*0.5))
print('[-90-0]: turn the robot anticlockwise')
end
if (a<=-math.pi*0.5) then --[-180 -90]: turn the robot clockwise
vr=-nominalVelocity
vl=nominalVelocity*(1+2*(a+math.pi*0.5)/(math.pi*0.5))
print('[-180 -90]: turn the robot clockwise')
end
omega=R*(vr-vl)/L
vel=(vr+vl)/2
-- update velocities
vl_new = vel - (L/2*omega*MPI/180.)/(R);
vr_new = vel + (L/2*omega*MPI/180.)/(R);
sim.setJointTargetVelocity(motorR,vr_new)
sim.setJointTargetVelocity(motorL,vl_new)
-- adjusting the orientation. Verify if we're close to the target. If we are, adjust the orientation
reachError = 0.01
posTg=sim.getObjectPosition(goal,-1)
rotTg=sim.getObjectOrientation(goal,-1)
posRobot=sim.getObjectPosition(robot,-1)
rotRobot=sim.getObjectOrientation(robot,-1)
if math.abs(posTg[1]-posRobot[1])< reachError and math.abs(posTg[2]-posRobot[2])< reachError then
print ('Robot close to the target.')
end
end
sim.wait(0.05, true)
end<file_sep>/lib/remoteapi.cpp
#include "remoteapi.h"
using namespace cv;
using namespace std;
using namespace glm;
simxFloat TagQuaternion[4];
simxFloat TagPosition[3];
Marker realTag;
simxFloat goalPos[3];
simxFloat robotPos[3];
RemoteApi::RemoteApi()
{
clientID = -1;
connect();
initialize_objects();
}
int RemoteApi::get_clientID()
{
return clientID;
}
void RemoteApi::connect()
{
clientID=simxStart("127.0.0.1",19999,true,true,-500000,5);
simxSynchronous(clientID,true);
if(clientID == -1)
{
cout << "ERROR: No connection avaliable\n";
simxFinish(clientID);
}
}
void RemoteApi::initialize_objects()
{
(simxGetObjectHandle(clientID, "wheelchair2", &robotHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Robot Connected"<<endl:cout<<"ERROR: Robot Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "wheelchair_rightMotor", &rightMotorHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Right motor Connected"<<endl:cout<<"ERROR: Right motor Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "wheelchair_leftMotor", &leftMotorHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Left motor Connected"<<endl:cout<<"ERROR: Left motor Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "Path2", &pathHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Path Connected"<<endl:cout<<"ERROR:Path Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "wheelchairFrame2", &startDummyHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Wheelchair frame Connected"<<endl:cout<<"ERROR:Wheelchair frame Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "wheelchairFrameGoal", &goalHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Goal frame Connected"<<endl:cout<<"ERROR: Goal frame Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "ARTag", &arTagHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"ARTag frame Connected"<<endl:cout<<"ERROR: ARTag frame Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "DoorPositionDummy", &doorHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Door frame Connected"<<endl:cout<<"ERROR: Door frame Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "CameraDummy", &cameraDummyHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Camera frame Connected"<<endl:cout<<"ERROR: Camera frame Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "GoalCameraDummy", &goalCameraDummyHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Camera frame Connected"<<endl:cout<<"ERROR: Camera frame Connection Failed"<<endl);
(simxGetObjectHandle(clientID, "_doorJoint", &doorJointHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"Door joint Connected"<<endl:cout<<"ERROR: Camera frame Connection Failed"<<endl);
jaco = Manipulator(clientID);
//execute_motion();
}
void RemoteApi::set_tag_position(Marker tag)
{
Marker realTag;
realTag = tag;
simxFloat RotQuaternion[4] = {(float)realTag.get_quaternion().x,
(float)realTag.get_quaternion().y,
(float)realTag.get_quaternion().z,
(float)realTag.get_quaternion().w};
simxFloat Orientation[3] = {(float)realTag.get_angle()[0],
(float)realTag.get_angle()[1],
(float)realTag.get_angle()[2]};
simxFloat Position[3] = {(float)realTag.get_position()[0],
(float)realTag.get_position()[1],
(float)realTag.get_position()[2]};
simxFloat doorPos[3];
simxFloat doorOri[3];
simxGetObjectPosition(clientID, doorHandle, -1, doorPos, simx_opmode_oneshot_wait);
//robot pos
simxGetObjectPosition(clientID, cameraDummyHandle, -1, robotPos, simx_opmode_oneshot_wait);
//change the door position based on the TAG position
doorPos[0]=robotPos[0]-(float)realTag.get_position()[0];
doorPos[1]=robotPos[1]+(float)realTag.get_position()[2];
cout << "doorPos:" <<doorPos[0] <<"; "<< doorPos[1] <<"; "<< doorPos[2] << endl;
realTag.print();
simxSetObjectPosition(clientID, doorHandle, -1, doorPos, simx_opmode_oneshot);
//simxSetObjectQuaternion(clientID, doorPosition, wheelChair, RotQuaternion, simx_opmode_blocking);
// change the goal position based on the door position.
// get the door position in relation to the world
if (simxGetObjectPosition(clientID, doorHandle, -1, doorPos, simx_opmode_oneshot_wait)!=simx_return_ok)
cout<< "ERROR: get door position failed."<< endl;
cout << "doorPos2:" <<doorPos[0] <<"; "<< doorPos[1] <<"; "<< doorPos[2] << endl;
//get the goalPosition relative to the world
if (simxGetObjectPosition(clientID, goalCameraDummyHandle, -1, goalPos, simx_opmode_oneshot_wait)!=simx_return_ok)
cout<< "ERROR: get goal position failed."<< endl;
goalPos[0]=doorPos[0]-0.3;
goalPos[1]=doorPos[1]-0.8;
simxSetObjectPosition(clientID, goalCameraDummyHandle, -1, goalPos, simx_opmode_oneshot);
// change the door orientation based on the camera capture.
if (simxGetObjectOrientation(clientID, doorHandle, cameraDummyHandle, doorOri, simx_opmode_oneshot_wait)!=simx_return_ok)
cout<< "ERROR: get door orientation failed."<< endl;
cout << "doorOri in relation to the Camera:" <<doorOri[0] <<"; "<< doorOri[1] <<"; "<< doorOri[2] << endl;
doorOri[3]= Orientation[3];
simxSetObjectOrientation(clientID, doorHandle, cameraDummyHandle, doorOri, simx_opmode_oneshot);
cout << "Now that we have the goal, start the path planning" << endl;
}
void RemoteApi::check_collision()
{
//get the collision object and the robot shape
(simxGetObjectHandle(clientID, "CollidableForPathPlanning", &collidableForPathPlanningHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"CollidableForPathPlanning Connected"<<endl:cout<<"ERROR: CollidableForPathPlanning Connection Failed"<<endl);
(simxGetCollectionHandle(clientID, "p3ObstacleCollection", &obstaclesHandle, simx_opmode_oneshot_wait)
== simx_return_ok?cout<<"obstacles Connected"<<endl:cout<<"ERROR: obstacles Connection Failed"<<endl);
const int inIntCount = 2;
int inInt []= {collidableForPathPlanningHandle, obstaclesHandle};
int outIntCount = 1;
int *collision;
int ret = simxCallScriptFunction(clientID, "autodrive2", sim_scripttype_childscript, "check_collision_sim",
inIntCount, inInt,0, NULL, 0, NULL,0,NULL,
&outIntCount, &collision, NULL, NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
(*collision == 0? cout << "We are not in collision = " << *collision << endl : cout <<"ERROR: We are colliding! " << endl);
}
void RemoteApi::path_planning()
{
int *pathCalculated;
int closeToTarget=-1;
int intCount=1;
const int inIntCount = 1;
int inInt []= {planningTaskHandle};
int result = simxCallScriptFunction(clientID, "autodrive2", sim_scripttype_childscript, "path_planning",
0, NULL,0, NULL, 0, NULL,0,NULL,
&intCount, &pathCalculated, NULL, NULL, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if(*pathCalculated != 0)
cout << "Path calculated = " << *pathCalculated << endl;
else
cout << "ERROR during the path planning." << endl;
}
void RemoteApi::path_following()
{
const int inIntCount = 4;
//Inputs : path handle, robot frame, left motor, right motor
int inInt []= {pathHandle, startDummyHandle, leftMotorHandle, rightMotorHandle};
//Outputs: Close to target, vl, vr
int outIntCount = 1;
int *closeToTarget =0;
int outFloatCount = 2;
float vr = 0;
float vl =0;
float *velocities;
do
{
int result = simxCallScriptFunction(clientID, "autodrive2", sim_scripttype_childscript, "path_following",
inIntCount, inInt,0, NULL, 0, NULL,0,NULL,
&outIntCount, &closeToTarget, &outFloatCount , &velocities, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if (result == simx_return_ok && velocities != NULL)
{
//cout << "closeToTarget = "<< *closeToTarget << endl;
vl = velocities[0];
vr = velocities[1];
//cout << "LeftV = " << vl <<", RightV = " << vr << endl;
//update velocities
simxSetJointTargetVelocity(clientID, rightMotorHandle, vr, simx_opmode_oneshot);
simxSetJointTargetVelocity(clientID, leftMotorHandle, vl, simx_opmode_oneshot);
}
}
while(*closeToTarget == 0);
}
void RemoteApi::adjust_orientation()
{
cout << "Now we are close to the object so we will adjust the orientation of the chair." << endl;
cout << "Start PID control:" << endl ;
float prev_error=0;
float integral=0;
float oldtime=0;
float Kp=0.1; //--mm/s;
float Ki=0.001;//--0--0.09;
float Kd=0.9;//--0.9--30;
cout << "Kp = " << Ki <<", Ki = " << Ki << Kp <<", Kd = " << Kd;
const int inIntCount = 2;
const int inFloatCount = 3;
//Inputs : robot, goal, prev_error, integral
int inInt []= {startDummyHandle,goalHandle};
float inFloat[] = {prev_error, integral, oldtime};
//Outputs: Stop, vl, vr, prev_error, integral
int outIntCount = 1;
int *outInt;
int outFloatCount =5;
float *outFloat;
float vl, vr;
int result;
int stop;
do
{
result = simxCallScriptFunction(clientID, "autodrive2", sim_scripttype_childscript, "adjusting_orientation",
inIntCount, inInt, inFloatCount, inFloat, 0, NULL,0,NULL,
&outIntCount, &outInt, &outFloatCount , &outFloat, NULL, NULL, NULL, NULL, simx_opmode_oneshot_wait);
if (result == simx_return_ok && outFloat != NULL)
{
vl = outFloat[0];
vr = outFloat[1];
prev_error = outFloat[2];
integral = outFloat[3];
oldtime = outFloat[4];
cout << "LeftV = " << vl <<", RightV = " << vr << endl;
stop = *outInt;
//update velocities
simxSetJointTargetVelocity(clientID, rightMotorHandle, vr, simx_opmode_oneshot);
simxSetJointTargetVelocity(clientID, leftMotorHandle, vl, simx_opmode_oneshot);
}
}
while(stop == 0);
cout << "The wheelchair now is in the correct position and orientation." << endl;
}
void RemoteApi::preapre_motion()
{
//set the target position/orientation of the manipulator based on the door position
//To avoid colision between the knob and the fingers of the manipulator:
//Do a first approach and adjust the orientation.
simxFloat doorPos[3];
simxFloat doorOri[3];
if (simxGetObjectPosition(clientID, doorHandle, -1, doorPos, simx_opmode_oneshot_wait)!=simx_return_ok)
cout<< "ERROR: get door position failed."<< endl;
if (simxGetObjectOrientation(clientID, doorHandle, -1, doorOri, simx_opmode_oneshot_wait)!=simx_return_ok)
cout<< "ERROR: get door orientation failed."<< endl;
jaco.setKnobPosition(doorPos);
jaco.setKnobOrientation(doorOri);
}
void RemoteApi::motion_planning()
{
jaco.motion_planning();
jaco.follow_path(1);
jaco.approach();
jaco.follow_path(2);
jaco.close_hand();
jaco.open_door();
jaco.follow_path(3);
jaco.push();
jaco.follow_path(4);
jaco.open_hand();
jaco.cross();
jaco.follow_path(6);
}
void RemoteApi::cross()
{
//just to test
float jointMaxPos = 1.57;
simxSetJointPosition(clientID, doorJointHandle, jointMaxPos, simx_opmode_oneshot);
if (simxGetObjectPosition(clientID, goalCameraDummyHandle, -1, goalPos, simx_opmode_oneshot_wait)!=simx_return_ok)
cout<< "ERROR: get goal position failed."<< endl;
goalPos[1]=goalPos[1]+2.2;
goalPos[0]=goalPos[0]-0.1;
simxSetObjectPosition(clientID, goalCameraDummyHandle, -1, goalPos, simx_opmode_oneshot);
path_planning();
path_following();
adjust_orientation();
}
void RemoteApi::return_to_initial_position()
{
jaco.return_to_start_position();
jaco.follow_path(5);
}<file_sep>/lib/cameraCalibration.h
#ifndef CAMERACALIBRATION_H // include guard
#define CAMERACALIBRATION_H
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <opencv/cv.h>
#include <vector>
#include <stdio.h>
#include <iostream>
#include <ctime>
using namespace cv;
using namespace std;
class CameraCalibration
{
private:
Mat frame;
vector<Mat> AllImages;
vector< vector< vector <Point2f> > > allCorners; // vector of all corners detected in all images
vector<vector<int> > allIds; // all ids of all images
Mat cameraMatrix, distCoeffs; //Camera Params
vector <Mat> rvecs, tvecs; //Used in calibration
double repError; // used in calibration
Size imgSize;
int calibrationFlags; //dont especify any CalibrationFlag
float aspectRatio; // Used in calibration
int imageCount;
String output_path;
Ptr<aruco::Dictionary> dictionary;
Ptr<aruco::CharucoBoard> charucoBoard;
public:
CameraCalibration(){
Mat frame;
vector<Mat> AllImages;
vector< vector< vector <Point2f> > > allCorners; // vector of all corners detected in all images
vector<vector<int> > allIds; // all ids of all images
Mat cameraMatrix, distCoeffs; //Camera Params
vector <Mat> rvecs, tvecs; //Used in calibration
double repError =0; // used in calibration
Size imgSize;
int calibrationFlags=0; //dont especify any CalibrationFlag
float aspectRatio=0; // Used in calibration
int imageCount=0;
String ROOT_PATH = "/home/renata/Documents/IC/CalibrationImages/";
String output_path = ROOT_PATH + "resultFile.txt";
Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_4X4_50 );
Ptr<aruco::CharucoBoard> charucoBoard = aruco::CharucoBoard::create(7,7,0.032,0.016,dictionary);
};
// Read .txt file
bool loadCameraCalibration (String resultFile, Mat& cameraMatrix, Mat& distanceCoeff);
// start calibration
bool start_calibration();
// capture the images to start_calibration
void calibrate();
// save the calibration result on a file
bool saveCameraParams();
// draw markers on the webcam view
Mat drawMarkers(Mat image);
// some info displayed before start calibration
void show_info();
// add the images captured on calibration
void add_image(Mat image);
// save the images to an output folder
void save_images_to_folder(string ImagesPath);
// load the paramters of the calibration
bool loadCameraCalibration ();
//getters-setters
Ptr<aruco::Dictionary> get_dictionary();
Ptr<aruco::CharucoBoard> get_charucoBoard();
Mat get_cameraMatrix();
Mat get_distCoeffs();
void set_output_path(String output_path);
String get_output_path();
};
#endif /* CAMERACALIBRATION_H */<file_sep>/lib/marker.h
#ifndef MARKER_H // include guard
#define MARKER_H
#define GLM_ENABLE_EXPERIMENTAL
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <opencv/cv.h>
#include <vector>
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApi.h"
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApiPlatform.h"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
using namespace cv;
using namespace std;
using namespace glm;
class Marker
{
private:
int ID;
Vec3d position, angle;
quat quaternion;
public:
int get_id();
void set_id(int id);
Vec3d get_position();
void set_position(Vec3d position);
Vec3d get_angle();
void set_angle(Vec3d angle);
quat get_quaternion();
void set_quaternion(quat q);
void set_quaternion(Vec3d angle);
vec3 Vec3dtoVec3 (Vec3d source);
void print();
static bool is_in_list(vector<Marker> marker_list, int markerID);
static Marker get_marker_in_list(vector<Marker> marker_list, int markerID);
//constructors
Marker(int id, Vec3d pos, Vec3d ang)
{
ID = id;
position = pos;
angle = ang;
set_quaternion(angle);
}
Marker()
{
ID = -1;
}
};
#endif /* MARKER_H */<file_sep>/lib/cameraCalibration.cpp
#include "cameraCalibration.h"
using namespace cv;
using namespace std;
//Webcam frame
Mat frame;
//Vector of images to calibrate
vector<Mat> mAllImages;
// vector of all corners detected in all images
vector< vector< vector <Point2f> > > mallCorners;
// all ids of all images
vector<vector<int> > mallIds;
//Camera Params
Mat cameraMatrix, mdistCoeffs;
//Used in calibration
vector <Mat> mrvecs, mtvecs;
// used in calibration
double mrepError =0;
// Image Size
Size mimgSize;
//dont especify any CalibrationFlag
int mcalibrationFlags=0;
// Used in calibration
float maspectRatio=0;
// Number of images salved
int mimageCount=0;
// Path to resultFile
String ROOT_PATH = "/home/renata/Documents/IC/CalibrationImages/";
String moutput_path = ROOT_PATH + "result.txt";
// detectorParameters of the arUco markers
Ptr<aruco::DetectorParameters> mdetectorParameters = aruco::DetectorParameters::create();
// vectors of points of the makers
vector< vector < Point2f > > mcorners, mrejected;
// vector to save the ids of the markers of one image
vector <int> mids;
// Dictionary of markers
Ptr<aruco::Dictionary> mdictionary = aruco::getPredefinedDictionary(aruco::DICT_4X4_50);
// Charuco board
Ptr<aruco::CharucoBoard> mcharucoBoard = aruco::CharucoBoard::create(7,5,0.02,0.01,mdictionary);
//all corner and all ids used to calibrate
vector <Mat> mallCharucoCorners, mallCharucoIds;
// ---------------------Getter and setter -------------------------
void CameraCalibration::set_output_path(String output_path)
{
moutput_path = output_path;
return;
}
String CameraCalibration::get_output_path()
{
return moutput_path;
}
Ptr<aruco::Dictionary> CameraCalibration::get_dictionary()
{
return mdictionary;
}
Ptr<aruco::CharucoBoard> CameraCalibration::get_charucoBoard()
{
return mcharucoBoard;
}
Mat CameraCalibration::get_cameraMatrix()
{
return cameraMatrix;
}
Mat CameraCalibration::get_distCoeffs()
{
return mdistCoeffs;
}
bool CameraCalibration::loadCameraCalibration ()
{
FileStorage fs (moutput_path, FileStorage::READ);
if (!fs.isOpened())
return false;
fs["camera_matrix"] >> cameraMatrix;
fs["distortion_coefficients"] >> mdistCoeffs;
return true;
}
// -----------------------------------------------------------------
// print some info to the user before calibration.
void CameraCalibration::show_info()
{
cout<<"Welcome to camera calibration.\n"
<<"INFO:To calibrate using a ChArUco board,"
<<"it is necessary to detect the board from different viewpoints.\n"
<<"Press s to save the webcam image to use on calibration.\n"
<<"After taking more than 5 pictures, press x to stop capturing and start calibration.\n"
<<"Press q to cancel calibration.\n";
}
//Capture the images to calibration.
void CameraCalibration::calibrate()
{
namedWindow ("WebCam", WINDOW_AUTOSIZE);
VideoCapture cap(0);
while (true)
{
cap>>frame;
char key = (char)waitKey(20);
if(key == 'q')
{
save_images_to_folder(ROOT_PATH);
destroyWindow("WebCam");
cout << "Calibration canceled.\n";
return;
}
if(key == 's' )
{
add_image(frame);
}
if(key == 'x')
{
save_images_to_folder(ROOT_PATH);
cout << "Starting calibration.\n";
if (start_calibration())
{
destroyWindow("WebCam");
return;
}
else
{
cout << "Calibration Failed.\n"
<< "Try again or press q to cancel.\n";
}
}
imshow("WebCam", drawMarkers(frame));
}
}
bool CameraCalibration::start_calibration()
{
if ((int)mAllImages.size()<5)
{
cout<< "Not enough images to calibrate\n";
return false;
}
// prepare data for Charuco calibration
int nImages = (int)mallCorners.size();
mallCharucoCorners.reserve(nImages);
mallCharucoIds.reserve(nImages);
for(int i=0; i< nImages; i++)
{
Mat currentCharucoCorners, currentCharucoIds;
aruco::interpolateCornersCharuco(mallCorners[i], mallIds[i], mAllImages[i],
mcharucoBoard, currentCharucoCorners,
currentCharucoIds, cameraMatrix, mdistCoeffs);
mallCharucoCorners.push_back(currentCharucoCorners);
mallCharucoIds.push_back(currentCharucoIds);
}
repError= aruco::calibrateCameraCharuco(mallCharucoCorners,mallCharucoIds,mcharucoBoard,mimgSize,
cameraMatrix, mdistCoeffs, mrvecs, mtvecs, mcalibrationFlags);
bool saveOk = saveCameraParams();
if (saveOk)
cout << "See results in " << moutput_path << endl;
return true;
return false;
}
Mat CameraCalibration::drawMarkers(Mat frame)
{
if (!frame.empty())
{
aruco::detectMarkers(frame, mdictionary, mcorners, mids, mdetectorParameters, mrejected);
aruco::refineDetectedMarkers(frame, mcharucoBoard, mcorners, mids, mrejected);
Mat mcurrentCharucoCorners, mcurrentCharucoIds;
if (mids.size()>0)
{
aruco::interpolateCornersCharuco(mcorners, mids, frame, mcharucoBoard,
mcurrentCharucoCorners, mcurrentCharucoIds);
aruco::drawDetectedMarkers(frame,mcorners);
}
if (mcurrentCharucoCorners.total()>0)
aruco::drawDetectedCornersCharuco(frame,mcurrentCharucoCorners,mcurrentCharucoIds);
return frame;
}
else
cout << "NULL frame\n";
return frame;
}
void CameraCalibration::add_image(Mat frame)
{
cout << "ids.size= "<< mids.size();
cout <<" corners.size= "<< mcorners.size()<< endl;
if((int)mcorners.size()>4) // minimum of identifiable markers
{
mAllImages.push_back (drawMarkers(frame));
mallCorners.push_back(mcorners);
mallIds.push_back(mids);
mimgSize = frame.size ();
cout << "Saved frame\n AllImagesSize=" << mAllImages.size()<< endl;
}
}
void CameraCalibration::save_images_to_folder(string ImagesPath)
{
for(int i=0; i< mAllImages.size(); i++)
{
String file_name = ImagesPath + string("image") + to_string(i) + string(".png");
bool result = imwrite(file_name, mAllImages[i]);
if (!result)
cout << "Image save fail. \n";
}
}
bool CameraCalibration::saveCameraParams()
{
FileStorage fs(moutput_path, FileStorage::WRITE);
cout << "fopen\n";
if(!fs.isOpened())
return false;
time_t tt;
time(&tt);
struct tm *t2 = localtime(&tt);
char buf[1024];
strftime(buf, sizeof(buf) - 1, "%c", t2);
fs << "calibration_time" << buf;
fs << "image_width" << mimgSize.width;
fs << "image_height" << mimgSize.height;
if(mcalibrationFlags & CALIB_FIX_ASPECT_RATIO) fs << "aspectRatio" << maspectRatio;
if(mcalibrationFlags != 0) {
sprintf(buf, "flags: %s%s%s%s",
mcalibrationFlags & CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
mcalibrationFlags & CALIB_FIX_ASPECT_RATIO ? "+fix_aspectRatio" : "",
mcalibrationFlags & CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
mcalibrationFlags & CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "");
}
fs << "flags" << mcalibrationFlags;
fs << "camera_matrix" << cameraMatrix;
fs << "cameraMatrixRows" << cameraMatrix.rows;
fs << "cameraMatrixCols" << cameraMatrix.cols;
fs << "distortion_coefficients" << mdistCoeffs;
fs << "avg_reprojection_error" << mrepError;
fs << "rotation vectors" << mrvecs;
fs << "translation vectors" << mtvecs;
return true;
}
<file_sep>/main.cpp
//Main class. This class will be used to initialize all the system.
#include <stdio.h>
#include "lib/cameraCalibration.cpp"
#include "lib/marker.cpp"
#include "lib/camera.cpp"
#include "lib/remoteapi.cpp"
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <opencv/cv.h>
#include <vector>
#include <iostream>
#include <ctime>
using namespace cv;
using namespace std;
int main (int argc,char *argv[])
{
//verify if there's a file on args. If not, ask if the user wants to do a calibration.
//Start the camera traking - 1 thread
//Start the User interface - 1 thread
//Start the communication with Vrep - 1 thread.
//CameraCalibration cam;
ifstream inFile (argv[1]);
if (!inFile)
{
cout << "There's no calibration file.\n"
<<"Do you want to start Camera Calibration?\n"
<<"Press y to calibrate the Camera\n"
<<"Press n to cancel\n";
char r;
cin>>r;
if (r=='n')
return 0;
if (r=='y')
{
CameraCalibration params;
params.show_info();
params.calibrate();
}
}
else
{
//Load the calibration params
CameraCalibration params;
params.set_output_path(argv[1]);
if (!params.loadCameraCalibration())
{
cout <<"Could not load the calibration params.\n";
}
// Start the maker tracking
Camera cam;
cam.info();
cam.open();
while(cam.get_status())
{
if(cam.is_ready())
{
cam.set_ready(false);
cout << "Ok, user choose to open a door.\n";
cout<<"Please, enter the ID of tag corresponding"
<< " to the door that you want to open\n";
int id=-1;
cin>>id;
if(id!=-1)
{
Marker simTag = cam.get_detectedMarker(id);
RemoteApi simulation;
simulation.set_tag_position(simTag);
simulation.check_collision();
simulation.path_planning();
simulation.path_following();
simulation.adjust_orientation();
simulation.preapre_motion();
simulation.motion_planning();
simulation.cross();
simulation.return_to_initial_position();
cout << "motion planning done"<<endl;
}
}
}
}
terminate();
//now we have to start the thread to find the marker and follow it.
//and the tread to start simulation and follow it.
return 0;
}<file_sep>/lib/camera.h
#ifndef CAMERA_H // include guard
#define CAMERA_H
#define GLM_ENABLE_EXPERIMENTAL
#include <opencv2/opencv.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
#include <opencv/cv.h>
#include <vector>
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApi.h"
#include "/home/renata/V-REP_PRO_EDU_V3_5_0_Linux/programming/remoteApi/extApiPlatform.h"
#include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp>
#include "cameraCalibration.h"
#include "marker.h"
using namespace cv;
using namespace std;
using namespace glm;
class Camera
{
private:
// camera params used to estimate the marker position
CameraCalibration params;
// all marker ids of the frame
vector <int> ids;
// Used to find the position
vector<vector<Point2f> > markerCorners, rejected;
// ARuCo Estimator
vector<vector<Point2f> > EstimateMarker;
// if you want to use some flag, or change the parameters of the search
Ptr<aruco::DetectorParameters> detectorParameters;
// vector of all detectedMarkers of the frames
vector <Marker> detectedMarkers;
// frame of the current corners and IDs detected
Mat currentCharucoCorners, currentCharucoIds;
// size of the markers
float arucoSquareDimension;
//Used to show the webcam image
thread t1;
void startCamera();
bool status;
bool ready;
public:
void open();
void draw_markers(Mat frame);
void add_marker(Mat frame);
bool get_status();
Marker get_detectedMarker(int id);
void info();
bool is_ready();
void set_ready(bool state);
Camera()
{
arucoSquareDimension= 0.12f;
detectorParameters = aruco::DetectorParameters::create();
if(!params.loadCameraCalibration())
{
cout << "Could not read the camera parameters." << endl;
}
status = true;
ready = false;
}
void close();
};
#endif /* MARKER_H */<file_sep>/autodrive.lua
------------------------------------------------------------------------------
-- Following few lines automatically added by V-REP to guarantee compatibility
-- with V-REP 3.1.3 and later:
if (sim_call_type==sim.syscb_init) then
sim.setScriptAttribute(sim.handle_self,sim.childscriptattribute_automaticcascadingcalls,false)
end
if (sim_call_type==sim.syscb_cleanup) then
end
if (sim_call_type==sim.syscb_sensing) then
sim.handleChildScripts(sim_call_type)
end
if (sim_call_type==sim.syscb_actuation) then
if not firstTimeHere93846738 then
firstTimeHere93846738=0
end
sim.setScriptAttribute(sim.handle_self,sim.scriptattribute_executioncount,firstTimeHere93846738)
firstTimeHere93846738=firstTimeHere93846738+1
------------------------------------------------------------------------------
function setAngle(ang) --set ang in ]-PI, PI]
-- input is an angle in radian and return the angle in rad between ]-pi,pi]
while ang>math.pi do
ang=ang-(2*math.pi)--print("while!!")
end
while ang<-math.pi do
ang=ang+(2*math.pi)--print("while!!")
end
return ang
end
function normAngle(ang) --get an angle in rad and returns it in [-pi, pi]
while ang>math.pi do ang=ang-2*math.pi end
while ang<=-math.pi do ang=ang+2*math.pi end
return ang
end
function getAngularDifference(goalAngle,startAngle)
dx=goalAngle-startAngle
if (dx>=0) then
dx=math.mod(dx+math.pi,2*math.pi)-math.pi
else
dx=math.mod(dx-math.pi,2*math.pi)+math.pi
end
return(dx)
end
if (sim.getScriptExecutionCount()==0) then
rad2deg=180/math.pi
deg2rad=math.pi/180
MPI=math.pi
goal=sim.getObjectHandle('p3_goalPos')
lmotorHandle=sim.getObjectHandle('motorLeft')
rmotorHandle=sim.getObjectHandle('motorRight')
robot=sim.getObjectHandle('wheelchairFrame')--body')
vel=0
omega=0
tolHeading=5*deg2rad -- tolerance heading in deg
tolPosition=0.2 -- reaching position tolerance in meter
gainHeading=20--40
gainSpeed=1--10
maxvel= 0.5 -- max linear velocity
maxomega=20*deg2rad -- max angular velocity
kro= 0.6--0.4--1
kalpha=345/823
kbeta=-0.6 -- -0.6-- -2/11
--alpha=0
newTarget=false
tgpos=sim.getObjectPosition(robot,-1)
tgori=sim.getObjectOrientation(robot,-1)
tgpos[3]=tgpos[3]+2.7000e-02 --shift in z to make the goal way up to the current robot pos
--to change if policy change i.e. goal disappear when not in auto mode
sim.setObjectPosition(goal,-1,tgpos)
sim.setObjectOrientation(goal,-1,tgori)
tgpos_old=tgpos
tgori_old=tgori
pathHandle=sim.getObjectHandle('p3_pathPlanningPath')
pathPlanningHandle=simGetPathPlanningHandle('PathPlanningTask')
collidableForPathPlanning=sim.getObjectHandle('p3CollidableForPathPlanning')
obstacles=sim.getCollectionHandle('p3ObstacleCollection')
randomModeUntilTime=0
pathCalculated=0 -- 0=not calculated, 1=beeing calculated, 2=calculated
tempPathSearchObject=-1
currentPosOnPath=0
--model related measures and constants definitions
wheelHandle=sim.getObjectHandle('bigWheelLeft_respondable')
res,zMin=sim.getObjectFloatParameter(wheelHandle,17)
res,zMax=sim.getObjectFloatParameter(wheelHandle,20)
R=(zMax-zMin)/2-- m (wheel radius)
local lw=sim.getObjectPosition(wheelHandle,-1)
local rw=sim.getObjectPosition(sim.getObjectHandle('bigWheelRight_respondable'),-1)
L = math.sqrt((lw[1]-rw[1])^2+(lw[2]-rw[2])^2) -- m (distance between wheels)
nominalVelocity=10--0.996 --EVENTUALLY GETTING FROM THE SLIDER
reachError=0.01
--PID rotation related init
prev_error=0
integral=0
oldtime=sim.getSimulationTime()
Kp=0.1 --mm/s
Ki=0.001--0--0.09
Kd=0.09--0.9--30
--to remove: for test
pathCalculated=0
------
end
sim.handleChildScripts(sim_call_type)
--mode=sim.readCustomDataBlock(robot,'mode')
mode='ptg'
if mode=='ptg' or mode =='lasernav' then
-- main code here
-- checking if the target position changed
targetP=sim.getObjectPosition(goal,-1)
vv={targetP[1]-tgpos[1],targetP[2]-tgpos[2]}
if (math.sqrt(vv[1]*vv[1]+vv[2]*vv[2])>0.01) then
pathCalculated=0 -- We have to recompute the path since the target position has moved
tgpos[1]=targetP[1] ^
tgpos[2]=targetP[2]
--newTarget=true
closeToTarget=false
end
currentTime=sim.getSimulationTime()
if closeToTarget==false then --we are far from the end or we have a new target so we create a path (if any yet)
--and follow it
rightV=0
leftV=0
if (pathCalculated==0) then
-- search for a path
if (sim.checkCollision(obstacles,collidableForPathPlanning)~=1) then -- Make sure we are not colliding when starting to compute the path!
if (tempPathSearchObject~=-1) then
simPerformPathSearchStep(tempPathSearchObject,true) -- delete any previous temporary path search object
end
orientation=sim.getObjectOrientation(robot,-1)
sim.setObjectOrientation(robot,-1,{0,0,orientation[3]}) -- Temporarily set the robot's orientation to be in the plane (the robot can slightly tilt back and forth)
tempPathSearchObject=simInitializePathSearch(pathPlanningHandle,10,0.03) -- search for a maximum of 10 seconds
sim.setObjectOrientation(robot,-1,orientation) -- Set the previous robot's orientation
if (tempPathSearchObject~=-1) then
pathCalculated=1
else sim.addStatusbarMessage('failed to find a path')
end
else
if (currentTime>randomModeUntilTime) then
randomModeUntilTime=currentTime+2 -- 2 seconds in random direction
randomVLeft=(-1+math.random()*2)*nominalVelocity
randomVRight=(-1+math.random()*2)*nominalVelocity
end
end
else
if (pathCalculated==1) then
r=simPerformPathSearchStep(tempPathSearchObject,false)
if (r<1) then
if (r~=-2) then
pathCalculated=0 -- path search failed, try again from the beginning
tempPathSearchObject=-1
end
else
pathCalculated=2 -- we found a path
currentPosOnPath=0
tempPathSearchObject=-1
end
else
l=sim.getPathLength(pathHandle)
r=sim.getObjectPosition(robot,-1)
while true do
p=sim.getPositionOnPath(pathHandle,currentPosOnPath/l)
d=math.sqrt((p[1]-r[1])*(p[1]-r[1])+(p[2]-r[2])*(p[2]-r[2]))
if (d>0.2)or(currentPosOnPath>=l) then
break
end
currentPosOnPath=currentPosOnPath+0.01
end
m=sim.getObjectMatrix(robot,-1)
m=simGetInvertedMatrix(m)
p=sim.multiplyVector(m,p)
-- Now p is relative to the robot
a=math.atan2(p[2],p[1])
if (a>=0)and(a<math.pi*0.5) then
rightV=nominalVelocity
leftV=nominalVelocity*(1-2*a/(math.pi*0.5))
end
if (a>=math.pi*0.5) then
leftV=-nominalVelocity
rightV=nominalVelocity*(1-2*(a-math.pi*0.5)/(math.pi*0.5))
end
if (a<0)and(a>-math.pi*0.5) then
leftV=nominalVelocity
rightV=nominalVelocity*(1+2*a/(math.pi*0.5))
end
if (a<=-math.pi*0.5) then
rightV=-nominalVelocity
leftV=nominalVelocity*(1+2*(a+math.pi*0.5)/(math.pi*0.5))
end
end
end
omega=R*(rightV-leftV)/L
vel=(rightV+leftV)/2
posTg=sim.getObjectPosition(goal,-1)
rotTg=sim.getObjectOrientation(goal,-1)
posRobot=sim.getObjectPosition(robot,-1)
rotRobot=sim.getObjectOrientation(robot,-1)
if math.abs(posTg[1]-posRobot[1])< reachError and math.abs(posTg[2]-posRobot[2])< reachError then
closeToTarget=true -- we then will enter the adjusting orientation only mode
end
print(sim.getSimulationTime(),'autodrive: following path')
else -- linear velocity =0, we just adjust the rotation
print(sim.getSimulationTime(),'autodrive: adjusting orientation')
vel=0
tgori=sim.getObjectOrientation(goal,-1)
curori=sim.getObjectOrientation(robot,-1)
dt=sim.getSimulationTime()-oldtime
dth=getAngularDifference(tgori[3],curori[3])
if math.abs(dth)>0.5*deg2rad then
--calculate the spinning velocity
if dt>0.05 then
error=getAngularDifference(tgori[3],curori[3])
integral=integral+error*dt
derivative=(error- prev_error)/dt
omega = Kp*error +Ki*integral +Kd * derivative
if omega> maxomega then omega=maxomega end
if omega< -maxomega then omega=-maxomega end
prev_error=error
oldtime=sim.getSimulationTime()
end
else
prev_error=0
integral=0
omega=0
dt=0
startTimer=sim.getSimulationTime()
end
end
--[[ controller in Siegward
--sim.addStatusbarMessage('autodrive mode: '..mode)
tgpos=sim.getObjectPosition(goal,-1)
tgori=sim.getObjectOrientation(goal,-1)
if tgpos_old[1]~=tgpos[1] or tgpos_old[2]~=tgpos[2] or tgori_old[1]~=tgori[1] or tgori_old[2]~=tgori[2] then
--here a new goal has been defined
newTarget=true
--else
-- newTarget=false
end
tgpos_old=tgpos
tgori_old=tgori
xg=tgpos[1]
yg=tgpos[2]
thetag=tgori[3]
curpos=sim.getObjectPosition(robot,-1)
curori=sim.getObjectOrientation(robot,-1)
xr=curpos[1] --current x robot
yr=curpos[2] --current y robot
thetar=curori[3] --current theta robot
ro=math.sqrt((xg-xr)^2+(yg-yr)^2)
alpha=setAngle(-thetar + math.atan2(yg-yr,xg-xr))
beta=setAngle(-math.atan2(yg-yr,xg-xr)+ thetag)
--print('ctrl loop:',math.abs(ro)>tolPosition , math.abs(thetag-thetar)>tolHeading)
--print('ro:',math.abs(ro),'dtheta',setAngle(math.abs(setAngle(thetag)-setAngle(thetar)))*180/math.pi)
if math.abs(ro)>tolPosition or setAngle(math.abs(setAngle(thetag)-setAngle(thetar)))>tolHeading then
newTarget=false
--print('\n fresh alpha',alpha)
-- while alpha>math.pi do
-- alpha=alpha-(2*math.pi)
-- --print('alpha SUP PI')
-- end
-- while alpha<-math.pi do
-- alpha=alpha+(2*math.pi)
-- --print('alpha INF PI')
-- end
--
alpha=setAngle(alpha)
-- print(math.abs(thetag-thetar))
--print('\n')
--print('ro',ro,'alpha',alpha*rad2deg,'beta',beta*rad2deg,'thetar',thetar*rad2deg,'thetag',thetag*rad2deg)
--print(' alpha (deg)',alpha*rad2deg, 'beta', beta*rad2deg)
if alpha <-MPI/2 or alpha >=MPI/2 then
ro=-ro
alpha=alpha+MPI
beta=beta+MPI
alpha=setAngle(alpha)
--while alpha>math.pi do alpha=alpha-(2*math.pi)end
--while alpha<-math.pi do alpha=alpha+(2*math.pi)end
--print('in I2: alpha (deg)',alpha*rad2deg, 'beta', beta*rad2deg)
end
vel=kro*ro
omega=kalpha*alpha + kbeta*beta
--sim.addStatusbarMessage('vel '..vel..' omega '..omega..' omega(deg/s) '..omega*rad2deg)
--print('vel',vel,'omega',omega,'omega(deg/s)',omega*rad2deg)
else
if newTarget==false then --robot is paused
--print('ROBOT IS STOPPED')
omega=0
vel=0
--ro=1000
--newTarget=true
end
end
--]]
--print('autodrive',vel, omega)
-- send vel and omega to robot control script
if vel>maxvel then vel=maxvel end
if vel<-maxvel then vel=-maxvel end
if omega>maxomega then omega=maxomega end
if omega<-maxomega then omega=-maxomega end
data=sim.packFloatTable({vel,omega*rad2deg})
sim.setStringSignal('autodrive',data)
end
if (sim.getSimulationState()==sim.simulation_advancing_lastbeforestop) then
print('\n\nEND autodrive')
end
------------------------------------------------------------------------------
-- Following few lines automatically added by V-REP to guarantee compatibility
-- with V-REP 3.1.3 and later:
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Following few lines automatically added by V-REP to guarantee compatibility
-- with V-REP 3.1.3 and later:
if (sim_call_type==sim.syscb_init) then
sim.setScriptAttribute(sim.handle_self,sim.childscriptattribute_automaticcascadingcalls,false)
end
if (sim_call_type==sim.syscb_cleanup) then
end
if (sim_call_type==sim.syscb_sensing) then
sim.handleChildScripts(sim_call_type)
end
if (sim_call_type==sim.syscb_actuation) then
if not firstTimeHere93846738 then
firstTimeHere93846738=0
end
sim.setScriptAttribute(sim.handle_self,sim.scriptattribute_executioncount,firstTimeHere93846738)
firstTimeHere93846738=firstTimeHere93846738+1
------------------------------------------------------------------------------
function goalChanged() -- return true if the goal position changed else false
if math.abs(tgpos_old[1]-tgpos[1])>0.001 or
math.abs(tgpos_old[2]-tgpos[2])>0.001 or
math.abs(tgori_old[3]-tgori[3])>0.1*deg2rad then
return true
else
return false
end
end
function setAngle(ang) --set ang in ]-PI, PI]
-- input is an angle in radian and return the angle in rad between ]-pi,pi]
while ang>math.pi do
ang=ang-(2*math.pi)--print("while!!")
end
while ang<-math.pi do
ang=ang+(2*math.pi)--print("while!!")
end
return ang
end
if (sim.getScriptExecutionCount()==0) then
-- initialize objects
motorR = sim.getObjectHandle('motorRight')
motorL = sim.getObjectHandle('motorLeft')
robot = sim.getObjectHandle('wheelchair_shape')
path_handle = sim.getObjectHandle('Path')
path_plan_handle=simGetPathPlanningHandle('PathPlanningTask0')
start_dummy_handle = sim.getObjectHandle('wheelchairFrame')
goal = sim.getObjectHandle('p3_goalPos')
wheelHandle=sim.getObjectHandle('bigWheelLeft_respondable')
res,zMin=sim.getObjectFloatParameter(wheelHandle,17)
res,zMax=sim.getObjectFloatParameter(wheelHandle,20)
R=(zMax-zMin)/2-- m (wheel radius)
next_point =0
dist = 0 -- dist from the robot to the point on the path
--some constants
MPI=math.pi
rad2deg=180/MPI
deg2rad=MPI/180
--model related measures and constants definitions
L = 0.6403 -- m (distance between wheels)
maxLinVel=0.5 --linear velocity in m/s
maxAngVel=220 --deg/sec (3.876ยจrad/sec)
maxomega=20*deg2rad
nominalVelocity=2.5--0.996 --EVENTUALLY GETTING FROM THE SLIDER
-- Path panning
planstate=simSearchPath(path_plan_handle,10)
if (planstate == 0) then
print('Could not find the path!!'..planstate)
end
-- Follow the path.
l=sim.getPathLength(path_handle)
path_pos = sim.getPositionOnPath(path_handle, next_point) -- pos_on_path [0-1]
path_ori = sim.getOrientationOnPath(path_handle, next_point)
sim.setObjectPosition(start_dummy_handle, -1, path_pos) -- put the robot in the start of the path
sim.setObjectOrientation(start_dummy_handle, -1, path_ori) -- ajust the robot orientation on the start
next_point = next_point + 0.1
sim.setObjectPosition(goal, -1,sim.getPositionOnPath(path_handle, next_point))
sim.setObjectOrientation(goal, -1, sim.getOrientationOnPath(path_handle, next_point))
-- First, adjust the orientation of the robot to make the path follow simplier.
--angular postion of the path.
dist_angle = sim.getObjectOrientation(path_handle, robot)
-- PID Control linear velocity.
prev_error=0
integral=0
oldtime=sim.getSimulationTime()
Kp=0.15 --mm/s
Ki=0.00--0--0.09
Kd=0.08--0.9--30
vcorr =0
curPos = sim.getObjectPosition(robot, -1)
targetPos = sim.getObjectPosition(goal, robot)
dist = math.sqrt(targetPos[1]*targetPos[1]+targetPos[2]*targetPos[2])
--print("dist = ".. dist)
while(next_point<1) do
print("next_point = "..next_point)
-- current position/distance
curPos = sim.getObjectPosition(robot, -1)
curOri = sim.getObjectOrientation(robot, -1)
next_point = sim.getClosestPositionOnPath(path_handle, curPos)
sim.setObjectPosition(goal, -1,sim.getPositionOnPath(path_handle, next_point))
targetPos = sim.getObjectPosition(goal, robot)
targetOri = sim.getObjectOrientation(goal, -1)
dist = math.sqrt(targetPos[1]*targetPos[1]+targetPos[2]*targetPos[2])
dist_ang = targetOri[3]-curOri[3]
dt=sim.getSimulationTime()-oldtime
-- print("dt = ".. dt)
if(dist>0.1) then
if (dt>=0.05) then
-- calculate the velocity
error= dist
integral=integral+error*dt
derivative=(error- prev_error)/dt
vcorr = Kp*error +Ki*integral +Kd*derivative
if vcorr> nominalVelocity then vcorr=nominalVelocity end
if vcorr< -nominalVelocity then vcorr=-nominalVelocity end
prev_error=error
oldtime=sim.getSimulationTime()
else
prev_error=0
integral=0
omega=0
dt=0
startTimer=sim.getSimulationTime()
print(startTimer)
end
-- update velocity
vr = nominalVelocity + vcorr
vl = nominalVelocity - vcorr
omega=R*(vr-vl)/L
vel=(vl+vr)/2
else
print("Close to the target")
vl = nominalVelocity
vr = nominalVelocity
end
-- print("vr = "..vr)
-- print("vl = " ..vl)
end
velold=vel
omegaold=omega
data=sim.packFloatTable({vel,omega*rad2deg})
if data~=dataold then
sim.setStringSignal('autodrive',data)
-- sim.addStatusbarMessage(sim.getSimulationTime()..' vel '..vel..' omega '..omega*rad2deg)
dataold=data
end
if (sim.getSimulationState()==sim.simulation_advancing_lastbeforestop) then
print('\n\nEND autodrive')
end
end
------------------------------------------------------------------------------
-- Following few lines automatically added by V-REP to guarantee compatibility
-- with V-REP 3.1.3 and later:
end
------------------------------------------------------------------------------
function sysCall_threadmain()
-- initialize objects
motorR = sim.getObjectHandle('motorRight')
motorL = sim.getObjectHandle('motorLeft')
robot = sim.getObjectHandle('wheelchair_shape')
path_handle = sim.getObjectHandle('Path')
path_plan_handle=simGetPathPlanningHandle('PathPlanningTask0')
start_dummy_handle = sim.getObjectHandle('wheelchairFrame')
goal = sim.getObjectHandle('p3_goalPos')
wheelHandle=sim.getObjectHandle('bigWheelLeft_respondable')
res,zMin=sim.getObjectFloatParameter(wheelHandle,17)
res,zMax=sim.getObjectFloatParameter(wheelHandle,20)
R=(zMax-zMin)/2-- m (wheel radius)
next_point =0
dist = 0 -- dist from the robot to the point on the path
--some constants
MPI=math.pi
rad2deg=180/MPI
deg2rad=MPI/180
--model related measures and constants definitions
L = 0.6403 -- m (distance between wheels)
maxLinVel=0.5 --linear velocity in m/s
maxAngVel=220 --deg/sec (3.876ยจrad/sec)
maxomega=20*deg2rad
nominalVelocity=2.5--0.996 --EVENTUALLY GETTING FROM THE SLIDER
function setAngle(ang) --set ang in ]-PI, PI]
-- input is an angle in radian and return the angle in rad between ]-pi,pi]
while ang>math.pi do
ang=ang-(2*math.pi)--print("while!!")
end
while ang<-math.pi do
ang=ang+(2*math.pi)--print("while!!")
end
return ang
end
function normAngle(ang) --get an angle in rad and returns it in [-pi, pi]
while ang>math.pi do ang=ang-2*math.pi end
while ang<=-math.pi do ang=ang+2*math.pi end
return ang
end
function getAngularDifference(goalAngle,startAngle)
dx=goalAngle-startAngle
if (dx>=0) then
dx=math.mod(dx+math.pi,2*math.pi)-math.pi
else
dx=math.mod(dx-math.pi,2*math.pi)+math.pi
end
return(dx)
end
data=sim.getStringSignal('autodrive')
end
function sysCall_cleanup()
-- Put some clean-up code here
end
-- ADDITIONAL DETAILS:
-- -------------------------------------------------------------------------
-- If you wish to synchronize a threaded loop with each simulation pass,
-- enable the explicit thread switching with
--
-- sim.setThreadAutomaticSwitch(false)
--
-- then use
--
-- sim.switchThread()
--
-- When you want to resume execution in next simulation step (i.e. at t=t+dt)
--
-- sim.switchThread() can also be used normally, in order to not waste too much
-- computation time in a given simulation step
-- -------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Following few lines automatically added by V-REP to guarantee compatibility
-- with V-REP 3.1.3 and later:
if (sim_call_type==sim.syscb_init) then
sim.setScriptAttribute(sim.handle_self,sim.childscriptattribute_automaticcascadingcalls,false)
end
if (sim_call_type==sim.syscb_cleanup) then
end
if (sim_call_type==sim.syscb_sensing) then
sim.handleChildScripts(sim_call_type)
end
if (sim_call_type==sim.syscb_actuation) then
if not firstTimeHere93846738 then
firstTimeHere93846738=0
end
sim.setScriptAttribute(sim.handle_self,sim.scriptattribute_executioncount,firstTimeHere93846738)
firstTimeHere93846738=firstTimeHere93846738+1
------------------------------------------------------------------------------
-- initialize objects
motorR = sim.getObjectHandle('motorRight')
motorL = sim.getObjectHandle('motorLeft')
robot = sim.getObjectHandle('wheelchair_shape')
path_handle = sim.getObjectHandle('Path')
path_plan_handle=simGetPathPlanningHandle('PathPlanningTask0')
start_dummy_handle = sim.getObjectHandle('wheelchairFrame')
goal = sim.getObjectHandle('p3_goalPos')
wheelHandle=sim.getObjectHandle('bigWheelLeft_respondable')
res,zMin=sim.getObjectFloatParameter(wheelHandle,17)
res,zMax=sim.getObjectFloatParameter(wheelHandle,20)
R=(zMax-zMin)/2-- m (wheel radius)
next_point =0
dist = 0 -- dist from the robot to the point on the path
--some constants
MPI=math.pi
rad2deg=180/MPI
deg2rad=MPI/180
--model related measures and constants definitions
L = 0.6403 -- m (distance between wheels)
maxLinVel=0.5 --linear velocity in m/s
maxAngVel=220 --deg/sec (3.876ยจrad/sec)
maxomega=20*deg2rad
nominalVelocity=2.5--0.996 --EVENTUALLY GETTING FROM THE SLIDER
-- Path panning
planstate=simSearchPath(path_plan_handle,10)
if (planstate == 0) then
print('Could not find the path!!'..planstate)
end
-- Follow the path.
l=sim.getPathLength(path_handle)
path_pos = sim.getPositionOnPath(path_handle, next_point) -- pos_on_path [0-1]
path_ori = sim.getOrientationOnPath(path_handle, next_point)
sim.setObjectPosition(start_dummy_handle, -1, path_pos) -- put the robot in the start of the path
sim.setObjectOrientation(start_dummy_handle, -1, path_ori) -- ajust the robot orientation on the start
next_point = next_point + 0.1
sim.setObjectPosition(goal, -1,sim.getPositionOnPath(path_handle, next_point))
sim.setObjectOrientation(goal, -1, sim.getOrientationOnPath(path_handle, next_point))
while(next_point<1) do
print("next_point = "..next_point)
-- current position/distance
curPos = sim.getObjectPosition(robot, -1)
curOri = sim.getObjectOrientation(robot, -1)
next_point = sim.getClosestPositionOnPath(path_handle, curPos)
sim.setObjectPosition(goal, -1,sim.getPositionOnPath(path_handle, next_point))
targetPos = sim.getObjectPosition(goal, robot)
targetOri = sim.getObjectOrientation(goal, -1)
dist = math.sqrt(targetPos[1]*targetPos[1]+targetPos[2]*targetPos[2])
dist_ang = targetOri[3]-curOri[3]
-- print("dt = ".. dt)
-- calculate the velocity by autodrive
data=sim.getStringSignal('autodrive')
-- update velocity
if data ~=nil then
param=sim.unpackFloatTable(data)
vel=param[1]
omega=param[2]
-- update velocities
vl = vel - (L/2*omega*MPI/180.)/(R);
vr = vel + (L/2*omega*MPI/180.)/(R);
RICR=L/2 *(vr+vl)/(vr-vl)
sim.setJointTargetVelocity(motorR,vl)
sim.setJointTargetVelocity(motorL,vr)
-- print("vr = "..vr)
-- print("vl = " ..vl)
end
end
sim.setJointTargetVelocity(motorR,0)
sim.setJointTargetVelocity(motorL,0)
print("Path is over!!!")
end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Following few lines automatically added by V-REP to guarantee compatibility
-- with V-REP 3.1.3 and later:
-- show target moving
function setAngle(ang) --set ang in ]-PI, PI]
-- input is an angle in radian and return the angle in rad between ]-pi,pi]
while ang>math.pi do ang=ang-(2*math.pi)print("while!!")end
while ang<-math.pi do ang=ang+(2*math.pi)print("while!!")end
return ang
end
function sysCall_init()
rad2deg=180/math.pi
deg2rad=math.pi/180
MPI=math.pi
goal=sim.getObjectHandle('p3_goalPos')
lmotorHandle=sim.getObjectHandle('motorLeft')
rmotorHandle=sim.getObjectHandle('motorRight')
roomba=sim.getObjectHandle('wheelchairFrame')--body')
vel=0
omega=0
tolHeading=5*deg2rad -- tolerance heading in deg
tolPosition=0.02 -- reaching position tolerance in meter
gainHeading=200--40
gainSpeed=1--10
maxvel= 0.5
kro=0.4-- 2/11
kalpha=345/823
kbeta=-0.6-- -2/11
--alpha=0
newTarget=false
tgpos=sim.getObjectPosition(roomba,-1)
tgori=sim.getObjectOrientation(roomba,-1)
tgpos[3]=tgpos[3]+100 --shift in z to make the goal way up to the current robot pos
--to change if policy change i.e. goal disappear when not in auto mode
sim.setObjectPosition(goal,-1,tgpos)
sim.setObjectOrientation(goal,-1,tgori)
tgpos_old=tgpos
tgori_old=tgori
end
function sysCall_actuation()
tgpos=sim.getObjectPosition(goal,-1)
tgori=sim.getObjectOrientation(goal,-1)
if tgpos_old[1]~=tgpos[1] or tgpos_old[2]~=tgpos[2] or tgori_old[1]~=tgori[1] or tgori_old[2]~=tgori[2] then
--here a new goal has been defined
newTarget=true
end
tgpos_old=tgpos
tgori_old=tgori
xg=tgpos[1]
yg=tgpos[2]
thetag=tgori[3]
curpos=sim.getObjectPosition(roomba,-1)
curori=sim.getObjectOrientation(roomba,-1)
xr=curpos[1] --current x robot
yr=curpos[2] --current y robot
thetar=curori[3] --current theta robot
ro=math.sqrt((xg-xr)^2+(yg-yr)^2)
alpha=setAngle(-thetar + math.atan2(yg-yr,xg-xr))
beta=setAngle(-math.atan2(yg-yr,xg-xr)+ thetag)
print('ctrl loop:',math.abs(ro)>tolPosition , math.abs(thetag-thetar)>tolHeading,math.abs(ro)>tolPosition or math.abs(thetag-thetar)>tolHeading)
print('ro:',math.abs(ro))
if math.abs(ro)>tolPosition or setAngle(math.abs(setAngle(thetag)-setAngle(thetar)))>tolHeading then
newTarget=false
--print('\n fresh alpha',alpha)
alpha=setAngle(alpha)
print(math.abs(thetag-thetar))
--print('\n')
--print('ro',ro,'alpha',alpha*rad2deg,'beta',beta*rad2deg,'thetar',thetar*rad2deg,'thetag',thetag*rad2deg)
--print(' alpha (deg)',alpha*rad2deg, 'beta', beta*rad2deg)
if alpha <-MPI/2 or alpha >=MPI/2 then
ro=-ro
alpha=alpha+MPI
beta=beta+MPI
alpha=setAngle(alpha)
print('in I2: alpha (deg)',alpha*rad2deg, 'beta', beta*rad2deg)
end
vel=kro*ro
omega=kalpha*alpha + kbeta*beta
--print('vel',vel,'omega',omega,'omega(deg/s)',omega*rad2deg)
else
if newTarget==false then --robot is paused
print('ROBOT IS STOPPED')
omega=0
vel=0
--ro=1000
--newTarget=true
end
end
-- send vel and omega to the motors here
data=sim.packFloatTable({vel,omega*rad2deg})
sim.setStringSignal('autodrive',data)
end
function sysCall_cleanup()
print('\n\nEND autodrive')
end
6.1755e-1
8.7352e-1
1.0234e+0
if (pathCalculated==1) then
print("path")
r=simPerformPathSearchStep(tempPathSearchObject,false)
if (r<1) then
if (r~=-2) then
pathCalculated=0 -- path search failed, try again from the beginning
tempPathSearchObject=-1
end
else
print("We've find a path")
c=2 -- we found a path
currentPosOnPath=0
tempPathSearchObject=-1
sim.setObjectPosition(robot,-1, sim.getPositionOnPath(pathHandle,currentPosOnPath))
sim.setObjectOrientation(robot, -1, sim.getOrientationOnPath(pathHandle,currentPosOnPath))
end
end
<file_sep>/lib/camera.cpp
#include "camera.h"
#include "cameraCalibration.h"
using namespace cv;
using namespace std;
CameraCalibration params;
vector <int> ids;
vector<vector<Point2f> > markerCorners, rejected;
vector<vector<Point2f> > EstimateMarker;
Ptr<aruco::DetectorParameters> detectorParameters;
vector <Marker> detectedMarkers;
Mat currentCharucoCorners, currentCharucoIds;
Mat image;
bool status = true;
bool ready= false;
float arucoSquareDimension =0.135f;
bool Camera::get_status()
{
return status;
}
bool Camera::is_ready()
{
return ready;
}
void Camera::set_ready(bool state)
{
ready = state;
}
Marker Camera::get_detectedMarker(int id)
{
return Marker::get_marker_in_list(detectedMarkers, id);
}
void Camera::startCamera()
{
VideoCapture cap(0);
namedWindow ("WebCam", WINDOW_AUTOSIZE);
while(true)
{
char key = (char)waitKey(30);
if(key == 'q')
{
destroyWindow("WebCam");
cout << "Camera Closed.\n";
status=false;
return;
}
if(key == 'y')
{
ready = true;
}
cap>>image;
draw_markers(image);
imshow("WebCam", image);
}
}
void Camera::draw_markers(Mat frame)
{
if (!frame.empty())
{
aruco::detectMarkers(frame, params.get_dictionary(), markerCorners, ids, detectorParameters, rejected);
aruco::refineDetectedMarkers(frame, params.get_charucoBoard(), markerCorners, ids, rejected);
Mat currentCharucoCorners, currentCharucoIds;
if (ids.size()>0)
{
aruco::interpolateCornersCharuco(markerCorners, ids, frame, params.get_charucoBoard(),
currentCharucoCorners, currentCharucoIds);
aruco::drawDetectedMarkers(frame,markerCorners);
add_marker(frame);
}
if (currentCharucoCorners.total()>0)
aruco::drawDetectedCornersCharuco(frame,currentCharucoCorners,currentCharucoIds);
}
else
cout << "NULL frame\n";
}
void Camera::add_marker(Mat frame)
{
vector<Vec3d> AngleVector;
vector<Vec3d> DistanceVector;
for(int i =0; i<ids.size();i++)
{
aruco:: estimatePoseSingleMarkers(markerCorners, arucoSquareDimension, params.get_cameraMatrix(),
params.get_distCoeffs(), AngleVector, DistanceVector);
if(!Marker::is_in_list(detectedMarkers, ids[i]))
{
Marker new_marker(ids[i], DistanceVector[i], AngleVector[i]);
aruco::drawAxis(frame, params.get_cameraMatrix(), params.get_distCoeffs(),
new_marker.get_angle(), new_marker.get_position(), 0.01f);
detectedMarkers.push_back(new_marker);
cout << "There is a new door on the way."<<endl
<< "If you want to open it, please press y." <<endl
<< "If you don't, just continue moving." <<endl;
new_marker.print();
}
}
}
void Camera::open()
{
thread mt1(&Camera::startCamera, this);
mt1.detach();
}
void Camera::info()
{
cout<< "Now the chair is in the manual control state." <<endl
<<"The user can move through the room." << endl
<<"If any door is found on the way "
<<"the user will be asked if he wants to open or keep moving."<< endl
<<"Press q to cancel the movement and close the camera." << endl;
}<file_sep>/README.md
# wheelchair-control
Project structure:
build/ : Directory containing the build instructions of the project.
lib/ : All object source and header files. The wheelchair control is formed by: - A camera object to handle the image captured by the webcam. - A maker object to handle the door detection and tracking. - A camera calibration object to do the calibration when needed.
main.cpp: responsable for door detection and start simulation. Requires a camera calibration file. If it's not present, the user has the option to do the calibration.
Example of running: ./Main cameraFile.txt
| cd8f0a2afb4f332dda987444fcf4d723aa32114d | [
"Markdown",
"CMake",
"C++",
"Lua"
] | 15 | CMake | renatavillegas/wheelchair-control | c2f22fd2b2ae81747662d3a57e13f2c202f01150 | 799583e6ee094030f3f87fd1ea8f6d231b0dceb2 |
refs/heads/master | <file_sep><?php
$connect = mysqli_connect('localhost', 'root', '', 'artur');
$query =
<<<SQL
select
users.id,
parents.id as parent_id,
users.name,
users.surname
from users as users
left join users as parents
on users.referred_by = parents.affiliate_id
SQL;
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$sub_data["id"] = $row["id"];
$sub_data["name"] = $row["name"];
// $sub_data["surname"] = $row["surname"];
// $sub_data["inn"] = $row["inn"];
$sub_data["parent_id"] = $row["parent_id"];
$sub_data["text"] = $row["name"]." ".$row["surname"];
//$sub_data["referral_full_name"] = $row["referral_full_name"];
$data[] = $sub_data;
}
foreach($data as $key => &$value)
{
$output[$value["id"]] = &$value;
}
foreach($data as $key => &$value)
{
if($value["parent_id"] && isset($output[$value["parent_id"]]))
{
$output[$value["parent_id"]]["nodes"][] = &$value;
}
}
foreach($data as $key => &$value)
{
if($value["parent_id"] && isset($output[$value["parent_id"]]))
{
unset($data[$key]);
}
}
//echo '<pre>';
echo json_encode($data);
//echo '<pre>';
/*echo "Hi";
*/
/*
echo '<pre>';
print_r($data);
echo '</pre>';
*/
| 08f7ee733f92e16fe235f22cc5c70f609ce3d0c7 | [
"PHP"
] | 1 | PHP | AKostyushko/treeview | bddeb4239960784a19b366034666d558068ed8de | c72caaadc13953019ce494c3b4fdfce3c90fa933 |
refs/heads/master | <file_sep>import Cache
import string
import os
import time
import sys
class SplitCache:
#define the init class with variables
def __init__(self, blockno, wordsinblock, fileloc):
mem = []
with open(fileloc) as f:
lines = f.readlines()
for line in lines:
token = string.split(string.lower(line))
if token[0] != 'go':
mem.append((int(token[1]), int(token[0], 0)))
self.codeCache = Cache.Cache(mem, blockno, wordsinblock)
self.dataCache = Cache.Cache(mem, blockno, wordsinblock)
<file_sep>import Cache
import string
class UnifiedCache:
def __init__(self,no_of_blocks,words_per_block,codefilepath):
mem = []
with open(codefilepath) as f:
lines = f.readlines()
for line in lines:
token = string.split(string.lower(line))
if token[0] !='go':
mem.append((int(token[1]), int(token[0],0)))
self.Cache = Cache.Cache(mem,no_of_blocks,words_per_block)<file_sep>import string, Cache, math
class multiLevelCache:
def __init__(self, no_of_blocks, words_per_block, codefilepath):
mem = []
with open(codefilepath) as f:
lines = f.readlines()
for line in lines:
token = string.split(string.lower(line))
if token[0] != 'go':
mem.append((int(token[1]), int(token[0], 0)))
self.no_of_blocks = no_of_blocks
self.wordbits = int(math.log(words_per_block, 2))
self.words_per_block = words_per_block
self.cache = [[0] * words_per_block] * no_of_blocks
self.l2Cache = Cache.Cache(mem, no_of_blocks, words_per_block)
self.capacityMissCount = 0
self.compulsoryMissCount = 0
self.conflictMissCount = 0
self.hitCount = 0
def isFull(self):
for row in self.cache:
for col in row:
if (col == 0):
return False
return True
def load(self, address):
blockIndex = (address >> self.wordbits) & (self.no_of_blocks - 1)
wordIndex = address & (self.words_per_block - 1)
addr = address / (self.no_of_blocks * self.words_per_block)
self.cache[blockIndex][wordIndex] = { addr : self.l2Cache.get(address)}
return self.cache[blockIndex][wordIndex].get(addr)
def get(self, address):
blockIndex = (address >> self.wordbits) & (self.no_of_blocks - 1)
wordIndex = address & (self.words_per_block - 1)
addr = address / (self.no_of_blocks * self.words_per_block)
elem = self.cache[blockIndex][wordIndex]
if (elem != 0 and elem.get(addr, None) != None):
self.hitCount += 1
return elem[addr]
else:
if (elem == 0):
self.compulsoryMissCount += 1
if (elem != 0 and self.isFull()):
self.capacityMissCount += 1
elif (elem != 0):
self.conflictMissCount += 1
elem = self.load(address)
return elem
def printCache(self):
return 'L1 Cache Capacity ' + str(self.no_of_blocks) + '*' + str(self.words_per_block) + ' Hit Count ' + str(
self.hitCount) + \
' miss count = ' + str(
self.compulsoryMissCount + self.capacityMissCount + self.conflictMissCount) + ' Compulsory Misses = ' + str(
self.compulsoryMissCount) + ' Conflict Misses = ' + str(
self.conflictMissCount) + ' Capacity Misses = ' + str(self.capacityMissCount) + '\n L2 Cache Capacity ' + str(self.l2Cache.no_of_blocks) + '*' + str(self.l2Cache.words_per_block) + ' Hit Count ' + str(
self.l2Cache.hitCount) + \
' miss count = ' + str(
self.l2Cache.compulsoryMissCount + self.l2Cache.capacityMissCount + self.l2Cache.conflictMissCount) + ' Compulsory Misses = ' + str(
self.l2Cache.compulsoryMissCount) + ' Conflict Misses = ' + str(
self.l2Cache.conflictMissCount) + ' Capacity Misses = ' + str(self.l2Cache.capacityMissCount)<file_sep>#! python
# (c) DL, UTA, 2009 - 2016
import sys, string, time
import UnifiedCache
import SplitCache
import MultiwaysetCache
import MultiLevel
wordsize = 24 # everything is a word
numregbits = 3 # actually +1, msb is indirect bit
opcodesize = 5
addrsize = wordsize - (opcodesize+numregbits+1) # num bits in address
memloadsize = 1024 # change this for larger programs
numregs = 2**numregbits
regmask = (numregs*2)-1 # including indirect bit
addmask = (2**(wordsize - addrsize)) -1
nummask = (2**(wordsize))-1
opcposition = wordsize - (opcodesize + 1) # shift value to position opcode
reg1position = opcposition - (numregbits +1) # first register position
reg2position = reg1position - (numregbits +1)
memaddrimmedposition = reg2position # mem address or immediate same place as reg2
realmemsize = memloadsize * 1 # this is memory size, should be (much) bigger than a program
#memory management regs
codeseg = numregs - 1 # last reg is a code segment pointer
dataseg = numregs - 2 # next to last reg is a data segment pointer
#ints and traps
trapreglink = numregs - 3 # store return value here
trapval = numregs - 4 # pass which trap/int
mem = [0] * realmemsize # this is memory, init to 0
reg = [0] * numregs # registers
clock = 1 # clock starts ticking
ic = 0 # instruction count
numcoderefs = 0 # number of times instructions read
numdatarefs = 0 # number of times data read
starttime = time.time()
curtime = starttime
# cache = UnifiedCache.UnifiedCache(4,2,'a1.out')
# cache = MultiwaysetCache.MultiwaysetCache(4,4,'a.out',2)
cache = MultiLevel.multiLevelCache(4,4,'a2.out')
# cache = SplitCache.SplitCache(4,2,'a2.out')
def startexechere ( p ):
# start execution at this address
reg[ codeseg ] = p
def getcodemem ( a ):
# get code memory at this address
if hasattr(cache,'codeCache'):
memval = cache.codeCache.get(a + reg[ codeseg ]) # Split Cache
else:
if hasattr(cache, 'get'):
memval = cache.get(a + reg[codeseg])
else:
memval = cache.Cache.get(a + reg[codeseg]) # normal cache
return ( memval )
def getdatamem ( a ):
# get code memory at this address
if hasattr(cache, 'dataCache'):
memval = cache.dataCache.get(a + reg[ dataseg ]) # Split Cache
else:
if hasattr(cache, 'get'):
memval = cache.get(a + reg[codeseg])
else:
memval = cache.Cache.get(a + reg[dataseg]) # normal cache
return ( memval )
def getregval ( r ):
# get reg or indirect value
if ( (r & (1<<numregbits)) == 0 ): # not indirect
rval = reg[ r ]
else:
rval = getdatamem( reg[ r - numregs ] ) # indirect data with mem address
return ( rval )
def checkres( v1, v2, res):
v1sign = ( v1 >> (wordsize - 1) ) & 1
v2sign = ( v2 >> (wordsize - 1) ) & 1
ressign = ( res >> (wordsize - 1) ) & 1
if ( ( v1sign ) & ( v2sign ) & ( not ressign ) ):
return ( 1 )
elif ( ( not v1sign ) & ( not v2sign ) & ( ressign ) ):
return ( 1 )
else:
return( 0 )
def dumpstate ( d ):
if ( d == 1 ):
print reg
elif ( d == 2 ):
print mem
elif ( d == 3 ):
print 'clock=', clock, 'IC=', ic, 'Coderefs=', numcoderefs,'Datarefs=', numdatarefs, 'Start Time=', starttime, 'Currently=', time.time()
elif ( d == 4 ):
if hasattr(cache, 'codeCache'):
print 'code Cache=',cache.codeCache.printCache(),'\n', 'data Cache=',cache.dataCache.printCache()
else:
if hasattr(cache,'printCache'):
print cache.printCache()
else: print 'Cache= ', cache.Cache.printCache()
def trap ( t ):
# unusual cases
# trap 0 illegal instruction
# trap 1 arithmetic overflow
# trap 2 sys call
# trap 3+ user
rl = trapreglink # store return value here
rv = trapval
if ( ( t == 0 ) | ( t == 1 ) ):
dumpstate( 1 )
dumpstate( 2 )
dumpstate( 3 )
dumpstate( 4 )
elif ( t == 2 ): # sys call, reg trapval has a parameter
what = reg[ trapval ]
if ( what == 1 ):
a = a #elapsed time
return ( -1, -1 )
return ( rv, rl )
# opcode type (1 reg, 2 reg, reg+addr, immed), mnemonic
opcodes = { 1: (2, 'add'), 2: ( 2, 'sub'),
3: (1, 'dec'), 4: ( 1, 'inc' ),
7: (3, 'ld'), 8: (3, 'st'), 9: (3, 'ldi'),
12: (3, 'bnz'), 13: (3, 'brl'),
14: (1, 'ret'),
16: (3, 'int') }
startexechere( 0 ) # start execution here if no "go"
# loadmem() # load binary executable
ip = 0 # start execution at codeseg location 0
# while instruction is not halt
while( 1 ):
ir = getcodemem( ip ) # - fetch
ip = ip + 1
opcode = ir >> opcposition # - decode
reg1 = (ir >> reg1position) & regmask
reg2 = (ir >> reg2position) & regmask
addr = (ir) & addmask
ic = ic + 1
# - operand fetch
if not (opcodes.has_key( opcode )):
tval, treg = trap(0)
if (tval == -1): # illegal instruction
break
memdata = 0 # contents of memory for loads
if opcodes[ opcode ] [0] == 1: # dec, inc, ret type
operand1 = getregval( reg1 ) # fetch operands
elif opcodes[ opcode ] [0] == 2: # add, sub type
operand1 = getregval( reg1 ) # fetch operands
operand2 = getregval( reg2 )
elif opcodes[ opcode ] [0] == 3: # ld, st, br type
operand1 = getregval( reg1 ) # fetch operands
operand2 = addr
elif opcodes[ opcode ] [0] == 0: # ? type
break
if (opcode == 7): # get data memory for loads
memdata = getdatamem( operand2 )
# execute
if opcode == 1: # add
result = (operand1 + operand2) & nummask
if ( checkres( operand1, operand2, result )):
tval, treg = trap(1)
if (tval == -1): # overflow
break
elif opcode == 2: # sub
result = (operand1 - operand2) & nummask
if ( checkres( operand1, operand2, result )):
tval, treg = trap(1)
if (tval == -1): # overflow
break
elif opcode == 3: # dec
result = operand1 - 1
elif opcode == 4: # inc
result = operand1 + 1
elif opcode == 7: # load
result = memdata
elif opcode == 9: # load immediate
result = operand2
elif opcode == 12: # conditional branch
result = operand1
if result <> 0:
ip = operand2
elif opcode == 13: # branch and link
result = ip
ip = operand2
elif opcode == 14: # return
ip = operand1
elif opcode == 16: # interrupt/sys call
result = ip
tval, treg = trap(reg1)
if (tval == -1):
break
reg1 = treg
ip = operand2
# write back
if ( (opcode == 1) | (opcode == 2 ) |
(opcode == 3) | (opcode == 4 ) ): # arithmetic
reg[ reg1 ] = result
elif ( (opcode == 7) | (opcode == 9 )): # loads
reg[ reg1 ] = result
elif (opcode == 13): # store return address
reg[ reg1 ] = result
elif (opcode == 16): # store return address
reg[ reg1 ] = result
# end of instruction loop
# end of execution
<file_sep>import math
class Cache:
def __init__(self,mem,no_of_blocks,words_per_block):
self.mem = mem
self.no_of_blocks = no_of_blocks
self.wordbits = int(math.log(words_per_block, 2))
self.words_per_block = words_per_block
self.cache = [[0]*words_per_block]*no_of_blocks
self.capacityMissCount = 0
self.compulsoryMissCount = 0
self.conflictMissCount = 0
self.hitCount = 0
def isFull(self):
for row in self.cache:
for col in row:
if(col ==0):
return False
return True
def load(self,address):
blockIndex = (address >> self.wordbits) & (self.no_of_blocks - 1)
wordIndex = address & (self.words_per_block - 1)
addr = address / (self.no_of_blocks*self.words_per_block)
blockAddress = (addr*(self.no_of_blocks*self.words_per_block))+ (blockIndex * self.words_per_block)
self.cache[blockIndex] = [{addr: m[1]} for m in self.mem[blockAddress:(blockAddress+(self.words_per_block))]]
return self.cache[blockIndex][wordIndex].get(addr)
def get(self, address):
blockIndex = (address >> self.wordbits) & (self.no_of_blocks - 1)
wordIndex = address & (self.words_per_block-1)
addr = address / (self.no_of_blocks * self.words_per_block)
elem = self.cache[blockIndex][wordIndex]
if( elem != 0 and elem.get(addr,None)!= None ):
self.hitCount += 1
return elem[addr]
else:
if(elem == 0):
self.compulsoryMissCount +=1
if(elem != 0 and self.isFull()):
self.capacityMissCount += 1
elif(elem != 0):
self.conflictMissCount += 1
elem = self.load(address)
return elem
def printCache(self):
return 'Cache Capacity '+str(self.no_of_blocks)+'*'+str(self.words_per_block)+' Hit Count ' + str(self.hitCount) +\
' miss count = '+str(self.compulsoryMissCount+self.capacityMissCount+self.conflictMissCount)+' Compulsory Misses = '+str(self.compulsoryMissCount)+' Conflict Misses = ' + str(self.conflictMissCount)+' Capacity Misses = ' + str(self.capacityMissCount)<file_sep># ComputerArchitecture-MultilevelCache-in-Assembler | 38579e1853741f149e9af572814ededfc6b23681 | [
"Markdown",
"Python"
] | 6 | Python | sushmithanagarajan/ComputerArchitecture-MultilevelCache-in-Assembler | b82af1f091108f576d8ec618c3ee8eaa75908346 | 31b652c495f6f12cfdd0c35b85c0c4c8a205a31b |
refs/heads/master | <file_sep>#!/usr/bin/python
import i3
to_be_swapped = [output for output in i3.get_outputs() if output['active']]
if len(to_be_swapped) == 2:
for output in to_be_swapped:
i3.workspace(output['current_workspace'])
i3.command('move', 'workspace to output right')
| 90709e75ac0d192d82770ff4527ed4ea8a56810b | [
"Python"
] | 1 | Python | r-darwish/i3-config | 0ba2def78d00e05b08d3d4e63c65a759bc222bfa | 16adda24a3e9979bba4d601e037226a5a5b5dbde |
refs/heads/master | <file_sep>'use strict'
import assert from 'assert'
import { collectPlatformsFromConfig } from '../src/'
describe('index', () => {
describe('collectPlatformsFromConfig', () => {
it('generic', () => {
collectPlatformsFromConfig('/home/apkawa/work/u24-mobile-app/U24App/config.xml')
.then(function (result) {
assert(result['ios'])
})
.catch(function (err) {
assert(0, err)
})
})
})
})
<file_sep>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ANDROID_REVERSE_DENSITY_MAP = exports.PLATFORMS = undefined;
exports.getSettings = getSettings;
var _lodash = require('lodash.frompairs');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getSettings(argv) {
/**
* @var {Object} settings - names of the config file and of the splash image
*/
const settings = {};
settings.CONFIG_FILE = argv.config || 'config.xml';
settings.SPLASH_FILE = argv.splash || 'splash.png';
settings.IOS = argv.ios || false;
settings.ANDROID = argv.android || false;
settings.ALL_PLATFORMS = !settings.IOS && !settings.ANDROID;
settings.PATCH_9 = argv['9-patch'] || false;
settings.PATCH_9_WIDTH = parseFloat(argv['9-patch-width'] || 0.25);
settings.PATCH_9_HEIGHT = parseFloat(argv['9-patch-height'] || 0.25);
settings.UPDATE_CONFIG_RESOURCES = argv['update-config'] || false;
settings.OLD_XCODE_PATH = argv['xcode-old'] || false;
}
const PLATFORMS = exports.PLATFORMS = {
ios: [
// iPhone
{ name: 'Default~iphone.png', width: 320, height: 480 }, { name: 'Default@2x~iphone.png', width: 640, height: 960 }, { name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 }, { name: 'Default-667h.png', width: 750, height: 1334 }, { name: 'Default-736h.png', width: 1242, height: 2208 }, { name: 'Default-Landscape-736h.png', width: 2208, height: 1242 },
// iPad
{ name: 'Default-Portrait~ipad.png', width: 768, height: 1024 }, { name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 }, { name: 'Default-Landscape~ipad.png', width: 1024, height: 768 }, { name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 }],
android: [
// Landscape
{
name: 'drawable-land-ldpi/screen.png',
width: 320,
height: 200,
density: 'land-ldpi'
}, {
name: 'drawable-land-mdpi/screen.png',
width: 480,
height: 320,
density: 'land-mdpi'
}, {
name: 'drawable-land-hdpi/screen.png',
width: 800,
height: 480,
density: 'land-hdpi'
}, {
name: 'drawable-land-xhdpi/screen.png',
width: 1280,
height: 720,
density: 'land-xhdpi'
}, {
name: 'drawable-land-xxhdpi/screen.png',
width: 1600,
height: 960,
density: 'land-xxhdpi'
}, {
name: 'drawable-land-xxxhdpi/screen.png',
width: 1920,
height: 1280,
density: 'land-xxxhdpi'
},
// Portrait
{
name: 'drawable-port-ldpi/screen.png',
width: 200,
height: 320,
density: 'port-ldpi'
}, {
name: 'drawable-port-mdpi/screen.png',
width: 320,
height: 480,
density: 'port-mdpi'
}, {
name: 'drawable-port-hdpi/screen.png',
width: 480,
height: 800,
density: 'port-hdpi'
}, {
name: 'drawable-port-xhdpi/screen.png',
width: 720,
height: 1280,
density: 'port-xhdpi'
}, {
name: 'drawable-port-xxhdpi/screen.png',
width: 960,
height: 1600,
density: 'port-xxhdpi'
}, {
name: 'drawable-port-xxxhdpi/screen.png',
width: 1280,
height: 1920,
density: 'port-xxxhdpi'
}]
};
const ANDROID_REVERSE_DENSITY_MAP = exports.ANDROID_REVERSE_DENSITY_MAP = (0, _lodash2.default)(PLATFORMS.android.map(value => [value.density, value]));<file_sep>import fs from 'fs-extra';
import path from 'path';
import minimist from 'minimist';
import Q from 'q';
import _ from 'underscore';
import ig from 'imagemagick';
import xml2js from 'xml2js';
import { getSettings, ANDROID_REVERSE_DENSITY_MAP, PLATFORMS } from './settings';
const argv = minimist(process.argv.slice(2));
const settings = getSettings(argv);
export const collectPlatformsFromConfig = function (configFile) {
const deferred = Q.defer();
const parser = new xml2js.Parser();
fs.readFile(configFile, (err, data) => {
if (err) {
deferred.reject(err);
}
parser.parseString(data, (err, result) => {
if (err) {
deferred.reject(err);
}
const platforms = {};
for (let i = 0; i < result.widget.platform.length; i++) {
const platform = result.widget.platform[i];
const platform_name = platform.$.name;
const splash_list = [];
for (let s = 0; s < platform.splash.length; s++) {
const splash = platform.splash[s];
const opts = {
name: splash.$.src,
width: splash.$.width,
height: splash.$.height,
};
const density = splash.$.density;
const density_info = ANDROID_REVERSE_DENSITY_MAP[density];
if (density_info) {
opts.width = density_info.width;
opts.height = density_info.height;
}
splash_list.push(opts);
}
platforms[platform_name] = splash_list;
}
deferred.resolve(platforms);
});
});
return deferred.promise;
};
/**
* Check which platforms are added to the project and return their splash screen names and sizes
*
* @param {String} projectName
* @param {object} configPlatforms
* @return {Promise} resolves with an array of platforms
*/
export const getPlatforms = function (args) {
const projectName = args[0];
const configPlatforms = args[1];
const deferred = Q.defer();
const platforms = [];
let xcodeFolder = '/Images.xcassets/LaunchImage.launchimage/';
if (settings.OLD_XCODE_PATH) {
xcodeFolder = '/Resources/splash/';
}
let platform;
// TODO collect path from config.xml
if (settings.ALL_PLATFORMS || settings.IOS) {
platform = {
name: 'ios',
// TODO: use async fs.exists
isAdded: fs.existsSync('platforms/ios'),
splashPath: `platforms/ios/${projectName}${xcodeFolder}`,
splash: PLATFORMS.ios,
};
if (settings.UPDATE_CONFIG_RESOURCES) {
platform.splashPath = '';
platform.splash = configPlatforms.ios;
}
platforms.push(platform);
}
if (settings.ALL_PLATFORMS || settings.ANDROID) {
platform = {
name: 'android',
isAdded: fs.existsSync('platforms/android'),
splashPath: 'platforms/android/res/',
splash: PLATFORMS.android,
};
if (settings.UPDATE_CONFIG_RESOURCES) {
platform.splashPath = '';
platform.splash = configPlatforms.android;
}
platforms.push(platform);
}
platforms.push({
name: 'windows',
isAdded: fs.existsSync('platforms/windows'),
splashPath: 'platforms/windows/images/',
splash: [
// Landscape
{ name: 'SplashScreen.scale-100.png', width: 620, height: 300 },
{ name: 'SplashScreen.scale-125.png', width: 775, height: 375 },
{ name: 'SplashScreen.scale-150.png', width: 930, height: 450 },
{ name: 'SplashScreen.scale-200.png', width: 1240, height: 600 },
{ name: 'SplashScreen.scale-400.png', width: 2480, height: 1200 },
// Portrait
{ name: 'SplashScreenPhone.scale-240.png', width: 1152, height: 1920 },
{ name: 'SplashScreenPhone.scale-140.png', width: 672, height: 1120 },
{ name: 'SplashScreenPhone.scale-100.png', width: 480, height: 800 },
],
});
deferred.resolve(platforms);
return deferred.promise;
};
/**
* @var {Object} console utils
*/
const display = {};
display.success = function (str) {
str = 'โ '.green + str;
console.log(` ${str}`);
};
display.error = function (str) {
str = 'โ '.red + str;
console.log(` ${str}`);
};
display.header = function (str) {
console.log('');
console.log(` ${str.cyan.underline}`);
console.log('');
};
/**
* read the config file and get the project name
*
* @return {Promise} resolves to a string - the project's name
*/
const getProjectName = function () {
const deferred = Q.defer();
const parser = new xml2js.Parser();
fs.readFile(settings.CONFIG_FILE, (err, data) => {
if (err) {
deferred.reject(err);
}
parser.parseString(data, (err, result) => {
if (err) {
deferred.reject(err);
}
const projectName = result.widget.name[0];
deferred.resolve(projectName);
});
});
return deferred.promise;
};
/**
* Crops and creates a new splash in the platform's folder.
*
* @param {Object} platform
* @param {Object} splash
* @return {Promise}
*/
const generateSplash = function (platform, splash) {
const deferred = Q.defer();
let srcPath = settings.SPLASH_FILE;
const platformPath = srcPath.replace(/\.png$/, `-${platform.name}.png`);
if (fs.existsSync(platformPath)) {
srcPath = platformPath;
}
let dstPath = platform.splashPath + splash.name;
const has9Patch = (platform.name == 'android' && dstPath.match(/\.9\.png$/));
dstPath = dstPath.replace(/\.9\.png$/, '.png');
const dst = path.dirname(dstPath);
if (!fs.existsSync(dst)) {
fs.mkdirsSync(dst);
}
ig.identify(srcPath, (err, srcInfo) => {
if (err) {
deferred.reject(err);
}
ig.crop({
srcPath,
dstPath,
quality: 1,
format: 'png',
width: splash.width,
height: splash.height,
}, (err, stdout, stderr) => {
if (err) {
deferred.reject(err);
} else {
if (platform.name == 'android' && (has9Patch || settings.PATCH_9)) {
// TODO from source size
const new_size = Math.max.apply(null, [splash.width, splash.height]);
const ratio = splash.width / splash.height;
const base_border = ((srcInfo.height * 0.25) * new_size) /
srcInfo.height;
let y_border = ((srcInfo.height * settings.PATCH_9_HEIGHT) *
new_size) / srcInfo.height;
let x_border = ((srcInfo.width * settings.PATCH_9_WIDTH) * new_size) /
srcInfo.width;
if (ratio < 1) {
x_border = (base_border - y_border) * ratio;
} else {
y_border = (base_border - x_border) * ratio;
}
y_border = Math.round(y_border);
x_border = Math.round(x_border);
const convert_args = [
'-background',
'white',
'-bordercolor',
'white',
dstPath,
'-border', '1',
'-fill', 'black',
'-draw', `line 1,0 ${x_border},0`,
'-draw', `line ${splash.width - x_border},0 ${splash.width},0`,
'-draw', `${'line 0,1 ' + ' 0,'}${y_border}`,
'-draw', `line 0,${splash.height - y_border} 0,${splash.height}`,
dstPath.replace(/\.png$/, '.9.png'),
];
ig.convert(convert_args);
}
deferred.resolve();
display.success(`${splash.name} created`);
}
});
});
return deferred.promise;
};
/**
* Generates splash based on the platform object
*
* @param {Object} platform
* @return {Promise}
*/
const generateSplashForPlatform = function (platform) {
const deferred = Q.defer();
display.header(`Generating splash screen for ${platform.name}`);
const all = [];
const splashes = platform.splash;
splashes.forEach((splash) => {
all.push(generateSplash(platform, splash));
});
Q.all(all).then(() => {
deferred.resolve();
}).catch((err) => {
console.log(err);
});
return deferred.promise;
};
/**
* Goes over all the platforms and triggers splash screen generation
*
* @param {Array} platforms
* @return {Promise}
*/
const generateSplashes = function (platforms) {
const deferred = Q.defer();
let sequence = Q();
const all = [];
_(platforms).where({ isAdded: true }).forEach((platform) => {
sequence = sequence.then(() => generateSplashForPlatform(platform));
all.push(sequence);
});
Q.all(all).then(() => {
deferred.resolve();
});
return deferred.promise;
};
/**
* Checks if at least one platform was added to the project
*
* @return {Promise} resolves if at least one platform was found, rejects otherwise
*/
const atLeastOnePlatformFound = function () {
const deferred = Q.defer();
getPlatforms().then((platforms) => {
const activePlatforms = _(platforms).where({ isAdded: true });
if (activePlatforms.length > 0) {
display.success(
`platforms found: ${_(activePlatforms).pluck('name').join(', ')}`);
deferred.resolve();
} else {
display.error(
'No cordova platforms found. ' +
'Make sure you are in the root folder of your Cordova project ' +
'and add platforms with \'cordova platform add\'',
);
deferred.reject();
}
});
return deferred.promise;
};
/**
* Checks if a valid splash file exists
*
* @return {Promise} resolves if exists, rejects otherwise
*/
const validSplashExists = function () {
const deferred = Q.defer();
fs.exists(settings.SPLASH_FILE, (exists) => {
if (exists) {
display.success(`${settings.SPLASH_FILE} exists`);
deferred.resolve();
} else {
display.error(`${settings.SPLASH_FILE} does not exist`);
deferred.reject();
}
});
return deferred.promise;
};
/**
* Checks if a config.xml file exists
*
* @return {Promise} resolves if exists, rejects otherwise
*/
const configFileExists = function () {
const deferred = Q.defer();
fs.exists(settings.CONFIG_FILE, (exists) => {
if (exists) {
display.success(`${settings.CONFIG_FILE} exists`);
deferred.resolve();
} else {
display.error(`cordova's ${settings.CONFIG_FILE} does not exist`);
deferred.reject();
}
});
return deferred.promise;
};
export function main() {
display.header('Checking Project & Splash');
// atLeastOnePlatformFound()
validSplashExists()
.then(configFileExists)
.then(() => Q.all(
[getProjectName(), collectPlatformsFromConfig(settings.CONFIG_FILE)]))
.then(getPlatforms)
.then(generateSplashes)
.catch((err) => {
if (err) {
console.log(err);
}
})
.then(() => {
console.log('');
});
}
<file_sep>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getPlatforms = exports.collectPlatformsFromConfig = undefined;
exports.main = main;
var _fsExtra = require('fs-extra');
var _fsExtra2 = _interopRequireDefault(_fsExtra);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _minimist = require('minimist');
var _minimist2 = _interopRequireDefault(_minimist);
var _q = require('q');
var _q2 = _interopRequireDefault(_q);
var _underscore = require('underscore');
var _underscore2 = _interopRequireDefault(_underscore);
var _imagemagick = require('imagemagick');
var _imagemagick2 = _interopRequireDefault(_imagemagick);
var _xml2js = require('xml2js');
var _xml2js2 = _interopRequireDefault(_xml2js);
var _settings = require('./settings');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const argv = (0, _minimist2.default)(process.argv.slice(2));
const settings = (0, _settings.getSettings)(argv);
const collectPlatformsFromConfig = exports.collectPlatformsFromConfig = function (configFile) {
const deferred = _q2.default.defer();
const parser = new _xml2js2.default.Parser();
_fsExtra2.default.readFile(configFile, (err, data) => {
if (err) {
deferred.reject(err);
}
parser.parseString(data, (err, result) => {
if (err) {
deferred.reject(err);
}
const platforms = {};
for (let i = 0; i < result.widget.platform.length; i++) {
const platform = result.widget.platform[i];
const platform_name = platform.$.name;
const splash_list = [];
for (let s = 0; s < platform.splash.length; s++) {
const splash = platform.splash[s];
const opts = {
name: splash.$.src,
width: splash.$.width,
height: splash.$.height
};
const density = splash.$.density;
const density_info = _settings.ANDROID_REVERSE_DENSITY_MAP[density];
if (density_info) {
opts.width = density_info.width;
opts.height = density_info.height;
}
splash_list.push(opts);
}
platforms[platform_name] = splash_list;
}
deferred.resolve(platforms);
});
});
return deferred.promise;
};
/**
* Check which platforms are added to the project and return their splash screen names and sizes
*
* @param {String} projectName
* @param {object} configPlatforms
* @return {Promise} resolves with an array of platforms
*/
const getPlatforms = exports.getPlatforms = function (args) {
const projectName = args[0];
const configPlatforms = args[1];
const deferred = _q2.default.defer();
const platforms = [];
let xcodeFolder = '/Images.xcassets/LaunchImage.launchimage/';
if (settings.OLD_XCODE_PATH) {
xcodeFolder = '/Resources/splash/';
}
let platform;
// TODO collect path from config.xml
if (settings.ALL_PLATFORMS || settings.IOS) {
platform = {
name: 'ios',
// TODO: use async fs.exists
isAdded: _fsExtra2.default.existsSync('platforms/ios'),
splashPath: `platforms/ios/${ projectName }${ xcodeFolder }`,
splash: _settings.PLATFORMS.ios
};
if (settings.UPDATE_CONFIG_RESOURCES) {
platform.splashPath = '';
platform.splash = configPlatforms.ios;
}
platforms.push(platform);
}
if (settings.ALL_PLATFORMS || settings.ANDROID) {
platform = {
name: 'android',
isAdded: _fsExtra2.default.existsSync('platforms/android'),
splashPath: 'platforms/android/res/',
splash: _settings.PLATFORMS.android
};
if (settings.UPDATE_CONFIG_RESOURCES) {
platform.splashPath = '';
platform.splash = configPlatforms.android;
}
platforms.push(platform);
}
platforms.push({
name: 'windows',
isAdded: _fsExtra2.default.existsSync('platforms/windows'),
splashPath: 'platforms/windows/images/',
splash: [
// Landscape
{ name: 'SplashScreen.scale-100.png', width: 620, height: 300 }, { name: 'SplashScreen.scale-125.png', width: 775, height: 375 }, { name: 'SplashScreen.scale-150.png', width: 930, height: 450 }, { name: 'SplashScreen.scale-200.png', width: 1240, height: 600 }, { name: 'SplashScreen.scale-400.png', width: 2480, height: 1200 },
// Portrait
{ name: 'SplashScreenPhone.scale-240.png', width: 1152, height: 1920 }, { name: 'SplashScreenPhone.scale-140.png', width: 672, height: 1120 }, { name: 'SplashScreenPhone.scale-100.png', width: 480, height: 800 }]
});
deferred.resolve(platforms);
return deferred.promise;
};
/**
* @var {Object} console utils
*/
const display = {};
display.success = function (str) {
str = 'โ '.green + str;
console.log(` ${ str }`);
};
display.error = function (str) {
str = 'โ '.red + str;
console.log(` ${ str }`);
};
display.header = function (str) {
console.log('');
console.log(` ${ str.cyan.underline }`);
console.log('');
};
/**
* read the config file and get the project name
*
* @return {Promise} resolves to a string - the project's name
*/
const getProjectName = function () {
const deferred = _q2.default.defer();
const parser = new _xml2js2.default.Parser();
_fsExtra2.default.readFile(settings.CONFIG_FILE, (err, data) => {
if (err) {
deferred.reject(err);
}
parser.parseString(data, (err, result) => {
if (err) {
deferred.reject(err);
}
const projectName = result.widget.name[0];
deferred.resolve(projectName);
});
});
return deferred.promise;
};
/**
* Crops and creates a new splash in the platform's folder.
*
* @param {Object} platform
* @param {Object} splash
* @return {Promise}
*/
const generateSplash = function (platform, splash) {
const deferred = _q2.default.defer();
let srcPath = settings.SPLASH_FILE;
const platformPath = srcPath.replace(/\.png$/, `-${ platform.name }.png`);
if (_fsExtra2.default.existsSync(platformPath)) {
srcPath = platformPath;
}
let dstPath = platform.splashPath + splash.name;
const has9Patch = platform.name == 'android' && dstPath.match(/\.9\.png$/);
dstPath = dstPath.replace(/\.9\.png$/, '.png');
const dst = _path2.default.dirname(dstPath);
if (!_fsExtra2.default.existsSync(dst)) {
_fsExtra2.default.mkdirsSync(dst);
}
_imagemagick2.default.identify(srcPath, (err, srcInfo) => {
if (err) {
deferred.reject(err);
}
_imagemagick2.default.crop({
srcPath,
dstPath,
quality: 1,
format: 'png',
width: splash.width,
height: splash.height
}, (err, stdout, stderr) => {
if (err) {
deferred.reject(err);
} else {
if (platform.name == 'android' && (has9Patch || settings.PATCH_9)) {
// TODO from source size
const new_size = Math.max.apply(null, [splash.width, splash.height]);
const ratio = splash.width / splash.height;
const base_border = srcInfo.height * 0.25 * new_size / srcInfo.height;
let y_border = srcInfo.height * settings.PATCH_9_HEIGHT * new_size / srcInfo.height;
let x_border = srcInfo.width * settings.PATCH_9_WIDTH * new_size / srcInfo.width;
if (ratio < 1) {
x_border = (base_border - y_border) * ratio;
} else {
y_border = (base_border - x_border) * ratio;
}
y_border = Math.round(y_border);
x_border = Math.round(x_border);
const convert_args = ['-background', 'white', '-bordercolor', 'white', dstPath, '-border', '1', '-fill', 'black', '-draw', `line 1,0 ${ x_border },0`, '-draw', `line ${ splash.width - x_border },0 ${ splash.width },0`, '-draw', `${ 'line 0,1 ' + ' 0,' }${ y_border }`, '-draw', `line 0,${ splash.height - y_border } 0,${ splash.height }`, dstPath.replace(/\.png$/, '.9.png')];
_imagemagick2.default.convert(convert_args);
}
deferred.resolve();
display.success(`${ splash.name } created`);
}
});
});
return deferred.promise;
};
/**
* Generates splash based on the platform object
*
* @param {Object} platform
* @return {Promise}
*/
const generateSplashForPlatform = function (platform) {
const deferred = _q2.default.defer();
display.header(`Generating splash screen for ${ platform.name }`);
const all = [];
const splashes = platform.splash;
splashes.forEach(splash => {
all.push(generateSplash(platform, splash));
});
_q2.default.all(all).then(() => {
deferred.resolve();
}).catch(err => {
console.log(err);
});
return deferred.promise;
};
/**
* Goes over all the platforms and triggers splash screen generation
*
* @param {Array} platforms
* @return {Promise}
*/
const generateSplashes = function (platforms) {
const deferred = _q2.default.defer();
let sequence = (0, _q2.default)();
const all = [];
(0, _underscore2.default)(platforms).where({ isAdded: true }).forEach(platform => {
sequence = sequence.then(() => generateSplashForPlatform(platform));
all.push(sequence);
});
_q2.default.all(all).then(() => {
deferred.resolve();
});
return deferred.promise;
};
/**
* Checks if at least one platform was added to the project
*
* @return {Promise} resolves if at least one platform was found, rejects otherwise
*/
const atLeastOnePlatformFound = function () {
const deferred = _q2.default.defer();
getPlatforms().then(platforms => {
const activePlatforms = (0, _underscore2.default)(platforms).where({ isAdded: true });
if (activePlatforms.length > 0) {
display.success(`platforms found: ${ (0, _underscore2.default)(activePlatforms).pluck('name').join(', ') }`);
deferred.resolve();
} else {
display.error('No cordova platforms found. ' + 'Make sure you are in the root folder of your Cordova project ' + 'and add platforms with \'cordova platform add\'');
deferred.reject();
}
});
return deferred.promise;
};
/**
* Checks if a valid splash file exists
*
* @return {Promise} resolves if exists, rejects otherwise
*/
const validSplashExists = function () {
const deferred = _q2.default.defer();
_fsExtra2.default.exists(settings.SPLASH_FILE, exists => {
if (exists) {
display.success(`${ settings.SPLASH_FILE } exists`);
deferred.resolve();
} else {
display.error(`${ settings.SPLASH_FILE } does not exist`);
deferred.reject();
}
});
return deferred.promise;
};
/**
* Checks if a config.xml file exists
*
* @return {Promise} resolves if exists, rejects otherwise
*/
const configFileExists = function () {
const deferred = _q2.default.defer();
_fsExtra2.default.exists(settings.CONFIG_FILE, exists => {
if (exists) {
display.success(`${ settings.CONFIG_FILE } exists`);
deferred.resolve();
} else {
display.error(`cordova's ${ settings.CONFIG_FILE } does not exist`);
deferred.reject();
}
});
return deferred.promise;
};
function main() {
display.header('Checking Project & Splash');
// atLeastOnePlatformFound()
validSplashExists().then(configFileExists).then(() => _q2.default.all([getProjectName(), collectPlatformsFromConfig(settings.CONFIG_FILE)])).then(getPlatforms).then(generateSplashes).catch(err => {
if (err) {
console.log(err);
}
}).then(() => {
console.log('');
});
} | 7f1fd6e60850a374d263673ab6f9a7e79ee50909 | [
"JavaScript"
] | 4 | JavaScript | Apkawa/cordova-splash | 6538061ea0769affd0218dfcb7bc94ff77c3b9ee | 9d61f2e5bdf15a84eeadbb70111695891aa46391 |
refs/heads/master | <repo_name>govorovsky/configen<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/Navigator.java
package ru.mail.flexsettings;
import android.content.DialogInterface;
import android.text.InputType;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import ru.mail.flexsettings.field.ObjectField;
public class Navigator {
private final FlexSettingsActivity mMainActivity;
public Navigator(FlexSettingsActivity activity) {
mMainActivity = activity;
}
public void editPrimitiveField(String name, String defValue, boolean isNumber, final EditListener<String> listener) {
final EditText edittext = new EditText(mMainActivity);
if (isNumber) {
edittext.setRawInputType(InputType.TYPE_CLASS_NUMBER);
}
if (defValue == null) {
defValue = "";
}
edittext.setText(defValue);
edittext.setSelection(defValue.length());
new AlertDialog.Builder(mMainActivity)
.setTitle("Set '" + name + "' value:")
.setView(edittext)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = edittext.getText().toString();
listener.onChanged(value);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
}
public void showObjectField(ObjectField objectField, FieldChangeListener changeListener) {
mMainActivity.setFragment(new FieldFragment(objectField, changeListener));
}
public void showUnsupported() {
Toast.makeText(
mMainActivity.getApplicationContext(),
"Operation unsupported",
Toast.LENGTH_SHORT
).show();
}
public interface EditListener<T> {
void onChanged(T value);
}
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/dsl/Types.kt
package ru.mail.condef.dsl
sealed class Type<out N> {
abstract fun defaultValue(): N
}
interface CompositeType {
val subtype: Type<*>?
}
class StringType : Type<String>() {
override fun defaultValue(): String = ""
}
class IntegerType : Type<Int>() {
override fun defaultValue(): Int = 0
}
class LongType : Type<Long>() {
override fun defaultValue(): Long = 0
}
class FreeObjectType(override val subtype: Type<*>? = null) : Type<Any?>(), CompositeType {
override fun defaultValue(): Any? = null
}
class StrictObjectType(val definition: Definition) : Type<Unit?>() {
override fun defaultValue(): Unit? = null
}
class MultiObjectType(val types:Map<String, Definition>) : Type<Unit?>() {
override fun defaultValue(): Unit? = null
}
class BoolType : Type<Boolean>() {
override fun defaultValue(): Boolean = false
}
class ArrayType<out N>(override val subtype: Type<N>) : Type<List<N>>(), CompositeType {
override fun defaultValue(): List<N> = listOf()
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/main/ConfigGenerator.kt
package ru.mail.condef.main
import dsl.rootDefinition
import ru.mail.condef.renderer.*
import java.io.File
import java.io.IOException
import java.nio.charset.Charset
class ConfigGenerator(
val packageName: String = "ru.mail",
val interfaceName: String = "Configuration",
val implClassName: String = "ConfigurationContentImpl",
val parserClassName: String = "ConfigurationJsonParser",
val settingsDefinitionClassName: String = "ConfigSettingsDefinition",
val settingsMapperClassName: String = "ConfigSettingsMapper",
val destDir: String = "generated",
val docFile: File = File("generatedDoc/configuration.html"),
val versionCode: String = "1900_alpha"
) {
companion object {
@JvmStatic
fun main(argv: Array<String>) {
ConfigGenerator("ru.mail").generate()
}
}
fun generate() {
ConfigCodeRenderer(
rootDefinition,
InterfaceGenerationStrategy(interfaceName),
packageName
).renderToFile("$destDir/$interfaceName.java")
ConfigCodeRenderer(
rootDefinition,
ImplementationGenerationStrategy(interfaceName, implClassName, static = false),
packageName
).renderToFile("$destDir/$implClassName.java")
ConfigSettingsDefinitionRenderer(
rootDefinition,
packageName
).renderToFile("$destDir/$settingsDefinitionClassName.java")
ConfigSettingsMapperRenderer(
rootDefinition,
packageName
).renderToFile("$destDir/$settingsMapperClassName.java")
ParserRenderer(
rootDefinition,
packageName,
parserClassName,
implClassName
).renderToFile("$destDir/$parserClassName.java")
AnalyticsSenderRenderer(
packageName
).renderToFile("$destDir/AnalyticsSender.java")
RequiredFieldExceptionRenderer(
packageName
).renderToFile("$destDir/RequiredFieldException.java")
DocumentationRenderer(rootDefinition, versionCode)
.renderToFile(docFile.absolutePath)
}
private fun Renderer.renderToFile(fileName: String) {
val writer = TextWriter()
render(writer)
val file = File(fileName)
if (file.exists() && !file.delete()) {
throw IOException("Cannot delete previous version of " + fileName)
}
val parent = File(file.parent)
if (!parent.exists() && !parent.mkdirs()) {
throw IOException("Cannot create dirs for " + file.parent)
}
val printWriter = file.printWriter(Charset.forName("UTF-8"))
try {
printWriter.print(writer.toString())
} finally {
printWriter.close()
}
}
}
<file_sep>/app/src/main/java/ru/mail/configen/DeveloperSettingsActivity.kt
package ru.mail.configen
import android.os.Bundle
import android.widget.Toast
import kotlinx.coroutines.*
import ru.mail.flexsettings.FlexSettingsActivity
class DeveloperSettingsActivity : FlexSettingsActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val field = ConfigSettingsDefinition.create()
runBlocking {
ConfigSettingsMapper.map(
field.asStrictObject(),
ConfigurationDelegate().loadConfig(this@DeveloperSettingsActivity),
ConfigurationDelegate().loadDeveloperSettings(this@DeveloperSettingsActivity)
)
}
showFieldScreen(field)
}
override fun onSaveSettings(settingsJson: String) {
GlobalScope.async {
ConfigurationDelegate().saveDeveloperSettings(applicationContext, settingsJson)
}
Toast.makeText(this, "Settings saved", Toast.LENGTH_LONG).show()
setResult(reqCodeSetSettings)
finish()
}
}<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/field/ObjectField.java
package ru.mail.flexsettings.field;
import java.util.Collections;
import java.util.List;
public abstract class ObjectField extends Field {
private final List<Field> mFields;
protected ObjectField(String name, List<Field> fields) {
super(name);
Collections.sort(fields);
mFields = fields;
}
public List<Field> getAllFields() {
return mFields;
}
public Field getField(String name) {
for (Field field : mFields) {
if (field.getName().equals(name)) {
return field;
}
}
throw new IllegalStateException("field '" + name + "' absent in field " + getName());
}
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/dsl/Validators.kt
package ru.mail.condef.dsl
import java.util.regex.Pattern
sealed class Validator
class SpecialValuesValidator<out T>(val values: List<T>) : Validator()
class RegexValidator(val pattern: Pattern) : Validator()
class RangeValidator(val fromInclusive: Int, val toInclusive: Int) : Validator()
<file_sep>/buildSrc/src/main/kotlin/dsl/Config.kt
package dsl
import ru.mail.condef.dsl.*
import java.util.regex.Pattern
val rootDefinition = definition(
"field_root" of StringType()
withDescription "Some root field"
withDefault null,
"feature" of FreeObjectType()
withDefault empty()
restrictedBy definition(
"isSomeFeatureEnabled" of BoolType()
withDescription "Some feature flag"
withDefault false,
"field1" of IntegerType()
withDescription "Some odd int value"
withAllowedValues listOf(1, 3, 5, 7)
withDefault 1,
"field2" of StringType()
withDescription "Some string value with regexp validation"
withAbsenceHandler requiredHandler()
withAllowedPattern Pattern.compile("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d"),
"field3" of ArrayType(StringType())
withDescription "Some field with allowed values validation"
withAllowedValuesInArray listOf("val1", "val2", "val3")
withDefault emptyList(),
"nestedConfig" of FreeObjectType()
withDefault empty()
restrictedBy definition(
"nestedField1" of IntegerType()
withDescription "Some nestedField"
withAllowedRange 10..20
withDefault 15,
"nestedField2" of StringType()
withDescription "some desc"
withDefault "some default"
)
)
)
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/StringEscapeUtils.kt
package ru.mail.condef.renderer
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException
import java.io.StringWriter
import java.io.Writer
import java.util.Locale
/**
* Escapes and unescapes `String`s for
* Java, Java Script, HTML, XML, and SQL.
*
*
* #ThreadSafe#
*
*
* **Note that this version is a stripped down version from Commons Lang 2.6 with only necessary methods for
* JSON builder**
* @author Apache Software Foundation
* @author Apache Jakarta Turbine
* @author Purple Technology
* @author [<NAME>](mailto:<EMAIL>)
* @author <NAME>
* @author <NAME>
* @author [<NAME>](<EMAIL>)
* @author [<NAME>](mailto:<EMAIL>)
* @author <NAME>
* @author <NAME>
* @since 2.0
*/
/**
*
* `StringEscapeUtils` instances should NOT be constructed in
* standard programming.
*
*
* Instead, the class should be used as:
* <pre>StringEscapeUtils.escapeJava("foo");</pre>
*
*
* This constructor is public to permit tools that require a JavaBean
* instance to operate.
*/
class StringEscapeUtils {
companion object {
/**
* Escapes the characters in a `String` using Java String rules.
*
*
* Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
*
*
* So a tab becomes the characters `'\\'` and `'t'`.
*
*
* The only difference between Java strings and JavaScript strings
* is that in JavaScript, a single quote must be escaped.
*
*
* Example:
* <pre>
* input string: He didn't say, "Stop!"
* output string: He didn't say, \"Stop!\"
</pre> *
*
* @param str String to escape values in, may be null
* @return String with escaped values, `null` if null string input
*/
fun escapeJava(str: String): String? {
return escapeJavaStyleString(str, false, false)
}
/**
* Worker method for the [.escapeJavaScript] method.
*
* @param str String to escape values in, may be null
* @param escapeSingleQuotes escapes single quotes if `true`
* @param escapeForwardSlash TODO
* @return the escaped string
*/
private fun escapeJavaStyleString(str: String?, escapeSingleQuotes: Boolean, escapeForwardSlash: Boolean): String? {
if (str == null) {
return null
}
try {
val writer = StringWriter(str.length * 2)
escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash)
return writer.toString()
} catch (ioe: IOException) {
// this should never ever happen while writing to a StringWriter
throw RuntimeException(ioe)
}
}
/**
* Worker method for the [.escapeJavaScript] method.
*
* @param out write to receieve the escaped string
* @param str String to escape values in, may be null
* @param escapeSingleQuote escapes single quotes if `true`
* @param escapeForwardSlash TODO
* @throws IOException if an IOException occurs
*/
@Throws(IOException::class)
private fun escapeJavaStyleString(out: Writer?, str: String?, escapeSingleQuote: Boolean,
escapeForwardSlash: Boolean) {
if (out == null) {
throw IllegalArgumentException("The Writer must not be null")
}
if (str == null) {
return
}
val sz: Int = str.length
for (i in 0 until sz) {
val ch = str[i]
// handle unicode
when {
ch.toInt() > 0xfff -> out.write("\\u" + hex(ch))
ch.toInt() > 0xff -> out.write("\\u0" + hex(ch))
ch.toInt() > 0x7f -> out.write("\\u00" + hex(ch))
ch.toInt() < 32 -> when (ch) {
'\b' -> {
out.write('\\'.toInt())
out.write('b'.toInt())
}
'\n' -> {
out.write('\\'.toInt())
out.write('n'.toInt())
}
'\t' -> {
out.write('\\'.toInt())
out.write('t'.toInt())
}
'\r' -> {
out.write('\\'.toInt())
out.write('r'.toInt())
}
else -> if (ch.toInt() > 0xf) {
out.write("\\u00" + hex(ch))
} else {
out.write("\\u000" + hex(ch))
}
}
else -> when (ch) {
'\'' -> {
if (escapeSingleQuote) {
out.write('\\'.toInt())
}
out.write('\''.toInt())
}
'"' -> {
out.write('\\'.toInt())
out.write('"'.toInt())
}
'\\' -> {
out.write('\\'.toInt())
out.write('\\'.toInt())
}
'/' -> {
if (escapeForwardSlash) {
out.write('\\'.toInt())
}
out.write('/'.toInt())
}
else -> out.write(ch.toInt())
}
}
}
}
/**
* Returns an upper case hexadecimal `String` for the given
* character.
*
* @param ch The character to convert.
* @return An upper case hexadecimal `String`
*/
private fun hex(ch: Char): String {
return Integer.toHexString(ch.toInt()).toUpperCase(Locale.ENGLISH)
}
}
}<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/HtmlBuilder.kt
package ru.mail.condef.renderer
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
interface Element {
fun render(builder: StringBuilder, indent: String)
}
class TextElement(private val text: String) : Element {
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent$text\n")
}
}
typealias attributes = Map<String, String>
@DslMarker
annotation class HtmlTagMarker
@HtmlTagMarker
abstract class Tag(private val name: String, private val attrs: attributes) : Element {
val children = arrayListOf<Element>()
val className: String? by optionalAttr(attrs, "class")
protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T {
tag.init()
children.add(tag)
return tag
}
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent<$name${renderAttributes()}>\n")
for (c in children) {
renderChild(c, builder, indent)
}
builder.append("$indent</$name>\n")
}
open fun renderChild(c: Element, builder: StringBuilder, indent: String) {
c.render(builder, indent + " ")
}
private fun renderAttributes(): String {
val builder = StringBuilder()
for ((attr, value) in attrs) {
if (!value.isEmpty()) {
builder.append(" $attr=\"$value\"")
}
}
return builder.toString()
}
private fun <T, TValue> optionalAttr(properties: Map<String, TValue>, key: String): ReadOnlyProperty<T, TValue?> {
return object : ReadOnlyProperty<T, TValue?> {
override fun getValue(thisRef: T, property: KProperty<*>) = properties[key]
}
}
override fun toString(): String {
val builder = StringBuilder()
render(builder, "")
return builder.toString()
}
}
abstract class TagWithText(name: String, map: attributes) : Tag(name, map) {
operator fun String.unaryPlus() {
children.add(TextElement(this))
}
}
class HTML : TagWithText("html", mapOf()) {
fun head(init: Head.() -> Unit) = initTag(Head(mapOf()), init)
fun body(init: Body.() -> Unit) = initTag(Body(mapOf()), init)
}
class Head(map: attributes) : TagWithText("head", map) {
fun title(init: Title.() -> Unit) = initTag(Title(), init)
fun style(init: Style.() -> Unit) = initTag(Style(), init)
fun script(init: Script.() -> Unit) = initTag(Script(), init)
fun link(attrs: attributes, init: Link.() -> Unit) = initTag(Link(attrs), init)
}
class Title : TagWithText("title", mapOf())
class Style : TagWithText("style", mapOf())
class Script : TagWithText("script", mapOf())
class Link(attrs: attributes): TagWithText("link", attrs)
abstract class BodyTag(name: String, attrs: attributes) : TagWithText(name, attrs) {
fun table(attrs: attributes = mapOf(), init: Table.() -> Unit) = initTag(Table(attrs), init)
fun b(attrs: attributes = mapOf(), init: B.() -> Unit) = initTag(B(attrs), init)
fun p(attrs: attributes = mapOf(), init: P.() -> Unit) = initTag(P(attrs), init)
fun h1(attrs: attributes = mapOf(), init: H1.() -> Unit) = initTag(H1(attrs), init)
fun pre(attrs: attributes = mapOf(), init: Pre.() -> Unit) = initTag(Pre(attrs), init)
fun a(attrs: attributes = mapOf(), init: A.() -> Unit) = initTag(A(attrs), init)
fun div(attrs: attributes = mapOf(), init: Div.() -> Unit) = initTag(Div(attrs), init)
}
class Body(attrs: attributes) : BodyTag("body", attrs)
class B(attrs: attributes) : BodyTag("b", attrs)
class P(attrs: attributes) : BodyTag("p", attrs)
class H1(attrs: attributes) : BodyTag("h1", attrs)
class Div(attrs: attributes) : BodyTag("div", attrs)
class Pre(attrs: attributes) : BodyTag("pre", attrs) {
override fun render(builder: StringBuilder, indent: String) {
super.render(builder, "")
}
override fun renderChild(c: Element, builder: StringBuilder, indent: String) {
c.render(builder, "") /* pre rendered as is without indent */
}
}
abstract class TableTag(name: String, map: attributes) : BodyTag(name, map) {
fun thead(attrs: attributes = mapOf(), init: THead.() -> Unit) = initTag(THead(attrs), init)
fun th(attrs: attributes = mapOf(), init: Th.() -> Unit) = initTag(Th(attrs), init)
fun tr(attrs: attributes = mapOf(), init: Tr.() -> Unit) = initTag(Tr(attrs), init)
fun td(attrs: attributes = mapOf(), init: Td.() -> Unit) = initTag(Td(attrs), init)
}
class Table(attrs: attributes) : TableTag("table", attrs)
class THead(attrs: attributes) : TableTag("thead", attrs)
class Tr(attrs: attributes) : TableTag("tr", attrs)
class Th(attrs: attributes) : TableTag("th", attrs)
class Td(attrs: attributes) : TableTag("td", attrs)
class A(attrs: attributes) : BodyTag("a", attrs) {
val href by attrs
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}
fun attrs(vararg atts: Pair<String, String>) = mapOf(*atts)<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/dsl/EmptyObject.kt
package ru.mail.condef.dsl
object EmptyObject
fun empty() : EmptyObject {
return EmptyObject
}
<file_sep>/buildSrc/build/resources/main/doc.js
window.addEventListener('DOMContentLoaded', function() {
console.log("dom loaded")
processRows()
setExampleToggleListeners()
})
function processRows(root, visible, depth = 1) {
var selector = root ? root.dataset.node : "_root"
var rows = document.querySelectorAll(`[data-node-parent="${selector}"]`)
if(rows.length > 0) {
if(root) {
createExpandLink(root.children[0])
}
rows.forEach( row => {
if(root) setVisibility(row, visible)
if(row.children.length > 0) {
row.children[0].style.paddingLeft = (depth * 18) + "px"
}
processRows(row, visible, depth + 1)
})
}
}
function createExpandLink(td) {
var el = document.createElement("a")
el.addEventListener("click", expandRows)
el.href = "#"
el.innerHTML = td.innerHTML
td.innerHTML = ""
td.appendChild(el)
}
function setExampleToggleListeners() {
var elements = document.querySelectorAll([".toggablePre"])
elements.forEach( el => {
el.addEventListener("click", togglePreVisibility);
})
}
function togglePreVisibility(event) {
event.preventDefault()
var preNode = this.parentNode.querySelector("pre")
setVisibility(preNode, isElementInvisible(preNode))
}
function expandRows(event) {
event.preventDefault()
toggleVisibility(this.parentNode.parentNode)
}
function isElementInvisible(el) {
return el.style.display == "none"
}
function toggleVisibility(r, visibility) {
var rows = document.querySelectorAll(`[data-node-parent="${r.dataset.node}"]`)
rows.forEach (row => {
shouldBeVisible = visibility != undefined ? visibility : isElementInvisible(row)
setVisibility(row, shouldBeVisible)
if(!shouldBeVisible) {
toggleVisibility(row, false)
}
})
}
function setVisibility(element, isVisible) {
element.style.display = isVisible ? (element.tagName.toLowerCase() == "pre" ? "block" : "table-row") : "none"
}
<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/SettingToJsonMapper.java
package ru.mail.flexsettings;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import ru.mail.flexsettings.field.Field;
import ru.mail.flexsettings.field.FreeObjectField;
import ru.mail.flexsettings.field.StrictObjectField;
public class SettingToJsonMapper {
public String map(StrictObjectField baseField) throws JSONException {
return mapStrictObject(baseField).toString();
}
private Object mapField(Field field) throws JSONException {
// TODO fix for required fields
// if (!field.isChanged()) {
// return null;
// }
if (field.isString()) {
return field.asString().getValue();
} else if (field.isBoolean()) {
return field.asBoolean().getValue();
} else if (field.isInteger()) {
return field.asInteger().getValue();
} else if (field.isLong()) {
return field.asLong().getValue();
} else if (field.isStrictObject()) {
return mapStrictObject(field.asStrictObject());
} else if (field.isFreeObject()) {
return mapFreeObject(field.asFreeObject());
} else {
return null;
}
}
private JSONObject mapFieldList(JSONObject baseJson, List<Field> fieldList) throws JSONException {
for (Field field : fieldList) {
baseJson.put(field.getName(), mapField(field));
}
return baseJson;
}
private JSONObject mapStrictObject(StrictObjectField baseField) throws JSONException {
return mapFieldList(new JSONObject(), baseField.getAllFields());
}
private JSONObject mapFreeObject(FreeObjectField baseField) throws JSONException {
return mapFieldList(new JSONObject(), baseField.getAllFields());
}
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/DocumentationRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
class DocumentationRenderer(private val definition: Definition, private val version: String) : Renderer {
override fun render(writer: TextWriter) {
with(writer) {
val docHtml = html {
head {
style { +cssStyles() }
title { +"Android Mail Configuration Constants" }
script {
+getJs()
}
link(attrs("rel" to "stylesheet",
"href" to "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css",
"integrity" to "<KEY>",
"crossorigin" to "anonymous")) {
}
}
body {
h1(attrs("class" to "text-center")) {
+"Android Mail Configuration for $version"
}
table(attrs("class" to "table table-bordered table-hover")) {
thead {
tr {
th(attrs("style" to "width: 20%")) {
+"JSON Field"
}
th(attrs("style" to "width: 35%")) {
+"Description"
}
th(attrs("style" to "width: 15%")) {
+"Value type"
}
th(attrs("style" to "width: 10%")) {
+"Default value"
}
th(attrs("style" to "width: 20%")) {
+"Example"
}
}
}
traverse(definition, this, emptyList())
}
}
}
append(docHtml.toString())
}
}
private fun getJs(): String {
val inputStream = javaClass.classLoader.getResourceAsStream("doc.js")
return inputStream.bufferedReader().use {
it.readText()
}
}
private fun cssStyles(): String {
return ""
}
private fun traverse(definition: Definition, table: Table, fieldPath: List<Field<*>>) {
definition.fields
.forEach {
val currentPath = fieldPath + it
renderTableRow(currentPath, table)
if (it.type is StrictObjectType) {
traverse(it.type.definition, table, currentPath)
} else if (it.type is CompositeType) {
when (it.type.subtype) {
is StrictObjectType ->
traverse((it.type.subtype as StrictObjectType).definition, table, currentPath)
is MultiObjectType -> (it.type.subtype as MultiObjectType).types.forEach { type ->
val multiObjectPath = currentPath + Field(Field.Name(type.key), it.type.subtype as MultiObjectType, SubstituteWithDefaultHandler(EmptyObject))
renderTableRow(multiObjectPath, table)
traverse(type.value, table, multiObjectPath)
}
}
}
}
}
private fun renderTableRow(path: List<Field<*>>, table: Table) {
val fullNodeName = getFieldName(path)
table.tr(
attrs(
"data-node" to fullNodeName,
"data-node-parent" to fullNodeName.substringBeforeLast('.', "_root")))
{
td {
+path.last().name.asJsonFieldName()
}
td {
+getDescription(path.last())
}
td {
div {
+getDefaultValueType(path.last().type)
}
path.last().validator?.let {
div(attrs("style" to "padding-top: 10px")) {
+getConstraints(it)
}
}
}
td {
+getDefaultValue(path.last())
}
td {
a(attrs("href" to "#", "class" to "toggablePre")) {
+"Example"
}
pre(attrs("style" to "display: none; margin-top: 10px; margin-bottom:0px;")) {
+getJsonExample(path)
}
}
}
}
private fun getDefaultValueType(type: Type<*>): String {
return when (type) {
is StrictObjectType, is FreeObjectType -> "Object"
is ArrayType<*> -> "Array of ${getDefaultValueType(type.subtype)}"
else -> type.javaClass.simpleName.split("Type")[0]
}
}
private fun getConstraints(validator: Validator): String {
return when (validator) {
is SpecialValuesValidator<*> -> "Allowed values: ${renderKotlinValue(validator.values)}"
is RegexValidator -> "Allowed regex pattern: ${validator.pattern.toRegex()}"
is RangeValidator -> "Allowed range [${validator.fromInclusive}...${validator.toInclusive}]"
}
}
private fun getFieldName(path: List<Field<*>>) =
path.joinToString(".") { it.name.asJsonFieldName() }
private fun getDescription(field: Field<*>) =
field.description
private fun getDefaultValue(field: Field<*>) = when (field.absenceHandler) {
is RequiredHandler -> "Required. Obtained from server"
is SubstituteWithDefaultHandler<*> -> renderKotlinValue(field.absenceHandler.defaultValue)
null -> throw IllegalStateException()
}
private fun renderKotlinValue(value: Any?): String = when (value) {
is String -> "\"$value\""
is Number, is Boolean -> value.toString()
is EmptyObject -> "-"
is Collection<*> -> value.joinToString(prefix = "[", postfix = "]") {
when (it) {
is String -> "\"$it\""
else -> it.toString()
}
}
is Map<*, *> -> renderMapValue(value)
null -> "null"
else -> throw IllegalArgumentException("Unknown default type ${value::class.java}")
}
private fun renderMapValue(value: Map<*, *>): String {
return value.map { (mapKey, mapValue) -> "\"${renderKotlinValue(mapKey)}\": ${renderKotlinValue(mapValue)}" }
.joinToString(prefix = "{", postfix = "}")
}
private fun getJsonExample(path: List<Field<*>>): String {
var json = "{\n%s\n}"
path.forEachIndexed { i, field ->
json = json.format(when (field.type) {
is StrictObjectType -> "${indent(i)}\"${field.name.asJsonFieldName()}\" : {\n%s\n${indent(i)}}"
is MultiObjectType -> if (field == path.last()) getExampleJsonValue(field, field.type, i) else "%s"
is FreeObjectType -> "${indent(i)}\"${field.name.asJsonFieldName()}\" : " + when (field.type.subtype) {
is StrictObjectType -> "{\n${indent(i + 1)}\"key\" : {\n${indent(i + 1)}%s\n${indent(i + 1)}}\n${indent(i)}}"
else -> "{\n${indent(i + 1)}\"key\" : ${getExampleJsonValue(field, field.type.subtype!!)}\n${indent(i)}}"
}
is ArrayType<*> -> "${indent(i)}\"${field.name.asJsonFieldName()}\" : " + when (field.type.subtype) {
is StrictObjectType, is MultiObjectType -> "[{\n%s\n${indent(i)}}]"
else -> "[\n${indent(i + 1)}${getExampleJsonValue(field, field.type.subtype)}\n${indent(i)}]"
}
else -> "${indent(i)}\"${field.name.asJsonFieldName()}\": ${getExampleJsonValue(field, field.type)}"
})
}
return json.format("${indent(path.lastIndex + 1)}<object>")
}
private fun getExampleJsonValue(field: Field<*>, type: Type<*>, indent: Int = 0) = when (type) {
is StringType, is IntegerType, is LongType -> getValueFromValidatorOrDefault(type, field.validator)
is BoolType -> "false"
is ArrayType<*> -> "[]"
is StrictObjectType, is FreeObjectType -> "{}"
is MultiObjectType -> getFullMultiObjectValue(field, type, indent)
}
private fun getFullMultiObjectValue(field: Field<*>, type: MultiObjectType, i: Int): String {
val fieldsRepr = mutableListOf<String>()
fieldsRepr.add("${indent(i)}\"type\" : \"${field.name.rawText}\"")
type.types[field.name.rawText]?.fields?.forEach {
fieldsRepr.add("${indent(i)}\"${it.name.rawText}\" : ${getExampleJsonValue(it, it.type)}")
}
return fieldsRepr.joinToString(separator = ",\n")
}
private fun getValueFromValidatorOrDefault(type: Type<*>, validator: Validator?) = when (validator) {
is SpecialValuesValidator<*> -> "\"${validator.values[0]}\""
is RangeValidator -> validator.fromInclusive.toString()
is RegexValidator, null -> when (type) {
is StringType -> "\"abc\""
is IntegerType -> "42"
is LongType -> "42"
else -> throw IllegalStateException("wrongs pair of validator and type")
}
}
private fun indent(num: Int) = " ".repeat(num + 1)
}<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/Renderer.kt
package ru.mail.condef.renderer
public interface Renderer {
fun render(writer:TextWriter)
}<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/dsl/Definition.kt
package ru.mail.condef.dsl
class Definition(val fields: List<Field<*>>)
fun definition(vararg fields: Field<*>) = Definition(listOf(*fields))
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/ConfigSettingsDefinitionRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
class ConfigSettingsDefinitionRenderer(
rootDefinition: Definition,
packageName: String
) : JavaCodeRenderer(rootDefinition, packageName) {
override fun listDependencies(): List<String> =
super.listDependencies() + listOf("ru.mail.flexsettings.field.Field")
override fun render(writer: TextWriter) {
super.render(writer)
writer.codeBlock("public class ConfigSettingsDefinition") {
codeBlock("public static Field create()") {
append("return Field.strictObject(\"base\",")
renderDefinition(this, definition)
append(");")
}
}
}
private fun renderDefinition(writer: TextWriter, definition: Definition) {
with(writer.withIncreasedIndentation()) {
definition.fields.forEachIndexed { index, field ->
if (index != 0) {
append(",").nextLine()
}
renderType(field.key(), field.type)
}
}
}
private fun TextWriter.renderType(key: String, type: Type<*>) {
when (type) {
is StringType -> renderStringField(key)
is BoolType -> renderBooleanField(key)
is IntegerType -> renderIntegerField(key)
is LongType -> renderLongField(key)
is StrictObjectType -> renderStrictObjectField(key, type)
is FreeObjectType -> renderFreeObjectField(key, type)
else -> renderUnsupported(key, type)
}
}
private fun TextWriter.renderStringField(key: String) {
renderPrimitiveField("string", key)
}
private fun TextWriter.renderBooleanField(key: String) {
renderPrimitiveField("bool", key)
}
private fun TextWriter.renderIntegerField(key: String) {
renderPrimitiveField("integer", key)
}
private fun TextWriter.renderLongField(key: String) {
renderPrimitiveField("longField", key)
}
private fun TextWriter.renderPrimitiveField(type: String, key: String) {
append("Field.$type(\"$key\")")
}
private fun TextWriter.renderStrictObjectField(key: String, type: StrictObjectType) {
append("Field.strictObject(\"$key\",")
renderDefinition(this, type.definition)
append(")")
}
private fun TextWriter.renderFreeObjectField(key: String, type: FreeObjectType) {
append("Field.freeObject(\"$key\",")
with(withIncreasedIndentation()) {
renderType("", type.subtype!!)
}
append(")")
}
private fun TextWriter.renderUnsupported(key: String, type: Type<*>) {
append("Field.empty(\"$key | ${type.javaClass.simpleName} \")")
}
private fun TextWriter.codeBlock(header: String, block: TextWriter.() -> Unit) {
appendLine("$header {")
with(withIncreasedIndentation()) {
block()
}
append("}")
}
private fun Field<*>.key() = name.rawText
}
<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/field/Field.java
package ru.mail.flexsettings.field;
public abstract class Field implements Comparable<Field> {
private final String mName;
private boolean mIsChanged;
public Field(String name) {
mName = name;
}
public String getName() {
return mName;
}
public boolean isChanged() {
return mIsChanged;
}
public void markChanged() {
mIsChanged = true;
}
public void setChanged(boolean isChanged) {
mIsChanged = isChanged;
}
public static StringField string(String name) {
return new StringField(name);
}
public boolean isString() {
return this instanceof StringField;
}
public StringField asString() {
return (StringField) this;
}
public static BooleanField bool(String name) {
return new BooleanField(name);
}
public boolean isBoolean() {
return this instanceof BooleanField;
}
public BooleanField asBoolean() {
return (BooleanField) this;
}
public static IntegerField integer(String name) {
return new IntegerField(name);
}
public boolean isInteger() {
return this instanceof IntegerField;
}
public IntegerField asInteger() {
return (IntegerField) this;
}
public static LongField longField(String name) {
return new LongField(name);
}
public boolean isLong() {
return this instanceof LongField;
}
public LongField asLong() {
return (LongField) this;
}
public static StrictObjectField strictObject(String name, Field... fields) {
return new StrictObjectField(name, fields);
}
public boolean isStrictObject() {
return this instanceof StrictObjectField;
}
public StrictObjectField asStrictObject() {
return (StrictObjectField) this;
}
public boolean isObject() {
return this instanceof ObjectField;
}
public ObjectField asObject() {
return (ObjectField) this;
}
public static FreeObjectField freeObject(String name, Field baseField) {
return new FreeObjectField(name, baseField);
}
public boolean isFreeObject() {
return this instanceof FreeObjectField;
}
public FreeObjectField asFreeObject() {
return (FreeObjectField) this;
}
public PrimitiveField<?> asPrimitive() {
return (PrimitiveField<?>) this;
}
public static EmptyField empty(String name) {
return new EmptyField(name);
}
public abstract Field copy(String name);
@Override
public int compareTo(Field o) {
return getName().compareTo(o.getName());
}
}
<file_sep>/settings.gradle
include ':app'
include ':flexsettings'
<file_sep>/app/build.gradle
import task.*
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "ru.mail.configen"
minSdkVersion 21
targetSdkVersion 29
versionCode getVersionCodeCustom()
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
static def getVersionCodeCustom() {
return 1
}
task configGenTask(type: ConfigGenerationTask) {
configurationDefinition = new File(project.rootDir, "buildSrc/src/main/kotlin/dsl/Config.kt")
packageName = "ru.mail.configen"
jsonParserClassName = "DTOConfigurationJsonParser"
configurationClassName = "DTOConfigurationImpl"
configurationInterfaceName = "DTOConfiguration"
settingsDefinitionClassName = "ConfigSettingsDefinition"
settingsMapperClassName = "ConfigSettingsMapper"
destDir = "${project.buildDir.toString()}/generated/source/modelConfig"
documentationFile = new File(project.rootProject.rootDir.absolutePath, "configuration.html")
buildVersion = getVersionCodeCustom()
android.sourceSets.main.java.srcDirs += destDir
}
project.afterEvaluate {
preBuild.dependsOn(configGenTask)
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0-RC"
implementation 'androidx.core:core-ktx:1.0.2'
implementation project(':flexsettings')
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/ConfigSettingsMapperRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
class ConfigSettingsMapperRenderer(
rootDefinition: Definition,
packageName: String
) : JavaCodeRenderer(rootDefinition, packageName) {
override fun listDependencies(): List<String> =
super.listDependencies() + listOf("Field", "StrictObjectField", "FreeObjectField").map { "ru.mail.flexsettings.field.$it" }
override fun render(writer: TextWriter) {
super.render(writer)
writer.codeBlock("public class ConfigSettingsMapper") {
codeBlock("public static void map(StrictObjectField configurationField, DTOConfiguration configuration, DTOConfiguration configurationState)") {
initDefinition("DTOConfiguration", "configuration", definition)
}
}
}
private fun TextWriter.initPrimitive(parentObjectName : String, type : String, field : Field<*>) {
val fieldGetter = "${parentObjectName}Field.getField(\"${field.key()}\")"
appendLine("$fieldGetter.as${type.capitalize()}().setValue($parentObjectName.${field.getterName()}());")
appendLine("$fieldGetter.setChanged(${parentObjectName}State.${field.getterName()}Set());")
}
private fun TextWriter.initStrictObject(parentClassName: String, parentObjectName: String, field: Field<*>) {
val className = "$parentClassName.${field.name.asClassName()}"
val objectName = field.name.asFieldName()
val fieldName = objectName + "Field"
nextLine()
appendLine("StrictObjectField $fieldName = ${parentObjectName}Field.getField(\"${field.key()}\").asStrictObject();")
appendLine("$className $objectName = $parentObjectName.${field.getterName()}();")
appendLine("$className ${objectName}State = ${parentObjectName}State.${field.getterName()}();")
appendLine("$fieldName.setChanged(${parentObjectName}State.${field.getterName()}Set());")
initDefinition(className, objectName, (field.type as StrictObjectType).definition)
}
private fun TextWriter.initFreeObject(parentClassName: String, parentObjectName: String, field: Field<*>) {
val className = "$parentClassName.${field.name.asClassName()}"
val objectName = field.name.asFieldName()
val fieldName = objectName + "Field"
val type = field.type as FreeObjectType
val mapClass = when (type.subtype) {
is StringType -> "String"
is StrictObjectType -> className
else -> "Void"
}
appendLine("FreeObjectField $fieldName = ${parentObjectName}Field.getField(\"${field.key()}\").asFreeObject();")
appendLine("$fieldName.setChanged(${parentObjectName}State.${field.getterName()}Set());")
appendLine("Map<String, $mapClass> $objectName = $parentObjectName.${field.getterName()}();")
appendLine("for (Map.Entry<String, $mapClass> entry : $objectName.entrySet()) {")
with(withIncreasedIndentation()) {
if (type.subtype is StringType) {
append("$fieldName.addField(entry.getKey()).asString().setValue(entry.getValue());")
appendLine("$fieldName.getField(entry.getKey()).setChanged($fieldName.isChanged());")
} else {
append("// TODO add support of ${type.subtype}")
}
}
append("}")
}
private fun TextWriter.initDefinition(parentClassName: String, parentObjectName: String, definition: Definition) {
definition.fields.forEach {
when (it.type) {
is StringType -> initPrimitive(parentObjectName, "string", it)
is BoolType -> initPrimitive(parentObjectName, "boolean", it)
is IntegerType -> initPrimitive(parentObjectName, "integer", it)
is LongType -> initPrimitive(parentObjectName, "long", it)
is StrictObjectType -> initStrictObject(parentClassName, parentObjectName, it)
is FreeObjectType -> initFreeObject(parentClassName, parentObjectName, it)
else -> appendLine("// ${it.name.asFieldName()} - ${it.type}")
}
}
}
private fun TextWriter.codeBlock(header: String, block: TextWriter.() -> Unit) {
appendLine("$header {")
with(withIncreasedIndentation()) {
block()
}
append("}")
}
private fun Field<*>.key() = name.rawText
private fun Field<*>.getterName() = name.asGetterName(type)
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/dsl/Absence.kt
package ru.mail.condef.dsl
sealed class AbsenceHandler
class SubstituteWithDefaultHandler<out T>(val defaultValue: T) : AbsenceHandler()
class RequiredHandler : AbsenceHandler()
fun requiredHandler() : RequiredHandler {
return RequiredHandler()
}<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/field/IntegerField.java
package ru.mail.flexsettings.field;
public class IntegerField extends PrimitiveField<Integer> {
public IntegerField(String name) {
super(name, 0);
}
@Override
public Field copy(String name) {
return new IntegerField(name);
}
@Override
public String toString() {
return "(IntegerField) \"" + getName() + "\" = " + getValue();
}
}
<file_sep>/README.md
# configen
Sample project to demonstrate usage of Kotlin DSL for Android application configuration purposes.
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/AnalyticsSenderRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
class AnalyticsSenderRenderer(val packageName: String) : Renderer {
override fun render(writer: TextWriter) {
with(writer) {
append("/*").nextLine()
append(" * Automatically generated file. DO NOT MODIFY").nextLine()
append("*/").nextLine().nextLine()
append("package $packageName;").nextLine(2)
append("public interface AnalyticsSender {")
withIncreasedIndentation().append("public void sendParsingConfigError(String fieldName, String reason, String actionTaken);")
append("}")
}
}
}<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/FieldFragment.java
package ru.mail.flexsettings;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.fragment.app.Fragment;
import ru.mail.flexsettings.field.Field;
public class FieldFragment extends Fragment {
private Field mField;
private FieldChangeListener mChangeListener;
public FieldFragment() {
}
@SuppressLint("ValidFragment")
public FieldFragment(Field field, FieldChangeListener changeListener) {
this();
mField = field;
mChangeListener = changeListener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
ListView list = view.findViewById(R.id.free_type_fragment);
if (mField.isObject()) {
FieldAdapter adapter = new FieldAdapter((FlexSettingsActivity) getActivity(), mField.asObject(), mChangeListener);
list.setAdapter(adapter);
}
return view;
}
}
<file_sep>/app/src/main/java/ru/mail/configen/MainActivity.kt
package ru.mail.configen
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import kotlinx.coroutines.*
const val reqCodeSetSettings = 1234
class MainActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val configView: TextView = findViewById(R.id.config)
GlobalScope.launch(Dispatchers.Main) {
val config = ConfigurationDelegate().loadConfig(applicationContext)
configView.text = "received config: \n" +
"config.fieldRoot ${config.fieldRoot}\n" +
"config.feature.field1 ${config.feature.field1}\n" +
"config.feature.field2 ${config.feature.field2}\n" +
"config.feature.field3 ${config.feature.field3}\n" +
"config.feature.nestedConfig.nestedField1 ${config.feature.nestedConfig.nestedField1}\n" +
"config.feature.nestedConfig.nestedField2 ${config.feature.nestedConfig.nestedField2}\n" +
""
}
findViewById<View>(R.id.dev_settings).setOnClickListener {
val intent = Intent(this@MainActivity, DeveloperSettingsActivity::class.java)
startActivityForResult(intent, reqCodeSetSettings)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == reqCodeSetSettings) {
recreate()
}
}
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/JavaCodeRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
import java.util.*
fun String.toCamelCase() =
split('_', '-', ' ').joinToString("") { it.capitalize() }
fun Field.Name.asClassName() = if (customName.isEmpty()) rawText.toCamelCase() else customName.toCamelCase()
fun Field.Name.asFieldName() = asClassName().decapitalize()
fun Field.Name.asGetterName(type: Type<*>) = when (type) {
is BoolType -> "is"
else -> "get"
} + asClassName()
fun Field.Name.asSetterName() = "set" + asClassName()
fun Field.Name.asJsonFieldName() = rawText
fun inferFieldTypeName(name: Field.Name, type: Type<*>): String = when (type) {
is StringType -> "String"
is IntegerType -> "Integer"
is LongType -> "Long"
is BoolType -> "Boolean"
is FreeObjectType -> "Map<String, ${inferFieldTypeName(name, type.subtype!!)}>"
is StrictObjectType -> name.asClassName()
is ArrayType<*> -> "List<${inferFieldTypeName(name, type.subtype)}>"
is MultiObjectType -> "${name.asClassName()}Base"
}
fun asPredefinedCollection(values: List<*>): String {
return "Arrays.asList(${values.joinToString {
when (it) {
is String -> "\"${it.toLowerCase(Locale.ENGLISH)}\""
is Int -> "$it"
is Long -> "${it}L"
else -> throw IllegalStateException("unsupported default type")
}
}})"
}
abstract class JavaCodeRenderer(val definition: Definition, val packageName: String) : Renderer {
override fun render(writer: TextWriter) {
with(writer) {
append("/*").nextLine()
append(" * Automatically generated file. DO NOT MODIFY").nextLine()
append("*/").nextLine().nextLine()
append("package $packageName;").nextLine(2)
performChecks(collectAllFieldsRecursively(definition))
listDependencies().forEach { import ->
append("import $import;")
nextLine()
}
}
}
protected open fun performChecks(fields: List<Field<*>>) {
checkUniqueClassNames(fields)
checkReservedWordsCollisions(fields)
checkUniqueParseMethodNames(fields)
checkUnsupportedRecursionTypes<ArrayType<*>>(fields)
checkUnsupportedRecursionTypes<FreeObjectType>(fields)
}
private fun checkReservedWordsCollisions(fields: List<Field<*>>) {
fields
.firstOrNull { reservedJavaWords.contains(it.name.asFieldName()) }
?.let {
throw IllegalStateException("Generated field `${it.name.asFieldName()}` clashes with reserved Java keyword, specify different name using `withFieldName`")
}
}
private inline fun <reified T : CompositeType> checkUnsupportedRecursionTypes(fields: List<Field<*>>) {
fields
.firstOrNull { it.type is T && it.type.subtype is T }
?.let {
throw IllegalStateException("${T::class.java} of ${T::class.java} does not supported")
}
}
private fun checkUniqueClassNames(fields: List<Field<*>>) {
fields
.filter { it.type is StrictObjectType || (it.type is ArrayType<*> && it.type.subtype is StrictObjectType) }
.groupBy { it.name.asClassName() }
.asIterable()
.firstNonSingle()
?.let {
throw IllegalStateException("Duplicate generated ClassName in Field `${it.key}`, specify custom class name using `withClassName`")
}
}
private fun checkUniqueParseMethodNames(fields: List<Field<*>>) {
fields
.filter { it.type is StrictObjectType || (it.type is ArrayType<*> || it.type is FreeObjectType) }
.groupBy { it.name.asClassName() + it.type.javaClass.simpleName }
.asIterable()
.firstNonSingle()
?.let {
throw IllegalStateException("Duplicate generated Method name in Field `${it.key}`, specify custom class name using `withClassName`")
}
}
private fun <T : Map.Entry<*, Collection<*>>> Iterable<T>.firstNonSingle(): T? {
return this.firstOrNull { it.value.size > 1 }
}
private fun collectAllFieldsRecursively(definition: Definition): List<Field<*>> {
return definition.fields
.flatMap {
val type = it.type
listOf(it) + if (type is StrictObjectType) {
collectAllFieldsRecursively(type.definition)
} else if (type is CompositeType && type.subtype is StrictObjectType) {
collectAllFieldsRecursively((type.subtype as StrictObjectType).definition)
} else if (type is MultiObjectType) {
type.types.values.flatMap { collectAllFieldsRecursively(it) }
} else {
emptyList()
}
}
}
protected open fun listDependencies(): List<String>
= listOf("List", "Map", "Set", "Collection", "Collections", "ArrayList", "HashMap", "HashSet", "Iterator", "Arrays", "regex.*", "Locale").map { "java.util.$it" }
companion object {
val reservedJavaWords = setOf("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "default",
"do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements",
"import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected",
"public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws",
"transient", "true", "try", "void", "volatile", "while", "continue")
}
}<file_sep>/app/src/main/java/ru/mail/configen/ConfigurationDelegate.kt
package ru.mail.configen
import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.File
class ConfigurationDelegate {
private val devConfig = "dev_config.json"
private val etalonConfig = "etalon_config.json"
suspend fun loadConfig(context: Context): DTOConfiguration {
return withContext(Dispatchers.IO) {
val parser = DTOConfigurationJsonParser(AnalyticsSenderImpl())
val file = File(context.filesDir, devConfig)
var developerSettings: DTOConfigurationImpl? = null
if (file.exists()) {
developerSettings = parser.parse(JSONObject(file.readText()))
}
val etalon = parser.parse(
JSONObject(context.resources.assets.open(etalonConfig)
.bufferedReader()
.use {
it.readText()
})
)
if (developerSettings != null) {
developerSettings.merge(etalon)
developerSettings
} else {
etalon
}
}
}
suspend fun loadDeveloperSettings(context: Context): DTOConfiguration {
return withContext(Dispatchers.IO) {
val file = File(context.filesDir, devConfig)
if (file.exists()) {
DTOConfigurationJsonParser(AnalyticsSenderImpl()).parse(JSONObject(file.readText()))
} else {
DTOConfigurationImpl()
}
}
}
suspend fun saveDeveloperSettings(context: Context, config: String) {
withContext(Dispatchers.IO) {
File(context.filesDir, devConfig).writeText(config)
}
}
class AnalyticsSenderImpl : AnalyticsSender {
override fun sendParsingConfigError(fieldName: String?, reason: String?, actionTaken: String?) {
Log.d("Parsing", "$fieldName validation error $reason $actionTaken")
}
}
}<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/dsl/Fields.kt
package ru.mail.condef.dsl
import java.util.regex.Pattern
data class Field<N>(
val name: Name,
val type: Type<N>,
val absenceHandler: AbsenceHandler? = null,
val validator: Validator? = null,
val description: String = ""
) {
data class Name(val rawText: String, val customName: String = "")
}
infix fun <N> String.of(type: Type<N>) = Field(Field.Name(this), type)
private fun <T, N> Field<N>.checkRedefinition(actual: T, expected: T, fieldName: String, newInstance: Field<N>): Field<N> {
if (actual == expected) {
return newInstance
} else {
throw IllegalArgumentException("Redefinition of $fieldName in field $name")
}
}
infix fun <N> Field<N>.withDescription(description: String): Field<N> = checkRedefinition(
this.description, "", "description", copy(description = description)
)
infix fun <N> Field<N>.withDefault(newDefaultValue: N?): Field<N> = checkRedefinition(
absenceHandler, null, "default",
copy(absenceHandler = SubstituteWithDefaultHandler(newDefaultValue))
)
infix fun <N> Field<N>.withAbsenceHandler(handler: AbsenceHandler): Field<N> = checkRedefinition(
absenceHandler, null, "default",
copy(absenceHandler = handler)
)
infix fun <N> Field<N>.withAllowedValues(values: List<N>): Field<N> = checkRedefinition(
validator, null, "validator",
copy(validator = SpecialValuesValidator(values))
)
infix fun <N> Field<List<N>>.withAllowedValuesInArray(values: List<N>): Field<List<N>> = checkRedefinition(
validator, null, "validator",
copy(validator = SpecialValuesValidator(values))
)
infix fun Field<Int>.withAllowedRange(range: IntRange): Field<Int> = checkRedefinition(
validator, null, "validator",
copy(validator = RangeValidator(range.start, range.endInclusive))
)
infix fun Field<String>.withAllowedPattern(pattern: Pattern): Field<String> = checkRedefinition(
validator, null, "validator",
copy(validator = RegexValidator(pattern))
)
infix fun <N> Field<N>.withClassName(className: String): Field<N> = checkRedefinition(
validator, null, "validator",
copy(name = Field.Name(this.name.rawText, className))
)
infix fun Field<Any?>.withValuesType(type: Type<*>): Field<Any?> =
Field(name, FreeObjectType(type), absenceHandler, validator, description)
infix fun Field<Any?>.withValuesType(definition: Definition): Field<Any?> =
Field(name, FreeObjectType(StrictObjectType(definition)), absenceHandler, validator, description)
infix fun <N> Field<N>.withFieldName(fieldName: String): Field<N> = withClassName(fieldName)
infix fun Field<List<String>>.withAllowedPatternOfEachElement(pattern: Pattern): Field<List<String>> = checkRedefinition(
validator, null, "validator",
copy(validator = RegexValidator(pattern))
)
infix fun Field<Any?>.restrictedBy(definition: Definition): Field<Unit?> =
Field(name, StrictObjectType(definition), absenceHandler, validator, description)
infix fun Field<List<Any?>>.withEachElementRestrictedBy(definition: Definition): Field<List<Unit?>> =
Field(name, ArrayType(StrictObjectType(definition)), absenceHandler, validator, description)
infix fun Field<List<Any?>>.withEachElementRestrictedByAnyOf(definitions: Map<String, Definition>): Field<List<Unit?>> =
Field(name, ArrayType(MultiObjectType(definitions)), absenceHandler, validator, description)
infix fun Field<List<Any?>>.withEachElementAllowedValuesType(type: Type<*>): Field<List<Any?>> =
Field(name, ArrayType(FreeObjectType(type)), absenceHandler, validator, description)
infix fun Field<List<Any?>>.withEachElementAllowedValuesType(definition: Definition): Field<List<Any?>> =
Field(name, ArrayType(FreeObjectType(StrictObjectType(definition))), absenceHandler, validator, description)
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/ConfigCodeRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
class ConfigCodeRenderer(
rootDefinition: Definition,
strategy: CodeGenerationStrategy,
packageName: String) : JavaCodeRenderer(rootDefinition, packageName) {
private val rootInterface = ContentsCodeRenderer(rootDefinition, strategy)
override fun render(writer: TextWriter) {
super.render(writer)
writer.append(rootInterface)
}
open class ContentsCodeRenderer(
definition: Definition,
private val codeGeneration: CodeGenerationStrategy) : Renderer {
internal val renderers = mutableListOf<Renderer>()
init {
renderers.addAll(codeGeneration.createRendersForFields(definition.fields))
val definitionsFromReturnTypes = definition.fields
.filter { it.type is StrictObjectType }
.map { Pair((it.type as StrictObjectType).definition, it.name.asClassName()) }
renderers.addAll(codeGeneration.createRendersForDefinitions(definitionsFromReturnTypes))
val definitionsFromCompositeTypes = definition.fields
.filter { it.type is CompositeType && it.type.subtype is StrictObjectType }
.map { Pair(((it.type as CompositeType).subtype as StrictObjectType).definition, it.name.asClassName()) }
renderers.addAll(codeGeneration.createRendersForDefinitions(definitionsFromCompositeTypes))
var definitionsFromMultiObjectTypes = definition.fields
.filter { it.type is MultiObjectType }
.map { Pair((it.type as MultiObjectType).types, it.name.asClassName()) }
definitionsFromMultiObjectTypes += definition.fields
.filter { it.type is CompositeType && it.type.subtype is MultiObjectType }
.map { Pair((((it.type as CompositeType).subtype as MultiObjectType).types), it.name.asClassName()) }
renderers.addAll(codeGeneration.createRendersForMultiObjectDefinitions(definitionsFromMultiObjectTypes))
renderers.add(codeGeneration.createRendererForMerge(definition.fields, codeGeneration.className))
}
override fun render(writer: TextWriter) {
writer.nextLine()
writer.append("public ${codeGeneration.entityHeader} {")
writer.withIncreasedIndentation().join(renderers) { nextLine(2) }
writer.append("}")
}
}
}
interface CodeGenerationStrategy {
val entityHeader: String
val className: String
fun createRendersForFields(fields: List<Field<*>>): Collection<Renderer>
fun createRendersForDefinitions(definitions: List<Pair<Definition, String>>): Collection<Renderer>
fun createRendersForMultiObjectDefinitions(types: List<Pair<Map<String, Definition>, String>>): Collection<Renderer>
fun createRendererForMerge(fields: List<Field<*>>, currentClassType: String) : Renderer
fun redefineNames(fieldName: String, superType: String = ""): CodeGenerationStrategy
}
class InterfaceGenerationStrategy(private val name: String, private val superType: String = "") : CodeGenerationStrategy {
override val entityHeader: String
get() = "interface $name" + if (superType.isEmpty()) "" else " extends $superType"
override val className: String
get() = name
override fun createRendersForFields(fields: List<Field<*>>): Collection<Renderer> {
return fields.map { InterfaceGetterRenderer(it.name, it.type) }
}
override fun createRendersForDefinitions(definitions: List<Pair<Definition, String>>): Collection<Renderer> {
return definitions.map { ConfigCodeRenderer.ContentsCodeRenderer(it.first, this.redefineNames(it.second)) }
}
override fun redefineNames(fieldName: String, superType: String): CodeGenerationStrategy = InterfaceGenerationStrategy(fieldName, superType)
override fun createRendersForMultiObjectDefinitions(types: List<Pair<Map<String, Definition>, String>>)
: Collection<Renderer> {
return types.flatMap {
val baseName = it.second.capitalize().toCamelCase()
val mapping = it.first
listOf(MultiObjectBaseInterface(baseName, mapping.keys.toList())) +
mapping.entries.map {
ConfigCodeRenderer.ContentsCodeRenderer(it.value, redefineNames(
baseName + it.key.capitalize().toCamelCase(), "${baseName}Base"))
}
}
}
override fun createRendererForMerge(fields: List<Field<*>>, currentClassType: String) : Renderer {
return MergeMethodRenderer(fields, currentClassType)
}
private data class InterfaceGetterRenderer(val name: Field.Name, val type: Type<*>) : Renderer {
override fun render(writer: TextWriter) {
writer.append("${inferFieldTypeName(name, type)} ${name.asGetterName(type)}();")
writer.appendLine("boolean ${name.asGetterName(type)}Set();")
}
}
private data class MultiObjectBaseInterface(val name: String, val subtypes: List<String>) : Renderer {
override fun render(writer: TextWriter) {
with(writer) {
append("public interface ${name}Base {")
withIncreasedIndentation().apply {
append("<T> T accept(Visitor<T> visitor);").nextLine(2)
append("interface Visitor<T> {")
withIncreasedIndentation().apply {
join(subtypes.map {
"T on${it.capitalize().toCamelCase()}(${name + it.capitalize().toCamelCase()} dto);".asRenderer()
}, { nextLine(2) })
}
append("}")
}
append("}")
}
}
fun String.asRenderer(): Renderer {
return object : Renderer {
override fun render(writer: TextWriter) {
writer.append(this@asRenderer)
}
}
}
}
private data class MergeMethodRenderer(
val fields: List<Field<*>>,
val name: String) : Renderer {
override fun render(writer: TextWriter) {
writer.append("public void merge($name from);")
}
}
}
class ImplementationGenerationStrategy(
private val interfaceName: String,
private val implName: String,
private val static: Boolean = true) : CodeGenerationStrategy {
override val entityHeader: String
get() = "${if (static) "static " else ""}class $implName implements $interfaceName"
override val className: String
get() = interfaceName
override fun createRendersForFields(fields: List<Field<*>>): Collection<Renderer> {
return fields.map { FieldRenderer(it.name, it.type, it.absenceHandler!!) } +
fields.map { GetterAndSetterRenderer(it.name, it.type) }
}
override fun createRendersForDefinitions(definitions: List<Pair<Definition, String>>): Collection<Renderer> {
return definitions.map { ConfigCodeRenderer.ContentsCodeRenderer(it.first, this.redefineNames(it.second)) }
}
override fun redefineNames(fieldName: String, superType: String): CodeGenerationStrategy
= ImplementationGenerationStrategy(fieldName, fieldName + "Impl")
override fun createRendersForMultiObjectDefinitions(types: List<Pair<Map<String, Definition>, String>>): Collection<Renderer> {
return types.flatMap {
val baseName = it.second.capitalize().toCamelCase()
val mapping = it.first
mapping.entries.map {
MultiObjectImplRenderer(it.value, redefineNames(
baseName + it.key.capitalize().toCamelCase()), it.key)
}
}
}
override fun createRendererForMerge(fields: List<Field<*>>, currentClassType: String) : Renderer {
return MergeMethodRenderer(fields, currentClassType)
}
private class MultiObjectImplRenderer(rootDefinition: Definition,
strategy: CodeGenerationStrategy,
className: String)
: ConfigCodeRenderer.ContentsCodeRenderer(rootDefinition, strategy) {
init {
renderers.add(VisitorMethodRenderer(className))
}
class VisitorMethodRenderer(private val className: String) : Renderer {
override fun render(writer: TextWriter) {
with(writer) {
append("@Override").nextLine()
append("public <T> T accept(Visitor<T> visitor) {")
with(withIncreasedIndentation()) {
append("return visitor.on${className.toCamelCase()}(this);")
}
append("}")
}
}
}
}
private data class FieldRenderer(
private val name: Field.Name,
private val type: Type<*>,
private val absenceHandler: AbsenceHandler) : Renderer {
private var internalWriter = TextWriter()
override fun render(writer: TextWriter) {
internalWriter = writer.newWriter()
val inferredDefault = inferDefault()
val baseLine = "private ${inferFieldTypeName(name, type)} m${name.asClassName()}"
if (inferredDefault != null) {
writer.append("$baseLine = $inferredDefault;")
} else {
writer.append("$baseLine;")
}
writer.nextLine()
writer.append("private boolean m${name.asClassName()}Set = false;")
}
private fun inferDefault(): String? = when (absenceHandler) {
is SubstituteWithDefaultHandler<*> -> inferDefaultValue(type, absenceHandler.defaultValue)
is RequiredHandler -> null
}
private fun inferDefaultValue(type: Type<*>, defaultValue: Any?): String = when (type) {
is StringType -> if (defaultValue is String) "\"$defaultValue\"" else "null"
is IntegerType -> "${defaultValue!! as Int}"
is LongType -> "${defaultValue!! as Long}L"
is BoolType -> "${defaultValue!! as Boolean}"
is FreeObjectType -> inferMapDefaultValue(type, defaultValue)
is StrictObjectType -> inferStrictObjectDefaultValue(defaultValue)
is MultiObjectType -> inferMultiObjectDefaultValue(defaultValue)
is ArrayType<*> -> inferArrayDefaultValues(defaultValue as List<*>)
}
private fun inferMultiObjectDefaultValue(defaultValue: Any?): String = when (defaultValue) {
null -> "null"
else -> throw IllegalStateException()
}
private fun inferMapDefaultValue(type: FreeObjectType, defaultValue: Any?): String = when (defaultValue) {
is Map<*, *> -> {
var initialValue = "new HashMap<>()"
if (!defaultValue.isEmpty()) {
if (type.subtype!! is StrictObjectType) {
initialValue = "new HashMap<String, ${inferFieldTypeName(name, type.subtype)}>() {{"
val writer = internalWriter.withIncreasedIndentation()
val definition = (type.subtype as StrictObjectType).definition
writer.append("${name.asClassName()}Impl toFill = null;").nextLine()
for (pair in defaultValue) {
writer.append("toFill = new ${name.asClassName()}Impl();").nextLine()
for (field in definition.fields) {
val arg = inferDefaultValue(field.type, (pair.value as Map<*, *>)[field.name.rawText])
writer.append("toFill.${field.name.asSetterName()}($arg);").nextLine()
}
writer.append("put(\"${pair.key.toString()}\", toFill);").nextLine(2)
}
}
}
initialValue + internalWriter.append("}}")
}
else -> "new HashMap<>()"
}
private fun inferStrictObjectDefaultValue(defaultValue: Any?): String = when (defaultValue) {
is EmptyObject -> "new ${name.asClassName()}Impl()"
null -> "null"
else -> throw IllegalStateException()
}
private fun inferArrayDefaultValues(defaultValue: List<*>): String {
return when {
defaultValue.isNotEmpty() -> asPredefinedCollection(defaultValue)
else -> "Collections.emptyList()"
}
}
}
private data class GetterAndSetterRenderer(
private val name: Field.Name,
private val type: Type<*>) : Renderer {
override fun render(writer: TextWriter) {
writer.append("@Override").nextLine()
writer.append("public ${inferFieldTypeName(name, type)} ${name.asGetterName(type)}() {")
writer.withIncreasedIndentation().append("return m${name.asClassName()};")
writer.append("}").nextLine(2)
writer.append("@Override").nextLine()
writer.append("public boolean ${name.asGetterName(type)}Set() {")
writer.withIncreasedIndentation().append("return m${name.asClassName()}Set;")
writer.append("}").nextLine(2)
writer.append("public void ${name.asSetterName()}(${inferFieldTypeName(name, type)} ${name.asFieldName()}) {")
with(writer.withIncreasedIndentation()) {
append("m${name.asClassName()}Set = true;").nextLine()
append("m${name.asClassName()} = ${name.asFieldName()};")
}
writer.append("}")
}
}
private data class MergeMethodRenderer(
val fields: List<Field<*>>,
val name: String) : Renderer {
override fun render(writer: TextWriter) {
writer.append("@Override").nextLine()
writer.append("public void merge($name from) {")
writer.nextLine()
for (field in fields) {
with(writer.withIncreasedIndentation()) {
if (field.type is StrictObjectType) {
writer.append("m${field.name.asClassName()}.merge(from.${field.name.asGetterName(field.type)}());")
} else {
writer.append("if(!m${field.name.asClassName()}Set && from.${field.name.asGetterName(field.type)}Set()) {")
writer.append("${field.name.asSetterName()}(from.${field.name.asGetterName(field.type)}());")
writer.append("}")
}
}
}
writer.append("}").nextLine()
}
}
}
<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/field/BooleanField.java
package ru.mail.flexsettings.field;
public class BooleanField extends PrimitiveField<Boolean> {
public BooleanField(String name) {
super(name, false);
}
@Override
public Field copy(String name) {
return new BooleanField(name);
}
@Override
public String toString() {
return "(BooleanField) \"" + getName() + "\" = " + getValue();
}
}
<file_sep>/buildSrc/src/main/kotlin/task/ConfigGenerationTask.kt
package task
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import ru.mail.condef.main.ConfigGenerator
import java.io.File
open class ConfigGenerationTask : DefaultTask() {
/*
* Package name for the generated classes.
*/
lateinit var packageName: String
/*
* Dest dir for classes
*/
lateinit var destDir: String
/*
* JSON parser class name.
*/
lateinit var jsonParserClassName: String
/*
* Configuration class name.
*/
lateinit var configurationClassName: String
/*
* Configuration class name.
*/
lateinit var configurationInterfaceName: String
/*
* Configuration settings definition class name.
*/
lateinit var settingsDefinitionClassName: String
/*
* Configuration settings mapper class name.
*/
lateinit var settingsMapperClassName: String
/*
* Configuration definition file.
*/
@InputFile
lateinit var configurationDefinition: File
/*
* Documentation file.
*/
@OutputFile
lateinit var documentationFile: File
/*
* Build version.
*/
lateinit var buildVersion: String
@TaskAction
fun executeTask() {
println("========== Generating config =========")
println(configurationDefinition.length())
println("Destination: ${getOutputDirName()}, " +
"Parser: $jsonParserClassName, " +
"Interface: $configurationInterfaceName, " +
"Impl: $configurationClassName")
ConfigGenerator(
packageName,
configurationInterfaceName,
configurationClassName,
jsonParserClassName,
settingsDefinitionClassName,
settingsMapperClassName,
getOutputDirName().absolutePath,
documentationFile,
buildVersion)
.generate()
}
@OutputDirectory
private fun getOutputDirName(): File {
return File(destDir + "/" + packageName.replace('.', '/'))
}
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/TextWriter.kt
package ru.mail.condef.renderer
class TextWriter(private val indentation: Int = 0) {
private val lines = mutableListOf<Any>()
private val line = StringBuilder()
init {
line.append(" ".repeat(indentation))
}
fun newWriter() = TextWriter(indentation)
fun withIncreasedIndentation(): TextWriter {
nextLine()
val writer = TextWriter(indentation + Constants.INDENTATION_STEP)
lines.add(writer)
return writer
}
fun append(append: String): TextWriter = apply { line.append(append) }
fun appendLine(append: String): TextWriter = apply { nextLine().append(append) }
fun append(renderer: Renderer): TextWriter = apply { renderer.render(this) }
fun join(renderers: Collection<Renderer>, joiner: TextWriter.() -> Unit): TextWriter {
for ((i, renderer) in renderers.withIndex()) {
append(renderer)
if (i != renderers.size - 1) {
this.joiner()
}
}
return this
}
fun nextLine(linesToAdd: Int = 1): TextWriter = apply {
for (i in 0..(linesToAdd - 1)) {
commitLine()
initNewLine()
}
}
private fun commitLine() {
lines.add(line.toString())
}
private fun initNewLine() {
line.setLength(0)
line.append(" ".repeat(indentation))
}
override fun toString(): String {
commitLine()
return lines.joinToString("\n")
}
companion object Constants {
private const val INDENTATION_STEP: Int = 4
}
}
<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/ParserRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
class ParserRenderer(definition: Definition,
packageName: String,
private val className: String,
private val implementationName: String)
: JavaCodeRenderer(definition, packageName) {
override fun listDependencies(): List<String> =
super.listDependencies() + listOf("JSONArray", "JSONException", "JSONObject").map { "org.json.$it" } + listNestedDependencies()
private fun listNestedDependencies(): Collection<String> {
val rootDependency = "$packageName.$implementationName"
val deps = mutableSetOf(rootDependency)
traverseDependencies(deps, definition, rootDependency)
return deps.map { "static $it.*" }
}
private fun traverseDependencies(traversed: MutableSet<String>, definition: Definition, currentDependency: String) {
definition.fields
.filter { it.type is StrictObjectType
|| (it.type is ArrayType<*> && (it.type.subtype is StrictObjectType || it.type.subtype is MultiObjectType)) }
.map {
val dependencyClass = "$currentDependency.${it.name.asClassName()}Impl"
traversed.add(dependencyClass)
when (it.type) {
is StrictObjectType -> {
traverseDependencies(traversed, it.type.definition, dependencyClass)
}
is ArrayType<*> -> {
when (it.type.subtype) {
is StrictObjectType -> traverseDependencies(traversed, it.type.subtype.definition, dependencyClass)
is MultiObjectType -> {
traversed.remove(dependencyClass) // we don't need base interface as dependency
it.type.subtype.types.forEach { entry ->
traversed.add("$currentDependency.${it.name.asClassName()}${entry.key.toCamelCase()}Impl")
traverseDependencies(traversed, entry.value, "$currentDependency.${it.name.asClassName()}${entry.key.toCamelCase()}Impl")
}
}
}
}
else -> throw IllegalStateException()
}
}
}
override fun render(writer: TextWriter) {
super.render(writer)
with(writer) {
nextLine()
append("public class $className {")
with(withIncreasedIndentation()) {
append("private AnalyticsSender mAnalyticsSender;")
nextLine()
append("public $className(AnalyticsSender analyticsSender) {")
withIncreasedIndentation().append("mAnalyticsSender = analyticsSender;")
append("}")
}
withIncreasedIndentation().join(parseMethods()) {
nextLine(2)
}
append("}")
}
}
private fun parseMethods(): Collection<Renderer> =
listOf(ParseStrictObjectMethod(definition, "parse", implementationName, Privacy.PUBLIC, implementationName))
.flatMap { listOf(it) + it.listSubMethods() + it.listSubMethodsFromCompositeTypes() }
abstract class ParseMethod(
val name: String,
val returnType: String,
val privacy: Privacy) : Renderer {
abstract fun collectWrittenFields(): List<Field<*>>
override fun render(writer: TextWriter) {
with(writer) {
appendMethodHeader(writer)
append("{")
appendCode(withIncreasedIndentation())
append("}")
}
}
abstract fun appendMethodHeader(writer: TextWriter)
abstract fun appendCode(writer: TextWriter)
protected fun inferValueSource(field: Field<*>, type: Type<*>, key: String, sourceName: String): String {
return when (type) {
is StringType -> "$sourceName.getString($key)"
is IntegerType -> "$sourceName.getInt($key)"
is LongType -> "$sourceName.getLong($key)"
is BoolType -> "$sourceName.getBoolean($key)"
is StrictObjectType -> "${inferParseFuncName(field, type)}($sourceName.getJSONObject($key))"
is ArrayType<*> -> "${inferParseFuncName(field, type)}($sourceName.getJSONArray($key))"
is FreeObjectType -> "${inferParseFuncName(field, type)}($sourceName.getJSONObject($key))"
is MultiObjectType -> "${inferParseFuncName(field, type)}($sourceName.getJSONObject($key))"
}
}
private fun inferParseFuncName(field: Field<*>, type: Type<*> = field.type): String {
return when (type) {
is ArrayType<*> -> "parse${field.name.asClassName()}Array"
is FreeObjectType -> "parse${field.name.asClassName()}Object"
is StrictObjectType -> "parse${field.name.asClassName()}"
is MultiObjectType -> "parse${field.name.asClassName()}"
else -> unsupportedType("Unsupported type $type")
}
}
protected fun isNeedUseCatchParsingBlock(type: Type<*>): Boolean {
return when (type) {
is StringType, is IntegerType, is BoolType, is LongType -> true
is StrictObjectType, is ArrayType<*>, is FreeObjectType, is MultiObjectType -> false
}
}
fun listSubMethods(): List<Renderer> {
return collectWrittenFields()
.filter {
it.type is StrictObjectType
|| it.type is ArrayType<*>
|| it.type is FreeObjectType
|| it.type is MultiObjectType
}
.map {
when (it.type) {
is StrictObjectType ->
parseStrictObject(it, it.type)
is ArrayType<*> ->
parseArray(it, it.type.subtype)
is FreeObjectType ->
parseFreeObject(it, it.type)
is MultiObjectType ->
parseMultiObject(it, it.type)
else -> unsupportedType()
}
}
.flatMap { listOf(it) + it.listSubMethods() + it.listSubMethodsFromCompositeTypes() }
}
fun listSubMethodsFromCompositeTypes(): List<Renderer> {
return collectWrittenFields()
.filter {
it.type is CompositeType && (
it.type.subtype is StrictObjectType
|| it.type.subtype is CompositeType
|| it.type.subtype is MultiObjectType)
}
.map {
when ((it.type as CompositeType).subtype) {
is StrictObjectType ->
parseStrictObject(it, it.type.subtype!!)
is FreeObjectType ->
parseFreeObject(it, it.type.subtype as FreeObjectType)
is ArrayType<*> ->
parseArray(Field(it.name, it.type.subtype!!), (it.type.subtype!! as ArrayType<*>).subtype)
is MultiObjectType ->
parseMultiObject(it, (it.type as CompositeType).subtype as MultiObjectType)
else -> unsupportedType("Only Strict, FreeObject and MultiObject are supported as composite subtypes $it")
}
}
}
private fun parseMultiObject(field: Field<*>, type: MultiObjectType): ParseMethod =
ParseMultiObjectMethod(
field,
type.types,
inferParseFuncName(field, type),
inferFieldTypeName(field.name, type),
Privacy.PRIVATE)
private fun parseStrictObject(field: Field<*>, type: Type<*>): ParseMethod =
ParseStrictObjectMethod(
getDefinition(field.type),
inferParseFuncName(field, type),
inferFieldTypeName(field.name, type),
Privacy.PRIVATE)
private fun parseFreeObject(field: Field<*>, type: FreeObjectType): ParseMethod =
ParseFreeObjectMethod(
type.subtype!!, field,
getDefinition(field.type),
inferParseFuncName(field, type),
inferFieldTypeName(field.name, type),
Privacy.PRIVATE)
private fun parseArray(field: Field<*>, type: Type<*>): ParseMethod =
ParseArrayMethod(field,
getDefinition(field.type),
inferParseFuncName(field),
inferFieldTypeName(field.name, type),
Privacy.PRIVATE)
private fun unsupportedType(msg: String = "Unsupported type"): Nothing = throw IllegalArgumentException(msg)
private fun getDefinition(type: Type<*>): Definition = when (type) {
is StrictObjectType -> type.definition
is FreeObjectType -> getDefinition(type.subtype!!)
is ArrayType<*> -> getDefinition(type.subtype)
else -> Definition(emptyList())
}
}
class ParseMultiObjectMethod(
private val field: Field<*>,
private val types: Map<String, Definition>,
methodName: String,
fieldTypeName: String,
privacy: Privacy) : ParseMethod(methodName, fieldTypeName, privacy) {
override fun collectWrittenFields(): List<Field<*>> {
return types.values.flatMap { it.fields }
}
override fun appendMethodHeader(writer: TextWriter) {
writer.append("${privacy.syntax} $returnType $name(JSONObject json) throws JSONException, RequiredFieldException")
}
override fun appendCode(writer: TextWriter) {
val typeKey = "\"type\""
with(writer) {
append("String key = json.getString($typeKey);").nextLine()
types.forEach { key, _ ->
append("if (\"$key\".equals(key)) {")
with(withIncreasedIndentation()) {
append("return ${toSubMethodName(key)}(json);")
}
append("}").nextLine()
}
appendParsingFieldError(this)
}
}
private fun appendParsingFieldError(writer: TextWriter) {
writer.append("mAnalyticsSender.sendParsingConfigError(\"${field.name.rawText}\", \"bad_value\", \"configuration_not_accepted\");")
writer.nextLine()
writer.append("throw new RequiredFieldException(\"${field.name.rawText}\");")
}
private fun toSubMethodName(key: String) = name + key.toCamelCase()
override fun render(writer: TextWriter) {
super.render(writer)
with(writer) {
nextLine(2)
types.forEach { key, definition ->
val parseStrictObjectMethod = ParseStrictObjectMethod(
definition,
toSubMethodName(key),
field.name.asClassName() + key.capitalize().toCamelCase(),
Privacy.PRIVATE
)
parseStrictObjectMethod.render(writer)
writer.nextLine(2)
parseStrictObjectMethod.listSubMethods().forEach {
it.render(writer)
writer.nextLine(2)
}
parseStrictObjectMethod.listSubMethodsFromCompositeTypes().forEach {
it.render(writer)
writer.nextLine(2)
}
}
}
}
}
class ParseArrayMethod(private val field: Field<*>,
private val definition: Definition,
name: String,
returnType: String,
privacy: Privacy) : ParseMethod(name, returnType, privacy) {
override fun collectWrittenFields(): List<Field<*>> = definition.fields
override fun appendMethodHeader(writer: TextWriter) {
writer.append("${privacy.syntax} List<$returnType> $name(JSONArray array) throws JSONException, RequiredFieldException")
}
override fun appendCode(writer: TextWriter) {
val validator = getValidator(field, (field.type as ArrayType<*>).subtype)
with(writer) {
validator.appendPreValidate(this)
append("List<$returnType> list = new ArrayList<>();").nextLine()
var writerForCatchBlock = this
if (isNeedUseCatchParsingBlock(field.type.subtype)) {
append("try {")
writerForCatchBlock = withIncreasedIndentation()
}
with(writerForCatchBlock) {
append("for (int i = 0; i < array.length(); i++) {")
with(withIncreasedIndentation()) {
appendParsingFieldBlock(field.type, validator)
}
append("}")
}
if (isNeedUseCatchParsingBlock(field.type.subtype)) {
appendCatchBlock(this, this@ParseArrayMethod)
}
nextLine()
append("return list;")
}
}
private fun TextWriter.appendParsingFieldBlock(type: ArrayType<*>, validator: ValidatorRenderer<*>) {
append("$returnType value = ${inferValueSource(field, type.subtype, "i", "array")};").nextLine()
validator.doIfValidate(this) {
append("list.add(value);")
} otherwise {
append("mAnalyticsSender.sendParsingConfigError(\"${field.name.rawText}\", \"bad_value\", \"configuration_not_accepted\");")
if (field.absenceHandler is RequiredHandler) {
nextLine()
append("throw new RequiredFieldException(\"${field.name.rawText}\");")
}
}
}
private fun appendCatchBlock(textWriter: TextWriter, parseArrayMethod: ParseArrayMethod) {
textWriter.append("} catch (JSONException e) {")
with(textWriter.withIncreasedIndentation()) {
if (parseArrayMethod.field.absenceHandler is RequiredHandler) {
append("mAnalyticsSender.sendParsingConfigError(\"${parseArrayMethod.field.name.rawText}\", \"bad_value\", \"configuration_not_accepted\");")
nextLine()
append("throw new RequiredFieldException(\"${parseArrayMethod.field.name.rawText}\");")
} else {
append("mAnalyticsSender.sendParsingConfigError(\"${parseArrayMethod.field.name.rawText}\", \"bad_type\", \"default_substituted\");")
}
}
textWriter.append("}")
}
}
class ParseFreeObjectMethod(private val subtype: Type<*>,
private val field: Field<*>,
private val definition: Definition,
name: String,
returnType: String,
privacy: Privacy) : ParseMethod(name, returnType, privacy) {
override fun collectWrittenFields(): List<Field<*>> = definition.fields
override fun appendMethodHeader(writer: TextWriter) {
writer.append("${privacy.syntax} $returnType $name(JSONObject json) throws JSONException, RequiredFieldException")
}
override fun appendCode(writer: TextWriter) {
with(writer) {
append("$returnType map = new HashMap<>();").nextLine()
append("Iterator<String> iter = json.keys();").nextLine()
append("while (iter.hasNext()) {")
with(withIncreasedIndentation()) {
append("String key = iter.next();").nextLine()
append("map.put(key, ${inferValueSource(field, subtype, "key", "json")});")
}
append("}").nextLine()
append("return map;")
}
}
}
class ParseStrictObjectMethod(private val definition: Definition,
name: String,
returnType: String,
privacy: Privacy,
private val implementationName: String = returnType + "Impl")
: ParseMethod(name, returnType, privacy) {
override fun collectWrittenFields(): List<Field<*>> = definition.fields
override fun appendMethodHeader(writer: TextWriter) {
writer.append("${privacy.syntax} $returnType $name(JSONObject json) throws JSONException, RequiredFieldException")
}
override fun appendCode(writer: TextWriter) {
with(writer) {
append("$implementationName obj = new $implementationName();").nextLine()
definition.fields.forEach { field ->
val validator = getValidator(field, field.type)
append("if (json.has(\"${field.name.asJsonFieldName()}\")) {")
with(withIncreasedIndentation()) {
append("${inferFieldTypeName(field.name, field.type)} value;").nextLine()
var writerForCatchBlock = this
if (isNeedUseCatchParsingBlock(field.type)) {
append("try {")
writerForCatchBlock = withIncreasedIndentation()
}
with(writerForCatchBlock) {
appendFieldParsingBlock(validator, field)
}
if (isNeedUseCatchParsingBlock(field.type)) {
appendCatchBlock(field)
}
}
append("}")
if (field.absenceHandler is RequiredHandler) {
appendErrorHandlingBlock(field)
}
nextLine()
}
append("return obj;")
}
}
private fun TextWriter.appendFieldParsingBlock(validator: ValidatorRenderer<*>, field: Field<*>) {
validator.appendPreValidate(this)
append("value = ${inferValueSource(field, field.type, "\"${field.name.asJsonFieldName()}\"", "json")};").nextLine()
validator.doIfValidate(this) {
append("obj.${field.name.asSetterName()}(value);")
}
if (validator is SpecialValuesValidatorRenderer) {
append(" else {")
append("mAnalyticsSender.sendParsingConfigError(\"${field.name.rawText}\", \"bad_value\", \"configuration_not_accepted\");")
if (field.absenceHandler is RequiredHandler) {
withIncreasedIndentation().append("throw new RequiredFieldException(\"${field.name.rawText}\");")
}
append("}")
}
}
private fun TextWriter.appendErrorHandlingBlock(field: Field<*>) {
append(" else {")
with(withIncreasedIndentation()) {
append("mAnalyticsSender.sendParsingConfigError(\"${field.name.rawText}\", \"bad_value\", \"configuration_not_accepted\");")
nextLine()
append("throw new RequiredFieldException(\"${field.name.rawText}\");")
}
append("}")
}
private fun TextWriter.appendCatchBlock(field: Field<*>) {
append("} catch (JSONException e) {")
with(withIncreasedIndentation()) {
if (field.absenceHandler is RequiredHandler) {
append("mAnalyticsSender.sendParsingConfigError(\"${field.name.rawText}\", \"bad_value\", \"configuration_not_accepted\");")
nextLine()
append("throw new RequiredFieldException(\"${field.name.rawText}\");")
} else {
append("mAnalyticsSender.sendParsingConfigError(\"${field.name.rawText}\", \"bad_type\", \"default_substituted\");")
}
}
append("}")
}
}
enum class Privacy(val syntax: String) {
PUBLIC("public"), PRIVATE("private")
}
}<file_sep>/buildSrc/src/main/kotlin/ru/mail/condef/renderer/ValidatorRenderer.kt
package ru.mail.condef.renderer
import ru.mail.condef.dsl.*
fun getValidator(field: Field<*>, type: Type<*>): ValidatorRenderer<*> {
return when(type) {
is ArrayType<*> -> StubValidator()
else -> when(field.validator) {
null -> StubValidator()
is SpecialValuesValidator<*> -> SpecialValuesValidatorRenderer(field.validator)
is RegexValidator -> RegexValidatorRenderer(field.validator)
is RangeValidator -> RangeValidatorRenderer(field.validator)
}
}
}
abstract class ValidatorRenderer<out T>(val validator: T?) {
abstract fun appendPreValidate(writer: TextWriter)
abstract fun validationCondition(): String
open fun doIfValidate(writer: TextWriter, toAppend: TextWriter.() -> Unit): ValidatorChain {
writer.append("if (${validationCondition()}) {")
writer.withIncreasedIndentation().toAppend()
writer.append("}")
return ValidatorChain(writer)
}
open class ValidatorChain(private val writer: TextWriter) {
open infix fun otherwise(toAppend: TextWriter.() -> Unit) {
writer.append(" else {")
writer.withIncreasedIndentation().toAppend()
writer.append("}")
}
}
}
class StubValidator : ValidatorRenderer<Any>(null) {
override fun validationCondition(): String {
return ""
}
override fun doIfValidate(writer: TextWriter, toAppend: TextWriter.() -> Unit): ValidatorChain {
writer.toAppend()
return object : ValidatorChain(writer) {
override fun otherwise(toAppend: TextWriter.() -> Unit) {
}
}
}
override fun appendPreValidate(writer: TextWriter) {
}
}
class SpecialValuesValidatorRenderer(validator: SpecialValuesValidator<*>) : ValidatorRenderer<SpecialValuesValidator<*>>(validator) {
override fun appendPreValidate(writer: TextWriter) {
writer.append("Set<?> allowed = new HashSet<>(${asPredefinedCollection(validator!!.values)});")
writer.nextLine()
}
override fun validationCondition(): String {
return if(validator!!.values[0] is String) "allowed.contains(((String)value).toLowerCase(Locale.ENGLISH))"
else "allowed.contains(value)"
}
}
class RegexValidatorRenderer(validator: RegexValidator) : ValidatorRenderer<RegexValidator>(validator) {
override fun appendPreValidate(writer: TextWriter) {
writer.append("Matcher matcher = Pattern.compile(\"${StringEscapeUtils.escapeJava(validator!!.pattern.toString())}\").matcher(\"\");")
writer.nextLine()
}
override fun validationCondition(): String {
return "matcher.reset(value).matches()"
}
}
class RangeValidatorRenderer(validator: RangeValidator) : ValidatorRenderer<RangeValidator>(validator) {
override fun appendPreValidate(writer: TextWriter) {
}
override fun validationCondition(): String {
return "value >= ${validator!!.fromInclusive} && value <= ${validator.toInclusive}"
}
}
<file_sep>/flexsettings/src/main/java/ru/mail/flexsettings/field/StringField.java
package ru.mail.flexsettings.field;
public class StringField extends PrimitiveField<String> {
public StringField(String name) {
super(name, "");
}
@Override
public Field copy(String name) {
return new StringField(name);
}
@Override
public String toString() {
return "(StringField) \"" + getName() + "\" = \"" + getValue() + "\"";
}
}
| cddb65a6e90e527dc9b869686cc7218ffdce7328 | [
"JavaScript",
"Markdown",
"Gradle",
"Java",
"Kotlin"
] | 36 | Java | govorovsky/configen | 913006665643f98d95c5c331718f8ac746635b5b | b6ed061b2ab9dd4a98ab1478fcda59887468e01e |
refs/heads/master | <repo_name>dfnogueira/Painel_Seg<file_sep>/config.py
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 09:46:43 2020
@author: fonte
"""
# .gitignore should include reference to config.py
# Proxy Key
login = "dst3834"
passw = "<PASSWORD>"
# google API Key
API_KEY = "<KEY>"
| 50916e21911a80ba472736fe3d35946a5eb18387 | [
"Python"
] | 1 | Python | dfnogueira/Painel_Seg | 9305e0fa0273d194eda738c7a16e62e82157afe1 | 270421b1e60ccaf983850d0d7973336bea6ddb0d |
refs/heads/master | <file_sep><?php
$sid = session_id();
$sql = mysql_query("SELECT SUM(jumlah*harga) as total,SUM(jumlah) as totaljumlah FROM orders_temp, produk
WHERE id_session='$sid' AND orders_temp.id_produk=produk.id_produk");
while($r=mysql_fetch_array($sql)){
if ($r[totaljumlah] != ""){
$total_rp = format_rupiah($r[total]);
echo "<i><a href='keranjang-belanja.html'>$r[totaljumlah] item</a></i><br />
<span class='border_cart'></span>
Total: <span class='price'>Rp. $total_rp</span>";
}
else{
echo "<i>0 item</i><br />
<span class='border_cart'></span>
Total: <span class='price'>Rp. 0</span>";
}
}
?>
<file_sep> <div class="shopping_cart">
<div class="cart_title">Keranjang belanja</div>
<div class="cart_details">
<?php require_once "item.php";?>
</div>
<div class="cart_icon"><img src="images/shoppingcart.png" alt="" title="" width="48" border="0" height="48">
</div>
</div>
<file_sep><?php
header('location:media.php');
?>
<file_sep>
<div class="title_box">Kategori</div>
<ul class="left_menu">
<?php
$kategori=mysql_query("select nama_kategori, kategori.id_kategori, kategori_seo,
count(produk.id_produk) as jml
from kategori left join produk
on produk.id_kategori=kategori.id_kategori
group by nama_kategori");
$no=1;
while($k=mysql_fetch_array($kategori)){
if(($no % 2)==0){
echo "<li class='genap'><a href='kategori-$k[id_kategori]-$k[kategori_seo].html'> $k[nama_kategori] ($k[jml])</a></li>";
}
else{
echo "<li class='ganjil'><a href='kategori-$k[id_kategori]-$k[kategori_seo].html'> $k[nama_kategori] ($k[jml])</a></li>";
}
$no++;
}
?>
</ul>
<file_sep><?php
echo "gema komputer, perangkat keras komputer, toko online";
?>
| b62f97a2b88139a875aa3e6e648cab15c9b2d4e8 | [
"PHP"
] | 5 | PHP | taufikbudi/toko-komputer | fc373cd44998feaf3d0e8710809c7f5dd75218ce | 25b4fe98644ae0879d37ad431a064e4bb34c3759 |
refs/heads/master | <repo_name>MiLandry/timer-app-react<file_sep>/src/components/ToggleableTimerForm.js
import React from 'react';
import TimerForm from './TimerForm';
const ToggleableTimerForm = React.createClass({
getInitialState: function () {
return {
isOpen: false,
};
},
handleFormOpen: function () {
this.setState({ isOpen: true });
},
handleFormClose: function () {
this.setState({ isOpen: false });
},
handleFormSubmit: function (timer) {
this.props.onFormSubmit(timer);
this.setState({ isOpen: false });
},
render: function () {
if (this.state.isOpen) {
return (
<TimerForm
onFormSubmit={this.handleFormSubmit}
onFormClose={this.handleFormClose}
/>
);
} else {
return (
<div className='ui basic content center aligned segment'>
<button
className='ui basic button icon'
onClick={this.handleFormOpen}
>
<i className='plus icon'></i>
</button>
</div>
);
}
},
});
export default ToggleableTimerForm;<file_sep>/src/components/EditableTimer.js
import React from 'react';
import TimerForm from './TimerForm';
import Timer from './Timer';
const EditableTimer = React.createClass({
getInitialState: function () {
return {
editFormOpen: false,
};
},
render: function () {
if (this.state.editFormOpen) {
return (
<TimerForm
id={this.props.id}
title={this.props.title}
project={this.props.project}
/>
);
} else {
return (
<Timer
id={this.props.id}
title={this.props.title}
project={this.props.project}
elapsed={this.props.elapsed}
runningSince={this.props.runningSince}
/>
);
}
},
});
export default EditableTimer;<file_sep>/src/components/TimersDashboard.js
import React from 'react';
import EditableTimerList from './EditableTimerList';
import ToggleableTimerForm from './ToggleableTimerForm';
const uuidV4 = require('uuid/v4');
const TimersDashboard = React.createClass({
newTimer: function (attrs = {}) {
const timer = {
title: attrs.title || 'Timer',
project: attrs.project || 'Project',
id: uuid.v4(), // eslint-disable-line no-undef
elapsed: 0,
};
return timer;
},
getInitialState: function () {
return {
timers: [
{
title: 'Practice squat',
project: 'Gym Chores',
id: uuidV4(),
elapsed: 5456099,
runningSince: Date.now(),
},
{
title: 'Bake squash',
project: 'Kitchen Chores',
id: uuidV4(),
elapsed: 1273998,
runningSince: null,
},
],
};
},
handleCreateFormSubmit: function (timer) {
this.createTimer(timer);
},
createTimer: function (timer) {
const t = this.newTimer(timer);
this.setState({
timers: this.state.timers.concat(t),
});
},
render: function () {
return (
<div className='ui three column centered grid'>
<div className='column'>
<EditableTimerList
timers={this.state.timers}
/>
<ToggleableTimerForm
onFormSubmit={this.handleCreateFormSubmit}
/>
</div>
</div>
);
},
});
export default TimersDashboard; | 5a1e49f4ca7a274e4ff7ea830973ae58f077ce1e | [
"JavaScript"
] | 3 | JavaScript | MiLandry/timer-app-react | 5c63b51ce808c302cd91266ab7129a034c463f38 | 4ecacd591538106293a1ce5d33f071a1489a13e7 |
refs/heads/master | <repo_name>brayanskiler/redesSocialesMaster<file_sep>/app/src/main/java/com/example/brian/redessocialesmaster/MainActivity.java
package com.example.brian.redessocialesmaster;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.facebook.share.widget.ShareDialog;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
Button compartir ;
Bitmap imagen ;
CallbackManager callbackManager;
TextView txtNombre, txtEmail;
ProgressDialog mDialog;
ImageView imgAvatar;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode,data);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
txtNombre = (TextView) findViewById(R.id.txtNombre);
txtEmail = (TextView) findViewById(R.id.txtEmail);
imgAvatar = (ImageView) findViewById(R.id.avatar);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile","first_name", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Retieving data...");
mDialog.show();
String accesstoken = loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
mDialog.dismiss();
Log.d("response", response.toString());
getData(object);
}
});
Bundle parameters = new Bundle();
parameters.putString("first_name","email");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException error) {
}
});
if (AccessToken.getCurrentAccessToken() != null){
txtEmail.setText(AccessToken.getCurrentAccessToken().getUserId());
}
compartir = (Button) findViewById(R.id.btnCompartir);
imagen = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher);
compartir.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharePhoto foto = new SharePhoto.Builder().setBitmap(imagen).build();
SharePhotoContent contenido = new SharePhotoContent.Builder().addPhoto(foto).build();
ShareLinkContent contenido2 = new ShareLinkContent.Builder().setContentUrl(Uri.parse("http://www.google.com")).build();
ShareDialog.show(MainActivity.this,contenido2);
}
});
}
private void getData(JSONObject object) {
try {
URL profile_picture = new URL("https://graph.facebook.com/"+object.getString("id")+"/picture?width=250&height=250");
Picasso.with(this).load(profile_picture.toString()).into(imgAvatar);
txtNombre.setText(object.getString("first_name"));
txtEmail.setText(object.getString("email"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
<file_sep>/settings.gradle
rootProject.name='redesSocialesMaster'
include ':app'
| 61f5d5f6d17e6432102fc7e478290647a82a5bf4 | [
"Java",
"Gradle"
] | 2 | Java | brayanskiler/redesSocialesMaster | 4c783e77438d8bc7dade1f36de86f8ddd4f1e377 | 745f10ddb87a6083a994f63f88ac884ff00a902f |
refs/heads/master | <repo_name>natsnyder1/AppleOrchard<file_sep>/ImageAnalysisLab/Drone Code/DroneCode/Main.cpp
#include <iostream>
#include <opencv2\imgproc.hpp>
#include <opencv\cv.h>
#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <opencv2\imgcodecs.hpp>
#include <array>
#include <math.h>
#include <numeric>
using namespace std;
using namespace cv;
// Classes
class AppleOrchard
{
private:
// Internal Classes that contain HSV Values and Predicates
class innerBaseClass
{
public:
int H_Min, H_Max, S_Min, S_Max, V_Min, V_Max, HSV_DILATE, HSV_ERODE, HSV_BLUR;
Scalar* HSV_LOW = NULL;
Scalar* HSV_HIGH = NULL;
innerBaseClass()
{
set();
message();
}
virtual void set()
{
H_Min = 0;
H_Max = 0;
S_Min = 0;
S_Max = 0;
V_Min = 0;
V_Max = 0;
HSV_DILATE = 0;
HSV_ERODE = 0;
HSV_BLUR = 0;
Scalar* HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
Scalar* HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
virtual void message()
{
cout << "Base Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class Histogram
{
private:
// Class Variables that Set Up Histogram
const int WIDTH = 2048;
const int HEIGHT = 2048;
int yAxisTop = 0; // Sets some space between top of graph to top of image
int yAxisBottom = 0; // Sets some space between bottom of graph and top of image
int xAxisLeft = 0; // Starts xaxis a bit of space away from the left side of image
int xAxisRight = 0; // ends xaxis a bit of space away from the right side of image
const int imageSections = 8; // The number of sections the graph is divided into for axis drawing operations
const int numBins = 200; // The number of slices the data is cut into
int xAxisDistance = 0; // The distance between the origin and the end of the x-axis
int interval = 0; // The x-distance between each bin displayed (xAxisDistance / numBins)
const int scaleDownRatio = 6; // since the bins usually get relatively full, its a good idea to scale down
int xSpacer = 0; // Used in "OutputRowHistogram" in conjunction with "interval" to step through the graph
// Variables for Constructing Histogram text
int sumPixelsInBins = 0; // Total sum of all pixels counted
int averageBinDensity = 0; // average pixels found in each bin summed and averaged from all bins
double standard_deviation = 0;
Point2d histogramText; // For writing words on Histogram
// Class Variables for text output on RowDensity histogram
string avgBins = "Average Bin Size: ";
string numRows = "Number of Rows: ";
string FilePath;
int fontFace = CV_FONT_HERSHEY_PLAIN;
const double fontScale = 2;
const int thickness = 2;
// Very important container that holds the histogram data
vector<int> binContainer; // will hold all of the horizontal / vertical density bins for a given picture, depending which algorithm is called
Mat thresholdImage; // given to object when class is instantiated
// Private Methods
// Function draws axis on the histogram image
void drawAxis() // Input an Image to use
{// Put x and y axis on our blank image
line(histImg, Point(xAxisLeft, yAxisTop), Point(xAxisLeft, yAxisBottom), Scalar(255, 0, 0), 15); // y-axis
line(histImg, Point(xAxisLeft, yAxisBottom), Point(xAxisRight, yAxisBottom), Scalar(255, 0, 0), 15); // x-axis
}
// Function executes when outputRowHistogram in outer class is called
void MeanAndStandardDeviation_BinContainer()
{
double totalBinSum = 0;
int numElements = binContainer.size();
double temp = 0;
double variance = 0;
for (vector<int>::iterator itMean = binContainer.begin(); itMean != binContainer.end(); ++itMean)
{
totalBinSum += *itMean;
}
averageBinDensity = totalBinSum / numElements;
for (vector<int>::iterator itStand = binContainer.begin(); itStand != binContainer.end(); ++itStand)
{
temp += pow(abs(averageBinDensity - *itStand), 2);
}
variance = temp / numElements;
standard_deviation = sqrt(variance);
}
/* findThresholdDensity finds the density of a threshold image you provide by either slicing the image horizontally or verticaly.
findThresholdDensity sets the binContainer variable which is used to output a threshold density histogram. Call this function almost immediately.
Enter threshold Image you would like to find the bin density of
Select either true or false for second paramter: False = Horizontal Binning. True = Veritical Binning */
void findThresholdDensity(Mat thresholdImage, bool flip = false)
{
Mat orchardThreshold;
thresholdImage.copyTo(orchardThreshold);
// 1) Declare internal variables
int numBins = 200; // This divides the picture into slivers
int binWidth = 0; // Number of pixels within a sliver. Will be set differently depending on flip being true of false
int counter = 0; // generic counter
double whitePixelBinCount = 0; // the amount of white pixels counted in a bin
vector <double> temp; // all purpose temporary vector
// 2) Depending on the users input, the switch case will either run true or false.
// False indicates the threshold image will be horizontally binned. True indicates that the threshold image will be vertically binned
binContainer.clear(); // Wipe binContainer clean
binContainer.reserve(200); // reserve 200 spots for the vector
switch (flip)
{
case false: // If false is exectued, then the threshold picture will be horizontally binned
binWidth = orchardThreshold.rows / numBins; // Number of pixels within a bin. Here it corresponds to horizontal slivers
// 3) Loop through all rows. Once row reaches binWidth, store the number of pixels counted in binContainer.
// binWidth is currently set to 15 (3000/200).. so every 15 rows the pixel count will be stored
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{ // We need to add the white pixels to find a total amount of pixels
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount); // store bin pixel count in binContainer
whitePixelBinCount = 0;
}
}
break;
case true: // If true is exectued, then the threshold image will be vertically binned
binWidth = orchardThreshold.cols / numBins; // Number of pixels within a sliver. Here it corresponds to vertical slivers
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{ // We need to sum the white pixels to find a total amount of pixels per bin
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount); // store bin pixel count in binContainer
whitePixelBinCount = 0;
}
}
break;
default:
cout << "Something Didnt Work Right" << endl;
break;
}
// 4) Using the newly filled binContainer, find the mean and standard deviation of the binData
MeanAndStandardDeviation_BinContainer();
}
public:
// The Histogram image used for outputting
Mat histImg; // used to output the threshold density histogram image
Histogram(Mat& _thresholdImage, string _FilePath)
{
// Constructor will set object parameters for the histogram
_thresholdImage.copyTo(thresholdImage);
FilePath = _FilePath;
histImg = Mat(HEIGHT, WIDTH, CV_8UC3, Scalar(255, 255, 255)); // used to output the threshold density histogram image
yAxisTop = histImg.rows / imageSections; // sets some space between top of graph to top of image
yAxisBottom = histImg.rows - yAxisTop; // sets some space between bottom of graph and top of image
xAxisLeft = histImg.cols / imageSections; // starts xaxis a bit of space away from the left side of image
xAxisRight = histImg.cols - xAxisLeft; // ends xaxis a bit of space away from the right side of image
xAxisDistance = xAxisRight - xAxisLeft; // complete x-axis distance
interval = xAxisDistance / numBins; // the step size between bins on the graph
xSpacer = xAxisLeft; // xSpacer is user to step through the graph and draw it
histogramText = Point2d(xAxisLeft, yAxisTop - 100);
}
void drawHistogram(bool flip)
{
// 1) Draw histogram axis
drawAxis();
// 2) We need to run findThresholdDensity to fill the bin container
findThresholdDensity(thresholdImage, flip);
// 3) Output Bins on Histogram by drawing rectangles on histogram image
for (vector<int>::iterator countContainer = binContainer.begin(); countContainer != binContainer.end(); ++countContainer)
{// Loop through the container and remove the bin sizes we have found
rectangle(histImg, Point(xSpacer, yAxisBottom), Point(xSpacer + interval, yAxisBottom - (*countContainer / scaleDownRatio)), Scalar(0, 0, 255), -1);
xSpacer += interval; // increment to the next bin space
}
// 4) Turn average value into a string so openCV can output it on your histogram
avgBins += to_string(averageBinDensity);
// 5) Draw Average Line and Output text
line(histImg, Point(xAxisLeft, yAxisBottom - averageBinDensity / scaleDownRatio), Point(xAxisRight, yAxisBottom - averageBinDensity / scaleDownRatio), Scalar(0, 255, 0), 15); // Shows the average bin density on the histogram
putText(histImg, avgBins, histogramText, fontFace, fontScale, Scalar(255, 0, 255), thickness);
// 6) Write image to filepath that the user instantiated the object with
imwrite(FilePath, histImg);
}
~Histogram();
};
class HSV_Values_Rows : public innerBaseClass
{
public:
HSV_Values_Rows()
{
HSV_Values_Rows::set();
HSV_Values_Rows::message();
}
virtual void set()
{
H_Min = 9;
H_Max = 30;
S_Min = 145;
S_Max = 162;
V_Min = 0;
V_Max = 145;
HSV_DILATE = 2;
HSV_ERODE = 4;
HSV_BLUR = 5;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Inherited Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class HSV_Values_YellowApples : public innerBaseClass
{
public:
HSV_Values_YellowApples()
{
set();
message();
}
void set()
{
H_Min = 0;
H_Max = 31;
S_Min = 152;
S_Max = 255;
V_Min = 180;
V_Max = 255;
// These are the Key Scalar Values needed to make a correct threshold image
HSV_DILATE = 1;
HSV_ERODE = 2;
HSV_BLUR = 1;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Inherited Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class HSV_Values_RedApples : public innerBaseClass
{
public:
HSV_Values_RedApples()
{
set();
message();
}
void set()
{
// These Values are not correct
H_Min = 0;
H_Max = 0;
S_Min = 0;
S_Max = 0;
V_Min = 0;
V_Max = 0;
// These are the Key Scalar Values needed to make a correct threshold image
HSV_DILATE = 0;
HSV_ERODE = 0;
HSV_BLUR = 1;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Inherited Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
struct sort_pred_double_descending {
bool operator()(const pair<double, Point2i> &left, const pair<double, Point2i> &right)
{
return left.first > right.first; // first value is the largest
}
};
// Class Variables that Set Up Histogram
const int WIDTH = 2048;
const int HEIGHT = 2048;
vector<int> binContainer; // will hold all of the horizontal / vertical density bins for a given picture, depending which algorithm is called
// Variables for Constructing Histogram text
int imageHeight = 0;
int imageWidth = 0;
int sumPixelsInBins = 0; // Total sum of all pixels counted
int averageBinDensity = 0; // average pixels found in each bin
double standard_deviation = 0;
Point2d histogramText; // For writing words on Histogram
// Class Variables for text output on RowDensity histogram
string avgBins = "Average Bin Size: ";
string numRows = "Number of Rows: ";
int fontFace = CV_FONT_HERSHEY_PLAIN;
const double fontScale = 4;
const int thickness = 2;
const int numBins = 200;
// Variables For Counting Apples In First Row
int appleMeanArea = 0;
int appleStdDeviation = 0;
int appleRadius = 0;
int interquartileAppleMean = 0;
int interquartileAppleStdDeviation = 0;
int interquartileAppleRadius = 0;
// Get and Set Operations for Constructor
void GetSetObjectProperties(Mat _BGRImage) // This GetSetGraphProperties is meant for constructor 1
{
// Constructor will use these to set the objects parameters
_BGRImage.copyTo(BGRImage);
imageHeight = _BGRImage.rows;
imageWidth = _BGRImage.cols;
// Constructor will find the threshold Image for both the Apple Orchard Rows and the Apples themselves
HSV_Values_YellowApples OrchardApples; // HSV Values for Morphological Ops
HSV_Values_Rows OrchardRows; // HSV Values for Morpholigical Ops
thresholdImg_Rows = convertRGB2HSV(BGRImage, &OrchardRows); // Convert BRG to Threshold Image of Orchard Rows using Row HSV Values
thresholdImg_Apples = convertRGB2HSV(BGRImage, &OrchardApples); // Convert BRG to Threshold Image of Orchard Rows using Row HSV Values
}
// Private Functions
// Function executes when outputRowHistogram is called
void MeanAndStandardDeviation_Rows()
{
double totalBinSum = 0;
int numElements = binContainer.size();
double temp = 0;
double variance = 0;
for (vector<int>::iterator itMean = binContainer.begin(); itMean != binContainer.end(); ++itMean)
{
totalBinSum += *itMean;
}
averageBinDensity = totalBinSum / numElements;
for (vector<int>::iterator itStand = binContainer.begin(); itStand != binContainer.end(); ++itStand)
{
temp += pow(abs(averageBinDensity - *itStand), 2);
}
variance = temp / numElements;
standard_deviation = sqrt(variance);
}
// Function exectutes when findApples is called. Calculates both mean & std_dev and interquartile mean & interquartile std_dev
void MeanAndStandardDeviation_Apples()
{
// Define Temporary Variables -- This
int _size = appleCoordinateContainer.size(); // size of the container
int quartile = _size / 4; // size of one quartile
int tempSum = 0; // temporary sum
// 1) Find the apple mean
for (vector< pair<double, Point2i> >::iterator itA = appleCoordinateContainer.begin(); itA != appleCoordinateContainer.end(); ++itA)
{
tempSum += itA->first;
}
appleMeanArea = tempSum / _size;
appleRadius = std::sqrt(appleMeanArea / 3.14);
// 2) Find apple standard deviation
tempSum = 0;
for (vector< pair<double, Point2i> >::iterator itA = appleCoordinateContainer.begin(); itA != appleCoordinateContainer.end(); ++itA)
{
tempSum += std::pow(std::abs(itA->first - appleMeanArea), 2);
}
appleStdDeviation = std::sqrt((tempSum / _size));
// 3) Find interquartile apple mean
tempSum = 0;
for (vector< pair<double, Point2i> >::iterator itA = appleCoordinateContainer.begin() + quartile; itA < appleCoordinateContainer.begin() + 3 * quartile; ++itA)
{
tempSum += itA->first;
}
interquartileAppleMean = (tempSum / (_size / 2));
interquartileAppleRadius = std::sqrt(interquartileAppleMean / 3.14);
// 4) Find interquartile apple standard deviation
tempSum = 0;
for (vector< pair<double, Point2i> >::iterator itA = appleCoordinateContainer.begin() + quartile; itA < appleCoordinateContainer.begin() + 3 * quartile; ++itA)
{
tempSum += std::pow(std::abs(itA->first - interquartileAppleMean), 2);
}
interquartileAppleStdDeviation = std::sqrt((tempSum / (_size / 2)));
}
// Crop The Image To Only View Objects in First Row
void cropBGRtoFirstRow(string FilePath)
{
int upperLeftYCoord = rowCoordinateContainer[1].second[1]; // Crop image from the start of the second row to the bottom of the first row
int upperRightXCoord = 0; // Tiny bit of buffer room
int buffer = 100; // To make sure no tree is getting cuttoff.
int height = rowCoordinateContainer[0].second[1] - rowCoordinateContainer[1].second[1] - buffer;
int width = 3999;
Mat ROI(BGRImage, Rect(upperRightXCoord, upperLeftYCoord, width, height));
ROI.copyTo(BGRImage_FirstRow);
imwrite(FilePath, BGRImage_FirstRow);
}
/* findThresholdDensity finds the density of a threshold image you provide by either slicing the image horizontally or verticaly.
findThresholdDensity sets the binContainer variable which is used to output a threshold density histogram. Call this function almost immediately.
Enter number to select which operation to conduct: 1 for Row Operations, 2 for Apple Operations
Select either true or false for second paramter: False = Horizontal Binning. True = Veritical Binning */
void findThresholdDensity(Mat& inputImg, bool flip = false)
{
// 1) Store inputImg (Needs to be a threshold Image for Binning to work) into orcharThreshold
Mat orchardThreshold;
inputImg.copyTo(orchardThreshold);
// 2) These will be used to bin the threshold image
const int numBins = 200; // This divides the picture into slivers
int binWidth = 0; // Number of pixels within a sliver. Will be set differently depending on flip being true of false
int counter = 0; // generic counter
double whitePixelBinCount = 0; // the amount of white pixels counted in a bin
vector <double> temp; // all purpose temporary vector
// 3) Loop through all rows. Once row reaches binWidth, store the number of pixels counted in binContainer.
// binWidth is currently set to 15 (3000/200).. so every 15 rows the pixel count will be stored
binContainer.reserve(200); // reserve 200 spots for the vector
switch (flip)
{
case false: // If false is exectued, then the horizontal density histogram will be found
binWidth = orchardThreshold.rows / numBins; // Number of pixels within a sliver. Here it corresponds to horizontal slivers
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{ // We need to add the white pixels to find a total amount of pixels
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount);
whitePixelBinCount = 0;
}
}
break;
case true: // If true is exectued, then the vertical density histogram will be found
binWidth = orchardThreshold.cols / numBins; // Number of pixels within a sliver. Here it corresponds to vertical slivers
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{ // We need to add the white pixels to find a total amount of pixels
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount);
whitePixelBinCount = 0;
}
}
break;
default:
cout << "Something Didnt Work Right" << endl;
break;
}
// 4) Add Buffer room at the end of the binContainer -- May rethink this
//vector<int>zeros(5, 0);
//vector<int>::iterator it = binContainer.end();
//binContainer.insert(it, zeros.begin(), zeros.end());
// 4) Now That binContainer is filled, go ahead and find the average and standard deviation
MeanAndStandardDeviation_Rows();
}
public:
// Image Variables
Mat BGRImage; // The read-in BGR Orchard Image that initialized the object itself
Mat BGRImage_FirstRow; // The BGR image cropped to the first row specifications
// Threshold Images of the Rows and the Apples found using the inner HSV_Values classes
Mat thresholdImg_Apples; // Threshold Image of the apples on the trees
Mat thresholdImg_Apples_FirstRow; // Threshold Image of the apples in first row
Mat thresholdImg_Rows; // Threshold Image of the rows to identify trees
int appleCount = 0;
// Very Important Row Coordinate Container. Holds the Row information for all rows found..Usually only need first or second row
vector<pair<string, array<int, 2> > > rowCoordinateContainer; // Holds the row information per picture. Format: "Row X", [Lower Cord, Upper Cord]
vector<pair<double, Point2i> > appleCoordinateContainer; // Holds the Apple information per picture. Format: "<Area,(xCord,yCord)>"
/* Defining Constructor Variables:
inputImageFileName = The blank image you wish to construct your graph on
thresholdImg = The image which you would like to find the density of white pixels for
outputImageFileName = The output file you would like to write the histogram to
HSV_Low, HSV_High = If you supply a RGB Img, you must also supply HSV inRange values
numBins = assumed to be 200, change to more or less if you wish
*/
//_________________________________Constructor________________________//
// You can setup your object with the internal graph that is provided
AppleOrchard(Mat _BGRImage)
{
GetSetObjectProperties(_BGRImage);
}
//_________________________________Public Member Functions________________________//
// To output the row density histogram, give the function the address of what folder to write the image to
void outputRowHistogram(string outputFilePath)
{// Use Histogram Object to output the Row Histogram
Histogram* rowHistogram = new Histogram(thresholdImg_Rows, outputFilePath);
rowHistogram->drawHistogram(false);
}
// To use findRowLocations, make sure you run findThresholdDensity first with the parameter ThresholdImg_Rows Matrix (Since that holds the row threshold)
// This algorithm will use the binContainer to determine where the rows in the Orchard Image are located
void findRowLocations()
{ // This algorithm will find the rows inside a picture, and output their locations and coordinates on the BGR Image
// 1) Call findThresholdDensity
findThresholdDensity(thresholdImg_Rows, false);
// 2) Find rows by using this algorithm Below
const int CONFIDENCE_LEVEL = 5; // If we have over ten bins in a row that are greater than the average, than most likely its a row
const int BELOW_AVERAGE_LEVEL = 5; // We need to see if the our bin count
const double rowComparisonValue = averageBinDensity + standard_deviation; // compares bin values to 3 deviations higher than the mean bin-value
const double fieldComparisonValue = averageBinDensity - standard_deviation;
const int yAxisIncrement = imageHeight / numBins; // If Height is 3000 pixels, then the increment should be (3000/200 = 15)
const int rowPadding = 100;
int compareRowCount = 0; // Check to see if bin values correspond to rows
int compareFieldCount = 0; // Check to see if bin values correspond to field space
int yImageValue = imageHeight; // height of picture
int rowCounter = 0;
bool rowStart = false;
pair<string, array<int, 2> >* myRow = NULL;
for (reverse_iterator<vector<int>::iterator> itb = binContainer.rbegin(); itb != binContainer.rend(); ++itb)
{// starts at the end of the binContainer. The entries at the end will correspond to the first row
// If the bin value is above the rowComparisonValue, and we are between rows, then we need to increment the compareRowCount variable
if ((*itb > averageBinDensity) && (rowStart == false))
{
++compareRowCount;
}
// If the bin value is not above the rowComparisonValue, and we are between rows, then we need to reset compareRowCount
if ((*itb < averageBinDensity) && (rowStart == false))
{
compareRowCount = 0;
}
// If the bin value is above the rowComparisonValue, and we are on a row, then we do not need to do anything
if ((*itb > averageBinDensity) && (rowStart == true))
{
compareFieldCount = 0;
}
// If the bin value is below the fieldComparisonValue, and a row has been found, then we need to increment compareFieldCounter
if ((*itb < averageBinDensity) && (rowStart == true))
{
++compareFieldCount;
}
// If the compareRowCount is at confidence_level.. then we are going to store the row end coordinate and turn rowStart on
if (compareRowCount == CONFIDENCE_LEVEL) // Then we have found a row. Let's store the y axis location
{
rowStart = true;
myRow = new pair<string, array<int, 2> >; // dynamically create another pair object that myRow will point at
myRow->first = "Row " + to_string(++rowCounter);
myRow->second[0] = NULL; // placeholder value
myRow->second[1] = yImageValue + 5 * yAxisIncrement; // Bottom Row value. Since we checked to find 5 confidence markers, backtrack 5 spots to find the start
compareRowCount = NULL; // Now that we found a row, reset compareRowCount
}
// If the compareFieldCount is at confidence_level.. then we are going to store the row begin coordinate and turn rowStart off
if (compareFieldCount == CONFIDENCE_LEVEL) // Then we have found a row. Let's store the y axis location
{
rowStart = false;
myRow->second[0] = yImageValue + 5 * yAxisIncrement; // Top Row value. Since we checked to find 5 confidence markers, backtrack 5 spots to find the start
rowCoordinateContainer.push_back(*myRow);
compareFieldCount = NULL; // Now that we found the end of the row, lets set the compareFieldCount to zero to restart process
myRow = NULL; // Now that we are done with the pointer, lets set it to NULL
}
yImageValue -= yAxisIncrement;
}
}
// This Algorithm is simply used to output the row coordinates on the BGRImage. This is a great way to visualize how accurate findRowLocations worked
void visualizeRowCoordinates(string outputFilePath)
{
// Draw rectangles around the rows found
for (vector<pair<string, array<int, 2> > >::iterator itRow = rowCoordinateContainer.begin(); itRow != rowCoordinateContainer.end(); ++itRow)
{
// Draws a rectangle around each and every row identified.
rectangle(BGRImage, Point(10, itRow->second[0]), Point(BGRImage.cols - 10, itRow->second[1]), Scalar(0, 0, 255), 3);
putText(BGRImage, itRow->first, Point(BGRImage.cols / 2, (itRow->second[0] + itRow->second[1]) / 2), fontFace, fontScale, Scalar(255, 0, 255), thickness);
}
// Output the file to the correct folder
imwrite(outputFilePath, BGRImage);
}
// Call this Algorithm after you have identified the individual rows and wish to count the individual TREES inside of that row
void CountTreesInRow()
{
}
void writeImageToFile(string FilePath, Mat& ImageToWrite)
{
imwrite(FilePath, ImageToWrite);
}
// Call this Algorithm after you have identified the individual rows and wish to count the individual APPLES inside of that row
void CountApplesInFirstRow(string FilePath)
{
// 1) We need to use the row container information to crop the BGR photo to only show the first row specifications
cropBGRtoFirstRow(FilePath);
// 2) Assume most objects in picture are apples, this will be corrected with more ImageLabTesting Filtering Routines
HSV_Values_YellowApples Apple_HSV_Values;
thresholdImg_Apples_FirstRow = convertRGB2HSV(BGRImage_FirstRow, &Apple_HSV_Values); // converts cropped BGR Image to a cropped threshold image
// 3) We will need to use the moments method to find all of the objects in the cropped image
vector <vector <Point> >contours; // holds the contours found for the apples
vector<Vec4i> hierarchy; // holds the hierarchial information for contours
Moments moment; // moments are used to calculate area values and x-y coordinates
double objectArea; // Used to store the object area
Point2i objectCenter; // Used to store the x,y coordinates of the objects
pair<double, Point2i> storeObjectData; // holds the pair of data
findContours(thresholdImg_Apples_FirstRow, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
// 4) Take the contours, find areas, and store the areas, and the coordinates of the objects into a "pair vector"
int count = -1;
for (vector < vector<Point> >::iterator itc = contours.begin(); itc != contours.end(); ++itc)
{
++count;
moment = moments((Mat)*itc);
// 5) If an object is greater than an agreed upon small apple size, we will count it as an apple
if (moment.m00 > 400) // Then it is a contender to be an apple
{
// 6) Store all the coordinates of the apples in a "pair" vector composed of their areas and their x,y coordinates in a Point
objectArea = moment.m00; // holds object area
objectCenter = Point2i(moment.m10 / objectArea, moment.m01 / objectArea); // holds centerpoint
storeObjectData = pair<double, Point2i>(objectArea, objectCenter); // holds the pair of data
appleCoordinateContainer.push_back(storeObjectData); // push data set into our container
}
}
// 7) Sort the data from greatest to smallest. End goal is to find the mean, median and mode
sort(appleCoordinateContainer.begin(), appleCoordinateContainer.end(), sort_pred_double_descending());
appleCount = appleCoordinateContainer.size();
// 8) Find the interquartile mean and use this information to determine an average circle radius
MeanAndStandardDeviation_Apples();
// 9) Draw circles around each of the found apples, and output the total count, and mean size at the top of the Image
for (vector< pair<double, Point2i> >::iterator itA = appleCoordinateContainer.begin(); itA != appleCoordinateContainer.end(); ++itA)
{
circle(BGRImage_FirstRow, itA->second, interquartileAppleRadius, Scalar(0, 0, 255), 2);
}
// 10) Write image to a File to view
string writeText = "Apples Found: " + to_string(appleCount);
putText(BGRImage_FirstRow, writeText, Point(50, 50), fontFace, fontScale, Scalar(255, 0, 255), thickness);
imwrite(FilePath, BGRImage_FirstRow);
}
// Simple dilation on an image using a dilation value provided
void dilateImage(int ORCHARD_DILATE, Mat& sourceImg)
{
// We are assuming that the dilation effect will be a rectangular dilation
Mat outputImage;
// Create the structuring element for dilation
Mat element = getStructuringElement(0, Size(2 * ORCHARD_DILATE + 1, 2 * ORCHARD_DILATE + 1),
Point(ORCHARD_DILATE, ORCHARD_DILATE));
dilate(sourceImg, outputImage, element);
//return outputImage;
}
// Simple erosion on an image using a erosion value provided
void erodeImage(int ORCHARD_ERODE, Mat& sourceImg)
{
Mat outputImg;
// Create the structuring element for erosion
Mat element = getStructuringElement(1, Size(2 * ORCHARD_ERODE + 1, 2 * ORCHARD_ERODE + 1),
Point(ORCHARD_ERODE, ORCHARD_ERODE));
// Erode the image using the structuring element
erode(sourceImg, outputImg, element);
//return outputImg;
}
// Simple Blur to take away some of the edge in objects
void blurImage(int ORCHARD_BLUR, Mat& sourceImg)
{
// Simply blur the image to different values, which will be used to determine if the blurred filter Image will
// lead to better image recognition
Mat blurredImage;
medianBlur(sourceImg, blurredImage, ORCHARD_BLUR);
//return blurredImage;
}
// since all HSV_Value classes inheret from the innerBaseClass, this is the best way to make sure all operations can convert using the method below
Mat convertRGB2HSV(Mat& BGRImg, innerBaseClass* ORCHARD)
{
// HSV Values for Morphological Operations
ORCHARD->set();
Mat Threshold, HSVImg, Threshold_Temp;
cvtColor(BGRImg, HSVImg, CV_BGR2HSV);
inRange(HSVImg, Scalar(ORCHARD->H_Min, ORCHARD->S_Min, ORCHARD->V_Min), Scalar(ORCHARD->H_Max, ORCHARD->S_Max, ORCHARD->V_Max), Threshold_Temp);
/*Threshold_Temp = dilateImage(ORCHARD->HSV_DILATE, Threshold_Temp); // dilate
Threshold_Temp = erodeImage(ORCHARD->HSV_ERODE, Threshold_Temp); // erode
Threshold = blurImage(ORCHARD->HSV_BLUR, Threshold_Temp); // blur
*/
dilateImage(ORCHARD->HSV_DILATE, Threshold_Temp); // dilate
erodeImage(ORCHARD->HSV_ERODE, Threshold_Temp); // erode
blurImage(ORCHARD->HSV_BLUR, Threshold_Temp); // blur
Threshold_Temp.copyTo(Threshold);
return Threshold;
}
};
class BlossomOrchard
{
private:
// Internal Classes Used for HSV Operations
class innerBaseClass
{
public:
int H_Min, H_Max, S_Min, S_Max, V_Min, V_Max, HSV_DILATE, HSV_ERODE, HSV_BLUR;
Scalar* HSV_LOW = NULL;
Scalar* HSV_HIGH = NULL;
innerBaseClass()
{
set();
message();
}
virtual void set()
{
H_Min = 0;
H_Max = 0;
S_Min = 0;
S_Max = 0;
V_Min = 0;
V_Max = 0;
HSV_DILATE = 0;
HSV_ERODE = 0;
HSV_BLUR = 1;
Scalar* HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
Scalar* HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
virtual void message()
{
cout << "Base Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class Histogram
{
private:
// Class Variables that Set Up Histogram
const int WIDTH = 2048;
const int HEIGHT = 2048;
int yAxisTop = 0; // Sets some space between top of graph to top of image
int yAxisBottom = 0; // Sets some space between bottom of graph and top of image
int xAxisLeft = 0; // Starts xaxis a bit of space away from the left side of image
int xAxisRight = 0; // ends xaxis a bit of space away from the right side of image
const int imageSections = 8; // The number of sections the graph is divided into for axis drawing operations
const int numBins = 200; // The number of slices the data is cut into
int xAxisDistance = 0; // The distance between the origin and the end of the x-axis
int interval = 0; // The x-distance between each bin displayed (xAxisDistance / numBins)
const int scaleDownRatio = 6; // since the bins usually get relatively full, its a good idea to scale down
int xSpacer = 0; // Used in "OutputRowHistogram" in conjunction with "interval" to step through the graph
// Variables for Constructing Histogram text
int sumPixelsInBins = 0; // Total sum of all pixels counted
int averageBinDensity = 0; // average pixels found in each bin summed and averaged from all bins
double standard_deviation = 0;
Point2d histogramText; // For writing words on Histogram
// Class Variables for text output on RowDensity histogram
string avgBins = "Average Bin Size: ";
string numRows = "Number of Rows: ";
string FilePath;
int fontFace = CV_FONT_HERSHEY_PLAIN;
const double fontScale = 2;
const int thickness = 2;
// Very important container that holds the histogram data
vector<int> binContainer; // will hold all of the horizontal / vertical density bins for a given picture, depending which algorithm is called
Mat thresholdImage; // given to object when class is instantiated
// Private Methods
// Function draws axis on the histogram image
void drawAxis() // Input an Image to use
{// Put x and y axis on our blank image
line(histImg, Point(xAxisLeft, yAxisTop), Point(xAxisLeft, yAxisBottom), Scalar(255, 0, 0), 15); // y-axis
line(histImg, Point(xAxisLeft, yAxisBottom), Point(xAxisRight, yAxisBottom), Scalar(255, 0, 0), 15); // x-axis
}
// Function executes when outputRowHistogram in outer class is called
void MeanAndStandardDeviation_BinContainer()
{
double totalBinSum = 0;
int numElements = binContainer.size();
double temp = 0;
double variance = 0;
for (vector<int>::iterator itMean = binContainer.begin(); itMean != binContainer.end(); ++itMean)
{
totalBinSum += *itMean;
}
averageBinDensity = totalBinSum / numElements;
for (vector<int>::iterator itStand = binContainer.begin(); itStand != binContainer.end(); ++itStand)
{
temp += pow(abs(averageBinDensity - *itStand), 2);
}
variance = temp / numElements;
standard_deviation = sqrt(variance);
}
/* findThresholdDensity finds the density of a threshold image you provide by either slicing the image horizontally or verticaly.
findThresholdDensity sets the binContainer variable which is used to output a threshold density histogram. Call this function almost immediately.
Enter threshold Image you would like to find the bin density of
Select either true or false for second paramter: False = Horizontal Binning. True = Veritical Binning */
void findThresholdDensity(Mat thresholdImage, bool flip = false)
{
Mat orchardThreshold;
thresholdImage.copyTo(orchardThreshold);
// 1) Declare internal variables
int numBins = 200; // This divides the picture into slivers
int binWidth = 0; // Number of pixels within a sliver. Will be set differently depending on flip being true of false
int counter = 0; // generic counter
double whitePixelBinCount = 0; // the amount of white pixels counted in a bin
vector <double> temp; // all purpose temporary vector
// 2) Depending on the users input, the switch case will either run true or false.
// False indicates the threshold image will be horizontally binned. True indicates that the threshold image will be vertically binned
binContainer.clear(); // Wipe binContainer clean
binContainer.reserve(200); // reserve 200 spots for the vector
switch (flip)
{
case false: // If false is exectued, then the threshold picture will be horizontally binned
binWidth = orchardThreshold.rows / numBins; // Number of pixels within a bin. Here it corresponds to horizontal slivers
// 3) Loop through all rows. Once row reaches binWidth, store the number of pixels counted in binContainer.
// binWidth is currently set to 15 (3000/200).. so every 15 rows the pixel count will be stored
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{ // We need to add the white pixels to find a total amount of pixels
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount); // store bin pixel count in binContainer
whitePixelBinCount = 0;
}
}
break;
case true: // If true is exectued, then the threshold image will be vertically binned
binWidth = orchardThreshold.cols / numBins; // Number of pixels within a sliver. Here it corresponds to vertical slivers
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{ // We need to sum the white pixels to find a total amount of pixels per bin
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount); // store bin pixel count in binContainer
whitePixelBinCount = 0;
}
}
break;
default:
cout << "Something Didnt Work Right" << endl;
break;
}
// 4) Using the newly filled binContainer, find the mean and standard deviation of the binData
MeanAndStandardDeviation_BinContainer();
}
public:
// The Histogram image used for outputting
Mat histImg; // used to output the threshold density histogram image
Histogram(Mat& _thresholdImage, string _FilePath)
{
// Constructor will set object parameters for the histogram
_thresholdImage.copyTo(thresholdImage);
FilePath = _FilePath;
histImg = Mat(HEIGHT, WIDTH, CV_8UC3, Scalar(255, 255, 255)); // used to output the threshold density histogram image
yAxisTop = histImg.rows / imageSections; // sets some space between top of graph to top of image
yAxisBottom = histImg.rows - yAxisTop; // sets some space between bottom of graph and top of image
xAxisLeft = histImg.cols / imageSections; // starts xaxis a bit of space away from the left side of image
xAxisRight = histImg.cols - xAxisLeft; // ends xaxis a bit of space away from the right side of image
xAxisDistance = xAxisRight - xAxisLeft; // complete x-axis distance
interval = xAxisDistance / numBins; // the step size between bins on the graph
xSpacer = xAxisLeft; // xSpacer is user to step through the graph and draw it
histogramText = Point2d(xAxisLeft, yAxisTop - 100);
}
void drawHistogram(bool flip)
{
// 1) Draw histogram axis
drawAxis();
// 2) We need to run findThresholdDensity to fill the bin container
findThresholdDensity(thresholdImage, flip);
// 3) Output Bins on Histogram by drawing rectangles on histogram image
for (vector<int>::iterator countContainer = binContainer.begin(); countContainer != binContainer.end(); ++countContainer)
{// Loop through the container and remove the bin sizes we have found
rectangle(histImg, Point(xSpacer, yAxisBottom), Point(xSpacer + interval, yAxisBottom - (*countContainer / scaleDownRatio)), Scalar(0, 0, 255), -1);
xSpacer += interval; // increment to the next bin space
}
// 4) Turn average value into a string so openCV can output it on your histogram
avgBins += to_string(averageBinDensity);
// 5) Draw Average Line and Output text
line(histImg, Point(xAxisLeft, yAxisBottom - averageBinDensity / scaleDownRatio), Point(xAxisRight, yAxisBottom - averageBinDensity / scaleDownRatio), Scalar(0, 255, 0), 15); // Shows the average bin density on the histogram
putText(histImg, avgBins, histogramText, fontFace, fontScale, Scalar(255, 0, 255), thickness);
// 6) Write image to filepath that the user instantiated the object with
imwrite(FilePath, histImg);
}
~Histogram();
};
class HSV_Values_TreeStems : public innerBaseClass
{
public:
HSV_Values_TreeStems()
{
set();
message();
}
void set()
{
H_Min = 131;
H_Max = 169;
S_Min = 0;
S_Max = 38;
V_Min = 114;
V_Max = 197;
HSV_DILATE = 2;
HSV_ERODE = 1;
HSV_BLUR = 19;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Base Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class HSV_Values_BlossomRows : public innerBaseClass
{
public:
HSV_Values_BlossomRows()
{
set();
message();
}
void set()
{
H_Min = 157;
H_Max = 255;
S_Min = 44;
S_Max = 255;
V_Min = 0;
V_Max = 255;
HSV_DILATE = 2;
HSV_ERODE = 3;
HSV_BLUR = 1;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Base Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class HSV_Values_Blossoms : public innerBaseClass
{
public:
HSV_Values_Blossoms()
{
set();
message();
}
void set()
{
H_Min = 105;
H_Max = 148;
S_Min = 12;
S_Max = 58;
V_Min = 201;
V_Max = 255;
HSV_DILATE = 1;
HSV_ERODE = 1;
HSV_BLUR = 1;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Derived Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
class HSV_Values_TreeCanopy : public innerBaseClass
{
public:
HSV_Values_TreeCanopy()
{
set();
message();
}
void set()
{
H_Min = 30;
H_Max = 112;
S_Min = 0;
S_Max = 37;
V_Min = 80;
V_Max = 255;
HSV_DILATE = 13;
HSV_ERODE = 45;
HSV_BLUR = 31;
HSV_LOW = new Scalar(H_Min, S_Min, V_Min);
HSV_HIGH = new Scalar(H_Max, S_Max, V_Max);
}
void message()
{
cout << "Derived Class Fired" << endl;
cout << "H_Max is: " << H_Max << endl;
}
};
struct sort_pred_double_descending {
bool operator()(const pair<double, Point2i> &left, const pair<double, Point2i> &right)
{
return left.first > right.first; // first value is the largest
}
};
// Class Variables for BlossomOrchard
Mat HSVImg_temp; // Temporary Image that can be used for HSV transformations
int imageHeight = 0; // The number of pixels that make up the height of the image
int imageWidth = 0; // The number of pixels that make up the width of the image
vector<int> binContainer; // will hold all of the horizontal / vertical density bins for a given picture, depending which algorithm is called
// Variables for Histogram Related Things
const int numBins = 200;
int sumPixelsInBins = 0; // Total sum of all pixels counted
int averageBinDensity = 0; // average pixels found in each bin summed and averaged from all bins
double standard_deviation = 0;
Point2d histogramText; // For writing words on Histogram
// Class Variables for text output on RowDensity histogram
string avgBins = "Average Bin Size: ";
string numRows = "Number of Rows: ";
int fontFace = CV_FONT_HERSHEY_PLAIN;
const double fontScale = 5;
const int thickness = 3;
// Variables For Counting Apples In First Row
int blossomMeanArea = 0;
int blossomStdDeviation = 0;
int blossomRadius = 0;
int interquartileBlossomMean = 0;
int interquartileBlossomStdDeviation = 0;
int interquartileBlossomRadius = 0;
// Private Functions
// Get and Set Operations for Constructor
void GetSetObjectProperties(Mat& _BGRImage) // This GetSetGraphProperties is meant for constructor 1
{
// Constructor will use these to set the objects parameters
_BGRImage.copyTo(BGRImage);
imageHeight = _BGRImage.rows;
imageWidth = _BGRImage.cols;
// Constructor will find the threshold Image for both the Apple Orchard Rows and the Apples themselves
HSV_Values_Blossoms OrchardBlossoms; // HSV Values for Morphological Ops
HSV_Values_BlossomRows OrchardRows; // HSV Values for Morpholigical Ops
thresholdImg_Rows = convertRGB2HSV(BGRImage, &OrchardRows); // Convert BRG to Threshold Image of Orchard Rows using Row HSV Values
thresholdImg_Blossoms = convertRGB2HSV(BGRImage, &OrchardBlossoms); // Convert BRG to Threshold Image of Orchard Rows using Row HSV Values
}
/* findThresholdDensity finds the density of a threshold image you provide by either slicing the image horizontally or verticaly.
findThresholdDensity sets the binContainer variable which is used to output a threshold density histogram. Call this function almost immediately.
Enter threshold Image you would like to find the bin density of
Select either true or false for second paramter: False = Horizontal Binning. True = Veritical Binning */
void findThresholdDensity(Mat& thresholdImage, bool flip = false)
{
Mat orchardThreshold;
thresholdImage.copyTo(orchardThreshold);
// 1) Declare internal variables
int numBins = 200; // This divides the picture into slivers
int binWidth = 0; // Number of pixels within a sliver. Will be set differently depending on flip being true of false
int counter = 0; // generic counter
double whitePixelBinCount = 0; // the amount of white pixels counted in a bin
vector <double> temp; // all purpose temporary vector
// 2) Depending on the users input, the switch case will either run true or false.
// False indicates the threshold image will be horizontally binned. True indicates that the threshold image will be vertically binned
binContainer.clear(); // Wipe binContainer clean
binContainer.reserve(200); // reserve 200 spots for the vector
switch (flip)
{
case false: // If false is exectued, then the threshold picture will be horizontally binned
binWidth = orchardThreshold.rows / numBins; // Number of pixels within a bin. Here it corresponds to horizontal slivers
// 3) Loop through all rows. Once row reaches binWidth, store the number of pixels counted in binContainer.
// binWidth is currently set to 15 (3000/200).. so every 15 rows the pixel count will be stored
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{ // We need to add the white pixels to find a total amount of pixels
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount); // store bin pixel count in binContainer
whitePixelBinCount = 0;
}
}
break;
case true: // If true is exectued, then the threshold image will be vertically binned
binWidth = orchardThreshold.cols / numBins; // Number of pixels within a sliver. Here it corresponds to vertical slivers
for (int _column = 0; _column < orchardThreshold.cols; _column++)
{
for (int _row = 0; _row < orchardThreshold.rows; _row++)
{ // We need to sum the white pixels to find a total amount of pixels per bin
whitePixelBinCount += orchardThreshold.at<uchar>(_row, _column) / 255;
}
counter++;
if (counter == binWidth)
{
counter = 0;
binContainer.push_back(whitePixelBinCount); // store bin pixel count in binContainer
whitePixelBinCount = 0;
}
}
break;
default:
cout << "Something Didnt Work Right" << endl;
break;
}
// 4) Using the newly filled binContainer, find the mean and standard deviation of the binData
MeanAndStandardDeviation_BinContainer();
}
// Function executes when outputRowHistogram is called
void MeanAndStandardDeviation_BinContainer()
{
double totalBinSum = 0;
int numElements = binContainer.size();
double temp = 0;
double variance = 0;
for (vector<int>::iterator itMean = binContainer.begin(); itMean != binContainer.end(); ++itMean)
{
totalBinSum += *itMean;
}
averageBinDensity = totalBinSum / numElements;
for (vector<int>::iterator itStand = binContainer.begin(); itStand != binContainer.end(); ++itStand)
{
temp += pow(abs(averageBinDensity - *itStand), 2);
}
variance = temp / numElements;
standard_deviation = sqrt(variance);
}
// Function exectutes when findBlossoms is called. Calculates both mean & std_dev and interquartile mean & interquartile std_dev
void MeanAndStandardDeviation_Blossoms()
{
// Define Temporary Variables -- This
int _size = blossomCoordinateContainer.size(); // size of the container
int quartile = _size / 4; // size of one quartile
int tempSum = 0; // temporary sum
// 1) Find the apple mean
for (vector< pair<double, Point2i> >::iterator itA = blossomCoordinateContainer.begin(); itA != blossomCoordinateContainer.end(); ++itA)
{
tempSum += itA->first;
}
blossomMeanArea = tempSum / _size;
blossomRadius = std::sqrt(blossomMeanArea / 3.14);
// 2) Find apple standard deviation
tempSum = 0;
for (vector< pair<double, Point2i> >::iterator itA = blossomCoordinateContainer.begin(); itA != blossomCoordinateContainer.end(); ++itA)
{
tempSum += std::pow(std::abs(itA->first - blossomMeanArea), 2);
}
blossomStdDeviation = std::sqrt((tempSum / _size));
// 3) Find interquartile apple mean
tempSum = 0;
for (vector< pair<double, Point2i> >::iterator itA = blossomCoordinateContainer.begin() + quartile; itA < blossomCoordinateContainer.begin() + 3 * quartile; ++itA)
{
tempSum += itA->first;
}
interquartileBlossomMean = (tempSum / (_size / 2));
interquartileBlossomRadius = std::sqrt(interquartileBlossomMean / 3.14);
// 4) Find interquartile apple standard deviation
tempSum = 0;
for (vector< pair<double, Point2i> >::iterator itA = blossomCoordinateContainer.begin() + quartile; itA < blossomCoordinateContainer.begin() + 3 * quartile; ++itA)
{
tempSum += std::pow(std::abs(itA->first - interquartileBlossomMean), 2);
}
interquartileBlossomStdDeviation = std::sqrt((tempSum / (_size / 2)));
}
// Function counts the bin container to determine tree locations within a cropped image. Called from countTreesInRow
void findTreeCoordinates(bool BlossomCanopyOrTreeStem)
{ // This algorithm will find the trees or inside an image, and output their locations and coordinates on the BGR Image
// Will fill one of two containers. The canopy container or the
// 1) Declare Variables for local use
const int CONFIDENCE_LEVEL_TREES = 1; // If we have over ten bins in a row that are greater than the average, than most likely its a row
const int CONFIDENCE_LEVEL_FIELD = 4;
const double treeComparisonValue = averageBinDensity + standard_deviation; // compares bin values to 3 deviations higher than the mean bin-value
const double fieldComparisonValue = averageBinDensity; //- .25 * standard_deviation;
const int xAxisIncrement = imageWidth / numBins; // If Width is 4000 pixels, then the increment should be (4000/200 = 20)
const int treePadding = 100;
int compareTreeCount = 0; // Check to see if bin values correspond to rows
int compareFieldCount = 0; // Check to see if bin values correspond to field space
int xImageValue = imageWidth; // Width of picture
int treeCounter = 0;
bool treeStart = false;
pair<string, array<int, 2> >* myTree = NULL;
// 2) Start at the back of the bin container (right side of image), and go through and determine how many trees are in the image
for (reverse_iterator<vector<int>::iterator> itb = binContainer.rbegin(); itb != binContainer.rend(); ++itb)
{// starts at the end of the binContainer. The entries at the end will correspond to the first tree
// If the bin value is above the rowComparisonValue, and we are between rows, then we need to increment the compareRowCount variable
if ((*itb > treeComparisonValue) && (treeStart == false))
{
++compareTreeCount;
}
// If the bin value is not above the rowComparisonValue, and we are between rows, then we need to reset compareRowCount
if ((*itb < treeComparisonValue) && (treeStart == false))
{
compareTreeCount = 0;
}
// If the bin value is above the rowComparisonValue, and we are on a row, then we do not need to do anything
if ((*itb > fieldComparisonValue) && (treeStart == true))
{
compareFieldCount = 0;
}
// If the bin value is below the fieldComparisonValue, and a row has been found, then we need to increment compareFieldCounter
if ((*itb < fieldComparisonValue) && (treeStart == true))
{
++compareFieldCount;
}
// If the compareRowCount is at confidence_level.. then we are going to store the tree end coordinate and turn rowStart on
if (compareTreeCount == CONFIDENCE_LEVEL_TREES) // Then we have found a row. Let's store the y axis location
{
treeStart = true;
myTree = new pair<string, array<int, 2> >; // dynamically create another pair object that myRow will point at
myTree->first = "Row " + to_string(++treeCounter);
myTree->second[0] = NULL; // placeholder value
myTree->second[1] = xImageValue + 5 * xAxisIncrement; // Bottom Row value. Since we checked to find 5 confidence markers, backtrack 5 spots to find the start
compareTreeCount = NULL; // Now that we found a row, reset compareRowCount
}
// If the compareFieldCount is at confidence_level.. then we are going to store the row begin coordinate and turn rowStart off
if (compareFieldCount == CONFIDENCE_LEVEL_FIELD) // Then we have found a row. Let's store the y axis location
{
treeStart = false;
myTree->second[0] = xImageValue + 5 * xAxisIncrement; // Top Row value. Since we checked to find 5 confidence markers, backtrack 5 spots to find the end position of the tree
// if user selects true, then blossom treeCanopyCoordinateContainer will be filled
if (BlossomCanopyOrTreeStem)
{
treeCanopyCoordinateContainer.push_back(*myTree);
}
// if user selects false, then the treeTrunkCoordinateContainer will be filled
else
{
treeTrunkCoordinateContainer.push_back(*myTree);
}
compareFieldCount = 0; // Now that we found the end of the row, lets set the compareFieldCount to zero to restart process
myTree = NULL; // Now that we are done with the pointer, lets set it to NULL
}
xImageValue -= xAxisIncrement;
}
}
// We need to use the row container information to set the BGRImage_First_Row Matrix
// Function crops The BGRImage To Only View Objects in First Row. Sets BGRImage_First_Row - May need higher flight altitude
void cropBGRtoFirstRow()
{
int upperLeftYCoord = rowCoordinateContainer[1].second[1]; // Crop image from the start of the second row to the bottom of the first row
int upperRightXCoord = 0; // Tiny bit of buffer room
int buffer = 100; // To make sure no tree is getting cuttoff.
int height = rowCoordinateContainer[0].second[1] - rowCoordinateContainer[1].second[1] - buffer;
int width = 3999;
Mat ROI(BGRImage, Rect(upperRightXCoord, upperLeftYCoord - buffer, width, height));
ROI.copyTo(BGRImage_FirstRow);
}
public:
// Image Variables
Mat BGRImage; // The read-in BGR Orchard Image that initialized the object itself
Mat BGRImage_FirstRow; // The BGR image cropped to the first row specifications
// Threshold Images of the Rows and the Apples found using the inner HSV_Values classes
Mat thresholdImg_Blossoms; // Threshold Image of the apples on the trees
Mat thresholdImg_Blossoms_FirstRow; // Threshold Image of the blossoms in first row
Mat thresholdImg_Trees_FirstRow; // Threshold Image of potential tree locations in first row
Mat thresholdImg_Rows; // Threshold Image of the rows to identify trees
int blossomCount = 0;
// Very Important Coordinate Containers. Holds the Row, blossom, and tree information.
vector<pair<string, array<int, 2> > > rowCoordinateContainer; // Holds the row information per picture. Format: "Row X", [Lower Cord, Upper Cord]
vector<pair<double, Point2i> > blossomCoordinateContainer; // Holds the blossom information per picture. Format: "<Area,(xCord,yCord)>"
vector<pair<string, array<int, 2> > > treeCanopyCoordinateContainer; // Holds the tree information per picture. Iterates Right to Left. Format: "Row X", [Left Cord, Right Cord]
vector<pair<string, array<int, 2> > > treeTrunkCoordinateContainer; // Holds the tree information per picture. Iterates Right to Left. Format: "Row X", [Left Cord, Right Cord]
/*
Defining Constructor Variables:
inputImageFileName = The blank image you wish to construct your graph on
thresholdImg = The image which you would like to find the density of white pixels for
outputImageFileName = The output file you would like to write the histogram to
HSV_Low, HSV_High = If you supply a RGB Img, you must also supply HSV inRange values
numBins = assumed to be 200, change to more or less if you wish
*/
//_________________________________Constructor________________________//
// You can setup your object with the internal graph that is provided
BlossomOrchard(Mat& _BGRImg)
{
GetSetObjectProperties(_BGRImg);
}
//_________________________________Public Member Functions________________________//
// To output the row density histogram, give the function the address of what folder to write the image to. OUTPUT ONLY SETS NOTHING
void outputRowHistogram(string outputFilePath)
{
// Use Histogram Object to Find the Histogram
Histogram* rowHistogram = new Histogram(thresholdImg_Rows, outputFilePath);
rowHistogram->drawHistogram(false); // False indicates a horizontal binning
}
// This algorithm will find the rows inside a picture, and output their locations and coordinates on the objects Read-In BGR Orchard Image
// This algorithm will use the binContainer to determine where the rows in the Orchard Image are located
// Once the row locations are found, the algorithm will take the row information and crop the BGR image to only the first row
void findRowLocations()
{
// 1) Fill the binContainer with the blossom row data
findThresholdDensity(thresholdImg_Rows, false);
// 2) Define Variables for determining Blossom Orchard rows
const int CONFIDENCE_LEVEL = 5; // If we have over ten bins in a row that are greater than the average, than most likely its a row
const int BELOW_AVERAGE_LEVEL = 5; // We need to see if the our bin count
const double rowComparisonValue = averageBinDensity + standard_deviation; // compares bin values to 3 deviations higher than the mean bin-value
const double fieldComparisonValue = averageBinDensity - standard_deviation;
const int yAxisIncrement = imageHeight / numBins; // If Height is 3000 pixels, then the increment should be (3000/200 = 15)
const int rowPadding = 100;
int compareRowCount = 0; // Check to see if bin values correspond to rows
int compareFieldCount = 0; // Check to see if bin values correspond to field space
int yImageValue = imageHeight; // height of picture
int rowCounter = 0;
bool rowStart = false;
pair<string, array<int, 2> >* myRow = NULL;
// 3) Iterate through the bin container to determine where the rows in the Orchard Image are located
for (reverse_iterator<vector<int>::iterator> itb = binContainer.rbegin(); itb != binContainer.rend(); ++itb)
{// starts at the end of the binContainer. The entries at the end will correspond to the first row
// If the bin value is above the rowComparisonValue, and we are between rows, then we need to increment the compareRowCount variable
if ((*itb > averageBinDensity) && (rowStart == false))
{
++compareRowCount;
}
// If the bin value is not above the rowComparisonValue, and we are between rows, then we need to reset compareRowCount
if ((*itb < averageBinDensity) && (rowStart == false))
{
compareRowCount = 0;
}
// If the bin value is above the rowComparisonValue, and we are on a row, then we do not need to do anything
if ((*itb > averageBinDensity) && (rowStart == true))
{
compareFieldCount = 0;
}
// If the bin value is below the fieldComparisonValue, and a row has been found, then we need to increment compareFieldCounter
if ((*itb < averageBinDensity) && (rowStart == true))
{
++compareFieldCount;
}
// If the compareRowCount is at confidence_level.. then we are going to store the row end coordinate and turn rowStart on
if (compareRowCount == CONFIDENCE_LEVEL) // Then we have found a row. Let's store the y axis location
{
rowStart = true;
myRow = new pair<string, array<int, 2> >; // dynamically create another pair object that myRow will point at
myRow->first = "Row " + to_string(++rowCounter);
myRow->second[0] = NULL; // placeholder value
myRow->second[1] = yImageValue + 5 * yAxisIncrement; // Bottom Row value. Since we checked to find 5 confidence markers, backtrack 5 spots to find the start
compareRowCount = NULL; // Now that we found a row, reset compareRowCount
}
// If the compareFieldCount is at confidence_level.. then we are going to store the row begin coordinate and turn rowStart off
if (compareFieldCount == CONFIDENCE_LEVEL) // Then we have found a row. Let's store the y axis location
{
rowStart = false;
myRow->second[0] = yImageValue + 5 * yAxisIncrement; // Top Row value. Since we checked to find 5 confidence markers, backtrack 5 spots to find the start
rowCoordinateContainer.push_back(*myRow);
compareFieldCount = NULL; // Now that we found the end of the row, lets set the compareFieldCount to zero to restart process
myRow = NULL; // Now that we are done with the pointer, lets set it to NULL
}
yImageValue -= yAxisIncrement;
}
// 4) Using the rowCoordinateContainer information, crop the BGR Orchard Image to show only first row, and save it in BGRImg_First_Row Matrix
cropBGRtoFirstRow();
}
// This Algorithm is simply used to output the row coordinates on the BGRImage. This is a great way to visualize how accurate findRowLocations worked
void visualizeRowCoordinates(string outputFilePath)
{
// Draw rectangles around the rows found
for (vector<pair<string, array<int, 2> > >::iterator itRow = rowCoordinateContainer.begin(); itRow != rowCoordinateContainer.end(); ++itRow)
{
// Draws a rectangle around each and every row identified.
rectangle(BGRImage, Point(10, itRow->second[0]), Point(BGRImage.cols - 10, itRow->second[1]), Scalar(0, 0, 255), 3);
putText(BGRImage, itRow->first, Point(BGRImage.cols / 2, (itRow->second[0] + itRow->second[1]) / 2), fontFace, fontScale, Scalar(255, 0, 255), thickness);
}
// Output the file to the correct folder
Mat _BGRImage;
BGRImage.copyTo(_BGRImage);
imwrite(outputFilePath, _BGRImage);
}
// To output the tree histogram, give give the function the address of what folder to write the image to
void outputTreeHistogram(string FilePath)
{
// Create a Histogram object to visually see the bin container
Histogram* treeHistogram = new Histogram(thresholdImg_Blossoms_FirstRow, FilePath);
treeHistogram->drawHistogram(true);
}
// Call this Algorithm after you have identified the first row and wish to fill the treeCanopyCoordinateContainer
void findTreesInFirstRow()
{
Mat tempFirstRowThreshold;
HSV_Values_TreeCanopy Trees_HSV;
// 1) Change BGRImage_FirstRow to thresholdImg_Blossoms_FirstRow so we may conduct HSV operations on the first row image
tempFirstRowThreshold = convertRGB2HSV(BGRImage_FirstRow, &Trees_HSV);
tempFirstRowThreshold.copyTo(thresholdImg_Trees_FirstRow);
// 2) We need to reset the bincontainer. We need findThresholdDensity to iterate vertically over the cropped first row photo
findThresholdDensity(thresholdImg_Trees_FirstRow, true);
// 3) Now that the binContainer is filled with blossom values, lets run findTreeCoordinates to fill the treeCanopyCoordinateContainer
findTreeCoordinates(true);
}
// Call this algorithms to the individual trees within the first row
void findTreesAreaMethod(string FilePath)
{
// 1) Declare temp Matrix and HSV_Values for the tree operation
Mat tempFirstRowThreshold;
//HSV_Values_TreeStems Trees_HSV;
HSV_Values_TreeCanopy Trees_HSV;
// 2) Change BGRImage_FirstRow to thresholdImg_Blossoms_FirstRow so we may conduct HSV operations on the first row image
tempFirstRowThreshold = convertRGB2HSV(BGRImage_FirstRow, &Trees_HSV);
tempFirstRowThreshold.copyTo(thresholdImg_Trees_FirstRow);
imwrite("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\60BLOSSOMTHRESHOLD.jpg", thresholdImg_Trees_FirstRow);
// 3) Use Moments method to find and collect areas of all threshold objects in thresholdImg_Blossoms_FirstRow
// We will need to use the moments method to find all of the objects in the cropped image
vector <vector <Point> >contours; // holds the contours found for the apples
vector<Vec4i> hierarchy; // holds the hierarchial information for contours
Moments moment; // moments are used to calculate area values and x-y coordinates
double objectArea; // Used to store the object area
Point2i objectCenter; // Used to store the x,y coordinates of the objects
pair<double, Point2i> objectGeographicalInfo; // holds the pair of data
pair < pair< double, Point2i >, vector < Point> > storageInfo;
vector <pair < pair< double, Point2i >,vector < Point> > > objectInformationContainer; // Looks Cray, its not. Vector holding a pair of -> [pair of (Object Area, CenterPoint), and vector of (contours)]
vector <pair < pair< double, Point2i >, vector < Point> > > treeAreasAndCoordinates; // Main coordinate container which holds tree canopy locations
// Sorting predicates
struct treeAreasAndCoordinates_sorting_predicate_double_descending {
bool operator()(const pair < pair< double, Point2i >, vector < Point> > &left, const pair < pair< double, Point2i >, vector < Point> > &right)
{
return left.first.first > right.first.first; // first value is the largest
}
};
struct treeAreasAndCoordinates_sorting_predicate_Point2i_XCord_descending {
bool operator()(const pair < pair< double, Point2i >, vector < Point> > &left, const pair < pair< double, Point2i >, vector < Point> > &right)
{
return left.first.second.x > right.first.second.x; // first value is the largest
}
};
struct treeAreasAndCoordinates_sorting_predicate_Point2i_XCord_ascending {
bool operator()(const pair < pair< double, Point2i >, vector < Point> > &left, const pair < pair< double, Point2i >, vector < Point> > &right)
{
return left.first.second.x < right.first.second.x; // first value is the largest
}
};
struct treeAreasAndCoordinates_sorting_predicate_XCord_Contours {
bool operator()(const Point2i &left, const Point2i &right)
{
return left.x > right.x; // first value is the largest
}
};
// 4) Find object contours
findContours(thresholdImg_Trees_FirstRow, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
// 5) Find all object sizes and locations
for (vector< vector<Point> >::iterator itC = contours.begin(); itC != contours.end(); ++itC)
{
moment = moments((Mat)*itC);
objectArea = moment.m00; // holds object area
objectCenter = Point2i(moment.m10 / objectArea, moment.m01 / objectArea); // holds centerpoint
objectGeographicalInfo = pair<double, Point2i>(objectArea, objectCenter); // holds the pair of data
storageInfo = pair < pair< double, Point2i >, vector < Point> >(objectGeographicalInfo, *itC);
objectInformationContainer.push_back(storageInfo); // This now holds the object information and the contours of the object
}
// 6) Sort all objects in object size descending order
sort(objectInformationContainer.begin(), objectInformationContainer.end(), treeAreasAndCoordinates_sorting_predicate_double_descending());
// 7) Now find all objects that are larger than 8000 between 250 down and 200 from bottom -- MAY NEED TO FIDDLE WITH VALUES
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = objectInformationContainer.begin(); itT != objectInformationContainer.end(); ++itT)
{
if (itT->first.first > 8000 && itT->first.second.y > 250 && itT->first.second.y < (BGRImage_FirstRow.rows - 200))
{
treeAreasAndCoordinates.push_back(*itT);
}
}
// 8) Sort all objects in xCoordinate size order descending
sort(treeAreasAndCoordinates.begin(), treeAreasAndCoordinates.end(), treeAreasAndCoordinates_sorting_predicate_Point2i_XCord_descending());
// 9) Sort all the x-contour coordinates from smallest to largest within the treeAreasAndCoordinates container
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = treeAreasAndCoordinates.begin(); itT != treeAreasAndCoordinates.end(); ++itT)
{
sort(itT->second.begin(), itT->second.end(), treeAreasAndCoordinates_sorting_predicate_XCord_Contours());
}
// 10) We need to find any objects that are overlapping. If an object has an area that crosses over another object, keep the bigger objects area, and remove the smaller from the vector
// Delete any contours that arent the extremes, these are now unneeded
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = treeAreasAndCoordinates.begin(); itT != treeAreasAndCoordinates.end(); ++itT)
{
itT->second.erase(itT->second.begin() + 1, itT->second.end() - 2);
}
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = treeAreasAndCoordinates.begin()+1; itT != treeAreasAndCoordinates.end(); ++itT)
{
// Check to See if you are at the end of the vector.. If you are then we cant compare anything else
if ( (itT+1) != treeAreasAndCoordinates.end() )
{
int itHR = (itT - 1)->second.begin()->x; // adjacent right object high x coordinate
int itLR = ((itT - 1)->second.end() - 1)->x; // adjacent right object low x coordinate
int itHC = itT->second.begin()->x; // current object high x coordinate
int itLC = (itT->second.end()-1)->x; // current object low x coordinate
int itHL = (itT + 1)->second.begin()->x; // adjacent left object high x coordinate
// Case 1: Double intersection: Both objects clash with middle object. Assign left block high rights coords, assign pseudo chords to center and right to prevent further intersection
if ( (itHC > itLR) && (itHL > itLC) )
{
// Assigning left block high rights coords
vector<Point>::const_iterator itFirst = (itT + 1)->second.begin();
(itT + 1)->second.insert(itFirst, Point2i(itHR,0));
//Assigning pseudo coords for center and right to prevent further intersection
itT->second.begin()->x = 5000; // HC
itT->second.begin()->y = 5000; // HC
(itT->second.end()-1)->x = 5000; // LC
(itT->second.end()-1)->y = 5000; // LC
(itT-1)->second.begin()->x = 5000; // HR
(itT-1)->second.begin()->y = 5000; // HR
((itT-1)->second.end() - 1)->x = 5000; // LR
((itT-1)->second.end() - 1)->y = 5000; // LR
}
// Case 2: Center object intersects with right and does not intersect with left
if ( (itHC > itLR) && (itLC > itHL) )
{
// Assign center block High Rights coords
vector<Point>::iterator it_First = itT->second.begin();
itT->second.insert(it_First, Point2i(itHR,0) );
// Assign right block pseudo cords
(itT - 1)->second.begin()->x = 5000; // HR
(itT - 1)->second.begin()->y = 5000; // HR
((itT - 1)->second.end() - 1)->x = 5000; // LR
((itT - 1)->second.end() - 1)->y = 5000; // LR
}
// Case 3: If left and center blocks are intersecting but right block does not
if ( (itHC < itLR) && (itHL > itLC) )
{
// Assign left block the coords of high center
vector<Point>::iterator itFirst = (itT+1)->second.begin();
(itT+1)->second.insert(itFirst, Point2i(itHC,0));
// Assign pseudo cords for center
itT->second.begin()->x = 5000; // HC
itT->second.begin()->y = 5000; // HC
(itT->second.end() - 1)->x = 5000; // LC
(itT->second.end() - 1)->y = 5000; // LC
}
// Case 4: If there is no intersection, then do nothing
if ( (itLR > itHC) && (itHC > itHL) )
{
__nop();
}
}
}
// 11) Remove all unneeded content within the treeAreasandCoordinatesContainer
vector <pair < pair< double, Point2i >, vector < Point> > > eraseObjects; // vector of iterators that point to positions inside the container to remove
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itF = treeAreasAndCoordinates.begin(); itF != treeAreasAndCoordinates.end(); ++itF)
{
if (itF->second.begin()->x == 5000)
{
eraseObjects.push_back(*itF);
}
}
// 12) Use erase-remove idiom to find and remove all of the objects within the container that are undesirable
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itF = eraseObjects.begin(); itF != eraseObjects.end(); ++itF)
{
treeAreasAndCoordinates.erase(remove(treeAreasAndCoordinates.begin(), treeAreasAndCoordinates.end(), *itF), treeAreasAndCoordinates.end());
}
// 13) Find mean and standard deviation
int meanWidth = 0;
int sum = 0;
int std_dev_width = 0;
int variance = 0;
vector<int>treeWidth;
// finding mean
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = treeAreasAndCoordinates.begin(); itT != treeAreasAndCoordinates.end(); ++itT)
{
int width = (itT->second.begin()->x) - (itT->second.end() - 1)->x;
sum += width;
treeWidth.push_back(width);
}
meanWidth = sum / treeWidth.size();
// finding std dev
for (vector<int>::iterator itC = treeWidth.begin(); itC != treeWidth.end(); ++itC)
{
variance = abs(pow((*itC - meanWidth), 2));
}
std_dev_width = sqrt((variance / treeWidth.size()));
// This Section below needs work!!!
// 10) Find reported tree areas that are too small and merge them with their larger neighbors
vector <pair < pair< double, Point2i >, vector < Point> > > eraseVec; // vector of iterators that point to positions inside the container to remove
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = treeAreasAndCoordinates.begin(); itT != treeAreasAndCoordinates.end(); ++itT)
{
int currentWidth = 0;
int leftNeighborWidth = 0; // how large the tree slice to the left of the current slice is
int rightNeighborWidth = 0; // how large the tree slice to the right of the current slice is
int leftMargin = 0; // how close the current tree slice is to the adjacent left tree slice
int rightMargin = 0; // how close the current tree slice is to the adjacent right tree slice
const int LEFT_MAX_MARGIN = 80;
const int RIGHT_MAX_MARGIN = 80;
// Case 1: End condition, No right neighboor
if (itT == treeAreasAndCoordinates.begin())
{
currentWidth = abs((itT->second.begin()->x) - (itT->second.end() - 1)->x);
leftNeighborWidth = abs(((itT + 1)->second.begin()->x) - ((itT + 1)->second.end() - 1)->x); // how large the tree slice to the left of the current slice is
leftMargin = abs((itT->second.end() - 1)->x - (itT + 1)->second.begin()->x); // how close the current tree slice is to the adjacent left tree slice
// Check to see which is the larger neighboor. This will be the one that absorbs the xCordinate of the current tree canopy slice
int xCoordinate = 0;
// If the left margins is greater than the max and the tree is not greater than a standard dev above mean, we know we have a stand alone tree... this means we should expand its width
if ((leftMargin > LEFT_MAX_MARGIN) && (currentWidth < (meanWidth + std_dev_width)) )
{
if (((itT->second.end() - 1)->x - (itT + 1)->second.begin()->x) > meanWidth) // if the difference between the two is greater than mean width, than expand left by half of mean width
{
(itT->second.end() - 1)->x -= (double)(.5 * meanWidth);
}
else
{
(itT->second.end() - 1)->x = (itT + 1)->second.begin()->x + 1.1*LEFT_MAX_MARGIN; // 1.1 to give it a little buffer
}
// We now give the current data object the dont mess with me 5000 y - value
itT->second.begin()->y = 5000; // Key that this object was just adjusted. All right side operations next iteration should not consider this object
}
// if the left margin is under max & the current width is smaller than mean - std_dev, merge current object with left
if ( (leftMargin < LEFT_MAX_MARGIN) && (currentWidth < (meanWidth - std_dev_width)) )
{
// Assign the rightmost coord to the next object in the container
xCoordinate = itT->second.begin()->x;
(itT + 1)->second.begin()->x = xCoordinate;
// Assign pseudo values to the current itT so it does not interfere with any operations
itT->second.begin()->x = 5000; // Psuedo Values
itT->second.begin()->y = 5000; // Psuedo Values
(itT->second.end()-1)->x = 5000; // Psuedo Values
(itT->second.end()-1)->y = 5000; // Psuedo Values
eraseVec.push_back(*itT); // store current iterator contents into the eraseVec to erase merged object
}
}
// Case 2: End Condition, No left neighboor
if ((itT + 1) == treeAreasAndCoordinates.end())
{
currentWidth = abs((itT->second.begin()->x) - (itT->second.end() - 1)->x);
rightNeighborWidth = abs(((itT - 1)->second.begin()->x) - ((itT - 1)->second.end() - 1)->x); // how large the tree slice to the right of the current slice is
rightMargin = abs(((itT - 1)->second.end() - 1)->x - itT->second.begin()->x); // how close the current tree slice is to the adjacent right tree slice
// If the width is smaller than a standard deviation under the mean, we need to merge the tree slice either left right, or make sure its a stand alone tree with incorrect width assigned
// Check to see which is the larger neighboor. This will be the one that absorbs the xCordinate of the current tree canopy slice
int xCoordinate = 0;
// If the right margins is greater than the max, smaller than a std_dev above the mean ,and the previous right coordinate was not just set to psuedo value 5000, we know we have a stand alone tree... this means we should expand its width on the right side
if ((rightMargin > RIGHT_MAX_MARGIN) && (currentWidth < (meanWidth + std_dev_width) ) && (itT->second.begin()->y != 5000) )
{
if ( ( ((itT - 1)->second.end() - 1)->x - itT->second.begin()->x ) > meanWidth)
{
itT->second.begin()->x += (double)(.5*meanWidth);
}
else
{
itT->second.begin()->x = ((itT - 1)->second.end() - 1)->x - 1.1*RIGHT_MAX_MARGIN; // 1.1 for a tiny bit more buffer room than the max
}
}
// If right margin is under max, the previous right coordinate was not just set to psuedo value 5000, and the current width is smaller than the mean - std_Dev, group right
if ((rightMargin < RIGHT_MAX_MARGIN) && (itT->second.begin()->y != 5000) && (currentWidth < (meanWidth - std_dev_width)) && (currentWidth < (.5*rightNeighborWidth)) && (rightNeighborWidth < (meanWidth + std_dev_width) ))
{
xCoordinate = (itT->second.end()-1)->x; // Verdicts still out regarding whether this should be the leftmost coordinate or the end of the image itself to prevent cuttoff
((itT - 1)->second.end()-1)->x = xCoordinate; // right tree slice gains end of xCoordinate
eraseVec.push_back(*itT); // store current iterator contents into the eraseVec
}
}
// Case 3: Both neighbors are defined
if ( (itT != treeAreasAndCoordinates.begin()) && ((itT + 1) != treeAreasAndCoordinates.end()) )
{
currentWidth = abs((itT->second.begin()->x) - (itT->second.end() - 1)->x);
leftNeighborWidth = abs(((itT + 1)->second.begin()->x) - ((itT + 1)->second.end() - 1)->x); // how large the tree slice to the left of the current slice is
rightNeighborWidth = abs(((itT - 1)->second.begin()->x) - ((itT - 1)->second.end() - 1)->x); // how large the tree slice to the right of the current slice is
leftMargin = abs((itT->second.end() - 1)->x - (itT + 1)->second.begin()->x); // how close the current tree slice is to the adjacent left tree slice
rightMargin = abs(((itT - 1)->second.end() - 1)->x - itT->second.begin()->x); // how close the current tree slice is to the adjacent right tree slice
// If the width is smaller than a standard deviation under the mean, we need to merge the tree slice either left right, or make sure its a stand alone tree with incorrect width assigned
// Check to see which is the larger neighboor. This will be the one that absorbs the xCordinate of the current tree canopy slice
int xCoordinate = 0;
// If both the left and right margins are greater than the max, AND the previous right coordinate was not just set to psuedo value 5000 , we know we have a stand alone tree... this means we should expand the current trees width its width
if ((leftMargin > LEFT_MAX_MARGIN) && (rightMargin > RIGHT_MAX_MARGIN) && ((itT-1)->second.begin()->y != 5000) ) // then the current tree slice will get absorbed into the leftneighbor
{
// Find the middle between the left and right objects
const int middleOfLeftMargin = ((itT->second.end() - 1)->x + (itT + 1)->second.begin()->x) / 2;
const int middleofRightMargin = (itT->second.begin()->x + ((itT - 1)->second.end() - 1)->x) / 2;
const int buffer = (double)(.1*LEFT_MAX_MARGIN);
const int leftBackTrack = (double)(.75*LEFT_MAX_MARGIN);
const int rightBackTrack = (double)(.75*RIGHT_MAX_MARGIN);
const int centerBacktrack = (double)(.25*LEFT_MAX_MARGIN);
// Have left and right backtrack 75 + buffer away, and middle 25 + buffer
(itT + 1)->second.begin()->x = middleOfLeftMargin - leftBackTrack - buffer;
((itT - 1)->second.end()-1)->x = middleofRightMargin + rightBackTrack + buffer;
itT->second.begin()->x = middleofRightMargin - centerBacktrack - buffer;
(itT->second.end() - 1)->x = middleOfLeftMargin + centerBacktrack + buffer;
}
// If the current width is less than a standard deviation below the mean, then we know we have to take some action since its definately not a whole tree
if (currentWidth < (meanWidth - std_dev_width))
{
// If the left margin is twice over max but less than a mean width, left neighbor is not collassal (2 std's over mean) and the right margin is under max, center gains right, prepare right for removal
if ((leftMargin >(1.5 * LEFT_MAX_MARGIN)) && (leftMargin < meanWidth) && (leftNeighborWidth < (meanWidth + 1.5 * std_dev_width)) && (rightMargin < RIGHT_MAX_MARGIN))
{
// Center gains right coordinate
xCoordinate = (itT-1)->second.begin()->x;
itT->second.begin()->x = xCoordinate; // Center Tree slice gains the x-coordinate of the right member
// Prepare right for removal
(itT - 1)->second.begin()->x = 5000; // HR
(itT - 1)->second.begin()->y = 5000; // HR
((itT - 1)->second.end() - 1)->x = 5000; // LR
((itT - 1)->second.end() - 1)->y = 5000; // LR
eraseVec.push_back(*(itT-1)); // store right object into eraseVec for removal
}
// if left margin is under max, the right margin is above max but less than a mean tree length over,the right tree is not over two standard deviations greater then mean , AND the previous right coordinate was not just set to psuedo value 5000, then we will group left with center
if ((leftMargin < LEFT_MAX_MARGIN) && (rightMargin >(1.5 * RIGHT_MAX_MARGIN)) && (rightMargin < meanWidth) && (rightNeighborWidth < (meanWidth + 1.5*std_dev_width) ) && ((itT - 1)->second.begin()->y != 5000))
{
// Give left centers highest x-coordinate
xCoordinate = itT->second.begin()->x;
(itT + 1)->second.begin()->x = xCoordinate;
// Prepare center for removal
itT->second.begin()->x = 5000; // HC
itT->second.begin()->y = 5000; // HC
(itT->second.end() - 1)->x = 5000; // LC
(itT->second.end() - 1)->y = 5000; // LC
eraseVec.push_back(*itT); // store current iterator contents into the eraseVec
}
// If both margins are under max, and the width of the current tree is half the size of the surrounding trees, if the left neighbor width is larger than the right neighborwidth, group left
if ((leftMargin < LEFT_MAX_MARGIN) && (rightMargin < RIGHT_MAX_MARGIN) && (currentWidth < (.5*leftNeighborWidth)) && (currentWidth < (.5*rightNeighborWidth)) && (leftNeighborWidth > rightNeighborWidth))
{
// Give left object centers high x values
xCoordinate = itT->second.begin()->x;
(itT + 1)->second.begin()->x = xCoordinate; // left tree slice gains xCoordinate
// Prepare center for removal
itT->second.begin()->x = 5000; // HC
itT->second.begin()->y = 5000; // HC
(itT->second.end() - 1)->x = 5000; // LC
(itT->second.end() - 1)->y = 5000; // LC
eraseVec.push_back(*itT); // store current iterator contents into the eraseVec
}
// If both margins are under max, then if the right neighbor width is larger than the left neighborwidth, group right with center
if ((leftMargin < LEFT_MAX_MARGIN) && (rightMargin < RIGHT_MAX_MARGIN) && (leftNeighborWidth < rightNeighborWidth))
{
// To prevent further collision or a growth pattern, give right centers lower x coordinate, and prepare center for removal
xCoordinate = (itT->second.end() - 1)->x;
((itT - 1)->second.end() - 1)->x = xCoordinate; // Right Tree slice gains the x-coordinate
// Prepare center for removal
itT->second.begin()->x = 5000; // HC
itT->second.begin()->y = 5000; // HC
(itT->second.end() - 1)->x = 5000; // LC
(itT->second.end() - 1)->y = 5000; // LC
eraseVec.push_back(*itT); // store center into the eraseVec
}
}
}
}
// 11) Delete the tree areas members that were found to be too small
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = eraseVec.begin(); itT != eraseVec.end(); ++itT)
{
treeAreasAndCoordinates.erase(remove(treeAreasAndCoordinates.begin(), treeAreasAndCoordinates.end(),*itT), treeAreasAndCoordinates.end());
}
// 12) Clear the eraseVec so we dont have a memory leak or a dangling pointer
eraseVec.clear();
// 13) Resort the data members to make sure all remaining object center coordinate are in descending order
sort(treeAreasAndCoordinates.begin(), treeAreasAndCoordinates.end(), treeAreasAndCoordinates_sorting_predicate_Point2i_XCord_descending());
// 10) Now that the xCordinates within each vector are sorted, lets go ahead and draw lines on the BGRCroppedImg;
//Mat _BGRImage_FirstRow;
//BGRImage_FirstRow.copyTo(_BGRImage_FirstRow);
for (vector <pair < pair< double, Point2i >, vector < Point> > >::iterator itT = treeAreasAndCoordinates.begin(); itT != treeAreasAndCoordinates.end(); ++itT)
{
rectangle(BGRImage_FirstRow, Point(itT->second.begin()->x, 100), Point((itT->second.end() - 1)->x, BGRImage_FirstRow.rows - 50), Scalar(255, 0, 0), 3);
}
// 11) Now write the Image into BlossomOrchard Folder for safe keeping
imwrite(FilePath, BGRImage_FirstRow);
}
void findTreesTrunkMethod(string FilePath1, string FilePath2)
{
// 1) Declare temp Matrix and HSV_Values for the tree operation
Mat tempFirstRowThreshold;
HSV_Values_TreeStems Trees_HSV;
// 2) Change BGRImage_FirstRow to thresholdImg_Blossoms_FirstRow so we may conduct HSV operations on the first row image
tempFirstRowThreshold = convertRGB2HSV(BGRImage_FirstRow, &Trees_HSV);
tempFirstRowThreshold.copyTo(thresholdImg_Trees_FirstRow);
imwrite("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\60BLOSSOMTHRESHOLD.jpg", thresholdImg_Trees_FirstRow);
// 3) Use Moments method to find and collect areas of all threshold objects in thresholdImg_Blossoms_FirstRow
// We will need to use the moments method to find all of the objects in the cropped image
vector <vector <Point> >contours; // holds the contours found for the apples
vector<Vec4i> hierarchy; // holds the hierarchial information for contours
Moments moment; // moments are used to calculate area values and x-y coordinates
double objectArea; // Used to store the object area
Point2i objectCenter; // Used to store the x,y coordinates of the objects
pair<double, Point2i> objectGeographicalInfo; // holds the pair of data
pair < pair< double, Point2i >, vector < Point> > storageInfo;
vector <pair < pair< double, Point2i >, vector < Point> > > objectInformationContainer; // Looks Cray, its not. Vector holding a pair of -> [pair of (Object Area, CenterPoint), and vector of (contours)]
vector <pair < pair< double, Point2i >, vector < Point> > >treeAreasAndCoordinates;
// Sorting predicates
struct treeAreasAndCoordinates_sorting_predicate_double_descending {
bool operator()(const pair < pair< double, Point2i >, vector < Point> > &left, const pair < pair< double, Point2i >, vector < Point> > &right)
{
return left.first.first > right.first.first; // first value is the largest
}
};
struct treeAreasAndCoordinates_sorting_predicate_Point2i_XCord_descending {
bool operator()(const pair < pair< double, Point2i >, vector < Point> > &left, const pair < pair< double, Point2i >, vector < Point> > &right)
{
return left.first.second.x > right.first.second.x; // first value is the largest
}
};
struct treeAreasAndCoordinates_sorting_predicate_XCord_Contours {
bool operator()(const Point2i &left, const Point2i &right)
{
return left.x > right.x; // first value is the largest
}
};
// 4) Find object contours
findContours(thresholdImg_Trees_FirstRow, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
// 5) Find all object sizes and locations
for (vector< vector<Point> >::iterator itC = contours.begin(); itC != contours.end(); ++itC)
{
moment = moments((Mat)*itC);
objectArea = moment.m00; // holds object area
objectCenter = Point2i(moment.m10 / objectArea, moment.m01 / objectArea); // holds centerpoint
objectGeographicalInfo = pair<double, Point2i>(objectArea, objectCenter); // holds the pair of data
storageInfo = pair < pair< double, Point2i >, vector < Point> >(objectGeographicalInfo, *itC);
objectInformationContainer.push_back(storageInfo); // This now holds the object information and the contours of the object
}
// 6) Sort all objects in object size descending order
sort(objectInformationContainer.begin(), objectInformationContainer.end(), treeAreasAndCoordinates_sorting_predicate_double_descending());
findThresholdDensity(tempFirstRowThreshold, true);
Histogram* treeHistogram = new Histogram(tempFirstRowThreshold, FilePath1);
treeHistogram->drawHistogram(true);
bool fillTreeTrunkContainer = false;
findTreeCoordinates(fillTreeTrunkContainer);
visualizeTreeCoordinates(FilePath2, fillTreeTrunkContainer);
}
// This Algorithm is simply used to output the tree coordinates on the cropped BGRImage. This is a great way to visualize how accurate findTreeCoordinates worked
// Enter true for tree canopy or false for tree trunk visualization...reason being is we have two seperate containers that need to be pulled from
void visualizeTreeCoordinates(string outputFilePath, bool TreeCanopyorTreeTrunk)
{
const int buffer = 50;
switch (TreeCanopyorTreeTrunk)
{
case true: // canopy
// Draw rectangles around the canopy found
for (vector<pair<string, array<int, 2> > >::iterator itRow = treeCanopyCoordinateContainer.begin(); itRow != treeCanopyCoordinateContainer.end(); ++itRow)
{
// Draws a rectangle around each and every tree identified.
rectangle(BGRImage_FirstRow, Point(itRow->second[0], buffer), Point(itRow->second[1], BGRImage_FirstRow.rows - buffer), Scalar(0, 0, 255), 3);
putText(BGRImage_FirstRow, itRow->first, Point(BGRImage.cols / 2, (itRow->second[0] + itRow->second[1]) / 2), fontFace, fontScale, Scalar(255, 0, 255), thickness);
}
break;
case false: // trunk
// Draw rectangles around the trunks found
for (vector<pair<string, array<int, 2> > >::iterator itRow = treeTrunkCoordinateContainer.begin(); itRow != treeTrunkCoordinateContainer.end(); ++itRow)
{
// Draws a rectangle around each and every tree identified.
rectangle(BGRImage_FirstRow, Point(itRow->second[0], buffer), Point(itRow->second[1], BGRImage_FirstRow.rows - buffer), Scalar(0, 0, 255), 3);
putText(BGRImage_FirstRow, itRow->first, Point(BGRImage.cols / 2, (itRow->second[0] + itRow->second[1]) / 2), fontFace, fontScale, Scalar(255, 0, 255), thickness);
}
break;
}
// Output the file to the correct folder
imwrite(outputFilePath, BGRImage_FirstRow);
}
// Call this Algorithm after you have identified the individual rows and wish to count the individual blossoms inside of that row
void countBlossomsInFirstRow(string FilePath)
{
// 1) We need to use the row container information to crop the BGR photo to only show the first row specifications
cropBGRtoFirstRow();
// 2) Assume most objects in picture are apples, this will be corrected with more ImageLabTesting Filtering Routines
HSV_Values_Blossoms Blossom_HSV_Values;
thresholdImg_Blossoms_FirstRow = convertRGB2HSV(BGRImage_FirstRow, &Blossom_HSV_Values); // converts cropped BGR Image to a cropped threshold image
// 3) We will need to use the moments method to find all of the objects in the cropped image
vector <vector <Point> >contours; // holds the contours found for the apples
vector<Vec4i> hierarchy; // holds the hierarchial information for contours
Moments moment; // moments are used to calculate area values and x-y coordinates
double objectArea; // Used to store the object area
Point2i objectCenter; // Used to store the x,y coordinates of the objects
pair<double, Point2i> storeObjectData; // holds the pair of data
findContours(thresholdImg_Blossoms_FirstRow, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
// 4) Take the contours, find areas, and store the areas, and the coordinates of the objects into a "pair vector"
int count = -1;
for (vector < vector<Point> >::iterator itc = contours.begin(); itc != contours.end(); ++itc)
{
++count;
moment = moments((Mat)*itc);
// 5) If an object is greater than an agreed upon small blossom size, we will count it as a blossom
if (moment.m00 > 20) // Then it is a contender to be a row
{
// 6) Store all the coordinates of the apples in a "pair" vector composed of their areas and their x,y coordinates in a Point
objectArea = moment.m00; // holds object area
objectCenter = Point2i(moment.m10 / objectArea, moment.m01 / objectArea); // holds centerpoint
storeObjectData = pair<double, Point2i>(objectArea, objectCenter); // holds the pair of data
blossomCoordinateContainer.push_back(storeObjectData); // push data set into our container
blossomCount++;
}
}
// 7) Sort the data from greatest to smallest. End goal is to find the mean, median and mode
sort(blossomCoordinateContainer.begin(), blossomCoordinateContainer.end(), sort_pred_double_descending());
blossomCount = blossomCoordinateContainer.size();
// 8) Find the interquartile mean and use this information to determine an average circle radius
MeanAndStandardDeviation_Blossoms();
// 9) Draw circles around each of the found apples, and output the total count, and mean size at the top of the Image
for (vector< pair<double, Point2i> >::iterator itA = blossomCoordinateContainer.begin(); itA != blossomCoordinateContainer.end(); ++itA)
{
circle(BGRImage_FirstRow, itA->second, interquartileBlossomRadius, Scalar(0, 0, 255), 2);
}
// 10) Write image to a File to view
string writeText = "Blossoms Found: " + to_string(blossomCount);
putText(BGRImage_FirstRow, writeText, Point(50, 50), fontFace, fontScale, Scalar(255, 0, 255), thickness);
imwrite(FilePath, BGRImage_FirstRow);
}
//----------------------------Utility Algorithms ----------------------------//
// Internal Member Function to write an image to a provided FilePath
void writeImageToFile(string FilePath, Mat ImageToWrite)
{
imwrite(FilePath, ImageToWrite);
}
// Simple dilation on an image using a dilation value provided
Mat dilateImage(int ORCHARD_DILATE, Mat sourceImg)
{
// We are assuming that the dilation effect will be a rectangular dilation
Mat outputImage;
// Create the structuring element for dilation
Mat element = getStructuringElement(0, Size(2 * ORCHARD_DILATE + 1, 2 * ORCHARD_DILATE + 1),
Point(ORCHARD_DILATE, ORCHARD_DILATE));
dilate(sourceImg, outputImage, element);
return outputImage;
}
// Simple erosion on an image using a erosion value provided
Mat erodeImage(int ORCHARD_ERODE, Mat sourceImg)
{
Mat outputImg;
// Create the structuring element for erosion
Mat element = getStructuringElement(1, Size(2 * ORCHARD_ERODE + 1, 2 * ORCHARD_ERODE + 1),
Point(ORCHARD_ERODE, ORCHARD_ERODE));
// Erode the image using the structuring element
erode(sourceImg, outputImg, element);
return outputImg;
}
// Simple Blur to take away some of the edge in objects
Mat blurImage(int ORCHARD_BLUR, Mat sourceImg)
{
// Simply blur the image to different values, which will be used to determine if the blurred filter Image will
// lead to better image recognition
Mat blurredImage;
medianBlur(sourceImg, blurredImage, ORCHARD_BLUR);
return blurredImage;
}
// since all HSV_Value classes inheret from the innerBaseClass, this is the best way to make sure all operations can convert using the method below
Mat convertRGB2HSV(Mat BGRImg, innerBaseClass* ORCHARD)
{
// HSV Values for Morphological Operations
ORCHARD->set();
Mat Threshold, HSVImg, Threshold_Temp;
cvtColor(BGRImg, HSVImg, CV_BGR2HSV);
inRange(HSVImg, Scalar(ORCHARD->H_Min, ORCHARD->S_Min, ORCHARD->V_Min), Scalar(ORCHARD->H_Max, ORCHARD->S_Max, ORCHARD->V_Max), Threshold_Temp);
/*Threshold_Temp = dilateImage(ORCHARD->HSV_DILATE, Threshold_Temp); // dilate
Threshold_Temp = erodeImage(ORCHARD->HSV_ERODE, Threshold_Temp); // erode
Threshold = blurImage(ORCHARD->HSV_BLUR, Threshold_Temp); // blur
*/
Threshold = dilateImage(ORCHARD->HSV_DILATE, Threshold_Temp); // dilate
Threshold_Temp = erodeImage(ORCHARD->HSV_ERODE, Threshold); // erode
Threshold = blurImage(ORCHARD->HSV_BLUR, Threshold_Temp); // blur
return Threshold;
}
};
// Function Prototypes
void BatchProcessAppleOrchard(const int firstImgNum, const int lastImgNum);
void BatchProcessBlossomOrchard(const int firstImgNum, const int lastImgNum);
int main(void)
{
//Batch Processing Images
BatchProcessBlossomOrchard(70, 90);
//BatchProcessAppleOrchard(20, 99);
}
void BatchProcessAppleOrchard(const int firstImgNum, const int lastImgNum)
{
// Variable Declarations
Mat BGRImg;
vector< AppleOrchard*> OrchardImages;
for (size_t i = firstImgNum; i < lastImgNum + 1; i++)
{
if (i < 10)
{
BGRImg = imread("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\UnprocessedImages\\160901 crop load\\DJI_000" + to_string(i) + ".jpg");
// Output File Paths
string rowHistoFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_RowHisto.jpg";
string rowsFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_RowsFound.jpg";
string treesFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_TreesFound.jpg";
string applesFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_ApplesFound.jpg";
if (BGRImg.rows != 0) // check to make sure the read-in image is actually an image
{
// Batch Processing the Apple Orchard Images
AppleOrchard* AppleImage = new AppleOrchard(BGRImg);
AppleImage->outputRowHistogram(rowHistoFilePath);
AppleImage->findRowLocations();
AppleImage->visualizeRowCoordinates(rowsFoundFilePath);
AppleImage->CountApplesInFirstRow(applesFoundFilePath);
OrchardImages.push_back(AppleImage);
}
}
else
{
BGRImg = imread("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\UnprocessedImages\\160901 crop load\\DJI_00" + to_string(i) + ".jpg");
// Output File Paths
string rowHistoFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_RowHisto.jpg";
string rowsFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_RowsFound.jpg";
string treesFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_TreesFound.jpg";
string applesFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\AppleOrchard\\" + to_string(i) + "AppleOrchard_ApplesFound.jpg";
if (BGRImg.rows != 0) // check to make sure the read-in image is actually an image
{
// Batch Processing the Apple Orchard Images
AppleOrchard* AppleImage = new AppleOrchard(BGRImg);
AppleImage->outputRowHistogram(rowHistoFilePath);
AppleImage->findRowLocations();
AppleImage->visualizeRowCoordinates(rowsFoundFilePath);
AppleImage->CountApplesInFirstRow(applesFoundFilePath);
OrchardImages.push_back(AppleImage);
}
}
}
}
void BatchProcessBlossomOrchard(const int firstImgNum, const int lastImgNum)
{
// Variable Declarations
Mat BGRImg;
vector< BlossomOrchard* > OrchardImages;
for (size_t i = firstImgNum; i < lastImgNum + 1; i++)
{
if (i < 10)
{
// Read in Images from Blossom Drone Photos
BGRImg = imread("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\UnprocessedImages\\160503_blossoms\\DJI_000" + to_string(i) + ".jpg");
// Output File Paths --Figure out how you want these to be organized...should have some organization scheme
string rowHistoFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_RowHisto.jpg";
string treeHistoFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreeHisto.jpg";
string rowsFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_RowsFound.jpg";
string treesFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreesFound.jpg";
string treesFoundAreaMethodFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreesFound_AM.jpg";
string treesFoundContoursMethodFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreesFound_AM.jpg";
string blossomsFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_BlossomsFound.jpg";
// Batch Processing the Blossom Orchard Images
// Error Handling
if (BGRImg.rows != 0) // check to make sure the read-in image is actually an image
{
BlossomOrchard* BlossomImage = new BlossomOrchard(BGRImg);
BlossomImage->findRowLocations();
BlossomImage->outputRowHistogram(rowHistoFilePath);
BlossomImage->visualizeRowCoordinates(rowsFoundFilePath);
BlossomImage->findTreesTrunkMethod(treeHistoFilePath, treesFoundFilePath);
BlossomImage->findTreesAreaMethod(treesFoundAreaMethodFilePath);
//BlossomImage->findTreesInFirstRow();
//BlossomImage->outputTreeHistogram(treeHistoFilePath);
//BlossomImage->visualizeTreeCoordinates(treesFoundFilePath);
BlossomImage->countBlossomsInFirstRow(blossomsFoundFilePath);
// Store The Pointer to the Object in the Orchard-Image Container
OrchardImages.push_back(BlossomImage);
}
}
else
{
// Read in Images from Blossom Drone Photos
BGRImg = imread("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\UnprocessedImages\\160503_blossoms\\DJI_00" + to_string(i) + ".jpg");
// Output File Paths --Figure out how you want these to be organized...should have some organization scheme
string rowHistoFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_RowHisto.jpg";
string treeHistoFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreeHisto.jpg";
string rowsFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_RowsFound.jpg";
string treesFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreesFound.jpg";
string treesFoundAreaMethodFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreesFound_AM.jpg";
string treesFoundContoursMethodFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_TreesFound_CM.jpg";
string blossomsFoundFilePath = "Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\ProcessedPhotos\\BlossomOrchard\\" + to_string(i) + "BlossomOrchard_BlossomsFound.jpg";
// Batch Processing the Blossom Orchard Images
// Error Handling
if (BGRImg.rows != 0) // check to make sure the read-in image is actually an image
{
BlossomOrchard* BlossomImage = new BlossomOrchard(BGRImg);
BlossomImage->findRowLocations();
BlossomImage->outputRowHistogram(rowHistoFilePath);
BlossomImage->visualizeRowCoordinates(rowsFoundFilePath);
//BlossomImage->findTreesContoursMethod(treesFoundContoursMethodFilePath);
BlossomImage->findTreesAreaMethod(treesFoundAreaMethodFilePath);
BlossomImage->findTreesTrunkMethod(treeHistoFilePath, treesFoundFilePath);
//BlossomImage->findTreesInFirstRow();
//BlossomImage->outputTreeHistogram(treeHistoFilePath);
//BlossomImage->visualizeTreeCoordinates(treesFoundFilePath);
BlossomImage->countBlossomsInFirstRow(blossomsFoundFilePath);
// Store The Object in the Orchard Image Container
OrchardImages.push_back(BlossomImage);
}
}
}
}
<file_sep>/ImageAnalysisLab/ImageAnalysisEnviro/Main.cpp
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <opencv2\imgproc.hpp>
#include <opencv\cv.h>
#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <opencv2\imgcodecs.hpp>
#include <array>
#include <cmath>
using namespace std;
using namespace cv;
// Function Prototypes
Mat blurImage_Image_Analysis(Mat inputImg);
Mat convertRGB2HSV_Image_Analysis(Mat sourceImg);
Mat erodeImage_Image_Analysis(int HSV_ERODE, Mat sourceImg);
Mat dilateImage_Image_Analysis(int HSV_DILATE, Mat sourceImg);
void snagKeyboardEvents(int &keyboardChoice);
void on_trackbar(int, void*);
void setUpTrackerBars(void);
void thresh_callback(int, void*);
// This Project is intended to be used to do soft coded image analysis. Desired result is find values and properties of image
// to quickly implement into main sections of drone code
// TrackerBar HSV Integer Values
// These are the Global HSV Values used for Quick Image Analysis
int H_LOW = 0;
int H_HIGH = 255;
int S_LOW = 0;
int S_HIGH = 255;
int V_LOW = 0;
int V_HIGH = 255;
int HSV_DILATE = 1;
int HSV_ERODE = 1;
int HSV_BLUR = 1;
int key;
int ESCAPE_KEY = 27;
// Some Global Boolean Values
bool toggleHSV = false;
bool toggleXmasTrees = false;
bool countObjects = false;
bool allowEnterance = false;
// Counter and Image Matrices
int _counter = 0;
Mat BGRImg,HSVImg,ThresholdImg;
int main()
{
// Read in Video Feed -- This Option Shows HSV Manipulation for real time processing
VideoCapture cap(0);
if (!cap.isOpened())return -1;
// You could use this option to simply just read in one image instead of a live video feed
//BGRImg = imread("Z:\\Desktop\\Honors_Thesis\\ImageAnalysisLab\\Photos\\UnprocessedImages\\Picture2.jpg");
// Call the tracker bar function to initialize trackerbars
setUpTrackerBars();
// Create a named window to display the image on screen with function imshow("Window Name");
namedWindow("ImageWindow", CV_WINDOW_NORMAL); //this is to show image...we want to output image into file
cout << "Hit Escape Key To Terminate Program" << endl;
while ((key = waitKey(50)) != ESCAPE_KEY)
{
// Comment this out below if you are reading in a still image
cap >> BGRImg;
//img = imread("Z:\\Desktop\\Honors_Thesis\\OpenCV_Chapter_Notes_And_Scripts\\UnprocessedImages\\FlowerBlossoms\\DJI_00" + to_string(14 + universal_counter) + ".jpg");
// Snag the keyboard event to see if any switches need to be made from HSV to BGR
snagKeyboardEvents(key);
// We need to do a conversion between the BGR Full color image and the HSV image. Then take the
// HSV image and run through the inRange function to filter out unwanted values
ThresholdImg = convertRGB2HSV_Image_Analysis(BGRImg); // Returns the threshold image using the trackervalues we updated
ThresholdImg = blurImage_Image_Analysis(ThresholdImg);
// We need to check if the user wishes to see the HSV Image or the Regular Image
if (toggleHSV) imshow("ImageWindow", ThresholdImg);
else imshow("ImageWindow", BGRImg);
// Count Objects -- Put Whatever Code Here
if (countObjects)
{
countObjects = !countObjects;
// Put Code To Run Here when you push the key that corresponds to the countObjects Boolean. Count Objects can be changed
}
}
destroyAllWindows();
}
Mat convertRGB2HSV_Image_Analysis(Mat sourceImg)
{
// HSV Values for Morphological Operations
Mat Threshold, HSVImg, Threshold_Temp;
cvtColor(BGRImg, HSVImg, CV_BGR2HSV);
inRange(HSVImg, Scalar(H_LOW,S_LOW,V_LOW), Scalar(H_HIGH,S_HIGH,V_HIGH), Threshold_Temp); // turn hsv into threshold
Threshold_Temp = dilateImage_Image_Analysis(HSV_DILATE, Threshold_Temp); // dilate
Threshold = erodeImage_Image_Analysis(HSV_ERODE, Threshold_Temp); // erode
return Threshold;
}
Mat dilateImage_Image_Analysis(int HSV_DILATE, Mat sourceImg)
{
// We are assuming that the dilation effect will be a rectangular dilation
Mat outputImage;
// Create the structuring element for dilation
Mat element = getStructuringElement(0, Size(2 * HSV_DILATE + 1, 2 * HSV_DILATE + 1),
Point(HSV_DILATE, HSV_DILATE));
dilate(sourceImg, outputImage, element);
return outputImage;
}
Mat erodeImage_Image_Analysis(int HSV_ERODE, Mat sourceImg)
{
Mat outputImg;
// Create the structuring element for erosion
Mat element = getStructuringElement(1, Size(2 * HSV_ERODE + 1, 2 * HSV_ERODE + 1),
Point(HSV_ERODE, HSV_ERODE));
// Erode the image using the structuring element
erode(sourceImg, outputImg, element);
return outputImg;
}
Mat blurImage_Image_Analysis(Mat inputImg)
{
// Simply blur the image to different values, which will be used to determine if the blurred filter Image will
// lead to better image recognition
Mat blurredImage;
medianBlur(inputImg, blurredImage, HSV_BLUR);
return blurredImage;
}
void setUpTrackerBars(void)
{
// Need to call the window in the same function as the trackbars themselves
namedWindow("TrackerBarWindow", CV_WINDOW_NORMAL);
// HSV Values
createTrackbar("H_MIN", "TrackerBarWindow", &H_LOW, H_HIGH, on_trackbar);
createTrackbar("H_MAX", "TrackerBarWindow", &H_HIGH, H_HIGH, on_trackbar);
createTrackbar("S_MIN", "TrackerBarWindow", &S_LOW, S_HIGH, on_trackbar);
createTrackbar("S_MAX", "TrackerBarWindow", &S_HIGH, S_HIGH, on_trackbar);
createTrackbar("V_MIN", "TrackerBarWindow", &V_LOW, V_HIGH, on_trackbar);
createTrackbar("V_MAX", "TrackerBarWindow", &V_HIGH, V_HIGH, on_trackbar);
//Dilate, Erode, and threshhold
createTrackbar("Dilate", "TrackerBarWindow", &HSV_DILATE, 50, on_trackbar);
createTrackbar("Erode", "TrackerBarWindow", &HSV_ERODE, 50, on_trackbar);
createTrackbar("Blur", "TrackerBarWindow", &HSV_BLUR, 50, on_trackbar);
}
void on_trackbar(int, void*)
{
/*
When you drag the trackerbar across the screen, the referenced value you enter is used to gage.
Apparently it somehow handles the mouse event on its own without putting in the while loop
*/
// We want to make sure these values are never zero
if (HSV_DILATE == 0)
HSV_DILATE = 1;
if (HSV_ERODE == 0)
HSV_ERODE = 1;
if (HSV_BLUR % 2 == 0)
HSV_BLUR += 1;
}
void snagKeyboardEvents(int &keyboardChoice)
{
// hitting the keyboard key t will show the HSV image and not the regular image
if (keyboardChoice == 't')
{
toggleHSV = !toggleHSV;
}
// by toggling the keyboard key f we will run a full analysis on the filefolder of images
if (keyboardChoice == 'f')
{
toggleXmasTrees = !toggleXmasTrees;
}
// by pressing the letter c, count the objects
if (keyboardChoice == 'c')
{
countObjects = !countObjects;
}
}
void thresh_callback(int, void*)
{
// Finding Threshold with Gray Image and Canny function
Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Detect edges using canny
Canny(src_gray, canny_output, thresh, thresh * 2, 3);
/// Find contours
findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Draw contours
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
/// Show in a window
namedWindow("Contours", CV_WINDOW_NORMAL);
imshow("Contours", drawing);
}
<file_sep>/README.md
#README.md
The AppleOrchard algorithms are written for high altitude and low altitude UAV image processing for a DJI Phantom 3 Quadcopter. The AppleOrchard code is written using C++ and OpenCV 3.0.
Functionality includes tree counting, blossom density prediction, row recognition, and apple yield on a per row basis.
<file_sep>/ImageAnalysisLab/Drone Code/ChristmasTrees/Main.cpp
#include <iostream>
#include <fstream>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv\cv.h>
#include <opencv2\highgui.hpp>
#include <opencv2\core.hpp>
#include <opencv2\imgcodecs.hpp>
#include <array>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
using namespace cv;
// The objective of this code is to identify christmas trees in a stochastic environment. The objectives are three fold.
// 1.) Count as many trees accurately as possible.
// 2.) Allow users to interact with the software so they can count trees in anindividual patch of an image.
// 3.) Document the geographical infomration in an organized method to allow file writing with it.
// The tree Image class will be designed to read a tree image in, find the amount of trees, their x,y location within the image
// and the final count.
// Function Prototypes
void onMouse_SelectCorners(int event, int x, int y, int, void* userInput);
void ChristmasTreeGUI();
void followBall();
uint8_t zoomInZoomOut();
// Class Describing the contents of high altitude christmas tree images
class christmasTreeImageAnalyzer
{
private:
// Nested Inner Classes
class innerHSVObject
{
public:
// Member variables
int H_LOW;
int H_HIGH;
int S_LOW;
int S_HIGH;
int V_LOW;
int V_HIGH;
int HSV_DILATE;
int HSV_ERODE;
int HSV_BLUR;
Scalar LOW;
Scalar HIGH;
innerHSVObject()
{
set();
}
virtual void set()
{
// Virtual override function
}
};
class XmasHSV: public innerHSVObject
{
private:
public:
XmasHSV()
{
set();
}
void set()
{
// Virtual override function
H_LOW = 28;
H_HIGH = 40;
S_LOW = 63;
S_HIGH = 176;
V_LOW = 150;
V_HIGH = 194;
HSV_DILATE = 4;
HSV_ERODE = 7;
HSV_BLUR = 1;
LOW = Scalar(H_LOW, S_HIGH, V_LOW);
HIGH = Scalar(H_HIGH, S_HIGH, V_HIGH);
}
};
class ImgStats
{
private:
vector<double> dataSet;
void getData(vector<pair<double, Point2i> >* data)
{
for (vector<pair<double, Point2i> >::iterator itT = data->begin(); itT != data->end(); ++itT)
{
dataSet.push_back(itT->first);
}
}
public:
double mean;
double median;
pair<double,int> mode;
double std_dev;
double variance;
double interquartile_Mean;
double interquartile_Std_Dev;
double interquartile_Variance;
double interquartile_Mode;
ImgStats(vector<pair<double, Point2i> >* _dataSet)
{
getData(_dataSet);
findMean();
findMedian();
findMode();
findStdDev();
findIQMean();
findIQStdDev();
findIQMode();
}
void findMean()
{
int sum = 0;
int average = 0;
for (vector<double>::iterator it = dataSet.begin(); it != dataSet.end(); ++it)
{
sum += *it;
}
mean = sum / dataSet.size();
}
void findStdDev()
{
double absDiff = 0;
double temp = 0;
for (vector<double>::iterator it = dataSet.begin(); it != dataSet.end(); ++it)
{
absDiff = abs(*it - mean);
temp += pow(absDiff, 2);
}
std_dev = sqrt( ( temp / (dataSet.size() - 1) ) );
variance = pow(std_dev, 2);
}
void findMedian()
{
// 1. Sort Array ascending
std::sort(dataSet.begin(), dataSet.end(), sort_double());
// 2. count middle
int middleNumber;
if (dataSet.size() % 2 == 0) // Even
{
middleNumber = dataSet.size() / 2;
median = (dataSet[middleNumber - 1] + dataSet[middleNumber]) / 2;
}
else
{
middleNumber = (dataSet.size() + 1) / 2;
median = dataSet[middleNumber];
}
}
void findMode()
{
vector<double> uniqueNumbers;
vector<int> numberFrequency;
vector< pair< double, int> > modeData;
// 1. Data must be sorted
vector<double> dataCopy = dataSet;
sort(dataCopy.begin(), dataCopy.end(), sort_double());
// 2. Go through each number
for (vector<double>::iterator itD = dataCopy.begin(); itD != dataCopy.end(); ++itD)
{
// Compare Numbers for frequency and uniqueness
bool found = false; // Found is set to true when it finds the number itD points to in unique numbers data set
for (vector<double>::iterator itU = uniqueNumbers.begin(); itU != uniqueNumbers.end(); ++itU)
{
// If the contents of the dataSet matches an entry within unique numbers, then the number has already been counted
if (*itD == *itU)
{
found = true;
}
}
// If the value found is false, then it means itD is a unique number and should be added to the itU dataset
if (found != true)
{
uniqueNumbers.push_back(*itD);
}
}
for (vector<double>::iterator itU = uniqueNumbers.begin(); itU != uniqueNumbers.end(); ++itU)
{
int count = 0;
for (vector<double>::iterator itD = uniqueNumbers.begin(); itD != uniqueNumbers.end(); ++itD)
{
if (*itU == *itD)
{
count++;
}
}
modeData.push_back(pair<double, int>(*itU, count));
}
sort(modeData.begin(), modeData.end(), sortMode());
mode = modeData[0];
}
void findIQMean()
{
int sum = 0;
int average = 0;
int count = 0;
for (vector<double>::iterator it = dataSet.begin() + dataSet.size() / 4; it != dataSet.end() - dataSet.size() / 4; ++it)
{
sum += *it;
count++;
}
interquartile_Mean = sum / count;
}
void findIQStdDev()
{
double absDiff = 0;
double temp = 0;
for (vector<double>::iterator it = dataSet.begin() + dataSet.size()/4; it != dataSet.end() - dataSet.size()/4; ++it)
{
absDiff = abs(*it - interquartile_Mean);
temp += pow(absDiff, 2);
}
interquartile_Std_Dev = sqrt((temp / (dataSet.size() - 1)));
interquartile_Variance = pow(std_dev, 2);
}
void findIQMode()
{
vector<double> uniqueNumbers;
vector<int> numberFrequency;
vector< pair< double, int> > modeData;
// 1. Data must be sorted
vector<double> dataCopy = dataSet;
std::sort(dataCopy.begin(), dataCopy.end(), sort_double());
// 2. Go through each number
for (vector<double>::iterator itD = dataCopy.begin() + dataCopy.size()/4; itD != dataCopy.end() - dataCopy.size()/4; ++itD)
{
// Compare Numbers for frequency and uniqueness
bool found = false; // Found is set to true when it finds the number itD points to in unique numbers data set
for (vector<double>::iterator itU = uniqueNumbers.begin(); itU != uniqueNumbers.end(); ++itU)
{
// If the contents of the dataSet matches an entry within unique numbers, then the number has already been counted
if (*itD == *itU)
{
found = true;
}
}
// If the value found is false, then it means itD is a unique number and should be added to the itU dataset
if (found != true)
{
uniqueNumbers.push_back(*itD);
}
}
for (vector<double>::iterator itU = uniqueNumbers.begin(); itU != uniqueNumbers.end(); ++itU)
{
int count = 0;
for (vector<double>::iterator itD = dataCopy.begin() + dataCopy.size()/4; itD != dataCopy.end() - dataCopy.size()/4; ++itD)
{
if (*itU == *itD)
{
count++;
}
}
modeData.push_back(pair<double, int>(*itU, count));
}
std::sort(modeData.begin(), modeData.end(), sortMode());
mode = modeData[0];
}
};
// Sorting Predicate: Sorts a vector container of pairs in decending order
struct sort_pred_double_descending {
bool operator()(const pair<double, Point2i> &left, const pair<double, Point2i> &right)
{
return left.first > right.first; // first value is the largest
}
};
// Sorting Predicate: Sorts a vector container of pair<> in ascending order
struct sort_pred_double_ascending {
bool operator()(const pair<double, Point2i> &left, const pair<double, Point2i> &right)
{
return left.first < right.first; // first value is the smallest
}
};
struct sort_double
{
bool operator()(const double& left, const double& right)
{
return left < right;
}
};
struct sortMode
{
bool operator()(const pair<double, int>& left, const pair<double, int> & right)
{
return right.second > left.second;
}
};
// Variables
Mat img; // Read in Image
int imHeight; // Image Height
int imWidth; // Image Width
ImgStats* myStats = NULL;
// Private function that acts upon img. converts image to threshold
Mat& findThreshold()
{
Mat hsvImg;
Mat threshold;
cvtColor(img, hsvImg, CV_BGR2HSV);
}
// Simple dilation on an image using a dilation value provided
Mat dilateImage(int ORCHARD_DILATE, Mat sourceImg)
{
// We are assuming that the dilation effect will be a rectangular dilation
Mat outputImage;
// Create the structuring element for dilation
Mat element = getStructuringElement(0, Size(2 * ORCHARD_DILATE + 1, 2 * ORCHARD_DILATE + 1),
Point(ORCHARD_DILATE, ORCHARD_DILATE));
dilate(sourceImg, outputImage, element);
return outputImage;
}
// Simple erosion on an image using a erosion value provided
Mat erodeImage(int ORCHARD_ERODE, Mat sourceImg)
{
Mat outputImg;
// Create the structuring element for erosion
Mat element = getStructuringElement(1, Size(2 * ORCHARD_ERODE + 1, 2 * ORCHARD_ERODE + 1),
Point(ORCHARD_ERODE, ORCHARD_ERODE));
// Erode the image using the structuring element
erode(sourceImg, outputImg, element);
return outputImg;
}
// since all HSV_Value classes inheret from the innerBaseClass, this is the best way to make sure all operations can convert using the method
Mat convertRGB2HSV(Mat BGRImg, innerHSVObject* ORCHARD)
{
// HSV Values for Morphological Operations
ORCHARD->set();
Mat Threshold, HSVImg, Threshold_Temp;
cvtColor(BGRImg, HSVImg, CV_BGR2HSV);
inRange(HSVImg, Scalar(ORCHARD->H_LOW, ORCHARD->S_LOW, ORCHARD->V_LOW), Scalar(ORCHARD->H_HIGH, ORCHARD->S_HIGH, ORCHARD->V_HIGH), Threshold_Temp);
Threshold_Temp = dilateImage(ORCHARD->HSV_DILATE, Threshold_Temp); // dilate
Threshold = erodeImage(ORCHARD->HSV_ERODE, Threshold_Temp); // erode
return Threshold;
}
public:
// Public treeImage constructure
christmasTreeImageAnalyzer(Mat& inputImg)
{
img = inputImg;
imHeight = inputImg.rows;
imWidth = inputImg.cols;
}
cv::Mat countTrees()
{
// 1. Convert the RGB Image into an HSV and subsequent threshold Image
Mat bgr;
Mat threshold, temp;
XmasHSV HSV_Values;
img.copyTo(bgr);
threshold = convertRGB2HSV(bgr, &HSV_Values);
// 2. With the new threshold image, find number of raw objects
threshold.copyTo(temp);
vector<pair<double, Point2i> > objectContainer;
vector< vector<Point> > contours; // Contours of objects
vector<Vec4i> hierarchy; // Hierarchy of Object
double objectArea; // Area of Object
Point2i xyCords; // Object Center Coordinates
// find contours
findContours(temp, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);
// loop through contours to find number of objects, sizes, and locations
for (vector<vector<Point2i> >::iterator itT = contours.begin(); itT != contours.end(); ++itT)
{
// Find moment of objects
Moments objMoment = moments((Mat)*itT);
// Prevent little pieces of noisy data form getting into img. Img size 4000x3000
if (objMoment.m00 > 50)
{
// Find Area and center
objectArea = objMoment.m00; // finds object area
xyCords = Point2i(objMoment.m10 / objectArea, objMoment.m01 / objectArea); // finds centerpoint
// Store Object inside container
objectContainer.push_back(pair<double, Point2i>(objectArea, xyCords));
}
}
// Sort Results by Area - Ascending
std::sort(objectContainer.begin(), objectContainer.end(), sort_pred_double_ascending());
// Find stats on the christmas tree sizes
myStats = new ImgStats(&objectContainer);
// Find Coordinates of the tree with the median size
Point2i treeCords;
for (vector<pair<double, Point2i> >::iterator itO = objectContainer.begin(); itO != objectContainer.end(); ++itO)
{
// find the coordinates for the median tree size in the data
if (itO->first == myStats->median)
{
treeCords = itO->second; // store coordinates
}
}
// Set the HSV Scalar Value for christmas trees you find
Mat hsvImg;
cvtColor(bgr, hsvImg, CV_BGR2HSV);
Vec3b intensity = hsvImg.at<Vec3b>(treeCords.y, treeCords.x);
// count objects and show image with counted trees
int treeCount = 0;
int radius = sqrt(myStats->interquartile_Mean / 3.14);
for (vector<pair<double, Point2i> >::iterator itO = objectContainer.begin(); itO != objectContainer.end(); ++itO)
{
// If the data is within 95% of the confidence interval
if ( ( itO->first > (myStats->mean - 2*myStats->std_dev) ) && (itO->first < (myStats->mean + 2*myStats->std_dev) ) )
{
circle(bgr, itO->second, radius, Scalar(0, 0, 255), -1);
++treeCount;
}
}
string text = "Trees Found = " + to_string(treeCount);
putText(bgr, text, Point(50, 50), FONT_HERSHEY_PLAIN, 4, Scalar(255, 0, 0), 3);
return bgr;
}
};
// Global Variables
int key;
Mat ROI;
Mat src;
int clickNum = 0;
int rectangleEventClickCounter = 0;
int cropEventClickCounter = 0;
char currentEvent;
cv::Point2i lastMouseLocation;
vector<Point2i> clickLocations;
Mat rectImg;
// Vector to hold images
vector<Mat> imageArray;
vector<cv::Mat>::iterator currentImageInArrayPointer;
uint8_t imageArrayIndexer = 0;
// Booleans
bool rectangleEventFinished = false;
bool croppedEventFinished = false;
// Constants
const uint8_t ESCAPE_KEY = 27;
const uint8_t ZOOM_IN = 61;
const uint8_t ZOOM_OUT = 45;
const uint8_t UNDO = 44;
const uint8_t REDO = 46;
// Sorting Predicates
struct sort_point2i_xleft
{
bool operator()(const Point2i& left, const Point2i& right)
{
return left.x < right.x;
}
};
struct sort_point2i_xright
{
bool operator()(const Point2i& left, const Point2i& right)
{
return left.x > right.x;
}
};
struct sort_point2i_ytop
{
bool operator()(const Point2i& top, const Point2i& bottom)
{
return top.y < bottom.y;
}
};
struct sort_point2i_ybottom
{
bool operator()(const Point2i& top, const Point2i& bottom)
{
return top.y > bottom.y;
}
};
int main(void)
{
ChristmasTreeGUI();
waitKey(0);
}
// Mouse Callback Event #1
void onMouse_SelectCorners(int event, int x, int y, int, void* userInput)
{
if (event != EVENT_LBUTTONDOWN) return;
// Get the pointer input image
Mat* img = (Mat*)userInput;
// Draw circle
cv::circle(*img, Point(x, y), 30, Scalar(0, 0, 255), 3);
// Increment userClicks, and update the click number on the screen
clickNum++;
clickLocations.push_back(Point2i(x, y));
}
void onMouse_DrawingFunctions(int event, int x, int y, int, void* userInput)
{
// If the user is using the rectangle feature 'r'. All code in this block makes the GUI functionality work with the user
if (currentEvent == 'r')
{ // If the mouse moves, then run this code
if (event == cv::EVENT_MOUSEMOVE)
{
lastMouseLocation = cv::Point2i(x, y); // Store the last mouse location
}
// If the mouse pad was clicked down, run this code
if (event == cv::EVENT_LBUTTONDOWN)
{
std::cout << "Mouse Down" << std::endl;
clickLocations.push_back(Point2i(x, y));
rectangleEventClickCounter++;
rectangleEventFinished = false;
}
// If the user had just let the mousepad come up, this code will run
if (event == cv::EVENT_LBUTTONUP)
{
rectangleEventClickCounter++;
if (rectangleEventClickCounter == 2) // If the user made an initial click then it will trigger here
{
// Update the rectangle being drawn in the users screen with the latest event data
std::cout << "Drawing Rectangle" << std::endl;
Mat temp = *(imageArray.begin() + imageArrayIndexer - 1);
cv::rectangle(temp, *(clickLocations.end() - 1), cv::Point2i(x, y), cv::Scalar(0, 0, 255), 2, 1); // Draw updated rectangle
*currentImageInArrayPointer = temp;
rectangleEventClickCounter = 0;
rectangleEventFinished = true;
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
}
}
}
// If the user is using the crop function 'c'. This will find the region of interest the user is interested in and add the cropped image to the cureent image array pointer
if (currentEvent == 'c')
{
// If the mouse moves, then run this code
if (event == cv::EVENT_MOUSEMOVE)
{
lastMouseLocation = cv::Point2i(x, y); // Store the last mouse location
}
// If the mousepad was clicked down, then run this code
if (event == cv::EVENT_LBUTTONDOWN)
{
std::cout << "Mouse Down" << std::endl;
clickLocations.push_back(Point2i(x, y));
cropEventClickCounter++;
croppedEventFinished = false;
}
// If the mousepad was down, as was released up, then this code segment will run
if (event == cv::EVENT_LBUTTONUP)
{
cropEventClickCounter++;
std::cout << "Mouse Up" << std::endl;
if (cropEventClickCounter == 2) // If the user made an initial click then it will trigger here
{
// Crop Image
std::cout << "Croppping Image" << std::endl;
// Condition for Cropping
if ((clickLocations.end() - 1)->x < x && (clickLocations.end() - 1)->y < y)
{
Mat tmp = cv::Mat(*currentImageInArrayPointer, cv::Rect(*(clickLocations.end() - 1), Point2i(x, y)));
*currentImageInArrayPointer = tmp;
destroyWindow("XmasTree");
namedWindow("XmasTree");
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
}
cropEventClickCounter = 0;
croppedEventFinished = true;
}
}
}
}
// Main function call for User Event
// Zoom in and Zoom out:
uint8_t zoomInZoomOut()
{
/// variables
Mat src, dst, tmp;
char* window_name = "Pyramids Demo";
/// General instructions
printf("\n Zoom In-Out demo \n ");
printf("------------------ \n");
printf(" * [i] -> Zoom in \n");
printf(" * [o] -> Zoom out \n");
printf(" * [ESC] -> Close program \n \n");
/// Test image - Make sure it s divisible by 2^{n}
src = imread("C:\\Users\\natsn\\Desktop\\Research\\ImageAnalysisLab\\Drone Code\\ChristmasTrees\\XmasTreeAerial.jpg");
if (!src.rows)
{
printf(" No data! -- Exiting the program \n");
return -1;
}
tmp = src;
dst = tmp;
/// Create window
namedWindow(window_name, CV_WINDOW_AUTOSIZE);
imshow(window_name, dst);
/// Loop
while (true)
{
int c;
c = waitKey(10);
if ((char)c == 27)
{
break;
}
if ((char)c == 'i')
{
pyrUp(tmp, dst, Size(tmp.cols * 2, tmp.rows * 2));
printf("** Zoom In: Image x 2 \n");
}
else if ((char)c == 'o')
{
pyrDown(tmp, dst, Size(tmp.cols / 2, tmp.rows / 2));
printf("** Zoom Out: Image / 2 \n");
}
imshow(window_name, dst);
tmp = dst;
}
return 0;
}
// Draw, Navigate, and Count Object within the image
void ChristmasTreeGUI()
{
int keyPressed;
// Change this line to the file that needs an image read in
src = imread("C:\\Users\\natsn\\Desktop\\Research\\ImageAnalysisLab\\Drone Code\\ChristmasTrees\\XmasTreeAerial.jpg");
if (src.rows == 0)
{
cout << "Failed To Open!" << endl;
exit(1);
}
// Store the image inside of the image array
imageArray.push_back(src); // Store The Image in the image node
currentImageInArrayPointer = imageArray.begin(); // Update the image pointer to point at the initial data
// Window for Image
namedWindow("XmasTree", WINDOW_AUTOSIZE);
/* // Let user zoom in, zoom out, click a region of interest, and drag a circle around tree
// r: Draw a rectangle using the mouse
// c: Crop image to specific dimensions
// +: Zoom into image
// -: Zoom out of image
// t: Train Machine- allows you to draw a circle over a tree for the computer to learn what the tree looks like
// <: Undo - Show previous image (if there is one)
// >: Redo - Show next image (if there is one)
*/
cout << " Press Keys r, c, +, -, t, b, f To Trigger Events " << endl;
cout << " r: Draw a rectangle using the mouse " << endl;
cout << " c: Crop image to specific dimensions " << endl;
cout << " +: Zoom into image " << endl;
cout << " -: Zoom out of image " << endl;
cout << " r: Count All Trees within the current image" << endl;
cout << " t: Train Machine- allows you to draw a circle over a tree for the computer to learn what the tree looks like (NOT FINISHED) " << endl;
cout << " <: Back - Show previous image (if there is one) " << endl;
cout << " >: Forward - Show previous image (if there is one) " << endl;
cout << " Press Escape To Exit From Drawing Function" << endl;
while (1)
{
// Find user keyboard event. WaitKey will wait the number of milliseconds you specify and then return the character on the keyboard that was pressed
keyPressed = waitKey(10);
// If the user wishes to draw a rectangle, then set up mouse events to allow drawing
if (keyPressed == 'r')
{
cout << "Hello From Draw Rectangle!" << endl;
currentEvent = 'r';
// Allow the update of the rectangle on the screen while the mouse is held down
// Initialize the Mouse Callback function - Any time a mouse click, movement, etc occurs,
// run the function specified inside of mouseCallBack function for the window you specify
setMouseCallback("XmasTree", onMouse_DrawingFunctions);
// Save last image we have to the image array
imageArray.push_back(*currentImageInArrayPointer); // Save the image
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
// Escape condition is the user wishes to stop drawing on their image by pressing the escape key
while ((keyPressed = waitKey(50)) != ESCAPE_KEY && !rectangleEventFinished)
{
// Let the mouse events draw the picture for us.
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
}
std::cout << "Rectangle Successfully Drawn" << std::endl;
std::cout << "Goodbye From Draw Rectangle!" << std::endl;
}
// Check To see if the user wishes to crop the image to their specifications
if (keyPressed == 'c')
{
currentEvent = 'c';
cout << "Hello From Crop Image" << endl;
setMouseCallback("XmasTree", onMouse_DrawingFunctions);
// The Array Should add the last image again to the arrayPointer so the crop function will not harm the source
imageArray.push_back(*currentImageInArrayPointer);
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
imshow("XmasTree", *currentImageInArrayPointer);
keyPressed = waitKey(25);
while ((keyPressed = waitKey(50)) != ESCAPE_KEY && !croppedEventFinished)
{
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
}
std::cout << "Image Cropped Successfully" << std::endl;
std::cout << "Goodbye From Crop Image!" << std::endl;
}
// If the user wants the number of trees to be counted, push f
if (keyPressed == 'f')
{
cout << "Hello From Find Number of Trees! " << endl;
cout << "Counting...." << endl;
// The Array Should add the last image again to the arrayPointer so the crop function will not harm the source
imageArray.push_back(*currentImageInArrayPointer);
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
christmasTreeImageAnalyzer aerialViewOfTrees(*currentImageInArrayPointer); // Initialize a Christmas Tree Analysis Object
*currentImageInArrayPointer = aerialViewOfTrees.countTrees();
destroyWindow("XmasTree");
cout << "Trees Successfully Counted!" << endl;
namedWindow("XmasTree");
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
cout << "Gooodbye from Count Trees!" << endl;
}
// Check if the user wants to zoom into the image
if (keyPressed == ZOOM_IN)
{
currentEvent = ZOOM_IN;
cout << "Hello From Zoom In!" << std::endl;
imageArray.push_back(*currentImageInArrayPointer); // Add The next node
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
pyrUp(imageArray[imageArrayIndexer - 1], *currentImageInArrayPointer, Size(currentImageInArrayPointer->cols * 2, currentImageInArrayPointer->rows * 2));
printf("** Zoom In: Image x 2 \n");
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
cout << "Image Has been zoomed in on" << std::endl;
cout << "Goodbye from Zoom In!" << std::endl;
}
if (keyPressed == ZOOM_OUT)
{
currentEvent = ZOOM_OUT;
cout << "Hello From Zoom Out!" << std::endl;
imageArray.push_back(*currentImageInArrayPointer); // Add The next node
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
pyrDown(imageArray[imageArrayIndexer -1], *currentImageInArrayPointer, Size(currentImageInArrayPointer->cols / 2, currentImageInArrayPointer->rows / 2));
printf("** Zoom Out: Image / 2 \n");
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
cout << "Image Has been zoomed out on" << std::endl;
cout << "Goodbye from Zoom Out!" << std::endl;
}
if (keyPressed == 't')
{
// Machine Training Code -- Update here
currentEvent == 't';
cout << "Hello From Zoom Out!" << std::endl;
imageArray.push_back(*currentImageInArrayPointer); // Add The next node
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
}
// If User hits the '<', show next image in chain (Undo last step)
if (keyPressed == UNDO)
{
// This means the user wants to go back to the last image they were seeing
if (imageArrayIndexer > 0)
{
imageArrayIndexer--;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
destroyWindow("XmasTree");
namedWindow("XmasTree");
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
}
}
// If User hits the '>', show next image in chain (Redo your undo)
if (keyPressed == REDO)
{
// This means the user wants to go back to the last image they were seeing
if ((imageArray.begin() + imageArrayIndexer + 1) != imageArray.end())
{
imageArrayIndexer++;
currentImageInArrayPointer = imageArray.begin() + imageArrayIndexer;
destroyWindow("XmasTree");
namedWindow("XmasTree");
imshow("XmasTree", *currentImageInArrayPointer);
waitKey(25);
}
}
}
} | fb502227c17deb379e7849dde2bbee940ac4d3c0 | [
"Markdown",
"C++"
] | 4 | C++ | natsnyder1/AppleOrchard | d3e418fce65ae98029dadbd02d8d70dd12bc4e8b | 5952d730511bdc7f13b6078545e6c823a1ab7265 |
refs/heads/master | <repo_name>JohnGroot/Grootchinko<file_sep>/Pachinko/Assets/Scripts/Game/ScoreManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public static ScoreManager Instance = null;
private int _score;
public int Score
{
get
{
return _score;
}
}
[SerializeField]private Text _ballCounter;
[SerializeField]private Text _ballCounter2;
[SerializeField]private Text _ballCounter3;
[SerializeField]private Text _ballCounter4;
[SerializeField]private Text _ballCounter5;
[SerializeField]private Text _ballCounter6;
[SerializeField]
[RangeAttribute(50, 500)]
private int STARTING_BALLS = 174;
private int _c_Balls;
private double textCounter = 0.0;
private float textCounterMax = 512.0f;
void Awake ()
{
if(Instance == null)
Instance = this;
_score = 0;
_c_Balls = STARTING_BALLS;
_ballCounter.text = (_c_Balls - _score).ToString();
_ballCounter2.text = (_c_Balls - _score).ToString();
_ballCounter3.text = (_c_Balls + _score).ToString();
_ballCounter4.text = (Mathf.Pow(_c_Balls - _score, Random.Range(0, 4))).ToString();
_ballCounter5.text = (Mathf.Sin(Mathf.Sin(_c_Balls - _score))).ToString();
}
public void HandleBallDrop ()
{
_score++;
int ballCounterScore = _c_Balls - _score;
if(ballCounterScore <= 0)
Application.Quit();
_ballCounter.text = (ballCounterScore).ToString();
_ballCounter2.text = _ballCounter.text;
_ballCounter3.text = (ballCounterScore).ToString();
_ballCounter4.text = ((double)Mathf.Pow(ballCounterScore, Random.Range(1, 5))).ToString();
_ballCounter5.text = (Mathf.Sin(Mathf.Sin(ballCounterScore))).ToString();
}
void OnDestroy()
{
}
void Update ()
{
textCounter = Random.Range(0.0f, textCounterMax);
UpdateText6(textCounter);
}
void UpdateText6(double textCounter)
{
_ballCounter6.text = ((double)Mathf.Pow(Mathf.Sin((float)textCounter), Random.Range(0, 15))).ToString();
}
}
<file_sep>/Pachinko/Assets/Scripts/Game/MachineManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class MachineManager : MonoBehaviour {
private Material _machineMat;
private float _backgroundRed, _backgroundGreen, _backgroundBlue;
private const float COLOR_INCREMENT = 0.20f;
private const float RED_MIN = 0.4f;
private const float COLOR_MIN = 0.3f;
private const float COLOR_MAX = 0.9f;
// Use this for initialization
void Awake ()
{
_machineMat = GetComponent<Renderer>().material;
_backgroundRed = _machineMat.color.r;
_backgroundGreen = _machineMat.color.g;
_backgroundBlue = _machineMat.color.b;
}
// Update is called once per frame
void Update ()
{
UpdateMachineColors();
}
private void UpdateMachineColors()
{
_backgroundRed = Mathf.Clamp(_backgroundRed + (JohnTech.CoinFlip() ? -COLOR_INCREMENT : COLOR_INCREMENT) * Time.deltaTime, RED_MIN, 1.0f);
_backgroundGreen = Mathf.Clamp(_backgroundGreen + (JohnTech.CoinFlip() ? -COLOR_INCREMENT : COLOR_INCREMENT) * Time.deltaTime, COLOR_MIN, COLOR_MAX);
_backgroundBlue = Mathf.Clamp(_backgroundBlue + (JohnTech.CoinFlip() ? -COLOR_INCREMENT : COLOR_INCREMENT) * Time.deltaTime, COLOR_MIN - 0.1f, COLOR_MAX - 0.1f);
_machineMat.color = new Color(_backgroundRed, _backgroundGreen, _backgroundBlue);
}
}
<file_sep>/Pachinko/Assets/Scripts/PegTech/PegTech.cs
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PegTech : MonoBehaviour {
private const float LIGHT_OFF_TIME = 0.25f;
private const float LIGHT_ON_TIME = 0.1f;
private const float COLOR_COUNT = 4;
private Light _childLight;
private List<Color> _currentColors;
// Use this for initialization
void Awake ()
{
_childLight = GetComponentInChildren<Light>();
_currentColors = new List<Color>();
ResetColors();
StartCoroutine("ChangeLight");
}
// Update is called once per frame
void Update ()
{
}
void ResetColors()
{
// Will Retrieve Colors based on background
_currentColors.Clear();
for(int i = 0; i < COLOR_COUNT; i++)
{
_currentColors.Add(new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(1.0f, 2.5f)));
}
/*_currentColors.Add(Color.red);
_currentColors.Add(Color.green);
_currentColors.Add(Color.blue);*/
}
IEnumerator ChangeLight()
{
// Only WHile balls are Shooting
if(_childLight)
{
while(true)
{
_childLight.intensity = 0.0f;
yield return new WaitForSeconds(LIGHT_OFF_TIME);
_childLight.intensity = Random.Range(2.0f, 4.0f);
_childLight.color = _currentColors[ Random.Range( 0, _currentColors.Count) ];
yield return new WaitForSeconds(Random.Range(LIGHT_OFF_TIME, LIGHT_ON_TIME));
}
}
}
}
<file_sep>/Pachinko/Assets/Scripts/PegTech/PegLightTech.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class PegLightTech : MonoBehaviour {
private Light _light;
// Use this for initialization
void Awake ()
{
LookAtCamera();
}
// Update is called once per frame
void Update ()
{
}
private void LookAtCamera()
{
transform.LookAt(Camera.main.transform);
}
}
<file_sep>/Pachinko/Assets/Scripts/UITech/UI_Score.cs
๏ปฟusing UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UI_Score : MonoBehaviour
{
private Text _text;
// Use this for initialization
void Awake ()
{
_text = GetComponent<Text>();
/*_text.text = "0";*/
}
void Update () {}
void OnDestroy()
{
}
void HandleUpdateUI(int score)
{
_text.text = score.ToString();
}
}
<file_sep>/Pachinko/Assets/Scripts/FlipTech/FlipController.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class FlipController : MonoBehaviour {
public enum FlipSide
{
CENTER = 0,
UP,
DOWN,
LEFT,
RIGHT,
DIAG_UP_LEFT,
DIAG_UP_RIGHT,
DIAG_DOWN_LEFT,
DIAG_DOWN_RIGHT
}
private const float FLIP_MIN = 0.1f;
private const float FLIP_MAX = 0.25f;
private const float FLIP_TIME = 0.25f;
private const float FLIP_SPEED = 3.0f;
private const float COLOR_MAX = 1.0f;
private const int COLOR_COUNT = 4;
private Material _flipMat;
private Color[] _flipColors = new Color[COLOR_COUNT];
private FlipSide _side;
public FlipSide Side
{
get
{
return _side;
}
set
{
_side = value;
}
}
// Use this for initialization
void Awake ()
{
_flipMat = GetComponent<Renderer>().material;
StartCoroutine("DelayedFlip");
RandomizeColors();
}
// Update is called once per frame
void Update ()
{
}
IEnumerator DelayedFlip()
{
yield return new WaitForSeconds(Random.Range(FLIP_MIN, FLIP_MAX));
_flipMat.color = _flipColors[Random.Range(0, COLOR_COUNT - 1)];
StartCoroutine("DelayedFlip");
}
public void RandomizeColors()
{
for (int i = 0; i < COLOR_COUNT; i++)
{
_flipColors[i] = RandomColor();
}
}
Color RandomColor()
{
Color tempColor = new Color(Random.Range(0.0f, COLOR_MAX), Random.Range(0.0f, COLOR_MAX), Random.Range(0.0f, COLOR_MAX));
return tempColor;
}
}
<file_sep>/Pachinko/Assets/Scripts/Tools/JohnTech.cs
๏ปฟusing UnityEngine;
using System.Collections;
static public class JohnTech
{
/// <summary>
/// True/False Coin Flip
/// </summary>
public static bool CoinFlip()
{
return UnityEngine.Random.value < 0.5f;
}
/// <summary>
/// Checks If Num Is Within Offset
/// </summary>
public static bool FloatCheckZero(float num, float offset = 0.1f) // Returns true if float is within pos/neg of offset
{
return num < offset && num > -offset;
}
// FROM WADEUTILS lel ;/
#region Increment Position Properties
public static void AddPosX(this Transform t, float newX)
{
t.position = new Vector3(t.position.x + newX, t.position.y, t.position.z);
}
public static void AddPosY(this Transform t, float newY)
{
t.position = new Vector3(t.position.x, t.position.y + newY, t.position.z);
}
public static void AddPosZ(this Transform t, float newZ)
{
t.position = new Vector3(t.position.x, t.position.y, t.position.z + newZ);
}
#endregion
#region Vector Clamp Functions
/// <summary>
/// Clamps x,y of this between min, max values
/// </summary>
public static void Vector2Clamp(this Vector2 vec, float min, float max)
{
vec.x = Mathf.Clamp(vec.x, min, max);
vec.y = Mathf.Clamp(vec.y, min, max);
}
public static void Vector2Clamp(this Vector2 vec, float xMin, float xMax, float yMin, float yMax)
{
vec.x = Mathf.Clamp(vec.x, xMin, xMax);
vec.y = Mathf.Clamp(vec.y, yMin, yMax);
}
/// <summary>
/// Clamps x,y,z of this between min, max values
/// </summary>
public static void Vector3Clamp(this Vector3 vec, float min, float max)
{
vec.x = Mathf.Clamp(vec.x, min, max);
vec.y = Mathf.Clamp(vec.y, min, max);
vec.z = Mathf.Clamp(vec.z, min, max);
}
/// <summary>
/// Clamps x,y,z of this between min, max values
/// zMin/Max defaults to 0
/// x and y min/max must be defined
/// </summary>
public static void Vector3Clamp(this Vector3 vec, float xMin, float xMax, float yMin, float yMax, float zMin = 0.0f, float zMax = 0.0f)
{
vec.x = Mathf.Clamp(vec.x, xMin, xMax);
vec.y = Mathf.Clamp(vec.y, yMin, yMax);
vec.z = Mathf.Clamp(vec.z, zMin, zMax);
}
#endregion
}
<file_sep>/Pachinko/Assets/Scripts/BallTech/BallController.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class BallController : MonoBehaviour {
private const float LAUNCH_FORCE = 260.0f;
private const float MIN_LAUNCH_FORCE = 0.3725f;
private const float BALL_LIFETIME = 15.0f;
private const float BALL_LIFETIME_MIN = .5f;
private const float BALL_MIN_ADJUST = 0.25f/*0.90f*/;
private const float BALL_MAX_ADJUST = 0.65f /*.925f*/;
private Rigidbody _ballRB;
private AudioSource _ballAudio;
private Transform _launchPosition;
public Transform LaunchPosition
{
get
{
return _launchPosition;
}
set
{
_launchPosition = value;
}
}
// Use this for initialization
void Awake ()
{
_ballRB = GetComponent<Rigidbody>();
_ballAudio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
}
public void OnActivate(float launchPower)
{
transform.position = _launchPosition.position; // Sets position to Launcher
_ballRB.velocity = Vector3.zero; // Makes sure ball isn't moving
_ballRB.constraints = RigidbodyConstraints.FreezePositionZ;
// "random" part at end should be input from knob
_ballRB.AddForce((_launchPosition.right/* + _launchPosition.up*/) * LAUNCH_FORCE * (2.25f * launchPower * Random.Range(BALL_MIN_ADJUST, BALL_MAX_ADJUST)));
/*if(launchPower <= MIN_LAUNCH_FORCE)
StartCoroutine("Lifespan", BALL_LIFETIME_MIN);
else*/
StartCoroutine("Lifespan", BALL_LIFETIME);
Debug.Log(launchPower);
}
IEnumerator Lifespan(float lifetime)
{
yield return new WaitForSeconds(lifetime);
gameObject.SetActive(false);
}
void OnTriggerEnter(Collider other)
{
if(other.GetComponent<HoleTech>())
{
_ballRB.constraints = RigidbodyConstraints.None;
return;
}
ScoreManager.Instance.HandleBallDrop();
gameObject.SetActive(false);
}
void OnCollisionEnter(Collision col)
{
_ballAudio.Play();
}
}
<file_sep>/Pachinko/Assets/Scripts/Game/CameraManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class CameraManager : MonoBehaviour {
private Vector3 CAM_MOVE = new Vector3(0.0f, 0.0f, 0.01f);
private const float CAM_STOP_POS = 3f;
Camera _camera;
private Vector3 CAM_START_POS = new Vector3(0.0f, 0.0f, 0.0f);
private Vector3 CAM_ZOOM_START_POS = new Vector3(0.0f, 0.0f, -25.0f);
private const bool SHAKE_ACTIVE = true;
private float _shakeRange = 0.001f;
private float _shakeWait = 1.0f;
private const float SHAKE_INCREMENT = 0.005f;
private const float SHAKE_WAIT_DEC = .025f;
private const float SHAKE_WAIT_MIN = 0.25f;
private const float SHAKE_DURATION = .5f;
[SerializeField]
private bool ZoomRoutine = false;
private float _backgroundRed, _backgroundGreen, _backgroundBlue;
private const float COLOR_INCREMENT = 0.4f;
private const float RED_MIN = 0.4f;
private const float COLOR_MIN = 0.25f;
private const float COLOR_MAX = 1.0f;
void Awake()
{
_camera = GetComponent<Camera>();
if(ZoomRoutine)
transform.position = CAM_ZOOM_START_POS;
_backgroundRed = _camera.backgroundColor.r;
_backgroundGreen = _camera.backgroundColor.g;
_backgroundBlue = _camera.backgroundColor.b;
}
void Start ()
{
if(ZoomRoutine)
StartCoroutine(CameraEnter());
StartCoroutine(DelayedGameZoom());
}
void Update ()
{
ChangeBackgroundColor();
if(Input.GetMouseButtonDown(2))
{
StartCoroutine(ScreenShake());
}
}
void ChangeBackgroundColor()
{
_backgroundRed = Mathf.Clamp(_backgroundRed + (JohnTech.CoinFlip() ? -COLOR_INCREMENT : COLOR_INCREMENT) * Time.deltaTime, RED_MIN, 1.0f);
_backgroundGreen = Mathf.Clamp(_backgroundGreen + (JohnTech.CoinFlip() ? -COLOR_INCREMENT : COLOR_INCREMENT) * Time.deltaTime, COLOR_MIN - 0.1f, COLOR_MAX - 0.1f);
_backgroundBlue = Mathf.Clamp(_backgroundBlue + (JohnTech.CoinFlip() ? -COLOR_INCREMENT : COLOR_INCREMENT) * Time.deltaTime, COLOR_MIN, COLOR_MAX);
_camera.backgroundColor = new Color(_backgroundRed, _backgroundGreen, _backgroundBlue);
}
IEnumerator CameraEnter()
{
StartCoroutine(ScreenShake());
while(transform.position.z <= CAM_STOP_POS)
{
transform.position += CAM_MOVE;
yield return 0;
}
//transform.position = Vector3.zero;
}
IEnumerator DelayedGameZoom()
{
float C_STOP_POS = CAM_START_POS.z + 2.0f;
while(transform.position.z <= C_STOP_POS)
{
transform.position += CAM_MOVE;
yield return new WaitForSeconds(3.0f);
//yield return new WaitUntil(CheckScore());
}
}
bool CheckScore() { return ScoreManager.Instance.Score == ScoreManager.Instance.Score - 1; }
IEnumerator ScreenShake()
{
float xShake, yShake;
float timer = 0.0f;
while(SHAKE_ACTIVE)
{
timer += Time.deltaTime;
xShake = Mathf.Sin(Mathf.Sin(Random.Range(-_shakeRange, _shakeRange)));
yShake = Mathf.Sin(Mathf.Sin(Random.Range(-_shakeRange, _shakeRange)));
transform.position = new Vector3(xShake, yShake, transform.position.z);
yield return 0;
transform.position = new Vector3(0.0f, 0.0f, transform.position.z);
if(timer >= SHAKE_DURATION)
{
_shakeRange += SHAKE_INCREMENT;
if(_shakeWait >= SHAKE_WAIT_MIN)
_shakeWait -= SHAKE_WAIT_DEC;
//yield return new WaitForSeconds(_shakeWait);
yield break;
}
}
}
}
<file_sep>/Pachinko/Assets/Scripts/Game/BallManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(BallLaunchController))]
public class BallManager : MonoBehaviour {
private const int INIT_BALL_COUNT = 20;
private const float LAUNCH_DELAY = 0.2f;
private const string BALL_NAME = "PachinkoBall";
private List<GameObject> BallList;
GameObject tempBall;
private bool _ballLaunched;
public bool BallLaunched
{
get
{
return _ballLaunched;
}
}
private BallLaunchController _launchController;
// Use this for initialization
void Awake ()
{
tempBall = Resources.Load("Prefabs/" + BALL_NAME) as GameObject;
_launchController = GetComponent<BallLaunchController>();
_launchController.Manager = this;
BallList = new List<GameObject>();
for(int i = 0; i < INIT_BALL_COUNT; i++)
{
GameObject ball = Instantiate(tempBall, Vector3.zero, Quaternion.identity) as GameObject;
ball.transform.parent = gameObject.transform;
ball.GetComponent<BallController>().LaunchPosition = gameObject.transform;
ball.SetActive(false);
BallList.Add(ball);
}
ResetVars();
}
// Update is called once per frame
void Update ()
{
/*if(!_ballLaunched)
{
StartCoroutine("LaunchBall");
}*/
}
private void ResetVars()
{
_ballLaunched = false;
}
IEnumerator LaunchBall(float launchPower)
{
/* _ballLaunched = true;
yield return 0;*/
GameObject currBall = BallList.Find(item => item.activeSelf == false);
if(currBall != null)
{
currBall.SetActive(true);
currBall.GetComponent<BallController>().OnActivate(launchPower);
}
else
{
currBall = Instantiate(tempBall, Vector3.zero, Quaternion.identity) as GameObject;
currBall.transform.parent = gameObject.transform;
currBall.GetComponent<BallController>().LaunchPosition = gameObject.transform;
BallList.Add(currBall);
currBall.GetComponent<BallController>().OnActivate(launchPower);
}
// Check if ball left chute ?
yield return new WaitForSeconds(LAUNCH_DELAY);
_ballLaunched = false;
}
public void CallLaunch(float launchPower)
{
_ballLaunched = true;
StartCoroutine("LaunchBall", launchPower);
}
}
<file_sep>/Pachinko/Assets/Scripts/PegTech/MachineLightController.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class MachineLightController : MonoBehaviour {
// Use this for initialization
void Awake ()
{
SetupLights();
}
// Update is called once per frame
void Update ()
{
}
private void SetupLights()
{
var lights = GetComponentsInChildren<Light>();
foreach(Light l in lights)
{
//l.type = LightType.Spot;
l.intensity = 10.0f;
//l.range = 10.0f;
}
}
}
<file_sep>/Pachinko/Assets/Scripts/Game/AudioManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AudioManager : MonoBehaviour {
public static AudioManager Instance;
public enum Sources
{
BACKGROUND_MUSIC,
BACKGROUND_SOUND,
BATTLESHIP_MARCH,
POCKET_OPEN
};
private AudioSource[] _sources;
private const float MUSIC_VOLUME_DEC = 0.25f;
private const float MUSIC_VOLUME_INC = 0.25f;
private const float AMBIENT_VOLUME_DEC = 0.25f;
private const float AMBIENT_VOLUME_INC = 0.25f;
private const float AMBIENT_VOLUME_MIN = 0.15f;
// Use this for initialization
void Awake ()
{
Instance = this;
_sources = GetComponentsInChildren<AudioSource>();
StartCoroutine(BattleshipMarchPlay());
}
// Update is called once per frame
void Update ()
{
}
public void FireVolumeChange()
{
_sources[(int)Sources.BACKGROUND_MUSIC].volume += MUSIC_VOLUME_INC * Time.deltaTime;
if(_sources[(int)Sources.BACKGROUND_SOUND].volume > AMBIENT_VOLUME_MIN)
{
_sources[(int)Sources.BACKGROUND_SOUND].volume -= AMBIENT_VOLUME_DEC * Time.deltaTime;
_sources[(int)Sources.BATTLESHIP_MARCH].volume -= AMBIENT_VOLUME_DEC * Time.deltaTime;
}
}
public void ResetVolumes()
{
_sources[(int)Sources.BACKGROUND_MUSIC].volume = 0.0f;
_sources[(int)Sources.BACKGROUND_SOUND].volume = 1.0f;
}
IEnumerator BattleshipMarchPlay()
{
while(true)
{
yield return new WaitForSeconds(Random.Range(20.0f, 25.0f));
_sources[(int)Sources.BATTLESHIP_MARCH].Stop();
yield return new WaitForSeconds(Random.Range(5.0f, 10.0f));
_sources[(int)Sources.BATTLESHIP_MARCH].Play();
}
}
public void PlayPocketAudio()
{
AudioManager.Instance._sources[(int)Sources.POCKET_OPEN].Play();
}
}
<file_sep>/Pachinko/Assets/Scripts/FernTech/FernTech.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class FernTech : MonoBehaviour {
[SerializeField]
private Vector3 RotationSpeed = new Vector3(0.0f, 10.0f, 0.0f);
private const float RAND_VAL = 3.0f;
// Use this for initialization
void Awake ()
{
}
// Update is called once per frame
void Update ()
{
transform.Rotate(RotationSpeed * Random.Range(1.0f, RAND_VAL) * Time.deltaTime);
}
}
<file_sep>/Pachinko/Assets/Scripts/PillarTech/PillarTech.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class PillarTech : MonoBehaviour {
private Vector3 ROTATE_SPEED = new Vector3(0.0f, 30.0f, 0.0f);
private const float SUBPILLAR_ROTATE_SCALAR = .25f;
private const float SUBPILLAR_SUBSCALAR = 2.0f;
private MeshRenderer[] subPillarArray;
private const float PILLAR_MOVE_MAX = 0.5f;
private const float PILLAR_MOVE_TIME = 3.25f;
[SerializeField] private Material[] _matOptions;
private int MAT_OPTION_COUNT;
// Use this for initialization
void Awake ()
{
subPillarArray = GetComponentsInChildren<MeshRenderer>();
MAT_OPTION_COUNT = _matOptions.Length;
/*foreach(MeshRenderer pillar in subPillarArray)*/
for(int i = 1; i < subPillarArray.Length; i++)
{
subPillarArray[i].material = _matOptions[Random.Range(0, MAT_OPTION_COUNT)];
}
StartCoroutine(PillarMove());
}
// Update is called once per frame
void Update ()
{
RotatePillar();
}
private void RotatePillar()
{
int i = 0;
foreach(MeshRenderer pillar in subPillarArray)
{
pillar.gameObject.transform.Rotate(-ROTATE_SPEED * Time.deltaTime * (.25f * ((i + 2) * SUBPILLAR_SUBSCALAR)) * Random.Range(1.45f, 5.25f));
i++;
}
gameObject.transform.Rotate(ROTATE_SPEED * Time.deltaTime);
}
IEnumerator PillarMove()
{
float moveTimer = 0.0f;
float moveDir = JohnTech.CoinFlip() ? -1.0f : 1.0f;
float startPosX = transform.position.x;
float finalPosX = transform.position.x + PILLAR_MOVE_MAX * moveDir;
while (moveTimer <= PILLAR_MOVE_TIME)
{
transform.position = new Vector3(Mathf.Lerp(startPosX, finalPosX, moveTimer / PILLAR_MOVE_TIME), transform.position.y, transform.position.z);
moveTimer += Time.deltaTime;
yield return 0;
}
yield return 0;
moveTimer = 0.0f;
while (moveTimer <= PILLAR_MOVE_TIME)
{
transform.position = new Vector3(Mathf.Lerp(finalPosX, startPosX, moveTimer / PILLAR_MOVE_TIME), transform.position.y, transform.position.z);
moveTimer += Time.deltaTime;
yield return 0;
}
yield return new WaitForSeconds(Random.Range(0.025f, 0.2f));
StartCoroutine(PillarMove());
}
}
<file_sep>/Pachinko/Assets/Scripts/FlipTech/FlipBoard.cs
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FlipBoard : MonoBehaviour {
private const float SPACING_INC = 10.0f;
private const float SPAWN_TIMER = 5.0f;
private const float CAMERA_INCREASE = 10.0f;
private const float CAMERA_MAX_SIZE = 120.0f;
private GameObject _flipFab;
[SerializeField] private Camera cam;
private Vector3 START_SPAWN;
private Vector3 START_ROT = new Vector3(-90.0f, 180.0f, 0.0f);
private List<GameObject> _outerFlips = new List<GameObject>();
private List<GameObject> _prevOuterFlips = new List<GameObject>();
// Use this for initialization
void Awake ()
{
_flipFab = Resources.Load("Prefabs/Flip") as GameObject;
START_SPAWN = new Vector3(0.0f, 0.0f, cam.transform.position.z - 10f);
}
void Start()
{
GameObject tempFlip = Instantiate(_flipFab, START_SPAWN, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.CENTER;
_outerFlips.Add(tempFlip);
StartCoroutine(SpawnRoutine());
}
// Update is called once per frame
void Update ()
{
}
IEnumerator SpawnRoutine()
{
_prevOuterFlips = new List<GameObject>(_outerFlips);
_outerFlips.Clear();
yield return new WaitForSeconds(SPAWN_TIMER);
foreach(GameObject flip in _prevOuterFlips)
{
FlipController.FlipSide spawnSide = flip.GetComponent<FlipController>().Side;
SpawnFlip(spawnSide, flip.transform.position);
}
if(cam.orthographicSize < CAMERA_MAX_SIZE)
{
yield return new WaitForSeconds(0.25f);
cam.orthographicSize += CAMERA_INCREASE;
StartCoroutine(SpawnRoutine());
}
}
private void SpawnFlip(FlipController.FlipSide spawnSide, Vector3 outerFlipPos)
{
GameObject tempFlip;
Vector3 newPos;
switch(spawnSide)
{
case FlipController.FlipSide.CENTER:
// Diagonal Up-Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_UP_LEFT;
_outerFlips.Add(tempFlip);
// Up
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.UP;
_outerFlips.Add(tempFlip);
// Diagonal Up Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y + SPACING_INC,cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_UP_RIGHT;
_outerFlips.Add(tempFlip);
// Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.RIGHT;
_outerFlips.Add(tempFlip);
// Diagonal Down Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_DOWN_RIGHT;
_outerFlips.Add(tempFlip);
// Down
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DOWN;
_outerFlips.Add(tempFlip);
// Diagonal Down Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_DOWN_LEFT;
_outerFlips.Add(tempFlip);
// Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.LEFT;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.DIAG_DOWN_LEFT:
// Down
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DOWN;
_outerFlips.Add(tempFlip);
// Diagonal Down Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_DOWN_LEFT;
_outerFlips.Add(tempFlip);
// Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.LEFT;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.DIAG_DOWN_RIGHT:
// Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.RIGHT;
_outerFlips.Add(tempFlip);
// Diagonal Down Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_DOWN_RIGHT;
_outerFlips.Add(tempFlip);
// Down
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DOWN;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.DIAG_UP_LEFT:
// Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.LEFT;
_outerFlips.Add(tempFlip);
// Diagonal Up-Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_UP_LEFT;
_outerFlips.Add(tempFlip);
// Up
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.UP;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.DIAG_UP_RIGHT:
// Up
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.UP;
_outerFlips.Add(tempFlip);
// Diagonal Up Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DIAG_UP_RIGHT;
_outerFlips.Add(tempFlip);
// Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.RIGHT;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.DOWN:
// Down
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y - SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.DOWN;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.RIGHT:
// Right
newPos = new Vector3(outerFlipPos.x + SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.RIGHT;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.LEFT:
// Left
newPos = new Vector3(outerFlipPos.x - SPACING_INC, outerFlipPos.y, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.LEFT;
_outerFlips.Add(tempFlip);
break;
case FlipController.FlipSide.UP:
// Up
newPos = new Vector3(outerFlipPos.x, outerFlipPos.y + SPACING_INC, cam.transform.position.z - 10f);
tempFlip = Instantiate(_flipFab, newPos, Quaternion.Euler(START_ROT)) as GameObject;
tempFlip.transform.parent = gameObject.transform;
tempFlip.GetComponent<FlipController>().Side = FlipController.FlipSide.UP;
_outerFlips.Add(tempFlip);
break;
default:
break;
}
}
}
<file_sep>/Pachinko/Assets/Scripts/BallTech/BallLaunchController.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class BallLaunchController : MonoBehaviour
{
private BallManager _ballManager;
public BallManager Manager
{
get
{
return _ballManager;
}
set
{
_ballManager = value;
}
}
private float _launchVal = 0.0f;
private Vector3 _mouseStartPos;
private float _mouseMax = 0.0f;
private const float MAX_IDLE_MOUSEWHEEL_TIME = 1.5f;
private float _mWheelTimer = 0.0f;
private const float LAUNCH_INCREMENT = 1.0f;
private const float SCROLL_LAUNCH_DECREMENT = 0.65f;
private const float LAUNCH_MAX = 0.5f;
private const float SCREEN_PERCENT = 0.25f;
[SerializeField] private RectTransform _launchBar;
private const float UI_LAUNCHBAR_MOD = 5.0f;
void Awake ()
{
_mouseMax = Screen.width * SCREEN_PERCENT;
}
void Update ()
{
//MouseLaunch();
MouseWheelLaunch();
UpdateLaunchBar();
}
void MouseLaunch()
{
if(Input.GetMouseButtonDown(0))
_mouseStartPos = Input.mousePosition;
if(Input.GetMouseButtonUp(0))
_launchVal = 0.0f;
if(Input.GetMouseButton(0))
{
_launchVal = Mathf.Max(Input.mousePosition.x - _mouseStartPos.x, 0.0f);
_launchVal = _launchVal / _mouseMax;
if(!Manager.BallLaunched)
{
AudioManager.Instance.FireVolumeChange();
//Debug.DrawLine(_mouseStartPos, Input.mousePosition, Color.red, 1.0f, false);
Manager.CallLaunch(Mathf.Min(_launchVal, LAUNCH_MAX));
}
}
}
void MouseWheelLaunch()
{
/*if(_mWheelTimer >= MAX_IDLE_MOUSEWHEEL_TIME)
{
_mWheelTimer = 0.0f;
_launchVal = 0.0f;
}*/
if(_launchVal > 0.0f)
_launchVal -= SCROLL_LAUNCH_DECREMENT * Time.deltaTime;
if(Mathf.Abs(Input.GetAxis("MouseScrollWheel")) > 0.0f)
{
_launchVal = Mathf.Min(_launchVal + Mathf.Abs(Input.GetAxis("MouseScrollWheel")) * Time.deltaTime, LAUNCH_MAX);
if(!Manager.BallLaunched)
{
AudioManager.Instance.FireVolumeChange();
//Debug.DrawLine(_mouseStartPos, Input.mousePosition, Color.red, 1.0f, false);
Manager.CallLaunch(_launchVal);
}
}
/*else
{
_mWheelTimer += Time.deltaTime;
}*/
}
// Uses Spacebar for controlling shooting
void SpaceLaunch()
{
if(Input.GetKey(KeyCode.Space) && !Manager.BallLaunched) // If Spacebar is down and Ball hasn't launched
{
_launchVal += LAUNCH_INCREMENT * Time.deltaTime;
AudioManager.Instance.FireVolumeChange();
}
if((_launchVal > 0.0f && !Input.GetKey(KeyCode.Space)) || _launchVal >= LAUNCH_MAX) // if Spacebar has been held down and then released
{
_ballManager.CallLaunch(_launchVal);
}
if(_launchVal > 0.0f && Manager.BallLaunched) // if Spacebar released and ball launched
{
_launchVal = 0.0f;
}
}
void UpdateLaunchBar()
{
_launchBar.localScale = new Vector3(_launchVal * UI_LAUNCHBAR_MOD, 1.0f, 1.0f);
}
}
<file_sep>/Pachinko/Assets/Scripts/PegTech/PegManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PegManager : MonoBehaviour {
private const int PEG_COUNT = 100;
private const float RESET_TIME = 1.0f;
private float timer = 0.0f;
private GameObject PegObj;
private Vector3 pegRotation = new Vector3(90.0f, 0.0f, 0.0f);
private List<GameObject> _pegList = new List<GameObject>();
// Use this for initialization
void Awake ()
{
PegObj = Resources.Load("Prefabs/SmallPegNoLight") as GameObject;
//InitializePegs();
}
// Update is called once per frame
void Update ()
{
//if (Input.GetKeyDown(KeyCode.R))
/*timer += Time.deltaTime;
if(timer >= RESET_TIME)
{
ResetPegs();
timer = 0.0f;
}*/
}
private void ResetPegs()
{
Vector3 spawnPos;
foreach(GameObject peg in _pegList)
{
spawnPos = new Vector3(Random.Range(-2.30f, 2.45f), Random.Range(7.0f, 11.45f), 11.36f);
peg.transform.localPosition = spawnPos;
}
}
private void InitializePegs()
{
GameObject tempPeg;
for(int i = 0; i < PEG_COUNT; i++)
{
tempPeg = Instantiate(PegObj, Vector3.zero, Quaternion.identity) as GameObject;
tempPeg.transform.parent = gameObject.transform;
tempPeg.transform.Rotate(pegRotation);
_pegList.Add(tempPeg);
}
//SpawnOutlineLights();
ResetPegs();
}
private void SpawnOutlineLights()
{
float xPos = -5.00f, yPos = 5.00f, offset = 0.25f;
int PEG_COUNT = 100;
GameObject tempPeg;
Vector3 newPos = Vector3.zero;
newPos.z = 10.0f;
for(int i = 0; i < PEG_COUNT; i++)
{
if (yPos >= 13.0f && xPos != 5.0f) // Determines if xPos should be moving right based on if at top of Machine
xPos += offset;
if(xPos >= 2.5f) // Determines if yPos should go down on right of machine
yPos -= offset;
else if(yPos <= 15.0f && xPos <= -2.5f) // Determines if yPos should move up
yPos += offset;
newPos.x = xPos;
newPos.y = yPos;
Debug.Log(newPos);
tempPeg = Instantiate(PegObj, Vector3.zero, Quaternion.identity) as GameObject;
tempPeg.transform.parent = gameObject.transform;
tempPeg.transform.localPosition = newPos;
tempPeg.transform.Rotate(pegRotation);
}
}
}
<file_sep>/Pachinko/Assets/Scripts/FlipTech/FlipManager.cs
๏ปฟusing UnityEngine;
using System.Collections;
public class FlipManager : MonoBehaviour {
private int FLIP_COUNT = 440;
private const float FLIP_X_CONSTRAINT = -9.5f;
private const float FLIP_Y_CONSTRAINT = 6.0f;
private const float FLIP_OFFSET = 1.0f;
private const float COLOR_TIMER = 20.0f;
private Vector3 FLIP_2_ROTATION = new Vector3(0.0f, 90.0f, 0.0f);
private GameObject FlipObj;
private FlipController[] _flips;
public enum FlipNum
{
FLIP_ONE = 0,
FLIP_TWO
}
public FlipNum Num;
// Use this for initialization
void Awake ()
{
Cursor.visible = false;
FlipObj = Resources.Load("Prefabs/Flip") as GameObject;
InitializeFlips();
StartCoroutine("SwitchFlipColors");
if(Num == FlipNum.FLIP_TWO)
transform.rotation = Quaternion.Euler(FLIP_2_ROTATION);
}
// Update is called once per frame
void Update ()
{
}
void InitializeFlips()
{
GameObject tempFlip;
Vector3 flipPos = new Vector3(FLIP_X_CONSTRAINT, FLIP_Y_CONSTRAINT, 14.0f);
for (int i = 0; i < FLIP_COUNT; i++)
{
tempFlip = Instantiate(FlipObj, flipPos, Quaternion.Euler(new Vector3(90.0f, 0.0f, 0.0f))) as GameObject;
flipPos.x += FLIP_OFFSET;
if(flipPos.x > 9.5f)
{
flipPos.y -= FLIP_OFFSET;
flipPos.x = FLIP_X_CONSTRAINT;
}
tempFlip.transform.parent = gameObject.transform;
}
_flips = GetComponentsInChildren<FlipController>();
}
IEnumerator SwitchFlipColors()
{
foreach(FlipController flip in _flips)
{
flip.RandomizeColors();
yield return 0;
}
yield return new WaitForSeconds(COLOR_TIMER);
StartCoroutine("SwitchFlipColors");
}
}
| 0600a6b8cc3028846184bdfd22086fdaa04380be | [
"C#"
] | 18 | C# | JohnGroot/Grootchinko | 74665ef96c99912937a625437b9c80f8e70c2006 | a2141c90ddef95726c7b05b0f70638eb7755d0e2 |
refs/heads/master | <repo_name>wimpykatana/reservation<file_sep>/src/reducers/index.js
import { combineReducers } from "redux"
import brand from "./brandReducer"
import store from "./storeReducer"
import user from "./userReducer"
export default combineReducers({
brand,
store,
user
})
<file_sep>/src/actions/storeActions.js
import axios from "axios";
import config from "../config/config.json"
export function fetchDataStore() {
return function (dispatch) {
dispatch({type: "FETCH_DATA_STORE"});
axios.get(config.apiURL + "/stores/" + BRAND_CODE +"?app=brand-reservations")
.then((response) => {
dispatch({type: "FETCH_DATA_STORE_FULFILLED", payload: response.data.stores})
})
.catch((err) => {
dispatch({type: "FETCH_DATA_REJECTED", payload: err})
})
}
}
export function setStore(storeId) {
return{
type: "SET_STORE",
payload: storeId,
}
}
/*************** SOME NOTE
fetchDataStore()
function to get stores data from API and put all get data to "redux store"
setStore(val)
function to set an active store chosen by user and put the store ID at "Redux Store"
*/<file_sep>/src/component/__smallComponent/dateTime/index.js
import React from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import _ from 'lodash';
import { connect } from "react-redux";
import { setReservationDate, setReservationTime, getReservationDateTime } from "../../../actions/userActions"
import './dateTime.scss';
let allStores;
let selectStoreID;
let activeStore;
let userSelectDay;
let userSelectTime;
let userSelectDate;
let activeStoreDineInHours;
let choseTime;
let storeStatus;
let openday;
let storeStatusTime;
let chooseStore;
let openTimeList;
let notDateAfter;
let notDateAfterNotification;
let timeToClose;
let timeToCloseNotification;
@connect((store) => {
return {
store: store.store.store,
};
})
class DateTime extends React.Component{
constructor (props) {
super(props);
this.state = {
startDate: moment(),
startTime: moment().format("HH:mm"),
inputDateValue: "Please choose Date"
};
this.handleChangeDate = this.handleChangeDate.bind(this);
this.handleTimeChoose = this.handleTimeChoose.bind(this);
this.dateClick = this.dateClick.bind(this);
}
componentWillMount(){
this.props.dispatch(getReservationDateTime());
}
dateClick(){
this.setState({
// startDate: date,
inputDateValue: ""
});
}
handleChangeDate(date) {
this.setState({
startDate: date,
inputDateValue: date
});
let dateNow = Date.now();
// console.log(moment(dateNow).format("DD-MM-YYYY"));
userSelectDay = date.format("dddd");
userSelectDate = new Date(date);
if(moment(userSelectDate).format("x") >= (moment(dateNow).format("x"))){
notDateAfter = true;
notDateAfterNotification = "";
}else{
notDateAfter = false;
notDateAfterNotification = <p className='has-error'>Please choose a date after today</p>;
}
openday = activeStoreDineInHours["dineInHours"].find(data => (data.dayOfWeek === _.toUpper(userSelectDay)));
storeStatus = openday ? null : <p className='has-error'>Store is CLOSE please choose other date</p>;
choseTime = openday ? null : "disabled";
if(!storeStatus){
let storeOpenHour = openday.startTime.split(":").slice(0,1).toString();
let storeOpenMinute = openday.startTime.split(":").slice(1,2).toString();
let storeCloseHour = openday.endTime.split(":").slice(0,1).toString();
let storeCloseMinute = openday.endTime.split(":").slice(1,2).toString();
let storeAvalibleTime = [];
for(let x=storeOpenHour; x <= storeCloseHour; x++){
if(x === storeOpenHour && storeOpenMinute === "00"){
storeAvalibleTime.push(""+ x +":00");
storeAvalibleTime.push(""+ x +":30");
}else if(x === storeOpenHour && storeOpenMinute === "30"){
storeAvalibleTime.push(""+ x +":30");
}
if(x > storeOpenHour && x < storeCloseHour) {
storeAvalibleTime.push("" + x + ":00");
storeAvalibleTime.push("" + x + ":30");
}
if(x == storeCloseHour && storeCloseMinute === "00"){
storeAvalibleTime.push("" + x + ":00");
}else if(x == storeCloseHour && storeCloseMinute === "30"){
storeAvalibleTime.push("" + x + ":00");
storeAvalibleTime.push("" + x + ":30");
}
}
openTimeList = storeAvalibleTime.map(avail => ( <option key={avail} value={avail}>{avail}</option>));
}
if(openday){
this.props.dispatch(setReservationDate(moment(userSelectDate).format("DD-MM-YYYY")))
}
}
handleTimeChoose(event){
this.setState({
startTime: event.target.value
});
userSelectTime = moment(event.target.value, "HH:mm");
let dateNow = Date.now();
if(moment(dateNow).format("DD-MM-YYYY") === moment(userSelectDate).format("DD-MM-YYYY") ){
let tanggalSekarang = moment(dateNow).format("DD-MM-YYYY").toString();
let jampilihanUser = event.target.value.toString();
let aha = ""+tanggalSekarang+" "+jampilihanUser;
let userSelectTodayDateTime = moment(aha, "DD-MM-YYYY HH:mm");
if(moment(userSelectTodayDateTime).format("x") > moment(dateNow).add(1,"h").format("x") ){
this.props.dispatch(setReservationTime(moment(userSelectTime).format("HH:mm")));
timeToClose= false;
timeToCloseNotification = "";
}else{
timeToClose = true;
timeToCloseNotification = <p className='has-error'>Please choose other time</p>;
}
}else{
timeToClose = null;
timeToCloseNotification = "";
this.props.dispatch(setReservationTime(moment(userSelectTime).format("HH:mm")));
}
}
init(){
allStores = this.props.store;
selectStoreID = _.toNumber(this.props.selectStoreID);
activeStore = allStores.filter((eachStore) => eachStore.id === selectStoreID);
activeStoreDineInHours = _.pick(activeStore[0], "dineInHours");
chooseStore = selectStoreID ? "" : "disabled";
choseTime = openday ? "" : "disabled";
choseTime = notDateAfter ? "" : "disabled";
}
render(){
this.init();
return(
<div className="col-12 nopaddings">
<div className="col-6 nopaddings float-left" style={{position: "static"}}>
<DatePicker
onFocus={this.dateClick}
dateFormat="DD-MM-YYYY"
selected={this.state.startDate}
onChange={this.handleChangeDate}
disabled={chooseStore}
value= {this.state.inputDateValue}
/>
</div>
<div className="col-6 nopaddings float-left" >
<select onChange={this.handleTimeChoose} disabled={choseTime} >
<option value="null">Please choose Time</option>
{openTimeList}
</select>
</div>
<div className="clearfix" />
{timeToCloseNotification}
{storeStatus}
{storeStatusTime}
{notDateAfterNotification}
</div>
)
}
}
export default DateTime<file_sep>/src/component/_pageLayout/reservation/index.js
import React from 'react';
import _ from 'lodash';
import moment from 'moment';
import Logo from "../../__smallComponent/logo";
import Title from '../../__smallComponent/title/title';
import Selectstore from "../../__smallComponent/selectStore";
import DateTime from "../../__smallComponent/dateTime";
import { withRouter, Redirect } from 'react-router-dom';
import "./reservation.scss";
import 'react-datepicker/dist/react-datepicker.css';
import { connect } from "react-redux";
import { fetchDataBrand } from "../../../actions/brandActions";
import { fetchDataStore } from "../../../actions/storeActions";
import { getReservationDateTime, makeReservation, getReservation, makeReservationGET } from "../../../actions/userActions";
let brandApp;
let brandAppProperties;
let brandLogo;
let brandBackgroundColor;
let primaryColor;
let store;
let occasionLists;
let occasionListsSelectValue;
let dateTimeHolder;
let paxHolder;
let minPax;
let maxPax;
let btnStatus = "disabled";
@connect((store) => {
return {
brand: store.brand.brand,
store: store.store.store,
selectStore: store.store.selectStore,
userSelectDateTime: store.user.userSelect,
userReservation: store.user.reservation
};
})
class Reservation extends React.Component{
constructor (props) {
super(props);
this.state = {
fnameValue: null,
lnameValue: null,
emailValue: null,
paxValue: null,
phonenumberValue: null,
specialreqValue: null,
occasionValue: null,
validateFName: null,
validateLName: null,
validateEmail: null,
validatePhone: null,
validatePax: null,
notification: null
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
this.handleLastNameChange = this.handleLastNameChange.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePax = this.handlePax.bind(this);
this.handlePhonenumber = this.handlePhonenumber.bind(this);
this.specialReq = this.specialReq.bind(this);
this.handleOccasion = this.handleOccasion.bind(this);
}
componentWillMount() {
this.props.dispatch(fetchDataBrand());
this.props.dispatch(fetchDataStore());
this.props.dispatch(getReservationDateTime());
this.props.dispatch(getReservation());
// this.props.dispatch(makeReservation());
}
handleFirstNameChange(event){
if(!(/^[a-zA-Z]+$/g).test(event.target.value)){
this.setState({
validateFName: <p className="has-error">Please input alphabet only without number and punctuation mark</p>
});
//input contain not letter character
}else{
this.setState({
fnameValue: event.target.value,
validateFName: null
});
//input contain only letter character
}
}
handleLastNameChange(event){
if(!(/^[a-zA-Z]+$/g).test(event.target.value)){
this.setState({
validateLName: <p className="has-error">Please input alphabet only without number and punctuation mark</p>
});
//input contain not letter character
}else{
this.setState({
lnameValue: event.target.value,
validateLName: null
});
//input contain only letter character
}
}
handleEmailChange(event){
if((/\S+@\S+\.\S+/).test(event.target.value)){
//email valid
this.setState({
emailValue: event.target.value,
validateEmail: null
});
} else {
this.setState({
validateEmail: <p className="has-error">Please input valid email address</p>
});
}
}
handlePax(event){
let pax = event.target.value;
if(pax <= maxPax && pax >= minPax){
this.setState({ paxValue: pax, validatePax: null });
}else{
this.setState({
validatePax: <p className="has-error">Please choose between {minPax} and {maxPax} </p>
});
}
}
handlePhonenumber(event){
if((/^[0-9]+$/g).test(event.target.value)){
this.setState({
phonenumberValue: event.target.value,
validatePhone: null
});
}else{
this.setState({
validatePhone: <p className="has-error">Please input numeric value only</p>
});
}
}
handleOccasion(event){
this.setState({
occasionValue: event.target.value
// submitBtn: ''
});
}
specialReq(event){
this.setState({
specialreqValue: event.target.value
});
}
handleSubmit(e) {
e.preventDefault();
let datetime = moment(''+this.props.userSelectDateTime.date+' '+this.props.userSelectDateTime.time, "DD-MM-YYYY HH:mm" ).format("x");
let obj = JSON.stringify({
store: this.props.selectStore.id,
fromTime: datetime,
pax: this.state.paxValue,
customer: {
firstName: this.state.fnameValue,
lastName: this.state.lnameValue,
phone: "+65" + this.state.phonenumberValue,
email: this.state.emailValue
},
specialRequest: this.state.specialreqValue,
occasion: this.state.occasionValue
});
let config = {
headers: {
'Content-Type': 'application/json;charset=UTF8'
}
};
if(!this.props.selectStore.id){
this.setState({
notification: <p className="has-error">Reservation Store must be filled</p>
});
}else if(!moment(this.props.userSelectDateTime.date, "DD-MM-YYYY").isValid()){
this.setState({
notification: <p className="has-error">Reservation Date must be filled</p>
});
}else if(!moment(this.props.userSelectDateTime.time, "HH:mm").isValid()){
this.setState({
notification: <p className="has-error">Reservation Time must be filled</p>
});
}else if(!this.state.paxValue){
this.setState({
notification: <p className="has-error">Reservation Pax must be filled</p>
});
}else if(!this.state.fnameValue){
this.setState({
notification: <p className="has-error">Reservation First Name must be filled</p>
});
}else if(!this.state.lnameValue){
this.setState({
notification: <p className="has-error">Reservation Last Name must be filled</p>
});
}else if(!this.state.emailValue){
this.setState({
notification: <p className="has-error">Reservation Email must be filled</p>
});
}else if(!this.state.phonenumberValue){
this.setState({
notification: <p className="has-error">Reservation Phone Number must be filled</p>
});
}else if(!this.state.occasionValue){
this.setState({
notification: <p className="has-error">Reservation Occasion must be filled</p>
});
}
else{
// console.log("looks ok");
// this.props.dispatch(makeReservation(obj,config));
this.props.dispatch(makeReservationGET(obj));
}
}
init() {
brandApp = this.props.brand.app;
store = this.props.store;
brandAppProperties = _.pick(brandApp, "properties");
brandLogo = _.pick(this.props.brand, "defaultImageId");
brandBackgroundColor = _.pick(brandAppProperties, "backgroundColor");
primaryColor = _.pick(brandAppProperties, "primaryColor");
let choosenStoreID = this.props.selectStore.id;
let choosenStoreValue = store.find(store => (store.id == choosenStoreID));
if(choosenStoreValue){
occasionLists = choosenStoreValue.reservationSetting.occasions;
minPax = choosenStoreValue.reservationSetting.minPax;
maxPax = choosenStoreValue.reservationSetting.maxPax;
btnStatus = null;
}
if(occasionLists){
occasionListsSelectValue = <select onChange={this.handleOccasion}>
<option value="null">Choose Occasion</option>
{
occasionLists.map(occasion => (
<option key={occasion} value={occasion}>{occasion}</option>
))
}
</select>;
}else{
occasionListsSelectValue = <select>
<option value="null">Choose Occasion</option>
</select>;
}
if(choosenStoreID){
dateTimeHolder = <DateTime selectStoreID={this.props.selectStore.id} />;
paxHolder = <div className="number-of-pax">
<input type="number" placeholder="Number of Pax" onChange={this.handlePax}/>
{this.state.validatePax}
</div>;
}else{
dateTimeHolder = null;
paxHolder = null;
}
}
render(){
this.init();
let successInput = _.map(this.props.userReservation, 'success').shift();
if(successInput){
return (
<Redirect to={{
pathname: '/confirmation'
}}/>
)
}
return(
<div className="content-holder" style={{backgroundColor: brandBackgroundColor}}>
<div className="content content-reservation">
<h3 className="brand-name">{this.props.brand.name}</h3>
<Logo filename={brandLogo["defaultImageId"]}/>
<div className="animated fadeInRight reservation-holder">
<div className="reservation-form-holder">
<Title name="Reservation Detail" color={primaryColor}/>
<form onSubmit={this.handleSubmit}>
<Selectstore value={this.props.store}/>
{dateTimeHolder}
{paxHolder}
<input type="text" placeholder="First Name" onChange={this.handleFirstNameChange} />
{this.state.validateFName}
<input type="text" placeholder="Last Name" onChange={this.handleLastNameChange} />
{this.state.validateLName}
<input type="email" placeholder="Email" onBlur={this.handleEmailChange}/>
{this.state.validateEmail}
<div className="phone-number container">
<div className="row">
<div className="col-2 d-flex align-items-center nolrpadding phone-area-code-holder"><p className="phone-area-code text-center">+65</p></div>
<div className="col-10 nolrpadding">
<input type="number" placeholder="Mobile Number" onChange={this.handlePhonenumber} />
</div>
</div>
</div>
<div className="special-remarks">
<input type="text" placeholder="Special Remarks e.g. Al Fresco" onChange={this.specialReq} />
</div>
{occasionListsSelectValue}
<div className="notification-holder">
{this.state.notification}
</div>
<input type="submit" value="submit" className="btn btn-eunoia center-block" disabled={btnStatus}/>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default Reservation<file_sep>/src/component/_pageLayout/login/index.js
import React from 'react'
import Title from "../../__smallComponent/title/title"
import "./login.scss"
import Logo from "../../__smallComponent/logo/index";
import { connect } from "react-redux"
import { fetchDataBrand } from "../../../actions/brandActions";
@connect((store) => {
return {
brand: store.brand.brand
};
})
class Login extends React.Component{
componentWillMount() {
this.props.dispatch(fetchDataBrand())
}
render(){
const brandApp = this.props.brand.app
const brandAppProperties = _.pick(brandApp, "properties")
const brandBackgroundColor = _.map(brandAppProperties,"backgroundColor")
return(
<div className="content-holder" style={{backgroundColor: brandBackgroundColor}}>
<div className="content">
<Logo/>
<div className="animated fadeInRight login-holder">
<Title name="Please Login"/>
<div className="login-form-holder">
<input type="text" placeholder="Email"/>
<input type="password" placeholder="<PASSWORD>"/>
<p><a href="#">Forget Password?</a></p>
<a href="#" className="btn btn-eunoia">Login</a>
</div>
</div>
</div>
</div>
)
}
}
export default Login<file_sep>/src/component/__smallComponent/storeComponent/index.js
import React from 'react';
import { connect } from 'react-redux';
import "./storeComponent.scss";
import { setStore } from "../../../actions/storeActions";
import { Redirect } from 'react-router-dom';
let storeValues;
let storeList;
@connect((store) => {
return {
store: store.store.store
};
})
class StoreComponent extends React.Component{
constructor(props){
super(props);
this.state = {
chooseStore: false,
};
this.init = this.init.bind(this);
}
handleClick(e){
this.props.dispatch(setStore(e));
this.setState({
chooseStore: true
});
}
init(){
storeValues = this.props.value;
if(storeValues){
storeList = storeValues.filter((storeValue) => storeValue.reservation).sort()
.map( storeValue => (
<div className={`col-lg-6 col-md-6 col-sm-12 animated fadeInRight store-list ${storeValue.name.toLowerCase().replace(" ", "-")}`}
data-store={storeValue.id}
key={storeValue.id}
onClick={() => this.handleClick(storeValue.id)}>
<div className="store-info-holder">
<h3>{storeValue.name}</h3>
<p>{storeValue.address.string}</p>
</div>
</div>
));
}else{
storeList = null;
}
}
render(){
this.init();
if(this.state.chooseStore){
return(
<Redirect to={{
pathname: '/action',
state: { from: '/' }
}} />
)
}
return(
<div className="row store-list-holder">
{storeList}
</div>
)
}
}
export default StoreComponent;<file_sep>/src/component/__smallComponent/logo/index.js
import React from 'react';
import "./logo.scss";
import config from "../../../config/config.json";
let logoImage = null;
class Logo extends React.Component{
init(){
if(this.props.filename){
logoImage = <img className="align-items-center" src={ config.imageLogoURL + this.props.filename}/>;
}else{
logoImage = <img className="align-items-center" src="" />;
}
}
render() {
this.init();
return (
<div className="Logo-holder text-center">
{logoImage}
</div>
);
}
}
export default Logo
<file_sep>/README.md
To run this app use npm (Node Packet Manager)
* Development
1. type "npm install" at terminal
2. after finish install run "npm start" at terminal
3. open http://localhost:3005/ in your browser
or
* Production
1. type "npm install" at terminal
1. after finish instal run "npm run build" at terminal to deploy file and deployed file stored at /dist
2. open index.html at /dist folder
<file_sep>/src/actions/brandActions.js
import axios from "axios";
import config from "../config/config.json"
export function fetchDataBrand() {
return function (dispatch) {
dispatch({type: "FETCH_DATA_BRAND"});
axios.get(config.apiURL + "/stores/"+ BRAND_CODE +"?app=brand-reservations")
.then((response) => {
dispatch({type: "FETCH_DATA_BRAND_FULFILLED", payload: response.data.brand})
})
.catch((err) => {
dispatch({type: "FETCH_DATA_REJECTED", payload: err})
})
};
}
/************* SOME NOTE
fetchDataBrand()
function to get a brand data from api and put all get data to "redux store"
*/<file_sep>/src/component/__smallComponent/selectStore/index.js
import React from "react";
import { connect } from "react-redux";
import { setStore } from "../../../actions/storeActions";
import "./selectStore.scss";
let stores = null;
let storeValues;
@connect((store) => {
return {
brand: store.brand.brand,
store: store.store
};
})
class Selectstore extends React.Component{
constructor(props){
super(props);
this.state = {
value: null
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event){
this.setState({ value: event.target.value });
this.props.dispatch(setStore(event.target.value));
}
init(){
storeValues = this.props.value;
if(storeValues){
// stores = <select onChange={event => this.setState({ value: event.target.value })}>
stores = <select ref='input' onChange={this.handleChange}>
<option value="null">Please choose store</option>
{
storeValues.filter((storeValue) => storeValue.reservation).sort()
.map( storeValue =>(
<option value={storeValue.id} key={storeValue.name}>{storeValue.name}</option>
))
}
</select>
}else{
stores = null;
}
}
render(){
this.init();
return(
<div className="store">
{stores}
</div>
)
}
}
export default Selectstore;<file_sep>/src/component/__smallComponent/newDateTime/index.js
import React from 'react';
import moment from 'moment';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker-cssmodules.min.css';
import './dateTime.scss';
import { connect } from "react-redux";
import { setReservationDate } from "../../../actions/userActions";
let dateVal;
let timeVal;
let storeListOpenHours;
let storeStartTime;
let storeEndTime;
let getAvailableStoreHours;
let activeStore;
let openDay;
let isOpen;
let storeStatus = null;
@connect((store) => {
return {
stores: store.store.store,
selectStore : store.store.selectStore.id
};
})
class Datetimeselect extends React.Component{
constructor(props){
super(props);
this.state ={
showDatePopup: false,
showTimePopup:false,
noScroll: false,
startDate: moment(),
}
this.init = this.init.bind(this);
this.dateHandleClick = this.dateHandleClick.bind(this);
this.timeHandleClick = this.timeHandleClick.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.closeTimePopup = this.closeTimePopup.bind(this);
dateVal = moment().format("DD-MM-YYYY");
}
componentWillMount(){
// this.props.dispatch(getReservationDateTime());
storeStatus = null;
document.getElementById("root").className = this.state.noScroll ? 'noscroll' : '';
timeVal = moment().add(2, 'hours').format("HH:mm");
}
componentDidUpdate() {
document.getElementById("root").className = this.state.noScroll ? 'noscroll' : '';
document.getElementById("value-date-holder-content").className = this.state.showDatePopup ? 'container value-date-holder nopaddings active' : 'container value-date-holder nopaddings ';
document.getElementById("value-time-holder-content").className = this.state.showTimePopup ? 'container value-time-holder nopaddings active' : 'container value-time-holder nopaddings ';
}
handleDateChange(date){
this.setState({
startDate: date,
});
let dateNow = moment().format('x');
let userSelectDate = moment(date).format("x");
let useSelectDay = moment(date).format("dddd");
isOpen = openDay.find(data => data.dayOfWeek === useSelectDay.toUpperCase());
document.getElementById("date-holder-scroll").scrollTo(0, 0);
console.log(isOpen);
if(isOpen){
//get time value
storeStartTime = isOpen.startTime;
storeEndTime = isOpen.endTime;
let storeOpenHour = isOpen.startTime.split(":").slice(0,1).toString();
let storeCloseHour = isOpen.endTime.split(":").slice(0,1).toString();
let storeAvalibleTime = [];
for(let x=storeOpenHour; x <= storeCloseHour; x++){
storeAvalibleTime.push(x);
}
getAvailableStoreHours = storeAvalibleTime.map(avail => ( <div key={avail} value={avail}>{avail}</div>));
storeStatus = null;
if(userSelectDate > dateNow){
//user can make reservation
dateVal = moment(date).format("DD-MM-YYYY");
this.setState({
showDatePopup: false,
noScroll: false
});
this.props.dispatch(setReservationDate(moment(date).format("DD-MM-YYYY")));
}else{
storeStatus = <p className='has-error'>Please choose a date after today</p>;
this.setState({
showDatePopup: true,
noScroll: true
});
}
}else{
storeStatus = <p className='has-error'>Store is CLOSE please choose other date</p>;
}
}
dateHandleClick(){
document.getElementById("root").scrollTo(0, 0);
this.setState({
showDatePopup: true,
showTimePopup: false,
noScroll: true
});
}
timeHandleClick(){
console.log("time click");
document.getElementById("root").scrollTo(0, 0);
this.setState({
showTimePopup: true,
showDatePopup: false,
noScroll: true
});
}
closeTimePopup(){
console.log("close this");
this.setState({
showTimePopup: false,
noScroll: false
});
}
init(){
activeStore = this.props.stores.filter((store) => (store.id === this.props.selectStore));
openDay = activeStore[0].dineInHours;
if(!isOpen){
storeListOpenHours = <p className='has-error text-center' onClick={this.closeTimePopup}>
Please choose a date first
</p>;
}else{
storeListOpenHours = getAvailableStoreHours;
}
}
render(){
this.init();
return(
<div className="form-holder-3 col-xs-12">
<div className="container date-time-holder">
<div className="col-xs-6 norpadding date-holder text-center" onClick={this.dateHandleClick}>
<p>DATE</p>
<p className="value-date">{dateVal}</p>
</div>
<div className="col-xs-6 nolpadding time-holder text-center" onClick={this.timeHandleClick}>
<p>TIME</p>
<p className="value-time">{timeVal}</p>
</div>
</div>
<div id="value-date-holder-content" className="container value-date-holder nopaddings">
<div id="date-holder-scroll" className="col-xs-12">
<div className="row text-center">
{storeStatus}
</div>
<DatePicker
inline
selected={this.state.startDate}
onChange={this.handleDateChange}
dateFormat="DD-MM-YYYY"
/>
</div>
</div>
<div id="value-time-holder-content" className="container value-time-holder nopaddings">
<div className="col-xs-12">
<div className="row text-center">
{storeStatus}
</div>
/*****
* for time popup is not finish yet get distraction
* right now just drop a value from api nothing cant do
*/
<div className="choose-time-content">
<div className="row">{`Store is available from ${storeStartTime} and will close at ${storeEndTime}`}</div>
{storeListOpenHours}
</div>
</div>
</div>
</div>
)
}
}
export default Datetimeselect;<file_sep>/src/component/_pageLayout/landing/index.js
import React from 'react';
import './landing.scss';
import { connect } from "react-redux";
import { fetchDataStore } from "../../../actions/storeActions";
import StoreComponent from '../../__smallComponent/storeComponent';
@connect((store) => {
return {
brand: store.brand.brand,
store: store.store.store,
selectStore: store.store.selectStore,
};
})
class Landing extends React.Component{
constructor(props){
super(props);
this.state = {
brand: null,
};
this.init = this.init.bind(this);
}
componentWillMount() {
this.props.dispatch(fetchDataStore());
}
init(){
}
render(){
this.init();
return(
<div className="welcome-holder">
<div className="container">
<StoreComponent value={this.props.store} />
</div>
</div>
)
}
}
export default Landing<file_sep>/src/component/main/index.js
import React from "react";
import { Switch, Route, browserHistory, IndexRoute } from 'react-router-dom';
import Login from "../_pageLayout/login";
// import Register from "../_pageLayout/register";
import Landing from '../_pageLayout/landing';
import Actionpage from '../_pageLayout/action';
import Makereservation from '../_pageLayout/makeReservation';
// import Reservation from "../_pageLayout/reservation";
// import Confirmation from "../_pageLayout/confirmation";
import Header from "../header";
class Main extends React.Component {
render(){
return(
<main className="main-holder">
{/*<Header/>*/}
<Switch>
<Route history={browserHistory} exact path="/" component={Landing}/>
<Route history={browserHistory} exact path="/action" component={Actionpage}/>
<Route history={browserHistory} exact path="/makereservation" component={Makereservation}/>
{/*<Route history={browserHistory} path="/reservation" component={Reservation}/>*/}
{/*<Route history={browserHistory} path="/confirmation" component={Confirmation}/>*/}
{/*<Route component={Reservation} />*/}
</Switch>
</main>
)
}
}
export default Main | 4f9db00151b87fe96703897c2c61aa1fda573d21 | [
"JavaScript",
"Markdown"
] | 13 | JavaScript | wimpykatana/reservation | 2b9a7d8553728c208d2cdab853f3649c6932804d | 79ff573fab2c62e3db19bb6ea0604bd965ba72d1 |
refs/heads/master | <repo_name>jsrois/cpp-rgx<file_sep>/README.md
### Cool (Ruby) regular expressions for parsing C++ code
<file_sep>/parser.rb
require './cpp_regexes.rb'
class Node
attr_reader :children, :name, :prefix, :type
def initialize (type, name, prefix = '')
@name = name
@prefix = prefix
@children = Array.new
@type = type
end
def complete_name
@prefix+@name
end
def add_child node
print '.'
$stdout.flush
@children << node
end
# idea: return list of candidates ["foo::bar", "cv::bar"] when an element "bar" is searched
def find element_name
if @name === name then
return true
else
retval = false;
@children.each do |child|
retval |= child.find element_name
return true if retval
end
end
end
def display(indent = 0)
puts "\s"*indent+"<#{@type} name=\"#{@name}\">"
@children.each { |c| c.display(indent+1) }
puts "\s"*indent+"</#{@type}>"
end
end
class NamespaceNode < Node
def initialize(name, contents, prefix)
super 'namespace',name,prefix
contents.gsub!(NAMESPACE_DECLARATION) do
add_child NamespaceNode.new($~[:name],$~[:scope],self.complete_name)
''
end
contents.gsub!(CLASS_DECLARATION) do
add_child ClassNode.new($~[:name],$~[:scope],self.complete_name)
''
end
contents.gsub!(METHOD_DECL) do
add_child MethodNode.new($~[:name],$~[:scope],self.complete_name)
''
end
end
end
class ClassNode < Node
def initialize(name, contents, prefix)
super 'class', name, prefix
contents.gsub!(METHOD_DECL) do
add_child MethodNode.new($~[:name],$~[:scope],self.complete_name)
''
end
end
end
class MethodNode < Node
def initialize (name,contents,prefix)
super 'method', name, prefix
end
end
class Parser
def parse_file (file_name)
parse_text File.open(file_name).read
end
protected
def parse_text text
# first remove comments
text.gsub!(COMMENTS) do |m| '' end
# then begin populating the node tree
NamespaceNode.new("::",text,'')
end
end
<file_sep>/cpp_regexes.rb
NAMESPACE_DECLARATION = %r{
(?<vn>:{2}?[A-Za-z_0-9~]+\g<vn>?){0} #valid-name
(?<s>{((\g<s>|[^{}]*))*}){0} #scope
namespace\s+(?<name>\g<vn>)\s*(?<scope>\g<s>)
}x
CLASS_DECLARATION = %r{
(?<vn>:{2}?[A-Za-z_0-9~]+\g<vn>?){0} #valid-name
(?<s>{((\g<s>|[^{}]*))*}){0} #scope
(?<pc>\s*(?:(?:public|protected|private)\s+\g<vn>(?:\s*,\s*\g<pc>)? )){0} #parent class(es)
class\s+
(?<name>\g<vn>)\s*
(?::\g<pc>)?\s*
(?<scope>\g<s>)?
\s*;
}x
METHOD_DECL = %r{
(?<vn>:{2}?(?:[A-Za-z_0-9~\[\]]+|operator[^\s])\g<vn>?){0} #valid-name
(?<s>{((\g<s>|[^{}]*))*}){0} #scope
(?<ps>\(((\g<ps>|[^\)\(]*))*\)){0} #parenthesis scope
(?<ts>\<((\g<ts>|[^\<\>]*))*\>){0} #template scope
(?<cm>template\s*\<ts>|const|static|inline){0} #class modifiers
(?:static\s+\g<vn>\s+(?<name>\g<vn>)\s*=[^;]*;)|
(?:\g<cm>\s+)* #[optional] modifiers
(?:
(?<name>\g<vn>)\s*\g<ps>\s*(?:;|(?::[^\{]+)\g<s>) #ctors and dtors
|
(?<retval>\g<vn>)[\s\*\&]*\s[\s\*\&]*(?<name>\g<vn>)\s* #functions and variable declarations
(?:; | #variable
\g<ps>\s*(?:const)?\s*(?:;|(?<scope>\g<s>)) #method decl / def
)
)
}x
COMMENTS = %r{
(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|
(\/\/.*)
}x
| cf1f16880883b173ff488da0d131c0d1dc5b7816 | [
"Markdown",
"Ruby"
] | 3 | Markdown | jsrois/cpp-rgx | b4f3f45a8e2d5e12885986bc78d9d2865e3f7338 | a071d75096480a1158646e69d72edbac8f49d90e |
refs/heads/master | <repo_name>NoSkillGirl/JavaScript<file_sep>/Sample_codes/change_paragraph_text.js
let paragraph = document.getElementById('text-area')
paragraph.innerText = 'This is paragraph text'<file_sep>/fix_alarm/alarm.js
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
let t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function alarmSet(){
let alarmTime = document.getElementById('alarm-time').value;
let currentTime = document.getElementById('txt').innerHTML;
if (alarmTime === currentTime){
document.getElementById('ring-txt').innerHTML = "Your alarm is Ringing";
setTimeout(function(){
document.getElementById("ring-txt").innerHTML = '';
}, 30000);
};
let t = setTimeout(alarmSet, 500);
}
function onload(){
startTime();
document.getElementById('alarm-time').value = "00:00:00"; //reset input box
}
| a5fd324ebfe3bfd9a861a65ae4171fcb803cb689 | [
"JavaScript"
] | 2 | JavaScript | NoSkillGirl/JavaScript | 4ffd71ffb95a3ecdbd4ed4fc29b21404a6aa5fc1 | dc5b183002f0ee088e31c76828909adff90bbec4 |
refs/heads/master | <repo_name>leo-zhou/CNN-visualization<file_sep>/display_them.py
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import PIL.Image
import os
def deg2dec(d):
return 1.*d[0][0]/d[0][1]+1.*d[1][0]/d[1][1]/60+1.*d[2][0]/d[2][1]/3600
prepath = '../cam/still_3_16/'
# images = [f for f in os.listdir(prepath) if f.endswith('.jpg')]
# images.sort()
background = mpimg.imread('../localize/map.jpg')
bb = [45.591834,45.595397,-122.462629,-122.456612]
nr, nc, n3 = background.shape
fig, (ax1, ax2) = plt.subplots(2,1)
fig.set_size_inches(5, 9, forward=True)
with open('points','r') as fr:
for line in fr:
images = line.split()
for image in images:
ax2.cla()
ax2.imshow(background)
ax2.set_xlim([0, nc-1])
ax2.set_ylim([nr-1, 0])
img = PIL.Image.open(prepath+image+'.jpg')
ax1.imshow(np.array(img))
lat = deg2dec(img._getexif()[34853][2])
lon = deg2dec(img._getexif()[34853][4]) * -1
x = 0 + (lon-bb[2])/(bb[3]-bb[2])*nc
y = nr - (lat-bb[0])/(bb[1]-bb[0])*nr
ax2.plot(x,y,'ro')
ax2.set_title('image={0}'.format(image))
plt.pause(1)
<file_sep>/display_fc6_filters.py
import numpy as np
import os, sys, pickle, re, time, copy
import matplotlib.pyplot as plt
# from matplotlib.patches import Rectangle
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
os.environ['GLOG_minloglevel'] = '2'
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as anim
caffe_root = '/home/mo/caffe/'
sys.path.append(caffe_root+'python')
import caffe
caffe.set_mode_gpu()
""" load net weights and allocate memory """
model_def = '/home/mo/caffe/models/places/places205CNN_deploy.prototxt'
W = '/home/mo/caffe/models/places/places205CNN_iter_300000.caffemodel'
net = caffe.Net(model_def, W, caffe.TEST)
net.blobs['data'].reshape(10, 3, 227, 227)
""" pre-processing for input """
blob = caffe.proto.caffe_pb2.BlobProto()
mu_f = open(caffe_root+'models/places/places205CNN_mean.binaryproto','rb')
blob.ParseFromString(mu_f.read())
mu = np.array(caffe.io.blobproto_to_array(blob))[0]
BGRmean = mu.mean(1).mean(1)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', BGRmean)
transformer.set_raw_scale('data', 255)
transformer.set_channel_swap('data', (2,1,0))
image = caffe.io.load_image('../cam/still_3_16/IMG_20160316_154023.jpg')
net.blobs['data'].data[0] = transformer.preprocess('data',image)
output = net.forward()
filters = net.params['fc6'][0].data
t = filters.reshape(4096,256,6,6)
cmap = plt.cm.Reds
x, y, z = np.meshgrid(range(256),range(6),range(6))
x = x.flatten().tolist()
y = y.flatten().tolist()
z = z.flatten().tolist()
ims = []
fig = plt.figure()
ax = Axes3D(fig)
for i in range(0,t.shape[0],100):
# ax.cla()
ax.axis('off')
# ax.azim -= 5
cs = cmap(t[i].flatten() / t[i].max())
h1 = ax.scatter(y,z,x,c=cs.tolist(),alpha=.1,marker='s',s=100,lw=0)
h2 = ax.text(.5,.5,.95, '... neuron #%d'%(i+1))
ims.append([h1,h2])
# plt.pause(.1)
ani = anim.ArtistAnimation(fig, ims)
print "saving animation to file"
ani.save('out.mp4', writer="avconv", fps=2)
<file_sep>/display_features_fc6.py
import pickle, os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
from matplotlib.patches import Rectangle
def visualize(data):
for m in range(data.shape[0]):
if data[m].max()!=data[m].min():
data[m] = (data[m]-data[m].min())/(data[m].max()-data[m].min())
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = ((0,n*n-data.shape[0]), (0,1), (0,1))+((0,0),)*(data.ndim-3)
data = np.pad(data, padding, mode='constant', constant_values=1)
data = data.reshape((n, n) + data.shape[1:])
data = data.transpose((0,2,1,3)+(4,)*(data.ndim-4))
return data.reshape((n*data.shape[1],n*data.shape[3])+data.shape[4:])
def coor(bb): #extract coordinates for bbox
cors = ( bb[0][0] , bb[1][0] )
rows = bb[0][1] - bb[0][0]
cols = bb[1][1] - bb[1][0]
return (cors,rows,cols)
layer = 'fc6'
# images = [f for f in os.listdir('../cam/still_3_16/') if f.endswith('.jpg')]
# images.sort()
images = []
with open('points','r') as fpoints:
for line in fpoints:
images += line.split()[0:3]
print 'list of images:'
print '\n'.join(images)
fig = plt.figure(figsize=(20,5))
ax0 = fig.add_subplot(1,1,1)
ax1 = fig.add_axes([.6,.4,.2,.2])
ax0.set_title('layer: conv3')
for image in images:
nail = mpimg.imread('../cam/still_3_16/'+image+'.jpg')
with open('features/'+image+'.meta','rb') as fmeta:
meta = pickle.load(fmeta)
with open('features/'+image+'.'+layer,'rb') as fr:
Y = pickle.load(fr)
Y /= np.sqrt(np.power(Y,2).sum(axis=1)).reshape(Y.shape[0],1)
for j in range(len(meta)):
ax0.cla()
ax0.imshow(Y[j,np.newaxis,:], aspect='auto', interpolation='nearest')
ax1.cla()
ax1.imshow(nail)
ax1.axis('off')
bbcors, bbrows, bbcols = coor(meta[j])
ax1.add_patch( Rectangle(bbcors[::-1], bbcols, bbrows,
fill=False, linewidth=1.5, edgecolor="red") )
fig.tight_layout()
fig.savefig('../fc6/%s_p%02d.png'%(image,j))
plt.pause(1)
# fig = plt.figure(figsize=(20,5))
# for image in images:
# with open('features/'+image[:-4]+'.'+layer,'rb') as fr:
# Y = pickle.load(fr)
# fig.clf()
# ax1 = fig.add_axes([.05, .15, .9, .8])
# ax2 = fig.add_axes([.05, .05, .9, .05])
# h1 = ax1.imshow(Y, aspect='auto', interpolation='nearest')
# fig.colorbar(h1, cax=ax2, orientation='horizontal')
# fig.savefig('../fc6-landmarks/'+image[:-4]+'.png')
# plt.pause(2)<file_sep>/display_features_lands.py
import pickle, os
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] = 'nearest'
def visualize(data,name):
for m in range(data.shape[0]):
if data[m].max()!=data[m].min():
data[m] = (data[m]-data[m].min())/(data[m].max()-data[m].min())
n = int(np.ceil(np.sqrt(data.shape[0])))
padding = ((0,n*n-data.shape[0]), (0,1), (0,1))+((0,0),)*(data.ndim-3)
data = np.pad(data, padding, mode='constant', constant_values=1)
data = data.reshape((n, n) + data.shape[1:])
data = data.transpose((0,2,1,3)+(4,)*(data.ndim-4))
data = data.reshape((n*data.shape[1],n*data.shape[3])+data.shape[4:])
plt.imshow(data)
plt.axis('off')
plt.pause(1)
plt.savefig('../conv3-landmarks/'+name, bbox_inches='tight')
layer = 'conv3'
with open('../localize/net_testing_'+layer) as fr:
X = pickle.load(fr)
for j in range(X.shape[0]):
visualize(X[j],'frame_%03d.jpg'%(j+1))
| e8a812c89a9f1abaf295412953c546f8c6825bc9 | [
"Python"
] | 4 | Python | leo-zhou/CNN-visualization | 6e7f6ba05cebc0f8c79050a52b75b5484c56e546 | 592c4351358d568a7f7417e7150a8826c357695b |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package discoverdublin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.stage.Window;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
/**
*
* @author Admin
*/
public class DiscoverDublin extends Application {
Stage stage;
MediaView mediaView1;
boolean flag;
@Override
public void start(Stage primaryStage) throws FileNotFoundException, URISyntaxException {
stage = primaryStage;
// Create the login form grid pane
//gridPane = createLoginFormPane();
// Add UI controls to the registration form grid pane
//addUIControls(gridPane);
// Create a pane for main window
GridPane gridPane = createMainwindowPane();
// Add UI controls to the registration form grid pane
addMainWindowUIControls(gridPane);
Scene scene = new Scene(gridPane, 900, 700);
primaryStage.setTitle("Discover Dublin");
primaryStage.setScene(scene);
addUIControls(primaryStage);
//primaryStage.show();
}
private GridPane createLoginFormPane() {
// Instantiate a new Grid Pane
GridPane gridPane = new GridPane();
// Position the pane at the center of the screen, both vertically and horizontally
gridPane.setAlignment(Pos.CENTER);
// Set a padding of 20px on each side
gridPane.setPadding(new Insets(60, 100, 40, 40));
// Set the horizontal gap between columns
gridPane.setHgap(10);
// Set the vertical gap between rows
gridPane.setVgap(10);
// Add Column Constraints
// columnOneConstraints will be applied to all the nodes placed in column one.
ColumnConstraints columnOneConstraints = new ColumnConstraints(100, 100, Double.MAX_VALUE);
columnOneConstraints.setHalignment(HPos.RIGHT);
// columnTwoConstraints will be applied to all the nodes placed in column two.
ColumnConstraints columnTwoConstrains = new ColumnConstraints(200,200, Double.MAX_VALUE);
columnTwoConstrains.setHgrow(Priority.ALWAYS);
gridPane.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);
return gridPane;
}
private GridPane createMainwindowPane() {
// Instantiate a new Grid Pane
GridPane gridPane = new GridPane();
// Position the pane at the center of the screen, both vertically and horizontally
gridPane.setAlignment(Pos.CENTER);
// Set a padding of 20px on each side
gridPane.setPadding(new Insets(40, 40, 40, 40));
// Set the horizontal gap between columns
gridPane.setHgap(10);
// Set the vertical gap between rows
gridPane.setVgap(10);
// Add Column Constraints
// columnOneConstraints will be applied to all the nodes placed in column one.
ColumnConstraints columnOneConstraints = new ColumnConstraints(100, 100, Double.MAX_VALUE);
columnOneConstraints.setHalignment(HPos.RIGHT);
// columnTwoConstraints will be applied to all the nodes placed in column two.
ColumnConstraints columnTwoConstrains = new ColumnConstraints(200,200, Double.MAX_VALUE);
columnTwoConstrains.setHgrow(Priority.ALWAYS);
gridPane.getColumnConstraints().addAll(columnOneConstraints, columnTwoConstrains);
return gridPane;
}
private void addUIControls(Stage pStage) throws FileNotFoundException {
GridPane gridPane = new GridPane();
Stage newStage = new Stage();
newStage.setTitle("Login");
gridPane.setBackground(new Background(new BackgroundFill(Color.MEDIUMSLATEBLUE, CornerRadii.EMPTY, Insets.EMPTY)));
// Add Header
Label headerLabel = new Label("Discover Dublin");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 36));
headerLabel.setTextFill(Color.web("#800080"));
gridPane.add(headerLabel, 2,0,3,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
//GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
Image image = new Image(new FileInputStream("flag.jpg"));
//Setting the image view
ImageView imageView = new ImageView(image);
//setting the fit height and width of the image view
imageView.setFitHeight(200);
imageView.setFitWidth(150);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
gridPane.add(imageView, 1, 2,1,3);
GridPane.setMargin(imageView, new Insets(20, 0,0,0));
// Add Email Label
Label userName = new Label("Username");
gridPane.add(userName, 2, 2);
GridPane.setHalignment(userName, HPos.LEFT);
gridPane.setPadding(new Insets(40, 40, 40, 40));
// Add Email Text Field
TextField userNameField = new TextField();
userNameField.setPrefHeight(40);
//userNameField.setMaxWidth(100);
gridPane.add(userNameField, 2, 3);
// Add Password Label
Label passwordLabel = new Label("<PASSWORD>");
gridPane.add(passwordLabel, 2, 4);
GridPane.setHalignment(passwordLabel, HPos.LEFT);
// Add Password Field
PasswordField passwordField = new PasswordField();
passwordField.setPrefHeight(40);
gridPane.add(passwordField, 2, 5);
// Add Submit Button
Button submitButton = new Button("Login");
submitButton.setPrefHeight(40);
submitButton.setDefaultButton(true);
submitButton.setPrefWidth(100);
gridPane.add(submitButton, 2, 6, 2, 1);
GridPane.setHalignment(submitButton, HPos.RIGHT);
GridPane.setMargin(submitButton, new Insets(20, 0,20,0));
Scene scene = new Scene (gridPane, 600, 400);
newStage.setScene(scene);
newStage.show();
submitButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if(userNameField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!", "Please enter your username");
return;
}
if(passwordField.getText().isEmpty()) {
showAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Form Error!", "Please enter a password");
return;
}
if(userNameField.getText().equals("dorset") && passwordField.getText().equals("<PASSWORD>")){
newStage.close();
pStage.show();
// Add UI controls to the registration form grid pane
//addMainWindowUIControls(gridPane);
//gridPane.getScene().getWindow().getOnCloseRequest();
}else{
//flag = false;
showAlert(Alert.AlertType.WARNING, gridPane.getScene().getWindow(), "Login failed!", "Invalid username/password!!!");
}
}
});
}
private void addMainWindowUIControls(GridPane gridPane) throws FileNotFoundException, URISyntaxException {
gridPane.setBackground(new Background(new BackgroundFill(Color.MEDIUMSLATEBLUE, CornerRadii.EMPTY, Insets.EMPTY)));
// Add Header
Label headerLabel = new Label("Discover Dublin");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 48));
headerLabel.setTextFill(Color.web("#800080"));
gridPane.add(headerLabel, 1,0);
GridPane.setHalignment(headerLabel, HPos.CENTER);
//GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
Image image = new Image(new FileInputStream("flag.jpg"));
//Setting the image view
ImageView imageView = new ImageView(image);
//setting the fit height and width of the image view
imageView.setFitHeight(70);
imageView.setFitWidth(50);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
gridPane.add(imageView, 3, 0);
GridPane.setMargin(imageView, new Insets(20, 0,0,0));
// Add history button
Button btnHistory = new Button("History");
btnHistory.setMaxWidth(Double.MAX_VALUE);
btnHistory.setStyle("-fx-background-color: #87CEFA;");
gridPane.add(btnHistory, 0, 1);
GridPane.setHalignment(btnHistory, HPos.LEFT);
//history content
BorderPane historyPane = new BorderPane();
BorderPane linksPane = new BorderPane();
BorderPane placesPane = new BorderPane();
BorderPane videosPane = new BorderPane();
ScrollPane QuizPane = new ScrollPane();
// menu option 1: adding element to history pane
String historyText="History of Dublin\n\n A not so brief history of Dublin. The first known settlement was Ath Cliath,\n"
+ "which took its name from a major ford across the tider River Liffry. At around\n the sixth"
+ "century a monastery Duiblinn(blackpoll) was fouded due south of\n the tidal pool in the River Poddle, a tributary of the Liffeyon the south bank.\n\n\n";
historyPane.setCenter(createLabel(historyText,Color.BLACK, Color.WHITE, 16));
gridPane.add(historyPane, 1, 1,2,6);
GridPane.setHalignment(historyPane, HPos.LEFT);
//menu option links
String linksTextHeading="Website Links";
linksPane.setTop(createLabel(linksTextHeading,Color.PURPLE, Color.MEDIUMSLATEBLUE, 20));
String linksText="https://www.visitdublin.com\n\nhttps://lovindublin.com/lifestyle/10-of-the-best-places-to-spend-the-day-in-dublin-that-wont-cost-you-a-penney";
linksPane.setCenter(createLabel(linksText,Color.BLACK, Color.MEDIUMSLATEBLUE, 16));
gridPane.add(linksPane, 1, 1,2,6);
GridPane.setHalignment(linksPane, HPos.LEFT);
linksPane.setVisible(false);
//play audio
ComboBox audioList = new ComboBox();
audioList.getItems().addAll("select","05_Reels__The_The_Maids_of_Castlebar_The_Swallow_s_Nest.mp3","08_Polkas__Seamus_Creagh_s_Trip_to_Dingle.mp3");
audioList.setPromptText("Select audio");
audioList.setEditable(true);
audioList.valueProperty().addListener(new ChangeListener<String>() {
@Override public void changed(ObservableValue ov, String t, String t1) {
//menu option places
String pathAudio = "resources\\audios\\"+t1;
//Instantiating Media class
Media media = new Media(new File(pathAudio).toURI().toString());
//Instantiating MediaPlayer class
MediaPlayer mediaPlayer = new MediaPlayer(media);
//by setting this property to true, the audio will be played
if(t1.equals("select"))
mediaPlayer.setAutoPlay(false);
else
mediaPlayer.setAutoPlay(true);
}
});
placesPane.setTop(audioList);
//linksPane.setCenter(createLabel(linksText,Color.BLACK, Color.MEDIUMSLATEBLUE, 16));
gridPane.add(placesPane, 1, 1,2,6);
GridPane.setHalignment(placesPane, HPos.LEFT);
placesPane.setVisible(false);
//play videos
ComboBox videosList = new ComboBox();
videosList.getItems().addAll("select","vid1.mp4","vid2.mp4","vid3.mp4");
videosList.setPromptText("Select video");
videosList.setEditable(true);
videosList.valueProperty().addListener(new ChangeListener<String>() {
@Override public void changed(ObservableValue ov, String t, String t1) {
//menu option video
String pathVideo = "resources\\videos\\"+t1;
//Instantiating Media class
Media media = new Media(new File(pathVideo).toURI().toString());
//Instantiating MediaPlayer class
MediaPlayer mediaPlayer = new MediaPlayer(media);
//by setting this property to true, the audio will be played
mediaView1 = new MediaView (mediaPlayer);
videosPane.setCenter(mediaView1);
mediaPlayer.setAutoPlay(true);
}
});
videosPane.setTop(videosList);
//linksPane.setCenter(createLabel(linksText,Color.BLACK, Color.MEDIUMSLATEBLUE, 16));
gridPane.add(videosPane, 1, 1,2,6);
GridPane.setHalignment(videosPane, HPos.LEFT);
videosPane.setVisible(false);
ScrollPane galleryPane = new ScrollPane();
TilePane tile = new TilePane();
galleryPane.setStyle("-fx-background-color: DAE6F3;");
tile.setPadding(new Insets(15, 15, 15, 15));
tile.setHgap(15);
String path ="resources\\images\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Images: "+listOfFiles.length);
for (final File file : listOfFiles) {
ImageView imageView1 = createImageView(file);
tile.getChildren().addAll(imageView1);
}
galleryPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); // Horizontal
galleryPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); // Vertical scroll bar
galleryPane.setFitToWidth(true);
galleryPane.setContent(tile);
gridPane.add(galleryPane,1, 1,2,6);
galleryPane.setVisible(false);
btnHistory.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
historyPane.setVisible(true);
linksPane.setVisible(false);
galleryPane.setVisible(false);
placesPane.setVisible(false);
videosPane.setVisible(false);
linksPane.setVisible(false);
QuizPane.setVisible(false);
}
}
);
// Add places button
Button btnPlaces = new Button("Places");
btnPlaces.setMaxWidth(Double.MAX_VALUE);
btnPlaces.setStyle("-fx-background-color: #87CEFA;");
gridPane.add(btnPlaces, 0, 2);
GridPane.setHalignment(btnPlaces, HPos.LEFT);
btnPlaces.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
historyPane.setVisible(false);
linksPane.setVisible(false);
galleryPane.setVisible(false);
placesPane.setVisible(true);
videosPane.setVisible(false);
linksPane.setVisible(false);
QuizPane.setVisible(false);
}
}
);
// Add gallery button
Button btnGallery = new Button("Gallery");
btnGallery.setMaxWidth(Double.MAX_VALUE);
btnGallery.setStyle("-fx-background-color: #87CEFA;");
gridPane.add(btnGallery, 0, 3);
GridPane.setHalignment(btnGallery, HPos.LEFT);
btnGallery.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
historyPane.setVisible(false);
linksPane.setVisible(false);
galleryPane.setVisible(true);
placesPane.setVisible(false);
videosPane.setVisible(false);
linksPane.setVisible(false);
QuizPane.setVisible(false);
}
}
);
// Add videos button
Button btnVideos = new Button("Videos");
btnVideos.setMaxWidth(Double.MAX_VALUE);
btnVideos.setStyle("-fx-background-color: #87CEFA;");
gridPane.add(btnVideos, 0, 4);
GridPane.setHalignment(btnVideos, HPos.LEFT);
btnVideos.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
historyPane.setVisible(false);
linksPane.setVisible(false);
galleryPane.setVisible(false);
placesPane.setVisible(false);
videosPane.setVisible(true);
linksPane.setVisible(false);
QuizPane.setVisible(false);
}
}
);
// Add links button
Button btnLinks = new Button("Links");
btnLinks.setMaxWidth(Double.MAX_VALUE);
btnLinks.setStyle("-fx-background-color: #87CEFA;");
gridPane.add(btnLinks, 0, 5);
GridPane.setHalignment(btnLinks, HPos.LEFT);
btnLinks.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
historyPane.setVisible(false);
linksPane.setVisible(false);
galleryPane.setVisible(false);
placesPane.setVisible(false);
videosPane.setVisible(false);
linksPane.setVisible(true);
QuizPane.setVisible(false);
}
}
);
ToggleGroup group1 = new ToggleGroup();
ToggleGroup group2 = new ToggleGroup();
ToggleGroup group3 = new ToggleGroup();
ToggleGroup group4 = new ToggleGroup();
VBox vbQuiz = new VBox(20);
HBox hb1 = new HBox(10);
HBox hb2 = new HBox(10);
HBox hb3 = new HBox(10);
HBox hb4 = new HBox(10);
//group 1
Label ques1 = new Label("1. What is the capital of Ireland?");
Label ques2 = new Label("2. What is the national language of Ireland?");
Label ques3 = new Label("3. What is the population (million) in Ireland?");
Label ques4 = new Label("4. Which province has the fewest counties?");
Button btnAnswer = new Button("Submit");
RadioButton rb11 = new RadioButton("Dublin");
hb1.getChildren().add(rb11);
rb11.setToggleGroup(group1);
RadioButton rb12 = new RadioButton("Cork");
hb1.getChildren().add(rb12);
rb12.setToggleGroup(group1);
RadioButton rb13 = new RadioButton("Galway");
hb1.getChildren().add(rb13);
rb13.setToggleGroup(group1);
vbQuiz.getChildren().add(ques1);
vbQuiz.getChildren().add(hb1);
RadioButton rb21 = new RadioButton("Irish");
hb2.getChildren().add(rb21);
rb21.setToggleGroup(group2);
RadioButton rb22 = new RadioButton("Portuguese");
hb2.getChildren().add(rb22);
rb22.setToggleGroup(group2);
RadioButton rb23 = new RadioButton("Catalan");
hb2.getChildren().add(rb23);
rb23.setToggleGroup(group2);
vbQuiz.getChildren().add(ques2);
vbQuiz.getChildren().add(hb2);
//
RadioButton rb31 = new RadioButton("4.784");
hb3.getChildren().add(rb31);
rb31.setToggleGroup(group3);
RadioButton rb32 = new RadioButton("3.689");
hb3.getChildren().add(rb32);
rb32.setToggleGroup(group3);
RadioButton rb33 = new RadioButton("5.879");
hb3.getChildren().add(rb33);
rb33.setToggleGroup(group3);
vbQuiz.getChildren().add(ques3);
vbQuiz.getChildren().add(hb3);
//
RadioButton rb41 = new RadioButton("Ulster");
hb4.getChildren().add(rb41);
rb41.setToggleGroup(group4);
RadioButton rb42 = new RadioButton("Munster");
hb4.getChildren().add(rb42);
rb42.setToggleGroup(group4);
RadioButton rb43 = new RadioButton("Connacht");
hb4.getChildren().add(rb43);
rb43.setToggleGroup(group4);
vbQuiz.getChildren().add(ques4);
vbQuiz.getChildren().add(hb4);
vbQuiz.getChildren().add(btnAnswer);
QuizPane.setContent(vbQuiz);
gridPane.add(QuizPane, 1, 1,2,6);
QuizPane.setVisible(false);
// Add quiz button
Button btnQuiz = new Button("Quiz");
btnQuiz.setStyle("-fx-background-color: #87CEFA;");
btnQuiz.setMaxWidth(Double.MAX_VALUE);
gridPane.add(btnQuiz, 0, 6);
GridPane.setHalignment(btnQuiz, HPos.LEFT);
btnQuiz.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
historyPane.setVisible(false);
linksPane.setVisible(false);
galleryPane.setVisible(false);
placesPane.setVisible(false);
videosPane.setVisible(false);
linksPane.setVisible(false);
QuizPane.setVisible(true);
}
}
);
btnAnswer.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
int correct = 0;
int total = 4;
if(rb11.isSelected() == true)
correct++;
if(rb21.isSelected() == true)
correct++;
if(rb31.isSelected() == true)
correct++;
if(rb43.isSelected() == true)
correct++;
showAlert(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Result of quiz", "Score: \n"+correct+" out of "+total);
}
}
);
}
private void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
}
private Label createLabel(String text, Color color,Color bgcolor, int size) {
Label l = new Label(text);
l.setContentDisplay(ContentDisplay.TOP);
l.setTextFill(color);
l.setStyle("-fx-background-color:'"+bgcolor+"'");
l.setPadding(new Insets(10,10,0,10));
l.setMaxHeight(Double.MAX_VALUE);
l.setFont(new Font(size));
return l;
}
private Button createButton(String text, Color color, int size) {
Rectangle r = new Rectangle(3 * size, 2 * size);
r.setFill(Color.TRANSPARENT);
r.setStroke(color);
r.setStrokeWidth(3);
Button l = new Button(text,r);
l.setContentDisplay(ContentDisplay.TOP);
l.setStyle("-fx-background-color: #FFFFFF;");
l.setFont(new Font(16));
return l;
}
private ImageView createImageView(final File imageFile) {
// DEFAULT_THUMBNAIL_WIDTH is a constant you need to define
// The last two arguments are: preserveRatio, and use smooth (slower)
// resizing
ImageView imageView = null;
try {
final Image image = new Image(new FileInputStream(imageFile), 150, 0, true,
true);
imageView = new ImageView(image);
imageView.setFitWidth(150);
imageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){
if(mouseEvent.getClickCount() == 2){
try {
BorderPane borderPane = new BorderPane();
ImageView imageView = new ImageView();
Image image = new Image(new FileInputStream(imageFile));
imageView.setImage(image);
imageView.setStyle("-fx-background-color: BLACK");
imageView.setFitHeight(stage.getHeight() - 10);
imageView.setPreserveRatio(true);
imageView.setSmooth(true);
imageView.setCache(true);
borderPane.setCenter(imageView);
borderPane.setStyle("-fx-background-color: BLACK");
Stage newStage = new Stage();
newStage.setWidth(stage.getWidth());
newStage.setHeight(stage.getHeight());
newStage.setTitle(imageFile.getName());
Scene scene = new Scene(borderPane,Color.BLACK);
newStage.setScene(scene);
newStage.show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
});
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
return imageView;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
<file_sep># Discover-Dublin
This JavaFX desktop application is created on Netbeans IDE helps to discover places in dublin with places, images, audio, quiz at the end.
| 60aa184ca394f0b0dfc90d178f4b17295d116ed6 | [
"Markdown",
"Java"
] | 2 | Java | ushapriya75/Discover-Dublin | 665a39672c1a7b04f440557faf5c55cf90401e56 | 974c9d7b2aa353b1416b293bb07d5ed322ff7561 |
refs/heads/main | <repo_name>FreshManCode/react_context_demo<file_sep>/README.md
# react_context_demo
reactไฝฟ็จcontext่ฟ่กไธไธๆไผ ้
| b38d4bbbaaf8fa784be5e9a5cbd478e83e54c2b9 | [
"Markdown"
] | 1 | Markdown | FreshManCode/react_context_demo | 591d540d56825ab158af633b3f3822af68ae1fc8 | 6c6ad77a6063ef3f72746e6781faac26a7c7c8c6 |
refs/heads/main | <file_sep># KRsync
A script to help you donwload things from rsync.kemono.party easily
## Usage
```
Download via rsync contents of specific creators from rsync.kemono.party
Usage: krsync -h
krsync --SERVICE --id <creator id> [ --dest <destination_dir> ]
--dest <destination_dir>, destination where you want the downloaded content to go
The <creator id> is the number at the end of the URL on any given creator's page
SERVICE:
--patreon, used when downloading a patreon creator
--subscribestar, used when downloading a subscribestar creator
--fantia, used when downloading a fantia creator
--fanbox, used when downloading a fanbox creator
--gumroad, used when downloading a gumroad creator
You can also edit the script to include the destination by default.
This is done by changing the string after "dest" in the shell script.
Remove the '', and add the destination of your choosing. That way, you don't have to add it every time.
```
<file_sep>#!/bin/bash
#rsync Patreon
echo Please enter the creator ID
read id
rsync -4ahmvz --ignore-existing --no-motd --progress --info=progress2 --no-D --no-g --no-o --no-p --exclude=*.clip --exclude=*.psd --exclude=*.sai --exclude=*PSD* rsync://rsync.kemono.party/kemono/attachments/$id /media/pi/ExtDrv1/Kemono
<file_sep>#!/bin/bash
#rsync Patreon
echo Please enter the creator ID
read id
rsync -4ahmvz --ignore-existing --progress --no-motd --no-D --no-g --no-o --no-p --exclude=*.clip --exclude=*.psd --exclude=*.sai rsync://rsync.kemono.party/kemono/attachments/$id /media/pi/ExtDrv1/Kemono
<file_sep>#!/bin/sh
name='krsync'
rsync_binary='rsync'
default_rysnc_args='-4ahmvz --ignore-existing --progress --no-motd --info=progress2 --no-D --no-g --no-o --no-p --exclude=*.clip --exclude=*.psd --exclude=*.sai'
additional_rsync_args=''
rsync_domain='rsync.kemono.party'
service_base_url="rsync://$rsync_domain/kemono/data/attachments"
used_url=''
service=''
id=''
dest=''
service_set=0
help() {
cat <<- _end_help_message
Download via rsync contents of specific creators from $rsync_domain
Usage: $name -h
$name --SERVICE --id <creator id> [ --dest <destination_dir> ]
--dest <destination_dir>, destination where you want the downloaded content to go
The <creator id> is the number at the end of the URL on any given creator's page
SERVICE:
--patreon, used when downloading a patreon creator
--subscribestar, used when downloading a subscribestar creator
--fantia, used when downloading a fantia creator
--fanbox, used when downloading a fanbox creator
--gumroad, used when downloading a gumroad creator
_end_help_message
}
while [ "$1" ]; do
case "$1" in
--help | -h )
help; exit 0;;
--subscribestar )
service='subscribestar'; service_set=1 ; shift; continue ;;
--fantia )
service='fantia'; service_set=1 ; shift; continue ;;
--fanbox )
service='fanbox'; service_set=1 ; shift; continue ;;
--patreon )
service_set=1 ; shift; continue ;;
--discord )
service_set=1 ; shift; continue ;;
--gumroad )
service='gumroad'; service_set=1 ; shift; continue ;;
--id )
shift; id="$1"; shift; continue ;;
--dest )
shift; dest="$1"; shift; continue ;;
* )
additional_rsync_args="$additional_rsync_args $1"; shift; continue ;;
esac
done
if [ -z "$id" ]; then
printf "Please specify an id with the --id flag\n"; exit 1;
fi
if [ "$service_set" = 0 ]; then
printf "Please specify a service\n"; exit 1;
fi
if [ -z "$dest" ]; then
printf "No destination set. Defaulting to using the current working directory\n"
dest='.'
fi
used_url="$service_base_url/$service/$id"
exec $rsync_binary $default_rysnc_args $additional_rsync_args $used_url $dest
<file_sep># Usah-s-Kemono-rsync-scripts
Some scripts I made that will allow people with minimum knowledge in using rsync and Bash to utilize kemono.party's rsync service.
# Instructions
You must edit the output directory listed in the files to the directory which you would like to use. This can be easily done in any text editor.
# How to use
* 1: Edit the output directory in the text editor of your choosing
* 2: Place scripts wherever you find most useful
* 3: Open Terminal and cd into that folder
* 4: Run the script like so: ~$ ./script.sh ( ./Patreon.sh for example)
* 5: Input the ID of the user/discord and press enter
* 6: ???
* 7: Profit
| 3a278f61548d50b4b03085a1a7793242746a9f87 | [
"Markdown",
"Shell"
] | 5 | Markdown | jojo935/KRsync-A-Kemono-rsync-script | d22308f60de89195061f3962cce0452053ff63f1 | 9e4edf8d04f77985b39703a85d21931ec395e2b1 |
refs/heads/master | <repo_name>Explodingcat/control-1-2<file_sep>/control1.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
struct Estacion {
int id;
int linea;
string cod;
string nombre;
int comb;
};
void imprimir_Nombres()
{
cout<<"<NAME>"<<endl;
cout<<"<NAME>"<<endl;
cout<<"<NAME>"<<endl;
}
void llenar_Metro(vector <Estacion> &metro)
{
Estacion a;
string linea,cad4,cad3;
int pos,cont=1,lin;
ifstream fixero("estaciones.csv");
while(!fixero.eof())
{
getline(fixero,linea);
pos=linea.find(" ");
cad4 = linea.substr(0,pos);
pos=linea.find(" ")+1;
cad3 =linea.substr(pos);
pos=cad3.find(" ");
if(cad4=="Lรญnea")
{
pos=cad3.find(" ");
cad3=cad3.substr(0,pos);
if(cad3=="4a")
{
lin=3;
}
else
{
lin=atoi(cad3.c_str());
}
a.id=0;
a.linea=0;
a.nombre="";
a.cod="";
a.comb=0;
metro.push_back(a);
}
else
{
a.id=cont;
a.linea=lin;
a.nombre=cad3;
a.cod=cad4;
a.comb=0;
cont++;
metro.push_back(a);
}
}
metro.pop_back();
Estacion b;
b.id=0;
b.linea=0;
b.nombre="";
b.cod="";
b.comb=0;
metro.push_back(b);
}
int buscar_Estacion(vector <Estacion> metro, string inic, string final, int *in, int *fin)
{
int cont=0;
for(int i=0;i<metro.size();i++)
{
if(metro[i].id!=0 && metro[i].cod==inic)
{
*in=i;
cont++;
}
if(metro[i].id!=0 && metro[i].cod==final)
{
*fin=i;
cont++;
}
}
return cont;
}
void buscar_Combis(vector <Estacion> &metro)
{
for(int i=0;i<metro.size();i++)
{
for(int j=0;j<metro.size();j++)
{
if(i!=j && metro[i].id!=0 && metro[j].id!=0 )
{
if(metro[i].nombre==metro[j].nombre && metro[i].comb==0)
{
metro[i].comb=metro[j].linea;
metro[j].comb=metro[i].linea;
}
}
}
}
}
void buscando_Opciones(vector <Estacion> metro, int *cont, string &cam, int inic, int des, vector <string> &posibles, vector <int> &valores)
{
int movd,movi,contd,conti,checkd=0,checki=0,aux;
string caminod,caminoi,can;
if(*cont>50)
{
*cont=1000;
}
else
{
if(*cont==0 && metro[inic].comb!=0)
{
for(int i=0;i<metro.size();i++)
{
if(metro[inic].nombre==metro[i].nombre && inic!=i)
{
aux=-1;
buscando_Opciones(metro,&aux,cam,i,des,posibles,valores);
}
}
}
if(*cont==-1)
*cont=0;
contd=*cont;
caminod=cam;
movd=inic+1;
while(metro[movd].id!=0 && checkd==0)
{
contd++;
caminod=caminod+"->"+metro[movd].nombre;
if(movd==des)
{
checkd=1;
posibles.push_back(caminod);
valores.push_back(contd);
}
else
{
if(metro[movd].comb!=0)
{
for(int i=0;i<metro.size();i++)
{
if(metro[movd].nombre==metro[i].nombre && movd!=i)
{
if(metro[i].nombre==metro[des].nombre)
{
checkd=1;
posibles.push_back(caminod);
valores.push_back(contd);
}
else
{
buscando_Opciones(metro,&contd,caminod,i,des,posibles,valores);
}
}
}
}
}
movd++;
}
conti=*cont;
caminoi=cam;
movi=inic-1;
while(metro[movi].id!=0 && checki==0)
{
conti++;
caminoi=caminoi+"->"+metro[movi].nombre;
if(movi==des)
{
posibles.push_back(caminoi);
valores.push_back(conti);
checki=1;
}
else
{
if(metro[movi].comb!=0)
{
for(int i=0;i<metro.size();i++)
{
if(metro[movi].nombre==metro[i].nombre && movi!=i)
{
if(metro[i].nombre==metro[des].nombre)
{
posibles.push_back(caminoi);
valores.push_back(conti);
checki=1;
}
else
{
buscando_Opciones(metro,&conti,caminoi,i,des,posibles,valores);
}
}
}
}
}
movi--;
}
}
}
void planificar_Viaje(vector <Estacion> metro, int ini, int des)
{
string recorrido=metro[ini].nombre;
vector <string> posibles;
vector <int> valores;
int cont=0,menor=999,redy=0;
if(metro[ini].nombre==metro[des].nombre)
{
cout<<"_________________RUTA PLANIFICADA___________________"<<endl;
cout<<metro[ini].nombre<<endl;
}
else
{
buscando_Opciones(metro,&cont,recorrido,ini,des,posibles,valores);
for(int i=0;i<valores.size();i++)
{
if(valores[i]<menor)
{
menor=valores[i];
}
}
for(int i=0;i<valores.size();i++) //verifica si existen mas de 1 ruta menor y entrega todas las opciones
{
if(valores[i]==menor)
{
cout<<"_________________RUTA PLANIFICADA___________________"<<endl;
cout<<posibles[i]<<endl;
cout<<endl;
}
}
}
}
int main(int argc, char* argv[])
{
vector <Estacion> metro;
string inic,final,hola;
int in,fin;
if(argc==2)
{
hola=argv[1];
if(hola=="-v")
{
imprimir_Nombres();
}
else
{
cout<<"Entrada Invalida"<<endl;
}
}
else
{
if(argc==4)
{
hola=argv[1];
if(hola=="-f")
{
inic=argv[2];
final=argv[3];
llenar_Metro(metro); //llena el vector de estaciones
if(buscar_Estacion(metro,inic,final,&in,&fin)==2)
{
buscar_Combis(metro); //funcion busca todas las estaciones que poseen estacion en mas de una linea, si lo encuentra guarda en variable comb el numero de la linea a la que combina.
planificar_Viaje(metro,in,fin);//planifica
}
else
{
cout<<"Verifique codigo estaciones"<<endl;
}
}
else
{
cout<<"Entrada Invalida"<<endl;
}
}
else
{
cout<<"Error en datos ingresados"<<endl;
}
}
}<file_sep>/README.md
# Control 2 Paralelo
*UPDATE*
09/09/2018
----------
30/08/2018
# Para Ejecutar se necesita el archivo estaciones.csv en la misma carpeta
# Control 1
16/08/2018
# Para Ejecutar se necesita el archivo estaciones.csv en la misma carpeta
| 6c7958ace2ae62b5f138af4944b2438bd719c9d3 | [
"Markdown",
"C++"
] | 2 | C++ | Explodingcat/control-1-2 | 0f0db4653173bd4e7e8cc0272ca7102ba0747b98 | 8f27ffdc602081f94edca48d7b7f2957b0578336 |
refs/heads/master | <repo_name>akshitdewan/cs61a-apps<file_sep>/code/src/renderer/components/SettingsDialog.js
import { createMuiTheme, InputAdornment, TextField } from "@material-ui/core";
import Switch from "@material-ui/core/Switch";
import ThemeProvider from "@material-ui/styles/ThemeProvider";
import * as React from "react";
import { useSettingsKey } from "../../web/settings";
import { dialogWrap } from "../utils/dialogWrap.js";
function SettingsDialog() {
const theme = React.useMemo(
() =>
createMuiTheme({
palette: {
type: "dark",
},
}),
[]
);
const [autocomplete, setAutocomplete] = useSettingsKey("enableAutocomplete");
const [doctestTimeout, setDoctestTimeout] = useSettingsKey("doctestTimeout");
return (
<ThemeProvider theme={theme}>
<form className="settingsDialogForm">
<table>
<thead>
<tr>
<th>Option</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label htmlFor="autocomplete-control">
Enable editor autocomplete
</label>
</td>
<td>
<Switch
checked={autocomplete}
onChange={(e) => setAutocomplete(e.target.checked)}
color="secondary"
inputProps={{ id: "autocomplete-control" }}
/>
</td>
</tr>
<tr>
<td>
<label htmlFor="doctest-timeout">Doctest Timeout</label>
</td>
<td>
<TextField
id="doctest-timeout"
type="number"
value={doctestTimeout}
InputProps={{
endAdornment: (
<InputAdornment position="end">s</InputAdornment>
),
}}
onChange={(e) => setDoctestTimeout(e.target.value)}
/>
</td>
</tr>
</tbody>
</table>
</form>
</ThemeProvider>
);
}
export default dialogWrap("Settings", SettingsDialog, "row");
<file_sep>/examtool/examtool/api/assemble_export.py
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, List, Optional, Union
from tqdm import tqdm
from examtool.api.extract_questions import get_name
from examtool.api.grade import grade
@dataclass(frozen=True)
class AssembledExam:
exam: str
email: str
name: str
sid: str
questions: List[Question]
@dataclass(frozen=True)
class Question:
name: str
prompt: Text
autograde_output: str
@dataclass(frozen=True)
class OptionQuestion(Question):
options: List[Text]
selected: List[Text]
@dataclass(frozen=True)
class Text:
text: str
tex: str
html: str
def __init__(self, element):
for k in ["text", "tex", "html"]:
object.__setattr__(self, k, element[k])
@dataclass(frozen=True)
class TextQuestion(Question):
response: str
height: int
def assemble_exam(
exam: str,
email: Optional[str],
response: Dict[str, Union[str, List[str]]],
template_questions: List[Dict],
student_questions: List[Dict],
name_question: str,
sid_question: str,
dispatch,
substitute_in_question_text: bool = False,
):
questions = []
exam = AssembledExam(
exam=exam,
email=email,
name=response.get(name_question, "NO NAME"),
sid=response.get(sid_question, "NO SID"),
questions=questions,
)
student_question_lookup = {q["id"]: q for q in student_questions}
for question in template_questions:
question_name = get_name(question)
if substitute_in_question_text:
question_text = Text(student_question_lookup.get(question["id"], question))
else:
question_text = Text(question)
autograde_output = (
grade(
email,
student_question_lookup[question["id"]],
response,
dispatch,
)
if question["id"] in response and question["id"] in student_question_lookup
else "STUDENT LEFT QUESTION BLANK"
if question["id"] in student_question_lookup
else "STUDENT DID NOT RECEIVE QUESTION"
)
if question.get("type") in ["multiple_choice", "select_all"]:
selected_options = response.get(question["id"], [])
if question.get("type") == "multiple_choice" and not isinstance(
selected_options, list
):
selected_options = [selected_options]
available_options = [Text(option) for option in question["options"]]
if question["id"] not in student_question_lookup:
student_options = available_options
else:
student_options = [
option["text"]
for option in sorted(
student_question_lookup[question["id"]]["options"],
key=lambda option: option.get("index", ""),
)
]
assert len(available_options) == len(student_options)
assembled_question = OptionQuestion(
name=question_name,
prompt=question_text,
options=available_options,
selected=(
[
option
for i, option in enumerate(available_options)
if student_options[i] in selected_options
]
),
autograde_output=autograde_output,
)
else:
assembled_question = TextQuestion(
name=question_name,
prompt=question_text,
autograde_output=autograde_output,
response=response.get(question["id"], "").replace("\t", " " * 4),
height=question.get("options") or 1
if question["type"].startswith("long")
else 1,
)
questions.append(assembled_question)
return exam
def export(
template_questions,
student_responses,
exam,
name_question,
sid_question,
*,
dispatch=None,
include_outline=True,
substitute_in_question_text=False,
):
assembles = {}
if include_outline:
assembles["OUTLINE"] = assemble_exam(
exam,
None,
{},
template_questions,
template_questions,
name_question,
sid_question,
dispatch,
)
for email, data in tqdm(student_responses.items(), desc="Assembling", unit="Exam"):
assembles[email] = assemble_exam(
exam,
email,
data.get("responses"),
template_questions,
data.get("student_questions"),
name_question,
sid_question,
dispatch,
substitute_in_question_text=substitute_in_question_text,
)
return assembles
<file_sep>/slack/slack_client.py
import json
import re
import traceback
import requests
from flask import jsonify, request, redirect
from clap_integration import ClapIntegration
from common.rpc.auth import list_courses, slack_workspace_name
from common.rpc.secrets import get_secret
from config_client import (
REJECTED,
UNABLE,
get_user_token,
store_user_token,
store_bot_token,
get_team_data,
)
from common.db import connect_db
from emoji_integration import EmojiIntegration
from golink_integration import GoLinkIntegration
from group_integration import GroupIntegration
from integration import combine_integrations
from lgtm_integration import LGTMIntegration
from piazza_integration import PiazzaIntegration
from ed_integration import EdIntegration
from prlink_integration import PRLinkIntegration
from issue_integration import IssueIntegration
from apps_prlink_integration import AppsPRLinkIntegration
from build_integration import BuildIntegration
from promotions import make_promo_block
from security import slack_signed
WORKSPACE_CACHE = {}
def get_course(workspace):
if workspace not in WORKSPACE_CACHE:
for course, _ in list_courses():
try:
WORKSPACE_CACHE[slack_workspace_name(course=course)] = course
except KeyError:
continue
return WORKSPACE_CACHE[workspace]
def create_slack_client(app):
@app.route("/oauth")
def oauth():
if not request.args["code"]:
return jsonify({"Error": "sadcat"}), 500
resp = requests.post(
"https://slack.com/api/oauth.v2.access",
{
"code": request.args["code"],
"client_id": get_secret(secret_name="CLIENT_ID"),
"client_secret": get_secret(secret_name="CLIENT_SECRET"),
},
)
if resp.status_code == 200:
data = resp.json()
bot_token = data["access_token"]
workspace_data = requests.post(
"https://slack.com/api/auth.test",
headers={"Authorization": "Bearer {}".format(bot_token)},
).json()
workspace_url = workspace_data["url"]
workspace = re.match(
r"https://([a-zA-Z\-0-9]+)\.slack\.com", workspace_url
).group(1)
store_bot_token(get_course(workspace), data["team"]["id"], bot_token)
store_user_token(
data["authed_user"]["id"], data["authed_user"]["access_token"]
)
with connect_db() as db:
db(
"DELETE FROM silenced_users WHERE user = (%s)",
[data["authed_user"]["id"]],
)
return redirect(workspace_url)
return jsonify({"Error": "sadcat"}), 500
@app.route("/interactive_handler", methods=["POST"])
@slack_signed
def handler():
payload = json.loads(request.form["payload"])
if "actions" not in payload or "value" not in payload["actions"][0]:
return ""
action = payload["actions"][0]["value"]
user_id = payload["user"]["id"]
if action == "activate":
requests.post(
payload["response_url"],
json={
"text": ":robot_face: Activated! While we can't update your previous message (:crying_cat_face:), all your future messages will be made awesome!",
"replace_original": "true",
},
)
elif action == "maybe_later":
requests.post(
payload["response_url"],
json={
"text": "Alright, I'll ask you again later. Or visit slack.apps.cs61a.org to activate this bot manually!!",
"replace_original": "true",
},
)
elif action == "never_ask_again":
with connect_db() as db:
db("INSERT INTO silenced_users VALUES (%s)", (user_id,))
requests.post(
payload["response_url"],
json={
"text": "Understood. If you ever change your mind, visit slack.apps.cs61a.org to activate this bot!",
"replace_original": "true",
},
)
return ""
@app.route("/message_send", methods=["POST"])
@slack_signed
def message_send():
d = request.json
try:
if "challenge" in d or request.headers.get("X-Slack-Retry-Reason"):
return
team_id = d["team_id"]
course, bot_token = get_team_data(team_id)
event = d["event"]
if event["type"] == "channel_created":
requests.post(
"https://slack.com/api/conversations.join",
json={"channel": event["channel"]["id"]},
headers={"Authorization": "Bearer {}".format(bot_token)},
).json()
return
token = get_user_token(event["user"])
if token is REJECTED:
return
if "edited" in event:
return
if "subtype" in event:
return
with connect_db() as db:
ret = db(
"SELECT service FROM activated_services WHERE course = (%s)",
[course],
)
active_services = set(x[0] for x in ret)
integrations = []
if "piazza" in active_services:
integrations.append(PiazzaIntegration)
elif "ed" in active_services:
integrations.append(EdIntegration)
if "claps" in active_services:
integrations.append(ClapIntegration)
if "emojify" in active_services:
integrations.append(EmojiIntegration)
if "golinks" in active_services:
integrations.append(GoLinkIntegration)
if "groups" in active_services:
integrations.append(GroupIntegration)
if "prlinks" in active_services:
integrations.append(PRLinkIntegration)
if "issues" in active_services:
integrations.append(IssueIntegration)
if "appsprlinks" in active_services:
integrations.append(AppsPRLinkIntegration)
if "build" in active_services:
integrations.append(BuildIntegration)
if "lgtm" in active_services:
integrations.append(LGTMIntegration)
combined_integration = combine_integrations(integrations)(
event["text"], token if token is not UNABLE else None, team_id, event
)
if combined_integration.responses:
for response in combined_integration.responses:
requests.post(
"https://slack.com/api/chat.postMessage",
json={
"channel": event["channel"],
**(
{"thread_ts": event["thread_ts"]}
if "thread_ts" in event
else {}
),
"text": response,
},
headers={"Authorization": "Bearer {}".format(bot_token)},
)
if (
combined_integration.message != event["text"]
or combined_integration.attachments
):
if token is not UNABLE:
resp = requests.post(
"https://slack.com/api/chat.update",
json={
"channel": event["channel"],
"ts": event["ts"],
"as_user": True,
"text": combined_integration.message,
"attachments": combined_integration.attachments,
},
headers={"Authorization": "Bearer {}".format(token)},
).json()
if not resp["ok"] and resp["error"] in {
"invalid_auth",
"token_revoked",
"account_inactive",
"missing_scope",
}:
# token available, but no permissions
token = UNABLE
if token is UNABLE or "slack_force" in event["text"]:
requests.post(
"https://slack.com/api/chat.postEphemeral",
json={
"blocks": make_promo_block(combined_integration.message),
"attachments": [],
"channel": event["channel"],
"user": event["user"],
**(
{"thread_ts": event["thread_ts"]}
if "thread_ts" in event
else {}
),
"username": "61A Slackbot",
},
headers={"Authorization": "Bearer {}".format(bot_token)},
).json()
except Exception as e:
print("".join(traceback.TracebackException.from_exception(e).format()))
finally:
if "challenge" in d:
return d["challenge"]
return ""
<file_sep>/examtool/examtool/api/render_pdf_export.py
from fpdf import FPDF
from examtool.api.assemble_export import AssembledExam, OptionQuestion, TextQuestion
def render_pdf_exam(assembled_exam: AssembledExam):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Courier", size=16)
pdf.multi_cell(200, 20, txt=assembled_exam.exam, align="L")
pdf.multi_cell(
200,
20,
txt=assembled_exam.name.encode("latin-1", "replace").decode("latin-1"),
align="L",
)
pdf.multi_cell(
200,
20,
txt=assembled_exam.sid.encode("latin-1", "replace").decode("latin-1"),
align="L",
)
pdf.set_font("Courier", size=9)
def out(text):
pdf.multi_cell(
200,
5,
txt=text.encode("latin-1", "replace").decode("latin-1"),
align="L",
)
for question in assembled_exam.questions:
pdf.add_page()
out("\nQUESTION")
for line in question.prompt.text.split("\n"):
out(line)
out("\nANSWER")
if isinstance(question, OptionQuestion):
for option in question.options:
if option in question.selected:
out("[X] " + option.text)
else:
out("[ ] " + option.text)
elif isinstance(question, TextQuestion):
for line in question.response.split("\n"):
out(line)
else:
assert False, f"Unknown question type {type(question)}"
out("\nAUTOGRADER")
out(question.autograde_output)
return pdf
<file_sep>/cats/src/OpeningDialog.js
import React from "react";
import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import "./OpeningDialog.css";
import { Mode } from "./App.js";
export default function OpeningDialog(props) {
const setMode = (mode) => () => {
props.setMode(mode);
};
return (
<Modal
size="sm"
aria-labelledby="contained-modal-title-vcenter"
centered
show={props.show}
>
<Modal.Header>
<Modal.Title>Welcome!</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Welcome to the 61A Typing Test!</p>
<p>Select a mode below to begin.</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={setMode(Mode.SINGLE)} variant="primary">
Single Player
</Button>
<Button onClick={setMode(Mode.WAITING)} variant="warning">
Multiplayer
</Button>
</Modal.Footer>
</Modal>
);
}
<file_sep>/buildtool/buildtool/build_coordinator.py
from threading import Thread
from typing import List
from build_worker import worker
from monitoring import create_status_monitor
from state import BuildState
from utils import BuildException
def run_build(
build_state: BuildState, targets: List[str], num_threads: int, quiet: bool
):
build_state.status_monitor = create_status_monitor(num_threads, quiet)
for target in targets:
root_rule = build_state.target_rule_lookup.try_lookup(
target
) or build_state.target_rule_lookup.lookup(build_state, ":" + target)
build_state.scheduled_but_not_ready.add(root_rule)
build_state.work_queue.put(root_rule)
build_state.status_monitor.move(total=1)
thread_instances = []
for i in range(num_threads):
thread = Thread(target=worker, args=(build_state, i), daemon=True)
thread_instances.append(thread)
thread.start()
build_state.work_queue.join()
if build_state.failure is not None:
raise build_state.failure
for _ in range(num_threads):
build_state.work_queue.put(None)
for thread in thread_instances:
thread.join()
build_state.status_monitor.stop()
if build_state.scheduled_but_not_ready:
# there is a dependency cycle somewhere!
for root_rule in targets:
if root_rule in build_state.scheduled_but_not_ready:
break
else:
raise BuildException("An internal error occurred.")
chain = []
pos = root_rule
while True:
if pos in chain:
chain.append(pos)
raise BuildException(
f"Circular dependency detected: Rule {pos} depends on itself "
f"through the path: {' -> '.join(map(str, chain))}"
)
else:
chain.append(pos)
pos = next(iter(pos.pending_rule_dependencies))
<file_sep>/cats/src/utils.js
import { useEffect, useRef } from "react";
export const getCurrTime = () => new Date().getTime() / 1000;
export const formatNum = (num) => (num ? num.toFixed(1) : "None");
export function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// eslint-disable-next-line consistent-return
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
// https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
export function randomString(len) {
const charSet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let out = "";
for (let i = 0; i < len; i++) {
const randomPoz = Math.floor(Math.random() * charSet.length);
out += charSet.substring(randomPoz, randomPoz + 1);
}
return out;
}
<file_sep>/code/src/web-server/requirements.txt
black
flask
gunicorn
braceexpand
flask-cors
lark-parser
-r common/requirements.txt
<file_sep>/index.md
# `cs61a-apps`
Welcome to the CS 61A docs! This wiki contains documentation for all
of our apps, which you can peruse through in the Github repo. It also
contains information about how various software works and how you can
contribute to it. We plan on including installation guides so that you
can use these tools in your own courses.
```{warning}
This is a work in progress, so please bear with us while we put it together!
```
```{toctree}
:hidden:
:maxdepth: 3
:caption: Meta
docs/contributors
docs/license
GitHub Repository <https://github.com/Cal-CS-61A-Staff/cs61a-apps>
```
```{toctree}
:hidden:
:maxdepth: 3
:caption: Utilities
common/index
hog-calc/index
logs/index
partnermatcher/index
paste/index
secrets/index
```
```{toctree}
:hidden:
:maxdepth: 3
:caption: Examtool
examtool/index
exam-write/index
```
```{toctree}
:hidden:
:maxdepth: 3
:caption: Apps
ag-master/index
auth/index
buildserver/index
Buildtool <buildtool/index>
cats/index
61A Code <code/index>
docs/index
domains/index
grade-display/index
hog-contest/index
hosted/index
howamidoing/index
oh/index
shortlinks/index
Piazza OnCall <piazzaoncall/index>
SICP <sicp/index>
```
<file_sep>/sicp/sicp/rpc.py
import os
from common.rpc.auth_utils import set_token_path
set_token_path(f"{os.path.expanduser('~')}/.sicp_token")
from common.rpc import auth
from common.rpc import buildserver
from common.rpc import domains
from common.rpc import hosted
from common.rpc import howamidoing
from common.rpc import indexer
from common.rpc import mail
from common.rpc import oh
from common.rpc import paste
from common.rpc import sandbox
from common.rpc import search
from common.rpc import secrets
from common.rpc import sections
from common.rpc import slack
from common.rpc import ag_master
from common.rpc import ag_worker
<file_sep>/oh/oh_queue/static/js/components/admin_slack_manager.js
function AdminSlackManager({ state: { config } }) {
return (
<React.Fragment>
<div className="table-responsive">
<table className="table table-hover">
<thead>
<tr>
<th>Option</th>
<th className="col-md-3">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Should the queue send a Slack notification when the queue is
long?
</td>
<td className="col-md-3">
<ConfigLinkedToggle
config={config}
configKey="slack_notif_long_queue"
/>
</td>
</tr>
<tr>
<td>
Should the queue send a Slack notification summarizing daily
appointments?
</td>
<td className="col-md-1">
<ConfigLinkedToggle
config={config}
configKey="slack_notif_appt_summary"
/>
</td>
</tr>
<tr>
<td>
Should the queue send a Slack notification if an appointment is
missed?
</td>
<td className="col-md-1">
<ConfigLinkedToggle
config={config}
configKey="slack_notif_missed_appt"
/>
</td>
</tr>
</tbody>
</table>
<p>
To setup Slack, visit{" "}
<a href="https://auth.apps.cs61a.org" target="_blank">
Auth
</a>{" "}
and register a Slack channel with the purpose <code>oh-queue</code>.
Then check that it works!
</p>
<p>
<button
className="btn btn-primary"
onClick={() => app.makeRequest("test_slack")}
>
Send a test message
</button>
<button
style={{ "margin-left": 5 }}
className="btn btn-warning"
onClick={() => app.makeRequest("appointment_summary")}
>
Send daily appointment summary
</button>
</p>
</div>
</React.Fragment>
);
}
<file_sep>/grade-display/okpy_export.py
import requests, auth, sys
from common.rpc.auth import get_endpoint
def export():
OK_SERVER = "https://okpy.org"
ENDPOINT = f"/api/v3/course/{get_endpoint(course='cs61a')}/grades"
FILE_PATH = "data/okpy_grades.csv"
access_token = auth.get_token()
print("Getting grades...")
grades = requests.get(
OK_SERVER + ENDPOINT, params={"access_token": access_token}
).json()
if "grades" in grades["data"]:
grades = grades["data"]["grades"]
else:
print(grades["message"])
sys.exit(1)
print("Saving grades...")
with open(FILE_PATH, "w") as f:
f.write(grades)
print("Done.")
<file_sep>/oh/oh_queue/static/js/components/slot.js
function Slot({ children, badgeText, onClick, className = "", link }) {
if (link) {
return (
<a
href="#"
className={"list-group-item slot-add-button" + className}
onClick={onClick}
>
{!!badgeText && <span className="badge">{badgeText}</span>}
{children}
</a>
);
} else {
return (
<li className={"list-group-item " + className}>
{!!badgeText && <span className="badge">{badgeText}</span>}
{children}
</li>
);
}
}
<file_sep>/oh/migrations/versions/c2365b4ad424_support_configurable_party_mode_names.py
"""support configurable party mode names
Revision ID: <KEY>
Revises: f427b9253aff
Create Date: 2021-01-13 05:57:35.023733
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "f427b9253aff"
from sqlalchemy import orm
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="party_name",
value="Party",
public=True,
course=course[0],
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
<file_sep>/buildserver/service_management.py
import json
from dataclasses import dataclass
from time import sleep
from typing import List
from urllib.parse import urlparse
import requests
from app_config import App, CLOUD_RUN_DEPLOY_TYPES, NO_PR_BUILD_DEPLOY_TYPES
from common.db import connect_db
from common.rpc.auth import post_slack_message
from common.rpc.hosted import delete, list_apps, create_pr_subdomain
from common.rpc.secrets import get_secret
from common.shell_utils import sh
from conf import STATIC_SERVER
from deploy import gen_service_name
class Hostname:
def to_str(self) -> str:
raise NotImplemented
@dataclass
class PyPIHostname(Hostname):
package: str
version: str
def to_str(self):
return f"pypi.org/project/{self.package}/{self.version}"
@dataclass
class PRHostname(Hostname):
app_name: str
pr_number: int
target_hostname: str
def to_str(self):
return f"{self.pr_number}.{self.app_name}.pr.cs61a.org"
def delete_unused_services(pr_number: int = None):
services = json.loads(
sh(
"gcloud",
"run",
"services",
"list",
"--platform",
"managed",
"--region",
"us-west1",
"--format",
"json",
"-q",
capture_output=True,
)
)
with connect_db() as db:
if pr_number is None:
active_services = db("SELECT app, pr_number FROM services", []).fetchall()
else:
active_services = db(
"SELECT app, pr_number FROM services WHERE pr_number != %s", [pr_number]
).fetchall()
active_service_names = set(
gen_service_name(app, pr_number) for app, pr_number in active_services
)
for service in services:
if service["metadata"]["name"] not in active_service_names:
if "pr" not in service["metadata"]["name"]:
post_slack_message(
course="cs61a",
message=f"<!channel> Service `{service['metadata']['name']}` was not detected in master, and the "
"buildserver attepted to delete it. For safety reasons, the buildserver will not delete "
"a production service. Please visit the Cloud Run console and shut the service down "
"manually, or review the most recent push to master if you believe that something has "
"gone wrong.",
purpose="infra",
)
else:
sh(
"gcloud",
"run",
"services",
"delete",
service["metadata"]["name"],
"--platform",
"managed",
"--region",
"us-west1",
"-q",
)
services = list_apps()
for service in services:
if service not in active_service_names:
delete(name=service)
if pr_number is not None:
with connect_db() as db:
db("DELETE FROM services WHERE pr_number=%s", [pr_number])
def update_service_routes(apps: List[App], pr_number: int):
if pr_number == 0:
return # no updates needed for deploys to master
for app in apps:
for hostname in get_pr_subdomains(app, pr_number):
if isinstance(hostname, PRHostname):
create_pr_subdomain(
app=hostname.app_name,
pr_number=hostname.pr_number,
pr_host=hostname.target_hostname,
)
def get_pr_subdomains(app: App, pr_number: int) -> List[Hostname]:
services = json.loads(
sh(
"gcloud",
"run",
"services",
"list",
"--platform",
"managed",
"--format",
"json",
capture_output=True,
)
)
def get_hostname(service_name):
for service in services:
if service["metadata"]["name"] == service_name:
return urlparse(service["status"]["address"]["url"]).netloc
return None
out = []
if app.config["deploy_type"] in CLOUD_RUN_DEPLOY_TYPES:
hostname = get_hostname(gen_service_name(app.name, pr_number))
assert hostname is not None
for pr_consumer in app.config["pr_consumers"]:
out.append(PRHostname(pr_consumer, pr_number, hostname))
elif app.config["deploy_type"] == "static":
for consumer in app.config["static_consumers"]:
hostname = get_hostname(gen_service_name(consumer, pr_number))
if hostname is None:
# consumer does not have a PR build, point to master build
hostname = get_hostname(gen_service_name(consumer, 0))
assert hostname is not None, "Invalid static resource consumer service"
out.append(PRHostname(consumer, pr_number, hostname))
if not app.config["static_consumers"]:
out.append(
PRHostname(
app.name,
pr_number,
get_hostname(gen_service_name(STATIC_SERVER, 0)),
)
)
elif app.config["deploy_type"] == "hosted":
for pr_consumer in app.config["pr_consumers"]:
out.append(
PRHostname(
pr_consumer,
pr_number,
f"{gen_service_name(app.name, pr_number)}.hosted.cs61a.org",
)
)
elif app.config["deploy_type"] == "pypi":
out.append(PyPIHostname(app.config["package_name"], app.deployed_pypi_version))
elif app.config["deploy_type"] in NO_PR_BUILD_DEPLOY_TYPES:
pass
else:
assert False, "Unknown deploy type, failed to create PR domains"
return out
<file_sep>/hog/src/ResetButton.js
// @flow
import React from "react";
import Button from "react-bootstrap/Button";
export default function ResetButton({ onClick }: { onClick: () => mixed }) {
return (
<Button variant="secondary" onClick={onClick}>
New Game
</Button>
);
}
<file_sep>/hog/server/main.py
from gui_files.common_server import start
from hog_gui import DEFAULT_SERVER, GUI_FOLDER, PORT
app = start(PORT, DEFAULT_SERVER, GUI_FOLDER)
if __name__ == "__main__":
app.run()
<file_sep>/oh/oh_queue/static/js/components/staff_online_setup.js
function StaffOnlineSetup({ state }) {
if (!state.currentUser || !state.currentUser.isStaff) {
return <NotFound />;
}
const submit = (e) => {
e.preventDefault();
const form = $("#staff-online-setup-form");
const formData = {};
form.serializeArray().forEach((input) => {
formData[input.name] = input.value;
});
const btn = $("#submitBtn");
btn.addClass("is-loading");
btn.attr("disabled", true);
const time = Date.now();
app.makeRequest("update_staff_online_setup", formData, (isSuccess) => {
setTimeout(() => {
btn.removeClass("is-loading");
btn.attr("disabled", false);
}, 250 - (Date.now() - time));
});
};
return (
<div>
<Navbar state={state} mode="online_setup" />
<OfflineIndicator offline={state.offline && state.loaded} />
<div className="container">
<br />
<p>
Consider using <a href="https://meet.google.com">Google Meet</a> to
host video calls, and <a href="https://code.cs61a.org">61A Code</a>{" "}
for a collaborative code editor.
</p>
<form id="staff-online-setup-form">
<div className="form-group">
<label htmlFor="staff-call-link">
Your Default Video Call Link
</label>
<input
type="text"
className="form-control"
id="staff-call-link"
name="staff-call-link"
placeholder="meet.google.com/xyz"
defaultValue={state.currentUser.call_url}
/>
</div>
<div className="form-group">
<label htmlFor="staff-doc-link">
Your Default Shared Document Link
</label>
<input
type="text"
className="form-control"
id="staff-doc-link"
name="staff-doc-link"
placeholder="code.cs61a.org/xyz"
defaultValue={state.currentUser.doc_url}
/>
</div>
<button
id="submitBtn"
type="submit"
className="btn btn-default"
onClick={submit}
>
Submit
</button>
</form>
</div>
</div>
);
}
<file_sep>/oh/oh_queue/static/js/components/my_assigned_tickets.js
function MyAssignedTickets({ state, tickets }) {
return (
!!tickets.length && (
<div>
<div className="assigned-tickets-header">Your Assigned Tickets</div>
{tickets.map((ticket) => (
<Ticket key={ticket.id} state={state} ticket={ticket} independent />
))}
</div>
)
);
}
<file_sep>/hosted/requirements.txt
certbot-dns-google==1.10.1
docker-dna==0.6.5
Flask==1.1.2
gunicorn==20.0.4
-r common/requirements.txt
<file_sep>/cats/src/Prompt.js
import React from "react";
import "./Prompt.css";
import Character from "./Character.js";
export default function Prompt(props) {
const { promptedWords } = props;
const { typedWords } = props;
const { currWord } = props;
const words = [];
let pastEnd = false;
for (let i = 0; i !== promptedWords.length; ++i) {
const promptedWord = promptedWords[i];
const typedWord = typedWords[i];
if (typedWord) {
const correct = promptedWord === typedWord;
for (const char of promptedWord) {
words.push(
<Character
key={words.length}
char={char}
correct={correct}
wrong={!correct}
/>
);
}
words.push(<Character key={words.length} char=" " />);
} else if (!pastEnd) {
for (let j = 0; j !== promptedWord.length; ++j) {
const correct = currWord[j] && promptedWord[j] === currWord[j];
const wrong = currWord[j] && promptedWord[j] !== currWord[j];
words.push(
<Character
key={words.length}
char={promptedWord[j]}
correct={correct}
wrong={wrong}
/>
);
}
words.push(<Character key={words.length} char=" " />);
pastEnd = true;
} else {
for (const char of promptedWord) {
words.push(<Character key={words.length} char={char} />);
}
words.push(<Character key={words.length} char=" " />);
}
}
return (
<div className="PromptBox">
Look at the following words:
<div className="Prompt">{words}</div>
</div>
);
}
<file_sep>/oh/oh_queue/static/js/components/admin_party_manager.js
function AdminPartyManager({ state }) {
return (
<React.Fragment>
<AdminOptionsManager>
<tr>
<td>What should {state.config.party_name} mode be called?</td>
<td className="col-md-1">
<ConfigLinkedText config={state.config} configKey="party_name" />
</td>
</tr>
<tr>
<td>
Should students be able to create and join {state.config.party_name}{" "}
groups?
</td>
<td className="col-md-1">
<ConfigLinkedToggle
config={state.config}
configKey="party_enabled"
/>
</td>
</tr>
<tr>
<td>
Should students be able to create individual tickets while{" "}
{state.config.party_name} mode is enabled?
</td>
<td className="col-md-1">
<ConfigLinkedToggle
config={state.config}
configKey="allow_private_party_tickets"
/>
</td>
</tr>
</AdminOptionsManager>
</React.Fragment>
);
}
<file_sep>/examtool/examtool/api/render_html_export.py
from contextlib import contextmanager
from html import escape
import pdfkit
from examtool.api.assemble_export import AssembledExam, OptionQuestion, TextQuestion
from examtool.api.utils import rel_path
def render_html_exam(assembled_exam: AssembledExam):
blocks = []
def out(text):
blocks.append(text.replace("โ", '"').replace("โ", '"').replace("โ", "'"))
def user_out(text):
out(escape(text))
def tag(name):
@contextmanager
def with_tag(**attrs):
out(f"<{name}")
for k, v in attrs.items():
if k == "className":
k = "class"
if not v:
continue
out(" ")
out(k)
out("=")
out(repr(str(v)))
out(">")
yield
out(f"</{name}>")
return with_tag
h3 = tag("h3")
div = tag("div")
label = tag("label")
input = tag("input")
pre = tag("pre")
for question in assembled_exam.questions:
with div(className="question"):
with h3():
out(question.name)
with div(className="questionText"):
out(question.prompt.html)
with div(className="gradable"):
with div(className="answer"):
if isinstance(question, OptionQuestion):
for option in question.options:
with div(className="checkbox"), label(), input(
type="checkbox", checked=option in question.selected
):
out(option.html)
elif isinstance(question, TextQuestion):
with div(className="response"):
with pre(style=f"height: {question.height * 3}em"):
user_out(question.response)
else:
assert False, f"Unknown question type {type(question)}"
with pre(className="autogradeOutput"):
user_out(question.autograde_output)
def export(target):
pdfkit.from_string(
"".join(blocks),
target,
options={
"log-level": "none",
"disable-smart-shrinking": None,
"zoom": 0.75,
},
css=rel_path("css/style.css"),
)
return export
<file_sep>/sandbox/main.py
import subprocess, os, socket, sys
import time, glob, pathlib
from utils import Server, Location
from common.shell_utils import sh
from common.rpc.secrets import get_secret
from utils import get_server_pid, get_active_servers
HOSTNAME = "cs61a.org"
NGINX_PORT = os.environ.get("PORT", "8001")
def main():
"""Start the Sandbox and IDE servers."""
print("Starting NGINX...", file=sys.stderr)
sh("nginx")
print("Starting sandbox...", file=sys.stderr)
sandbox_port = get_open_port()
sb = subprocess.Popen(
["gunicorn", "-b", f":{sandbox_port}", "-w", "4", "sandbox:app", "-t", "3000"],
env=os.environ,
)
proxy(f"sb.{HOSTNAME} *.sb.{HOSTNAME}", sandbox_port, f"sb.{HOSTNAME}")
proxy(f"*.sb.pr.{HOSTNAME}", sandbox_port, f"sb.pr.{HOSTNAME}")
print("Starting IDE...", file=sys.stderr)
ide_port = get_open_port()
ide = subprocess.Popen(
["gunicorn", "-b", f":{ide_port}", "-w", "4", "ide:app", "-t", "3000"],
env=os.environ,
)
proxy(f"ide.{HOSTNAME}", ide_port, f"ide.{HOSTNAME}")
proxy(f"*.ide.pr.{HOSTNAME}", ide_port, f"ide.pr.{HOSTNAME}")
print("Writing NGINX default config...", file=sys.stderr)
with open(f"/etc/nginx/sites-enabled/default", "w") as f:
f.write(
DEFAULT_SERVER.format(
ide_port=ide_port, sb_port=sandbox_port, nginx_port=NGINX_PORT
)
)
sh("nginx", "-s", "reload")
if not os.path.exists("/save/root/berkeley-cs61a"):
print("Cloning good copy of 61A repo...", file=sys.stderr)
sh(
"git",
"clone",
f"https://{get_secret(secret_name='GITHUB_IDE_TOKEN')}@github.com/Cal-CS-61A-Staff/berkeley-cs61a",
"/save/root/berkeley-cs61a",
)
print("Checking out latest good copy commit..", file=sys.stderr)
sh("git", "pull", cwd="/save/root/berkeley-cs61a")
print("Ready.", file=sys.stderr)
while True:
servers = get_active_servers()
now = time.time()
for server in servers:
heartbeat = pathlib.Path(
f"/save/{server}/.local/share/code-server/heartbeat"
)
last_beat = heartbeat.stat().st_mtime
if now - last_beat > 900:
pid = get_server_pid(server)
print(f"Killing {server} for idling...", file=sys.stderr)
sh("kill", pid.decode("utf-8")[:-1])
print(f"Killed.", file=sys.stderr)
print("Cleanup complete. Sleeping for 900 seconds...", file=sys.stderr)
time.sleep(900)
def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port
def proxy(domain, port, fn):
conf = Server(
Location(
"/",
include="proxy_params",
proxy_pass=f"http://127.0.0.1:{port}",
),
listen=NGINX_PORT,
server_name=domain,
)
with open(f"/etc/nginx/sites-enabled/{fn}", "w") as f:
f.write(str(conf))
DEFAULT_SERVER = """
server {{
location / {{
include proxy_params;
if ($http_x_forwarded_for_host ~ "^(.*)ide.(pr.)?cs61a.org(.*)") {{
proxy_pass http://127.0.0.1:{ide_port};
}}
if ($http_x_forwarded_for_host ~ "^(.*)sb.(pr.)?cs61a.org(.*)") {{
proxy_pass http://127.0.0.1:{sb_port};
}}
}}
listen {nginx_port} default_server;
server_name _;
}}
"""
if __name__ == "__main__":
main()
<file_sep>/common/rpc/domains.py
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/add_domain")
def add_domain(*, course: str, domain: str):
...
<file_sep>/domains/README.md
# Domains Tool
This app registers and hosts a new domain automatically, adding the new domain
to the `hosted_apps` table.
<file_sep>/oh/oh_queue/static/js/components/group_card.js
function GroupCard({ group, state }: { group: Group, state: State }) {
const { Link } = ReactRouterDOM;
let panelColor = "panel-default";
const inGroup = groupIsMine(state, group);
if (inGroup) {
panelColor = "panel-primary";
} else {
panelColor = "panel-default";
}
const panelClass = classNames({
panel: true,
[panelColor]: true,
});
const ownerName = group.attendees[0].user.shortName;
const joinText =
group.attendees.length === 1
? `Join ${ownerName}!`
: `Join ${ownerName} and ${group.attendees.length - 1} others!`;
const joinGroup = () => {
const join = () => app.makeRequest("join_group", group.id, true);
const ticket = getMyTicket(state);
if (ticket && ticket.group_id) {
Swal.fire({
title: "Are you sure?",
text:
"You have created a ticket for your previous group. If you switch groups," +
" that ticket will be deleted",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, do it!",
}).then((result) => {
if (result.value) {
join();
}
});
} else {
join();
}
};
return (
<div className={panelClass}>
<div className="panel-heading">
{state.assignments[group.assignment_id].name}{" "}
{ticketQuestion(state, group)} ·{" "}
{state.locations[group.location_id].name}
<div className="btn-group" role="group" style={{ float: "right" }}>
{isStaff(state) && (
<button
type="button"
className="btn btn-xs btn-default"
onClick={() => app.makeRequest("delete_group", group.id)}
>
<span className="glyphicon glyphicon-trash" aria-hidden="true" />
</button>
)}
</div>
</div>
<div className="panel-body">
{inGroup ? (
<p>
<b>You are in this group.</b>
</p>
) : (
<p>
{state.currentUser ? ownerName : "A student"} is looking to
collaborate!
</p>
)}
{group.description ? (
<blockquote style={{ fontSize: 15 }}>{group.description}</blockquote>
) : (
<p>
<i>No description</i>
</p>
)}
<p>Created {ticketTimeAgo(group)}.</p>
{state.currentUser && (
<Link to={inGroup ? `groups/${group.id}` : null}>
<button
className={inGroup ? "btn btn-primary" : "btn btn-default"}
type="button"
onClick={inGroup ? null : joinGroup}
>
{inGroup ? "Return to group" : joinText}
</button>
</Link>
)}
</div>
</div>
);
}
<file_sep>/oh/migrations/versions/1f54dee7ae76_add_simul_appointment_limit.py
"""add simul appointment limit
Revision ID: 1f54dee7ae76
Revises: c2f835ce68a7
Create Date: 2020-03-12 23:45:37.468475
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "1f54dee7ae76"
down_revision = "c2f835ce68a7"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="simul_appointment_limit", value="1", public=True, course=course[0]
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
<file_sep>/buildtool/buildtool/__init__.py
import sys
import pathlib
from typing import Callable, Optional, Sequence, Union
sys.path.append(str(pathlib.Path(__file__).parent.absolute()))
"""
Below are some stubs to make imports in BUILD and rules.py files more pleasant
see loader.py for injected implementation
"""
def load(path: str):
...
def callback(
*,
name: Optional[str] = None,
deps: Sequence[str] = (),
impl: Callable,
out: Union[str, Sequence[str]] = (),
):
...
def find(path: str, unsafe_ignore_extension=False):
...
<file_sep>/conf.py
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath("."))
# -- Project information -----------------------------------------------------
project = "cs61a-apps"
copyright = "2021 CS 61A"
author = "CS 61A"
myst_substitutions = {"docs_in_charge": "Vanshaj"}
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.viewcode",
"sphinx.ext.intersphinx",
"sphinx.ext.extlinks",
"sphinxcontrib.openapi",
"myst_parser",
]
myst_enable_extensions = [
"linkify",
"substitution",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [
"_build",
"Thumbs.db",
".DS_Store",
"**env",
"**/*common*",
"**/node_modules",
]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "furo"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# Set a custom page title.
html_title = "cs61a-apps"
# Allow Markdown files to be parsed using myst.
source_suffix = [".rst", ".md"]
# -- Options for autodoc -----------------------------------------------------
# Do not import the following libraries, just pretend like they exist.
autodoc_mock_imports = [
"colorama",
"cachetools",
"sqlalchemy",
"flask",
"flask_oauthlib",
"flask_sqlalchemy",
"werkzeug",
"models",
"utils",
"google",
"setup_functions",
"process_input",
"runner",
"dna",
"networkx",
"pandas",
"tournament",
"logger",
"thread_utils",
]
# Use the following structure to shorten URL targets.
extlinks = {"repo": ("https://github.com/Cal-CS-61A-Staff/tree/master/%s", "repo ")}
# Link to parts of other software documentation, if needed.
intersphinx_mapping = {
"flask": ("https://flask.palletsprojects.com/en/1.1.x", None),
"flask_oauthlib": ("https://flask-oauthlib.readthedocs.io/en/latest", None),
"python": ("https://docs.python.org/3", None),
"pandas": ("https://pandas.pydata.org/docs", None),
}
# Change the order in which autodoc renders members of a file/class.
autodoc_member_order = "bysource"
<file_sep>/howamidoing/src/BinSelector.js
import React from "react";
export default function BinSelector({ children, toggled, onToggle }) {
const className = toggled ? "btn btn-secondary" : "btn btn-outline-secondary";
return (
<button type="button" className={className} onClick={onToggle}>
{children}
</button>
);
}
<file_sep>/ok-help/src/Category.js
import React from "react";
import "./Category.css";
import CheckBox from "./CheckBox.js";
import ValueField from "./ValueField.js";
export default function Category(props) {
const checkBoxes = props.category.optionalArgs.map((arg, index) => {
if (arg.isValue) {
return (
<ValueField
field={arg}
key={index}
onChange={(val) => props.setOption(arg.longForm, val)}
/>
);
} else {
return (
<CheckBox
flag={arg}
key={index}
onChange={(val) => props.setOption(arg.longForm, val)}
/>
);
}
});
const className = `Category ${props.active ? "activated" : "deactivated"}`;
return (
<div className="col-lg-3">
<div className={className} onClick={props.onClick}>
<h3>{props.category.name}</h3>
<div className="text-muted">{props.category.explanation}</div>
<div>{checkBoxes}</div>
</div>
</div>
);
}
<file_sep>/hog/src/RollingDice.js
// @flow
import React, { useState } from "react";
import DiceResults from "./DiceResults";
import { useInterval } from "./utils";
export default function RollingDice({ numRolls }: { numRolls: number }) {
const randomRolls = () =>
Array(numRolls)
.fill()
.map(() => Math.floor(Math.random() * 6) + 1);
const [rolls, setRolls] = useState(randomRolls);
useInterval(() => {
setRolls(randomRolls);
}, 200);
return <DiceResults rolls={rolls} />;
}
<file_sep>/buildtool/buildtool/cache.py
import hashlib
import os
import traceback
from os.path import dirname
from pathlib import Path
from typing import Iterator
from fs_utils import copy_helper, hash_file
from google.cloud.exceptions import NotFound
from google.cloud.storage import Blob
from state import Rule
from utils import BuildException, CacheMiss
CLOUD_BUCKET_PREFIX = "gs://"
AUX_CACHE = ".aux_cache"
STATS = dict(hits=0, misses=0, inserts=0)
def get_bucket(cache_directory: str):
if cache_directory.startswith(CLOUD_BUCKET_PREFIX):
from google.cloud import storage
client = storage.Client()
return client.bucket(cache_directory[len(CLOUD_BUCKET_PREFIX) :])
def make_cache_fetcher(cache_directory: str, *, is_aux=False):
bucket = get_bucket(cache_directory)
delta = 1 if not is_aux else 0
def cache_fetcher(state: str, target: str) -> str:
if bucket:
try:
out = aux_fetcher(state, target)
STATS["hits"] += delta
return out
except CacheMiss:
dest = str(Path(state).joinpath(target))
try:
out = bucket.blob(dest).download_as_string().decode("utf-8")
STATS["hits"] += delta
except NotFound:
STATS["misses"] += delta
raise CacheMiss
else:
# cache it on disk
aux_memorize(state, target, out)
return out
else:
dest = Path(cache_directory).joinpath(state).joinpath(target)
try:
with open(dest, "r") as f:
out = f.read()
STATS["hits"] += delta
return out
except FileNotFoundError:
STATS["misses"] += delta
raise CacheMiss
def cache_loader(cache_key: str, rule: Rule, dest_root: str) -> bool:
cache_location, cache_paths = get_cache_output_paths(
cache_directory, rule, cache_key
)
if bucket:
del cache_location
if not aux_loader(cache_key, rule, dest_root):
try:
cache_fetcher(cache_key, ".touch")
except CacheMiss:
STATS["misses"] += delta
return False
for src_name, cache_path in zip(rule.outputs, cache_paths):
cache_path = str(Path(cache_key).joinpath(cache_path))
os.makedirs(dest_root, exist_ok=True)
try:
if src_name.endswith("/"):
os.makedirs(
Path(dest_root).joinpath(src_name), exist_ok=True
)
blobs: Iterator[Blob] = list(
bucket.list_blobs(prefix=cache_path)
)
for blob in blobs:
target = str(
Path(dest_root)
.joinpath(src_name)
.joinpath(blob.name[len(cache_path) + 1 :])
)
os.makedirs(dirname(target), exist_ok=True)
blob.download_to_filename(target)
STATS["hits"] += delta
else:
target = str(Path(dest_root).joinpath(src_name))
os.makedirs(dirname(target), exist_ok=True)
bucket.blob(cache_path).download_to_filename(target)
STATS["hits"] += delta
except NotFound:
STATS["misses"] += delta
return False
# now that we have fetched, let's cache it on disk
aux_save(cache_key, rule, dest_root)
return True
else:
if not os.path.exists(cache_location):
STATS["misses"] += delta
return False
try:
copy_helper(
src_root=cache_location,
src_names=cache_paths,
dest_root=dest_root,
dest_names=rule.outputs,
)
STATS["hits"] += delta
except FileNotFoundError:
raise BuildException(
"Cache corrupted. This should never happen unless you modified the cache "
"directory manually! If so, delete the cache directory and try again."
)
return True
return cache_fetcher, cache_loader
def make_cache_memorize(cache_directory: str, *, is_aux=False):
bucket = get_bucket(cache_directory)
delta = 1 if not is_aux else 0
def memorize(state: str, target: str, data: str):
if bucket:
try:
prev_saved = aux_fetcher(state, target)
except CacheMiss:
prev_saved = None
aux_memorize(state, target, data)
if prev_saved != data:
STATS["inserts"] += delta
bucket.blob(str(Path(state).joinpath(target))).upload_from_string(data)
else:
cache_target = Path(cache_directory).joinpath(state).joinpath(target)
os.makedirs(os.path.dirname(cache_target), exist_ok=True)
STATS["inserts"] += delta
cache_target.write_text(data)
def save(cache_key: str, rule: Rule, output_root: str):
cache_location, cache_paths = get_cache_output_paths(
cache_directory, rule, cache_key
)
memorize(cache_key, ".touch", "")
if bucket:
del cache_location # just to be safe
for src_name, cache_path in zip(rule.outputs, cache_paths):
if src_name.endswith("/"):
dir_root = Path(output_root).joinpath(src_name)
for path, subdirs, files in os.walk(dir_root):
path = os.path.relpath(path, dir_root)
for name in files:
# output_root -> src_name/ -> [path -> name]
# <cache_base> -> cache_key -> cache_path -> [path -> name]
target = Path(path).joinpath(name)
src_loc = (
Path(output_root).joinpath(src_name).joinpath(target)
)
aux_cache_loc = (
Path(AUX_CACHE)
.joinpath(cache_key)
.joinpath(cache_path)
.joinpath(target)
)
if not os.path.exists(aux_cache_loc) or (
hash_file(src_loc) != hash_file(aux_cache_loc)
):
STATS["inserts"] += delta
bucket.blob(
str(
Path(cache_key)
.joinpath(cache_path)
.joinpath(target)
)
).upload_from_filename(str(src_loc))
else:
# output_root -> src_name
# <cache_base> -> cache_key -> cache_path
target = Path(output_root).joinpath(src_name)
aux_cache_loc = (
Path(AUX_CACHE).joinpath(cache_key).joinpath(cache_path)
)
if not os.path.exists(aux_cache_loc) or (
hash_file(target) != hash_file(aux_cache_loc)
):
STATS["inserts"] += delta
bucket.blob(
str(Path(cache_key).joinpath(cache_path)),
).upload_from_filename(
str(Path(output_root).joinpath(src_name)),
)
aux_save(cache_key, rule, output_root)
else:
STATS["inserts"] += delta
copy_helper(
src_root=output_root,
src_names=rule.outputs,
dest_root=cache_location,
dest_names=cache_paths,
)
return memorize, save
def get_cache_output_paths(cache_directory: str, rule: Rule, cache_key: str):
cache_location = Path(cache_directory).joinpath(cache_key)
keys = [
hashlib.md5(output_path.encode("utf-8")).hexdigest()
for output_path in rule.outputs
]
for i, (output_path, key) in enumerate(zip(rule.outputs, keys)):
if output_path.endswith("/"):
keys[i] += "/"
return cache_location, keys
aux_fetcher, aux_loader = make_cache_fetcher(AUX_CACHE, is_aux=True)
aux_memorize, aux_save = make_cache_memorize(AUX_CACHE, is_aux=True)
<file_sep>/logs/README.md
# `logs`
This app is used to peek at the latest logs for any given app via
logs.cs61a.org (restricted to course admins).
This app has no local setup, because it isn't meant to be run locally.
<file_sep>/oh/migrations/versions/00aea7233ef8_add_chatmessage_description.py
"""Add ChatMessage description
Revision ID: 00aea7233ef8
Revises: <KEY>
Create Date: 2020-09-06 04:35:59.664574
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "5c55d6d588c5"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
from sqlalchemy.dialects import mysql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"chat_message", sa.Column("body", sa.String(length=255), nullable=False)
)
op.alter_column(
"config_entries", "key", existing_type=mysql.VARCHAR(length=255), nullable=False
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column(
"config_entries", "key", existing_type=mysql.VARCHAR(length=255), nullable=True
)
op.drop_column("chat_message", "body")
# ### end Alembic commands ###
<file_sep>/hog-contest/tournament.py
import base64
import json
import queue
from collections import defaultdict
from datetime import datetime
from itertools import product
from threading import Thread
from pytz import timezone
from common.db import connect_db
from logger import log
from runner import score
from thread_utils import only_once
NUM_WORKERS = 4
LOG_MOD = 1
THRESHOLD = 0.500001
last_updated = "the end of the tournament." # "unknown"
def post_tournament():
"""
RANKINGS and WINRATES are nonlocal variables
Connect to the database. Fetch all name and hash pairs from the CACHED_STRATEGIES
table (Call this hash_lookup). Fetch all winrates from CACHED_WINRATES table (call
this db_winrates).
Create a nested defaultdict for the winrate and a defaultdict for num rates.
Create a 2d array from the data in hash loopup, where each data point is a [name, hash]
pair and call this new data structure ACTIVE_TEAMS.
Iterate through db_winrates and add the data into the nested WINRATE_DICT
(data: h0, h1, rate) such that it follows the following convention:
- WINRATE_DICT[h0][h1] = winrate
- WINRATE_DICT[h1][h0] = 1 - winrate
- WINRATE_DICT[h0][h0] = 0.5
- WINRATE_DICT[h1][h1] = 0.5
Have two teams play against each other. If the winrate of team0 agains team1 is
greater that THRESHOLD, then add 1 win to the num_teams dict for team0.
Construct a new array for teams data consisting of [team name decoded, number of wins, and the hash].
Sort the teams by number of wins, and construct a ranking.
Create a 2-d Matrix of WINRATES of each team playing each other.
:return: None
"""
log("Updating website...")
global ranking, winrates
with connect_db() as db:
hash_lookup = db("SELECT name, hash FROM cached_strategies").fetchall()
db_winrates = db(
"SELECT hash_0, hash_1, winrate FROM cached_winrates"
).fetchall()
winrate_dict = defaultdict(lambda: defaultdict(float))
num_wins = defaultdict(int)
active_teams = []
for name, hash in hash_lookup:
active_teams.append([name, hash])
for hash_0, hash_1, winrate in db_winrates:
winrate_dict[hash_0][hash_1] = winrate
winrate_dict[hash_1][hash_0] = 1 - winrate
winrate_dict[hash_0][hash_0] = 0.5
winrate_dict[hash_1][hash_1] = 0.5
for team_0, hash_0 in active_teams:
for team_1, hash_1 in active_teams:
if winrate_dict[hash_0][hash_1] > THRESHOLD:
num_wins[team_0] += 1
teams = []
for name, hash in hash_lookup:
teams.append([base64.b64decode(name).decode("utf-8"), num_wins[name], hash])
teams.sort(key=lambda x: x[1], reverse=True)
ranking = build_ranking(teams)
winrates = []
for _, _, hash_0 in teams:
winrates.append([])
for _, _, hash_1 in teams:
winrates[-1].append(winrate_dict[hash_0][hash_1])
def build_ranking(teams):
"""
Assigns rankings to the teams based on their winrates. If teams are tied,
they will be assigned the same ranking as each other.
:param teams: A list of teams, where each element is a list containing a team's name
and winrate (among potentially other data). This list is already sorted by num wins in descending order.
:type teams: list
:return: List of teams with their rank, name, and number of wins, in ascending order of rank.
"""
out = []
prev_wins = float("inf")
curr_rank = -1
cnt = 0
for name, wins, *_ in teams:
cnt += 1
if wins < prev_wins:
curr_rank += cnt
prev_wins = wins
cnt = 0
out.append([curr_rank, name, wins])
return out
def worker(t_id, q, out, goal):
"""
We get each task from the queue. Score the strategies.
Store the score in the OUT dictionary.
Finish the task.
If the size of our queue is a factor of LOG_MOD, then we log the number of matches completed.
:param t_id: Id number
:type t_id: int
:param q: Queue of tasks
:type q: Queue
:param out: data structure of the storing the score between strategies.
:type out: dictionary
:param goal: Size of the queue of tasks. AKA Number of tasks.
:type goal: int
:return: None
"""
while True:
task = q.get()
if task is None:
break
hash_0, strat_0, hash_1, strat_1 = task
log("Thread {}: Matching {} vs {}".format(t_id, hash_0, hash_1))
out[hash_0, hash_1] = score(strat_0, strat_1)
log("Thread {} finished match.".format(t_id))
q.task_done()
if q.qsize() % LOG_MOD == 0:
log("{} / {} matches complete".format(goal - q.qsize(), goal))
def unwrap(strat):
"""
Return the hash of the strat, and load the strategy from json.
:param strat: data structure containing data pertaining to the strategy.
:type strat: dictionary
:return: tuple of hash and the strategy loaded from json.
"""
return strat["hash"], json.loads(strat["strategy"])
@only_once
def run_tournament():
"""
Connects to database, and fetches data from CACHED_STRATEGIES and CACHED_WINRATES.
Stores the current time as START_TIME.
Store the data from CACHED_WINRATES in a dictionary called WINRATES.
Create a QUEUE for tasks.
Iterate through entry0, entry1 in the Cartesian product of ALL_STRATEGIES and
ALL_STRATEGIES. If hash of entry0 is greater than or equal to the hash of entry1 move
onto the next entry pair. If the tuple of the hashes of entry0 and entry1 are in the
WINRATES dictionary, then add 1 to the NUM_DONE variable, and move onto the next entry pair.
If neither of the former two cases are true, then call unwrap on both of the entries and put
the output of both calls in a list and put this list in the tasks queue.
Create a dictionary called OUT, and a list called THREADS.
Create a THREAD where the target=worker, and pass in the arguments T_ID, the queue of TASKS,
the OUT dictionary, and SIZE of the TASKS queue.
Start each process. Then append to the THREADS list.
Join the TASKS structure.
Add end-of-queue markers to the TASKS structure.
Store the newly computed winrates into the CACHED_WINRATES data table.
Update the LAST_UPDATED time with the START_TIME. Call
the POST_TOURNAMENT function.
"""
global last_updated
with connect_db() as db:
all_strategies = db("SELECT hash, strategy FROM cached_strategies").fetchall()
cached_winrates = db(
"SELECT hash_0, hash_1, winrate FROM cached_winrates"
).fetchall()
start_time = datetime.now().astimezone(timezone("US/Pacific"))
log("Starting tournament with frozen copy of strategies...")
winrates = {}
for hash_0, hash_1, winrate in cached_winrates:
winrates[hash_0, hash_1] = winrate
tasks = queue.Queue()
num_done = 0
for entry_0, entry_1 in product(all_strategies, all_strategies):
if entry_0["hash"] >= entry_1["hash"]:
continue
if (entry_0["hash"], entry_1["hash"]) in winrates:
num_done += 1
continue
tasks.put([*unwrap(entry_0), *unwrap(entry_1)])
num_todo = tasks.qsize()
log(
"{} matches recovered from cache, {} to be recomputed".format(
num_done, num_todo
)
)
out = {} # access is thread-safe since we're always writing to diff. keys
threads = []
for i in range(NUM_WORKERS):
t = Thread(target=worker, args=(i, tasks, out, num_todo))
log("Starting thread {}...".format(i))
t.start()
threads.append(t)
tasks.join()
log("Tournament finished, storing results...")
for i in range(NUM_WORKERS):
tasks.put(None)
with connect_db() as db:
for (hash_0, hash_1), winrate in out.items():
db(
"INSERT INTO cached_winrates VALUES (%s, %s, %s)",
[hash_0, hash_1, winrate],
)
last_updated = start_time
post_tournament()
log("Website updated")
<file_sep>/grade-display/roster_export.py
import requests, auth, sys
from common.rpc.auth import get_endpoint
def export():
OK_SERVER = "https://okpy.org"
ENDPOINT = f"/api/v3/course/{get_endpoint(course='cs61a')}/roster"
FILE_PATH = "data/roster.csv"
access_token = auth.get_token()
print("Getting roster...")
roster = requests.get(
OK_SERVER + ENDPOINT, params={"access_token": access_token}
).json()
if "roster" in roster["data"]:
roster = roster["data"]["roster"]
else:
print(roster["message"])
sys.exit(1)
print("Saving roster...")
with open(FILE_PATH, "w") as f:
f.write(roster)
print("Done.")
<file_sep>/partnermatcher/README.md
# `partnermatcher`
This is an app that is used to calculate the optimal pairings for students
looking for project partners, based on their response to several
partner-matching questions.
## Setup
To use the partner matching script, first create a form for students to fill out
with the following columns:
- Email Address
- What is 8am PT (Berkeley Time) in your time?
- How skillful a programmer do you consider yourself to be at this time?
- Are you taking CS 61A for a letter grade?
- What are three words that describe your interests?
Create a venv and install Python dependencies:
```bash
$ python3 -m venv env
$ env/bin/pip install -r requirements.txt
```
## Running the Script
Once the deadline to fill out the form has passed, export the results to
`partnermatcher/data.csv`. Then, update the spreadsheet location information
on lines 96 and 97. Make sure these sheets are shared with
`<EMAIL>`.
To run the matching script and upload output to Google Sheets, run
`env/bin/python main.py`.<file_sep>/buildserver/rebuilder.py
from time import time
from datetime import timedelta
from common.db import connect_db
from common.jobs import job
from common.rpc.buildserver import deploy_prod_app_sync
AUTO_REBUILDS = {
"website-base": timedelta(hours=1),
"cs170-website": timedelta(hours=1),
}
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS auto_rebuilds (
app varchar(128),
unix integer
)"""
)
def create_rebuilder(app):
@job(app, "rebuilder")
def rebuilder():
now = int(time())
for app, interval in AUTO_REBUILDS.items():
with connect_db() as db:
last_rebuild = db(
"SELECT MAX(unix) FROM auto_rebuilds WHERE app=(%s)", [app]
).fetchone()
if (
not last_rebuild
or not last_rebuild[0]
or now - last_rebuild[0] > interval.total_seconds()
):
db(
"INSERT INTO auto_rebuilds (app, unix) VALUES (%s, %s)",
[app, now],
)
deploy_prod_app_sync(target_app=app, noreply=True)
<file_sep>/cats/src/Indicator.js
import React from "react";
export default function Indicator(props) {
return <div className="Indicator">{props.text}</div>;
}
<file_sep>/examtool/README.md
## Overview
This is the CLI for the 61A `examtool`. To edit the various web apps, see the other `exam-*` folders in the `cs61a-apps` repo.
To install, run `pip install examtool[cli]`. To develop, create a virtualenv and run `pip install -e .[cli]`.
The CLI also requires `wget` and `pdflatex` to be installed and in your PATH.
To deploy exams to the server, you must be registered as an admin for your course at https://auth.apps.cs61a.org.
## Workflow
First, visit https://write.final.cs61a.org to write your exam, following [these instructions](https://github.com/Cal-CS-61A-Staff/cs61a-apps/blob/master/exam-write/README.md). When your exam is ready, export it as a JSON and place the JSON in a folder.
In that folder, run `examtool deploy` and select that JSON along with a roster CSV. When deployed, the exam will be accessible at https://exam.cs61a.org. Roster CSVs must have a header and the columns:
* `Email` - The email of a student
* `Deadline` - The due date of an exam for a particular student expressed as a Unix timestamp
* `No Watermark` - An optional column that is `1` if this student should not receive a watermarked exam (e.g. for DSP accomodations). Defaults to `0` if not specified.
You may wish to send exam PDFs to your students. To do so, run `examtool compile-all` to generate unique encrypted PDFs for each student. When they are all generated, run `examtool send` to email them to your students. Note that compilation requires `pdflatex` and `wget`. Compilation of watermarked PDFs also requires `inkscape`.
After your exam ends, run `examtool download` to download your student submissions as a single CSV and as PDFs to upload to Gradescope. To upload them to Gradescope, run `examtool gradescope-upload`.
To use an experimental autograder, run `gradescope-autograde` to download the exam, create the Gradescope assignment, upload them to Gradescope, add the outline to Gradescope, group all of the submissions, and finally apply grades to the groupings! Note you can use the same command to upload and autograde exams to the same Gradescope assignment, just ensure you use the `update` flag.
If you do not want the exam to be autograded, run `examtool download` to download your student submissions as a single CSV and as PDFs to upload to Gradescope. Use the `--via-html` flag to create formatted PDFs, or `--direct-pdf` to create plaintext PDFs. You must install `wkhtmltopdf` and place it in your PATH to create formatted PDFs.
To upload PDFs to Gradescope, run `examtool gradescope-upload`.
Note that if you ran alternate versions of your exam, it is possible that a student might have taken both versions (say, if they switched from the regular to the alternate version after filling out part of the regular version). To check for such students, run `examtool check-dupes`, and then manually decide which of their submissions should be uploaded to Gradescope.
Run `examtool loginas` to log in as a student and view their exam.
To identify cheating or recover from students losing their Internet connection, run `examtool logs` to see the full submission history of a particular student, or all students in the roster.
Run `examtool save-logs` and then `examtool cheaters` to identify students who have used substituted words that did not occur in their exam, implying that they may be cheaters. Run `examtool identify-watermark` if you have a screenshot of a watermarked exam that you wish to identify. Run `examtool identify-keyword` if you wish to determine which students received exams with a particular keyword.
<file_sep>/buildserver/env.py
GITHUB_BOT_USER = "pusherbot"
<file_sep>/slack/golink_integration.py
import itertools
import re
from collections import namedtuple
from integration import Integration
from utils import OrderedSet
GoLink = namedtuple("GoLink", ["path"])
VALID_PATH = r"[0-9A-Za-z\-]"
PATH_REGEX = r"(?P<path>{}+)".format(VALID_PATH)
REGEX_TEMPLATE = r"<(https?://)?go\.cs61a\.org/{}/?(\|[^\s|]+)?>"
SHORT_REGEX_TEMPLATE = r"go/{}/?"
class GoLinkIntegration(Integration):
def _process(self):
self._golinks = OrderedSet()
for match in itertools.chain(
re.finditer(REGEX_TEMPLATE.format(PATH_REGEX), self._message),
re.finditer(SHORT_REGEX_TEMPLATE.format(PATH_REGEX), self._message),
):
self._golinks.add(GoLink(match.group("path")))
@property
def message(self):
out = self._message
for golink in self._golinks:
out = re.sub(
REGEX_TEMPLATE.format(golink.path), "go/{}".format(golink.path), out
)
out = re.sub(
SHORT_REGEX_TEMPLATE.format(golink.path),
r"<https://go.cs61a.org/{}|go/{}>".format(golink.path, golink.path),
out,
)
return out
<file_sep>/ag-master/README.md
# 61A Autograder
This is the communication layer between Okpy and the 61A Autograder Worker,
which grades students assignments and sends score back to Okpy. The worker code
is kept private for security reasons, but this only affects you if you choose
to use our workers and don't implement your own. If you wish to use ours, ask
a 61A Infrastructure TA for guidance.
## Setup
1. Clone the repo and switch into the `ag_master` directory.
2. Run `sicp venv` to create a virtual environment (`python3 -m venv env`) and
install requirements (`env/bin/pip install -r requirements.txt`).
3. Run `env/bin/python main.py` to start the Autograder server. You may need to
be logged into a `gcloud` account with access to the `cs61a` project in order
to access cloud storage buckets, as local development is currently somewhat
unsupported.
## Recreating the Autograder
You can create your own version of this autograder to autograde assignments
submitted through Okpy. Should you choose to do so, you'll need to set up a
server with some endpoints that Okpy can query. See API Model for more details.<file_sep>/code/src/languages/lark/web/extractLarkTests.js
import { PS1, PS2 } from "../constants/prompts";
const DOCTEST_START = "%doctest";
const DOCTEST_END = "%end";
export default function extractLarkTests(text) {
const lines = text.split("\n");
const grammar = [];
const cases = [];
let inDoctest = false;
let caseName = null;
let currentCase = null;
let currentInput = [];
let currentOutput = [];
for (let lineNum = 0; lineNum !== lines.length; ++lineNum) {
const line = lines[lineNum];
const trimmedLine = line.trimEnd();
if (inDoctest) {
if (trimmedLine === DOCTEST_END || trimmedLine.startsWith(PS1)) {
if (currentInput.length !== 0) {
currentCase.push({
input: currentInput.join("\n"),
output: currentOutput.join("\n"),
});
currentInput = [];
currentOutput = [];
}
if (trimmedLine === DOCTEST_END) {
cases.push({ caseName, tests: currentCase });
currentCase = null;
inDoctest = false;
} else {
currentInput.push(line.slice(PS1.length));
}
} else if (trimmedLine.startsWith(PS2)) {
if (currentInput.length === 0 || currentOutput.length !== 0) {
throw Error(`Unexpected prompt ${PS2.trim()} on line ${lineNum}`);
}
currentInput.push(line.slice(PS2.length));
} else {
if (currentInput.length === 0) {
throw Error(
`${PS1.trim()} input must be provided before the expected output on line ${lineNum}.`
);
}
currentOutput.push(trimmedLine);
}
} else if (trimmedLine.startsWith(DOCTEST_START)) {
inDoctest = true;
caseName = trimmedLine.slice(DOCTEST_START.length).trim();
currentCase = [];
} else {
grammar.push(trimmedLine);
}
}
if (inDoctest) {
throw Error(`${DOCTEST_START} block not terminated with ${DOCTEST_END}`);
}
return { grammar: grammar.join("\n"), cases };
}
<file_sep>/common/secrets.py
import string
from os import getenv
from random import SystemRandom
def get_master_secret():
"""Get ``APP_MASTER_SECRET`` from the environment using :func:`os.getenv`.
:return: the master secret
"""
return getenv("APP_MASTER_SECRET")
def new_secret():
"""Get a new 64-character secret, with each character a random uppercase
letter or a digit.
:return: the randomly-generated secret
"""
return "".join(
SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(64)
)
<file_sep>/cats/server/requirements.txt
Flask
gunicorn
mysqlclient
cryptography
claptcha
-r common/requirements.txt
<file_sep>/sicp/sicp/pr.py
import click, sys, os
from common.rpc.auth_utils import get_token
from common.rpc.buildserver import trigger_build_sync
from github import Github
from github.GithubException import UnknownObjectException
APPS = "Cal-CS-61A-Staff/cs61a-apps"
@click.group("pr")
def pr():
"""
Commands to interface with PRs.
"""
pass
@pr.command()
@click.argument("num")
@click.argument("targets", nargs=-1)
def build(num, targets):
"""Build TARGETS for pull request NUM.
NUM is the PR number you want to build targets
for, and TARGETS is the list of apps you want
to build within that PR. If no targets are passed
in, then all apps modified in the PR are built.
"""
repo = Github().get_repo(APPS)
try:
pull = repo.get_pull(int(num))
except UnknownObjectException:
raise Exception("Couldn't find that PR.")
if pull.state == "closed":
raise Exception("Cannot build targets for a closed PR!")
print(f"PR {num}: {pull.title}")
print(f"Building targets: {targets if targets else ['all']}")
for target in targets:
trigger_build_sync(
pr_number=int(num),
target_app=target,
_impersonate="buildserver",
noreply=True,
)
print("Build triggered!")
<file_sep>/hog/src/ScoreIndicator.js
// @flow
import React from "react";
import styled from "styled-components";
import { numberStrings } from "./constants";
const OuterDiv = styled.div`
width: 150px;
border: solid black 2px;
font-weight: bold;
text-align: center;
display: flex;
flex-direction: column;
`;
const ScoreDiv = styled.div`
width: 100%;
height: 130px;
line-height: 130px;
font-size: 48pt;
background: ${(props) => (props.isCurrent ? "white" : "transparent")};
`;
const PlayerDiv = styled.div`
width: 100%;
line-height: 30px;
background: ${(props) => (props.isCurrent ? "#17a2b8" : "grey")};
color: white;
`;
type Props = { score: number, playerIndex: number, currentPlayer: number };
export default function ScoreIndicator({
score,
playerIndex,
currentPlayer,
}: Props) {
const isCurrent = currentPlayer === playerIndex;
return (
<OuterDiv>
<ScoreDiv isCurrent={isCurrent}>{score}</ScoreDiv>
<PlayerDiv isCurrent={isCurrent}>
{isCurrent ? "โ " : ""}
Player {numberStrings[playerIndex]}
</PlayerDiv>
</OuterDiv>
);
}
<file_sep>/howamidoing/src/ConfigEditor.js
import React, { useState } from "react";
import $ from "jquery";
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-github";
var original = "";
$.ajax("/config/config.js", { async: false, dataType: "text" }).done(
(origConfig) => {
original = origConfig;
}
);
export default function ConfigEditor() {
const editorRef = React.useRef();
const [modified, setModified] = useState(false);
const [saving, setSaving] = useState(false);
const updateModified = () => {
const curr = editorRef.current.editor.getValue();
setModified(curr !== original);
};
const postConfig = () => {
setSaving(true);
const newOrig = editorRef.current.editor.getValue().slice();
$.post("/setConfig", { data: newOrig, dataType: "text" }).done(() => {
setSaving(false);
original = newOrig;
updateModified();
});
};
return (
<>
<AceEditor
mode="javascript"
theme="github"
ref={editorRef}
defaultValue={original.slice()}
name="configEditor"
onChange={updateModified}
style={{
width: "100%",
}}
showPrintMargin={false}
wrapEnabled={true}
/>
<button
type="submit"
className="btn btn-primary"
style={{
marginTop: "10px",
marginBottom: "10px",
}}
onClick={(e) => {
e.preventDefault();
postConfig();
}}
id="saveButton"
disabled={saving || !modified}
>
{saving ? "Saving..." : modified ? "Save Configuration" : "No Changes"}
</button>
</>
);
}
<file_sep>/cats/server/gui_files/db.py
../common/db.py<file_sep>/common/db.py
import os
import sys
from contextlib import contextmanager
from os import getenv
from os.path import exists
from time import sleep
from typing import List
import sqlalchemy.engine.url
from common.rpc.secrets import get_secret
use_devdb = getenv("ENV", "DEV") in ("DEV", "TEST")
use_prod_proxy = getenv("ENV") == "DEV_ON_PROD"
is_sphinx = "sphinx" in sys.argv[0]
if use_devdb:
database_url = "sqlite:///" + os.path.join(
os.path.abspath(os.path.dirname(__file__)), "../app.db"
)
elif use_prod_proxy:
curr = os.path.abspath(os.path.curdir)
prev = None
while True:
if ".git" in os.listdir(curr):
app = os.path.basename(prev)
break
prev = curr
curr = os.path.dirname(curr)
assert (
input(
"Are you sure? You are about to use the PROD database on a DEV build (y/N) "
)
.strip()
.lower()
== "y"
)
if "cloud_sql_proxy" not in os.listdir(curr):
print(
"Follow the instructions at https://cloud.google.com/sql/docs/mysql/sql-proxy to install the proxy "
"in the root directory of the repository, then try again."
)
exit(0)
database_url = sqlalchemy.engine.url.URL(
drivername="mysql+pymysql",
username="buildserver",
password=get_secret(secret_name="DATABASE_PW"),
host="127.0.0.1",
port=3307,
database=app.replace("-", "_"),
).__to_string__(hide_password=False)
else:
database_url = getenv("DATABASE_URL")
engine = sqlalchemy.create_engine(
database_url,
**(
dict(
connect_args=dict(
ssl=dict(
cert="/shared/client-cert.pem",
key="/shared/client-key.pem",
ca="/shared/server-ca.pem",
),
)
)
if exists("/shared/client-cert.pem")
else {}
),
**(
{}
if use_devdb
else dict(pool_size=5, max_overflow=2, pool_timeout=30, pool_recycle=1800)
),
)
@contextmanager
def connect_db(*, retries=3):
"""Create a context that uses a connection to the current database.
:param retries: the number of times to try connecting to the database
:type retries: int
:yields: a function with parameters ``(query: str, args: List[str] = [])``,
where the ``query_str`` should use ``%s`` to represent sequential
arguments in the ``args_list``
:example usage:
.. code-block:: python
with connect_db() as db:
db("INSERT INTO animals VALUES %s", ["cat"])
output = db("SELECT * FROM animals")
"""
if is_sphinx:
def no_op(*args, **kwargs):
class NoOp:
fetchone = lambda *args: None
fetchall = lambda *args: None
return NoOp()
yield no_op
else:
for i in range(retries):
try:
conn = engine.connect()
break
except:
sleep(3)
continue
else:
raise
with conn:
def db(query: str, args: List[str] = []):
if use_devdb:
query = query.replace("%s", "?")
return conn.execute(query, args)
yield db
@contextmanager
def transaction_db():
"""Create a context that performs a transaction on current database.
The difference between this and :meth:`~common.db.connect_db` is that this
method batches queries in a transaction, and only runs them once the
context is abandoned.
:yields: a function with parameters ``(query: str, args: List[str] = [])``,
where the ``query_str`` should use ``%s`` to represent sequential
arguments in the ``args_list``
:example usage:
.. code-block:: python
with transaction_db() as db:
db("INSERT INTO animals VALUES %s", ["cat"])
output = db("SELECT * FROM animals")
"""
with engine.begin() as conn:
def db(*args):
query, *rest = args
if use_devdb:
query = query.replace("%s", "?")
return conn.execute(query, *rest)
yield db
<file_sep>/examtool_web_common/js/StudentMessagesList.js
import React from "react";
import { Card, Row, Col, ListGroup } from "react-bootstrap";
import { useExamData, useTime } from "./AlertsContext";
import { timeDeltaMinutesString } from "./timeUtils";
export default function StudentMessagesList() {
const time = useTime();
const examData = useExamData();
if (examData.messages.length === 0) {
return null;
}
return (
<Row>
<Col>
{examData.messages.map(
({ id, message, question, timestamp, responses }) => (
<div key={id}>
<Card>
<Card.Header>
<b>
{responses.length === 0
? "Unresolved Thread"
: "Resolved Thread"}
</b>{" "}
[{question}]
</Card.Header>
<ListGroup variant="flush">
<ListGroup.Item key={id} style={{ whiteSpace: "pre-wrap" }}>
<b>You: </b>
{message} ({timeDeltaMinutesString(time - timestamp)})
</ListGroup.Item>
{responses.map(
({
id: replyID,
message: response,
timestamp: responseTime,
}) => (
<ListGroup.Item
key={replyID}
style={{ whiteSpace: "pre-wrap" }}
>
<b>Staff: </b>
{response} (
{timeDeltaMinutesString(time - responseTime)})
</ListGroup.Item>
)
)}
</ListGroup>
</Card>
<br />
</div>
)
)}
</Col>
</Row>
);
}
<file_sep>/auth/auth_client.py
import re
import string
from random import SystemRandom
from flask import redirect, request
from auth_utils import course_oauth_secure, get_name
from common.db import connect_db
from common.url_for import url_for
from common.html import html, make_row
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS auth_keys (
client_name varchar(128),
auth_key varchar(128),
creator varchar(128),
course varchar(128),
service varchar(128),
unused BOOLEAN
)"""
)
init_db()
def gen_key(length=64):
return "".join(
SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(length)
)
def prettify(course_code):
m = re.match(r"([a-z]+)([0-9]+[a-z]?)", course_code)
return m and (m.group(1) + " " + m.group(2)).upper()
def create_auth_client(app):
def client_data(course):
with connect_db() as db:
ret = db(
"SELECT client_name, creator, unused FROM auth_keys WHERE course=(%s)",
[course],
).fetchall()
client_names = [
make_row(
f'{client_name}, created by {creator} {"(unused)" if unused else ""} ',
url_for("revoke_key", course=course, client_name=client_name),
)
for client_name, creator, unused in ret
]
create_client = f"""
Create new client and obtain secret key:
<form action="{url_for("create_key", course=course)}" method="post">
<input name="client_name" type="text" placeholder="client_name">
<input type="submit">
</form>
"""
return "<h3>Clients</h3>" + create_client + "<p>".join(client_names)
app.help_info.add(client_data)
@app.route("/auth/<course>/request_key", methods=["POST"])
@course_oauth_secure()
def create_key(course):
name = request.form["client_name"]
key = gen_key()
with connect_db() as db:
ret = db(
"SELECT * FROM auth_keys WHERE client_name = (%s)", [name]
).fetchone()
if ret:
return "client_name already in use", 409
ret = db(
"SELECT * FROM super_auth_keys WHERE client_name = (%s)", [name]
).fetchone()
if ret:
return "client_name already in use", 409
db(
"INSERT INTO auth_keys VALUES (%s, %s, %s, %s, %s, %s)",
[name, key, get_name(), course, "all", True],
)
return html(f"<pre>{key}</pre>")
@app.route("/auth/<course>/revoke_key", methods=["POST"])
@course_oauth_secure()
def revoke_key(course):
name = request.args["client_name"]
with connect_db() as db:
db(
"DELETE FROM auth_keys WHERE client_name = (%s) and course = (%s)",
[name, course],
)
return redirect("/")
@app.route("/auth/<course>/revoke_all_unused_keys", methods=["POST"])
@course_oauth_secure()
def revoke_all_unused_keys(course):
with connect_db() as db:
db("DELETE FROM auth_keys WHERE unused = TRUE and course = (%s)", [course])
return html("All unused keys revoked.")
<file_sep>/cats/src/Indicators.js
import React from "react";
import "./Indicators.css";
import Indicator from "./Indicator";
import { formatNum } from "./utils";
export default function Indicators({ wpm, accuracy, remainingTime }) {
return (
<div className="Indicators">
<Indicator text={`WPM: ${formatNum(wpm)}`} />
<Indicator text={`Accuracy: ${formatNum(accuracy)}`} />
<Indicator text={`Time: ${remainingTime}`} />
</div>
);
}
<file_sep>/howamidoing/src/GradePlanner.js
import React from "react";
import FinalNeededScoreTable from "./FinalNeededScoreTable.js";
export default function GradePlanner(props) {
const {
canDisplayFinalGrades,
computeNeededFinalScore,
participationProvided,
} = window;
const { data: scores } = props;
if (!canDisplayFinalGrades(scores)) {
return (
<>
<div className="card">
<h5 className="card-header">Grade Planning</h5>
<div className="card-body">
<h5 className="card-title">Insufficient Data</h5>
<p className="card-text">
You need to specify your expected assignment scores (except for
the final!) in the below table to enable grade planning.
</p>
<p>
Or click the button to set them all to the maximum (including
extra credit)!
</p>
<button
className="btn btn-primary"
type="button"
onClick={props.onSetCourseworkToMax}
>
Set all unknown non-final scores to maximum
</button>
</div>
</div>
<br />
</>
);
}
const [grades, needed] = computeNeededFinalScore(scores);
if (!participationProvided(scores)) {
return (
<>
<div className="card">
<h5 className="card-header">Grade Planning</h5>
<div className="card-body">
<FinalNeededScoreTable grades={grades} needed={needed} />
<p className="card-text">
To take exam recovery points into account, specify an estimate of
your participation credits. Or click the button to set them all to
the maximum!
</p>
<button
className="btn btn-primary"
type="button"
onClick={props.onSetParticipationToMax}
>
Set all unknown participation credits to maximum
</button>
</div>
</div>
<br />
</>
);
} else {
return (
<>
<div className="card">
<h5 className="card-header">Grade Planning</h5>
<div className="card-body">
<FinalNeededScoreTable grades={grades} needed={needed} />
</div>
</div>
<br />
</>
);
}
}
<file_sep>/oh/migrations/versions/5c55d6d588c5_add_chatmessage_table.py
"""Add chatmessage table
Revision ID: 5c55d6d588c5
Revises: 951e6bbd<PASSWORD>
Create Date: 2020-09-06 04:26:45.280552
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
from sqlalchemy.dialects import mysql
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"chat_message",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created", sa.DateTime(), nullable=True),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("ticket_id", sa.Integer(), nullable=True),
sa.Column("appointment_id", sa.Integer(), nullable=True),
sa.Column("group_id", sa.Integer(), nullable=True),
sa.Column("course", sa.String(length=255), nullable=False),
sa.ForeignKeyConstraint(["appointment_id"], ["appointment.id"]),
sa.ForeignKeyConstraint(["group_id"], ["group.id"]),
sa.ForeignKeyConstraint(["ticket_id"], ["ticket.id"]),
sa.ForeignKeyConstraint(["user_id"], ["user.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_chat_message_appointment_id"),
"chat_message",
["appointment_id"],
unique=False,
)
op.create_index(
op.f("ix_chat_message_course"), "chat_message", ["course"], unique=False
)
op.create_index(
op.f("ix_chat_message_group_id"), "chat_message", ["group_id"], unique=False
)
op.create_index(
op.f("ix_chat_message_ticket_id"), "chat_message", ["ticket_id"], unique=False
)
op.create_index(
op.f("ix_chat_message_user_id"), "chat_message", ["user_id"], unique=False
)
op.alter_column(
"config_entries", "key", existing_type=mysql.VARCHAR(length=255), nullable=False
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column(
"config_entries", "key", existing_type=mysql.VARCHAR(length=255), nullable=True
)
op.drop_index(op.f("ix_chat_message_user_id"), table_name="chat_message")
op.drop_index(op.f("ix_chat_message_ticket_id"), table_name="chat_message")
op.drop_index(op.f("ix_chat_message_group_id"), table_name="chat_message")
op.drop_index(op.f("ix_chat_message_course"), table_name="chat_message")
op.drop_index(op.f("ix_chat_message_appointment_id"), table_name="chat_message")
op.drop_table("chat_message")
# ### end Alembic commands ###
<file_sep>/hog/src/GameOptions.js
// @flow
import React from "react";
import Form from "react-bootstrap/Form";
import styled from "styled-components";
import type { RuleSet } from "./App";
const StyledDiv = styled.div`
margin-top: 15px;
`;
type Props = {
gameRules: RuleSet,
onGameRulesChange: (string, boolean) => mixed,
};
export default function GameOptions({ gameRules, onGameRulesChange }: Props) {
return (
<StyledDiv>
<h5>Enable game rules:</h5>
{Object.entries(gameRules).map(([rule, state]) => (
<Form.Check
key={rule}
custom
inline
type="switch"
id={`rule-checkbox-${rule}`}
checked={state}
label={rule}
onChange={() => onGameRulesChange(rule, !state)}
/>
))}
</StyledDiv>
);
}
<file_sep>/code/src/web-server/oauth_client.py
import os
import urllib.parse
import requests
from flask import session, request, redirect, jsonify, abort
from flask_oauthlib.client import OAuth
from werkzeug import security
from common.rpc.secrets import get_secret
from common.url_for import url_for
from constants import COOKIE_IS_POPUP, COOKIE_SHORTLINK_REDIRECT
CONSUMER_KEY = "61a-web-repl"
def create_oauth_client(app):
oauth = OAuth(app)
if os.getenv("ENV") == "prod":
consumer_key = CONSUMER_KEY
app.secret_key = get_secret(secret_name="OKPY_OAUTH_SECRET")
else:
consumer_key = "local-dev-all"
app.secret_key = "<KEY>"
if not app.debug:
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
)
remote = oauth.remote_app(
"ok-server", # Server Name
consumer_key=consumer_key,
consumer_secret=app.secret_key,
request_token_params={"scope": "all", "state": lambda: security.gen_salt(10)},
base_url="https://okpy.org/api/v3/",
request_token_url=None,
access_token_method="POST",
access_token_url="https://okpy.org/oauth/token",
authorize_url="https://okpy.org/oauth/authorize",
)
def kill_popup():
response = app.make_response("<script> window.close(); </script>")
response.delete_cookie(COOKIE_IS_POPUP)
return response
def check_req(uri, headers, body):
"""Add access_token to the URL Request."""
if "access_token" not in uri and session.get("dev_token"):
params = {"access_token": session.get("dev_token")[0]}
url_parts = list(urllib.parse.urlparse(uri))
query = dict(urllib.parse.parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urllib.parse.urlencode(query)
uri = urllib.parse.urlunparse(url_parts)
return uri, headers, body
remote.pre_request = check_req
@app.route("/oauth/popup_login")
def popup_login():
response = remote.authorize(callback=url_for("authorized", _external=True))
response.set_cookie(COOKIE_IS_POPUP, value="")
return response
@app.route("/oauth/popup_logout")
def popup_logout():
session.pop("dev_token", None)
return kill_popup()
@app.route("/oauth/login")
def login():
response = remote.authorize(callback=url_for("authorized", _external=True))
response.delete_cookie(COOKIE_IS_POPUP)
return response
@app.route("/oauth/authorized")
def authorized():
resp = remote.authorized_response()
if resp is None:
return "Access denied: error=%s" % (request.args["error"])
if isinstance(resp, dict) and "access_token" in resp:
session["dev_token"] = (resp["access_token"], "")
if COOKIE_IS_POPUP in request.cookies:
return kill_popup()
if COOKIE_SHORTLINK_REDIRECT in request.cookies:
return app.load_file(request.cookies[COOKIE_SHORTLINK_REDIRECT])
else:
return redirect("/")
@app.route("/api/user", methods=["POST"])
def client_method():
if "dev_token" not in session:
abort(401)
token = session["dev_token"][0]
r = requests.get("https://okpy.org/api/v3/user/?access_token={}".format(token))
if not r.ok:
abort(401)
return jsonify(r.json())
@remote.tokengetter
def get_oauth_token():
return session.get("dev_token")
app.remote = remote
<file_sep>/buildserver/build.py
import os
from shutil import copytree, rmtree
from urllib.parse import urlparse
from app_config import App
from common.rpc.secrets import get_secret
from common.shell_utils import clean_all_except, sh, tmp_directory
def gen_working_dir(app: App):
return f"{app}_working_DO_NOT_USE"
def clone_commit(remote: str, sha: str, *, in_place=False):
path = urlparse(remote).path
def clone():
sh("git", "init")
sh(
"git",
"fetch",
"--depth=1",
f"https://{get_secret(secret_name='GITHUB_ACCESS_TOKEN')}@github.com{path}",
sha,
)
sh("git", "checkout", "FETCH_HEAD", "-f")
if in_place:
clone()
else:
with tmp_directory(clean=True):
clone()
def build(app: App):
with tmp_directory():
os.chdir(app.name)
app_dir = app.name
os.chdir("..")
working_dir = gen_working_dir(app)
copytree(app_dir, working_dir, dirs_exist_ok=True, symlinks=False)
os.chdir(working_dir)
{
"oh_queue": run_oh_queue_build,
"create_react_app": run_create_react_app_build,
"webpack": run_webpack_build,
"61a_website": run_61a_website_build,
"hugo": run_hugo_build,
"sphinx": run_sphinx_build,
"jekyll": run_jekyll_build,
"none": run_noop_build,
}[app.config["build_type"]]()
os.chdir("..")
def run_oh_queue_build():
sh("python", "-m", "venv", "env")
sh("env/bin/pip", "freeze")
sh("env/bin/pip", "install", "-r", "requirements.txt")
sh("yarn")
sh("env/bin/python", "./manage.py", "build")
def run_create_react_app_build():
sh("yarn")
sh("yarn", "build")
clean_all_except(["deploy"])
copytree("deploy", ".", dirs_exist_ok=True)
rmtree("deploy")
def run_webpack_build():
sh("yarn")
sh("yarn", "run", "webpack")
sh("rm", "-rf", "node_modules")
def run_61a_website_build():
env = dict(
CLOUD_STORAGE_BUCKET="website-pdf-cache.buckets.cs61a.org",
)
def build(target):
# need to re-run make for stupid reasons
out = sh(
"make",
"--no-print-directory",
"-C",
"src",
target,
env=env,
capture_output=True,
)
print(out.decode("utf-8"))
build("all")
sh("cp", "-aT", "published", "released")
build("unreleased")
sh("cp", "-aT", "published", "unreleased")
clean_all_except(["released", "unreleased"])
def run_hugo_build():
sh("python", "make_content.py")
sh("hugo")
clean_all_except(["public"])
copytree("public", ".", dirs_exist_ok=True)
rmtree("public")
def run_sphinx_build():
sh("python3", "-m", "venv", "env")
sh("env/bin/pip", "install", "-r", "requirements.txt")
sh("env/bin/sphinx-build", "-b", "dirhtml", "..", "_build")
clean_all_except(["_build"])
copytree("_build", ".", dirs_exist_ok=True)
rmtree("_build")
def run_jekyll_build():
sh("bundle", "install")
sh("bundle", "exec", "jekyll", "build")
clean_all_except(["_site"])
copytree("_site", ".", dirs_exist_ok=True)
rmtree("_site")
def run_noop_build():
pass
<file_sep>/cats/server/gui_files/common_server.py
../../gui_files/common_server.py<file_sep>/oh/migrations/versions/680b44ae9515_support_ticket_sort_key.py
"""support ticket sort_key
Revision ID: 680b44ae9515
Revises: <KEY>
Create Date: 2021-02-11 11:14:35.398091
"""
# revision identifiers, used by Alembic.
revision = "6<KEY>"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
from datetime import datetime
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"ticket",
sa.Column(
"sort_key",
sa.DateTime(),
nullable=True,
),
)
op.execute("UPDATE ticket SET sort_key=created")
op.alter_column("ticket", "sort_key", nullable=False)
op.create_index(op.f("ix_ticket_sort_key"), "ticket", ["sort_key"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_ticket_sort_key"), table_name="ticket")
op.drop_column("ticket", "sort_key")
# ### end Alembic commands ###
<file_sep>/code/src/renderer/utils/dispatch.js
import { LARK, PYTHON, SCHEME, SQL } from "../../common/languages.js";
import pyTest from "../../languages/python/utils/test";
import scmTest from "../../languages/scheme/utils/test";
import larkTest from "../../languages/lark/utils/test";
import { runLarkCode } from "../../languages/lark/utils/run";
import pyFormat from "../../languages/python/utils/format.js";
import scmFormat from "../../languages/scheme/utils/format.js";
import pyGenerateDebugTrace from "../../languages/python/utils/generateDebugTrace.js";
import scmGenerateDebugTrace from "../../languages/scheme/utils/generateDebugTrace.js";
import { runPyCode, runPyFile } from "../../languages/python/utils/run.js";
import { runScmCode, runScmFile } from "../../languages/scheme/utils/run.js";
import SchemeDebugger from "../../languages/scheme/components/SchemeDebugger.js";
import PythonTutorDebug from "../../languages/python/components/PythonTutorDebug.js";
import pyDebugPrefix from "../../languages/python/utils/debugPrefix.js";
import scmDebugPrefix from "../../languages/scheme/utils/debugPrefix.js";
import { runSQLCode } from "../../languages/sql/utils/run.js";
import ProcessPool from "./processPool.js";
export function format(language) {
const options = {
[PYTHON]: pyFormat,
[SCHEME]: scmFormat,
};
return options[language];
}
export function generateDebugTrace(language) {
const options = {
[PYTHON]: pyGenerateDebugTrace,
[SCHEME]: scmGenerateDebugTrace,
};
return options[language];
}
const interpreterPool = new ProcessPool(
{
[PYTHON]: runPyCode,
[SCHEME]: runScmCode,
[SQL]: runSQLCode,
},
2
);
export function runCode(language) {
switch (language) {
case LARK:
return runLarkCode;
default:
return interpreterPool.pop(language);
}
}
export function runFile(language) {
const options = {
[PYTHON]: runPyFile,
[SCHEME]: runScmFile,
};
return options[language];
}
export function testCode(language) {
const options = {
[PYTHON]: pyTest,
[SCHEME]: scmTest,
[LARK]: larkTest,
};
return options[language];
}
export function Debugger(language) {
const options = {
[PYTHON]: PythonTutorDebug,
[SCHEME]: SchemeDebugger,
};
return options[language];
}
export function debugPrefix(language) {
const options = {
[PYTHON]: pyDebugPrefix,
[SCHEME]: scmDebugPrefix,
};
return options[language];
}
export function extension(language) {
const extensions = {
[PYTHON]: ".py",
[SCHEME]: ".scm",
[SQL]: ".sql",
[LARK]: ".lark",
};
return extensions[language];
}
<file_sep>/static-server/main.py
from flask import Flask
from flask_compress import Compress
from utils import get_bucket, serve_path
app = Flask(__name__, static_folder=None)
if __name__ == "__main__":
app.debug = True
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>", methods=["GET"])
def get(path):
bucket = get_bucket(
{
"time": "time",
"loom": "loom",
"react": "react",
"ok-help": "ok-help",
"wiki": "wiki",
"docs": "docs",
"cs170-website": "cs170-website",
"cs170": "cs170-website",
# simple default app for PR testing
"static-server": "time",
},
"time",
)
return serve_path(bucket, "/", path)
Compress(app)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/search/requirements.txt
Flask
gunicorn
flask-cors
-r common/requirements.txt
<file_sep>/loom/src/App.js
import React, { useState } from "react";
import Button from "react-bootstrap/Button";
import Col from "react-bootstrap/Col";
import Container from "react-bootstrap/Container";
import "./App.css";
import FormControl from "react-bootstrap/FormControl";
import InputGroup from "react-bootstrap/InputGroup";
import Row from "react-bootstrap/Row";
import "bootstrap/dist/css/bootstrap.min.css";
function App() {
const [urls, setUrls] = useState([]);
const [enteredURL, setEnteredURL] = useState("");
const handleClick = () => {
const id = enteredURL.match(/share\/([a-z0-9]+)/)[1];
const processedURL = `https://www.loom.com/embed/${id}`;
setUrls(urls.concat([processedURL]));
setEnteredURL("");
};
return (
<Container fluid>
<Row>
<Col>
<h1>Loom Viewer</h1>
</Col>
</Row>
<Row>
<Col>
<InputGroup className="mb-3">
<FormControl
placeholder="https://www.loom.com/share/abcdefg"
aria-label="Loom URL"
aria-describedby="basic-addon2"
value={enteredURL}
onChange={(e) => setEnteredURL(e.target.value)}
/>
<InputGroup.Append>
<Button onClick={handleClick} variant="outline-secondary">
Add
</Button>
</InputGroup.Append>
</InputGroup>
</Col>
</Row>
<div style={{ width: "100%", display: "flex", flexWrap: "wrap" }}>
{urls.map((url) => (
<LoomView key={url} url={url} />
))}
</div>
</Container>
);
}
function LoomView({ url }) {
const [hidden, setHidden] = useState(false);
if (hidden) {
return null;
}
return (
<div style={{ position: "relative" }}>
<button
style={{ position: "absolute", top: 0, right: 0 }}
className="btn btn-danger"
onClick={() => setHidden(true)}
>
×
</button>
<iframe
style={{ width: 550, height: 300 }}
src={url}
frameBorder="0"
allowFullScreen
/>
</div>
);
}
export default App;
<file_sep>/auth/main.py
from flask import Flask
from admins_client import create_admins_client
from auth_client import create_auth_client
from common.oauth_client import create_oauth_client
from domains_client import create_domains_client
from google_client import create_google_client
from management_client import create_management_client
from piazza_client import create_piazza_client
from ed_client import create_ed_client
from slack_client import create_slack_client
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
create_oauth_client(app, "61a-account-auth")
create_management_client(app)
create_auth_client(app)
create_admins_client(app)
create_google_client(app)
create_piazza_client(app)
create_ed_client(app)
create_slack_client(app)
create_domains_client(app)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/disc/main.py
from flask import Flask, Response, abort, jsonify, request, session
from flask.sessions import SecureCookieSessionInterface
from flask_cors import CORS
from common.db import connect_db, transaction_db
from common.oauth_client import (
create_oauth_client,
get_user,
is_enrolled,
login,
)
VALID_ORIGINS = r"https://.*cs61a\.org"
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
app.debug = True
CORS(app, origins=VALID_ORIGINS, supports_credentials=True)
create_oauth_client(app, "61a-discussions")
"""
This is normally risky! It is safe here because
(a) CORS prevents an attacker from reading reply data, even if their request is authenticated
(b) The endpoints require a Content-Type of application/json, so browsers will send a pre-flight
meaning that they will not even send POSTs unless they pass the CORS check, which they don't
To ensure safety, we must ensure that
(a) GET requests have no side-effects
(b) POST requests must have the JSON Content-Type, so a malicious site cannot send requests on
behalf of a user that can cause issues.
(c) The CORS policy only allows *.cs61a.org to send POSTs with credentials
"""
@app.after_request
def patch_session_samesite(response: Response):
response.headers.add(
"Set-Cookie",
f"session={SecureCookieSessionInterface().get_signing_serializer(app).dumps(dict(session))}; "
"HttpOnly; SameSite=Lax; Path=/; Secure;",
)
return response
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS saves (
email varchar(128),
name varchar(512),
value LONGBLOB
);"""
)
@app.route("/")
def index():
session["email"] = get_user()["email"]
return "<script> window.close(); </script>"
@app.route("/whoami")
def whoami():
email = session.get("email")
return f"You are {email}"
@app.route("/save", methods=["POST"])
def save():
email = session.get("email")
if not email:
abort(401)
name = request.json["name"]
value = request.json["value"]
with transaction_db() as db:
db("DELETE FROM saves WHERE email=%s AND name=%s", [email, name])
db(
"INSERT INTO saves (email, name, value) VALUES (%s, %s, %s)",
[email, name, value],
)
return dict(success=True)
@app.route("/fetch", methods=["POST"])
def fetch():
email = session.get("email")
if not email:
abort(401)
with connect_db() as db:
resp = db("SELECT name, value FROM saves WHERE email=%s", [email]).fetchall()
return jsonify(
{
name: value.decode("utf-8") if value is not None else None
for name, value in resp
}
)
@app.route("/clear", methods=["POST"])
def clear():
email = session.get("email")
if not email:
abort(401)
with connect_db() as db:
db("DELETE FROM saves WHERE email=%s", [email])
return dict(success=True)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/ag-master/index.md
```{include} README.md
```
## Data Models
There are 2 data models used by this app: `Assignment` and `Job`.
```{eval-rst}
.. automodule:: docs.ag_master.models
:members:
```
## Utility Decorators
The autograder has two decorators that restrict access to various functions
and endpoints.
```{eval-rst}
.. automodule:: docs.ag_master.utils
:members:
```
## Course Admin Endpoints
```{eval-rst}
.. automodule:: docs.ag_master.admin
:members:
```
There is also a GUI available at autograder.cs61a.org for the following actions:
- Viewing all of a course's assignments (`/<course>`)
- Viewing a particular assignment (`/<course>/<assignment>`)
- Viewing a particular job (`/<course>/job/<id>`)
- Forcing unfinished jobs for an assignment to fail
(`/<course>/<assignment>/fail_unfinished`)
- Retriggering failed jobs for an assignment
(`/<course>/<assignment>/retrigger_unsuccessful`)
## Superadmin Endpoints
The following superadmin endpoint is available for viewing information about a
course: `/admin/<endpoint>`.
## Worker Communication
There are a few endpoints created solely to communicate grading jobs with the
worker instances.
```{eval-rst}
.. automodule:: docs.ag_master.worker
:members:
```
## Okpy Communication
There are a few endpoints created to communicate job requests and outputs
between Okpy and the autograder. There is one RPC endpoint,
{func}`~common.rpc.ag_master.trigger_jobs`, and a handful of REST endpoints.
For the REST endpoints, see the next section.
```{eval-rst}
.. automodule:: docs.ag_master.okpy
:members:
```
## API Model
This is the set of endpoints that will be used to communicate between Okpy
(or other grading base) and the autograder host. If you wish to recreate the
autograder, you will need to implement the following 3 endpoints. In addition,
you will likely need to get the contents of each backup that is being graded,
which can be done using the
[View a Backup](https://okpy.github.io/documentation/ok-api.html#backups-view-a-backup)
target of the Okpy API. You will also need to POST the scores output to Okpy,
which can be done using the
[Create a Score](https://okpy.github.io/documentation/ok-api.html#scores-create-a-score)
target of the Okpy API.
```{eval-rst}
.. openapi:: openapi.yml
```<file_sep>/buildserver/Dockerfile
FROM python:3.8-buster
RUN echo "deb https://deb.nodesource.com/node_12.x buster main" > /etc/apt/sources.list.d/nodesource.list
RUN wget -qO- https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" > /etc/apt/sources.list.d/yarn.list
RUN wget -qO- https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN apt-get update
RUN apt-get install -yqq nodejs yarn
RUN pip install -U pip && pip install pipenv
RUN rm -rf /var/lib/apt/lists/*
RUN wget https://www.openssl.org/source/openssl-1.0.2g.tar.gz -O - | tar -xzpip
RUN curl https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz > /tmp/google-cloud-sdk.tar.gz
RUN mkdir -p /usr/local/gcloud \
&& tar -C /usr/local/gcloud -xvf /tmp/google-cloud-sdk.tar.gz \
&& /usr/local/gcloud/google-cloud-sdk/install.sh -q
ENV PATH /usr/local/gcloud/google-cloud-sdk/bin:$PATH
RUN gcloud components install beta
RUN apt install -y git
RUN apt-get update && apt-get install -y rsync
RUN apt install -y --no-install-recommends texlive-full
RUN apt-get update && apt-get install -y latexmk && git config --global core.symlinks true
RUN apt-get update && apt-get install -y hugo zip
RUN apt-get update && apt-get install -y groff
RUN apt-get update && apt-get install -y pandoc
RUN apt-get update && apt-get install -yqq ruby-full build-essential zlib1g-dev
ENV GEM_HOME $HOME/gems
ENV PATH $HOME/gems/bin:$PATH
RUN gem install jekyll:3.8.5 bundler:1.17.2
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
RUN pip install -r requirements.txt
CMD gunicorn -b :$PORT -w 1 main:app -t 3000
<file_sep>/slack/issue_integration.py
import itertools
import re
from collections import namedtuple
from integration import Integration
from utils import OrderedSet
Issue = namedtuple("Issue", ["path"])
VALID_PATH = r"[0-9\-]"
PATH_REGEX = r"(?P<path>{}+)".format(VALID_PATH)
REGEX_TEMPLATE = (
r"<(https?://)?github\.com/Cal-CS-61A-Staff/berkeley-cs61a/issues/{}/?(\|[^\s|]+)?>"
)
SHORT_REGEX_TEMPLATE = r"is/{}/?"
class IssueIntegration(Integration):
def _process(self):
self._issues = OrderedSet()
for match in itertools.chain(
re.finditer(REGEX_TEMPLATE.format(PATH_REGEX), self._message),
re.finditer(SHORT_REGEX_TEMPLATE.format(PATH_REGEX), self._message),
):
self._issues.add(Issue(match.group("path")))
@property
def message(self):
out = self._message
for issue in self._issues:
out = re.sub(
REGEX_TEMPLATE.format(issue.path), "is/{}".format(issue.path), out
)
out = re.sub(
SHORT_REGEX_TEMPLATE.format(issue.path),
r"<https://github.com/Cal-CS-61A-Staff/berkeley-cs61a/issues/{}|is/{}>".format(
issue.path, issue.path
),
out,
)
return out
<file_sep>/examtool_web_common/js/auth.js
import { auth2 } from "gapi";
export function getToken() {
return window.location.hostname === "localhost"
? null
: auth2.getAuthInstance().currentUser.get().getAuthResponse(true).id_token;
}
export function getAuthParams() {
return {
token: getToken(),
...getLoginAsParams(),
};
}
export function getLoginAsParams() {
const hash = window.location.hash.slice(1);
return hash
? Object.fromEntries(hash.split(";").map((part) => part.split("=")))
: {};
}
export function inAdminMode() {
return !!getLoginAsParams().loginas;
}
<file_sep>/common/requirements.txt
sqlalchemy==1.3.18
PyMySQL==0.10.0
requests==2.25.0
cachetools==4.1.1
flask_oauthlib==0.9.5
werkzeug==0.16.1
<file_sep>/examtool_web_common/js/ConnectAlertButton.js
import React, { useState } from "react";
import FailText from "./FailText";
import LoadingButton from "./LoadingButton";
export default function ConnectAlertButton({ onDownloadClick }) {
const [loading, setLoading] = useState(false);
const [failText, setFailText] = useState("");
const download = async () => {
setLoading(true);
setFailText("");
const err = await onDownloadClick();
if (err) {
setFailText(err);
}
setLoading(false);
};
return (
<>
<LoadingButton onClick={download} disabled={loading} loading={loading}>
Connect to Server
</LoadingButton>
<FailText text={failText} suffixType="alerts" />
</>
);
}
<file_sep>/oh/migrations/versions/951e6bbdffc9_add_user_heartbeat_column.py
"""add user heartbeat column
Revision ID: 951e6bbdffc9
Revises: 4c81c3744bc4
Create Date: 2020-09-06 04:04:50.903594
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "a870d3c6be98"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"user", sa.Column("heartbeat_time", sa.DateTime(), nullable=True, index=True)
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("user", "heartbeat_reply")
# ### end Alembic commands ###
<file_sep>/static-server/utils.py
import tempfile
from datetime import timedelta
from os import getenv
from typing import Dict
from urllib.parse import urlparse, urlunparse
from flask import abort, current_app, redirect, request, safe_join, send_file
from google.cloud import storage
from google.cloud.exceptions import NotFound
from common.url_for import get_host
def get_bucket(app_lookup: Dict[str, str], default_app: str = None):
if current_app.debug:
return f"{default_app}.buckets.cs61a.org"
host = get_host()
if ".pr." in host:
pr, app, *_ = host.split(".")
pr = int(pr)
if app not in app_lookup:
abort(404)
bucket = f"{app_lookup[app]}-pr{pr}.buckets.cs61a.org"
try:
storage.Client().get_bucket(bucket)
return bucket
except NotFound:
pass
else:
app, *_ = host.split(".")
if app not in app_lookup:
abort(404)
return f"{app_lookup[app]}.buckets.cs61a.org"
def serve_path(bucket, root, path, *, path_404="404.html"):
filename = safe_join(root, path)[1:]
client = storage.Client()
bucket = client.get_bucket(bucket)
try:
if not filename:
raise NotFound(filename)
blob = bucket.blob(filename)
with tempfile.NamedTemporaryFile() as temp:
blob.download_to_filename(temp.name)
mimetype = None
if filename.endswith(".scm"):
mimetype = "text/x-scheme"
return send_file(
temp.name,
attachment_filename=filename,
mimetype=mimetype,
cache_timeout=timedelta(minutes=15).total_seconds(),
)
except NotFound:
if filename == path_404:
abort(404)
elif filename.endswith("index.html"):
return serve_path(bucket, root, path_404, path_404=path_404), 404
else:
if path and not path.endswith("/"):
if bucket.blob(filename + "/" + "index.html").exists():
target = urlunparse(
(
"https" if getenv("ENV") == "prod" else "http",
get_host(),
"/" + path + "/",
urlparse(request.url).params,
urlparse(request.url).query,
urlparse(request.url).fragment,
)
)
return redirect(target, 301)
else:
return serve_path(bucket, root, path_404, path_404=path_404), 404
return serve_path(bucket, root, path + "index.html", path_404=path_404)
<file_sep>/grade-display/README.md
# Grade Display Scripts
This folder contains up-to-date versions of the scripts used to display grades on howamidoing.cs61a.org.
To change how grades are processed before being uploaded to howamidoing, take a look at `assemble.py`. To change how grades are exported from Gradescope and the relevant columns are saved, take a look at `gs_export.py`. To update variables for the current semester, take look at `config.json`. This is the only file that should require changes!
<file_sep>/indexer/search.js
const html = `
<link rel='stylesheet' href='https://indexer.cs61a.org/search.css' type='text/css'>
<input class="cs61a-search-input" placeholder='Search for resources or posts on Piazza'/>
<div class="cs61a-search-results"></div>
<ul class="cs61a-search-expander list-inline hidden">
<li>
<a class="label label-outline" target="_blank">More Results</a>
</li>
</ul>
`;
document.querySelector(".cs61a-search").innerHTML = html;
const limit = 5;
const inputField = document.querySelector(".cs61a-search-input");
const results = document.querySelector(".cs61a-search-results");
const moreButton = document.querySelector(".cs61a-search-expander");
const headers = ["Resource", "Type", "Tags"];
const ngrams = (token, weight = 1) => {
return [
`${token}^${weight}`,
`${token}._2gram^${weight}`,
`${token}._gram^${weight}`,
];
};
const search = async (query, limit) => {
if (limit <= 0) {
return [];
}
const genericParams = {
from: 0,
size: limit === Infinity ? 100 : limit,
query: {
multi_match: {
query,
type: "bool_prefix",
fields: [
...ngrams("name"),
...ngrams("tags"),
...ngrams("type"),
...ngrams("content"),
],
fuzziness: "AUTO",
},
},
highlight: {
fields: {
name: { number_of_fragments: 0 },
tags: { number_of_fragments: 0 },
type: { number_of_fragments: 0 },
content: {},
},
order: "score",
},
};
const params = {
piazza_params: genericParams,
resource_params: genericParams,
};
const { piazza, resources } = await (
await fetch("https://search.cs61a.org/query", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(params),
})
).json();
const results = []
.concat(resources.hits.hits, piazza.hits.hits)
.sort((a, b) => b._score - a._score);
return results
.map(({ _source: { name, display, type, link, tags }, highlight }) => {
const bestHighlight = Object.fromEntries(
Object.entries(highlight || {}).map(([k, v]) => [k, v[0]])
);
const displayName = display || name;
if (displayName.includes("<a")) {
return [displayName, type, tags.join(", "), bestHighlight.content];
} else {
const wrapper = document.createElement("div");
const a = document.createElement("a");
a.href = link;
a.innerHTML = displayName;
wrapper.appendChild(a);
return [
wrapper.innerHTML,
type,
tags.join(", "),
bestHighlight.content,
];
}
})
.slice(0, limit);
};
const updateTable = (rows, isMore) => {
results.innerHTML = "";
if (rows.length !== 0) {
const table = document.createElement("table");
table.classList.add("table", "table-hover");
const tableHeader = document.createElement("thead");
const headerRow = document.createElement("tr");
for (const header of headers) {
const headerElem = document.createElement("th");
headerElem.textContent = header;
headerRow.appendChild(headerElem);
}
tableHeader.appendChild(headerRow);
table.appendChild(tableHeader);
const tableBody = document.createElement("tbody");
for (const row of rows) {
const tableRow = document.createElement("tr");
for (let i = 0; i !== headers.length; ++i) {
const elem = document.createElement("td");
elem.innerHTML = row[i];
tableRow.appendChild(elem);
}
tableBody.appendChild(tableRow);
if (row[3]) {
const text = row[3]
.replace("<em>", "||em||")
.replace("</em>", "||notem||");
const previewDiv = document.createElement("div");
previewDiv.classList.add("preview");
previewDiv.innerHTML = text;
const stripped = previewDiv.innerText.trim();
const emph = stripped
.replace("||em||", "<em>")
.replace("||notem||", "</em>");
previewDiv.innerHTML = emph;
tableRow.children[0].appendChild(previewDiv);
}
}
table.appendChild(tableBody);
results.appendChild(table);
}
if (rows.length !== 0 && isMore) {
moreButton.classList.remove("hidden");
} else {
moreButton.classList.add("hidden");
}
};
const makeUpdater = (getAll) => async () => {
const total = getAll ? Infinity : limit;
const r1 = await search(inputField.value, total);
updateTable(inputField.value && r1, !getAll);
};
inputField.addEventListener("input", makeUpdater(false));
moreButton.addEventListener("click", makeUpdater(true));
<file_sep>/buildtool/buildtool/execution.py
from __future__ import annotations
import os
import traceback
from pathlib import Path
from subprocess import CalledProcessError
from typing import Callable, Collection, Optional, Sequence
from colorama import Style
from cache import make_cache_memorize
from common.shell_utils import sh as run_shell
from context import Env, MemorizeContext
from fs_utils import copy_helper, hash_file
from monitoring import log
from state import BuildState, Rule
from utils import BuildException, MissingDependency
from common.hash_utils import HashState
class ExecutionContext(MemorizeContext):
def __init__(
self,
repo_root: str,
cwd: str,
hashstate: HashState,
load_deps: Callable[[Sequence[str]], None],
memorize: Callable[[str, str, str], None],
):
super().__init__(repo_root, cwd, hashstate)
self.load_deps = load_deps
self.memorize = memorize
self.sh_queue = []
os.makedirs(self.cwd, exist_ok=True)
def normalize_single(self, path: str):
if path.startswith("@//"):
return os.path.abspath(os.path.join(os.curdir, path[3:]))
elif path.startswith("//"):
return os.path.abspath(os.path.join(self.repo_root, path[2:]))
else:
return path
def normalize(self, env: Optional[Env]):
if env is None:
return {}
out = {}
for key in env:
if isinstance(env[key], str):
out[key] = self.normalize_single(env[key])
else:
out[key] = ":".join(
self.normalize_single(component) for component in env[key]
)
return out
def sh(self, cmd: str, env: Env = None):
super().sh(cmd=cmd, env=env)
self.sh_queue.append([cmd, self.cwd, self.normalize(env)])
def run_shell_queue(self):
for cmd, cwd, env in self.sh_queue:
log("RUNNING cmd:", cmd)
run_shell(
cmd,
shell=True,
cwd=cwd,
quiet=True,
capture_output=True,
inherit_env=False,
env=env,
)
self.sh_queue = []
def add_deps(self, deps: Sequence[str]):
super().add_deps(deps)
self.run_shell_queue()
self.load_deps(
[dep if dep.startswith(":") else self.absolute(dep) for dep in deps]
)
def input(
self, *, file: Optional[str] = None, sh: Optional[str] = None, env: Env = None
):
# we want the state *before* running the action
state = self.hashstate.state()
super().input(file=file, sh=sh, env=env)
self.run_shell_queue()
if file is not None:
self.load_deps([self.absolute(file)])
with open(self.absolute(file), "r") as f:
return f.read()
else:
log("RUNNING", sh)
out = run_shell(
sh,
shell=True,
cwd=self.cwd,
capture_output=True,
quiet=True,
inherit_env=False,
env=self.normalize(env),
).decode("utf-8")
self.memorize(state, HashState().record(sh, env).state(), out)
return out
def build(
build_state: BuildState,
rule: Rule,
deps: Collection[str],
*,
scratch_path: Optional[Path],
):
"""
All the dependencies that can be determined from caches have been
obtained. Now we need to run. Either we will successfully finish everything,
or we will get a missing dependency and have to requeue
"""
cache_memorize, _ = make_cache_memorize(build_state.cache_directory)
in_sandbox = scratch_path is not None
loaded_deps = set()
def load_deps(deps):
deps = set(deps) - loaded_deps
# check that these deps are built! Since they have not been checked by the PreviewExecution.
missing_deps = []
for dep in deps:
if dep not in build_state.source_files:
dep_rule = build_state.target_rule_lookup.lookup(build_state, dep)
if dep_rule not in build_state.ready:
missing_deps.append(dep)
if missing_deps:
raise MissingDependency(*missing_deps)
loaded_deps.update(deps)
if in_sandbox:
log(f"Loading dependencies {deps} into sandbox")
copy_helper(
src_root=build_state.repo_root,
dest_root=scratch_path,
src_names=[dep for dep in deps if not dep.startswith(":")],
symlink=not rule.do_not_symlink,
)
load_deps(deps)
hashstate = HashState()
ctx = ExecutionContext(
scratch_path if in_sandbox else build_state.repo_root,
scratch_path.joinpath(rule.location)
if in_sandbox
else Path(build_state.repo_root).joinpath(rule.location),
hashstate,
load_deps,
cache_memorize,
)
for dep in rule.deps:
dep_rule = build_state.target_rule_lookup.try_lookup(dep)
if dep.startswith(":"):
setattr(ctx.deps, dep[1:], dep_rule.provided_value)
else:
hashstate.update(dep.encode("utf-8"))
hashstate.update(hash_file(dep))
if dep not in build_state.source_files:
ctx.deps[dep] = dep_rule.provided_value
try:
rule.provided_value = rule.impl(ctx)
for out in rule.outputs:
# needed so that if we ask for another output, we don't panic if it's not in the cache
hashstate.record(out)
if in_sandbox:
ctx.run_shell_queue()
except CalledProcessError as e:
raise BuildException(
"".join(
[
str(e) + "\n",
Style.RESET_ALL,
f"Location: {scratch_path}\n",
f"Working Directory: {ctx.cwd}\n",
e.stdout.decode("utf-8"),
e.stderr.decode("utf-8"),
traceback.format_exc(),
]
)
)
if in_sandbox:
try:
copy_helper(
src_root=scratch_path,
src_names=rule.outputs,
dest_root=build_state.repo_root,
)
except FileNotFoundError as e:
raise BuildException(
f"Output file {e.filename} from rule {rule} was not generated."
)
for input_path in ctx.inputs:
if input_path.startswith(":"):
# don't hash rule deps
continue
hashstate.update(input_path.encode("utf-8"))
hashstate.update(hash_file(input_path))
return hashstate.state()
<file_sep>/common/index.md
```{include} README.md
```
## CLI Utilities
This file contains miscellaneous utilities for command-line interfaces.
```{eval-rst}
.. automodule:: common.cli_utils
:members:
```
## Course Configuration
This file contains various methods that can help identify a course as well as
determine the level of access a user (logged in with Okpy) has to the course.
```{eval-rst}
.. automodule:: common.course_config
:members:
```
## Database Interface
This file contains the logic for interfacing with the 61A database backend,
or for interfacing with a local database if you don't have access to the
production database (or are developing something volatile).
By default, this code assumes that you are running locally without access to
the production database. As such, the default action is to create a local
`app.db` if an application requests to use a database. In production, the
environment variable `DATABASE_URL` is used to connect to the production
database.
To develop on the production database, use `ENV=DEV_ON_PROD` and pass in
`DATABASE_PW=<PASSWORD>`, where `password` is the SQL password for the
`<PASSWORD>` user. Ask a Head of Software if you need access to this.
```{note}
Developing on production requires the Cloud SQL Proxy. Follow the instructions
at https://cloud.google.com/sql/docs/mysql/sql-proxy to install the proxy
in the root directory of the repository.
```
```{eval-rst}
.. automodule:: common.db
:members:
```
## Hash Utilities
This file contains some utilities for hashing data.
```{eval-rst}
.. automodule:: common.hash_utils
:members:
```
## HTML Helpers
This file contains some helpful HTML formatting tools for a standard frontend.
```{caution}
Do **not** use this library for student-facing apps, as it is vulnerable to XSS.
Only use it for quick staff-only frontends.
```
```{eval-rst}
.. automodule:: common.html
:members:
```
## Job Routing
This file contains a decorator utility to add URL rules for recurring actions.
```{eval-rst}
.. automodule:: common.jobs
:members:
```
## OAuth Client
This file contains some utilities for Okpy OAuth communication.
```{eval-rst}
.. automodule:: common.oauth_client
:members:
```
## Secrets
This file contains some utilities to create/get secrets for an app.
```{eval-rst}
.. automodule:: common.secrets
:members:
```
## Shell Utilities
This file contains some utilities to communicate with a shell.
```{eval-rst}
.. automodule:: common.shell_utils
:members:
```
## `url_for`
This file creates a new `url_for` method to improve upon the default
{func}`~flask.url_for`.
```{eval-rst}
.. automodule:: common.url_for
:members:
```
```{toctree}
:hidden:
:maxdepth: 3
rpc/index
```<file_sep>/hog/server/default_graphics.py
# Default dice for the Hog game. These can be overriden by students.
dice = [
"",
"""<?xml version="1.0" encoding="UTF-8"?>
<svg data-name="Layer 1" viewBox="0 0 76.08 76.08" xmlns="http://www.w3.org/2000/svg">
<defs>
<style>.cls-1{fill:#fff;stroke-miterlimit:10;}.cls-1,.cls-3{stroke:#000;}.cls-2{font-size:22.7px;font-family:"Helvetica Neue",Arial;}.cls-3{stroke-miterlimit:2;stroke-width:1.5px;fill-rule:evenodd;}</style>
</defs>
<rect class="cls-1" x=".5" y=".5" width="75.08" height="75.08" rx="9.25"/>
<text class="cls-2" transform="translate(7 26)">TURN<tspan x="0.71" y="40.24">OVER</tspan></text>
<path class="cls-3" d="M44.29,38A6.25,6.25,0,1,1,38,31.79,6.25,6.25,0,0,1,44.29,38Z"/>
</svg>
""",
"""<?xml version="1.0" encoding="UTF-8"?>
<svg data-name="Layer 1" viewBox="0 0 76.08 76.08" xmlns="http://www.w3.org/2000/svg">
<defs>
<style>.cls-1{fill:#fff;stroke-miterlimit:10;}.cls-1,.cls-2{stroke:#000;}.cls-2{stroke-miterlimit:2;stroke-width:1.5px;fill-rule:evenodd;}</style>
</defs>
<rect class="cls-1" x=".5" y=".5" width="75.08" height="75.08" rx="9.25"/>
<path class="cls-2" d="m44.29 20.32a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
<path class="cls-2" d="m44.29 56.32a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
</svg>
""",
"""<?xml version="1.0" encoding="UTF-8"?>
<svg data-name="Layer 1" viewBox="0 0 76.08 76.08" xmlns="http://www.w3.org/2000/svg">
<defs>
<style>.cls-1{fill:#fff;stroke-miterlimit:10;}.cls-1,.cls-2{stroke:#000;}.cls-2{stroke-miterlimit:2;stroke-width:1.5px;fill-rule:evenodd;}</style>
</defs>
<rect class="cls-1" x=".5" y=".5" width="75.08" height="75.08" rx="9.25"/>
<path class="cls-2" d="M26.14,19.85a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,26.14,19.85Z"/>
<path class="cls-2" d="M62.14,55.85a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,62.14,55.85Z"/>
<path class="cls-2" d="M44.14,37.85a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,44.14,37.85Z"/>
</svg>
""",
"""<?xml version="1.0" encoding="UTF-8"?>
<svg data-name="Layer 1" viewBox="0 0 76.08 76.08" xmlns="http://www.w3.org/2000/svg">
<defs>
<style>.cls-1{fill:#fff;stroke-miterlimit:10;}.cls-1,.cls-2{stroke:#000;}.cls-2{stroke-miterlimit:2;stroke-width:1.5px;fill-rule:evenodd;}</style>
</defs>
<rect class="cls-1" x=".5" y=".5" width="75.08" height="75.08" rx="9.25"/>
<path class="cls-2" d="M26,20a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,26,20Z"/>
<path class="cls-2" d="M26,56a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,26,56Z"/>
<path class="cls-2" d="M62,20a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,62,20Z"/>
<path class="cls-2" d="M62,56a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,62,56Z"/>
</svg>
""",
"""<?xml version="1.0" encoding="UTF-8"?>
<svg data-name="Layer 1" viewBox="0 0 76.08 76.08" xmlns="http://www.w3.org/2000/svg">
<defs>
<style>.cls-1{fill:#fff;stroke-miterlimit:10;}.cls-1,.cls-2{stroke:#000;}.cls-2{stroke-miterlimit:2;stroke-width:1.5px;fill-rule:evenodd;}</style>
</defs>
<rect class="cls-1" x=".5" y=".5" width="75.08" height="75.08" rx="9.25"/>
<path class="cls-2" d="m26.29 19.75a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
<path class="cls-2" d="m26.29 55.75a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
<path class="cls-2" d="m62.29 19.75a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
<path class="cls-2" d="m62.29 55.75a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
<path class="cls-2" d="m44.29 37.75a6.25 6.25 0 1 1-6.29-6.25 6.25 6.25 0 0 1 6.29 6.25z"/>
</svg>
""",
"""<?xml version="1.0" encoding="UTF-8"?>
<svg data-name="Layer 1" viewBox="0 0 76.08 76.08" xmlns="http://www.w3.org/2000/svg">
<defs>
<style>.cls-1{fill:#fff;stroke-miterlimit:10;}.cls-1,.cls-2{stroke:#000;}.cls-2{stroke-miterlimit:2;stroke-width:1.5px;fill-rule:evenodd;}</style>
</defs>
<rect class="cls-1" x=".5" y=".5" width="75.08" height="75.08" rx="9.25"/>
<path class="cls-2" d="M26,19.75a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,26,19.75Z"/>
<path class="cls-2" d="M26,55.75a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,26,55.75Z"/>
<path class="cls-2" d="M26,37.75a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,26,37.75Z"/>
<path class="cls-2" d="M62,19.75a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,62,19.75Z"/>
<path class="cls-2" d="M62,55.75a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,62,55.75Z"/>
<path class="cls-2" d="M62,37.75a6.25,6.25,0,1,1-6.25-6.25A6.25,6.25,0,0,1,62,37.75Z"/>
</svg>
""",
]
<file_sep>/oh/oh_queue/static/js/components/my_appointments.js
function MyAppointments({ state }) {
const studentContent = getMySignups(state)
.filter(
({ appointment }) =>
appointment.status === "active" || isSoon(appointment)
)
.map(({ appointment, signup }) => {
const handleClick =
appointment.status !== "pending" && (() => redirect(appointment.id));
return (
<ConfirmedAppointmentCard
assignments={state.assignments}
locations={state.locations}
appointment={appointment}
signup={signup}
onClick={handleClick}
/>
);
});
const staffContent = getMyAppointmentsStaff(state)
.filter(
(appointment) => appointment.status === "active" || isSoon(appointment)
)
.filter(({ status }) => status !== "resolved")
.filter(({ signups }) => signups.length > 0)
.sort(
(x, y) =>
(+!!y.helper - +!!x.helper) * 2 + appointmentTimeComparator(x, y)
)
.map((appointment) => {
return (
<StaffUpcomingAppointmentCard
appointment={appointment}
locations={state.locations}
/>
);
});
const content =
state.currentUser && state.currentUser.isStaff
? staffContent
: studentContent;
return (
content.length > 0 && (
<div>
<div className="assigned-tickets-header">Upcoming Appointments</div>
{content}
</div>
)
);
}
<file_sep>/examtool/examtool/cli/utils.py
import re
import click
from datetime import date, datetime
from collections import OrderedDict
exam_name_option = click.option(
"--exam", prompt=True, default="cs61a-test-final", help="The exam name."
)
hidden_output_folder_option = click.option(
"--out",
default=None,
help="Output folder. Leave as default for dependent commands to work.",
type=click.Path(),
)
hidden_target_folder_option = click.option(
"--target",
default=None,
help="Target folder for PDFs. Leave as default unless the source output folder is not the default.",
type=click.Path(),
)
def verify_roster(*, roster):
for i, row in enumerate(roster):
j = len(row)
if j != 2 and j != 3:
print(
f"ValueError: The roster must contain 2 or 3 columns: Email, Timestamp, Skip Watermarks [Optional]. "
f"Found {j} item(s) on row {i + 1}: {row}"
)
return False
return True
def prettify(course_code):
m = re.match(r"([a-z]+)([0-9]+[a-z]?)", course_code)
return m and (m.group(1) + " " + m.group(2)).upper()
def determine_semester():
sem_map = OrderedDict()
sem_map["1/1"] = "Spring"
sem_map["6/1"] = "Summer"
sem_map["9/1"] = "Fall"
today = date.today()
def compare_date(DATE_TO_COMPARE):
parsed = (
datetime.strptime(DATE_TO_COMPARE, "%m/%d").date().replace(year=today.year)
)
return parsed > today
sem = next(iter(sem_map))
for DATE_TO_COMPARE, new_sem in sem_map.items():
if compare_date(DATE_TO_COMPARE):
break
sem = new_sem
return f"{sem} {today.year}"
<file_sep>/oh/migrations/versions/7a9d9550b30f_added_online_entries.py
"""added online entries
Revision ID: 7a9d9550b30f
Revises: <KEY>
Create Date: 2020-03-08 21:58:32.016397
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "7a9d9550b30f"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("ticket", sa.Column("call_url", sa.String(length=255), nullable=True))
op.add_column("ticket", sa.Column("doc_url", sa.String(length=255), nullable=True))
op.add_column("user", sa.Column("call_url", sa.String(length=255), nullable=True))
op.add_column("user", sa.Column("doc_url", sa.String(length=255), nullable=True))
# ### end Alembic commands ###
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="online_active", value="false", public=True, course=course[0]
)
)
session.add(
ConfigEntry(
key="students_set_online_link",
value="false",
public=True,
course=course[0],
)
)
session.add(
ConfigEntry(
key="students_set_online_doc",
value="false",
public=True,
course=course[0],
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("ticket", "doc_url")
op.drop_column("ticket", "call_url")
op.drop_column("user", "doc_url")
op.drop_column("user", "call_url")
# ### end Alembic commands ###
<file_sep>/buildserver/github_utils.py
from enum import Enum, unique
from typing import Optional
from urllib.parse import urlparse
from github import Github
from github.PullRequest import PullRequest
from common.db import connect_db
from common.rpc.secrets import get_secret
from common.url_for import url_for
from env import GITHUB_BOT_USER
from target_determinator import determine_targets
def update_status(packed_ref: str, pr_number: int):
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
repo_url, sha = unpack(packed_ref)
repo_name = urlparse(repo_url).path.split(".")[0][
1:
] # This is awful ... but it works
repo = g.get_repo(repo_name)
# First we will update the commit-specific status indicator
with connect_db() as db:
statuses = db(
"SELECT app, status FROM builds WHERE packed_ref=%s", [packed_ref]
).fetchall()
statuses = [(app, BuildStatus(status)) for app, status in statuses]
if all(status == BuildStatus.success for _, status in statuses):
repo.get_commit(sha).create_status(
"success",
"https://logs.cs61a.org/service/buildserver",
"All modified services built!",
"Pusher",
)
elif any(status == BuildStatus.failure for _, status in statuses):
repo.get_commit(sha).create_status(
"failure",
"https://logs.cs61a.org/service/buildserver",
"Pusher failed to build a modified service",
"Pusher",
)
elif all(
status in (BuildStatus.building, BuildStatus.queued) for _, status in statuses
):
repo.get_commit(sha).create_status(
"pending",
"https://logs.cs61a.org/service/buildserver",
"Pusher is building all modified services",
"Pusher",
)
else:
# There are no failures, but not everything is building / built
repo.get_commit(sha).create_status(
"pending",
"https://logs.cs61a.org/service/buildserver",
"You must build all modified apps before merging",
"Pusher",
)
if pr_number == 0:
return
pr = repo.get_pull(pr_number)
# Now we will update the PR comment, looking at builds for all packed_refs in the PR
apps = determine_targets(repo, pr.get_files())
success = []
failure = []
running = []
queued = []
triggerable = []
with connect_db() as db:
for app in apps:
successful_build = db(
"SELECT url, log_url, unix, packed_ref FROM builds WHERE app=%s AND pr_number=%s AND status='success' ORDER BY unix DESC LIMIT 1",
[app, pr_number],
).fetchone()
if successful_build:
url, log_url, success_unix, packed_ref = successful_build
_, sha = unpack(packed_ref)
if url:
for link in url.split(","):
success.append((app, link, sha, log_url))
else:
success.append((app, None, sha, log_url))
failed_build = db(
"SELECT unix, log_url, packed_ref FROM builds WHERE app=%s AND pr_number=%s AND status='failure' ORDER BY unix DESC LIMIT 1",
[app, pr_number],
).fetchone()
if failed_build:
unix, log_url, packed_ref = failed_build
if not successful_build or success_unix < unix:
_, sha = unpack(packed_ref)
failure.append((app, sha, log_url))
running_build = db(
"SELECT packed_ref FROM builds WHERE app=%s AND pr_number=%s AND status='building'",
[app, pr_number],
).fetchone()
if running_build:
[packed_ref] = running_build
_, sha = unpack(packed_ref)
running.append((app, sha))
queued_build = db(
"SELECT packed_ref FROM builds WHERE app=%s AND pr_number=%s AND status='queued'",
[app, pr_number],
).fetchone()
if queued_build:
[packed_ref] = queued_build
_, sha = unpack(packed_ref)
queued.append((app, sha))
latest_commit_build = db(
"SELECT * FROM builds WHERE app=%s AND pr_number=%s AND packed_ref=%s AND status!='pushed'",
[app, pr_number, pack(repo_url, pr.head.sha)],
).fetchone()
if not latest_commit_build:
triggerable.append(app)
if repo.name == "berkeley-cs61a":
message = f"## Build Status ([pr/{pr_number}]({pr.html_url}))\n\n"
elif repo.name == "cs61a-apps":
message = f"## Build Status ([apps/{pr_number}]({pr.html_url}))\n\n"
else:
message = f"## Build Status (#{pr_number})\n\n"
if success:
message += (
"**Successful Builds**\n"
+ "\n".join(
f" - [{host}](https://{host}) ({sha}) [[logs]({log_url})]"
if host
else f" - `{app}` ({sha}) [[logs]({log_url})]"
for app, host, sha, log_url in success
)
+ "\n\n"
)
if failure:
message += (
"**Failed Builds**\n"
+ "\n".join(
f" - `{app}` ({sha}) [[logs]({log_url})]"
for app, sha, log_url in failure
)
+ "\n\n"
)
if running:
message += (
"**Running Builds**\n"
+ "\n".join(f" - `{app}` ({sha})" for app, sha in running)
+ "\n\n"
)
if queued:
message += (
"**Queued Builds**\n"
+ "\n".join(f" - `{app}` ({sha})" for app, sha in queued)
+ "\n\n"
)
if (success or failure or running or queued) and triggerable:
message += "-----\n"
if triggerable:
message += (
f"**[Click here]({url_for('trigger_build', pr_number=pr.number)})** to trigger all builds "
f"for the most recent commit ({pr.head.sha})\n\n"
"Or trigger builds individually:\n"
) + "\n".join(
f" - [Click here]({url_for('trigger_build', pr_number=pr.number, app=app)}) "
f"to build `{app}` at the most recent commit ({pr.head.sha})"
for app in triggerable
)
set_pr_comment(message, pr)
def set_pr_comment(text: str, pr: Optional[PullRequest]):
if pr is None:
return
comments = pr.get_issue_comments()
for comment in comments:
if comment.user.login == GITHUB_BOT_USER:
comment.edit(text)
comment.update()
break
else:
pr.create_issue_comment(text)
def pack(clone_url: str, sha: str) -> str:
"""
Pack the source for a commit into a single str
"""
return clone_url + "|" + sha
def unpack(packed_ref: str):
return packed_ref.split("|")
@unique
class BuildStatus(Enum):
pushed = "pushed"
queued = "queued"
building = "building"
failure = "failure"
success = "success"
<file_sep>/common/course_config.py
import re, requests
from os import getenv
from cachetools import TTLCache
from flask import request
from common.rpc import auth
DOMAIN_COURSES = TTLCache(1000, 1800)
COURSE_ENDPOINTS = TTLCache(1000, 1800)
ENDPOINT_ID = TTLCache(1000, 1800)
def get_course(domain=None):
"""Gets the course code of the course that owns the current domain, using
:meth:`~common.rpc.auth.get_domain`.
:param domain: the domain name in question, inferred using
:meth:`~common.course_config.get_domain` if omitted
:type domain: str
:return: the course code, such as "cs61a"
"""
if getenv("ENV") != "prod":
return "cs61a"
if not domain:
domain = get_domain()
if "pr" in domain:
DOMAIN_COURSES[domain] = "cs61a"
if domain not in DOMAIN_COURSES:
DOMAIN_COURSES[domain] = auth.get_course(domain=domain)
return DOMAIN_COURSES[domain]
def get_domain():
"""Gets the domain that this request is being made on.
:return: the domain name, based on request headers
"""
return request.headers.get("X-Forwarded-For-Host") or request.headers["HOST"]
def get_endpoint(course=None):
"""Gets a course's most recent Okpy endpoint, typically the current
semester's, using :meth:`~common.rpc.auth.get_endpoint`.
:param course: the course code, such as "cs61a", inferred using
:meth:`~common.course_config.get_course` if omitted
:type course: str
:return: the Okpy endpoint, such as "cal/cs61a/sp21"
"""
if getenv("ENV") != "prod":
return "cal/cs61a/sp21"
if not course:
course = get_course()
if course not in COURSE_ENDPOINTS:
COURSE_ENDPOINTS[course] = auth.get_endpoint(course=course)
return COURSE_ENDPOINTS[course]
def get_course_id(course=None):
"""Gets a course's most recent Okpy course ID, typically the current
semester's, using :meth:`~common.rpc.auth.get_endpoint_id`.
:param course: the course code, such as "cs61a", inferred using
:meth:`~common.course_config.get_course` if omitted
:type course: str
:return: the Okpy endpoint, such as 707
"""
if getenv("ENV") != "prod":
return 1
if not course:
course = get_course()
if course not in ENDPOINT_ID:
ENDPOINT_ID[course] = auth.get_endpoint_id(course=course)
return ENDPOINT_ID[course]
def is_admin(email, course=None):
"""Returns whether or not an email address belongs to an admin
for the given course, using :meth:`~common.rpc.auth.is_admin`.
:param email: the email address in question
:type email: str
:param course: the course code, such as "cs61a", inferred using
:meth:`~common.course_config.get_course` if omitted
:type course: str
:return: ``True`` if the user is an admin, ``False`` otherwise
"""
if getenv("ENV") != "prod":
return True
if not course:
course = get_course()
return auth.is_admin(email=email, course=course, force_course=course)
def is_admin_token(access_token, course=None):
"""Returns whether or not an Okpy access token belongs to an admin
for the given course.
:param access_token: the Okpy access token in question
:type access_token: str
:param course: the course code, such as "cs61a", inferred using
:meth:`~common.course_config.get_course` if omitted
:type course: str
:return: ``True`` if the user is an admin, ``False`` otherwise
"""
ret = requests.get(
"https://okpy.org/api/v3/user/", params={"access_token": access_token}
)
return ret.status_code == 200 and is_admin(
ret.json()["data"]["email"],
course=course,
)
def format_coursecode(course):
"""Formats a course code is a pretty way, separating the department from
the course number.
:param course: the course code, such as "cs61a"
:type course: str
:return: prettified course code, such as "CS 61A"
"""
m = re.match(r"([a-z]+)([0-9]+[a-z]?)", course)
return m and (m.group(1) + " " + m.group(2)).upper()
<file_sep>/buildtool/example/src/another.c
#include <stdio.h>
void gobears() {
printf("Go, bears!\n");
}
<file_sep>/search/main.py
import requests
from flask import Flask, redirect
from flask_cors import CORS
from common.rpc.search import (
clear_piazza,
clear_resources,
insert_piazza,
insert_resources,
query,
)
from common.rpc.secrets import only
app = Flask(__name__)
CORS(app)
ELASTIC_SEARCH = "http://localhost:9200"
PIAZZA_INDEX = "piazza"
RESOURCE_INDEX = "resources"
config = {
"mappings": {
"properties": {
"name": {"type": "search_as_you_type"},
"content": {"type": "search_as_you_type"},
"type": {"type": "search_as_you_type"},
"tags": {"type": "search_as_you_type"},
}
},
"settings": {
"analysis": {
"filter": {
"english_stop": {"type": "stop", "stopwords": "_english_"},
"english_keywords": {"type": "keyword_marker", "keywords": ["example"]},
"english_stemmer": {"type": "stemmer", "language": "english"},
"english_possessive_stemmer": {
"type": "stemmer",
"language": "possessive_english",
},
"zero_prefix_remover": {
"type": "pattern_replace",
"pattern": r"0([0-9])+",
"replacement": r"$1",
},
},
"analyzer": {
"default": {
"tokenizer": "standard",
"char_filter": ["html_strip"],
"filter": [
"english_possessive_stemmer",
"lowercase",
"english_stop",
"english_keywords",
"english_stemmer",
"zero_prefix_remover",
],
}
},
}
},
}
@app.route("/")
def index():
return redirect("https://cs61a.org")
@clear_piazza.bind(app)
@only("indexer", allow_staging=True)
def clear_piazza():
requests.delete(f"{ELASTIC_SEARCH}/{PIAZZA_INDEX}").json()
return requests.put(f"{ELASTIC_SEARCH}/{PIAZZA_INDEX}", json=config).json()
@insert_piazza.bind(app)
@only("indexer", allow_staging=True)
def insert_piazza(posts):
for post in posts:
id = post["id"]
requests.post(f"{ELASTIC_SEARCH}/{PIAZZA_INDEX}/_doc/{id}", json=post)
return {"success": True}
@clear_resources.bind(app)
@only("indexer", allow_staging=True)
def clear_resources():
requests.delete(f"{ELASTIC_SEARCH}/{RESOURCE_INDEX}").json()
return requests.put(f"{ELASTIC_SEARCH}/{RESOURCE_INDEX}", json=config).json()
@insert_resources.bind(app)
@only("indexer", allow_staging=True)
def insert_resources(resources):
for resource in resources:
requests.post(f"{ELASTIC_SEARCH}/{RESOURCE_INDEX}/_doc", json=resource)
return {"success": True}
@query.bind(app)
def query(piazza_params, resource_params):
piazza = requests.get(
f"{ELASTIC_SEARCH}/{PIAZZA_INDEX}/_search", json=piazza_params
).json()
resources = requests.get(
f"{ELASTIC_SEARCH}/{RESOURCE_INDEX}/_search", json=resource_params
).json()
return {"piazza": piazza, "resources": resources}
if __name__ == "__main__":
app.run()
<file_sep>/paste/README.md
# `paste`
This app allows users to upload and share text through posts called "pastes"
(similar to pastebin). Try it out at paste.cs61a.org!<file_sep>/ag-master/okpy.py
import base64
import tempfile
import traceback
import time
from typing import Optional
from flask import abort, request
from google.cloud import storage
from common.rpc.ag_master import trigger_jobs
from common.rpc.ag_worker import batch_grade, ping_worker
from common.rpc.auth import get_endpoint
from common.rpc.secrets import only
from common.secrets import new_secret
from models import Assignment, Job, db
from utils import BUCKET
def create_okpy_endpoints(app):
"""Creates various RPC endpoints to interface with Okpy. See the
following:
- :func:`~common.rpc.ag_master.trigger_jobs`
"""
@app.route("/api/ok/v3/grade/batch", methods=["POST"])
def okpy_batch_grade_impl():
data = request.json
subm_ids = data["subm_ids"]
assignment = data["assignment"]
access_token = data["access_token"]
if assignment == "test":
return "OK"
assignment: Optional[Assignment] = Assignment.query.get(assignment)
if not assignment or assignment.endpoint != get_endpoint(
course=assignment.course
):
abort(404, "Unknown Assignment")
if len(subm_ids) / assignment.batch_size > 50:
abort(
405,
"Too many batches! Please set the batch_size so that there are <= 50 batches.",
)
job_secrets = [new_secret() for _ in subm_ids]
queue_time = int(time.time())
jobs = [
Job(
assignment_secret=assignment.assignment_secret,
backup=backup_id,
status="queued",
job_secret=job_secret,
external_job_id=new_secret(),
access_token=access_token,
queued_at=queue_time,
)
for backup_id, job_secret in zip(subm_ids, job_secrets)
]
db.session.bulk_save_objects(jobs)
db.session.commit()
trigger_jobs(
assignment_id=assignment.assignment_secret, jobs=job_secrets, noreply=True
)
return dict(jobs=[job.external_job_id for job in jobs])
@trigger_jobs.bind(app)
@only("ag-master")
def trigger_jobs_impl(assignment_id, jobs):
assignment: Assignment = Assignment.query.get(assignment_id)
job_batches = [
jobs[i : i + assignment.batch_size]
for i in range(0, len(jobs), assignment.batch_size)
]
bucket = storage.Client().get_bucket(BUCKET)
blob = bucket.blob(f"zips/{assignment.endpoint}/{assignment.file}")
with tempfile.NamedTemporaryFile() as temp:
blob.download_to_filename(temp.name)
with open(temp.name, "rb") as zf:
encoded_zip = base64.b64encode(zf.read()).decode("ascii")
for job_batch in job_batches:
try:
ping_worker(retries=3)
batch_grade(
command=assignment.command,
jobs=job_batch,
grading_zip=encoded_zip,
noreply=True,
timeout=8,
)
except:
Job.query.filter(Job.job_secret.in_(job_batch)).update(
{
Job.status: "failed",
Job.result: "trigger_job error\n" + traceback.format_exc(),
},
synchronize_session="fetch",
)
db.session.commit()
@app.route("/results/<job_id>", methods=["GET"])
def get_results_for(job_id):
job = Job.query.filter_by(external_job_id=job_id).one()
if job.status in ("finished", "failed"):
return job.result, 200
return "Nope!", 202
@app.route("/results", methods=["POST"])
def get_results_impl():
job_ids = request.json
jobs = Job.query.filter(Job.external_job_id.in_(job_ids)).all()
res = {
job.external_job_id: dict(status=job.status, result=job.result)
for job in jobs
}
for job in job_ids:
if job not in res:
res[job] = None
return res
<file_sep>/sicp/sicp/venv.py
import click
from common.shell_utils import sh
import os, shutil
ENV = "env"
REQ = "requirements.txt"
@click.command()
@click.argument("dir", default="./")
@click.argument("req", default="./")
@click.option("--reset", is_flag=True)
def venv(dir, req, reset):
"""Create a virtual environment in DIR.
DIR is the location of the virtual env
(minus the `env` folder itself). REQ is
the location of the requirements file.
Both of these arguments default to `./`.
If you want to forcibly recreate an env,
use the RESET option.
"""
if not dir.endswith("/"):
dir = dir + "/"
if req.endswith("requirements.txt"):
req = req[:-16]
if not req.endswith("/"):
req = req + "/"
if os.path.exists(f"{dir}{ENV}"):
if reset:
shutil.rmtree(f"{dir}{ENV}")
else:
print("This environment already exists!")
return
sh("python3", "-m", "venv", f"{dir}{ENV}")
sh(f"{dir}{ENV}/bin/pip3", "install", "-r", f"{req}{REQ}")
<file_sep>/examtool_web_common/js/ExamAlerts.js
import React, { useEffect, useRef, useState } from "react";
import { Modal } from "react-bootstrap";
import Button from "react-bootstrap/Button";
import Toast from "react-bootstrap/Toast";
import AlertsContext from "./AlertsContext";
import AskQuestion from "./AskQuestion";
import StudentMessagesList from "./StudentMessagesList";
import { timeDeltaMinutesString } from "./timeUtils";
import useExamAlertsData from "./useExamAlertsData";
import useTick from "./useTick";
export default function ExamAlerts({ exam, setDeadline }) {
const [fail, setFail] = useState(false);
const [show, setShow] = useState(true);
const [showModal, setShowModal] = useState(false);
const announcementListRef = useRef();
const [examData, stale, onConnect, send] = useExamAlertsData(
exam,
false,
setDeadline,
() => {
setShow(true);
announcementListRef.current.scrollTop =
announcementListRef.current.scrollHeight;
}
);
const time = useTick();
useEffect(() => {
onConnect().then((err) => !err || setFail(true));
}, []);
return (
<AlertsContext.Provider value={{ time, examData, stale }}>
<div
ref={announcementListRef}
style={{
position: "fixed",
overflow: "auto",
bottom: 80,
right: 32,
width: 350,
maxHeight: "80%",
}}
>
{show &&
examData &&
examData.announcements
.slice()
.reverse()
.map(
({
id,
message,
question,
timestamp: announcementTime,
private: isPrivate,
}) => (
<Toast key={id}>
<Toast.Header closeButton={false}>
<strong className="mr-auto">
{isPrivate ? (
"Staff Reply"
) : (
<>Announcement for {question}</>
)}
</strong>
<small>
{timeDeltaMinutesString(time - announcementTime)}
</small>
</Toast.Header>
<Toast.Body>
<div style={{ whiteSpace: "pre-wrap" }}>{message}</div>
</Toast.Body>
</Toast>
)
)}
</div>
<div
style={{
position: "fixed",
bottom: 32,
right: 32,
width: 350,
background: "white",
}}
>
<Button
block
onClick={() => setShow((x) => !x)}
variant="outline-secondary"
>
{show ? "Hide Announcements" : "Show Announcements"}
{stale ? " (Offline)" : ""}
{examData ? "" : " (Loading...)"}
</Button>
</div>
{examData && examData.enableClarifications && (
<div
style={{
position: "fixed",
bottom: 32,
left: 32,
width: 200,
background: "white",
}}
>
<Button
block
onClick={() => setShowModal(true)}
variant="outline-secondary"
>
Clarifications
</Button>
</div>
)}
{fail && (
<Modal show>
<Modal.Header closeButton>
<Modal.Title>Network Connection Lost!</Modal.Title>
</Modal.Header>
<Modal.Body>
The tool was unable to fetch announcements from the server. Please
refresh and try again. If this error persists, contact your course
staff.
</Modal.Body>
</Modal>
)}
{examData && examData.enableClarifications && (
<Modal show={showModal} onHide={() => setShowModal(false)} size="lg">
<Modal.Header>Ask a question</Modal.Header>
<Modal.Body>
<AskQuestion exam={exam} send={send} />
<StudentMessagesList />
</Modal.Body>
</Modal>
)}
</AlertsContext.Provider>
);
}
<file_sep>/oh/oh_queue/static/js/components/not_found.js
// TODO make this prettier
let NotFound = () => (
<div className="container">
<div className="row">
<div className="col-xs-12">
<h1 className="text-center">Not found</h1>
<p className="text-center">
This request does not exist or you don't have permission to view it
</p>
</div>
</div>
</div>
);
<file_sep>/code/src/web-server/embed_handler.py
from flask import render_template, request
def create_embed_handler(app):
@app.route("/embed")
@app.route("/embed2")
def serve_embed():
data = {
"fileName": request.args["fileName"],
"data": request.args["data"],
"shareRef": None,
}
return render_template(
"index.html",
initData={
"loadFile": data,
"srcOrigin": request.args["srcOrigin"],
},
)
<file_sep>/oh/oh_queue/slack.py
from collections import defaultdict, namedtuple
from datetime import timedelta, datetime
from typing import List
from common.rpc.auth import post_slack_message
from oh_queue.models import (
CourseNotificationState,
Ticket,
TicketStatus,
Appointment,
get_current_time,
AppointmentStatus,
db,
ConfigEntry,
)
def make_send(course):
def send(message):
post_slack_message(
course=course, message=message, purpose="oh-queue", noreply=True
)
return send
def worker(app):
with app.app_context():
course_notif_states: List[
CourseNotificationState
] = CourseNotificationState.query.all()
for notif_state in course_notif_states:
queue_url = "https://{}".format(notif_state.domain)
course = notif_state.course
send = make_send(course)
if (
ConfigEntry.query.filter_by(key="slack_notif_long_queue", course=course)
.one()
.value
== "true"
):
# check for overlong queue
if datetime.now() - notif_state.last_queue_ping > timedelta(hours=8):
queue_len = Ticket.query.filter_by(
course=course, status=TicketStatus.pending
).count()
if queue_len > 10:
send(
"<!here> The OH queue currently has more than {} students waiting. "
"If you can, please drop by and help! Go to the <{}|OH Queue> to see more.".format(
queue_len, queue_url
)
)
notif_state.last_queue_ping = datetime.now()
if (
ConfigEntry.query.filter_by(
key="slack_notif_missed_appt", course=course
)
.one()
.value
== "true"
):
# check for appointments that should have started
appointments = Appointment.query.filter(
Appointment.start_time < get_current_time() - timedelta(minutes=2),
Appointment.status == AppointmentStatus.pending,
Appointment.course == course,
).all()
for appointment in appointments:
if appointment.num_reminders_sent >= 2:
continue
if len(appointment.signups) > 0:
appointment_url = "{}/appointments/{}".format(
queue_url, appointment.id
)
if appointment.helper:
if appointment.num_reminders_sent == 0:
send(
"<!{email}> You have an appointment right now that hasn't started, and students are "
"waiting! Your appointment is {location}. Go to the <{appointment_url}|OH Queue> to see more "
"information.".format(
email=appointment.helper.email,
location="*Online*"
if appointment.location.name == "Online"
else "at *{}*".format(
appointment.location.name
),
appointment_url=appointment_url,
)
)
else:
send(
"<!here> {name}'s appointment is right now but hasn't started, and students are "
"waiting! The appointment is {location}. Can anyone available help out? "
"Go to the <{appointment_url}|OH Queue> to see more information.".format(
name=appointment.helper.name,
location="*Online*"
if appointment.location.name == "Online"
else "at *{}*".format(
appointment.location.name
),
appointment_url=appointment_url,
)
)
else:
send(
"<!here> An appointment is scheduled for right now that hasn't started, and students "
"are waiting! *No staff member has signed up for it!* The appointment is {location}. "
"Go to the <{appointment_url}|OH Queue> to see more information.".format(
location="*Online*"
if appointment.location.name == "Online"
else "at *{}*".format(appointment.location.name),
appointment_url=appointment_url,
)
)
else:
if not appointment.helper:
send(
"An appointment is scheduled right now that hasn't started, but no students have "
"signed up *and no staff member was assigned*. I am automatically resolving the "
"appointment. Be careful - a student _could_ have signed up since the appointment "
"wasn't hidden."
)
appointment.status = AppointmentStatus.resolved
appointment.num_reminders_sent += 1
if (
ConfigEntry.query.filter_by(
key="slack_notif_appt_summary", course=course
)
.one()
.value
== "true"
):
if notif_state.last_appointment_notif.day != get_current_time().day:
# send appointment summary
notif_state.last_appointment_notif = get_current_time()
send_appointment_summary(course)
db.session.commit()
def send_appointment_summary(course):
appointments = Appointment.query.filter(
get_current_time() < Appointment.start_time,
Appointment.start_time < get_current_time() + timedelta(days=1),
Appointment.status == AppointmentStatus.pending,
Appointment.course == course,
).all()
Upcoming = namedtuple("Upcoming", ["total", "nonempty", "start_time"])
staff = defaultdict(lambda: Upcoming(0, 0, None))
for appointment in appointments:
if appointment.helper:
old = staff[appointment.helper.email]
staff[appointment.helper.email] = old._replace(
total=old.total + 1,
nonempty=old.nonempty + int(bool(appointment.signups)),
start_time=min(
old.start_time or appointment.start_time, appointment.start_time
),
)
if not staff:
return
make_send(course)(
[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Hi all! You all have appointments today (Pacific Time).",
},
},
{"type": "divider"},
*[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "<!{email}>\nYou have *{total}* appointments, "
"*{nonempty}* of which currently have students signed up. "
"Your first appointment begins at {time} Pacific Time, "
"in about {delta} hours from the time of this message.".format(
email=email,
total=upcoming.total,
nonempty=upcoming.nonempty,
time=upcoming.start_time.strftime("%I:%M%p"),
delta=(upcoming.start_time - get_current_time()).seconds
// 3600,
),
},
}
for email, upcoming in staff.items()
],
{"type": "divider"},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Remember that if you can't make your appointment you should unassign "
"yourself and notify someone to replace you. If you want to remove "
"yourself from an appointment with no students, just hit the "
":double_vertical_bar: icon or just resolve the appointment.",
},
},
]
)
<file_sep>/sections/src/StateContext.js
// @flow strict
import * as React from "react";
import type { State } from "./models";
export default React.createContext<{
...State,
updateState: (State) => void,
}>({
config: {
canStudentsChange: true,
canTutorsChange: true,
canTutorsReassign: true,
message: "",
},
currentUser: null,
sections: [],
history: [],
taughtSections: [],
enrolledSection: null,
updateState: () => {},
});
<file_sep>/common/rpc/utils.py
import json
import traceback
from functools import wraps
from time import sleep
from typing import List
from urllib.error import HTTPError
import flask
import requests
from cachetools import TTLCache
from flask import Response, has_request_context, jsonify, request, stream_with_context
from common.rpc.auth_utils import get_token, refresh_token
from common.secrets import get_master_secret
STATUS_MARKER = "__INTERNAL_STATUS_MARKER"
GCP_INTERNAL_ERROR_CODE = 503
class Service:
def __init__(self, route):
self.route = route
def find_default_endpoints(app: str, path: str):
endpoints = []
if has_request_context():
proxied_host = request.headers.get("X-Forwarded-For-Host")
if proxied_host:
parts = proxied_host.split(".")
if "pr" in parts:
pr = parts[0]
endpoints.append(f"https://{pr}.{app}.pr.cs61a.org{path}")
endpoints.append(f"https://{app}.cs61a.org{path}")
return endpoints
def select_endpoint(endpoints: List[str], path: str, retries: int):
# try all the PR candidates
for i, endpoint in enumerate(endpoints[:-1]):
try:
for _ in range(retries + 1):
# check if the PR / endpoint exists
check_exists = requests.get(
endpoint[: -len(path)],
allow_redirects=False,
)
if check_exists.status_code == GCP_INTERNAL_ERROR_CODE:
# this error is not our fault, retry after a short pause
sleep(1)
continue
check_exists.raise_for_status()
return endpoint
else:
# if we exhaust all our retries, give up on this endpoint
continue
except (HTTPError, requests.ConnectionError):
continue
# fall back to prod
return endpoints[-1]
def stream_encode(out):
try:
for x in out:
yield bytes(x, encoding="ascii", errors="replace")
except Exception as e:
yield STATUS_MARKER
yield bytes(str(e), encoding="ascii", errors="replace")
else:
yield STATUS_MARKER
def receive_stream(resp: Response):
buffer = []
ok = True
for x in resp.iter_content():
buffer.append(x.decode("ascii"))
buff_string = "".join(buffer)
if STATUS_MARKER in buff_string:
# We are now reading in the error message
# Stop flushing the buffer
ok = False
if ok and len(buff_string) > len(STATUS_MARKER):
yield buff_string[: -len(STATUS_MARKER)]
buffer = [buff_string[-len(STATUS_MARKER) :]]
buff_string = "".join(buffer)
if not buff_string.endswith(STATUS_MARKER):
# some error occurred
pos = buff_string.index(STATUS_MARKER)
raise Exception(buff_string[pos + len(STATUS_MARKER) :])
yield from buffer[: -len(STATUS_MARKER)]
def create_service(app: str, override=None, providers=None):
app = override or app.split(".")[-1]
def route(path, *, streaming=False):
def decorator(func):
@wraps(func)
def wrapped(*, noreply=False, timeout=1, retries=0, **kwargs):
assert (
not noreply or not retries
), "Cannot retry a noreply request, use streaming instead"
if providers:
endpoints = [f"{provider}{path}" for provider in providers]
else:
endpoints = find_default_endpoints(app, path)
endpoint = select_endpoint(endpoints, path, retries)
if noreply:
try:
requests.post(endpoint, json=kwargs, timeout=timeout)
except requests.exceptions.ReadTimeout:
return
else:
for _ in range(retries + 1):
resp = requests.post(endpoint, json=kwargs, stream=streaming)
if resp.status_code == GCP_INTERNAL_ERROR_CODE:
sleep(1)
continue
break
else:
# we exhausted all our retries
resp.raise_for_status()
if resp.status_code == 401:
raise PermissionError(resp.text)
elif resp.status_code == 500:
raise Exception(resp.text)
resp.raise_for_status()
if streaming:
return receive_stream(resp)
else:
return resp.json()
def bind(app: flask.Flask):
def decorator(func):
def handler():
kwargs = request.json
try:
out = func(**kwargs)
if streaming:
return Response(stream_with_context(stream_encode(out)))
else:
return jsonify(out)
except PermissionError as e:
return "", 401
except Exception as e:
traceback.print_exc()
print(str(e))
return "", 500
app.add_url_rule(path, func.__name__, handler, methods=["POST"])
return func
return decorator
wrapped.bind = bind
return wrapped
return decorator
return Service(route)
def requires_master_secret(func):
@wraps(func)
def wrapped(*, _impersonate=None, _sudo_token=None, **kwargs):
if _sudo_token:
return func(**kwargs, _impersonate=_impersonate, _sudo_token=_sudo_token)
elif not get_master_secret() and _impersonate and not _sudo_token:
from common.rpc.secrets import (
get_secret_from_server,
) # placed here to avoid circular imports
print(f"Attempting to impersonate {_impersonate}")
try:
sudo_secret = get_secret_from_server(
secret_name="MASTER",
_impersonate=_impersonate,
_sudo_token=get_token(),
)
except PermissionError:
refresh_token()
try: # second attempt, in case the first was just an expired token
sudo_secret = get_secret_from_server(
secret_name="MASTER",
_impersonate=_impersonate,
_sudo_token=get_token(),
)
except PermissionError:
raise PermissionError(
"You must be logged in as an admin to do that."
)
master_secret = sudo_secret
else:
master_secret = get_master_secret()
return func(**kwargs, master_secret=master_secret)
return wrapped
def requires_access_token(func):
@wraps(func)
def wrapped(**kwargs):
try:
return func(**kwargs, access_token=get_token())
except PermissionError:
refresh_token()
return func(**kwargs, access_token=get_token())
return wrapped
def cached(ttl: int = 1800):
"""
Caches the return value of this RPC method for `ttl` seconds (defaults to 1800s)
"""
cache = TTLCache(1000, ttl)
def decorator(func):
@wraps(func)
def wrapped(**kwargs):
key = json.dumps(kwargs)
if key not in cache:
cache[key] = func(**kwargs)
return cache[key]
return wrapped
return decorator
<file_sep>/shortlinks/README.md
# Shortlinks
Handler for go.cs61a.org and links.cs61a.org shortlinks.
## Local Development
Create and activate a venv:
```bash
$ python3 -m venv env
$ source env/bin/activate
```
Use `pip` to install all the dependencies:
```bash
$ pip install -r requirements.txt
```
Run the server:
```bash
$ python main.py
```<file_sep>/examtool/examtool/cli/identify_watermark.py
import click
import cv2
from examtool.api.database import get_exam, get_roster
from examtool.api.watermark_decoder import decode_watermark
from examtool.api.watermarks import Point
from examtool.cli.utils import exam_name_option
@click.command()
@exam_name_option
@click.option(
"--image",
prompt=True,
type=click.Path(exists=True),
help="The image or screenshot you wish to identify.",
)
def identify_watermark(exam, image):
"""
Identify the student from a screenshot containing a watermark.
"""
img = cv2.imread(image)
img = cv2.copyMakeBorder(img, 100, 100, 100, 100, cv2.BORDER_CONSTANT)
corners = []
bits = []
def handle_click(event, x, y, flags, params):
if event == cv2.EVENT_LBUTTONDOWN:
bits.append(Point(x, y))
cv2.circle(img, (x, y), 5, (255, 0, 0), -1)
if event == cv2.EVENT_RBUTTONDOWN:
corners.append(Point(x, y))
cv2.circle(img, (x, y), 5, (0, 255, 0), -1)
cv2.namedWindow("image")
cv2.setMouseCallback("image", handle_click)
while True:
cv2.imshow("image", img)
if cv2.waitKey(20) & 0xFF == 13:
break
print(decode_watermark(get_exam(exam=exam), get_roster(exam=exam), corners, bits))
<file_sep>/examtool_web_common/js/StaffMessageReplyBox.js
import React, { useState } from "react";
import { Form } from "react-bootstrap";
import FailText from "./FailText";
import LoadingButton from "./LoadingButton";
export default function StaffMessageReplyBox({ compact, message, send }) {
const [reply, setReply] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [failText, setFailText] = useState("");
const submit = async (reject) => {
setIsLoading(true);
const err = await send("send_response", {
id: message,
reply: compact
? reject
? "Staff cannot answer this question"
: "Staff has read your message"
: reply,
});
if (err) {
setFailText(err);
} else {
setReply("");
}
setIsLoading(false);
};
return (
<>
{!compact && (
<Form.Group>
<Form.Control
as="textarea"
rows={3}
value={reply}
placeholder="Reply to the private message."
onChange={(e) => setReply(e.target.value)}
/>
</Form.Group>
)}
<Form.Group>
<LoadingButton
loading={isLoading}
disabled={isLoading}
onClick={submit}
size={compact && "sm"}
variant={compact ? "warning" : "primary"}
>
{compact ? "โ" : "Send"}
</LoadingButton>
{compact && (
<LoadingButton
loading={isLoading}
disabled={isLoading}
onClick={() => submit(true)}
size={compact && "sm"}
variant="secondary"
>
โ
</LoadingButton>
)}
<FailText text={failText} suffixType="alerts" />
</Form.Group>
</>
);
}
<file_sep>/slack/build_integration.py
import re
import requests
from common.rpc.auth import is_admin
from common.rpc.buildserver import trigger_build_sync
from integration import Integration
VALID_PATH = r"[0-9A-Za-z\-]+"
PATH_REGEX = rf"(?P<path>{VALID_PATH})"
REGEX_TEMPLATE = fr"(https?://)?github\.com/Cal-CS-61A-Staff/cs61a-apps/pull/{PATH_REGEX}/?(\|[^\s|]+)?"
class BuildIntegration(Integration):
reply = None
def _process(self):
if "friend computer please build" not in self._message.lower():
return
if "cs61a" != self._course:
return
users = requests.get(
"https://slack.com/api/users.list", params={"token": self._bot_token}
).json()
for member in users["members"]:
if member["id"] == self._event["user"]:
sender_email = member["profile"].get("email")
break
if not sender_email or not is_admin(course="cs61a", email=sender_email):
return
match = re.search(REGEX_TEMPLATE, self._message)
if not match:
return
try:
pr = int(match.group("path"))
except ValueError:
return
trigger_build_sync(pr_number=pr, noreply=True)
self.reply = ":building_construction: Build triggered!"
@property
def message(self):
if self.reply:
return self._message + "\n\n" + self.reply
else:
return self._message
<file_sep>/sicp/sicp/build.py
import os
import pathlib
import sys
import time
import webbrowser
from base64 import b64encode
from os.path import relpath
from threading import Thread
from typing import Union
import click
import requests
from cachetools import LRUCache
from colorama import Fore, Style
from crcmod.crcmod import _usingExtension
from crcmod.predefined import mkPredefinedCrcFun
from tqdm import tqdm
from watchdog.events import (
DirMovedEvent,
FileMovedEvent,
FileSystemEvent,
FileSystemEventHandler,
)
from watchdog.observers import Observer
from common.cli_utils import pretty_print
from common.rpc.auth_utils import get_token
from common.rpc.sandbox import (
get_server_hashes,
initialize_sandbox,
is_sandbox_initialized,
run_make_command,
update_file,
)
from common.shell_utils import sh
# TODO: Properly indicate if the extension is not installed
REPO = "berkeley-cs61a"
SYMLINK = "SYMLINK"
SUCCESS = "SUCCESS"
tracked_files = set()
remote_state = {}
recent_files = LRUCache(15)
do_build = True
def find_target():
if not hasattr(find_target, "out"):
remote = sh(
"git",
"config",
"--get",
"remote.origin.url",
capture_output=True,
quiet=True,
).decode("utf-8")
if REPO not in remote:
raise Exception(
"You must run this command in the berkeley-cs61a repo directory"
)
find_target.out = (
sh("git", "rev-parse", "--show-toplevel", capture_output=True, quiet=True)
.decode("utf-8")
.strip()
)
return find_target.out
def get_sandbox_url():
username = requests.get(
"https://okpy.org/api/v3/user/", params={"access_token": get_token()}
).json()["data"]["email"][: -len("<EMAIL>")]
return f"https://{username}.sb.cs61a.org"
@click.command()
def build():
os.chdir(find_target())
if not is_sandbox_initialized():
print("Sandbox is not initialized.")
if click.confirm(
"You need to initialize your sandbox first. Continue?", default=True
):
initialize_sandbox()
for line in run_make_command(target="virtualenv"):
print(line, end="")
print()
else:
return
print("Please wait until synchronization completes...")
print("Scanning local directory...")
full_synchronize_with_remote(get_server_hashes, show_progress=True)
sandbox_url = get_sandbox_url()
print(
f"Synchronization completed! You can now begin developing. Preview your changes at {sandbox_url}"
)
webbrowser.open(sandbox_url)
Thread(target=catchup_synchronizer_thread, daemon=True).start()
Thread(target=catchup_full_synchronizer_thread, daemon=True).start()
Thread(target=file_events_thread, daemon=True).start()
# run this thread on the main thread to handle KeyboardInterrupts
input_thread()
def input_thread():
try:
import readline
except ImportError:
# todo: use pyreadline on windows
pass
try:
while True:
print(Style.BRIGHT, end="")
target = input("make> ")
print(Style.RESET_ALL, end="")
if not target.strip():
continue
try:
for line in run_make_command(target=target):
print(line, end="")
except KeyboardInterrupt:
print(Fore.RED)
pretty_print("๐ซ", "Build cancelled.")
except Exception as e:
print(Fore.RED)
print(str(e))
pretty_print("๐ฟ", "Build failed.")
else:
print(Fore.GREEN)
pretty_print("๐", "Build completed!")
except KeyboardInterrupt:
pretty_print("๐", "Interrupt signal received, have a nice day!")
sys.exit(0)
def file_events_thread():
while True:
observer = Observer()
try:
observer.schedule(Handler(), find_target(), recursive=True)
observer.start()
for _ in range(15):
time.sleep(1)
finally:
observer.stop()
observer.join()
def catchup_synchronizer_thread():
while True:
recent_synchronization()
time.sleep(1)
def catchup_full_synchronizer_thread():
while True:
full_synchronize_with_remote()
time.sleep(15)
class Handler(FileSystemEventHandler):
def on_any_event(self, event: FileSystemEvent):
synchronize(event.src_path)
def on_moved(self, event: Union[DirMovedEvent, FileMovedEvent]):
synchronize(event.dest_path)
def synchronize(path: str):
os.chdir(find_target())
path = relpath(path)
if isinstance(path, bytes):
path = path.decode("ascii")
if path not in tracked_files:
# do not synchronize untracked files
# if this is a file just created, it will be tracked on the next full_synchronization pass
return
recent_files[path] = None
# path is a path to either a file or a symlink, NOT a directory
if os.path.islink(path):
update_file(path=path, symlink=os.readlink(path))
elif os.path.isfile(path):
with open(path, "rb") as f:
update_file(
path=path, encoded_file_contents=b64encode(f.read()).decode("ascii")
)
elif not os.path.exists(path):
update_file(path=path, delete=True)
remote_state[path] = get_hash(path)
def recent_synchronization():
for path in set(recent_files.keys()): # set() is needed to avoid concurrency issues
if remote_state.get(path) != get_hash(path):
synchronize(path)
def full_synchronize_with_remote(remote_state_getter=None, show_progress=False):
global remote_state
current_state = hash_all(show_progress=show_progress)
if callable(remote_state_getter):
# When we want to fetch it lazily
if show_progress:
print("Fetching server state...")
remote_state = remote_state_getter()
paths = set(current_state) | set(remote_state)
to_update = []
for path in paths:
if current_state.get(path) != remote_state.get(path):
to_update.append(path)
for path in tqdm(to_update) if show_progress else to_update:
synchronize(path)
remote_state = current_state
def get_hash(path):
assert _usingExtension, "You must use the crcmod C extension"
if isinstance(path, bytes):
path = path.decode("ascii")
hash_func = mkPredefinedCrcFun("crc-32")
if os.path.islink(path):
return SYMLINK + os.readlink(path)
try:
with open(path, "rb") as f:
return hash_func(f.read())
except FileNotFoundError:
return
except IsADirectoryError:
return
def hash_all(show_progress=False):
global tracked_files
files = (
sh(
"git", "ls-files", "--exclude-standard", capture_output=True, quiet=True
).splitlines() # All tracked files
+ sh(
"git",
"ls-files",
"-o",
"--exclude-standard",
capture_output=True,
quiet=True,
).splitlines() # Untracked but not ignored files
)
out = {}
for file in tqdm(files) if show_progress else files:
h = get_hash(file)
if isinstance(file, bytes):
file = file.decode("ascii")
out[relpath(file)] = h
tracked_files = set(out) | set(remote_state)
return out
<file_sep>/buildtool/buildtool/context.py
from __future__ import annotations
import os
from abc import ABC
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Union
from fs_utils import normalize_path
from common.hash_utils import HashState
Env = Dict[str, Union[str, List[str]]]
@dataclass
class ContextualRelativePath:
path: str
context: Context
def resolve(self):
return str(self)
def __str__(self):
return os.path.relpath(
Path(self.context.repo_root).joinpath(self.path), self.context.cwd
)
class DotDict:
def __init__(self):
self.items = {}
def __getitem__(self, item):
return self.items[item]
def __setitem__(self, key, value):
self.items[key] = value
class Context(ABC):
def __init__(self, repo_root: str, cwd: str):
self.repo_root = repo_root
self.cwd = os.path.abspath(cwd)
self.deps = DotDict()
def absolute(self, path: str):
return normalize_path(self.repo_root, self.cwd, path)
def relative(self, path: str):
return ContextualRelativePath(self.absolute(path), self)
def chdir(self, dest: str):
self.cwd = os.path.abspath(
Path(self.repo_root).joinpath(
normalize_path(self.repo_root, self.cwd, dest)
)
)
def sh(self, cmd: str, env: Env = None):
raise NotImplementedError
def add_dep(self, dep: str):
self.add_deps([dep])
def add_deps(self, deps: Sequence[str]):
raise NotImplementedError
def input(self, *, file: Optional[str], sh: Optional[str], env: Env = None):
raise NotImplementedError
class MemorizeContext(Context):
def __init__(self, repo_root: str, cwd: str, hashstate: HashState):
super().__init__(repo_root, cwd)
self.hashstate = hashstate
self.inputs = []
self.uses_dynamic_inputs = False
self.hashstate.record(self.absolute(self.cwd))
def chdir(self, dest: str):
super().chdir(dest)
self.hashstate.record("chdir", dest)
def sh(self, cmd: str, env: Env = None):
self.hashstate.record("sh", cmd, env)
def add_deps(self, deps: Sequence[str]):
self.hashstate.record("add_deps", deps)
for dep in deps:
if dep.startswith(":"):
self.inputs.append(dep)
else:
self.inputs.append(self.absolute(dep))
def input(self, *, file: Optional[str], sh: Optional[str], env: Env = None):
self.uses_dynamic_inputs = True
self.hashstate.record("input", file, sh, env)
if file is not None:
self.inputs.append(self.absolute(file))
<file_sep>/auth/piazza_client.py
from flask import request, jsonify, redirect
from piazza_api import Piazza
from auth_utils import key_secure, course_oauth_secure
from common.db import connect_db
from common.html import html
from common.rpc.auth import perform_piazza_action, piazza_course_id
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS piazza_config (
course_id varchar(256),
test_course_id varchar(256),
student_user varchar(256),
student_pw varchar(256),
staff_user varchar(256),
staff_pw varchar(256),
course varchar(128)
)"""
)
init_db()
def create_piazza_client(app):
def piazza_help(course):
with connect_db() as db:
ret = db(
"SELECT student_user, staff_user, course_id, test_course_id FROM piazza_config WHERE course=%s",
[course],
).fetchone()
student_email, staff_email, course_id, test_course_id = (
ret if ret else [""] * 4
)
return f"""
<h3> Piazza Service Accounts </h3>
Student email address: <a href="mailto:{student_email}">{student_email}</a>
<p>
Staff email address: <a href="mailto:{staff_email}">{staff_email}</a>
<p>
Piazza course: <a href="https://piazza.com/class/{course_id}">https://piazza.com/class/{course_id}</a>
<p>
Test Piazza course: <a href="https://piazza.com/class/{test_course_id}">https://piazza.com/class/{test_course_id}</a>
<p>
Enroll these accounts on the latest course Piazza.
<p>
To configure, go to <a href="/piazza/{course}/config">Piazza Config</a>.
"""
app.help_info.add(piazza_help)
# noinspection PyPep8Naming
@app.route("/piazza/<action>", methods=["POST"])
def perform_action_DEPRECATED_DO_NOT_USE(action):
kwargs = dict(request.json)
del kwargs["client_name"]
is_test = kwargs.pop("test", False)
as_staff = kwargs.pop("staff")
secret = kwargs.pop("secret")
course = kwargs.pop("course", None)
kwargs.pop("test", None)
return jsonify(
perform_action(
secret=secret,
course=course,
action=action,
as_staff=as_staff,
is_test=is_test,
kwargs=kwargs,
)
)
@perform_piazza_action.bind(app)
@key_secure
def perform_action(action, course, as_staff=False, is_test=None, kwargs=None):
with connect_db() as db:
if as_staff:
user, pw = db(
"SELECT staff_user, staff_pw FROM piazza_config WHERE course = (%s)",
[course],
).fetchone()
else:
user, pw = db(
"SELECT student_user, student_pw FROM piazza_config WHERE course = (%s)",
[course],
).fetchone()
if is_test:
(course_id,) = db(
"SELECT test_course_id FROM piazza_config WHERE course = (%s)",
[course],
).fetchone()
else:
(course_id,) = db(
"SELECT course_id FROM piazza_config WHERE course = (%s)", [course]
).fetchone()
p = Piazza()
p.user_login(user, pw)
course = p.network(course_id)
if kwargs is None:
kwargs = {}
try:
return getattr(course, action)(**kwargs)
except Exception as e:
return str(e), 400
# noinspection PyUnusedLocal `staff` exists only for API backwards compatibility
@piazza_course_id.bind(app)
@key_secure
def course_id(course, staff=False, test=False, is_test=False):
is_test = test or is_test # test exists for backwards compatibility only
with connect_db() as db:
if is_test:
(course_id,) = db(
"SELECT test_course_id FROM piazza_config WHERE course=(%s)",
[course],
).fetchone()
else:
(course_id,) = db(
"SELECT course_id FROM piazza_config WHERE course=(%s)", [course]
).fetchone()
return course_id
@app.route("/piazza/<course>/config", methods=["GET"])
@course_oauth_secure()
def piazza_config(course):
return html(
f"""
Enter account details for Piazza service accounts. Leave fields blank to avoid updating them.
Ensure that these accounts are enrolled in the appropriate Piazzas!
<form action="/piazza/{course}/set_config" method="post">
<label>
Piazza course ID <br />
<input name="course_id" type="text"> <br />
</label>
<label>
Test Piazza course ID <br />
<input name="test_course_id" type="text"> <br />
</label>
<br />
<label>
Student Username <br />
<input name="student_user" type="text"> <br />
</label>
<label>
Student Password <br />
<input name="student_pw" type="<PASSWORD>"> <br />
</label>
<br />
<label>
Staff Username <br />
<input name="staff_user" type="text"> <br />
</label>
<label>
Staff Password <br />
<input name="staff_pw" type="<PASSWORD>"> <br />
</label>
<label>
<input type="submit">
</form>
"""
)
@app.route("/piazza/<course>/set_config", methods=["POST"])
@course_oauth_secure()
def set_piazza_config(course):
with connect_db() as db:
ret = db(
"SELECT * FROM piazza_config WHERE course=(%s)", [course]
).fetchone()
if ret:
(
course_id,
test_course_id,
student_user,
student_pw,
staff_user,
staff_pw,
_,
) = ret
else:
(
course_id,
test_course_id,
student_user,
student_pw,
staff_user,
staff_pw,
) = [""] * 6
course_id = request.form["course_id"] or course_id
test_course_id = request.form["test_course_id"] or test_course_id
student_user = request.form["student_user"] or student_user
student_pw = request.form["student_pw"] or student_pw
staff_user = request.form["staff_user"] or staff_user
staff_pw = request.form["staff_pw"] or staff_pw
with connect_db() as db:
db("DELETE FROM piazza_config WHERE course=(%s)", [course])
db(
"INSERT INTO piazza_config VALUES (%s, %s, %s, %s, %s, %s, %s)",
[
course_id,
test_course_id,
student_user,
student_pw,
staff_user,
staff_pw,
course,
],
)
return redirect("/")
<file_sep>/examtool_web_common/safe_firestore.py
from google.cloud import firestore
def valid(id: str):
if (
not isinstance(id, str)
or "/" in id
or ".." in id
or id == "."
or id[:2] == "__"
):
raise Exception("Invalid ID! This error has been logged.")
return id
class SafeFirestore:
def __init__(self, obj=None):
self.obj = obj or firestore.Client()
def document(self, name=None):
return SafeFirestore(
self.obj.document(valid(name)) if name else self.obj.document()
)
def collection(self, name=None):
return SafeFirestore(
self.obj.collection(valid(name)) if name else self.obj.collection()
)
def __getattr__(self, item):
return getattr(self.obj, item)
<file_sep>/oh/oh_queue/static/js/components/presence_indicator.js
let PresenceIndicator = ({ state, hideWaitTime, hideWelcome }) => {
let presence = state.presence;
let numStudentsOnline = presence && presence.students ? presence.students : 0;
let numStaffOnline = presence && presence.staff ? presence.staff : 0;
let color = numStaffOnline ? "success" : "warning";
let pendingTickets = getTickets(state, "pending");
let assignedTickets = getTickets(state, "assigned");
var studentMessage = numStudentsOnline + " students";
var staffMessage = numStaffOnline + " assistants";
if (numStudentsOnline === 1) {
studentMessage = studentMessage.slice(0, -1);
}
if (numStaffOnline === 1) {
staffMessage = staffMessage.slice(0, -1);
}
let message = studentMessage + " and " + staffMessage + " currently online.";
// PARAM 1: expected service time ~ Exponential(1/10)
var avgHelpTime = 10;
// how many assistants are unoccupied
var availableAssistants = numStaffOnline - assignedTickets.length;
// how many students need help, assuming all avaiable assistants are assigned
var stillNeedHelp = Math.max(0, pendingTickets.length - availableAssistants);
var waitColor = "#646468";
// catch if there actually are no assistants available
if (numStaffOnline == 0) {
var timeRange = "??";
} else {
// min of numStaffOnline exponentials is exponential, take expectation
var expectedWaitFirst = Math.ceil(avgHelpTime / numStaffOnline);
// standard deviation of exponential equals the expectation
var stdDev = expectedWaitFirst;
// expectation for stillNeedHelp + 1th student on queue
var expectedWaitTotal = (stillNeedHelp + 1) * expectedWaitFirst;
// PARAM 2: (75% conf interval by CLT, 1.15 is from zscore of Normal)
var bound = (1.15 * stdDev) / Math.sqrt(numStaffOnline);
// interval bounds
var estWaitTimeMin = Math.max(0, Math.floor(expectedWaitTotal - bound));
var estWaitTimeMax = Math.ceil(expectedWaitTotal + bound);
// colors for the time
if (expectedWaitTotal <= 5) {
waitColor = "#009900";
} else if (expectedWaitTotal < 10) {
waitColor = "#739900";
} else if (expectedWaitTotal < 25) {
waitColor = "#cc5200";
} else {
waitColor = "#ff0000";
}
// concatenate time range string
var timeRange = estWaitTimeMin + " - " + estWaitTimeMax;
if (estWaitTimeMax > 120) {
timeRange = "> 120";
}
}
var welcomeMessage = state.config.welcome;
const openQueue = () => {
app.makeRequest(`update_config`, {
key: "is_queue_open",
value: "true",
});
};
return (
<div className="col-xs-12">
{!hideWaitTime &&
state.config.is_queue_open === "false" &&
(state.config.party_enabled || isStaff(state)) && (
<div
className="alert alert-danger alert-dismissable fade in"
role="alert"
>
<button
type="button"
className="close"
aria-label="Close"
data-dismiss="alert"
>
<span aria-hidden="true">×</span>
</button>
<h3>The queue is currently closed!</h3>
{state.currentUser && state.currentUser.isStaff && (
<button className="btn btn-primary" onClick={openQueue}>
Open queue
</button>
)}
</div>
)}
{!hideWelcome && (
<div
className="alert alert-info alert-dismissable fade in"
role="alert"
>
<button
type="button"
className="close"
aria-label="Close"
data-dismiss="alert"
>
<span aria-hidden="true">×</span>
</button>
<ReactMarkdown source={welcomeMessage} />
</div>
)}
{state.config.online_active === "true" &&
state.currentUser &&
state.currentUser.isStaff &&
[
state.config.students_set_online_link,
state.config.students_set_online_doc,
].includes("false") && (
<div
className="alert alert-warning alert-dismissable fade in"
role="alert"
>
<button
type="button"
className="close"
aria-label="Close"
data-dismiss="alert"
>
<span aria-hidden="true">×</span>
</button>
<h4>Configure Online Queue Settings</h4>
<h5>
Remember to go to <Link to="/online_setup">Online Setup</Link> to
configure your settings for video calls and shared documents,
otherwise you will not be able to interact with students on the
Online Queue.
</h5>
</div>
)}
{!hideWaitTime && (
<div
className={`alert alert-${color} alert-dismissable fade in`}
role="alert"
>
<button
type="button"
className="close"
aria-label="Close"
data-dismiss="alert"
>
<span aria-hidden="true">×</span>
</button>
<h4>
Estimated wait time:{" "}
<font color={waitColor}>
<strong>{timeRange}</strong>
</font>{" "}
minutes
</h4>
<h5>{message}</h5>
<MagicWordDisplay state={state} />
{presence && state.currentUser && state.currentUser.isStaff && (
<React.Fragment>
<p>
<a
data-toggle="collapse"
href="#collapseExample"
role="button"
aria-expanded="false"
aria-controls="collapseExample"
>
See online assistants.
</a>
</p>
<div className="collapse" id="collapseExample">
<div className="card card-body">
<ul>
{presence.staff_list.map(([email, name]) => (
<li>
{name} (<a href={`mailto:${email}`}> {email}</a>)
</li>
))}
</ul>
</div>
</div>
</React.Fragment>
)}
</div>
)}
</div>
);
};
<file_sep>/exam-server/requirements.txt
# my deps
google-cloud-firestore==1.9.0
google-auth==1.22.1
cryptography==3.1.1
<file_sep>/oh/oh_queue/static/js/components/admin_assignments_manager.js
function AdminAssignmentsManager({ state }) {
const { assignments } = state;
return (
<AdminItemsManager
itemType="assignment"
columns={["ID", "Name", "Visibility"]}
items={Object.values(assignments)}
>
{(item) => [
item.id,
<AdminItemsTextField
itemType="assignment"
placeholder="<NAME>"
propType="name"
item={item}
/>,
<AdminItemsBooleanField
itemType="assignment"
propType="visible"
item={item}
onText="Visible"
offText="Hidden"
/>,
]}
</AdminItemsManager>
);
}
<file_sep>/buildtool/buildtool/fs_utils.py
import hashlib
import os
from functools import lru_cache
from pathlib import Path
from shutil import SameFileError, copyfile, copytree
from typing import List
from utils import BuildException
from common.shell_utils import sh
def find_root():
repo_root = os.path.abspath(os.path.curdir)
while True:
if "WORKSPACE" in os.listdir(repo_root):
return repo_root
repo_root = os.path.dirname(repo_root)
if repo_root == os.path.dirname(repo_root):
break
raise BuildException(
"Unable to find WORKSPACE file - are you in the project directory?"
)
@lru_cache()
def get_repo_files() -> List[str]:
return [
file.decode("ascii") if isinstance(file, bytes) else file
for file in sh(
"git", "ls-files", "--exclude-standard", capture_output=True, quiet=True
).splitlines() # All tracked files
+ sh(
"git",
"ls-files",
"-o",
"--exclude-standard",
capture_output=True,
quiet=True,
).splitlines() # Untracked but not ignored files
]
def normalize_path(repo_root, build_root, path):
suffix = "/" if path.endswith("/") else ""
if path.startswith("//"):
path = Path(repo_root).joinpath(path[2:])
else:
path = Path(repo_root).joinpath(build_root, path)
path = Path(os.path.abspath(path))
repo_root = Path(os.path.abspath(repo_root))
if repo_root != path and repo_root not in path.parents:
raise BuildException(
f"Target `{path}` is not in the root directory of the repo."
)
return str(path.relative_to(repo_root)) + suffix
def copy_helper(*, src_root, dest_root, src_names, dest_names=None, symlink=False):
if not dest_names:
dest_names = src_names
assert len(src_names) == len(dest_names)
for src_name, dest_name in zip(src_names, dest_names):
src = Path(src_root).joinpath(src_name)
dest = Path(dest_root).joinpath(dest_name)
os.makedirs(os.path.dirname(dest), exist_ok=True)
try:
if symlink:
Path(dest).symlink_to(src)
elif src_name.endswith("/"):
copytree(src=src, dst=dest, dirs_exist_ok=True)
else:
copyfile(src, dest)
except SameFileError:
pass
def hash_file(path):
# only hash files whose contents are "locked in". That way we can cache safely.
if path in hash_file.cache:
return hash_file.cache[path]
else:
with open(path, "rb") as f:
out = hash_file.cache[path] = (
hashlib.md5(f.read()).hexdigest().encode("utf-8")
)
return out
hash_file.cache = {}
<file_sep>/common/rpc/paste.py
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/paste_text")
def paste_text(*, data: str, name: str = None, is_private: bool = False):
...
@requires_master_secret
@service.route("/api/get_paste")
def get_paste(*, name: str) -> str:
...
def get_paste_url(name: str):
return f"https://paste.cs61a.org/{name}"
<file_sep>/oh/oh_queue/reminders.py
from base64 import b64encode
from ics import Calendar, Event
import pytz
from common.course_config import get_domain
from common.rpc.mail import send_email
from common.course_config import format_coursecode, get_course
from oh_queue.models import AppointmentSignup
def send_appointment_reminder(signup: AppointmentSignup):
appointment = signup.appointment
user = signup.user
c = Calendar()
e = Event()
e.name = f"{format_coursecode(get_course())} Appointment"
e.begin = pytz.timezone("America/Los_Angeles").localize(appointment.start_time)
e.end = e.begin + appointment.duration
e.location = appointment.location.name
c.events.add(e)
helper_msg = (
f"It will be led by {appointment.helper.name}.\n" if appointment.helper else ""
)
send_email(
sender="OH Queue <<EMAIL>>",
target=user.email,
subject=f"{format_coursecode(get_course())} Appointment Scheduled",
body=(
f"""
Hi {user.short_name},
An appointment has been scheduled for you using the {format_coursecode(get_course())} OH Queue.
It is at {appointment.start_time.strftime('%A %B %-d, %I:%M%p')} Pacific Time, at location {appointment.location.name}.
{helper_msg}
To edit or cancel this appointment, go to https://{get_domain()}.
Best,
The 61A Software Team
""".strip()
),
attachments={"invite.ics": b64encode(str(c).encode("utf-8")).decode("ascii")},
)
<file_sep>/common/rpc/README.md
# `common.rpc`
This is our custom RPC implementation, used by all of our apps to communicate
securely with each other.
<file_sep>/examtool/examtool/api/extract_questions.py
from examtool.api.scramble import is_compressible_group
def extract_questions(
exam,
extract_public_bool: bool = True,
top_level: bool = True,
include_groups: bool = False,
nest_all: bool = False,
):
def merge_text(parent, child):
for attr in ["text", "html", "tex"]:
child[attr] = parent["name"] + "\n\n" + parent[attr] + "\n\n" + child[attr]
def group_questions(group):
out = _group_questions(group)
try:
first = next(out)
except StopIteration:
return
merge_text(group, first)
yield first
for child in out:
if nest_all:
merge_text(group, child)
yield child
def _group_questions(group):
for i, element in enumerate(
group.get("elements", []) + group.get("questions", [])
):
element["index"] = f"{group.get('index', '0.')}{i + 1}."
if element.get("type") == "group":
if include_groups:
yield element
out = group_questions(element)
yield from out
else:
yield element
if extract_public_bool:
yield from extract_public(exam)
if top_level:
for i, group in enumerate(exam["groups"]):
group["index"] = str(i + 1) + "."
if include_groups:
yield group
yield from group_questions(group)
else:
yield from group_questions(exam)
def extract_public(exam):
if exam.get("public"):
yield from extract_questions(
exam["public"], extract_public_bool=False, top_level=False
)
def extract_groups(group):
for g in group["groups"]:
if is_compressible_group(g):
for g2 in g["elements"]:
yield g2
else:
yield g
def get_name(element):
if "name" in element:
return f"{element['index']} {element['name']}"
else:
return element["index"]
<file_sep>/auth/domains_client.py
from flask import redirect, request
from auth_utils import course_oauth_secure
from common.db import connect_db
from common.rpc.auth import get_course
from common.rpc.domains import add_domain
from common.url_for import url_for
from common.html import make_row
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS domains_config (
domain varchar(128),
course varchar(128)
)"""
)
init_db()
def create_domains_client(app):
def domains_help(course):
with connect_db() as db:
ret = db(
"SELECT domain FROM domains_config WHERE course=(%s)", [course]
).fetchall()
client_names = [
make_row(domain, url_for("remove_domain", domain=domain, course=course))
for domain, in ret
]
register_domain = f"""
Register new domain:
<form action="/domains/{course}/register_domain" method="post">
<input name="domain_name" type="text" placeholder="seating.cs61a.org">
<input type="submit">
</form>
View the status of your domain setup at
<a href="https://domains.cs61a.org/">domains.cs61a.org</a>
<br />
"""
return "<h3>Domains</h3>" + register_domain + "<p>".join(client_names)
app.help_info.add(domains_help)
@app.route("/domains/<course>/register_domain", methods=["POST"])
@course_oauth_secure()
def register_domain(course):
domain_name = request.form["domain_name"]
with connect_db() as db:
ret = db(
"SELECT * FROM domains_config WHERE domain = (%s)", [domain_name]
).fetchone()
if ret:
return "domain already registered", 409
db("INSERT INTO domains_config VALUES (%s, %s)", [domain_name, course])
add_domain(course=course, domain=domain_name, noreply=True)
return redirect("/")
@app.route("/domains/<course>/remove_domain", methods=["POST"])
@course_oauth_secure()
def remove_domain(course):
domain = request.args["domain"]
with connect_db() as db:
db(
"DELETE FROM domains_config WHERE domain = (%s) AND course = (%s)",
[domain, course],
)
return redirect("/")
@get_course.bind(app)
def handle_get_course(domain, **_kwargs):
# note: deliberately not secured, not sensitive data
with connect_db() as db:
[course] = db(
"SELECT course FROM domains_config WHERE domain = (%s)", [domain]
).fetchone()
return course
<file_sep>/hog/src/constants.js
// @flow
export const numberStrings = ["ZERO", "ONE"];
export const bgColors = ["#28a745", "#17a2b8"];
export const colors = ["white", "white"];
<file_sep>/sandbox/ide.py
import os, shutil, subprocess, sys, yaml, socket, requests, time
from contextlib import contextmanager
from flask import Flask, request, redirect, session
from werkzeug.security import gen_salt
from functools import wraps
from utils import (
db_lock,
Server,
Location,
get_server_cmd,
get_server_pid,
get_active_servers,
is_software_ta,
)
from common.oauth_client import (
create_oauth_client,
is_staff,
login,
get_user,
)
from common.rpc.hosted import add_domain
from common.rpc.secrets import get_secret
from common.shell_utils import sh
from common.html import html
from common.url_for import get_host, url_for
from common.db import connect_db
NGINX_PORT = os.environ.get("PORT", "8001")
DEFAULT_USER = "prbuild"
SK_RETURN_TO = "start_kill_return_to"
app = Flask(__name__)
create_oauth_client(
app, "61a-ide", secret_key=get_secret(secret_name="OKPY_IDE_SECRET")
)
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS ide (
username varchar(128),
initialized boolean, -- this is unused in the ide context, for now
locked boolean
);"""
)
VSCODE_ASSOC = """
{
"files.associations": {
"BUILD": "python",
"WORKSPACE": "python"
},
"files.trimTrailingWhitespace": true
}
"""
def auth_only(func):
@wraps(func)
def wrapped(*args, **kwargs):
if not is_staff("cs61a") or not is_berkeley():
return login()
return func(*args, **kwargs)
return wrapped
def gen_index_html(out, username, show_active=False):
if not get_server_pid(username):
out += "inactive or nonexistent.<br />"
out += f"""<form action="{url_for('start')}" method="POST">
<input type="hidden" name="username" value="{username}" />
<input type="submit" value="Start IDE" />
</form>"""
return html(out)
config = get_config(username)
if is_prod_build():
domain = f"{username}.{get_host()}"
else:
domain = f"{username}-{get_host()}"
out += "active.<br />"
out += f"""<form action="https://{domain}/login", method="POST">
<input type="hidden" name="base" value="" /><input type="hidden" name="password" value="{config['password']}" />
<input type="submit" value="Open IDE" />
</form><form action="{url_for('kill')}" method="POST">
<input type="hidden" name="username" value="{username}" />
<input type="submit" value="Kill IDE" />
</form>"""
active = get_active_servers()
if active and show_active:
out += "<p>Active servers: " + ", ".join(active) + "</p>"
return html(out)
@app.route("/")
@auth_only
def index():
username = get_username()
out = "<h1>61A Sandbox IDE</h1>\n"
out += f"Hi {get_user()['name'].split()[0]}! Your IDE is "
session[SK_RETURN_TO] = url_for("index")
return gen_index_html(out, username, is_software_ta(get_user()["email"]))
@app.route("/sudo/<username>")
@auth_only
def sudo(username):
if not is_software_ta(get_user()["email"]):
return redirect(url_for("index"))
out = "<h1>61A Sandbox IDE</h1>\n"
out += f"Hi {get_user()['name'].split()[0]}! {username}'s IDE is "
session[SK_RETURN_TO] = url_for("sudo", username=username)
return gen_index_html(out, username, True)
@app.route("/start", methods=["POST"])
@auth_only
def start():
username = request.form.get("username")
try:
sh("id", "-u", username)
user_exists = True
except subprocess.CalledProcessError:
user_exists = False
if is_prod_build():
domain = f"{username}.{get_host()}"
else:
domain = f"{username}-{get_host()}"
if not user_exists:
print(f"User {username} doesn't exist, creating...", file=sys.stderr)
sh("useradd", "-b", "/save", "-m", username, "-s", "/bin/bash")
print(
f"Proxying {domain} to {get_hosted_app_name()}...",
file=sys.stderr,
)
add_domain(
name=get_hosted_app_name(),
domain=domain,
proxy_set_header={
"Host": "$host",
"Upgrade": "$http_upgrade",
"Connection": "upgrade",
"Accept-Encoding": "gzip",
},
)
sh("chown", "-R", username, f"/save/{username}")
print("Home folder owner set.", file=sys.stderr)
sh("mkdir", "-p", "/save/.cache")
sh("chmod", "a+rw", "/save/.cache")
if not get_server_pid(username):
print(f"Server for {username} is not running, starting...", file=sys.stderr)
with db_lock("ide", username):
passwd = gen_salt(24)
port = get_open_port()
config = {
"bind-addr": f"127.0.0.1:{port}",
"auth": "<PASSWORD>",
"password": <PASSWORD>,
}
with open(f"/save/{username}/.code-server.yaml", "w") as csc:
yaml.dump(config, csc)
sh("chown", "-R", username, f"/save/{username}/.code-server.yaml")
print("Configuration ready.", file=sys.stderr)
sanitized = os.environ.copy()
del sanitized["DATABASE_URL"]
del sanitized["APP_HOME"]
del sanitized["APP_MASTER_SECRET"]
del sanitized["ENV"]
del sanitized["INSTANCE_CONNECTION_NAME"]
sanitized["PORT"] = str(port)
print("Environment sanitized.", file=sys.stderr)
subprocess.Popen(get_server_cmd(username), env=sanitized)
print("Subprocess opened.", file=sys.stderr)
conf = Server(
Location(
"/",
include="proxy_params",
proxy_pass=f"http://127.0.0.1:{port}",
proxy_set_header={
"Host": "$host",
"Upgrade": "$http_upgrade",
"Connection": "upgrade",
"Accept-Encoding": "gzip",
},
),
server_name=domain,
listen=NGINX_PORT,
error_page=f"502 https://{get_host()}",
)
with open(f"/etc/nginx/sites-enabled/{domain}", "w") as f:
f.write(str(conf))
sh("nginx", "-s", "reload")
print("NGINX configuration written and server restarted.", file=sys.stderr)
if not os.path.exists(f"/save/{username}/berkeley-cs61a"):
print(f"Copy of repo for {username} not found.", file=sys.stderr)
if os.path.exists("/save/root/berkeley-cs61a"):
print("Found a known good repo, copying...", file=sys.stderr)
shutil.copytree(
"/save/root/berkeley-cs61a",
f"/save/{username}/berkeley-cs61a",
symlinks=True,
)
print(
"Tree copied. Writing Visual Studio Code associations...",
file=sys.stderr,
)
os.mkdir(f"/save/{username}/berkeley-cs61a/.vscode")
with open(
f"/save/{username}/berkeley-cs61a/.vscode/settings.json", "w"
) as f:
f.write(VSCODE_ASSOC)
print("Done.", file=sys.stderr)
sh("chown", "-R", username, f"/save/{username}/berkeley-cs61a")
print("Tree owner changed.", file=sys.stderr)
print("Waiting for code-server to come alive, if needed...", file=sys.stderr)
while requests.get(f"https://{domain}").status_code != 200:
time.sleep(1)
print("code-server is alive.", file=sys.stderr)
print("IDE ready.", file=sys.stderr)
return redirect(session.pop(SK_RETURN_TO, url_for("index")))
@app.route("/kill", methods=["POST"])
@auth_only
def kill():
username = request.form.get("username")
pid = get_server_pid(username)
if pid:
sh("kill", pid.decode("utf-8")[:-1])
sh("sleep", "2") # give the server a couple of seconds to shutdown
return redirect(session.pop(SK_RETURN_TO, url_for("index")))
def is_prod_build():
return ".pr." not in get_host() and "cs61a" in get_host()
def get_hosted_app_name():
return "sandbox" if is_prod_build() else f"sandbox-pr{get_host().split('.')[0]}"
def get_username():
return (
get_user()["email"].split("@")[0].replace(".", "-")
if is_prod_build()
else DEFAULT_USER
)
def is_berkeley():
return get_user()["email"].endswith("@berkeley.edu")
def get_config(username):
with open(f"/save/{username}/.code-server.yaml") as csc:
data = yaml.load(csc)
return data
def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port
if __name__ == "__main__":
app.run()
<file_sep>/buildserver/external_build.py
import os
import shutil
from github.Repository import Repository
from app_config import App
from common.secrets import get_master_secret
from common.shell_utils import sh
from conf import PROJECT_ID
from deploy import gen_service_name
def run_highcpu_build(
app: App,
pr_number: int,
sha: str,
repo: Repository,
):
for f in os.listdir("./deploy_files"):
if f == "cloudbuild.yaml":
# don't use this one, we don't want any caching
continue
shutil.copyfile(f"./deploy_files/{f}", f"./{f}")
shutil.copyfile("./dockerfiles/buildserver.Dockerfile", "./Dockerfile")
with open("Dockerfile", "a+") as f:
f.seek(0)
contents = f.read()
contents = contents.replace("$BASE_IMAGE", app.config["build_image"])
contents = contents.replace("$APP_NAME", app.name)
contents = contents.replace("$PR_NUMBER", str(pr_number))
contents = contents.replace("$SHA", sha)
contents = contents.replace("$REPO_ID", repo.full_name)
contents = contents.replace("$MASTER_SECRET", get_master_secret())
f.seek(0)
f.truncate()
f.write(contents)
sh(
"gcloud",
"builds",
"submit",
"-q",
"--tag",
"gcr.io/{}/temp-{}".format(PROJECT_ID, gen_service_name(app.name, pr_number)),
# "--machine-type=N1_HIGHCPU_32",
)
<file_sep>/hog-contest/requirements.txt
flask
gunicorn
mysqlclient
pytz
-r common/requirements.txt
<file_sep>/buildserver/scheduling.py
import sys
from datetime import timedelta
from time import time
from typing import Dict, List, Optional
from common.db import connect_db
from common.rpc.auth import post_slack_message
from common.rpc.paste import get_paste_url, paste_text
from github_utils import BuildStatus, update_status
BUILD_TIME = timedelta(minutes=20).total_seconds()
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS builds (
unix int,
app varchar(128),
pr_number int,
status varchar(128),
packed_ref varchar(256),
url varchar(256),
log_url varchar(256),
build_limit_time int
);
"""
)
"""
Each pushed_ref corresponds to a particular commit.
For each (app, pr_number) tuple, there will be a number of rows, at most one row per packed_ref.
There will be some number of rows with status = success or failure, at most one with status = building,
at most one with status = queued, and some number with status = pushed.
"""
def enqueue_builds(
targets: List[str],
pr_number: int,
packed_ref: str,
) -> Dict[str, List[str]]:
"""
Returns a map of packed_ref -> List[app_name] containing those apps that can now be built,
and enqueues the rest to be built when the blocking buildserver run terminates
"""
with connect_db() as db:
# Before anything, we need to clear any stalled builds
db(
"UPDATE builds SET status='failure' WHERE status='building' AND build_limit_time < %s",
[time()],
)
# First, we enqueue all our current targets
for target in targets:
status = db(
"SELECT status FROM builds WHERE app=%s AND pr_number=%s AND packed_ref=%s",
[
target,
pr_number,
packed_ref,
],
).fetchone()
if status == BuildStatus.building.name:
# no need to start a second build for the same (app, packed_ref)
continue
# enqueues itself and dequeues anyone else who is queued
db(
"UPDATE builds SET status='pushed' WHERE app=%s AND pr_number=%s AND packed_ref!=%s AND status='queued'",
[target, pr_number, packed_ref],
)
if status is None:
# we have just been pushed or manually triggered
db(
"INSERT INTO builds VALUES (%s, %s, %s, 'queued', %s, NULL, NULL, NULL)",
[time(), target, pr_number, packed_ref],
)
else:
db(
"UPDATE builds SET status='queued' WHERE app=%s AND pr_number=%s AND packed_ref=%s",
[target, pr_number, packed_ref],
)
# force db flush
with connect_db() as db:
# Then, we dequeue any target that is now ready to be built
can_build_list = []
queued = db(
"SELECT app, packed_ref FROM builds WHERE pr_number=%s AND status='queued'",
[pr_number],
).fetchall()
# sanity check that there are no duplicate apps
assert len(queued) == len({app for app, _ in queued})
for app, packed_ref in queued:
conflicts = db(
"SELECT * FROM builds WHERE app=%s AND pr_number=%s AND status='building'",
[app, pr_number],
).fetchall()
if conflicts:
# cannot build app, because someone else is currently building
continue
else:
# we can build now!
db(
"UPDATE builds SET status='building', build_limit_time=%s WHERE app=%s AND pr_number=%s AND packed_ref=%s",
[time() + BUILD_TIME, app, pr_number, packed_ref],
)
can_build_list.append((app, packed_ref))
# group output by packed_ref for convenience of caller
can_build = {}
for app, packed_ref in can_build_list:
if packed_ref not in can_build:
can_build[packed_ref] = []
can_build[packed_ref].append(app)
for packed_ref in set(packed_ref for app, packed_ref in queued):
update_status(packed_ref, pr_number)
return can_build
def report_build_status(
target: str,
pr_number: int,
packed_ref: str,
status: BuildStatus,
url: Optional[str],
log_data: Optional[str],
*,
private: bool
):
try:
log_url = get_paste_url(
paste_text(data=log_data, is_private=private, retries=3)
)
except Exception:
print(log_data, file=sys.stderr)
print("Paste failure, logs were dumped to stdout", file=sys.stderr)
try:
post_slack_message(
course="cs61a",
message="Paste failed on buildserver, continuing anyway, please check logs ASAP",
purpose="infra",
)
except:
pass
log_url = "https://logs.cs61a.org/service/buildserver"
with connect_db() as db:
existing = db(
"SELECT * FROM builds WHERE app=%s AND pr_number=%s AND packed_ref=%s",
[
target,
pr_number,
packed_ref,
],
).fetchone()
build_limit_time = (
time() + BUILD_TIME if status == BuildStatus.building else None
)
if not existing:
# we have just been pushed or manually triggered
db(
"INSERT INTO builds VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
[
time(),
target,
pr_number,
status.name,
packed_ref,
url,
log_url,
build_limit_time,
],
)
else:
db(
"UPDATE builds SET status=%s, url=%s, log_url=%s, build_limit_time=%s "
"WHERE app=%s AND pr_number=%s AND packed_ref=%s",
[
status.name,
url,
log_url,
build_limit_time,
target,
pr_number,
packed_ref,
],
)
update_status(
packed_ref,
pr_number,
)
<file_sep>/piazzaoncall/README.md
# Piazza-Oncall
## Description
Piazza-Oncall monitors piazza and pings the staff Slack to help with unanswered questions. It assigns a staff member to each question (with individual staff members for each followup) and sends out a daily reminder for all unresolved questions and followups.
## Setup
All packages are detailed in requirements.txt. Include a .csv file named staff_roster.csv in the program directory. The staff roster should minimally contain `email`, `name`, and `Weight` columns; extraneous columns will be ignored. Name/email will indicate the staff member to tag in slack while the `Weight` indicates their probability of being selected for a random post/followup.
## High Priority Messages
If a question remains unresolved for some customizable (default: 3) days, the reminder includes `@channel` to encourage a faster response to the post or followup. A post's age is determined by its date of creation, while a followup's age is determined by its last nested comment. For example, a 5-day old (unresolved) followup with a 3-hour old reply would not be marked as high priority, since it would be dated at 3-hours old. However, it still would be included in the regular reminders since it's still marked unresolved.
## Assign Staff Members
The syntax `oncall: <email_username>` can be used to assign specific staff members to a post. For example, `oncall: oski` in the body of the piazza post would assign the staff member with <EMAIL> to the post. Staff members assigned with the oncall syntax are responsible for the entire post, including any followups (no new staff members will be assigned to followups).
Oncall can also be used to assign multiple staff members. For example,
```
oncall: oski
oncall: gobears
```
in the body of the piazza post would assign the staff members with emails <EMAIL> and <EMAIL> to the entire post, including any followups.
## Exclude Posts
To prevent a staff member from being assigned to an unresolved post, use the syntax `oncall: ignore`. Ignore takes precedence over any other assignment. For example,
```
oncall: oski
oncall: ignore
```
would result in no staff members being assigned to the post, even though oski was specified for assignment.
<file_sep>/secrets/main.py
import hashlib
from functools import wraps
from typing import List, Tuple
from flask import Flask, abort, redirect, request, url_for
from common.course_config import is_admin, is_admin_token
from common.db import connect_db
from common.oauth_client import create_oauth_client, get_user, is_staff, login
from common.rpc.secrets import (
create_master_secret,
get_secret_from_server,
load_all_secrets,
validate_master_secret,
)
from common.secrets import new_secret
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
app.debug = True
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS secrets (
app varchar(128),
name varchar(128),
public_value varchar(512),
staging_value varchar(512)
)"""
)
secret_key = db(
"SELECT public_value FROM secrets WHERE app='secrets' and name='OKPY_OAUTH_SECRET'"
).fetchone()
create_oauth_client(app, "61a-secrets", secret_key[0] if secret_key is not None else "")
@validate_master_secret.bind(app)
def validate_master_secret(master_secret):
"""
Validates a master secret.
:param master_secret: secret to be validated
:type master_secret: str
:return: a tuple of the app and a bool for if that app is a staging app
"""
with connect_db() as db:
public_app = db(
"SELECT app FROM secrets WHERE public_value=%s AND name='MASTER'",
[master_secret],
).fetchone()
if public_app is not None:
return public_app[0], False
staging_app = db(
"SELECT app FROM secrets WHERE staging_value=%s AND name='MASTER'",
[master_secret],
).fetchone()
if staging_app is not None:
return staging_app[0], True
abort(401)
# intentional duplicate of the RPC decorator, since this calls
# the local version of validate_master_secret, not the RPC wrapper
def validates_master_secret(func):
"""
Wraps a function to call a local version of validate_master_secret instead of the RPC wrapper.
:param func: function to be wrapped
:type func: function
:return: wrapped function that will call validate_master_secret
"""
@wraps(func)
def wrapped(
*,
master_secret=None,
_sudo_token=None,
_impersonate=None,
_is_staging=False,
**kwargs,
):
if master_secret:
app, is_staging = validate_master_secret(master_secret=master_secret)
return func(app=app, is_staging=is_staging, **kwargs)
elif _sudo_token and is_admin_token(_sudo_token, course="cs61a"):
return func(app=_impersonate, is_staging=_is_staging, **kwargs)
raise PermissionError
return wrapped
@get_secret_from_server.bind(app)
@validates_master_secret
def get_secret(app, is_staging, secret_name):
"""
Gets a secret from secrets.
:param app: app to get secret for
:type app: str
:param is_staging: whether app is a staging app
:type is_staging: bool
:param secret_name: name of secret
:type secret_name: str
:return: string of either the staging value or public value depending on if the app was a staging app.
"""
with connect_db() as db:
public_value, staging_value = db(
"SELECT public_value, staging_value FROM secrets WHERE app=%s AND name=%s",
[app, secret_name],
).fetchone()
if is_staging:
return staging_value
else:
return public_value
@load_all_secrets.bind(app)
@validates_master_secret
def load_all_secrets(app, is_staging, created_app_name):
"""
Loads all secrets for a particular app.
:param app: app loading the secrets
:type app: string
:param is_staging: whether app is a staging app
:type is_staging: bool
:param created_app_name: name of the app to get secrets for
:type created_app_name: str
:return: dict of name and public value for all secrets of created_app_name
"""
if app != "buildserver" or is_staging:
abort(403) # only buildserver running in prod can view all secrets
with connect_db() as db:
return dict(
db(
"SELECT name, public_value FROM secrets WHERE app=%s",
[created_app_name],
).fetchall()
)
@create_master_secret.bind(app)
@validates_master_secret
def create_master_secret(app, is_staging, created_app_name):
"""
Creates a master secret.
:param app: app creating the secret
:type app: str
:param is_staging: whether app is a staging app
:type is_staging: bool
:param created_app_name: app to create master secret for
:type created_app_name: str
:return: tuple of two randomly generated 64-character secrets.
"""
if app != "buildserver" or is_staging:
abort(403) # only buildserver running in prod can create new apps
with connect_db() as db:
out = db(
"SELECT public_value, staging_value FROM secrets WHERE app=%s AND name='MASTER'",
[created_app_name],
).fetchone()
if out is not None:
return list(out)
out = new_secret(), new_secret()
db(
"INSERT INTO secrets (app, name, public_value, staging_value) VALUES (%s, %s, %s, %s)",
[created_app_name, "MASTER", *out],
)
return out
def display_hash(secret: str):
"""
Displays the first 8 characters of the md5 hash of a secret.
:param secret: secret to display
:type secret: str
"""
return hashlib.md5(secret.encode("utf-8")).hexdigest()[:8]
@app.route("/")
def index():
if not is_staff("cs61a"):
return login()
with connect_db() as db:
secrets: List[Tuple[str, str, str, str]] = db(
"SELECT app, name, public_value, staging_value FROM secrets"
).fetchall()
return """
<h1>Secrets Tool</h1>
<p>
Add a secret:
<form action="/create_secret" method="POST">
<input name="app" placeholder="App name" />
<input name="name" placeholder="Secret name" />
<input name="public" placeholder="Public value" />
<input name="staging" placeholder="Staging value" />
<button type="submit">Submit</button>
</form>
</p>
<p>
You should assume that the staging value is visible to any member of 61A staff.
For instance, for Auth keys, provide a 61A-specific key for the staging value,
and a super key only for the public value, to avoid leaking information. That said,
staging values are not directly exposed and access will be logged in deploy logs,
so don't worry about it too much, just be careful.
</p>
""" + "".join(
f"""<p>
<form
style="display: inline"
action="{url_for("delete_secret", app_name=app, secret_name=name)}"
method="post"
>
{app}/{name} - {display_hash(public_value)} (staging: {display_hash(staging_value)})
<input type="submit" value="Remove">
</form>"""
for app, name, public_value, staging_value in secrets
)
@app.route("/create_secret", methods=["POST"])
def create_secret():
if not is_staff("cs61a"):
return login()
app = request.form["app"]
name = request.form["name"]
public = request.form["public"]
staging = request.form["staging"]
with connect_db() as db:
existing = db(
"SELECT * FROM secrets WHERE app=%s AND name=%s", [app, name]
).fetchall()
if existing:
abort(409)
db(
"INSERT INTO secrets (app, name, public_value, staging_value) VALUES (%s, %s, %s, %s)",
[app, name, public, staging],
)
return redirect(url_for("index"))
@app.route("/delete_secret/<app_name>/<secret_name>", methods=["POST"])
def delete_secret(app_name, secret_name):
if not is_admin(get_user()["email"], "cs61a"):
return login()
with connect_db() as db:
db("DELETE FROM secrets WHERE app=%s AND name=%s", [app_name, secret_name])
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/hog-calc/index.md
```{include} README.md
```
## Main
This file compares Hog strategies and outputs strategy win rates.
```{eval-rst}
.. automodule:: docs.hog_calc.main
:members:
```
## Process Input
This file contains methods for validating and recording Hog strategies.
```{eval-rst}
.. automodule:: docs.hog_calc.process_input
:members:
```
## Runner
This file contains methods for matching and scoring two given Hog strategies.
```{eval-rst}
.. automodule:: docs.hog_calc.runner
:members:
```
<file_sep>/auth/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
google-api-python-client==1.10.0
google-auth==1.20.1
git+https://github.com/hfaran/piazza-api.git@develop
-r common/requirements.txt
<file_sep>/sections/src/SectionStateContext.js
// @flow strict
import * as React from "react";
import type { SectionDetails } from "./models";
export default React.createContext<{
...SectionDetails,
updateState: (SectionDetails) => void,
}>({
id: "",
staff: null,
students: [],
description: "",
capacity: 0,
startTime: 0,
endTime: 0,
callLink: null,
sessions: [],
tags: [],
updateState: () => {},
});
<file_sep>/oh/oh_queue/static/js/components/jumbotron.js
let Jumbotron = ({ state }) => {
var isQueueOpen = state.config && JSON.parse(state.config.is_queue_open);
const appointments =
JSON.parse(state.config.appointments_open) &&
state.config.recommend_appointments;
const party_enabled = state.config.party_enabled;
if (!state.currentUser) {
var titleText = "Hi! Please sign in";
var subtitleText = "Sign in with your course OK account to request help";
var contents = (
<a className="btn btn-block btn-jumbo btn-outline" href="/login">
Sign in with Ok
</a>
);
} else if (!isQueueOpen) {
var titleText = `Hello, ${state.currentUser.shortName}`;
var subtitleText = "The queue is currently closed. Check back later!";
var contents = <RequestForm state={state} />;
} else {
var titleText = `Hello, ${state.currentUser.shortName}`;
var subtitleText = "Fill out the form to request help!";
var contents = <RequestForm state={state} />;
}
if (state.currentUser && party_enabled) {
subtitleText = "Join an existing group, or create a new one!";
} else if (state.currentUser && appointments && !isQueueOpen) {
subtitleText = " Click the button to make an appointment for a future OH!";
}
return (
<div className="jumbotron blue">
<div className="container">
<section className="page-header">
<div className="row">
<Messages messages={state.messages} />
</div>
<div className="row">
<div className="col-md-7 col-lg-8">
<h3 className="truncate">{titleText}</h3>
<p className="truncate">{subtitleText}</p>
</div>
<div className="col-md-5 col-lg-4">
<div className="request-form">{contents}</div>
</div>
</div>
</section>
</div>
</div>
);
};
<file_sep>/oh/oh_queue/static/js/common.js
function requestNotificationPermission() {
try {
Push.Permission.request(null, function () {
console.log("Permission denied for notifications");
});
} catch (e) {
// Ignore Push.js errors about unsupported devices
}
}
function notifyUser(title, body, tag) {
try {
Push.create(title, {
body: body,
icon: window.location.origin + "/static/img/logo-tiny.png",
onClick: function () {
window.focus();
this.close();
},
tag: tag,
});
} catch (e) {
// Ignore Push.js errors about unsupported devices
}
}
function cancelNotification(tag) {
try {
Push.close(tag);
} catch (e) {
// Ignore Push.js errors about unsupported devices
}
}
function initializeTooltip(elem, options) {
$(elem).tooltip(options);
}
function isPartyRoot(state) {
return (
state.config.party_enabled &&
(!JSON.parse(state.config.is_queue_open) || !isStaff(state))
);
}
// The one and only app. Other components may reference this variable.
// See components/app.js for more documentation
let app = ReactDOM.render(<App />, document.getElementById("content"));
<file_sep>/buildtool/buildtool/__main__.py
from __future__ import annotations
import os
import traceback
from json import loads
from shutil import rmtree
from typing import List, Tuple
import click
from cache import STATS
from colorama import Fore, Style
from build_coordinator import run_build
from build_worker import TIMINGS as BUILD_TIMINGS
from common.cli_utils import pretty_print
from monitoring import enable_logging, enable_profiling
from state import BuildState
from fs_utils import find_root, get_repo_files
from loader import config, load_rules, TIMINGS as LOAD_TIMINGS
from utils import BuildException
from workspace_setup import initialize_workspace
def display_error(error: BuildException):
print(Fore.RED)
pretty_print("๐ซ", "Build failed.")
print(Style.BRIGHT)
print(error)
@click.command()
@click.argument("targets", metavar="target", required=False, nargs=-1)
@click.option(
"--profile",
"-p",
default=False,
is_flag=True,
help="Show performance profiling data, cache hit rates, and log all executed commands.",
)
@click.option(
"--shell-log",
"-s",
default=False,
is_flag=True,
help="Log all executed commands.",
)
@click.option(
"--locate",
"-l",
default=False,
is_flag=True,
help="Rather than building, locate the BUILD file declaring a particular target.",
)
@click.option(
"--verbose",
"-v",
default=False,
is_flag=True,
help="Show detailed logs to identify problems. For most purposes, --profile is a better option.",
)
@click.option(
"--quiet",
"-q",
default=False,
is_flag=True,
help="Disable the progress bars normally shown during a build. Does not affect the output of "
"--locate or --profile, and errors will still be printed if the build fails.",
)
@click.option(
"--skip-version-check",
default=False,
is_flag=True,
help="Ignore any minimum version requirements specified in the WORKSPACE file.",
)
@click.option(
"--skip-setup",
default=False,
is_flag=True,
help="Do not install / verify dependencies in the WORKSPACE file.",
)
@click.option(
"--skip-build",
default=False,
is_flag=True,
help="Do not build the targets passed in. Automatically set when running --locate.",
)
@click.option(
"--clean",
"-c",
default=False,
is_flag=True,
help="Clean the output directory specified in the WORKSPACE file so only built targets will be kept.",
)
@click.option(
"--threads",
"-t",
"num_threads",
default=8,
help="The number of worker threads used in execution. Increase this number if using a remote build cache.",
)
@click.option(
"--state-directory",
default=".state",
help="The local directory used to keep track of the state of the WORKSPACE install.",
)
@click.option(
"--cache-directory",
default=os.getenv("BUILDTOOL_CACHE_DIRECTORY", ".cache"),
help="The directory used to cache build outputs and intermediate layers. If a cloud storage bucket is passed "
"in as gs://bucket-name, it will be used alongside an .aux_cache local directory as a source for cached outputs. "
"Override with the BUILDTOOL_CACHE_DIRECTORY environment variable.",
)
@click.option(
"--flag",
"-f",
"flags",
type=str,
multiple=True,
help="These flags are exposed at load and build time, via `from buildtool import flags`. "
"Values can be supplied as JSON like --flag KEY=JSON_VALUE, and flags without values default to `true`.",
)
def cli(
targets: Tuple[str],
profile: bool,
shell_log: bool,
locate: bool,
verbose: bool,
quiet: bool,
skip_version_check: bool,
skip_setup: bool,
skip_build: bool,
clean: bool,
num_threads: int,
state_directory: str,
cache_directory: str,
flags: List[str],
):
"""
This is a `make` alternative with a simpler syntax and some useful features.
"""
try:
repo_root = find_root()
os.chdir(repo_root)
if verbose:
enable_logging()
if profile or shell_log:
enable_profiling()
flags = [flag.split("=", 1) + ["true"] for flag in flags]
flags = {flag[0].lower(): loads(flag[1]) for flag in flags}
if not skip_setup:
setup_rule_lookup = load_rules(
flags, workspace=True, skip_version_check=skip_version_check
)
setup_targets = [
target[5:] for target in targets if target.startswith("setup:")
]
if locate and setup_targets:
raise BuildException(
"--locate cannot be used with setup rules - they are declared in WORKSPACE"
)
setup_targets = setup_targets or (
[config.default_setup_rule] if config.default_setup_rule else []
)
initialize_workspace(
setup_rule_lookup,
setup_targets,
state_directory,
quiet,
)
target_rule_lookup = load_rules(flags, skip_version_check=skip_version_check)
target_rule_lookup.verify()
all_files = get_repo_files()
source_files = target_rule_lookup.find_source_files(all_files)
if profile:
print("Slow Build / Rules Files (Loading Phase):")
slowest = sorted(LOAD_TIMINGS, key=lambda x: LOAD_TIMINGS[x], reverse=True)[
:20
]
for key in slowest:
print(key, LOAD_TIMINGS[key])
print()
need_target = locate or not skip_build
if not targets and need_target:
if config.default_build_rule is None:
raise BuildException("No target provided, and no default target set.")
targets = [config.default_build_rule]
if locate:
for target in targets:
if target in source_files:
raise BuildException(
f"Target {target} is a source file, not a build target."
)
rule = target_rule_lookup.try_lookup(target)
if rule is None and not target.startswith(":"):
rule = target_rule_lookup.try_lookup(f":{target}")
if rule is None:
raise BuildException(f"Target {target} was not found.")
print(
f"Target {target} is declared by {rule} in {rule.location}/BUILD."
)
exit(0)
if not skip_build:
for _ in range(2 if clean else 1):
if clean:
for out_dir in config.output_directories:
rmtree(out_dir, ignore_errors=True)
for rule in set(target_rule_lookup.direct_lookup.values()) | set(
target_rule_lookup.direct_lookup.values()
):
rule.pending_rule_dependencies = set()
rule.runtime_dependents = set()
run_build(
BuildState(
target_rule_lookup=target_rule_lookup,
source_files=source_files,
cache_directory=cache_directory,
repo_root=repo_root,
),
[target for target in targets if not target.startswith("setup:")],
num_threads,
quiet,
)
if profile:
print("Slow Rules (Execution Phase):")
slowest = sorted(
BUILD_TIMINGS, key=lambda x: BUILD_TIMINGS[x], reverse=True
)[:20]
for key in slowest:
print(key, BUILD_TIMINGS[key])
print("Cache Statistics")
print(
f"{STATS['hits']} cache hits, {STATS['misses']} cache misses, {STATS['inserts']} cache inserts (approx)"
)
except BuildException as e:
display_error(e)
exit(1)
except Exception as e:
display_error(BuildException("Internal error: " + repr(e)))
print(f"\n{Style.RESET_ALL}" + traceback.format_exc())
exit(1)
if __name__ == "__main__":
cli()
<file_sep>/oh/oh_queue/static/js/components/appointment_edit_form.js
function AppointmentEditForm({ isOpen, appointment, onSubmit }) {
const root = React.useRef();
const [description, setDescription] = React.useState("");
React.useEffect(() => {
setDescription(appointment.description);
}, [isOpen, appointment]);
React.useEffect(() => {
if (isOpen) {
$(root.current).modal("show");
} else {
$(root.current).modal("hide");
}
}, [isOpen]);
const handleSubmit = () => {
app.makeRequest("update_appointment", {
id: appointment.id,
description,
});
onSubmit();
};
return ReactDOM.createPortal(
<div className="modal fade" ref={root} tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
<h4 className="modal-title">Edit Appointment</h4>
</div>
<div className="modal-body">
<input
className="form-control form-right"
type="text"
name="question"
title="Question"
placeholder="Description (keep it short!)"
value={description}
onChange={(e) => setDescription(e.target.value)}
required
/>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-default"
data-dismiss="modal"
>
Close
</button>
<button
type="button"
className="btn btn-primary"
onClick={handleSubmit}
>
Update
</button>
</div>
</div>
</div>
</div>,
document.body
);
}
<file_sep>/code/src/languages/lark/utils/test.js
import LarkClient from "../web/larkClient";
// run Lark doctests
export default function test(code, onSuccess, onError) {
const client = new LarkClient();
client
.test(code)
.then(onSuccess)
.catch((e) => onError(e.toString()));
return client.stop;
}
<file_sep>/common/README.md
# `common`
This is a collection of utilities used by multiple apps in our ecosystem.
<file_sep>/ok-help/src/CheckBox.js
import React from "react";
import useId from "./utils.js";
import "./CheckBox.css";
export default function CheckBox(props) {
const id = useId();
return (
<div className="CheckBox custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id={id.current}
onChange={(e) => props.onChange(e.target.checked)}
/>
<label className="custom-control-label" htmlFor={id.current}>
<b>{props.flag.name}</b>
<br />
<small>{props.flag.explanation}</small>
</label>
</div>
);
}
<file_sep>/howamidoing/src/StaffView.js
import React from "react";
import "react-select2-wrapper/css/select2.css";
import { Row, Col } from "react-bootstrap";
import StudentTargetSelector from "./StudentTargetSelector.js";
import UploadTargets from "./UploadTargets.js";
import AssignmentDetails from "./AssignmentDetails.js";
import ConfigEditor from "./ConfigEditor.js";
export default function StaffView({ students, onSubmit }) {
if (window.location.toString().includes("histogram")) {
return <AssignmentDetails assignment="Labs" onLogin={onSubmit} />;
}
if (window.location.toString().endsWith("edit")) {
return <ConfigEditor />;
}
return (
<div>
<Row>
<Col>
<StudentTargetSelector students={students} onSubmit={onSubmit} />
</Col>
</Row>
<UploadTargets />
</div>
);
}
<file_sep>/buildtool/setup.py
from setuptools import setup, find_packages
with open("README.md") as f:
readme = f.read()
setup(
name="buildtool",
version="0.1.*",
author="<NAME>",
author_email="<EMAIL>",
long_description=readme,
long_description_content_type="text/markdown",
licence="MIT",
packages=find_packages(
include=["buildtool", "buildtool.common", "buildtool.common.rpc"]
),
package_data={"": ["**/*.tex"]},
include_package_data=True,
entry_points={
"console_scripts": [
"buildtool=buildtool.__main__:cli",
"bt=buildtool.__main__:cli",
]
},
python_requires=">=3.8",
install_requires=[
"click",
"flask",
"cachetools",
"colorama",
"requests",
"tqdm",
"google-cloud-storage",
"packaging",
],
)
<file_sep>/cats/server/gui_files/leaderboard_integrity.py
import base64
import json
import os
import random
import time
from functools import wraps
from queue import Queue
from threading import Thread
import cats
fernet = None
COMMON_WORDS_SET = set(cats.lines_from_file("data/common_words.txt"))
CAPTCHA_QUEUE_LEN = 200
CAPTCHA_LENGTH = 10
CAPTCHA_WORD_LEN = 10
captcha_queue = Queue()
def require_fernet(f):
@wraps(f)
def wrapped(*args, **kwargs):
global fernet
if not fernet:
from cryptography.fernet import Fernet
fernet = Fernet(os.environ.get("FERNET_KEY", Fernet.generate_key()))
return f(*args, **kwargs)
return wrapped
def token_writer(f):
@wraps(f)
@require_fernet
def wrapped(*args, **kwargs):
data = f(*args, **kwargs)
decoded = json.dumps(data).encode("utf-8")
return fernet.encrypt(decoded).decode("utf-8")
return wrapped
def token_reader(fail):
def decorator(f):
@wraps(f)
@require_fernet
def wrapped(*, token, **kwargs):
from cryptography.fernet import InvalidToken
if not token:
return fail
try:
return f(
token=json.loads(fernet.decrypt(token.encode("utf-8"))), **kwargs
)
except (TypeError, InvalidToken):
return fail
return wrapped
return decorator
@token_writer
def create_wpm_authorization(user, wpm):
return {
"user": user,
"wpm": wpm,
}
@token_reader(fail=0)
def get_authorized_limit(user, token):
if token["user"] != user:
return 0
return token["wpm"]
@token_writer
def encode_challenge(user, words):
return {
"user": user,
"words": words,
"startTime": time.time(),
}
@token_reader(fail=(False, False))
def decode_challenge(token):
return token["user"], token["words"], token["startTime"]
def populate_captcha_queue():
while captcha_queue.qsize() < CAPTCHA_QUEUE_LEN:
captcha_queue.put(generate_captcha())
def generate_captcha():
from claptcha import Claptcha
word = random.choice([x for x in COMMON_WORDS_SET if len(x) < CAPTCHA_WORD_LEN])
c = Claptcha(word, "gui_files/FreeMono.ttf", margin=(20, 10))
image_b64 = base64.b64encode(c.bytes[1].getvalue()).decode("utf-8")
return "data:image/png;base64," + image_b64, word
def get_captcha_urls(num_words=CAPTCHA_LENGTH):
Thread(target=populate_captcha_queue).start()
images, words = [], []
for _ in range(num_words):
image, word = captcha_queue.get()
images.append(image)
words.append(word)
return images, words
<file_sep>/common/rpc/search.py
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/clear/piazza")
def clear_piazza():
...
@requires_master_secret
@service.route("/insert/piazza")
def insert_piazza(*, posts):
...
@requires_master_secret
@service.route("/clear/resources")
def clear_resources():
...
@requires_master_secret
@service.route("/insert/resources")
def insert_resources(*, resources):
...
@service.route("/query")
def query(*, piazza_params, resource_params):
...
<file_sep>/examtool/examtool/cli/cheaters.py
import csv
import json
import os
from collections import defaultdict
from dataclasses import asdict
import click
from examtool.api.database import get_roster
from examtool.api.substitution_finder import find_unexpected_words
from examtool.cli.utils import exam_name_option, hidden_target_folder_option
@click.command()
@exam_name_option
@hidden_target_folder_option
@click.option(
"--out",
type=click.File("w"),
default=None,
help="Output a CSV containing the list of cheaters",
)
def cheaters(exam, target, out):
"""
Identify potential instances of cheating.
"""
if not target:
target = "out/logs/" + exam
logs = defaultdict(list)
for email, deadline in get_roster(exam=exam):
short_target = os.path.join(target, email)
full_target = os.path.join(target, "full", email)
if os.path.exists(short_target):
with open(short_target) as f:
logs[email].extend(json.load(f))
if os.path.exists(full_target):
with open(full_target) as f:
data = json.load(f)
for record in data:
if "snapshot" not in record:
print(email, record)
else:
logs[email].append(
{**record["snapshot"], "timestamp": record["timestamp"]}
)
logs[email].append(
{**record["history"], "timestamp": record["timestamp"]}
)
logs = list(logs.items())
suspects = find_unexpected_words(exam, logs)
if out:
if suspects:
writer = csv.writer(out)
keys = asdict(suspects[0])
writer.writerow(list(keys))
for suspect in suspects:
writer.writerow(asdict(suspect).values())
suspect.explain()
else:
for suspect in suspects:
suspect.explain()
<file_sep>/sections/server/seed.py
from datetime import datetime, timedelta
from os import getenv
from random import choice
import pytz
from main import app
from models import Section, User, db
def seed():
if getenv("ENV") == "prod":
return
with app.app_context():
db.drop_all()
db.create_all()
pst = pytz.timezone("US/Pacific")
sections = []
for i in range(100):
t = pst.localize(
datetime(year=2020, month=8, day=20, hour=i % 10, minute=0, second=0)
)
section = Section(
description=f"This is the {i}th demo section.",
start_time=t.timestamp(),
end_time=(t + timedelta(minutes=30)).timestamp(),
capacity=5,
)
section.tags = ["NPE"]
sections.append(section)
db.session.add(section)
users = []
for i in range(200):
section = choice(sections)
user = User(
email=f"<EMAIL>",
name=f"Oski {i}th of his name",
is_staff=False,
)
user.sections = [section]
users.append(user)
db.session.commit()
if __name__ == "__main__":
seed()
<file_sep>/code/src/web-server/language_apis.py
import re
from json import dumps
from multiprocessing import Process, Queue
import black
import requests
from flask import jsonify, request
from lark import Lark, LarkError, Token, Tree, UnexpectedEOF
from IGNORE_scheme_debug import (
Buffer,
SchemeError,
debug_eval,
scheme_read,
tokenize_lines,
)
from formatter import scm_reformat
def create_language_apis(app):
# python
@app.route("/api/pytutor", methods=["POST"])
def pytutor_proxy():
data = {
"user_script": request.form["code"],
# "options_json": r'{"cumulative_mode":true,"heap_primitives":false}',
}
if "options_json" in request.form:
data["options_json"] = request.form["options_json"]
response = requests.post(
"http://pythontutor.com/web_exec_py3.py",
data=data,
)
return response.text
@app.route("/api/black", methods=["POST"])
def black_proxy():
try:
return jsonify(
{
"success": True,
"code": black.format_str(
request.form["code"], mode=black.FileMode()
)
+ "\n",
}
)
except Exception as e:
return jsonify({"success": False, "error": repr(e)})
# scheme
@app.route("/api/scm_debug", methods=["POST"])
def scm_debug():
code = request.form["code"]
q = Queue()
p = Process(target=scm_worker, args=(code, q))
p.start()
p.join(10)
if not q.empty():
return jsonify(q.get())
@app.route("/api/scm_format", methods=["POST"])
def scm_format():
try:
return jsonify(
{"success": True, "code": scm_reformat(request.form["code"])}
)
except Exception as e:
return jsonify({"success": False, "error": repr(e)})
@app.route("/api/lark_run", methods=["POST"])
def lark_run():
grammar = request.form["grammar"]
import_regex = r"%import common\.([a-zA-Z]*)"
imports = [match.group(1) for match in re.finditer(import_regex, grammar)]
grammar = re.sub(r"%import common\.[a-zA-Z]*", "", grammar)
if "%import" in grammar:
return jsonify(dict(error="Arbitrary %imports are not supported"))
for terminal in imports:
grammar += f"""
%import common.{terminal}
"""
text = request.form.get("text", None)
try:
parser = Lark(grammar, start="start")
except LarkError as e:
return jsonify(dict(error=str(e)))
if text is None:
return jsonify(dict(success=True))
try:
parse_tree = parser.parse(text)
except UnexpectedEOF as e:
return jsonify(
dict(
error=str(e)
+ "[Hint: use the .begin and .end commands to input multiline strings]\n"
)
)
except LarkError as e:
return jsonify(dict(error=str(e)))
def export(node):
if isinstance(node, Tree):
return [
node.data,
[export(child) for child in node.children],
]
elif isinstance(node, Token):
return [repr(node.value)]
else:
return [repr(node)]
return jsonify(
success=True, parsed=export(parse_tree), repr=parse_tree.pretty()
)
def scm_worker(code, queue):
try:
buff = Buffer(tokenize_lines(code.split("\n")))
exprs = []
while buff.current():
exprs.append(scheme_read(buff))
out = debug_eval(exprs)
except (SyntaxError, SchemeError) as err:
queue.put(dumps(dict(error=str(err))))
except:
queue.put(dumps(dict(error="An internal error occurred.")))
raise
else:
queue.put(out)
<file_sep>/common/jobs.py
from functools import wraps
from flask import Flask
def job(app: Flask, endpoint):
"""Adds a URL rule for a recurring job at ``/jobs/<endpoint>``.
:param app: the app the method belongs to
:type app: ~flask.Flask
:param endpoint: the endpoint to route to the method
:type endpoint: str
:return: a decorator which can be applied to a function to bind it to
``/jobs/<endpoint>``
"""
def decorator(func):
@wraps(func)
def wrapped():
func()
return ""
app.add_url_rule(
f"/jobs/{endpoint}",
func.__name__ + "_job",
wrapped,
strict_slashes=False,
methods=["POST"],
)
return func
return decorator
<file_sep>/hosted/index.md
```{include} README.md
```
## Code Documentation
This file contains the Python portion of the app.
```{eval-rst}
.. automodule:: hosted.app
:members:
```<file_sep>/oh/config.py
import os
from common.db import database_url
from common.rpc.secrets import get_secret
basedir = os.path.abspath(os.path.dirname(__file__))
ENV = os.getenv("ENV", "dev")
if ENV == "DEV_ON_PROD":
ENV = "dev"
if ENV == "dev":
DEBUG = True
SECRET_KEY = "dev"
else:
DEBUG = False
SECRET_KEY = get_secret(secret_name="SESSION_COOKIE_SECRET")
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
SQLALCHEMY_DATABASE_URI = database_url
SQLALCHEMY_TRACK_MODIFICATIONS = False
DATABASE_CONNECT_OPTIONS = {}
LOCAL_TIMEZONE = os.getenv("TIMEZONE", "US/Pacific")
AUTH_KEY = "oh-queue-staging" if os.getenv("IN_STAGING") else "oh-queue"
if ENV == "dev":
AUTH_SECRET = ""
OK_KEY = "local-dev-email"
OK_SECRET = "KH0mvknMUWT5w3U7zvz6<KEY>"
else:
AUTH_SECRET = get_secret(secret_name="AUTH_SECRET")
OK_KEY = "oh-queue"
OK_SECRET = get_secret(secret_name="OKPY_OAUTH_SECRET")
OK_SERVER_URL = os.getenv("OK_DEPLOYMENT", "https://okpy.org")
HOST = os.getenv("HOST", "127.0.0.1")
PORT = int(os.getenv("PORT", "5000"))
<file_sep>/howamidoing/src/loadAssignments.js
export const getAssignments = () => {
const { createAssignments } = window;
return createAssignments();
};
export const getAssignmentLookup = () => {
const ASSIGNMENTS = getAssignments();
const lookup = {};
const populateLookup = (assignment) => {
lookup[assignment.name] = assignment;
if (assignment.isTopic) {
for (const child of assignment.children) {
populateLookup(child);
}
}
};
for (const assignment of ASSIGNMENTS) {
populateLookup(assignment);
}
return lookup;
};
<file_sep>/cats/src/TopicPicker.js
import React, { useState } from "react";
import Button from "react-bootstrap/Button";
import Col from "react-bootstrap/Col";
import Form from "react-bootstrap/Form";
import "./TopicPicker.css";
export default function TopicPicker({ onClick }) {
const [topics, setTopics] = useState("");
const handleChange = (e) => {
setTopics(e.target.value);
};
const handleClick = () => {
onClick(
topics
.split(/\s|,/)
.map((x) => x.trim().toLowerCase())
.filter((x) => x.length)
);
};
return (
<div className="TopicPicker">
<Form
onSubmit={(e) => {
e.preventDefault();
handleClick();
}}
>
<Form.Label>Specify topics of interest</Form.Label>
<Form.Row>
<Col>
<Form.Control
placeholder="Cat, Cats, Kittens, ..."
value={topics}
onChange={handleChange}
/>
</Col>
<Button variant="primary" onClick={handleClick}>
Submit
</Button>
</Form.Row>
<Form.Text className="text-muted">
List topics separated by commas.
</Form.Text>
</Form>
</div>
);
}
<file_sep>/hosted/README.md
# Hosted Apps DNA
This is 61A's stateful app hosting service, a wrapper around
[@itsvs](https://github.com/itsvs)'s [dna](https://dna.vanshaj.dev/) tool.
This app has no local setup, as it is not meant to be run locally. Most of the
code here is just RPC wrappers, which haven't been documented yet, so feel free
to peruse through the code and reference the `dna` docs if you want to
understand this app better.
The `buildserver` deploy script for this app is available
[here](https://github.com/Cal-CS-61A-Staff/cs61a-apps/blob/62ff040c72f63b0258508e72c76d162cf9dcc16a/buildserver/deploy.py#L382).<file_sep>/oh/oh_queue/static/js/components/appointment_buttons.js
function AppointmentButtons({ ids }) {
const action = (action) => () => {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this action!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, do it!",
}).then((result) => {
if (result.value) {
app.makeRequest("bulk_appointment_action", { action, ids }, () => {
Swal.fire("Success!", "Your action has been performed.", "success");
});
}
});
};
const { Link } = ReactRouterDOM;
return (
<div className="appointment-buttons">
{ids == null && (
<Link className="btn btn-success" to="/admin/appointments">
Add Appointments
</Link>
)}
<button className="btn btn-warning" onClick={action("open_all_assigned")}>
Activate all assigned appointments
</button>
<button className="btn btn-primary" onClick={action("resolve_all_past")}>
Resolve all past appointments
</button>
<button
className="btn btn-danger"
onClick={action("remove_all_unassigned")}
>
Delete all unassigned appointments
</button>
<button
className="btn btn-info"
onClick={action("resend_reminder_emails")}
>
Resend reminder emails
</button>
</div>
);
}
<file_sep>/common/rpc/index.md
```{include} README.md
```
## Utilities
### Auth
```{eval-rst}
.. automodule:: common.rpc.auth_utils
:members:
```
### Miscellaneous
```{eval-rst}
.. automodule:: common.rpc.utils
:members:
```
## Autograder
```{eval-rst}
.. automodule:: common.rpc.ag_master
:members:
```
## 61A Auth
```{eval-rst}
.. automodule:: common.rpc.auth
:members:
```
## Buildserver
```{eval-rst}
.. automodule:: common.rpc.buildserver
:members:
```
## 61A Domains
```{eval-rst}
.. automodule:: common.rpc.domains
:members:
```
## Hosted Apps
```{eval-rst}
.. automodule:: common.rpc.hosted
:members:
```
## Howamidoing
```{eval-rst}
.. automodule:: common.rpc.howamidoing
:members:
```
## CS 162 Mailserver
```{eval-rst}
.. automodule:: common.rpc.mail
:members:
```
## Office Hours Queue
```{eval-rst}
.. automodule:: common.rpc.oh
:members:
```
## Paste
```{eval-rst}
.. automodule:: common.rpc.paste
:members:
```
## Sandbox + IDE
```{eval-rst}
.. automodule:: common.rpc.sandbox
:members:
```
## Secrets Tool
```{eval-rst}
.. automodule:: common.rpc.secrets
:members:
```
## Sections/Tutorials
```{eval-rst}
.. automodule:: common.rpc.sections
:members:
```
## Slackbot
```{eval-rst}
.. automodule:: common.rpc.slack
:members:
```<file_sep>/oh/migrations/versions/3b7d60ea61e3_added_appointment_description_field.py
"""added appointment description field
Revision ID: 3b7d60ea61e3
Revises: <PASSWORD>
Create Date: 2020-04-05 08:30:54.515681
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "<PASSWORD>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"appointment", sa.Column("description", sa.String(length=255), nullable=False)
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("appointment", "description")
# ### end Alembic commands ###
<file_sep>/hog-calc/runner.py
import subprocess
GOAL_SCORE = 100
MAX_ROLLS = 10
def make_strat_str(strat_0, strat_1):
"""Takes in two separate strategies and converts them both into a string
separating each num_roll of dice by a newline.
:param strat_0: the first inputted strategy
:type strat_0: list
:param strat_1: the second inputted strategy
:type strat_1: list
:return: a string with number of dice rolls per score value per strategy
"""
out = []
for strat in [strat_0, strat_1]:
for i in range(GOAL_SCORE):
for j in range(GOAL_SCORE):
out.append(str(strat[i][j]))
return "\n".join(out)
def match(strat_0, strat_1, *, use_contest=True):
"""Plays a match between two strategies.
:param strat_0: the first inputted strategy
:type strat_0: list
:param strat_1: the second inputted strategy
:type strat_1: list
:param use_contest: determines whether bacon or bacon_proj is used
:type use_contest: bool
:return: the float result of a match between two strategies
"""
p = subprocess.Popen(
["./bacon" if use_contest else "./bacon_proj"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
strat_str = make_strat_str(strat_0, strat_1)
out, err = p.communicate(bytes(strat_str, "utf-8"))
if err:
raise Exception(err.decode("utf-8"))
return float(out.decode("utf-8"))
def score(strat_0, strat_1, *, use_contest=True):
"""
Determine the score of a matchup between the two strategies.
:param strat_0: the first inputted strategy
:type strat_0: list
:param strat_1: the second inputted strategy
:type strat_1: list
:param use_contest: determines whether bacon or bacon_proj is used
:type use_contest: bool
:return: the float score of matching up two strategies
"""
return (
1
+ match(strat_0, strat_1, use_contest=use_contest)
- match(strat_1, strat_0, use_contest=use_contest)
) / 2
<file_sep>/code/src/web-server/shortlink_generator.py
import random
from common.rpc.secrets import only
from flask import request, abort
from common.db import connect_db
from common.rpc.code import create_code_shortlink
from constants import NOT_LOGGED_IN, NOT_AUTHORIZED, NOT_FOUND, ServerFile
from oauth_utils import check_auth
def attempt_generated_shortlink(path, app):
with connect_db() as db:
try:
ret = db("SELECT * FROM staffLinks WHERE link=%s;", [path]).fetchone()
if ret is not None:
return ServerFile(
ret["link"],
ret["fileName"],
"",
ret["fileContent"].decode(),
ret["shareRef"],
False,
)._asdict()
ret = db("SELECT * FROM studentLinks WHERE link=%s;", [path]).fetchone()
if ret is None:
return NOT_FOUND
if check_auth(app):
return ServerFile(
ret["link"],
ret["fileName"],
"",
ret["fileContent"].decode(),
ret["shareRef"],
False,
)._asdict()
else:
return NOT_AUTHORIZED
except Exception:
return NOT_LOGGED_IN
def create_shortlink_generator(app):
try:
with open("sanitized_words.txt") as f:
words = f.read().split("\n")
except FileNotFoundError:
words = [f"word{i}" for i in range(1000)]
def save_file_web(staff_only):
file_name, file_content, share_ref = (
request.form["fileName"],
request.form["fileContent"],
request.form["shareRef"],
)
return save_file(file_name, file_content, share_ref, staff_only)
def save_file(file_name, file_content, share_ref, staff_only, link=None):
db_name = "studentLinks" if staff_only else "staffLinks"
with connect_db() as db:
if not link:
link = "".join(
random.sample(words, 1)[0].strip().title() for _ in range(3)
)
db(
f"INSERT INTO {db_name} VALUES (%s, %s, %s, %s)",
[link, file_name, file_content, share_ref],
)
return "code.cs61a.org/" + link
@app.route("/api/share", methods=["POST"])
def share():
return save_file_web(True)
@app.route("/api/staff_share", methods=["POST"])
def staff_share():
if not check_auth(app):
abort(403)
return save_file_web(False)
@create_code_shortlink.bind(app)
@only("examtool")
def create_code_shortlink_impl(
name: str, contents: str, staff_only: bool = True, link: str = None
):
return save_file(name, contents, None, staff_only, link)
def setup_shortlink_generator():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS studentLinks (
link varchar(128),
fileName varchar(128),
fileContent BLOB,
shareRef varchar(128))"""
)
db(
"""CREATE TABLE IF NOT EXISTS staffLinks (
link varchar(128),
fileName varchar(128),
fileContent BLOB,
shareRef varchar(128))"""
)
# ALTER TABLE staffLinks ADD shareRef varchar(128);
<file_sep>/gui_files/svg.py
class SVGRect:
def __init__(self, x, y, width, height, stroke, fill):
self.x = x
self.y = y
self.width = width
self.height = height
self.stroke = stroke
self.fill = fill
def __str__(self):
return """<rect x="{0}" y="{1}" width="{2}" height="{3}" stroke="{4}" fill="{5}" />""".format(
self.x, self.y, self.width, self.height, self.stroke, self.fill
)
class SVGCircle:
def __init__(self, x, y, radius, stroke, fill):
self.x = x
self.y = y
self.radius = radius
self.stroke = stroke
self.fill = fill
def __str__(self):
return (
"""<circle cx="{0}" cy="{1}" r="{2}" stroke="{3}" fill="{4}" />""".format(
self.x, self.y, self.radius, self.stroke, self.fill
)
)
class SVGLine:
def __init__(self, x1, y1, x2, y2, stroke):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.stroke = stroke
def __str__(self):
return """<line x1="{0}" y1="{1}" x2="{2}" y2="{3}" stroke="{4}" />""".format(
self.x1, self.y1, self.x2, self.y2, self.stroke
)
class SVGPolygon:
def __init__(self, points, stroke, fill):
self.points = points # list of lists
self.stroke = stroke
self.fill = fill
def __str__(self):
points_str = " ".join(",".join(map(str, point)) for point in self.points)
return """<polygon points="{0}" stroke="{1}" fill="{2}"/>""".format(
points_str, self.stroke, self.fill
)
class SVGText:
def __init__(self, x, y, text, stroke, fill, font_size, font_family):
self.x = x
self.y = y
self.text = text
self.stroke = stroke
self.fill = fill
self.font_size = font_size
self.font_family = font_family
def __str__(self):
return """<text x="{0}" y="{1}" stroke="{2}" fill="{3}" font-size="{4}" font-family="{5}">{6}</text>""".format(
self.x,
self.y,
self.stroke,
self.fill,
self.font_size,
self.font_family,
self.text,
)
class SVGGraphic:
def __init__(self, width, height):
self.width = width
self.height = height
self.shapes = []
def draw_rect(self, x, y, width, height, stroke, fill):
self.shapes.append(SVGRect(x, y, width, height, stroke, fill))
def draw_circle(self, x, y, radius, stroke, fill):
self.shapes.append(SVGCircle(x, y, radius, stroke, fill))
def draw_line(self, x1, y1, x2, y2, stroke):
self.shapes.append(SVGLine(x1, y1, x2, y2, stroke))
def draw_polygon(self, points, stroke, fill):
self.shapes.append(SVGPolygon(points, stroke, fill))
def write_text(self, x, y, text, stroke, fill, font_size, font_family):
self.shapes.append(SVGText(x, y, text, stroke, fill, font_size, font_family))
def __str__(self):
shapes = "".join(str(shape) for shape in self.shapes)
return """<svg width="{0}" height="{1}" xmlns="http://www.w3.org/2000/svg">{2}</svg>""".format(
self.width, self.height, shapes
)
def create_graphic(width, height):
return SVGGraphic(width, height)
def draw_rect(graphic, x, y, width, height, stroke="black", fill="black"):
graphic.draw_rect(x, y, width, height, stroke, fill)
def draw_circle(graphic, x, y, radius, stroke="black", fill="black"):
graphic.draw_circle(x, y, radius, stroke, fill)
def draw_line(graphic, x1, y1, x2, y2, stroke="black"):
graphic.draw_line(x1, y1, x2, y2, stroke)
def draw_triangle(graphic, x1, y1, x2, y2, x3, y3, stroke="black", fill="black"):
graphic.draw_polygon([[x1, y1], [x2, y2], [x3, y3]], stroke, fill)
def write_text(
graphic,
x,
y,
text,
stroke="black",
fill="black",
font_size="medium",
font_family="serif",
):
graphic.write_text(x, y, text, stroke, fill, font_size, font_family)
<file_sep>/oh/oh_queue/static/js/components/row.js
function Row({ title, link, prop1, prop2 }) {
return (
<div className="ticket-row clearfix ticket-link">
<Link to={link} className="clearfix">
<div className="pull-left ticket-index" />
<h4 className="pull-left">
<Link to={link}>{title}</Link>
<br className="visible-xs" />
<small className="visible-xs ticket-status-xs">{prop2}</small>
<small className="visible-xs ticket-desc-xs" />
<small className="visible-xs ticket-created-xs">{prop1}</small>
</h4>
<h4 className="pull-left hidden-xs ticket-created-md">
<small>{prop1}</small>
</h4>
<h4 className="pull-right hidden-xs ticket-status-md ">
<small>{prop2}</small>
</h4>
</Link>
</div>
);
}
<file_sep>/secrets/README.md
# `secrets`
Serves as an access point to the secrets table in the cloud database so that
secrets don't have to be hardcoded into the apps. Various actions require access
and tokens beyond what most staff is allowed to have, so secrets ensure that
only people who should be able to access a certain resource are able to access
it. Restricted to admins.
<file_sep>/oh/migrations/prev_versions/56a1480bb7cc_queue_magic_word.py
"""Add queue password support
Revision ID: <KEY>
Revises: 1b5a90520562
Create Date: 2019-10-14 01:01:34.298396
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "1b5a90520562"
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
from oh_queue.models import ConfigEntry
# BaseTable = declarative_base()
# class ConfigEntry(BaseTable):
# __tablename__ = 'config_entries'
# key = sa.Column(sa.String(255), primary_key=True)
# value = sa.Column(sa.Text(), nullable=False)
# public = sa.Column(sa.Boolean, default=False)
def upgrade():
pass
def downgrade():
pass
<file_sep>/examtool/examtool/api/utils.py
import os
import random
import string
from functools import wraps
from typing import Optional
def as_list(func):
@wraps(func)
def wrapped(*args, **kwargs):
return list(func(*args, **kwargs))
return wrapped
def sanitize_email(email):
return email.replace("_", r"\_")
def dict_to_list(d):
out = [None] * len(d)
for k, v in d.items():
out[int(k)] = v
return out
def rand_id(length=32):
return "".join(random.choices(string.ascii_uppercase, k=length))
def list_to_dict(l):
return {i: x for i, x in enumerate(l)}
def rel_path(path):
root = os.path.dirname(os.path.abspath(__file__))
return os.path.join(root, path)
def rel_open(path, *args, **kwargs):
return open(rel_path(path), *args, **kwargs)
class IDFactory:
def __init__(self, *, id_start="", id_end="", length=32, allow_random_ids=True):
if length is None:
length = 32
self.length = length
self.id_start = id_start
self.id_end = id_end
self.allow_random_ids = allow_random_ids
self.current_ids = set()
def id_from_str(self, string):
return self.id_start + string + self.id_end
def get_id(self, string: Optional[str] = None):
if string is None:
if not self.allow_random_ids:
raise SyntaxError(
"A custom ID is required but was not set for this question!"
)
qid = rand_id(length=self.length)
while qid in self.current_ids:
qid = rand_id(length=self.length)
else:
qid = self.id_from_str(string)
if qid in self.current_ids:
raise SyntaxError(f"Received duplicate question IDs {qid}.")
self.current_ids.add(qid)
return qid
<file_sep>/oh/requirements.txt
click==6.7
Flask==1.0.0
Flask-Login==0.4.0
Flask-Migrate==2.0.0
Flask-Script==2.0.5
Flask-SQLAlchemy==2.3.2
itsdangerous==0.24
Jinja2==2.10.1
MarkupSafe==0.23
oauthlib==2.0.1
python-engineio==3.9.0
python-socketio==1.7.1
pytz==2016.10
requests-oauthlib==0.8.0
six==1.10.0
flask-debugtoolbar==0.11.0
webassets==0.12.1
gunicorn==20.0.4
eventlet==0.27.0
names==0.3.0
raven[flask]==6.0.0
APScheduler==3.6.3
flask-compress==1.5.0
ics==0.7
-r common/requirements.txt
<file_sep>/docs/contributors.rst
Contributors
=======================================================
Here's a list of people who contributed to our various
apps!
Autograder
-------------------------------------------------------
- |Vanshaj|
- Documented by |Vanshaj|
61A Auth
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by |TBD|
Buildserver
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by |TBD|
Buildtool
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
61A Code
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
Common
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by |TBD|
Discussion Cache
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
Docs/Wiki
-------------------------------------------------------
- |Vanshaj|
- Documented by |Vanshaj|
Domains
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@lucywan <https://github.com/lucywan>`__)
and <NAME> (`@kenny-chi <https://github.com/kenny-chi>`__)
Examtool
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
Grade Display
-------------------------------------------------------
- |Vanshaj|
- Documented by |TBD|
Hog Calculator
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@curiousdragon <https://github.com/curiousdragon>`__)
and <NAME> (`@GCGikas <https://github.com/GCGikas>`__)
Hog Contest
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@nikhita8 <https://github.com/nikhita8>`__)
and Uma Unni (`@umaunni3 <https://github.com/umaunni3>`__)
Hosted Apps (DNA)
-------------------------------------------------------
- |Vanshaj|
- Documented by <NAME> (`@cbugwadia32 <https://github.com/cbugwadia32>`__)
Howamidoing
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by <NAME> (`@constanceshi <https://github.com/constanceshi>`__)
and <NAME> (`@64bitpandas <https://github.com/64bitpandas>`__)
Logs
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@emmayokota <https://github.com/emmayokota>`__)
Office Hours Queue
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
Partner Matcher
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by <NAME> (`@Funplings <https://github.com/Funplings>`__)
Paste
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@emmayokota <https://github.com/emmayokota>`__)
Piazza OnCall
-------------------------------------------------------
- |Animesh|
- Documented by |TBD|
Redirect
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@Seans1337 <https://github.com/Seans1337>`__)
Sandbox + IDE
-------------------------------------------------------
- |Vanshaj|
- |Rahul|
- Documented by |TBD|
Secrets
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by <NAME> (`@ren-zhou <https://github.com/ren-zhou>`__)
Sections
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
Shortlinks
-------------------------------------------------------
- |Rahul|
- Documented by <NAME> (`@cbugwadia32 <https://github.com/cbugwadia32>`__)
SICP
-------------------------------------------------------
- |Vanshaj|
- |Rahul|
- Documented by |TBD|
Slackbot
-------------------------------------------------------
- |Rahul|
- |Vanshaj|
- Documented by |TBD|
Static Server
-------------------------------------------------------
- |Rahul|
- Documented by |TBD|
.. |Rahul| replace:: <NAME> (`@rahularya50 <https://github.com/rahularya50>`__)
.. |Vanshaj| replace:: <NAME> (`@itsvs <https://github.com/itsvs>`__)
.. |Animesh| replace:: <NAME> (`@AnimeshAgrawal <https://github.com/AnimeshAgrawal>`__)
.. |TBD| replace:: (to be documented)
<file_sep>/grade-display/requirements.txt
beautifulsoup4==4.9.3
certifi==2020.11.8
cffi==1.14.4
chardet==3.0.4
click==7.1.2
cryptography==3.2.1
Flask==1.1.2
fullGSapi==1.2.1
gunicorn==20.0.4
idna==2.10
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
py-mini-racer==0.4.0
pycparser==2.20
PyYAML==5.3.1
requests==2.25.0
soupsieve==2.0.1
urllib3==1.26.2
werkzeug==0.16.1
-r common/requirements.txt
<file_sep>/piazzaoncall/ed.py
from common.rpc.auth import Network, perform_ed_action
class EdNetwork(Network):
def __init__(self, course, is_staff, is_test):
super().__init__(course, is_staff, is_test, perform_ed_action)
def get_unresolved(self):
feed = self.get_feed(limit=999999)["threads"]
unresolved = unresolved_followups = 0
for post in feed:
u = post.get("is_answered", True)
uf = post.get("unresolved_count", 0)
if u or not uf:
continue
title = post["title"]
if "EC" in title or "extra credit" in title.lower():
continue
unresolved += u
unresolved_followups += uf
return unresolved, unresolved_followups
def iter_all_posts(self, limit=None): # new
"""Get all posts visible to the current user
This grabs you current feed and ids of all posts from it; each post
is then individually fetched. This method does not go against
a bulk endpoint; it retrieves each post individually, so a
caution to the user when using this.
:type limit: int|None
:param limit: If given, will limit the number of posts to fetch
before the generator is exhausted and raises StopIteration.
:returns: An iterator which yields all posts which the current user
can view
:rtype: generator
"""
feed = self.get_feed(limit=999999)
posts = feed["threads"]
if limit:
posts = posts[:limit]
for post in posts:
yield post
def list_unresolved(self): # new
"""Returns a generator of all unresolved posts"""
feed = self.get_feed(limit=999999)
posts = feed.get("threads")
for s in posts:
if (
s.get("approved_status", "approved") != "rejected"
and (
s.get("type", "question") != "post" or s.get("is_megathread", True)
)
and not s.get("is_answered", True)
and s.get("unresolved_count", 1)
):
yield s
network = EdNetwork("cs61a", True, False)
<file_sep>/ag-master/utils.py
from functools import wraps
from common.course_config import is_admin, is_admin_token
from common.oauth_client import get_user, is_staff, login
BUCKET = "ag-master.buckets.cs61a.org"
SUBM_ENDPOINT = "/api/v3/backups"
SCORE_ENDPOINT = "/api/v3/score/"
def admin_only(func):
"""Require a user to either be logged into the UI, or so pass in an
access token. Either way, the user must be an admin for the course they're
attempting to access.
:return: a function that takes in an ``access_token`` and a ``course``,
along with the parameters passed into the original ``func``, which is
called with all of the available arguments except ``access_token``
"""
@wraps(func)
def wrapped(*args, access_token=None, course="cs61a", **kwargs):
token_good = access_token and is_admin_token(
access_token=access_token, course=course
)
cookie_good = is_staff(course=course) and is_admin(
email=get_user()["email"], course=course
)
if token_good or cookie_good:
try:
return func(*args, **kwargs, course=course)
except PermissionError:
pass
if access_token:
raise PermissionError
else:
return login()
return wrapped
def super_admin_only(func):
"""Does almost the same thing as :func:`~docs.ag_master.utils.admin_only`,
except the course must be ``cs61a``.
:return: a function that takes in an ``access_token`` and a ``course``,
along with the parameters passed into the original ``func``, which is
called without ``access_token`` or ``course``
"""
@wraps(func)
@admin_only
def wrapped(*args, course, **kwargs):
if course != "cs61a":
raise PermissionError
return func(*args, **kwargs)
return wrapped
<file_sep>/code/src/common/languages.js
export const PYTHON = "PYTHON";
export const SCHEME = "SCHEME";
export const SQL = "SQL";
export const LARK = "LARK";
<file_sep>/slack/staff.py
from typing import NamedTuple
class StaffMember(NamedTuple):
firstName: str
lastName: str
emoji: str
STAFF = [
StaffMember(firstName="Aaron", lastName="Chen", emoji=":aaron:"),
StaffMember(firstName="Abhinav", lastName="Ashar", emoji=":abhinav:"),
StaffMember(firstName="Addison", lastName="Chan", emoji=":addison:"),
StaffMember(firstName="Albert", lastName="Xu", emoji=":albert:"),
StaffMember(firstName="Alex", lastName="Kassil", emoji=":alex:"),
StaffMember(firstName="Alicia", lastName="Wang", emoji=":alicia:"),
StaffMember(firstName="Alina", lastName="Herri", emoji=":alina:"),
StaffMember(firstName="Amit", lastName="Bhat", emoji=":amit:"),
StaffMember(firstName="Amrita", lastName="Palaparthi", emoji=":amrita:"),
StaffMember(firstName="Amritansh", lastName="Saraf", emoji=":amritansh:"),
StaffMember(firstName="Andrew", lastName="Lenz", emoji=":andrew-l:"),
StaffMember(firstName="Andrew", lastName="Shieh", emoji=":andrew-s:"),
StaffMember(firstName="Andrew", lastName="Mcguire", emoji=":andrew-m:"),
StaffMember(firstName="Animesh", lastName="Agrawal", emoji=":animesh:"),
StaffMember(firstName="Arushi", lastName="Somani", emoji=":arushi:"),
StaffMember(firstName="Ben", lastName="Cuan", emoji=":ben:"),
StaffMember(firstName="Brandon", lastName="Choy", emoji=":brandon-c:"),
StaffMember(firstName="Brandon", lastName="Shin", emoji=":brandon-s:"),
StaffMember(firstName="Cait", lastName="Phan", emoji=":cait:"),
StaffMember(firstName="Catherine", lastName="Gee", emoji=":catherine:"),
StaffMember(firstName="Cesar", lastName="<NAME>", emoji=":cesar:"),
StaffMember(firstName="Chi", lastName="Tsai", emoji=":chi:"),
StaffMember(firstName="Christine", lastName="Luo", emoji=":christine:"),
StaffMember(firstName="Christopher", lastName="Wang", emoji=":christopher:"),
StaffMember(firstName="Connie", lastName="Shi", emoji=":connie:"),
StaffMember(firstName="Cooper", lastName="Bedin", emoji=":cooper:"),
StaffMember(firstName="Crystal", lastName="Wang", emoji=":crystal:"),
StaffMember(firstName="Cyrus", lastName="Bugwadia", emoji=":cyrus:"),
StaffMember(firstName="Daniel", lastName="Shin", emoji=":daniel:"),
StaffMember(firstName="Daphne", lastName="Pan", emoji=":daphne:"),
StaffMember(firstName="DeNero", lastName="Denero", emoji=":john:"),
StaffMember(firstName="Derek", lastName="Wan", emoji=":derek:"),
StaffMember(firstName="Eknoor", lastName="Kaur", emoji=":eknoor:"),
StaffMember(firstName="Emma", lastName="Yokota", emoji=":emma:"),
StaffMember(firstName="Eric", lastName="Wang", emoji=":eric:"),
StaffMember(firstName="Ethan", lastName="Chiu", emoji=":ethan:"),
StaffMember(firstName="George", lastName="Gikas", emoji=":george:"),
StaffMember(firstName="Griffin", lastName="Prechter", emoji=":griffin:"),
StaffMember(firstName="Gurkaran", lastName="<NAME>", emoji=":gurkaran:"),
StaffMember(firstName="Han", lastName="Qi", emoji=":han:"),
StaffMember(firstName="Imran", lastName="Khaliq", emoji=":imran:"),
StaffMember(firstName="Jade", lastName="Singh", emoji=":jade:"),
StaffMember(firstName="Jamie", lastName="Hong", emoji=":jamie:"),
StaffMember(firstName="Jemmy", lastName="Zhou", emoji=":jemmy:"),
StaffMember(firstName="Jennifer", lastName="Huang", emoji=":jennifer:"),
StaffMember(firstName="Jenny", lastName="Wang", emoji=":jenny:"),
StaffMember(firstName="Jessica", lastName="Yu", emoji=":jessica:"),
StaffMember(firstName="John", lastName="So", emoji=":john:"),
StaffMember(firstName="John", lastName="Denero", emoji=":john:"),
StaffMember(firstName="Joshua", lastName="Baum", emoji=":joshua:"),
StaffMember(firstName="Julie", lastName="Ma", emoji=":julie:"),
StaffMember(firstName="Kaavya", lastName="Shah", emoji=":kaavya:"),
StaffMember(firstName="Kenneth", lastName="Chi", emoji=":kenneth:"),
StaffMember(firstName="Kenny", lastName="Chi", emoji=":kenny:"),
StaffMember(firstName="Kevin", lastName="Yang", emoji=":kevin-y:"),
StaffMember(firstName="Kevin", lastName="Zhu", emoji=":kevin-z:"),
StaffMember(firstName="Kevin", lastName="Li", emoji=":kevin-l:"),
StaffMember(firstName="Khushi", lastName="Malde", emoji=":khushi:"),
StaffMember(firstName="Kristy", lastName="Lee", emoji=":kristy:"),
StaffMember(firstName="Laryn", lastName="Qi", emoji=":laryn:"),
StaffMember(firstName="Lauren", lastName="Meier", emoji=":lauren:"),
StaffMember(firstName="Linh", lastName="Tran", emoji=":linh:"),
StaffMember(firstName="Lucy", lastName="Wan", emoji=":lucy:"),
StaffMember(firstName="Marie", lastName="Chorpita", emoji=":marie:"),
StaffMember(firstName="Mathilde", lastName="Mckeever", emoji=":mathilde:"),
StaffMember(firstName="Matthew", lastName="Lee", emoji=":matthew:"),
StaffMember(firstName="Matthew", lastName="Guo", emoji=":matthew-g:"),
StaffMember(firstName="Megan", lastName="Zhu", emoji=":megan:"),
StaffMember(firstName="Melanie", lastName="Cooray", emoji=":melanie:"),
StaffMember(firstName="Melody", lastName="Sifry", emoji=":melody:"),
StaffMember(firstName="Melvin", lastName="Aristio", emoji=":melvin:"),
StaffMember(firstName="Michael", lastName="Lu", emoji=":michael:"),
StaffMember(firstName="Minnie", lastName="Chen", emoji=":minnie:"),
StaffMember(firstName="Mohsin", lastName="Sarwari", emoji=":mohsin:"),
StaffMember(firstName="Murtaza", lastName="Ali", emoji=":murtaza:"),
StaffMember(firstName="Nancy", lastName="Shaw", emoji=":nancy:"),
StaffMember(firstName="Nikhita", lastName="Anumukonda", emoji=":nikhita:"),
StaffMember(firstName="Olivia", lastName="Shiah", emoji=":olivia:"),
StaffMember(firstName="Owen", lastName="Gong", emoji=":owen:"),
StaffMember(firstName="Pamela", lastName="Fox", emoji=":pamela:"),
StaffMember(firstName="Parth", lastName="Gupta", emoji=":parth:"),
StaffMember(firstName="Patricia", lastName="Ouyang", emoji=":patricia:"),
StaffMember(firstName="Pranad", lastName="Reddy", emoji=":pranad:"),
StaffMember(firstName="Rachel", lastName="Dejaen", emoji=":rachel:"),
StaffMember(firstName="Rahul", lastName="Arya", emoji=":rahul-a:"),
StaffMember(firstName="Richard", lastName="Roggenkemper", emoji=":richard-r:"),
StaffMember(firstName="Richard", lastName="Zhu", emoji=":richard-z:"),
StaffMember(firstName="Rohan", lastName="Dsouza", emoji=":rohan:"),
StaffMember(firstName="Ryan", lastName="Chao", emoji=":ryan:"),
StaffMember(firstName="Sahil", lastName="Morchi", emoji=":sahil:"),
StaffMember(firstName="Sameer", lastName="Saptarshi", emoji=":sameer:"),
StaffMember(firstName="Samuel", lastName="Taplin", emoji=":samuel:"),
StaffMember(firstName="Sarina", lastName="Sabouri", emoji=":sarina:"),
StaffMember(firstName="Sean", lastName="Obrien", emoji=":sean-o:"),
StaffMember(firstName="Sean", lastName="Sananikone", emoji=":sean-s:"),
StaffMember(firstName="Selina", lastName="Wu", emoji=":selina:"),
StaffMember(firstName="Shayna", lastName="Kothari", emoji=":shayna:"),
StaffMember(firstName="Sherry", lastName="Fan", emoji=":sherry:"),
StaffMember(firstName="Sophia", lastName="Xiao", emoji=":sophia:"),
StaffMember(firstName="Sreevidya", lastName="Ganga", emoji=":sreevidya:"),
StaffMember(firstName="Steven", lastName="Chen", emoji=":steven:"),
StaffMember(firstName="Tim", lastName="Tu", emoji=":tim:"),
StaffMember(firstName="Todd", lastName="Yu", emoji=":todd:"),
StaffMember(firstName="Uma", lastName="Unni", emoji=":uma:"),
StaffMember(firstName="Vanshaj", lastName="Singhania", emoji=":vanshaj:"),
StaffMember(firstName="Vivian", lastName="Lu", emoji=":vivian:"),
StaffMember(firstName="Yersultan", lastName="Sapar", emoji=":yersultan:"),
]
STAFF_EMOJI = {x.emoji for x in STAFF}
<file_sep>/hog-contest/thread_utils.py
import queue
from functools import wraps
from threading import Thread
def only_once(f):
q = queue.Queue()
@wraps(f)
def worker():
while True:
args, kwargs = q.get()
f(*args, **kwargs)
q.task_done()
@wraps(f)
def wrapped(*args, **kwargs):
q.put([args, kwargs])
Thread(target=worker, daemon=True).start()
return wrapped
<file_sep>/auth/ed_api.py
import requests
class Ed:
BASE = "https://us.edstem.org/api"
FEED = "/threads?limit={limit}&sort=date&order=desc"
THREAD = BASE + "/threads/{cid}?view=1"
def user_login(self, username, password):
resp = requests.post(
Ed.BASE + "/token", json=dict(login=username, password=<PASSWORD>)
)
self.token = resp.json()["token"]
def network(self, id):
self.course_endpoint = Ed.BASE + f"/courses/{id}"
return self
def get_feed(self, limit):
resp = requests.get(
self.course_endpoint + Ed.FEED.format(limit=limit),
headers={"x-token": self.token},
)
return resp.json()
def get_post(self, cid):
resp = requests.get(Ed.THREAD.format(cid=cid), headers={"x-token": self.token})
return resp.json()["thread"]
<file_sep>/slack/lgtm_integration.py
import re
import requests
from github import Github
from common.rpc.auth import read_spreadsheet
from common.rpc.secrets import get_secret
from integration import Integration
VALID_PATH = r"[0-9A-Za-z\-]+"
REPO_REGEX = rf"(?P<repo>{VALID_PATH}/{VALID_PATH})"
PATH_REGEX = rf"(?P<path>{VALID_PATH})"
REGEX_TEMPLATE = (
fr"(https?://)?github\.com/{REPO_REGEX}/pull/{PATH_REGEX}/?(\|[^\s|]+)?"
)
COURSE_ORGS = {"Cal-CS-61A-Staff": "cs61a", "61c-teach": "cs61c"}
TRIGGER_WORDS = {
"lgtm": "APPROVE",
"sucks": "REQUEST_CHANGES",
"needs changes": "REQUEST_CHANGES",
}
STAFF_GITHUB = {
username: email
for email, username in read_spreadsheet(
course="cs61a",
url="https://docs.google.com/spreadsheets/d/11f3e2Vszybnxcjipkx0WPYTgDvYadzIKEkz7Tb_48kg/",
sheet_name="Sheet1",
)[1:]
}
class LGTMIntegration(Integration):
reply = None
def _process(self):
for trigger_word, event in TRIGGER_WORDS.items():
if trigger_word in self._message.lower():
break
else:
return
match = re.search(REGEX_TEMPLATE, self._message)
if not match:
return
try:
repo = match.group("repo")
pr = int(match.group("path"))
except ValueError:
return
if COURSE_ORGS[repo.split("/")[0]] != self._course:
return
users = requests.get(
"https://slack.com/api/users.list", params={"token": self._bot_token}
).json()
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
repo = g.get_repo(repo)
pr = repo.get_pull(pr)
if pr.user.login in STAFF_GITHUB:
github_email = STAFF_GITHUB[pr.user.login]
else:
github_email = pr.user.email
if not github_email:
return
for member in users["members"]:
if member["profile"].get("email") == github_email:
break
else:
return
for member in users["members"]:
if member["id"] == self._event["user"]:
sender_email = member["profile"].get("email")
break
else:
return
if sender_email == github_email:
return
action = "approved" if event == "APPROVE" else "requested changes on"
pr.create_review(
body="{} {} this PR via the Slackbot!".format(
member["profile"].get("real_name_normalized"), action
),
event=event,
)
if trigger_word == "lgtm":
self.reply = ":white_check_mark: Automatically approved on GitHub!"
elif trigger_word == "sucks":
self.reply = ":poop: Wow, this really needs changes..."
else:
self.reply = ":x: Changes requested on GitHub!"
@property
def message(self):
if self.reply:
return self._message + "\n\n" + self.reply
else:
return self._message
<file_sep>/slack/integration.py
import abc
from typing import List, Type
from config_client import get_team_data
class Integration(abc.ABC):
def __init__(self, message: str, token, team_id, event):
self._message = message
self._token = token
self._team_id = team_id
self._event = event
self._course, self._bot_token = get_team_data(team_id)
self._process()
def _process(self):
pass
@property
def message(self):
return self._message
@property
def attachments(self):
return []
@property
def responses(self):
return []
def combine_integrations(integrations: List[Type[Integration]]):
class CombinedIntegration(Integration):
def _process(self):
text = self._message
attachments = []
responses = []
for integration_type in integrations:
integration = integration_type(
text, self._token, self._team_id, self._event
)
text = integration.message
attachments.extend(integration.attachments)
responses.extend(integration.responses)
self._text = text
self._attachments = attachments
self._responses = responses
@property
def message(self):
return self._text
@property
def attachments(self):
return self._attachments
@property
def responses(self):
return self._responses
return CombinedIntegration
<file_sep>/sections/src/nullThrows.js
// @flow strict
export default function nullThrows<T>(t: ?T): T {
if (t == null) {
throw Error("Expected input to be nonnull");
}
return t;
}
<file_sep>/hog/src/RollButton.js
// @flow
import React, { useState } from "react";
import Button from "react-bootstrap/Button";
import styled from "styled-components";
import { numberStrings } from "./constants";
const Wrapper = styled.div`
font-size: 1.25rem;
width: 100%;
text-align: center;
margin-top: 20px;
`;
type Props = {|
playerIndex: number,
piggyPoints: boolean,
onClick: (number) => mixed,
|};
export default function RollButton({
playerIndex,
piggyPoints,
onClick,
}: Props) {
const min = piggyPoints ? 0 : 1;
const [numberOfRolls, setNumberOfRolls] = useState(min);
const handleChange = (e) => {
const val = Math.max(Math.min(10, e.target.value), min);
setNumberOfRolls(e.target.value && val);
};
const handleClick = () => {
onClick(numberOfRolls);
};
return (
<Wrapper>
<p>
It is Player{" "}
<b>
{numberStrings[playerIndex]}
‘s
</b>{" "}
turn.
</p>
<p>
Roll{" "}
<input
type="number"
min={min}
max={10}
value={numberOfRolls}
onChange={handleChange}
/>{" "}
Dice.
<Button
variant="info"
size="lg"
style={{ marginLeft: "10px" }}
onClick={handleClick}
>
{" "}
Roll!
</Button>
</p>
<p></p>
</Wrapper>
);
}
<file_sep>/exam-alerts/api.py
import base64
import random
import time
from os import getenv
from google.cloud import texttospeech
import requests
from flask import abort
from examtool.api.utils import rand_id
from examtool.api.extract_questions import extract_questions, get_name
from examtool.api.scramble import is_compressible_group, scramble
BATCH_SIZE = 400
assert BATCH_SIZE < 500
def get_email_from_secret(secret):
ret = requests.get("https://okpy.org/api/v3/user/", params={"access_token": secret})
if ret.status_code != 200:
abort(401)
return ret.json()["data"]["email"]
def get_student_data(db, student, exam):
student_data = (
db.collection("exam-alerts")
.document(exam)
.collection("students")
.document(student)
.get()
.to_dict()
)
exam = db.collection("exams").document(exam).get().to_dict()
student_data["questions"] = get_student_question_mapping(student, exam)
return student_data
def get_student_question_mapping(student, exam):
elements = list(extract_questions(exam, include_groups=True))
for element in elements:
element["id"] = element.get("id", rand_id()) # add IDs to groups
elements = {
element["id"]: get_name(element)
for element in elements
if element["type"] != "group" or not is_compressible_group(element)
}
old_seed = int(random.random() * 1000000)
out = [
{
"student_question_name": get_name(element),
"canonical_question_name": elements[element["id"]],
}
for element in list(
extract_questions(scramble(student, exam), include_groups=True)
)
]
random.seed(old_seed)
return out
def get_student_question_name(student_data, canonical_question_name):
for question in student_data["questions"]:
if (
question["canonical_question_name"].strip()
== canonical_question_name.strip()
):
return question["student_question_name"]
def get_canonical_question_name(student_data, student_question_name):
for question in student_data["questions"]:
if question["student_question_name"].strip() == student_question_name.strip():
return question["canonical_question_name"]
def is_admin(email, course):
if getenv("ENV") == "dev":
return True
return requests.post(
"https://auth.apps.cs61a.org/admins/is_admin",
json={
"client_name": getenv("AUTH_CLIENT_NAME"),
"secret": getenv("AUTH_CLIENT_SECRET"),
"email": email,
"course": course,
},
).json()
def clear_collection(db, ref):
batch = db.batch()
cnt = 0
for document in ref.stream():
batch.delete(document.reference)
cnt += 1
if cnt > BATCH_SIZE:
batch.commit()
batch = db.batch()
cnt = 0
batch.commit()
def get_announcements(student_data, announcements, messages, received_audio, get_audio):
"""
Announcements are of the form
{
type: "scheduled" | "immediate",
canonical_question_name: string,
offset: int,
base: "start" | "end",
message: string,
spoken_message: ?string
}
Immediate announcements only need a message. If no question name is provided, the announcement will be
made relative to the exam start/end, otherwise it will be relative to the question
when that question starts / ends.
"""
to_send = []
request_time = time.time()
if request_time > student_data["end_time"] + 45 * 60:
return []
for announcement in announcements:
announcement_id, announcement = announcement.id, announcement.to_dict()
def include_it(time):
to_send.append(
{
"id": announcement_id,
"timestamp": time,
"message": announcement["message"],
"question": announcement.get("question", "Overall Exam"),
"private": False,
}
)
if received_audio is not None and announcement_id not in received_audio:
to_send[-1]["audio"] = get_audio(announcement_id)
question_name = announcement.get("canonical_question_name")
if question_name:
student_question_name = get_student_question_name(
student_data, question_name
)
if student_question_name is not None:
announcement["question"] = student_question_name
else:
# student did not receive this question
continue
if announcement["type"] == "immediate":
include_it(announcement["timestamp"])
elif announcement["type"] == "scheduled":
threshold = (
student_data["start_time"]
if announcement["base"] == "start"
else student_data["end_time"]
)
threshold += int(announcement["offset"])
if request_time >= threshold:
include_it(threshold)
for message in messages:
for response in message["responses"]:
to_send.append(
{
"id": response["id"],
"timestamp": response["timestamp"],
"message": response["message"],
"question": message["question"] or "Overall Exam",
"private": True,
}
)
if received_audio is not None and response["id"] not in received_audio:
to_send[-1]["audio"] = get_audio(response["id"])
to_send.sort(key=lambda x: x["timestamp"])
to_send.reverse()
return to_send
def generate_audio(message, prefix="Attention students. "):
message = prefix + message
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.SynthesisInput({"text": message})
voice = texttospeech.VoiceSelectionParams(
{
"name": "en-US-Wavenet-B",
"language_code": "en-US",
}
)
audio_config = texttospeech.AudioConfig(
{"audio_encoding": texttospeech.AudioEncoding.MP3}
)
audio = client.synthesize_speech(
input=synthesis_input, voice=voice, audio_config=audio_config
).audio_content
audio = base64.b64encode(audio).decode("ascii")
return audio
<file_sep>/cats/src/Leaderboard.js
import Cookies from "js-cookie";
import React, { useState, useEffect } from "react";
import Modal from "react-bootstrap/Modal";
import "./Leaderboard.css";
import EditName from "./EditName";
import LeaderboardEntry from "./LeaderboardEntry.js";
import post from "./post";
export default function Leaderboard(props) {
const [leaderboard, setLeaderboard] = useState([]);
const updateLeaderboard = () => {
post("/leaderboard").then((data) => {
setLeaderboard(data);
});
};
const handleNameChange = (newName) => {
post("/update_name", {
newName,
user: Cookies.get("user"),
}).then(updateLeaderboard);
};
useEffect(() => {
if (props.show) {
updateLeaderboard();
} else {
setLeaderboard([]);
}
}, [props.show]);
return (
<Modal
size="md"
aria-labelledby="contained-modal-title-vcenter"
centered
show={props.show}
onHide={props.onHide}
>
<Modal.Header closeButton>
<Modal.Title className="Header">Leaderboard</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="Entries">
<p id="Title">Top WPMs</p>
{leaderboard.map(([name, wpm], index) => (
<LeaderboardEntry
name={name}
index={index}
rank={index + 1}
score={wpm}
/>
))}
</div>
</Modal.Body>
<EditName onNameChange={handleNameChange} />
</Modal>
);
}
<file_sep>/buildserver/deploy.py
import json
import os
import shutil
from subprocess import CalledProcessError
from time import sleep
import sqlalchemy
import sqlalchemy.engine.url
from app_config import App, CLOUD_RUN_DEPLOY_TYPES
from build import gen_working_dir
from common.db import connect_db
from common.hash_utils import HashState
from common.rpc.hosted import add_domain, new
from common.rpc.secrets import create_master_secret, get_secret, load_all_secrets
from common.secrets import new_secret
from common.shell_utils import sh, tmp_directory
from conf import DB_INSTANCE_NAME, DB_IP_ADDRESS, PROJECT_ID
from pypi_utils import update_setup_py
def gen_master_secret(app: App, pr_number: int):
public_value, staging_value = create_master_secret(created_app_name=app.name)
return public_value if pr_number == 0 else staging_value
def gen_env_variables(app: App, pr_number: int):
# set up and create database user
database = app.name.replace("-", "_")
with connect_db() as db:
db_pw = db(
"SELECT mysql_pw FROM mysql_users WHERE app=(%s)", [app.name]
).fetchone()
if db_pw is None:
db_pw = new_secret()
# unable to use placeholders here, but it's safe because we control the app.name and db_pw
db(f"CREATE DATABASE IF NOT EXISTS {database}")
db(f'CREATE USER "{app.name}"@"%%" IDENTIFIED BY "{db_pw}";')
db(f"GRANT ALL ON {database}.* TO '{app}'@'%%'")
db("FLUSH TABLES mysql.user")
db(
"INSERT INTO mysql_users (app, mysql_pw) VALUES (%s, %s)",
[app.name, db_pw],
)
else:
db_pw = db_pw[0]
if app.config["deploy_type"] == "hosted":
database_url = sqlalchemy.engine.url.URL(
drivername="mysql",
host=DB_IP_ADDRESS,
username=app.name,
password=<PASSWORD>,
database=database,
).__to_string__(hide_password=False)
elif app.config["deploy_type"] in CLOUD_RUN_DEPLOY_TYPES:
database_url = sqlalchemy.engine.url.URL(
drivername="mysql+pymysql",
username=app.name,
password=<PASSWORD>,
database=database,
query={"unix_socket": "{}/{}".format("/cloudsql", DB_INSTANCE_NAME)},
).__to_string__(hide_password=False)
else:
database_url = None
# set up the remaining secrets
return dict(
ENV="prod",
DATABASE_URL=database_url,
INSTANCE_CONNECTION_NAME=DB_INSTANCE_NAME,
**(
dict(APP_MASTER_SECRET=gen_master_secret(app, pr_number))
if "rpc" in app.config["permissions"]
else {}
),
**(
load_all_secrets(created_app_name=app.name)
if pr_number == 0 and "rpc" in app.config["permissions"]
else {}
),
)
def gen_url(app_name: str, pr_number: int):
if pr_number == 0:
return f"{app_name}.experiments.cs61a.org/*"
else:
return f"{pr_number}.pr.{app_name}.experiments.cs61a.org/*"
def gen_service_name(app_name: str, pr_number: int):
if pr_number == 0:
return app_name
else:
return f"{app_name}-pr{pr_number}"
def gen_service_account(app: App):
# set up and create service account
hashstate = HashState()
permissions = sorted(app.config["permissions"])
hashstate.record(permissions)
service_account_name = f"managed-{hashstate.state()}"[
:30
] # max len of account ID is 30 chars
service_account_email = (
f"{<EMAIL>"
)
existing_accounts = json.loads(
sh(
"gcloud",
"iam",
"service-accounts",
"list",
"--format",
"json",
capture_output=True,
)
)
for account in existing_accounts:
if account["email"] == service_account_email:
break
else:
# need to create service account
sh(
"gcloud",
"iam",
"service-accounts",
"create",
service_account_name,
f"--description",
f'Managed service account with permissions: {" ".join(permissions)}',
"--display-name",
"Managed service account - DO NOT EDIT MANUALLY",
)
sleep(60) # it takes a while to create service accounts
role_lookup = dict(
# permissions that most apps might need
storage="roles/storage.admin",
database="roles/cloudsql.client",
logging="roles/logging.admin",
# only buildserver needs these
iam_admin="roles/resourcemanager.projectIamAdmin",
cloud_run_admin="roles/run.admin",
cloud_functions_admin="roles/cloudfunctions.admin",
)
for permission in permissions:
if permission == "rpc":
pass # handled later
else:
role = role_lookup[permission]
try:
sh(
"gcloud",
"projects",
"add-iam-policy-binding",
PROJECT_ID,
f"--member",
f"serviceAccount:{service_account_email}",
f"--role",
role,
)
except CalledProcessError:
# abort
sh(
"gcloud",
"iam",
"service-accounts",
"delete",
service_account_email,
)
raise
return service_account_name
def deploy_commit(app: App, pr_number: int):
with tmp_directory():
os.chdir(gen_working_dir(app))
{
"flask": run_flask_deploy,
"flask-pandas": run_flask_pandas_deploy,
"docker": run_dockerfile_deploy,
"pypi": run_pypi_deploy,
"cloud_function": run_cloud_function_deploy,
"service": run_service_deploy,
"static": run_static_deploy,
"hosted": run_hosted_deploy,
"none": run_noop_deploy,
}[app.config["deploy_type"]](app, pr_number)
def run_flask_deploy(app: App, pr_number: int):
shutil.copy("../../dockerfiles/flask.Dockerfile", "./Dockerfile")
run_dockerfile_deploy(app, pr_number)
def run_flask_pandas_deploy(app: App, pr_number: int):
shutil.copy("../../dockerfiles/flask-pandas.Dockerfile", "./Dockerfile")
run_dockerfile_deploy(app, pr_number)
def build_docker_image(app: App, pr_number: int) -> str:
for f in os.listdir("../../deploy_files"):
shutil.copyfile(f"../../deploy_files/{f}", f"./{f}")
service_name = gen_service_name(app.name, pr_number)
prod_service_name = gen_service_name(app.name, 0)
with open("cloudbuild.yaml", "a+") as f:
f.seek(0)
contents = f.read()
contents = contents.replace("PROD_SERVICE_NAME", prod_service_name)
contents = contents.replace("SERVICE_NAME", service_name)
f.seek(0)
f.truncate()
f.write(contents)
with open("Dockerfile", "a+") as f:
f.seek(0)
contents = f.read()
contents = contents.replace(
"<APP_MASTER_SECRET>", gen_master_secret(app, pr_number)
)
f.seek(0)
f.truncate()
f.write(contents)
sh("gcloud", "builds", "submit", "-q", "--config", "cloudbuild.yaml")
return f"gcr.io/{PROJECT_ID}/{service_name}"
def run_dockerfile_deploy(app: App, pr_number: int):
image = build_docker_image(app, pr_number)
service_name = gen_service_name(app.name, pr_number)
if app.name == "buildserver":
# we exempt buildserver to avoid breaking CI/CD in case of bugs
service_account = None
else:
service_account = gen_service_account(app)
sh(
"gcloud",
"beta",
"run",
"deploy",
service_name,
"--image",
image,
*(("--service-account", service_account) if service_account else ()),
"--region",
"us-west1",
"--platform",
"managed",
"--timeout",
"45m",
"--cpu",
str(app.config["cpus"]),
"--memory",
app.config["memory_limit"],
"--concurrency",
str(app.config["concurrency"]),
"--allow-unauthenticated",
"--add-cloudsql-instances",
DB_INSTANCE_NAME,
"--update-env-vars",
",".join(
f"{key}={val}" for key, val in gen_env_variables(app, pr_number).items()
),
"-q",
)
if pr_number == 0:
domains = json.loads(
sh(
"gcloud",
"beta",
"run",
"domain-mappings",
"list",
"--platform",
"managed",
"--region",
"us-west1",
"--format",
"json",
capture_output=True,
)
)
for domain in app.config["first_party_domains"]:
for domain_config in domains:
if domain_config["metadata"]["name"] == domain:
break
else:
sh(
"gcloud",
"beta",
"run",
"domain-mappings",
"create",
"--service",
service_name,
"--domain",
domain,
"--platform",
"managed",
"--region",
"us-west1",
)
jobs = json.loads(
sh(
"gcloud",
"scheduler",
"jobs",
"list",
"-q",
"--format=json",
capture_output=True,
)
)
for job in jobs:
name = job["name"].split("/")[-1]
if name.startswith(f"{app}-"):
sh("gcloud", "scheduler", "jobs", "delete", name, "-q")
for job in app.config["tasks"]:
sh(
"gcloud",
"beta",
"scheduler",
"jobs",
"create",
"http",
f"{app}-{job['name']}",
f"--schedule={job['schedule']}",
f"--uri=https://{app}.cs61a.org/jobs/{job['name']}",
"--attempt-deadline=1200s",
"-q",
)
def run_pypi_deploy(app: App, pr_number: int):
sh("python", "-m", "venv", "env")
update_setup_py(app, pr_number)
sh("env/bin/pip", "install", "setuptools")
sh("env/bin/pip", "install", "wheel")
sh("env/bin/python", "setup.py", "sdist", "bdist_wheel")
sh(
"twine",
"upload",
*(f"dist/{file}" for file in os.listdir("dist")),
env=dict(
TWINE_USERNAME="__token__",
TWINE_PASSWORD=get_secret(secret_name="PYPI_PASSWORD"),
),
)
def run_cloud_function_deploy(app: App, pr_number: int):
if pr_number != 0:
return
sh(
"gcloud",
"functions",
"deploy",
app.name,
"--runtime",
"python37",
"--trigger-http",
"--entry-point",
"index",
"--timeout",
"500",
)
def run_static_deploy(app: App, pr_number: int):
bucket = f"gs://{gen_service_name(app.name, pr_number)}.buckets.cs61a.org"
prod_bucket = f"gs://{gen_service_name(app.name, 0)}.buckets.cs61a.org"
try:
sh("gsutil", "mb", "-b", "on", bucket)
except CalledProcessError:
# bucket already exists
pass
sh("gsutil", "-m", "rsync", "-dRc", ".", bucket)
def run_service_deploy(app: App, pr_number: int):
if pr_number != 0:
return # do not deploy PR builds to prod!
for file in os.listdir("."):
sh(
"gcloud",
"compute",
"scp",
"--recurse",
file,
app.config["service"]["host"] + ":" + app.config["service"]["root"],
"--zone",
app.config["service"]["zone"],
)
sh(
"gcloud",
"compute",
"ssh",
app.config["service"]["host"],
"--command=sudo systemctl restart {}".format(app.config["service"]["name"]),
"--zone",
app.config["service"]["zone"],
)
def run_hosted_deploy(app: App, pr_number: int):
image = build_docker_image(app, pr_number)
service_name = gen_service_name(app.name, pr_number)
new(img=image, name=service_name, env=gen_env_variables(app, pr_number))
if pr_number == 0:
for domain in app.config["first_party_domains"]:
add_domain(name=service_name, domain=domain)
def run_noop_deploy(_app: App, _pr_number: int):
pass
<file_sep>/auth/README.md
# 61A Auth
This tool allows applications to access Google Drive and Piazza by wrapping the two APIs in a much simpler OKPy-based interface.
## Quickstart
To start, visit [auth.apps.cs61a.org](https://auth.apps.cs61a.org) and register a client with a unique `client_name`. Keep track of the `secret` returned after you register a client - you can't see it again!
The `secret` lets applications access any Google Document or Sheet that is shared with the service account, as well as private Piazza posts. The service account email address can be seen at [auth.apps.cs61a.org](https://auth.apps.cs61a.org). **IMPORTANT: If the `secret` is compromised, _IMMEDIATELY_ go to [auth.apps.cs61a.org](https://auth.apps.cs61a.org) and recreate the client with a new `secret`**, as anyone with the `secret` can access sensitive information shared with the service account.
## Basic Usage
### Drive
To read a Google Document, ensure that the service account has access to it, either by making the document visible to "anyone with the link" or by sharing it with the service account directly. Then, you can read the Google Document by making a POST request to `auth.apps.cs61a.org/google/read_document` with the document `url` as a JSON-encoded POST parameter, along with the `client_name` and `secret` For example, in Python, you can do
```python
import requests
text = requests.post("https://auth.apps.cs61a.org/google/read_document", json={
"url": "https://docs.google.com/document/d/10xo4ofWCnYbmmNBGDGQqVfpOZVo/edit",
"client_name": "my-client",
"secret": "my-secret"
}).json()
```
The JSON-encoded body of the response will be the plain text content of that document.
To read a Google Sheet (e.g. to use one to configure an application), make an analogous POST request to `https://auth.apps.cs61a.org/google/read_spreadsheet` with the same parameters before, except also include the parameter `sheet_name` to indicate which sheet of the spreadsheet you want to export. For instance, you can do
```python
import requests
data = requests.post("https://auth.apps.cs61a.org/google/read_spreadsheet", json={
"url": "https://docs.google.com/spreadsheets/d/1sUeanmzo_Kj1HaXM2v0/edit",
"sheet_name": "Sheet5",
"client_name": "my-client",
"secret": "my-secret",
}).json()
```
The body of the response will be a `List[List[String]]`, with the outer list containing each row until the last non-empty row, and the inner list containing each cell in its corresponding row until the last non-empty cell. As before, it will be JSON-encoded.
To write a Google spreadsheet, make sure the service account can write to it, and then run
```python
import requests
text = requests.post("https://auth.apps.cs61a.org/google/write_spreadsheet", json={
"url": "https://docs.google.com/document/d/10xo4ofWCnYbmmNBGDGQqVfpOZVo/edit",
"sheet_name",
"content": [["A1", "B1", "C1"], ["A2", "B2", "C2"]],
"client_name": "my-client",
"secret": "my-secret"
}).json()
```
Where `content` is in the safe format as the return value of `read_spreadsheet`. The response should be `{"success" : True}`
### Piazza
To interact with Piazza, make an authorized POST request to `auth.apps.cs61a.org/piazza/<action>`, where `<action>` is the desired action to take. Pass in the boolean JSON-encoded parameter `staff` to determine whether the action should be taken using a service account acting as a student or as a member of staff. Pass in the boolean parameter `test=true` to use the test Piazza - otherwise, the live Piazza will be used.
These actions correspond to methods of the same name on a `Network` object from the `piazza-api` Python package. To pass arguments into this method call, supply them as additional JSON keys in the POST request. The keys `client_name`, `secret`, and `staff` will be removed from the method call. The JSON-encoded method response will be returned.
For example, to list recent posts on Piazza as seen by a student, you can make the request
```python
import requests
recents = requests.post("https://auth.apps.cs61a.org/piazza/get_feed", json={
"limit": 150,
"staff": False,
"client_name": "my-client",
"client_secret": "my-secret",
}).json()
```
## Advanced Usage
To programmatically create a client, make a POST request to `/api/request_key` with an OKPy cookie corresponding to an account with staff access to the okpy course `cal/cs61a/CURR_SEMESTER`. You can generate such a cookie by running `python3 ok --get-token` and storing it in the cookie `dev_token`. For the remainder of this section, all POST requests will require such a cookie to be in place.
To revoke a key corresponding to a particular client, make a POST request to `/api/revoke_key?client_name=<CLIENT_NAME>` with the `client_name` parameter set to the name of the desired client whose key is being revoked.
To revoke all keys that have never been used to handle a request, make a POST request to `/api/revoke_all_unused_keys`. You can also visit this link in the browser directly while signed into OKPy to perform the same action.
To revoke _ALL_ keys that have been issued, even those currently in use, make a POST request to `/api/DANGEROUS_revoke_all_keys`. In production, it should be very rare that this needs to be done - consider revoking individual keys by visiting the website or invoking the `revoke_key` API on individual clients.
## Deployment Instructions
To quickly deploy an update, run `make deploy`. When deploying for the first time, you must first create a MySQL database linked to the app by running `dokku mysql:create auth auth`, before deploying. After deploying, you must visit [auth.apps.cs61a.org/google/config](https://auth.apps.cs61a.org/google/config) and [auth.apps.cs61a.org/piazza/config](https://auth.apps.cs61a.org/piazza/config) and set everything up before the homepage will start working.
## Obtaining a Google Service Account
Go to [console.cloud.google.com](https://console.cloud.google.com), create a project, then go to `IAM & admin -> Service accounts` and create a new account. You do not need to give this account a role, but you must download a file containing a JSON private key and upload it to the 61A Auth service.
## Development Instructions
- Clone the repository and install the dependencies in `src/requirements.txt`.
- Open `src/oauth_client.py` and change the `CONSUMER_KEY` and `SECRET` variables to correspond to a valid okpy OAuth client. Contact the maintainer of this project to obtain these variables.
- Install and set up `mysql`. In `mysql`, run `CREATE DATABASE account_proxy;`.
- Then run `src/app.py`, and the server should start.
<file_sep>/examtool_web_common/js/StaffAlertsList.js
import React from "react";
import { Button, Card } from "react-bootstrap";
export default function StaffAlertsList({ staffData, send }) {
const deleteAnnouncement = (id) => () => send("delete_announcement", { id });
return (
<>
<h3>Public Announcements</h3>
{staffData.announcements.map(
({
base,
id,
offset,
canonical_question_name: questionName,
message,
spoken_message: spokenMessage,
}) => (
<div key={id}>
<Card>
<Card.Header>
Announcement for {questionName || "the overall exam"}{" "}
{offset && `(${base}+${offset})`}
<Button
style={{ float: "right" }}
variant="primary"
onClick={deleteAnnouncement(id)}
size="sm"
>
Delete
</Button>
</Card.Header>
<Card.Body>
{message}
{/* eslint-disable-next-line no-nested-ternary */}
{spokenMessage === "" ? (
<i> [Silent]</i>
) : spokenMessage == null ? null : (
<i> [Audio Override: {spokenMessage}]</i>
)}
</Card.Body>
</Card>
<br />
</div>
)
)}
</>
);
}
<file_sep>/auth/admins_client.py
from flask import redirect, request
from auth_utils import course_oauth_secure, get_name, key_secure, get_email
from common.db import connect_db
from common.rpc.auth import is_admin, list_admins
from common.url_for import url_for
from common.html import error, make_row
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS course_admins (
email varchar(128),
name varchar(128),
course varchar(128),
creator varchar(128)
)"""
)
init_db()
def create_admins_client(app):
def client_data(course):
with connect_db() as db:
ret = db(
"SELECT email, name, course, creator FROM course_admins WHERE course=(%s)",
[course],
).fetchall()
admin_names = [
make_row(
f'{name} (<a href="mailto:{email}">{email}</a>), added by {creator} ',
url_for("remove_admin", course=course, email=email),
)
for email, name, course, creator in ret
]
create_client = f"""
Add new course administrator:
<form action="{url_for("add_admin", course=course)}" method="post">
<input name="email" type="email" placeholder="Email address">
<input type="submit">
</form>
"""
return "<h3>Admins</h3>" + create_client + "<p>".join(admin_names)
app.help_info.add(client_data)
@app.route("/admins/<course>/add_admin", methods=["POST"])
@course_oauth_secure()
def add_admin(course):
email = request.form["email"]
with connect_db() as db:
check = db(
"SELECT * FROM course_admins WHERE email=(%s) AND course=(%s)",
[email, course],
).fetchone()
if check:
return error("User is already an admin"), 409
with connect_db() as db:
db(
"INSERT INTO course_admins VALUES (%s, %s, %s, %s)",
[email, "Unknown", course, get_name()],
)
# make sure that you can't accidentally lock yourself out
with connect_db() as db:
check = db(
"SELECT * FROM course_admins WHERE email=(%s) AND course=(%s)",
[get_email(), course],
).fetchone()
if not check:
db(
"INSERT INTO course_admins VALUES (%s, %s, %s, %s)",
[get_email(), get_name(), course, get_name()],
)
return redirect(url_for("index"))
@app.route("/admins/<course>/remove_admin", methods=["POST"])
@course_oauth_secure()
def remove_admin(course):
email = request.args["email"]
with connect_db() as db:
db(
"DELETE FROM course_admins WHERE email=(%s) AND course=(%s)",
[email, course],
)
return redirect(url_for("index"))
@is_admin.bind(app)
@key_secure
def handle_is_admin(course, email, force_course=None):
if force_course and course != force_course:
raise PermissionError
with connect_db() as db:
return bool(
db(
"SELECT * FROM course_admins WHERE email=(%s) AND course=(%s)",
[email, force_course if force_course else course],
).fetchone()
)
@list_admins.bind(app)
@key_secure
def handle_list_admins(course):
with connect_db() as db:
return [
list(x)
for x in db(
"SELECT email, name FROM course_admins WHERE course=(%s)", [course]
).fetchall()
]
<file_sep>/oh/migrations/versions/e80617a584e0_added_slack_config_options.py
"""added slack config options
Revision ID: e80617a584e0
Revises: <KEY>
Create Date: 2020-04-09 15:03:43.071903
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "e80617a584e0"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="slack_notif_long_queue",
value="false",
public=True,
course=course[0],
)
)
session.add(
ConfigEntry(
key="slack_notif_appt_summary",
value="false",
public=True,
course=course[0],
)
)
session.add(
ConfigEntry(
key="slack_notif_missed_appt",
value="false",
public=True,
course=course[0],
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
<file_sep>/cats/src/TypedWord.js
import React from "react";
import "./TypedWord.css";
export default class TypedWord extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
updated: false,
};
}
componentDidUpdate() {
if (!this.state.updated) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({ updated: true });
}
}
render() {
let className = "TypedWord ";
if (this.state.updated && this.props.incorrect) {
className += "both";
} else if (this.props.incorrect) {
className += "incorrect";
} else if (this.state.updated) {
className += "updated";
}
return <span className={className}>{this.props.word} </span>;
}
}
<file_sep>/common/rpc/sandbox.py
from typing import Optional
from common.rpc.utils import create_service, requires_access_token
service = create_service(__name__, override="sb")
@requires_access_token
@service.route("/api/update_file")
def update_file(
*,
path: str,
encoded_file_contents: Optional[str] = None,
symlink: Optional[str] = None,
delete: bool = False,
):
...
@requires_access_token
@service.route("/api/get_server_hashes")
def get_server_hashes():
...
@requires_access_token
@service.route("/api/run_make_command", streaming=True)
def run_make_command(*, target: str):
...
@requires_access_token
@service.route("/api/is_sandbox_initialized")
def is_sandbox_initialized():
...
@requires_access_token
@service.route("/api/initialize_sandbox")
def initialize_sandbox(*, force=True):
...
<file_sep>/sicp/sicp/autograder.py
import base64
import os
from common.rpc.auth_utils import set_token_path
from common.rpc.ag_master import upload_zip, create_assignment
class Autograder:
def __init__(self, course):
self.course = course
set_token_path(f"{os.path.expanduser('~')}/.sicp_token")
def upload_zip(self, zip_file):
"""
Uploads `filename` zip and returns the download url, overriding any
existing filesOverrides existing
"""
assert zip_file.endswith(".zip"), "Upload Error"
with open(zip_file, "rb") as f:
upload_zip(
course=self.course,
name=zip_file,
file=base64.b64encode(f.read()).decode("ascii"),
)
def create_assignment(
self, assign, script, zip_file, batch_size=100, grading_base="https://okpy.org"
):
return create_assignment(
name=assign,
command=script,
file=zip_file,
batch_size=batch_size,
grading_base=grading_base,
course=self.course,
)
<file_sep>/examtool/examtool/cli/identify_keyword.py
import click
from examtool.api.substitution_finder import find_keyword
from examtool.cli.utils import exam_name_option
@click.command()
@exam_name_option
@click.option(
"--keyword",
prompt=True,
help="The keyword you wish to identify.",
)
def identify_keyword(exam, keyword):
"""
Identify the student from a keyword present in their exam.
"""
find_keyword(exam, keyword)
<file_sep>/domains/main.py
import socket
from enum import Enum
from time import sleep
import requests
from flask import Flask, abort, redirect, request
from common.course_config import format_coursecode, is_admin
from common.db import connect_db
from common.html import html
from common.oauth_client import create_oauth_client, get_user, is_logged_in, login
from common.rpc.buildserver import get_base_hostname
from common.rpc.secrets import get_secret, validates_master_secret
from common.url_for import url_for
from common.rpc.domains import add_domain
APP_LOOKUP = {
"oh": "oh",
"hwparty": "oh",
"joinme": "oh",
"lab": "oh",
"howamidoing": "howamidoing",
"status": "howamidoing",
"seating": "seating",
"links": "shortlinks",
"go": "shortlinks",
"eecs": "shortlinks",
# legacy prefixes
"me100": "oh",
"csenrolltest": "oh",
"cs169-oh": "oh",
"cs188-oh": "oh",
"cs186-oh": "oh",
"stat140-oh": "oh",
}
class Status(Enum):
VALIDATING = "VALIDATING"
DNS_INVALID = "DNS_INVALID"
PROVISIONING = "PROVISIONING"
PROVISIONING_FAILED = "PROVISIONING_FAILED"
UPDATING_OAUTH = "UPDATING_OAUTH"
INTERNAL_ERROR = "INTERNAL_ERROR"
SUCCESS = "SUCCESS"
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
app.debug = True
create_oauth_client(app, "61a-domains")
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS hosted_apps (
domain VARCHAR(128),
course VARCHAR(128),
app VARCHAR(128),
status VARCHAR(128)
)
"""
)
@app.route("/")
def index():
if not is_logged_in():
return login()
return html(
"""
Select course:
<form method="post" action="/view_course">
<input placeholder="cs61a" name="course"> <input type="submit" value="Login">
</form>"""
)
@app.route("/view_course", methods=["POST"])
@app.route("/view_course/<course>", methods=["GET"], endpoint="canonical_view_course")
def view_course(course=None):
if not course:
course = request.form["course"]
return redirect(url_for("canonical_view_course", course=course))
if not is_logged_in():
return login()
email = get_user()["email"]
if not is_admin(email, course):
abort(403)
with connect_db() as db:
apps = db(
"SELECT domain, app, status FROM hosted_apps WHERE course=(%s)", [course]
).fetchall()
return html(
f"""
<h2>Hosted Apps for {format_coursecode(course)}</h2>
{"<p>".join(f"<code>{domain}</code> ({app}) - {status}" for domain, app, status in apps)}
"""
)
def set_status(domain: str, status: Status):
"""Updates the status for a domain name
:param domain: domain name
:type domain: str
:param status: new status of domain
:type status: Status
:return: None
"""
with connect_db() as db:
db(
"UPDATE hosted_apps SET status=(%s) WHERE domain=(%s)",
[status.value, domain],
)
@add_domain.bind(app)
@validates_master_secret
def add_domain(app, is_staging, course, domain):
"""Adds domain to hosted_apps table and hosts new domain
:param app: "auth"
:type app: str
:param is_staging: whether app is staging or not
:type is_staging: boolean
:param course: course name
:type course: str
:param domain: domain name
:type domain: str
:return: None or Error
"""
try:
if app != "auth":
abort(401)
app = APP_LOOKUP[domain.split(".")[0]]
with connect_db() as db:
status = db(
"SELECT status FROM hosted_apps WHERE domain=(%s)", [domain]
).fetchone()
if status is not None and status[0] == Status.SUCCESS:
return "" # domain already provisioned
db("DELETE FROM hosted_apps WHERE domain=(%s)", [domain])
with connect_db() as db:
db(
"INSERT INTO hosted_apps (domain, course, app, status) VALUES (%s, %s, %s, %s)",
[domain, course, app, Status.VALIDATING.value],
)
try:
ip = socket.gethostbyname(domain)
except socket.gaierror:
ip = None
if ip != socket.gethostbyname("proxy.cs61a.org"):
set_status(domain, Status.DNS_INVALID)
return
set_status(domain, Status.PROVISIONING)
try:
requests.post(
"https://proxy.cs61a.org/create_domain",
json=dict(
app=app,
domain=domain,
target=get_base_hostname(target_app=app),
secret=get_secret(secret_name="DOMAIN_WEBHOOK_SECRET"),
),
).raise_for_status()
except requests.exceptions.ConnectionError:
pass # nginx restarts so the connection crashes
sleep(5)
if not requests.get(f"https://{domain}/").ok:
set_status(domain, Status.PROVISIONING_FAILED)
return
set_status(domain, Status.UPDATING_OAUTH)
# TODO
set_status(domain, Status.SUCCESS)
return
except:
set_status(domain, Status.INTERNAL_ERROR)
raise
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/examtool_web_common/js/useStyleWatcher.js
import { useEffect } from "react";
export default function useStyleWatcher(ref, callback, deps) {
useEffect(() => {
if (!ref.current) {
return () => null;
}
const observer = new MutationObserver(callback);
observer.observe(ref.current, {
attributes: true,
attributeFilter: ["style"],
});
return () => observer.disconnect();
}, [ref.current, ...deps]);
}
<file_sep>/oh/scripts/merge.py
import enum
import json
import os
import pickle
import sys
from datetime import datetime
sys.path.append(os.path.abspath("../oh_queue"))
sys.path.append(os.path.abspath(".."))
os.chdir("..")
import models
from oh_queue import app
app.config["SQLALCHEMY_DATABASE_URL"] = os.getenv("DATABASE_URL")
EXPORTING = False
def dump(obj):
fields = {}
for field in [x for x in dir(obj) if not x.startswith("_") and x != "metadata"]:
if field + "_id" in dir(obj):
fields[field] = None
continue
data = obj.__getattribute__(field)
try:
if not isinstance(data, datetime) and not isinstance(data, enum.Enum):
json.dumps(data)
fields[field] = data
except TypeError:
continue
return fields
out = {}
MIGRATED_COURSES = ["cs61a", "cs61c"]
OBJECTS = [
models.User,
models.ConfigEntry,
models.Assignment,
models.Location,
models.Ticket,
models.TicketEvent,
models.Appointment,
models.AppointmentSignup,
models.Group,
models.GroupAttendance,
models.ChatMessage,
]
FIELD_MAP = {"helper": "user"}
if EXPORTING:
with app.app_context():
for cls in OBJECTS:
print(cls, file=sys.stderr)
out[cls.__tablename__] = {}
for obj in cls.query.all():
if obj.course in MIGRATED_COURSES:
continue
out[cls.__tablename__][obj.id] = dump(obj)
with open("scripts/oh2.json", "wb") as f:
pickle.dump(out, f)
if not EXPORTING:
with open("scripts/oh2.json", "rb") as f:
data = pickle.load(f)
with app.app_context():
lookup = {}
cache = {}
live_objects = {}
for cls in OBJECTS:
lookup[cls.__tablename__] = {}
cache[cls.__tablename__] = {}
live_objects[cls.__tablename__] = {obj.id: obj for obj in cls.query.all()}
for obj in data[cls.__tablename__].values():
id = obj.pop("id")
if (
id in live_objects[cls.__tablename__]
and live_objects[cls.__tablename__][id].course == obj["course"]
):
# it's the same object, no need to upload
continue
# need to duplicate
print(id, obj)
obj.pop("get_id", None)
obj.pop("is_authenticated", None)
obj.pop("is_anonymous", None)
obj.pop("is_active", None)
obj.pop("heartbeat_time", None)
obj.pop("short_name", None)
for field in list(obj.keys()):
if "_id" in field:
# lookup ORM object
target_id = obj.pop(field)
obj_field_name = field[:-3]
model_name = FIELD_MAP.get(obj_field_name, obj_field_name)
if target_id in lookup[model_name]:
obj[obj_field_name] = lookup[model_name][target_id]
assert obj["course"] == obj[obj_field_name].course
else:
[target_cls] = (
cls
for cls in OBJECTS
if cls.__tablename__ == model_name
)
if target_id is not None:
obj[obj_field_name] = live_objects[model_name][
target_id
]
assert obj["course"] == obj[obj_field_name].course, (
obj[obj_field_name].course,
obj_field_name,
)
else:
obj[obj_field_name] = None
obj = cls(**obj) # hydrate SQLAlchemy object
models.db.session.add(obj)
lookup[cls.__tablename__][id] = obj
models.db.session.commit()
<file_sep>/howamidoing/server/main.py
import json
import os
import sys
from common.course_config import get_course
from common.db import connect_db, transaction_db
from common.oauth_client import create_oauth_client, get_user, is_logged_in, is_staff
from common.rpc.howamidoing import upload_grades as rpc_upload_grades
from common.rpc.secrets import only
from common.rpc.auth import validate_secret
from setup_functions import set_default_config, set_grades
from flask import Flask, redirect, request, jsonify, render_template, Response
CONSUMER_KEY = "61a-grade-view"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
AUTHORIZED_ROLES = ["staff", "instructor", "grader"]
DEV = os.getenv("ENV") != "prod"
IS_SPHINX = "sphinx" in sys.argv[0]
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS configs (
courseCode varchar(128),
config LONGBLOB)"""
)
db(
"""CREATE TABLE IF NOT EXISTS students (
courseCode varchar(128),
email varchar(128),
shortData varchar(256),
data BLOB)"""
)
db(
"""CREATE TABLE IF NOT EXISTS headers (
courseCode varchar(128),
header BLOB)"""
)
db(
"""CREATE TABLE IF NOT EXISTS lastUpdated (
courseCode varchar(128),
lastUpdated TIMESTAMP)"""
)
if DEV and not IS_SPHINX:
with connect_db() as db:
with open("./public/config/dummy_grade_data.csv") as grades:
set_grades(grades.read(), "cs61a", db)
set_default_config(db)
def last_updated():
"""Finds the timestamp of when the current database was last updated
for this course.
Uses a database query function yielded by :func:`common.db.connect_db`
and the course code returned by :func:`common.course_config.get_course`
:return: Timestamp or ``Unknown`` (string) if any exceptions occur while fetching from the current database
"""
try:
with connect_db() as db:
return db(
"SELECT lastUpdated from lastUpdated where courseCode=%s",
[get_course()],
).fetchone()[0]
except:
return "Unknown"
def create_client(app):
@app.route("/")
def index():
return render_template("index.html", courseCode=get_course())
@app.route("/histogram")
def histogram():
return render_template("index.html", courseCode=get_course())
@app.route("/redirect")
def ohlord():
return redirect("https://howamidoing.cs61a.org")
@app.route("/edit")
def config_editor():
return render_template("index.html", courseCode=get_course())
@app.route("/config/config.js")
def config():
with connect_db() as db:
data = db(
"SELECT config FROM configs WHERE courseCode=%s", [get_course()]
).fetchone()
print(data)
return Response(data, mimetype="application/javascript")
@app.route("/query/")
def query():
try:
if is_logged_in():
user = get_user()
email = user["email"]
target = request.args.get("target", None)
if is_staff(get_course()):
if target:
email = target
else:
all_students = []
with connect_db() as db:
lookup = db(
"SELECT shortData FROM students WHERE courseCode=%s",
[get_course()],
).fetchall()
for row in lookup:
parsed = json.loads(row[0])
all_students.append(parsed)
return jsonify(
{
"success": True,
"isStaff": True,
"allStudents": all_students,
"email": user["email"],
"name": user["name"],
"lastUpdated": last_updated(),
}
)
with connect_db() as db:
[short_data, data] = db(
"SELECT shortData, data FROM students WHERE courseCode=%s AND email=%s",
[get_course(), email],
).fetchone()
[header] = db(
"SELECT header FROM headers WHERE courseCode=%s", [get_course()]
).fetchone()
short_data = json.loads(short_data)
data = json.loads(data)
header = json.loads(header)
return jsonify(
{
"success": True,
"header": header,
"data": data,
"email": short_data["Email"],
"name": short_data["Name"],
"SID": short_data["SID"],
"lastUpdated": last_updated(),
}
)
else:
return jsonify({"success": False, "retry": True})
except Exception:
pass
return jsonify({"success": False, "retry": False})
@app.route("/allScores", methods=["POST"])
def all_scores():
if not is_staff(get_course()):
return jsonify({"success": False})
with connect_db() as db:
[header] = db(
"SELECT header FROM headers WHERE courseCode=%s", [get_course()]
).fetchone()
header = json.loads(header)
data = db(
"SELECT data FROM students WHERE courseCode=%s", get_course()
).fetchall()
scores = []
for [score] in data:
score = json.loads(score)
scores.append(score)
return jsonify({"header": header, "scores": scores})
@app.route("/setConfig", methods=["POST"])
def set_config():
if not is_staff(get_course()):
return jsonify({"success": False})
data = request.form.get("data")
with connect_db() as db:
db("DELETE FROM configs WHERE courseCode=%s", [get_course()])
db("INSERT INTO configs VALUES (%s, %s)", [get_course(), data])
return jsonify({"success": True})
@app.route("/setGrades", methods=["POST"])
def set_grades_route():
if not is_staff(get_course()):
return jsonify({"success": False})
data = request.form.get("data")
with transaction_db() as db:
set_grades(data, get_course(), db)
return jsonify({"success": True})
@app.route("/setGradesSecret", methods=["POST"])
def set_grades_secret_route():
if validate_secret(secret=request.form.get("secret")) != "cs61a":
return jsonify({"success": False})
data = request.form.get("data")
with transaction_db() as db:
set_grades(data, get_course(), db)
return jsonify({"success": True})
@rpc_upload_grades.bind(app)
@only("grade-display", allow_staging=True)
def upload_grades(data: str):
with transaction_db() as db:
set_grades(data, get_course(), db)
def print_to_stderr(print_function):
"""Writes to sys.stderr using the desired print function.
:param print_function: a print function
:return: a function that writes the input to sys.stderr using the desired print function
"""
def print(*s):
print_function(*s, file=sys.stderr)
return print
print = print_to_stderr(print)
app = Flask(
__name__, static_url_path="", static_folder="static", template_folder="static"
)
if __name__ == "__main__":
app.debug = True
create_client(app)
create_oauth_client(app, CONSUMER_KEY)
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8000, debug=True)
<file_sep>/domains/register_new_domain.py
import hmac
import os
import subprocess
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.getenv("SECRET")
# note: this can't be made a dependency, because pr_proxy does not use the standard build system
def sh(*args):
subprocess.run(args).check_returncode()
@app.route("/create_domain", methods=["POST"])
def create_domain():
secret = request.json["secret"]
if not hmac.compare_digest(secret, SECRET):
abort(403)
domain = request.json["domain"]
target = request.json["target"]
conf = f"{domain}_autoconf.conf"
existing_domains = os.listdir("/etc/nginx/conf.d")
for existing_domain in existing_domains:
if existing_domain == conf:
return ""
if not os.path.isfile(f"etc/letsencrypt/live/{domain}/fullchain.pem"):
sh("certbot", "certonly", "--nginx", "-d", domain, "--non-interactive")
# will kill the request here, so a restart is required
with open(f"/etc/nginx/conf.d/{conf}", "w+") as f:
f.write(
f"""
server {{
listen 443 ssl;
server_name {domain};
ssl_certificate /etc/letsencrypt/live/{domain}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/{domain}/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
location / {{
proxy_pass https://{target}/;
proxy_set_header Host {target};
proxy_set_header X-Forwarded-For-Host {domain};
proxy_read_timeout 1800;
proxy_connect_timeout 1800;
proxy_send_timeout 1800;
send_timeout 1800;
}}
}}"""
)
sh("systemctl", "restart", "nginx")
return ""
<file_sep>/sections/src/AttendanceRow.js
// @flow strict
import React from "react";
import Button from "react-bootstrap/Button";
import { AttendanceStatus } from "./models";
import type { AttendanceStatusType } from "./models";
type Props = {
editable: boolean,
status: ?AttendanceStatusType,
onClick?: (AttendanceStatusType) => void,
};
const buttonColorMap = {
present: "success",
excused: "warning",
absent: "danger",
};
export default function AttendanceRow({ editable, status, onClick }: Props) {
return (
<>
{Object.entries(AttendanceStatus).map(([statusOption, text]) => (
<span key={statusOption}>
<Button
size="sm"
variant={
status === statusOption
? buttonColorMap[statusOption]
: `outline-${buttonColorMap[statusOption]}`
}
disabled={!editable && status !== statusOption}
onClick={() =>
onClick && onClick(((statusOption: any): AttendanceStatusType))
}
>
{text}
</Button>{" "}
</span>
))}
</>
);
}
<file_sep>/common/rpc/buildserver.py
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/clear_queue")
def clear_queue(*, repo: str, pr_number: int):
...
@requires_master_secret
@service.route("/api/trigger_build")
def trigger_build_sync(*, pr_number: int, target_app: str = None):
...
@requires_master_secret
@service.route("/api/deploy_prod_app_sync")
def deploy_prod_app_sync(*, target_app: str):
...
@requires_master_secret
@service.route("/api/get_base_hostname")
def get_base_hostname(*, target_app: str) -> str:
...
<file_sep>/.githooks/pre-commit
#!/bin/sh
JS_FILES=$(git diff --cached --name-only --diff-filter=ACMR "*.js" "*.jsx" | sed 's| |\\ |g')
PY_FILES=$(git diff --cached --name-only --diff-filter=ACMR "*.py" | sed 's| |\\ |g')
[ -z "$JS_FILES" ] && [ -z "$PY_FILES" ] && echo "No files to reformat." && exit 0
prettier()
{
echo "Running Prettier..."
# Prettify all selected files
echo "$JS_FILES" | xargs prettier --write
# Add back the modified/prettified files to staging
echo "$JS_FILES" | xargs git add
}
[ ! -z "$JS_FILES" ] && prettier
black()
{
echo "Running Black..."
# Black all selected files
echo "$PY_FILES" | xargs python3 -m black
# Add back the modified/blacked files to staging
echo "$PY_FILES" | xargs git add
}
[ ! -z "$PY_FILES" ] && black
exit 0
<file_sep>/hog/src/Commentary.js
import React from "react";
import Alert from "react-bootstrap/Alert";
export default function Commentary({ messages }: { messages: [string] }) {
if (messages) {
return messages.map((message, i) => {
return (
<Alert key={i} variant="dark">
{message}
</Alert>
);
});
}
return null;
}
<file_sep>/docs/license.rst
License
=======================================================
``cs61a-apps`` is licensed under the MIT License.
.. include:: ../LICENSE
:literal:<file_sep>/indexer/requirements.txt
Flask
gunicorn
beautifulsoup4
PyPdf2
-r common/requirements.txt
<file_sep>/piazzaoncall/main.py
from flask import Flask
from common.jobs import job
# from piazza_oc import Main
from ed_oc import Main
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
@job(app, "ping_unread")
def run():
Main().run()
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/examtool/examtool/api/watermarks.py
from __future__ import annotations
import random
from dataclasses import dataclass
from examtool.api.utils import as_list
from examtool.gui_files.svg import SVGGraphic
@dataclass(frozen=True)
class Point:
x: int
y: int
def __iter__(self):
yield self.x
yield self.y
def dist(self, other: Point):
return (self.x - other.x) ** 2 + (self.y - other.y) ** 2
@as_list
def get_watermark_points(seed):
old_seed = int(random.random() * 100000)
random.seed(seed)
for _ in range(20):
yield Point(random.randrange(100), random.randrange(100))
random.seed(old_seed)
def create_watermark(seed, *, brightness, scale=2):
graphic = SVGGraphic(100 * scale, 100 * scale)
color = f"rgb({255 - brightness}, {255 - brightness / 2}, 0)"
graphic.draw_line(0, 0, 10, 10, color)
graphic.draw_line(0, 10, 10, 0, color)
for x, y in get_watermark_points(seed):
graphic.draw_rect(x * scale, y * scale, scale, scale, color, color)
return str(graphic)
<file_sep>/sicp/sicp/send.py
from base64 import b64encode
from os.path import basename
from typing import List
import click
from click import Path
from common.rpc.mail import send_email
@click.command()
@click.option(
"--sender",
default="CS 61A Mailtool",
help="The sender display name",
)
@click.option(
"--sender-user",
default="cs61a",
help="The sender username",
)
@click.option(
"--sender-domain",
default="berkeley.edu",
help="The sender domain",
)
@click.option(
"--target",
help="The destination email address e.g. <EMAIL>",
prompt=True,
)
@click.option("--subject", help="The subject line of the message", prompt=True)
@click.option("--body", help="The contents of the message", prompt=True)
@click.option(
"--attachment",
"attachments",
type=Path(exists=True, dir_okay=False),
multiple=True,
help="Files to attach to the email",
)
def send(
sender: str,
sender_user: str,
sender_domain: str,
target: str,
subject: str,
body: str,
attachments: List[str],
):
"""
Send emails from eecs.berkeley.edu routed through a university mailserver.
"""
loaded_attachments = {}
for attachment in attachments:
with open(attachment, "rb") as f:
loaded_attachments[basename(attachment)] = b64encode(f.read()).decode(
"ascii"
)
assert sender_domain.endswith("berkeley.edu")
send_email(
sender=f"{sender} <{sender_user}@{sender_domain}>",
target=target,
subject=subject,
body=body,
attachments=loaded_attachments,
_impersonate="mail",
)
<file_sep>/auth/auth_utils.py
from functools import wraps
from flask import session, request, redirect, abort
from common.db import connect_db
from common.oauth_client import get_user
from common.url_for import url_for
AUTHORIZED_ROLES = ["staff", "instructor", "grader"]
def is_staff(course):
try:
token = session.get("access_token") or request.cookies.get("access_token")
if not token:
return False
email = get_user()["email"]
with connect_db() as db:
if course:
admins = db(
"SELECT email FROM course_admins WHERE course=(%s)", [course]
).fetchall()
admins = set(x[0] for x in admins)
if admins:
if email in admins:
db(
"UPDATE course_admins SET name=(%s) WHERE email=(%s)",
[get_name(), email],
)
return True
else:
return False
# otherwise, let anyone on staff access
with connect_db() as db:
if course is not None:
[endpoint] = db(
"SELECT endpoint FROM courses WHERE course=(%s)", [course]
).fetchone()
else:
endpoint = None
for participation in get_user()["participations"]:
if participation["role"] not in AUTHORIZED_ROLES:
continue
if participation["course"]["offering"] != endpoint and endpoint is not None:
continue
return True
return False
except Exception as e:
# fail safe!
print(e)
return False
def get_name():
return get_user()["name"]
def get_email():
return get_user()["email"]
def admin_oauth_secure(app):
def decorator(route):
@wraps(route)
def wrapped(*args, **kwargs):
assert "course" not in kwargs
if not is_staff(MASTER_COURSE):
return redirect(url_for("login"))
return route(*args, **kwargs)
return wrapped
return decorator
def course_oauth_secure():
def decorator(route):
@wraps(route)
def wrapped(*args, **kwargs):
if not is_staff(kwargs["course"]):
return redirect(url_for("login"))
return route(*args, **kwargs)
return wrapped
return decorator
def oauth_secure():
def decorator(route):
@wraps(route)
def wrapped(*args, **kwargs):
if not is_staff(None):
return redirect(url_for("login"))
return route(*args, **kwargs)
return wrapped
return decorator
def key_secure(route):
@wraps(route)
def wrapped(**kwargs):
kwargs.pop("client_name", None) # legacy argument
secret = kwargs.pop("secret")
with connect_db() as db:
ret_regular = db(
"SELECT client_name, course FROM auth_keys WHERE auth_key = (%s)",
[secret],
).fetchone()
ret_super = db(
"SELECT client_name FROM super_auth_keys WHERE auth_key = (%s)",
[secret],
).fetchone()
if ret_regular:
client_name = ret_regular[0]
course = ret_regular[1]
db(
"UPDATE auth_keys SET unused = FALSE WHERE client_name=(%s)",
[client_name],
)
# the course might still be passed in, but should be ignored
kwargs.pop("course", None)
elif ret_super:
client_name = ret_super[0]
db(
"UPDATE super_auth_keys SET unused = FALSE WHERE client_name=(%s)",
[client_name],
)
course = kwargs.pop("course")
else:
abort(401)
return route(**kwargs, course=course)
return wrapped
MASTER_COURSE = "cs61a"
<file_sep>/code/src/languages/lark/utils/run.js
import { LARK } from "../../../common/languages";
import { send } from "../../../renderer/utils/communication.js";
import { RUN_LARK_CODE } from "../constants/communicationEnums.js";
// eslint-disable-next-line import/prefer-default-export
export function runLarkCode(code, onOutput, onErr, onHalt) {
return send(
{ handler: LARK, type: RUN_LARK_CODE, code },
onOutput,
onErr,
onHalt
);
}
<file_sep>/examtool/examtool/api/auth.py
../../../common/rpc/auth_utils.py<file_sep>/hog/src/StrategyPicker.js
// @flow
import React, { useState } from "react";
import FormControl from "react-bootstrap/FormControl";
import InputGroup from "react-bootstrap/InputGroup";
import styled from "styled-components";
const StyledDiv = styled.div`
margin-top: 15px;
`;
type Props = { strategy: ?string, onStrategyChange: (?string) => mixed };
export default function StrategyPicker({ strategy, onStrategyChange }: Props) {
const defaultString = "Pick a strategy";
const displayStrategy = strategy || defaultString;
const [selected, setSelected] = useState(displayStrategy);
const handleClick = (e) => {
if (e.target.checked) {
onStrategyChange(selected);
} else {
onStrategyChange(null);
}
};
const handleSelect = (e) => {
setSelected(e.target.value);
onStrategyChange(e.target.value);
};
return (
<StyledDiv>
<h5>Play against the computer:</h5>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<InputGroup.Checkbox
aria-label="Checkbox for following text input"
checked={!!strategy}
onChange={handleClick}
/>
</InputGroup.Prepend>
<FormControl as="select" onChange={handleSelect} value={selected}>
<option disabled hidden>
{defaultString}
</option>
<option>piggypoints_strategy</option>
<option>more_boar_strategy</option>
<option>final_strategy</option>
</FormControl>
</InputGroup>
</StyledDiv>
);
}
<file_sep>/common/rpc/secrets.py
from functools import wraps
from os import getenv
from flask import abort
from common.rpc.utils import cached, create_service, requires_master_secret
service = create_service(__name__)
def get_secret(*, secret_name):
return getenv(secret_name) or get_secret_from_server(secret_name=secret_name)
@cached()
@requires_master_secret
@service.route("/api/get_secret")
def get_secret_from_server(*, secret_name):
...
@requires_master_secret
@service.route("/api/load_all_secrets")
def load_all_secrets(*, created_app_name):
...
def validates_master_secret(func):
@wraps(func)
def wrapped(*, master_secret, **kwargs):
app, is_staging = validate_master_secret(master_secret=master_secret)
return func(app=app, is_staging=is_staging, **kwargs)
return wrapped
def only(allowed_app, *, allow_staging=True):
def decorator(func):
@wraps(func)
def wrapped(*, master_secret, **kwargs):
app, is_staging = validate_master_secret(master_secret=master_secret)
allowed_apps = (
[allowed_app] if isinstance(allowed_app, str) else allowed_app
)
if app not in allowed_apps:
abort(403)
if is_staging and not allow_staging:
abort(403)
return func(**kwargs)
return wrapped
return decorator
@cached()
@service.route("/api/validate_master_secret")
def validate_master_secret(*, master_secret):
...
@requires_master_secret
@service.route("/api/create_master_secret")
def create_master_secret(*, created_app_name):
...
<file_sep>/oh/oh_queue/static/js/components/request_form.js
function RequestForm(props) {
let state = props.state;
const forceTicket = props.forceTicket;
const appointments =
JSON.parse(state.config.appointments_open) &&
state.config.recommend_appointments;
let party_enabled = state.config.party_enabled && !forceTicket;
const is_queue_open =
JSON.parse(state.config.is_queue_open) &&
(!party_enabled || state.config.allow_private_party_tickets);
const disabled = !party_enabled && !is_queue_open;
let descriptionRequired = state.config.description_required === "true";
let submit = (e) => {
e.preventDefault();
let form = $("#request-form");
let descriptionBox = $("#description-box");
let descriptionDOM = descriptionBox[0];
if (descriptionDOM.reportValidity && !descriptionDOM.reportValidity()) {
return;
}
let formData = {};
form.serializeArray().forEach((input) => {
formData[input.name] = input.value;
});
formData["description"] = descriptionBox.val();
app.makeRequest(party_enabled ? "create_group" : "create", formData, true);
$("#description-overlay").hide();
};
let show = (e) => {
e.preventDefault();
let form = $("#request-form");
let formDOM = form[0];
if (formDOM.reportValidity && !formDOM.reportValidity()) {
return;
}
if (!descriptionRequired || party_enabled) {
return submit(e);
}
let descriptionBox = $("#description-box");
descriptionBox.prop("required", true);
$("#description-overlay").show();
};
const history = ReactRouterDOM.useHistory();
const openAlternative = () => {
if (is_queue_open && party_enabled) {
history.push("/queue");
} else {
history.push("/appointments");
}
};
let { assignments, locations } = state;
let filteredAssignments = Object.values(assignments)
.filter((assignment) => assignment.visible)
.sort((a, b) => a.name.localeCompare(b.name));
let filteredLocations = Object.values(locations)
.filter((location) => location.visible)
.sort((a, b) => a.name.localeCompare(b.name));
let magicWordInput = false;
if (
state.config &&
!party_enabled &&
state.config.queue_magic_word_mode &&
state.config.queue_magic_word_mode !== "none"
) {
magicWordInput = (
<div className="form-group form-group-lg">
<div className="input-group">
<input
className="form-control"
type="password"
id="magic-word"
name="magic_word"
title="Magic Word"
placeholder="Magic Word"
required
disabled={disabled}
/>
</div>
</div>
);
}
const [locationID, setLocationID] = React.useState(null);
const handleLocationChange = (e) => {
setLocationID(e.target.value);
};
const showOnlineInput = locationID && state.locations[locationID].online;
const linkKnown = locationID && state.locations[locationID].link;
return (
<div>
<form id="request-form">
{magicWordInput}
{(!disabled || !appointments) && (
<React.Fragment>
<div className="form-group form-group-lg">
<div className="input-group">
<SelectPicker
options={filteredAssignments}
className="selectpicker form-control form-left"
data-live-search="true"
data-size="8"
data-width="60%"
data-style="btn-lg btn-default"
id="assignment_id"
name="assignment_id"
title="Assignment"
required
disabled={disabled && !appointments}
/>
<input
className="form-control form-right"
type="text"
id="question"
name="question"
title="Question"
placeholder="Question"
required
disabled={disabled && !appointments}
/>
</div>
</div>
{showOnlineInput && (
<React.Fragment>
{(party_enabled ||
state.locations[locationID].name !== "Online" ||
JSON.parse(state.config.students_set_online_link)) && (
<div className="form-group form-group-lg">
<label htmlFor="call-link">
{linkKnown
? "Breakout Room (optional)"
: "Video Call Link"}
</label>
<input
className="form-control"
type="text"
id="call-link"
name="call-link"
title="Video Call Link"
placeholder={
linkKnown ? "Breakout Room 6" : "meet.google.com/xyz"
}
required={!linkKnown}
disabled={disabled && !appointments}
/>
</div>
)}
{(party_enabled ||
JSON.parse(state.config.students_set_online_doc)) && (
<div className="form-group form-group-lg">
<label htmlFor="doc-link">
Shared Document Link (optional)
</label>
<input
className="form-control"
type="text"
id="doc-link"
name="doc-link"
title="Shared Doc Link"
placeholder="docs.google.com/xyz"
disabled={disabled && !appointments}
/>
</div>
)}
</React.Fragment>
)}
<div className="form-group form-group-lg">
<div className="input-group">
<SelectPicker
options={filteredLocations}
className="selectpicker form-control form-left"
data-live-search="true"
data-size="8"
data-width="60%"
data-style="btn-lg btn-default"
id="location_id"
name="location_id"
title="Location"
required
onChange={handleLocationChange}
disabled={disabled}
/>
<div className="input-group-btn form-right pull-left">
<button
className="btn btn-lg btn-default"
onClick={show}
disabled={disabled}
>
{party_enabled ? "Create" : "Request"}
</button>
</div>
</div>
</div>
</React.Fragment>
)}
{((party_enabled && (appointments || is_queue_open)) ||
(appointments && (!forceTicket || is_queue_open))) && (
<div className="form-group form-group-lg">
<button
className="btn btn-lg btn-default"
onClick={openAlternative}
>
{party_enabled && is_queue_open
? "Or ask staff privately"
: disabled
? "Schedule Appointment"
: "Or make an appointment"}
</button>
</div>
)}
</form>
<div id="description-overlay" className="description-overlay">
<div id="description-form" className="description-form">
<div>
<h4> Please describe your issue below: </h4>
<textarea
id="description-box"
className="description-box"
rows="5"
defaultValue={state.config.default_description}
placeholder={
state.config.default_description ||
'It would be helpful if you could describe your issue. For example, "I have a SyntaxError in my ___ function. I've tried using ____ and ____."'
}
/>
<button
className="btn btn-lg btn-default"
onClick={submit}
disabled={disabled}
>
Request
</button>
</div>
</div>
</div>
</div>
);
}
<file_sep>/logs/Dockerfile
FROM python:3.8-buster
RUN curl https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz > /tmp/google-cloud-sdk.tar.gz
RUN mkdir -p /usr/local/gcloud \
&& tar -C /usr/local/gcloud -xvf /tmp/google-cloud-sdk.tar.gz \
&& /usr/local/gcloud/google-cloud-sdk/install.sh -q
ENV PATH $PATH:/usr/local/gcloud/google-cloud-sdk/bin
RUN gcloud components install beta
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
RUN pip install -r requirements.txt
CMD gunicorn -b :$PORT -w 4 main:app -t 3000
<file_sep>/buildtool/buildtool/preview_execution.py
from typing import Callable, Union
from cache import make_cache_fetcher
from context import Env, MemorizeContext
from fs_utils import hash_file
from monitoring import log
from state import BuildState, Rule
from utils import CacheMiss, MissingDependency
from common.hash_utils import HashState
class PreviewContext(MemorizeContext):
def __init__(
self,
repo_root: str,
cwd: str,
hashstate: HashState,
dep_fetcher: Callable[[str], str],
cache_fetcher: Callable[[str, str], str],
):
super().__init__(repo_root, cwd, hashstate)
self.dep_fetcher = dep_fetcher
self.cache_fetcher = cache_fetcher
def input(self, *, file: str = None, sh: str = None, env: Env = None):
state = self.hashstate.state()
super().input(file=file, sh=sh, env=env)
if file is not None:
return self.dep_fetcher(self.absolute(file))
else:
return self.cache_fetcher(state, HashState().record(sh, env).state())
def make_dep_fetcher(build_state: BuildState):
def dep_fetcher(input_path, *, get_hash=False) -> Union[str, bytes]:
try:
if input_path not in build_state.source_files:
rule = build_state.target_rule_lookup.lookup(build_state, input_path)
# this input may be stale / unbuilt
# if so, do not read it, but instead throw MissingDependency
if rule not in build_state.ready:
raise MissingDependency(input_path)
# so it's already ready for use!
if get_hash:
return hash_file(input_path)
else:
with open(input_path) as f:
return f.read()
except FileNotFoundError:
raise MissingDependency(input_path)
return dep_fetcher
def get_deps(build_state: BuildState, rule: Rule):
"""
Use static dependencies and caches to try and identify as *many*
needed dependencies as possible, without *any* spurious dependencies.
"""
hashstate = HashState()
cache_fetcher, _ = make_cache_fetcher(build_state.cache_directory)
dep_fetcher = make_dep_fetcher(build_state)
ctx = PreviewContext(
build_state.repo_root,
rule.location,
hashstate,
dep_fetcher,
cache_fetcher,
)
log(f"Looking for static dependencies of {rule}")
for dep in rule.deps:
if dep not in build_state.source_files:
dep_rule = build_state.target_rule_lookup.lookup(build_state, dep)
if dep_rule not in build_state.ready:
log(
f"Static dependency {dep} of {dep_rule} is not ready, skipping impl"
)
# static deps are not yet ready
break
ctx.deps[dep] = dep_rule.provided_value
if dep.startswith(":"):
setattr(ctx.deps, dep[1:], dep_rule.provided_value)
continue
hashstate.update(dep.encode("utf-8"))
try:
hashstate.update(dep_fetcher(dep, get_hash=True))
except MissingDependency:
# get static deps before running the impl!
# this means that a source file is *missing*, but the error will be thrown in enqueue_deps
break
else:
ok = False
try:
log(f"Running impl of {rule} to discover dynamic dependencies")
rule.provided_value = rule.impl(ctx)
log(f"Impl of {rule} completed with discovered deps: {ctx.inputs}")
for out in rule.outputs:
# needed so that if we ask for another output, we don't panic if it's not in the cache
hashstate.record(out)
ok = True
except CacheMiss:
log(f"Cache miss while running impl of {rule}")
pass # stops context execution
except MissingDependency as e:
log(f"Dependencies {e.paths} were unavailable while running impl of {rule}")
pass # dep already added to ctx.inputs
except Exception as e:
print(
"Error occurred during PreviewExecution. This may be normal, if a cached file that has not "
"yet been reported / processed has been changed. However, it may also be an internal error, so "
"it is being logged here. If it is an internal error, please contact the maintainer."
)
print(repr(e))
# if `ok`, hash loaded dynamic dependencies
if ok:
log(
f"Runtime dependencies resolved for {rule}, now checking dynamic dependencies"
)
for input_path in ctx.inputs:
if input_path.startswith(":"):
input_dep = build_state.target_rule_lookup.try_lookup(input_path)
if input_dep is None or input_dep not in build_state.ready:
ok = False
log(f"Dynamic rule dependency {input_path} is not yet ready")
break
else:
hashstate.update(input_path.encode("utf-8"))
try:
data = dep_fetcher(input_path, get_hash=True)
except MissingDependency as e:
# this dependency was not needed for deps calculation
# but is not verified to be up-to-date
ok = False
log(
f"Dynamic dependencies {e.paths} were not needed for the impl, but are not up to date"
)
break
else:
hashstate.update(data)
return (
hashstate.state() if ok else None,
ctx.inputs + rule.deps,
ctx.uses_dynamic_inputs,
)
return None, rule.deps, None
<file_sep>/buildtool/buildtool/monitoring.py
from dataclasses import dataclass
from sys import stderr
from threading import Lock
from typing import Callable, Protocol
from tqdm import tqdm
def enable_logging():
log.enabled = True
def enable_profiling():
log.profile = True
def log(*args):
if log.enabled:
print(*args, file=stderr)
elif args[0].startswith("RUNNING") and log.profile:
print(*args, file=stderr)
log.enabled = False
log.profile = False
class MoveCallable(Protocol):
def __call__(self, *, curr: int = None, total: int = None) -> None:
...
@dataclass
class StatusMonitor:
update: Callable[[int, str], None]
move: MoveCallable
stop: Callable[[], None]
def create_status_monitor(num_threads: int, quiet: bool):
status = ["IDLE"] * num_threads
bar = tqdm(total=0, disable=quiet)
lock = Lock()
pos = 0
tot = 0
def update(index: int, msg: str):
status[index] = msg
# with lock:
# bar.set_description(", ".join(status))
def move(*, curr: int = None, total: int = None):
nonlocal pos, tot
with lock:
if curr is not None:
pos += curr
bar.update(curr)
if total is not None:
tot += total
bar.total = tot
bar.refresh()
bar.set_description(str((pos, tot)))
def stop():
bar.close()
return StatusMonitor(update, move, stop)
<file_sep>/slack/promotions.py
def make_promo_block(message):
quoted_message = "\n".join(">" + x for x in message.split("\n"))
return [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Your message includes content that I can improve! It could look like: \n{}\nDo you want to activate this bot for your posts on this Slack workspace?".format(
quoted_message
),
},
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "Yes, activate the bot!"},
"style": "primary",
"value": "activate",
"url": "https://slack.apps.cs61a.org",
},
{
"type": "button",
"text": {"type": "plain_text", "text": "Maybe later..."},
"value": "maybe_later",
},
{
"type": "button",
"text": {"type": "plain_text", "text": "No, never ask me again."},
"style": "danger",
"value": "never_ask_again",
"confirm": {
"title": {"type": "plain_text", "text": "Are you sure?"},
"text": {
"type": "mrkdwn",
"text": "Imagine how good your posts could look!",
},
"confirm": {"type": "plain_text", "text": "Do it."},
"deny": {
"type": "plain_text",
"text": "Stop, I've changed my mind!",
},
},
},
],
},
]
<file_sep>/common/rpc/indexer.py
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/index_piazza")
def index_piazza():
...
@requires_master_secret
@service.route("/api/clear_resources")
def clear_resources():
...
@requires_master_secret
@service.route("/api/upload_resources")
def upload_resources():
...
<file_sep>/hog-calc/process_input.py
import base64
import hashlib
import json
from werkzeug.exceptions import abort
from common.db import connect_db
from runner import GOAL_SCORE, MAX_ROLLS
def validate_strat(received_strat):
"""This function validates that the strategy inputted gives out a number of
rolls for each pair of score values that is within the acceptable range of
rolls. It then returns the strategy.
:param received_strat: the strategy that was submitted by a student
:type received_strat: dict
:return: list of lists with the strategy's number of rolls for given scores
"""
extracted_strat = []
for i in range(GOAL_SCORE):
extracted_strat.append([])
for j in range(GOAL_SCORE):
try:
val = int(received_strat[i][j])
except ValueError:
abort(
400,
"Your strategy returns for inputs ({}, {}), which is not an integer.".format(
i, j, received_strat[i][j]
),
)
return
if not (0 <= val <= MAX_ROLLS):
abort(
400,
"Your strategy rolls {} dice for inputs ({}, {}), which is not a valid roll.".format(
i, j, val
),
)
extracted_strat[-1].append(val)
return extracted_strat
def record_strat(name, group, received_strat):
"""This function takes in a submitted strategy and validates it, then
encodes it in JSON format along with the name, a hash of the strategy, and
the email of one of the users in the group, and stores it on the CS61A
database.
:param name: the name of the strategy provided
:type name: str
:param group: the group of students submitting the strategy
:type group: list
:param received_strat: the strategy that was submitted, which will be
evaluated and stored on the database
:type received_strat: dict
:return: the hash of the received strategy
"""
if not isinstance(name, str):
abort(400, "Name is not a string!")
name = base64.encodebytes(bytes(name, "utf-8"))
if len(name) >= 1024:
abort(400, "Strategy name is too long!")
name = name.decode("utf-8")
extracted_strat = validate_strat(received_strat)
# extracted_strat probably OK
email = group[0]
encoded_strat = json.dumps(extracted_strat)
hashed = hashlib.md5(bytes(encoded_strat, "utf-8")).hexdigest()
# time to load it into the database
with connect_db() as db:
dupes = db(
"SELECT email FROM cached_strategies WHERE name = (%s)", [name]
).fetchall()
for dupe in dupes:
if dupe["email"] not in group:
abort(
409,
"Another strategy has already been submitted with the same name.",
)
for member in group:
db("DELETE FROM cached_strategies WHERE email=(%s)", [member])
db(
"INSERT INTO cached_strategies VALUES (%s, %s, %s, %s)",
[email, name, hashed, encoded_strat],
)
return hashed
<file_sep>/oh/migrations/versions/a870d3c6be98_add_config_entry_for_individual_party_.py
"""Add config entry for individual party tickets
Revision ID: a870d3c6be98
Revises: e96dc20c344a
Create Date: 2020-08-28 05:14:38.022254
"""
from sqlalchemy import orm
# revision identifiers, used by Alembic.
revision = "a870d3c6be98"
down_revision = "e96dc20c344a"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="allow_private_party_tickets",
value="true",
public=True,
course=course[0],
)
)
session.commit()
def downgrade():
pass
<file_sep>/oh/oh_queue/static/js/components/admin_tabs.js
function AdminTabs({ currentTab, partyAlias }) {
if (currentTab === "admin") {
currentTab = "general";
}
const links = [
"general",
"tickets",
"party",
"appointments",
"assignments",
"locations",
"online",
"slack",
];
const body = links.map((link, index) => (
<li role="presentation" className={currentTab === link ? "active" : ""}>
<Link to={index ? "/admin/" + link : "/admin"}>
{link === "party" ? partyAlias : link[0].toUpperCase() + link.slice(1)}
</Link>
</li>
));
return <ul className="nav nav-tabs">{body}</ul>;
}
<file_sep>/sections/src/Messages.js
/* eslint-disable react/no-array-index-key */
// @flow strict
import * as React from "react";
import Alert from "react-bootstrap/Alert";
type Props = {
messages: Array<string>,
onChange: (Array<string>) => void,
};
export default function Messages({ messages, onChange }: Props) {
const hideMessage = (i) =>
onChange(messages.slice(0, i).concat(messages.slice(i + 1)));
return (
<>
{messages.map((message, i) => (
<Alert
variant="danger"
onClose={() => hideMessage(i)}
dismissible
key={i}
>
{message}
</Alert>
))}
</>
);
}
<file_sep>/oh/oh_queue/static/js/components/magic_word_display.js
class MagicWordDisplay extends React.Component {
constructor(...args) {
super(...args);
this.state = {
loaded: false,
oldMagicWord: undefined,
magicWord: undefined,
refreshInterval: null,
};
this.loadState = this.loadState.bind(this);
this.loadState();
}
loadState() {
if (this.state.loaded) return;
var config = this.props.state.config;
if (!this.props.state.loaded || !config) {
setTimeout(this.loadState, 100);
return;
}
if (isStaff(this.props.state) && config.queue_magic_word_mode !== "none") {
if (this.state.refreshInterval) {
clearInterval(this.state.refreshInterval);
this.state.refreshInterval = null;
}
this.setState({
refreshInterval: setInterval(() => {
let mode = this.props.state.config.queue_magic_word_mode;
if (
mode !== "timed_numeric" &&
(mode !== "none" || this.state.magicWord !== undefined)
)
return;
app.makeRequest("refresh_magic_word", (res) => {
let magicWord = res.magic_word || null;
this.setState({
oldMagicWord: this.state.magicWord,
magicWord: magicWord,
});
});
}, 10000),
});
}
this.setState({
loaded: true,
});
}
componentWillUnmount() {
if (this.state.refreshInterval) {
clearInterval(this.state.refreshInterval);
this.state.refreshInterval = null;
}
}
render() {
if (!this.state.loaded) {
this.loadState();
return false;
}
if (
this.props.state.config.queue_magic_word_mode === "none" ||
this.state.magicWord === undefined
) {
return false;
}
let magicWordElem = <i>Loading...</i>;
if (this.state.magicWord) {
let magicWord = this.state.magicWord;
magicWordElem = <code>{magicWord}</code>;
}
return (
<div>
<h4>Magic word: {magicWordElem}</h4>
</div>
);
}
}
<file_sep>/ag-master/models.py
from __future__ import annotations
from typing import List
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from common.db import database_url
def create_models(app: Flask):
"""Creates database models
:param app: the app to attach the database URL to
:type app: ~flask.Flask
"""
app.config["SQLALCHEMY_DATABASE_URI"] = database_url
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy()
class Assignment(db.Model):
"""Represents an Assignment that can be autograded
:param assignment_secret: a randomly-generated unique key to be used by
Okpy to identify this assignment
:type assignment_secret: str
:param name: the shortname of the assignment, conventionally the same as
the Okpy shortname
:type name: str
:param course: the course code for the course whose assignment this is
:type course: str
:param endpoint: the Okpy endpoint for the relevant course (saved here as
endpoints change across semesters)
:type endpoint: str
:param file: the name of the grading zip file to use to grade the assignment
:type file: str
:param command: the command to run on the worker to grade a backup
:type command:
:param last_modified: the unix timestamp for the last modification of this
assignment on the autograder
:type last_modified: int
:param batch_size: the grading batch size for this assignment (one worker
will grade this many items -- must be set such that less than 50 total
batches are created by an individual run)
:type batch_size: int
:param grading_base: the server associated with this assignment (usually
https://okpy.org)
:type grading_base: str
:param jobs: all grading jobs associated with this assignment
:type jobs: list[Job]
"""
assignment_secret: str = db.Column(db.String(64), primary_key=True, index=True)
name: str = db.Column(db.String(64), nullable=False)
course: str = db.Column(db.String(64), index=True, nullable=False)
endpoint: str = db.Column(db.String(64), index=True, nullable=False)
file: str = db.Column(db.String(64), nullable=False)
command: str = db.Column(db.Text, nullable=False)
last_modified: int = db.Column(db.Integer, nullable=False)
batch_size: int = db.Column(db.Integer, nullable=False, default=100)
grading_base: str = db.Column(
db.String(64), nullable=False, default="https://okpy.org"
)
jobs: List[Job]
class Job(db.Model):
"""Represents an autograding Job
:param job_secret: the internal job identifier, used for communication
between the host and the worker
:type job_secret: str
:param external_job_id: the external job identifier, used for communication
between the grading server and the host
:type external_job_id: str
:param assignment_secret: a foreign key to the assignment identifier
:type assignment_secret: str
:param assignment: the assignment that this job is associated with
:type assignment: Assignment
:param backup: the grading server backup this job is associated with
:type backup: str
:param status: whether this is queued, started, running, finished, etc.
:type status: str
:param result: the grading command's output for this job
:type result: str
:param access_token: the grading server's access token to get backup
content and upload scores for this job
:type access_token: str
:param queued_at: the unix timestamp for when this job was queued -- if
multiple jobs are queued by the same request, they are automatically
treated as a single trigger by the UI
:type queued_at: int
:param started_at: the unix timestamp for when the worker began running
this job
:type started_at: int
:param finished_at: the unix timestamp for when the worker returned the
result for this job, whether it succeeded or errored
:type finished_at: int
"""
job_secret: str = db.Column(db.String(64), index=True, primary_key=True)
external_job_id: str = db.Column(db.String(64), index=True, nullable=False)
assignment_secret: str = db.Column(
db.String(64),
db.ForeignKey("assignment.assignment_secret"),
index=True,
nullable=False,
)
assignment: Assignment = db.relationship("Assignment", backref=db.backref("jobs"))
backup: str = db.Column(db.String(64), nullable=False)
status: str = db.Column(db.String(64), default="queued", nullable=False)
result: str = db.Column(db.Text, default="", nullable=False)
access_token: str = db.Column(db.String(64), nullable=False)
queued_at: int = db.Column(db.Integer, nullable=False)
started_at: int = db.Column(db.Integer)
finished_at: int = db.Column(db.Integer)
<file_sep>/code/src/renderer/utils/svg.min.js
../../../static/svg.min.js<file_sep>/docs/requirements.txt
furo==2020.12.30b24
linkify-it-py==1.0.1
myst-parser==0.13.3
Sphinx==3.4.3
docutils==0.16
sphinx-autobuild==2020.9.1
sphinxcontrib-openapi==0.7.0
<file_sep>/oh/oh_queue/static/js/components/fancy_toggle.js
function FancyToggle({ checked, onChange, offText, onText }) {
const [initialized, setInitialized] = React.useState(false);
const toggleRef = React.useRef();
const initializeToggle = (toggle) => {
if (!toggle || initialized) return;
$(toggle).bootstrapToggle();
$(toggle).change(() => handleClick(toggle));
setInitialized(true);
toggleRef.current = toggle;
};
const handleClick = (toggle) => {
onChange(toggle.checked);
};
React.useEffect(() => {
if (toggleRef.current) {
$(toggleRef.current).off("change");
$(toggleRef.current).bootstrapToggle(checked ? "on" : "off");
$(toggleRef.current).change(() => handleClick(toggleRef.current));
}
}, [toggleRef.current, checked]);
return (
<input
ref={initializeToggle}
type="checkbox"
defaultChecked={checked}
data-off={offText}
data-on={onText}
data-size="mini"
data-toggle="toggle"
onClick={handleClick}
/>
);
}
<file_sep>/buildserver/dependency_loader.py
import os
from os import chdir, mkdir
from os.path import isdir
from shutil import copyfile, copytree
from github import Github
from github.Repository import Repository
from app_config import App
from build import clone_commit, gen_working_dir
from common.rpc.secrets import get_secret
from common.shell_utils import tmp_directory
def load_dependencies(app: App, sha: str, repo: Repository):
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
def clone_repo(repo_str: str):
cloned_repo = g.get_repo(repo_str)
cloned_sha = (
sha
if cloned_repo.full_name == repo.full_name
else cloned_repo.get_branch(cloned_repo.default_branch).commit.sha
)
clone_commit(cloned_repo.clone_url, cloned_sha, in_place=True)
with tmp_directory():
for dependency in app.config["dependencies"]:
folder_name = dependency["repo"].replace("/", "-")
if not isdir(folder_name):
# dependency is not already loaded
mkdir(folder_name)
chdir(folder_name)
clone_repo(dependency["repo"])
chdir("..")
try:
copytree(
os.path.join(folder_name, dependency["src"]),
os.path.join(app.name, dependency["dest"]),
symlinks=False,
dirs_exist_ok=True,
)
except NotADirectoryError:
copyfile(
os.path.join(folder_name, dependency["src"]),
os.path.join(app.name, dependency["dest"]),
)
if app.config["repo"]:
working_dir = gen_working_dir(app)
mkdir(working_dir)
chdir(working_dir)
clone_repo(app.config["repo"])
chdir("..")
<file_sep>/common/rpc/sections.py
from typing import Union
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/export_attendance_rpc")
def rpc_export_attendance(*, full: bool):
...
<file_sep>/sections/scripts/update_tutors.py
import csv
import os
import sys
from datetime import datetime, timedelta
import pytz
sys.path.append(os.path.abspath("../server"))
from common.rpc.auth import read_spreadsheet
from main import app
from models import Section, User, db
hour = 4
min = 0
reader = read_spreadsheet(
url="https://docs.google.com/spreadsheets/d/1S10VeClOIzcMaEQcRrdzdUl_NCLFNX3YeyK9Z3DXn1U/",
sheet_name=f"'{hour}:{min+5:02}'",
)
pst = pytz.timezone("US/Pacific")
start_time = pst.localize(
datetime(year=2020, month=8, day=26, hour=hour + 12, minute=min + 5)
)
end_time = start_time + timedelta(minutes=25)
users = {}
def get_user(email, name):
if email in users:
return users[email]
user = User.query.filter_by(email=email).one_or_none()
if user is None:
user = User(email=email, name=name, is_staff=True)
users[email] = user
return user
with app.app_context():
sections = Section.query.filter_by(
staff=None, start_time=start_time.timestamp(), end_time=end_time.timestamp()
).all()
sections_by_npe = [[], []]
for section in sections:
sections_by_npe[section.tag_string == "NPE"].append(section)
print([len(sections) for sections in sections_by_npe])
for row in reader:
if not row:
break
if row[0] != "FALSE":
continue
assert len(row) == 11
npe = row[-2] == "TRUE"
if row[-1] == "TRUE":
print("Reassigning empty section to tutor: {}, NPE: {}".format(row[1], npe))
section = sections_by_npe[npe].pop()
section.staff = get_user(row[2], row[1])
else:
print("Creating new section with tutor: {}, NPE: {}".format(row[1], npe))
section = Section(
start_time=start_time.timestamp(),
end_time=end_time.timestamp(),
capacity=5,
staff=get_user(row[2], row[1]),
)
if npe:
section.tags = ["NPE"]
db.session.add(section)
db.session.commit()
<file_sep>/oh/migrations/prev_versions/e330a9be55f8_added_fields_for_juggling.py
"""Added fields for juggling
Revision ID: e330a9be55f8
Revises: <KEY>
Create Date: 2020-02-23 06:10:28.465718
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "e330a9be55f8"
down_revision = "e4b5bd2a05cc"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("ticket", sa.Column("hold_time", sa.DateTime(), nullable=True))
op.add_column(
"ticket", sa.Column("rerequest_threshold", sa.DateTime(), nullable=True)
)
op.add_column("ticket", sa.Column("rerequest_time", sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("ticket", "rerequest_time")
op.drop_column("ticket", "rerequest_threshold")
op.drop_column("ticket", "hold_time")
# ### end Alembic commands ###
<file_sep>/slack/group_integration.py
import re
import requests
from common.rpc.auth import list_admins
from integration import Integration
TAG_REGEX = r"@(?P<course>[a-zA-Z0-9]+)"
class GroupIntegration(Integration):
@property
def responses(self):
users = None
for match in re.finditer(TAG_REGEX, self._message):
course = match.group("course")
try:
if course == "heads" or course == "admins":
course = self._course
admins = list_admins(course=course)
except:
continue
if not admins:
continue
users = (
users
or requests.get(
"https://slack.com/api/users.list",
params={"token": self._bot_token},
).json()
)
tags = []
for member in users["members"]:
for email, name in admins:
if (
member["profile"].get("email") == email
or member["profile"].get("real_name_normalized") == name
):
tags.append("<@{}>".format(member["id"]))
yield "Admins for {}: {}".format(course, ", ".join(tags))
<file_sep>/oh/migrations/versions/ab9f3b203744_add_notification_state.py
"""Add notification state
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2020-09-09 17:49:06.161756
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"notification_state",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("last_queue_ping", sa.DateTime(), nullable=False),
sa.Column("last_appointment_notif", sa.DateTime(), nullable=False),
sa.Column("domain", sa.String(length=255), nullable=False),
sa.Column("course", sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_notification_state_course"),
"notification_state",
["course"],
unique=False,
)
op.add_column(
"appointment", sa.Column("num_reminders_sent", sa.Integer(), nullable=False)
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("appointment", "num_reminders_sent")
op.drop_index(op.f("ix_notification_state_course"), table_name="notification_state")
op.drop_table("notification_state")
# ### end Alembic commands ###
<file_sep>/buildserver/worker.py
import tempfile
import traceback
from sys import stderr, stdout
from typing import Iterable, Optional, Union
from github.File import File
from github.PullRequest import PullRequest
from github.Repository import Repository
from app_config import App
from build import build, clone_commit
from common.db import connect_db
from common.rpc.buildserver import clear_queue
from common.shell_utils import redirect_descriptor
from dependency_loader import load_dependencies
from deploy import deploy_commit
from external_build import run_highcpu_build
from external_repo_utils import update_config
from github_utils import (
BuildStatus,
pack,
unpack,
)
from scheduling import enqueue_builds, report_build_status
from service_management import get_pr_subdomains, update_service_routes
from target_determinator import determine_targets
def land_app(
app: App,
pr_number: int,
sha: str,
repo: Repository,
):
if app.config is None:
delete_app(app, pr_number)
return
update_config(app, pr_number)
if app.config["build_image"]:
run_highcpu_build(app, pr_number, sha, repo)
else:
land_app_worker(app, pr_number, sha, repo)
def land_app_worker(
app: App,
pr_number: int,
sha: str,
repo: Repository,
):
load_dependencies(app, sha, repo)
build(app)
deploy_commit(app, pr_number)
def delete_app(app: App, pr_number: int):
with connect_db() as db:
db(
"DELETE FROM services WHERE app=%s AND pr_number=%s",
[app.name, pr_number],
)
if pr_number == 0:
db("DELETE FROM apps WHERE app=%s", [app.name])
def land_commit(
sha: str,
repo: Repository,
base_repo: Repository,
pr: Optional[PullRequest],
files: Iterable[Union[File, str]],
*,
target_app: Optional[str] = None,
dequeue_only=False,
):
"""
:param sha: The hash of the commit we are building
:param repo: The repo containing the above commit
:param base_repo: The *base* cs61a-apps repo containing the deploy.yaml config
:param pr: The PR made to trigger the build, if any
:param files: Files changed in the commit, used for target determination
:param target_app: App to rebuild, if not all
:param dequeue_only: Only pop targets off the queue, do not build any new targets
"""
if dequeue_only:
targets = []
elif target_app:
targets = [target_app]
else:
targets = determine_targets(
repo, files if repo.full_name == base_repo.full_name else []
)
pr_number = pr.number if pr else 0
grouped_targets = enqueue_builds(targets, pr_number, pack(repo.clone_url, sha))
for packed_ref, targets in grouped_targets.items():
repo_clone_url, sha = unpack(packed_ref)
# If the commit is made on the base repo, take the config from the current commit.
# Otherwise, retrieve it from master
clone_commit(
base_repo.clone_url,
sha
if repo_clone_url == base_repo.clone_url
else base_repo.get_branch(base_repo.default_branch).commit.sha,
)
apps = [App(target) for target in targets]
for app in apps:
with tempfile.TemporaryFile("w+") as logs:
try:
with redirect_descriptor(stdout, logs), redirect_descriptor(
stderr, logs
):
land_app(app, pr_number, sha, repo)
if app.config is not None:
update_service_routes([app], pr_number)
except:
traceback.print_exc(file=logs)
logs.seek(0)
report_build_status(
app.name,
pr_number,
pack(repo.clone_url, sha),
BuildStatus.failure,
None,
logs.read(),
private=repo.full_name == base_repo.full_name,
)
else:
logs.seek(0)
report_build_status(
app.name,
pr_number,
pack(repo.clone_url, sha),
BuildStatus.success,
None
if app.config is None
else ",".join(
hostname.to_str()
for hostname in get_pr_subdomains(app, pr_number)
),
logs.read(),
private=repo.full_name == base_repo.full_name,
)
if grouped_targets:
# because we ran a build, we need to clear the queue of anyone we blocked
# we run this in a new worker to avoid timing out
clear_queue(repo=repo.full_name, pr_number=pr_number, noreply=True)
<file_sep>/oh/oh_queue/static/js/components/appointment_student_card.js
function AppointmentStudentCard({
status,
signup,
assignments,
isStaff,
okpyEndpointID,
}) {
const assignmentName = signup.assignment_id
? assignments[signup.assignment_id].name
: "";
const questionName = signup.question ? " Question " + signup.question : "";
const okPyURL =
"https://okpy.org/admin/course/" +
okpyEndpointID +
"/" +
encodeURIComponent(signup.user.email);
const okPyLink = isStaff && okpyEndpointID && (
<button
className="btn btn-sm btn-default pull-right"
onClick={() => window.open(okPyURL, "_blank")}
>
View Backups
</button>
);
const question =
assignmentName + questionName ? (
<Slot>
<div className="slot-question-row">
{assignmentName + questionName}
{okPyLink}
</div>
</Slot>
) : (
<Slot className="slot-question-row slot-disabled">
<i>No question specified</i>
{okPyLink}
</Slot>
);
const description = signup.description ? (
<Slot className="ticket-view-desc">{signup.description}</Slot>
) : (
<Slot className="slot-disabled">
<i>No description provided</i>
</Slot>
);
const colorLookup = {
unknown: "default",
present: "primary",
excused: "warning",
absent: "danger",
};
const color = colorLookup[signup.attendance_status];
return (
<div className={`panel panel-${color}`}>
<div className="panel-heading">
<h3 className="panel-title">{signup.user.name}</h3>
</div>
<ul className="list-group">
{question}
{description}
</ul>
{isStaff && status === "active" && (
<div className="panel-footer attendance-buttons">
<AttendanceButton color="primary" signup={signup} status="present" />
<AttendanceButton color="warning" signup={signup} status="excused" />
<AttendanceButton color="danger" signup={signup} status="absent" />
</div>
)}
</div>
);
}
function AttendanceButton({ signup, status, color }) {
const handleClick = () => {
app.makeRequest("mark_attendance", { signup_id: signup.id, status });
};
const active = signup.attendance_status === status;
return (
<button
className={`btn btn-${color}`}
onClick={handleClick}
disabled={signup.status === "resolved" || active}
>
{status[0].toUpperCase() + status.slice(1).toLowerCase()}
</button>
);
}
<file_sep>/hog/server/hog.py
print(
"If you are reading this, you need to replace hog.py with your project solution for the gui to work!"
)
<file_sep>/oh/oh_queue/static/js/components/tabs.js
/* Mostly from https://toddmotto.com/creating-a-tabs-component-with-react/
* Use like this:
*
* <Tabs selectedIndex={0} onSelect={(index) => ...}>
* <Tab label="My Tab">
* ... tab content
* </Tab>
* <Tab label="Other Tab">
* ... tab content
* </Tab>
* </Tabs>
*/
let Tabs = ({ selectedIndex, onSelect, children }) => {
children = React.Children.toArray(children).filter((x) => x);
let renderLabel = (child, index) => {
let active = selectedIndex === index;
let tabClass = classNames({
active: active,
pulsating: child.props.shouldHighlight && !active,
});
return (
<li key={index} className={tabClass}>
<a
href="#"
onClick={(e) => {
e.preventDefault();
onSelect(index);
}}
>
{child.props.label}
</a>
</li>
);
};
return (
<div className="row tabs-container">
<div className="col-xs-12 tabs">
<ul className="nav nav-tabs nav-justified">
{children.map(renderLabel)}
</ul>
<div className="tab-content">{children[selectedIndex]}</div>
</div>
</div>
);
};
const Tab = (props) => {
return <div>{props.children}</div>;
};
<file_sep>/buildtool/buildtool/workspace_setup.py
import os
from typing import Dict, List, Optional, Sequence, Set
from cache import make_cache_fetcher, make_cache_memorize
from context import Env
from execution import ExecutionContext
from fs_utils import hash_file
from monitoring import create_status_monitor, log
from state import Rule, TargetLookup
from utils import BuildException, CacheMiss
from common.hash_utils import HashState
class WorkspaceExecutionContext(ExecutionContext):
def __init__(
self,
hashstate: HashState,
):
super().__init__(
os.curdir, os.curdir, hashstate, lambda *args: None, lambda *args: None
)
def add_deps(self, deps: Sequence[str]):
raise BuildException("Cannot add dependencies dynamically in a setup rule.")
def input(
self,
*,
file: Optional[str] = None,
sh: Optional[str] = None,
env: Optional[Env] = None,
):
if file is not None:
raise BuildException(
f"Cannot add dependencies dynamically in a setup rule. Add {file} as a static dependency "
f'then use input(sh="cat {file}") instead.'
)
else:
return super().input(file=file, sh=sh, env=env)
def normalize(self, env: Optional[Env]):
if env is None:
env = {}
return super().normalize({**env, **os.environ})
def initialize_workspace(
setup_rule_lookup: TargetLookup,
setup_targets: List[str],
state_directory: str,
quiet: bool,
):
# we don't need the indirect lookup as we only have rule and source deps
direct_lookup: Dict[str, Rule] = setup_rule_lookup.direct_lookup
work_queue = []
for setup_target in setup_targets:
if setup_target not in direct_lookup:
raise BuildException(f"Unknown or unspecified setup target {setup_target}")
work_queue.append(direct_lookup[setup_target])
rebuilt: Set[str] = set()
ready: Set[str] = set()
cache_fetcher, _ = make_cache_fetcher(state_directory)
cache_memorize, _ = make_cache_memorize(state_directory)
if work_queue:
status_monitor = create_status_monitor(1, quiet)
status_monitor.move(total=len(work_queue))
while work_queue:
todo = work_queue.pop()
log(f"Popping setup rule {todo} off work queue")
hashstate = HashState()
ctx = WorkspaceExecutionContext(hashstate)
unchecked_rules = []
for dep in todo.deps:
hashstate.record(dep)
if dep.startswith(":"):
if dep not in direct_lookup:
raise BuildException(f"Unable to find setup rule {dep}")
dep_rule = direct_lookup[dep]
if dep_rule not in ready:
unchecked_rules.append(dep_rule)
continue
ctx.deps[dep] = dep_rule.provided_value
setattr(ctx.deps, dep[1:], dep_rule.provided_value)
else:
try:
hashstate.update(hash_file(dep))
except FileNotFoundError:
raise BuildException(f"Source file {dep} not found.")
if unchecked_rules:
for dep in unchecked_rules:
if dep not in work_queue:
log(f"Setup rule {todo} is enqueuing {dep}")
status_monitor.move(total=1)
work_queue.append(dep)
else:
log(
f"Setup rule {todo} is waiting on {dep}, which is already enqueued"
)
dep.runtime_dependents.add(todo)
todo.pending_rule_dependencies.add(dep)
else:
# our dependent rules are ready, now we need to see if we need to rerun
todo.provided_value = todo.impl(ctx)
if todo.name is None:
raise BuildException(
f"All setup rules must have names, but {todo} does not."
)
try:
ok = cache_fetcher("workspace", todo.name) == hashstate.state()
if not ok:
log(f"State mismatch for rule {todo}, need to rerun")
except CacheMiss:
log(f"State not found for rule {todo}, need to run for first time")
ok = False
for dep in todo.deps:
if dep.startswith(":"):
if direct_lookup[dep] in rebuilt:
log(
f"Dependency {dep} of setup rule {todo} was rebuilt, so we must rebuild {todo} as well"
)
ok = False
for out in todo.outputs:
if not os.path.exists(out):
log(f"Output {out} is missing for setup rule {todo}, forcing rerun")
ok = False
break
if not ok:
# we need to fully run
ctx.run_shell_queue()
rebuilt.add(todo)
cache_memorize("workspace", todo.name, hashstate.state())
# either way, now we can trigger our dependents
ready.add(todo)
for dep in todo.runtime_dependents:
dep.pending_rule_dependencies.remove(todo)
if not dep.pending_rule_dependencies:
work_queue.append(dep)
status_monitor.move(total=1)
status_monitor.move(curr=1)
<file_sep>/common/rpc/ag_master.py
from typing import List, Dict
from common.rpc.utils import (
create_service,
requires_master_secret,
requires_access_token,
)
service = create_service(__name__, "ag-master")
@requires_master_secret
@service.route("/api/trigger_jobs")
def trigger_jobs(*, assignment_id: str, jobs: List[str]):
"""Given a list of job IDs, queues autograder workers to begin grading.
:param assignment_id: the assignment secret key, used as an identifier
:type assignment_id: str
:param jobs: the list of job IDs to queue
:type jobs: list[str]
Bound in :func:`~docs.ag_master.okpy.create_okpy_endpoints`
"""
...
@service.route("/api/get_submission")
def get_submission(*, job_id: str) -> Dict:
"""Given a job ID, gets submission information from Okpy and forwards it
to the requesting worker.
:param job_id: the job ID associated with the requested backup
:type job_id: str
:return: a dictionary containing backup information, specifically the
``data`` value `here <https://okpy.github.io/documentation/ok-api.html#backups-view-a-backup>`_
Bound in :func:`~docs.ag_master.worker.create_worker_endpoints`
"""
...
@service.route("/api/handle_output")
def handle_output(*, output: str, job_id: str):
"""Given output and a job ID, parses the output for scores and uploads them
to Okpy. See :class:`~docs.ag_master.worker` for helper functions used.
:param output: the autograder worker output
:type output: str
:param job_id: the job ID associated with the output
:type job_id: str
Bound in :func:`~docs.ag_master.worker.create_worker_endpoints`
"""
...
@service.route("/api/set_failure")
def set_failure(*, job_id: str, result: str):
"""Given a job ID and some output result, set the job to failed and report
the failure to Okpy.
:param job_id: the job ID associated with the output
:type job_id: str
:param result: the autograder worker output
:type result: str
Bound in :func:`~docs.ag_master.worker.create_worker_endpoints`
"""
...
@requires_access_token
@service.route("/api/upload_zip")
def upload_zip(*, course: str, name: str, file: str):
"""Given a course, a filename, and base64-encoded zip file contents,
upload the file to a cloud storage bucket. This method is meant to be
accessed using the SICP command-line tool.
:param course: the course code
:type course: str
:param name: the filename
:type name: str
:param file: base64-encoded zip-file contexts
:type file: str
Bound in :func:`~docs.ag_master.admin.create_admin_endpoints`
"""
...
@requires_access_token
@service.route("/api/create_assignment")
def create_assignment(
*,
course: str,
name: str,
file: str,
command: str,
batch_size: int,
grading_base: str,
) -> str:
"""Given some information about an assignment, register it into the
autograder database so that it may be graded using the autograder. This
method is meant to be accessed using the SICP command-line tool.
:param course: the course code
:type course: str
:param name: the assignment shortname
:type name: str
:param file: the assignment filename (should be the same as ``name`` in
:func:`~common.rpc.ag_master.upload_zip`)
:type file: str
:param command: the command the worker should run to grade a backup for this
assignment
:type command: str
:param batch_size: how many backups should be graded by one worker
:type batch_size: int
:param grading_base: the grading server associated with the assignment
(by default, https://okpy.org)
:type grading_base: str
Bound in :func:`~docs.ag_master.admin.create_admin_endpoints`
"""
...
<file_sep>/examtool/examtool/api/download.py
import json
from tqdm import tqdm
from examtool.api.database import get_exam, get_roster, get_submissions
from examtool.api.extract_questions import extract_questions
from examtool.api.scramble import scramble
def download(exam, emails_to_download: [str] = None, debug: bool = False):
exam_json = get_exam(exam=exam)
exam_json.pop("secret")
exam_json = json.dumps(exam_json)
template_questions = list(extract_questions(json.loads(exam_json)))
total = [
["Email"]
+ [question["text"] for question in extract_questions(json.loads(exam_json))]
]
email_to_data_map = {}
if emails_to_download is None:
roster = get_roster(exam=exam)
emails_to_download = [email for email, _ in roster]
i = 1
for email, response in tqdm(
get_submissions(exam=exam), dynamic_ncols=True, desc="Downloading", unit="Exam"
):
i += 1
if emails_to_download is not None and email not in emails_to_download:
continue
if debug and 1 < len(response) < 10:
tqdm.write(email, response)
total.append([email])
for question in template_questions:
total[-1].append(response.get(question["id"], ""))
student_questions = list(
extract_questions(scramble(email, json.loads(exam_json), keep_data=True))
)
email_to_data_map[email] = {
"student_questions": student_questions,
"responses": response,
}
return json.loads(exam_json), template_questions, email_to_data_map, total
def get_question_to_page_mapping(
template_questions,
exam,
out,
name_question,
sid_question,
dispatch=None,
):
questions = []
pages = []
for q in tqdm(
template_questions,
desc="Getting question page numbers",
unit="Question",
dynamic_ncols=True,
):
questions.append(q)
pdf = write_exam(
None,
{},
exam,
questions,
questions,
name_question,
sid_question,
dispatch,
)
pages.append(pdf.page_no())
# for i, q in enumerate(questions):
# print(f"[{i}] pg: {pages[i]} - {q['id']}")
# import ipdb; ipdb.set_trace()
return pages
<file_sep>/common/hash_utils.py
import hashlib
class HashState:
"""Utility class for hashing data. Uses ``hashlib.md5``.
:example usage:
.. code-block:: python
>>> state = HashState()
>>> state.update(b"hello world")
>>> state.state()
'fe0cf2fe0d7cb366190a4a80af973909'
"""
def __init__(self):
self._state = hashlib.md5()
def update(self, data: bytes):
"""Append some data to the current state.
:param data: the data to append
:type data: bytes
:return: self
"""
self._state.update(str(len(data)).encode("utf-8") + b":")
self._state.update(data + b":")
return self
def record(self, *args):
"""Append multiple pieces of data to the current state.
:param args: the data to append
:type args: *str
:return: self
"""
self._state.update(str(args).encode("utf-8"))
return self
def state(self):
"""Get a hex digest of the current state.
:return: the hex digest of the current state
"""
return self._state.hexdigest()
<file_sep>/common/rpc/hosted.py
from typing import Dict, Optional
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__, "deploy.hosted")
@requires_master_secret
@service.route("/api/list_apps")
def list_apps():
...
@requires_master_secret
@service.route("/api/new")
def new(*, img: str, name: Optional[str] = None, env: Dict[str, str] = {}):
...
@requires_master_secret
@service.route("/api/stop")
def stop(*, name: str):
...
@requires_master_secret
@service.route("/api/run")
def run(*, name: str):
...
@requires_master_secret
@service.route("/api/delete")
def delete(*, name: str):
...
@requires_master_secret
@service.route("/api/add_domain")
def add_domain(
*, name: str, domain: str, force: bool = False, proxy_set_header: dict = {}
):
...
@requires_master_secret
@service.route("/api/service_log")
def service_log():
...
@requires_master_secret
@service.route("/api/container_log")
def container_log(*, name: str):
...
@requires_master_secret
@service.route("/api/create_pr_subdomain")
def create_pr_subdomain(*, app: str, pr_number: int, pr_host: str):
...
<file_sep>/hog/server/hog_gui.py
"""Web server for the hog GUI."""
import io
import os
import logging
from contextlib import redirect_stdout
from gui_files.common_server import route, start
import hog
import dice
import default_graphics
PORT = 31415
DEFAULT_SERVER = "https://hog.cs61a.org"
GUI_FOLDER = "gui_files/"
PATHS = {}
class HogLoggingException(Exception):
pass
@route
def take_turn(prev_rolls, move_history, goal, game_rules):
"""Simulate the whole game up to the current turn."""
fair_dice = dice.make_fair_dice(6)
dice_results = []
more_boar = game_rules["More Boar"]
try:
old_more_boar = hog.more_boar
if not more_boar:
hog.more_boar = lambda score0, score1: False
def logged_dice():
if len(dice_results) < len(prev_rolls):
out = prev_rolls[len(dice_results)]
else:
out = fair_dice()
dice_results.append(out)
return out
final_scores = None
final_message = None
who = 0
commentary = hog.both(
hog.announce_highest(0),
hog.both(hog.announce_highest(1), hog.announce_lead_changes()),
)
def log(*logged_scores):
nonlocal final_message, commentary
f = io.StringIO()
with redirect_stdout(f):
commentary = commentary(*logged_scores)
final_message = f.getvalue()
return log
move_cnt = 0
def strategy_for(player):
def strategy(*scores):
nonlocal final_scores, move_cnt, who
final_scores = scores
if player:
final_scores = final_scores[::-1]
who = player
if move_cnt == len(move_history):
raise HogLoggingException()
move = move_history[move_cnt]
move_cnt += 1
return move
return strategy
game_over = False
try:
final_scores = trace_play(
hog.play,
strategy_for(0),
strategy_for(1),
0,
0,
dice=logged_dice,
say=log,
goal=goal,
)[:2]
except HogLoggingException:
pass
else:
game_over = True
finally:
hog.more_boar = old_more_boar
return {
"rolls": dice_results,
"finalScores": final_scores,
"message": final_message,
"gameOver": game_over,
"who": who,
}
@route
def strategy(name, scores):
STRATEGIES = {
"piggypoints_strategy": hog.piggypoints_strategy,
"more_boar_strategy": hog.more_boar_strategy,
"final_strategy": hog.final_strategy,
}
return STRATEGIES[name](*scores[::-1])
@route("dice_graphic.svg")
def draw_dice_graphic(num):
num = int(num[0])
# Either draw student-provided dice or our default dice
if hasattr(hog, "draw_dice"):
graphic = hog.draw_dice(num)
return str(graphic)
return default_graphics.dice[num]
def safe(commentary):
def new_commentary(*args, **kwargs):
try:
result = commentary(*args, **kwargs)
except TypeError:
result = commentary
return safe(result)
return new_commentary
def trace_play(play, strategy0, strategy1, score0, score1, dice, goal, say):
"""Wraps the user's play function and
(1) ensures that strategy0 and strategy1 are called exactly once per turn
(2) records the entire game, returning the result as a list of dictionaries,
each with keys "s0_start", "s1_start", "who", "num_dice", "dice_values"
Returns (s0, s1, trace) where s0, s1 are the return values from play and trace
is the trace as specified above.
This might seem a bit overcomplicated but it will also used to create the game
traces for the fuzz test (when run against the staff solution).
"""
game_trace = []
def mod_strategy(who, my_score, opponent_score):
if game_trace:
prev_total_score = game_trace[-1]["s0_start"] + game_trace[-1]["s1_start"]
if prev_total_score == my_score + opponent_score:
# game is still on last turn since the total number of points
# goes up every turn
return game_trace[-1]["num_dice"]
current_num_dice = (strategy0, strategy1)[who](my_score, opponent_score)
current_turn = {
"s0_start": [my_score, opponent_score][who],
"s1_start": [my_score, opponent_score][1 - who],
"who": who,
"num_dice": current_num_dice,
"dice_values": [], # no dice rolled yet
}
game_trace.append(current_turn)
return current_num_dice
def mod_dice():
roll = dice()
if not game_trace:
raise RuntimeError("roll_dice called before either strategy function")
game_trace[-1]["dice_values"].append(roll)
return roll
s0, s1 = play(
lambda a, b: mod_strategy(0, a, b),
lambda a, b: mod_strategy(1, a, b),
score0,
score1,
dice=mod_dice,
goal=goal,
say=safe(say),
)
return s0, s1, game_trace
if __name__ == "__main__" or "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""):
app = start(PORT, DEFAULT_SERVER, GUI_FOLDER)
<file_sep>/common/rpc/howamidoing.py
from typing import Union
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/upload_grades")
def upload_grades(*, data: str):
...
<file_sep>/wiki/make_content.py
import os, yaml, requests
from shutil import copyfile
with open("metadata.yaml") as md:
metadata = yaml.load(md)
metadata = metadata if metadata else {}
users = {
"rahularya50": "<NAME>",
"itsvs": "<NAME>",
"AnimeshAgrawal": "<NAME>",
}
def get_name(user):
if user not in users:
users[user] = (
requests.get(f"https://api.github.com/users/{user}").json().get("name", "")
)
return users[user]
def get_user(user):
name = get_name(user)
if name:
return f"{name} (@{user})"
return f"@{user}"
class WikiApp:
def __init__(self, path, name=None, dest=None):
self.path = path
with open(f"../{self.path}/README.md") as r:
self.lines = [l for l in r.readlines()]
self.name = name if name else self.lines[0][2:-1]
self.dest = dest if dest else f"{self.path}/_index.md"
self.contrib = metadata.get(path, [])
self.contrib = [
f"<a href='https://github.com/{contrib}' target='_blank'>{get_user(contrib)}</a>"
for contrib in self.contrib
]
class StubApp:
def __init__(self, path, name=None, description=None):
self.path = path
self.lines = (
description.split("\n")
if description
else ["", "This app has not yet been documented."]
)
self.name = name if name else self.path.replace("-", " ").title()
self.name += " (Stub)"
self.dest = f"{self.path}/_index.md"
self.contrib = metadata.get(path, [])
self.contrib = [
f"<a href='https://github.com/{contrib}' target='_blank'>{get_user(contrib)}</a>"
for contrib in self.contrib
]
EXCLUDE = set(["node_modules", ".pytest_cache", "env"])
PATHS = {
"auth": WikiApp("auth", "Auth"),
"code": WikiApp("code", "Code"),
"examtool": WikiApp("examtool", "Examtool"),
"exam-write": WikiApp("exam-write", "Writing Exams", dest="examtool/writing.md"),
"grade-display": WikiApp("grade-display", "Grade Display"),
"howamidoing": WikiApp("howamidoing", "Howamidoing"),
"oh": WikiApp("oh", "Office Hours Queue"),
"oh/migrations": WikiApp(
"oh/migrations", "Generating Migrations", dest="oh/migrations.md"
),
"sicp": WikiApp("sicp", "SICP"),
"piazzaoncall": WikiApp("piazzaoncall", "Piazza Oncall"),
}
if not os.path.exists("content"):
os.makedirs("content")
INDEX = """# CS 61A Infra Wiki
Welcome to the CS 61A Infrastructure Wiki! This
wiki contains information about how various CS 61A
software works and how you can contribute to it.
We also plan on including installation guides so
that you can use these tools in your own courses.
This is a work in progress, so please *bear* with
us while we put it together! Apps marked `(Stub)`
are currently missing documentation but are
included to credit the code writers.
"""
with open("content/_index.md", "w") as index:
index.write(INDEX)
apps = []
for root, dirs, files in os.walk("../"):
dirs[:] = [d for d in dirs if d not in EXCLUDE]
if root == "../wiki":
dirs[:] = []
for file in files:
if file == "README.md":
apps.append(root[3:])
def write_app(app):
if not os.path.exists(f"content/{app.dest.split('/')[0]}"):
os.makedirs(f"content/{app.dest.split('/')[0]}")
with open(f"content/{app.dest}", "w") as c:
c.write("---\n")
c.write(f"title: {app.name}\n")
c.write(f"contrib: {app.contrib}\n")
c.write("---\n\n")
for l in app.lines[1:]:
c.write(f"{l}")
for app_raw in apps:
app = PATHS.get(app_raw, WikiApp(app_raw))
print(app_raw)
write_app(app)
STUBS = [
StubApp("buildserver"),
StubApp("buildtool", name="Build Tool"),
StubApp("common"),
StubApp("domains"),
StubApp("hog-contest"),
StubApp("indexer"),
StubApp("logs"),
StubApp("partnermatcher", name="Partner Matcher"),
StubApp("paste"),
StubApp("search"),
StubApp("secrets"),
StubApp("sections"),
StubApp("shortlinks"),
StubApp("slack", name="Slackbot"),
StubApp("static-server"),
StubApp("wiki"),
]
for app in STUBS:
print(app.path)
write_app(app)
<file_sep>/hog-contest/logger.py
from collections import deque
from datetime import datetime
MAX_LOG_LEN = 100
logs = deque(maxlen=MAX_LOG_LEN)
def log(msg):
print(msg)
logs.append("{}: {}".format(datetime.now(), msg))
def get_log():
return "\n".join(logs)
<file_sep>/oh/migrations/prev_versions/1535e0a43842_unified_instance_across_courses.py
"""unified instance across courses
Revision ID: 1535e0a43842
Revises: 7141eb5952ee
Create Date: 2020-03-07 22:00:55.601998
"""
# revision identifiers, used by Alembic.
revision = "1535e0a43842"
down_revision = "7141eb5952ee"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"assignment", sa.Column("course", sa.String(length=255), nullable=False)
)
op.add_column(
"config_entries", sa.Column("course", sa.String(length=255), nullable=False)
)
op.add_column(
"location", sa.Column("course", sa.String(length=255), nullable=False)
)
op.add_column("ticket", sa.Column("course", sa.String(length=255), nullable=False))
op.add_column(
"ticket_event", sa.Column("course", sa.String(length=255), nullable=False)
)
op.add_column("user", sa.Column("course", sa.String(length=255), nullable=False))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("user", "course")
op.drop_column("ticket_event", "course")
op.drop_column("ticket", "course")
op.drop_column("location", "course")
op.drop_column("config_entries", "id")
op.drop_column("config_entries", "course")
op.drop_column("assignment", "course")
# ### end Alembic commands ###
<file_sep>/redirect/main.py
from flask import Flask, redirect, request
app = Flask(__name__)
LOOKUP = {
"tutor": "http://pythontutor.com/composingprograms.html",
"book": "https://composingprograms.com",
"python": "https://code.cs61a.org/python",
"scheme": "https://code.cs61a.org/scheme",
"sql": "https://code.cs61a.org/sql",
"ok-help": "https://ok-help.cs61a.org",
"ok": "https://okpy.org",
"staging": "https://solutions.cs61a.org",
}
def lookup(hostname):
"""Gets the URL to redirect to based on a hostname.
:param hostname: redirect link to check
:type hostname: string
:return: a string that represents the url to redirect to
"""
if hostname in LOOKUP:
return LOOKUP[hostname]
prefix = hostname.split(".")[0]
if prefix in LOOKUP:
return LOOKUP[prefix]
return f"https://inst.eecs.berkeley.edu/~cs61a/{prefix}"
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def catch_all(path):
"""Gets the URL to redirect to based on a path if it exists.
:param path: path to return to, doesn't have to exist
:type path: string
:return: a string that represents the url to redirect to
"""
hostname = request.headers["HOST"]
if path:
return redirect(f"{lookup(hostname)}/{path}")
else:
return redirect(lookup(hostname))
if __name__ == "__main__":
app.run()
<file_sep>/sections/server/main.py
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from login import create_login_client
from models import create_models, db
from state import create_state_client
app = Flask(
__name__, static_url_path="", static_folder="static", template_folder="static"
)
if __name__ == "__main__":
app.debug = True
create_state_client(app)
create_login_client(app)
create_models(app)
db.init_app(app)
db.create_all(app=app)
if __name__ == "__main__":
DebugToolbarExtension(app)
app.run(host="127.0.0.1", port=8000, debug=True)
<file_sep>/search/Dockerfile
FROM docker.elastic.co/elasticsearch/elasticsearch:7.5.1
ENV discovery.type=single-node
ENV network.host=127.0.0.1
RUN yum -y install centos-release-scl
RUN yum -y install rh-python36
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
SHELL [ "/usr/bin/scl", "enable", "rh-python36" ]
RUN pip install -r requirements.txt
CMD gunicorn --bind :$PORT --workers 1 --threads 8 main:app --daemon & /usr/local/bin/docker-entrypoint.sh
<file_sep>/cats/src/LeaderboardEntry.js
import React from "react";
import "./LeaderboardEntry.css";
export default function LeaderboardEntry(props) {
return (
<div className="Entry">
<span className="Rank">{props.rank}</span>
<span className="Score">{props.score.toFixed(2)}</span>
<span className="Name">{props.name}</span>
</div>
);
}
<file_sep>/solutions/main.py
from flask import Flask, redirect
from flask_compress import Compress
from static_server.utils import get_bucket, serve_path
from common.oauth_client import (
create_oauth_client,
is_enrolled,
login,
get_user,
AUTHORIZED_ROLES,
)
from common.course_config import get_endpoint
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>", methods=["GET"])
def index(path):
try:
info = get_user()
for p in info["participations"]:
if (
p["course"]["offering"] == get_endpoint("cs61a")
and p["role"] == "student"
):
return redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
except:
pass # don't let the rickroll crash anything else
if not is_enrolled("cs61a", roles=[*AUTHORIZED_ROLES, "lab assistant"]):
return login()
bucket = get_bucket(
{
"cs61a": "website-base",
"solutions2": "website-base",
"solutions": "website-base",
},
"website-base",
)
return serve_path(bucket, "/unreleased/", path, path_404="404/index.html")
Compress(app)
create_oauth_client(app, "cs61a-staging")
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/oh/oh_queue/static/js/components/navbar.js
/* React Components */
let Navbar = ({ state, mode }) => {
var { currentUser } = state;
var myTicket = getMyTicket(state);
if (myTicket && myTicket.group_id) {
myTicket = null;
}
const myGroup = getMyGroup(state);
var { Link } = ReactRouterDOM;
const words = mode.split("_");
if (words.length === 1 && words[0] === "party") {
words[0] = state.config.party_name;
}
const title = words
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(" ");
const partyAsRoot = isPartyRoot(state);
const defaultMode = partyAsRoot ? "party" : "queue";
return (
<nav className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<button
type="button"
className="navbar-toggle collapsed"
data-toggle="collapse"
data-target="#navbar-collapse-section"
>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<Link
className="navbar-brand"
to={"/" + (mode === defaultMode ? "" : mode)}
>
<strong>{window.courseName} |</strong>
{" " + title}
</Link>
</div>
<div className="collapse navbar-collapse" id="navbar-collapse-section">
<ul className="nav navbar-nav navbar-right">
{!!myGroup && (
<li>
<Link to={`/groups/${myGroup.id}/`}>My Group</Link>
</li>
)}
{!!myTicket && (
<li>
<Link to={`/tickets/${myTicket.id}/`}>My Request</Link>
</li>
)}
{currentUser && state.config.party_enabled && (
<li>
<Link to={partyAsRoot ? "/" : "/party"}>
{state.config.party_name}
</Link>
</li>
)}
{currentUser && (
<li>
<Link to={partyAsRoot ? "/queue" : "/"}>Queue</Link>
</li>
)}
{currentUser && JSON.parse(state.config.appointments_open) && (
<li>
<Link to="/appointments">Appointments</Link>
</li>
)}
{currentUser && currentUser.isStaff && (
<li>
<Link to="/activity_log">Activity Log</Link>
</li>
)}
{currentUser && currentUser.isStaff && (
<li>
<Link to="/admin">Admin</Link>
</li>
)}
{currentUser ? (
<li className="dropdown">
<a
href="#"
className="dropdown-toggle"
data-toggle="dropdown"
role="button"
>
{currentUser.name} <span className="caret" />
</a>
<ul className="dropdown-menu">
{state.config.online_active && currentUser.isStaff && (
<li>
<Link to="/online_setup">Online Setup</Link>
</li>
)}
<li>
<Link to={`/user/${currentUser.id}`}>Ticket History</Link>
</li>
<li>
<a href="/logout">Log out</a>
</li>
</ul>
</li>
) : (
<li>
<a href="/login/">Staff Login</a>
</li>
)}
</ul>
</div>
</div>
</nav>
);
};
<file_sep>/ag-master/admin.py
import base64
import time
import pytz
from google.cloud import storage
from typing import List
from flask import request, render_template, abort
from datetime import datetime
from common.rpc.ag_master import create_assignment, trigger_jobs, upload_zip
from common.rpc.auth import get_endpoint
from common.secrets import new_secret
from common.oauth_client import get_user
from models import Assignment, db, Job
from utils import BUCKET, admin_only
TZ = pytz.timezone("America/Los_Angeles")
def create_admin_endpoints(app):
"""Creates various RPC endpoints to manage assignment grading. See the
following:
- :func:`~common.rpc.ag_master.upload_zip`
- :func:`~common.rpc.ag_master.create_assignment`
"""
@upload_zip.bind(app)
@admin_only
def upload_zip_rpc(course, name, file):
file = base64.b64decode(file.encode("ascii"))
bucket = storage.Client().get_bucket(BUCKET)
blob = bucket.blob(f"zips/{get_endpoint(course=course)}/{name}")
blob.upload_from_string(file, content_type="application/zip")
@create_assignment.bind(app)
@admin_only
def create_assignment_rpc(course, name, file, command, batch_size, grading_base):
assignment: Assignment = Assignment.query.filter_by(
name=name, course=course, endpoint=get_endpoint(course=course)
).one_or_none()
if not assignment:
assignment = Assignment(
name=name,
assignment_secret=new_secret(),
course=course,
endpoint=get_endpoint(course=course),
)
db.session.add(assignment)
assignment.file = file
assignment.command = command
assignment.last_modified = int(time.time())
assignment.batch_size = batch_size
assignment.grading_base = grading_base
db.session.commit()
return assignment.assignment_secret
@app.template_filter("dt")
def format_dt(value, format="%b %d, %Y at %I:%M %p %Z"):
if value is None:
return "no date provided"
return datetime.fromtimestamp(int(value), TZ).strftime(format)
@app.route("/<course>")
@admin_only
def get_assignments(course):
endpoint = get_endpoint(course=course)
assignments: List[Assignment] = Assignment.query.filter(
Assignment.endpoint == endpoint
).all()
return render_template(
"assignments.html",
course=course,
assignments=sorted(assignments, key=lambda a: -a.last_modified),
)
@app.route("/<course>/<assignment>/fail_unfinished", methods=["POST"])
@admin_only
def fail_unfinished_jobs(course, assignment):
endpoint = get_endpoint(course=course)
jobs = (
Job.query.join(Assignment)
.filter(Assignment.endpoint == endpoint)
.filter(Assignment.name == assignment)
.filter(Job.status.in_(("queued", "running")))
.all()
)
count = Job.query.filter(
Job.job_secret.in_([job.job_secret for job in jobs])
).update(
{
Job.status: "failed",
Job.finished_at: int(time.time()),
Job.result: f"Marked as failed by {get_user()['email']}.",
},
synchronize_session="fetch",
)
db.session.commit()
return dict(modified=count)
@app.route("/<course>/<assignment>/retrigger_unsuccessful", methods=["POST"])
@admin_only
def retrigger_unsuccessful_jobs(course, assignment):
endpoint = get_endpoint(course=course)
assignment = Assignment.query.filter_by(
name=assignment, endpoint=endpoint
).one()
jobs = (
Job.query.join(Assignment)
.filter(Assignment.endpoint == endpoint)
.filter(Assignment.name == assignment.name)
.filter(Job.status != "finished")
.all()
)
for job in jobs:
job.status = "queued"
db.session.commit()
trigger_jobs(
assignment_id=assignment.assignment_secret,
jobs=[job.job_secret for job in jobs if job.status == "queued"],
)
return dict(modified=len(jobs))
@app.route("/<course>/<assign>")
@admin_only
def get_jobs(course, assign):
endpoint = get_endpoint(course=course)
jobs: List[Job] = (
Job.query.join(Assignment)
.filter(Assignment.endpoint == endpoint)
.filter(Assignment.name == assign)
)
assign = (
Assignment.query.filter(Assignment.name == assign)
.filter(Assignment.endpoint == endpoint)
.one_or_none()
)
if not assign:
abort(404, "Assignment not found.")
queued_at = request.args.get("queued_at", 0)
if queued_at:
jobs = jobs.filter(Job.queued_at == queued_at)
status = request.args.get("status", "all")
if status != "all":
jobs = jobs.filter(Job.status == status)
jobs = jobs.all()
batches = {}
for job in jobs:
if str(job.queued_at) not in batches:
batches[str(job.queued_at)] = {
"jobs": [],
"finished": 0,
"failed": 0,
"running": 0,
"queued": 0,
"completed": 0,
"total": 0,
}
batch = batches[str(job.queued_at)]
details = {
"started_at": job.started_at,
"finished_at": job.finished_at,
"backup": job.backup,
"status": job.status,
"result": job.result,
"id": job.external_job_id,
}
if details["finished_at"]:
if details["status"] == "finished":
batch["finished"] += 1
details["duration"] = details["finished_at"] - details["started_at"]
else:
batch["failed"] += 1
batch["completed"] += 1
elif details["started_at"]:
batch["running"] += 1
else:
batch["queued"] += 1
batch["total"] += 1
batch["progress"] = batch["completed"] / batch["total"]
batch["jobs"].append(details)
return render_template(
"assignment.html",
course=course,
assign=assign,
batches={k: batches[k] for k in sorted(batches, reverse=True)},
queued_at=str(queued_at),
status=status,
)
@app.route("/<course>/job/<id>")
@admin_only
def job_details(course, id):
endpoint = get_endpoint(course=course)
job: Job = (
Job.query.join(Assignment)
.filter(Assignment.endpoint == endpoint)
.filter(Job.external_job_id == id)
.one_or_none()
)
if not job:
abort(404, "Job not found.")
return render_template(
"job.html",
course=course,
backup=job.backup,
status=job.status,
result=job.result,
start=job.started_at,
finish=job.finished_at,
)
<file_sep>/oh/oh_queue/static/js/components/admin_layout.js
class AdminLayout extends React.Component {
render() {
let { Route, Switch } = ReactRouterDOM;
var { location, match, state } = this.props;
const { pathname } = location;
return (
<div className="admin-root">
<Navbar state={state} mode="admin" />
<OfflineIndicator offline={state.offline && state.loaded} />
<br />
<div className="container">
<Messages messages={state.messages} />
<AdminTabs
currentTab={pathname.split("/")[pathname.split("/").length - 1]}
partyAlias={state.config.party_name}
/>
<Switch location={location}>
<Route
exact
path={`${match.path}`}
render={(props) => (
<AdminConfigManager state={state} {...props} />
)}
/>
<Route
path={`${match.path}/tickets`}
render={(props) => (
<AdminTicketsManager state={state} {...props} />
)}
/>
<Route
path={`${match.path}/appointments`}
render={(props) => (
<AdminAppointmentsManager state={state} {...props} />
)}
/>
<Route
path={`${match.path}/assignments`}
render={(props) => (
<AdminAssignmentsManager state={state} {...props} />
)}
/>
<Route
path={`${match.path}/locations`}
render={(props) => (
<AdminLocationsManager state={state} {...props} />
)}
/>
<Route
path={`${match.path}/online`}
render={(props) => (
<AdminOnlineManager state={state} {...props} />
)}
/>
<Route
path={`${match.path}/slack`}
render={(props) => <AdminSlackManager state={state} {...props} />}
/>
<Route
path={`${match.path}/party`}
render={(props) => <AdminPartyManager state={state} {...props} />}
/>
</Switch>
</div>
</div>
);
}
}
<file_sep>/examtool/examtool/api/watermark_decoder.py
from json import dumps, loads
from typing import List
import numpy as np
from tqdm import tqdm
from examtool.api.scramble import scramble
from examtool.api.watermarks import Point, get_watermark_points
def decode_watermark(exam_data, roster, corners: List[Point], bits: List[Point]):
"""
Assume x coord increases from left to right, y increases from top to bottom
"""
observed_points = correct_watermark_bits(corners, bits)
email_distances = [
[email, bit_distance(observed_points, exam_data, email)]
for email, _ in tqdm(roster)
]
email_distances.sort(key=lambda x: x[1])
return email_distances[:10]
def bit_distance(observed_points: List[Point], exam_data, email):
scrambled_exam = scramble(email, loads(dumps(exam_data)))
expected_points = get_watermark_points(scrambled_exam["watermark"]["value"])
assert len(observed_points) >= len(expected_points) / 2, "Too few observed bits"
costs = []
for observed_point in observed_points:
closest = min(expected_points, key=observed_point.dist)
costs.append(
observed_point.dist(closest) ** 2
) # large penalty for misalignment
costs.sort()
del costs[-5:]
return sum(costs) / len(costs)
def correct_watermark_bits(corners: List[Point], bits: List[Point]):
assert len(corners) == 4, "All four corners must be selected"
corners.sort(key=lambda pt: pt.x)
left, right = corners[:2], corners[2:]
left.sort(key=lambda pt: pt.y)
right.sort(key=lambda pt: pt.y)
top_left, bottom_left = left
top_right, bottom_right = right
def compute_basis_map(points):
*base, ref = points
A = np.array(
[
*zip(*base),
[1, 1, 1],
]
)
b = np.array([*ref, 1])
coeffs = np.linalg.solve(A, b)
return A * coeffs
source_transform = compute_basis_map(
[
top_left,
top_right,
bottom_right,
bottom_left,
]
)
target_transform = compute_basis_map(
[Point(5, 5), Point(105, 5), Point(105, 105), Point(5, 105)]
)
full_transform = target_transform @ np.linalg.inv(source_transform)
homogenized_bits = full_transform @ np.vstack(
[np.array(list(zip(*bits))), np.ones(len(bits))]
)
return [
Point(x % 100, y % 100)
for x, y in zip(
homogenized_bits[0] / homogenized_bits[2],
homogenized_bits[1] / homogenized_bits[2],
)
]
<file_sep>/auth/ed_client.py
from flask import request, jsonify, redirect
from ed_api import Ed
from auth_utils import key_secure, course_oauth_secure
from common.db import connect_db
from common.html import html
from common.rpc.auth import perform_ed_action, ed_course_id
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS ed_config (
course_id varchar(256),
test_course_id varchar(256),
student_user varchar(256),
student_pw varchar(256),
staff_user varchar(256),
staff_pw varchar(256),
course varchar(128)
)"""
)
init_db()
def create_ed_client(app):
def ed_help(course):
with connect_db() as db:
ret = db(
"SELECT student_user, staff_user, course_id, test_course_id FROM ed_config WHERE course=%s",
[course],
).fetchone()
student_email, staff_email, course_id, test_course_id = (
ret if ret else [""] * 4
)
return f"""
<h3> Ed Service Accounts </h3>
Student email address: <a href="mailto:{student_email}">{student_email}</a>
<p>
Staff email address: <a href="mailto:{staff_email}">{staff_email}</a>
<p>
Ed course: <a href="https://edstem.org/us/courses/{course_id}">https://edstem.org/us/courses/{course_id}</a>
<p>
Test Ed course: <a href="https://edstem.org/us/courses/{test_course_id}">https://edstem.org/us/courses/{test_course_id}</a>
<p>
Enroll these accounts on the latest course Ed.
<p>
To configure, go to <a href="/ed/{course}/config">Ed Config</a>.
"""
app.help_info.add(ed_help)
@perform_ed_action.bind(app)
@key_secure
def perform_action_ed(action, course, as_staff=False, is_test=None, kwargs=None):
with connect_db() as db:
if as_staff:
user, pw = db(
"SELECT staff_user, staff_pw FROM ed_config WHERE course = (%s)",
[course],
).fetchone()
else:
user, pw = db(
"SELECT student_user, student_pw FROM ed_config WHERE course = (%s)",
[course],
).fetchone()
if is_test:
(course_id,) = db(
"SELECT test_course_id FROM ed_config WHERE course = (%s)",
[course],
).fetchone()
else:
(course_id,) = db(
"SELECT course_id FROM ed_config WHERE course = (%s)", [course]
).fetchone()
e = Ed()
e.user_login(user, pw)
e.network(course_id)
if kwargs is None:
kwargs = {}
try:
return getattr(e, action)(**kwargs)
except Exception as e:
return str(e), 400
# noinspection PyUnusedLocal `staff` exists only for API backwards compatibility
@ed_course_id.bind(app)
@key_secure
def course_id_ed(course, staff=False, test=False, is_test=False):
is_test = test or is_test # test exists for backwards compatibility only
with connect_db() as db:
if is_test:
(course_id,) = db(
"SELECT test_course_id FROM ed_config WHERE course=(%s)",
[course],
).fetchone()
else:
(course_id,) = db(
"SELECT course_id FROM ed_config WHERE course=(%s)", [course]
).fetchone()
return course_id
@app.route("/ed/<course>/config", methods=["GET"])
@course_oauth_secure()
def ed_config(course):
return html(
f"""
Enter account details for Ed service accounts. Leave fields blank to avoid updating them.
Ensure that these accounts are enrolled in the appropriate Eds!
<form action="/ed/{course}/set_config" method="post">
<label>
Ed course ID <br />
<input name="course_id" type="text"> <br />
</label>
<label>
Test Ed course ID <br />
<input name="test_course_id" type="text"> <br />
</label>
<br />
<label>
Student Username <br />
<input name="student_user" type="text"> <br />
</label>
<label>
Student Password <br />
<input name="student_pw" type="password"> <br />
</label>
<br />
<label>
Staff Username <br />
<input name="staff_user" type="text"> <br />
</label>
<label>
Staff Password <br />
<input name="staff_pw" type="password"> <br />
</label>
<label>
<input type="submit">
</form>
"""
)
@app.route("/ed/<course>/set_config", methods=["POST"])
@course_oauth_secure()
def set_ed_config(course):
with connect_db() as db:
ret = db("SELECT * FROM ed_config WHERE course=(%s)", [course]).fetchone()
if ret:
(
course_id,
test_course_id,
student_user,
student_pw,
staff_user,
staff_pw,
_,
) = ret
else:
(
course_id,
test_course_id,
student_user,
student_pw,
staff_user,
staff_pw,
) = [""] * 6
course_id = request.form["course_id"] or course_id
test_course_id = request.form["test_course_id"] or test_course_id
student_user = request.form["student_user"] or student_user
student_pw = request.form["student_pw"] or student_pw
staff_user = request.form["staff_user"] or staff_user
staff_pw = request.form["staff_pw"] or staff_pw
with connect_db() as db:
db("DELETE FROM ed_config WHERE course=(%s)", [course])
db(
"INSERT INTO ed_config VALUES (%s, %s, %s, %s, %s, %s, %s)",
[
course_id,
test_course_id,
student_user,
student_pw,
staff_user,
staff_pw,
course,
],
)
return redirect("/")
<file_sep>/oh/oh_queue/static/js/components/app.js
/* This component holds the global application state, and manages the websocket
* connection. To update the state, call a method on the global "app" object,
* e.g. as
*
* app.addMessage("Something bad happened", "danger");
*
* Because it sits at the root of React heirarchy, any state changes in the app
* will cause the entire app to re-render, so any state changes are reflected
* instantly.
*
* All other React components are "stateless". Many of them are simply pure
* functions that take the state and produce HTML. A few are slightly more
* complicated in that they have to interact with jQuery or the network.
*
* NB: calling app methods inside a render() method will result in an infinite
* loop.
*/
class App extends React.Component {
constructor(props) {
super(props);
this.state = initialState;
this.socket = new Socket();
this.socket.on("connect", () => {
this.setOffline(false);
});
this.socket.on("disconnect", () => this.setOffline(true));
this.socket.on("state", (data, callback) => {
this.updateState(data);
if (callback) {
callback();
}
});
this.socket.on("event", (data) => this.updateTicket(data));
this.socket.on("appointment_event", (data) => this.updateAppointment(data));
this.socket.on("group_event", (data) => this.updateGroup(data));
this.loadTicket = this.loadTicket.bind(this);
this.loadAppointment = this.loadAppointment.bind(this);
this.loadGroup = this.loadGroup.bind(this);
}
refresh() {
this.setState(this.state);
}
setOffline(offline) {
this.state.offline = offline;
this.refresh();
}
updateState(data) {
if (Array.isArray(data.assignments)) {
this.state.assignments = {};
for (var assignment of data.assignments) {
this.state.assignments[assignment.id] = assignment;
}
}
if (Array.isArray(data.locations)) {
this.state.locations = {};
for (var location of data.locations) {
this.state.locations[location.id] = location;
}
}
if (Array.isArray(data.tickets)) {
const ticketIDs = new Set();
for (var ticket of data.tickets) {
setTicket(this.state, ticket);
ticketIDs.add(ticket.id);
}
const oldTicketIDs = this.state.tickets.keys();
for (const oldTicketID of oldTicketIDs) {
if (!ticketIDs.has(oldTicketID)) {
this.state.tickets.delete(oldTicketID);
}
}
}
if (data.hasOwnProperty("config")) {
this.state.config = data.config;
for (const key of [
"daily_appointment_limit",
"weekly_appointment_limit",
"simul_appointment_limit",
"show_okpy_backups",
"slack_notif_long_queue",
"slack_notif_appt_summary",
"slack_notif_missed_appt",
"party_enabled",
"allow_private_party_tickets",
"recommend_appointments",
"only_registered_students",
]) {
this.state.config[key] = JSON.parse(this.state.config[key]);
}
}
if (data.hasOwnProperty("current_user")) {
this.state.currentUser = data.current_user;
}
if (data.hasOwnProperty("appointments")) {
const appointmentIDMap = Object.fromEntries(
this.state.appointments.map((appointment) => [
appointment.id,
appointment,
])
);
data.appointments.forEach((appointment) =>
setAppointment(
this.state,
appointment,
() => this.router.history.push("/appointments/" + appointment.id),
appointmentIDMap
)
);
this.state.appointments = Array.from(data.appointments).sort(
appointmentTimeComparator
);
}
if (data.hasOwnProperty("groups")) {
this.state.groups = Array.from(data.groups).sort((x) => x.id);
}
if (data.hasOwnProperty("presence")) {
this.state.presence = data.presence;
}
this.state.loaded = true;
this.refresh();
}
shouldNotify(ticket, type) {
return isStaff(this.state) && type === "create";
}
updateAppointment({ appointment, type }) {
setAppointment(this.state, appointment, () => {
this.router.history.push("/appointments/" + appointment.id);
});
this.refresh();
}
updateTicket(data) {
setTicket(this.state, data.ticket);
this.refresh();
}
updateGroup(data) {
setGroup(this.state, data.group);
this.refresh();
}
loadTicket(id) {
loadTicket(this.state, id);
this.refresh();
this.socket.emit("load_ticket", id, (ticket) => {
receiveTicket(this.state, id, ticket);
this.refresh();
});
}
loadAppointment(id) {
if (isStaff(this.state)) {
this.socket.emit("load_appointment", id, (appointment) => {
setAppointment(this.state, appointment);
this.refresh();
});
}
}
loadGroup(id) {
if (isStaff(this.state)) {
this.socket.emit("load_group", id, (group) => {
setGroup(this.state, group);
this.refresh();
});
}
}
toggleFilter() {
this.state.filter.enabled = !this.state.filter.enabled;
this.refresh();
}
setFilter(filter) {
filter.enabled = !!this.state.filter.enabled;
this.state.filter = filter;
this.refresh();
}
addMessage(message, category) {
addMessage(this.state, message, category);
this.refresh();
}
clearMessage(id) {
clearMessage(this.state, id);
this.refresh();
}
makeRequest(eventType, request, follow_redirect = false, callback) {
if (typeof request === "function") {
follow_redirect = request;
request = undefined;
}
if (typeof follow_redirect === "function") {
callback = follow_redirect;
follow_redirect = false;
}
let cb = (response) => {
if (response == null) {
if (callback) callback(response);
return;
}
let messages = response.messages || [];
for (var message of messages) {
this.addMessage(message.text, message.category);
}
if (follow_redirect && response.redirect) {
this.router.history.push(response.redirect);
}
if (callback) callback(response);
};
if (request !== undefined) {
this.socket.emit(eventType, request, cb);
} else {
this.socket.emit(eventType, cb);
}
}
render() {
let { BrowserRouter, Route, Switch } = ReactRouterDOM;
let state = this.state;
const Root = isPartyRoot(state) ? Party : Home;
return (
<BrowserRouter ref={(router) => (this.router = router)}>
<div>
<Switch>
<Route
exact
path="/"
render={(props) => <Root state={state} {...props} />}
/>
<Route
exact
path="/party"
render={(props) => <Party state={state} {...props} />}
/>
<Route
exact
path="/queue"
render={(props) => <Home state={state} {...props} />}
/>
<Route
exact
path="/appointments"
render={(props) => <Appointments state={state} {...props} />}
/>
<Route
exact
path="/online_setup"
render={(props) => <StaffOnlineSetup state={state} {...props} />}
/>
<Route
path="/admin"
render={(props) => <AdminLayout state={state} {...props} />}
/>
<Route
path="/activity_log"
render={(props) => <ActivityLogLayout state={state} {...props} />}
/>
<Route
path="/error"
render={(props) => <ErrorView state={state} {...props} />}
/>
<Route
path="/presence"
render={(props) => <PresenceIndicator state={state} {...props} />}
/>
<Route
path="/tickets/:id"
render={(props) => (
<TicketLayout
state={state}
socket={this.socket}
loadTicket={this.loadTicket}
{...props}
/>
)}
/>
<Route
path="/appointments/:id"
render={(props) => (
<AppointmentLayout
state={state}
socket={this.socket}
loadAppointment={this.loadAppointment}
{...props}
/>
)}
/>
<Route
path="/groups/:id"
render={(props) => (
<PartyGroupLayout
state={state}
socket={this.socket}
loadGroup={this.loadGroup}
{...props}
/>
)}
/>
<Route
path="/user/:id"
render={(props) => <UserLayout state={state} {...props} />}
/>
<Route
render={(props) => (
<ErrorView state={state} {...props} message="Page Not Found" />
)}
/>
</Switch>
</div>
</BrowserRouter>
);
}
}
<file_sep>/website/main.py
from flask import Flask
from flask_compress import Compress
from static_server.utils import get_bucket, serve_path
from common.oauth_client import create_oauth_client, is_staff, login
from common.url_for import get_host
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>", methods=["GET"])
def index(path):
if ".pr." in get_host() and not is_staff("cs61a"):
return login()
bucket = get_bucket(
{
"cs61a": "website-base",
"website": "website-base",
"website-server": "website-base",
},
"website-base",
)
return serve_path(bucket, "/released/", path, path_404="404/index.html")
Compress(app)
create_oauth_client(app, "cs61a-staging")
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/exam-write/README.md
# Writing Exams
Essentially, you write your exam in Markdown, with some special commands to
separate questions / question groups and to change settings.
An exam is made up of groups, which each contain questions.
Each question can be:
- Short (code?) answer
- Long (code?) answer
- Multiple choice
- Select all
Groups and questions can contain description text written in Markdown, including
- Images
- Tables
- LaTeX
- Code blocks
Basically anything that works in GitHub Markdown should work here - if it doesn't work,
it should be considered a bug.
The general syntax of this structure looks like:
```
# BEGIN GROUP Section 1
# BEGIN QUESTION
This is a question
# INPUT SHORT_ANSWER
# END QUESTION
# BEGIN QUESTION
This is another question, that's multiple-choice.
# INPUT OPTION Option 1
# INPUT OPTION Option 2
# END QUESTION
# END GROUP
```
## Group Syntax
Each group block is introduced with a
```
# BEGIN GROUP <title> [<points>]
```
statement. The title and point values are both optional. For instance,
```
# BEGIN GROUP Gobears [4]
```
creates a group of questions called `Gobears` worth `4` points. Note that a group title
_must_ be in plain text, _not_ Markdown.
Each group then can have some body text written in Markdown. After this body text comes a
sequence of element blocks. Element blocks are either nested group blocks or question blocks. Then a group is ended with
```
# END GROUP
```
Groups can also contain config statements. If you include the config statement
```
# CONFIG PICK <num>
```
within a group block, then only `num` elements (subgroups or questions) will be randomly selected and presented to the student, rather than the entire group.
If you include the config statement
```
# CONFIG SCRAMBLE
```
within a group block, then its enclosed elements will be randomly re-ordered.
## Question Syntax
Each question block is introduced with
```
# BEGIN QUESTION [<points>]
```
Note that, unlike groups, questions do not have titles. Then you can provide some question
body text, written in Markdown. Then you must provide at least one `INPUT` statement. Then
you can provide `SOLUTION` and `NOTE` blocks.
If you provide text after an input statement, but outside `SOLUTION` or `NOTE` blocks, it will be used as an optional template
for the input field. For instance,
```
# BEGIN QUESTION
Question prompt.
# INPUT SHORT_ANSWER
Template answer.
# BEGIN SOLUTION
Correct answer.
# END SOLUTION
# END QUESTION
```
A random ID is generated for each question whenever the exam is compiled. Student submissions are associated
with a particular question ID. To recompile an exam while keeping the same IDs, to avoid losing this association,
you can set a fixed question ID, using the following syntax:
```
# CONFIG ID <question-id>
```
Then a question is ended with
```
# END QUESTION
```
## Input Syntax
An input statement is written as
```
# INPUT <type> <content>
```
All the input statements within a single question must be of the same `type`.
For multiple-choice questions, you put one input statement for each possible choice,
with `type = OPTION` for select-one, and `type = SELECT` for select-all. The value of the choice
is the `content`, written in Markdown. For instance, you could write
```
# INPUT OPTION An option
```
to provide a single multiple choice option with value `An option`.
To fix an option in place even if `SCRAMBLE_OPTIONS` is enabled, use the syntax
```
# INPUT <type> FIXED <content>
```
and it will not be shuffled.
To indicate a correct option when generating solutions, use the syntax
```
# INPUT <type> CORRECT <content>
```
If `FIXED` and `CORRECT` are used together, use the syntax
```
# INPUT <type> FIXED CORRECT <content>
```
Note that the order matters. Exact duplicate options cannot be used in a single question.
To enter `<content>` that spans multiple lines, use a backslash `\` to indicate that the content continues
on the next line. For instance
```
# INPUT <type> FIXED CORRECT <first_content> \
<more_content> \
<even_more_content>
```
This syntax can be used anywhere to include newlines in a single-line element. To actually include a backslash at the end of a line, write `\\`.
For short / long answer questions, you must provide exactly one input statement within that question.
The `type` can be `SHORT_ANSWER`, `SHORT_CODE_ANSWER`, `LONG_ANSWER`, or `LONG_CODE_ANSWER`. `CODE`
means that the font will be monospaced and tab will work to indent text typed in a `LONG_CODE_ANSWER`.
For short answer questions, the `content` can optionally be a Javascript regular expression that matches valid
inputs, though invalid inputs can still be saved by the user. For long answer questions, the `content`
can optionally be an integer representing the number of lines provided in the input field before the user
has to start scrolling. This also affects the height of the box in the generated PDF in a similar way.
## Solution and Note Syntax
Each solution block looks like
```
# BEGIN SOLUTION
...
# END SOLUTION
```
and each note block looks like
```
# BEGIN NOTE
...
# END NOTE
```
Solutions will be included in the text entry box in the PDF when solutions are generated, and notes will be
included _after_ the text entry box (e.g. as further explanations). Notes can be included for any type of
question, but solutions can only be included for free-response type questions.
## Public Syntax
If you want to have some questions that can be filled out before the exam starts, use a
```
# BEGIN PUBLIC
...
# END PUBLIC
```
block, just like a group block. This will create a question group that is visible before students start the
exam. At most one such block can exist in the exam.
## Scramble Syntax
At the beginning of the exam, before anything else, you can provide config statements, written as
```
# CONFIG <option>
```
The valid choices of `option` are `SCRAMBLE_GROUPS` and `SCRAMBLE_OPTIONS`. These will
randomize the order of groups and questions or multiple choice options respectively for each student. The tool
will de-randomize all of these before grading.
To randomize just groups at a particular depth, write
```
# CONFIG SCRAMBLE_GROUPS <depth> <depth> ...
```
to specify the scrambled depths, which are zero-indexed. Questions are one level lower than their parent group.
To fix a particular group or question in its place while scrambling the others, use the syntax
`# BEGIN GROUP FIXED` or `# BEGIN QUESTION FIXED`. You can still provide titles (for groups) and point values
while using this syntax.
## Define Syntax
It is also possible to replace particular words or variables in an exam for each student, to prevent cheating.
The syntax is
```
# DEFINE <target> <alt1> <alt2> ...
```
This will replace all instances of `target` with one of the alternatives, chosen randomly. This will be scoped to
the block where it is made i.e. if it is written at the top-level, it will replace the `target` everywhere in the document,
if it is written in a group, it will replace the `target` everywhere in the group, etc.
If you have a set of variables which should be replaced with a set of another, and you do not want duplicate choices, you can use this define syntax:
```
# DEFINE MATCH [<target1> <target2> ...] [<alt1> <alt2> ...]
```
This will uniquely set each target with one of the alts. You may have more alts than targets but you **must** have at least as many alts as targets.
If you have a group of variables that should be replaced with one of a list of alternative groups, you can use this define syntax:
```
# DEFINE GROUP (<target1> <target2> ...) (<alt1a> <alt2a> ...) (<alt1b> <alt1b>... ) ...
```
It will either set `target1` to `alt1a` and `target2` to `alt2a`, or `target1` to `alt1b` and `target2` to `alt2b`.
If you wish to set a variable to an integer within a range, you can use this define syntax:
```
# DEFINE RANGE <target> <low> <high>
```
It will set `target` to a random integer in the interval `[low, high)`.
Note that this syntax does not support Markdown - it is a very naive text substitution in the generated HTML, so don't
try anything too fancy with it!
## Inline Groups
To allow for more advanced scrambling, you can use the config statement
```
# CONFIG INLINE
```
within a group to move its child elements into its parent. This is useful when using `# CONFIG PICK`.
As an example, consider the following exam pseudo-structure
```
# BEGIN GROUP
# BEGIN GROUP 1
# Q 1A
# Q 1B
# Q 1C
# CONFIG PICK 2
# CONFIG INLINE
# END GROUP
# BEGIN GROUP 2
# Q 2A
# Q 2B
# Q 2C
# CONFIG PICK 2
# CONFIG INLINE
# END GROUP
# CONFIG PICK 3
# CONFIG SHUFFLE
# END GROUP
```
The tool will pick two questions from group 1 and two from group 2. Then these four questions will be placed in
the enclosing group, replacing their nested groups. Then, out of these four questions, three will be chosen.
Thus, we obtain a single group with three questions in random order, at most two of which can be
from category 1 or category 2.
## Import Syntax
To write exams over multiple files, use the syntax
```
# IMPORT <path>
```
to insert the contents of the file at `<path>` in the current file. The `<path>` is evaluated with respect to the
folder containing the importing file, and may be a relative or absolute path.
## Watermark Syntax
Optionally, you can include a repeating watermark in the background of exams, that is unique to each student.
This can be done using the syntax
```
# CONFIG WATERMARK <brightness>
```
where `brightness` is an integer from 0 to 255 that represents the brightness of the watermark.
<file_sep>/code/src/languages/lark/constants/prompts.js
export const PS1 = "lark> ";
export const PS2 = "....> ";
<file_sep>/code/src/renderer/utils/settingsHandler.js
import { useEffect, useState } from "react";
import { CLAIM_SETTINGS } from "../../common/communicationEnums";
import { send } from "./communication";
export default function useSettings() {
const [settings, setSettings] = useState({});
useEffect(() => {
const [, , detach] = send({ type: CLAIM_SETTINGS }, (raw) =>
setSettings(JSON.parse(raw))
);
return detach;
}, []);
return settings;
}
<file_sep>/oh/migrations/versions/f427b9253aff_add_config_to_restrict_to_registered_.py
"""Add config to restrict to registered students only
Revision ID: f427b9253aff
Revises: <KEY>
Create Date: 2020-12-21 19:02:58.286415
"""
# revision identifiers, used by Alembic.
revision = "f427b9253aff"
down_revision = "<KEY>"
from sqlalchemy import orm
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="only_registered_students",
value="false",
public=True,
course=course[0],
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
<file_sep>/gui_files/common_server.py
import argparse
import json
import socketserver
import ssl
import time
import traceback
import webbrowser
import os
from functools import wraps
from http import HTTPStatus, server
from http.server import HTTPServer
from urllib.error import URLError
from urllib.parse import unquote, urlparse, parse_qs
from urllib.request import Request, urlopen
STATIC_PATHS = {}
PATHS = {}
CONTENT_TYPE_LOOKUP = dict(
html="text/html",
css="text/css",
js="application/javascript",
svg="image/svg+xml",
)
def path_optional(decorator):
def wrapped(func_or_path):
if callable(func_or_path):
return decorator("/" + func_or_path.__name__)(func_or_path)
else:
def actual_decorator(f):
return decorator(func_or_path)(f)
return actual_decorator
return wrapped
def route(path):
"""Register a route handler."""
if callable(path):
return route("/" + path.__name__)(path)
if not path.startswith("/"):
path = "/" + path
def wrap(f):
if "." in path:
STATIC_PATHS[path] = f
else:
PATHS[path] = f
return f
return wrap
class Handler(server.BaseHTTPRequestHandler):
"""HTTP handler."""
def do_GET(self):
try:
self.send_response(HTTPStatus.OK)
parsed_url = urlparse(unquote(self.path))
path = parsed_url.path
query_params = parse_qs(parsed_url.query)
if path in STATIC_PATHS:
out = bytes(STATIC_PATHS[path](**snakify(query_params)), "utf-8")
else:
path = GUI_FOLDER + path[1:]
if "scripts" in path and not path.endswith(".js"):
path += ".js"
if path == GUI_FOLDER:
path = GUI_FOLDER + "index.html"
with open(path, "rb") as f:
out = f.read()
self.send_header("Content-type", CONTENT_TYPE_LOOKUP[path.split(".")[-1]])
self.end_headers()
self.wfile.write(out)
except Exception as e:
print(e)
def do_POST(self):
content_length = int(self.headers["Content-Length"])
raw_data = self.rfile.read(content_length).decode("utf-8")
data = json.loads(raw_data)
path = unquote(self.path)
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", "application/json")
self.end_headers()
try:
result = PATHS[path](**snakify(data))
self.wfile.write(bytes(json.dumps(result), "utf-8"))
except Exception as e:
print(e)
raise
def log_message(self, *args, **kwargs):
pass
class Server:
def __getattr__(self, item):
def f(**kwargs):
if IS_SERVER:
return PATHS["/" + item](**kwargs)
else:
return multiplayer_post(item, kwargs)
return f
Server = Server()
def multiplayer_post(path, data, server_url=None):
"""Post DATA to a multiplayer server PATH and return the response."""
if not server_url:
server_url = DEFAULT_SERVER
data_bytes = bytes(json.dumps(data), encoding="utf-8")
request = Request(server_url + "/" + path, data_bytes, method="POST")
try:
response = urlopen(request, context=ssl._create_unverified_context())
text = response.read().decode("utf-8")
if text.strip():
return json.loads(text)
except Exception as e:
traceback.print_exc()
print(e)
return None
def multiplayer_route(path, server_path=None):
"""Convert a function that takes (data, send) into a route."""
if not server_path:
server_path = path
def wrap(f):
def send(data):
return multiplayer_post(server_path, data)
def routed_fn(data):
response = f(data, send)
return response
route(path)(routed_fn)
return f
return wrap
@path_optional
def forward_to_server(path):
def wrap(f):
@wraps(f)
def wrapped(*args, **kwargs):
if IS_SERVER:
return f(*args, **kwargs)
else:
return multiplayer_post(path, kwargs)
return wrapped
return wrap
def server_only(f):
@wraps(f)
def wrapped(*args, **kwargs):
if IS_SERVER:
return f(*args, **kwargs)
else:
raise Exception("Method not available locally!")
return wrapped
def sendto(f):
def wrapped(data):
return f(**data)
return wrapped
def start_server():
global IS_SERVER
IS_SERVER = True
from flask import Flask, request, jsonify, send_from_directory, Response
app = Flask(__name__, static_url_path="", static_folder="")
for route, handler in PATHS.items():
def wrapped_handler(handler=handler):
return jsonify(handler(**snakify(request.get_json(force=True))))
app.add_url_rule(route, handler.__name__, wrapped_handler, methods=["POST"])
for route, handler in STATIC_PATHS.items():
def wrapped_handler(route=route, handler=handler):
query_params = parse_qs(request.query_string.decode())
return Response(
handler(**snakify(query_params)),
mimetype=CONTENT_TYPE_LOOKUP[route.split(".")[-1]],
)
app.add_url_rule(route, handler.__name__, wrapped_handler, methods=["GET"])
@app.route("/")
def index():
return send_from_directory("", "index.html")
return app
def start_client(port, default_server, gui_folder, standalone):
"""Start web server."""
global DEFAULT_SERVER, GUI_FOLDER, IS_SERVER
DEFAULT_SERVER = default_server
GUI_FOLDER = gui_folder
IS_SERVER = False
socketserver.TCPServer.allow_reuse_address = True
httpd = HTTPServer(("localhost", port), Handler)
if not standalone:
webbrowser.open("http://localhost:" + str(port), new=0, autoraise=True)
httpd.serve_forever()
def snakify(data):
out = {}
for key, val in data.items():
snake_key = []
for x in key:
if x == x.upper():
snake_key += "_"
snake_key += x.lower()
out["".join(snake_key)] = val
return out
@route("/kill")
def kill():
if not IS_SERVER:
print("Exiting GUI")
exit(0)
def start(port, default_server, gui_folder, db_init=None):
global DEFAULT_SERVER
DEFAULT_SERVER = default_server
parser = argparse.ArgumentParser(description="Project GUI Server")
parser.add_argument(
"-s", help="Stand-alone: do not open browser", action="store_true"
)
parser.add_argument("-f", help="Force Flask app", action="store_true")
args, unknown = parser.parse_known_args()
import __main__
if "gunicorn" not in os.environ.get("SERVER_SOFTWARE", "") and not args.f:
request = Request(
"http://127.0.0.1:{}/kill".format(port),
bytes(json.dumps({}), encoding="utf-8"),
method="POST",
)
try:
urlopen(request)
print("Killing existing gui process...")
time.sleep(1)
except URLError:
pass
start_client(port, default_server, gui_folder, args.s)
else:
if db_init:
db_init()
app = start_server()
if args.f:
app.run(port=port, threaded=False, processes=1)
else:
return app
<file_sep>/common/html.py
from flask import current_app
def make_row(content, target, action="Remove"):
"""Create a form with value ``content`` that POSTs to ``target`` when the
button labeled ``action`` is pressed.
:param content: the body of the form
:type content: str - HTML
:param target: the URL to POST to
:type target: str
:param action: the label of the submit button
:type action: str
:return: a string representing the HTML form
"""
return f"""<form style="display: inline" action="{target}" method="post">
{content}
<input type="submit" value="{action}">
</form>"""
def html(out):
"""Adds some styling to the HTML body ``out``.
Specifically, adds a header of the form "61A App Name" and prepends
the SPCSS stylesheet (https://cdn.jsdelivr.net/npm/spcss@0.5.0).
:param out: the original HTML
:type out: str
:return: a string representing the stylized HTML.
"""
if "<h1>" not in out:
if hasattr(current_app, "remote"):
header = current_app.remote.consumer_key
if header.startswith("61a-"):
header = header[3:]
header = header.replace("-", " ").title()
out = f"<h1>61A {header}</h1>" + out
return f"""
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/spcss@0.5.0">
{out}
"""
def error(out):
"""Formats a page representing an error.
Specifically, preformats the error message and adds a red header, with
some instructions on who to contact for help.
:param out: the error message
:type out: str
:return: a string representing the stylized HTML.
"""
report = f"<pre>{out}</pre>" if out else ""
return html(
f"<h2 style='color: red'>Something went wrong.</h2>{report} "
f'If you are on 61A staff, visit <a href="https://logs.cs61a.org">logs.cs61a.org</a> '
f"to see crash logs. Otherwise, please post in the EECS Crossroads Slack for help."
)
<file_sep>/buildserver/main.py
import hmac
from flask import Flask, abort, redirect, request
from github import Github
import api
from common.db import connect_db
from common.html import html
from common.oauth_client import create_oauth_client, get_user, is_staff, login
from common.rpc.auth import is_admin
from common.rpc.buildserver import (
clear_queue,
deploy_prod_app_sync,
get_base_hostname,
trigger_build_sync,
)
from common.rpc.secrets import get_secret, only, validates_master_secret
from common.url_for import url_for
from conf import GITHUB_REPO
from github_utils import BuildStatus, pack, set_pr_comment
from rebuilder import create_rebuilder
from scheduling import report_build_status
from service_management import delete_unused_services
from target_determinator import determine_targets
from worker import land_commit
DO_NOT_BUILD = "DO NOT BUILD"
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
create_oauth_client(app, "61a-buildserver")
create_rebuilder(app)
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS services (
app varchar(128),
pr_number int,
locked boolean,
is_web_service boolean
)
"""
)
db(
"""CREATE TABLE IF NOT EXISTS apps (
app varchar(128),
repo varchar(128),
autobuild boolean
)"""
)
db(
"""CREATE TABLE IF NOT EXISTS mysql_users (
app varchar(128),
mysql_pw varchar(128)
)"""
)
def deploy_prod_app_description(app):
if app == "website-base":
return "<p>Redeploy cs61a.org</p>"
return ""
@app.route("/")
def index():
if not is_staff("cs61a"):
return login()
email = get_user()["email"]
if not is_admin(course="cs61a", email=email):
abort(401)
with connect_db() as db:
apps = db("SELECT app FROM services WHERE pr_number=0", []).fetchall()
pr_apps = db(
"SELECT app, pr_number FROM services WHERE pr_number>0 ORDER BY pr_number DESC",
[],
).fetchall()
return html(
f"""
This service manages the deployment of the 61A website and various apps.
{"".join(f'''
<form action="/deploy_prod_app">
{deploy_prod_app_description(app)}
<input type="submit" name="app" value="{app}" />
</form>
''' for [app] in apps)}
{"".join(f'''
<form action="/trigger_build">
<input type="hidden" name="app" value="{app}" />
<input type="hidden" name="pr_number" value="{pr_number}" />
<input type="submit" value="{app + "-pr" + str(pr_number)}" />
</form>
''' for [app, pr_number] in pr_apps)}
<form action="/delete_unused_services" method="post">
<input type="submit" value="Delete unused services" />
</form>
"""
)
@app.route("/deploy_prod_app")
def deploy_prod_app():
if not is_staff("cs61a"):
return login()
email = get_user()["email"]
if not is_admin(course="cs61a", email=email):
abort(401)
app = request.args["app"]
deploy_prod_app_sync(target_app=app, noreply=True)
return html(f"Deploying <code>{app}</code> from master!")
@deploy_prod_app_sync.bind(app)
@validates_master_secret
def handle_deploy_prod_app_sync(app, is_staging, target_app):
if app != "buildserver" or is_staging:
abort(401)
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
repo = g.get_repo(GITHUB_REPO)
land_commit(
repo.get_branch(repo.default_branch).commit.sha,
repo,
repo,
None,
[f"{target_app}/main.py"],
)
@app.route("/trigger_build")
def trigger_build():
if not is_staff("cs61a"):
return login()
email = get_user()["email"]
if not is_admin(course="cs61a", email=email):
abort(401)
if "app" in request.args:
target = request.args["app"]
else:
target = None
pr_number = int(request.args["pr_number"])
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
repo = g.get_repo(GITHUB_REPO)
pr = repo.get_pull(pr_number)
if DO_NOT_BUILD in [l.name for l in pr.labels]:
return html(
f"PR <code>{pr_number}</code> has a DO NOT BUILD label on it, so it cannot be built. Remove this label to build the PR."
)
trigger_build_sync(pr_number=pr_number, target_app=target, noreply=True)
return html(f"Building PR <code>{pr_number}</code>!")
@trigger_build_sync.bind(app)
@validates_master_secret
def handle_trigger_build_sync(app, is_staging, pr_number, target_app=None):
if app not in ("slack", "buildserver") or is_staging:
raise PermissionError
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
repo = g.get_repo(GITHUB_REPO)
pr = repo.get_pull(pr_number)
if DO_NOT_BUILD in [l.name for l in pr.labels]:
raise PermissionError
land_commit(pr.head.sha, repo, repo, pr, pr.get_files(), target_app=target_app)
@clear_queue.bind(app)
@only("buildserver", allow_staging=True)
def clear_queue(repo: str, pr_number: int):
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
repo = g.get_repo(repo)
pr = repo.get_pull(pr_number) if pr_number else None
land_commit(
pr.head.sha if pr else repo.get_branch(repo.default_branch).commit.sha,
repo,
g.get_repo(GITHUB_REPO),
pr,
[],
dequeue_only=True,
)
@app.route("/delete_unused_services", methods=["POST"])
def delete_unused_services_handler():
if not is_staff("cs61a"):
return login()
email = get_user()["email"]
if not is_admin(course="cs61a", email=email):
return login()
delete_unused_services()
return redirect(url_for("index"))
@app.route("/webhook", methods=["POST"])
def webhook():
if not hmac.compare_digest(
"sha1="
+ hmac.new(
get_secret(secret_name="GITHUB_WEBHOOK_SECRET").encode("ascii"),
request.get_data(),
"sha1",
).hexdigest(),
request.headers["X-Hub-Signature"],
):
abort(401)
payload = request.json
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
if "pusher" in payload and payload["ref"] == "refs/heads/master":
base_repo = g.get_repo(GITHUB_REPO)
repo = g.get_repo(payload["repository"]["id"])
sha = payload["after"]
land_commit(
sha,
repo,
base_repo,
None,
[
file
for commit in payload["commits"]
for file in commit["added"] + commit["modified"] + commit["removed"]
],
)
delete_unused_services()
if "pull_request" in payload:
repo_id = payload["repository"]["id"]
repo = g.get_repo(repo_id)
pr = repo.get_pull(payload["pull_request"]["number"])
if payload["action"] in ("opened", "synchronize", "reopened"):
if repo.full_name != GITHUB_REPO:
land_commit(pr.head.sha, repo, g.get_repo(GITHUB_REPO), pr, [])
else:
for target in determine_targets(repo, pr.get_files()):
report_build_status(
target,
pr.number,
pack(repo.clone_url, pr.head.sha),
BuildStatus.pushed,
None,
None,
private=True,
)
elif payload["action"] == "closed":
set_pr_comment("PR closed, shutting down PR builds...", pr)
delete_unused_services(pr.number)
set_pr_comment("All PR builds shut down.", pr)
return ""
@get_base_hostname.bind(app)
@only("domains", allow_staging=True)
def get_base_hostname(target_app):
return api.get_base_hostname(target_app)
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8080, debug=True, threaded=False)
<file_sep>/examtool/examtool/cli/loginas.py
import webbrowser
import click
from examtool.cli.utils import exam_name_option
@click.command()
@exam_name_option
@click.option(
"--email", help="The email address of the student to impersonate.", prompt=True
)
def loginas(exam, email):
"""
Login to examtool as a student.
"""
webbrowser.open(f"https://exam.cs61a.org/{exam}#loginas={email}")
if __name__ == "__main__":
loginas()
<file_sep>/howamidoing/src/Row.js
import React from "react";
import "./Row.css";
import ScoreEntry from "./ScoreEntry.js";
function formatScore(score, places = 2) {
if (Number.isNaN(parseFloat(score))) {
return score;
}
return Number.parseFloat(score).toFixed(places);
}
export default function Row(props) {
let className = "Row";
if (props.collapsed) {
className += " closed";
}
if (props.childrenCollapsed !== undefined) {
className += " pointable";
}
const score =
Number.isNaN(props.score) || props.future || props.booleanValued ? (
<ScoreEntry
name={props.name}
value={props.plannedScore}
placeholder={props.placeholder}
readOnly={props.readOnly}
onChange={(val) =>
props.booleanValued
? props.onChange(props.name, val * props.maxScore)
: props.onChange(props.name, val)
}
booleanValued={props.booleanValued}
/>
) : (
formatScore(props.score)
);
const maxScore =
!props.booleanValued && props.maxScore && Number.isFinite(props.maxScore)
? ` / ${formatScore(props.maxScore)}`
: "";
const displayedScore = !props.noScore && score;
return (
<tr
onClick={props.onClick}
className={className}
style={{ color: props.hidden ? "gray" : "black" }}
>
<td style={{ paddingLeft: 10 + 40 * props.indent }}>
{props.childrenCollapsed !== undefined ? (
<button
type="button"
className="close closeButton"
aria-label="Close"
>
<span aria-hidden="true">
{props.childrenCollapsed ? "+" : "-"}
</span>
</button>
) : (
false
)}
<div className="collapse show">{props.name}</div>
</td>
<td>
<div className="collapse show">
{displayedScore}
{maxScore}
</div>
</td>
</tr>
);
}
<file_sep>/solutions/requirements.txt
-r static_server/requirements.txt
<file_sep>/howamidoing/src/Dropdown.js
import React from "react";
import "./Dropdown.css";
import Select2 from "react-select2-wrapper";
export default function MyDropdown({ value, children, onChange }) {
return (
<div className="Dropdown">
<Select2
style={{ width: 300 }}
value={value}
onSelect={(e) => onChange(children.indexOf(e.target.value))}
data={children}
/>
</div>
);
}
<file_sep>/paste/main.py
from random import choice
from string import ascii_lowercase
from flask import Flask, Response, abort, redirect, request, escape
from common.db import connect_db
from common.html import html
from common.oauth_client import create_oauth_client, is_staff, login
from common.rpc.paste import get_paste, paste_text
from common.rpc.secrets import validates_master_secret
from common.url_for import url_for
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
app.debug = True
create_oauth_client(app, "61a-paste")
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS pastes (
name varchar(128),
data LONGBLOB,
private boolean
);"""
)
@app.route("/")
def index():
if not is_staff("cs61a"):
return login()
return html(
f"""
Paste text here:
<br/><p>
<form action="{url_for("submit")}" method="POST">
<textarea name="data" rows="30" cols="50" name="comment" ></textarea>
</p>
<input type="submit"></input>
</form>
"""
)
@app.route("/save", methods=["POST"])
def submit():
if not is_staff("cs61a"):
return login()
data = request.form["data"]
return redirect(url_for("load_formatted", name=paste_worker(data)))
@app.route("/<string:name>")
def load_formatted(name):
out = load(name)
if isinstance(out, str):
return html(
f"""<body style="max-width: calc(100% - 10em)">
<h1>61A Paste</h1>
<pre>{escape(out)}</pre>
<a href=\"{url_for('load_raw', name=name)}\">(raw)</a>
</body>"""
)
else:
return out
@app.route("/<string:name>/raw")
def load_raw(name):
return Response(load(name), mimetype="text")
def load(name, skip_auth=False):
"""Loads the paste text for given name
:param name: name associated with the paste text
:type name: str
:param skip_auth: a flag to skip the authentication for the user;
``False`` by default
:type skip_auth: bool
:return: a string representing the paste text for this user
"""
out = None
with connect_db() as db:
data = db(
"SELECT data FROM pastes WHERE name=%s AND private=FALSE",
[name],
).fetchone()
if data:
out = data[0]
if out is None:
if not skip_auth and not is_staff("cs61a"):
return login()
with connect_db() as db:
data = db(
"SELECT data FROM pastes WHERE name=%s",
[name],
).fetchone()
if data:
out = data[0]
if out is None:
abort(404)
elif isinstance(out, bytes):
return out.decode("utf-8")
else:
return out
@paste_text.bind(app)
@validates_master_secret
def paste_text(app, is_staging, data: str, name: str = None, is_private: bool = False):
return paste_worker(data, name, is_private)
def paste_worker(data: str, name: str = None, is_private: bool = False):
"""Creates and saves a new entry in the pastes table representing the given
paste data. If name is not provided, generates a random string as name.
:param data: the paste text
:type data: str
:param name: name of the given user; ``None`` by default
:type name: str
:param is_private: a flag determining whether or not this data is private;
``False`` by default
:type is_private: bool
:return: string representing the name
"""
if name is None:
name = "".join(choice(ascii_lowercase) for _ in range(24))
with connect_db() as db:
db("DELETE FROM pastes WHERE name=%s", [name])
db(
"INSERT INTO pastes (name, data, private) VALUES (%s, %s, %s)",
[name, data, is_private],
)
return name
@get_paste.bind(app)
@validates_master_secret
def get_paste(app, is_staging, name: str):
return load(name, skip_auth=True)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/ag-master/requirements.txt
Flask
gunicorn
flask_sqlalchemy
google-cloud-storage==1.30.0
-r common/requirements.txt
<file_sep>/buildtool/buildtool/utils.py
class BuildException(Exception):
pass
# thrown internally by contexts to exit early, should always be caught
class CacheMiss(Exception):
pass
class MissingDependency(Exception):
def __init__(self, *paths: str):
self.paths = paths
<file_sep>/sicp/sicp/auth.py
import click, requests
from common.rpc.auth_utils import refresh_token, get_token
@click.group("auth")
def auth():
"""
Commands to interface with authentication.
"""
pass
@auth.command()
def whoami():
"""
Get current user information.
"""
r = requests.get(
"https://okpy.org/api/v3/user/?access_token={}".format(get_token())
)
if not r.ok:
print("You don't appear to be logged in.")
data = r.json()["data"]
print(f"Hi {data.get('name')}! You're logged in as {data.get('email')}.")
@auth.command()
@click.option(
"--browser/--no-browser",
default=True,
help="Choose between browser-based and browserless authentication",
)
def login(browser):
"""
Log into Ok and get an access token.
"""
refresh_token(no_browser=not browser)
<file_sep>/gui_files/svg_test.py
import unittest
import gui_files.svg as svg
class TestSVG(unittest.TestCase):
def assert_contains_str(self, str, substr):
self.assertTrue(str.find(substr) > -1, "%s does not contain %s" % (str, substr))
def test_create_graphic(self):
graphic = svg.create_graphic(200, 300)
self.assertEqual(
str(graphic),
"""<svg width="200" height="300" xmlns="http://www.w3.org/2000/svg"></svg>""",
)
def test_draw_rect(self):
graphic = svg.create_graphic(200, 300)
svg.draw_rect(graphic, 10, 20, 30, 40)
self.assert_contains_str(
str(graphic),
"""<rect x="10" y="20" width="30" height="40" stroke="black" fill="black" />""",
)
def test_draw_circle(self):
graphic = svg.create_graphic(200, 300)
svg.draw_circle(graphic, 10, 20, 30)
self.assert_contains_str(
str(graphic),
"""<circle cx="10" cy="20" r="30" stroke="black" fill="black" />""",
)
def test_draw_line(self):
graphic = svg.create_graphic(200, 300)
svg.draw_line(graphic, 10, 20, 30, 40)
self.assert_contains_str(
str(graphic), """<line x1="10" y1="20" x2="30" y2="40" stroke="black" />"""
)
def test_draw_triangle(self):
graphic = svg.create_graphic(200, 300)
svg.draw_triangle(graphic, 10, 20, 15, 150, 150, 150)
self.assert_contains_str(
str(graphic),
"""<polygon points="10,20 15,150 150,150" stroke="black" fill="black"/>""",
)
def test_write_text(self):
graphic = svg.create_graphic(200, 300)
svg.write_text(graphic, 10, 20, "Turn over")
self.assert_contains_str(
str(graphic),
"""<text x="10" y="20" stroke="black" fill="black" font-size="medium" font-family="serif">Turn over</text>""",
)
def test_write_text_font(self):
graphic = svg.create_graphic(200, 300)
svg.write_text(
graphic, 10, 20, "Turn over", font_size="20", font_family="sans-serif"
)
self.assert_contains_str(
str(graphic),
"""<text x="10" y="20" stroke="black" fill="black" font-size="20" font-family="sans-serif">Turn over</text>""",
)
def test_stroke_fill(self):
graphic = svg.create_graphic(200, 300)
svg.draw_rect(graphic, 10, 20, 30, 40, "pink", "blue")
self.assert_contains_str(
str(graphic),
"""<rect x="10" y="20" width="30" height="40" stroke="pink" fill="blue" />""",
)
if __name__ == "__main__":
unittest.main()
<file_sep>/piazzaoncall/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
certifi==2020.6.20
chardet==3.0.4
gunicorn==20.0.4
idna==2.10
numpy==1.19.1
python-dateutil==2.8.1
pytz==2020.1
schedule==0.6.0
six==1.15.0
urllib3==1.25.10
-r common/requirements.txt
<file_sep>/ok-help/src/App.js
import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import "./App.css";
import GeneratedCommand from "./GeneratedCommand.js";
import CommandOptions from "./CommandOptions.js";
import OPTIONS from "./schema.js";
function App() {
const [activeIndex, setActiveIndex] = useState(null);
const [selectedOptions, setSelectedOptions] = useState(
OPTIONS.map(() => ({}))
);
return (
<div className="App container">
<div className="row">
<div className="col">
<br />
<h1 className="display-4">
<strong>okpy</strong> Command Generator
</h1>
</div>
</div>
<GeneratedCommand
options={OPTIONS[activeIndex]}
selectedArgs={selectedOptions[activeIndex]}
/>
<CommandOptions
options={OPTIONS}
activeIndex={activeIndex}
setActiveIndex={setActiveIndex}
selectedOptions={selectedOptions}
setSelectedOptions={setSelectedOptions}
/>
</div>
);
}
export default App;
<file_sep>/oh/migrations/prev_versions/7141eb5952ee_add_ticket_message.py
"""add ticket message
Revision ID: 7141eb5952ee
Revises: e330a9be55f8
Create Date: 2020-03-02 18:02:22.699824
"""
# revision identifiers, used by Alembic.
revision = "7141eb5952ee"
down_revision = "e330a9be55f8"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from sqlalchemy import orm
from oh_queue.models import *
def upgrade():
pass
def downgrade():
pass
<file_sep>/buildserver/conf.py
GITHUB_REPO = "Cal-CS-61A-Staff/cs61a-apps"
PROJECT_ID = "cs61a-140900"
DB_SHORT_INSTANCE_NAME = "cs61a-apps-us-west1"
DB_INSTANCE_NAME = f"{PROJECT_ID}:us-west2:{DB_SHORT_INSTANCE_NAME}"
DB_IP_ADDRESS = "192.168.127.12"
STATIC_SERVER = "static-server"
<file_sep>/oh/oh_queue/static/js/components/update_assignment_box.js
function UpdateAssignmentBox({
state,
elem,
onSubmit,
}: {
state: State,
elem: Group | Ticket,
onSubmit: ({ assignment_id: number, question: string }) => void,
}) {
const { assignments } = state;
let filteredAssignments = Object.values(assignments)
.filter((assignment) => assignment.visible)
.sort((a, b) => a.name.localeCompare(b.name));
const [assignment_id, setAssignment] = React.useState(elem.assignment_id);
const [question, setQuestion] = React.useState(elem.question);
return (
<div className="request-form form-group form-group-lg">
<div className="input-group">
<SelectPicker
options={filteredAssignments}
value={assignment_id}
onChange={(e) => setAssignment(parseInt(e.target.value))}
className="selectpicker form-control form-left"
data-live-search="true"
data-size="8"
data-width="60%"
data-style="btn-lg btn-default"
id="assignment_id"
name="assignment_id"
title="Assignment"
required
/>
<input
className="form-control form-right"
type="text"
id="question"
name="question"
title="Question"
placeholder="Question"
value={question}
onChange={(e) => setQuestion(e.target.value)}
/>
</div>
{assignment_id !== elem.assignment_id || question !== elem.question ? (
<button
onClick={() => onSubmit({ assignment_id, question })}
className="description-button btn btn-default btn-lg btn-block"
>
{" "}
Update Assignment{" "}
</button>
) : null}
</div>
);
}
<file_sep>/oh/oh_queue/views.py
import datetime
import functools
import random
import time
from operator import or_
from urllib.parse import urljoin, urlparse
from flask import g, jsonify, render_template, request
from flask_login import current_user, login_user
from oh_queue import app, db
from oh_queue.models import (
Appointment,
AppointmentSignup,
AppointmentStatus,
Assignment,
AttendanceStatus,
ChatMessage,
ConfigEntry,
CourseNotificationState,
Group,
GroupAttendance,
GroupAttendanceStatus,
GroupStatus,
Location,
Ticket,
TicketEvent,
TicketEventType,
TicketStatus,
User,
active_statuses,
get_current_time,
)
from oh_queue.slack import send_appointment_summary
from oh_queue.reminders import send_appointment_reminder
from sqlalchemy import desc, func
from sqlalchemy.orm import joinedload
from common.course_config import (
format_coursecode,
get_course,
get_course_id,
get_domain,
)
from common.rpc.auth import post_slack_message, read_spreadsheet, validate_secret
from common.url_for import url_for
def user_json(user):
return {
"id": user.id,
"email": user.email,
"name": user.name,
"shortName": user.short_name,
"isStaff": user.is_staff,
"call_url": user.call_url,
"doc_url": user.doc_url,
}
def student_json(user):
"""Only send student information to staff."""
can_see_details = current_user.is_authenticated and (
current_user.is_staff or user.id == current_user.id
)
if not can_see_details:
return None
return user_json(user)
def message_json(message: ChatMessage):
return {
"user": user_json(message.user),
"body": message.body,
"created": message.created.isoformat(),
}
def ticket_json(ticket):
group = ticket.group
return {
"id": ticket.id,
"status": ticket.status.name,
"user": user_json(ticket.user) if group else student_json(ticket.user),
"created": ticket.created.isoformat(),
"sort_key": ticket.sort_key.isoformat(),
"rerequest_threshold": ticket.rerequest_threshold
and ticket.rerequest_threshold.isoformat(),
"hold_time": ticket.hold_time and ticket.hold_time.isoformat(),
"rerequest_time": ticket.rerequest_time and ticket.rerequest_time.isoformat(),
"updated": ticket.updated and ticket.updated.isoformat(),
"location_id": ticket.location_id,
"assignment_id": ticket.assignment_id,
"description": ticket.description,
"question": ticket.question,
"helper": ticket.helper and user_json(ticket.helper),
"call_url": ticket.call_url,
"doc_url": ticket.doc_url,
"group_id": group.id if group else None,
"messages": [message_json(message) for message in ticket.messages],
}
def assignment_json(assignment):
return {"id": assignment.id, "name": assignment.name, "visible": assignment.visible}
def location_json(location):
return {
"id": location.id,
"name": location.name,
"visible": location.visible,
"online": location.online,
"link": location.link,
}
def get_online_location():
online_location = Location.query.filter_by(
course=get_course(), name="Online"
).one_or_none()
online_visible = (
ConfigEntry.query.filter_by(key="online_active", course=get_course())
.one()
.value
== "true"
)
if online_location is None:
online_location = Location(
name="Online",
visible=online_visible,
course=get_course(),
online=True,
link="",
)
db.session.add(online_location)
db.session.commit()
else:
online_location.visible = online_visible
db.session.commit()
return online_location
def config_json():
config = {}
for config_entry in ConfigEntry.query.filter_by(course=get_course()).all():
if config_entry.public:
config[config_entry.key] = config_entry.value
config["okpy_endpoint_id"] = get_course_id()
return config
def appointments_json(appointment: Appointment):
return {
"id": appointment.id,
"start_time": appointment.start_time.isoformat(),
"duration": appointment.duration.total_seconds(),
"signups": [signup_json(signup) for signup in appointment.signups],
"capacity": appointment.capacity,
"location_id": appointment.location_id,
"helper": appointment.helper and user_json(appointment.helper),
"status": appointment.status.name,
"description": appointment.description,
"messages": [message_json(message) for message in appointment.messages],
}
def signup_json(signup: AppointmentSignup):
return {
"id": signup.id,
"assignment_id": signup.assignment_id,
"user": user_json(signup.user), # TODO: This should be private!
"question": signup.question,
"description": signup.description,
"attendance_status": signup.attendance_status.name,
}
def group_json(group: Group):
return {
"id": group.id,
"created": group.created.isoformat(),
"attendees": [
group_attendance_json(attendance)
for attendance in group.attendees
if attendance.group_attendance_status == GroupAttendanceStatus.present
],
"location_id": group.location_id,
"ticket_id": group.ticket_id,
"assignment_id": group.assignment_id,
"question": group.question,
"description": group.description,
"group_status": group.group_status.name,
"call_url": group.call_url,
"doc_url": group.doc_url,
"messages": [message_json(message) for message in group.messages],
}
def group_attendance_json(attendance: GroupAttendance):
return {
"id": attendance.id,
"group_id": attendance.group_id,
"group_attendance_status": attendance.group_attendance_status.name,
"user": user_json(attendance.user),
}
def add_response(event, payload):
g.response_buffer.append([event, payload])
def emit_event(ticket, event_type):
ticket_event = TicketEvent(
event_type=event_type, ticket=ticket, user=current_user, course=get_course()
)
db.session.add(ticket_event)
db.session.commit()
add_response("event", {"type": event_type.name, "ticket": ticket_json(ticket)})
def emit_appointment_event(appointment, event_type):
# TODO: log to db
add_response(
"appointment_event",
{"type": event_type, "appointment": appointments_json(appointment)},
)
def emit_group_event(group, event_type):
add_response("group_event", {"type": event_type, "group": group_json(group)})
def emit_state(attrs, entity=None):
state = {}
if "tickets" in attrs:
tickets = (
Ticket.query.filter(
Ticket.status.in_(active_statuses), Ticket.course == get_course()
)
.options(joinedload(Ticket.user, innerjoin=True))
.options(joinedload(Ticket.helper))
.options(joinedload(Ticket.group))
.all()
)
if entity not in tickets and isinstance(entity, Ticket):
if has_ticket_access(entity):
tickets.append(entity)
state["tickets"] = [ticket_json(ticket) for ticket in tickets]
if "assignments" in attrs:
assignments = Assignment.query.filter_by(course=get_course()).all()
state["assignments"] = [
assignment_json(assignment) for assignment in assignments
]
if "locations" in attrs:
locations = Location.query.filter(
Location.course == get_course(), Location.name != "Online"
).all()
state["locations"] = [location_json(location) for location in locations]
state["locations"].append(location_json(get_online_location()))
if "config" in attrs:
state["config"] = config_json()
if "appointments" in attrs:
appointments = (
Appointment.query.filter(
Appointment.status != AppointmentStatus.resolved,
Appointment.course == get_course(),
)
.order_by(Appointment.id)
.options(joinedload(Appointment.helper))
.options(
joinedload(Appointment.signups).joinedload(
AppointmentSignup.user, innerjoin=True
)
)
.all()
)
if entity not in appointments and isinstance(entity, Appointment):
if current_user.is_staff or current_user.id in [
signup.user.id for signup in entity.signups
]:
appointments.append(entity)
state["appointments"] = [
appointments_json(appointment) for appointment in appointments
]
if "groups" in attrs:
groups = Group.query.filter(
Group.group_status == GroupStatus.active, Group.course == get_course()
).all()
if entity not in groups and isinstance(entity, Group):
if has_group_access(entity):
groups.append(entity)
state["groups"] = [group_json(group) for group in groups]
if "current_user" in attrs:
state["current_user"] = student_json(current_user)
if "presence" in attrs:
out = dict(
students=User.query.filter(
User.heartbeat_time
> datetime.datetime.utcnow() - datetime.timedelta(seconds=30),
User.course == get_course(),
User.is_staff == False,
).count()
)
active_staff = {
(t.helper.email, t.helper.name)
for t in Ticket.query.filter(
Ticket.status.in_(active_statuses),
Ticket.helper != None,
Ticket.course == get_course(),
).all()
}
active_staff |= {
(user.email, user.name)
for user in User.query.filter(
User.heartbeat_time
> datetime.datetime.utcnow() - datetime.timedelta(seconds=30),
User.course == get_course(),
User.is_staff == True,
).all()
}
out["staff"] = len(active_staff)
out["staff_list"] = list(active_staff)
state["presence"] = out
add_response("state", state)
def init_config():
db.session.add(
ConfigEntry(
key="welcome",
value="Welcome to the OH Queue!",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(key="is_queue_open", value="true", public=True, course=get_course())
)
db.session.add(
ConfigEntry(
key="description_required", value="false", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="queue_magic_word_mode", value="none", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="queue_magic_word_data", value="", public=False, course=get_course()
)
)
db.session.add(
ConfigEntry(key="juggling_delay", value="5", public=True, course=get_course())
)
db.session.add(
ConfigEntry(key="ticket_prompt", value="", public=True, course=get_course())
)
db.session.add(
ConfigEntry(
key="appointments_open", value="false", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="online_active", value="false", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="students_set_online_link",
value="false",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="students_set_online_doc",
value="false",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="daily_appointment_limit", value="2", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="weekly_appointment_limit", value="5", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="simul_appointment_limit", value="5", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="show_okpy_backups", value="false", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="slack_notif_long_queue",
value="false",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="slack_notif_appt_summary",
value="false",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="slack_notif_missed_appt",
value="false",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="party_enabled", value="false", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="allow_private_party_tickets",
value="true",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="recommend_appointments", value="true", public=True, course=get_course()
)
)
db.session.add(
ConfigEntry(
key="only_registered_students",
value="false",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="party_name",
value="Party",
public=True,
course=get_course(),
)
)
db.session.add(
ConfigEntry(
key="default_description",
value="",
public=True,
course=get_course(),
)
)
db.session.commit()
# We run a React app, so serve index.html on all routes
@app.route("/")
@app.route("/<path:path>")
@app.route("/tickets/<int:ticket_id>/")
@app.route("/groups/<int:group_id>/")
@app.route("/error", endpoint="error")
def index(*args, **kwargs):
check = db.session.query(ConfigEntry).filter_by(course=get_course()).first()
if not check:
init_config()
notif_state = CourseNotificationState.query.filter_by(
course=get_course()
).one_or_none()
if not notif_state:
notif_state = CourseNotificationState(
course=get_course(),
domain=get_domain(),
last_queue_ping=datetime.datetime.now(),
last_appointment_notif=get_current_time(),
)
db.session.add(notif_state)
db.session.commit()
return render_template("index.html", course_name=format_coursecode(get_course()))
@app.before_request
def initialize_response_buffer():
g.response_buffer = []
def api(endpoint):
def decorator(f):
@functools.wraps(f)
def handler():
args = request.json
resp = f() if args == {} else f(args)
return jsonify({"action": resp, "updates": g.response_buffer})
def sudo_handler():
data = request.json
secret = data["secret"]
email = data["email"]
course = data.get("course", None)
args = data.get("args", None)
course = validate_secret(secret=secret, course=course)
user = User.query.filter_by(course=course, email=email).one()
login_user(user)
resp = f() if args is None else f(args)
return jsonify({"action": resp, "updates": g.response_buffer})
app.add_url_rule(
"/api/{}".format(endpoint), f.__name__, handler, methods=["POST"]
)
app.add_url_rule(
"/api/sudo/{}".format(endpoint),
"sudo_" + f.__name__,
sudo_handler,
methods=["POST"],
)
return f
return decorator
def socket_error(message, category="danger", ticket_id=None):
redirect = url_for("index")
if ticket_id is not None:
redirect = url_for("index", ticket_id=ticket_id)
return {"messages": [{"category": category, "text": message}], "redirect": redirect}
def socket_redirect(**kwargs):
from flask import url_for
redirect = url_for("index", **kwargs)
return {"redirect": redirect}
def socket_unauthorized():
return socket_error("You don't have permission to do that")
def logged_in(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
if not current_user.is_authenticated and current_user.course == get_course():
return socket_unauthorized()
return f(*args, **kwds)
return wrapper
def is_staff(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
if not (
current_user.is_authenticated
and current_user.is_staff
and current_user.course == get_course()
):
return socket_unauthorized()
return f(*args, **kwds)
return wrapper
def has_ticket_access(ticket: Ticket):
if not current_user.is_authenticated:
return False
group = ticket.group
if group:
if not (current_user.is_staff or is_member_of(group)):
return False
elif not (current_user.is_staff or ticket.user.id == current_user.id):
return False
return True
def requires_ticket_access(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
data = args[0]
ticket_id = data.get("id")
if not ticket_id:
return socket_error("Invalid ticket ID")
ticket = Ticket.query.filter_by(id=ticket_id, course=get_course()).one_or_none()
if not has_ticket_access(ticket):
return socket_unauthorized()
kwds["ticket"] = ticket
return f(*args, **kwds)
return wrapper
def has_group_access(group: Group):
if not current_user.is_authenticated:
return socket_unauthorized()
if not group:
return False
if not (current_user.is_staff or is_member_of(group)):
return False
return True
def requires_group_access(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
data = args[0]
group_id = data.get("id")
if not group_id:
return socket_error("Invalid group ID")
group = Group.query.filter_by(id=group_id, course=get_course()).one_or_none()
if not has_group_access(group):
return socket_unauthorized()
kwds["group"] = group
return f(*args, **kwds)
return wrapper
@api("connect")
def connect(data=None):
if not current_user.is_authenticated:
pass
current_user.heartbeat_time = datetime.datetime.utcnow()
entity_type = None
if data:
url = data["url"]
path = urlparse(url).path
path = path.strip("/")
parts = path.split("/")
if len(parts) == 2:
if parts[1].isdigit():
entity_type = parts[0]
entity_id = int(parts[1])
if entity_type == "tickets":
entity = Ticket.query.filter_by(course=get_course(), id=entity_id).one_or_none()
elif entity_type == "appointments":
entity = Appointment.query.filter_by(
course=get_course(), id=entity_id
).one_or_none()
elif entity_type == "groups":
entity = Group.query.filter_by(course=get_course(), id=entity_id).one_or_none()
else:
entity = None
emit_state(
[
"tickets",
"appointments",
"assignments",
"groups",
"locations",
"current_user",
"config",
"presence",
],
entity,
)
def get_magic_word(mode=None, data=None, time_offset=0):
if mode is None:
mode = (
ConfigEntry.query.filter_by(
course=get_course(), key="queue_magic_word_mode"
)
.one()
.value
)
if mode == "none":
return None
if data is None:
data = (
ConfigEntry.query.filter_by(
course=get_course(), key="queue_magic_word_data"
)
.one()
.value
)
if mode == "text":
return data
if mode == "timed_numeric":
# We don't need fancy ultra-secure stuff here
# A basic server-side time-based, seeded RNG is enough
# Seed data should be in the form 'a:b:c:d', where:
# a: 8-byte seed (in hexadecimal)
# b: Downsampling interval (in seconds)
# c: Minimum generated number (in unsigned decimal)
# d: Maximum generated number (in unsigned decimal)
data = data.split(":")
# Downsample time to allow for temporal leeway
rand = random.Random()
timestamp = time.time() // int(data[1])
# Seeded RNG
rand.seed("{}.{}".format(timestamp + time_offset, data[0]))
return str(rand.randint(int(data[2]), int(data[3]))).zfill(len(data[3]))
raise Exception("Unrecognized queue magic word mode")
def check_magic_word(magic_word):
mode = (
ConfigEntry.query.filter_by(course=get_course(), key="queue_magic_word_mode")
.one()
.value
)
if mode == "none":
return True
data = (
ConfigEntry.query.filter_by(course=get_course(), key="queue_magic_word_data")
.one()
.value
)
if mode == "timed_numeric":
# Allow for temporal leeway from lagging clients/humans
for offset in (0, -1, 1):
if get_magic_word(mode, data, time_offset=offset) == magic_word:
return True
return False
return get_magic_word(mode, data) == magic_word
@api("refresh_magic_word")
@is_staff
def refresh_magic_word():
return {"magic_word": get_magic_word()}
@api("create")
@logged_in
def create(form):
"""Stores a new ticket to the persistent database, and emits it to all
connected clients.
"""
is_open = (
ConfigEntry.query.filter_by(course=get_course(), key="is_queue_open")
.one()
.value
== "true"
)
party_enabled = (
ConfigEntry.query.filter_by(course=get_course(), key="party_enabled")
.one()
.value
== "true"
)
private_party_tickets_allowed = (
ConfigEntry.query.filter_by(
course=get_course(), key="allow_private_party_tickets"
)
.one()
.value
== "true"
)
if not is_open or (party_enabled and not private_party_tickets_allowed):
return socket_error("The queue is closed", category="warning")
if not check_magic_word(form.get("magic_word")):
return socket_error("Invalid magic_word", category="warning")
my_ticket = Ticket.for_user(current_user)
if my_ticket:
return socket_error(
"You are already on the queue",
category="warning",
ticket_id=my_ticket.ticket_id,
)
assignment_id = form.get("assignment_id")
location_id = form.get("location_id")
question = form.get("question")
description = form.get("description") or (
ConfigEntry.query.filter_by(course=get_course(), key="default_description")
.one()
.value
)
call_link = form.get("call-link", "")
doc_link = form.get("doc-link", "")
location = Location.query.filter_by(
course=get_course(), id=location_id
).one_or_none()
if not location:
return socket_error(
"Unknown location (id: {})".format(location_id), category="warning"
)
call_link = process_call_link(call_link, location)
if doc_link:
doc_link = urljoin("https://", doc_link)
# Create a new ticket and add it to persistent storage
if assignment_id is None or location_id is None or not question:
return socket_error("You must fill out all the fields", category="warning")
assignment = Assignment.query.filter_by(
course=get_course(), id=assignment_id
).one_or_none()
if not assignment:
return socket_error(
"Unknown assignment (id: {})".format(assignment_id), category="warning"
)
ticket = Ticket(
status=TicketStatus.pending,
user=current_user,
assignment=assignment,
location=location,
question=question,
description=description,
course=get_course(),
call_url=call_link,
doc_url=doc_link,
)
db.session.add(ticket)
db.session.commit()
emit_event(ticket, TicketEventType.create)
return socket_redirect(ticket_id=ticket.id)
def get_tickets(ticket_ids):
return Ticket.query.filter(
Ticket.id.in_(ticket_ids), Ticket.course == get_course()
).all()
def get_next_ticket(location=None):
"""Return the user's first assigned but unresolved ticket.
If none exist, return the first pending student re-request.
If none exist, return to the first unassigned ticket.
If a location is passed in, only returns a next ticket from
provided location.
"""
ticket = Ticket.query.filter(
Ticket.helper_id == current_user.id,
Ticket.status == TicketStatus.assigned,
Ticket.course == get_course(),
).first()
if not ticket:
ticket = Ticket.query.filter(
Ticket.status == TicketStatus.rerequested,
Ticket.helper_id == current_user.id,
Ticket.course == get_course(),
).order_by(Ticket.sort_key)
ticket = ticket.first()
if not ticket:
ticket = Ticket.query.filter(
Ticket.status == TicketStatus.rerequested,
Ticket.helper_id == None,
Ticket.course == get_course(),
).order_by(Ticket.sort_key)
ticket = ticket.first()
if not ticket:
ticket = Ticket.query.filter(
Ticket.status == TicketStatus.pending, Ticket.course == get_course()
).order_by(Ticket.sort_key)
if location:
ticket = ticket.filter(Ticket.location == location)
ticket = ticket.first()
if ticket:
return socket_redirect(ticket_id=ticket.id)
else:
return socket_redirect()
@api("next")
@is_staff
def next_ticket(ticket_ids):
return get_next_ticket()
def is_member_of(group):
return any(
attendance.user.id == current_user.id
for attendance in group.attendees
if attendance.group_attendance_status == GroupAttendanceStatus.present
)
@api("delete")
@logged_in
def delete(ticket_ids):
tickets = get_tickets(ticket_ids)
for ticket in tickets:
ticket_group = ticket.group
if not (
current_user.is_staff
or ticket.user.id == current_user.id
or ticket_group
and is_member_of(ticket_group)
):
return socket_unauthorized()
ticket.status = TicketStatus.deleted
emit_event(ticket, TicketEventType.delete)
db.session.commit()
@api("resolve")
@logged_in
def resolve(data):
"""Gets ticket_ids and an optional argument 'local'.
Resolves all ticket_ids. If 'local' is set, then
will only return a next ticket from the same location
where the last ticket was resolved from.
"""
ticket_ids = data.get("ticket_ids")
local = data.get("local", False)
location = None
tickets = get_tickets(ticket_ids)
for ticket in tickets:
if not (current_user.is_staff or ticket.user.id == current_user.id):
return socket_unauthorized()
ticket.status = TicketStatus.resolved
if local:
location = ticket.location
emit_event(ticket, TicketEventType.resolve)
db.session.commit()
return get_next_ticket(location)
@api("juggle")
@is_staff
def juggle(data):
"""
Gets ticket_ids and places them all on the juggle queue for the corresponding staff member
"""
ticket_ids = data.get("ticket_ids")
tickets = get_tickets(ticket_ids)
location = None
for ticket in tickets:
ticket.status = TicketStatus.juggled
ticket.hold_time = datetime.datetime.utcnow()
ticket.rerequest_threshold = ticket.hold_time + datetime.timedelta(
minutes=int(
ConfigEntry.query.filter_by(course=get_course(), key="juggling_delay")
.one()
.value
)
)
location = ticket.location
emit_event(ticket, TicketEventType.juggle)
db.session.commit()
return get_next_ticket(location)
@api("assign")
@is_staff
def assign(ticket_ids):
tickets = get_tickets(ticket_ids)
for ticket in tickets:
ticket.status = TicketStatus.assigned
ticket.helper_id = current_user.id
emit_event(ticket, TicketEventType.assign)
db.session.commit()
@api("return_to")
@is_staff
def return_to(ticket_ids):
tickets = get_tickets(ticket_ids)
for ticket in tickets:
ticket.status = TicketStatus.assigned
ticket.helper_id = current_user.id
emit_event(ticket, TicketEventType.return_to)
db.session.commit()
@api("rerequest")
@logged_in
def rerequest(data):
ticket_ids = data.get("ticket_ids")
tickets = get_tickets(ticket_ids)
for ticket in tickets:
if not ticket.user.id == current_user.id:
return socket_unauthorized()
if ticket.rerequest_threshold > datetime.datetime.utcnow():
return socket_unauthorized()
ticket.status = TicketStatus.rerequested
ticket.rerequest_time = datetime.datetime.utcnow()
emit_event(ticket, TicketEventType.rerequest)
db.session.commit()
@api("cancel_rerequest")
@logged_in
def cancel_rerequest(data):
ticket_ids = data.get("ticket_ids")
tickets = get_tickets(ticket_ids)
for ticket in tickets:
if not ticket.user.id == current_user.id:
return socket_unauthorized()
ticket.status = TicketStatus.juggled
emit_event(ticket, TicketEventType.juggle)
db.session.commit()
@api("release_holds")
@is_staff
def release_holds(data):
ticket_ids = data.get("ticket_ids")
to_me = data.get("to_me")
tickets = get_tickets(ticket_ids)
for ticket in tickets:
if ticket.status in [TicketStatus.juggled, TicketStatus.rerequested]:
ticket.helper_id = current_user.id if to_me else None
emit_event(ticket, TicketEventType.hold_released)
db.session.commit()
return socket_redirect()
@api("unassign")
@is_staff
def unassign(ticket_ids):
tickets = get_tickets(ticket_ids)
for ticket in tickets:
ticket.status = TicketStatus.pending
ticket.helper_id = None
emit_event(ticket, TicketEventType.unassign)
db.session.commit()
@api("shuffle_tickets")
@is_staff
def shuffle_tickets(ticket_ids):
tickets = get_tickets(ticket_ids)
ticket_sort_keys = [ticket.sort_key for ticket in tickets]
random.shuffle(ticket_sort_keys)
for ticket, sort_key in zip(tickets, ticket_sort_keys):
ticket.sort_key = sort_key
emit_event(ticket, TicketEventType.shuffled)
db.session.commit()
@api("load_ticket")
@is_staff
def load_ticket(ticket_id):
if not ticket_id:
return socket_error("Invalid ticket ID")
ticket = Ticket.query.filter_by(course=get_course(), id=ticket_id).one_or_none()
if ticket:
return ticket_json(ticket)
def apply_ticket_update(data, ticket=None):
if not ticket:
ticket_id = data["id"]
ticket = Ticket.query.filter_by(id=ticket_id, course=get_course()).one()
if "description" in data:
ticket.description = data["description"]
if "location_id" in data:
ticket.location = Location.query.filter_by(
course=get_course(), id=data["location_id"]
).one()
if "assignment_id" in data:
ticket.assignment = Assignment.query.filter_by(
course=get_course(), id=data["assignment_id"]
).one()
if "question" in data:
ticket.question = data["question"]
@api("update_ticket")
@requires_ticket_access
def update_ticket(data, ticket):
apply_ticket_update(data, ticket)
db.session.commit()
emit_event(ticket, TicketEventType.update)
return ticket_json(ticket)
@api("update_tickets")
@is_staff
def update_tickets(arr):
ticket_ids = [data["id"] for data in arr]
tickets = Ticket.query.filter(
Ticket.id.in_(ticket_ids), Ticket.course == get_course()
).all()
ticket_dict = {ticket.id: ticket for ticket in tickets}
for data in arr:
apply_ticket_update(data, ticket_dict[data["id"]])
db.session.commit()
return emit_state(["tickets"])
@api("add_assignment")
@is_staff
def add_assignment(data):
name = data["name"]
assignment = Assignment(name=name, course=get_course())
db.session.add(assignment)
db.session.commit()
emit_state(["assignments"])
db.session.refresh(assignment)
return assignment_json(assignment)
@api("update_assignment")
@is_staff
def update_assignment(data):
assignment = Assignment.query.filter_by(course=get_course(), id=data["id"]).one()
if "name" in data:
assignment.name = data["name"]
if "visible" in data:
assignment.visible = data["visible"]
db.session.commit()
emit_state(["assignments"])
return assignment_json(assignment)
@api("add_location")
@is_staff
def add_location(data):
name = data["name"]
if name == "Online":
return
location = Location(name=name, course=get_course(), link="", online=False)
db.session.add(location)
db.session.commit()
emit_state(["locations"])
db.session.refresh(location)
return location_json(location)
@api("update_location")
@is_staff
def update_location(data):
location = Location.query.filter_by(id=data["id"], course=get_course()).one()
if "name" in data:
location.name = data["name"]
if "visible" in data:
location.visible = data["visible"]
if "link" in data:
location.link = data["link"]
if "online" in data:
location.online = data["online"]
if location.link:
location.online = True
location.link = location.link and urljoin("https://", location.link)
if location.name == "Online":
return
db.session.commit()
emit_state(["locations"])
return location_json(location)
@api("update_config")
@is_staff
def update_config(data):
config = {}
if "keys" in data:
config = {k: v for k, v in zip(data["keys"], data["values"]) if v is not None}
elif "key" in data:
config = {data["key"]: data["value"]}
if "queue_magic_word_mode" in config:
if config["queue_magic_word_mode"] == "timed_numeric":
config["queue_magic_word_data"] = (
format(random.randrange(2 ** 64), "x") + ":60:0:9999"
)
for key, value in config.items():
entry = ConfigEntry.query.filter_by(key=key, course=get_course()).one()
entry.value = value
db.session.commit()
emit_state(["config", "locations"])
return config_json()
@api("assign_staff_appointment")
@is_staff
def assign_staff_appointment(appointment_id):
appointment = Appointment.query.filter(
Appointment.id == appointment_id, Appointment.course == get_course()
).one()
appointment.helper_id = current_user.id
db.session.commit()
emit_appointment_event(appointment, "staff_unassigned")
@api("unassign_staff_appointment")
@is_staff
def unassign_staff_appointment(appointment_id):
appointment = Appointment.query.filter(
Appointment.id == appointment_id, Appointment.course == get_course()
).one()
appointment.helper_id = None
db.session.commit()
emit_appointment_event(appointment, "staff_unassigned")
@api("assign_appointment")
@logged_in
def assign_appointment(data):
user_id = current_user.id
if current_user.is_staff:
user = User.query.filter_by(
email=data["email"], course=get_course()
).one_or_none()
if not user:
return socket_error("Email could not be found")
user_id = user.id
else:
user = current_user
old_signup = AppointmentSignup.query.filter_by(
appointment_id=data["appointment_id"], user_id=user_id, course=get_course()
).one_or_none()
appointment = Appointment.query.filter_by(
id=data["appointment_id"], course=get_course()
).one() # type = Appointment
if not current_user.is_staff:
daily_threshold = int(
ConfigEntry.query.filter_by(
key="daily_appointment_limit", course=get_course()
)
.one()
.value
)
weekly_threshold = int(
ConfigEntry.query.filter_by(
key="weekly_appointment_limit", course=get_course()
)
.one()
.value
)
pending_threshold = int(
ConfigEntry.query.filter_by(
key="simul_appointment_limit", course=get_course()
)
.one()
.value
)
start = appointment.start_time.replace(
hour=0, minute=0, second=0, microsecond=0
)
week_start = start - datetime.timedelta(days=appointment.start_time.weekday())
week_end = week_start + datetime.timedelta(days=7)
num_this_week = (
AppointmentSignup.query.join(AppointmentSignup.appointment)
.filter(
week_start < Appointment.start_time,
Appointment.start_time < week_end,
AppointmentSignup.user_id == current_user.id,
AppointmentSignup.attendance_status != AttendanceStatus.excused,
)
.count()
- int(bool(old_signup))
)
if num_this_week >= weekly_threshold:
return socket_error(
"You have already signed up for {} OH slots this week".format(
weekly_threshold
)
)
day_end = start + datetime.timedelta(days=1)
num_today = (
AppointmentSignup.query.join(AppointmentSignup.appointment)
.filter(
start < Appointment.start_time,
Appointment.start_time < day_end,
AppointmentSignup.user_id == current_user.id,
AppointmentSignup.attendance_status != AttendanceStatus.excused,
)
.count()
- int(bool(old_signup))
)
if num_today >= daily_threshold:
return socket_error(
"You have already signed up for {} OH slots for the same day".format(
daily_threshold
)
)
num_pending = (
AppointmentSignup.query.join(AppointmentSignup.appointment)
.filter(
Appointment.status == AppointmentStatus.pending,
AppointmentSignup.user_id == current_user.id,
)
.count()
- int(bool(old_signup))
)
if num_pending >= pending_threshold:
return socket_error(
"You have already signed up for {} OH slots that have not yet occurred.".format(
pending_threshold
)
)
old_attendance = (
old_signup.attendance_status if old_signup else AttendanceStatus.unknown
)
if appointment.status != AppointmentStatus.pending:
return socket_error("Appointment is not pending")
if old_signup:
db.session.delete(old_signup)
db.session.commit()
if (
len(appointment.signups) >= appointment.capacity
and not current_user.is_staff
and not old_signup
):
return socket_error("Appointment is at full capacity")
signup = AppointmentSignup(
appointment_id=data["appointment_id"],
user_id=user_id,
assignment_id=data["assignment_id"],
question=data["question"],
description=data["description"],
attendance_status=old_attendance,
course=get_course(),
)
db.session.add(signup)
db.session.commit()
send_appointment_reminder(signup)
emit_appointment_event(appointment, "student_assigned")
@api("unassign_appointment")
@logged_in
def unassign_appointment(signup_id):
old_signup = AppointmentSignup.query.filter_by(
id=signup_id, course=get_course()
).first()
appointment = old_signup.appointment
if (
not current_user.is_staff
and (not old_signup or old_signup.user_id != current_user.id)
or appointment.status != AppointmentStatus.pending
):
return socket_unauthorized()
db.session.delete(old_signup)
db.session.commit()
emit_appointment_event(appointment, "student_unassigned")
@api("load_appointment")
@is_staff
def load_appointment(appointment_id):
if not appointment_id:
return socket_error("Invalid appointment ID")
appointment = Appointment.query.filter_by(
id=appointment_id, course=get_course()
).one()
if appointment:
return appointments_json(appointment)
@api("set_appointment_status")
@is_staff
def set_appointment_status(data):
appointment_id = data["appointment"]
status = data["status"]
appointment = Appointment.query.filter_by(
id=appointment_id, course=get_course()
).one()
appointment.status = AppointmentStatus[status]
db.session.commit()
emit_appointment_event(appointment, "status_change")
@api("mark_attendance")
@is_staff
def mark_attendance(data):
signup_id = data["signup_id"]
attendance_status = data["status"]
signup = AppointmentSignup.query.filter_by(id=signup_id, course=get_course()).one()
signup.attendance_status = AttendanceStatus[attendance_status]
db.session.commit()
emit_appointment_event(signup.appointment, "attendance_marked")
@api("toggle_visibility")
@is_staff
def toggle_visibility(appointment_id):
appointment = Appointment.query.filter_by(
id=appointment_id, course=get_course()
).one()
if appointment.status == AppointmentStatus.hidden:
appointment.status = AppointmentStatus.pending
elif appointment.status == AppointmentStatus.pending:
appointment.status = AppointmentStatus.hidden
else:
return socket_error(
"Cannot show/hide appointment that is in progress / completed"
)
db.session.commit()
emit_appointment_event(appointment, "visibility_toggled")
@api("delete_appointment")
@is_staff
def delete_appointment(appointment_id):
appointment = Appointment.query.filter_by(
id=appointment_id, course=get_course()
).one()
db.session.delete(appointment)
db.session.commit()
emit_state(["appointments"])
@api("upload_appointments")
@is_staff
def upload_appointments(data):
sheet_url = data["sheetUrl"]
sheet_name = data["sheetName"]
try:
data = read_spreadsheet(course="cs61a", url=sheet_url, sheet_name=sheet_name)
locations = {}
def get_location(name):
if name not in locations:
locations[name] = Location.query.filter_by(
name=name, course=get_course()
).one()
return locations[name]
helpers = {}
def get_helper(email, name):
if not email:
return None
if email not in helpers:
helper = User.query.filter_by(
email=email, course=get_course()
).one_or_none()
if not helper:
helper = User(
name=name, email=email, is_staff=True, course=get_course()
)
db.session.add(helper)
db.session.commit()
helpers[email] = helper
return helpers[email]
header = data[0]
for row in data[1:]:
start_date_raw = row[header.index("Day")]
start_time_raw = row[header.index("Start Time")]
start_time = datetime.datetime.strptime(
start_date_raw + " " + start_time_raw, "%B %d %I:%M %p"
)
start_time = start_time.replace(year=datetime.datetime.now().year)
appointment = Appointment(
start_time=start_time,
duration=datetime.timedelta(
minutes=int(row[header.index("Duration (mins)")])
),
capacity=int(row[header.index("Capacity")]),
location=get_location(row[header.index("Location")]),
status=AppointmentStatus.hidden,
helper=get_helper(
row[header.index("Email")], row[header.index("Name")]
),
course=get_course(),
)
db.session.add(appointment)
db.session.commit()
except Exception as e:
return socket_error("Internal Error:" + str(e))
emit_state(["appointments"])
@api("update_staff_online_setup")
@is_staff
def update_staff_online_setup(data):
if "staff-call-link" in data:
current_user.call_url = data["staff-call-link"] and urljoin(
"https://", data["staff-call-link"]
)
if "staff-doc-link" in data:
current_user.doc_url = data["staff-doc-link"] and urljoin(
"https://", data["staff-doc-link"]
)
db.session.add(current_user)
db.session.commit()
emit_state(["current_user"])
emit_state(["tickets", "appointments"])
@api("send_chat_message")
@logged_in
def send_chat_message(data):
mode = data.get("mode")
event_id = data["id"]
message = ChatMessage(user=current_user, course=get_course(), body=data["content"])
if mode == "appointment":
appointment = Appointment.query.filter_by(
course=get_course(), id=event_id
).one()
if not current_user.is_staff:
for signup in appointment.signups:
if signup.user.id == current_user.id:
break
else:
return socket_unauthorized()
message.appointment = appointment
elif mode == "ticket":
ticket = Ticket.query.filter_by(course=get_course(), id=event_id).one()
if not current_user.is_staff and ticket.user_id != current_user.id:
return socket_unauthorized()
message.ticket = ticket
elif mode == "group":
group = Group.query.filter_by(course=get_course(), id=event_id).one()
if not current_user.is_staff and not is_member_of(group):
return socket_unauthorized()
message.group = group
db.session.add(message)
db.session.commit()
if mode == "appointment":
emit_appointment_event(message.appointment, "message_sent")
elif mode == "ticket":
emit_event(message.ticket, TicketEventType.message_sent)
elif mode == "group":
emit_group_event(message.group, "message_sent")
@api("bulk_appointment_action")
@is_staff
def bulk_appointment_action(data):
action = data["action"]
ids = data.get("ids", None)
if action == "open_all_assigned":
appointments = Appointment.query.filter(
Appointment.course == get_course(),
Appointment.helper_id != None,
Appointment.status == AppointmentStatus.hidden,
)
if ids is not None:
appointments = appointments.filter(Appointment.id.in_(ids))
appointments.update(
{Appointment.status: AppointmentStatus.pending}, synchronize_session=False
)
elif action == "resolve_all_past":
appointments = Appointment.query.filter(
Appointment.course == get_course(),
Appointment.helper_id != None,
Appointment.start_time < get_current_time(),
Appointment.status == AppointmentStatus.pending,
)
if ids is not None:
appointments = appointments.filter(Appointment.id.in_(ids))
appointments = appointments.all()
Appointment.query.filter(
Appointment.id.in_({x.id for x in appointments})
).update(
{Appointment.status: AppointmentStatus.resolved}, synchronize_session=False
)
elif action == "remove_all_unassigned":
appointments = (
Appointment.query.filter(
Appointment.course == get_course(), Appointment.helper_id == None
)
.outerjoin(Appointment.signups)
.group_by(Appointment)
.having(func.count(AppointmentSignup.id) == 0)
)
if ids is not None:
appointments = appointments.filter(Appointment.id.in_(ids))
appointments = appointments.all()
Appointment.query.filter(
Appointment.id.in_({x.id for x in appointments})
).delete(False)
elif action == "resend_reminder_emails":
appointments = Appointment.query.filter(
Appointment.course == get_course(),
Appointment.start_time > get_current_time(),
Appointment.status == AppointmentStatus.pending,
)
if ids is not None:
appointments = appointments.filter(Appointment.id.in_(ids))
for appointment in appointments:
for signup in appointment.signups:
send_appointment_reminder(signup)
db.session.commit()
emit_state(["appointments"])
@api("list_users")
@is_staff
def list_users():
return [user_json(user) for user in User.query.filter_by(course=get_course()).all()]
@api("get_user")
@logged_in
def get_user(user_id):
if user_id != current_user.id and not current_user.is_staff:
return socket_unauthorized()
user = User.query.filter_by(course=get_course(), id=user_id).one()
tickets = (
Ticket.query.filter(
or_(Ticket.user_id == user.id, Ticket.helper_id == user.id),
Ticket.course == get_course(),
)
.order_by(desc(Ticket.created))
.options(joinedload(Ticket.user, innerjoin=True))
.options(joinedload(Ticket.helper))
.options(joinedload(Ticket.group))
.all()
)
appointments = (
Appointment.query.filter(
Appointment.helper_id == user.id, Appointment.course == get_course()
)
.order_by(desc(Appointment.start_time))
.options(joinedload(Appointment.helper))
.options(
joinedload(Appointment.signups).joinedload(
AppointmentSignup.user, innerjoin=True
)
)
.all()
)
signups = (
AppointmentSignup.query.join(AppointmentSignup.appointment)
.filter(
AppointmentSignup.user_id == user.id, Appointment.course == get_course()
)
.options(
joinedload(AppointmentSignup.appointment).options(
joinedload(Appointment.helper)
)
)
.order_by(desc(Appointment.start_time))
.all()
)
return {
"user": user_json(user),
"tickets": [ticket_json(ticket) for ticket in tickets],
"appointments": (
[appointments_json(appointment) for appointment in appointments]
+ [appointments_json(signup.appointment) for signup in signups]
),
}
def apply_appointment_update(data, appointment=None):
if not appointment:
appointment_id = data["id"]
appointment = Appointment.query.filter_by(
id=appointment_id, course=get_course()
).one()
if "description" in data:
appointment.description = data["description"]
if "location_id" in data:
appointment.location = Location.query.filter_by(
course=get_course(), id=data["location_id"]
).one()
if "helper_id" in data:
if data["helper_id"] is None:
appointment.helper = None
else:
appointment.helper = User.query.filter_by(
course=get_course(), id=data["helper_id"]
).one()
@api("update_appointment")
@is_staff
def update_appointment(data):
apply_appointment_update(data)
db.session.commit()
return emit_state(["appointments"])
@api("update_appointments")
@is_staff
def update_appointments(arr):
appointment_ids = [data["id"] for data in arr]
appointments = Appointment.query.filter(
Appointment.id.in_(appointment_ids), Appointment.course == get_course()
).all()
appointment_dict = {appointment.id: appointment for appointment in appointments}
for data in arr:
apply_appointment_update(data, appointment_dict[data["id"]])
db.session.commit()
return emit_state(["appointments"])
@api("test_slack")
@is_staff
def test_slack():
notif_config: CourseNotificationState = CourseNotificationState.query.filter_by(
course=get_course()
).one()
post_slack_message(
message="This is a test message from the OH queue! Your default queue domain is {}. This channel will "
"be used for all future notifications. To change the channel, visit auth.cs61a.org and "
"update the channel associated with `oh-queue`.".format(notif_config.domain),
purpose="oh-queue",
course=get_course(),
)
@api("appointment_summary")
@is_staff
def appointment_summary():
send_appointment_summary(get_course())
def leave_current_groups():
prev_attendance = GroupAttendance.query.filter_by(
user_id=current_user.id, group_attendance_status=GroupAttendanceStatus.present
).one_or_none()
if prev_attendance:
prev_attendance.group_attendance_status = GroupAttendanceStatus.gone
db.session.commit()
other_attendances = GroupAttendance.query.filter_by(
group=prev_attendance.group,
group_attendance_status=GroupAttendanceStatus.present,
).all()
if prev_attendance.group.ticket and (
not other_attendances
or prev_attendance.group.ticket.user_id == current_user.id
):
# delete the ticket if the group is closed or the ticket creator leaves
prev_attendance.group.ticket.status = TicketStatus.deleted
emit_event(prev_attendance.group.ticket, TicketEventType.delete)
if not other_attendances:
prev_attendance.group.group_status = GroupStatus.resolved
db.session.commit()
emit_group_event(prev_attendance.group, "group_closed")
else:
emit_group_event(prev_attendance.group, "group_left")
def process_call_link(link, location):
if link:
if location.link:
if all(x.isdigit() for x in link):
return "Breakout Room " + link
else:
return urljoin("https://", link)
return link
@api("create_group")
@logged_in
def create_group(form):
party_enabled = ConfigEntry.query.filter_by(
course=get_course(), key="party_enabled"
).one()
if party_enabled.value != "true":
return socket_error("Party mode is not enabled.", category="warning")
assignment_id = form.get("assignment_id")
location_id = form.get("location_id")
question = form.get("question")
call_link = form.get("call-link", "")
doc_link = form.get("doc-link", "")
location = Location.query.filter_by(
course=get_course(), id=location_id
).one_or_none()
if not location:
return socket_error(
"Unknown location (id: {})".format(location_id), category="warning"
)
call_link = process_call_link(call_link, location)
if doc_link:
doc_link = urljoin("https://", doc_link)
if assignment_id is None or location_id is None or not question:
return socket_error("You must fill out all the fields", category="warning")
assignment = Assignment.query.filter_by(
course=get_course(), id=assignment_id
).one_or_none()
if not assignment:
return socket_error(
"Unknown assignment (id: {})".format(assignment_id), category="warning"
)
if location.name == "Online" and not call_link:
return socket_error("You must fill out all the fields", category="warning")
leave_current_groups()
group = Group(
group_status=GroupStatus.active,
assignment=assignment,
location=location,
description="Hi! Anyone else want to work on this problem with me?",
question=question,
course=get_course(),
call_url=call_link,
doc_url=doc_link,
)
db.session.add(group)
group_attendance = GroupAttendance(
group=group,
user=current_user,
group_attendance_status=GroupAttendanceStatus.present,
course=get_course(),
)
db.session.add(group_attendance)
db.session.commit()
emit_group_event(group, "group_created")
return socket_redirect(group_id=group.id)
@api("load_group")
@is_staff
def load_group(group_id):
if not group_id:
return socket_error("Invalid group ID")
group = Group.query.filter_by(id=group_id, course=get_course()).one()
if group:
return group_json(group)
@api("join_group")
@logged_in
def join_group(group_id):
group = Group.query.filter_by(
id=group_id, course=get_course(), group_status=GroupStatus.active
).one()
leave_current_groups()
attendance = GroupAttendance(
group=group,
user=current_user,
group_attendance_status=GroupAttendanceStatus.present,
course=get_course(),
)
db.session.add(attendance)
db.session.commit()
emit_group_event(group, "group_joined")
return socket_redirect(group_id=group_id)
@api("leave_group")
@logged_in
def leave_group(group_id):
leave_current_groups()
return socket_redirect()
def apply_group_update(data, group=None):
if not group:
group_id = data["id"]
group = Group.query.filter_by(id=group_id, course=get_course()).one()
if "description" in data:
group.description = data["description"]
if "assignment_id" in data:
group.assignment = Assignment.query.filter_by(
course=get_course(), id=data["assignment_id"]
).one()
if "question" in data:
group.question = data["question"]
if "location_id" in data:
group.location = Location.query.filter_by(
course=get_course(), id=data["location_id"]
).one()
@api("update_group")
@requires_group_access
def update_group(data, group):
apply_group_update(data, group)
db.session.commit()
emit_group_event(group, "update_group")
return group_json(group)
@api("update_groups")
@is_staff
def update_groups(arr):
group_ids = [data["id"] for data in arr]
groups = Group.query.filter(
Group.id.in_(group_ids), Group.course == get_course()
).all()
group_dict = {group.id: group for group in groups}
for data in arr:
apply_group_update(data, group_dict[data["id"]])
db.session.commit()
return emit_state(["groups"])
@api("create_group_ticket")
@requires_group_access
def create_group_ticket(data, group):
is_queue_open = ConfigEntry.query.filter_by(
course=get_course(), key="is_queue_open"
).one()
if is_queue_open.value != "true":
return socket_error("The queue is closed", category="warning")
if (
group.ticket
and group.ticket.status not in [TicketStatus.resolved, TicketStatus.deleted]
or Ticket.for_user(current_user)
):
return socket_error("You are already on the queue", category="warning")
ticket = Ticket(
status=TicketStatus.pending,
user=current_user,
assignment=group.assignment,
location=group.location,
question=group.question,
description="This ticket is associated with a group.",
course=get_course(),
call_url=group.call_url,
doc_url=group.doc_url,
)
db.session.add(ticket)
db.session.commit()
group.ticket = ticket
db.session.commit()
emit_event(ticket, TicketEventType.create)
emit_group_event(group, "group_ticket_created")
@api("delete_group")
@is_staff
def delete_group(group_id):
group = Group.query.filter_by(id=group_id, course=get_course()).one()
delete_group_worker(group, emit=True)
db.session.commit()
def delete_group_worker(group, *, emit):
group.group_status = GroupStatus.resolved
for attendance in group.attendees:
attendance.group_attendance_status = GroupAttendanceStatus.gone
if emit:
emit_group_event(group, "group_closed")
if group.ticket:
group.ticket.status = TicketStatus.deleted
if emit:
emit_event(group.ticket, TicketEventType.delete)
@app.route("/debug")
def debug():
try:
emit_state(
[
"tickets",
"assignments",
"groups",
"locations",
"current_user",
"config",
"appointments",
]
)
except AttributeError:
pass
return "<body></body>"
<file_sep>/oh/oh_queue/static/js/components/appointment_layout.js
const { Link } = ReactRouterDOM;
function AppointmentLayout({ state, match, loadAppointment, socket }) {
const appointmentID = +match.params.id;
if (!getAppointment(state, appointmentID)) {
loadAppointment(appointmentID);
return "loading...";
}
const appointment = getAppointment(state, appointmentID);
const title = appointment.helper
? `${appointment.helper.shortName}'s Section`
: "Unassigned Section";
const suffix = appointment.description && " for " + appointment.description;
$(function () {
$('[data-toggle="tooltip"]').tooltip();
});
const handleStaffSignup = () => {
app.makeRequest("assign_staff_appointment", appointment.id);
};
const handleStaffUnassign = () => {
app.makeRequest("unassign_staff_appointment", appointment.id);
};
const updateAppointment = (status) => () => {
app.makeRequest("set_appointment_status", {
appointment: appointment.id,
status,
});
};
const attendanceDone = appointment.signups.every(
({ attendance_status }) => attendance_status !== "unknown"
);
let actionButton = null;
if (state.currentUser.isStaff) {
if (appointment.status === "resolved") {
actionButton = (
<Link to="/">
<AppointmentLayoutButton color="default" onClick={() => null}>
Return to Queue
</AppointmentLayoutButton>
</Link>
);
} else if (!appointment.helper) {
actionButton = (
<AppointmentLayoutButton color="success" onClick={handleStaffSignup}>
Sign up to help section
</AppointmentLayoutButton>
);
} else if (appointment.helper.id !== state.currentUser.id) {
actionButton = (
<div>
<AppointmentLayoutButton color="warning" onClick={handleStaffSignup}>
Reassign Appointment
</AppointmentLayoutButton>
<AppointmentLayoutButton color="danger" onClick={handleStaffUnassign}>
Unassign Appointment
</AppointmentLayoutButton>
</div>
);
} else if (appointment.status === "pending") {
actionButton = (
<div>
<AppointmentLayoutButton
color="primary"
onClick={updateAppointment("active")}
>
Start Appointment
</AppointmentLayoutButton>
<AppointmentLayoutButton color="danger" onClick={handleStaffUnassign}>
Unassign Appointment
</AppointmentLayoutButton>
</div>
);
} else if (attendanceDone) {
actionButton = (
<div>
<AppointmentLayoutButton
color="danger"
onClick={updateAppointment("resolved")}
>
End Appointment
</AppointmentLayoutButton>
<AppointmentLayoutButton
color="default"
onClick={updateAppointment("pending")}
>
Requeue Appointment
</AppointmentLayoutButton>
</div>
);
} else {
actionButton = (
<div>
<span
className="d-inline-block btn-block"
tabIndex="0"
data-toggle="tooltip"
data-placement="top"
title="You must record attendance before ending appointments."
>
<button
className="btn btn-danger btn-lg btn-block"
disabled
style={{ pointerEvents: "none" }}
>
End Appointment
</button>
</span>
<AppointmentLayoutButton
color="default"
onClick={updateAppointment("pending")}
>
Requeue Appointment
</AppointmentLayoutButton>
</div>
);
}
}
let onlineButtons = null;
if (
state.locations[appointment.location_id].online &&
appointment.status === "active"
) {
const callURL =
state.locations[appointment.location_id].link ||
appointment.helper.call_url;
const callButton = callURL && (
<AppointmentLayoutButton
color="success"
onClick={() => window.open(callURL, "_blank")}
>
Join Call
</AppointmentLayoutButton>
);
const docButton = appointment.helper.doc_url && (
<AppointmentLayoutButton
color="info"
onClick={() => window.open(appointment.helper.doc_url, "_blank")}
>
Open Shared Document
</AppointmentLayoutButton>
);
if (callButton || docButton) {
onlineButtons = (
<React.Fragment>
{callButton}
{docButton}
{actionButton && <hr />}
</React.Fragment>
);
}
}
return (
<div>
<Navbar state={state} mode="appointments" />
<div className="container">
<br />
<h2 className="list-group-item-heading text-center">
{title}
{suffix}
<small className="clearfix">
{formatAppointmentDuration(appointment)} ·{" "}
{state.locations[appointment.location_id].name}
</small>
<p className="ticket-view-text text-center">
{" "}
{appointment.status[0].toUpperCase() +
appointment.status.slice(1)}{" "}
</p>
<hr />
{(onlineButtons || actionButton) && (
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3">
<div className="well">
{onlineButtons}
{actionButton}
</div>
</div>
</div>
)}
</h2>
{state.currentUser.isStaff && !attendanceDone && (
<div className="alert alert-danger" role="alert">
Remember to record attendance!
</div>
)}
<Messages messages={state.messages} />
<div className="card-holder">
{appointment.signups.map((signup) => (
<AppointmentStudentCard
isStaff={state.currentUser.isStaff}
status={appointment.status}
signup={signup}
assignments={state.assignments}
okpyEndpointID={
state.config.show_okpy_backups && state.config.okpy_endpoint_id
}
/>
))}
</div>
<ChatBox
key={appointment.id}
currentUser={state.currentUser}
socket={socket}
id={appointment.id}
messages={appointment.messages}
mode="appointment"
/>
{state.config.ticket_prompt && (
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3 text-center">
<hr />
<ReactMarkdown source={state.config.ticket_prompt} />
</div>
</div>
)}
</div>
</div>
);
}
function AppointmentLayoutButton({ color, children, onClick }) {
return (
<button className={`btn btn-${color} btn-lg btn-block`} onClick={onClick}>
{children}
</button>
);
}
<file_sep>/cats/server/utils.py
"Utility functions for file and string manipulation"
import string
def lines_from_file(path):
"""Return a list of strings, one for each line in a file."""
with open(path, "r") as f:
return [line.strip() for line in f.readlines()]
punctuation_remover = str.maketrans("", "", string.punctuation)
def remove_punctuation(s):
"""Return a string with the same contents as s, but with punctuation removed.
>>> remove_punctuation("It's a lovely day, don't you think?")
'Its a lovely day dont you think'
"""
return s.strip().translate(punctuation_remover)
def lower(s):
"""Return a lowercased version of s."""
return s.lower()
def split(s):
"""Return a list of words contained in s, which are sequences of characters
separated by whitespace (spaces, tabs, etc.).
>>> split("It's a lovely day, don't you think?")
["It's", 'a', 'lovely', 'day,', "don't", 'you', 'think?']
"""
return s.split()
<file_sep>/oh/oh_queue/static/js/components/staff_upcoming_appointment_card.js
function StaffUpcomingAppointmentCard({ appointment, locations }) {
const possessive = appointment.helper ? "Your" : "This";
const descriptionText = appointment.description && (
<React.Fragment>
It will be on the subject of <b>{appointment.description}</b>.
</React.Fragment>
);
const content = (
<React.Fragment>
{possessive} appointment is at{" "}
<b>{locations[appointment.location_id].name}</b>, with a group of{" "}
<b>{appointment.signups.length}</b> students. {descriptionText}
</React.Fragment>
);
const history = ReactRouterDOM.useHistory();
const handleClick = (e) => {
e.preventDefault();
history.push("/appointments/" + appointment.id);
};
const style = {};
if (!appointment.helper) {
style.borderLeft = "5px solid red";
}
if (appointment.status === "active") {
style.borderLeft = "5px solid #337ab7";
}
return (
<div className="panel panel-default" onClick={handleClick} style={style}>
<ul className="list-group">
<a href="#" className="list-group-item">
{!appointment.helper && (
<span className="badge badge-danger">No helper assigned!</span>
)}
{appointment.status === "active" && (
<span className="badge badge-primary">In Progress</span>
)}
<h4 className="list-group-item-heading appointment-card-heading">
{formatAppointmentDate(appointment)}
</h4>
<div className="appointment-card-subheading">
{formatAppointmentDuration(appointment)}
</div>
{content}
</a>
</ul>
</div>
);
}
<file_sep>/hog-contest/README.md
# Hog Contest
This is the leaderboard for the Hog Contest.
## Setup
Install the dependencies in `requirements.txt`. From the `berkeley-cs61a` repo,
copy `src/proj/hog/hog_eval.cpp` into `./main.cpp`. Run `python3 main.py` to
start the Flask app.
<file_sep>/slack/security.py
import hashlib
import hmac
import time
from functools import wraps
from flask import abort, request
from common.oauth_client import get_user, login
from common.rpc.secrets import get_secret
AUTHORIZED_ROLES = ["staff", "instructor", "grader", "lab assistant"]
def slack_signed(route):
@wraps(route)
def wrapped(*args, **kwargs):
data = request.get_data().decode("utf-8")
timestamp = request.headers["X-Slack-Request-Timestamp"]
slack_signature = request.headers["X-Slack-Signature"]
if abs(time.time() - int(timestamp)) > 60 * 5:
abort(403)
basestring = "v0:" + timestamp + ":" + data
my_signature = (
"v0="
+ hmac.new(
get_secret(secret_name="SIGNING_SECRET").encode(),
basestring.encode(),
hashlib.sha256,
).hexdigest()
)
if hmac.compare_digest(my_signature.encode(), slack_signature.encode()):
return route(*args, **kwargs)
else:
abort(403)
return wrapped
def get_staff_endpoints():
try:
ret = get_user()
for course in ret["participations"]:
if course["role"] not in AUTHORIZED_ROLES:
continue
yield course["course"]["offering"]
except Exception as e:
# fail safe!
print(e)
return False
def logged_in(route):
@wraps(route)
def wrapped(*args, **kwargs):
if not list(get_staff_endpoints()):
return login()
return route(*args, **kwargs)
return wrapped
<file_sep>/oh/oh_queue/static/js/components/admin_home.js
class AdminHome extends React.Component {
render() {
return (
<div className="jumbotron blue">
<div className="container">
<section className="page-header">
<div className="row">
<div className="col-md-12">
<h1>{window.courseName} Admin Panel</h1>
<h2>Edit assignments, locations, and more!</h2>
<p>
Found a bug? Want to change something? Talk to us at{" "}
<a href="https://github.com/Cal-CS-61A-Staff/oh-queue">
our GitHub repo
</a>
!
</p>
</div>
</div>
</section>
</div>
</div>
);
}
}
<file_sep>/oh/oh_queue/static/js/components/admin_items_boolean_field.js
function AdminItemsBooleanField({
itemType,
propType,
item,
onText = "Yes",
offText = "No",
}) {
const handleChange = (value) => {
app.makeRequest(`update_${itemType}`, { id: item.id, [propType]: value });
};
return (
<FancyToggle
onText={onText}
offText={offText}
checked={item[propType]}
onChange={handleChange}
/>
);
}
<file_sep>/static-server/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
google-cloud-storage==1.30.0
flask-compress==1.5.0
-r common/requirements.txt
<file_sep>/cats/src/Input.js
import React, { Component } from "react";
import "./Input.css";
import TypedWord from "./TypedWord.js";
export default class Input extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
if (this.inputRef.current) {
this.inputRef.current.focus();
}
}
handleClick = () => {
if (this.inputRef.current) {
this.inputRef.current.focus();
}
};
render() {
const typedWords = this.props.words.map((word, index) => {
const incorrect = this.props.correctWords[index] !== word;
return <TypedWord key={index} word={word} incorrect={incorrect} />;
});
return (
<div className="Input">
And type them below:
<div className="InputBox" onClick={this.handleClick}>
{typedWords}
{this.props.active && (
<InputField
ref={this.inputRef}
active={this.props.active}
onChange={this.props.onChange}
onWordTyped={this.props.onWordTyped}
popPrevWord={this.props.popPrevWord}
/>
)}
</div>
</div>
);
}
}
class InputField extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleKeyDown = (e) => {
if (e.keyCode !== 8) {
return;
}
if (e.target.innerText !== "") {
return;
}
this.setText(this.props.popPrevWord(), false);
e.preventDefault();
this.handleInput(e);
};
handleInput = (e) => {
const value = e.target.innerText;
if (/\s/.test(value)) {
const words = value.split(/\s/);
const newWords = [];
for (let i = 0; i !== words.length - 1; ++i) {
const ok = this.props.onWordTyped(words[i]);
if (!ok) {
newWords.push(words[i]);
}
}
this.setText(newWords.join(" ") + words[words.length - 1]);
} else {
this.props.onChange(value);
}
};
setText = (text, toStart) => {
this.inputRef.current.innerText = text;
// https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442
const range = document.createRange();
range.selectNodeContents(this.inputRef.current);
range.collapse(toStart);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
};
focus() {
this.inputRef.current.focus();
}
render() {
return (
<span
className="InputField"
ref={this.inputRef}
contentEditable={this.props.active}
onInput={this.handleInput}
onKeyDown={this.handleKeyDown}
onPaste={(e) => e.preventDefault()}
/>
);
}
}
<file_sep>/logs/main.py
from html import escape
from json import loads
from flask import Flask, abort
from common.oauth_client import create_oauth_client, get_user, is_staff, login
from common.shell_utils import sh
from common.url_for import url_for
from common.rpc.auth import is_admin
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
app.debug = True
create_oauth_client(app, "61a-logs")
@app.route("/")
def index():
if not is_staff("cs61a"):
return login()
email = get_user()["email"]
if not is_admin(course="cs61a", email=email):
abort(401)
service_list = "\n".join(
f"<p /><a href={url_for('create_secret', service=service)}>{service}</a>"
for service in list_services()
)
return f"""
<h1>Log Viewer</h1>
{service_list}
"""
@app.route("/service/<service>")
def create_secret(service):
if not is_staff("cs61a"):
return login()
email = get_user()["email"]
if not is_admin(course="cs61a", email=email):
abort(401)
if service not in list_services():
abort(404)
out = reversed(
[
entry["timestamp"] + " " + escape(entry["textPayload"])
for entry in loads(
sh(
"gcloud",
"logging",
"read",
f"projects/cs61a-140900/logs/run.googleapis.com AND resource.labels.service_name={service}",
"--limit",
"100",
"--format",
"json",
capture_output=True,
)
)
if "textPayload" in entry
]
)
return "<pre>" + "\n".join(map(str, out)) + "</pre>"
def list_services():
"""Returns the list of services from Google Cloud Run necessary to access app logs
:return: list of services
"""
return [
service["metadata"]["name"]
for service in loads(
sh(
"gcloud",
"run",
"services",
"list",
"--platform",
"managed",
"--region",
"us-west1",
"--format",
"json",
"-q",
capture_output=True,
)
)
]
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/buildtool/buildtool/build_worker.py
import time
import traceback
from collections import defaultdict
from pathlib import Path
from queue import Empty, Queue
from shutil import rmtree
from subprocess import CalledProcessError
from cache import make_cache_fetcher, make_cache_memorize
from colorama import Style
from execution import build
from monitoring import log
from preview_execution import get_deps
from state import BuildState
from utils import BuildException, MissingDependency
from work_queue import enqueue_deps
TIMINGS = defaultdict(int)
def clear_queue(queue: Queue):
while not queue.empty():
try:
queue.get(False)
except Empty:
continue
queue.task_done()
def worker(build_state: BuildState, index: int):
scratch_path = Path(build_state.repo_root).joinpath(Path(f".scratch_{index}"))
if scratch_path.exists():
rmtree(scratch_path, ignore_errors=True)
_, cache_save = make_cache_memorize(build_state.cache_directory)
_, cache_loader = make_cache_fetcher(build_state.cache_directory)
while True:
if build_state.failure is not None:
# every thread needs to clear the queue since otherwise some other thread might still be filling it up
clear_queue(build_state.work_queue)
return # some thread has failed, emergency stop
todo = build_state.work_queue.get()
if todo is None:
return
start_time = time.time()
try:
build_state.status_monitor.update(index, "Parsing: " + str(todo))
log(f"Target {todo} popped from queue by worker {index}")
# only from caches, will never run a subprocess
cache_key, deps, uses_dynamic_deps = get_deps(build_state, todo)
if uses_dynamic_deps:
log("Target", todo, "Uses dynamic deps")
if cache_key is None:
# unable to compute cache_key, potentially because not all deps are ready
log(
f"Target {todo} either has unbuilt dependencies, "
f"or does not have a cached dynamic dependency resolved"
)
deps_ready = not enqueue_deps(
build_state, todo, deps, catch_failure=uses_dynamic_deps
)
if deps_ready:
log("Apparently it is missing an input cache in the impl")
else:
log("Apparently it is waiting on unbuilt dependencies")
else:
log(f"All the dependencies of target {todo} are ready: {deps}")
# if the cache_key is ready, *all* the deps must be ready, not just the discoverable deps!
# unless the cache_key is not actually cached, in which case our inputs() could be wrong, so
# we have to run in the working directory to verify
deps_ready = True
if deps_ready:
done = False
# check if we're already cached!
if cache_key:
if cache_loader(cache_key, todo, build_state.repo_root):
log(f"Target {todo} was loaded from the cache")
done = True
if not done:
# time to execute! but *not* inside the lock
# when we release the lock, stuff may change outside, but
# we don't care since *our* dependencies (so far) are all available
log(f"Target {todo} is not in the cache, rerunning...")
build_state.status_monitor.update(index, "Building: " + str(todo))
try:
# if cache_key is None, we haven't finished evaluating the impl, so we
# don't know all the dependencies it could need. Therefore, we must
# run it in the working directory, so the impl can find the dependencies it needs
# Then, we run it *again*, to verify that the dependencies are accurate
in_sandbox = cache_key is not None and not uses_dynamic_deps
# if the rule uses_dynamic_deps, then it is possible that a ctx.input() call
# in the rule, that was pulled from a cache, will in fact give different outputs
# since some dependency has changed. So it is not safe to run it in a sandbox directory,
# as the dependencies may not all be ready
if not in_sandbox:
log(
f"We don't know the dependencies of {todo}, "
f"so we are running the impl in the root directory to find out!"
)
cache_key = build(
build_state, todo, todo.deps, scratch_path=None
)
# now, if no exception has thrown, all the deps are available to the deps finder
alt_cache_key, deps, _ = get_deps(build_state, todo)
try:
alt_cache_key_2 = build(
build_state,
todo,
deps,
scratch_path=scratch_path,
)
except MissingDependency:
raise BuildException("An internal error has occurred.")
except CalledProcessError as e:
build_state.status_monitor.stop()
print(e.cmd)
print(e)
raise BuildException(
f"The dependencies for target {todo} are not fully specified, "
f"as it failed to build when provided only with them."
)
assert (
cache_key == alt_cache_key == alt_cache_key_2
), "An internal error has occurred"
else:
log(
f"We know all the dependencies of {todo}, so we can run it in a sandbox"
)
build(build_state, todo, deps, scratch_path=scratch_path)
log(f"Target {todo} has been built fully!")
cache_save(cache_key, todo, scratch_path)
done = True
except MissingDependency as d:
log(
f"Target {todo} failed to fully build because of the missing dynamic "
f"dependencies: {d.paths}, requeuing"
)
scheduled = enqueue_deps(build_state, todo, d.paths)
if not scheduled:
# due to race conditions, our dependencies are actually all ready now!
# no one else will enqueue us, so it is safe to enqueue ourselves
build_state.work_queue.put(todo)
build_state.status_monitor.move(total=1)
if scratch_path.exists():
rmtree(scratch_path, ignore_errors=True)
if done:
with build_state.scheduling_lock:
build_state.ready.add(todo)
# no one will ever add us back, since we are in `ready`
build_state.scheduled_but_not_ready.remove(todo)
# now it's time to set up our dependents
# we need to be inside the lock even if we have no dependents, in case
# we *gain* dependents from another thread which could have held the lock!
for dependent in todo.runtime_dependents:
dependent.pending_rule_dependencies.remove(todo)
if not dependent.pending_rule_dependencies:
# this guy is ready to go
build_state.work_queue.put(dependent)
build_state.status_monitor.move(total=1)
# either way, we're done with this task for now
build_state.status_monitor.move(curr=1)
build_state.work_queue.task_done()
# record timing data
run_time = time.time() - start_time
TIMINGS[str(todo)] += run_time
except Exception as e:
if not isinstance(e, BuildException):
suffix = f"\n{Style.RESET_ALL}" + traceback.format_exc()
else:
suffix = ""
build_state.status_monitor.stop()
build_state.failure = BuildException(
f"Error while executing rule {todo}: " + str(e) + suffix
)
build_state.work_queue.task_done()
<file_sep>/ag-master/worker.py
from functools import wraps
from typing import List, Union
import requests
import time
from common.rpc.ag_master import get_submission, handle_output, set_failure
from models import Job, db
from utils import SCORE_ENDPOINT, SUBM_ENDPOINT
def job_transition(*, at: Union[str, List[str]], to: str):
"""Decorates a function by making sure that the relevant job transitions
to a logically forward state when the function is called. This prevents
exploiting job statuses, as it prevents the function from running if the
job is in an invalid state.
:param at: the statuses the job must be in in order for the decorated
function to run
:type at: str, list[str]
:param to: the status the job will be set to once the decorated function
runs
:type to: str
"""
def decorator(func):
@wraps(func)
def handler(*, job_id, **kwargs):
job = Job.query.get(job_id)
if not job:
raise KeyError
if isinstance(at, str):
at_list = [at]
else:
at_list = at
if job.status not in at_list:
raise PermissionError
try:
return func(job=job, **kwargs)
finally:
job.status = to
db.session.commit()
return handler
return decorator
def create_worker_endpoints(app):
"""Creates various RPC endpoints to interface with the worker. See the
following:
- :func:`~common.rpc.ag_master.get_submission`
- :func:`~common.rpc.ag_master.handle_output`
- :func:`~common.rpc.ag_master.set_failure`
"""
@get_submission.bind(app)
@job_transition(at="queued", to="started")
def get_submission_rpc(job):
r = requests.get(
f"{job.assignment.grading_base}{SUBM_ENDPOINT}/{job.backup}",
params=dict(access_token=job.access_token),
)
job.started_at = int(time.time())
db.session.commit()
r.raise_for_status()
return r.json()["data"]
@handle_output.bind(app)
@job_transition(at="started", to="finished")
def handle_output_rpc(output, job):
scores = parse_scores(output)
for score in scores:
score["bid"] = job.backup
requests.post(
job.assignment.grading_base + SCORE_ENDPOINT,
data=score,
params=dict(access_token=job.access_token),
)
job.result = output
job.finished_at = int(time.time())
db.session.commit()
@set_failure.bind(app)
@job_transition(at=["queued", "started"], to="failed")
def set_failure_rpc(job, result):
job.result = result
job.finished_at = int(time.time())
db.session.commit()
def extract_scores(transcript):
"""Extract scores of different types from a grading job's output, starting
from the bottom of the output
:param transcript: the grading output
:type transcript: str
:return: a list of (key, score) pairs
"""
score_lines = []
found_score = False
for line in reversed(transcript.split("\n")):
line = line.strip()
if line.lower() == "score:":
found_score = True
break
if ":" in line:
score_lines.append(line)
if not found_score:
raise ValueError('no scores found; "Score" must appear on a line by ' "itself")
pairs = [l.split(":", 1) for l in reversed(score_lines)]
if len(pairs) == 0:
raise ValueError('no scores found; "Score" must be followed with a ' "colon")
return [(k, float(v)) for k, v in pairs]
def parse_scores(output):
"""Parse a grading job's output for scores or errors
:param output: the grading job's output
:type output: str
:return: a list of score dictionaries of the form
``{score: float, kind: str, message: str}``
"""
all_scores = []
try:
scores = extract_scores(output)
for name, points in scores:
if len(output) > 9000:
output = (
output[:750]
+ "\nTruncated "
+ str(len(output) - 1500)
+ " Characters.\n"
+ output[-750:]
)
all_scores.append(
{"score": float(points), "kind": name, "message": str(output)}
)
except ValueError as e:
message = "Error - Parse: " + str(e) + "Got: \n{}".format(output)
return [{"score": 0.0, "kind": "Error", "message": message}]
return all_scores
<file_sep>/auth/slack_client.py
from flask import redirect, request
from auth_utils import course_oauth_secure, key_secure
from common.db import connect_db
from common.rpc.auth import post_slack_message, slack_workspace_name
from common.rpc.slack import list_channels, post_message
from common.url_for import url_for
from common.html import make_row
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS slack_config (
course varchar(128),
workspace varchar(128)
)"""
)
db(
"""CREATE TABLE IF NOT EXISTS slack_channels (
course varchar(128),
purpose varchar(128),
channel varchar(128),
channel_id varchar(128)
)"""
)
init_db()
def create_slack_client(app):
def slack_help(course):
with connect_db() as db:
workspace = db(
"SELECT workspace FROM slack_config WHERE course=(%s)", [course]
).fetchone()
workspace = workspace[0] if workspace else ""
registered_channels = db(
"SELECT purpose, channel, channel_id FROM slack_channels WHERE course=(%s)",
[course],
).fetchall()
try:
channels = list_channels(course=course)
except:
registration = """
To register Slack channels, first go to
<a href="https://slack.cs61a.org">slack.cs61a.org</a>
to add the bot to your workspace.
"""
else:
channels = [
f"<option value=\"{channel['name']}\">{channel['name']}</option>"
for channel in channels
]
registration = f"""
Register a new Slack channel.
<form action="/slack/{course}/register_channel" method="post">
<input name="purpose" type="text" placeholder="Purpose">
<select name="channel">
{channels}
</select>
<input type="submit">
</form>
"""
registered_channels_list = "<p>".join(
make_row(
f"{purpose} associated with #{channel} (id: {channel_id})",
url_for("remove_channel", course=course, purpose=purpose),
)
for purpose, channel, channel_id in registered_channels
)
return f"""
<h3> Slack Configuration </h3>
<p>
Current workspace: <a href="https://{workspace}.slack.com">{workspace}.slack.com</a>
</p>
{registration}
{registered_channels_list}
</form>
<p>
To configure, go to <a href="/slack/{course}/config">Slack Config</a>.
"""
app.help_info.add(slack_help)
@slack_workspace_name.bind(app)
@key_secure
def workspace_name(course):
with connect_db() as db:
workspace = db(
"SELECT workspace FROM slack_config WHERE course=(%s)", [course]
).fetchone()
if workspace:
return workspace[0]
@app.route("/slack/<course>/config", methods=["GET"])
@course_oauth_secure()
def slack_config(course):
return """
Enter Slack workspace url.
<form action="/slack/{}/set_config" method="post">
<label>
Slack Workspace <br />
<input name="workspace" type="text" placeholder="cs61a.slack.com"> <br />
</label>
<label>
<input type="submit">
</form>
""".format(
course
)
@app.route("/slack/<course>/set_config", methods=["POST"])
@course_oauth_secure()
def set_slack_config(course):
workspace = request.form["workspace"].split(".")[0]
with connect_db() as db:
existing = db(
"SELECT course FROM slack_config WHERE workspace=(%s) AND course <>(%s)",
[workspace, course],
).fetchone()
if existing:
return "{} is already using that workspace.".format(existing)
db("DELETE FROM slack_config WHERE course=(%s)", [course])
db("INSERT INTO slack_config VALUES (%s, %s)", [course, workspace])
return redirect("/")
@app.route("/slack/<course>/register_channel", methods=["POST"])
@course_oauth_secure()
def register_channel(course):
purpose = request.form["purpose"]
channel_name = request.form["channel"]
channel_data = list_channels(course=course)
for channel in channel_data:
if channel["name"] == channel_name:
channel_id = channel["id"]
break
else:
return "Channel not found.", 404
with connect_db() as db:
ret = db(
"SELECT * FROM slack_channels WHERE course = (%s) AND purpose = (%s)",
[course, purpose],
).fetchone()
if ret:
return "Channel with same purpose already registered", 409
db(
"INSERT INTO slack_channels VALUES (%s, %s, %s, %s)",
[course, purpose, channel_name, channel_id],
)
return redirect("/")
@app.route("/slack/<course>/remove_channel", methods=["POST"])
@course_oauth_secure()
def remove_channel(course):
purpose = request.args["purpose"]
with connect_db() as db:
db(
"DELETE FROM slack_channels WHERE course=(%s) AND purpose=(%s)",
[course, purpose],
)
return redirect("/")
@post_slack_message.bind(app)
@key_secure
def handle_post_message(course, message, purpose):
with connect_db() as db:
(channel_id,) = db(
"SELECT channel_id FROM slack_channels WHERE course=(%s) AND purpose=(%s)",
[course, purpose],
).fetchone()
post_message(course=course, message=message, channel=channel_id)
return ""
<file_sep>/sections/server/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
flask_sqlalchemy==2.4.4
flask-login==0.5.0
flask-debugtoolbar==0.11.0
pytz==2020.1
-r common/requirements.txt
<file_sep>/howamidoing/src/FileDropTarget.js
import React from "react";
import "./FileDropTarget.css";
export default function FileDropTarget({ onFileSelect, children }) {
const highlight = (elem) => {
elem.setAttribute("hover", "true");
};
const unHighlight = (elem) => {
elem.setAttribute("hover", "false");
};
const processFilesUploaded = (files) => {
const file = files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => onFileSelect(reader.result);
};
const handleDragEnter = (e) => {
e.preventDefault();
e.stopPropagation();
highlight(e.currentTarget);
};
const handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
highlight(e.currentTarget);
};
const handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
unHighlight(e.currentTarget);
};
const handleDrop = (e) => {
e.preventDefault();
e.stopPropagation();
unHighlight(e.currentTarget);
const dt = e.dataTransfer;
const { files } = dt;
processFilesUploaded(files);
};
const handleFileUpload = (e) => {
processFilesUploaded(e.target.files);
};
return (
<div className="FileDropTarget">
<div
className="FileDropTargetBox"
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<span className="centeredTextHolder">{children}</span>
</div>
<label className="fileUploadButton">
<div>
<span className="centeredTextHolder">
Or click here to upload them manually
</span>
</div>
<input
style={{ display: "none" }}
type="file"
onChange={handleFileUpload}
/>
</label>
</div>
);
}
<file_sep>/buildserver/api.py
import json
from urllib.parse import urlparse
from deploy import gen_service_name
from common.shell_utils import sh
def get_base_hostname(app: str) -> str:
services = json.loads(
sh(
"gcloud",
"run",
"services",
"list",
"--platform",
"managed",
"--format",
"json",
capture_output=True,
)
)
for service in services:
if service["metadata"]["name"] == gen_service_name(app, 0):
return urlparse(service["status"]["address"]["url"]).netloc
raise KeyError
<file_sep>/code/src/renderer/components/SuccessIcon.js
import React from "react";
export default function SuccessIcon(props) {
if (props.none) {
return (
<i
className="fas fa-question-circle"
style={{ color: "white", ...props.style }}
/>
);
} else if (props.success) {
return (
<i
className="fas fa-check"
style={{ color: "lightgreen", ...props.style }}
/>
);
} else {
return (
<i
className="fas fa-exclamation-triangle"
style={{ color: "orange", ...props.style }}
/>
);
}
}
<file_sep>/oh/migrations/versions/e96dc20c344a_add_online_options_to_locations.py
"""Add online options to locations
Revision ID: e96dc20c344a
Revises: <KEY>
Create Date: 2020-08-28 03:23:57.419222
"""
# revision identifiers, used by Alembic.
revision = "e96dc20c344a"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("location", sa.Column("link", sa.String(length=255), nullable=False))
op.add_column(
"location", sa.Column("online", sa.Boolean(), nullable=False, default=True)
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("location", "online")
op.drop_column("location", "link")
# ### end Alembic commands ###
<file_sep>/oh/README.md
# Office Hours Queue
## Overview
Provides a web-based interface for requesting help during office hours.
Students request help on an assignment and question number from a location.
This app uses [Ok](https://okpy.org) to manage access. Even if you aren't using Ok for assignments, you should create a course on Ok and enroll all of your staff, academic interns, and students with the appropriate roles.
## For other courses
This is a hosted app provided by 61A. To set it up for your own course, visit [Auth](https://auth.apps.cs61a.org) and add the desired domain under `Domains`. Make sure that the OKPy endpoint and course name are what you expect. Then contact 61A staff for your queue to be activated. If you want to move the queue to a new OKPy course, update the endpoint on Auth - the change should be reflected in the queue within an hour.
## Installation
1. Clone this repo:
```
git clone https://github.com/Cal-CS-61A-Staff/oh-queue.git
```
Then cd into it:
```
cd oh-queue
```
2. Create and activate a virtualenv:
```
python3 -m virtualenv env (If this does not work, try: `virtualenv -p python3 env`)
source env/bin/activate
```
3. Use pip to install all the dependencies:
```
pip install -r requirements.txt
npm install
```
4. Run the database migrations to setup the initial database.
```
./manage.py resetdb
./manage.py seed_data
./manage.py db upgrade
```
5. Run the server:
```
./manage.py server
```
6. Point your browser to http://localhost:5000. (This might take a while the first time.)
7. You can log in as any email while testing by going to http://localhost:5000/testing-login/.
### Dokku: Initial Deployment
dokku apps:create app-name
dokku clone app-name https://github.com/Cal-CS-61A-Staff/oh-queue
dokku mysql:create db-name
dokku mysql:link db-name app-name
dokku domains:set app-name <domain>
dokku config:set app-name OH_QUEUE_ENV=prod OK_KEY=<OK CLIENT> OK_SECRET=<OK SECRET> SECRET_KEY=<DB SECRET> AUTH_KEY=<AUTH_KEY> AUTH_SECRET=<AUTH_SECRET>
dokku run app-name ./manage.py db upgrade
dokku letsencrypt app-name
# Change OK OAuth to support the domain
For `OK_KEY` and `OK_SECRET`, you'll need to create an Ok OAuth client [here](https://okpy.org/admin/clients) and have it approved by an Ok admin.
### Dokku: Upgrading
dokku clone app-name https://github.com/Cal-CS-61A-Staff/oh-queue
dokku run app-name ./manage.py db upgrade
<file_sep>/cats/server/gui_files/multiplayer.py
import time
from collections import namedtuple, defaultdict
from datetime import datetime, timedelta
from random import randrange
import cats
from gui_files.common_server import route, forward_to_server, server_only
from gui_files.leaderboard_integrity import (
get_authorized_limit,
get_captcha_urls,
encode_challenge,
decode_challenge,
create_wpm_authorization,
)
MIN_PLAYERS = 2
MAX_PLAYERS = 4
QUEUE_TIMEOUT = timedelta(seconds=1)
MAX_WAIT = timedelta(seconds=5)
MAX_NAME_LENGTH = 90
MAX_UNVERIFIED_WPM = 90
CAPTCHA_ACCURACY_THRESHOLD = 60
CAPTCHA_SLOWDOWN_FACTOR = 0.6
def db_init():
global connect_db
from gui_files.db import connect_db
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS leaderboard (
name varchar(128),
user_id varchar(128),
wpm double,
PRIMARY KEY (`user_id`)
);"""
)
def create_multiplayer_server():
State = namedtuple("State", ["queue", "game_lookup", "game_data", "progress"])
State = State({}, {}, {}, defaultdict(list))
@route
@server_only
def provide_id():
return randrange(1000000000)
@route
@forward_to_server
def request_match(id):
if id in State.game_lookup:
game_id = State.game_lookup[id]
return {
"start": True,
"text": State.game_data[game_id]["text"],
"players": State.game_data[game_id]["players"],
}
if id not in State.queue:
State.queue[id] = [None, datetime.now()]
State.queue[id][0] = datetime.now()
to_remove = []
for player, (recent_time, join_time) in State.queue.items():
if datetime.now() - recent_time > QUEUE_TIMEOUT:
to_remove.append(player)
for player in to_remove:
del State.queue[player]
if (
len(State.queue) >= MAX_PLAYERS
or max(
datetime.now() - join_time
for recent_time, join_time in State.queue.values()
)
>= MAX_WAIT
and len(State.queue) >= MIN_PLAYERS
):
# start game!
import gui
curr_text = gui.request_paragraph()
game_id = gui.request_id()
for player in State.queue:
State.game_lookup[player] = game_id
queue = State.queue
players = list(queue.keys())
State.game_data[game_id] = {"text": curr_text, "players": players}
for player in queue:
State.progress[player] = [(0, time.time())]
State.queue.clear()
return {"start": True, "text": curr_text, "players": players}
else:
return {"start": False, "numWaiting": len(State.queue)}
@route
@server_only
def set_progress(id, progress):
"""Record progress message."""
State.progress[id].append((progress, time.time()))
return ""
@route
@forward_to_server
def request_progress(targets):
now = {t: State.progress[t][-1] for t in targets}
elapsed = [[now[t][0], now[t][1] - State.progress[t][0][1]] for t in targets]
return elapsed
@route
@forward_to_server
def request_all_progress(targets):
return [State.progress[target] for target in targets]
@route
@forward_to_server
def record_wpm(name, user, wpm, token):
authorized_limit = get_authorized_limit(user=user, token=token)
if (
wpm > max(MAX_UNVERIFIED_WPM, authorized_limit)
or len(name) > MAX_NAME_LENGTH
):
return
with connect_db() as db:
db("DELETE FROM leaderboard WHERE user_id = (%s)", [user])
db(
"INSERT INTO leaderboard (name, user_id, wpm) VALUES (%s, %s, %s)",
[name, user, wpm],
)
@route
@forward_to_server
def check_on_leaderboard(user):
with connect_db() as db:
users = list(
x[0]
for x in db(
"SELECT user_id FROM leaderboard ORDER BY wpm DESC LIMIT 20"
).fetchall()
)
return bool(user in users)
@route
@forward_to_server
def update_name(new_name, user):
if len(new_name) > MAX_NAME_LENGTH:
return
with connect_db() as db:
db("UPDATE leaderboard SET name=(%s) WHERE user_id=(%s)", [new_name, user])
@route
@forward_to_server
def check_leaderboard_eligibility(wpm, user, token):
with connect_db() as db:
vals = db(
"SELECT wpm FROM leaderboard ORDER BY wpm DESC LIMIT 20"
).fetchall()
threshold = vals[-1][0] if len(vals) >= 20 else 0
prev_best = db(
"SELECT wpm FROM leaderboard WHERE user_id=(%s)", [user]
).fetchone()
if prev_best:
threshold = max(threshold, prev_best[0])
authorized_limit = get_authorized_limit(user=user, token=token)
return {
"eligible": wpm >= threshold,
"needVerify": wpm > max(authorized_limit, MAX_UNVERIFIED_WPM),
}
@route
@forward_to_server
def request_wpm_challenge(user):
captcha_image_urls, words = get_captcha_urls()
token = encode_challenge(user, words)
return {
"images": captcha_image_urls,
"token": token,
"lastWordLen": len(words[-1]),
}
@route
@forward_to_server
def claim_wpm_challenge(user, token, typed, claimed_wpm):
challenge_user, reference, start_time = decode_challenge(token=token)
end_time = time.time()
if user != challenge_user:
return
accuracy = cats.accuracy(" ".join(typed), " ".join(reference))
wpm = cats.wpm(" ".join(reference), end_time - start_time)
if wpm < claimed_wpm * CAPTCHA_SLOWDOWN_FACTOR:
# too slow!
return {"success": False, "message": "Your captcha was typed too slowly!"}
if accuracy < CAPTCHA_ACCURACY_THRESHOLD:
# too inaccurate!
return {"success": False, "message": "You made too many mistakes!"}
return {"success": True, "token": create_wpm_authorization(user, claimed_wpm)}
@route
@forward_to_server
def leaderboard():
with connect_db() as db:
return list(
list(x)
for x in db(
"SELECT name, wpm FROM leaderboard ORDER BY wpm DESC LIMIT 20"
).fetchall()
)
<file_sep>/ag-master/main.py
from flask import Flask
from common.oauth_client import create_oauth_client
from models import create_models, db
from admin import create_admin_endpoints
from okpy import create_okpy_endpoints
from worker import create_worker_endpoints
from superadmin import create_superadmin_endpoints
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
create_oauth_client(app, "61a-autograder")
create_models(app)
create_admin_endpoints(app)
create_okpy_endpoints(app)
create_worker_endpoints(app)
create_superadmin_endpoints(app)
@app.before_first_request
def init_db():
db.init_app(app)
db.create_all(app=app)
@app.route("/")
def index():
return ""
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/sections/src/MessageContext.js
// @flow strict
import * as React from "react";
type MessageContextType = {
pushMessage: (string) => void,
};
export default React.createContext<MessageContextType>({
pushMessage: () => {},
});
<file_sep>/buildserver/requirements.txt
Flask==1.1.2
PyGitHub==1.52
gunicorn==20.0.4
PyYAML==5.3.1
google-cloud-storage==1.30.0
python-dateutil==2.8.1
twine==3.2.0
crcmod==1.7
gsutil==4.55
autopep8==1.5.4
-e buildtool
-r common/requirements.txt
<file_sep>/docs/index.md
```{include} README.md
```<file_sep>/slack/config_client.py
import json
from flask import request, url_for, abort
from werkzeug.utils import redirect
from common.rpc.auth import get_endpoint, list_courses, slack_workspace_name
from common.rpc.secrets import get_secret
from common.db import connect_db
from security import logged_in, get_staff_endpoints
REJECTED = object()
UNABLE = object()
CLIENT_ID = get_secret(secret_name="CLIENT_ID")
def get_add_to_slack_link(domain):
return f"https://{domain}.slack.com/oauth/v2/authorize?client_id={CLIENT_ID}&scope=channels:join,channels:read,chat:write,users:read,users:read.email,groups:read&user_scope=channels:history,chat:write,groups:history,im:history,mpim:history,users:read"
with open("config.json") as f:
CONFIG = json.load(f)
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS tokens (
user varchar(128),
token text,
PRIMARY KEY (`user`)
);"""
)
db(
"""CREATE TABLE IF NOT EXISTS silenced_users (
user varchar(128),
PRIMARY KEY (`user`)
);"""
)
db(
"""CREATE TABLE IF NOT EXISTS bot_data (
bot_access_token varchar(256),
team_id varchar(256),
course varchar(128)
)"""
)
db(
"""CREATE TABLE IF NOT EXISTS activated_services (
course varchar(128),
service varchar(128)
)"""
)
init_db()
def create_config_client(app):
@app.route("/")
@logged_in
def index():
staff_endpoints = set(get_staff_endpoints())
active_courses = []
for course, endpoint in list_courses():
if endpoint in staff_endpoints:
active_courses.append(course)
if len(active_courses) == 0:
return (
"You are not a member of staff in any course that uses this tool",
401,
)
if len(active_courses) == 1:
return redirect(url_for("register_course", course=active_courses[0]))
options = "<p>".join(
'<button formaction="register/{}">{}</button>'.format(course, course)
for course in active_courses
)
return f"""
Please select your course:
<form method="get">
{options}
</form>
"""
@app.route("/register/<course>")
def register_course(course):
if get_endpoint(course=course) not in get_staff_endpoints():
abort(403)
with connect_db() as db:
ret = db("SELECT * FROM bot_data WHERE course = (%s)", [course]).fetchone()
if ret:
# course already setup
return redirect(get_add_to_slack_link(slack_workspace_name(course=course)))
else:
return redirect(url_for("course_config", course=course))
@app.route("/config/<course>")
def course_config(course):
if get_endpoint(course=course) not in get_staff_endpoints():
abort(403)
with connect_db() as db:
ret = db(
"SELECT service FROM activated_services WHERE course = (%s)", [course]
)
active_services = set(x[0] for x in ret)
service_list = "<br />".join(
f"""
<label>
<input
type="checkbox"
name="{service}"
{"checked" if service in active_services else ""}
>
{service.title()}: {description}
</label>
"""
for service, description in CONFIG["services"].items()
)
return f"""
First, ensure that <a href="https://auth.apps.cs61a.org">61A Auth</a> is set up for your course.
<p>
Then set up the bot.
<form action="{url_for("set_course_config", course=course)}" method="post">
Services:
<br />
{service_list}
<br />
<input type="submit" />
</form>
<p>
Then, <a href={get_add_to_slack_link(slack_workspace_name(course=course))}>
add the slackbot to your workspace!
</a>
"""
@app.route("/set_config/<course>", methods=["POST"])
def set_course_config(course):
if get_endpoint(course=course) not in get_staff_endpoints():
abort(403)
with connect_db() as db:
for service in CONFIG["services"]:
db(
"DELETE FROM activated_services WHERE course=(%s) AND service=(%s)",
[course, service],
)
if service in request.form:
db(
"INSERT INTO activated_services VALUES (%s, %s)",
[course, service],
)
return redirect(url_for("course_config", course=course))
def store_user_token(user, token):
with connect_db() as db:
result = db("SELECT user FROM tokens WHERE user=%s", (user,))
if not result.fetchone():
db("INSERT INTO tokens VALUES (%s, %s)", (user, token))
db("UPDATE tokens SET token=(%s) WHERE user=(%s)", (token, user))
def get_user_token(user):
with connect_db() as db:
out = db("SELECT token FROM tokens WHERE user=%s", (user,)).fetchone()
if not out:
check = db(
"SELECT user FROM silenced_users WHERE user=%s", (user,)
).fetchone()
if check: # user doesn't want to use the tool :(
return REJECTED
return UNABLE
return out["token"]
def store_bot_token(course, team_id, token):
with connect_db() as db:
check = db("SELECT * FROM bot_data WHERE course = (%s)", [course]).fetchone()
if not check:
db("INSERT INTO bot_data VALUES (%s, %s, %s)", ["", "", course])
db(
"UPDATE bot_data SET bot_access_token=(%s), team_id=(%s) WHERE course=(%s)",
[token, team_id, course],
)
def get_team_data(team_id):
with connect_db() as db:
return db(
"SELECT course, bot_access_token FROM bot_data WHERE team_id = (%s)",
[team_id],
).fetchone()
<file_sep>/logs/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
google-cloud-logging==1.15.1
-r common/requirements.txt
<file_sep>/common/rpc/code.py
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__, "code")
@requires_master_secret
@service.route("/api/create_code_shortlink")
def create_code_shortlink(
name: str, contents: str, staff_only: bool = True, link: str = None
):
...
<file_sep>/oh/oh_queue/static/js/components/admin_items_text_field.js
function AdminItemsTextField({ itemType, placeholder, propType, item }) {
const editItem = (e) => {
e.preventDefault();
const value = e.target.elements[0].value;
const button = e.target.elements[1];
$(button).addClass("is-loading");
app.makeRequest(
`update_${itemType}`,
{ id: item.id, [propType]: value },
() => $(button).removeClass("is-loading")
);
};
return (
<form className="form-inline" onSubmit={editItem}>
<div className="form-group form-group-sm">
<div className="input-group">
<input
className="form-control"
type="text"
placeholder={placeholder}
data-item-id={item.id}
defaultValue={item[propType]}
/>
<span className="input-group-btn">
<button className="btn btn-default btn-sm" type="submit">
Edit
</button>
</span>
</div>
</div>
</form>
);
}
<file_sep>/slack/api_client.py
import json
from functools import wraps
import requests
from flask import abort
from common.db import connect_db
from common.rpc.secrets import validates_master_secret
from common.rpc.slack import list_channels, post_message
def api_secure(f):
@wraps(f)
@validates_master_secret
def wrapped(app, is_staging, **kwargs):
if app != "auth":
abort(401)
return f(**kwargs)
return wrapped
def create_api_client(app):
@list_channels.bind(app)
@api_secure
def handle_list_channels(course):
with connect_db() as db:
(bot_token,) = db(
"SELECT bot_access_token FROM bot_data WHERE course = (%s)", [course]
).fetchone()
resp = requests.post(
"https://slack.com/api/users.conversations",
{"exclude_archived": True, "types": "public_channel,private_channel"},
headers={"Authorization": "Bearer {}".format(bot_token)},
).json()
return resp["channels"]
@post_message.bind(app)
@api_secure
def handle_post_message(course, message, channel):
with connect_db() as db:
(bot_token,) = db(
"SELECT bot_access_token FROM bot_data WHERE course = (%s)", [course]
).fetchone()
if isinstance(message, str):
message = email_replace(message, bot_token)
requests.post(
"https://slack.com/api/chat.postMessage",
json={"channel": channel, "text": message},
headers={"Authorization": "Bearer {}".format(bot_token)},
)
else:
stringify = json.dumps(message)
stringify = email_replace(stringify, bot_token)
message = json.loads(stringify)
requests.post(
"https://slack.com/api/chat.postMessage",
json={"channel": channel, "blocks": message},
headers={"Authorization": "Bearer {}".format(bot_token)},
)
def email_replace(message, bot_token):
users = requests.get(
"https://slack.com/api/users.list", params={"token": bot_token}
).json()
for member in users["members"]:
message = message.replace(
f"<!{member['profile'].get('email')}>", f"<@{member['id']}>"
)
return message
<file_sep>/sicp/sicp/__init__.py
import sys
import pathlib
sys.path.append(str(pathlib.Path(__file__).parent.absolute()))
<file_sep>/buildtool/README.md
## Overview
This is a `make` alternative with a simpler syntax and some useful features.
## Example
### Hello, World!
To create a buildtool project, place a `WORKSPACE` file at the root of your project. For now, it can be empty. Run `git init` to initialize a git repo in your project root.
Then you can define build rules in `BUILD` files. Imagine a simple project with one source file: `src/main.c`, that can be compiled with `gcc main.c -c -o ../build/a.out` to produce the output file `build/a.out`. Our project structure looks like:
```
- WORKSPACE
- src/
- main.c
- BUILD
```
We have placed a `BUILD` file in the `src/` directory. We will declare a rule called `main` that builds `main.c` and produces `a.out` in this `BUILD` file.
```python
# src/BUILD
from buildtool import callback
def impl(ctx):
ctx.sh("mkdir -p ../build")
ctx.sh("gcc main.c -c -o ../build/a.out")
callback(
name="main",
deps=["main.c"],
impl=impl,
out="../build/a.out",
)
```
Let's see what this file does. The `callback` tells `buildtool` that we are declaring a rule with `name="main"`. The `deps` of a rule are the files that the rule requires to run. The `out` is a file (or list of files) that a rule produces from its deps. Finally, the implementation `impl` of a rule describes the actions that a rule performs in order to generate its output from its inputs.
The paths passed into the callback are relative to the folder containing the `BUILD` file.
An `impl` function takes in a single argument: the build context `ctx`. When defining a rule's implementation, do not use functions like `os.system` directly - aside from invoking methods in the `ctx`, all `impl` functions must be side-effect free. Here, `ctx.sh(...)` runs a shell command in the directory containing the `BUILD` folder.
Now we can run this rule. Run `buildtool main` inside the project. The output file `build/a.out` should have appeared.
So far, we haven't done anything that couldn't be done with a simple Makefile.
However, now try modifying the build rule so `deps=[]`, and rerun `buildtool main` (or just `bt main` for short). We get an error
```
error: no such file or directory: 'main.c'
```
This is despite the fact that `src/main.c` is clearly still in our repo. Buildtool runs all builds in a separate "sandbox" directory with only the explicitly stated dependencies made available. This means that it is (almost) impossible to make a mistake when specifying rule dependencies, since then the build will fail when run in the sandbox directory.
### Generic Rules
Now imagine that we have a second source file `another.c` in `src/`, and want to compile it to `build/b.out`. One way would be to copy/paste the existing `main` build rule and create a second rule to generate `b.out`. Instead, however, we can define a generic build rule, and _declare_ it twice - once for each of our two targets.
This can be done as follows:
```python
# src/BUILD
from buildtool import callback
def declare(*, name: str, src: str, out: str):
def impl(ctx):
ctx.sh("mkdir -p ../build")
ctx.sh(f"gcc {src} -c -o {out}")
callback(
name=name,
deps=[src],
impl=impl,
out=out,
)
declare(name="main", src="main.c", out="../build/a.out")
declare(name="another", src="another.c", out="../build/b.out")
```
The `declare` function is just a standard Python function, and when `src/BUILD` is evaluated, `callback()` is called twice by `declare()` to declare each of our rules.
### Loading Files
In larger repos, it may make sense to move these generic rules into a separate file. Let us do so here, creating a `rules.py` file in the same `src/` directory, so our file hierarchy now looks like:
```
- WORKSPACE
- src/
- main.c
- another.c
- BUILD
- rules.py
```
We move `declare` into `rules.py`, so
```python
# src/rules.py
from buildtool import callback
def declare(*, name: str, src: str, out: str):
def impl(ctx):
ctx.sh("mkdir -p ../build")
ctx.sh(f"gcc {src} -c -o {out}")
return callback(
name=name,
deps=[src],
impl=impl,
out=out,
)
```
To import it from `rules.py`, we can use the `load()` function, as follows:
```python
# src/BUILD
from buildtool import load
rules = load("rules.py")
rules.declare(name="main", src="main.c", out="../build/a.out")
rules.declare(name="another", src="another.c", out="../build/b.out")
```
The path passed to `load()` is relative to the loading file. `*.py` files can also load other `*.py` files, so long as no cycles exist. It is not possible to load a `BUILD` file from another file. Furthermore, it is only possible to declare a rule from a `BUILD` file. Now we can run `bt main` or `bt another` to generate `a.out` and `b.out`, respectively.
### Rule Dependencies
In addition to depending on other files, rules can depend on other rules. Unlike depending on files, depending on other rules will not change the files made available when running builds in the sandbox directory. Instead, if rule `A` depends on rule `B`, then whenever we build rule `A`, rule `B` is guaranteed to also be built.
For instance, we may wish to have a build target to build both `main` and `another` together. This can be done as follows:
```python
# src/BUILD
from buildtool import load, callback
rules = load("rules.py")
rules.declare(name="main", src="main.c", out="../build/a.out")
rules.declare(name="another", src="another.c", out="../build/b.out")
callback(
name="all",
deps=[":main", ":another"],
)
```
By adding a `:` in front of the names of a dependency, we signify that it is the name of a rule, not the name of a file. When running builds from the command-line, we can also use this syntax to disambiguate between a rule and a file with the same name (e.g. `bt :all`), but it is not required if the target can be resolved unambiguously.
Now, running `bt all` will build both `a.out` and `b.out`.
If `name` is passed to `callback()`, it will return `:<name>`. This lets us avoid repeating rule names, as follows:
```python
# src/BUILD
from buildtool import load, callback
rules = load("rules.py")
callback(
name="all",
deps=[
rules.declare(name="main", src="main.c", out="../build/a.out"),
rules.declare(name="another", src="another.c", out="../build/b.out")
],
)
```
However, it is good practice to avoid "nesting" rules in this fashion.
### Paths and Globbing
Rather than writing a separate rule for each `.c` file in `src/`, we may wish to automatically declare rules to build them. This can be done using the `find()` function, which lets us glob for files, as follows:
```python
# src/BUILD
from buildtool import load, callback, find
from os.path import basename
rules = load("rules.py")
all_rules = []
for src in find("*.c"):
name = basename(src)[:-2]
all_rules.append(rules.declare(name=name, src=src, out=f"../build/{name}.out"))
callback(
name="all",
deps=all_rules,
)
```
The path passed to `find()` is relative to the directory containing the `BUILD` file. We can also pass in paths relative to the root of the project, by prefixing them with `//`. So instead of writing `find("*.c")`, we could have equivalently written `find("//src/*.c")`. This syntax for paths relative to the project root can be used elsewhere where paths are required, such as an element of `deps`, the value of `out`, or as an argument to `load()`.
If we run `bt main`, we get the following error:
```
subprocess.CalledProcessError: Command '['gcc //src/main.c -o ../build/main.out']' returned non-zero exit status 1.
```
We see that `find()` has returned a path relative to the project root, which cannot be directly passed to the shell. One fix would be to again use `os.path.basename` in `rules.py` to extract the filename `main.c`. However, this will cause problems if we later try to use our rule to compile a file in a subfolder. Instead, there exists a method `ctx.relative()` that takes in a path of any format and outputs a path relative to the working directory in an implementation.
We can use this method to modify `rules.py` as follows:
```python
# src/rules.py
from buildtool import callback
def declare(*, name: str, src: str, out: str):
def impl(ctx):
ctx.sh("mkdir -p ../build")
ctx.sh(f"gcc {ctx.relative(src)} -c -o {ctx.relative(out)}")
return callback(
name=name,
deps=[src],
impl=impl,
out=out,
)
```
For now, we will not worry about updating the `mkdir` call to support subdirectories. Now `bt all` should work correctly.
### Dynamic Dependencies
Sometimes, we do not know all the dependencies of a rule in advance. For instance, imagine that `main.c` depends on `another.c`. If we run `bt main`, we get the error
```
main.c:2:10: fatal error: 'another.c' file not found
```
becaues only explicitly stated dependencies are available when running a build.
One solution would be to update `declare()` to take in a list of dependencies and manually specify that `main.c` depends on `another.c`. Alternatively, we can add a dependency dynamically when running the build.
First, we need to know how to detect dependencies. If we run `gcc main.c -MM`, we obtain:
```shell
$ gcc main.c -MM
main.o: main.c another.c
```
This is in a format acceptable for Makefiles, but we need to process it to extract the raw file names. We can do so by modifying `rules.py` as follows:
```python
# src/rules.py
from buildtool import callback
def declare(*, name: str, src: str, out: str):
def impl(ctx):
ctx.sh("mkdir -p ../build")
raw_deps = ctx.input(sh=f"gcc {ctx.relative(src)} -MM")
deps = raw_deps.strip().split(" ")[1:]
ctx.add_deps(deps)
ctx.sh(f"gcc {ctx.relative(src)} -c -o {ctx.relative(out)}")
return callback(
name=name,
impl=impl,
out=out,
)
```
First, we use `ctx.input(sh=...)` to run a shell command and read back the stdout. After parsing the output to determine what files to depend on, we then use `ctx.add_deps()` to add them as _dynamic dependencies_, replacing the `deps=[src]` previously passed into `callback()`. Finally, we run the standard compile, as before. Notice that the initial `ctx.input()` call depended on `src`, but it was only added as a dependency _afterwards_. This is allowed with dynamic dependencies, so long as after the `impl()` completes, all the dependencies ever used have been added.
Now, `bt all` successfully builds the target files.
### Workspaces
We now are able to build a simple project. When managing large projects, it is useful to also automate setup of the build environment, so a user can clone the repo, run `buildtool`, and obtain the built output without any manual configuration. This is the role of the `WORKSPACE` file.
In a `WORKSPACE` file, there is a new import available from `buildtool`: the `config`. A simple `WORKSPACE` file may look like this:
```python
# WORKSPACE
from buildtool import config
config.register_default_build_rule(":all")
config.register_output_directory("build")
config.require_buildtool_version("0.1.25")
```
The default build rule is the rule that is invoked when running `bt` in a project directory with no rule specified. The output directory is a directory that is cleaned when running `bt --clean`, in order to remove previous build artifacts (multiple output directories can be registered). Finally, a minimum `buildtool` version can be required, so that if old versions are used to build the project, a clear error message will be printed instructing the user to update.
In addition, we can declare _setup rules_ in the `WORKSPACE` file. Unlike build rules, setup rules are not run in sandboxed directories, so their dependencies are not automatically enforced. While they must specify their outputs, since they run in the main project directory, they are not verified either. Unlike build rules, setup rules cannot use `ctx.add_deps()`, but must specify their dependencies statically.
For instance, imagine that `gcc` is not present in the `/usr/bin/` directory, but is instead located somewhere else in the `PATH`. The `PATH` is normalized to `/usr/bin/` in build rules, so our previous rule would not work since the shell would not be able to find `gcc`. Instead, we will use a setup rule to detect `gcc` and add a symlink from `//env/bin/gcc` to wherever it is located on the machine. Then we will use this symlink in our build rules to compile our `*.c` files.
We modify our `WORKSPACE` file as follows:
```python
# WORKSPACE
from buildtool import config, callback
def declare_gcc_symlink():
def impl(ctx):
target = ctx.input(sh=f"which gcc").strip()
ctx.sh("mkdir -p env/bin")
ctx.sh("rm -f env/bin/gcc")
ctx.sh(f"ln -s {target} env/bin/gcc")
return callback(
name="gcc",
impl=impl,
out="env/bin/gcc",
)
callback(
name="init",
deps=[declare_gcc_symlink()]
)
config.register_default_setup_rule(":init")
config.register_default_build_rule(":all")
config.register_output_directory("build")
config.require_buildtool_version("0.1.25")
```
Notice that the `impl()` of `declare_gcc_symlink()` clears any past outputs before rerunning, since it runs in the project directory directly, not in a sandbox. In addition, notice that we have registered a `default_setup_rule` in our config. If such a rule is registered, buildtool will ensure that it is built before building any subsequent targets.
To run the `gcc` setup rule separately, run `bt setup:gcc`. Unlike build rules, we cannot run `bt env/bin/gcc` to regenerate the file - we can only run setup rules from the command line by their name. Thus, all setup rules are required to have a name, though they can _depend_ on source files or on files built by other setup rules.
Next, we will modify `rules.py` to use `//env/bin/gcc`, instead of `/usr/bin/gcc`. Rather than hardcoding this new path into `ctx.sh`, we will modify the `PATH` used by `ctx.sh()` to look in `//env/bin` and then `/bin`, but not `/usr/bin`. This can be done as follows:
```python
# src/rules.py
from buildtool import callback
ENV = dict(PATH=["@//env/bin/", "/bin"])
def declare(*, name: str, src: str, out: str):
def impl(ctx):
ctx.sh("mkdir -p ../build", env=ENV)
raw_deps = ctx.input(sh=f"gcc {ctx.relative(src)} -MM", env=ENV)
deps = raw_deps.strip().split(" ")[1:]
ctx.add_deps(deps)
ctx.sh(f"gcc {ctx.relative(src)} -c -o {ctx.relative(out)}", env=ENV)
return callback(
name=name,
impl=impl,
out=out,
)
```
When we prefix a path with `@//`, it means that the path is relative to the project root directory, even if the build is being run in a sandbox. In contrast, if a path is prefixed with `//`, then it is treated as relative to the sandbox root directory when running a sandboxed builds. Paths can only be prefixed by `@//` in environment variables, not anywhere else.
Notice that we have not defined the `PATH` in `ENV` to be a string, but rather as a list of paths, using buildtool syntax. The buildtool will automatically resolve these paths to absolute paths and concatenate them together to form a string that will be passed into the shell environment. This is done so that absolute paths are never handled directly in build rules - they are to be avoided since they cause issues with caching. If an absolute path is needed as part of a shell command, it can be added to the environment and then accessed using shell syntax.
We can now run `bt all` to regenerate the output. Notice that an `env/` folder has been created, containing the `gcc` symlink. Conventionally, we do not register the `env/` folder (or other targets built by setup rules) as an output directory, since it is unlikely to be the user's intention to clear it when running `bt --clear`.
<file_sep>/code/src/renderer/components/ModalButton.js
import React from "react";
export default function ModalButton({ children, buttonText, onClick }) {
return (
<div className="ModalButton">
{children}
<button className="fileDownloadBtn" type="button" onClick={onClick}>
{buttonText}
</button>
</div>
);
}
<file_sep>/slack/prlink_integration.py
import itertools
import re
from collections import namedtuple
from integration import Integration
from utils import OrderedSet
PrLink = namedtuple("PrLink", ["path"])
VALID_PATH = r"[0-9A-Za-z\-]"
PATH_REGEX = r"(?P<path>{}+)".format(VALID_PATH)
REGEX_TEMPLATE = (
r"<(https?://)?github\.com/Cal-CS-61A-Staff/berkeley-cs61a/pull/{}/?(\|[^\s|]+)?>"
)
SHORT_REGEX_TEMPLATE = r"pr/{}/?"
class PRLinkIntegration(Integration):
def _process(self):
self._prlinks = OrderedSet()
for match in itertools.chain(
re.finditer(REGEX_TEMPLATE.format(PATH_REGEX), self._message),
re.finditer(SHORT_REGEX_TEMPLATE.format(PATH_REGEX), self._message),
):
self._prlinks.add(PrLink(match.group("path")))
@property
def message(self):
out = self._message
for prlink in self._prlinks:
out = re.sub(
REGEX_TEMPLATE.format(prlink.path), "pr/{}".format(prlink.path), out
)
out = re.sub(
SHORT_REGEX_TEMPLATE.format(prlink.path),
r"<https://github.com/Cal-CS-61A-Staff/berkeley-cs61a/pull/{}|pr/{}>".format(
prlink.path, prlink.path
),
out,
)
return out
<file_sep>/oh/migrations/versions/3ac7f97f07e4_add_appointment_limits.py
"""add appointment limits
Revision ID: 3ac7f97f07e4
Revises: <KEY>
Create Date: 2020-03-11 04:59:46.480627
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "3ac7f97f07e4"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="daily_appointment_limit", value="2", public=True, course=course[0]
)
)
session.add(
ConfigEntry(
key="weekly_appointment_limit", value="5", public=True, course=course[0]
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
<file_sep>/piazzaoncall/piazza.py
from common.rpc.auth import Network, perform_piazza_action
class PiazzaNetwork(Network):
def __init__(self, course, is_staff, is_test):
super().__init__(course, is_staff, is_test, perform_piazza_action)
def get_unresolved(self):
feed = self.get_feed(limit=999999, offset=0)["feed"]
unresolved = unresolved_followups = 0
for post in feed:
u = post.get("no_answer", 0)
uf = post.get("no_answer_followup", 0)
if not u and not uf:
continue
subject = post["subject"]
if "EC" in subject or "extra credit" in subject.lower():
continue
unresolved += u
unresolved_followups += uf
return unresolved, unresolved_followups
def iter_all_posts1(self, limit=None): # new
"""Get all posts visible to the current user
This grabs you current feed and ids of all posts from it; each post
is then individually fetched. This method does not go against
a bulk endpoint; it retrieves each post individually, so a
caution to the user when using this.
:type limit: int|None
:param limit: If given, will limit the number of posts to fetch
before the generator is exhausted and raises StopIteration.
:returns: An iterator which yields all posts which the current user
can view
:rtype: generator
"""
feed = self.get_feed(limit=999999, offset=0)
cids = [post["id"] for post in feed["feed"]]
if limit:
cids = cids[:limit]
for cid in cids:
yield self.get_post(cid=cid)
def list_unresolved(self): # new
"""Returns a generator of all unresolved posts"""
feed = self.get_feed(limit=999999, offset=0)
post_snippets = feed.get("feed")
for s in post_snippets:
if s.get("no_answer", False) or s.get("no_answer_followup", False):
cid = s["id"]
yield self.get_post(cid=cid)
network = PiazzaNetwork("cs61a", True, False)
<file_sep>/common/rpc/ag_worker.py
from typing import List
from common.rpc.utils import create_service
service = create_service(__name__, "ag-worker")
@service.route("/api/ping_worker")
def ping_worker():
...
@service.route("/api/batch_grade")
def batch_grade(*, command: str, jobs: List[str], grading_zip: str):
...
<file_sep>/examtool_web_common/js/logger.js
import { getAuthParams } from "./auth";
import post from "./post";
function makePrefixes(exam) {
const baseHistoryPrefix = "history:";
const baseAnswerPrefix = "answerPrefix:";
return {
historyPrefix: `${exam}|${baseHistoryPrefix}|`,
answerPrefix: `${exam}|${baseAnswerPrefix}|`,
};
}
export function logAnswer(exam, questionID, value) {
try {
const { historyPrefix, answerPrefix } = makePrefixes(exam);
localStorage.setItem(`${historyPrefix}${questionID}|${Date.now()}`, value);
localStorage.setItem(`${answerPrefix}${questionID}`, value);
} catch (e) {
console.error(e);
}
}
export async function synchronize(exam) {
try {
const history = {};
const snapshot = {};
const { historyPrefix, answerPrefix } = makePrefixes(exam);
for (const [key, value] of Object.entries(localStorage)) {
if (key.startsWith(historyPrefix)) {
history[key.slice(historyPrefix.length)] = value;
localStorage.removeItem(key);
} else if (key.startsWith(answerPrefix)) {
snapshot[key.slice(answerPrefix.length)] = value;
}
}
post("backup_all", {
exam,
history,
snapshot,
...getAuthParams(),
});
} catch (e) {
console.error(e);
}
}
window.synchronize = synchronize;
<file_sep>/examtool/examtool/cli/download.py
import csv
import os
import pathlib
from multiprocessing.pool import ThreadPool
import click
from tqdm import tqdm
from examtool.api.render_html_export import render_html_exam
from examtool.api.render_pdf_export import render_pdf_exam
from examtool.cli.utils import exam_name_option, hidden_output_folder_option
import examtool.api.download
import examtool.api.assemble_export
@click.command()
@exam_name_option
@click.option(
"--name-question",
default=None,
help="The ID of the question for the student's name.",
)
@click.option(
"--sid-question", default=None, help="The ID of the question for the student's SID."
)
@click.option(
"--with-substitutions/--without-substitutions",
default=False,
help="Include keyword substitutions in exported question bodies.",
)
@click.option(
"--via-html/--direct-pdf",
default=False,
help="Use an HTML-based PDF exporter or export directly to PDF.",
)
@click.option(
"--num-threads",
default=16,
type=int,
help="The number of threads to process the JSON file.",
)
@hidden_output_folder_option
def download(
exam, out, name_question, sid_question, with_substitutions, via_html, num_threads
):
"""
Download student submissions for an exam.
Exams are downloaded as PDFs into a target folder - specify `out` to redirect the folder.
An `OUTLINE.pdf` is also generated for Gradescope, as is a `summary.csv` for analytics or autograding.
"""
out = out or "out/export/" + exam
pathlib.Path(out).mkdir(parents=True, exist_ok=True)
(
exam_json,
template_questions,
email_to_data_map,
total,
) = examtool.api.download.download(exam)
with open(os.path.join(out, "summary.csv"), "w") as f:
writer = csv.writer(f)
for row in total:
writer.writerow(row)
assembled_exams = examtool.api.assemble_export.export(
template_questions,
email_to_data_map,
exam,
name_question,
sid_question,
substitute_in_question_text=with_substitutions,
)
def render(name_exam):
name, exam = name_exam
target = os.path.join(out, f"{name}.pdf")
if via_html:
export = render_html_exam(exam)
export(target)
else:
pdf = render_pdf_exam(exam)
pdf.output(target)
with ThreadPool(num_threads) as p:
list(
tqdm(
p.imap_unordered(render, assembled_exams.items()),
total=len(assembled_exams),
desc="Rendering",
unit="Exam",
)
)
if __name__ == "__main__":
download()
<file_sep>/oh/migrations/versions/4c81c3744bc4_add_models_for_hw_party_mode.py
"""Add models for HW party mode
Revision ID: 4c81c3744bc4
Revises: <KEY>
Create Date: 2020-07-05 06:22:08.392455
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "<KEY>"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"group",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created", sa.DateTime(), nullable=True),
sa.Column("question", sa.String(length=255), nullable=False),
sa.Column("description", sa.String(length=255), nullable=False),
sa.Column("assignment_id", sa.Integer(), nullable=True),
sa.Column("location_id", sa.Integer(), nullable=False),
sa.Column("ticket_id", sa.Integer(), nullable=True),
sa.Column(
"group_status", oh_queue.models.db.String(length=255), nullable=False
),
sa.Column("call_url", sa.String(length=255), nullable=True),
sa.Column("doc_url", sa.String(length=255), nullable=True),
sa.Column("course", sa.String(length=255), nullable=False),
sa.ForeignKeyConstraint(
["assignment_id"],
["assignment.id"],
),
sa.ForeignKeyConstraint(
["location_id"],
["location.id"],
),
sa.ForeignKeyConstraint(
["ticket_id"],
["ticket.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_group_assignment_id"), "group", ["assignment_id"], unique=False
)
op.create_index(op.f("ix_group_course"), "group", ["course"], unique=False)
op.create_index(op.f("ix_group_created"), "group", ["created"], unique=False)
op.create_index(
op.f("ix_group_location_id"), "group", ["location_id"], unique=False
)
op.create_index(op.f("ix_group_ticket_id"), "group", ["ticket_id"], unique=False)
op.create_table(
"group_attendance",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("group_id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column(
"group_attendance_status",
oh_queue.models.db.String(length=255),
nullable=False,
),
sa.Column("course", sa.String(length=255), nullable=False),
sa.ForeignKeyConstraint(
["group_id"],
["group.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["user.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_group_attendance_course"), "group_attendance", ["course"], unique=False
)
op.create_index(
op.f("ix_group_attendance_group_id"),
"group_attendance",
["group_id"],
unique=False,
)
op.create_index(
op.f("ix_group_attendance_user_id"),
"group_attendance",
["user_id"],
unique=False,
)
# ### end Alembic commands ###
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="party_enabled", value="false", public=True, course=course[0]
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_group_attendance_user_id"), table_name="group_attendance")
op.drop_index(op.f("ix_group_attendance_group_id"), table_name="group_attendance")
op.drop_index(op.f("ix_group_attendance_course"), table_name="group_attendance")
op.drop_table("group_attendance")
op.drop_index(op.f("ix_group_ticket_id"), table_name="group")
op.drop_index(op.f("ix_group_location_id"), table_name="group")
op.drop_index(op.f("ix_group_created"), table_name="group")
op.drop_index(op.f("ix_group_course"), table_name="group")
op.drop_index(op.f("ix_group_assignment_id"), table_name="group")
op.drop_table("group")
# ### end Alembic commands ###
<file_sep>/oh/oh_queue/static/js/components/admin_locations_manager.js
function AdminLocationsManager({ state }) {
const { locations } = state;
return (
<AdminItemsManager
itemType="location"
columns={["ID", "Name", "Zoom Link (optional)", "Online", "Visibility"]}
items={Object.values(locations).filter(({ name }) => name !== "Online")}
>
{(item) => [
item.id,
<AdminItemsTextField
itemType="location"
placeholder="New Name"
propType="name"
item={item}
/>,
<AdminItemsTextField
itemType="location"
placeholder="Zoom Link (optional)"
propType="link"
item={item}
/>,
<AdminItemsBooleanField
itemType="location"
propType="online"
item={item}
/>,
<AdminItemsBooleanField
itemType="location"
propType="visible"
item={item}
onText="Visible"
offText="Hidden"
/>,
]}
</AdminItemsManager>
);
}
<file_sep>/howamidoing/src/BinSelectors.js
import React from "react";
import BinSelector from "./BinSelector.js";
export default function BinSelectors({ bins, toggled, onToggle }) {
const binSelectors = bins.map((bin, i) => (
<BinSelector key={bin} toggled={toggled[i]} onToggle={() => onToggle(i)}>
{bin}
</BinSelector>
));
return (
<>
<div>Show students with scores:</div>
<div className="btn-group" role="group" aria-label="Basic example">
{binSelectors}
</div>
</>
);
}
<file_sep>/oh/manage.py
#!/usr/bin/env python3
import datetime
import functools
import os
import random
import sys
import alembic
import names
from alembic.config import Config
from flask import render_template
from flask_debugtoolbar import DebugToolbarExtension
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from common.course_config import get_course
from oh_queue import app
from oh_queue.models import (
db,
Assignment,
Location,
Ticket,
TicketStatus,
User,
Appointment,
AppointmentSignup,
AppointmentStatus,
)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)
alembic_cfg = Config("migrations/alembic.ini")
def not_in_production(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
if app.config.get("ENV") == "prod":
print("this command should not be run in production. Aborting")
sys.exit(1)
return f(*args, **kwargs)
return wrapper
@manager.command
@not_in_production
def seed_data():
print("Seeding...")
assignments = [
Assignment(name=name, course=get_course(), visible=True)
for name in ["Hog", "Maps", "Ants", "Scheme"]
]
locations = [
Location(name=name, course=get_course(), visible=True, online=False, link="")
for name in ["109 Morgan", "241 Cory", "247 Cory"]
]
questions = list(range(1, 16)) + ["Other", "EC", "Checkoff"]
descriptions = ["", "I'm in the hallway", "SyntaxError on Line 5"]
appointments = [
Appointment(
start_time=datetime.datetime.now()
+ datetime.timedelta(hours=random.randrange(-8, 50)),
duration=datetime.timedelta(minutes=random.randrange(30, 120, 30)),
location=random.choice(locations),
capacity=5,
status=AppointmentStatus.pending,
course=get_course(),
)
for _ in range(70)
]
for assignment in assignments:
db.session.add(assignment)
for location in locations:
db.session.add(location)
for appointment in appointments:
db.session.add(appointment)
db.session.commit()
students = []
for i in range(50):
real_name = names.get_full_name()
first_name, last_name = real_name.lower().split(" ")
email = "{0}{1}@{2}".format(
random.choice([first_name, first_name[0]]),
random.choice([last_name, last_name[0]]),
random.choice(["berkeley.edu", "gmail.com"]),
)
student = User.query.filter_by(email=email).one_or_none()
if not student:
student = User(name=real_name, email=email, course=get_course())
students.append(student)
db.session.add(student)
db.session.commit()
delta = datetime.timedelta(minutes=random.randrange(0, 30))
ticket = Ticket(
user=student,
status=TicketStatus.pending,
created=datetime.datetime.utcnow() - delta,
assignment=random.choice(assignments),
location=random.choice(locations),
question=random.choice(questions),
description=random.choice(descriptions),
course=get_course(),
)
db.session.add(ticket)
signups = [
AppointmentSignup(
appointment=random.choice(appointments),
user=random.choice(students),
assignment=random.choice(assignments),
question=random.choice(questions),
description=random.choice(descriptions),
course=get_course(),
)
for _ in range(120)
]
for signup in signups:
db.session.add(signup)
db.session.commit()
@manager.command
@not_in_production
def resetdb():
print("Dropping tables...")
db.drop_all(app=app)
initdb()
@manager.command
def initdb():
print("Creating tables...")
db.create_all(app=app)
print("Stamping DB revision...")
alembic.command.stamp(alembic_cfg, "head")
@manager.command
@not_in_production
def build():
render_template("index.html", course_name="test")
@manager.command
@not_in_production
def server():
DebugToolbarExtension(app)
app.run(host=app.config.get("HOST"), port=app.config.get("PORT"), debug=True)
if __name__ == "__main__":
manager.run()
<file_sep>/sections/scripts/populate_db.py
assert False # don't run this!
import csv
import os
import sys
from datetime import datetime, timedelta
import pytz
sys.path.append(os.path.abspath("../server"))
from common.rpc.auth import read_spreadsheet
from main import app
from models import Section, User, db
staff_reader = read_spreadsheet(
url="https://docs.google.com/spreadsheets/d/1qHgmwwg_kt3mhQtY3pFFimuAEom1AIxgThQ82_DdoHw/",
sheet_name=f"Tutor Mapping",
)
student_reader = read_spreadsheet(
url="https://docs.google.com/spreadsheets/d/1qHgmwwg_kt3mhQtY3pFFimuAEom1AIxgThQ82_DdoHw/",
sheet_name=f"Student Mapping",
)
pst = pytz.timezone("US/Pacific")
lookup = {}
with app.app_context():
db.drop_all()
db.create_all()
users = {}
for row in staff_reader[1:]:
name, email, time, group, is_npe = row
is_npe = is_npe == "TRUE"
day, hour_str = time.split(" ")
if day == "Thu":
day = 21
elif day == "Wed":
day = 20
else:
assert False, f"Unknown day {day}"
hour = int(hour_str[:-2])
if hour_str[-2:] == "PM" and hour != 12:
hour += 12
start_time = pst.localize(
datetime(year=2021, month=1, day=day, hour=hour, minute=10)
)
end_time = start_time + timedelta(minutes=50)
if email not in users:
users[email] = User(email=email, name=name, is_staff=True)
section = Section(
id=group,
start_time=start_time.timestamp(),
end_time=end_time.timestamp(),
capacity=9,
staff=users[email],
)
if is_npe:
section.tags = ["NPE"]
lookup[group] = section
db.session.add(section)
for row in student_reader[1:]:
name, email, time, group, npe = row
lookup[group].students.append(User(email=email, name=name, is_staff=False))
db.session.commit()
<file_sep>/indexer/main.py
import re
from io import BytesIO
import requests
from PyPDF2 import pdf as pdf_reader
from PyPDF2.utils import PdfReadError
from bs4 import BeautifulSoup
from flask import Flask
from common.rpc.auth import PiazzaNetwork, piazza_course_id
from common.rpc.indexer import clear_resources, index_piazza, upload_resources
from common.rpc.search import (
clear_piazza,
clear_resources as clear_resources_worker,
insert_piazza,
insert_resources,
)
from common.rpc.secrets import only
SITE_DOMAIN = "https://cs61a.org"
PIAZZA_TEMPLATE = "https://piazza.com/class/{}?cid={}"
GOOGLE_DOC_PREFIX = "https://docs.google.com/document/"
GOOGLE_DOC_EXPORT_TEMPLATE = (
"https://docs.google.com/document/u/1/export?format=txt&id={}"
)
app = Flask(__name__, static_folder="")
@app.route("/search.js")
def search_js():
return app.send_static_file("search.js")
@app.route("/search.css")
def search_css():
return app.send_static_file("search.css")
@index_piazza.bind(app)
@only(["course-deploy", "buildserver"])
def index_piazza():
print("Starting to scrape Piazza")
piazza = PiazzaNetwork(course="cs61a", is_staff=False, is_test=False)
feed = piazza.get_feed(limit=10000)["feed"]
course_id = piazza_course_id()
clear_piazza()
posts = []
for post in feed:
if post["status"] == "private":
continue
i = post["nr"]
tags = post["folders"]
subject = post["subject"]
content = post["content_snipet"]
name = "@{} {}".format(i, subject)
link = PIAZZA_TEMPLATE.format(course_id, i)
indexedPost = {
"tags": tags,
"type": "Piazza Post",
"subject": subject,
"content": content,
"name": name,
"link": link,
"id": i,
}
posts.append(indexedPost)
insert_piazza(posts=posts)
print("Piazza scraping completed")
return {"success": True}
@clear_resources.bind(app)
@only(["course-deploy", "buildserver"])
def clear_resources():
clear_resources_worker()
return {"success": True}
@upload_resources.bind(app)
@only(["course-deploy", "buildserver"])
def upload_resources(resources):
print("Starting to scrape resource batch")
buffer = []
buffer_length = 0
resource: dict
for resource in resources:
content = resource.get("content", [])
html_content = resource.get("html_content", [])
pdf_content = resource.get("pdf_content", [])
for link in resource["links"]:
force_txt = False
if link.startswith(SITE_DOMAIN):
# data already in "*_content" attrs
continue
if link.startswith(GOOGLE_DOC_PREFIX):
fmt = re.compile(r"/d/(.*)/")
doc_id = fmt.search(link).group(1)
link = GOOGLE_DOC_EXPORT_TEMPLATE.format(doc_id)
force_txt = True
try:
if force_txt:
content.append(requests.get(link).text)
elif link.endswith(".html"):
html_content.append(requests.get(link).text)
elif link.endswith(".pdf"):
pdf_content.append(requests.get(link).content)
except requests.exceptions.ConnectionError:
continue
for html_data in html_content:
html_soup = BeautifulSoup(html_data, "html.parser")
for p in html_soup.find_all("p"):
content.append(p.get_text())
for pdf in pdf_content:
try:
reader = pdf_reader.PdfFileReader(BytesIO(pdf))
for page in range(reader.getNumPages()):
content.append(reader.getPage(page).extractText())
except PdfReadError:
continue
resource.pop("html_content", None)
resource.pop("pdf_content", None)
resource.pop("links", None)
buffer_length += sum(map(len, content))
buffer.append(resource)
if buffer_length > 10 ** 5 or resource == resources[-1]:
insert_resources(resources=buffer)
buffer = []
buffer_length = 0
print("Resource scraping completed")
return {"success": True}
if __name__ == "__main__":
app.run()
<file_sep>/oh/migrations/versions/c568f4d277de_add_config_field_to_toggle_okpy_backup_.py
"""add config field to toggle OKPy backup visibility
Revision ID: c568f4d277de
Revises: <KEY>
Create Date: 2020-04-06 14:22:14.162321
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "c568f4d277de"
down_revision = "<KEY>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="show_okpy_backups", value="false", public=True, course=course[0]
)
)
session.commit()
def downgrade():
pass
<file_sep>/domains/index.md
```{include} README.md
```
## Code Documentation
```{eval-rst}
.. automodule:: domains.main
:members:
```
<file_sep>/code/src/languages/lark/web/communication.js
import { RUN_LARK_CODE } from "../constants/communicationEnums";
import LarkClient from "./larkClient";
export default function receive(arg) {
if (arg.type === RUN_LARK_CODE) {
new LarkClient(arg.key).start(arg.code);
}
}
<file_sep>/oh/oh_queue/static/js/components/activity_log_layout.js
function ActivityLogLayout({ state }) {
const [activeTab, setActiveTab] = React.useState(0);
const [userList, setUserList] = React.useState([]);
const [isLoading, setIsLoading] = React.useState(false);
const [searchText, setSearchText] = React.useState("");
if (state.currentUser && !state.currentUser.isStaff) {
const { Redirect } = ReactRouterDOM;
return <Redirect to={`user/${state.currentUser.id}`} />;
}
if (app && !isLoading && userList.length === 0) {
setIsLoading(true);
app.makeRequest("list_users", (users) => {
setUserList(users);
});
}
const foundUsers = userList.filter(({ name, email }) =>
(name + email).toLowerCase().includes(searchText.toLowerCase())
);
return (
<div>
<Navbar state={state} mode="activity_log" />
<OfflineIndicator offline={state.offline && state.loaded} />
<div className="jumbotron">
<div className="container">
<h2> Activity Log </h2>
<p>View the activity of any user of the queue.</p>
<div className="form-group">
<form>
<div className="input-group appointment-input">
<input
className="form-control"
required="required"
placeholder="Search for a student or a member of staff"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
/>
<span className="input-group-btn">
<button className="btn btn-default" type="button">
Search
</button>
</span>
</div>
</form>
</div>
<div className="activity-buttons">
<Link
to={`/user/${state.currentUser && state.currentUser.id}`}
className="btn btn-primary"
>
My activity
</Link>
<Link className="btn btn-warning">Class Overview</Link>
</div>
</div>
</div>
<div className="container">
<Messages messages={state.messages} />
{searchText ? (
<Tabs selectedIndex={0} onClick={() => null}>
<Tab label={`Search Results (${foundUsers.length})`}>
<UserList users={foundUsers} />
</Tab>
</Tabs>
) : (
<Tabs selectedIndex={activeTab} onSelect={setActiveTab}>
<Tab label="Staff">
<UserList users={userList.filter(({ isStaff }) => isStaff)} />
</Tab>
<Tab label="Students">
<UserList users={userList.filter(({ isStaff }) => !isStaff)} />
</Tab>
</Tabs>
)}
</div>
</div>
);
}
function UserList({ users }) {
return (
<div className="queue">
{users.map((user) => (
<User user={user} />
))}
</div>
);
}
function User({ user }) {
return (
<Row
title={user.name}
link={`/user/${user.id}`}
prop1={user.email}
prop2={`Role: ${user.isStaff ? "Staff" : "Student"}`}
/>
);
}
<file_sep>/exam-alerts/Makefile
.PHONY: dev
dev:
export GOOGLE_APPLICATION_CREDENTIALS=$(shell pwd)/../creds.json; \
export FLASK_APP=examtool_web_common/run_local; \
export ENV=dev; \
yarn run concurrently "webpack --watch --mode development" "nodemon --exec python run_local.py"
<file_sep>/cats/src/HighScorePrompt.js
import React, { useState, useRef } from "react";
import Cookies from "js-cookie";
import Modal from "react-bootstrap/Modal";
import CaptchaChallenge from "./CaptchaChallenge";
import CaptchaPrompt from "./CaptchaPrompt";
import NameForm from "./NameForm";
import post from "./post";
export default function HighScorePrompt({
show,
onHide,
needVerify,
wpm,
onSubmit,
}) {
const [images, setImages] = useState([]);
const [lastWordLen, setLastWordLen] = useState([]);
const [message, setMessage] = useState("");
const [verified, setVerified] = useState(!needVerify);
const token = useRef(null);
if (!show && images.length) {
setImages([]);
}
const requestChallenge = async () => {
const {
images: receivedImages,
token: receivedToken,
lastWordLen: receivedLastWordLen,
} = await post("/request_wpm_challenge", {
user: Cookies.get("user"),
});
setImages(receivedImages);
setLastWordLen(receivedLastWordLen);
token.current = receivedToken;
};
const submitChallenge = async (typed) => {
const {
success,
message: failureMessage,
token: successToken,
} = await post("/claim_wpm_challenge", {
user: Cookies.get("user"),
token: token.current,
typed,
claimedWpm: wpm,
});
if (success) {
setVerified(true);
Cookies.set("token", successToken);
} else {
setMessage(`The server said: ${failureMessage} Please try again.`);
setImages([]);
}
};
const captcha = images.length ? (
<CaptchaChallenge
images={images}
lastWordLen={lastWordLen}
onSubmit={submitChallenge}
/>
) : (
<CaptchaPrompt message={message} onClick={requestChallenge} />
);
const contents = verified ? <NameForm onSubmit={onSubmit} /> : captcha;
return (
<Modal
size="md"
aria-labelledby="contained-modal-title-vcenter"
centered
show={show}
onHide={onHide}
>
<Modal.Header closeButton>
<Modal.Title className="Header">High Score</Modal.Title>
</Modal.Header>
<Modal.Body>{contents}</Modal.Body>
</Modal>
);
}
<file_sep>/ok-help/src/schema.js
class Flag {
constructor(shortForm, longForm, name, explanation) {
this.shortForm = shortForm;
this.longForm = longForm;
this.name = name;
this.explanation = explanation;
this.isValue = false;
}
}
class Value {
constructor(shortForm, longForm, name, explanation) {
this.shortForm = shortForm;
this.longForm = longForm;
this.name = name;
this.explanation = explanation;
this.isValue = true;
}
}
class Category {
constructor(name, explanation, mandatoryArgs, optionalArgs) {
this.name = name;
this.explanation = explanation;
this.mandatoryArgs = mandatoryArgs;
this.optionalArgs = optionalArgs;
}
}
const QUESTION_VALUE = new Value(
"q",
"question",
"Select Question",
"Choose which question you want to work on. If you don't set this " +
"option, okpy will go through all the questions!"
);
const VERBOSE_FLAG = new Flag(
"v",
"verbose",
"Verbose",
"Show the results of all tests, not just those that fail."
);
const ALL_FLAG = new Flag(
null,
"all",
"All",
"Run tests for all the questions in the config file, including optional questions."
);
const SUBMIT_FLAG = new Flag(
null,
"submit",
"Submit",
"Submit your progress so far on all questions in the assignment."
);
const REVISE_FLAG = new Flag(
null,
"revise",
"Revise",
"Submit your composition revisions for the assignment."
);
const BACKUP_FLAG = new Flag(
null,
"backup",
"Backup",
"Backup your progress so far on all questions in the assignment, without submitting."
);
const LOCAL_FLAG = new Flag(
null,
"local",
"Local",
"Run locally, without backing up to or downloading updates from the server."
);
const INTERACTIVE_FLAG = new Flag(
"i",
"interactive",
"Interactive Mode",
"Start the Python interpreter after a failed test, to help debug."
);
const VERSION_FLAG = new Flag(
null,
"version",
"Version",
"Print the current version of okpy and then exit."
);
const HELP_FLAG = new Flag(
"h",
"help",
"Help",
"Print the help message built into okpy and then exit."
);
const TESTS_FLAG = new Flag(
null,
"tests",
"View Tests",
"View all the test names available in the current assignment."
);
const AUTHENTICATE_FLAG = new Flag(
null,
"authenticate",
"Authenticate",
"Re-authenticate with okpy, even if you are already signed in."
);
const NO_BROWSER_FLAG = new Flag(
null,
"no-browser",
"No Browser",
"Do not use a web browser for authentication."
);
const UPDATE_FLAG = new Flag(
null,
"update",
"Update",
"Update okpy, if an update is available, and then exit."
);
const SCORE_FLAG = new Flag(
null,
"score",
"Score",
"Score all questions based on number of tests passed for each."
);
export default [
new Category(
"Unlock",
"You should unlock the test cases for each problem before solving it.",
[new Flag("u", "unlock", "Unlock")],
[QUESTION_VALUE, LOCAL_FLAG, NO_BROWSER_FLAG]
),
new Category(
"Run Tests",
"After writing code, you should test it against the provided test cases.",
[],
[
QUESTION_VALUE,
INTERACTIVE_FLAG,
VERBOSE_FLAG,
SCORE_FLAG,
ALL_FLAG,
LOCAL_FLAG,
NO_BROWSER_FLAG,
]
),
new Category(
"Submission",
"When you're ready, you can submit your code for us to grade.",
[],
[SUBMIT_FLAG, REVISE_FLAG, BACKUP_FLAG, NO_BROWSER_FLAG]
),
new Category(
"Advanced",
"Okpy is a powerful tool - try out some of the more advanced options!",
[],
[
AUTHENTICATE_FLAG,
TESTS_FLAG,
VERSION_FLAG,
NO_BROWSER_FLAG,
UPDATE_FLAG,
HELP_FLAG,
]
),
];
<file_sep>/slack/scripts/staff-emojify.py
import shutil, sys
from os import listdir, path
from collections import Counter
""" Takes in 2 arguments: an input directory staff images with filename format
firstname-lastname and an output directory. Returns a duplicate of all staff
images with filename in format firstname or firstname-lastinitial if multiple
staff members have the same firstname. Also returns mapping.txt in the output
folder, which lists the mapping between names and image titles."""
supported_types = (".png", ".jpg", ".jpeg", ".tiff")
images = []
for f in listdir(sys.argv[1]):
if f.lower().endswith(supported_types):
images.append(f)
else:
print("ignored " + f)
seen = set()
overlap = [
k for k, v in Counter(map(lambda i: i.split("-")[0], images)).items() if v > 1
]
mapping = ""
for image in images:
split = image.split(".")
names, extension = split[0].split("-"), split[1]
extension, splitname = image.split(".")[1], image.split(".")
if image.split("-")[0] in overlap:
mapping += f"{' '.join(names)} \t {names[0] + '-' + names[1][:1]}\n"
filename = path.join(
sys.argv[2], names[0] + "-" + names[1][:1] + "." + extension
)
else:
mapping += f"{' '.join(names)} \t {names[0]}\n"
filename = path.join(sys.argv[2], names[0] + "." + extension)
shutil.copyfile(path.join(sys.argv[1], image), filename)
print(mapping)
with open(path.join(sys.argv[2], "mapping.txt"), "w") as lst:
lst.write(mapping)
<file_sep>/redirect/README.md
# `redirect`
This utility sets up different redirects from the CS 61A website. To add new
redirects, edit the lookup dictionary in `main.py`. At the end of a semester,
edit `deploy.yaml` to include `<semester>.cs61a.org`. This target will
automatically redirect to `inst.eecs.berkeley.edu/~cs61a/<semester>`.
This app has no local setup instructions, because it is not meant to be run
locally.<file_sep>/exam-write/Makefile
.PHONY: dev
dev:
export MODE=write; \
export FLASK_APP=examtool_web_common/run_local; \
export ENV=dev; \
yarn run concurrently "webpack --watch" "python main.py"
<file_sep>/oh/oh_queue/static/js/components/slots_form.js
function SlotsForm({
assignments,
showEmail,
email,
onEmailChange,
selectedAssignment,
onSelectedAssignmentChange,
question,
onQuestionChange,
description,
onDescriptionChange,
}) {
return (
<form class="slots-form">
<div className="form-group form-group-lg">
{showEmail && (
<React.Fragment>
<input
className="form-control"
type="text"
name="email"
title="Student Email"
placeholder="<EMAIL>"
value={email}
onChange={(e) => onEmailChange(e.target.value)}
required
/>
<br />
</React.Fragment>
)}
<div className="input-group">
<SelectPicker
options={assignments}
value={selectedAssignment}
onChange={(e) => onSelectedAssignmentChange(e.target.value)}
className="selectpicker form-control form-left"
data-live-search="true"
data-size="8"
data-width="60%"
data-style="btn-lg btn-default"
name="assignment_id"
title="Assignment"
required
/>
<input
className="form-control form-right"
type="text"
name="question"
title="Question"
placeholder="Question"
value={question}
onChange={(e) => onQuestionChange(e.target.value)}
required
/>
</div>
<br />
<div className="input-group">
<textarea
className="description-box"
rows="5"
value={description}
onChange={(e) => onDescriptionChange(e.target.value)}
placeholder={
"It would be helpful if you could describe your" +
" main points of confusion. For example, \"I don't understand how" +
' tree recursion works." \n\nCourse staff will read your' +
" descriptions before the section so that we can better help you."
}
required
/>
</div>
</div>
</form>
);
}
<file_sep>/sections/src/AddSessionModal.js
// @flow strict
import * as React from "react";
import Button from "react-bootstrap/Button";
import ListGroup from "react-bootstrap/ListGroup";
import Modal from "react-bootstrap/Modal";
import styled from "styled-components";
import { sessionStartTimes } from "./models";
import type { Section } from "./models";
import useSectionAPI from "./useSectionAPI";
type Props = {
section: Section,
show: boolean,
onClose: () => void,
};
const FloatRightDiv = styled.div`
float: right;
`;
export default function AddSessionModel({ section, show, onClose }: Props) {
const startSession = useSectionAPI("start_session");
const startTimes = sessionStartTimes(section);
return (
<Modal show={show} onHide={onClose}>
<Modal.Header closeButton>
<Modal.Title>Add Missing Session</Modal.Title>
</Modal.Header>
<Modal.Body>
<ListGroup variant="flush">
{startTimes.map((startTime) => (
<ListGroup.Item>
{startTime.format("MMMM D")}{" "}
<FloatRightDiv>
<Button
size="sm"
onClick={() =>
startSession({
section_id: section.id,
start_time: startTime.unix(),
}).finally(onClose)
}
>
Add
</Button>
</FloatRightDiv>
</ListGroup.Item>
))}
</ListGroup>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={onClose}>
Close
</Button>
</Modal.Footer>
</Modal>
);
}
<file_sep>/oh/migrations/versions/ee50ab5f3371_added_appointments_tables.py
"""added appointments tables
Revision ID: <KEY>
Revises: 7857a34<PASSWORD>
Create Date: 2020-03-08 20:15:02.275445
"""
# revision identifiers, used by Alembic.
from sqlalchemy import orm
revision = "<KEY>"
down_revision = "7<PASSWORD>"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"appointment",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("start_time", sa.DateTime(), nullable=False),
sa.Column("duration", sa.Interval(), nullable=False),
sa.Column("capacity", sa.Integer(), nullable=False),
sa.Column("location_id", sa.Integer(), nullable=False),
sa.Column("helper_id", sa.Integer(), nullable=True),
sa.Column("status", oh_queue.models.db.String(length=255), nullable=False),
sa.Column("course", sa.String(length=255), nullable=False),
sa.ForeignKeyConstraint(
["helper_id"],
["user.id"],
),
sa.ForeignKeyConstraint(
["location_id"],
["location.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_appointment_helper_id"), "appointment", ["helper_id"], unique=False
)
op.create_index(
op.f("ix_appointment_location_id"), "appointment", ["location_id"], unique=False
)
op.create_index(
op.f("ix_appointment_start_time"), "appointment", ["start_time"], unique=False
)
op.create_index(
op.f("ix_appointment_status"), "appointment", ["status"], unique=False
)
op.create_table(
"appointment_signup",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("appointment_id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("assignment_id", sa.Integer(), nullable=True),
sa.Column("question", sa.String(length=255), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column(
"attendance_status", oh_queue.models.db.String(length=255), nullable=False
),
sa.Column("course", sa.String(length=255), nullable=False),
sa.ForeignKeyConstraint(
["appointment_id"],
["appointment.id"],
),
sa.ForeignKeyConstraint(
["assignment_id"],
["assignment.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["user.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_appointment_signup_appointment_id"),
"appointment_signup",
["appointment_id"],
unique=False,
)
op.create_index(
op.f("ix_appointment_signup_assignment_id"),
"appointment_signup",
["assignment_id"],
unique=False,
)
op.create_index(
op.f("ix_appointment_signup_user_id"),
"appointment_signup",
["user_id"],
unique=False,
)
# ### end Alembic commands ###
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="online_active", value="false", public=True, course=course[0]
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(
op.f("ix_appointment_signup_user_id"), table_name="appointment_signup"
)
op.drop_index(
op.f("ix_appointment_signup_assignment_id"), table_name="appointment_signup"
)
op.drop_index(
op.f("ix_appointment_signup_appointment_id"), table_name="appointment_signup"
)
op.drop_table("appointment_signup")
op.drop_index(op.f("ix_appointment_status"), table_name="appointment")
op.drop_index(op.f("ix_appointment_start_time"), table_name="appointment")
op.drop_index(op.f("ix_appointment_location_id"), table_name="appointment")
op.drop_index(op.f("ix_appointment_helper_id"), table_name="appointment")
op.drop_table("appointment")
# ### end Alembic commands ###
<file_sep>/ag-master/superadmin.py
from models import Assignment
from utils import super_admin_only
def create_superadmin_endpoints(app):
@app.route("/admin/<endpoint>")
@super_admin_only
def course_info_admin(endpoint):
assignments = Assignment.query.filter_by(endpoint=endpoint).all()
return {
"assignments": [
{
"name": a.name,
"file": a.file,
"command": a.command,
"assignment_secret": a.assignment_secret,
}
for a in assignments
],
}
<file_sep>/slack/clap_integration.py
import re
from integration import Integration
class ClapIntegration(Integration):
@property
def message(self):
if self._message.startswith(r"\kavi"):
return re.sub(
r"^\\kavi(.*)$",
lambda mat: ":kavi: ".join(mat.group(1).strip().split(" ")),
self._message,
)
return re.sub(
r"^\\clap(.*)$",
lambda mat: ":clap: ".join(mat.group(1).strip().split(" ")),
self._message,
)
<file_sep>/slack/emoji_integration.py
import random
import re
from string import punctuation
import requests
from integration import Integration
from staff import STAFF, STAFF_EMOJI
cached_names = {}
class EmojiIntegration(Integration):
@property
def message(self):
return process(self._message, self._token)
def get_name(id, token):
if id in cached_names:
return cached_names[id]
resp = requests.post(
"https://slack.com/api/users.info", {"token": token, "user": id}
)
out = resp.json()["user"]["real_name"]
cached_names[id] = out
return out
def can_get_name(id):
if " " in id or "@" in id:
return False
return True
def get_staff(word, token):
candidates = set()
if (
word.startswith("<@")
and word.endswith(">")
and token
and can_get_name(word[2:-1])
):
word = get_name(word[2:-1], token)
for staff in STAFF:
if (staff.firstName + " " + staff.lastName).lower() == word.lower():
candidates.add(staff)
for staff in STAFF:
if word.lower() == (staff.firstName + " " + staff.lastName[0]).lower():
candidates.add(staff)
for staff in STAFF:
if staff.firstName.lower() == word.lower():
candidates.add(staff)
if candidates:
return random.choice(list(candidates))
def strip_punctuation(word):
if word.startswith("<@") and word.endswith(">"):
return "", word, ""
rest = word.lstrip(punctuation)
leading = word[: len(word) - len(rest)]
stripped = rest.rstrip(punctuation)
trailing = rest[len(stripped) :]
return leading, stripped, trailing
def has_staff_emoji(text):
emojis = re.findall(":.+?:", text)
for emoji in emojis:
if emoji in STAFF_EMOJI:
return True
return False
def process(text, token):
text = text.replace("<@", " <@")
text = text.replace(" <@", " <@")
if text.startswith(" <@"):
text = text[1:]
words = text.split(" ")
if has_staff_emoji(text):
return text
for i, word in enumerate(words):
if not words[i]:
continue
if i != len(words) - 1:
next_word = words[i + 1]
combined = word + " " + next_word
leading, stripped, trailing = strip_punctuation(combined)
staff = get_staff(stripped, token)
if staff is not None:
words[i] = leading + combined + f" ({staff.emoji}) " + trailing
words[i + 1] = ""
continue
leading, stripped, trailing = strip_punctuation(word)
staff = get_staff(stripped, token)
if staff is None:
continue
words[i] = leading + stripped + f" ({staff.emoji})" + trailing
return " ".join(words)
<file_sep>/oh/migrations/prev_versions/42d3400175b3_add_description_field.py
"""Add description field
Revision ID: 42d3400175b3
Revises: 5<PASSWORD>
Create Date: 2017-02-24 14:31:48.263104
"""
# revision identifiers, used by Alembic.
revision = "42d3400175b3"
down_revision = "5e2ef12760a4"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("ticket", sa.Column("description", sa.Text(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("ticket", "description")
# ### end Alembic commands ###
<file_sep>/oh/oh_queue/static/js/components/admin_items_manager.js
function AdminItemsManager({ children, columns, itemType, items }) {
const [input, setInput] = React.useState("");
const [isLoading, setIsLoading] = React.useState(false);
const isValidInput = input
? !items.map((item) => item.name).includes(input)
: null;
const onChange = (input) => {
setInput(input);
};
const addItemInput = () => {
if (!isValidInput) {
return;
}
setIsLoading(true);
app.makeRequest(`add_${itemType}`, { name: input }, (success) => {
setIsLoading(false);
if (success) {
setInput("");
}
});
};
const formGroupClassNames = classNames({
"form-group": true,
"has-error": isValidInput === false,
"has-success": isValidInput === true,
});
return (
<div className="table-responsive">
<table className="table table-hover">
<thead>
<tr>
{columns.map((column) => (
<th key={column}>
<span>{column}</span>
</th>
))}
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id}>
{children(item).map((child, i) => (
<td key={i}>{child}</td>
))}
</tr>
))}
</tbody>
</table>
<table className="table table-hover">
<tbody>
<tr key="new">
<td>
<div className={formGroupClassNames}>
<input
className={`form-control`}
type="text"
minLength="1"
placeholder="Add new entry"
disabled={isLoading}
value={input}
onChange={(e) => onChange(e.target.value)}
/>
</div>
</td>
<td className="col-md-1">
<button
type="button"
className="btn btn-default"
disabled={!isValidInput || isLoading}
onClick={addItemInput}
>
{isLoading ? <div className="spinner-loading" /> : "Add"}
</button>
</td>
</tr>
</tbody>
</table>
</div>
);
}
<file_sep>/oh/oh_queue/__init__.py
import logging
# Flask-related stuff
from datetime import datetime, timedelta
from flask import Flask
from flask_compress import Compress
from common.jobs import job
from oh_queue import auth, assets
from oh_queue.models import (
Group,
GroupAttendance,
GroupAttendanceStatus,
GroupStatus,
db,
TicketStatus,
)
from oh_queue.slack import worker
logging.basicConfig(level=logging.INFO)
# Initialize the application
app = Flask(__name__)
app.config.from_object("config")
app.url_map.strict_slashes = False
app.jinja_env.globals.update(
{"TicketStatus": TicketStatus, "assets_env": assets.assets_env}
)
db.init_app(app)
auth.init_app(app)
# Import views
import oh_queue.views
@job(app, "slack_notify")
def slack_poll():
worker(app)
@job(app, "clear_inactive_groups")
def clear_inactive_groups():
active_groups = Group.query.filter_by(group_status=GroupStatus.active).all()
for group in active_groups:
for attendance in group.attendees:
if (
attendance.group_attendance_status == GroupAttendanceStatus.present
and attendance.user.heartbeat_time
and attendance.user.heartbeat_time
> datetime.utcnow() - timedelta(minutes=3)
):
break
else:
oh_queue.views.delete_group_worker(group, emit=False)
db.session.commit()
# Caching
@app.after_request
def after_request(response):
cache_control = "no-store"
response.headers.add("Cache-Control", cache_control)
return response
Compress(app)
<file_sep>/exam-alerts/requirements.txt
# my deps
google-cloud-firestore
google-cloud-texttospeech
google-auth
cryptography
<file_sep>/code/src/renderer/utils/help.js
// eslint-disable-next-line import/prefer-default-export
export function openHelp() {
window.open("https://cs61a.org/articles/61a-code-docs");
}
<file_sep>/code/src/languages/python/utils/test.js
import { DOCTEST_MARKER } from "../../../renderer/components/File";
import { runPyCode } from "./run";
export default function test(code, onSuccess, onError) {
let commandSent = false;
const [interactCallback, killCallback, detachCallback] = runPyCode(
code,
(out) => {
if (!out.startsWith(DOCTEST_MARKER)) {
return;
}
const rawData = out.slice(DOCTEST_MARKER.length);
// eslint-disable-next-line no-eval
const doctestData = (0, eval)(rawData);
killCallback();
onSuccess(doctestData);
},
(err) => {
if (err.trim() !== ">>>") {
// something went wrong in setup
killCallback();
detachCallback();
onError(err.trim());
commandSent = true;
}
if (!commandSent) {
commandSent = true;
interactCallback("__run_all_doctests()\n");
}
},
() => {}
);
return () => {
detachCallback();
killCallback();
};
}
<file_sep>/cats/README.md
# Cats
## Developing
1. Run `yarn` to install dependencies - do this when you first download it!
2. Run `cd server && python flask_app.py & yarn start` - start web server and webpack dev server
## Deploying
1. Once you're satisfied with your changes, make a PR in cs61a-apps
2. See the PR in action at <pr_num>.cats.pr.cs61a.org
3. When the PR is merged, it will automatically be deployed with our `hosted` deploy tool!
<file_sep>/code/src/languages/lark/web/larkClient.js
/* eslint-disable no-await-in-loop */
import $ from "jquery";
import { registerProcess } from "../../../main/processes";
import { exit, out, err } from "../../../web/webBackend";
import { PS1, PS2 } from "../constants/prompts";
import extractLarkTests from "./extractLarkTests";
export default class LarkClient {
constructor(key) {
this.key = key;
this.grammar = null;
this.cases = null;
this.inputQueue = [];
this.blocked = false;
this.multiline = false;
this.multilineInput = [];
this.treeview = true;
this.stopped = false;
}
receive = (code) => {
const { grammar, cases } = extractLarkTests(code);
this.grammar = grammar;
this.cases = cases;
};
start = async (code) => {
registerProcess(this.key, {
stdin: {
write: (line) => {
this.inputQueue.push(line);
this.run();
},
},
kill: () => {
this.stop();
exit(this.key, "\n\nLark client stopped.");
},
});
try {
this.receive(code);
} catch (e) {
console.error(e);
err(this.key, e.toString());
exit(this.key, "\n\nLark client stopped.");
return;
}
const { error } = await this.larkRun();
if (error) {
err(this.key, error);
exit(this.key, "\n\nLark client stopped.");
} else {
err(this.key, PS1);
}
};
test = async (code) => {
this.receive(code);
const { error: grammarError } = await this.larkRun();
if (grammarError) {
throw Error(grammarError);
}
const results = [];
for (let i = 0; i !== this.cases.length; ++i) {
const testCase = this.cases[i];
const caseName =
testCase.caseName ||
(this.cases.length === 1 ? "Doctests" : `Case ${i + 1}`);
for (const { input, output } of testCase.tests) {
const lines = input.split("\n");
const caseCode = [
PS1 + lines[0],
...lines.slice(1).map((line) => PS2 + line),
];
const result = {
name: [caseName, input],
rawName: `${caseName} > ${input}`,
code: [input],
};
const { success, error, repr } = await this.larkRun(input);
if (success) {
result.success = repr.trim() === output.trim();
result.raw = (
result.success
? [...caseCode, output]
: [...caseCode, "Expected:", output, "Received:", repr]
).join("\n");
} else {
result.success = false;
result.raw = [
...caseCode,
"Expected:",
output,
"Received:",
error,
].join("\n");
}
results.push(result);
}
}
return results;
};
stop = () => {
this.stopped = true;
};
run = async () => {
if (this.blocked) {
return;
}
this.blocked = true;
while (this.inputQueue.length > 0) {
const line = this.inputQueue.shift();
if (this.multiline) {
if (line.trim() === ".end") {
await this.parse(this.multilineInput.join(""));
this.multiline = false;
} else {
this.multilineInput.push(line);
}
} else if (line.trim() === ".begin") {
this.multiline = true;
this.multilineInput = [];
} else if (line.trim() === ".toggleviz") {
this.treeview = !this.treeview;
out(this.key, `Tree view ${this.treeview ? "enabled" : "disabled"}.\n`);
} else {
await this.parse(line.slice(0, line.length - 1));
}
if (this.multiline) {
err(this.key, PS2);
} else {
err(this.key, PS1);
}
}
this.blocked = false;
};
parse = async (text) => {
const { success, error, parsed, repr } = await this.larkRun(text);
if (success) {
if (this.treeview) {
out(this.key, `DRAW: ${JSON.stringify(["Tree", parsed])}`);
} else {
out(this.key, repr);
}
} else {
err(this.key, error);
}
};
larkRun = (text) => {
if (this.stopped) {
return { success: false, error: "The process has stopped." };
}
return $.post("/api/lark_run", {
grammar: this.grammar,
text,
}).catch((error) => {
console.error(error);
return { success: false, error: "An internal error occurred." };
});
};
}
<file_sep>/oh/oh_queue/static/js/state.js
/* This file contains functions for manipulating the global state of the app.
*
* This file uses flow type annotations for greater safety. To typecheck, run
* npm run-script flow
*/
type User = {
id: number,
email: string,
name: string,
shortName: string,
isStaff: boolean,
call_url: ?string,
doc_url: ?string,
};
type Ticket = {
id: number,
status:
| "pending"
| "assigned"
| "resolved"
| "deleted"
| "juggled"
| "rerequested",
user: User,
created: string, // ISO 8601 datetime string
sort_key: string, // ISO 8601 datetime string
rerequest_threshold: ?string, // ISO 8601 datetime string
hold_time: ?string, // ISO 8601 datetime string
rerequest_time: ?string, // ISO 8601 datetime string
updated: ?string,
location_id: number,
assignment_id: number,
question: string,
description: ?string,
helper: ?User,
call_url: string,
doc_url: string,
group_id: number,
};
type TicketAssignment = {
id: number,
name: string,
};
type TicketLocation = {
id: number,
name: string,
};
type Filter = {
/* Selected options. null means do not filter by an attribute. */
assignment_id: ?number,
location_id: ?number,
question: ?string,
};
type Message = {
id: number,
category: string, // e.g. "danger", "warning"
text: string,
visible: boolean,
};
type Appointment = {
id: number,
start_time: string, // datetime string
duration: number, // seconds
signups: Array<Signup>,
capacity: number,
location_id: number,
helper: ?User,
status: "pending" | "active" | "resolved",
};
type Signup = {
id: number,
assignment_id: number,
user: ?User,
question: ?string,
description: ?string,
attendance_status: "unknown" | "present" | "excused" | "absent",
};
type Group = {
id: number,
attendees: Array<GroupAttendance>,
location_id: number,
ticket_id: ?number,
assignment_id: number,
question: ?string,
description: ?string,
group_status: "active" | "resolved",
call_url: string,
doc_url: string,
};
type GroupAttendance = {
id: number,
group_id: number,
user: User,
group_attendance_status: "present" | "gone",
};
type State = {
/* May be null if the user is not logged in. */
currentUser: ?User,
/* True on page load, before the initial websocket connection. */
loaded: boolean,
/* True if the websocket has disconnected. */
offline: boolean,
/* Ticket assignments */
assignments: Map<number, TicketAssignment>,
appointments: Array<Appointment>,
groups: Array<Group>,
/* Ticket locations */
locations: Map<number, TicketLocation>,
/* Server configuration */
config: { [string]: string },
/* All known tickets, including ones that have been resolved or deleted.
* We may have to load past tickets asynchronously though.
* This is an ES6 Map from ticket ID to the ticket data.
*/
tickets: Map<number, Ticket>,
/* Ticket IDs for any tickets we are currently loading. */
loadingTickets: Set<number>,
/* Current ticket filter. */
filter: Filter,
/* Selected queue tab. */
queueTabIndex: number,
/* Flashed messages. */
messages: Array<Message>,
nextMessageID: number,
};
let initialState: State = {
currentUser: null,
loaded: false,
offline: true,
assignments: {},
locations: {},
config: {},
appointments: [],
groups: [],
tickets: new Map(),
loadingTickets: new Set(),
filter: {
location_id: null,
assignment_id: null,
question: null,
},
queueTabIndex: 0,
messages: [],
nextMessageID: 1,
};
const referenceTimeZone = "America/Los_Angeles";
const currTimeZone = moment.tz.guess();
function ticketDisplayTime(ticket: Ticket): string {
return moment.utc(ticket.created).local().format("h:mm A");
}
function ticketTimeAgo(ticket: Ticket | Group): string {
return moment.utc(ticket.created).fromNow();
}
function ticketTimeSinceAssigned(ticket: Ticket): string {
return moment.utc(ticket.updated).fromNow();
}
function ticketTimeToReRequest(ticket: Ticket): string {
return moment.utc(ticket.rerequest_threshold).fromNow();
}
function isPending(ticket: Ticket): boolean {
return ticket.status === "pending";
}
function isActive(ticket: Ticket): boolean {
return ["pending", "assigned", "juggled", "rerequested"].includes(
ticket.status
);
}
function ticketAssignment(state: State, ticket: Ticket): TicketAssignment {
return state.assignments[ticket.assignment_id];
}
function ticketLocation(state: State, ticket: Ticket): TicketLocation {
return state.locations[ticket.location_id];
}
function ticketQuestion(state: State, ticket: Ticket | Group): string {
var question = ticket.question;
if (!isNaN(question)) {
question = "Q" + parseInt(question);
}
return question;
}
function ticketStatus(state: State, ticket: Ticket): string {
if (ticket.status === "assigned" && ticket.helper) {
return (
"Being helped by " +
(isTicketHelper(state, ticket) ? "you" : ticket.helper.name)
);
} else if (ticket.status === "resolved") {
if (ticket.helper) {
return "Resolved by " + ticket.helper.name;
} else {
return "Resolved";
}
} else if (ticket.status === "deleted") {
return "Deleted";
} else if (ticket.status === "juggled") {
return ticket.group_id ? "Working in a group" : "Working solo";
} else if (ticket.status === "rerequested") {
return `Waiting for ${
isTicketHelper(state, ticket)
? "you"
: ticket.helper
? ticket.helper.name
: "any assistant"
} to come back`;
} else {
return "Queued";
}
}
function ticketPosition(state: State, ticket: Ticket): ?string {
let index = getTickets(state, "pending").findIndex(
(pendingTicket) => pendingTicket.id === ticket.id
);
if (index != -1) {
return "#" + (index + 1);
}
}
function isStaff(state: State): boolean {
return state.currentUser != null && state.currentUser.isStaff;
}
function getTicket(state: State, id: number): ?Ticket {
return state.tickets.get(id);
}
function setTicket(state: State, ticket: Ticket): void {
if (ticketIsMine(state, ticket, true)) {
let oldTicket = getMyTicket(state);
if (oldTicket) {
if (oldTicket.status === "pending" && ticket.status === "assigned") {
var location = ticketLocation(state, ticket);
notifyUser(
"Your name is being called",
ticket.helper.name + " is looking for you in " + location.name,
ticket.id + ".assign"
);
} else if (
oldTicket.status === "assigned" &&
ticket.status !== "assigned"
) {
cancelNotification(ticket.id + ".assign");
}
}
}
if (isStaff(state)) {
const oldTicket = getTicket(state, ticket.id);
if (!oldTicket && ticket.status === "pending") {
const assignment = ticketAssignment(state, ticket);
const location = ticketLocation(state, ticket);
const question = ticketQuestion(state, ticket);
notifyUser(
"New request for " + assignment.name + " " + question,
location.name,
ticket.id + ".create"
);
} else if (ticket.status !== "pending") {
cancelNotification(ticket.id + ".create");
}
}
state.tickets.set(ticket.id, ticket);
}
function loadTicket(state: State, id: number): void {
state.loadingTickets.add(id);
}
function isLoading(state: State, id: number): boolean {
return state.loadingTickets.has(id);
}
function receiveTicket(state: State, id: number, ticket: ?Ticket) {
if (ticket != null) {
setTicket(state, ticket);
}
state.loadingTickets.delete(id);
}
/* Return an array of pending tickets, sorted by queue time.
*/
function getTickets(state: State, status: string): Array<Ticket> {
return Array.from(state.tickets.values())
.filter((ticket) => ticket.status === status)
.sort((a, b) => {
if (a.sort_key < b.sort_key) {
return -1;
} else if (a.sort_key > b.sort_key) {
return 1;
} else {
return 0;
}
});
}
function applyFilter(filter: Filter, tickets: Array<Ticket>): Array<Ticket> {
let assignmentId = parseInt(filter.assignment_id);
if (!isNaN(assignmentId)) {
tickets = tickets.filter((ticket) => ticket.assignment_id === assignmentId);
}
let locationId = parseInt(filter.location_id);
if (!isNaN(locationId)) {
tickets = tickets.filter((ticket) => ticket.location_id === locationId);
}
if (filter.question) {
tickets = tickets.filter((ticket) => ticket.question === filter.question);
}
return tickets;
}
function ticketIsMine(
state: State,
ticket: Ticket,
includeGroup: boolean
): boolean {
return (
state.currentUser != null &&
((ticket.user && state.currentUser.id === ticket.user.id) ||
(includeGroup &&
getMyGroup(state) &&
getMyGroup(state).id === ticket.group_id))
);
}
function isTicketHelper(state: State, ticket: Ticket): boolean {
return (
state.currentUser &&
ticket.helper &&
state.currentUser.id === ticket.helper.id
);
}
/* Return the current user's active ticket. */
function getMyTicket(state: State): ?Ticket {
return Array.from(state.tickets.values()).find(
(ticket) => isActive(ticket) && ticketIsMine(state, ticket)
);
}
/* Return the first ticket the current user is helping. */
function getHelpingTicket(state: State): ?Ticket {
return Array.from(state.tickets.values()).find(
(ticket) => isActive(ticket) && isTicketHelper(state, ticket)
);
}
function addMessage(state: State, text: string, category: string): void {
state.messages.push({
id: state.nextMessageID,
text,
category,
visible: true,
});
state.nextMessageID += 1;
}
function clearMessage(state: State, id: number): void {
let message = state.messages.find((message) => message.id === id);
if (message) {
message.visible = false;
}
}
const timeComparator = (a, b) => (a.isAfter(b) ? 1 : -1);
const appointmentTimeComparator = (a, b) =>
moment(a.start_time).isSame(moment(b.start_time))
? b.id - a.id
: moment(a.start_time).isAfter(moment(b.start_time))
? 1
: -1;
function getMySignups(state: State) {
if (!state.currentUser) {
return [];
}
const mySignups = [];
for (const appointment of state.appointments) {
for (const signup of appointment.signups) {
if (signup.user && signup.user.id === state.currentUser.id) {
mySignups.push({ appointment, signup });
}
}
}
return mySignups;
}
function isSoon(appointment) {
return getAppointmentStartTime(appointment).isBefore(
moment().add(2, "hours")
);
}
function getMyAppointmentsStaff(state: State) {
if (!state.currentUser) {
return [];
}
const myAppointments = [];
for (const appointment of state.appointments) {
if (
(!appointment.helper && appointment.status === "pending") ||
(appointment.helper && appointment.helper.id === state.currentUser.id)
) {
myAppointments.push(appointment);
}
}
return myAppointments;
}
function getAppointment(state: State, appointment_id: number): Appointment {
return state.appointments.find(({ id }) => id === appointment_id);
}
function setAppointment(
state: State,
appointment: Appointment,
redirect,
lookup: ?Array<Appointment>
): void {
if (!appointment.id) {
return;
}
const oldAppointment = lookup
? lookup[appointment.id]
: getAppointment(state, appointment.id);
if (appointmentIncludesMe(state, appointment)) {
if (oldAppointment) {
if (
oldAppointment.status === "pending" &&
appointment.status === "active"
) {
notifyUser(
"Your appointment has started",
appointment.helper.name +
" is waiting for you in " +
state.locations[appointment.location_id].name,
appointment.id + ".appointment.assign"
);
redirect();
} else if (
oldAppointment.status === "active" &&
appointment.status !== "active"
) {
cancelNotification(appointment.id + ".appointment.assign");
}
}
}
if (!lookup) {
if (oldAppointment) {
state.appointments.splice(state.appointments.indexOf(oldAppointment), 1);
}
state.appointments.push(appointment);
state.appointments.sort(appointmentTimeComparator);
}
}
function appointmentIncludesMe(state: State, appointment: Appointment) {
if (!appointment.signups) {
return false;
}
for (const signup of appointment.signups) {
if (
signup.user &&
state.currentUser &&
signup.user.id === state.currentUser.id
) {
return true;
}
}
return false;
}
function getAppointmentStartTime(appointment) {
return moment.tz(appointment.start_time, referenceTimeZone).tz(currTimeZone);
}
function getAppointmentEndTime(appointment) {
return getAppointmentStartTime(appointment).add(
appointment.duration,
"seconds"
);
}
function formatAppointmentDate(appointment) {
return getAppointmentStartTime(appointment).format("dddd, MMMM D");
}
function formatAppointmentDuration(appointment) {
if (currTimeZone === referenceTimeZone) {
return `${getAppointmentStartTime(appointment).format(
"h:mma"
)}โ${getAppointmentEndTime(appointment).format("h:mma")}`;
} else {
return `${getAppointmentStartTime(appointment).format(
"h:mma"
)}โ${getAppointmentEndTime(appointment).format(
"h:mma z"
)} (UTC${getAppointmentEndTime(appointment).format("Z")})`;
}
}
function formatAppointmentDurationWithDate(appointment) {
if (currTimeZone === referenceTimeZone) {
return `${getAppointmentStartTime(appointment).format(
"dddd, MMMM D"
)} at ${getAppointmentStartTime(appointment).format(
"h:mma"
)}โ${getAppointmentEndTime(appointment).format("h:mma")}`;
} else {
return `${getAppointmentStartTime(appointment).format(
"dddd, MMMM D"
)} at ${getAppointmentStartTime(appointment).format(
"h:mma"
)}โ${getAppointmentEndTime(appointment).format(
"h:mma z"
)} (UTC${getAppointmentEndTime(appointment).format("Z")})`;
}
}
function getGroup(state: State, group_id: number): Group {
return state.groups.find(({ id }) => id === group_id);
}
function setGroup(state: State, group: Group): void {
if (!group.id) {
return;
}
const oldGroup = getGroup(state, group.id);
if (oldGroup) {
state.groups.splice(state.groups.indexOf(oldGroup), 1);
}
state.groups.push(group);
state.groups.sort((group) => group.id);
}
function groupIsActive(group: Group): boolean {
return group.group_status === "active";
}
function groupIsMine(state: State, group: Group): boolean {
return (
state.currentUser &&
group.attendees.some(
(attendance) => attendance.user.id === state.currentUser.id
)
);
}
function getMyGroup(state: State): ?Ticket {
return Array.from(state.groups.values()).find(
(group) => groupIsActive(group) && groupIsMine(state, group)
);
}
<file_sep>/common/shell_utils.py
import os
import subprocess
import sys
from contextlib import contextmanager
from io import BytesIO
from shutil import rmtree
from typing import List, TextIO, Union
from typing.io import IO
def sh(
*args,
env={},
capture_output=False,
stream_output=False,
quiet=False,
shell=False,
cwd=None,
inherit_env=True,
):
"""Run a command on the command-line and optionally return output.
:param args: a variable number of arguments representing the command to
pass into :class:`~subprocess.Popen` or :func:`~subprocess.run`
:type args: *str
:param env: environment variables to set up the command environment with
:type env: dict
:param capture_output: a flag to return output from the command; uses
:class:`~subprocess.Popen`
:type capture_output: bool
:param stream_output: a flag to stream output from the command; uses
:func:`~subprocess.run`
:type stream_output: bool
:param quiet: a flag to run the command quietly; suppressed printed output
:type quiet: bool
:param shell: a flag to run the command in a full shell environment
:type shell: bool
:param cwd: the working directory to run the command in; current directory
is used if omitted
:type cwd: str
:param inherit_env: a flag to include :obj:`os.environ` in the environment;
``True`` by default
:type inherit_env: bool
.. warning::
Only one of ``capture_output`` and ``stream_output`` can be ``True``.
"""
assert not (
capture_output and stream_output
), "Cannot both capture and stream output"
if shell:
args = [" ".join(args)]
if inherit_env:
env = {**os.environ, **env, "ENV": "dev"}
if stream_output:
out = subprocess.Popen(
args,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1,
shell=shell,
cwd=cwd,
)
def generator():
while True:
line = out.stdout.readline()
yield line
returncode = out.poll()
if returncode is not None:
if returncode != 0:
# This exception will not be passed to the RPC handler,
# so we need to handle it ourselves
raise subprocess.CalledProcessError(returncode, args, "", "")
else:
return ""
return generator()
elif capture_output:
out = subprocess.run(
args, env=env, capture_output=capture_output, shell=shell, cwd=cwd
)
else:
out = subprocess.run(
args, env=env, stdout=subprocess.PIPE, shell=shell, cwd=cwd
)
if capture_output and not quiet:
print(out.stdout.decode("utf-8"), file=sys.stdout)
print(out.stderr.decode("utf-8"), file=sys.stderr)
out.check_returncode()
return out.stdout
def clean_all_except(folders: List[str]):
for dirpath, _, filenames in os.walk("."):
dirnames = dirpath.split(os.sep)[1:]
if not dirnames:
for filename in filenames:
os.remove(filename)
elif dirnames[0] not in folders:
rmtree(dirpath)
@contextmanager
def tmp_directory(*, clean=False):
main_dir = os.getcwd()
if clean:
sh("rm", "-rf", "tmp")
os.mkdir("tmp")
try:
os.chdir("tmp")
yield None
finally:
os.chdir(main_dir)
@contextmanager
def redirect_descriptor(
src: Union[IO, TextIO, BytesIO], target: Union[IO, TextIO, BytesIO]
):
src_fd: int = src.fileno()
alt_src_fd = os.dup(src_fd)
src.flush()
os.dup2(target.fileno(), src_fd)
try:
yield src
finally:
src.flush()
os.dup2(alt_src_fd, src_fd)
<file_sep>/hog-contest/process_input.py
../hog-calc/process_input.py<file_sep>/sicp/sicp/clone.py
import click
from common.shell_utils import sh
import os, sys
from subprocess import CalledProcessError
HTTPS = "https://github.com/"
SSH = "git@github.com:"
@click.command()
@click.argument("repo")
@click.argument("dest", default="")
@click.option("--ssh", is_flag=True)
def clone(repo, dest, ssh):
"""Clone REPO into DEST.
REPO is the name of the 61a repo to set up.
Currently, "apps" and "cs61a" are supported.
By default, DEST is set to the name of REPO.
If you want to clone over SSH, use the SSH
option.
"""
if repo == "apps":
run_apps_clone(dest if dest else "cs61a-apps", SSH if ssh else HTTPS)
elif repo == "cs61a":
run_61a_clone(dest if dest else "berkeley-cs61a", SSH if ssh else HTTPS)
else:
click.echo("No need to use sicp for that! Just git clone.", err=True)
def run_apps_clone(dir, protocol):
print("========== Cloning cs61a-apps ==========")
sh("git", "clone", f"{protocol}Cal-CS-61A-Staff/cs61a-apps", dir)
print("========== Linking .githooks ===========")
os.chdir(dir)
sh("chmod", "+x", ".githooks/pre-commit")
sh("git", "config", "core.hooksPath", ".githooks")
print("====== Installing Black & Prettier =====")
if "black" not in sh("pip3", "list", quiet=True).decode("utf-8"):
sh("pip3", "install", "black")
try:
if "prettier" not in sh("npm", "list", "-g", quiet=True).decode("utf-8"):
sh("sudo", "npm", "install", "-g", "prettier")
except CalledProcessError:
print(
"Failed to install prettier globally as needed! "
+ "Make sure you have npm installed and have sudo privileges.",
file=sys.stderr,
)
print("================ Done! =================")
def run_61a_clone(dir, protocol):
print("======== Cloning berkeley-cs61a ========")
sh("git", "clone", f"{protocol}Cal-CS-61A-Staff/berkeley-cs61a", dir)
print("================ Done! =================")
<file_sep>/contest_utils/rate_limiting.py
import time
from functools import wraps
from flask import abort, current_app, request
from common.course_config import get_endpoint
from common.db import connect_db
from contest_utils.oauth import create_remote
def validate(data, timeout):
for participation in data["participations"]:
if participation["course"]["offering"] == get_endpoint("cs61a"):
break
else:
abort(
401, "You are not enrolled in CS 61A, and so are not authorized to submit."
)
email = data["email"]
with connect_db() as db:
ret = db(
"SELECT last_access FROM accesses WHERE email=(%s)", [email]
).fetchone()
now = int(time.time())
if ret and now - ret[0] < timeout:
abort(
429,
"You have made many requests in a short amount of time. Please wait a bit and try again.",
)
with connect_db() as db:
db("DELETE FROM accesses WHERE email=(%s)", [email])
db("INSERT INTO accesses VALUES (%s, %s)", [email, now])
def ratelimited(timeout):
def decorator(route):
@wraps(route)
def wrapper(*args, **kwargs):
remote = create_remote(current_app)
token = request.form["token"]
data = remote.get("user", token=token).data["data"]
validate(data, timeout.total_seconds())
return route(*args, **kwargs)
return wrapper
return decorator
<file_sep>/oh/oh_queue/auth.py
from flask import Blueprint, abort, redirect, render_template, request, session
from flask_login import LoginManager, login_user, logout_user, current_user
from flask_oauthlib.client import OAuth, OAuthException
from werkzeug import security
from common.course_config import get_course
from common.url_for import url_for
from oh_queue.models import db, User, ConfigEntry
auth = Blueprint("auth", __name__)
auth.config = {}
oauth = OAuth()
@auth.record
def record_params(setup_state):
app = setup_state.app
server_url = app.config.get("OK_SERVER_URL")
auth.ok_auth = oauth.remote_app(
"ok-server",
consumer_key=app.config.get("OK_KEY"),
consumer_secret=app.config.get("OK_SECRET"),
request_token_params={"scope": "email", "state": lambda: security.gen_salt(10)},
base_url=server_url + "/api/v3/",
request_token_url=None,
access_token_method="POST",
access_token_url=server_url + "/oauth/token",
authorize_url=server_url + "/oauth/authorize",
)
auth.debug = app.config.get("DEBUG")
@auth.ok_auth.tokengetter
def get_access_token(token=None):
return session.get("access_token")
login_manager = LoginManager()
@login_manager.user_loader
def load_user(user_id):
return User.query.filter_by(id=user_id, course=get_course()).one_or_none()
@login_manager.unauthorized_handler
def unauthorized():
session["after_login"] = request.url
return redirect(url_for("auth.login"))
def authorize_user(user):
login_user(user, remember=True)
return redirect(url_for("index"))
def user_from_email(name, email, is_staff):
"""Get a User with the given email, or create one."""
from common.course_config import get_course
user = User.query.filter_by(email=email, course=get_course()).one_or_none()
if not user:
user = User(name=name, email=email, course=get_course(), is_staff=is_staff)
else:
user.name = name
user.is_staff = is_staff
user.course = get_course()
db.session.add(user)
db.session.commit()
return user
@auth.route("/login/", strict_slashes=False)
def login():
callback = url_for(".authorized", _external=True)
return auth.ok_auth.authorize(callback=callback)
@auth.route("/assist/", strict_slashes=False)
def try_login():
if current_user.is_authenticated:
return redirect(url_for("index"))
callback = url_for(".authorized", _external=True)
return auth.ok_auth.authorize(callback=callback)
@auth.route("/login/authorized", strict_slashes=False)
def authorized():
from common.course_config import get_endpoint
message = request.args.get("error")
if message:
message = "Ok OAuth error: %s" % (message)
return redirect(url_for("error", message=message))
try:
auth_resp = auth.ok_auth.authorized_response()
if auth_resp is None:
message = "Invalid Ok response: %s" % (message)
return redirect(url_for("error", message=message))
except OAuthException as ex:
message = str(ex)
return redirect(url_for("error", message=message))
token = auth_resp["access_token"]
session["access_token"] = (token, "") # (access_token, secret)
info = auth.ok_auth.get("user").data["data"]
email = info["email"]
name = info["name"]
if not name:
name = email
if ", " in name:
last, first = name.split(", ")
name = first + " " + last
is_staff = False
offering = get_endpoint()
for p in info["participations"]:
if p["course"]["offering"] == offering:
if p["role"] != "student":
is_staff = True
else:
is_staff = False
break
else:
if (
ConfigEntry.query.filter_by(
course=get_course(), key="only_registered_students"
)
.one()
.value
== "true"
):
return redirect(
url_for(
"error",
message="Only registered students can log in",
)
)
user = user_from_email(name, email, is_staff)
return authorize_user(user)
@auth.route("/logout/", strict_slashes=False)
def logout():
logout_user()
session.pop("access_token", None)
return redirect(url_for("index"))
@auth.route("/testing-login/", strict_slashes=False)
def testing_login():
if not auth.debug:
abort(404)
callback = url_for(".testing_authorized")
return render_template("login.html", callback=callback)
@auth.route("/testing-login/authorized", methods=["POST"], strict_slashes=False)
def testing_authorized():
if not auth.debug:
abort(404)
form = request.form
is_staff = form.get("is_staff") == "on"
user = user_from_email(form["name"], form["email"], is_staff)
return authorize_user(user)
def init_app(app):
app.register_blueprint(auth)
login_manager.init_app(app)
<file_sep>/sicp/sicp/__main__.py
import sys
from warnings import warn
import click, os
from sicp.build import build
from sicp.clone import clone
from sicp.venv import venv
from sicp.pr import pr
from sicp.auth import auth
from sicp.send import send
from common.rpc.auth_utils import set_token_path
@click.group()
def cli():
"""
This is an experimental general-purpose 61A task runner.
"""
set_token_path(f"{os.path.expanduser('~')}/.sicp_token")
cli.add_command(clone)
cli.add_command(build)
cli.add_command(venv)
cli.add_command(pr)
cli.add_command(auth)
cli.add_command(send)
if sys.version_info[0] == 3 and sys.version_info[1] < 8:
warn("sicp may not work properly on versions of Python before 3.8")
if __name__ == "__main__":
cli()
<file_sep>/oh/migrations/prev_versions/5e2ef12760a4_create_database.py
"""Create database
Revision ID: 5e2ef12760a4
Revises: None
Create Date: 2017-02-24 14:18:24.856934
"""
# revision identifiers, used by Alembic.
revision = "5e2ef12760a4"
down_revision = None
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"user",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created", sa.DateTime(), nullable=True),
sa.Column("email", sa.String(length=255), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("is_staff", sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_user_email"), "user", ["email"], unique=False)
op.create_table(
"ticket",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("created", sa.DateTime(), nullable=True),
sa.Column("updated", sa.DateTime(), nullable=True),
sa.Column("status", oh_queue.models.db.String(length=255), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("assignment", sa.String(length=255), nullable=False),
sa.Column("question", sa.String(length=255), nullable=False),
sa.Column("location", sa.String(length=255), nullable=False),
sa.Column("helper_id", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
["helper_id"],
["user.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["user.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_ticket_created"), "ticket", ["created"], unique=False)
op.create_index(op.f("ix_ticket_helper_id"), "ticket", ["helper_id"], unique=False)
op.create_index(op.f("ix_ticket_status"), "ticket", ["status"], unique=False)
op.create_index(op.f("ix_ticket_user_id"), "ticket", ["user_id"], unique=False)
op.create_table(
"ticket_event",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("time", sa.DateTime(), nullable=True),
sa.Column("event_type", oh_queue.models.db.String(length=255), nullable=False),
sa.Column("ticket_id", sa.Integer(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["ticket_id"],
["ticket.id"],
),
sa.ForeignKeyConstraint(
["user_id"],
["user.id"],
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("ticket_event")
op.drop_index(op.f("ix_ticket_user_id"), table_name="ticket")
op.drop_index(op.f("ix_ticket_status"), table_name="ticket")
op.drop_index(op.f("ix_ticket_helper_id"), table_name="ticket")
op.drop_index(op.f("ix_ticket_created"), table_name="ticket")
op.drop_table("ticket")
op.drop_index(op.f("ix_user_email"), table_name="user")
op.drop_table("user")
# ### end Alembic commands ###
<file_sep>/grade-display/sections_export.py
import csv
from common.rpc.sections import rpc_export_attendance
def export():
print("Getting tutorial attendance...")
raw = rpc_export_attendance(full=False)["custom"]["attendances"]
c = csv.reader(raw)
print("Saving tutorial attendance...")
with open("data/tutorials.csv", "w") as f:
f.write("Email,Tutorial Attendance (Total)\n")
f.write(raw)
print("Done.")
if __name__ == "__main__":
export()
<file_sep>/oh/oh_queue/static/js/components/party.js
let Party = ({ match, state, children }) => {
let { Route, Switch } = ReactRouterDOM;
if (isStaff(state) || getMyTicket(state)) {
requestNotificationPermission();
}
if (!state.loaded) return null;
const showJumbotron = !getMyGroup(state);
let containerClass = classNames({
container: true,
"stub-jumbotron": !showJumbotron,
});
return (
<div>
<Navbar state={state} mode="party" />
<OfflineIndicator offline={state.offline && state.loaded} />
<div>
{showJumbotron && <Jumbotron state={state} />}
{!showJumbotron && <Messages messages={state.messages} />}
</div>
<div className={containerClass}>
<div className="row">
<PresenceIndicator state={state} hideWaitTime />
</div>
<div className="row">
<div className="col-xs-12">
<MyAppointments state={state} />
<div className="card-holder">
{state.groups
.filter((group: Group) => group.group_status === "active")
.map((group) => (
<GroupCard group={group} state={state} />
))}
</div>
</div>
</div>
</div>
</div>
);
};
<file_sep>/sections/server/login.py
from os import getenv
import flask
from flask import redirect
from flask_login import LoginManager, login_user, logout_user
from common.course_config import get_course, get_endpoint
from common.oauth_client import create_oauth_client, get_user, is_staff
from common.url_for import url_for
from models import User, db
dev = getenv("ENV") != "prod"
def create_login_client(app: flask.Flask):
login_manager = LoginManager()
login_manager.init_app(app)
def login():
user_data = get_user()
user = User.query.filter_by(email=user_data["email"]).one_or_none()
if user is None:
user = User(
email=user_data["email"], name=user_data["name"], is_staff=False
)
db.session.add(user)
user.name = user_data["name"] or user_data["email"]
for participation in user_data["participations"]:
if participation["course"]["offering"] == get_endpoint():
break
else:
if getenv("ENV") == "prod":
return
user.is_staff = is_staff("cs61a" if dev else get_course())
db.session.commit()
login_user(user)
create_oauth_client(app, "sections", success_callback=login)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
@app.route("/oauth/logout")
def logout():
logout_user()
return redirect(url_for("index"))
<file_sep>/buildserver/app_config.py
from dataclasses import dataclass
from typing import List, Literal, Optional, TypedDict
import yaml
from common.shell_utils import tmp_directory
CLOUD_RUN_DEPLOY_TYPES = {"flask", "flask-pandas", "docker"}
NO_PR_BUILD_DEPLOY_TYPES = {"service", "cloud_function", "none"}
WEB_DEPLOY_TYPES = {
"flask",
"flask-pandas",
"docker",
"hosted",
"static",
"cloud_function",
}
Permission = Literal[
"rpc",
"database",
"storage",
"logging",
"iam_admin",
"cloud_run_admin",
"cloud_functions_admin",
]
class Config(TypedDict):
build_type: Literal[
"create_react_app",
"oh_queue",
"webpack",
"61a_website",
"hugo",
"jekyll",
"none",
]
deploy_type: Literal[
"flask",
"flask-pandas",
"docker",
"pypi",
"cloud_function",
"static",
"service",
"hosted",
"none",
]
build_image: Optional[str]
cpus: int
memory_limit: str
first_party_domains: List[str]
concurrency: int
tasks: List["Task"]
dependencies: List["Dependency"]
repo: Optional[str]
package_name: str
static_consumers: List[str]
service: "Service"
pr_consumers: List[str]
permissions: List[Permission]
class Task(TypedDict):
name: str
schedule: str
class Dependency(TypedDict):
repo: str
src: str
dest: str
class Service(TypedDict):
host: str
root: str
zone: str
name: str
@dataclass
class App:
name: str
config: Optional[Config]
# updated by deploy.py, since PyPI takes a while to update
deployed_pypi_version: Optional[str]
def __init__(self, name: str):
self.name = name
self.deployed_pypi_version = None
with tmp_directory():
try:
with open(f"{name}/deploy.yaml") as f:
self.config = Config(**yaml.safe_load(f))
self.config["build_image"] = self.config.get("build_image", None)
self.config["cpus"] = self.config.get("cpus", 1)
self.config["memory_limit"] = self.config.get(
"memory_limit", "256M"
)
self.config["first_party_domains"] = self.config.get(
"first_party_domains", [f"{name}.cs61a.org"]
)
self.config["concurrency"] = self.config.get("concurrency", 80)
self.config["tasks"] = self.config.get("tasks", [])
self.config["dependencies"] = self.config.get("dependencies", [])
self.config["package_name"] = self.config.get("package_name", name)
self.config["static_consumers"] = self.config.get(
"static_consumers", []
)
self.config["repo"] = self.config.get("repo")
self.config["service"] = self.config.get("service")
self.config["pr_consumers"] = self.config.get(
"pr_consumers", [name]
)
self.config["permissions"] = self.config.get(
"permissions", ["rpc", "database"]
)
except FileNotFoundError:
# app has been deleted in PR
self.config = None
def __str__(self):
return self.name
<file_sep>/oh/oh_queue/static/js/components/config_linked_text.js
function ConfigLinkedText({
config,
configKey,
lines = 1,
placeholder,
title,
optional,
}) {
const Input = lines > 1 ? "textarea" : "input";
return (
<ConfigLinked
configKey={configKey}
config={config}
render={({ onSubmit, onChange, value, submitButton }) => (
<form onSubmit={onSubmit}>
<div className="form-group">
{title && <label>{title}</label>}
<Input
type="text"
className="form-control"
required={optional ? undefined : "required"}
value={value}
onChange={onChange}
placeholder={placeholder}
rows={lines}
/>
</div>
{submitButton}
</form>
)}
/>
);
}
<file_sep>/ok-help/src/CommandOptions.js
import React from "react";
import Category from "./Category.js";
import "./CommandOptions.css";
export default function CommandOptions(props) {
const { activeIndex, setActiveIndex, selectedOptions, setSelectedOptions } =
props;
const categories = props.options.map(
// eslint-disable-next-line react/no-array-index-key
(category, index) => (
<Category
category={category}
key={index}
active={index === activeIndex}
onClick={() => setActiveIndex(index)}
setOption={(option, val) => {
selectedOptions[index][option] = val;
setSelectedOptions({ ...selectedOptions });
}}
/>
)
);
return <div className="CommandOptions row">{categories}</div>;
}
<file_sep>/buildserver/pypi_utils.py
import re
from typing import Optional, Tuple
from packaging.version import Version
import requests
from app_config import App
VERSION_REGEX = r"version=\"(\d*).(\d)*.\*\""
def get_latest_version(
app: App, pr_number: int
) -> Tuple[Optional[Version], Optional[Version]]:
"""
Finds the latest deployed version of the package, or `None` if no
such version can be found. If we are making a prod build, it just finds
the latest deployed prod version. If we are making a PR build, it returns
both the latest deployed prod version, as well as the latest pre-release for
that PR.
"""
package_name = app.config["package_name"]
data = requests.get(f"https://pypi.org/pypi/{package_name}/json")
if data.status_code == 404:
return None, None
versions = [Version(release) for release in data.json()["releases"]]
prod_versions = [version for version in versions if version.pre is None]
pr_versions = [
version
for version in versions
if version.pre is not None and version.pre[1] == pr_number
]
latest_prod = max(prod_versions) if prod_versions else None
latest_pr = max(pr_versions) if pr_versions else None
return latest_prod, latest_pr
def update_setup_py(app: App, pr_number: int):
with open("setup.py", "a+") as f:
f.seek(0)
setup_contents = f.read()
match = re.search(VERSION_REGEX, setup_contents)
if match is None:
raise Exception("Could not find version in setup.py")
major, minor = int(match.group(1)), int(match.group(2))
latest_prod_version, latest_pr_version = get_latest_version(app, pr_number)
if latest_prod_version is None:
micro = 0
else:
if (
latest_prod_version.major > major
or latest_prod_version.major == major
and latest_prod_version.minor > minor
):
raise Exception(
f"Latest version {latest_prod_version} is greater than current build {major}.{minor}"
)
if (
latest_prod_version.major == major
and latest_prod_version.minor == minor
):
micro = latest_prod_version.micro + 1
else:
micro = 0
if latest_pr_version is None:
dev_number = 0
else:
dev_number = latest_pr_version.dev + 1
if pr_number == 0:
next_version = Version(f"{major}.{minor}.{micro}")
else:
next_version = Version(
f"{major}.{minor}.{micro}b{pr_number}.dev{dev_number}"
)
f.seek(0)
f.truncate()
f.write(re.sub(VERSION_REGEX, f'version="{next_version}"', setup_contents))
app.deployed_pypi_version = str(next_version)
<file_sep>/oh/oh_queue/static/js/components/appointment_card.js
const calcSpareCapacity = (appointment) =>
Math.max(0, appointment.capacity - appointment.signups.length);
function AppointmentCard({
currentUser,
locations,
appointment,
assignments,
compact,
onStudentSignup,
}) {
let panelColor = "panel-default";
let canAdd = true;
const spareCapacity = calcSpareCapacity(appointment);
if (currentUser.isStaff) {
if (appointment.helper && appointment.status === "hidden") {
panelColor = "panel-danger";
} else if (appointment.helper && appointment.helper.id === currentUser.id) {
panelColor = "panel-primary";
} else if (currentUser.isStaff && !appointment.helper) {
panelColor = "panel-warning";
}
} else {
if (
appointment.signups.some(({ user }) => user && user.id === currentUser.id)
) {
panelColor = "panel-success";
canAdd = false;
} else if (spareCapacity === 0) {
panelColor = "panel-danger";
}
}
const panelClass = classNames({
panel: true,
[panelColor]: true,
});
const handleStaffSignup = () => {
app.makeRequest("assign_staff_appointment", appointment.id);
};
const handleStaffUnassign = () => {
app.makeRequest("unassign_staff_appointment", appointment.id);
};
const handleStudentSignup = (e, signup) => {
e.preventDefault();
onStudentSignup(appointment.id, signup);
};
const toggleVisibility = () => {
app.makeRequest("toggle_visibility", appointment.id);
};
const deleteAppointment = () => {
app.makeRequest("delete_appointment", appointment.id);
};
return (
<div className={panelClass}>
<AppointmentCardHeader
appointment={appointment}
locations={locations}
compact={compact}
isStaff={currentUser && currentUser.isStaff}
onVisibilityToggle={toggleVisibility}
onDeleteClick={deleteAppointment}
/>
<ul className="list-group">
{(!compact || currentUser.isStaff) && (
<AppointmentCardHelperRow
appointment={appointment}
currentUser={currentUser}
onStaffSignup={handleStaffSignup}
onStaffUnassign={handleStaffUnassign}
/>
)}
{
<AppointmentCardStudentList
appointment={appointment}
currentUser={currentUser}
assignments={assignments}
compact={compact}
onStudentSignup={handleStudentSignup}
/>
}
{(!compact || !currentUser.isStaff) && (
<AppointmentCardPostList
appointment={appointment}
currentUser={currentUser}
canAdd={canAdd}
compact={compact}
onStudentSignup={handleStudentSignup}
/>
)}
</ul>
</div>
);
}
function AppointmentCardHeader({
appointment,
locations,
isStaff,
onVisibilityToggle,
onDeleteClick,
}) {
const [modalOpen, setModalOpen] = React.useState(false);
const spareCapacity = calcSpareCapacity(appointment);
let subtitle = (
<React.Fragment>
{locations[appointment.location_id].name} · {spareCapacity} slot
{spareCapacity === 1 ? "" : "s"} left
</React.Fragment>
);
let hiddenWarning = appointment.status === "hidden" && (
<React.Fragment> · HIDDEN</React.Fragment>
);
let description = isStaff && appointment.description && (
<React.Fragment> · {appointment.description}</React.Fragment>
);
const visibilityClass =
appointment.status === "hidden"
? "glyphicon glyphicon-play"
: "glyphicon glyphicon-pause";
return (
<div className="panel-heading">
<div className="btn-group" role="group" style={{ float: "right" }}>
{isStaff && (
<button
type="button"
className="btn btn-xs btn-default"
onClick={() => setModalOpen(true)}
>
<span className="glyphicon glyphicon-edit" aria-hidden="true" />
</button>
)}
{isStaff && (
<button
type="button"
className="btn btn-xs btn-default"
onClick={onVisibilityToggle}
>
<span className={visibilityClass} aria-hidden="true" />
</button>
)}
{isStaff && (
<button
type="button"
className="btn btn-danger btn-xs btn-default"
onClick={onDeleteClick}
>
<span className="glyphicon glyphicon-trash" aria-hidden="true" />
</button>
)}
</div>
{!isStaff && <span className="badge">{appointment.description}</span>}
<h3 className="panel-title">{formatAppointmentDuration(appointment)}</h3>
<small>
{subtitle}
{hiddenWarning}
{description}
</small>
<AppointmentEditForm
isOpen={modalOpen}
appointment={appointment}
onSubmit={() => setModalOpen(false)}
/>
</div>
);
}
function AppointmentCardHelperRow({
appointment,
currentUser,
onStaffSignup,
onStaffUnassign,
}) {
return (
<Slot>
{appointment.helper
? `Helper: ${appointment.helper.name}`
: "No helper assigned yet."}
{currentUser.isStaff &&
(appointment.helper ? (
<button
className="btn btn-danger btn-take-over btn-xs"
onClick={onStaffUnassign}
>
Unassign
</button>
) : (
<button
className="btn btn-success btn-take-over btn-xs"
onClick={onStaffSignup}
>
Sign up
</button>
))}
</Slot>
);
}
function AppointmentCardStudentList({
appointment,
assignments,
currentUser,
compact,
onStudentSignup,
}) {
return appointment.signups.map((signup) => {
const assignmentText = signup.assignment_id
? assignments[signup.assignment_id].name
: "";
const questionText =
(signup.assignment_id ? " " : "") +
(parseInt(signup.question) ? "Q" : "") +
(signup.question || "");
return (
((signup.user && currentUser.id === signup.user.id) || !compact) && (
<Slot
link={
signup.user &&
(signup.user.id === currentUser.id || currentUser.isStaff)
}
badgeText={assignmentText + questionText}
onClick={(e) => onStudentSignup(e, signup)}
>
{currentUser.isStaff
? signup.user.name
: signup.user && currentUser.id === signup.user.id
? "You (click to edit)"
: "Anonymous Student"}
</Slot>
)
);
});
}
function AppointmentCardPostList({
appointment,
currentUser,
onStudentSignup,
compact,
canAdd,
}) {
const spareCapacity = calcSpareCapacity(appointment);
return (
<React.Fragment>
{currentUser.isStaff && (
<Slot link onClick={onStudentSignup}>
Add a student to the section
</Slot>
)}
{!currentUser.isStaff && canAdd && spareCapacity > 0 && (
<Slot link onClick={onStudentSignup}>
Add yourself to the section
</Slot>
)}
{!compact &&
Array(Math.max(spareCapacity - (canAdd || currentUser.isStaff), 0))
.fill()
.map(() => <Slot className="slot-disabled">Extra Slot</Slot>)}
</React.Fragment>
);
}
<file_sep>/contest_utils/oauth.py
from flask import request, current_app
from flask_oauthlib.client import OAuth
from werkzeug import security
CONSUMER_KEY = "hog-contest"
def create_remote(app):
oauth = OAuth(app)
remote = oauth.remote_app(
"ok-server", # Server Name
consumer_key=CONSUMER_KEY,
consumer_secret="dummy",
request_token_params={"scope": "email", "state": lambda: security.gen_salt(10)},
base_url="https://okpy.org/api/v3/",
request_token_url=None,
access_token_method="POST",
access_token_url="https://okpy.org/oauth/token",
authorize_url="https://okpy.org/oauth/authorize",
)
return remote
def get_group(endpoint):
remote = create_remote(current_app)
token = request.form["token"]
email = remote.get("user", token=token).data["data"]["email"]
group_info = remote.get(
"assignment/{}/group/{}".format(endpoint, email), token=token
)
group = []
for user in group_info.data["data"]["members"]:
if user["status"] == "active":
group.append(user["user"]["email"])
if len(group) > 1:
return group
else:
return [email]
<file_sep>/exam-admin/requirements.txt
# my deps
google-cloud-firestore
cryptography
google-auth
sendgrid
<file_sep>/buildserver/dockerfiles/buildserver.Dockerfile
FROM gcr.io/cs61a-140900/$BASE_IMAGE:latest
ENV APP_MASTER_SECRET $MASTER_SECRET
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
RUN python external_build_worker.py $APP_NAME $PR_NUMBER $SHA $REPO_ID
<file_sep>/partnermatcher/index.md
```{include} README.md
```
## Script Documentation
This file performs the partner matching algorithm. `get_words()` and
`get_weight` are helper functions; `match()` is the main function which runs
the algorithm.
```{eval-rst}
.. automodule:: partnermatcher.main
:members:
```
<file_sep>/common/oauth_client.py
import os
import urllib.parse
import flask
import requests
from flask import current_app, g, session, request, redirect, abort, jsonify
from flask_oauthlib.client import OAuth
from werkzeug import security
from urllib.parse import urlparse
from common.rpc.auth import get_endpoint
from common.rpc.secrets import get_secret
from common.url_for import get_host, url_for
AUTHORIZED_ROLES = ("staff", "instructor", "grader")
REDIRECT_KEY = "REDIRECT_KEY"
def get_user():
"""Get some information on the currently logged in user.
:return: a dictionary representing user data (see
`here <https://okpy.github.io/documentation/ok-api.html#users-view-a-specific-user>`_
for an example)
"""
g.user_data = g.get("user_data") or current_app.remote.get("user")
return g.user_data.data["data"]
def is_logged_in():
"""Get whether the current user is logged into the current session.
:return: ``True`` if the user is logged in, ``False`` otherwise
"""
return "access_token" in session
def is_staff(course):
"""Get whether the current user is enrolled as staff, instructor, or grader
for ``course``.
:param course: the course code to check
:type course: str
:return: ``True`` if the user is on staff, ``False`` otherwise
"""
return is_enrolled(course, roles=AUTHORIZED_ROLES)
def is_enrolled(course, *, roles=None):
"""Check whether the current user is enrolled as any of the ``roles`` for
``course``.
:param course: the course code to check
:type course: str
:param roles: the roles to check for the user
:type roles: list-like
:return: ``True`` if the user is any of ``roles``, ``False`` otherwise
"""
try:
endpoint = get_endpoint(course=course)
for participation in get_user()["participations"]:
if roles and participation["role"] not in roles:
continue
if participation["course"]["offering"] != endpoint:
continue
return True
return False
except Exception as e:
# fail safe!
print(e)
return False
def login():
"""Store the current URL as the redirect target on success, then redirect
to the login endpoint for the current app.
:return: a :func:`~flask.redirect` to the login endpoint for the current
:class:`~flask.Flask` app.
"""
session[REDIRECT_KEY] = urlparse(request.url)._replace(netloc=get_host()).geturl()
return redirect(url_for("login"))
def create_oauth_client(
app: flask.Flask,
consumer_key,
secret_key=None,
success_callback=None,
return_response=None,
):
"""Add Okpy OAuth for ``consumer_key`` to the current ``app``.
Specifically, adds an endpoint ``/oauth/login`` that redirects to the Okpy
login process, ``/oauth/authorized`` that receives the successful result
of authentication, ``/api/user`` that acts as a test endpoint, and a
:meth:`~flask_oauthlib.client.OAuthRemoteApp.tokengetter`.
:param app: the app to add OAuth endpoints to
:type app: ~flask.Flask
:param consumer_key: the OAuth client consumer key
:type consumer_key: str
:param secret_key: the OAuth client secret, inferred using
:func:`~common.rpc.secrets.get_secret` if omitted
:type secret_key: str
:param success_callback: an optional function to call upon login
:type success_callback: func
:param return_response: an optional function to send the OAuth response to
:type return_response: func
"""
oauth = OAuth(app)
if os.getenv("ENV") == "prod":
if secret_key is None:
app.secret_key = get_secret(secret_name="OKPY_OAUTH_SECRET")
else:
app.secret_key = secret_key
else:
consumer_key = "local-dev-all"
app.secret_key = "<KEY>"
if not app.debug:
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
)
remote = oauth.remote_app(
"ok-server", # Server Name
consumer_key=consumer_key,
consumer_secret=app.secret_key,
request_token_params={"scope": "all", "state": lambda: security.gen_salt(10)},
base_url="https://okpy.org/api/v3/",
request_token_url=None,
access_token_method="POST",
access_token_url="https://okpy.org/oauth/token",
authorize_url="https://okpy.org/oauth/authorize",
)
def check_req(uri, headers, body):
"""Add access_token to the URL Request."""
if "access_token" not in uri and session.get("access_token"):
params = {"access_token": session.get("access_token")[0]}
url_parts = list(urllib.parse.urlparse(uri))
query = dict(urllib.parse.parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urllib.parse.urlencode(query)
uri = urllib.parse.urlunparse(url_parts)
return uri, headers, body
remote.pre_request = check_req
@app.route("/oauth/login")
def login():
if app.debug:
response = remote.authorize(callback=url_for("authorized", _external=True))
else:
response = remote.authorize(
url_for("authorized", _external=True, _scheme="https")
)
return response
@app.route("/oauth/authorized")
def authorized():
resp = remote.authorized_response()
if resp is None:
return "Access denied: error=%s" % (request.args["error"])
if isinstance(resp, dict) and "access_token" in resp:
session["access_token"] = (resp["access_token"], "")
if return_response:
return_response(resp)
if success_callback:
success_callback()
target = session.get(REDIRECT_KEY)
if target:
session.pop(REDIRECT_KEY)
return redirect(target)
return redirect(url_for("index"))
@app.route("/api/user", methods=["POST"])
def client_method():
if "access_token" not in session:
abort(401)
token = session["access_token"][0]
r = requests.get("https://okpy.org/api/v3/user/?access_token={}".format(token))
if not r.ok:
abort(401)
return jsonify(r.json())
@remote.tokengetter
def get_oauth_token():
return session.get("access_token")
app.remote = remote
<file_sep>/partnermatcher/main.py
from networkx import max_weight_matching, nx
import pandas as pd
from common.rpc.auth import write_spreadsheet
EMAIL_COL = "Email Address"
TIMEZONE_COL = "What is 8am PT (Berkeley Time) in your time?"
SKILL_COL = "How skillful a programmer do you consider yourself to be at this time?"
PNP_COL = "Are you taking CS 61A for a letter grade?"
WORDS_COL = "What are three words that describe your interests?"
def get_words(row):
"""Returns a list of stripped, lower case words from the ``WORDS_COL``
column of a student response row.
:param row: One-dimensional array containing a student's responses to the
partner matching questions.
:type row: ~pandas.Series
:return: a list of stripped, lower case words from the ``WORDS_COL`` column
of a student response row.
"""
return [
word.strip().lower()
for word in sorted((row[WORDS_COL] or "").split(",")) + [""] * 3
]
def get_weight(row1, row2):
"""Calculates and returns the partner matching weight between two students
based on their responses. The higher the weight, the more the partner
matching algorithm will favor matching these two students together.
:param row1: One-dimensional array containing the first student's responses
to the partner matching questions.
:type row1: ~pandas.Series
:param row2: One-dimensional array containing the second student's responses
to the partner matching questions.
:type row2: ~pandas.Series
:return: an int representing the partner matching weight between the student
whose responses are in row1 and the students whose responses are in
row2.
"""
score = 0
if row1[TIMEZONE_COL] == row2[TIMEZONE_COL]:
score += 20
if row1[SKILL_COL] == row2[SKILL_COL]:
score += 10
if row1[PNP_COL] == row2[PNP_COL]:
score += 5
words1 = get_words(row1)
words2 = get_words(row2)
score += sum(1 for word in words1 if word and word in words2)
return score
def match():
"""Performs the partner matching algorithm. The algorithm calculates the
weight between each pair of students using ``get_weight()``, forms a graph
where the nodes are the students and the edge weights are the weights
between each pair of students, and then calculates the maximum-weighted
matching of the graph, writing the results out to a Google sheet.
"""
data = pd.read_csv("data.csv", dtype=str).fillna("")
g = nx.Graph()
for i, _ in data.iterrows():
g.add_node(i)
for i, row1 in data.iterrows():
for j, row2 in data.iterrows():
if i >= j:
continue
g.add_edge(i, j, weight=get_weight(row1, row2))
matching = max_weight_matching(g)
csv = [["Student 1", "Student 2", "Timezone 1", "Timezone 2", "Words 1", "Words 2"]]
for i, j in matching:
csv.append(
[
data.ix[i][EMAIL_COL],
data.ix[j][EMAIL_COL],
data.ix[i][TIMEZONE_COL],
data.ix[j][TIMEZONE_COL],
data.ix[i][WORDS_COL],
data.ix[j][WORDS_COL],
]
)
write_spreadsheet(
url="https://docs.google.com/spreadsheets/d/1vpx-28ox2CNsyzbwrHLB9nCfiOZXksXp-jCgj21fNuw/",
sheet_name="Sheet1",
content=csv,
)
if __name__ == "__main__":
match()
<file_sep>/examtool_web_common/js/AskQuestion.js
import React, { useState } from "react";
import { Row, Card, Col, Form } from "react-bootstrap";
import { useExamData } from "./AlertsContext";
import FailText from "./FailText";
import LoadingButton from "./LoadingButton";
export default function AskQuestion({ send }) {
const examData = useExamData();
const [message, setMessage] = useState("");
const [question, setQuestion] = useState("Overall Exam");
const [isLoading, setIsLoading] = useState(false);
const [failText, setFailText] = useState("");
const submit = async () => {
setIsLoading(true);
const err = await send("ask_question", {
question: question === "Overall Exam" ? null : question,
message,
});
if (err) {
setFailText(err);
} else {
setMessage("");
}
setIsLoading(false);
};
return (
<Row>
<Col>
<Card>
<Card.Header>Request Clarification</Card.Header>
<Card.Body>
<Form>
<Form.Group>
<Form.Control
as="textarea"
rows={3}
value={message}
placeholder="Send a private message to staff."
onChange={(e) => setMessage(e.target.value)}
/>
</Form.Group>
<Form.Group>
<Form.Control
as="select"
value={question}
onChange={(e) => setQuestion(e.target.value)}
custom
>
<option value={null}>Overall Exam</option>
{examData.questions.map((questionName) => (
<option key={questionName}>{questionName}</option>
))}
</Form.Control>
</Form.Group>
<Form.Group>
<LoadingButton
loading={isLoading}
disabled={isLoading}
onClick={submit}
>
Send
</LoadingButton>
<FailText text={failText} suffixType="alerts" />
</Form.Group>
</Form>
</Card.Body>
</Card>
<br />
</Col>
</Row>
);
}
<file_sep>/oh/oh_queue/static/js/components/home.js
let Home = ({ match, state, children }) => {
let { Route, Switch } = ReactRouterDOM;
if (isStaff(state) || getMyTicket(state)) {
requestNotificationPermission();
}
// TODO loading indicator instead of blank screen
if (!state.loaded) return null;
return (
<div>
<Navbar state={state} mode="queue" />
<OfflineIndicator offline={state.offline && state.loaded} />
<Queue state={state} />
</div>
);
};
<file_sep>/cats/src/FastestWordsDisplay.js
import React from "react";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import Table from "react-bootstrap/Table";
export default function FastestWordsDisplay({ fastestWords, playerIndex }) {
return (
fastestWords.length > 0 && (
<>
<h4>Fastest words typed by each player</h4>
<Row>
{fastestWords.map((words, i) => (
<Col>
<Table striped bordered hover>
<thead>
<tr>
<th>
Player {i + 1}
{playerIndex === i && " (you)"}
</th>
</tr>
</thead>
<tbody>
{words.map((word) => (
<tr>
<td>{word}</td>
</tr>
))}
</tbody>
</Table>
</Col>
))}
</Row>
</>
)
);
}
<file_sep>/sandbox/utils.py
from contextlib import contextmanager
from common.db import connect_db
import glob, subprocess
from common.shell_utils import sh
@contextmanager
def db_lock(active_db, username):
try:
with connect_db() as db:
locked = db(
f"SELECT locked FROM {active_db} WHERE username=%s", [username]
).fetchone()
if locked is None:
# environment does not exist
db(
f"INSERT INTO {active_db} (username, initialized, locked) VALUES (%s, FALSE, TRUE)",
[username],
)
yield
else:
[locked] = locked
if locked:
# TODO: Some way to force an unlock from the CLI
raise BlockingIOError(
f"Another operation is currently taking place on {active_db}"
)
else:
db(
f"UPDATE {active_db} SET locked=TRUE WHERE username=%s",
[username],
)
yield
finally:
with connect_db() as db:
db(f"UPDATE {active_db} SET locked=FALSE WHERE username=%s", [username])
def get_server_cmd(username):
return [
"su",
username,
"-c",
f"code-server --config /save/{username}/.code-server.yaml",
]
def get_server_pid(username):
try:
return sh(
"pgrep", "-f", " ".join(get_server_cmd(username)), capture_output=True
)
except subprocess.CalledProcessError:
return False
def get_active_servers():
servers = glob.glob("/save/**/.local/share/code-server/heartbeat")
return [
server.split("/")[2]
for server in servers
if get_server_pid(server.split("/")[2])
]
# IDE has no AUTH_KEY and this was easier than giving it one
def is_software_ta(email):
return email in ["<EMAIL>", "<EMAIL>"]
# Some utilities for NGINX follow. These are originally sourced from:
# https://raw.githubusercontent.com/itsvs/dna/master/dna/utils/nginx_utils.py
class Block:
"""Represents a block in an nginx configuration
:param name: the name of this block
:type name: str
:param sections: sub-blocks of this block
:type sections: list[:class:`~dna.utils.Block`]
:param options: variables to include in this block
:type options: kwargs
.. important::
If you'd like to include a ``return`` statement
in your block, pass its value into the constructor
as ``ret``.
"""
def __init__(self, name, *sections, **options):
self.name = name
self.sections = sections
self.options = options
if "ret" in self.options:
self.options["return"] = self.options["ret"]
del self.options["ret"]
def _repr_indent(self, indent=""):
"""Represent this nginx block
:param indent: the indentation block to preceed every\
line in this representation with; add 4 indents to\
sub-blocks
:type indent: str
"""
result = indent + self.name + " {\n"
for block in self.sections:
result += block._repr_indent(indent=" " + indent)
for option in self.options:
result += indent + " " + option + " " + self.options[option] + ";\n"
return result + indent + "}\n"
def __repr__(self):
return self._repr_indent(indent="")
class Server(Block):
"""A :class:`~dna.utils.Block` called ``server``"""
def __init__(self, *sections, **options):
super().__init__("server", *sections, **options)
class Location(Block):
"""A :class:`~dna.utils.Block` called ``location``
:param location: the location being proxied
:type location: str
:param proxy_set_header: a dictionary of proxy\
headers to pass into nginx
:type proxy_set_header: dict
"""
def __init__(self, location, *sections, proxy_set_header={}, **options):
location = f"location {location}"
proxy_set_header = {
f"proxy_set_header {header}": value
for (header, value) in proxy_set_header.items()
}
super().__init__(location, *sections, **options, **proxy_set_header)
<file_sep>/buildtool/example/src/rules.py
from buildtool import callback
ENV = dict(PATH=["@//env/bin/", "/bin"])
def declare(*, name: str, src: str, out: str):
def impl(ctx):
ctx.sh("mkdir -p ../build", env=ENV)
raw_deps = ctx.input(sh=f"gcc {ctx.relative(src)} -MM", env=ENV)
deps = raw_deps.strip().split(" ")[1:]
ctx.add_deps(deps)
ctx.sh(f"gcc {ctx.relative(src)} -c -o {ctx.relative(out)}", env=ENV)
return callback(
name=name,
impl=impl,
out=out,
)
<file_sep>/hog/src/ScoreIndicators.js
// @flow
import React from "react";
import styled from "styled-components";
import ScoreIndicator from "./ScoreIndicator";
const Wrapper = styled.div`
display: flex;
justify-content: space-evenly;
`;
export default function ScoreIndicators({
scores,
currentPlayer,
}: {
scores: $ReadOnlyArray<number>,
}) {
return (
<Wrapper>
{scores.map((score, i) => (
<ScoreIndicator
key={i}
score={score}
playerIndex={i}
currentPlayer={currentPlayer}
/>
))}
</Wrapper>
);
}
<file_sep>/oh/oh_queue/assets.py
import glob
import os
from os import getenv
import webassets.filter
ASSETS_DIRECTORY = "oh_queue/static"
assets_env = webassets.Environment(directory=ASSETS_DIRECTORY, url="/static")
assets_env.config["BABEL_BIN"] = "node_modules/babel-cli/bin/babel.js"
babel = webassets.filter.get_filter("babel", presets="es2015,react")
assets_env.register("style.css", "css/style.css", output="public/style.css")
def glob_assets(pattern):
cwd = os.getcwd()
try:
os.chdir(ASSETS_DIRECTORY)
return glob.glob(pattern, recursive=True)
finally:
os.chdir(cwd)
assets_env.config["BABEL_EXTRA_ARGS"] = ["--plugins", "preval"]
if getenv("ENV", "dev") != "prod":
assets_env.register(
"common.js",
*glob_assets("js/components/*.js"),
"js/state.js",
"js/socket.js",
"js/common.js", # must be last
filters=babel,
output="public/common.js",
)
else:
assets_env.register("common.js", "public/common.js")
<file_sep>/oh/migrations/prev_versions/e4b5bd2a05cc_added_description_requirement_config.py
"""Added description requirement config
Revision ID: e4b5bd2a05cc
Revises: <KEY>
Create Date: 2020-02-04 03:04:27.899172
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "<KEY>"
from alembic import op
from sqlalchemy import orm
from oh_queue.models import *
def upgrade():
connection = op.get_bind()
session = orm.Session(bind=connection)
session.commit()
def downgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
session.commit()
<file_sep>/oh/oh_queue/static/js/components/update_location_box.js
class UpdateLocationBox extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.submit = this.submit.bind(this);
}
handleChange(event) {
let { state, ticket } = this.props;
this.newLocationId = event.target.value;
this.setState(state); //force a re-render
}
submit() {
let { state, ticket } = this.props;
app.makeRequest("update_ticket", {
id: ticket.id,
location_id: this.newLocationId,
});
this.setState(state); //force a render
}
render() {
let { state, ticket } = this.props;
let { locations } = state;
let staff = isStaff(state);
if (staff) {
return null;
}
return (
<div>
<h4> If you have moved, please update your new location here:</h4>
<div className="form-group form-group-lg">
<div className="input-group">
<SelectPicker
onChange={this.handleChange}
options={locations}
className="selectpicker form-control"
id="location"
data-width="80%"
data-style="btn-lg btn-default"
name="location"
title="Location"
/>
<div className="input-group-btn form-right pull-left">
<button
className="btn btn-lg btn-default"
onClick={this.submit}
disabled={
this.newLocationId == undefined ||
this.newLocationId == ticket.location_id
}
>
Update
</button>
</div>
</div>
</div>
</div>
);
}
}
<file_sep>/oh/oh_queue/static/js/components/ticket_layout.js
function TicketLayout({ loadTicket, state, socket, match }) {
let id = +match.params.id;
let ticket = getTicket(state, id);
React.useEffect(() => {
if (ticket == null) {
loadTicket(id);
}
}, []);
const [description, setDescription] = React.useState("");
React.useEffect(() => {
if (ticket) setDescription(ticket.description);
}, [ticket && ticket.description]);
const handleAssignmentSubmit = (args) => {
app.makeRequest("update_ticket", Object.assign(args, { id }));
};
const handleDescriptionSubmit = () => {
app.makeRequest("update_ticket", {
id,
description,
});
};
if (ticket == null) {
if (isLoading(state, id)) {
return null; // TODO loading indicator instead of blank screen
} else {
return <NotFound />;
}
}
if (!isStaff(state) && !ticketIsMine(state, ticket, true)) {
return <NotFound />;
}
let assignment = ticketAssignment(state, ticket);
let location = ticketLocation(state, ticket);
let question = ticketQuestion(state, ticket);
const group = getGroup(state, ticket.group_id);
return (
<div>
<Navbar state={state} mode="queue" />
<div className="container">
<Messages messages={state.messages} />
<div className="row ticket">
<div className="col-xs-12">
<h2 className="ticket-view-name text-center">
{group
? `${group.attendees[0].user.shortName}'s Group`
: ticket.status === "pending" && isStaff(state)
? "Help to View Name"
: ticket.user.name}
<small className="clearfix">
{assignment.name} {question} · {location.name}
{location.link && ticket.call_url && ` (${ticket.call_url})`}
</small>
</h2>
<p className="ticket-view-text text-center">
{" "}
{ticketStatus(state, ticket)}{" "}
</p>
</div>
</div>
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3">
<hr />
<DescriptionBox
locked={!!ticket.group_id}
state={state}
ticket={ticket}
prompt="Please describe your issue below:"
placeholder={
state.config.default_description ||
"It would be helpful if you could describe your issue. For example," +
' "I have a SyntaxError in my ___ function. I've tried using ____ and ____."'
}
description={description}
onChange={setDescription}
onSubmit={handleDescriptionSubmit}
/>
</div>
</div>
{!ticket.group_id && (
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3">
<hr />
<UpdateAssignmentBox
state={state}
elem={ticket}
onSubmit={handleAssignmentSubmit}
/>
</div>
</div>
)}
{!ticket.group_id && (
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3">
<hr />
<UpdateLocationBox state={state} ticket={ticket} />
</div>
</div>
)}
<TicketButtons state={state} ticket={ticket} />
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3">
<hr />
<ChatBox
key={id}
currentUser={state.currentUser}
socket={socket}
mode={group ? "group" : "ticket"}
messages={group ? group.messages : ticket.messages}
id={group ? group.id : id}
/>
</div>
</div>
{state.config.ticket_prompt && (
<div className="row">
<div className="col-xs-12 col-md-6 col-md-offset-3">
<hr />
<ReactMarkdown source={state.config.ticket_prompt} />
</div>
</div>
)}
</div>
</div>
);
}
<file_sep>/howamidoing/src/FutureCheckBox.js
import React from "react";
export default function FutureCheckBox(props) {
return (
<div className="custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id="futureCheckBox"
checked={props.checked}
onChange={props.onChange}
/>
<label className="custom-control-label" htmlFor="futureCheckBox">
Show unreleased / ungraded assignments and enable grade planning.
</label>
</div>
);
}
<file_sep>/cats/src/Options.js
import React from "react";
import "./Options.css";
export default function Options(props) {
return (
<>
<CheckBox
id="autoCorrectCheckBox"
text="Enable Auto-Correct"
value={props.autoCorrect}
onChange={props.onAutoCorrectToggle}
/>
<br />
<RestartButton onClick={props.onRestart} />
</>
);
}
function CheckBox(props) {
return (
<div className="Options custom-control custom-checkbox">
<input
type="checkbox"
className="custom-control-input"
id={props.id}
checked={props.value}
onChange={props.onChange}
/>
<label className="custom-control-label" htmlFor={props.id}>
{props.text}
</label>
</div>
);
}
function RestartButton(props) {
return (
<div className="Button">
<button type="button" className="btn btn-primary" onClick={props.onClick}>
Restart
</button>
</div>
);
}
<file_sep>/sandbox/sandbox.py
import os
import threading
from base64 import b64decode
from contextlib import contextmanager
from functools import wraps
from os.path import abspath
from pathlib import Path
from random import randrange
from subprocess import CalledProcessError
from typing import Optional
import requests
from flask import Flask, abort, g, jsonify, request, safe_join, send_file
from common.course_config import get_endpoint
from common.db import connect_db
from common.oauth_client import (
AUTHORIZED_ROLES,
create_oauth_client,
is_staff,
login,
)
from common.rpc.hosted import add_domain
from common.rpc.paste import get_paste, get_paste_url, paste_text
from common.rpc.sandbox import (
get_server_hashes,
initialize_sandbox,
is_sandbox_initialized,
run_make_command,
update_file,
)
from common.rpc.secrets import get_secret
from common.shell_utils import sh
from common.url_for import get_host, url_for
from sicp.build import get_hash, hash_all
from utils import db_lock
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
WORKING_DIRECTORY = abspath("tmp") if app.debug else "/save"
HOT_RELOAD_SCRIPT_PATH = abspath("hot_reloader.js")
PDFJS_DIRECTORY = abspath("pdfjs")
REPO = "Cal-CS-61A-Staff/berkeley-cs61a"
ENV = dict(
CLOUD_STORAGE_BUCKET="website-pdf-cache.buckets.cs61a.org", IN_SANDBOX="true"
)
DEFAULT_USER = "prbuild"
PDF_INLINE_SCRIPT = """
<div style="width: 100%; height: 100%;">
<iframe
src="/pdfjs/web/viewer.html?file=SRC_PATH"
style="width: 100%; height: 100%;"
frameborder="0"
scrolling="no"
>
</iframe>
</div>
"""
HOT_RELOAD_INLINE_SCRIPT = """
<script>
const version=VERSION;
const manualVersion=MANUAL_VERSION;
</script>
<script src="/hot_reloader.js"></script>
"""
create_oauth_client(app, "61a-sandbox")
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS sandboxes (
username varchar(128),
initialized boolean,
locked boolean,
version integer, -- updated every time we sync a file
manual_version integer -- updated after every manual make command
);"""
)
db(
"""CREATE TABLE IF NOT EXISTS builds (
username varchar(128),
target varchar(256),
pending boolean
);"""
)
db(
"""CREATE TABLE IF NOT EXISTS targets (
username varchar(128),
target varchar(256),
logs varchar(128),
version integer
)"""
)
def is_staff_userdata(userdata):
endpoint = get_endpoint(course="cs61a")
for participation in userdata["participations"]:
if participation["role"] not in AUTHORIZED_ROLES:
continue
if participation["course"]["offering"] != endpoint:
continue
return True
return False
def verifies_access_token(func):
@wraps(func)
def decorated(**kwargs):
token = kwargs.pop("access_token")
ret = requests.get(
"https://okpy.org/api/v3/user/", params={"access_token": token}
)
if ret.status_code != 200:
raise PermissionError
g.email = ret.json()["data"]["email"]
if not is_staff_userdata(ret.json()["data"]) or not g.email.endswith(
"@berkeley.edu"
):
raise PermissionError
g.username = (
g.email[: -len("@berkeley.edu")] if is_prod_build() else DEFAULT_USER
)
return func(**kwargs)
return decorated
def is_prod_build():
return not app.debug and ".pr." not in get_host() and "cs61a" in get_host()
def get_working_directory(username):
return os.path.join(WORKING_DIRECTORY, username, "berkeley-cs61a")
def get_host_username():
return get_host().split(".")[0] if is_prod_build() else DEFAULT_USER
def path_to_target(path):
return safe_join("../published", path)
@app.route("/")
@app.route("/<path:path>", strict_slashes=False)
def index(path="index.html"):
if not is_staff("cs61a"):
return login()
username = get_host_username()
base_directory = get_working_directory(username)
if "." not in path:
return index(path + "/index.html")
original_path = path
target = path_to_target(path)
path = safe_join(base_directory, "published", path)
# if not is_up_to_date(username, target):
# build(username, target)
if path.endswith(".html") or path.endswith(".pdf"):
logs = get_logs(username, target)
if logs is not None:
name, data = logs
out = f"""
<pre>{data}</pre>
<a href={get_paste_url(name)}>{get_paste_url(name)}</a>
"""
elif os.path.exists(path):
if path.endswith(".pdf"):
out = PDF_INLINE_SCRIPT.replace("SRC_PATH", "/raw/" + original_path)
else:
with open(path, "r") as f:
out = f.read()
else:
out = ""
out += HOT_RELOAD_INLINE_SCRIPT.replace(
"MANUAL_VERSION", str(get_manual_version(username))
).replace(
"VERSION",
str(get_version(username, target)),
)
return out
else:
try:
return send_file(path, cache_timeout=-1)
except FileNotFoundError:
return "", 404
@app.route("/raw/<path:path>")
def raw(path):
if not is_staff("cs61a"):
abort(403)
path = safe_join(get_working_directory(get_host_username()), "published", path)
try:
return send_file(path, cache_timeout=-1)
except FileNotFoundError:
return "", 404
@app.route("/pdfjs/<path:path>")
def pdfjs(path):
path = safe_join(PDFJS_DIRECTORY, path)
try:
return send_file(path)
except FileNotFoundError:
return "", 404
def get_src_version(username):
with connect_db() as db:
version = db(
"SELECT version FROM sandboxes WHERE username=%s",
[username],
).fetchone()
if version is None:
return 0
else:
return version[0] or 0
def get_manual_version(username):
with connect_db() as db:
manual_version = db(
"SELECT manual_version FROM sandboxes WHERE username=%s",
[username],
).fetchone()
if manual_version is None:
return 0
else:
return manual_version[0] or 0
@app.route("/hot_reloader.js")
def hot_reloader():
if not is_staff("cs61a"):
abort(403)
return send_file(HOT_RELOAD_SCRIPT_PATH)
@app.route("/get_revision", methods=["POST"])
def get_revision():
if not is_staff("cs61a"):
abort(403)
path = request.json["path"]
src_version = get_src_version(get_host_username())
manual_version = get_manual_version(get_host_username())
version = get_version(get_host_username(), path_to_target(path))
return jsonify(
dict(pubVersion=version, srcVersion=src_version, manualVersion=manual_version)
)
@app.route("/rebuild_path", methods=["POST"])
def rebuild_path():
if not is_staff("cs61a"):
abort(403)
path = request.json["path"]
build(get_host_username(), path_to_target(path))
return ""
@update_file.bind(app)
@verifies_access_token
def update_file(
path: str,
encoded_file_contents: Optional[str] = None,
symlink: Optional[str] = None,
delete: bool = False,
):
base = get_working_directory(g.username)
target = safe_join(base, path)
del path
if delete:
if os.path.islink(target):
os.unlink(target)
elif os.path.exists(target):
os.remove(target)
else:
target = Path(target)
target.parent.mkdir(parents=True, exist_ok=True)
if symlink:
if os.path.islink(target):
os.unlink(target)
elif os.path.exists(target):
os.remove(target)
os.symlink(symlink, target)
else:
decoded_file_contents = b64decode(encoded_file_contents.encode("ascii"))
with open(target, "wb+") as f:
f.write(decoded_file_contents)
assert get_hash(target) is not None
with connect_db() as db:
db(
"UPDATE sandboxes SET version=%s WHERE username=%s",
[randrange(1, 1000), g.username],
)
@run_make_command.bind(app)
@verifies_access_token
def run_make_command(target):
os.chdir(get_working_directory(g.username))
os.chdir("src")
clear_pending_builds(g.username)
try:
yield from sh(
"make",
"VIRTUAL_ENV=../env",
target,
env=ENV,
stream_output=True,
shell=True,
)
finally:
increment_manual_version(g.username)
def increment_manual_version(username):
with connect_db() as db:
db(
"UPDATE sandboxes SET manual_version=%s, version=%s WHERE username=%s",
[randrange(1, 1000), randrange(1, 1000), username],
)
def get_pending_targets(username):
with connect_db() as db:
return [
target
for [target] in db(
"SELECT target FROM builds WHERE username=%s AND pending=TRUE",
[username],
).fetchall()
]
def clear_pending_builds(username):
with connect_db() as db:
db(
"UPDATE builds SET pending=FALSE WHERE username=%s",
[username],
)
def build(username, target):
pending = get_pending_targets(username)
if target in pending:
# target is already scheduled to be built
return
with connect_db() as db:
db(
"INSERT INTO builds (username, target, pending) VALUES (%s, %s, %s)",
[username, target, True],
)
if not pending:
# We need to start the build ourselves
with app.app_context():
threading.Thread(target=build_worker, args=[username]).start()
def get_version(username, target):
with connect_db() as db:
version = db(
"SELECT version FROM targets WHERE username=%s AND target=%s",
[username, target],
).fetchone()
if version is None:
return 0
else:
return version[0]
def update_version(username, target, version, logs=None):
old_version = get_version(username, target)
with connect_db() as db:
if old_version:
db(
"UPDATE targets SET version=%s, logs=%s WHERE username=%s AND target=%s",
[version, logs, username, target],
)
else:
db(
"INSERT INTO targets (username, target, version, logs) VALUES (%s, %s, %s, %s)",
[username, target, version, logs],
)
def is_up_to_date(username, target):
src_version = get_src_version(username)
curr_version = get_version(username, target)
return src_version == curr_version
def get_logs(username, target):
with connect_db() as db:
logs = db(
"SELECT logs FROM targets WHERE username=%s AND target=%s",
[username, target],
).fetchone()
if logs is not None and logs[0] is not None:
return logs[0], get_paste(name=logs[0])
else:
return None
def build_worker(username):
# Note that we are not necessarily running in an app context
try:
while True:
targets = get_pending_targets(username)
if not targets:
break
target = targets[0]
src_version = get_src_version(username)
os.chdir(get_working_directory(username))
os.chdir("src")
ok = False
try:
sh("make", "-n", "VIRTUAL_ENV=../env", target, env=ENV)
except CalledProcessError as e:
if e.returncode == 2:
# target does not exist, no need to build
update_version(username, target, src_version)
ok = True
if not ok:
# target exists, time to build!
try:
sh(
"make",
"VIRTUAL_ENV=../env",
target,
env={**ENV, "LAZY_LOADING": "true"},
capture_output=True,
quiet=True,
)
except CalledProcessError as e:
log_name = paste_text(
data=(
(e.stdout or b"").decode("utf-8")
+ (e.stderr or b"").decode("utf-8")
)
)
update_version(username, target, src_version, log_name)
else:
update_version(username, target, src_version)
with connect_db() as db:
db(
"UPDATE builds SET pending=FALSE WHERE username=%s AND target=%s",
[username, target],
)
except:
# in the event of failure, cancel all builds and trigger refresh
increment_manual_version(username)
clear_pending_builds(username)
raise
@get_server_hashes.bind(app)
@verifies_access_token
def get_server_hashes():
base = get_working_directory(g.username)
os.chdir(base)
return hash_all()
@is_sandbox_initialized.bind(app)
@verifies_access_token
def is_sandbox_initialized():
return check_sandbox_initialized(g.username)
def check_sandbox_initialized(username):
with connect_db() as db:
initialized = db(
"SELECT initialized FROM sandboxes WHERE username=%s", [username]
).fetchone()
if initialized is None or not initialized[0]:
return False
# sanity check that the working directory exists
return os.path.exists(get_working_directory(username))
@initialize_sandbox.bind(app)
@verifies_access_token
def initialize_sandbox(force=False):
with db_lock("sandboxes", g.username):
initialized = check_sandbox_initialized(g.username)
if initialized and not force:
raise Exception("Sandbox is already initialized")
elif initialized:
sh("rm", "-rf", get_working_directory(g.username))
Path(get_working_directory(g.username)).mkdir(parents=True, exist_ok=True)
os.chdir(get_working_directory(g.username))
sh("git", "init")
sh(
"git",
"fetch",
"--depth=1",
f"https://{get_secret(secret_name='GITHUB_ACCESS_TOKEN')}@github.com/{REPO}",
"master",
)
sh("git", "checkout", "FETCH_HEAD", "-f")
os.mkdir("published") # needed for lazy-loading builds
if is_prod_build():
add_domain(name="sandbox", domain=f"{g.username}.sb.cs61a.org")
with connect_db() as db:
db("UPDATE sandboxes SET initialized=TRUE WHERE username=%s", [g.username])
if __name__ == "__main__":
app.run()
<file_sep>/code/src/renderer/components/HTMLCanvas.js
/* eslint-disable react/no-array-index-key */
import React, { useRef, useEffect } from "react";
export default function HTMLCanvas({ layers, draw }) {
const rendererCanvasesRef = useRef(Array(layers));
const baseCanvasesRef = useRef(null);
const deltaX = useRef(-1500);
const deltaY = useRef(-1000);
if (baseCanvasesRef.current === null) {
baseCanvasesRef.current = Array(layers)
.fill()
.map(() => document.createElement("canvas"));
for (const canvas of baseCanvasesRef.current) {
canvas.width = 3000;
canvas.height = 2000;
}
}
function updateRenderCanvases() {
const baseCanvases = baseCanvasesRef.current;
const renderCanvases = rendererCanvasesRef.current;
for (let i = 0; i !== layers; ++i) {
const baseCanvas = baseCanvases[i];
const renderCanvas = renderCanvases[i];
const ctx = renderCanvas.getContext("2d");
ctx.clearRect(0, 0, renderCanvas.width, renderCanvas.height);
ctx.drawImage(baseCanvas, deltaX.current, deltaY.current);
}
}
useEffect(() => {
deltaX.current = Math.round(
rendererCanvasesRef.current[0].parentNode.offsetWidth / 2 - 1500
);
deltaY.current = Math.round(
rendererCanvasesRef.current[0].parentNode.offsetHeight / 2 - 1000
);
}, [rendererCanvasesRef.current]);
useEffect(() => {
draw(baseCanvasesRef.current);
updateRenderCanvases();
});
useEffect(() => {
const topRenderCanvas = rendererCanvasesRef.current[layers - 1];
let prevCursorOffsetX;
let prevCursorOffsetY;
let isDragging = false;
function mouseDownHandler(e) {
prevCursorOffsetX = e.clientX;
prevCursorOffsetY = e.clientY;
isDragging = true;
}
function mouseMoveHandler(e) {
if (isDragging) {
deltaX.current += e.clientX - prevCursorOffsetX;
deltaY.current += e.clientY - prevCursorOffsetY;
prevCursorOffsetX = e.clientX;
prevCursorOffsetY = e.clientY;
updateRenderCanvases();
}
}
function mouseUpHandler() {
isDragging = false;
}
topRenderCanvas.addEventListener("mousedown", mouseDownHandler);
topRenderCanvas.addEventListener("mousemove", mouseMoveHandler);
topRenderCanvas.addEventListener("mouseup", mouseUpHandler);
return () => {
topRenderCanvas.removeEventListener("mousedown", mouseDownHandler);
topRenderCanvas.removeEventListener("mousemove", mouseMoveHandler);
topRenderCanvas.removeEventListener("mouseup", mouseUpHandler);
};
}, [rendererCanvasesRef.current]);
const canvasLayers = Array(layers)
.fill()
.map((_, i) => (
<canvas
className="canvasLayer"
width={3000}
height={2000}
key={i}
ref={(elem) => {
rendererCanvasesRef.current[i] = elem;
}}
>
{i}
</canvas>
));
return <div className="canvas">{canvasLayers}</div>;
}
<file_sep>/auth/management_client.py
import re
import string
from random import SystemRandom
from flask import request, redirect, jsonify
from common.db import connect_db
from auth_utils import (
key_secure,
oauth_secure,
admin_oauth_secure,
course_oauth_secure,
MASTER_COURSE,
is_staff,
get_name,
get_user,
)
from common.rpc.auth import get_endpoint, get_endpoint_id, list_courses, validate_secret
from common.url_for import url_for
from common.html import html, make_row
def init_db():
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS auth_keys (
client_name varchar(128),
auth_key varchar(128),
creator varchar(128),
course varchar(128),
service varchar(128),
unused BOOLEAN
)"""
)
db(
"""CREATE TABLE IF NOT EXISTS super_auth_keys (
client_name varchar(128),
auth_key varchar(128),
creator varchar(128),
unused BOOLEAN
)"""
)
db(
"""CREATE TABLE IF NOT EXISTS courses (
course varchar(128),
endpoint varchar(128),
endpoint_id INTEGER
)"""
)
ret = db("SELECT * FROM courses WHERE course=(%s)", [MASTER_COURSE]).fetchone()
if not ret:
db(
"INSERT INTO courses (course, endpoint, endpoint_id) VALUES (%s, %s, %s)",
["cs61a", "cal/cs61a/sp20", 151],
)
init_db()
def gen_key(length=64):
return "".join(
SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(length)
)
def prettify(course_code):
m = re.match(r"([a-z]+)([0-9]+[a-z]?)", course_code)
return m and (m.group(1) + " " + m.group(2)).upper()
class Data:
def __init__(self):
self.callbacks = []
def add(self, callback):
self.callbacks.append(callback)
def render(self, *args):
return "<p>".join(callback(*args) for callback in self.callbacks)
def create_management_client(app):
app.general_info = Data()
app.help_info = Data()
def general_help():
return """
<title>61A Auth</title>
<link rel="icon" href="https://cs61a.org/assets/images/favicon.ico">
<h1> 61A Auth </h1>
Go to <a href="https://go.cs61a.org/auth-help">go/auth-help</a> to see detailed usage / deployment instructions.
"""
def add_course():
if not is_staff(MASTER_COURSE):
return ""
with connect_db() as db:
courses = db("SELECT course, endpoint FROM courses").fetchall()
courses = [
make_row(
"{} ({}), at endpoint {}".format(prettify(course), course, endpoint),
url_for("remove_course", course=course),
)
for course, endpoint in courses
]
return """
<h2>Admin</h2>
<h3>Courses</h3>
Activate Auth for a new course (method only available to 61A admins):
<form action="/api/add_course" method="post">
<input name="course" type="text" placeholder="course name">
<input name="endpoint" type="text" placeholder="OKPy endpoint">
<input type="submit">
</form>
""" + "<p>".join(
courses
)
def super_clients():
if not is_staff(MASTER_COURSE):
return ""
with connect_db() as db:
ret = db(
"SELECT client_name, creator, unused FROM super_auth_keys"
).fetchall()
super_client_names = [
make_row(
f'{client_name}, created by {creator} {"(unused)" if unused else ""} ',
url_for("revoke_super_key", client_name=client_name),
)
for client_name, creator, unused in ret
]
return f"""
<h3>Super-Clients</h3>
<p>
Warning - the API keys for these clients are extremely sensitive,
as they can access <i>any</i> course's data. Only use them for 61A-hosted apps,
and reset them whenever a head TA leaves course staff.
</p>
Create new super-client and obtain secret key:
<form action="{url_for("create_super_key")}" method="post">
<input name="client_name" type="text" placeholder="client_name">
<input type="submit">
</form>
""" + "<p>".join(
super_client_names
)
app.general_info.add(general_help)
app.general_info.add(add_course)
app.general_info.add(super_clients)
def course_config(course):
with connect_db() as db:
endpoint, endpoint_id = db(
"SELECT endpoint, endpoint_id FROM courses WHERE course=(%s)", [course]
).fetchone()
user_data = get_user()
for participation in user_data["participations"]:
if participation["course"]["offering"] == endpoint:
endpoint_id = participation["course_id"]
db(
"UPDATE courses SET endpoint_id=(%s) WHERE endpoint=(%s)",
[[endpoint_id, endpoint]],
)
return """
<h3>Config</h3>
<p>
Current endpoint: {} (id: {})
</p>
Set new endpoint:
<form action="/api/{}/set_endpoint" method="post">
<input name="endpoint" type="text" placeholder="OKPy endpoint">
<input type="submit">
</form>
""".format(
endpoint, endpoint_id, course
)
app.help_info.add(lambda course: "<h2>{}</h2>".format(prettify(course)))
app.help_info.add(course_config)
@app.route("/")
@oauth_secure()
def index():
out = [app.general_info.render()]
with connect_db() as db:
for course, endpoint in db(
"SELECT course, endpoint FROM courses"
).fetchall():
if is_staff(course):
out.append(app.help_info.render(course))
return html("".join(out))
@app.route("/api/add_course", methods=["POST"])
@admin_oauth_secure(app)
def add_course():
course = request.form["course"]
endpoint = request.form["endpoint"]
if not prettify(course):
return (
"Course code not formatted correctly. It should be lowercase with no spaces.",
400,
)
with connect_db() as db:
ret = db("SELECT * FROM courses WHERE course = (%s)", course).fetchone()
if ret:
return "A course already exists with the same name.", 403
db("INSERT INTO courses VALUES (%s, %s, %s)", [course, endpoint, None])
return redirect("/")
@app.route("/api/remove_course", methods=["POST"])
@admin_oauth_secure(app)
def remove_course():
course = request.args["course"]
with connect_db() as db:
db("DELETE FROM courses WHERE course = (%s)", [course])
return redirect("/")
@list_courses.bind(app)
def handle_list_courses(**_kwargs):
# note: deliberately not secured, not sensitive data
with connect_db() as db:
return [
list(x) for x in db("SELECT course, endpoint FROM courses").fetchall()
]
# noinspection PyPep8Naming
@app.route("/api/<course>/get_endpoint", methods=["POST"])
def handle_get_endpoint_DEPRECATED_DO_NOT_USE(course):
return jsonify(handle_get_endpoint(course))
@get_endpoint.bind(app)
def handle_get_endpoint(course):
# note: deliberately not secured, not sensitive data
with connect_db() as db:
endpoint = db(
"SELECT endpoint FROM courses WHERE course = (%s)", [course]
).fetchone()
if endpoint:
return endpoint[0]
raise KeyError
@validate_secret.bind(app)
@key_secure
def handle_validate_secret(course):
return course
@app.route("/api/<course>/set_endpoint", methods=["POST"])
@course_oauth_secure()
def set_endpoint(course):
endpoint = request.form["endpoint"]
with connect_db() as db:
db(
"UPDATE courses SET endpoint = (%s) WHERE course = (%s)",
[endpoint, course],
)
return redirect("/")
# noinspection PyPep8Naming
@app.route("/api/<course>/get_endpoint_id", methods=["POST"])
def handle_get_endpoint_id_DEPRECATED_DO_NOT_USE(course):
return jsonify(handle_get_endpoint_id(course))
@get_endpoint_id.bind(app)
def handle_get_endpoint_id(course):
with connect_db() as db:
endpoint = db(
"SELECT endpoint_id FROM courses WHERE course = (%s)", [course]
).fetchone()
if endpoint:
return endpoint[0]
@app.route("/api/request_super_key", methods=["POST"])
@admin_oauth_secure(app)
def create_super_key():
name = request.form["client_name"]
key = gen_key()
with connect_db() as db:
ret = db(
"SELECT * FROM auth_keys WHERE client_name = (%s)", [name]
).fetchone()
if ret:
return "client_name already in use", 409
ret = db(
"SELECT * FROM super_auth_keys WHERE client_name = (%s)", [name]
).fetchone()
if ret:
return "client_name already in use", 409
db(
"INSERT INTO super_auth_keys VALUES (%s, %s, %s, %s)",
[name, key, get_name(), True],
)
return key
@app.route("/api/revoke_super_key", methods=["POST"])
@admin_oauth_secure(app)
def revoke_super_key():
name = request.args["client_name"]
with connect_db() as db:
db("DELETE FROM super_auth_keys WHERE client_name = (%s)", [name])
return redirect("/")
<file_sep>/oh/oh_queue/static/js/components/admin_appointments_manager.js
function AdminAppointmentsManager({ state }) {
const [sheetUrl, setSheetUrl] = React.useState("");
const [sheetName, setSheetName] = React.useState("");
const [isLoading, setIsLoading] = React.useState(false);
const handleSheetUrlChange = (e) => {
setSheetUrl(e.target.value);
};
const handleSheetNameChange = (e) => {
setSheetName(e.target.value);
};
const submit = () => {
setIsLoading(true);
app.makeRequest(
"upload_appointments",
{
sheetUrl,
sheetName,
},
false,
() => {
setIsLoading(false);
}
);
};
return (
<React.Fragment>
<AdminOptionsManager>
<tr>
<td>Should students be able to make appointments?</td>
<td className="col-md-1">
<ConfigLinkedToggle
config={state.config}
configKey="appointments_open"
offText="No"
onText="Yes"
/>
</td>
</tr>
<tr>
<td>
Should students be prompted to make appointments when the queue
closes?
</td>
<td className="col-md-1">
<ConfigLinkedToggle
config={state.config}
configKey="recommend_appointments"
offText="No"
onText="Yes"
/>
</td>
</tr>
<tr>
<td>
<p>How many appointments should a student be able to make daily?</p>
</td>
<td className="col-md-3">
<ConfigLinkedNumeric
config={state.config}
configKey="daily_appointment_limit"
/>
</td>
</tr>
<tr>
<td>
<p>
How many appointments should a student be able to make weekly?
</p>
</td>
<td className="col-md-3">
<ConfigLinkedNumeric
config={state.config}
configKey="weekly_appointment_limit"
/>
</td>
</tr>
<tr>
<td>
<p>
How many appointments should a student have be pending
simultaneously?
</p>
</td>
<td className="col-md-3">
<ConfigLinkedNumeric
config={state.config}
configKey="simul_appointment_limit"
/>
</td>
</tr>
</AdminOptionsManager>
<form>
<div className="input-group appointment-input">
<input
id="url-selector"
type="text"
className="form-control"
placeholder="Link to a spreadsheet containing appointments"
required
value={sheetUrl}
onChange={handleSheetUrlChange}
/>
<input
id="sheet-selector"
className="form-control form-right"
type="text"
name="question"
title="Sheet name"
placeholder="Sheet name"
required
value={sheetName}
onChange={handleSheetNameChange}
/>
<span className="input-group-btn">
<button
className={"btn btn-default " + (isLoading ? "is-loading" : "")}
type="button"
onClick={submit}
>
Update
</button>
</span>
</div>
<small>
You must share this spreadsheet with the 61A service account{" "}
<a href="mailto:<EMAIL>">
<EMAIL>
</a>
.
</small>
</form>
</React.Fragment>
);
}
<file_sep>/buildserver/external_build_worker.py
# this is used to trigger the worker via Cloud Build
import sys
from github import Github
from app_config import App
from build import clone_commit
from common.rpc.secrets import get_secret
from conf import GITHUB_REPO
from worker import land_app_worker
if __name__ == "__main__":
g = Github(get_secret(secret_name="GITHUB_ACCESS_TOKEN"))
_, app_name, pr_number, sha, repo_id = sys.argv
base_repo = g.get_repo(GITHUB_REPO)
clone_commit(
base_repo.clone_url,
sha
if repo_id == base_repo.full_name
else base_repo.get_branch(base_repo.default_branch).commit.sha,
)
land_app_worker(App(app_name), int(pr_number), sha, g.get_repo(repo_id))
<file_sep>/code/src/renderer/components/FileSelector.js
import React from "react";
import RecentFileSelector from "./RecentFileSelector.js";
import OkBackupsButton from "./OkBackupsButton.js";
export default function FileSelector({
recentFiles,
onFileCreate,
onBackupsButtonClick,
}) {
return (
<div className="recentHolder browserFileSelector">
<RecentFileSelector files={recentFiles} onFileSelect={onFileCreate} />
<br />
<OkBackupsButton onBackupsButtonClick={onBackupsButtonClick} />
</div>
);
}
<file_sep>/examtool_web_common/run_local.py
import os
import sys
from flask import Flask, request
sys.path.append(os.path.abspath("."))
from main import index
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
@app.route("/<path:path>", methods=["GET", "POST"])
def main(path="/"):
return index(request)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/buildserver/dockerfiles/flask-pandas.Dockerfile
FROM python:buster
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
RUN pip install pandas
RUN pip install -r requirements.txt
CMD gunicorn -b :$PORT -w 4 main:app -t 3000
<file_sep>/common/rpc/oh.py
from common.rpc.utils import create_service
service = create_service(__name__)
<file_sep>/examtool_web_common/js/StaffMessagesList.js
import React, { useEffect, useState } from "react";
import { Button, Card, Form, Modal, ListGroup } from "react-bootstrap";
import { useTime } from "./AlertsContext";
import { getToken } from "./auth";
import { Group, postRenderFormat } from "./Exam";
import Question from "./Question";
import StaffMessageReplyBox from "./StaffMessageReplyBox";
import { timeDeltaMinutesString } from "./timeUtils";
import post from "./post";
export default function StaffMessagesList({ selectedExam, staffData, send }) {
const time = useTime();
const [showModal, setShowModal] = useState(false);
const [questionData, setQuestionData] = useState(null);
const [compactMode, setCompactMode] = useState(false);
const loadQuestion = async (id, student) => {
setQuestionData(null);
setShowModal(true);
try {
const resp = await post("get_question", {
token: getToken(),
exam: selectedExam,
latestTimestamp: staffData.latestTimestamp,
student,
id,
});
const data = await resp.json();
if (!data.success) {
throw Error();
}
setQuestionData(data.question);
} catch {
setShowModal(false);
}
};
useEffect(() => postRenderFormat(document.body), [questionData]);
const makeReplyBox = (id, compact) => (
<StaffMessageReplyBox message={id} compact={compact} send={send} />
);
return (
<>
<h3>Private Messages</h3>
<Form.Group>
<Form.Check
id="staffCheckbox"
custom
type="checkbox"
label="Compact Mode"
value={compactMode}
onChange={(e) => setCompactMode(e.target.checked)}
/>
</Form.Group>
{staffData.messages.map(
({
id,
responses,
email,
message,
question,
timestamp: messageTime,
}) => (
<div key={id}>
<Card
bg={responses.length === 0 ? "danger" : "default"}
text={responses.length === 0 ? "white" : "dark"}
>
<Card.Header>
<b>
{responses.length === 0
? "Unresolved Thread"
: "Resolved Thread"}
</b>{" "}
[{question || "Overall Exam"}]{" "}
{responses.length === 0 && (
<span style={{ float: "right", marginLeft: 10 }}>
{" "}
{makeReplyBox(id, true)}{" "}
</span>
)}
{question != null && (
<Button
style={{ float: "right" }}
variant="primary"
size="sm"
onClick={() => loadQuestion(question, email)}
>
View Question
</Button>
)}
</Card.Header>
<ListGroup variant="flush">
<ListGroup.Item
style={{ whiteSpace: "pre-wrap" }}
variant="secondary"
>
<b>{email}: </b>
{message} ({timeDeltaMinutesString(time - messageTime)})
</ListGroup.Item>
{responses.map(
({
id: replyID,
message: response,
timestamp: responseTime,
}) => (
<ListGroup.Item
key={replyID}
style={{ whiteSpace: "pre-wrap" }}
>
<b>Staff: </b>
{response} ({timeDeltaMinutesString(time - responseTime)})
</ListGroup.Item>
)
)}
{!compactMode && (
<ListGroup.Item style={{ whiteSpace: "pre-wrap" }}>
{makeReplyBox(id, false)}
</ListGroup.Item>
)}
</ListGroup>
</Card>
<br />
</div>
)
)}
<Modal show={showModal} onHide={() => setShowModal(false)} size="lg">
<Modal.Header closeButton>Question Preview</Modal.Header>
<Modal.Body>
{questionData != null &&
(questionData.type === "group" ? (
<Group
group={questionData}
number={questionData.index.slice(0, -1)}
/>
) : (
<Question
question={questionData}
number={questionData.index.slice(0, -1)}
/>
))}
</Modal.Body>
<Modal.Footer>
<Button onClick={() => setShowModal(false)}>Close</Button>
</Modal.Footer>
</Modal>
</>
);
}
<file_sep>/common/url_for.py
from os import getenv
from urllib.parse import urlparse
from flask import request, url_for as flask_url_for
def get_host() -> str:
"""Get the current host URL from request headers.
:return: ``X-Forwarded-For-Host`` or ``Host``
.. note::
61A apps use ``X-Forwarded-For-Host``, which is not a standard header,
for legacy reasons. This may be fixed in the future, but not for now.
"""
return request.headers.get("X-Forwarded-For-Host") or request.headers.get("Host")
def url_for(*args, **kwargs) -> str:
"""Return the absolute URL target for the requested method.
Uses :func:`~flask.url_for` to get the relative endpoint, then prepends the
host from :func:`get_host` to the URL to make it absolute.
All arguments are passed directly into :func:`~flask.url_for`.
:return: the absolute target URL
"""
host = get_host()
redirect_url = urlparse(flask_url_for(*args, **kwargs))
# noinspection PyProtectedMember
return redirect_url._replace(
netloc=host, scheme="https" if getenv("ENV") == "prod" else "http"
).geturl()
<file_sep>/examtool_web_common/js/StudentAlertsList.js
import React from "react";
import { Badge, Card, Row, Col, ListGroup } from "react-bootstrap";
import { useExamData, useTime, useStale } from "./AlertsContext";
import { timeDeltaMinutesString } from "./timeUtils";
export default function StudentAlertsList() {
const time = useTime();
const examData = useExamData();
const stale = useStale();
return (
<Row>
<Col>
<Card>
<Card.Header>
Announcements
{stale && (
<Badge style={{ float: "right" }} variant="danger">
Disconnected
</Badge>
)}
</Card.Header>
<ListGroup variant="flush">
{examData.announcements.map(
({ id, message, question, timestamp, private: isPrivate }) => (
<ListGroup.Item key={id} style={{ whiteSpace: "pre-wrap" }}>
<b>[{isPrivate ? "Private" : question}]</b> {message} (
{timeDeltaMinutesString(time - timestamp)})
</ListGroup.Item>
)
)}
</ListGroup>
</Card>
</Col>
</Row>
);
}
<file_sep>/sicp/setup.py
from setuptools import setup, find_packages
with open("README.md") as f:
readme = f.read()
setup(
name="sicp",
version="0.1.*",
author="<NAME>, <NAME>",
author_email="<EMAIL>",
long_description=readme,
long_description_content_type="text/markdown",
licence="MIT",
packages=find_packages(include=["sicp", "sicp.common", "sicp.common.rpc"]),
package_data={"": ["**/*.tex"]},
include_package_data=True,
entry_points={"console_scripts": ["sicp=sicp.__main__:cli"]},
python_requires=">=3.6",
install_requires=[
"click",
"watchdog",
"crcmod",
"tqdm",
"flask",
"cachetools",
"colorama",
"requests",
"PyGithub",
],
)
<file_sep>/examtool/examtool/cli/login.py
import click
from examtool.api.auth import refresh_token
@click.command()
@click.option(
"--browser/--no-browser",
default=True,
help="Choose between browser-based and browserless authentication",
)
def login(browser):
"""
Login to OKPy.
"""
token = refresh_token(no_browser=not browser)
print("Token = {}".format(token))
print("Token automatically saved")
if __name__ == "__main__":
login()
<file_sep>/domains/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
-r common/requirements.txt
<file_sep>/howamidoing/src/UploadStatusModal.js
import React from "react";
export default React.forwardRef(({ success }, ref) => (
<div
className="modal fade"
tabIndex="-1"
role="dialog"
aria-hidden="true"
ref={ref}
>
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">Upload Status</h5>
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
{success
? "Upload succeeded!"
: "Upload failed :( Refresh, and try again!" +
" If the issue persists, please contact the developers."}
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
data-dismiss="modal"
>
Close
</button>
</div>
</div>
</div>
</div>
));
<file_sep>/cats/src/index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import post from "./post";
import * as serviceWorker from "./serviceWorker";
document.body.prepend(
new Comment(String.raw`
_________________________________________
/ Hello adventurous student! If you want \
| to see the source of the GUI, go to Dev |
| Tools => Sources => Page => top => |
| [this domain] => static => js and |
\ enjoy! /
-----------------------------------------
\
\
\ _
\ | \
\ | |
| |
|\ | |
/, ~\ / /
X \`-.....-------./ /
~-. ~ ~ |
\ / |
\ /_ ___\ /
| /\ ~~~~~ \ |
| | \ || |
| |\ \ || )
(_/ (_/ ((_/
`)
);
post("/favicon").then((image) => {
document.querySelector('link[rel="shortcut icon"]').href = image;
});
ReactDOM.render(<App />, document.getElementById("root"));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
<file_sep>/hog-contest/runner.py
../hog-calc/runner.py<file_sep>/howamidoing/src/ScoreHistogram.js
import React from "react";
import {
Histogram,
BarSeries,
withParentSize,
XAxis,
YAxis,
} from "@data-ui/histogram";
const ResponsiveHistogram = withParentSize(
({ parentWidth, parentHeight, ...rest }) => (
<Histogram width={parentWidth} height={parentHeight} {...rest} />
)
);
export default function ScoreHistogram({ students, bins, extractedData }) {
return (
<div style={{ height: "40vh" }}>
{students.length === 0 || (
<ResponsiveHistogram
ariaLabel="Lab score histogram"
orientation="vertical"
cumulative={false}
normalized
valueAccessor={(datum) => datum}
binType="numeric"
binValues={bins}
renderTooltip={({ datum, color }) => (
<div>
<strong style={{ color }}>
{datum.bin0} to {datum.bin1}
</strong>
<div>
<strong>count </strong>
{datum.count}
</div>
<div>
<strong>cumulative </strong>
{datum.cumulative}
</div>
<div>
<strong>density </strong>
{datum.density}
</div>
</div>
)}
>
<BarSeries animated rawData={extractedData} />
<XAxis />
<YAxis />
</ResponsiveHistogram>
)}
</div>
);
}
<file_sep>/ok-help/src/GeneratedCommand.js
import React, { useState, useRef } from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";
import $ from "jquery";
import { Textfit } from "react-textfit";
import "./GeneratedCommand.css";
export default function GeneratedCommand(props) {
const [copyText, setCopyText] = useState("Copy");
const sensor = useRef();
const ref = useRef();
let generated = "python3 ok";
if (props.options) {
for (const option of props.options.mandatoryArgs) {
if (option.shortForm) {
generated += ` -${option.shortForm}`;
} else {
generated += ` --${option.longForm}`;
}
}
for (const option of props.options.optionalArgs) {
if (props.selectedArgs[option.longForm]) {
if (option.shortForm) {
generated += ` -${option.shortForm}`;
} else {
generated += ` --${option.longForm}`;
}
if (option.isValue) {
generated += ` ${props.selectedArgs[option.longForm]}`;
}
}
}
}
function stickTop() {
const windowTop = $(window).scrollTop();
const { top } = $(sensor.current).offset();
if (windowTop > top) {
$(sensor.current).height($(ref.current).outerHeight());
$(ref.current).addClass("sticky");
} else {
$(ref.current).removeClass("sticky");
$(sensor.current).height(0);
}
}
$(window).scroll(stickTop);
return (
<>
<div ref={sensor} />
<div className="row" ref={ref}>
<div className="col">
<div className="GeneratedCommand">
<div className="Command">
<Textfit mode="single" forceSingleModeWidth={false} max={28}>
<code>{generated}</code>
</Textfit>
</div>
<div className="CopyButtonContainer">
<CopyToClipboard
text={generated}
onCopy={() => {
setCopyText("Copied!");
setTimeout(() => {
setCopyText("Copy");
}, 1000);
document.activeElement.blur();
}}
>
<button className="btn btn-primary CopyButton" type="button">
<span>{copyText}</span>
</button>
</CopyToClipboard>
</div>
</div>
</div>
</div>
</>
);
}
<file_sep>/oh/migrations/versions/7857a34ef101_removed_uniqueness_constraints.py
"""removed uniqueness constraints
Revision ID: 7857a34ef101
Revises: None
Create Date: 2020-03-08 05:38:00.904655
"""
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = None
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index("name", table_name="assignment")
op.drop_index("name", table_name="location")
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_index("name", "location", ["name"], unique=True)
op.create_index("name", "assignment", ["name"], unique=True)
# ### end Alembic commands ###
<file_sep>/exam-write/requirements.txt
# my deps
Flask
gunicorn
pypandoc
-e ./examtool[cli,admin]
<file_sep>/sections/src/SectionAttendance.js
// @flow strict
import { useState } from "react";
import * as React from "react";
import Button from "react-bootstrap/Button";
import AddSessionModel from "./AddSessionModal";
import type { SectionDetails } from "./models";
import SessionAttendance from "./SessionAttendance";
type Props = {
section: SectionDetails,
};
export default function SectionAttendance({ section }: Props) {
const [adding, setAdding] = useState(false);
return (
<>
<SessionAttendance section={section} />
{section.sessions
.slice()
.reverse()
.map((session) => (
<SessionAttendance
key={session.startTime}
session={session}
section={section}
/>
))}
<p>
<br />
<Button variant="secondary" size="sm" onClick={() => setAdding(true)}>
Add Missing Session
</Button>
</p>
<AddSessionModel
show={adding}
section={section}
onClose={() => setAdding(false)}
/>
</>
);
}
<file_sep>/dice/main.py
from datetime import timedelta
from json import dumps, loads
from random import shuffle
from time import time
from flask import Flask, Response, abort, render_template, request
from common.course_config import get_endpoint
from common.db import connect_db
from common.secrets import new_secret
from contest_utils.oauth import get_group
from contest_utils.rate_limiting import ratelimited
NUM_DICE = 6
MAX_CAPTION_LEN = 100
ASSIGNMENT = "proj01showcase"
app = Flask(__name__, static_folder="", static_url_path="")
if __name__ == "__main__":
app.debug = True
with connect_db() as db:
db("CREATE TABLE IF NOT EXISTS accesses (email VARCHAR(128), last_access INTEGER)")
db(
"""CREATE TABLE IF NOT EXISTS designs (
id varchar(128),
created_time integer,
email varchar(128),
caption varchar(512),
dice LONGBLOB,
endpoint varchar(512)
);"""
)
@app.route("/")
def index():
with connect_db() as db:
artworks = db(
"SELECT id, caption FROM designs WHERE endpoint=(%s)",
[get_endpoint("cs61a")],
).fetchall()
shuffle(artworks)
resp = Response(render_template("index.html", artworks=artworks))
resp.cache_control.max_age = 0
return resp
@app.route("/img")
def img():
id = request.args["id"]
index = int(request.args["index"])
with connect_db() as db:
caption, dice = db(
"SELECT caption, dice FROM designs WHERE id=(%s)", [id]
).fetchone()
dice = loads(dice)
resp = Response(dice[index], mimetype="image/svg+xml")
resp.headers["Content-Security-Policy"] = "default-src 'none'"
if "script" in dice[index]:
resp.headers["Content-Security-Policy-Observation"] = "Nice try"
resp.cache_control.max_age = 3600
return resp
@app.route("/api/submit_designs", methods=["POST"])
@ratelimited(timedelta(minutes=1))
def submit():
caption = str(request.form["caption"])
if len(caption) > MAX_CAPTION_LEN:
abort(
413,
f"Your caption is too long - it should be at most {MAX_CAPTION_LEN} characters.",
)
dice = loads(request.form["dice"])
dice_list = []
for svg in dice:
if not isinstance(svg, str):
abort(401)
dice_list.append(svg)
del dice
if len(dice_list) != NUM_DICE:
abort(401)
group = get_group(get_endpoint("cs61a") + "/" + ASSIGNMENT)
with connect_db() as db:
for member in group:
db("DELETE FROM designs WHERE email=(%s)", [member])
email = group[0]
db(
"INSERT INTO designs (id, created_time, email, caption, dice, endpoint) VALUES (%s, %s, %s, %s, %s, %s)",
[
new_secret(),
int(time()),
email,
caption,
dumps(dice_list),
get_endpoint("cs61a"),
],
)
return dict(success=True, group=group)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/oh/oh_queue/static/js/components/config_linked_numeric.js
function ConfigLinkedNumeric({ config, configKey }) {
return (
<ConfigLinked
configKey={configKey}
config={config}
render={({ onSubmit, onChange, value, submitButton }) => (
<form onSubmit={onSubmit}>
<div className="form-group">
<input
type="number"
className="form-control"
required="required"
value={value}
onChange={onChange}
/>
</div>
{submitButton}
</form>
)}
/>
);
}
<file_sep>/hog-calc/main.py
import json
from datetime import timedelta
from flask import Flask, jsonify, request
from common.db import connect_db
from contest_utils.rate_limiting import ratelimited
from process_input import validate_strat
from runner import score
app = Flask(__name__)
with connect_db() as db:
db("CREATE TABLE IF NOT EXISTS accesses (email VARCHAR(128), last_access INTEGER)")
db(
"""CREATE TABLE IF NOT EXISTS cached_strategies (
email VARCHAR(128), name VARCHAR(1024), hash VARCHAR(128), strategy LONGBLOB
)"""
)
db(
"CREATE TABLE IF NOT EXISTS cached_winrates (hash_0 VARCHAR(128), hash_1 VARCHAR(128), winrate DOUBLE)"
)
@app.route("/api/compare_strategies", methods=["POST"])
@ratelimited(timedelta(minutes=1))
def compare_strategies():
strat0 = json.loads(request.form["strat0"])
strat1 = json.loads(request.form["strat1"])
use_contest = bool(request.form.get("use_contest"))
return jsonify(
{
"success": True,
"win_rate": score(
validate_strat(strat0),
validate_strat(strat1),
use_contest=use_contest,
),
}
)
if __name__ == "__main__":
app.run()
<file_sep>/common/rpc/mail.py
from typing import Dict
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__, providers=["https://cs162.org/autograder/"])
@requires_master_secret
@service.route("/api/send_email")
def send_email(
*,
sender: str,
target: str,
subject: str,
body: str,
attachments: Dict[str, str] = {},
):
...
<file_sep>/sicp/README.md
## Overview
This is the general-purpose CS 61A command-line task runner, used to manage our various services.
<file_sep>/examtool_web_common/js/AlertsApp.js
import React, { useEffect, useState } from "react";
import { Col, Container, Form, Row } from "react-bootstrap";
import AlertsContext from "./AlertsContext";
import AskQuestion from "./AskQuestion";
import ConnectAlertButton from "./ConnectAlertButton";
import CreateAnnouncement from "./CreateAnnouncement";
import GoogleSignInButton from "./GoogleSignInButton";
import post from "./post";
import StaffAlertsList from "./StaffAlertsList";
import StaffMessagesList from "./StaffMessagesList";
import StudentMessagesList from "./StudentMessagesList";
import StudentAlertsList from "./StudentAlertsList";
import TimerBanner from "./TimerBanner";
import useExamAlertsData from "./useExamAlertsData";
import useTick from "./useTick";
export default function Alerts() {
const [username, setUsername] = useState("");
const [examList, setExamList] = useState([]);
const forceSelectedExam = decodeURIComponent(window.location.pathname)
.replace("/", "")
.trim();
const [selectedExam, setSelectedExam] = useState(forceSelectedExam);
const [isStaff, setIsStaff] = useState(false);
const [examData, stale, onConnect, send] = useExamAlertsData(
selectedExam,
isStaff
);
const time = useTick();
const handleExamSelect = (e) => {
setSelectedExam(e.target.value);
};
useEffect(() => {
(async () => {
setExamList(await (await post("list_exams")).json());
})();
}, []);
useEffect(() => {
document.title = stale
? "(DISCONNECTED) Exam Announcements"
: "Exam Announcements";
}, [stale]);
return (
<AlertsContext.Provider value={{ time, examData, stale }}>
<Container>
<br />
<Row>
<Col>
<h1>Exam Announcements</h1>
</Col>
</Row>
<Row>
<Col>
<GoogleSignInButton onSuccess={setUsername} />
</Col>
</Row>
<br />
{username && !examData && !forceSelectedExam && (
<Row>
<Col>
<Form>
<Form.Group controlId="exampleForm.SelectCustom">
<Form.Label>Now, choose your exam:</Form.Label>
<Form.Control
as="select"
value={selectedExam}
onChange={handleExamSelect}
custom
>
<option hidden disabled selected value="">
Select an exam
</option>
{examList.map((exam) => (
<option key={exam}>{exam}</option>
))}
</Form.Control>
</Form.Group>
<Form.Group>
<Form.Check
id="staffCheckbox"
custom
type="checkbox"
label="Log in as staff"
value={isStaff}
onChange={(e) => setIsStaff(e.target.checked)}
/>
</Form.Group>
</Form>
</Col>
</Row>
)}
{username && selectedExam && !examData && (
<Row>
<Col>
<p>
You have selected the exam <b>{selectedExam}</b>.
{!forceSelectedExam && (
<>
{" "}
If this does not look correct, please re-select your exam.
</>
)}
</p>
<p>
Click the button to connect to the exam server. You can do this
before the exam begins.
</p>
<ConnectAlertButton
exam={selectedExam}
isStaff={isStaff}
onDownloadClick={onConnect}
/>
</Col>
</Row>
)}
{!isStaff && examData && (
<Row>
<Col>
<TimerBanner data={examData} />
</Col>
</Row>
)}
{!isStaff && examData && (
<Row>
<Col>
<StudentAlertsList />
</Col>
{examData.enableClarifications === true && (
<Col xs={6}>
<AskQuestion send={send} />
<StudentMessagesList />
</Col>
)}
</Row>
)}
{isStaff && examData && (
<CreateAnnouncement staffData={examData} send={send} />
)}
{isStaff && examData && (
<Row>
<Col xs={6}>
<StaffAlertsList staffData={examData} send={send} />
</Col>
<Col xs={6}>
<StaffMessagesList
selectedExam={selectedExam}
staffData={examData}
send={send}
/>
</Col>
</Row>
)}
<br />
</Container>
</AlertsContext.Provider>
);
}
<file_sep>/oh/oh_queue/static/js/components/config_linked_toggle.js
function ConfigLinkedToggle({
config,
configKey,
offText = "No",
onText = "Yes",
}) {
if (!app || Object.keys(config).length === 0) {
return null;
}
return (
<ConfigLinked
configKey={configKey}
config={config}
render={({ onSubmit, value }) => (
<FancyToggle
checked={value === "true" || value === true}
offText={offText}
onText={onText}
onChange={(x) => onSubmit(x ? "true" : "false")}
/>
)}
/>
);
}
<file_sep>/exam-alerts/main.py
import time
from collections import defaultdict
from os import getenv
from flask import jsonify, abort
from google.oauth2 import id_token
from google.auth.transport import requests as g_requests
from api import (
get_canonical_question_name,
get_student_data,
get_student_question_name,
is_admin,
clear_collection,
get_announcements,
get_email_from_secret,
generate_audio,
)
# this can be public
from examtool.api.extract_questions import extract_questions, get_name
from examtool.api.scramble import scramble
from examtool_web_common.safe_firestore import SafeFirestore
CLIENT_ID = "713452892775-59gliacuhbfho8qvn4ctngtp3858fgf9.apps.googleusercontent.com"
DEV_EMAIL = getenv("DEV_EMAIL", "<EMAIL>")
def update_cache():
global main_html, main_js
with open("static/index.html") as f:
main_html = f.read()
with open("static/main.js") as f:
main_js = f.read()
update_cache()
def get_email(request):
if getenv("ENV") == "dev":
return request.json.get("loginas") or DEV_EMAIL
token = request.json["token"]
# validate token
id_info = id_token.verify_oauth2_token(token, g_requests.Request(), CLIENT_ID)
if id_info["iss"] not in ["accounts.google.com", "https://accounts.google.com"]:
raise ValueError("Wrong issuer.")
email = id_info["email"]
if "loginas" in request.json:
exam = request.json["exam"]
course = exam.split("-")[0]
if not is_admin(email, course):
raise PermissionError
email = request.json["loginas"]
return email
def group_messages(message_list, get_message):
students = defaultdict(list)
messages = {}
latest_timestamp = (
max(message["timestamp"] for message in message_list) if message_list else 0
)
def add_message(message):
message = {**message, "responses": []}
students[message["email"]].append(message)
messages[message["id"]] = message
for message in message_list:
if "reply_to" not in message:
add_message(message)
for message in message_list:
if "reply_to" in message:
if message["reply_to"] not in messages:
add_message(get_message(message["reply_to"]))
messages[message["reply_to"]]["responses"].append(message)
for message in messages.values():
message["responses"].sort(key=lambda response: response["timestamp"])
return students, latest_timestamp
def index(request):
try:
if getenv("ENV") == "dev":
update_cache()
db = SafeFirestore()
if request.path.endswith("main.js"):
return main_js
if request.path.endswith("list_exams"):
return jsonify(
db.collection("exam-alerts")
.document("all")
.get()
.to_dict()["exam-list"]
)
if request.path == "/" or request.json is None:
return main_html
exam = request.json["exam"]
course = exam.split("-")[0]
prev_latest_timestamp = float(request.json["latestTimestamp"])
def get_message(id):
message = (
db.collection("exam-alerts")
.document(exam)
.collection("messages")
.document(id)
.get()
)
return {
**message.to_dict(),
"id": message.id,
}
student_reply = False
if request.path.endswith("ask_question"):
email = get_email(request)
student_question_name = request.json["question"]
message = request.json["message"]
student_data = get_student_data(db, email, exam)
if student_question_name is not None:
canonical_question_name = get_canonical_question_name(
student_data, student_question_name
)
if canonical_question_name is None:
return abort(400)
else:
canonical_question_name = None
db.collection("exam-alerts").document(exam).collection(
"messages"
).document().set(
dict(
question=canonical_question_name,
message=message,
email=email,
timestamp=time.time(),
)
)
student_reply = True
if request.path.endswith("fetch_data") or student_reply:
received_audio = request.json.get("receivedAudio")
email = get_email(request)
exam_data = db.collection("exam-alerts").document(exam).get().to_dict()
student_data = get_student_data(db, email, exam)
announcements = list(
db.collection("exam-alerts")
.document(exam)
.collection("announcements")
.stream()
)
messages = [
{**message.to_dict(), "id": message.id}
for message in (
db.collection("exam-alerts")
.document(exam)
.collection("messages")
.where("timestamp", ">", prev_latest_timestamp)
.where("email", "==", email)
.stream()
)
if message.to_dict()["email"] == email
]
messages, latest_timestamp = group_messages(messages, get_message)
messages = messages[email]
latest_timestamp = max(latest_timestamp, prev_latest_timestamp)
for message in messages:
if message["question"] is not None:
message["question"] = get_student_question_name(
student_data, message["question"]
)
return jsonify(
{
"success": True,
"exam_type": "ok-exam",
"enableClarifications": exam_data.get(
"enable_clarifications", False
),
"startTime": student_data["start_time"],
"endTime": student_data["end_time"],
"timestamp": time.time(),
"questions": [
question["student_question_name"]
for question in student_data["questions"]
]
if time.time() > student_data["start_time"]
else [],
"announcements": get_announcements(
student_data,
announcements,
messages,
received_audio,
lambda x: (
db.collection("exam-alerts")
.document(exam)
.collection("announcement_audio")
.document(x)
.get()
.to_dict()
or {}
).get("audio"),
),
"messages": sorted(
[
{
"id": message["id"],
"message": message["message"],
"timestamp": message["timestamp"],
"question": message["question"] or "Overall Exam",
"responses": message["responses"],
}
for message in messages
],
key=lambda message: message["timestamp"],
reverse=True,
),
"latestTimestamp": latest_timestamp,
}
)
# only staff endpoints from here onwards
email = (
get_email_from_secret(request.json["secret"])
if "secret" in request.json
else get_email(request)
)
if not is_admin(email, course):
abort(401)
if request.path.endswith("fetch_staff_data"):
pass
elif request.path.endswith("add_announcement"):
announcement = request.json["announcement"]
announcement["timestamp"] = time.time()
ref = (
db.collection("exam-alerts")
.document(exam)
.collection("announcements")
.document()
)
ref.set(announcement)
spoken_message = announcement.get("spoken_message", announcement["message"])
if spoken_message:
audio = generate_audio(spoken_message)
db.collection("exam-alerts").document(exam).collection(
"announcement_audio"
).document(ref.id).set({"audio": audio})
elif request.path.endswith("clear_announcements"):
clear_collection(
db,
db.collection("exam-alerts").document(exam).collection("announcements"),
)
clear_collection(
db,
db.collection("exam-alerts")
.document(exam)
.collection("announcement_audio"),
)
elif request.path.endswith("delete_announcement"):
target = request.json["id"]
db.collection("exam-alerts").document(exam).collection(
"announcements"
).document(target).delete()
elif request.path.endswith("send_response"):
message_id = request.json["id"]
reply = request.json["reply"]
message = (
db.collection("exam-alerts")
.document(exam)
.collection("messages")
.document(message_id)
.get()
)
ref = (
db.collection("exam-alerts")
.document(exam)
.collection("messages")
.document()
)
ref.set(
{
"timestamp": time.time(),
"email": message.to_dict()["email"],
"reply_to": message.id,
"message": reply,
}
)
audio = generate_audio(
reply, prefix="A staff member sent the following reply: "
)
db.collection("exam-alerts").document(exam).collection(
"announcement_audio"
).document(ref.id).set({"audio": audio})
elif request.path.endswith("get_question"):
question_title = request.json["id"]
student = request.json["student"]
student_data = get_student_data(db, student, exam)
question_title = get_student_question_name(student_data, question_title)
exam = db.collection("exams").document(exam).get().to_dict()
questions = extract_questions(scramble(student, exam), include_groups=True)
for question in questions:
if get_name(question).strip() == question_title.strip():
return jsonify({"success": True, "question": question})
abort(400)
else:
abort(404)
# (almost) all staff endpoints return an updated state
exam_data = db.collection("exam-alerts").document(exam).get().to_dict()
announcements = sorted(
(
{"id": announcement.id, **announcement.to_dict()}
for announcement in db.collection("exam-alerts")
.document(exam)
.collection("announcements")
.stream()
),
key=lambda announcement: announcement["timestamp"],
reverse=True,
)
grouped_messages, latest_timestamp = group_messages(
[
{**message.to_dict(), "id": message.id}
for message in db.collection("exam-alerts")
.document(exam)
.collection("messages")
.where("timestamp", ">", prev_latest_timestamp)
.stream()
],
get_message,
)
latest_timestamp = max(prev_latest_timestamp, latest_timestamp)
messages = sorted(
[
{"email": email, **message}
for email, messages in grouped_messages.items()
for message in messages
],
key=lambda message: (
len(message["responses"]) > 0,
-message["timestamp"],
message["email"],
),
)
return jsonify(
{
"success": True,
"exam": exam_data,
"announcements": announcements,
"messages": messages,
"latestTimestamp": latest_timestamp,
}
)
except Exception as e:
if getenv("ENV") == "dev":
raise
print(e)
print(dict(request.json))
return jsonify({"success": False})
<file_sep>/oh/oh_queue/static/js/components/ticket.js
let Ticket = ({ state, ticket, independent }) => {
let assignment = ticketAssignment(app.state, ticket);
let location = ticketLocation(app.state, ticket);
const staff = isStaff(state);
const staffName = ticket.helper
? isTicketHelper(state, ticket)
? "you"
: ticket.helper.name
: "someone";
const studentName = ticket.user
? ticketIsMine(state, ticket)
? "you"
: staff
? ticket.user.name
: "a student"
: "someone";
const capitalize = (x) => x[0].toUpperCase() + x.slice(1);
const possessive = (x) => (x === "you" ? "your" : x + "'s");
var status;
if (ticket.status === "pending") {
status = ticketDisplayTime(ticket) + " in " + location.name;
} else if (ticket.status === "juggled") {
status = `${capitalize(staffName)} put ${studentName} on hold ${moment
.utc(ticket.hold_time)
.fromNow()}.`;
} else if (ticket.status === "rerequested") {
status = `${capitalize(studentName)} re-requested ${possessive(
staffName
)} help ${moment.utc(ticket.rerequest_time).fromNow()}.`;
} else {
if (isStaff(state)) {
status =
capitalize(staffName) +
" (Started helping " +
ticketTimeSinceAssigned(ticket) +
")";
} else {
status = ticketStatus(state, ticket);
}
}
var description;
if (isStaff(state) || ticketIsMine(state, ticket)) {
description = ticket.description;
}
let question = ticketQuestion(app.state, ticket);
return (
<TicketLink state={state} ticket={ticket} independent={independent}>
<div className="pull-left ticket-index">
{ticketPosition(state, ticket)}
</div>
<h4 className="pull-left">
{assignment.name} {question}
<br className="visible-xs" />
<small className="visible-xs ticket-status-xs">{status}</small>
<small className="visible-xs ticket-desc-xs">{description}</small>
<small className="visible-xs ticket-created-xs">
Ticket created: {ticketTimeAgo(ticket)}
</small>
</h4>
<h4 className="pull-left hidden-xs ticket-desc-md ">
<small>{description}</small>
</h4>
<h4 className="pull-left hidden-xs ticket-created-md ">
<small>Ticket created: {ticketTimeAgo(ticket)}</small>
</h4>
<h4 className="pull-right hidden-xs ticket-status-md">
<small>
{status}{" "}
{moment
.duration(moment.utc().diff(moment.utc(ticket.created)))
.asDays() > 1 && <span className="badge"> Old Ticket </span>}
</small>
</h4>
</TicketLink>
);
};
let TicketLink = ({ state, ticket, children, independent }) => {
var { Link } = ReactRouterDOM;
let highlight =
ticketIsMine(state, ticket, true) || isTicketHelper(state, ticket);
let link = ticketIsMine(state, ticket, true) || isStaff(state);
let ticketClass = classNames({
"ticket-row": true,
clearfix: true,
"ticket-link": link,
"ticket-highlight": highlight,
"ticket-independent": independent,
"ticket-rerequested": ticket.status === "rerequested",
"ticket-juggled": ticket.status === "juggled",
});
if (link) {
return (
<div className={ticketClass}>
<Link to={`/tickets/${ticket.id}`} className="clearfix">
{children}
</Link>
</div>
);
} else {
return <div className={ticketClass}>{children}</div>;
}
};
<file_sep>/buildtool/buildtool/state.py
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from queue import Queue
from threading import Lock
from typing import Callable, Dict, List, Optional, Sequence, Set
from context import Context
from monitoring import StatusMonitor
from utils import BuildException
@dataclass
class BuildState:
# config parameters
cache_directory: str
target_rule_lookup: TargetLookup
source_files: SourceFileLookup
repo_root: str
# logging
status_monitor: StatusMonitor = None
# dynamic state
scheduling_lock: Lock = field(default_factory=Lock)
ready: Set[Rule] = field(default_factory=set)
scheduled_but_not_ready: Set[Rule] = field(default_factory=set)
work_queue: Queue[Optional[Rule]] = field(default_factory=Queue)
failure: Optional[BuildException] = None
@dataclass
class SourceFileLookup:
tracked_files: Set[str]
def __contains__(self, dep):
return os.path.relpath(os.path.realpath(dep), os.curdir) in self.tracked_files
@dataclass
class TargetLookup:
direct_lookup: Dict[str, Rule] = field(default_factory=dict)
location_lookup: Dict[str, Rule] = field(default_factory=dict)
def __iter__(self):
yield from self.direct_lookup
yield from self.location_lookup
def lookup(self, build_state: BuildState, dep: str) -> Rule:
if dep in build_state.source_files:
raise BuildException(
f"Dependency {dep} is a source file, not a buildable dependency. "
f"This is likely an internal error."
)
else:
rule = self.try_lookup(dep)
if rule is None:
raise BuildException(f"Unable to resolve dependency {dep}")
return rule
def try_lookup(self, dep: str) -> Optional[Rule]:
if dep in self.direct_lookup:
return self.direct_lookup[dep]
else:
# check locations
for parent in Path(dep).parents:
key = str(parent) + "/"
if key in self.location_lookup:
return self.location_lookup[key]
def find_source_files(self, all_files: List[str]) -> SourceFileLookup:
out = set(all_files)
for file in all_files:
if self.try_lookup(file) is not None:
out.remove(file)
return SourceFileLookup(out)
def verify(self):
# check for overlaps involving location_lookups
for path in list(self.direct_lookup) + list(self.location_lookup):
# check that this path does not lie inside a parent, by checking all prefixes
for parent in Path(path).parents:
key = str(parent) + "/"
if key in self.location_lookup:
raise BuildException(
f"Outputs {key} and {path} overlap - all outputs must be disjoint"
)
@dataclass(eq=False)
class Rule:
name: Optional[str]
location: str
deps: Sequence[str]
impl: Callable[[Context], None]
outputs: Sequence[str]
# advanced config
do_not_symlink: bool
runtime_dependents: Set[Rule] = field(default_factory=set)
pending_rule_dependencies: Set[Rule] = field(default_factory=set)
provided_value: object = None
def __hash__(self):
return hash(id(self))
def __str__(self):
if self.name:
return f":{self.name}"
elif len(self.outputs) == 1:
return self.outputs[0]
else:
return f"<anonymous rule from {self.location}/BUILD>"
<file_sep>/buildserver/target_determinator.py
import os
from typing import Iterable, Optional, Set, Union
from github.File import File
from github.Repository import Repository
from common.db import connect_db
from conf import GITHUB_REPO
def get_app(path: Optional[str]):
if path is None:
return None
path = os.path.normpath(path)
folders = path.split(os.sep)
if len(folders) <= 1:
# not in any app folder
return None
return str(folders[0])
def determine_targets(repo: Repository, files: Iterable[Union[File, str]]) -> Set[str]:
modified_apps = []
if repo.full_name == GITHUB_REPO:
for file in files:
if isinstance(file, str):
modified_apps.append(get_app(file))
else:
modified_apps.append(get_app(file.filename))
modified_apps.append(get_app(file.previous_filename))
with connect_db() as db:
modified_apps.extend(
app
for [app] in db(
"SELECT app FROM apps WHERE repo=(%s)", [repo.full_name]
).fetchall()
)
return set([app for app in modified_apps if app is not None])
<file_sep>/disc/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
flask-cors==3.0.10
-r common/requirements.txt
<file_sep>/oh/oh_queue/static/js/components/user_layout.js
function UserLayout({ state, match }) {
const userID = +match.params.id;
const [userData, setUserData] = React.useState({});
const [isLoading, setIsLoading] = React.useState(false);
if (app && !isLoading && Object.keys(userData).length === 0) {
setIsLoading(true);
app.makeRequest("get_user", userID, false, (userData) => {
setUserData(userData);
});
}
if (Object.keys(userData).length === 0) {
return null;
}
const ticketRows = userData.tickets.map((ticket) => [
moment.utc(ticket.created),
<Row
title={ticket.user.name + "'s Ticket"}
link={`/tickets/${ticket.id}`}
prop1={moment().to(moment.utc(ticket.created))}
prop2={state.locations[ticket.location_id].name}
/>,
]);
const appointmentRows = userData.appointments.map((appointment) => {
const { id, location_id, signups, start_time } = appointment;
const students = signups.map(({ user: { name } }) => name);
let studentNameList;
if (students.length === 0) {
studentNameList = "nobody";
} else if (students.length === 1) {
studentNameList = students[0];
} else {
studentNameList =
students.slice(0, students.length - 1).join(", ") +
" and " +
students[students.length - 1];
}
const title = "Section with " + studentNameList;
return [
getAppointmentStartTime(appointment),
<Row
title={title}
link={`/appointments/${id}`}
prop1={moment().to(getAppointmentStartTime({ start_time }))}
prop2={state.locations[location_id].name}
/>,
];
});
const rows = []
.concat(ticketRows, appointmentRows)
.sort((a, b) => -timeComparator(a[0], b[0]))
.map((x) => x[1]);
return (
<div>
<Navbar state={state} mode="activity_log" />
<OfflineIndicator offline={state.offline && state.loaded} />
<div className="jumbotron">
<div className="container">
<h2> {userData.user.name} </h2>
<p>{userData.user.email}</p>
<div className="activity-buttons">
<Link to="/activity_log" className="btn btn-warning">
Back to list
</Link>
</div>
</div>
</div>
<div className="container">
<h3>History</h3>
<div className="queue">{rows}</div>
</div>
</div>
);
}
<file_sep>/slack/piazza_integration.py
import itertools
import re
from collections import namedtuple
from html import unescape
from common.rpc.auth import perform_piazza_action, piazza_course_id
from integration import Integration
from utils import OrderedSet
SHORT_REGEX = r"@(?P<cid>[0-9]+)(_f(?P<fid>[0-9]+))?"
LONG_REGEX = r"<(https?://)?piazza\.com/class/{}\?cid=(?P<cid>[0-9]+)(_f(?P<fid>[0-9]+))?(\|[^\s|]+)?>"
Post = namedtuple("Post", ["subject", "content", "url", "full_cid"])
class PiazzaIntegration(Integration):
def _process(self):
course_id = piazza_course_id(course=self._course)
self._posts = OrderedSet()
for match in itertools.chain(
re.finditer(SHORT_REGEX, self._message),
re.finditer(LONG_REGEX.format(course_id), self._message),
):
cid = int(match.group("cid"))
fid_str = match.group("fid")
full_cid = match.group("cid") + ("_f{}".format(fid_str) if fid_str else "")
post = perform_piazza_action(
action="get_post",
course=self._course,
as_staff=True,
kwargs=dict(cid=cid),
)
subject = post["history"][0]["subject"]
content = post["history"][0]["content"]
if fid_str:
fid = int(fid_str) # 1 indexed
curr_id = 0
for child in post["children"]:
if child["type"] != "followup":
continue
curr_id += 1
if fid == curr_id:
break
else:
return
content = child["subject"]
subject = unescape(subject)
content = unescape(re.sub("<[^<]+?>", "", content))
url = "https://piazza.com/class/{}?cid={}".format(course_id, full_cid)
self._posts.add(Post(subject, content, url, full_cid))
@property
def message(self):
out = self._message
for post in self._posts:
shortform = "@{}".format(post.full_cid)
link = "<{}|@{}>".format(post.url, post.full_cid)
out = out.replace("<{}>".format(post.url), shortform)
out = out.replace("<{}|{}>".format(post.url, post.url), shortform)
out = out.replace(shortform, link)
return out
@property
def attachments(self):
return [
{
"color": "#3575a8",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":piazza: *<{}|{}>* \n {}".format(
post.url, post.subject, post.content[:2500]
),
},
"accessory": {
"type": "button",
"text": {"type": "plain_text", "text": "Open"},
"value": "piazza_open_click",
"url": post.url,
},
}
],
}
for post in self._posts
]
<file_sep>/common/rpc/slack.py
from typing import Union
from common.rpc.utils import create_service, requires_master_secret
service = create_service(__name__)
@requires_master_secret
@service.route("/api/list_channels")
def list_channels(*, course: str):
...
@requires_master_secret
@service.route("/api/post_message")
def post_message(*, course: str, message: Union[str, dict], channel: str):
...
<file_sep>/buildtool/buildtool/work_queue.py
from __future__ import annotations
from collections import Collection
from state import BuildState, Rule
from monitoring import log
def enqueue_deps(
build_state: BuildState,
rule: Rule,
candidate_deps: Collection[str],
*,
catch_failure: bool = False,
) -> bool:
waiting_for_deps = False
with build_state.scheduling_lock:
for dep in candidate_deps:
if dep in build_state.source_files:
# nothing to do
continue
if catch_failure:
runtime_dep: Rule = build_state.target_rule_lookup.try_lookup(dep)
if runtime_dep is None:
continue
else:
runtime_dep: Rule = build_state.target_rule_lookup.lookup(
build_state, dep
)
if runtime_dep not in build_state.ready:
waiting_for_deps = True
if runtime_dep not in build_state.scheduled_but_not_ready:
# enqueue dependency
log(f"Enqueueing dependency {runtime_dep}")
build_state.scheduled_but_not_ready.add(runtime_dep)
build_state.work_queue.put(runtime_dep)
build_state.status_monitor.move(total=1)
else:
log(f"Waiting on already queued dependency {runtime_dep}")
# register task in the already queued / executing dependency
# so when it finishes we may be triggered
runtime_dep.runtime_dependents.add(rule)
rule.pending_rule_dependencies.add(runtime_dep)
return waiting_for_deps
<file_sep>/howamidoing/src/ScoreEntry.js
import React, { Component } from "react";
import "./ScoreEntry.css";
function valid(x) {
return !Number.isNaN(x) && x !== undefined;
}
export default class ScoreEntry extends Component {
constructor(props) {
super(props);
this.checkboxRef = React.createRef();
}
componentDidMount() {
this.postRender();
}
componentDidUpdate() {
this.postRender();
}
handleClick = (e) => {
e.stopPropagation();
};
postRender = () => {
if (this.props.booleanValued && Number.isNaN(this.props.value)) {
this.checkboxRef.current.indeterminate = true;
} else if (this.props.booleanValued) {
this.checkboxRef.current.indeterminate = false;
}
};
render() {
if (this.props.booleanValued) {
return (
<div className="custom-control custom-checkbox">
<input
type="checkbox"
ref={this.checkboxRef}
checked={
!Number.isNaN(this.props.value) &&
Number.parseFloat(this.props.value) !== 0
}
className="custom-control-input"
onClick={this.handleClick}
onChange={(e) =>
!this.props.readOnly &&
this.props.onChange(e.target.checked ? 1 : 0)
}
readOnly={this.props.readOnly}
id={this.props.name}
/>
<label className="custom-control-label" htmlFor={this.props.name} />
</div>
);
} else {
return (
<input
className="ScoreEntry"
type="number"
value={valid(this.props.value) ? this.props.value : ""}
placeholder={
valid(this.props.placeholder) ? this.props.placeholder : ""
}
min="0"
step="0.1"
onClick={this.handleClick}
onChange={(e) => this.props.onChange(e.target.value)}
readOnly={this.props.readOnly}
/>
);
}
}
}
<file_sep>/slack/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
PyGitHub==1.53
-r common/requirements.txt
<file_sep>/examtool/examtool/cli/save_logs.py
import json
import os
import pathlib
import click
from examtool.api.database import get_full_logs, get_roster, get_logs
from examtool.cli.utils import exam_name_option, hidden_output_folder_option
@click.command()
@exam_name_option
@hidden_output_folder_option
@click.option(
"--full", default=False, is_flag=True, help="Get keylogging logs too, if available."
)
@click.option(
"--fetch_all",
default=False,
is_flag=True,
help="Re-download all logs.",
)
def save_logs(exam, out, full, fetch_all):
"""
Save the full submission log for later analysis.
Note that this command is slow.
To view a single log entry, run `examtool log`.
"""
out = out or "out/logs/" + exam
full_out = os.path.join(out, "full")
pathlib.Path(out).mkdir(parents=True, exist_ok=True)
pathlib.Path(full_out).mkdir(parents=True, exist_ok=True)
roster = get_roster(exam=exam)
for i, (email, deadline) in enumerate(roster):
print(email)
try:
target = os.path.join(out, email)
if os.path.exists(target) and not fetch_all:
print("Skipping", email)
else:
print("Fetching short logs for", email)
logs = get_logs(exam=exam, email=email)
with open(target, "w") as f:
json.dump(logs, f)
if full:
target = os.path.join(full_out, email)
if os.path.exists(target) and not fetch_all:
print("Skipping", email, "for full logs")
else:
print("Fetching full logs for", email)
logs = get_full_logs(exam=exam, email=email)
with open(os.path.join(full_out, email), "w") as f:
json.dump(logs, f)
except KeyboardInterrupt:
raise
except:
print("Failure for email", email, "continuing...")
<file_sep>/howamidoing/src/StudentTable.js
import React from "react";
export default function StudentTable({ students, onLogin }) {
const cols = ["Name", "Email", "SID", "Score"];
const studentRows = students.map((student, i) => (
// eslint-disable-next-line react/no-array-index-key
<tr key={i}>
{cols.map((x) => (
<td key={x}>{student[x]}</td>
))}
<td>
<button type="button" onClick={() => onLogin(student.Email)}>
Enter
</button>
</td>
</tr>
));
return (
<table className="table table-hover">
<thead>
<tr>
{cols.map((col) => (
<th scope="col" key={col}>
{col}
</th>
))}
<th>Login As</th>
</tr>
</thead>
<tbody>{studentRows}</tbody>
</table>
);
}
<file_sep>/howamidoing/src/computeTotals.js
/* eslint-disable no-param-reassign */
function parse(score) {
if (Number.isNaN(parseFloat(score))) {
return score;
}
return Number.parseFloat(score);
}
export default (assignments, scores, future) => {
const totals = {};
const computeTotals = (curr) => {
if (totals[curr.name]) {
// TODO: remove this kludge
return totals[curr.name];
}
if (curr.future && !future) {
return NaN;
}
if (!curr.isTopic) {
totals[curr.name] =
scores[curr.name] !== undefined ? parse(scores[curr.name]) : NaN;
return totals[curr.name];
}
const childTotals = [];
let out = 0;
for (const child of curr.children.slice().reverse()) {
if (child.future && !future) {
continue;
}
const childTotal = computeTotals(child, totals);
out += childTotal;
childTotals.push(childTotal);
}
childTotals.reverse();
if (curr.customCalculator) {
out = curr.customCalculator(childTotals, future);
}
const limit = future ? curr.futureMaxScore : curr.maxScore;
if (limit && !curr.uncapped) {
out = Math.min(out, limit);
}
totals[curr.name] = out;
if (
scores[curr.name] !== undefined &&
!Number.isNaN(Number.parseFloat(scores[curr.name]))
) {
totals[curr.name] = Number.parseFloat(scores[curr.name]);
return totals[curr.name];
}
return out;
};
for (const assignment of assignments) {
computeTotals(assignment);
}
return totals;
};
<file_sep>/docs/README.md
# 61A Documentation
This app generates documentation for all 61A apps. If you need any help or have
questions at any point during the process, please message {{ docs_in_charge }}!
## Setup
1. Clone the repo and switch into the `docs` directory.
2. Create a new branch for your project using `git checkout -b docs/app-name`,
where `app-name` is the name of the app you're documenting (use hyphens if
the name is multiple words). If someone has already created this branch,
omit the `-b` flag.
3. Set up the Python environment using `python3 -m venv env` and
`env/bin/pip install -r requirements.txt`, or simply `sicp venv`
if you have `sicp` installed.
4. Run the Sphinx autobuilder using
`env/bin/sphinx-autobuild -b dirhtml .. _build`
5. Visit http://localhost:8000 to see the docs.
Alternatively, to compile all docs once, run
`env/bin/sphinx-build -b dirhtml .. _build`. This will generate an output
folder `_build` containing the compiled documentation. Useful for when you
don't want to run the file watcher.
## Writing Documentation
To write documentation for an app, we use a combination of
[reStructuredText](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html)
and [MyST](https://myst-parser.readthedocs.io/en/latest/). MyST allows us to
write Sphinx documentation in a markdown equivalent of reStructuredText. The
documentation for MyST should help you write the `index` and `README` files,
but we'll cover some examples and tips below anyway. The documentation for
reStructuredText will help you write the inline Python documentation.
### Text Editor Setup
First thing you should do is set up your text editor's vertical ruler to let
you know when you're hitting an 80-character limit (this is a standard, but not
a rule). In Visual Studio Code, this can be achieved by adding the following to
your `settings.json`:
```json
"editor.rulers": [
{
"column": 80,
"color": "#555"
},
]
```
### Creating the README
```{note}
We will use [MyST](https://myst-parser.readthedocs.io/en/latest/) for the
README.
```
Then, for whichever app you want to document, create a `README.md` under the
directory for that app, and set it up like so:
```md
# App Name
A brief description of what the app is meant to do.
## Setup
Include some steps to tell people how to develop this app locally.
## Other Sections
Include details that could help people develop or use the app.
```
### Creating the Index
```{note}
We will use [MyST](https://myst-parser.readthedocs.io/en/latest/) for the
index.
```
In order to place this app on the navbar, create an `index.md` under the same
directory, and set it up like so:
````
```{include} README.md
```
## Code Segment 1
```{eval-rst}
.. automodule:: app_directory.module_name
:members:
```
````
Where ``app_directory.module_name`` is the path to the file you're including,
such as ``common.db``.
Code segments like the one at the end of the example will auto-include the code
documentation for the various components of the app.
### Documenting Code
```{note}
We will use
[reStructuredText](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html)
for inline Python documentation.
```
To document a method in a Python file, format it like so:
```python
def function(param1: str, param2: int = 2):
"""Description of the function.
Can span multiple lines or paragraphs, if needed!
:param param1: one line about the first parameter
:type param1: str
:param param2: one line about the second parameter
:type param2: int
:return: one line about the return value (including type)
"""
# function body is here
```
Where `str` and `int` should be replaced with the actual type of the parameter.
```{note}
The type annotations go in two places: the function dignature, as well as the
body of the docstring.
```
This will result in the following rendered documentation:
```{eval-rst}
.. py:function:: function(param1: str, param2: int = 2)
Description of the function.
Can span multiple lines or paragraphs, if needed!
:param param1: one line about the first parameter
:type param1: str
:param param2: one line about the second parameter
:type param2: int
:return: one line about the return value (including type)
```
### Documenting `rpc` Methods
You do not have to write documentation for methods that are bound to RPC. For
example, if you're documenting `howamidoing`, when you get to `upload_grades`,
you can simply write the following (see emphasized line):
```{eval-rst}
.. code-block:: python
:emphasize-lines: 4
@rpc_upload_grades.bind(app)
@only("grade-display", allow_staging=True)
def upload_grades(data: str):
"""See :func:`~common.rpc.howamidoing.upload_grades`."""
with transaction_db() as db:
set_grades(data, get_course(), db)
```
### Linking to Other Documentation
If you mention another function, method, or class, please include a link to the
documentation for such. If this is in a MyST file, you can do this as follows:
```
{func}`common.shell_utils.sh`
{meth}`common.hash_utils.HashState.update`
{class}`~subprocess.Popen`
```
This will appear as {func}`common.shell_utils.sh`,
{meth}`common.hash_utils.HashState.update`, and {class}`~subprocess.Popen`.
If this is in a Python file (using rST), you can do this as follows:
```
:func:`common.shell_utils.sh`
:meth:`~common.hash_utils.HashState.update`
:class:`subprocess.Popen`
```
This will appear as {func}`common.shell_utils.sh`,
{meth}`~common.hash_utils.HashState.update`, and {class}`subprocess.Popen`.
```{note}
Per the examples above, if you insert a `~` before the path to the
documentation, Sphinx will render the link using only the name of the object
itself, and will drop the path itself. This is desirable for cleanliness, so
use this whenever linking to a document.
```
If you want to refer to something that is documented outside of this project,
the Python docs, and the Flask docs, message {{ docs_in_charge }} with what
you're trying to document, as well as a link to the documentation for the
relevant project. He will then add it to `intersphinx_mapping` dictionary in
the configuration, so that you can link to it as you would anything else. As an
example, to link to Flask's `redirect` function, you can use
``{func}`~flask.redirect` ``. This will render as {func}`~flask.redirect`.
## Full Example
### Sample README
Here's what the `common` README file looks like:
```{eval-rst}
.. literalinclude:: ../common/README.md
:language: markdown
```
### Sample Index
Here's what the `common` index file looks like:
```{eval-rst}
.. literalinclude:: ../common/index.md
```
### Sample Code Documentation
Here's what the {func}`common.db.connect_db` docs look like:
```{eval-rst}
.. literalinclude:: ../common/db.py
:pyobject: connect_db
```
Here's what the {func}`common.shell_utils.sh` docs look like:
```{eval-rst}
.. literalinclude:: ../common/shell_utils.py
:pyobject: sh
```
<file_sep>/grade-display/auth.py
import requests, sys, time
import logging, ssl
from flask import redirect
from common.oauth_client import is_staff
from common.rpc.secrets import get_secret
from common.url_for import url_for
from common.db import connect_db
log = logging.getLogger(__name__)
CLIENT_ID = "grade-display-exports"
CLIENT_SECRET = get_secret(secret_name="OKPY_OAUTH_SECRET")
OAUTH_SCOPE = "all"
TIMEOUT = 10
TOKEN_ENDPOINT = "/oauth/token"
# ---------------------
with connect_db() as db:
db(
"""CREATE TABLE IF NOT EXISTS tokens (
access_token VARCHAR(128),
expires_at INTEGER,
refresh_token VARCHAR(128)
)
"""
)
def make_token_post(server, data):
"""Try getting an access token from the server. If successful, returns the
JSON response. If unsuccessful, raises an OAuthException.
"""
try:
response = requests.post(server + TOKEN_ENDPOINT, data=data, timeout=TIMEOUT)
body = response.json()
except Exception as e:
log.warning("Other error when exchanging code", exc_info=True)
raise OAuthException(error="Authentication Failed", error_description=str(e))
if "error" in body:
log.error(body)
raise OAuthException(
error=body.get("error", "Unknown Error"),
error_description=body.get("error_description", ""),
)
return body
def make_refresh_post(refresh_token):
data = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
}
info = make_token_post(server_url(), data)
return info["access_token"], int(info["expires_in"]), info["refresh_token"]
def get_storage():
with connect_db() as db:
token = db("SELECT * FROM tokens").fetchone()
if token:
access_token = token[0]
expires_at = token[1]
refresh_token = token[2]
return access_token, expires_at, refresh_token
return None, 0, None
def update_storage(data):
access_token, expires_in, refresh_token = (
data.get("access_token"),
data.get("expires_in"),
data.get("refresh_token"),
)
if not (access_token and expires_in and refresh_token):
raise AuthenticationException(
"Authentication failed and returned an empty token."
)
cur_time = int(time.time())
with connect_db() as db:
db("DELETE FROM tokens")
db(
"INSERT INTO tokens (access_token, expires_at, refresh_token) VALUES (%s, %s, %s)",
[access_token, cur_time + expires_in, refresh_token],
)
def refresh_local_token():
cur_time = int(time.time())
access_token, expires_at, refresh_token = get_storage()
if cur_time < expires_at - 10:
return access_token
access_token, expires_in, refresh_token = make_refresh_post(refresh_token)
if not (access_token and expires_in):
raise AuthenticationException(
"Authentication failed and returned an empty token."
)
update_storage(
{
"access_token": access_token,
"expires_in": expires_in,
"refresh_token": refresh_token,
}
)
return access_token
def server_url():
return "https://okpy.org"
def authenticate(app):
"""Returns an OAuth token that can be passed to the server for
identification. If FORCE is False, it will attempt to use a cached token
or refresh the OAuth token. If NOINTERACT is true, it will return None
rather than prompting the user.
"""
try:
access_token = refresh_local_token()
except Exception:
print("Performing authentication.")
if not is_staff("cs61a"):
return redirect(url_for("login"))
return "Authorized!"
def get_token():
return refresh_local_token()
class OkException(Exception):
"""Base exception class for OK."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
log.debug("Exception raised: {}".format(type(self).__name__))
log.debug("python version: {}".format(sys.version_info))
class AuthenticationException(OkException):
"""Exceptions related to authentication."""
class OAuthException(AuthenticationException):
def __init__(self, error="", error_description=""):
super().__init__()
self.error = error
self.error_description = error_description
<file_sep>/code/src/renderer/components/App.js
/* eslint-disable import/first,global-require */
let hot;
if (!ELECTRON) {
({ hot } = require("react-hot-loader/root"));
}
import { useEffect, useState } from "react";
import * as React from "react";
import useSettings from "../utils/settingsHandler";
import LaunchScreen from "./LaunchScreen.js";
import MainScreen from "./MainScreen.js";
let MenuBar;
if (!ELECTRON) {
MenuBar = require("./MenuBar.js").default;
}
import { sendNoInteract } from "../utils/communication.js";
import { OPEN_FILE } from "../../common/communicationEnums.js";
const App = ({ path }) => {
const [launch, setLaunch] = useState(true);
const [initFile, setInitFile] = useState(null);
const [startInterpreter, setStartInterpreter] = useState();
const [srcOrigin, setSrcOrigin] = useState();
const settings = useSettings();
const handleAllClosed = () => {
setLaunch(true);
};
const handleFileCreate = (file, interpreter, origin) => {
setStartInterpreter(interpreter);
setSrcOrigin(origin);
setInitFile(file);
setLaunch(false);
};
let primaryElem;
if (launch) {
primaryElem = <LaunchScreen onFileCreate={handleFileCreate} />;
} else {
primaryElem = (
<MainScreen
onAllClosed={handleAllClosed}
initFile={initFile}
srcOrigin={srcOrigin}
startInterpreter={startInterpreter}
settings={settings}
/>
);
}
useEffect(() => {
if (path) {
sendNoInteract({
type: OPEN_FILE,
location: path,
}).then((value) => {
if (value.success) {
handleFileCreate(value.file);
}
});
}
window.history.replaceState(false, "", "/");
if (!ELECTRON && window.initData) {
const {
loadFile,
srcOrigin: initSrcOrigin,
startInterpreter: initStartInterpreter,
} = initData;
if (loadFile) {
handleFileCreate(
{
name: loadFile.fileName,
location: null,
content: loadFile.data,
shareRef: loadFile.shareRef,
},
initStartInterpreter,
initSrcOrigin
);
}
}
}, []);
if (ELECTRON) {
return primaryElem;
} else {
return (
<>
<MenuBar />
{primaryElem}
</>
);
}
};
export default ELECTRON ? App : hot(App);
<file_sep>/buildtool/buildtool/loader.py
from __future__ import annotations
import os
import sys
import time
import traceback
from dataclasses import dataclass, field
from glob import glob
from importlib.metadata import version
from typing import Callable, Dict, List, Optional, Sequence, Set, Union
from colorama import Style
from fs_utils import find_root, get_repo_files, normalize_path
from packaging.version import parse
from state import Rule, TargetLookup
from utils import BuildException
LOAD_FRAME_CACHE: Dict[str, Struct] = {}
TIMINGS = {}
start_time_stack = []
@dataclass
class Config:
# CLI config
skip_version_check: bool = False
# loaded config
default_setup_rule: Optional[str] = None
default_build_rule: Optional[str] = None
active: bool = False
output_directories: List[str] = field(default_factory=list)
def _check_active(self):
if not self.active:
raise BuildException("Cannot use config in this context.")
@staticmethod
def _check_rule(rule: str):
if not rule.startswith(":"):
raise BuildException(f"Can only register a rule, not {rule}")
def register_default_setup_rule(self, rule: str):
self._check_active()
self._check_rule(rule)
if self.default_setup_rule is not None:
raise BuildException(
f"Default setup rule is already set to {self.default_setup_rule}"
)
self.default_setup_rule = rule
def register_default_build_rule(self, rule: str):
self._check_active()
self._check_rule(rule)
if self.default_build_rule is not None:
raise BuildException(
f"Default build rule is already set to {self.default_build_rule}"
)
self.default_build_rule = rule
def register_output_directory(self, path: str):
self._check_active()
self.output_directories.append(normalize_path(os.curdir, os.curdir, path))
def require_buildtool_version(self, min_version: str):
if self.skip_version_check:
return
curr_version = version("buildtool").replace("-", "9999")
if parse(curr_version) < parse(min_version):
raise BuildException(
f"Current buildtool version {curr_version} < {min_version}, the minimum required "
"for this project. Please upgrade, or pass in --skip-version-check to skip this check."
)
config = Config()
def make_callback(
repo_root: str,
build_root: Optional[str],
src_files: Set[str],
# output parameter
target_rule_lookup: TargetLookup,
):
make_callback.build_root = build_root
make_callback.find_cache = {}
make_callback.target_rule_lookup = target_rule_lookup
def fail(target):
raise BuildException(
f"The target `{target}` is built by multiple rules. Targets can only be produced by a single rule."
)
def add_target_rule(target, rule):
target_rule_lookup = make_callback.target_rule_lookup
if target.endswith("/"):
# it's a folder dependency
if target in target_rule_lookup.location_lookup:
fail(target)
target_rule_lookup.location_lookup[target] = rule
else:
if target in target_rule_lookup.direct_lookup:
fail(target)
target_rule_lookup.direct_lookup[target] = rule
def callback(
*,
name: Optional[str] = None,
deps: Sequence[str] = (),
impl: Callable = lambda _: None,
out: Union[str, Sequence[str]] = (),
do_not_symlink: bool = False,
):
build_root = make_callback.build_root
if build_root is None:
raise BuildException(
"Rules files can only define functions, not invoke callback()"
)
if isinstance(out, str):
out = [out]
rule = Rule(
name=name,
location=build_root,
deps=[
dep
if dep.startswith(":")
else normalize_path(repo_root, build_root, dep)
for dep in deps
],
impl=impl,
outputs=[normalize_path(repo_root, build_root, output) for output in out],
do_not_symlink=do_not_symlink,
)
for output in rule.outputs:
add_target_rule(output, rule)
if name is not None:
add_target_rule(":" + name, rule)
return f":{name}"
def find(path, *, unsafe_ignore_extension=False):
build_root = make_callback.build_root
target = normalize_path(repo_root, build_root, path)
if target in make_callback.find_cache:
return make_callback.find_cache[target]
if build_root is None:
raise BuildException(
"Rules files can only define functions, not invoke find()"
)
if not unsafe_ignore_extension:
ext = path.split(".")[-1]
if "/" in ext:
raise BuildException(
"Cannot find() files without specifying an extension"
)
out = [
os.path.relpath(path, repo_root)
for path in glob(
normalize_path(repo_root, build_root, path),
recursive=True,
)
]
make_callback.find_cache[target] = out = [
"//" + path
for path in out
if os.path.relpath(os.path.realpath(path), repo_root) in src_files
]
return sorted(out)
def resolve(path):
build_root = make_callback.build_root
if build_root is None:
raise BuildException(
"Rules files can only define functions, not invoke resolve(). "
"If you are in an impl() function, use ctx.resolve() instead."
)
return "//" + normalize_path(repo_root, build_root, path)
return callback, find, resolve
class Struct:
def __init__(self, entries, default=False):
self.__dict__.update(entries)
self.default = default
def __getattr__(self, item):
if self.default:
return None
else:
return getattr(super(), item)
def make_load_rules(repo_root: str, rules_root: str):
make_load_rules.rules_root = os.path.dirname(rules_root)
def load_rules(path):
path = normalize_path(repo_root, make_load_rules.rules_root, path)
if not path.endswith(".py"):
raise BuildException(f"Cannot import from a non .py file: {path}")
if path in LOAD_FRAME_CACHE:
return LOAD_FRAME_CACHE[path]
start_time_stack.append(time.time())
old_rules_root = make_load_rules.rules_root
__builtins__["load"] = make_load_rules(repo_root, path)
# We hide the callback here, since you should not be running the
# callback (or anything else!) in an import, but just providing defs
frame = {"__builtins__": __builtins__}
reset_mock_imports(frame, ["load"])
cached_root = make_callback.build_root
make_callback.build_root = None
with open(path) as f:
try:
exec(f.read(), frame)
except Exception:
raise BuildException(
f"Error while processing rules file {path}:\n"
+ f"\n{Style.RESET_ALL}"
+ traceback.format_exc()
)
make_callback.build_root = cached_root
make_load_rules.rules_root = old_rules_root
TIMINGS[path] = load_time = time.time() - start_time_stack.pop()
start_time_stack[0] += load_time
out = LOAD_FRAME_CACHE[path] = Struct(frame)
return out
return load_rules
def reset_mock_imports(frame, targets):
exec(
"import buildtool; "
+ " ".join(f"buildtool.{target} = {target};" for target in targets),
frame,
)
def load_rules(
flags: Dict[str, object],
*,
skip_version_check: bool,
workspace: bool = False,
):
flags = Struct(flags, default=True)
repo_root = find_root()
src_files = get_repo_files()
build_files = (
["WORKSPACE"]
if workspace
else [file for file in src_files if file.split("/")[-1] == "BUILD"]
)
target_rule_lookup = TargetLookup()
sys.path.insert(0, repo_root)
callback, find, resolve = make_callback(
repo_root, None, set(src_files), target_rule_lookup
)
config.skip_version_check = skip_version_check
for build_file in build_files:
make_callback.build_root = os.path.dirname(build_file)
with open(build_file) as f:
frame = {}
load = make_load_rules(repo_root, build_file)
__builtins__["callback"] = callback
__builtins__["find"] = find
__builtins__["resolve"] = resolve
__builtins__["load"] = load
__builtins__["flags"] = flags
frame = {
**frame,
"__builtins__": __builtins__,
}
reset_mock_imports(frame, ["callback", "find", "load", "flags", "resolve"])
if workspace:
__builtins__["config"] = config
config.active = True
reset_mock_imports(frame, ["config"])
start_time_stack.append(time.time())
try:
exec(f.read(), frame)
config.active = False
except Exception:
raise BuildException(
f"Error while processing BUILD file {build_file}:\n"
+ f"\n{Style.RESET_ALL}"
+ traceback.format_exc()
)
TIMINGS[build_file] = time.time() - start_time_stack.pop()
make_callback.build_root = None
return target_rule_lookup
<file_sep>/buildserver/external_repo_utils.py
from app_config import App, WEB_DEPLOY_TYPES
from common.db import connect_db
def update_config(app: App, pr_number: int):
with connect_db() as db:
db(
"DELETE FROM services WHERE app=(%s) AND pr_number=(%s)",
[app.name, pr_number],
)
db(
"INSERT INTO services VALUES (%s, %s, %s, %s)",
[app.name, pr_number, False, app.config["deploy_type"] in WEB_DEPLOY_TYPES],
)
if pr_number == 0:
db("DELETE FROM apps WHERE app=%s", [app.name])
if app.config["repo"]:
db(
"INSERT INTO apps (app, repo, autobuild) VALUES (%s, %s, %s)",
[app.name, app.config["repo"], True],
)
<file_sep>/cats/src/ProgressBars.js
import React from "react";
import "./ProgressBars.css";
import ProgressBar from "react-bootstrap/ProgressBar";
export default function ProgressBars({ progress: allProgress, playerIndex }) {
const variants = ["info", "warning", "success", "danger"];
return (
<div className="ProgressBars">
{allProgress.map(([progress, time], index) => {
const displayText = progress === 1 && `${time.toFixed(2)} seconds`;
const playerSuffix = index === playerIndex ? " (you)" : "";
return (
<div className="ProgressBar" key={index}>
<ProgressBar
variant={variants[index]}
animated
label={`Player ${index + 1}${playerSuffix}`}
now={progress * 100}
/>
<div className="barData">{displayText}</div>
</div>
);
})}
</div>
);
}
<file_sep>/oh/migrations/versions/c2f835ce68a7_index_by_course.py
"""index by course
Revision ID: c2f835ce68a7
Revises: 3<PASSWORD>
Create Date: 2020-03-11 12:53:56.472366
"""
# revision identifiers, used by Alembic.
revision = "c2f835ce68a7"
down_revision = "3ac7f97f07e4"
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_index(
op.f("ix_appointment_course"), "appointment", ["course"], unique=False
)
op.create_index(
op.f("ix_appointment_signup_course"),
"appointment_signup",
["course"],
unique=False,
)
op.create_index(
op.f("ix_assignment_course"), "assignment", ["course"], unique=False
)
op.create_index(
op.f("ix_config_entries_course"), "config_entries", ["course"], unique=False
)
op.create_index(op.f("ix_location_course"), "location", ["course"], unique=False)
op.create_index(op.f("ix_ticket_course"), "ticket", ["course"], unique=False)
op.create_index(
op.f("ix_ticket_event_course"), "ticket_event", ["course"], unique=False
)
op.create_index(op.f("ix_user_course"), "user", ["course"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_user_course"), table_name="user")
op.drop_index(op.f("ix_ticket_event_course"), table_name="ticket_event")
op.drop_index(op.f("ix_ticket_course"), table_name="ticket")
op.drop_index(op.f("ix_location_course"), table_name="location")
op.drop_index(op.f("ix_config_entries_course"), table_name="config_entries")
op.drop_index(op.f("ix_assignment_course"), table_name="assignment")
op.drop_index(op.f("ix_appointment_signup_course"), table_name="appointment_signup")
op.drop_index(op.f("ix_appointment_course"), table_name="appointment")
# ### end Alembic commands ###
<file_sep>/examtool/examtool/api/substitution_finder.py
import json
from dataclasses import dataclass
from typing import Dict
from examtool.api.utils import dict_to_list
from tqdm import tqdm
from examtool.api.database import get_exam, get_roster
from examtool.api.extract_questions import extract_questions, get_name
from examtool.api.scramble import scramble, get_elements
@dataclass
class SuspectedCheating:
question: str
email: str
base_keyword: str
expected: str
observed: str
answer: str
substitutions: Dict[str, str]
def explain(self):
print(
f"In question {self.question}, student {self.email} used keyword {self.observed} for "
f"{self.base_keyword}, when they should have used {self.expected}"
)
print(
f"\tThey wrote `{' '.join(self.answer.split())}`. Their substitutions were: {self.substitutions}"
)
def find_unexpected_words(exam, logs):
data = get_exam(exam=exam)
exam_json = json.dumps(data)
original_questions = {q["id"]: q for q in extract_questions(json.loads(exam_json))}
suspected_cheating = []
for i, (email, log) in enumerate(tqdm(logs)):
all_alternatives = get_substitutions(data)
scrambled_questions = {
q["id"]: q
for q in extract_questions(
scramble(email, json.loads(exam_json), keep_data=True), nest_all=True
)
}
flagged_question_variants = set()
for record in log:
record.pop("timestamp")
for question, answer in record.items():
question = question.split("|")[0]
if question not in all_alternatives:
continue
student_substitutions = scrambled_questions[question]["substitutions"]
for keyword in student_substitutions:
for variant in all_alternatives[question][keyword]:
if variant == student_substitutions[keyword]:
continue
if (question, keyword, variant) in flagged_question_variants:
continue
if variant in answer:
# check for false positives
if variant in scrambled_questions[question]["text"]:
continue
flagged_question_variants.add((question, keyword, variant))
suspected_cheating.append(
SuspectedCheating(
get_name(original_questions[question]),
email,
keyword,
student_substitutions[keyword],
variant,
answer,
student_substitutions,
)
)
return suspected_cheating
def find_keyword(exam, phrase):
data = get_exam(exam=exam)
exam_json = json.dumps(data)
for email, _ in get_roster(exam=exam):
scrambled = scramble(email, json.loads(exam_json))
if phrase in json.dumps(scrambled):
print(email)
def get_substitutions(exam):
out = {}
def process_element(element):
substitutions = element.get("substitutions", {}).copy()
for item in element.get("substitutions_match", []):
for directive in item["directives"]:
substitutions[directive] = item["replacements"]
for blocks in element.get("substitution_groups", []):
directives = blocks["directives"]
replacements = dict_to_list(blocks["replacements"])
for directive, directive_replacements in zip(
directives, zip(*(dict_to_list(d) for d in replacements))
):
substitutions[directive] = directive_replacements
for key in element.get("substitution_ranges", {}):
substitutions[key] = [] # hack to make RANGEs not crash
return substitutions
def process_group(group, substitutions):
group_substitutions = process_element(group)
for element in get_elements(group):
if element.get("type") == "group":
process_group(element, {**substitutions, **group_substitutions})
else:
process_question(element, {**substitutions, **group_substitutions})
def process_question(question, substitutions):
out[question["id"]] = {**substitutions, **process_element(question)}
global_substitutions = process_element(exam)
for group in exam["groups"]:
process_group(group, global_substitutions)
return out
<file_sep>/slack/main.py
from flask import Flask
from api_client import create_api_client
from common.oauth_client import create_oauth_client
from config_client import create_config_client
from slack_client import create_slack_client
app = Flask(__name__)
if __name__ == "__main__":
app.debug = True
create_config_client(app)
create_slack_client(app)
create_oauth_client(app, "eecs-slackbot")
create_api_client(app)
if __name__ == "__main__":
app.run(debug=True)
<file_sep>/sandbox/requirements.txt
Flask==1.1.2
google-cloud-storage==1.33.0
gunicorn==20.0.4
mysqlclient==2.0.1
PyYAML==5.3.1
pyserve==0.2.8
xerox==0.4.1
-e ./buildtool
-e ./sicp
-r common/requirements.txt
<file_sep>/slack/ed_integration.py
import itertools
import re
from collections import namedtuple
from html import unescape
from common.rpc.auth import perform_ed_action, ed_course_id
from integration import Integration
from utils import OrderedSet
SHORT_REGEX = r"@(?P<num>[0-9]+)"
LONG_REGEX = (
r"<(https?://)?edstem\.org/us/courses/{}\/discussion/(?P<pid>[0-9]+)(\|[^\s|]+)?>"
)
Post = namedtuple("Post", ["subject", "content", "url", "num", "pid"])
class EdIntegration(Integration):
def _process(self):
course_id = ed_course_id(course=self._course)
ed_posts = perform_ed_action(
action="get_feed",
course=self._course,
as_staff=True,
kwargs=dict(limit=999999),
)["threads"]
self._posts = OrderedSet()
for match in itertools.chain(
re.finditer(SHORT_REGEX, self._message),
re.finditer(LONG_REGEX.format(course_id), self._message),
):
num = int(match.group("num"))
pid = int(match.group("pid"))
post = None
if pid:
for p in ed_posts:
if p.get("id", 0) == pid:
post = p
break
elif num:
for p in ed_posts:
if p.get("number", 0) == num:
post = p
break
if not post:
continue
subject = post["title"]
content = post["document"]
subject = unescape(subject)
content = unescape(re.sub("<[^<]+?>", "", content))
url = "https://edstem.org/us/courses/{}/discussion/{}".format(
course_id, post["id"]
)
self._posts.add(Post(subject, content, url, post["number"], post["id"]))
@property
def message(self):
out = self._message
for post in self._posts:
shortform = "@{}".format(post.num)
link = "<{}|@{}>".format(post.url, post.num)
out = out.replace("<{}>".format(post.url), shortform)
out = out.replace("<{}|{}>".format(post.url, post.url), shortform)
out = out.replace(shortform, link)
return out
@property
def attachments(self):
return [
{
"color": "#3575a8",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": ":piazza: *<{}|{}>* \n {}".format(
post.url, post.subject, post.content[:2500]
),
},
"accessory": {
"type": "button",
"text": {"type": "plain_text", "text": "Open"},
"value": "piazza_open_click",
"url": post.url,
},
}
],
}
for post in self._posts
]
<file_sep>/oh/oh_queue/static/js/components/messages.js
let Messages = ({ messages }) => (
<div className="row messages">
{messages.map((message) => (
<Message key={message.id} message={message} />
))}
</div>
);
let Message = ({ message }) => {
let { id, text, category, visible } = message;
if (!visible) {
return null;
}
return (
<div className="col-xs-12">
<div className={`alert alert-${category} alert-dismissible`} role="alert">
<button
type="button"
className="close"
aria-label="Close"
onClick={() => app.clearMessage(id)}
>
<span aria-hidden="true">×</span>
</button>
{text}
</div>
</div>
);
};
<file_sep>/common/cli_utils.py
from colorama import Style
def pretty_print(emoji: str, msg: str):
"""Pretty prints a message.
:param emoji: the emoji to wrap the message in
:type emoji: str
:param msg: the message to wrap with the emoji
:type msg: str
"""
print(f"{emoji}{Style.BRIGHT} {msg} {Style.RESET_ALL}{emoji}")
<file_sep>/hog-calc/requirements.txt
flask
gunicorn
pytz
-r common/requirements.txt
<file_sep>/oh/migrations/prev_versions/1b5a90520562_admin_config.py
"""Add admin config support
Revision ID: 1b5a90520562
Revises: <PASSWORD>
Create Date: 2019-09-29 15:28:21.510635
"""
# revision identifiers, used by Alembic.
revision = "1b5a90520562"
down_revision = "<PASSWORD>"
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
BaseTable = declarative_base()
class ConfigEntry(BaseTable):
__tablename__ = "config_entries"
id = sa.Column(sa.Integer(), primary_key=True)
key = sa.Column(sa.String(255))
value = sa.Column(sa.Text(), nullable=False)
public = sa.Column(sa.Boolean, default=False)
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
# Create new tables
ConfigEntry.__table__.create(connection)
# Seed default config values
session.commit()
def downgrade():
# Get alembic DB bind
connection = op.get_bind()
# Create new tables
op.drop_table("config_entries")
<file_sep>/cats/src/NameForm.js
import React, { useRef } from "react";
export default function NameForm({ onSubmit }) {
const inputRef = useRef(null);
return (
<>
Congratulations! Your WPM is fast enough to place on our leaderboard!
Enter a name here to associate it with your score:
<br />
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit(inputRef.current.value);
}}
>
<div className="form-group">
<input
type="text"
ref={inputRef}
className="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="Enter username"
/>
<small id="emailHelp" className="form-text text-muted">
Please don't name yourself anything inappropriate!
</small>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">
Submit
</button>
</div>
</form>
</>
);
}
<file_sep>/buildserver/README.md
# Buildserver
Navigate to https://buildserver.cs61a.org/.
To build the website, click the `website-base` button.
<file_sep>/ok-help/src/utils.js
import { useRef } from "react";
let id = 0;
export default function useId() {
return useRef(++id);
}
<file_sep>/oh/migrations/prev_versions/7f68eed434ab_assignment_location_config.py
"""Assignment, location configuration
Revision ID: 7f68eed434ab
Revises: 42d3400175b3
Create Date: 2019-03-06 16:24:48.445773
"""
# revision identifiers, used by Alembic.
revision = "7f68eed434ab"
down_revision = "42d3400175b3"
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.declarative import declarative_base
BaseTable = declarative_base()
class Assignment(BaseTable):
__tablename__ = "assignment"
id = sa.Column(sa.Integer, primary_key=True)
created = sa.Column(sa.DateTime, default=sa.func.now())
name = sa.Column(sa.String(255), nullable=False, unique=True)
visible = sa.Column(sa.Boolean, default=False)
class Location(BaseTable):
__tablename__ = "location"
id = sa.Column(sa.Integer, primary_key=True)
created = sa.Column(sa.DateTime, default=sa.func.now())
name = sa.Column(sa.String(255), nullable=False, unique=True)
visible = sa.Column(sa.Boolean, default=False)
class TicketHelper(BaseTable):
__tablename__ = "ticket"
id = sa.Column(sa.Integer, primary_key=True)
assignment_name = sa.Column("assignment", sa.String(length=255))
assignment_id = sa.Column(sa.ForeignKey("assignment.id"))
location_name = sa.Column("location", sa.String(length=255))
location_id = sa.Column(sa.ForeignKey("location.id"))
assignment = orm.relationship(Assignment, backref="ticket")
location = orm.relationship(Location, backref="ticket")
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
# Custom migrations
## Create new tables
Assignment.__table__.create(connection)
Location.__table__.create(connection)
## Create new columns
op.add_column("ticket", sa.Column("assignment_id", sa.Integer(), nullable=False))
op.add_column("ticket", sa.Column("location_id", sa.Integer(), nullable=False))
## Add existing assignments
assignment_names = [
name.strip()
for [name] in session.query(TicketHelper.assignment_name).distinct()
]
assignments = {name: Assignment(name=name) for name in assignment_names}
session.add_all(assignments.values())
## Add existing locations
location_names = [
name.strip() for [name] in session.query(TicketHelper.location_name).distinct()
]
locations = {name: Location(name=name) for name in location_names}
session.add_all(locations.values())
## Set assignment, location ID based on name
for ticket in session.query(TicketHelper):
ticket.assignment = assignments[ticket.assignment_name]
ticket.location = locations[ticket.location_name]
session.commit()
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column(
"ticket",
"question",
existing_type=mysql.VARCHAR(collation="utf8mb4_general_ci", length=255),
nullable=False,
)
op.create_index(
op.f("ix_ticket_assignment_id"), "ticket", ["assignment_id"], unique=False
)
op.create_index(
op.f("ix_ticket_location_id"), "ticket", ["location_id"], unique=False
)
op.create_foreign_key(
"fk_ticket_assignment_id", "ticket", "assignment", ["assignment_id"], ["id"]
)
op.create_foreign_key(
"fk_ticket_location_id", "ticket", "location", ["location_id"], ["id"]
)
op.drop_column("ticket", "location")
op.drop_column("ticket", "assignment")
# ### end Alembic commands ###
def downgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"ticket",
sa.Column(
"assignment",
mysql.VARCHAR(collation="utf8mb4_general_ci", length=255),
nullable=False,
),
)
op.add_column(
"ticket",
sa.Column(
"location",
mysql.VARCHAR(collation="utf8mb4_general_ci", length=255),
nullable=False,
),
)
op.drop_constraint("fk_ticket_location_id", "ticket", type_="foreignkey")
op.drop_constraint("fk_ticket_assignment_id", "ticket", type_="foreignkey")
op.drop_index(op.f("ix_ticket_location_id"), table_name="ticket")
op.drop_index(op.f("ix_ticket_assignment_id"), table_name="ticket")
op.alter_column(
"ticket",
"question",
existing_type=mysql.VARCHAR(collation="utf8mb4_general_ci", length=255),
nullable=True,
)
# Custom migrations
## Populate assignment and location columns
for ticket in session.query(TicketHelper):
ticket.assignment_name = ticket.assignment.name
ticket.location_name = ticket.location.name
session.commit()
op.drop_column("ticket", "location_id")
op.drop_column("ticket", "assignment_id")
op.drop_table("location")
op.drop_table("assignment")
# ### end Alembic commands ###
<file_sep>/oh/oh_queue/static/js/components/confirmed_appointment.js
function ConfirmedAppointment({ mySignups, locations, assignments }) {
let body;
if (mySignups.length === 0) {
body = <p>Choose a slot to schedule a visit to office hours! </p>;
} else {
const innerBody = mySignups.map(({ appointment, signup }) => (
<ConfirmedAppointmentCard
appointment={appointment}
assignments={assignments}
signup={signup}
locations={locations}
/>
));
body = <div className="confirmed-appointment-container">{innerBody}</div>;
}
return (
<div className="jumbotron">
<div className="container">
<h2> Your Appointments </h2>
{body}
</div>
</div>
);
}
<file_sep>/oh/oh_queue/static/js/components/confirmed_appointment_card.js
function ConfirmedAppointmentCard({
appointment,
signup,
locations,
assignments,
}) {
const assignmentName =
signup.assignment_id && assignments[signup.assignment_id].name;
const questionName = signup.question ? " Question " + signup.question : "";
const questionBlock = assignmentName && (
<React.Fragment>
have asked for help with <b>{assignmentName + questionName}</b>, and
</React.Fragment>
);
const helperBlock = appointment.helper && (
<React.Fragment>
by <b>{appointment.helper.name}</b>,{" "}
</React.Fragment>
);
const content = (
<React.Fragment>
Your appointment is at <b>{locations[appointment.location_id].name}</b>.
You {questionBlock} will be helped {helperBlock} in a group of{" "}
<b>{Math.max(appointment.capacity, appointment.signups.length)}</b>.
</React.Fragment>
);
const [modalOpen, setModalOpen] = React.useState(false);
const history = ReactRouterDOM.useHistory();
const handleClick = (e) => {
e.preventDefault();
if (appointment.status === "active") {
history.push("/appointments/" + appointment.id);
} else {
setModalOpen(true);
}
};
const style = {};
if (appointment.status === "active") {
style.borderLeft = "5px solid #337ab7";
}
return (
<React.Fragment>
<div className="panel panel-default" onClick={handleClick} style={style}>
<ul className="list-group">
<a href="#" className="list-group-item">
{appointment.status === "active" && (
<span className="badge badge-primary">Click To Enter</span>
)}
<h4 className="list-group-item-heading appointment-card-heading">
{formatAppointmentDate(appointment)}
</h4>
<div className="appointment-card-subheading">
{formatAppointmentDuration(appointment)}
</div>
{content}
</a>
</ul>
</div>
<AppointmentOverlay
assignments={assignments}
appointment={appointment.id}
signup={signup}
isOpen={modalOpen}
onSubmit={() => setModalOpen(false)}
/>
</React.Fragment>
);
}
<file_sep>/redirect/index.md
```{include} README.md
```
## Code Documentation
All of the code for redirection is contained in `main.py`. It tries to retrieve
from a set LOOKUP dictionary and if it doesn't exist tries to directly get a url
from the inst.eecs website. `catch_all()` recieves a path and calls `lookup()`
to get the link. `lookup()` creates the redirect link.
```{eval-rst}
.. automodule:: redirect.main
:members:
```
<file_sep>/oh/oh_queue/static/js/components/description_box.js
function DescriptionBox({
editable,
locked,
state,
ticket,
prompt,
placeholder,
description,
onChange,
onSubmit,
}) {
let staff = isStaff(state);
if ((!editable && staff) || locked) {
return (
<p className="ticket-view-desc">
{ticket.description ? ticket.description : <i>No description</i>}
</p>
);
} else {
return (
<div>
<h4>{prompt}</h4>
<textarea
className="description-box"
value={description}
onChange={(e) => onChange(e.target.value)}
rows="5"
placeholder={placeholder}
/>
{description !== ticket.description ? (
<button
onClick={onSubmit}
className="description-button btn btn-default btn-lg btn-block"
>
{" "}
Save Description{" "}
</button>
) : null}
</div>
);
}
}
<file_sep>/examtool/examtool/api/convert.py
import json
import re
import os
import pypandoc
from tqdm import tqdm
from multiprocessing.pool import ThreadPool
from os.path import dirname
from examtool.api.utils import list_to_dict, IDFactory
VERSION = 2 # increment when backward-incompatible changes are made
def html_convert(x):
return pypandoc.convert_text(x, "html5", "md", ["--mathjax"])
def tex_convert(x):
return pypandoc.convert_text(x, "latex", "md")
class LineBuffer:
def __init__(self, text, *, src_map=None):
self.lines = text.strip().split("\n")
self.src_map = src_map
self.i = 0
def _pop(self) -> str:
if self.i == len(self.lines):
raise SyntaxError("File terminated unexpectedly")
self.i += 1
return self.lines[self.i - 1]
def pop(self) -> str:
line = self._pop()
stripped = line.rstrip()
while stripped.endswith("\\"):
if stripped.endswith(r"\\"):
line = stripped[:-1]
break
line = stripped[:-1] + "\n" + self._pop()
stripped = line.rstrip()
return line
def empty(self):
return self.i == len(self.lines)
def location(self):
if self.src_map is None:
return [self.i, "<string>"]
else:
return self.src_map[self.i - 1]
def parse_directive(line):
if not any(
line.startswith(f"# {x} ")
for x in ["BEGIN", "END", "INPUT", "CONFIG", "DEFINE", "IMPORT"]
):
return None, None, None
tokens = line.split(" ", 3)
return (
tokens[1],
tokens[2] if len(tokens) > 2 else "",
tokens[3] if len(tokens) > 3 else "",
)
def process_title(line):
tokens = line.split(" ")
point_sec = tokens[-1]
has_fixed = tokens and tokens[0] == "FIXED"
if has_fixed:
tokens = tokens[1:]
line = " ".join(tokens)
if not point_sec or point_sec[0] != "[" or point_sec[-1] != "]":
return line.strip(), has_fixed, None
try:
return " ".join(tokens[:-1]).strip(), has_fixed, float(point_sec[1:-1])
except ValueError:
return line.strip(), has_fixed, None
class ToParse:
def __init__(self, text, type):
self.text = text
self.type = type
self.html = None
self.tex = None
def parse(text):
return {"text": text, "html": ToParse(text, "html"), "tex": ToParse(text, "tex")}
def parse_define(directive, rest, defines):
defines["substitutions"] = defines.get("substitutions", {})
defines["substitutions_match"] = defines.get("substitutions_match", [])
defines["substitution_groups"] = defines.get("substitution_groups", [])
defines["substitution_ranges"] = defines.get("substitution_ranges", {})
if directive == "MATCH":
regex = r"\[(.*)\]\s+\[(.*)\]"
matches = re.match(regex, rest)
if not matches or len(matches.groups()) != 2:
raise SyntaxError("Invalid declaration of DEFINE MATCH")
directives, replacements = matches.groups()
directives_list = directives.split(" ")
replacements_list = replacements.split(" ")
if len(replacements_list) < len(directives_list):
raise SyntaxError(
"DEFINE MATCH must have at least as many replacements as it has directives"
)
defines["substitutions_match"].append(
{"directives": directives_list, "replacements": replacements_list}
)
elif directive == "GROUP":
regex = r"(\([^()]+\)\s*)+"
matches = re.match(regex, rest)
if not matches:
raise SyntaxError("Invalid declaration of DEFINE GROUP")
blocks = re.findall(r"\([^()]+\)", rest)
if len(blocks) <= 1:
raise SyntaxError("DEFINE GROUP is incomplete")
for i, block in enumerate(blocks):
blocks[i] = tuple(block[1:-1].split(" "))
if not all(len(block) == len(blocks[0]) for block in blocks):
raise SyntaxError("DEFINE GROUP blocks must all be of the same length")
defines["substitution_groups"].append(
{
"directives": blocks[0],
"replacements": list_to_dict(
[list_to_dict(block) for block in blocks[1:]]
),
}
)
elif directive == "RANGE":
blocks = rest.split(" ")
if len(blocks) != 3:
raise SyntaxError("DEFINE RANGE takes exactly three arguments")
directive, low, high = blocks
try:
low = int(low)
high = int(high)
except ValueError:
raise SyntaxError("DEFINE RANGE bounds must be integers")
defines["substitution_ranges"][directive] = [low, high]
else:
defines["substitutions"][directive] = rest.split(" ")
def parse_input_lines(lines):
if not lines:
raise SyntaxError("No INPUT directives found in QUESTION")
_, directive, rest = parse_directive(lines[0])
correct_options = []
if directive == "OPTION" or directive == "SELECT":
options = []
existing_options = set()
for line in lines:
_, other_directive, rest = parse_directive(line)
if other_directive != directive:
raise SyntaxError("Multiple INPUT types found in a single QUESTION")
fixed = "FIXED "
is_fixed = False
if rest.startswith(fixed):
is_fixed = True
rest = rest[len(fixed) :]
correct = "CORRECT "
is_correct = False
if rest.startswith(correct):
is_correct = True
rest = rest[len(correct) :]
if is_correct:
correct_options.append(rest)
if rest in existing_options:
raise SyntaxError("Cannot have duplicate INPUT options")
existing_options.add(rest)
options.append(parse(rest))
options[-1]["fixed"] = is_fixed
return (
"multiple_choice" if directive == "OPTION" else "select_all",
options,
correct_options,
)
elif directive in (
"SHORT_ANSWER",
"SHORT_CODE_ANSWER",
"LONG_ANSWER",
"LONG_CODE_ANSWER",
):
if len(lines) > 1:
raise SyntaxError(
"Multiple INPUT directives found for a {}".format(directive)
)
if directive == "SHORT_ANSWER":
return "short_answer", rest.strip(), None
elif directive == "SHORT_CODE_ANSWER":
return "short_code_answer", rest.strip(), None
try:
num_lines = int(rest or "10")
except TypeError:
raise SyntaxError("Expected integer as option for {}".format(directive))
if directive == "LONG_ANSWER":
return "long_answer", num_lines, None
elif directive == "LONG_CODE_ANSWER":
return "long_code_answer", num_lines, None
raise SyntaxError("Unrecognized directive: {}".format(directive))
def consume_rest_of_solution(buff, end):
out = []
while True:
line = buff.pop()
mode, directive, rest = parse_directive(line)
if mode is None:
out.append(line)
elif mode == "END":
if directive == end:
return parse("\n".join(out))
else:
raise SyntaxError(
f"Unexpected END ({directive if directive else line}) in SOLUTION"
)
else:
raise SyntaxError(
f"Unexpected directive ({mode if mode else line}) in SOLUTION"
)
def consume_rest_of_question(buff, id_factory):
contents = []
input_lines = []
defines = {}
solution = None
solution_note = None
config = {}
template = []
while True:
line = buff.pop()
mode, directive, rest = parse_directive(line)
if mode is None:
if input_lines and line.strip():
template.append(line)
elif not input_lines:
contents.append(line)
elif mode == "INPUT":
input_lines.append(line)
elif mode == "BEGIN":
if directive == "SOLUTION":
solution = consume_rest_of_solution(buff, directive)
elif directive == "NOTE":
solution_note = consume_rest_of_solution(buff, directive)
else:
raise SyntaxError(
f"Unexpected BEGIN ({directive if directive else line}) in QUESTION"
)
elif mode == "END":
if directive == "QUESTION":
(
question_type,
options,
option_solutions,
) = parse_input_lines(input_lines)
if option_solutions and solution:
raise SyntaxError("Received multiple solutions.")
template = "\n".join(template)
if template:
if question_type in ("long_answer", "long_code_answer"):
# OK
pass
elif question_type in ("short_answer", "short_code_answer"):
if "\n" in template:
raise SyntaxError(
"Cannot have newlines in template for INPUT SHORT ANSWER"
)
else:
raise SyntaxError(
f"Cannot have a template for question type {question_type}"
)
return {
"id": id_factory.get_id(config.get("ID")),
"type": question_type,
"solution": {
"solution": solution,
"options": option_solutions,
"note": solution_note,
},
**parse("\n".join(contents)),
"config": config,
"options": options,
"template": template,
**defines,
}
else:
raise SyntaxError(
f"Unexpected END {directive if directive else line} in QUESTION"
)
elif mode == "DEFINE":
parse_define(directive, rest, defines)
elif mode == "CONFIG":
config[directive] = rest
else:
raise SyntaxError(
f"Unexpected directive ({mode if mode else line}) in QUESTION"
)
def consume_rest_of_group(buff, end, id_factory):
group_contents = []
elements = []
started_elements = False
defines = {}
pick_some = None
scramble = False
inline = False
while True:
line = buff.pop()
mode, directive, rest = parse_directive(line)
if mode is None:
if started_elements and line.strip():
raise SyntaxError("Unexpected text in GROUP after QUESTIONs started")
elif not started_elements:
group_contents.append(line)
elif mode == "BEGIN" and directive == "QUESTION":
started_elements = True
title, is_fixed, points = process_title(rest)
if title:
raise SyntaxError(
"Unexpected arguments passed in BEGIN QUESTION directive"
)
question = consume_rest_of_question(buff, id_factory)
question["points"] = points
question["fixed"] = is_fixed
elements.append(question)
elif mode == "BEGIN" and directive == "GROUP":
started_elements = True
title, is_fixed, points = process_title(rest)
group = consume_rest_of_group(buff, "GROUP", id_factory)
if (title or points) and group["inline"]:
raise SyntaxError("Cannot create an inline group with title or points")
group["name"] = title
group["points"] = points
group["fixed"] = is_fixed
elements.append(group)
elif mode == "END" and directive == end:
return {
"type": "group",
**parse("\n".join(group_contents)),
"elements": elements,
**defines,
"pick_some": pick_some,
"scramble": scramble,
"inline": inline,
}
elif mode == "DEFINE":
parse_define(directive, rest, defines)
elif mode == "CONFIG":
if directive == "PICK":
if pick_some:
raise SyntaxError("Multiple CONFIG PICK found in GROUP")
try:
pick_some = int(rest)
except ValueError:
raise SyntaxError("Invalid argument passed to CONFIG PICK")
elif directive == "SCRAMBLE":
scramble = True
elif directive == "INLINE":
inline = True
else:
raise SyntaxError(
f"Unexpected CONFIG directive ({directive if directive else line}) in GROUP"
)
else:
raise SyntaxError(f"Unexpected directive ({line}) in GROUP")
def _convert(text, *, path=None, allow_random_ids=True):
groups = []
public = None
config = {}
defines = {}
watermark = None
if path is not None:
buff = load_imports(text, path)
else:
buff = LineBuffer(text)
id_factory = IDFactory(allow_random_ids=allow_random_ids)
try:
while not buff.empty():
line = buff.pop()
if not line.strip():
continue
mode, directive, rest = parse_directive(line)
if mode == "CONFIG":
if directive in [
"SCRAMBLE_GROUPS",
"SCRAMBLE_QUESTIONS",
"SCRAMBLE_OPTIONS",
]:
config[directive.lower()] = [int(x) for x in rest.split(" ") if x]
elif directive == "WATERMARK":
watermark = dict(brightness=int(rest))
else:
raise SyntaxError(
"Unexpected CONFIG directive {}".format(directive)
)
elif mode == "BEGIN" and directive in ["GROUP", "PUBLIC"]:
title, is_fixed, points = process_title(rest)
group = consume_rest_of_group(buff, directive, id_factory)
group["name"] = title
group["points"] = points
group["fixed"] = is_fixed
if (title.strip() or points) and group["inline"]:
raise SyntaxError(
"Cannot create an inline group with a title or points"
)
if directive == "PUBLIC":
if public:
raise SyntaxError("Only one PUBLIC block is allowed")
if is_fixed:
raise SyntaxError("PUBLIC blocks are already FIXED")
public = group
else:
groups.append(group)
elif mode == "DEFINE":
parse_define(directive, rest, defines)
else:
raise SyntaxError(f"Unexpected directive: {line}")
except SyntaxError as e:
line_num, file = buff.location()
raise SyntaxError(
"Parse stopped on {}:{} with error: {}".format(file, line_num, e)
)
return {
"public": public,
"groups": groups,
"config": config,
**defines,
"watermark": watermark,
"version": VERSION,
}
def pandoc(target, *, draft=False, num_threads):
to_parse = []
def explore(pos):
if isinstance(pos, ToParse):
to_parse.append(pos)
elif isinstance(pos, dict):
for child in pos.values():
explore(child)
elif isinstance(pos, list):
for child in pos:
explore(child)
explore(target)
pandoc_delimiter = """\n\nDELIMITER\n\n"""
if draft:
def transpile_target(t):
return pandoc_delimiter.join(x.text for x in to_parse if x.type == t)
html = html_convert(transpile_target("html")).split(
html_convert(pandoc_delimiter)
)
tex = tex_convert(transpile_target("tex")).split(tex_convert(pandoc_delimiter))
for x, h in zip(filter(lambda x: x.type == "html", to_parse), html):
x.html = h
for x, t in zip(filter(lambda x: x.type == "tex", to_parse), tex):
x.tex = t
else:
def pandoc_convert(x):
x.__dict__[x.type] = (
html_convert(x.text) if x.type == "html" else tex_convert(x.text)
)
with ThreadPool(num_threads) as p:
list(
tqdm(
p.imap_unordered(pandoc_convert, to_parse),
total=len(to_parse),
desc="Parts Processed",
unit="Part",
)
)
def pandoc_dump(obj):
assert isinstance(obj, ToParse)
return obj.__dict__[obj.type]
return json.dumps(target, default=pandoc_dump)
def convert(text, *, path=None, draft=False, allow_random_ids=True, num_threads):
return json.loads(
convert_str(
text,
path=path,
draft=draft,
allow_random_ids=allow_random_ids,
num_threads=num_threads,
)
)
def convert_str(
text,
*,
path=None,
draft=False,
allow_random_ids=True,
num_threads=16,
):
return pandoc(
_convert(text, path=path, allow_random_ids=allow_random_ids),
draft=draft,
num_threads=num_threads,
)
def import_file(filepath: str) -> str:
if not filepath:
raise SyntaxError("IMPORT must take in a filepath")
with open(filepath, "r") as f:
return f.read()
def load_imports(base_text: str, base_path: str):
lines = []
def _load(text: str, path: str):
for i, line in enumerate(text.split("\n")):
mode, directive, rest = parse_directive(line)
if mode == "IMPORT":
filepath = os.path.join(
dirname(path), " ".join([directive, rest]).rstrip()
)
try:
_load(import_file(filepath), filepath)
except FileNotFoundError:
raise SyntaxError(
f"Parse stopped on {path}:{i + 1}: Unable to import {filepath}"
)
else:
lines.append([i + 1, path, line])
_load(base_text, base_path)
line_strs = []
src_map = []
for line_num, path, line in lines:
line_strs.append(line)
src_map.append([line_num, path])
return LineBuffer("\n".join(line_strs), src_map=src_map)
<file_sep>/hosted/app.py
import os, sys
from dna import DNA
from flask import Flask
from functools import wraps
from common.rpc.hosted import (
add_domain,
delete,
list_apps,
new,
service_log,
container_log,
)
from common.rpc.secrets import only
from common.shell_utils import sh
from common.oauth_client import (
create_oauth_client,
is_staff,
login,
get_user,
)
from common.rpc.auth import is_admin
from common.rpc.slack import post_message
CERTBOT_ARGS = [
"--dns-google",
"--dns-google-propagation-seconds",
"180",
]
is_sphinx = "sphinx" in sys.argv[0]
app = Flask(__name__)
if not is_sphinx:
dna = DNA(
"hosted",
cb_args=CERTBOT_ARGS,
)
if not os.path.exists("data/saves"):
os.makedirs("data/saves")
sh("chmod", "666", f"{os.getcwd()}/dna.sock")
@list_apps.bind(app)
@only("buildserver")
def list_apps():
return {
service.name: {
"image": service.image,
"domains": [d.url for d in service.domains],
}
for service in dna.services
}
@new.bind(app)
@only("buildserver")
def new(img, name=None, env={}):
name = name if name else img.split("/")[-1]
[
_ for _ in dna.pull_image(img)
] # temporary fix until DNA supports pulling without streaming
if "ENV" not in env:
env["ENV"] = "prod"
if "PORT" not in env:
env["PORT"] = 8001
save = f"{os.getcwd()}/data/saves/{name}"
if not os.path.exists(save):
os.makedirs(save)
shared = f"{os.getcwd()}/data/shared"
if not os.path.exists(shared):
os.makedirs(shared)
volumes = {
save: {
"bind": "/save",
"mode": "rw",
},
shared: {
"bind": "/shared",
"mode": "ro",
},
}
dna.run_deploy(
name,
img,
"8001",
environment=env,
volumes=volumes,
hostname=name,
)
dna.add_domain(
name,
f"{name}.hosted.cs61a.org",
)
return dict(success=True)
@delete.bind(app)
@only("buildserver")
def delete(name):
dna.delete_service(name)
return dict(success=True)
@add_domain.bind(app)
@only(["buildserver", "sandbox"], allow_staging=True)
def add_domain(
name, domain, force_wildcard=False, force_provision=False, proxy_set_header={}
):
return dict(
success=dna.add_domain(
name, domain, force_wildcard, force_provision, proxy_set_header
)
)
@service_log.bind(app)
@only("logs")
def service_log():
logs = sh("journalctl", "-u", "dockerapi", "-n", "100", quiet=True).decode("utf-8")
return dict(success=True, logs=logs)
@container_log.bind(app)
@only("logs")
def container_log(name):
return dict(success=True, logs=dna.docker_logs(name))
def check_auth(func):
"""Takes in a function, and returns a wrapper of that function.
The wrapper will request user authentication (as staff) if needed.
Otherwise, it will execute the function as normal.
:param func: function to wrap
:type func: func
:return: wrapper function that requests authentication as needed
"""
@wraps(func)
def wrapped(*args, **kwargs):
if not (is_staff("cs61a") and is_admin(email=get_user()["email"])):
return login()
return func(*args, **kwargs)
return wrapped
if not is_sphinx:
create_oauth_client(app, "hosted-apps")
dna_api = dna.create_api_client(precheck=check_auth)
app.register_blueprint(dna_api, url_prefix="/dna")
dna_logs = dna.create_logs_client(precheck=check_auth)
app.register_blueprint(dna_logs, url_prefix="/logs")
# PR Proxy Setup
from dna.utils import Certbot
from dna.utils.nginx_utils import Server, Location
from common.rpc.hosted import create_pr_subdomain
proxy_cb = Certbot(CERTBOT_ARGS + ["-i", "nginx"])
pr_confs = f"{os.getcwd()}/data/pr_proxy"
if not is_sphinx:
if not os.path.exists(pr_confs):
os.makedirs(pr_confs)
if not os.path.exists(f"/etc/nginx/conf.d/hosted_pr_proxy.conf"):
with open(f"/etc/nginx/conf.d/hosted_pr_proxy.conf", "w") as f:
f.write(f"include {pr_confs}/*.conf;")
@create_pr_subdomain.bind(app)
@only("buildserver")
def create_pr_subdomain(app, pr_number, pr_host):
target_domain = f"{pr_number}.{app}.pr.cs61a.org"
conf_path = f"{pr_confs}/{target_domain}.conf"
expected_cert_name = f"*.{app}.pr.cs61a.org"
nginx_config = Server(
Location(
"/",
proxy_pass=f"https://{pr_host}/",
proxy_read_timeout="1800",
proxy_connect_timeout="1800",
proxy_send_timeout="1800",
send_timeout="1800",
proxy_set_header={
"Host": pr_host,
"X-Forwarded-For-Host": target_domain,
},
),
server_name=target_domain,
listen="80",
)
if not os.path.exists(conf_path):
with open(conf_path, "w") as f:
f.write(str(nginx_config))
sh("nginx", "-s", "reload")
cert = proxy_cb.cert_else_false(expected_cert_name, force_exact=True)
for _ in range(2):
if cert:
break
proxy_cb.run_bot(domains=[expected_cert_name], args=["certonly"])
cert = proxy_cb.cert_else_false(expected_cert_name, force_exact=True)
if not cert:
error = f"Hosted Apps failed to sign a certificate for {expected_cert_name}!"
post_message(message=error, channel="infra")
return dict(success=False, reason=error)
proxy_cb.attach_cert(cert, target_domain)
return dict(success=True)
if __name__ == "__main__":
app.run(host="0.0.0.0")
<file_sep>/hog-calc/README.md
# `hog-calc`
This contains methods used to compare strategies for Hog.
## Running Locally
Create a venv and install dependencies.
```bash
$ python3 -m venv env
$ env/bin/pip install -r requirements.txt
```
Run `env/bin/python main.py` to start the Flask server, then make a POST request
to `http://localhost:5000/api/compare_strategies` to start comparing strategies.
<file_sep>/oh/oh_queue/static/js/components/offline_indicator.js
function OfflineIndicator({ offline }) {
return (
<div className={`offline offline-${offline ? "down" : "up"}`}>
<div className="offline-content">
{offline
? "Connection lost. Reconnecting..."
: "Your computer is connected."}
</div>
</div>
);
}
<file_sep>/oh/oh_queue/models.py
import datetime
import enum
import pytz
from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class EnumType(db.TypeDecorator):
impl = db.String(255)
def __repr__(self):
"""Make alembic detect the right type"""
return "db.String(length=255)"
def __init__(self, enum_class):
super(EnumType, self).__init__(self)
self.enum_class = enum_class
def process_bind_param(self, enum_value, dialect):
return enum_value.name
def process_result_value(self, name, dialect):
return self.enum_class[name]
@property
def python_type(self):
return self.enum_class
class User(db.Model, UserMixin):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, default=db.func.now())
email = db.Column(db.String(255), nullable=False, index=True)
name = db.Column(db.String(255), nullable=False)
is_staff = db.Column(db.Boolean, default=False)
course = db.Column(db.String(255), nullable=False, index=True)
call_url = db.Column(db.String(255))
doc_url = db.Column(db.String(255))
heartbeat_time = db.Column(db.DateTime, default=db.func.now(), index=True)
@property
def short_name(self):
first_name = self.name.split()[0] if self.name.split() else ""
if "@" in first_name:
return first_name.rsplit("@")[0]
return first_name
class ConfigEntry(db.Model):
"""Represents persistent server-side configuration entries"""
__tablename__ = "config_entries"
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.String(255), nullable=False)
value = db.Column(db.Text(), nullable=False)
public = db.Column(db.Boolean, default=False)
course = db.Column(db.String(255), nullable=False, index=True)
class Assignment(db.Model):
"""Represents a ticket's assignment."""
__tablename__ = "assignment"
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, default=db.func.now())
name = db.Column(db.String(255), nullable=False)
visible = db.Column(db.Boolean, default=False)
course = db.Column(db.String(255), nullable=False, index=True)
class Location(db.Model):
"""Represents a ticket's location."""
__tablename__ = "location"
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, default=db.func.now())
name = db.Column(db.String(255), nullable=False)
online = db.Column(db.Boolean, nullable=False)
link = db.Column(db.String(255), nullable=False)
visible = db.Column(db.Boolean, default=False)
course = db.Column(db.String(255), nullable=False, index=True)
TicketStatus = enum.Enum(
"TicketStatus", "pending assigned resolved deleted juggled rerequested"
)
active_statuses = [
TicketStatus.pending,
TicketStatus.assigned,
TicketStatus.juggled,
TicketStatus.rerequested,
]
class Ticket(db.Model):
"""Represents an ticket in the queue. A student submits a ticket and receives
help from a staff member.
"""
__tablename__ = "ticket"
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, default=db.func.now(), index=True)
updated = db.Column(db.DateTime, onupdate=db.func.now())
status = db.Column(EnumType(TicketStatus), nullable=False, index=True)
sort_key = db.Column(db.DateTime, default=db.func.now(), index=True)
group = db.relationship("Group", back_populates="ticket", uselist=False)
rerequest_threshold = db.Column(
db.DateTime
) # time when student allowed to re-request help
hold_time = db.Column(db.DateTime) # time when student was put on hold
rerequest_time = db.Column(db.DateTime) # time when student re-requested help
user_id = db.Column(db.ForeignKey("user.id"), nullable=False, index=True)
helper_id = db.Column(db.ForeignKey("user.id"), index=True)
assignment_id = db.Column(
db.ForeignKey("assignment.id"), nullable=False, index=True
)
location_id = db.Column(db.ForeignKey("location.id"), nullable=False, index=True)
question = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
user = db.relationship(User, foreign_keys=[user_id])
helper = db.relationship(User, foreign_keys=[helper_id])
assignment = db.relationship(Assignment, foreign_keys=[assignment_id])
location = db.relationship(Location, foreign_keys=[location_id])
course = db.Column(db.String(255), nullable=False, index=True)
call_url = db.Column(db.String(255))
doc_url = db.Column(db.String(255))
@classmethod
def for_user(cls, user):
if user and user.is_authenticated:
from common.course_config import get_course
return cls.query.filter(
cls.user_id == user.id,
cls.course == get_course(),
cls.status.in_([TicketStatus.pending, TicketStatus.assigned]),
).one_or_none()
@classmethod
def by_status(cls, status=None):
"""Tickets in any of the states as status.
@param status: Iterable containing TicketStatus values
"""
if status is None:
status = [TicketStatus.pending, TicketStatus.assigned]
return cls.query.filter(cls.status.in_(status)).order_by(cls.created).all()
TicketEventType = enum.Enum(
"TicketEventType",
"create assign unassign resolve delete update juggle rerequest return_to hold_released message_sent shuffled",
)
class TicketEvent(db.Model):
"""Represents an event that changes a ticket during its lifecycle."""
__tablename__ = "ticket_event"
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=db.func.now())
event_type = db.Column(EnumType(TicketEventType), nullable=False)
ticket_id = db.Column(db.ForeignKey("ticket.id"), nullable=False)
user_id = db.Column(db.ForeignKey("user.id"), nullable=False)
course = db.Column(db.String(255), nullable=False, index=True)
ticket = db.relationship(Ticket)
user = db.relationship(User)
AppointmentStatus = enum.Enum("AppointmentStatus", "pending active resolved hidden")
class Appointment(db.Model):
"""Represents an appointment block."""
__tablename__ = "appointment"
id = db.Column(db.Integer, primary_key=True)
start_time = db.Column(db.DateTime, index=True, nullable=False)
duration = db.Column(db.Interval, nullable=False)
capacity = db.Column(db.Integer, nullable=False)
num_reminders_sent = db.Column(db.Integer, nullable=False, default=0)
description = db.Column(db.String(255), nullable=False, default="")
location_id = db.Column(db.ForeignKey("location.id"), nullable=False, index=True)
location = db.relationship(Location, foreign_keys=[location_id])
helper_id = db.Column(db.ForeignKey("user.id"), index=True)
helper = db.relationship(User, foreign_keys=[helper_id])
signups = db.relationship("AppointmentSignup", back_populates="appointment")
status = db.Column(EnumType(AppointmentStatus), nullable=False, index=True)
course = db.Column(db.String(255), nullable=False, index=True)
AttendanceStatus = enum.Enum("AttendanceStatus", "unknown present excused absent")
class AppointmentSignup(db.Model):
__tablename__ = "appointment_signup"
id = db.Column(db.Integer, primary_key=True)
appointment_id = db.Column(
db.ForeignKey("appointment.id"), nullable=False, index=True
)
appointment = db.relationship("Appointment", back_populates="signups")
user_id = db.Column(db.ForeignKey("user.id"), nullable=False, index=True)
user = db.relationship(User, foreign_keys=[user_id])
assignment_id = db.Column(db.ForeignKey("assignment.id"), index=True)
assignment = db.relationship(Assignment, foreign_keys=[assignment_id])
question = db.Column(db.String(255), nullable=False)
description = db.Column(db.Text)
attendance_status = db.Column(
EnumType(AttendanceStatus), nullable=False, default=AttendanceStatus.unknown
)
course = db.Column(db.String(255), nullable=False, index=True)
GroupStatus = enum.Enum("GroupStatus", "active resolved")
class Group(db.Model):
__tablename__ = "group"
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, default=db.func.now(), index=True)
question = db.Column(db.String(255), nullable=False)
description = db.Column(db.String(255), nullable=False, default="")
assignment_id = db.Column(db.ForeignKey("assignment.id"), index=True)
assignment = db.relationship(Assignment, foreign_keys=[assignment_id])
location_id = db.Column(db.ForeignKey("location.id"), nullable=False, index=True)
location = db.relationship(Location, foreign_keys=[location_id])
ticket_id = db.Column(db.ForeignKey("ticket.id"), nullable=True, index=True)
ticket = db.relationship(Ticket, back_populates="group", foreign_keys=[ticket_id])
attendees = db.relationship(
"GroupAttendance", back_populates="group", lazy="joined"
)
group_status = db.Column(
EnumType(GroupStatus), nullable=False, default=GroupStatus.active
)
call_url = db.Column(db.String(255))
doc_url = db.Column(db.String(255))
course = db.Column(db.String(255), nullable=False, index=True)
GroupAttendanceStatus = enum.Enum("GroupAttendanceStatus", "present gone")
class GroupAttendance(db.Model):
__tablename__ = "group_attendance"
id = db.Column(db.Integer, primary_key=True)
group_id = db.Column(db.ForeignKey("group.id"), nullable=False, index=True)
group = db.relationship("Group", back_populates="attendees")
user_id = db.Column(db.ForeignKey("user.id"), nullable=False, index=True)
user = db.relationship(User, foreign_keys=[user_id], lazy="joined")
group_attendance_status = db.Column(
EnumType(GroupAttendanceStatus),
nullable=False,
default=GroupAttendanceStatus.present,
)
course = db.Column(db.String(255), nullable=False, index=True)
class ChatMessage(db.Model):
__tablename__ = "chat_message"
id = db.Column(db.Integer, primary_key=True)
created = db.Column(db.DateTime, default=db.func.now())
body = db.Column(db.String(255), nullable=False, default="")
user_id = db.Column(db.ForeignKey("user.id"), nullable=False, index=True)
user = db.relationship(User, foreign_keys=[user_id])
ticket_id = db.Column(db.ForeignKey("ticket.id"), nullable=True, index=True)
ticket = db.relationship("Ticket", backref=db.backref("messages", lazy="joined"))
appointment_id = db.Column(
db.ForeignKey("appointment.id"), nullable=True, index=True
)
appointment = db.relationship(
"Appointment", backref=db.backref("messages", lazy="joined")
)
group_id = db.Column(db.ForeignKey("group.id"), nullable=True, index=True)
group = db.relationship("Group", backref=db.backref("messages", lazy="joined"))
course = db.Column(db.String(255), nullable=False, index=True)
class CourseNotificationState(db.Model):
__tablename__ = "notification_state"
id = db.Column(db.Integer, primary_key=True)
last_queue_ping = db.Column(db.DateTime, nullable=False)
last_appointment_notif = db.Column(db.DateTime, nullable=False)
domain = db.Column(db.String(255), nullable=False)
course = db.Column(db.String(255), nullable=False, index=True)
def get_current_time():
return (
pytz.utc.localize(datetime.datetime.utcnow())
.astimezone(pytz.timezone("America/Los_Angeles"))
.replace(tzinfo=None)
)
<file_sep>/auth/google_client.py
import json
from flask import request, redirect
from auth_utils import key_secure, course_oauth_secure
from common.db import connect_db
from common.html import html
from google_api import load_document, load_sheet, dump_sheet
from common.rpc.auth import read_document, read_spreadsheet, write_spreadsheet
def init_db():
with connect_db() as db:
db(
"CREATE TABLE IF NOT EXISTS auth_json (email varchar(256), data LONGBLOB, course varchar(128))"
)
init_db()
def create_google_client(app):
def google_help(course):
with connect_db() as db:
email = db(
"SELECT email FROM auth_json WHERE course=(%s)", [course]
).fetchone()
email = email[0] if email else ""
return f"""
<h3> Google Service Account </h3>
Email address: <a href="mailto:{email}">{email}</a>
<p>
Share relevant Google Documents / Sheets with the above email account.
<p>
To configure, go to <a href="/google/{course}/config">Google Config</a>.
"""
app.help_info.add(google_help)
@read_document.bind(app)
@key_secure
def handle_read_document(course, url=None, doc_id=None):
return load_document(url=url, doc_id=doc_id, course=course)
@read_spreadsheet.bind(app)
@key_secure
def handle_read_spreadsheet(course, sheet_name, url=None, doc_id=None):
return load_sheet(url=url, doc_id=doc_id, sheet_name=sheet_name, course=course)
@write_spreadsheet.bind(app)
@key_secure
def handle_write_spreadsheet(course, sheet_name, content, url=None, doc_id=None):
return dump_sheet(
url=url,
doc_id=doc_id,
sheet_name=sheet_name,
content=content,
course=course,
)
@app.route("/google/<course>/config", methods=["GET"])
@course_oauth_secure()
def google_config(course):
return html(
f"""
Upload Google service worker JSON. This may break existing Google integrations!
<form action="/google/{course}/set_auth_json" method="post" enctype="multipart/form-data">
<input name="data" type="file">
<input type="submit">
</form>
"""
)
@app.route("/google/<course>/set_auth_json", methods=["POST"])
@course_oauth_secure()
def set_auth_json(course):
f = request.files["data"]
f.seek(0)
data = f.read().decode("utf-8")
if not data.strip():
return "Upload failed, file is blank", 403
parsed = json.loads(data)
email = parsed["client_email"]
with connect_db() as db:
db("DELETE FROM auth_json WHERE course=(%s)", [course])
db("INSERT INTO auth_json VALUES (%s, %s, %s)", [email, data, course])
return redirect("/")
<file_sep>/auth/google_api.py
import json
import re
from io import BytesIO
from google.oauth2 import service_account
import googleapiclient.discovery
from googleapiclient.http import MediaIoBaseDownload
from common.db import connect_db
SCOPES = ["https://www.googleapis.com/auth/drive"]
SERVICE_ACCOUNT_FILE = "google-auth.json"
def get_doc_id(url):
fmt = re.compile(r"/d/(.*)/")
doc_id = fmt.search(url).group(1)
return doc_id
def get_credentials(course):
with connect_db() as db:
data = json.loads(
db("SELECT data FROM auth_json WHERE course = (%s)", [course]).fetchone()[0]
)
return service_account.Credentials.from_service_account_info(data, scopes=SCOPES)
def load_document(*, url=None, doc_id=None, course):
doc_id = doc_id or get_doc_id(url)
service = googleapiclient.discovery.build(
"drive", "v3", credentials=get_credentials(course)
)
request = service.files().export_media(fileId=doc_id, mimeType="text/plain")
file = BytesIO()
downloader = MediaIoBaseDownload(file, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print(status, "Download {:d}%.".format(int(status.progress() * 100)))
return file.getvalue().decode("utf-8")
def load_sheet(*, url=None, doc_id=None, sheet_name, course):
service = googleapiclient.discovery.build(
"sheets", "v4", credentials=get_credentials(course)
)
doc_id = doc_id or get_doc_id(url)
result = (
service.spreadsheets()
.values()
.get(spreadsheetId=doc_id, range=sheet_name)
.execute()
)
return result["values"]
def dump_sheet(*, url=None, doc_id=None, sheet_name, course, content):
service = googleapiclient.discovery.build(
"sheets", "v4", credentials=get_credentials(course)
)
doc_id = doc_id or get_doc_id(url)
result = (
service.spreadsheets()
.values()
.update(
spreadsheetId=doc_id,
range=sheet_name,
valueInputOption="USER_ENTERED",
body=dict(range=sheet_name, values=content),
)
.execute()
)
return {"success": True}
| ae72e1c3469c6a372037c25d2f8e40710d12d20b | [
"reStructuredText",
"JavaScript",
"Markdown",
"Makefile",
"Python",
"Text",
"C",
"Dockerfile",
"Shell"
] | 443 | JavaScript | akshitdewan/cs61a-apps | 155f2afe98b238fb4b1c4ca1c79610ec55e826e6 | fb14b53d7823c4cd23a2283085b12746aa7fc43c |
refs/heads/master | <repo_name>lytedev/euler_c<file_sep>/src/3/main.c
#include <stdio.h>
#include <stdint.h>
int
main() {
uint64_t
result = 0;
// TODO: Code
printf("%lu\n", result);
return 0;
}
<file_sep>/readme.md
# Project Euler in C
*Note*: This project is always in heavy development and is for learning
purposes. Please don't expect anything to work. Feel free to criticize and
share your opinions.
So I've been wanting to pickup more C. Especially since it's so widely used in
a lot of the projects I'm using on my Linux workstation setup. I figured a good
way to do this was to actually finish Project Euler and see what I can do!
I might include some other random C projects here as well as I'm learning along
with any notes I need for myself.
Also, this `Makefile` is super handy, so I want to keep that around as well.
<3
<file_sep>/src/1/main.c
#include <stdio.h>
#include <stdint.h>
int
main() {
uint64_t sum = 0;
for (uint64_t i = 0; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
printf("%lu\n", sum);
return 0;
}
<file_sep>/Makefile
CC=clang
CFLAGS=-std=c11 -O2 -Os -Wno-missing-field-initializers -Wall -Wextra -Wpedantic -Werror -Wshadow -march=native
LIBS=
BIN_DIR=bin
SRC=$(wildcard src/*/*.c)
BIN=$(patsubst src/%/,$(BIN_DIR)/%,$(dir $(SRC)))
all: $(BIN)
$(BIN):
@mkdir -p $(BIN_DIR)
@echo $@
$(CC) -o $@ $(wildcard $(patsubst $(BIN_DIR)/%,src/%/*.c,$@)) $(CFLAGS) $(LIBS)
cfiles: $(SRC)
@echo $^
bin:
@echo $(BIN)
clean: $(BIN_DIR)
rm -rf $(BIN_DIR)
rebuild : clean all
<file_sep>/src/2/main.c
#include <stdio.h>
#include <stdint.h>
int
main() {
const uint64_t
max = 50;
uint64_t
i,
result = 0;
uint64_t fibs [max];
fibs[0] = 1;
fibs[1] = 2;
// manually add fibs[1] since it's even
result += fibs[1];
for (i = 2; i < max; i++) {
fibs[i] = fibs[i - 1] + fibs[i - 2];
if (fibs[i] > 4000000) break;
if (fibs[i] % 2 == 0) result += fibs[i];
}
printf("%lu\n", result);
return 0;
}
| 2f3b785c1e4e340a9a0965473a804df92b79fae8 | [
"Markdown",
"C",
"Makefile"
] | 5 | C | lytedev/euler_c | 5cb6b9618a2c53ee2cb7f4ea85cafb16d0b6a4aa | e773a30492fc909deb1fe67f9cf674a7cdc4a1f5 |
refs/heads/master | <file_sep>#R code for simulating unbalanced scenario (Scenario1 in paper), which has 4 traits with case sample size of 100 and 1 trait with case sample size of 500.
library(bindata)
library(MultiPhen)
n=10000
maf=0.05
#User can specify different beta0 to control case sample size
beta0=c(-4.6,-4.6,-4.6,-4.6,-3)
x<-sample(c(0,1,2),n,replace=T,prob=c((1-maf)*(1-maf),2*maf*(1-maf),maf*maf))
x<-as.matrix(x)
#User can specify different beta to control the effect sizes of the SNPs
beta=c(0.3,0.3,0.3,0.3,0.3)
#User can input a phenotype matrix which they wish to produce the correlation matrix for simulated traits. In this example, d file contains 5 traits as columns and individuals as rows (with a header and no rowname). Here I'm posting an example of the correlation matrix (b_cor) among 5 traits that described in the manuscript.
#d<-read.table("random_select_5_trait_from_ukb",header=T)
#b_cor<-cor(d)
#b_cor
# F322 F432 I208 I258 I429
#F322 1.0000000000 0.0415276512 0.0007543885 0.001951613 -0.001077797
#F432 0.0415276512 1.0000000000 0.0008421039 0.005441721 0.002168689
#I208 0.0007543885 0.0008421039 1.0000000000 0.098728472 0.003179557
#I258 0.0019516132 0.0054417214 0.0987284719 1.000000000 0.029784037
#I429 -0.0010777969 0.0021686888 0.0031795574 0.029784037 1.000000000
b_cor<-matrix(c(1.0000000000,0.0415276512,0.0007543885,0.001951613,-0.001077797, 0.0415276512, 1.0000000000, 0.0008421039, 0.005441721, 0.002168689, 0.0007543885, 0.0008421039, 1.0000000000, 0.098728472, 0.003179557, 0.0019516132, 0.0054417214, 0.0987284719, 1.000000000, 0.029784037, -0.0010777969, 0.0021686888, 0.0031795574, 0.029784037, 1.000000000),nrow=5,ncol=5,byrow=TRUE)
prob<-matrix(nrow=10000, ncol=5)
prob[,1]<-exp(beta0[1]+x %*% t(beta[1]))/(1+exp(beta0[1]+x %*% t(beta[1])))
prob[,2]<-exp(beta0[2]+x %*% t(beta[2]))/(1+exp(beta0[2]+x %*% t(beta[2])))
prob[,3]<-exp(beta0[3]+x %*% t(beta[3]))/(1+exp(beta0[3]+x %*% t(beta[3])))
prob[,4]<-exp(beta0[4]+x %*% t(beta[4]))/(1+exp(beta0[4]+x %*% t(beta[4])))
prob[,5]<-exp(beta0[5]+x %*% t(beta[5]))/(1+exp(beta0[5]+x %*% t(beta[5])))
y<-t(apply(prob, 1, function(m) rmvbin(1, margprob=m, bincorr=b_cor)))
colnames(y) <-c("Trait_1","Trait_2", "Trait_3", "Trait_4", "Trait_5")
logistic.out1 <- glm(y[,1] ~ x[,1],family=binomial)
tmp1 <- summary(logistic.out1)[[12]][2,]
logistic.out2 <- glm(y[,2] ~ x[,1],family=binomial)
tmp2 <- summary(logistic.out2)[[12]][2,]
logistic.out3 <- glm(y[,3] ~ x[,1],family=binomial)
tmp3 <- summary(logistic.out3)[[12]][2,]
logistic.out4 <- glm(y[,4] ~ x[,1],family=binomial)
tmp4 <- summary(logistic.out4)[[12]][2,]
logistic.out5 <- glm(y[,5] ~ x[,1],family=binomial)
tmp5 <- summary(logistic.out5)[[12]][2,]
tmp<-cbind(tmp1,tmp2,tmp3,tmp4,tmp5)
tmp_t<-t(tmp)
write.table(tmp_t,file="run1.unbalanced.logistic.output",quote=F,row.names=T,col.names=T,sep='\t')
y<-as.matrix(y)
rownames(y)<-seq(1:10000)
rownames(x)<-seq(1:10000)
mPhen_out <- mPhen(x[,1, drop=FALSE], y, phenotypes = all, resids = NULL, covariates=NULL, strats = NULL,opts = mPhen.options(c("regression","pheno.input")))
mPhen_jointp <- mPhen_out$Results[,,,2][6]
write.table(mPhen_jointp, file="run1.unbalanced.multiphen.output", col.names=T, row.names=T, sep="\t",quote=F)
<file_sep># Multivariate Simulation
This repository has the example R code for simulating balanced and unbalanced case control sample sizes for testing univariate and multivariate analyses. The total sample size is 10,000 and the balance/imbalance describes the property of case sample size. The code is flexiable in simulating other sample sizes by changing the parameters.
Reference:
(Accepted) X.Zhang, R.Li, M.D.Ritchie. Statistical Impact of Sample Size and Imbalance on Multivariate Analysis in silico and A Case Study in the UK Biobank. AMIA Annu Symp Proc. 2020.
| 5f5ab6063f0ab2f9183ca86cffc24e0195c8a95d | [
"Markdown",
"R"
] | 2 | R | blairzhang126/Multivariate-Sim | 554f42d3a35205ce4545d198cf16e48917aec130 | 98950d6c5fc967679b49cde5b60adb459402dd99 |
refs/heads/master | <file_sep>package com.vicky.apps.rockpaperscissor.ui.view
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.vicky.apps.gamecore.GameEngineCore
import com.vicky.apps.gamecore.GameType
import com.vicky.apps.gamecore.Result
import com.vicky.apps.gamecore.ResultCallback
import com.vicky.apps.rockpaperscissor.base.AppConstants
import com.vicky.apps.rockpaperscissor.base.BaseActivity
import com.vicky.apps.rockpaperscissor.common.ViewModelProviderFactory
import com.vicky.apps.rockpaperscissor.ui.adapter.DataAdapter
import com.vicky.apps.rockpaperscissor.ui.viewmodel.MainViewModel
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
class MainActivity : BaseActivity() {
@Inject
lateinit var factory: ViewModelProviderFactory
private lateinit var viewModel:MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.vicky.apps.rockpaperscissor.R.layout.activity_main)
initializeValues()
val intent = Intent(this,GameActivity::class.java)
playerVsComputer.setOnClickListener {
intent.putExtra(AppConstants.GAME_TYPE_INTENT,GameType.PLAYER_VS_COMPUTER)
startActivity(intent)
}
computerVsComputer.setOnClickListener {
intent.putExtra(AppConstants.GAME_TYPE_INTENT,GameType.COMPUTER_VS_COMPUTER)
startActivity(intent)
}
}
private fun initializeValues() {
viewModel = ViewModelProviders.of(this, factory).get(MainViewModel::class.java)
viewModel.setCompositeData(compositeDisposable)
}
}
<file_sep>package com.vicky.apps.gamecore
enum class GameType {
PLAYER_VS_COMPUTER, COMPUTER_VS_COMPUTER
}<file_sep>package com.vicky.apps.rockpaperscissor.common
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.vicky.apps.gamecore.GamePlay
import com.vicky.apps.rockpaperscissor.data.remote.Repository
import com.vicky.apps.rockpaperscissor.ui.viewmodel.GameViewModel
import com.vicky.apps.rockpaperscissor.ui.viewmodel.MainViewModel
import javax.inject.Inject
class ViewModelProviderFactory @Inject constructor(val gamePlay: GamePlay) :
ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return MainViewModel() as T
}else if(modelClass.isAssignableFrom(GameViewModel::class.java)){
return GameViewModel(gamePlay) as T
}
throw IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName())
}
}<file_sep>package com.vicky.apps.gamecore
enum class GameState {
PLAYER_A_WON, PLAYER_B_WON, DRAW
}<file_sep>package com.vicky.apps.gamecore
class GameObject (val item:String){
var attacks:List<GameObject> = arrayListOf()
var defends:List<GameObject> = arrayListOf()
}<file_sep>package com.vicky.apps.rockpaperscissor.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.vicky.apps.gamecore.GameConstants
import com.vicky.apps.rockpaperscissor.R
import com.vicky.apps.rockpaperscissor.ui.model.GameItems
class DataAdapter constructor(var data:List<GameItems>, val clickListener: (GameItems, Int) -> Unit) : RecyclerView.Adapter<DataAdapter.DataViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_child_view,parent,false)
return DataViewHolder(v)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
when(data[position].item){
GameConstants.OBJECT_NAME_ROCK -> holder.imageView.setImageResource(R.drawable.rock)
GameConstants.OBJECT_NAME_SCISSOR -> holder.imageView.setImageResource(R.drawable.scissor)
GameConstants.OBJECT_NAME_PAPER -> holder.imageView.setImageResource(R.drawable.paper)
}
if(data[position].selected){
holder.imageView.alpha = 1F
}else{
holder.imageView.alpha = 0.1F
}
holder.imageView.setOnClickListener { clickListener(data[position],position) }
}
fun updateData(data: List<GameItems>){
this.data = data
notifyDataSetChanged()
}
class DataViewHolder(v:View): RecyclerView.ViewHolder(v){
val imageView = v.findViewById<ImageView>(R.id.itemImage)
}
}<file_sep>package com.vicky.apps.gamecore
data class Result(val state:GameState ,val playerAObject: GameObject, val playerBObject: GameObject)<file_sep>package com.vicky.apps.rockpaperscissor.base
object AppConstants {
const val GAME_TYPE_INTENT = "gametype"
}<file_sep>package com.vicky.apps.gamecore
interface GamePlay {
fun initializeGame(gameType: GameType, resultCallback: ResultCallback)
fun getListOfGameObjects():List<GameObject>
fun assignPlayerSelection(gameObject: GameObject)
fun startResult()
}<file_sep>package com.vicky.apps.gamecore
class Player(var type:String){
lateinit var gameObject: GameObject
}
<file_sep>package com.vicky.apps.rockpaperscissor.ui.viewmodel
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.vicky.apps.rockpaperscissor.common.SchedulerProvider
import com.vicky.apps.rockpaperscissor.data.remote.Repository
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.subscribeBy
class MainViewModel():ViewModel() {
private val response: MutableLiveData<Boolean> = MutableLiveData()
fun getSubscription():MutableLiveData<Boolean> = response
private lateinit var compositeDisposable: CompositeDisposable
fun setCompositeData(compositeDisposable: CompositeDisposable) {
this.compositeDisposable = compositeDisposable
}
}<file_sep>package com.vicky.apps.rockpaperscissor.ui.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.vicky.apps.gamecore.*
import com.vicky.apps.rockpaperscissor.ui.model.GameItems
import com.vicky.apps.rockpaperscissor.ui.model.ResultUI
class GameViewModel(private val gamePlay: GamePlay) : ViewModel() {
private var gameObjects: List<GameObject> = arrayListOf()
private var playerSelected: Boolean = false
var gameItemsPlayerA: List<GameItems> = arrayListOf()
var gameItemsPlayerB: List<GameItems> = arrayListOf()
val progressLiveData: MutableLiveData<Long> = MutableLiveData()
val resultLiveData: MutableLiveData<ResultUI> = MutableLiveData()
fun initializeGame(gameType: GameType) {
gamePlay.initializeGame(gameType, object : ResultCallback {
override fun onProgress(progress: Long) {
onProgressLoader(progress)
}
override fun onResult(result: Result) {
onResultFinal(result)
}
})
gameObjects = gamePlay.getListOfGameObjects()
gameItemsPlayerA = populateGameObjects()
gameItemsPlayerB = populateGameObjects()
}
fun getPlayerSelected() = playerSelected
private fun populateGameObjects(): List<GameItems> {
val gameItems: MutableList<GameItems> = arrayListOf()
gameObjects.forEach {
gameItems.add(GameItems(it.item))
}
return gameItems
}
fun playerSelection(gameItems: GameItems) {
val gameObject = gameObjects.find {
it.item == gameItems.item
}
gameObject?.let {
gamePlay.assignPlayerSelection(gameObject)
}
gameItemsPlayerB.map {
it.selected = gameItems.item == it.item
}
playerSelected = true
}
fun startGame(){
gamePlay.startResult()
}
fun resetGame(){
playerSelected = false
resetList()
}
fun resetList(){
resetPlayerA()
gameItemsPlayerB.map {
it.selected = false
}
}
fun resetPlayerA(){
gameItemsPlayerA.map {
it.selected = false
}
}
private fun onProgressLoader(onProgress: Long) {
progressLiveData.value = onProgress
}
private fun onResultFinal(result: Result) {
gameItemsPlayerA.map {
it.selected = it.item == result.playerAObject.item
}
gameItemsPlayerB.map {
it.selected = it.item == result.playerBObject.item
}
resultLiveData.postValue(ResultUI(result.state))
}
fun getRandomNumber(): Int{
return (gameObjects.indices).shuffled().first()
}
}<file_sep>package com.vicky.apps.rockpaperscissor.ui.view
import android.os.Bundle
import android.view.View
import android.widget.Adapter
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.vicky.apps.gamecore.GameState
import com.vicky.apps.gamecore.GameType
import com.vicky.apps.rockpaperscissor.R
import com.vicky.apps.rockpaperscissor.base.AppConstants
import com.vicky.apps.rockpaperscissor.base.BaseActivity
import com.vicky.apps.rockpaperscissor.common.ViewModelProviderFactory
import com.vicky.apps.rockpaperscissor.ui.adapter.DataAdapter
import com.vicky.apps.rockpaperscissor.ui.model.GameItems
import com.vicky.apps.rockpaperscissor.ui.model.ResultUI
import com.vicky.apps.rockpaperscissor.ui.viewmodel.GameViewModel
import kotlinx.android.synthetic.main.activity_game.*
import javax.inject.Inject
class GameActivity : BaseActivity() {
@Inject
lateinit var factory: ViewModelProviderFactory
private lateinit var viewModel: GameViewModel
private var gamePlayed: Boolean = false
private var gameType: GameType? = null
private lateinit var playerAdapterA : DataAdapter
private lateinit var playerAdapterB : DataAdapter
private val recyclerViewA : RecyclerView by lazy {
playerARecycler
}
private val recyclerViewB : RecyclerView by lazy {
playerBRecycler
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
initializeViewModel()
initializeRecyclers()
initializeButton()
val gameType:GameType = intent?.
getSerializableExtra(AppConstants.GAME_TYPE_INTENT) as GameType
gameType?.let {
this.gameType = it
initializeGame(gameType)
}
resetGame()
}
private fun initializeButton() {
playButton.setOnClickListener {
playButtonClicked()
}
changeModeButton.setOnClickListener {
finish()
}
}
private fun enableDisableButton(boolean: Boolean){
playButton.isEnabled = boolean
changeModeButton.isEnabled = boolean
}
private fun playButtonClicked() {
if(gamePlayed){
resetGame()
gamePlayed = false
return
}
if(gameType == GameType.PLAYER_VS_COMPUTER){
if(viewModel.getPlayerSelected()){
startPlay()
}
}else {
startPlay()
}
}
private fun initializeRecyclers() {
recyclerViewA.layoutManager = GridLayoutManager(this, 3)
recyclerViewB.layoutManager = GridLayoutManager(this, 3)
playerAdapterA = DataAdapter(viewModel.gameItemsPlayerA){
gameItems, i -> clickInPlayerA(gameItems,i)
}
playerAdapterB = DataAdapter(viewModel.gameItemsPlayerB){
gameItems, i -> clickInPlayerB(gameItems,i)
}
recyclerViewA.adapter = playerAdapterA
recyclerViewB.adapter = playerAdapterB
}
private fun clickInPlayerB(gameItems: GameItems, i: Int) {
if(gameType == GameType.PLAYER_VS_COMPUTER){
viewModel.playerSelection(gameItems)
playerAdapterB.updateData(viewModel.gameItemsPlayerB)
}
}
private fun clickInPlayerA(gameItems: GameItems, i: Int) {
}
private fun initializeGame(gameType: GameType) {
viewModel.initializeGame(gameType)
updateAdapter()
updatePlayerText(gameType)
}
private fun updateAdapter(){
playerAdapterA.updateData(viewModel.gameItemsPlayerA)
playerAdapterB.updateData(viewModel.gameItemsPlayerB)
}
private fun initializeViewModel() {
viewModel = ViewModelProviders.of(this, factory).get(GameViewModel::class.java)
viewModel.resultLiveData.observe(this, Observer {
onResult(it)
})
viewModel.progressLiveData.observe(this, Observer {
onProgress(it)
})
}
private fun startPlay(){
enableDisableButton(false)
viewModel.startGame()
}
private fun onProgress(it: Long?) {
if(gameType == GameType.COMPUTER_VS_COMPUTER){
viewModel.resetList()
viewModel.gameItemsPlayerA[viewModel.getRandomNumber()].selected = true
viewModel.gameItemsPlayerB[viewModel.getRandomNumber()].selected = true
updateAdapter()
}else {
viewModel.resetPlayerA()
viewModel.gameItemsPlayerA[viewModel.getRandomNumber()].selected = true
playerAdapterA.updateData(viewModel.gameItemsPlayerA)
}
resultText.text = it.toString()
}
private fun onResult(result: ResultUI?) {
when(result?.gameState){
GameState.PLAYER_A_WON -> playerAWon()
GameState.PLAYER_B_WON -> playerBWon()
GameState.DRAW -> draw()
}
enableDisableButton(true)
gamePlayed = true
}
private fun resetGame(){
if(gameType == GameType.PLAYER_VS_COMPUTER){
resultText.text = getString(R.string.choose_your_move)
}else {
resultText.text = getString(R.string.click_play)
}
viewModel.resetGame()
updateAdapter()
}
private fun draw() {
resultText.text = getString(R.string.draw)
}
private fun playerBWon() {
if(gameType == GameType.PLAYER_VS_COMPUTER){
resultText.text = getString(R.string.you_won)
}else {
resultText.text = getString(R.string.computer_b_won)
}
}
private fun playerAWon() {
if(gameType == GameType.PLAYER_VS_COMPUTER){
resultText.text = getString(R.string.you_lose)
}else {
resultText.text = getString(R.string.computer_a_won)
}
}
private fun updatePlayerText(gameType: GameType) {
if(gameType == GameType.PLAYER_VS_COMPUTER){
playerAText.text = getString(R.string.computer)
playerBText.text = getString(R.string.player)
}else if (gameType == GameType.COMPUTER_VS_COMPUTER){
playerAText.text = getString(R.string.computer)
playerBText.text = getString(R.string.computer)
}
}
}
<file_sep>package com.vicky.apps.rockpaperscissor.ui.model
data class GameItems(val item:String,var selected:Boolean = false)<file_sep>package com.vicky.apps.rockpaperscissor.di
import android.app.Application
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.vicky.apps.gamecore.GameConstants
import com.vicky.apps.gamecore.GameEngineCore
import com.vicky.apps.gamecore.GamePlay
import com.vicky.apps.rockpaperscissor.base.NetworkConstant
import com.vicky.apps.rockpaperscissor.common.SchedulerProvider
import com.vicky.apps.rockpaperscissor.data.remote.ApiService
import com.vicky.apps.rockpaperscissor.data.remote.Repository
import dagger.Module
import dagger.Provides
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
class AppModule {
@Provides
@Singleton
fun provideSchedulerProvider() = SchedulerProvider(Schedulers.io(), AndroidSchedulers.mainThread())
@Provides
@Singleton
fun provideGson(): Gson {
return GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
}
@Provides
@Singleton
fun provideOkHttpClient(application: Application): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val cacheDir = File(application.cacheDir, UUID.randomUUID().toString())
// 10 MiB cache
val cache = Cache(cacheDir, 10 * 1024 * 1024)
return OkHttpClient.Builder()
.cache(cache)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
}
@Provides
@Singleton
fun provideApiService(gson: Gson, okHttpClient: OkHttpClient): ApiService {
return Retrofit.Builder()
.baseUrl(NetworkConstant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build().create(ApiService::class.java)
}
@Provides
@Singleton
fun provideRepository(apiService: ApiService): Repository{
return Repository(apiService)
}
@Provides
@Singleton
fun provideGameEngine(): GamePlay {
return GameEngineCore(counterTime = GameConstants.COUNTER_5_SECONDS)
}
}
<file_sep># Rock Paper Scissor
Architecture Design Pattern - MVVM (Model View ViewModel)
Tech Stack
-----------
- Programming language - **Kotlin**
- NetWork API - **RetroFit**
- Dependancy Injection - **Dagger 2 for Kotlin**
- Offline Storing - **Room ORM (Arch components)**
- Streams - **RxAndroid and LiveData**
- Architecture Components - **ViewModel, LiveData, Android JetPAck Components**
- Testing Framework - **Junit, Mockito , Expresso, AndroidJunit4**
App Structure
-------------
App module - Application UI Logic , designs and navigation
GameCore Module - Game core logic, exported the app module with abstraction
The application is divided into two modules. The application/Presentation layer is where the UI design is implemented,
whereas the gamecore module is android library which contains the game core logic. This way we can abstract/extract the game logic
and use it in other apps by adding it as dependency.
Screenshots
--------------
Solarized dark | Solarized Ocean
:-------------------------:|:-------------------------:
 | <file_sep>package com.vicky.apps.gamecore
class GameConstants {
companion object {
const val COUNTER_3_SECONDS = 3L
const val COUNTER_5_SECONDS = 5L
const val THREE_OBJECT_GAME = 3
const val OBJECT_NAME_ROCK = "rock"
const val OBJECT_NAME_PAPER = "paper"
const val OBJECT_NAME_SCISSOR = "scissor"
const val PLAYER_TYPE_HUMAN = "human"
const val PLAYER_TYPE_COMPUTER = "computer"
}
}<file_sep>package com.vicky.apps.rockpaperscissor.di
import com.vicky.apps.rockpaperscissor.ui.view.GameActivity
import com.vicky.apps.rockpaperscissor.ui.view.MainActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ActivityBuilder {
@ContributesAndroidInjector
abstract fun bindMainActivity(): MainActivity
@ContributesAndroidInjector
abstract fun bindGameActivity(): GameActivity
}<file_sep>include ':app', ':gamecore'
<file_sep>package com.vicky.apps.rockpaperscissor.ui.model
import com.vicky.apps.gamecore.GameState
class ResultUI(val gameState: GameState)<file_sep>package com.vicky.apps.rockpaperscissor.base
object NetworkConstant {
val BASE_URL = "https://google.com"
}
<file_sep>package com.vicky.apps.gamecore
interface ResultCallback {
fun onProgress(progress:Long)
fun onResult(result: Result)
}<file_sep>package com.vicky.apps.gamecore
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
import java.util.concurrent.TimeUnit
class GameEngineCore(private val counterTime: Long = GameConstants.COUNTER_3_SECONDS,
private val gameObjectCount:Int = GameConstants.THREE_OBJECT_GAME) : GamePlay {
private lateinit var gameType:GameType
private lateinit var resultCallback: ResultCallback
private lateinit var playerA: Player
private lateinit var playerB: Player
private lateinit var gameObjects:List<GameObject>
private val compositeDisposable = CompositeDisposable()
override fun initializeGame(gameType: GameType, resultCallback: ResultCallback) {
this.gameType = gameType
this.resultCallback = resultCallback
initializePlayer()
gameObjects = initializeGameObjects()
}
override fun getListOfGameObjects(): List<GameObject> = gameObjects
override fun assignPlayerSelection(gameObject: GameObject) {
if(gameType == GameType.PLAYER_VS_COMPUTER)
playerB.gameObject = gameObject
else
throw Exception()
}
override fun startResult() {
initTimer()
}
private fun emitResults(){
resultCallback.onResult(generateResult(playerA,playerB))
}
private fun initTimer() {
val disposeTimer = Observable.interval(0,1, TimeUnit.SECONDS)
.take(counterTime+1)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
resultCallback.onProgress(counterTime - it)
if(it == counterTime){
assignValues()
emitResults()
}
}
}
private fun assignValues() {
if(gameType == GameType.PLAYER_VS_COMPUTER){
playerA.gameObject = getRandomGameObject()
}else if(gameType == GameType.COMPUTER_VS_COMPUTER){
playerA.gameObject = getRandomGameObject()
playerB.gameObject = getRandomGameObject()
}
}
private fun generateResult(playerA:Player, playerB: Player):Result{
if (playerA.gameObject.attacks.contains(playerB.gameObject)) {
return Result(GameState.PLAYER_A_WON, playerA.gameObject, playerB.gameObject)
} else if (playerA.gameObject.defends.contains(playerB.gameObject)) {
return Result(GameState.PLAYER_B_WON, playerA.gameObject, playerB.gameObject)
} else {
return Result(GameState.DRAW, playerA.gameObject, playerB.gameObject)
}
}
private fun initializeGameObjects(): List<GameObject>{
val rock = GameObject(GameConstants.OBJECT_NAME_ROCK)
val paper = GameObject(GameConstants.OBJECT_NAME_PAPER)
val scissor = GameObject(GameConstants.OBJECT_NAME_SCISSOR)
rock.attacks = arrayListOf(scissor)
rock.defends = arrayListOf(paper)
paper.attacks = arrayListOf(rock)
paper.defends = arrayListOf(scissor)
scissor.attacks = arrayListOf(paper)
scissor.defends = arrayListOf(rock)
return arrayListOf(rock,paper,scissor)
}
private fun initializePlayer(){
if (gameType == GameType.PLAYER_VS_COMPUTER){
playerA = Player(GameConstants.PLAYER_TYPE_COMPUTER)
playerB = Player(GameConstants.PLAYER_TYPE_HUMAN)
}else if(gameType == GameType.COMPUTER_VS_COMPUTER){
playerA = Player(GameConstants.PLAYER_TYPE_COMPUTER)
playerB = Player(GameConstants.PLAYER_TYPE_COMPUTER)
}
}
private fun getRandomGameObject():GameObject{
val totalCount = gameObjectCount - 1
return gameObjects[(0..totalCount).shuffled().first()]
}
} | 22b2e1fc8c6cf5ec1749d4db2b00d5b8a98b8b88 | [
"Markdown",
"Kotlin",
"Gradle"
] | 23 | Kotlin | vickycj/RockPaperScissor | e9cad10ec69f968be8dcb0673eaeb72750e8ac2b | 8d2b3965ab8f102131c3984f1f5e145738ea08de |
refs/heads/master | <repo_name>Buenomaurilio/PythonConnectionSQLSERVER<file_sep>/ConnectionSqlServer.py
import pyodbc
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute("select * from produto")
for row in cursor:
print(f'row = {row}')
print()
def create (conn):
print("Create")
cursor = conn.cursor()
cursor.execute('insert into produto(nome,preco,qtd) values(?,?,?);',('manteiga', 5.67, 4))
conn.commit()
read(conn)
conn = pyodbc.connect(
"Driver={SQL SERVER Native Client 11.0};"
"Server=vaio;"
"Database=loja;"
"Trusted_Connection=yes;"
)
read(conn)
create(conn)
conn.close() | 804ccddc4dfbeb631ae206be7a759c647b6393e7 | [
"Python"
] | 1 | Python | Buenomaurilio/PythonConnectionSQLSERVER | 8ec2017a83ef72742266d41adb1f4157c823d339 | 7c41279c1b852a3f9c4bc5e13dc3d6d4159fdcfa |
refs/heads/master | <repo_name>rubelux/reifyme<file_sep>/addons/ac/mongoDBc.server.js
YUI.add('addon-ac-mongoDBc', function(Y, NAME) {
var mongodb = require('mongodb');
function MongoDBcAcAddon(command, adapter, ac) {
// The "command" is the Mojito internal details
// for the dispatch of the mojit instance.
// The "adapter" is the output adapter, containing
// the "done()", "error()", etc, methods.
// The "ac" is the ActionContext object to which
// this addon is about to be attached.
}
MongoDBcAcAddon.prototype = {
// The "namespace" is where in the ActionContext
// the user can find this addon. The namespace
// must be the same as the first part of the addon file.
// Thus, this addon file must be named 'cheese'.{affinity}.js'
namespace: 'mongoDBc',
loadData: function() {
var server = new mongodb.Server("127.0.0.1", 27017, {});
var dbTest = new mongodb.Db('unTestDB', server, {});
var retuValue = function(docs){
return docs;
}
dbTest.open(function (error, client) {
if (error) throw error;
var collection = new mongodb.Collection(client, 'personas');
var resultP = collection.find({'nombre': 'pepe'}).toArray(function(err, docs) {
//imprimimos en la consola el resultado
retuValue(docs)
});
});
// Y.log(server);
}
}; //prototype
// If this addon depends on another, that can
// be specified here. Circular dependencies are not
// supported or automatically detected,
// so please be careful.
MongoDBcAcAddon.dependsOn = ['http'];
Y.mojito.addons.ac.mongoDBc = MongoDBcAcAddon;
}, '0.0.1', {requires: ['mojito']});<file_sep>/mojits/Body/models/user.server.js
/*
* Copyright (c) 2012 Yahoo! Inc. All rights reserved.
*/
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('BodyModelUser', function(Y, NAME) {
var mongodb = require('mongodb');
/**
* The BodyModelFoo module.
*
* @module Body
*/
/**
* Constructor for the BodyModelFoo class.
*
* @class BodyModelFoo
* @constructor
*/
Y.namespace('mojito.models')[NAME] = {
init: function(config) {
this.config = config;
},
/**
* Method that will be invoked by the mojit controller to obtain data.
*
* @param callback {function(err,data)} The callback function to call when the
* data has been retrieved.
*/
search: function (callback) {
var server = new mongodb.Server("127.0.0.1", 27017, {});
var dbTest = new mongodb.Db('unTestDB', server, {});
// Y.log(server)
dbTest.open(function (error, client) {
if (error) throw error;
var collection = new mongodb.Collection(client, 'personas');
var resultP = collection.find({'nombre': 'pepe'}).toArray(function(err, docs) {
if (error) throw error;
//imprimimos en la consola el resultado
//retuValue(docs)
callback ({some:docs});
});
})
callback({some:'nothing'});
}//search
};
}, '0.0.1', {requires: ['mojito']});
<file_sep>/mojits/login/controller.server.js
/*
* Copyright (c) 2012 Yahoo! Inc. All rights reserved.
*/
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('login', function(Y, NAME) {
/**
* The login module.
*
* @module login
*/
/**
* Constructor for the Controller class.
*
* @class Controller
* @constructor
*/
Y.namespace('mojito.controllers')[NAME] = {
/**
* Method corresponding to the 'index' action.
*
* @param ac {Object} The ActionContext that provides access
* to the Mojito API.
*/
"index": function(ac) {
var req = ac.http.getRequest()
, userInfo = req.user;
if(userInfo){
var username =userInfo.username;
}
ac.done({
username: username
});
}
};
}, '0.0.1', {requires: ['mojito', 'passport', 'mojito-http-addon']});
<file_sep>/README.md
reifyme
=======
social comunity
this is just a prove of concept of a social community app based on Mojito and YUI3, with simple login using
connect.js and passportjs.
<file_sep>/mojits/Content/controller.server.js
/*
* Copyright (c) 2012 Yahoo! Inc. All rights reserved.
*/
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('Content', function(Y, NAME) {
Y.namespace('mojito.controllers')[NAME] = {
index: function(ac) {
/*var req = ac.http.getRequest(),
passport = req.passport;
Y.log(passport)*/
ac.composite.done();
}
};
}, '0.0.1', {requires: ['mojito', 'mojito-composite-addon', 'mojito-http-addon']});
<file_sep>/mojits/ContRight/controller.server.js
/*
* Copyright (c) 2012 Yahoo! Inc. All rights reserved.
*/
/*jslint anon:true, sloppy:true, nomen:true*/
YUI.add('ContRight', function(Y, NAME) {
/**
* The ContRight module.
*
* @module ContRight
*/
/**
* Constructor for the Controller class.
*
* @class Controller
* @constructor
*/
Y.namespace('mojito.controllers')[NAME] = {
index: function(ac) {
ac.done({title: 'this is my title'});
},
show:function(ac){
var url = ac.params.getFromMerged('url') || 'http://www.rubelux.net' ;
ac.done({title: 'this is my try' + url , url: url});
}
};
}, '0.0.1', {requires: ['mojito-params-addon']});
| 847849346a4d1b6b768bb959f70792f9e5f2ab0f | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | rubelux/reifyme | c243ad123e69d024d2705e10f25baf8dddeb5e22 | 234f7950457d2a244e5705df2f92fddacebf27c8 |
refs/heads/master | <repo_name>aaadryyy/react-gifs<file_sep>/src/components/ListGif.jsx
import React from "react";
import Gif from "./Gif";
const ListGif = ({ gifs, handleSelect }) => {
return (
<div className="gif-list">
{gifs
? gifs.map((gif, key) => {
return <Gif id={gif.id} key={key} handleSelect={handleSelect} />;
})
: ""}
</div>
);
};
export default ListGif;
<file_sep>/src/components/SearchBar.jsx
import React from "react";
const SearchBar = ({ handleChange }) => {
return <input className="form-search" type="text" onChange={handleChange} />;
};
export default SearchBar;
<file_sep>/src/index.jsx
import React from "react";
import giphy from "giphy-api";
import ReactDOM from "react-dom";
import SearchBar from "./components/SearchBar";
import Gif from "./components/Gif";
import ListGif from "./components/ListGif";
import "../assets/stylesheets/application.scss";
class App extends React.Component {
state = {
input: "",
gifs: null,
selected: ""
};
handleChange = event => {
this.setState({ input: event.target.value });
giphy("jmHM25AtCUYQKJfJKM7Sg92hL4jxc9ka").search(
{
q: this.state.input,
limit: 10
},
(err, res) => {
this.setState({ gifs: res.data });
}
);
};
handleSelect = id => {
this.setState({ selected: id });
};
render() {
const { gifs, selected } = this.state;
return (
<div>
<div className="left-scene">
<SearchBar handleChange={this.handleChange} />
<div className="selected-gif">
<Gif id={selected} />
</div>
</div>
<div className="right-scene">
<ListGif gifs={gifs} handleSelect={this.handleSelect} />
</div>
</div>
);
}
}
const root = document.getElementById("root");
if (root) {
ReactDOM.render(<App />, root);
}
<file_sep>/src/components/Gif.jsx
import React, { Fragment } from "react";
const Gif = ({ id, handleSelect }) => {
return (
<Fragment>
{id !== "" ? (
<img
className="gif"
src={`https://media.giphy.com/media/${id}/giphy.gif`}
onClick={() => handleSelect(id)}
/>
) : (
""
)}
</Fragment>
);
};
export default Gif;
| 313367c01592c9ff6f9898957f56d58e1368e230 | [
"JavaScript"
] | 4 | JavaScript | aaadryyy/react-gifs | e581b6672f94c3defb0edc768cc94000b5012528 | 86d37c1ba30b6083cab88ca8dc065f5a5d2f8b50 |
refs/heads/master | <file_sep><?php
/**
* (c) CloudMunch Inc.
* All Rights Reserved
* Un-authorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*
* <NAME> <EMAIL>
*/
/**
* This file handles error/debug logs
*/
const DEBUG = 'DEBUG';
const INFO = 'INFO';
$__log_level = "DEBUG";
function myErrorHandler($errno, $errstr, $errfile, $errline) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
date_default_timezone_set('UTC');
$date = date(DATE_ATOM);
switch ($errno) {
case E_RECOVERABLE_ERROR :
case E_COMPILE_ERROR :
case E_CORE_ERROR :
case E_PARSE :
case E_ERROR :
case E_USER_ERROR :
echo "<b><font color=\"red\">ERROR</b> [$date] $errstr\n";
// echo " Fatal error on line $errline in file $errfile";
// echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "\nAborting...</font><br />\n";
exit (1);
break;
case E_CORE_WARNING :
case E_WARNING :
case E_USER_WARNING :
if (strpos($errstr, 'ssh2_connect():') !== false) {
$msg = "Could not connect to the server";
echo "<b>INFO</b> [$date] $msg\n";
} else {
echo "<b>WARNING</b> [$date] $errstr\n";
}
break;
case E_STRICT :
case E_NOTICE :
case E_USER_NOTICE :
echo "<b>NOTICE</b> [$date] $errstr $errfile $errline\n";
break;
default :
echo "Unknown error type: [$date] $errstr\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
set_error_handler("myErrorHandler");
/**
*
* @param string $log_level : loglevel to set for the app
*/
function set_log_level($log_level){
$__log_level = $log_level;
}
/**
*
* @param string $msgNo : debug/warning/info/error
* @param string $msg : message to be logged.
*/
function loghandler($msgNo, $msg) {
date_default_timezone_set('UTC');
$date = date(DATE_ATOM);
// BITMASK support
if(strpos(strtolower($__log_level), strtolower($msgNo)) !== false || strtolower($__log_level) == "debug") {
// If $__log_level is set as DEBUG - show all logs from the plugin as - DEBUG
if(strtolower($__log_level) == "debug") {
$msgNo = "DEBUG";
}
switch (strtolower($msgNo)) {
case "warning" :
echo "<b>WARNING</b> [$date] $msg\n";
break;
case "info" :
echo "<b>INFO</b> [$date] $msg\n";
break;
case "error" :
echo "<b style='color:red'>ERROR</b> [$date] $msg\n";
break;
case "debug" :
echo "<b>DEBUG</b> [$date] $msg\n";
break;
}
}else{
return false;
}
}
?> | bf0904f86c60cac297d2d151fda0605cfea54201 | [
"PHP"
] | 1 | PHP | syamk/CloudMunch-php-SDK-V1 | 2835ba66e2a102df879b15f654cd3cb1afbf1027 | 52bdf6f2aa9966ba32e9f24405360477cd07d4ad |
refs/heads/master | <file_sep>/*
* Copyright (c) 2020 Arm Limited
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#include "mbed_trace.h"
#define TRACE_GROUP "AWSClock"
extern "C" {
#include "iot_clock.h"
#include "iot_threads.h"
}
struct SystemTimer {
Thread thread;
void (*routine)(void*);
void *routineArgument;
uint32_t first_period;
uint32_t period;
void thread_routine() {
ThisThread::sleep_for(first_period);
while (true) {
routine(routineArgument);
if (period == 0) { break; }
ThisThread::sleep_for(period);
}
tr_debug("closing thread");
}
};
uint64_t IotClock_GetTimeMs(void) {
return rtos::Kernel::get_ms_count();
}
bool IotClock_GetTimestring(char * pBuffer, size_t bufferSize, size_t * pTimestringLength) {
auto now = time(NULL);
auto length = strftime(pBuffer, bufferSize, "%d %b %Y %H:%M", localtime(&now));
if (pTimestringLength != NULL) {
*pTimestringLength = length;
}
return (bufferSize >= length);
}
bool IotClock_TimerCreate(IotTimer_t * pNewTimer, IotThreadRoutine_t expirationRoutine, void * pArgument ) {
*pNewTimer = new SystemTimer { { osPriorityNormal, OS_STACK_SIZE, nullptr, "AwsPortTimer" }, expirationRoutine, pArgument, 0, false };
return true;
}
bool IotClock_TimerArm(IotTimer_t * pTimer, uint32_t relativeTimeoutMs, uint32_t periodMs) {
auto timer = *pTimer;
timer->first_period = relativeTimeoutMs;
timer->period = periodMs;
if (timer->thread.get_state() == Thread::State::Deleted) {
timer->thread.start({timer, &SystemTimer::thread_routine});
}
return true;
}
void IotClock_TimerDestroy(IotTimer_t * pTimer) {
delete *pTimer;
*pTimer = nullptr;
}
| 273d129322e752097056244e57f309fea216f672 | [
"C++"
] | 1 | C++ | rajkan01/mbed-client-for-aws | 60ed34b399464d08d2a73e21ea3cbe537ca50c33 | 4efb01af2b3410fa465da451e88baf360072323a |
refs/heads/main | <file_sep>import React from 'react';
import '../Stylesheets/HScrollGrid.css';
class HScrollGrid extends React.Component{
constructor(props){
super(props);
this.hscrollRef = React.createRef();
}
componentDidMount(){
let n = this.hscrollRef.current ? this.hscrollRef.current.children.length : 0;
let gW = `${this.props.gridWidth}px`;
let gH = `${this.props.gridHeight}px`;
let cW = `${this.props.cardWidth}px`;
let cardBgColor = this.props.backgroundColor ? this.props.backgroundColor : 'transparent';
if(this.hscrollRef.current){
this.hscrollRef.current.style.setProperty('--total', n);
this.hscrollRef.current.style.setProperty('--gridWidth', gW);
this.hscrollRef.current.style.setProperty('--gridHeight', gH);
this.hscrollRef.current.style.setProperty('--cardWidth', cW);
this.hscrollRef.current.style.setProperty('--cBgCol', cardBgColor);
}
}
render(){
return(
<ul className="hscroll-grid" data-testid="test-ul" ref={this.hscrollRef}>
{this.props.children}
</ul>
);
}
}
export default HScrollGrid;<file_sep>"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
require("../Stylesheets/HScrollGrid.css");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var HScrollGrid = /*#__PURE__*/function (_React$Component) {
_inherits(HScrollGrid, _React$Component);
var _super = _createSuper(HScrollGrid);
function HScrollGrid(props) {
var _this;
_classCallCheck(this, HScrollGrid);
_this = _super.call(this, props);
_this.hscrollRef = /*#__PURE__*/_react.default.createRef();
return _this;
}
_createClass(HScrollGrid, [{
key: "componentDidMount",
value: function componentDidMount() {
var n = this.hscrollRef.current ? this.hscrollRef.current.children.length : 0;
var gW = "".concat(this.props.gridWidth, "px");
var gH = "".concat(this.props.gridHeight, "px");
var cW = "".concat(this.props.cardWidth, "px");
var cardBgColor = this.props.backgroundColor ? this.props.backgroundColor : 'transparent';
if (this.hscrollRef.current) {
this.hscrollRef.current.style.setProperty('--total', n);
this.hscrollRef.current.style.setProperty('--gridWidth', gW);
this.hscrollRef.current.style.setProperty('--gridHeight', gH);
this.hscrollRef.current.style.setProperty('--cardWidth', cW);
this.hscrollRef.current.style.setProperty('--cBgCol', cardBgColor);
}
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/_react.default.createElement("ul", {
className: "hscroll-grid",
"data-testid": "test-ul",
ref: this.hscrollRef
}, this.props.children);
}
}]);
return HScrollGrid;
}(_react.default.Component);
var _default = HScrollGrid;
exports.default = _default;<file_sep><h1 align="center">
<h1 align="center">react-horizontal-scroll-grid</h1>
</h1>
<h4 align="center">A simple UI component for <a href="https://reactjs.org/" target="_blank">React</a></h4>
[](https//npmjs.com/package/react-horizontal-scroll-grid)
[](https://github.com/keyurparalkar/react-horizontal-scroll-grid/blob/main/License.md)
```
<HScrollGrid gridWidth={400} gridHeight={100} cardWidth={100} backgroundColor="antiquewhite">
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</HScrollGrid>
```
### Demo

### Changelog
|Version | Compatibility|
|------------|--------------|
|0.1.3 | React 16.3+ |
### Technical Documentation
* [Installing](#Installing)
* [Exports](#Exports)
#### Installing
```
npm install react-horizontal-scroll-grid
```
#### Exports
The `HScrollGrid` component can exported as follows:
```
import HScrollGrid from "react-horizontal-scroll-grid"
```
### HScrollGrid
A `HScrollGrid` is a simple UI Wrapper Component which helps you to display in your `<li>` items in horizontal scroll view. It is completely css based implementation. The count of child elements is directly computed at `componentDidMount` stage and set using css variables.
#### HScrollGrid Props
|Prop Name | Required |Default value | Description|
|------------|--------------|----------|---------|
|gridWidth | Yes| `null` | Should be passed as `number`
|gridHeight | Yes | `null`| Should be passed as `number` *
|cardWidth| Yes | `null`| Should be passed as `number`
|backgroundColor |No| `transparent`| Should be passed `String`
**NOTE**
* `gridWidth`, `gridHeight`,`cardWidth` should be passed in as `number` since they are used as pixels in css.
* Please be aware that by providing the value of `gridHeight` you are also setting the height of each child element to `gridHeight` i.e. Grid's `gridHeight` = card's `gridHeight`
#### Usage
```
import React from 'react';
import HScrollGrid from 'react-horizontal-scroll-grid';
const Example = () => {
const keys = [1, 2, 3, 4, 5, 6];
const cards = keys.map(elem => <li key={elem}> Test </li>);
return (
<>
<HScrollGrid
gridWidth={400}
gridHeight={100}
cardWidth={100}
backgroundColor="antiquewhite"
>
{cards}
</HScrollGrid>
<HScrollGrid
gridWidth={700}
gridHeight={100}
cardWidth={200}
backgroundColor="antiquewhite"
>
{cards}
</HScrollGrid>
<HScrollGrid
gridWidth={1000}
gridHeight={300}
cardWidth={400}
backgroundColor="#ecf2a7"
>
{cards}
</HScrollGrid>
</>
)
};
export default Example;
```
## Built with
- [React](https://reactjs.org/)
- [Jest](https://jestjs.io/en/)
## Features
- Provides a UI wrapper to wrap child elements in horizontal scrolling view.
- Dynamic child element count computation using css variables.
- Easy-to-use
## You can reach out ๐๐
Feel free to contact me about the problems. I will try to help as much as I can ๐
[](https://www.linkedin.com/in/keyur-paralkar-494415107/)
[](mailto:<EMAIL>)
[](https://twitter.com/keurplkar)
[](https://github.com/keyurparalkar/)
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
| 636082cf2955784f27be94fbaa7f5ab08594a8b1 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | keyurparalkar/react-horizontal-scroll-grid | 2e0b199942df6068171d459e8c3946af36a234b1 | c1ab15fc98b0bfdc5f51b3fde596fcfd132a3b38 |
refs/heads/master | <file_sep>package com.hoaxify.ws.shared;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DummyController {
@GetMapping("/secured")
String securedBdoy(){
return "Secure";
}
}
<file_sep>username.NotNull.message = bo\u015F<file_sep>package com.hoaxify.ws.user;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserRepository extends JpaRepository<User,Long> {
User findByUsername(String username);
}
<file_sep>username.NotNull.message = cannot null | ccbf640f460b7995edcb95027587769274897a6e | [
"Java",
"INI"
] | 4 | Java | Osman93/ws | 5f3a3061265e58dacd042ac0434903dcdbb2ea5a | cd25190b7f66a4a22b7918d7bce24236e9c815fd |
refs/heads/master | <file_sep><?php
require_once("facebook.php");
$config = array(
'appId' => '570243296401349',
'secret' => '<KEY>',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$link = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db_selected = mysql_select_db('quizApp', $link) or die(mysql_error());
$query = mysql_query("SELECT * FROM registrationDetails WHERE userID='" . $user_id . "'");
$row = mysql_fetch_array($query);
if ($row)
;
else {
header('Location: ./checkpoint.php');
exit;
}
} catch (FacebookApiException $e) {
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=login.html">');
}
} else {
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=login.html">');
}
?>
<html>
<head>
<title></title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width">
<link href="./css/coreStyling.css" rel="stylesheet" type="text/css" media="screen" />
<link href="./css/dashboardStyling.css" rel="stylesheet" type="text/css" media="screen" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,600,300,700,800|Raleway:200extrlight' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="topBar" class="topBar">
<div id="head" class="head">RoboQZ</div>
<div id="topContainer1" class="topContainer1">
<a onclick="facebookLogout();
return false"><img id="powerButton" class="powerButton" src="./image/pw.png" /></a>
</div>
<div id="topContainer2" class="topContainer2">
<img id="userPic" class="userPic" src="<?php echo $row['linkToDisplayPic']; ?>">
<div id="userName" class="userName" ><span class="fn"><?php echo $row['firstName'] . ' ' . $row['lastName']; ?></span><br><span class="ln"><?php echo $row['email']; ?></span></div>
</div>
</div>
<div id="workspace" class="workspace">
<div id="progress" class="docks progress">
progress
</div>
<div id="current" class="docks current">the current status
<div id="currentLevel" class="currentNode currentLevel" >Level</div>
<div id="currentScore" class="currentNode currentScore" >The Score</div>
</div>
<div id="leader" class="docks leader">
Check out the current standings
<div id="button" class="button btype3">Leaderboard</div>
</div>
<div id="rules" class="docks rules">
Get a hand into the rules
<div id="button" class="button btype2">Proceed to Questions</div>
</div>
<div id="likeWrapper" class="docks likeWrapper">
Like us on Facebook !
<div class="fb-like-box" data-href="https://www.facebook.com/bitsapogee" data-width="260" data-height="280" data-colorscheme="dark" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>
</div>
<div id="proceed" class="proceed">
<div id="button" class="fwd btype1">Proceed To Questions</div>
</div>
</div>
<div id="botBar" class="botBar">
<div id="linkWrapper" class="linkWrapper">
<a style="text-decoration: none;color:black;" href="http://www.bits-apogee.org">APOGEE 2014</a> | <a style="color:black;text-decoration: none;" href="http://www.bits-pilani.ac.in/Pilani/index.aspx">BITS Pilani<a/>
</div>
</div>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=570243296401349";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '570243296401349',
status: true,
cookie: true,
xfbml: true
});
};
(function(d) {
var js;
var id = 'facebook-jssdk';
var ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function facebookLogout() {
FB.logout(function(response) {
window.location.href = "./login.html";
});
}
</script>
</body>
</html>
<file_sep>QuizBuilder
===========
###DVM, Bits Pilani Quiz Builder Implementation
*Code here can be used and modified if required by the Department/Club/Assoc conducting the quiz event.*
###Current Implementation status:
- [x] Design Completed.
- [x] Database Structure Decided.
- [x] Design Decided
###Implementation Deadlines:
First release on 2nd Feb 2014
Version 1, Feature to be completed,
- [ ] Static Site Design.
- [ ] Facebook Integration.
- [ ] Complete Backend Design.
Version 2, 10th Feb 2014,
- [ ] Timeline.
- [ ] Complete CMS.
- [ ] Complete Ajax Support.
Version 3, 12th Feb 2014, Final,
- [ ] Testing.
- [ ] Bugs to be handled.
- [ ] Edits by seniors if required.
###Work Distribution:
Tarun:
Backend.
Pranjal:
Dashboard.
Login.
Header.
Question Display.
Timeline.
Ishan:
Timeline.
Leaderboard.
Image Display.
Extra Lightbox, Utility Display.
Footer(if any)
Score.
<file_sep><?php
require_once("facebook.php");
$config = array(
'appId' => '570243296401349',
'secret' => '<KEY>',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<img src="loading.gif" />
<?php
if ($user_id) {
try {
$link = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db_selected = mysql_select_db('quizApp', $link) or die(mysql_error());
$query = mysql_query("SELECT * FROM registrationDetails WHERE userID='" . $user_id . "'");
$row = mysql_fetch_array($query);
if ($row)
echo ('success');
else {
$user_profile = $facebook->api('/me', 'GET');
$firstName = $user_profile['first_name'];
$lastName = $user_profile['last_name'];
$email = $user_profile['email'];
$user_pic = $facebook->api('/me/picture', 'GET', array('redirect' => false, 'width' => '200', 'height' => '200'));
$url = $user_pic['data']['url'];
$time = time();
mysql_query("INSERT INTO registrationDetails (userID,firstName,lastName,email,initialTimestamp,linkToDisplayPic) VALUES ('$user_id','$firstName','$lastName','$email','$time','$url')");
mysql_query("INSERT INTO userupdate (userID,level,score,lastTimestamp) VALUES ('$user_id','0','0','$time')");
}
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=dashboard.php">');
} catch (FacebookApiException $e) {
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=login.html">');
}
} else {
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=login.html">');
}
?>
</body>
</html>
<file_sep><?php
require_once("facebook.php");
$config = array(
'appId' => '570243296401349',
'secret' => '<KEY>',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$link = mysql_connect('localhost', 'root', '') or die(mysql_error());
$db_selected = mysql_select_db('quizApp', $link) or die(mysql_error());
$query = mysql_query("SELECT * FROM registrationDetails WHERE userID='" . $user_id . "'");
$row = mysql_fetch_array($query);
if ($row)
;
else {
header('Location: ./checkpoint.php');
exit;
}
} catch (FacebookApiException $e) {
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=login.html">');
}
} else {
echo('<META HTTP-EQUIV="Refresh" Content="0; URL=login.html">');
}
?>
<html>
<head>
<title></title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width">
<link href="./css/coreStyling.css" rel="stylesheet" type="text/css" media="screen" />
<link href="./css/leaderboardStyling.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open Sans">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="topBar" class="topBar">
<div id="head" class="head">RoboQZ</div>
<div id="topContainer1" class="topContainer1">
<a onclick="facebookLogout();
return false"><img id="powerButton" class="powerButton" src="./image/pw.png" /></a>
</div>
<div id="topContainer2" class="topContainer2">
<img id="userPic" class="userPic" src="<?php echo $row['linkToDisplayPic']; ?>">
<div id="userName" class="userName" ><span class="fn"><?php echo $row['firstName'] . ' ' . $row['lastName']; ?></span><br><span class="ln"><?php echo $row['email']; ?></span></div>
</div>
</div>
<div id="sidebar" class="sidebar">
<div id="navBox" class="navBox">
<a href="./dashboard.php"><img class="backIcon" src="./image/back.png"></a><div id="navBox1" class="navBox1">| Leaderboard</div>
<div id="i1" class="i1">Standing among Friends</div>
<div id="i2" class="i1">Overall Standing</div>
</div>
</div>
<div id="displayBoard" class="displayBoard">
<div id="starredResult" class="starredResult">
<div id="starredRank" class="starredRank">#1</div>
<img id="starredPic" class="starredPic" src="<?php echo $row['linkToDisplayPic']; ?>">
<div id="starredInfo" class="starredInfo"><span class="starredName"><NAME></span> <br> <span class="starredJoining">Joined : 12:34PM January 13, 2014</span></div>
<div id="starredImp" class="starredImp"> <br>
<span class="starredScore">1236</span><br>
Level : 12
</div>
</div>
<div id="starredResult" class="starredResult">
<div id="starredRank" class="starredRank">#2</div>
<img id="starredPic" class="starredPic" src="<?php echo $row['linkToDisplayPic']; ?>">
<div id="starredInfo" class="starredInfo"><span class="starredName"><NAME></span> <br> <span class="starredJoining">Joined : 12:34PM January 13, 2014</span></div>
<div id="starredImp" class="starredImp"> <br>
<span class="starredScore">1003</span><br>
Level : 12
</div>
</div>
<div id="starredResult" class="starredResult">
<div id="starredRank" class="starredRank">#3</div>
<img id="starredPic" class="starredPic" src="<?php echo $row['linkToDisplayPic']; ?>">
<div id="starredInfo" class="starredInfo"><span class="starredName"><NAME></span> <br> <span class="starredJoining">Joined : 12:34PM January 13, 2014</span></div>
<div id="starredImp" class="starredImp"> <br>
<span class="starredScore">945</span><br>
Level : 12
</div>
</div>
<div id="result" class="result"></div>
<div id="result" class="result"></div>
<div id="result" class="result"></div>
<div id="result" class="result"></div>
</div>
<div id="botBar" class="botBar">
<div id="fb-likeWrapper" class="fb-likeWrapper">
<div class="fb-like" data-href="https://www.facebook.com/bitsapogee" data-layout="standard" data-width="600" data-action="like" data-show-faces="false" data-share="true"></div>
</div>
<div id="linkWrapper" class="linkWrapper">
<a style="text-decoration: none;color:black;" href="http://www.bits-apogee.org">APOGEE 2014</a> | <a style="color:black;text-decoration: none;" href="http://www.bits-pilani.ac.in/Pilani/index.aspx">BITS Pilani<a/>
</div>
</div>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=570243296401349";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '570243296401349',
status: true,
cookie: true,
xfbml: true
});
};
(function(d) {
var js;
var id = 'facebook-jssdk';
var ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function facebookLogout() {
FB.logout(function(response) {
window.location.href = "./login.html";
});
}
</script>
</body>
</html>
| e486788846ad876cdbafc3eb094cfd002208fc2f | [
"Markdown",
"PHP"
] | 4 | PHP | ishan28mkip/QuizBuilder | d0c6748964a58977e0dfbd2b22ab56b434e540bf | faaf02207ccac10baf5ccd55058a3bd74f24a9e8 |
refs/heads/master | <file_sep>package models
import "time"
type Education struct {
Title string
Institute string
From time.Time
To time.Time
}
<file_sep>package main
import (
"context"
"fmt"
"github.com/gorilla/mux"
"github.com/jLemmings/GoCV/controllers"
"github.com/jLemmings/GoCV/middleware"
"github.com/jLemmings/GoCV/models"
"github.com/jLemmings/GoCV/utils"
"github.com/joho/godotenv"
"log"
"net/http"
"os"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
resp := utils.Message(true, "success")
resp["data"] = "Hello World"
utils.Respond(w, resp)
}
func main() {
if os.Getenv("ENV") != "PROD" {
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env.production file")
}
}
users, err := models.GetDB().NewRef("users").OrderByKey().GetOrdered(context.Background())
if err != nil {
log.Fatal(err)
}
for _, r := range users {
var user models.User
if err := r.Unmarshal(&user); err != nil {
log.Fatalln("Error unmarshaling result:", err)
}
fmt.Println("USER WAS FOUND:", user.FirstName, user.LastName)
}
if users == nil {
fmt.Println(os.Getenv("firstName"))
if os.Getenv("firstName") == "" || os.Getenv("lastName") == "" || os.Getenv("email") == "" || os.Getenv("password") == "" || os.Getenv("github") == "" {
log.Fatal("For setup please enter your user information.")
}
models.InitializeFirstUser(os.Getenv("firstName"), os.Getenv("lastName"), os.Getenv("email"), os.Getenv("password"), os.Getenv("github"))
}
router := mux.NewRouter().StrictSlash(true)
router.Use(mux.CORSMethodMiddleware(router))
router.Use(middleware.LogMiddleware)
router.HandleFunc("/users/{id}", controllers.GetUser).Methods("GET")
router.HandleFunc("/", helloWorld).Methods("GET")
protectedRoutes := router.PathPrefix("").Subrouter()
protectedRoutes.HandleFunc("/users", controllers.CreateUser).Methods("POST")
protectedRoutes.HandleFunc("/users/{id}", controllers.UpdateUserClaim).Methods("POST")
protectedRoutes.HandleFunc("/users", controllers.GetUsers).Methods("GET")
protectedRoutes.HandleFunc("/users/{id}", controllers.UpdateUser).Methods("PUT")
protectedRoutes.HandleFunc("/backup/{id}", controllers.CreateBackup).Methods("GET")
protectedRoutes.HandleFunc("/backup/{id}", controllers.RestoreBackup).Methods("POST")
protectedRoutes.Use(middleware.AuthMiddleware)
log.Println("Server Started localhost:" + os.Getenv("PORT"))
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), router))
}
<file_sep>module github.com/jLemmings/GoCV
go 1.13
require (
firebase.google.com/go v3.9.0+incompatible
github.com/google/go-github/v28 v28.1.1
github.com/gorilla/mux v1.7.3
github.com/joho/godotenv v1.3.0
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c // indirect
golang.org/x/net v0.0.0-20190909003024-a7b16738d86b // indirect
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
google.golang.org/api v0.10.0
)
<file_sep>package models
import (
"context"
firebase "firebase.google.com/go"
"firebase.google.com/go/auth"
"firebase.google.com/go/db"
"github.com/joho/godotenv"
"google.golang.org/api/option"
"log"
"os"
)
var fireAuth *auth.Client
var fireDB *db.Client
func init() {
if os.Getenv("ENV") != "PROD" {
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env.production file")
}
}
ctx := context.Background()
var opt option.ClientOption
if os.Getenv("ENV") == "PROD" {
opt = option.WithCredentialsJSON([]byte(os.Getenv("SERVICE_ACCOUNT")))
} else {
opt = option.WithCredentialsFile("serviceAccountDEV.json")
}
config := &firebase.Config{
DatabaseURL: os.Getenv("DATABASE_URL"),
}
app, err := firebase.NewApp(ctx, config, opt)
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
client, err := app.Auth(ctx)
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
fireAuth = client
database, err := app.Database(ctx)
if err != nil {
log.Fatalf("error getting Auth client: %v\n", err)
}
fireDB = database
}
func GetAuth() *auth.Client {
return fireAuth
}
func GetDB() *db.Client {
return fireDB
}
<file_sep>package models
import (
"context"
"firebase.google.com/go/auth"
"fmt"
"github.com/google/go-github/v28/github"
"github.com/jLemmings/GoCV/utils"
"log"
"strings"
"time"
)
type User struct {
ID string
ProfileImageURL string
FirstName string
LastName string
Email string
Password string
Bio string
GithubProfile string
Experience []Experience
Education []Education
Projects []Project
}
func (user *User) Validate() (map[string]interface{}, bool) {
if user.Password == "" {
return utils.Message(false, "Password should be on the payload"), false
}
if user.Email == "" {
return utils.Message(false, "Email should be on the payload"), false
}
if user.FirstName == "" {
return utils.Message(false, "FirstName should be on the payload"), false
}
if user.LastName == "" {
return utils.Message(false, "LastName should be on the payload"), false
}
return utils.Message(true, "success"), true
}
func (user *User) Create() map[string]interface{} {
if resp, ok := user.Validate(); !ok {
return resp
}
params := (&auth.UserToCreate{}).
Email(user.Email).
Password(user.Password)
fireUser, err := GetAuth().CreateUser(context.Background(), params)
utils.HandleErr(err)
user.ID = fireUser.UID
user.Experience = []Experience{{
Title: "My Title",
Description: "My Description",
From: time.Time{},
To: time.Time{},
Tasks: []string{"Test", "bob", "Fred"},
}}
user.Education = []Education{{
Title: "My Title",
Institute: "My Institute",
From: time.Time{},
To: time.Time{},
}}
user.Password = ""
err = GetDB().NewRef("users/"+user.ID).Set(context.Background(), user)
if err != nil {
log.Fatal(err)
}
resp := utils.Message(true, "success")
resp["user"] = user
return resp
}
func GetUsers() []*User {
users := make([]*User, 0)
err := GetDB().NewRef("users").OrderByValue().Get(context.Background(), &User{})
if err != nil {
fmt.Println(err)
return nil
}
return users
}
func GetUser(userId string) *User {
results, err := GetDB().NewRef("users").OrderByKey().EqualTo(userId).GetOrdered(context.Background())
if err != nil {
log.Fatalln("Error querying database:", err)
}
for _, r := range results {
var user User
if err := r.Unmarshal(&user); err != nil {
log.Fatalln("Error unmarshaling result:", err)
}
user.Projects = getProjects(user.GithubProfile)
return &user
}
return &User{}
}
func UpdateUser(userId string, userToUpdate User) *User {
user := &User{}
err := GetDB().NewRef("users"+userId).Update(context.Background(), map[string]interface{}{
"ProfileImageURL": userToUpdate.ProfileImageURL,
"FirstName": userToUpdate.FirstName,
"LastName": userToUpdate.LastName,
"Email": userToUpdate.Email,
"Password": <PASSWORD>,
"Bio": userToUpdate.Password,
"GithubProfile": userToUpdate.GithubProfile,
"Experience": userToUpdate.Experience,
"Education": userToUpdate.Education,
})
if err != nil {
log.Println("Error updating user: ", err)
}
return user
}
func InitializeFirstUser(firstName string, lastName string, email string, password string, github string) {
user := User{
ProfileImageURL: "",
FirstName: firstName,
LastName: lastName,
Email: email,
Password: <PASSWORD>,
Bio: "",
GithubProfile: github,
Experience: []Experience{},
Education: []Education{},
}
log.Println(user)
user.Create()
}
func getProjects(githubProfile string) []Project {
opt := &github.RepositoryListOptions{Type: "public"}
var allRepos []*github.Repository
for {
repos, resp, err := GetGitClient().Repositories.List(context.Background(), githubProfile, opt)
utils.HandleErr(err)
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
var responseRepos []Project
for _, repo := range allRepos {
var project Project
project.Name = *repo.Name
project.URL = *repo.HTMLURL
project.LastUpdate = *repo.UpdatedAt
if repo.Description != nil {
project.Stack = strings.Split(*repo.Description, ",")
}
if repo.Language != nil {
project.Language = *repo.Language
}
responseRepos = append(responseRepos, project)
}
return responseRepos
}
<file_sep>package models
import (
"time"
)
type Experience struct {
Title string
Description string
From time.Time
To time.Time
Tasks []string
}
<file_sep>package models
import (
"context"
"github.com/google/go-github/v28/github"
"github.com/joho/godotenv"
"golang.org/x/oauth2"
"log"
"os"
)
var gitClient *github.Client
func init() {
ctx := context.Background()
if os.Getenv("ENV") != "PROD" {
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env.production file")
}
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GITHUB_KEY")},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
gitClient = client
}
func GetGitClient() *github.Client {
return gitClient
}
<file_sep>package controllers
import (
"context"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jLemmings/GoCV/models"
"github.com/jLemmings/GoCV/utils"
"log"
"net/http"
)
var GetUsers = func(w http.ResponseWriter, r *http.Request) {
data := models.GetUsers()
resp := utils.Message(true, "success")
resp["data"] = data
utils.Respond(w, resp)
}
var CreateUser = func(w http.ResponseWriter, r *http.Request) {
user := &models.User{}
err := json.NewDecoder(r.Body).Decode(user)
if err != nil {
log.Print(err)
utils.Respond(w, utils.Message(false, "Error while decoding request body"))
return
}
resp := user.Create()
utils.Respond(w, resp)
}
var GetUser = func(w http.ResponseWriter, r *http.Request) {
request := mux.Vars(r)
data := models.GetUser(request["id"])
resp := utils.Message(true, "success")
resp["data"] = data
utils.Respond(w, resp)
}
var UpdateUser = func(w http.ResponseWriter, r *http.Request) {
request := mux.Vars(r)
id := request["id"]
user := &models.User{}
err := json.NewDecoder(r.Body).Decode(user)
utils.HandleErr(err)
updatedUser := models.UpdateUser(id, *user)
resp := utils.Message(true, "success")
resp["data"] = updatedUser
utils.Respond(w, resp)
}
var UpdateUserClaim = func(w http.ResponseWriter, r *http.Request) {
request := mux.Vars(r)
id := request["id"]
claims := map[string]interface{}{"admin": true}
err := models.GetAuth().SetCustomUserClaims(context.Background(), id, claims)
utils.HandleErr(err)
user, err := models.GetAuth().GetUser(context.Background(), id)
utils.HandleErr(err)
resp := utils.Message(true, "success")
fmt.Print("Added Claim: ", user.CustomClaims, "to UID: ", user.UID)
utils.Respond(w, resp)
}
var CreateBackup = func(w http.ResponseWriter, r *http.Request) {
request := mux.Vars(r)
id := request["id"]
fmt.Println(id)
fmt.Println("IN CREATE BACKUP")
results, err := models.GetDB().NewRef("users").OrderByKey().GetOrdered(context.Background())
if err != nil {
log.Fatal("RESULTS ERROR: ", err)
}
if len(results) != 0 {
var user models.User
for _, r := range results {
err := r.Unmarshal(&user)
if err != nil {
log.Fatalln("Error unmarshaling result:", err)
}
if user.ID == id {
fmt.Println("USER WAS FOUND:", user.ID)
}
}
/**
fileName := "temp/" + user.ID + "_backup.bak"
userByte, err := json.Marshal(user)
if err != nil {
fmt.Println("Byte ERROR: ", err)
}
err = ioutil.WriteFile(fileName, userByte, 0644)
if err != nil {
fmt.Println("File ERROR: ", err)
}
downloadBytes, err := ioutil.ReadFile(fileName)
fileSize := len(string(downloadBytes))
mime := http.DetectContentType(downloadBytes)
w.Header().Set("Content-Type", mime)
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
w.Header().Set("Expires", "0")
w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Content-Length", strconv.Itoa(fileSize))
w.Header().Set("Content-Control", "private, no-transform, no-store, must-revalidate")
http.ServeContent(w, r, fileName, time.Now(), bytes.NewReader(downloadBytes))
*/
resp := utils.Message(true, "success")
resp["data"] = user
utils.Respond(w, resp)
} else {
resp := utils.Message(true, "failed")
resp["data"] = "NO RESULTS FOUND"
utils.Respond(w, resp)
}
}
var RestoreBackup = func(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var user models.User
err := decoder.Decode(&user)
if err != nil {
panic(err)
}
err = models.GetDB().NewRef("users").Set(context.Background(), map[string]*models.User{
user.ID: {
ID: user.ID,
ProfileImageURL: user.ProfileImageURL,
FirstName: user.FirstName,
LastName: user.LastName,
Email: user.Email,
Password: <PASSWORD>,
Bio: user.Bio,
GithubProfile: user.GithubProfile,
Experience: user.Experience,
Education: user.Education,
},
})
if err != nil {
log.Fatalln("Error setting value:", err)
}
resp := utils.Message(true, "success")
resp["data"] = "Restored backup successfully"
utils.Respond(w, resp)
}
<file_sep>package middleware
import (
"context"
"fmt"
"github.com/jLemmings/GoCV/models"
"github.com/jLemmings/GoCV/utils"
"log"
"net/http"
)
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RequestURI + r.Method)
uid := r.Header.Get("authorization")
if uid != "" {
user, err := models.GetAuth().VerifyIDToken(context.Background(), uid)
fmt.Println("UID: ", user.UID)
utils.HandleErr(err)
claims := user.Claims
if admin, ok := claims["admin"]; ok {
if admin.(bool) {
log.Println("I AM ADMIN")
next.ServeHTTP(w, r)
}
} else {
fmt.Println("IN NOT OK: ", ok)
// TODO: REMOVE AFTER IMPLEMENTATION
next.ServeHTTP(w, r)
// http.Error(w, "Forbidden", http.StatusForbidden)
}
} else {
fmt.Println("No UID")
http.Error(w, "Forbidden", http.StatusForbidden)
}
// Do stuff here
log.Println(r.RequestURI + r.Method)
// Call the next handler, which can be another middleware in the chain, or the final handler.
})
}
<file_sep>package models
import (
"github.com/google/go-github/v28/github"
)
type Project struct {
Name string
Description string
Language string
URL string
Stack []string
LastUpdate github.Timestamp
}
| 472b6bdd9bd191eabca821f7aca78998a08edcc8 | [
"Go Module",
"Go"
] | 10 | Go | jLemmings/GoCV | 13028633a1d4cb9465ea127b99aff9168e500b28 | b41f719b1a1b32a54505e108aa2927be9d2853c4 |
refs/heads/master | <file_sep># DaoVang
Bร i tแบญp lแปn trรญ tuแป nhรขn tแบกo
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package daovang;
import java.util.Scanner;
/**
*
* @author ceol1
*/
/**
*
* W lร mรด hรฌnh bแบฃn ฤแป ฤฦฐแปฃc dแปฑng
* "B" lร รด cแบญn hแป
* "S" lร รด cแบญn quรกi
* "P" lร รด chแปฉa hแป
* "G" lร รด chแปฉa vร ng
* "W" lร รด chแปฉa quรกi
*/
class Environment {
Scanner scr = new Scanner(System.in);
//char w[][]=new char[5][5];
int np; //Sแป hแป
int wp, gp; // vแป trรญ quรกi,vแป trรญ vร ng
int pos[]; // vแป trรญ hแป
int b_pos[] = new int[20];
int s_pos[] = new int[20];
int n = 4 ; // cแบฅp ma trแบญn ~ sแป รด 1 chiแปu
int width = n+1;
//Khoi tao bien
void accept(String w[][]) {
for (int i = 0; i < 20; ++i) {
b_pos[i] = -1;
s_pos[i] = -1;
}
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
w[i][j] = "";
}
}
/**
* vแบฝ bแบฃn ฤแป mร n hinh
*/
int count = 1;
System.out.println("\n\n********* Wumpus World Problem *********\n-by <NAME>.\n");
System.out.println("The positions are as follows.");
for (int i = 1; i <= n; ++i) {
System.out.println("\n-----------------------------------------------------------------");
System.out.print("|\t");
for (int j = 1; j <= n; ++j) {
System.out.print((count++) + "\t|\t");
}
}
System.out.println("\n-----------------------------------------------------------------");
/**
* Nhแบญp liแปu
*/
System.out.println("\nAgent start position: 13");
w[n][1] = "A";
System.out.println("\nEnter the number of pits.");
np = scr.nextInt();// Nhแบญp sแป hแป
pos = new int[np];// Khแปi tแบกo mแบฃng vแป trรญ hแป
System.out.println("Positions of pit, gold and wumpus should not overlap.");
System.out.println("Enter the position of pits.");
for (int i = 0; i < np; ++i) {//tแบกo mแบฃng vแป trรญ hแป
pos[i] = scr.nextInt();
show_sense(pos[i], 1, w);//ฤฦฐa cรกc dแบฅu hiแปu แป รด liแปn kแป vร o ma trแบญn w
}
System.out.println("Enter the position of wumpus.");
wp = scr.nextInt();// nhแบญp vแป trรญ cแปงa quรกi
show_sense(wp, 2, w);////ฤฦฐa cรกc dแบฅu hiแปu แป รด liแปn kแป vร o ma trแบญn w
System.out.println("Enter the position of gold.");
gp = scr.nextInt();//nhแบญp vแป trรญ cแปงa vร ng
insert(w);// ฤฦฐa vแป trรญ quรกi, hแป, vร ng vร o ma trแบญn w
}
//Khoi tao ma tran
void insert(String w[][]) {
int temp = 0;
int count = 0;
//flag1 cho biแบฟt ฤรฃ tรญnh รด vร ng chฦฐa
//flag2 cho biแบฟt ฤรฃ thรชm รด quรกi chฦฐa
int flag1 = 0, flag2 = 0;
for (int i = 0; i < np; ++i) {
temp = pos[i];//temp bแบฑng sแป รด chแปฉa hแป
count = 0;// biแบฟn ฤแบฟm sแป รด hiแปn tแบกi
for (int j = 1; j <= n; ++j) {
for (int k = 1; k <= n; ++k) {
++count;
if (count == temp) {
w[j][k] += "P";// hแป
} else if (count == gp && flag1 == 0) {
w[j][k] += "G";//vร ng
flag1 = 1;
} else if (count == wp && flag2 == 0) {
w[j][k] += "W";//quรกi
flag2 = 1;
}
}
}
}
display(w);
}
/**
* ฤฦฐa vแป trรญ ฤแปi tฦฐแปฃng vร o trong mแบฃng
* @param a vแป trรญ ฤแปi tฦฐแปฃng
* @param b loแบกi ฤแปi tฦฐแปฃng 1 lร hแป 2 lร quรกi
* @param w mแบฃng ma trแบญn
*/
void show_sense(int a, int b, String w[][]) {
int t1, t2, t3, t4;
t1 = a - 1;//รด trรกi liแปn kแป
t2 = a + 1;//รด phแบฃi liแปn kแป
t3 = a + n;//รด dฦฐแปi liแปn kแป
t4 = a - n;//รด trรชn liแปn kแป
if (a == 5 || a == 9) {
t1 = 0;
}
if (a == 8 || a == 12) {
t2 = 0;
}
if (a == 4) {
t2 = 0;
}
if (a == 13) {
t1 = 0;
}
if (t3 > 16) {
t3 = 0;
}
if (t4 < 0) {
t4 = 0;
}
//int temp[]=new int[4];
if (b == 1) {//hแป
b_pos[0] = t1;
b_pos[1] = t2;
b_pos[2] = t3;
b_pos[3] = t4;
} else if (b == 2) {//quรกi
s_pos[0] = t1;
s_pos[1] = t2;
s_pos[2] = t3;
s_pos[3] = t4;
}
int temp1, count;
for (int i = 0; i < 4; ++i) {
if (b == 1) {
temp1 = b_pos[i];
} else {
temp1 = s_pos[i];
}
count = 0;
for (int j = 1; j <= n; ++j) {
for (int k = 1; k <= n; ++k) {
++count;
if (count == temp1 && b == 1 && !w[j][k].contains("B")) {
w[j][k] += "B";// cแบญn hแป
} else if (count == temp1 && b == 2 && !w[j][k].contains("S")) {
w[j][k] += "S";// cแบญn quรกi
}
}
}
}
//display(w);
}
/**
*
* @param w
* Hiแปn thแป lแบกi ma trแบญn w khi ฤรฃ thรชm xong cรกc ฤแปi tฦฐแปฃng bแบฃn ฤแป
*/
void display(String w[][]) {
System.out.println("\nThe environment for problem is as follows.\n");
for (int i = 1; i <= n; ++i) {
System.out.println("\n-----------------------------------------------------------------");
System.out.print("|\t");
for (int j = 1; j <= n; ++j) {
System.out.print(w[i][j] + "\t|\t");
}
}
System.out.println("\n-----------------------------------------------------------------");
}
}
| acb8df63113c32d32722eb23003712f54ef35697 | [
"Markdown",
"Java"
] | 2 | Markdown | BeePig/DaoVang | 3372d13ee7d74316eaccab341b582664a13b76a6 | bf7f2a2b7b5da955ff476a2fb36781ff583f656f |
refs/heads/master | <file_sep>import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AuthGuard } from "../auth/auth-guard.service";
import { ShoppingListComponent } from "./shopping-list.component";
const ShoppingRoute:Routes=[
{path: 'shopping-list',component:ShoppingListComponent,canActivate:[AuthGuard]}
];
@NgModule(
{
imports:[
RouterModule.forChild(ShoppingRoute),
],
exports:[RouterModule]
}
)
export class ShoppingRoutingModule{
}<file_sep># Food
This project is a recipe app which will use Angular 6 for the front-end part.
The backend is currently just use firebase to supply the database and authentication
To view the Project, just click below
<a href="http://172.16.58.3/" target="_blank">Recipes Web</a>
<br/>Using email:<EMAIL>
password:<PASSWORD> To login
<br/>
To download the front end.
just npm install and ng serve
<file_sep>import { Injectable } from "@angular/core";
import { Http, Response } from "@angular/http";
import { RecipesService } from "../recipes/recipes.service";
import {map, catchError} from 'rxjs/operators'
import { AuthService } from "../auth/auth.service";
@Injectable()
export class DataStorageService{
constructor(private http:Http,
private recipeService:RecipesService,
private authService:AuthService
){
}
storeRecipes(){
const token=this.authService.getToken();
return this.http.put('https://myfood-b8020.firebaseio.com/receips.json?auth='+token
,this.recipeService.getRecipes()).pipe(
map(
(response:Response)=>{
const data=response.json();
return data;
}
)
);
}
getRecipes(){
const token=this.authService.getToken();
return this.http.get('https://myfood-b8020.firebaseio.com/receips.json?auth='+token).pipe(
map((response:Response)=>{
const data=response.json();
return data;
})
)
}
}<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core';
import { Ingredient } from '../shared/ingredient.model';
import { ShoppingListService } from './shipping-list.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-shopping-list',
templateUrl: './shopping-list.component.html',
styleUrls: ['./shopping-list.component.css'],
})
export class ShoppingListComponent implements OnInit, OnDestroy{
ingredients:Ingredient[]=[];
ingreidentSubsciption:Subscription;
constructor(private shoppingListService:ShoppingListService) { }
ngOnInit() {
this.ingredients=this.shoppingListService.getIngredients();
this.ingreidentSubsciption=this.shoppingListService.ingredientGotChanged.subscribe(
(ingredients:Ingredient[])=>{
this.ingredients=ingredients;
}
)
}
onClickToEdit(index:number){
this.shoppingListService.editedShoppingListItem.next(index);
}
ngOnDestroy(){
this.ingreidentSubsciption.unsubscribe();
}
}
<file_sep>import { NgModule } from "@angular/core";
import { Routes, RouterModule} from '@angular/router';
import { AuthGuard } from "../auth/auth-guard.service";
const appRoutes: Routes =[
{path:'',redirectTo:'signin',pathMatch:'full'},
{path:'recipes',loadChildren:'../recipes/recipes.module#RecipesModule',canLoad:[AuthGuard]}
];
@NgModule({
imports:[
RouterModule.forRoot(appRoutes)
],
exports:[
RouterModule
]
})
export class AppRoutingMoudule{
}<file_sep>import {Component, OnInit} from '@angular/core'
import { DataStorageService } from '../../shared/data-storage.service';
import { Recipe } from '../../recipes/recipe-model';
import { AuthService } from '../../auth/auth.service';
import { Router } from '@angular/router';
import { RecipesService } from '../../recipes/recipes.service';
@Component(
{
selector:'app-header',
templateUrl:'./header.component.html'
}
)
export class HeaderComponent{
constructor(private dataStoreService:DataStorageService,
private recipeService:RecipesService,
private authService:AuthService,
private router:Router){}
isAuthenticated(){
return this.authService.isAuthenticated();
}
onSaveRecipes(){
this.dataStoreService.storeRecipes().subscribe(
(receipes)=>{
console.log(receipes);
}
);
}
fetchRecipes(){
this.dataStoreService.getRecipes().subscribe(
(recipes:Recipe[])=>{
this.recipeService.loadRecipes(recipes);
}
);
}
onLogout(){
this.authService.logOut();
this.router.navigate(['/signin']);
}
}<file_sep>import { Recipe } from "./recipe-model";
import { EventEmitter, Injectable } from "@angular/core";
import { Ingredient } from "../shared/ingredient.model";
import { Subject } from "rxjs";
import { DataStorageService } from "../shared/data-storage.service";
@Injectable()
export class RecipesService{
recipeSelected=new EventEmitter<Recipe>();
recipeWasUpdated=new Subject<Recipe[]>();
private recipes:Recipe[]=[
new Recipe('Hamburger','test recipe',
'http://en.foodtravel.tv/datastore/recfood/873/Picture1873_normal.jpg',
[new Ingredient("meat",1),new Ingredient('cheese',5)]),
new Recipe('Salad','another recipe',
'https://images.pexels.com/photos/461198/pexels-photo-461198.jpeg',
[new Ingredient('cucumber',5),new Ingredient('cheese',3)]),
];
selectedId:number;
getRecipes(){
return this.recipes.slice();
}
getRecipe(index:number){
return this.recipes[index];
}
addRecipe(recipe:Recipe){
this.recipes.push(recipe);
this.recipeWasUpdated.next(this.recipes.slice());
}
updateRecipe(index:number,recipe:Recipe){
this.recipes[index]=recipe;
this.recipeWasUpdated.next(this.recipes.slice());
}
deleteRecipe(index:number){
this.recipes.splice(index,1);
this.recipeWasUpdated.next(this.recipes.slice());
}
loadRecipes(recipes:Recipe[]){
this.recipes=recipes;
this.recipeWasUpdated.next(this.recipes.slice());
}
} | 39d5501263922a9afcc5faca3e1ed94c3e8b7205 | [
"Markdown",
"TypeScript"
] | 7 | TypeScript | jerryguowei/recipes | 241f2961b11d1a6a9a037635492bd8cfbbfea2ca | a799f540040a61d6910e986abc209f90c4d5243b |
refs/heads/master | <file_sep>import gensafeprime
import random
def choose_random_prime(n):
"""
Returns prime p with generator g of group Zp*
if g is generator then g^((p-1)/q)!=1
since p=2q+1, (p-1)/q become 2
"""
if (n==2):
return [2,1]
elif (n==3):
return [5,2]
elif (n==4):
return [11,2]
elif (n==5):
return [23,11]
p=gensafeprime.generate(n)
while(True):
g=random.randrange(2,p,1)
if(pow(g,2,p) !=1):
return [p,g]
def CRH(x,y,k):
"""
Returns hashed value using DLP
"""
global g,p
return pow(g,x+k*y,p)
def signing(x,M):
"""
Returns digital signature
"""
global g,p
r=random.randrange(1,p,1)
t=pow(g,r,p)
c=CRH(t,M,p)
return [t,c*x+r]
def get_message(L):
"""
Return concatanated message
"""
M=""
for i in L:
if i == None:
M+="0"
else:
M+=str(i)
M=int(M)
M=M%p
return M
def cal_hash(a):
"""
Calculate hash of previous block of D
"""
global g,p,v
if v == 1:
return None
M=get_message([a.data_item,a.hash_prev,a.sign_prev[0],a.sign_prev[1],a.prev_ptr])
h=CRH(M,g,p)
return h
def cal_sign(a,b,c):
"""
Calculate sign of current block contents using data_item, hash_prev and prev_ptr
"""
global g,p,v
if v != 3:
return [None,None]
x=random.randrange(1,p,1)
M=get_message([a,b,c])
return signing(x,M)
class node():
"""
Node class
"""
def __init__(self,a,b,c,d):
self.data_item=a
self.hash_prev=b
self.sign_prev=c
self.prev_ptr=d
def printval(self):
print("data_item =",self.data_item)
print("hash_prev =",self.hash_prev)
print("sign_prev =",self.sign_prev)
print("prev_ptr =",self.prev_ptr)
class stack():
"""
Stack class
"""
def __init__(self):
self.isempty=True
self.size=0
self.top=None
self.storage={}
def push(self,x):
if self.isempty:
self.isempty=False
tn=node(x,None,[None,None],None)
self.top=tn
self.storage[id(tn)]=tn
else:
h=cal_hash(self.top)
s=cal_sign(x,h,id(self.top))
tn=node(x,h,s,id(self.top))
self.top=tn
self.storage[id(tn)]=tn
self.size+=1
def pop(self):
if not self.isempty:
if self.size == 1:
del self.storage[id(self.top)]
self.isempty=True
self.top=None
else:
t1=id(self.top)
t2=self.storage[t1].prev_ptr
del self.storage[t1]
self.top=self.storage[t2]
self.size-=1
else:
print("Stack is empty")
def printstack(self):
if not self.isempty:
temp=ms.top
while(temp.prev_ptr):
temp.printval()
print()
temp=self.storage[temp.prev_ptr]
temp.printval()
print()
else:
print("Stack is empty")
def run():
"""
Take user input and build the stack
"""
print("Check empty: 1")
print("Size: 2")
print("Top element: 3")
print("Push: 4")
print("Pop: 5")
print("Print stack: 6")
while True:
x=int(input())
if x == 1:
print(ms.isempty)
elif x == 2:
print(ms.size)
elif x == 3:
if not ms.isempty:
print(ms.top.data_item)
else:
print("Stack is empty")
elif x == 4:
n=int(input())
ms.push(n)
elif x == 5:
ms.pop()
elif x == 6:
ms.printstack()
if __name__ == "__main__":
p,g = choose_random_prime(128)
v=int(input("Enter version of D: "))
ms=stack()
run()<file_sep>import gensafeprime
import random
def choose_random_prime(n):
"""
Returns prime p with generator g of group Zp*
if g is generator then g^((p-1)/q)!=1
since p=2q+1, (p-1)/q become 2
"""
if (n==2):
return [2,1]
elif (n==3):
return [5,2]
elif (n==4):
return [11,2]
elif (n==5):
return [23,11]
p=gensafeprime.generate(n)
while(True):
g=random.randrange(2,p,1)
if(pow(g,2,p) !=1):
return [p,g]
def CRH(x,y,k):
"""
Returns hashed value using DLP
"""
global g,p
return pow(g,x+k*y,p)
def signing(x,M):
"""
Returns digital signature
"""
global g,p
r=random.randrange(1,p,1)
t=pow(g,r,p)
c=CRH(t,M,y)
return [t,c*x+r]
def verify(A,y,M):
"""
Verifies the signature
"""
global g,p
t,z=A
LHS=pow(g,z,p)
RHS=((pow(y,CRH(t,M,y),p))*t)%p
return (LHS == RHS)
if __name__ == "__main__":
p,g = choose_random_prime(int(input()))
M=random.randrange(1,p,1)
x=random.randrange(1,p,1)
y=pow(g,x,p)
print(verify(signing(x,M),y,M))<file_sep>## Introduction
This repo contains implementations of various cryptography algorithms
- Digital signature usong ZKP for DLP
- Fault tolerant storage scheme using Shamir secret sharing
- Blockchain basic
- OT using El Gamel scheme
Refer to PDF's for further details on each.<file_sep>import numpy as np
import random
def choose_random_prime(n):
"""
Returns prime p with generator g of group Zp*
if g is generator then g^((p-1)/q)!=1
since p=2q+1, (p-1)/q become 2
"""
import gensafeprime
if (n==2):
return [2,1]
elif (n==3):
return [5,2]
elif (n==4):
return [11,2]
elif (n==5):
return [23,11]
p=gensafeprime.generate(n)
while(True):
g=random.randrange(2,p,1)
if(pow(g,2,p) !=1):
return [p,g]
def CRH(x,y,k):
"""
Returns hashed value using DLP
"""
global g,p
return pow(g,x+k*y,p)
def signing(x,M,y):
"""
Returns digital signature
"""
global g,p
r=random.randrange(1,p,1)
t=pow(g,r,p)
c=CRH(t,M,y)
return [t,c*x+r]
def verify(A,y,M):
"""
Verifies the signature
"""
global g,p
t,z=A
LHS=pow(g,z,p)
RHS=((pow(y,CRH(t,M,y),p))*t)%p
return (LHS == RHS)
def construct_poly(k,b):
"""
Return polynomial of degree k-1
"""
coef=[]
for i in range(k):
coef.append(random.getrandbits(b))
return coef
def eval_pol(P,x):
"""
Find P(x)%p
"""
global p
ret=0
for i in range(len(P)):
ret=(ret+(P[i]*pow(x,i,p)))%p
return ret
def get_points(P,n):
"""
Return n points lying on P
"""
X=[]
Y=[]
for i in range(n):
t=random.randint(0,2*n)
while(t in X):
t=random.randint(0,2*n)
X.append(t)
Y.append(eval_pol(P,t))
return X,Y
def encode(X,Y):
"""
Return encoded blocks
"""
global g,p
nop=len(X)
encoded_block=[]
pbl_keys=[]
for i in range(nop):
M=Y[i]
x=random.randrange(1,p,1)
y=pow(g,x,p)
z=signing(x,M,y)
encoded_block.append([X[i],Y[i],z])
pbl_keys.append(y)
return encoded_block,pbl_keys
def corrupt(pk,e):
"""
Corrupt e blocks
"""
global p
n=len(pk)
for i in range(e):
ind=random.randrange(0,n,1)
y=random.randrange(1,p,1)
while(y == pk[ind]):
y=random.randrange(1,p,1)
pk[ind]=y
return pk
def check_corrupt(enc,pk):
"""
Remove corrupted blocks
"""
global g,p
n=len(enc)
temp=[]
for i in range(n):
if(verify(enc[i][2],pk[i],enc[i][1])):
temp.append(enc[i])
return temp
def preprocess(X,k):
"""
Preprocess array for reconstruction
"""
global p
A=[]
for i in range(k):
A.append([X[i][0],X[i][1]])
A=np.array(A)
return A
def reconstruct_poly(X,k):
"""
Returns reconstruct polynomial
"""
import sympy as sp
global p
X=preprocess(X,k)
x=X[:k,0]
x=np.tile(x,(k,1)).T
y=X[:k,1]
t1=np.tile(np.arange(k),(k,1))
t2=np.power(x,t1)
coef=sp.Matrix(t2).inv_mod(p) @ y
coef=[i%p for i in coef]
return coef
def check(x,y):
"""
Checks if reconstructed polynomial is same or not
"""
for i in range(len(y)):
if(x[i]!=y[i]):
return False
return True
def printresult(P,enc,Q,result):
"""
Print the values used in code
"""
print("p =",p)
print("g =",g)
print("n =",n)
print("k =",k)
print("e =",e)
print("b =",b)
# print("k blocks = ",end="")
# for i in P:
# print(i,end=" ")
# print()
# print("encoded blocks = ")
# for i in range(len(enc)):
# print("("+str(enc[i][0])+","+str(enc[i][1])+")")
# print("reconstructed blocks = ",end="")
# for i in Q:
# print(i,end=" ")
# print()
print("verdict =",result)
def routing_scheme():
"""
Implements a robust routing scheme
"""
#sender side
P=construct_poly(k,b)
X,Y=get_points(P,n)
enc,pk=encode(X,Y)
#corrupting e channels
pk=corrupt(pk,e)
#receiver side
correct_blocks=check_corrupt(enc,pk)
Q=reconstruct_poly(correct_blocks,k)
#for verification
result=check(P,Q)
printresult(P,enc,Q,result)
def egencrypt(M,k):
"""
Encrypt message using EG
"""
q,g,h=k
m=M[0]+M[1]
y=random.randint(1,q)
s=pow(h,y,q)
c1=pow(g,y,q)
c2=(m*s)%q
return m,[c1,c2]
def egdecrypt(M,k,x):
"""
Decrypt message using EG
"""
c1,c2=M
q,g,h=k
s=pow(c1,x,q)
s_inv=pow(s,q-2,q)
m=(c2*s_inv)%q
return m
def generate_key():
"""
Generate public key for EG protocol
"""
q,g=choose_random_prime(256)
x=random.randint(1,q)
h=pow(g,x,q)
return [q,g,h],x
def OT():
"""
Implememts OT between client A and server B
"""
N=100
#array with the server
B=random.sample(range(10*N),N)
#array to send to server
A=[]
for i in range(N):
A.append([random.randint(0,10*N),random.randint(0,10*N)])
#chose ind
ind=random.randint(0,N)
#generate key
pbl_k,pvt_k=generate_key()
#preprocess array before sending to server
orig,A[ind]=egencrypt(A[ind],pbl_k)
#create array to send to client
C=[]
for i in range(len(A)):
temp=egdecrypt(A[i],pbl_k,pvt_k)
C.append(B[i]^temp)
#check result
print("Index used is:",ind)
print("B[i](array with Bob):",B[ind])
print("C[i](array returned by Bob):",C[ind])
print("C[i] xor r:",C[ind]^orig)
if B[ind] == C[ind]^orig :
print("Successful Transfer")
else:
print("Unsuccessful Transfer")
if __name__ == "__main__":
#declare variables
p,g=choose_random_prime(256)
# n,k,e,b=[int(x) for x in input().split()]
n,k,e,b=[120,5,13,200]
# routing_scheme()
OT() | 3f26da14c8e0cb72a2983cac3e3a2ae803ffd49a | [
"Markdown",
"Python"
] | 4 | Python | sarthak77/Cryptography_Algorithms | 46b1203bc9a32c0f3293c648f4a577b5a2c1d401 | fbbcbcee21bc2d77df8e52e7e05b864fb88c0854 |
refs/heads/master | <file_sep>#ifndef EZ_STRING
#define EZ_STRING
#include <string.h>
#include <stdlib.h>
#define GLOBAL_STRING(size) (String)&( (string_s){ char [size], size } )
typedef struct
{
char * cstr;
int size;
} string_s;
typedef string_s* String;
void clear(String str) {
str->cstr[0] = '\0';
}
String string_sized(unsigned int size) {
String str = (String)malloc(sizeof(string_s));
str->size = size;
str->cstr = (char*)malloc(sizeof(char)*(str->size));
clear(str);
return str;
}
String string(const char* cstr) {
String str = string_sized((unsigned int)strlen(cstr)+1);
strcpy(str->cstr, cstr);
return str;
}
String copy(String s) {
return string(s->cstr);
}
char* rest(String str) {
return str->cstr + strlen(str) - 1;
}
void expand(String str, int size) {
str->size += size;
char* newCstr= (char*)malloc(sizeof(char)*(str->size));
strcpy(newCstr, str->cstr);
free(str->cstr);
str->cstr = newCstr;
}
unsigned int len(String s) {
return s->size - 1;
}
void delete(String str) {
if (str == NULL)
return;
if (str->cstr != NULL) {
free(str->cstr);
}
free(str);
}
#endif<file_sep>#include <stdio.h>
#include "ezstring.h"
String read_string();
String read_string_max(int max);
int main() {
String s = string("my string");
printf("%s \n", s->cstr);
String sizedString = string_sized(50);
expand(sizedString, 255);
sprintf(sizedString->cstr, "sized strings are %s and 2+3=%d and my other string is %s", "awesome", 5, s->cstr);
printf("%s \n", sizedString->cstr);
delete(s);
delete(sizedString);
printf("Please enter your username: ");
String username = read_string_max(255);
printf("Welcome, %s\n", username->cstr);
printf("Write a long text :");
String long_str = read_string();
printf("Your long text :%s\n", long_str->cstr);
system("PAUSE");
}
String read_string_max(int max) {
String str_big = string_sized(max);
scanf("%s", str_big->cstr);
String str = copy(str_big);
delete(str_big);
return str;
}
String read_string() {
static String str_big;
if(str_big == NULL)
str_big= string_sized(255*10);
else
clear(str_big);
scanf("%s", str_big->cstr);
String str = copy(str_big);
return str;
} | 9f7463395da4203ead2cc5ef8739e0d0af20788c | [
"C"
] | 2 | C | celoron/ezstring | 81d06cd3b1ab625dfd38a4397cbf81524be0a7f2 | 1c8d2c73b92a49fc95813eb00d399a9c697c90d6 |
refs/heads/master | <repo_name>cookieplz/samsamoo<file_sep>/src/main/java/com/ezen/samsamoo/dao/ArticleDao.java
package com.ezen.samsamoo.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.ezen.samsamoo.dto.Article;
import com.ezen.samsamoo.dto.Board;
import java.util.List;
import java.util.Map;
@Mapper
public interface ArticleDao {
// ๊ฒ์ํ ๋ฒํธ(id)๋ฅผ ํตํด ๊ฒ์ํ ํ ๊ฐ์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public Board getBoardById(@Param("id") int id);
// ๊ฒ์๊ธ ๋ฒํธ(id)๋ฅผ ํตํด ๊ฒ์๊ธ ํ ๊ฐ๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public Article getArticleById(@Param("id") int id);
// ๊ฒ์๊ธ ๋ฒํธ(id)๋ฅผ ํตํด ๊ฒ์๊ธ ํ ๊ฐ์ ์์ธํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public Article getForPrintArticleById(@Param("id") int id);
// ๊ฒ์ํ ๋ด์ ์ ์ฒด ๊ฒ์๊ธ์ ๊ฐ์๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public int getArticlesTotalCount(@Param("boardId") int boardId,
@Param("searchKeywordTypeCode") String searchKeywordTypeCode, @Param("searchKeyword") String searchKeyword);
// ๊ฒ์๊ธ๋ค์ ์์ธํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public List<Article> getForPrintArticles(@Param("boardId") int boardId,
@Param("searchKeywordTypeCode") String searchKeywordTypeCode, @Param("searchKeyword") String searchKeyword,
@Param("limitFrom") int limitFrom, @Param("limitTake") int limitTake);
// ๊ฒ์๊ธ ์ฐ๊ธฐ
public void writeArticle(Map<String, Object> param);
// ๊ฒ์๊ธ ์์ ํ๊ธฐ
public void modifyArticle(Map<String, Object> param);
// ๊ฒ์๊ธ ์ญ์ ํ๊ธฐ
public void deleteArticleById(@Param("id") int id);
// insert ์ดํ ๋ฐ์ดํฐ๊ฐ ๋ค์ด๊ฐ auto_increment๋ก ๋์ด์๋ PK๊ฐ์ ๊ฐ์ ธ์ค๊ธฐ
public int getLastInsertId();
// ๊ฒ์๊ธ ์กฐํ์ 1์ฉ ์ฆ๊ฐ
public int updateHitCount(@Param("id") int id);
// ๊ฒ์๊ธ ์ข์์ 1์ฉ ์ฆ๊ฐ
public int updateLikeCount(@Param("id") int id);
// ๊ฒ์๊ธ ์ซ์ด์ 1์ฉ ์ฆ๊ฐ
public int updateDislikeCount(@Param("id") int id);
}
<file_sep>/src/main/java/com/ezen/samsamoo/dao/MemberDao.java
package com.ezen.samsamoo.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.ezen.samsamoo.dto.Member;
import java.util.List;
@Mapper
public interface MemberDao {
// ๋ก๊ทธ์ธ ์์ด๋๋ฅผ ํตํด ํ์ ํ ๋ช
์ ๋ฐ์ดํฐ ์ป๊ธฐ
public Member getMemberByLoginId(@Param("loginId") String loginId);
// member ๋ฒํธ๋ฅผ ํตํด ํ์ ํ ๋ช
์ ๋ฐ์ดํฐ ์ป๊ธฐ
public Member getMemberById(@Param("id") int id);
// ํ์ ์ด๋ฆ๊ณผ ์ด๋ฉ์ผ์ ํตํด ํ์ ํ๋ช
์ ๋ฐ์ดํฐ ์ป๊ธฐ
public Member getMemberByNameAndEmail(@Param("name") String name, @Param("email") String email);
// ํ์๋ค์ ์์ธํ ์ ๋ณด ๋ฆฌ์คํธ๋ฅผ ์ป๊ธฐ
public List<Member> getForPrintMembers();
// ํ์๊ฐ์
ํ๊ธฐ
public void join(@Param("loginId") String loginId, @Param("loginPw") String loginPw, @Param("name") String name, @Param("nickname") String nickname, @Param("cellphoneNo") String cellphoneNo, @Param("email") String email);
// ํ์ ์์ ํ๊ธฐ
void modify(@Param("id") int id, @Param("loginPw") String loginPw, @Param("name") String name, @Param("nickname") String nickname, @Param("cellphoneNo") String cellphoneNo, @Param("email") String email);
// insert ์ดํ ๋ฐ์ดํฐ๊ฐ ๋ค์ด๊ฐ auto_increment๋ก ๋์ด์๋ PK๊ฐ์ ๊ฐ์ ธ์ค๊ธฐ
public int getLastInsertId();
}
<file_sep>/src/main/java/com/ezen/samsamoo/service/ArticleService.java
package com.ezen.samsamoo.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ezen.samsamoo.dao.ArticleDao;
import com.ezen.samsamoo.dto.Article;
import com.ezen.samsamoo.dto.Board;
import com.ezen.samsamoo.dto.Member;
import com.ezen.samsamoo.dto.ResultData;
import com.ezen.samsamoo.util.Util;
@Service
public class ArticleService {
@Autowired
private ArticleDao articleDao;
@Autowired
private SamFileService samFileService;
@Autowired
private MemberService memberService;
//----------------------------------------------------------------------------------------------------
// ๊ฒ์๊ธ์ด ์กด์ฌํ์ง ์๋์ง ํ์ธํ๋ ํจ์
private boolean isEmpty(Article article) {
if (article == null) {
return true;
} else if (article.isDelStatus()) { // ๊ฒ์๊ธ์ด ์ญ์ ๋ ์ํ๋ ๊ฒ์๊ธ์ด ์กด์ฌํ์ง ์๋ ๊ฒ์ผ๋ก ์ทจ๊ธ
return true;
}
return false;
}
//----------------------------------------------------------------------------------------------------
// ๊ฒ์ํ ๋ฒํธ(id)๋ฅผ ํตํด ๊ฒ์ํ ํ ๊ฐ์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public Board getBoardById(int id) {
return articleDao.getBoardById(id);
}
// ๊ฒ์๊ธ ๋ฒํธ(id)๋ฅผ ํตํด ๊ฒ์๊ธ ํ ๊ฐ๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public Article getArticleById(int id) {
return articleDao.getArticleById(id);
}
// ๊ฒ์๊ธ ๋ฒํธ(id)๋ฅผ ํตํด ๊ฒ์๊ธ ํ ๊ฐ์ ์์ธํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public Article getForPrintArticleById(int id) {
return articleDao.getForPrintArticleById(id);
}
//----------------------------------------------------------------------------------------------------
// ๊ฒ์ํ ๋ด์ ์ ์ฒด ๊ฒ์๊ธ์ ๊ฐ์๋ฅผ ๊ฐ์ ธ์ค๊ธฐ
public int getArticlesTotalCount(int boardId, String searchKeywordTypeCode, String searchKeyword) {
if (searchKeyword != null && searchKeyword.length() == 0) {
searchKeyword = null;
}
return articleDao.getArticlesTotalCount(boardId, searchKeywordTypeCode, searchKeyword);
}
// ๊ฒ์๊ธ๋ค์ ์์ธํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ(ForPrint๊ฐ ๋ถ์ผ๋ฉด ์์ธํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๋ ํจ์๋ก ๋ง๋ค์ด๋์)
public List<Article> getForPrintArticles(int boardId, String searchKeywordTypeCode, String searchKeyword,
int itemsCountInAPage, int page) {
if (searchKeyword != null && searchKeyword.length() == 0) {
searchKeyword = null;
}
int limitFrom = (page - 1) * itemsCountInAPage;
int limitTake = itemsCountInAPage;
return articleDao.getForPrintArticles(boardId, searchKeywordTypeCode, searchKeyword, limitFrom, limitTake);
}
//----------------------------------------------------------------------------------------------------
// ๊ฒ์๊ธ ์ฐ๊ธฐ
public ResultData writeArticle(Map<String, Object> param) {
articleDao.writeArticle(param);
int id = Util.getAsInt(param.get("id"), 0);
samFileService.changeInputFileRelIds(param, id);
return new ResultData("S-1", "๊ฒ์๋ฌผ์ด ์์ฑ๋์์ต๋๋ค.", "id", id);
}
// ๊ฒ์๊ธ ์ญ์ ํ๊ธฐ
public ResultData deleteArticleById(int id) {
Article article = getArticleById(id);
if (isEmpty(article)) {
return new ResultData("F-1", "๊ฒ์๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.", "id", id);
}
articleDao.deleteArticleById(id);
return new ResultData("S-1", id + "๋ฒ ๊ฒ์๋ฌผ์ด ์ญ์ ๋์์ต๋๋ค.", "id", id, "boardId", article.getBoardId());
}
//----------------------------------------------------------------------------------------------------
// ๊ฒ์๊ธ ์กฐํ์ 1์ฉ ์ฆ๊ฐํ๊ธฐ
public ResultData updateHitCountById(int id) {
Article article = getArticleById(id);
if(isEmpty(article)) {
return new ResultData("F-1", "๊ฒ์๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.", "id", id);
}
articleDao.updateHitCount(id);
return new ResultData("S-1", "๋๊ธ ์กฐํ์๊ฐ ์ฆ๊ฐ๋์์ต๋๋ค.", "id", id);
}
// ๊ฒ์๊ธ ์ข์์ 1์ฉ ์ฆ๊ฐํ๊ธฐ
public ResultData updateLikeCountById(int id) {
Article article = getArticleById(id);
if(isEmpty(article)) {
return new ResultData("F-1", "๊ฒ์๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.", "id", id);
}
articleDao.updateLikeCount(id);
return new ResultData("S-1", "์ข์์๊ฐ ์ฆ๊ฐ๋์์ต๋๋ค.", "id", id);
}
// ๊ฒ์๊ธ ์ซ์ด์ 1์ฉ ์ฆ๊ฐํ๊ธฐ
public ResultData updateDislikeCountById(int id) {
Article article = getArticleById(id);
if(isEmpty(article)) {
return new ResultData("F-1", "๊ฒ์๋ฌผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.", "id", id);
}
articleDao.updateDislikeCount(id);
return new ResultData("S-1", "์ซ์ด์๊ฐ ์ฆ๊ฐ๋์์ต๋๋ค.", "id", id);
}
//---------------------------------------------------------------------
// ๊ฒ์๊ธ ์์ ํ๊ธฐ
public ResultData modifyArticle(Map<String, Object> param) {
articleDao.modifyArticle(param);
int id = Util.getAsInt(param.get("id"), 0);
return new ResultData("S-1", "๊ฒ์๋ฌผ์ ์์ ํ์์ต๋๋ค.", "id", id);
}
//๊ฒ์๋ฌผ ์์ ์ ๊ถํ ์ฒดํฌ
public ResultData getActorCanModifyRd(Article article, Member member) {
if(article.getMemberId() == member.getId()) {
return new ResultData("S-1", "๊ฐ๋ฅํฉ๋๋ค.");
}
if(memberService.isAdmin(member)) {
return new ResultData("S-1", "๊ฐ๋ฅํฉ๋๋ค.");
}
return new ResultData("F-1", "๊ถํ์ด ์์ต๋๋ค.");
}
//๊ฒ์๊ธ ์ญ์ ์ ๊ถํ ์ฒดํฌ
public ResultData getActorCanDeleteRd(Article article, Member member) {
return getActorCanModifyRd(article, member); // ์ด์ฐจํผ ์ญ์ ๊ถํ์ด๋ ์์ ๊ถํ์ด๋ ๋น์ทํด์ ์ฌํ์ฉ ๊ฐ๊ฟ
}
}
<file_sep>/src/main/java/com/ezen/samsamoo/service/EtcInfoService.java
package com.ezen.samsamoo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ezen.samsamoo.dao.EtcInfoDao;
import com.ezen.samsamoo.dto.EtcInfo;
@Service
public class EtcInfoService {
@Autowired
private EtcInfoDao etcInfoDao;
//----------------------------------------------------------------------------------------------------
// relId, relTypeCode, typeCode, type2Code, expireDate๋ฅผ ์ด์ฉํด ๊ธฐํ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ
public EtcInfo get(String relTypeCode, int relId, String typeCode, String type2Code) {
return etcInfoDao.get(relTypeCode, relId, typeCode, type2Code);
}
// ํ์ผ ์ด๋ฆ์ ํตํด ํ์ผ์ ๋ํ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ค๊ธฐ ์ํ ํจ์
// ์์ปจ๋ "member__0__extra__profileImg__1"์ ๊ฒฝ์ฐ
// splitํ๋ฉด relTypeCode = member, reId = 0, typeCode = extra, type2Code = profileImg๊ฐ ๋๋ ๊ฒ์ด๋ค.
// ์์ฝํ์๋ฉด __ ๋จ์๋ก ์ชผ๊ฐ์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ธฐ ์ํ ํจ์์ด๋ค.
public EtcInfo get(String name) {
String[] nameBits = name.split("__");
String relTypeCode = nameBits[0];
int relId = Integer.parseInt(nameBits[1]);
String typeCode = nameBits[2];
String type2Code = nameBits[3];
return get(relTypeCode, relId, typeCode, type2Code);
}
//----------------------------------------------------------------------------------------------------
// relId, relTypeCode, typeCode, type2Code, expireDate๋ฅผ ์ด์ฉํด ๋ฐธ๋ฅ๊ฐ์ ๊ฐ์ ธ์ค๊ธฐ
public String getValue(String relTypeCode, int relId, String typeCode, String type2Code) {
String value = etcInfoDao.getValue(relTypeCode, relId, typeCode, type2Code);
if ( value == null ) {
return "";
}
return value;
}
public String getValue(String name) {
String[] nameBits = name.split("__");
String relTypeCode = nameBits[0];
int relId = Integer.parseInt(nameBits[1]);
String typeCode = nameBits[2];
String type2Code = nameBits[3];
return getValue(relTypeCode, relId, typeCode, type2Code);
}
//----------------------------------------------------------------------------------------------------
// relId, relTypeCode, typeCode, type2Code, expireDate์ etcInfo ๊ฐ์ฒด์ ์ ์ฅํ๊ธฐ
public int setValue(String relTypeCode, int relId, String typeCode, String type2Code, String value, String expireDate) {
etcInfoDao.setValue(relTypeCode, relId, typeCode, type2Code, value, expireDate);
EtcInfo etcInfo = get(relTypeCode, relId, typeCode, type2Code);
if (etcInfo != null) {
return etcInfo.getId();
}
return -1;
}
public int setValue(String name, String value, String expireDate) {
String[] nameBits = name.split("__");
String relTypeCode = nameBits[0];
int relId = Integer.parseInt(nameBits[1]);
String typeCode = nameBits[2];
String type2Code = nameBits[3];
return setValue(relTypeCode, relId, typeCode, type2Code, value, expireDate);
}
//----------------------------------------------------------------------------------------------------
// relId, relTypeCode, typeCode, type2Code, expireDate์ ์ด์ฉํด ๋ฐ์ดํฐ ์ญ์ ํ๊ธฐ
public int remove(String name) {
String[] nameBits = name.split("__");
String relTypeCode = nameBits[0];
int relId = Integer.parseInt(nameBits[1]);
String typeCode = nameBits[2];
String type2Code = nameBits[3];
return remove(relTypeCode, relId, typeCode, type2Code);
}
public int remove(String relTypeCode, int relId, String typeCode, String type2Code) {
return etcInfoDao.remove(relTypeCode, relId, typeCode, type2Code);
}
}
<file_sep>/src/main/java/com/ezen/samsamoo/dto/Reply.java
package com.ezen.samsamoo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Reply {
private int id; // ๋ฒํธ
private String regDate; // ์์ฑ ๋ ์ง
private String updateDate; // ์์ ๋ ์ง
private String relTypeCode; // ๊ด๋ จ ๋ฐ์ดํฐ ํ์
(ex: article, member)
private int relId; // ๊ด๋ จ ๋ฐ์ดํฐ ๋ฒํธ(ex: ๊ฒ์๊ธ id)
private int memberId; // ๋๊ธ์ด ํ์ id
private int parentId; // ๋ถ๋ชจ ๋๊ธ id
private String body; // ๋๊ธ ๋ด์ฉ
private boolean blindStatus; // ๋ธ๋ผ์ธ๋ ์ฌ๋ถ
private String blindDate; // ๋ธ๋ผ์ธ๋ ๋ ์ง
private boolean delStatus; // ์ญ์ ์ฌ๋ถ
private String delDate; // ์ญ์ ๋ ์ง
private int likeCount; // ์ข์์ ์
private int dislikeCount; //์ซ์ด์ ์
private String extra__writerName; // ๋๊ธ์ด ํ์ ๋๋ค์
// ๋๊ธ ๋ด์ฉ ๊ทธ๋๋ก ๊ฐ์ ธ์ค๋ ํจ์
// ๊ฐํ๋ฌธ์(\n์ <br/>๋ก ์นํ)
public String getBodyForPrint() {
String bodyForPrint = body.replaceAll("\r\n", "<br>");
bodyForPrint = bodyForPrint.replaceAll("\r", "<br>");
bodyForPrint = bodyForPrint.replaceAll("\n", "<br>");
return bodyForPrint;
}
// ํ๋กํ ์ด๋ฏธ์ง Uri ๊ฐ์ง๊ณ ์ค๊ธฐ
public String getWriterProfileImgUri() {
return "/common/samFile/file/member/" + memberId + "/extra/profileImg/1";
}
// ํ์ฌ ์์ ๋ ๋์ฒด ์ด๋ฏธ์ง
public String getWriterProfileFallbackImgUri() {
return "/resource/img/profileNongdamgom";
}
// ๋์ฒด ์ด๋ฏธ์ง๋ฅผ html์ ์ฝ์
ํ๊ธฐ ์ํ ๋ฉ์๋
public String getWriterProfileFallbackImgOnErrorHtmlAttr() {
return "this.src = '" + getWriterProfileFallbackImgUri() + "'";
}
}<file_sep>/src/main/java/com/ezen/samsamoo/dao/SamFileDao.java
package com.ezen.samsamoo.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.ezen.samsamoo.dto.SamFile;
import java.util.List;
import java.util.Map;
@Mapper
public interface SamFileDao {
// ์
๋ก๋๋ ํ์ผ์ ๋ฉํ์ ๋ณด๋ฅผ DB์ ์ ์ฅ
void saveMeta(Map<String, Object> param);
// ํ์ผ ๋ฐ์ดํฐ ๊ฐ์ง๊ณ ์ค๊ธฐ
SamFile getSamFile(@Param("relTypeCode") String relTypeCode, @Param("relId") int relId,
@Param("typeCode") String typeCode, @Param("type2Code") String type2Code, @Param("fileNo") int fileNo);
// ํ์ผ ๋ฒํธ๋ฅผ ์ด์ฉํด ํ์ผ ๋ฐ์ดํฐ ๊ฐ์ง๊ณ ์ค๊ธฐ
SamFile getSamFileById(@Param("id") int id);
// ํ์ผ๋ค ์ฌ๋ฌ ๊ฐ ๊ฐ์ง๊ณ ์ค๊ธฐ
List<SamFile> getSamFiles(@Param("relTypeCode") String relTypeCode, @Param("relId") int relId,
@Param("typeCode") String typeCode, @Param("type2Code") String type2Code);
// ๊ด๋ จํ์
์ฝ๋์ ๊ด๋ จ ๋ฐ์ดํฐ ๋ฒํธ๋ฅผ ์ด์ฉํด ํ์ผ๋ค ์ฌ๋ฌ ๊ฐ ๊ฐ์ง๊ณ ์ค๊ธฐ
List<SamFile> getSamFilesByRelTypeCodeAndRelId(@Param("relTypeCode") String relTypeCode, @Param("relId") int relId);
// ๊ด๋ จ ํ์
์ฝ๋, ๊ด๋ จ ๋ฐ์ดํฐ ๋ฒํธ, ํ์
์ฝ๋, ํ์
2์ฝ๋๋ฅผ ์ด์ฉํด์ ํ์ผ๋ค ๊ฐ์ง๊ณ ์ค๊ธฐ( dao.xml์์ ์ฟผ๋ฆฌ ๋ณด๋ฉด ์ฝ๊ฒ ์ดํดํ ์ ์์)
List<SamFile> getSamFilesRelTypeCodeAndRelIdsAndTypeCodeAndType2Code(@Param("relTypeCode") String relTypeCode,
@Param("relIds") List<Integer> relIds, @Param("typeCode") String typeCode,
@Param("type2Code") String type2Code);
// ๊ด๋ จ ๋ฐ์ดํฐ๋ฒํธ ๋ฐ๊พธ๊ธฐ
void changeRelId(@Param("id") int id, @Param("relId") int relId);
// ํ์ผ ์ญ์ ํ๊ธฐ
void deleteFile(@Param("id") int id);
// ํ์ผ๋ค ์ญ์ ํ๊ธฐ
void deleteFiles(@Param("relTypeCode") String relTypeCode, @Param("relId") int relId);
}
<file_sep>/src/main/java/com/ezen/samsamoo/dto/Board.java
package com.ezen.samsamoo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public
class Board {
private int id; // ๊ฒ์ํ ๋ฒํธ
private String regDate; // ์์ฑ๋ ์ง
private String updateDate; // ์์ ๋ ์ง
private String code; //์ฝ๋
private String name; //์ด๋ฆ
private boolean delStatus; // ๋ธ๋ผ์ธ๋ ์ฌ๋ถ
private String delDate; // ๋ธ๋ผ์ด๋ ๋ ์ง
private int hitCount; // ์กฐํ์
private int repliesCount; // ๋๊ธ์
private int likeCount; // ์ข์์์
private int dislikeCount; // ์ซ์ด์์
}<file_sep>/src/main/java/com/ezen/samsamoo/config/WebMvcConfig.java
package com.ezen.samsamoo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.ezen.samsamoo.interceptor.BeforeActionInterceptor;
import com.ezen.samsamoo.interceptor.NeedAdminInterceptor;
import com.ezen.samsamoo.interceptor.NeedToLoginInterceptor;
import com.ezen.samsamoo.interceptor.NeedToLogoutInterceptor;
// WebMvcConfig์๋ค๊ฐ ์ค์ ์ ํ๋ฉด์ ์ฌ๊ธฐ์ ์๋ ์ค์ ์ ์คํ๋ง ๋ถํธ๊ฐ ์ฝ๋๋ค.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
BeforeActionInterceptor beforeActionInterceptor;
@Autowired
NeedToLoginInterceptor needToLoginInterceptor;
@Autowired
NeedAdminInterceptor needAdminInterceptor;
@Autowired
NeedToLogoutInterceptor needToLogoutInterceptor;
@Value("${custom.samFileDirPath}")
private String samFileDirPath;
//CORS ํ์ฉ
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
// ์ธํฐ์
ํฐ๋ฅผ ์ ์ฉํ๋ ์ญํ ์ ๋ด๋น
@Override
public void addInterceptors(InterceptorRegistry registry) {
// beforeActionInterceptor -> ๋ชจ๋ ์ก์
์คํ์ ์ ์คํ๋๋๋ก ์ฒ๋ฆฌ
registry.addInterceptor(beforeActionInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/resource/**")
.excludePathPatterns("/sam/**")
.excludePathPatterns("/error");
// ๋ก๊ทธ์ธ์ด ํ์ํ ๊ฒฝ์ฐ
registry.addInterceptor(needToLoginInterceptor)
.addPathPatterns("/usr/article/write")
.addPathPatterns("/usr/article/doWrite")
.addPathPatterns("/usr/article/doDelete")
.addPathPatterns("/usr/article/modify")
.addPathPatterns("/usr/article/doModify")
.addPathPatterns("/usr/reply/doWrite")
.addPathPatterns("/usr/reply/doDelete")
.addPathPatterns("/usr/reply/doDeleteAjax")
.addPathPatterns("/usr/reply/modify")
.addPathPatterns("/usr/reply/doModify")
.addPathPatterns("/usr/member/modify")
.addPathPatterns("/usr/member/doModify")
.addPathPatterns("/usr/member/checkPassword")
.addPathPatterns("/usr/member/doCheckPassword")
.excludePathPatterns("/resource/**")
.excludePathPatterns("/sam/**");
// ๋ก๊ทธ์์์ด ํ์ํ ๊ฒฝ์ฐ
registry.addInterceptor(needToLogoutInterceptor)
.addPathPatterns("/usr/member/findLoginId")
.addPathPatterns("/usr/member/doFindLoginId")
.addPathPatterns("/usr/member/findLoginPw")
.addPathPatterns("/usr/member/doFindLoginPw")
.addPathPatterns("/usr/member/login")
.addPathPatterns("/usr/member/doLogin")
.addPathPatterns("/usr/member/getLoginIdDup")
.addPathPatterns("/usr/member/join")
.addPathPatterns("/usr/member/doJoin")
.addPathPatterns("/usr/member/findLoginId")
.addPathPatterns("/usr/member/doFindLoginId")
.addPathPatterns("/usr/member/findLoginPw")
.addPathPatterns("/usr/member/doFindLoginPw")
.excludePathPatterns("/resource/**")
.excludePathPatterns("/sam/**");
// ์ด๋๋ฏผ ํ์
registry.addInterceptor(needAdminInterceptor)
.addPathPatterns("/adm/**")
.excludePathPatterns("/adm/member/findLoginId")
.excludePathPatterns("/adm/member/doFindLoginId")
.excludePathPatterns("/adm/member/findLoginPw")
.excludePathPatterns("/adm/member/doFindLoginPw")
.excludePathPatterns("/adm/member/login")
.excludePathPatterns("/adm/member/doLogin")
.excludePathPatterns("/adm/member/getLoginIdDup")
.excludePathPatterns("/adm/member/join")
.excludePathPatterns("/adm/member/doJoin")
.excludePathPatterns("/adm/member/findLoginId")
.excludePathPatterns("/adm/member/doFindLoginId")
.excludePathPatterns("/adm/member/findLoginPw")
.excludePathPatterns("/adm/member/doFindLoginPw")
.excludePathPatterns("/resource/**")
.excludePathPatterns("/sam/**");
registry.addInterceptor(needToLogoutInterceptor)
.addPathPatterns("/adm/member/findLoginId")
.addPathPatterns("/adm/member/doFindLoginId")
.addPathPatterns("/adm/member/findLoginPw")
.addPathPatterns("/adm/member/doFindLoginPw")
.addPathPatterns("/adm/member/login")
.addPathPatterns("/adm/member/doLogin")
.addPathPatterns("/adm/member/getLoginIdDup")
.addPathPatterns("/adm/member/join")
.addPathPatterns("/adm/member/doJoin")
.addPathPatterns("/adm/member/findLoginId")
.addPathPatterns("/adm/member/doFindLoginId")
.addPathPatterns("/adm/member/findLoginPw")
.addPathPatterns("/adm/member/doFindLoginPw")
.excludePathPatterns("/resource/**")
.excludePathPatterns("/sam/**");
}
// ์ ์ ๋ฆฌ์์ค ์ ๊ทผํ๊ธฐ ์ํ ๊ฒฝ๋ก ์ค์
// ResourceHandlerRegistry -> ๋ฆฌ์์ค ๋ฑ๋ก ๋ฐ ํธ๋ค๋ฌ๋ฅผ ๊ด๋ฆฌํ๋ ๊ฐ์ฒด
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/sam/**") // ๋ฆฌ์์ค์ ๋งค์นญ๋ url ๋ฑ๋ก
.addResourceLocations("file:///" + samFileDirPath + "/") // ๋ฆฌ์์ค์ ์์น ๋ฑ๋ก
.setCachePeriod(20); // ์บ์๊ฐ ์ผ๋ง๋ ์ง์ํ ์ง ์ ํ๋ ๋ฉ์๋ (20์ด๋ก ์ค์ )
}
}
<file_sep>/src/main/java/com/ezen/samsamoo/dto/EtcInfo.java
package com.ezen.samsamoo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
// ๋ถ๊ฐ ์ ๋ณด ํ
์ด๋ธ
// ๋ฉ์ธ์ ๋ค์ด๊ฐ๊ธฐ๋ ์์ฝ๊ณ ๊ทธ๋ฌ๋ ์์ผ๋ฉด ์๋๋ ์ฉ๋ฆฌ ์ ๋ณด๋ค
// ์์ปจ๋ ์ด๋ค ํ์์ด ๊ฐ์ฅ ์ต๊ทผ์ ์ธ์ ์ ์ง๋ฅผ ๋นํ๋์ง์ ๊ฐ์ ์ ๋ณด๋ฅผ ์ ์ฅํ๊ธฐ ์ํด์
// member ํ
์ด๋ธ์ ์นผ๋ผ์ ํ๋ ๋ง๋๋ฉด ๊ทธ๊ฑด ๋๋ฌด ๋ฐ์ดํฐ ๋ญ๋น๊ฐ ํฌ๋ค
// ๋ฐ๋ผ์ ์ด๋ฌํ ์ฌ์ํ ๊ธฐ๋ก์ ๋จ๊ธฐ๊ธฐ ์ํด ๋ง๋ ํ
์ด๋ธ์ด ๋ฐ๋ก EtcInfo ํ
์ด๋ธ์ด๋ค.
// ๋ค์์ ํ
์ด๋ธ์ ๋ฐ์ดํฐ๋ฅผ ๋ด๊ธฐ ์ํด ์กด์ฌํ๋ค.
public class EtcInfo {
private int id; // ๋ถ๊ฐ ์ ๋ณด ํ
์ด๋ธ ๋ฒํธ
private String regDate; // ์์ฑ ์ผ์
private String updateDate; // ์์ ์ผ์
private String expireDate; // ๋ง๋ฃ ์ผ์
private String relTypeCode; // ๊ด๋ จํ์
์ฝ๋ -> ์ด ํ
์ด๋ธ์ ๋ค์ด๊ฐ๋ ๋ฐ์ดํฐ๊ฐ ์จ๊ฐ ์ก๊ฒ๋ค(ex: member)์ด ๋ค ๋ค์ด๊ฐ๊ธฐ๋๋ฌธ์ ๊ตฌ๋ถ์ ํด์ฃผ๊ธฐ ์ํด ์กด์ฌ
private int relId; // ๊ด๋ จ๋ฒํธ // ex: 1
private String typeCode; // ํ์
์ฝ๋ -> ๋๋ถ๋ฅ(ex: extra(๋ถ๊ฐ์ ๋ณด))
private String type2Code; //ํ์
2์ฝ๋ -> ์๋ถ๋ฅ(ex: modifyPrivateAuthCode)
private String value; // ex: 1234
// ๋ฐ๋ผ์ ์ด ๊ฒฝ์ฐ์๋
/* INSERT INTO attr
* SET regDate = NOW(),
* updateDate = NOW(),
* relTypeCode = 'member',
* relId = 1,
* typeCode = 'extra',
* type2Code = 'modifyPrivateAuthCode',
* `value` = '1234',
* expireDate = '2021-07-17 17:00:50'; ์ง๊ธ ์๊ฐ์ด 16:00:00์ด๋ผ๋ฉด 1์๊ฐ ์ง๋ฆฌ ์ธ์ฆ์ฝ๋๋ฅผ ๋ฐ๊ธํด์ค์
*
* -> 1๋ฒ ํ์์ด ํ์์ ๋ณด๋ฅผ ์์ ํ๊ธฐ ์ํด ๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํ๊ณ ์๋ฒ์ชฝ์์ ๋น๋ฐ๋ฒํธ๋ฅผ ์ฒดํฌ ํํ
* ํ ์๊ฐ ์ง๋ฆฌ authCode(์ธ์ฆ์ฝ๋)๋ฅผ ๋ฐ๊ธํด์ค๋ค.
*/
}
<file_sep>/src/main/java/com/ezen/samsamoo/controller/UsrHomeController.java
package com.ezen.samsamoo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UsrHomeController {
// ๋ฉ์ธํ์ด์ง๋ก ๋ฆฌ๋ค์ด๋ ํธ
@RequestMapping("/")
public String showMainRoot() {
return "redirect:/usr/home/main";
}
// ๋ฉ์ธํ์ด์ง uri
@RequestMapping("/usr/home/main")
public String showMain() {
return "usr/home/main";
}
} | 8cc01e4855f4c6e06c0243b9db56e87228709e7d | [
"Java"
] | 10 | Java | cookieplz/samsamoo | 4ef5bc0945a115706f1668fff195bbcabafde913 | 03b639e363984ce2377f676c340195686c4583fc |
refs/heads/master | <repo_name>Lukaschen1986/reproducible_pro1<file_sep>/PA1_template.Rmd
---
title: "PA1_template"
output: html_document
---
# PA1_template
## Loading and preprocessing the data
```{r}
getwd()
setwd("D:/R//Data Science/lesson5/pro1")
df <- read.csv(file = "activity.csv", header = T)
head(df)
summary(df)
str(df)
```
## What is mean total number of steps taken per day?
### 1. Calculate the total number of steps taken per day
```{r}
steps_per_day <- aggregate(df[c("steps")], list(date = df$date), FUN = sum, na.rm = T)
steps_per_day
```
### 2. Make a histogram of the total number of steps taken each day
```{r}
hist(steps_per_day$steps, col = "red", xlab = "Steps", main = "Histogram of Total Number of Steps Each Day")
rug(steps_per_day$steps)
```
### 3. Calculate and report the mean and median of the total number of steps taken per day
```{r}
mean(steps_per_day$steps)
median(steps_per_day$steps)
```
## What is the average daily activity pattern?
### 1. Make a time series plot
```{r}
average_number_of_steps <- aggregate(df[c("steps")], list(interval = df$interval), FUN = mean, na.rm = T)
with(average_number_of_steps, plot(interval, steps, type = "l", col = "red"))
legend("topright", lwd = 1, col = "red", legend = c("steps"))
```
### 2. the 5-minute interval which contains the maximum number of steps
```{r}
average_number_of_steps$interval[which.max(average_number_of_steps$steps)]
```
## Imputing missing values
### 1. Calculate and report the total number of missing values
```{r}
sum(is.na(df))
```
### 2. a strategy for imputing missing data
```{r}
df_2 <- merge(df, average_number_of_steps, by = c("interval"))
library(dplyr)
df_arrange <- arrange(df_2, steps.x)
df_NoNA <- df_arrange[1:15264,]
df_NA <- df_arrange[15265:17568,]
df_NA$steps.x <- df_NA$steps.y
```
### 3. a new dataset with the missing data filled in
```{r}
df_new <- rbind(df_NoNA, df_NA)
df_new$steps.y <- NULL
sum(is.na(df_new))
```
### 4. Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day.
```{r}
steps_per_day_NoNA <- aggregate(df_new[c("steps.x")], list(date = df_new$date), FUN = sum, na.rm = T)
hist(steps_per_day_NoNA$steps.x, col = "red", xlab = "Steps", main = "Histogram of Total Number of Steps Each Day")
rug(steps_per_day_NoNA$steps.x)
mean(steps_per_day_NoNA$steps.x)
median(steps_per_day_NoNA$steps.x)
```
## Are there differences in activity patterns between weekdays and weekends?
### 1. Create a new factor variable in the dataset with two levels
```{r}
df_new$date <- as.Date(df_new$date)
df_new$weekday <- format(df_new$date, format = "%a")
df_new$weekday.2[df_new$weekday == "Mon"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Tue"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Wed"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Thu"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Fri"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Sat"] <- "weekend"
df_new$weekday.2[df_new$weekday == "Sun"] <- "weekend"
table(df_new$weekday.2)
```
### 2. Make a panel plot containing a time series plot
```{r}
average_number_of_steps_weekday <- aggregate(df_new[c("steps.x")], list(interval = df_new$interval, weekday = df_new$weekday.2), FUN = mean, na.rm = T)
library(ggplot2)
ggplot(average_number_of_steps_weekday, aes(x = interval, y = steps.x)) + geom_line(aes(color = weekday)) + facet_grid(weekday ~ .)
```
<file_sep>/doc/PA1_template.R
# Loading and preprocessing the data
getwd()
setwd("D:/R//Data Science/lesson5/pro1")
df <- read.csv(file = "activity.csv", header = T)
head(df)
summary(df)
str(df)
# 1 What is mean total number of steps taken per day?
## 1.1 Calculate the total number of steps taken per day
steps_per_day <- aggregate(df[c("steps")], list(date = df$date), FUN = sum, na.rm = T)
steps_per_day
## 1.2 Make a histogram of the total number of steps taken each day
hist(steps_per_day$steps, col = "red", xlab = "Steps", main = "Histogram of Total Number of Steps Each Day")
rug(steps_per_day$steps)
## 1.3 Calculate and report the mean and median of the total number of steps taken per day
mean(steps_per_day$steps)
median(steps_per_day$steps)
# 2 What is the average daily activity pattern?
## 2.1 Make a time series plot
average_number_of_steps <- aggregate(df[c("steps")], list(interval = df$interval), FUN = mean, na.rm = T)
with(average_number_of_steps, plot(interval, steps, type = "l", col = "red"))
legend("topright", lwd = 1, col = "red", legend = c("steps"))
## 2.2 the 5-minute interval which contains the maximum number of steps
average_number_of_steps$interval[which.max(average_number_of_steps$steps)]
# 3 Imputing missing values
## 3.1 Calculate and report the total number of missing values
sum(is.na(df))
## 3.2 a strategy for imputing missing data
df_2 <- merge(df, average_number_of_steps, by = c("interval"))
library(dplyr)
df_arrange <- arrange(df_2, steps.x)
df_NoNA <- df_arrange[1:15264,]
df_NA <- df_arrange[15265:17568,]
df_NA$steps.x <- df_NA$steps.y
## 3.3 a new dataset with the missing data filled in
df_new <- rbind(df_NoNA, df_NA)
df_new$steps.y <- NULL
sum(is.na(df_new))
## 3.4 Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day.
steps_per_day_NoNA <- aggregate(df_new[c("steps.x")], list(date = df_new$date), FUN = sum, na.rm = T)
hist(steps_per_day_NoNA$steps.x, col = "red", xlab = "Steps", main = "Histogram of Total Number of Steps Each Day")
rug(steps_per_day_NoNA$steps.x)
mean(steps_per_day_NoNA$steps.x)
median(steps_per_day_NoNA$steps.x)
# 4 Are there differences in activity patterns between weekdays and weekends?
## 4.1 Create a new factor variable in the dataset with two levels
df_new$date <- as.Date(df_new$date)
df_new$weekday <- format(df_new$date, format = "%a")
df_new$weekday.2[df_new$weekday == "Mon"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Tue"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Wed"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Thu"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Fri"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Sat"] <- "weekend"
df_new$weekday.2[df_new$weekday == "Sun"] <- "weekend"
table(df_new$weekday.2)
## 4.2 Make a panel plot containing a time series plot
average_number_of_steps_weekday <- aggregate(df_new[c("steps.x")], list(interval = df_new$interval, weekday = df_new$weekday.2), FUN = mean, na.rm = T)
library(ggplot2)
ggplot(average_number_of_steps_weekday, aes(x = interval, y = steps.x)) + geom_line(aes(color = weekday)) + facet_grid(weekday ~ .)
library(knitr)
knit2html("PA1_template.Rmd")
<file_sep>/README.md
# reproducible_pro1
## PA1_template.Rmd is in the "master" branch
## PA1_template.md and PA1_template.html are in "doc"
## All the plots are in "figure"
<file_sep>/doc/PA1_template.md
---
title: "PA1_template"
output: html_document
---
# PA1_template
## Loading and preprocessing the data
```r
getwd()
```
```
## [1] "D:/R/Data Science/lesson5/pro1"
```
```r
setwd("D:/R//Data Science/lesson5/pro1")
df <- read.csv(file = "activity.csv", header = T)
head(df)
```
```
## steps date interval
## 1 NA 2012-10-01 0
## 2 NA 2012-10-01 5
## 3 NA 2012-10-01 10
## 4 NA 2012-10-01 15
## 5 NA 2012-10-01 20
## 6 NA 2012-10-01 25
```
```r
summary(df)
```
```
## steps date interval
## Min. : 0.00 2012-10-01: 288 Min. : 0.0
## 1st Qu.: 0.00 2012-10-02: 288 1st Qu.: 588.8
## Median : 0.00 2012-10-03: 288 Median :1177.5
## Mean : 37.38 2012-10-04: 288 Mean :1177.5
## 3rd Qu.: 12.00 2012-10-05: 288 3rd Qu.:1766.2
## Max. :806.00 2012-10-06: 288 Max. :2355.0
## NA's :2304 (Other) :15840
```
```r
str(df)
```
```
## 'data.frame': 17568 obs. of 3 variables:
## $ steps : int NA NA NA NA NA NA NA NA NA NA ...
## $ date : Factor w/ 61 levels "2012-10-01","2012-10-02",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ interval: int 0 5 10 15 20 25 30 35 40 45 ...
```
## What is mean total number of steps taken per day?
### 1. Calculate the total number of steps taken per day
```r
steps_per_day <- aggregate(df[c("steps")], list(date = df$date), FUN = sum, na.rm = T)
steps_per_day
```
```
## date steps
## 1 2012-10-01 0
## 2 2012-10-02 126
## 3 2012-10-03 11352
## 4 2012-10-04 12116
## 5 2012-10-05 13294
## 6 2012-10-06 15420
## 7 2012-10-07 11015
## 8 2012-10-08 0
## 9 2012-10-09 12811
## 10 2012-10-10 9900
## 11 2012-10-11 10304
## 12 2012-10-12 17382
## 13 2012-10-13 12426
## 14 2012-10-14 15098
## 15 2012-10-15 10139
## 16 2012-10-16 15084
## 17 2012-10-17 13452
## 18 2012-10-18 10056
## 19 2012-10-19 11829
## 20 2012-10-20 10395
## 21 2012-10-21 8821
## 22 2012-10-22 13460
## 23 2012-10-23 8918
## 24 2012-10-24 8355
## 25 2012-10-25 2492
## 26 2012-10-26 6778
## 27 2012-10-27 10119
## 28 2012-10-28 11458
## 29 2012-10-29 5018
## 30 2012-10-30 9819
## 31 2012-10-31 15414
## 32 2012-11-01 0
## 33 2012-11-02 10600
## 34 2012-11-03 10571
## 35 2012-11-04 0
## 36 2012-11-05 10439
## 37 2012-11-06 8334
## 38 2012-11-07 12883
## 39 2012-11-08 3219
## 40 2012-11-09 0
## 41 2012-11-10 0
## 42 2012-11-11 12608
## 43 2012-11-12 10765
## 44 2012-11-13 7336
## 45 2012-11-14 0
## 46 2012-11-15 41
## 47 2012-11-16 5441
## 48 2012-11-17 14339
## 49 2012-11-18 15110
## 50 2012-11-19 8841
## 51 2012-11-20 4472
## 52 2012-11-21 12787
## 53 2012-11-22 20427
## 54 2012-11-23 21194
## 55 2012-11-24 14478
## 56 2012-11-25 11834
## 57 2012-11-26 11162
## 58 2012-11-27 13646
## 59 2012-11-28 10183
## 60 2012-11-29 7047
## 61 2012-11-30 0
```
### 2. Make a histogram of the total number of steps taken each day
```r
hist(steps_per_day$steps, col = "red", xlab = "Steps", main = "Histogram of Total Number of Steps Each Day")
rug(steps_per_day$steps)
```

### 3. Calculate and report the mean and median of the total number of steps taken per day
```r
mean(steps_per_day$steps)
```
```
## [1] 9354.23
```
```r
median(steps_per_day$steps)
```
```
## [1] 10395
```
## What is the average daily activity pattern?
### 1. Make a time series plot
```r
average_number_of_steps <- aggregate(df[c("steps")], list(interval = df$interval), FUN = mean, na.rm = T)
with(average_number_of_steps, plot(interval, steps, type = "l", col = "red"))
legend("topright", lwd = 1, col = "red", legend = c("steps"))
```

### 2. the 5-minute interval which contains the maximum number of steps
```r
average_number_of_steps$interval[which.max(average_number_of_steps$steps)]
```
```
## [1] 835
```
## Imputing missing values
### 1. Calculate and report the total number of missing values
```r
sum(is.na(df))
```
```
## [1] 2304
```
### 2. a strategy for imputing missing data
```r
df_2 <- merge(df, average_number_of_steps, by = c("interval"))
library(dplyr)
df_arrange <- arrange(df_2, steps.x)
df_NoNA <- df_arrange[1:15264,]
df_NA <- df_arrange[15265:17568,]
df_NA$steps.x <- df_NA$steps.y
```
### 3. a new dataset with the missing data filled in
```r
df_new <- rbind(df_NoNA, df_NA)
df_new$steps.y <- NULL
sum(is.na(df_new))
```
```
## [1] 0
```
### 4. Make a histogram of the total number of steps taken each day and Calculate and report the mean and median total number of steps taken per day.
```r
steps_per_day_NoNA <- aggregate(df_new[c("steps.x")], list(date = df_new$date), FUN = sum, na.rm = T)
hist(steps_per_day_NoNA$steps.x, col = "red", xlab = "Steps", main = "Histogram of Total Number of Steps Each Day")
rug(steps_per_day_NoNA$steps.x)
```

```r
mean(steps_per_day_NoNA$steps.x)
```
```
## [1] 10766.19
```
```r
median(steps_per_day_NoNA$steps.x)
```
```
## [1] 10766.19
```
## Are there differences in activity patterns between weekdays and weekends?
### 1. Create a new factor variable in the dataset with two levels
```r
df_new$date <- as.Date(df_new$date)
df_new$weekday <- format(df_new$date, format = "%a")
df_new$weekday.2[df_new$weekday == "Mon"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Tue"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Wed"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Thu"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Fri"] <- "weekday"
df_new$weekday.2[df_new$weekday == "Sat"] <- "weekend"
df_new$weekday.2[df_new$weekday == "Sun"] <- "weekend"
table(df_new$weekday.2)
```
```
##
## weekday weekend
## 12960 4608
```
### 2. Make a panel plot containing a time series plot
```r
average_number_of_steps_weekday <- aggregate(df_new[c("steps.x")], list(interval = df_new$interval, weekday = df_new$weekday.2), FUN = mean, na.rm = T)
library(ggplot2)
ggplot(average_number_of_steps_weekday, aes(x = interval, y = steps.x)) + geom_line(aes(color = weekday)) + facet_grid(weekday ~ .)
```

| a3331d1015c4be1de34b6af75db8002406faa414 | [
"Markdown",
"R",
"RMarkdown"
] | 4 | RMarkdown | Lukaschen1986/reproducible_pro1 | ccd8ab8f2301b9919674a64fc1703c7b4219c08c | 75f86844eb6a0c8d908029aabe918c8f34ad3f67 |
refs/heads/master | <file_sep>define(['react', 'jsx!Component'], function(React, Component) {
var AggregateComponent = React.createClass({
render: function() {
return <ul>
<li><Component name="Component1" /></li>
<li><Component name="Component2" /></li>
</ul>;
}
});
return AggregateComponent;
})
<file_sep>define(["noDependencies"], function(nodeps) {
return "depends on <" + nodeps + ">";
})
<file_sep>package org.araqnid.testbed.jreact;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.inject.Qualifier;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service;
import com.google.common.util.concurrent.ServiceManager;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
public class AppConfigModule extends AbstractModule {
private static final Logger LOG = LoggerFactory.getLogger(AppConfigModule.class);
private final Map<String, String> environment;
public AppConfigModule(Map<String, String> environment) {
this.environment = ImmutableMap.copyOf(environment);
}
@Override
protected void configure() {
bindConstant().annotatedWith(JettyModule.Port.class).to(getenv("PORT").orElse("61030"));
install(new JettyModule());
}
@Provides
@Version
public String appVersion() {
return Optional.ofNullable(AppConfigModule.class.getPackage().getImplementationVersion()).orElse("0.0.0");
}
@Provides
@Singleton
public ServiceManager serviceManager(@Managed Set<Service> services, @Version String appVersion) {
ServiceManager serviceManager = new ServiceManager(services);
serviceManager.addListener(new ServiceManager.Listener() {
@Override
public void stopped() {
}
@Override
public void healthy() {
LOG.info("Started {}", appVersion);
}
@Override
public void failure(Service service) {
System.exit(1);
}
}, MoreExecutors.directExecutor());
return serviceManager;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD })
@Qualifier
@Documented
public @interface Version {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD })
@Qualifier
@Documented
public @interface Managed {
}
private Optional<String> getenv(String key) {
return Optional.ofNullable(environment.get(key));
}
}
<file_sep>define([], function() {
return "emptyDependencies module";
})
<file_sep>define(['react'], function(React) {
var Component = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired
},
getDefaultProps: function() {
return {
name: "Component"
};
},
render: function() {
return <div>{ this.props.name } content</div>;
}
});
return Component;
})
<file_sep>rootProject.name='nashorn-react-rendering'
<file_sep>package org.araqnid.testbed.jreact;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Qualifier;
import javax.inject.Singleton;
import org.araqnid.testbed.jreact.AppConfigModule.Managed;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;
import com.google.common.reflect.ClassPath;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.Service;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.multibindings.Multibinder;
public class JettyModule extends AbstractModule {
@Override
protected void configure() {
managedServices().addBinding().to(JettyService.class);
}
@Provides
@Singleton
public Server jettyServer(@Port int port, Handler handler) {
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(port);
server.addConnector(connector);
server.setHandler(handler);
return server;
}
@Provides
public Handler handler(@Named("webappRoot") Resource webappRoot) {
ServletContextHandler servletContextHandler = new ServletContextHandler();
servletContextHandler.setBaseResource(webappRoot);
servletContextHandler.addServlet(DefaultServlet.class, "/*");
return servletContextHandler;
}
@Provides
@Named("webappRoot")
@Singleton
public Resource webappRoot() throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
return new EmbeddedResource(classLoader, "web", ClassPath.from(classLoader));
}
private Multibinder<Service> managedServices() {
return Multibinder.newSetBinder(binder(), Service.class, Managed.class);
}
public static class JettyService extends AbstractIdleService {
private final Server server;
@Inject
public JettyService(Server server) {
this.server = server;
}
@Override
protected void startUp() throws Exception {
server.start();
}
@Override
protected void shutDown() throws Exception {
server.stop();
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD })
@Qualifier
@Documented
public @interface Port {
}
}
<file_sep>package org.araqnid.testbed.jreact;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import jdk.nashorn.api.scripting.JSObject;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.junit.Ignore;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.CharSource;
import com.google.common.io.Resources;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
public class InvokeReactTest {
private final ScriptEngineManager engineManager = new ScriptEngineManager();
private final ScriptEngine nashornEngine = engineManager.getEngineByName("nashorn");
private final Invocable nashornInvoker = (Invocable) nashornEngine;
@Test
public void react_can_be_loaded() throws Exception {
nashornEngine.eval("global = {};");
loadScript("react-with-addons");
assertThat(nashornEngine.eval("global.React.version"), equalTo(ReactResources.REACT_VERSION));
}
@Test
public void jsx_transformer_can_be_loaded() throws Exception {
nashornEngine.eval("global = {};");
loadScript("JSXTransformer");
assertThat(nashornEngine.eval("global.JSXTransformer"), not(nullValue()));
}
@Test
public void renders_static_element() throws Exception {
nashornEngine.eval("global = {};");
loadScript("react-with-addons");
Object jsReact = nashornEngine.eval("global.React");
Object element = nashornInvoker.invokeMethod(jsReact, "createElement", "div", null, "Static content");
Object renderOutput = nashornInvoker.invokeMethod(jsReact, "renderToStaticMarkup", element);
assertThat(renderOutput, equalTo("<div>Static content</div>"));
}
@Test
public void renders_static_element_with_react_ids() throws Exception {
nashornEngine.eval("global = {};");
loadScript("react-with-addons");
Object jsReact = nashornEngine.eval("global.React");
Object element = nashornInvoker.invokeMethod(jsReact, "createElement", "div", null, "Static content");
Object renderOutput = nashornInvoker.invokeMethod(jsReact, "renderToString", element);
assertThat((String) renderOutput,
matches("<div data-reactid=\"[^\"]+\" data-react-checksum=\"-?[0-9]+\">Static content</div>"));
}
@Test
public void renders_static_component() throws Exception {
nashornEngine.eval("global = {};");
loadScript("react-with-addons");
Object jsReact = nashornEngine.eval("global.React");
Object componentBody = nashornEngine
.eval("(function(){ return { render: function() { return global.React.createElement(\"div\", {}, \"Component content\") } } })()");
Object component = nashornInvoker.invokeMethod(jsReact, "createClass", componentBody);
Object renderElement = nashornInvoker.invokeMethod(jsReact, "createElement", component);
Object renderOutput = nashornInvoker.invokeMethod(jsReact, "renderToStaticMarkup", renderElement);
assertThat(renderOutput, equalTo("<div>Component content</div>"));
}
@Test
public void renders_component_with_data_from_props() throws Exception {
nashornEngine.eval("global = {};");
String str = "xyzzyString";
Object rawProps = ImmutableMap.of("content", str);
Json json = nashornInvoker.getInterface(nashornEngine.getBindings(ScriptContext.ENGINE_SCOPE).get("JSON"),
Json.class);
JSObject props = json.parse(new ObjectMapper().writeValueAsString(rawProps));
loadScript("react-with-addons");
Object jsReact = nashornEngine.eval("global.React");
Object componentBody = nashornEngine
.eval("(function(){ return { render: function() { return global.React.createElement(\"div\", {}, \"content: \" + this.props.content) } } })()");
Object component = nashornInvoker.invokeMethod(jsReact, "createClass", componentBody);
Object renderElement = nashornInvoker.invokeMethod(jsReact, "createElement", component, props);
Object renderOutput = nashornInvoker.invokeMethod(jsReact, "renderToStaticMarkup", renderElement);
assertThat(renderOutput, equalTo("<div>content: " + str + "</div>"));
}
@Test
public void transforms_jsx_source() throws Exception {
nashornEngine.eval("global = {};");
loadScript("JSXTransformer");
JSXTransformer jsxTransformer = nashornInvoker.getInterface(nashornEngine.eval("global.JSXTransformer"),
JSXTransformer.class);
String source = "var content = <Content>foo</Content>;";
JSObject transformOutput = jsxTransformer.transform(source);
assertThat(transformOutput.keySet(), equalTo(ImmutableSet.of("code")));
assertThat(transformOutput.getMember("code"),
equalTo("var content = React.createElement(Content, null, \"foo\");"));
}
@Test
public void transforms_jsx_source_with_options() throws Exception {
nashornEngine.eval("global = {};");
loadScript("JSXTransformer");
JSXTransformer jsxTransformer = nashornInvoker.getInterface(nashornEngine.eval("global.JSXTransformer"),
JSXTransformer.class);
String source = "var content = <Content>foo</Content>;";
JSXTransformer.Options options = new JSXTransformer.Options(false, false);
JSObject transformOutput = jsxTransformer.transform(source, options);
assertThat(transformOutput.keySet(), equalTo(ImmutableSet.of("code")));
assertThat(transformOutput.getMember("code"),
equalTo("var content = React.createElement(Content, null, \"foo\");"));
}
@Test
public void transforms_jsx_source_with_options_specifying_harmony_transform() throws Exception {
nashornEngine.eval("global = {};");
loadScript("JSXTransformer");
JSXTransformer jsxTransformer = nashornInvoker.getInterface(nashornEngine.eval("global.JSXTransformer"),
JSXTransformer.class);
String source = "var f = v => this.props[v];";
JSXTransformer.Options options = new JSXTransformer.Options(true, false);
JSObject transformOutput = jsxTransformer.transform(source, options);
assertThat(transformOutput.keySet(), equalTo(ImmutableSet.of("code")));
assertThat(transformOutput.getMember("code"),
equalTo("var f = function(v) {return this.props[v];}.bind(this);"));
}
@Test
public void renders_jsx_component() throws Exception {
nashornEngine.eval("global = {};");
loadScript("react-with-addons");
Object jsReact = nashornEngine.eval("global.React");
loadScript("JSXTransformer");
Object jsJSXTransformer = nashornEngine.eval("global.JSXTransformer");
Object jsxComponent = nashornInvoker.invokeMethod(jsJSXTransformer, "exec",
withReactSymbol("React.createClass({ render: function() { return <div>JSX component</div>; } })"));
Object renderElement = nashornInvoker.invokeMethod(jsReact, "createElement", jsxComponent);
Object renderOutput = nashornInvoker.invokeMethod(jsReact, "renderToStaticMarkup", renderElement);
assertThat(renderOutput, equalTo("<div>JSX component</div>"));
}
@Test
public void react_symbol_can_be_added_to_implicit_global() throws Exception {
nashornEngine.eval("global = {};");
loadScript("react-with-addons");
Object jsReact = nashornEngine.eval("global.React");
Bindings bindings = nashornEngine.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("React", jsReact);
loadScript("JSXTransformer");
Object jsJSXTransformer = nashornEngine.eval("global.JSXTransformer");
Object jsxComponent = nashornInvoker.invokeMethod(jsJSXTransformer, "exec",
"React.createClass({ render: function() { return <div>JSX component</div>; } })");
Object renderElement = nashornInvoker.invokeMethod(jsReact, "createElement", jsxComponent);
Object renderOutput = nashornInvoker.invokeMethod(jsReact, "renderToStaticMarkup", renderElement);
assertThat(renderOutput, equalTo("<div>JSX component</div>"));
}
@Test
public void modules_can_export_directly_to_implicit_global() throws Exception {
nashornEngine.eval("var global = this");
loadScript("react-with-addons");
assertThat(nashornEngine.eval("React.version"), equalTo(ReactResources.REACT_VERSION));
assertThat(nashornEngine.getBindings(ScriptContext.ENGINE_SCOPE).get("React"), not(nullValue()));
}
@Test
public void stringify_formats_object_passed_directly() throws Exception {
assertThat(nashornEngine.eval("JSON.stringify({a:1})"), equalTo("{\"a\":1}"));
}
@Test
public void stringify_formats_object_passed_indirectly() throws Exception {
JSObject obj = (JSObject) nashornEngine.eval("({a:1})");
JSObject jsonStringify = (JSObject) nashornEngine.eval("JSON.stringify");
assertThat(obj.keySet(), equalTo(ImmutableSet.of("a")));
assertThat(obj.values(), containsInAnyOrder(1));
assertThat(jsonStringify.call(null, obj), equalTo("{\"a\":1}"));
}
@Test
@Ignore("so why doesn't this work?")
public void stringify_formats_object_passed_via_adaptor() throws Exception {
JSObject obj = (JSObject) nashornEngine.eval("({a:1})");
JSObject jsonObject = (JSObject) nashornEngine.eval("JSON");
Json json = nashornInvoker.getInterface(jsonObject, Json.class);
assertThat(json.stringify(obj, null, " "), equalTo("{\"a\":1}"));
}
private static String withReactSymbol(String js) {
return String.format("(function(React) { return %s })(global.React)", js);
}
private void loadScript(String src) throws IOException, ScriptException {
CharSource charSource = Resources.asCharSource(ReactResources.resourceFor(src), StandardCharsets.UTF_8);
nashornEngine.getContext().setAttribute(ScriptEngine.FILENAME, src, ScriptContext.ENGINE_SCOPE);
try (BufferedReader reader = charSource.openBufferedStream()) {
nashornEngine.eval(reader);
} finally {
nashornEngine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
}
}
private static Matcher<String> matches(String regex) {
return new TypeSafeDiagnosingMatcher<String>() {
private final Pattern pattern = Pattern.compile(regex);
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
mismatchDescription.appendText("was ");
mismatchDescription.appendValue(item);
return pattern.matcher(item).matches();
}
@Override
public void describeTo(Description description) {
description.appendText("matching ").appendValue(pattern.pattern());
}
};
}
public interface Json {
JSObject parse(String str);
String stringify(JSObject obj, JSObject replacer, String space);
}
public interface JSXTransformer {
JSObject transform(String source);
JSObject transform(String source, Options options);
public class Options {
private final boolean harmony;
private final boolean stripTypes;
public Options(boolean harmony, boolean stripTypes) {
this.harmony = harmony;
this.stripTypes = stripTypes;
}
public boolean isHarmony() {
return harmony;
}
public boolean isStripTypes() {
return stripTypes;
}
}
}
}
<file_sep>Server-side rendering using Nashorn and React
=============================================
This is a Java webapp, which aims to demonstrate "isomorphic" rendering- a one-page application where data is rendered server-side for the initial load, including consistent handling of URI paths for both server-side and client-side routing.
React.js is used to render based on some data model, both client and server side. In the server, the rendering is performed by running the components using the Nashorn JavaScript engine.
This is at a very early stage, and doesn't actually produce anything yet. In the test sources are demonstrations that Nashorn can in fact load React, transform JSX and render components. Some framework will be necessary to allow the routing outputs to be applied to the components both client- and server-side.
[](https://travis-ci.org/araqnid/nashorn-react-rendering)
<file_sep>package org.araqnid.testbed.jreact;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import jdk.nashorn.api.scripting.JSObject;
import org.junit.Test;
import static org.araqnid.testbed.jreact.JSObjectMatchers.jsArray;
import static org.araqnid.testbed.jreact.JSObjectMatchers.jsArrayishContaining;
import static org.araqnid.testbed.jreact.JSObjectMatchers.jsFunction;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
public class CallbackFromJavascriptTest {
private final ScriptEngineManager engineManager = new ScriptEngineManager();
private final ScriptEngine nashornEngine = engineManager.getEngineByName("nashorn");
@SuppressWarnings("unused")
private final Invocable nashornInvoker = (Invocable) nashornEngine;
@Test
public void can_callback_with_a_function() throws Exception {
Bindings engineBindings = nashornEngine.getBindings(ScriptContext.ENGINE_SCOPE);
Queue<JSObject> invocations = new ConcurrentLinkedQueue<>();
engineBindings.put("__loader", new Loader() {
@Override
public void define(JSObject args) {
invocations.add(args);
}
});
nashornEngine.eval("this.define = function() { __loader.define(arguments) }");
nashornEngine.eval("define(function() { return \"content\"; })");
assertThat(invocations, contains(jsArrayishContaining(jsFunction())));
}
@Test
public void can_call_the_callback() throws Exception {
Bindings engineBindings = nashornEngine.getBindings(ScriptContext.ENGINE_SCOPE);
Queue<JSObject> invocations = new ConcurrentLinkedQueue<>();
engineBindings.put("__loader", new Loader() {
@Override
public void define(JSObject args) {
invocations.add(args);
}
});
nashornEngine.eval("this.define = function() { __loader.define(arguments) }");
nashornEngine.eval("define(function() { return \"content\"; })");
JSObject invocation = invocations.poll();
JSObject callback = (JSObject) invocation.getSlot(0);
Object result = callback.call(null);
assertThat(result, equalTo("content"));
}
@Test
public void can_callback_with_an_array_and_a_function() throws Exception {
Bindings engineBindings = nashornEngine.getBindings(ScriptContext.ENGINE_SCOPE);
Queue<JSObject> invocations = new ConcurrentLinkedQueue<>();
engineBindings.put("__loader", new Loader() {
@Override
public void define(JSObject args) {
invocations.add(args);
}
});
nashornEngine.eval("this.define = function() { __loader.define(arguments) }");
nashornEngine.eval("define([\"bar\"], function(bar) { return \"content\"; })");
assertThat(invocations, contains(jsArrayishContaining(jsArray(), jsFunction())));
}
public interface Loader {
void define(JSObject function);
}
}
<file_sep>define(function() {
return "noDependencies module";
})
<file_sep>package org.araqnid.testbed.jreact;
import java.io.IOException;
import org.junit.Test;
import com.google.common.reflect.ClassPath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
public class EmbeddedResourceTest {
@Test
public void resource_for_root_exists() throws Exception {
EmbeddedResource resource = webappRoot();
assertThat(resource.exists(), equalTo(true));
}
@Test
public void resource_for_root_is_a_directory() throws Exception {
EmbeddedResource resource = webappRoot();
assertThat(resource.isDirectory(), equalTo(true));
}
@Test
public void resource_for_root_contains_index() throws Exception {
EmbeddedResource resource = webappRoot();
assertThat(resource.list(), hasItemInArray("index.html"));
}
private EmbeddedResource webappRoot() throws IOException {
return new EmbeddedResource(getClass().getClassLoader(), "web", ClassPath.from(getClass()
.getClassLoader()));
}
}
<file_sep>package org.araqnid.testbed.jreact;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import jdk.nashorn.api.scripting.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.CharSource;
import com.google.common.io.Resources;
import static com.google.common.base.Functions.toStringFunction;
import static com.google.common.base.Verify.verifyNotNull;
public class JSModuleContainer {
private static final Pattern JSX_PATTERN = Pattern.compile("jsx!(.+)");
private final ScriptEngineManager engineManager = new ScriptEngineManager();
private final ScriptEngine nashornEngine = engineManager.getEngineByName("nashorn");
private final Map<String, Module> modules = new HashMap<>();
private final String root;
public JSModuleContainer(String root) {
this.root = root;
}
public Object require(String moduleName) throws IOException, ScriptException {
Module module = modules.get(moduleName);
if (module != null) {
if (module.state != Module.State.LOADED)
throw new IllegalStateException(moduleName + " in state " + module.state);
}
else {
module = load(moduleName);
}
return module.value;
}
public <T> T require(String moduleName, Class<T> targetInterface) throws IOException, ScriptException {
Module module = modules.get(moduleName);
if (module != null) {
if (module.state != Module.State.LOADED)
throw new IllegalStateException(moduleName + " in state " + module.state);
}
else {
module = load(moduleName);
}
if (module.adaptors.containsKey(targetInterface)) return module.adaptors.getInstance(targetInterface);
Invocable nashornInvoker = (Invocable) nashornEngine;
if (!(module.value instanceof JSObject)) { throw new ClassCastException("Non-object module '" + moduleName
+ "' is not compatible with " + targetInterface); }
T adaptor = nashornInvoker.getInterface(module.value, targetInterface);
if (adaptor == null)
throw new ClassCastException("Module '" + moduleName + "' is not compatible with " + targetInterface);
module.adaptors = ImmutableClassToInstanceMap.builder().putAll(module.adaptors).put(targetInterface, adaptor)
.build();
return adaptor;
}
private Module load(String moduleName) throws IOException, ScriptException {
Matcher jsxMatcher = JSX_PATTERN.matcher(moduleName);
if (jsxMatcher.matches()) {
return loadJSX(moduleName, jsxMatcher.group(1));
}
else if (moduleName.equals("react") || moduleName.equals("JSXTransformer")) {
ensureReactLoaded();
return modules.get(moduleName);
}
else {
return loadBasic(moduleName);
}
}
private Module loadBasic(String moduleName) throws IOException, ScriptException {
Module module = new Module();
modules.put(moduleName, module);
URL resource = Resources.getResource(root + "/" + moduleName + ".js");
JSObject defineCall = loadModuleFactory(moduleName, resource,
Resources.asCharSource(resource, StandardCharsets.UTF_8));
define(module, moduleName, defineCall);
return module;
}
private JSObject loadModuleFactory(String moduleName, URL resource, CharSource charSource) throws ScriptException,
IOException {
ScriptContext scriptContext = new SimpleScriptContext();
Bindings engineBindings = nashornEngine.createBindings();
scriptContext.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
LoaderProxy loaderProxy = new LoaderProxy();
engineBindings.put("__loader", loaderProxy);
engineBindings.put("console", new Console(moduleName.replace('/', '_')));
engineBindings.put("define", nashornEngine.eval("(function() { __loader.define(arguments) })", scriptContext));
scriptContext.setAttribute(ScriptEngine.FILENAME, resource.toString(), ScriptContext.ENGINE_SCOPE);
try (BufferedReader reader = charSource.openBufferedStream()) {
nashornEngine.eval(reader, scriptContext);
}
if (loaderProxy.defineCalls.isEmpty()) throw new IllegalStateException("No call to define() from " + resource);
JSObject defineCall = loaderProxy.defineCalls.poll();
if (!loaderProxy.defineCalls.isEmpty())
throw new IllegalStateException("Multiple calls to define() from " + resource);
return defineCall;
}
private void define(Module module, String moduleName, JSObject defineCall) throws IOException, ScriptException {
JSObject callback;
List<String> dependencies;
if (defineCall.values().size() == 1) {
JSObject arg0 = (JSObject) defineCall.getSlot(0);
if (!arg0.isFunction())
throw new IllegalStateException(moduleName + ": single-arg call to define was not passed a function");
callback = arg0;
dependencies = ImmutableList.of();
}
else if (defineCall.values().size() == 2) {
JSObject arg0 = (JSObject) defineCall.getSlot(0);
dependencies = ImmutableList.copyOf(Collections2.transform(arg0.values(), Functions.toStringFunction()));
JSObject arg1 = (JSObject) defineCall.getSlot(1);
if (!arg1.isFunction())
throw new IllegalStateException(moduleName + ": second argument to define was not passed a function");
callback = arg1;
}
else {
throw new IllegalStateException(moduleName + ": was passed " + defineCall.values().size() + " arguments");
}
List<Object> dependencyValues = Lists.newArrayListWithExpectedSize(dependencies.size());
for (String dependencyName : dependencies) {
dependencyValues.add(require(dependencyName));
}
module.value = callback.call(null, dependencyValues.toArray());
module.state = Module.State.LOADED;
}
private Module loadJSX(String moduleName, String residualName) throws IOException, ScriptException {
ensureReactLoaded();
Module module = new Module();
modules.put(moduleName, module);
URL resource = Resources.getResource(root + "/" + residualName + ".jsx");
JSXTransformer adaptor = modules.get("JSXTransformer").adaptors.getInstance(JSXTransformer.class);
JSObject jsTransformOutput = adaptor.transform(Resources.asCharSource(resource, StandardCharsets.UTF_8).read());
String jsSource = (String) jsTransformOutput.getMember("code");
JSObject defineCall = loadModuleFactory(residualName, resource, CharSource.wrap(jsSource));
define(module, moduleName, defineCall);
return module;
}
private void ensureReactLoaded() {
Module reactModule = modules.get("react");
if (reactModule != null) {
if (reactModule.state == Module.State.LOADED) return;
throw new IllegalStateException("React module is in state " + reactModule.state);
}
try {
loadReactModule("JSXTransformer", "JSXTransformer", "JSXTransformer", JSXTransformer.class);
} catch (IOException | ScriptException e) {
throw new IllegalStateException("Unable to load JSXTransformer", e);
}
try {
loadReactModule("react", "react-with-addons.min", "React", React.class);
} catch (IOException | ScriptException e) {
throw new IllegalStateException("Unable to load React", e);
}
}
private <T> Module loadReactModule(String moduleName, String scriptName, String symbol, Class<T> adaptTo)
throws IOException, ScriptException {
Module module = new Module();
modules.put(moduleName, module);
module.value = loadReactScript(ReactResources.resourceFor(scriptName), symbol);
Invocable nashornInvoker = (Invocable) nashornEngine;
module.adaptors = ImmutableClassToInstanceMap.builder()
.put(adaptTo, nashornInvoker.getInterface(module.value, adaptTo)).build();
module.state = Module.State.LOADED;
return module;
}
private JSObject loadReactScript(URL resource, String symbol) throws IOException, ScriptException {
ScriptContext scriptContext = new SimpleScriptContext();
Bindings engineBindings = nashornEngine.createBindings();
scriptContext.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
engineBindings.put("__loader", new LoaderProxy());
engineBindings.put("console", new Console(symbol));
nashornEngine.eval("var global = this", scriptContext);
scriptContext.setAttribute(ScriptEngine.FILENAME, resource.toString(), ScriptContext.ENGINE_SCOPE);
CharSource charSource = Resources.asCharSource(resource, StandardCharsets.UTF_8);
try (BufferedReader reader = charSource.openBufferedStream()) {
nashornEngine.eval(reader, scriptContext);
}
return (JSObject) verifyNotNull(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE).get(symbol));
}
private static final class Module {
private static final ClassToInstanceMap<Object> NONE = ImmutableClassToInstanceMap.builder().build();
enum State {
LOADING, LOADED
};
public State state = State.LOADING;
public Object value;
public ClassToInstanceMap<Object> adaptors = NONE;
}
public static class LoaderProxy {
final Queue<JSObject> defineCalls = new ConcurrentLinkedQueue<>();
public void define(JSObject args) {
defineCalls.add(args);
}
@Override
public String toString() {
return "LoaderProxy";
}
}
public class Console {
private final Logger logger;
private Console(String context) {
logger = LoggerFactory.getLogger(JSModuleContainer.class.getName() + ".JS." + context);
}
public void log(String message, JSObject... args) {
logger.info(format(message, args));
}
public void info(String message, JSObject... args) {
logger.info(format(message, args));
}
public void warn(String message, JSObject... args) {
logger.warn(format(message, args));
}
public void error(String message, JSObject... args) {
logger.error(format(message, args));
}
private String format(String message, JSObject... args) {
return Joiner.on(' ').join(
Iterables.concat(ImmutableList.<Object> of(message),
Lists.transform(Arrays.asList(args), toStringFunction())));
}
}
public interface JSXTransformer {
void exec(String str);
JSObject transform(String source);
}
public interface React {
JSObject createElement(String str);
JSObject createElement(String str, JSObject props, JSObject... children);
JSObject createElement(JSObject factory);
JSObject createElement(JSObject factory, JSObject props);
String renderToStaticMarkup(JSObject element);
String renderToString(JSObject element);
}
}
<file_sep>apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
mainClassName = 'org.araqnid.testbed.jreact.Main'
sourceCompatibility = 1.8
version = '0.0.' + (System.getenv("BUILD_NUMBER") ?: System.getenv("TRAVIS_BUILD_NUMBER") ?: "0")
ext {
reactVersion = '0.13.1'
jettyVersion = '9.2.10.v20150310'
jacksonVersion = '2.5.2'
resteasyVersion = '3.0.11.Final'
guiceVersion = '4.0-beta5'
}
jar {
manifest {
attributes 'Implementation-Title': project.description ?: project.name,
'Implementation-Version': version,
'X-Service-Class': mainClassName
}
}
sourceSets {
integrationTest {
compileClasspath += main.output + test.output;
runtimeClasspath += main.output + test.output;
}
browserTest {
compileClasspath += main.output;
runtimeClasspath += main.output;
}
}
configurations {
integrationTestCompile.extendsFrom testCompile
integrationTestRuntime.extendsFrom testRuntime
browserTestCompile.extendsFrom testCompile
browserTestRuntime.extendsFrom testRuntime
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.guava:guava:18.0'
compile 'com.google.inject:guice:' + guiceVersion
compile 'com.google.inject.extensions:guice-servlet:' + guiceVersion
compile 'com.google.inject.extensions:guice-multibindings:' + guiceVersion
compile 'org.slf4j:slf4j-api:1.7.10'
compile 'org.eclipse.jetty:jetty-server:' + jettyVersion
compile 'org.eclipse.jetty:jetty-servlet:' + jettyVersion
compile 'com.google.code.findbugs:jsr305:3.0.0'
compile 'org.jboss.resteasy:resteasy-jaxrs:' + resteasyVersion
compile 'org.jboss.resteasy:resteasy-guice:' + resteasyVersion
compile 'org.jboss.resteasy:resteasy-jackson2-provider:' + resteasyVersion
compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:' + jacksonVersion
compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:' + jacksonVersion
compile 'com.fasterxml.jackson.module:jackson-module-guice:' + jacksonVersion
compile 'com.fasterxml.jackson.datatype:jackson-datatype-guava:' + jacksonVersion
compile 'com.fasterxml.jackson.datatype:jackson-datatype-jdk7:' + jacksonVersion
compile 'com.fasterxml.jackson.datatype:jackson-datatype-jdk8:' + jacksonVersion
runtime 'ch.qos.logback:logback-classic:1.1.2'
runtime 'org.webjars:react:' + reactVersion
testCompile 'junit:junit:4.12'
testCompile 'org.hamcrest:hamcrest-library:1.3'
testCompile 'org.hamcrest:hamcrest-integration:1.3'
testCompile 'org.mockito:mockito-core:1.10.19'
testRuntime 'org.webjars:react:' + reactVersion
browserTestCompile ('org.seleniumhq.selenium:selenium-java:2.42.2') {
exclude module: 'httpclient'
}
integrationTestCompile 'org.apache.httpcomponents:httpclient:4.4'
// marking this as integrationTestCompile causes a conflict for Eclipse which tries to take the transitive 4.2 version via resteasy too
compile 'org.apache.httpcomponents:httpclient:4.4'
}
task runtimeDeps(dependsOn: 'processResources') {
def sha1 = java.security.MessageDigest.getInstance("SHA-1")
def metainf = new File("$buildDir/resources/main/META-INF")
def depsFile = new File(metainf, project.name + ".deps.txt")
outputs.file depsFile
outputs.upToDateWhen {
if (!depsFile.exists()) return false
def currentContent = depsFile.text
def newArtifacts = 0
configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { artifact ->
if (currentContent.indexOf(' ' + artifact.moduleVersion.id + ' ' + artifact.type + '\n') < 0) newArtifacts++
}
return newArtifacts == 0
}
doLast {
metainf.mkdirs()
depsFile.text = ''
configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { artifact ->
depsFile.text += sha1.digest(artifact.file.bytes).collect {String.format "%02x", it}.join() + ' ' + artifact.moduleVersion.id + ' ' + artifact.type + '\n'
}
}
}
jar.dependsOn(runtimeDeps)
task reactVersionProperties {
def sourceSet = project.sourceSets.main
def generatedSourceDir = new File("${project.buildDir}/generated-sources/${sourceSet.name}")
def versionPropertiesFile = new File(generatedSourceDir, "org/araqnid/testbed/jreact/react.version.properties")
outputs.dir generatedSourceDir
outputs.upToDateWhen { versionPropertiesFile.exists() && versionPropertiesFile.text.indexOf(project.ext.reactVersion) > 0 }
outputs.file versionPropertiesFile
sourceSet.resources.srcDir generatedSourceDir
def processResourcesTask = project.tasks.getByName(sourceSet.processResourcesTaskName)
processResourcesTask.dependsOn(project.tasks.getByName("reactVersionProperties"))
doLast {
new File(versionPropertiesFile.parent).mkdirs()
versionPropertiesFile.text = "react.version=" + project.ext.reactVersion + "\n"
}
}
task integrationTest(type: Test, dependsOn: 'test') {
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
task browserTest(type: Test) {
testClassesDir = sourceSets.browserTest.output.classesDir
classpath = sourceSets.browserTest.runtimeClasspath
}
build.dependsOn(integrationTestClasses, browserTestClasses)
check.dependsOn(integrationTest)
eclipse {
classpath {
plusConfigurations += [ configurations.integrationTestCompile ];
plusConfigurations += [ configurations.browserTestCompile ];
file {
whenMerged { classpath ->
def libs = classpath.entries.findAll { it.kind == 'lib' }
libs.findAll { it.moduleVersion.group == 'com.google.inject' && it.moduleVersion.name == 'guice' }.collect { entry ->
entry.accessRules.add(new org.gradle.plugins.ide.eclipse.model.AccessRule('discouraged', 'com/google/inject/Inject'))
entry.accessRules.add(new org.gradle.plugins.ide.eclipse.model.AccessRule('discouraged', 'com/google/inject/Provider'))
entry.accessRules.add(new org.gradle.plugins.ide.eclipse.model.AccessRule('discouraged', 'com/google/inject/BindingAnnotation'))
entry.accessRules.add(new org.gradle.plugins.ide.eclipse.model.AccessRule('discouraged', 'com/google/inject/ScopeAnnotation'))
entry.accessRules.add(new org.gradle.plugins.ide.eclipse.model.AccessRule('discouraged', 'com/google/inject/Singleton'))
entry.accessRules.add(new org.gradle.plugins.ide.eclipse.model.AccessRule('discouraged', 'com/google/inject/name/Named'))
}
}
}
}
}
| 3038a5f05b05d65627636a41d632fc0acfec2451 | [
"JavaScript",
"Java",
"Markdown",
"Gradle"
] | 14 | JavaScript | araqnid/nashorn-react-rendering | 2caceba15e82b511dc547974f8d67bd6c385847f | 9712f733453b4dcb8901f6ddefbc7b95ce555f8f |
refs/heads/master | <repo_name>saadkhalil/botintel<file_sep>/app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Pages;
use View;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct() {
$variable1 = Pages::latest('id','desc')->where('is_blog',0)->where('status',1)->limit(4)->get();
View::share ( 'variable1', $variable1 );
}
}
<file_sep>/app/Http/Controllers/Auth/ForgotPasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Mail;
use App\User;
use Hash;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
public function forgotsubmit(Request $request)
{
if (User::where('email', '=', $request->email)->exists()) {
// user found
$userdetail=User::where('email', '=', $request->email)->first();
$email=$userdetail->email;
$link=url('/').'/changepassword/'.$userdetail->remember_token;
$message_text="Hello ".$userdetail->full_name."
Please <a href='".$link."'>click here</a> to change your password.
";
Mail::raw($message_text, function ($message) use ($email){
$message->to($email);
$message->from('<EMAIL>','Botintel');
$message->subject('Forgotten Password Request - Botintel'); });
return json_encode('sent');
}
}
public function changepassword(Request $request,$token){
if (User::where('remember_token', '=', $token)->exists()) {
$data['token']=$token;
return view('front.changepassword',$data);
}
else{
return redirect('/')->withError('Error , Token is not valid');
}
}
public function passwordsubmit(Request $request){
$remember=$request->remember_token;
$password=$request->input('npassword');
$updatepassword =User::where('remember_token',$remember)->first();
$updatepassword->password=<PASSWORD>::make($password);
$updatepassword->remember_token=$request->input('_token');
$updatepassword->updated_at=date("Y-m-d H:i:s");
$updatepassword->save();
return redirect('/')->withMessage("Password Successfully Changed");
}
}
<file_sep>/app/Http/Controllers/Frontend/ReleaseController.php
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use DB;
use App\Releases;
class ReleaseController extends Controller
{
//
public function index(){
if(Auth::user()):
$now=date('Y-m-d H:i:s');
$data['releases']=Releases::where('release_date','>',$now)->where('store_id',2)->where('country','US')->get();
return view('front.release',$data);
else:
return redirect('/');
endif;
}
public function checkrelease(Request $request){
$country=$request->country;
$brand=$request->brand;
$now=date('Y-m-d H:i:s');
$query = DB::table('releases');
if(!empty($country) && !empty($brand)):
foreach ($country as $cr) {
$query->orWhere('country',$cr);
$query->whereIn('store_id',$brand);
}
elseif(!empty($country)):
$query->whereIn('country',$country);
elseif(!empty($brand)):
$query->whereIn('store_id',$brand);
endif;
$query->where('release_date','>',$now);
$row=$query->get();
return json_decode($row);
}
}
<file_sep>/app/Http/Controllers/Frontend/SettingsController.php
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use DB;
use Hash;
use App\User;
use App\Subscriptions;
class SettingsController extends Controller
{
//
public function index(){
if($user=Auth::user()):
$data['subscription']=Subscriptions::all();
$data['userdetails'] =DB::table('users')->select('users.*','users.id as UserID','subscription.*')
->leftjoin('subscription', 'subscription.id', '=', 'users.subscription_id')
->where('users.id',$user->id)
->first();
// print_r($data['userdetails']);
// die;
return view('front.settings',$data);
else:
return redirect('/');
endif;
}
public function update(Request $request){
$user=Auth::user();
$userdetails=User::where('id',$user->id)->first();
$userdetails->full_name=$request->input('fullname');
$userdetails->gender=$request->input('gender');
$userdetails->language=$request->input('language');
$userdetails->timezone=$request->input('timezone');
$userdetails->nick_name=$request->input('nickname');
$userdetails->phone=$request->input('phone');
$userdetails->country=$request->input('countries');
$userdetails->updated_at=date("Y-m-d H:i:s");
$userdetails->save();
return redirect()->back()->with('message', 'Personal Information Successfully Updated.');
}
public function upgradeplan(Request $request){
$user=Auth::user();
$subscribedetails=Subscriptions::where('id',$request->subscription)->first();
$planid=strtolower($subscribedetails->subscription_name);
$userdetails=User::where('id',$user->id)->first();
$userdetails->subscription_id=$request->subscription;
$userdetails->updated_at=date("Y-m-d H:i:s");
$userdetails->save();
$userdetails->subscription('main')->swap($planid);
// $subscription = DB::table('subscriptions')->where('user_id',$userdetails->id)->first();
// $subscription->stripe_plan = $planid;
// $subscription->save();
return redirect()->back()->with('message', 'Plan Successfully Upgraded.');
}
public function cancelplan(Request $request)
{
$user=Auth::user();
$userdetails=User::where('id',$user->id)->first();
$userdetails->updated_at=date("Y-m-d H:i:s");
$userdetails->subscription_active=0;
$userdetails->save();
$subscribedetails=Subscriptions::where('id',$request->sub)->first();
$planid=strtolower($subscribedetails->subscription_name);
$userdetails->subscription('main')->cancel();
echo 1;
}
public function changepassword(Request $request){
if (Hash::check($request->input("password"), Auth::user()->password)) {
//add logic here
$password=<PASSWORD>($request->input("<PASSWORD>"));
$updatepassword =User::where('id', '=', Auth::user()->id)->first();
$updatepassword->password=<PASSWORD>($request->input("<PASSWORD>"));
$updatepassword->updated_at=date("Y-m-d H:i:s");
$updatepassword->save();
return redirect()->back()->withMessage("Password Successfully Changed");
}
else {
return redirect()->back()->withError("Old Password is not Valid");
}
}
}
<file_sep>/public/front/js/main.js
// -------------------------------------------------------------
// bootstrap dropdown hover menu setup
// -------------------------------------------------------------
$('ul.nav li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).slideDown(400);
$('span', this).toggleClass("caret caret-up");
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).slideUp(400);
$('span', this).toggleClass("caret caret-up");
});
$('.dropdown-toggle').removeAttr('data-toggle');
// -------------------------------------------------------------
// WOW setup
// -------------------------------------------------------------
jQuery(function ($) {
var wow = new WOW({
mobile: false
});
wow.init();
}());
// -------------------------------------------------------------
// date setup
// -------------------------------------------------------------
var d = new Date();
var n = d.getFullYear();
document.getElementById("date-year").innerHTML = n;
// -------------------------------------------------------------
// Modal Animation setup
//
$(".modal").each(function(l){$(this).on("show.bs.modal",function(l){var o=$(this).attr("data-easein");"shake"==o?$(".modal-dialog").velocity("callout."+o):"pulse"==o?$(".modal-dialog").velocity("callout."+o):"tada"==o?$(".modal-dialog").velocity("callout."+o):"flash"==o?$(".modal-dialog").velocity("callout."+o):"bounce"==o?$(".modal-dialog").velocity("callout."+o):"swing"==o?$(".modal-dialog").velocity("callout."+o):$(".modal-dialog").velocity("transition."+o)})});
// -------------------------------------------------------------
// Filter Button setup
//
$(document).ready(function(){
$(".filter-button").click(function(){
var value = $(this).attr('data-filter');
if(value == "all")
{
//$('.filter').removeClass('hidden');
$('.filter').show('1000');
}
else
{
// $('.filter[filter-item="'+value+'"]').removeClass('hidden');
// $(".filter").not('.filter[filter-item="'+value+'"]').addClass('hidden');
$(".filter").not('.'+value).hide('3000');
$('.filter').filter('.'+value).show('3000');
}
});
if ($(".filter-button").removeClass("active")) {
$(this).removeClass("active");
}
$(this).addClass("active");
})
// -------------------------------------------------------------
// Tooltip setup
//
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
$(document).ready(function(){
// $("#us").click(function(){
// var active = $(this).addClass('selected');
// });
// $("#eu").click(function(){
// var active = $(this).addClass('selected');
// });
// $("#nike").click(function(){
// var active = $(this).addClass('selected');
// });
// $("#adidas").click(function(){
// var active = $(this).addClass('selected');
// $('#nike').removeClass('selected');
// });
$(".filter-button").click(function(){
var eu = $('#eu').val();
var us = $('#us').val();
var nike = $('#nike').val();
var adidas = $('#adidas').val();
var filterform= $('#filterform').serialize();
$.ajax({
type: 'get',
data: filterform,
url: 'releases/checkRelease',
dataType: 'json',
success: function(res){
if(res){
$.each( res, function( key, value ) {
$("#releaseview").append('<div class="col-sm-4 col-md-4 filter releaserecord" ><div class="thumbnail"><img src="'+value.release_image+'" alt="img-01"><div class="caption"><p>Name: '+value.release_name+'</p><p>SKU: '+value.release_code+'</p><p>Release Date: '+value.release_date+' PST<p>Submission Time: <span class="demo" id="st'+value.id+'" data-countdown="'+value.sub_time+'"></span></p><div class="caption-hover"><p>Description: '+value.release_description+'</p></div></div></div></div></div>');
});
countdown();
}
},
error: function(res){
$('#message').html("<div class='alert alert-danger fade in'><a href='#' class='close' data-dismiss='alert'>×</a><strong>Error ! Records Not Found</strong></div>");
}
});
});
$('#configreset').click(function(){
$('#fullname').val('');
$('#phone').val('');
$('#timezone').val('');
$('#countries').val('');
$('#nickname').val('');
$('#language').val('');
$("input:radio").removeAttr("checked");
});
$('#packageBox1').click(function() {
if($(this).attr('id') == 'packageBox1') {
//alert($(this).attr('id'));
$('#packageBox1').addClass('checked-selected');
$('#packageBox2').removeClass('checked-selected');
$('#packageBox3').removeClass('checked-selected');
}
});
$('#packageBox2').click(function() {
if($(this).attr('id') == 'packageBox2') {
// alert($(this).attr('id'));
$('#packageBox2').addClass('checked-selected');
$('#packageBox1').removeClass('checked-selected');
$('#packageBox3').removeClass('checked-selected');
}
});
$('#packageBox3').click(function() {
if($(this).attr('id') == 'packageBox3') {
//alert($(this).attr('id'));
$('#packageBox3').addClass('checked-selected');
$('#packageBox1').removeClass('checked-selected');
$('#packageBox2').removeClass('checked-selected');
}
});
/* $(function(){
$('#packageBox1').click(function(){
alert($(this).val());
if($(this).val() == 'packageBox1'){
$('.payment').addClass('checked-selected');
}
});
});*/
});<file_sep>/app/Http/Controllers/Auth/RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Subscriptions;
use App\Pages;
use Mail;
use DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Database\Query\Builder;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/release';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'fname' => 'required|string|max:255',
'lname' => 'required|string|max:255',
'phone' => 'required|',
'subscription_id' => 'required_without_all:subscription_id',
'email' => 'required|string|email|max:255|unique:users',
'agree' =>'accepted'
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
$fullname=$data['fname'].' '.$data['lname'];
$userarray=array('full_name' => $fullname,
'email' => $data['email'],
'phone' => $data['phone'],
'subscription_id' => $data['subscription_id']);
// print_r($userarray);
// die;
return User::create($userarray);
}
public function showRegistrationForm()
{
// if(!Auth::user()):
// return Redirect::to('/release');
// endif;
$data['subscriptions']=Subscriptions::all();
$data['variable1'] = Pages::latest('id','desc')->where('is_blog',0)->where('status',1)->limit(4)->get();
return view('auth.register', $data);
}
public function store(Request $request)
{
$randstring=str_random(8);
$password = <PASSWORD>($rand<PASSWORD>);
$fullname=$request->input('fname').' '.$request->input('lname');
$user= new User ;
$user->full_name= $fullname;
$user->email= $request->input('email');
$user->password= <PASSWORD>;
$user->phone= $request->input('phone');
$user->subscription_id= $request->input('subscription_id');
$user->remember_token=$request->input("_token");
$user->subscription_active=1;
$user->save();
$userID=$user->id;
$subscripedetail=Subscriptions::where('id',$request->input('subscription_id'))->first();
$subscriped=strtolower($subscripedetail->subscription_name);
$user->newSubscription('main',$subscriped)->create($request->stripeToken);
$link=url('/').'/verification/'.$user->remember_token;
$email=$request->input('email');
$data=array(
'fullname' => $fullname,
'subscription_name' => strtoupper($subscripedetail->subscription_name),
'email' => $email,
'password' => $<PASSWORD>,
'link' => $link,
);
Mail::send('emails.register', $data, function ($message) use ($email){
$message->to($email);
$message->from('<EMAIL>','Botintel');
$message->subject('Sign Up - Botintel');
});
if ($user->subscribed('main',$subscriped)) {
return redirect('/')->with('message', 'Registered Successfully, Check your mail !');
}
return redirect()-back()->with('error', 'Not Registered Successfully');
}
public function verification($id)
{
if (User::where('remember_token', '=', $id)->count() > 0) {
$update= DB::table('users')
->where('remember_token', $id)
->update(['status' => 1 , 'updated_at'=>date("Y-m-d H:i:s")]);
return redirect('/')->withMessage("Activated , Please login with your password");
}
else {
return redirect('/')->withError("User is not valid");
}
//
}
public function cancel(Request $request)
{
// Token is created using Checkout or Elements!
// Get the payment token ID submitted by the form:
$token = $_POST['stripeToken'];
$customer = \Stripe\Customer::create([
'source' => $token,
'email' => '<EMAIL>',
]);
$charge = \Stripe\Charge::create([
'amount' => 1000,
'currency' => 'usd',
'customer' => $customer->id,
]);
print_r($charge);
die;
return redirect()->back()->with('message', 'Payment Successfully Updated.');
}
}
<file_sep>/app/Http/Controllers/AdminTasksController.php
<?php namespace App\Http\Controllers;
use Session;
use Illuminate\Http\Request;
use DB;
use CRUDBooster;
use App\Tasks;
use Excel;
use Illuminate\Support\Str;
class AdminTasksController extends \crocodicstudio\crudbooster\controllers\CBController {
public function cbInit() {
# START CONFIGURATION DO NOT REMOVE THIS LINE
$this->title_field = "id";
$this->limit = "20";
$this->orderby = "id,desc";
$this->global_privilege = false;
$this->button_table_action = true;
$this->button_bulk_action = true;
$this->button_action_style = "button_icon";
$this->button_add = true;
$this->button_edit = true;
$this->button_delete = true;
$this->button_detail = true;
$this->button_show = true;
$this->button_filter = true;
$this->button_import = false;
$this->button_export = false;
$this->table = "tasks";
# END CONFIGURATION DO NOT REMOVE THIS LINE
# START COLUMNS DO NOT REMOVE THIS LINE
$this->col = [];
$this->col[] = ["label"=>"TasksID","name"=>"task_id"];
$this->col[] = ["label"=>"Release","name"=>"release_id","join"=>"releases,release_name"];
$this->col[] = ["label"=>"Size","name"=>"size_id","join"=>"sizes,size_name"];
$this->col[] = ["label"=>"Profile","name"=>"profile_id","join"=>"profile,profile_name"];
$this->col[] = ["label"=>"Email","name"=>"profile_id","join"=>"profile,user_id"];
$this->col[] = ["label"=>"Successful Order","name"=>"successful","callback_php"=>'($row->successful == 1? "Yes" : "No")'];
$this->col[] = ["label"=>"Status","name"=>"status","callback_php"=>'($row->status == 1? "Active" : "Inactive")'];
$this->col[] = ["label"=>"Created At","name"=>"created_at","callback_php"=>'($row->created_at != "" ? date("jS M Y h:i A",strtotime($row->created_at)) : "")'];
$this->col[] = ["label"=>"Last Updated","name"=>"updated_at","callback_php"=>'($row->updated_at != "" ? date("jS M Y h:i A",strtotime($row->updated_at)) : "")'];
# END COLUMNS DO NOT REMOVE THIS LINE
# START FORM DO NOT REMOVE THIS LINE
$this->form = [];
$this->form[] = ['label'=>'Release','name'=>'release_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'releases,release_name'];
$this->form[] = ['label'=>'Size','name'=>'size_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'sizes,size_name'];
$this->form[] = ['label'=>'Profile','name'=>'profile_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'profile,profile_name'];
$this->form[] = ['label'=>'Status','name'=>'status','type'=>'radio','validation'=>'required|integer|min:0','width'=>'col-sm-10','dataenum'=>'1|Yes;0|No'];
$this->form[] = ['label'=>'Successful Order','name'=>'successful','type'=>'radio','validation'=>'required|integer|min:0','width'=>'col-sm-9','dataenum'=>'1|Yes;2|No;0|Pending'];
# END FORM DO NOT REMOVE THIS LINE
# OLD START FORM
//$this->form = [];
//$this->form[] = ['label'=>'Release','name'=>'release_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'releases,release_name'];
//$this->form[] = ['label'=>'Size','name'=>'size_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'sizes,size_name'];
//$this->form[] = ['label'=>'Profile','name'=>'profile_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-10','datatable'=>'profile,profile_name'];
//$this->form[] = ['label'=>'Status','name'=>'status','type'=>'radio','validation'=>'required|integer|min:0','width'=>'col-sm-10','dataenum'=>'1|Yes;0|No'];
//$this->form[] = ['label'=>'Successful Order','name'=>'successful','type'=>'radio','validation'=>'required|integer|min:0','width'=>'col-sm-9','dataenum'=>'1|Yes;0|Pending'];
# OLD END FORM
/*
| ----------------------------------------------------------------------
| Sub Module
| ----------------------------------------------------------------------
| @label = Label of action
| @path = Path of sub module
| @foreign_key = foreign key of sub table/module
| @button_color = Bootstrap Class (primary,success,warning,danger)
| @button_icon = Font Awesome Class
| @parent_columns = Sparate with comma, e.g : name,created_at
|
*/
$this->sub_module = array();
/*
| ----------------------------------------------------------------------
| Add More Action Button / Menu
| ----------------------------------------------------------------------
| @label = Label of action
| @url = Target URL, you can use field alias. e.g : [id], [name], [title], etc
| @icon = Font awesome class icon. e.g : fa fa-bars
| @color = Default is primary. (primary, warning, succecss, info)
| @showIf = If condition when action show. Use field alias. e.g : [id] == 1
|
*/
$this->addaction = array();
/*
| ----------------------------------------------------------------------
| Add More Button Selected
| ----------------------------------------------------------------------
| @label = Label of action
| @icon = Icon from fontawesome
| @name = Name of button
| Then about the action, you should code at actionButtonSelected method
|
*/
$this->button_selected = array();
/*
| ----------------------------------------------------------------------
| Add alert message to this module at overheader
| ----------------------------------------------------------------------
| @message = Text of message
| @type = warning,success,danger,info
|
*/
$this->alert = array();
/*
| ----------------------------------------------------------------------
| Add more button to header button
| ----------------------------------------------------------------------
| @label = Name of button
| @url = URL Target
| @icon = Icon from Awesome.
|
*/
$this->index_button = array();
$this->index_button[] = ['label'=>'Export all to Excel','url'=>"javascript:;","icon"=>"fa fa-anchor" ];
$this->index_button[] = ['label'=>'Export','url'=>"javascript:;","icon"=>"fa fa-anchor"];
/*
| ----------------------------------------------------------------------
| Customize Table Row Color
| ----------------------------------------------------------------------
| @condition = If condition. You may use field alias. E.g : [id] == 1
| @color = Default is none. You can use bootstrap success,info,warning,danger,primary.
|
*/
$this->table_row_color = array();
/*
| ----------------------------------------------------------------------
| You may use this bellow array to add statistic at dashboard
| ----------------------------------------------------------------------
| @label, @count, @icon, @color
|
*/
$this->index_statistic = array();
/*
| ----------------------------------------------------------------------
| Add javascript at body
| ----------------------------------------------------------------------
| javascript code in the variable
| $this->script_js = "function() { ... }";
|
*/
$this->script_js = NULL;
$this->script_js="
function generateexcel(id){
window.location.replace(site_url+'/generateexcel/'+id);
}
$('#export').click(function() {
var checkboxs=document.getElementsByClassName('checkbox');
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay){
$('#form-table').attr('action','tasks/exporttasks');
$('#form-table').submit();
$('#form-table').attr('action','tasks/action-selected');
}
else {
alert('Please check any tasks');
}
});
$( '#export-all-to-excel' ).click(function() {
var id=0;
window.location.replace(site_url+'/generateexcel/'+id);
});
";
/*
| ----------------------------------------------------------------------
| Include HTML Code before index table
| ----------------------------------------------------------------------
| html code to display it before index table
| $this->pre_index_html = "<p>test</p>";
|
*/
$this->pre_index_html = null;
/*
| ----------------------------------------------------------------------
| Include HTML Code after index table
| ----------------------------------------------------------------------
| html code to display it after index table
| $this->post_index_html = "<p>test</p>";
|
*/
$this->post_index_html = null;
/*
| ----------------------------------------------------------------------
| Include Javascript File
| ----------------------------------------------------------------------
| URL of your javascript each array
| $this->load_js[] = asset("myfile.js");
|
*/
$this->load_js = array();
/*
| ----------------------------------------------------------------------
| Add css style at body
| ----------------------------------------------------------------------
| css code in the variable
| $this->style_css = ".style{....}";
|
*/
$this->style_css = NULL;
/*
| ----------------------------------------------------------------------
| Include css File
| ----------------------------------------------------------------------
| URL of your css each array
| $this->load_css[] = asset("myfile.css");
|
*/
$this->load_css = array();
}
/*
| ----------------------------------------------------------------------
| Hook for button selected
| ----------------------------------------------------------------------
| @id_selected = the id selected
| @button_name = the name of button
|
*/
public function actionButtonSelected($id_selected,$button_name) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate query of index result
| ----------------------------------------------------------------------
| @query = current sql query
|
*/
public function hook_query_index(&$query) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate row of index table html
| ----------------------------------------------------------------------
|
*/
public function hook_row_index($column_index,&$column_value) {
if($column_index==5):
$column_value=CRUDBooster::first('users',['id'=>$column_value])->email;
endif;
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate data input before add data is execute
| ----------------------------------------------------------------------
| @arr
|
*/
public function hook_before_add(&$postdata) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for execute command after add public static function called
| ----------------------------------------------------------------------
| @id = last insert id
|
*/
public function hook_after_add($id) {
$taskid=strtoupper(Str::random(4)).''.$id;
DB::table($this->table)->where('id',$id)->update(['task_id'=>$taskid]);
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate data input before update data is execute
| ----------------------------------------------------------------------
| @postdata = input post data
| @id = current id
|
*/
public function hook_before_edit(&$postdata,$id) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for execute command after edit public static function called
| ----------------------------------------------------------------------
| @id = current id
|
*/
public function hook_after_edit($id) {
//Your code here
}
public function getDetail($id) {
//Create an Auth
if(!CRUDBooster::isRead() && $this->global_privilege==FALSE || $this->button_edit==FALSE) {
CRUDBooster::redirect(CRUDBooster::adminPath(),trans("crudbooster.denied_access"));
}
$data = [];
$data['page_title'] = 'Detail Data';
$data['row'] = DB::table('tasks')->select('tasks.id as tid','releases.release_name','profile.profile_name','sizes.size_name','tasks.status as status')
->Leftjoin('releases', 'releases.id', '=', 'tasks.release_id')
->Leftjoin('profile', 'profile.id', '=', 'tasks.profile_id')
->Leftjoin('sizes', 'sizes.id', '=', 'tasks.size_id')
->where('tasks.id',$id)->first();
//Please use cbView method instead view method from laravel
$this->cbView('vendor.laravel-filemanager.custom_detail_view',$data);
}
/*
| ----------------------------------------------------------------------
| Hook for execute command before delete public static function called
| ----------------------------------------------------------------------
| @id = current id
|
*/
public function hook_before_delete($id) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for execute command after delete public static function called
| ----------------------------------------------------------------------
| @id = current id
|
*/
public function hook_after_delete($id) {
//Your code here
}
public function generateExcel($id)
{
if($id > 0){
// $details = Tasks::select('profile.profile_name','users.email','releases.release_code','sizes.size_name','users.full_name','profile.delivery_address1','profile.delivery_address2','profile.delivery_city','profile.delivery_city','profile.delivery_state','profile.delivery_zip','profile.delivery_country','profile.delivery_phone','profile.payment_card_type','profile.payment_cardno','profile.payment_expmon','profile.payment_expyear','profile.payment_cvv')
// ->Leftjoin('profile', 'profile.id', '=', 'tasks.profile_id')
// ->Leftjoin('users', 'users.id', '=', 'profile.user_id')
// ->Leftjoin('sizes', 'sizes.id', '=', 'tasks.size_id')
// ->Leftjoin('releases', 'releases.id', '=', 'tasks.release_id')
// ->where('tasks.id',$id)
// ->get();
$details = DB::select(DB::raw("SELECT tasks.task_id,users.email,profile.profile_name,profile.payment_email,releases.release_code,sizes.size_name,profile.delivery_fname,profile.delivery_lname,profile.delivery_address1,profile.delivery_address2,profile.delivery_city,profile.delivery_city,profile.delivery_state,profile.delivery_zip,profile.delivery_country,profile.delivery_phone,profile.payment_card_type,profile.payment_cardno,profile.payment_expmon,profile.payment_expyear,profile.payment_cvv from tasks LEFT JOIN profile ON profile.id=tasks.profile_id LEFT JOIN users ON users.id=profile.user_id LEFT JOIN sizes ON sizes.id=tasks.size_id LEFT JOIN releases ON releases.id=tasks.release_id where tasks.id=$id"));
}
else{
// $details = Tasks::select('profile.profile_name','users.email','releases.release_code','sizes.size_name','SUBSTRING_INDEX(full_name, ' ', 1)as Fname','profile.delivery_address1','profile.delivery_address2','profile.delivery_city','profile.delivery_city','profile.delivery_state','profile.delivery_zip','profile.delivery_country','profile.delivery_phone','profile.payment_card_type','profile.payment_cardno','profile.payment_expmon','profile.payment_expyear','profile.payment_cvv')
// ->Leftjoin('profile', 'profile.id', '=', 'tasks.profile_id')
// ->Leftjoin('users', 'users.id', '=', 'profile.user_id')
// ->Leftjoin('sizes', 'sizes.id', '=', 'tasks.size_id')
// ->Leftjoin('releases', 'releases.id', '=', 'tasks.release_id')
// ->get();
$details = DB::select(DB::raw("SELECT tasks.task_id,users.email,profile.profile_name,profile.payment_email,releases.release_code,sizes.size_name,profile.delivery_fname,profile.delivery_lname,profile.delivery_address1,profile.delivery_address2,profile.delivery_city,profile.delivery_city,profile.delivery_state,profile.delivery_zip,profile.delivery_country,profile.delivery_phone,profile.payment_card_type,profile.payment_cardno,profile.payment_expmon,profile.payment_expyear,profile.payment_cvv from tasks LEFT JOIN profile ON profile.id=tasks.profile_id LEFT JOIN users ON users.id=profile.user_id LEFT JOIN sizes ON sizes.id=tasks.size_id LEFT JOIN releases ON releases.id=tasks.release_id"));
}
$detailsArray = [];
// Define the Excel spreadsheet headers
$detailsArray[] = ['TaskID','AccountEmail','Profile Name','Email','PID','Size','First Name','Last Name','Address1','Address2','City','State','Zip','Country','Phone','Card Type','Card No','Expiration Month','Expiration Year','CVV'];
foreach ($details as $detail) {
$detail = (array) $detail;
$detailsArray[] = $detail;
}
// Generate and return the spreadsheet
Excel::create('tasks', function($excel) use ($detailsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('tasks');
$excel->setCreator('botintel')->setCompany('FleekBiz');
$excel->setDescription('tasks file');
// Build the spreadsheet, passing in the payments array
$excel->sheet('tasks', function($sheet) use ($detailsArray) {
$sheet->fromArray($detailsArray, null, 'A1', false, false);
});
})->download('xlsx');
}
public function exporttasks(Request $request){
$checkboxs=$request->input('checkbox');
$check=implode(',',$checkboxs);
$details = DB::select(DB::raw("SELECT tasks.task_id,users.email,profile.profile_name,profile.payment_email,releases.release_code,sizes.size_name,profile.delivery_fname,profile.delivery_lname,profile.delivery_address1,profile.delivery_address2,profile.delivery_city,profile.delivery_city,profile.delivery_state,profile.delivery_zip,profile.delivery_country,profile.delivery_phone,profile.payment_card_type,profile.payment_cardno,profile.payment_expmon,profile.payment_expyear,profile.payment_cvv from tasks LEFT JOIN profile ON profile.id=tasks.profile_id LEFT JOIN users ON users.id=profile.user_id LEFT JOIN sizes ON sizes.id=tasks.size_id LEFT JOIN releases ON releases.id=tasks.release_id where tasks.id IN ($check)"));
$detailsArray = [];
// Define the Excel spreadsheet headers
$detailsArray[] = ['TaskID','AccountEmail','Profile Name','Email','PID','Size','First Name','Last Name','Address1','Address2','City','State','Zip','Country','Phone','Card Type','Card No','Expiration Month','Expiration Year','CVV'];
foreach ($details as $detail) {
$detail = (array) $detail;
$detailsArray[] = $detail;
}
// Generate and return the spreadsheet
Excel::create('tasks', function($excel) use ($detailsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('tasks');
$excel->setCreator('botintel')->setCompany('FleekBiz');
$excel->setDescription('tasks file');
// Build the spreadsheet, passing in the payments array
$excel->sheet('tasks', function($sheet) use ($detailsArray) {
$sheet->fromArray($detailsArray, null, 'A1', false, false);
});
})->download('xlsx');
}
//By the way, you can still create your own method in here... :)
//By the way, you can still create your own method in here... :)
}<file_sep>/app/Http/Controllers/Frontend/ProfileController.php
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use DB;
use App\Profile;
use App\User;
class ProfileController extends Controller
{
//
public function index(){
if($user=Auth::user()):
$data['userprofiles'] =DB::table('users')->select('users.*','users.id as UserID','profile.*')
->leftjoin('profile', 'profile.user_id', '=', 'users.id')
->where('profile.user_id',$user->id)
->get();
$data['subscriped']=DB::table('users')->select('users.*','users.id as UserID','subscription.*')
->leftjoin('subscription', 'subscription.id', '=', 'users.subscription_id')
->where('users.id',$user->id)
->first();
return view('front.profile',$data);
else:
return redirect('/');
endif;
}
public function getprofile(Request $request){
$getprofile=Profile::where('id',$request->input('id'))->first();
if($getprofile):
echo $getprofile;
endif;
}
public function delprofile(Request $request){
$delprofile=Profile::find($request->input('id'));
$delprofile->delete();
echo true;
}
public function insertprofile(Request $request){
$userprofile = Profile::where('user_id',Auth::user()->id)->get();
$insertprofile= new Profile;
$insertprofile->user_id=Auth::user()->id;
$i=2;
if(count($userprofile) >0):
foreach($userprofile as $userprof):
$insertprofile->profile_name='Profile '.$i;
$i++;
endforeach;
else:
$insertprofile->profile_name='Profile 1';
endif;
$insertprofile->created_at=date('Y-m-d H:i:s');
$insertprofile->save();
echo true;
}
public function submit(Request $request)
{
// print_r($request->input());
// die;
if(!empty($request->input('id'))){
$userprofile=Profile::where('id',$request->input('id'))->first();
$userprofile->profile_name=$request->input('profilename');
$userprofile->delivery_fname=$request->input('fname');
$userprofile->delivery_lname=$request->input('lname');
$userprofile->delivery_address1=$request->input('address1');
$userprofile->delivery_address2=$request->input('address2');
$userprofile->delivery_city=$request->input('city');
$userprofile->delivery_state=$request->input('state');
$userprofile->delivery_country=$request->input('countries');
$userprofile->delivery_zip=$request->input('zip');
$userprofile->delivery_phone=$request->input('phone');
$userprofile->payment_email=$request->input('paymentemail');
$userprofile->payment_card_type=$request->input('cardtype');
$userprofile->payment_cvv=$request->input('cvv');
$userprofile->payment_cardno=$request->input('cardnumber');
$userprofile->payment_expmon=$request->input('expmon');
$userprofile->payment_expyear=$request->input('expyear');
$userprofile->updated_at=date('Y-m-d H:i:s');
$userprofile->save();
return redirect()->back()->with('message', 'Profile Successfully Updated.');
}
else{
// $userprofile = Profile::where('user_id',Auth::user()->id)->get();
// $insertprofile= new Profile;
// $insertprofile->user_id=Auth::user()->id;
// $i=2;
// if(count($userprofile) >0):
// foreach($userprofile as $userprof):
// $insertprofile->profile_name='Profile '.$i;
// $i++;
// endforeach;
// else:
// $insertprofile->profile_name='Profile 1';
// endif;
$insertprofile= new Profile;
$insertprofile->user_id=Auth::user()->id;
$insertprofile->profile_name=$request->input('profilename');
$insertprofile->delivery_fname=$request->input('fname');
$insertprofile->delivery_lname=$request->input('lname');
$insertprofile->delivery_address1=$request->input('address1');
$insertprofile->delivery_address2=$request->input('address2');
$insertprofile->delivery_city=$request->input('city');
$insertprofile->delivery_state=$request->input('state');
$insertprofile->delivery_country=$request->input('countries');
$insertprofile->delivery_zip=$request->input('zip');
$insertprofile->delivery_phone=$request->input('phone');
$insertprofile->payment_email=$request->input('paymentemail');
$insertprofile->payment_card_type=$request->input('cardtype');
$insertprofile->payment_cvv=$request->input('cvv');
$insertprofile->payment_cardno=$request->input('cardnumber');
$insertprofile->payment_expmon=$request->input('expmon');
$insertprofile->payment_expyear=$request->input('expyear');
$insertprofile->created_at=date('Y-m-d H:i:s');
$insertprofile->save();
return redirect()->back()->with('message', 'Profile Successfully Inserted.');
}
}
}
<file_sep>/app/Releases.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Releases extends Model
{
//
protected $table="releases";
protected $primaryKey="id";
}
<file_sep>/app/Http/Controllers/AdminReleasesController.php
<?php namespace App\Http\Controllers;
use Session;
use Request;
use DB;
use CRUDBooster;
class AdminReleasesController extends \crocodicstudio\crudbooster\controllers\CBController {
public function cbInit() {
# START CONFIGURATION DO NOT REMOVE THIS LINE
$this->title_field = "release_name";
$this->limit = "20";
$this->orderby = "id,desc";
$this->global_privilege = false;
$this->button_table_action = true;
$this->button_bulk_action = true;
$this->button_action_style = "button_icon";
$this->button_add = true;
$this->button_edit = true;
$this->button_delete = true;
$this->button_detail = true;
$this->button_show = true;
$this->button_filter = true;
$this->button_import = false;
$this->button_export = false;
$this->table = "releases";
# END CONFIGURATION DO NOT REMOVE THIS LINE
# START COLUMNS DO NOT REMOVE THIS LINE
$this->col = [];
$this->col[] = ["label"=>"Image","name"=>"release_image","image"=>true];
$this->col[] = ["label"=>"Name","name"=>"release_name"];
$this->col[] = ["label"=>"Store","name"=>"store_id","join"=>"stores,store_name"];
$this->col[] = ["label"=>"Country","name"=>"country"];
$this->col[] = ["label"=>"Release Date","name"=>"release_date"];
$this->col[] = ["label"=>"Submission Time Limit","name"=>"submission_time","callback_php"=>'$row->submission_time .=" hours"'];
$this->col[] = ["label"=>"Status","name"=>"status","callback_php"=>'($row->status == 1? "Active" : "Inactive")'];
# END COLUMNS DO NOT REMOVE THIS LINE
# START FORM DO NOT REMOVE THIS LINE
$this->form = [];
$this->form[] = ['label'=>'SKU','name'=>'release_code','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-6'];
$this->form[] = ['label'=>'Store','name'=>'store_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-6','datatable'=>'stores,store_name'];
$this->form[] = ['label'=>'Country','name'=>'country','type'=>'select2','validation'=>'required|min:1|max:255','width'=>'col-sm-6','dataenum'=>'US;EU;AU;CA;GB;DE;DK;FR;IT;NL;RU;'];
$this->form[] = ['label'=>'Name','name'=>'release_name','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-6'];
$this->form[] = ['label'=>'Description','name'=>'release_description','type'=>'textarea','validation'=>'required','width'=>'col-sm-6'];
$this->form[] = ['label'=>'Release Date','name'=>'release_date','type'=>'datetime','validation'=>'required|date_format:Y-m-d H:i:s','width'=>'col-sm-6'];
$this->form[] = ['label'=>'Submission Time Limit','name'=>'submission_time','type'=>'number','validation'=>'required|min:0|max:100','width'=>'col-sm-6'];
$this->form[] = ['label'=>'Image','name'=>'release_image','type'=>'upload','validation'=>'required|min:1|max:1000','width'=>'col-sm-6'];
$this->form[] = ['label'=>'Status','name'=>'status','type'=>'radio','validation'=>'required|integer|min:0','width'=>'col-sm-6','dataenum'=>'1|Active;0|In Active'];
# END FORM DO NOT REMOVE THIS LINE
# OLD START FORM
//$this->form = [];
//$this->form[] = ['label'=>'SKU','name'=>'release_code','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-6'];
//$this->form[] = ['label'=>'Store','name'=>'store_id','type'=>'select2','validation'=>'required|integer|min:0','width'=>'col-sm-6','datatable'=>'stores,store_name'];
//$this->form[] = ['label'=>'Country','name'=>'country','type'=>'select2','validation'=>'required|min:1|max:255','width'=>'col-sm-6','dataenum'=>'US;EU;AU;CA;GB;DE;DK;FR;IT;NL;RU;'];
//$this->form[] = ['label'=>'Name','name'=>'release_name','type'=>'text','validation'=>'required|min:1|max:255','width'=>'col-sm-6'];
//$this->form[] = ['label'=>'Description','name'=>'release_description','type'=>'textarea','validation'=>'required','width'=>'col-sm-6'];
//$this->form[] = ['label'=>'Release Date','name'=>'release_date','type'=>'datetime','validation'=>'required|date_format:Y-m-d H:i:s','width'=>'col-sm-6'];
//$this->form[] = ['label'=>'Submission Time Limit','name'=>'submission_time','type'=>'number','validation'=>'required|min:0|max:100','width'=>'col-sm-6'];
//$this->form[] = ['label'=>'Image','name'=>'release_image','type'=>'upload','validation'=>'required|min:1|max:1000','width'=>'col-sm-6'];
//$this->form[] = ['label'=>'Status','name'=>'status','type'=>'radio','validation'=>'required|integer|min:0','width'=>'col-sm-6','dataenum'=>'1|Active;0|In Active'];
# OLD END FORM
/*
| ----------------------------------------------------------------------
| Sub Module
| ----------------------------------------------------------------------
| @label = Label of action
| @path = Path of sub module
| @foreign_key = foreign key of sub table/module
| @button_color = Bootstrap Class (primary,success,warning,danger)
| @button_icon = Font Awesome Class
| @parent_columns = Sparate with comma, e.g : name,created_at
|
*/
$this->sub_module = array();
/*
| ----------------------------------------------------------------------
| Add More Action Button / Menu
| ----------------------------------------------------------------------
| @label = Label of action
| @url = Target URL, you can use field alias. e.g : [id], [name], [title], etc
| @icon = Font awesome class icon. e.g : fa fa-bars
| @color = Default is primary. (primary, warning, succecss, info)
| @showIf = If condition when action show. Use field alias. e.g : [id] == 1
|
*/
$this->addaction = array();
/*
| ----------------------------------------------------------------------
| Add More Button Selected
| ----------------------------------------------------------------------
| @label = Label of action
| @icon = Icon from fontawesome
| @name = Name of button
| Then about the action, you should code at actionButtonSelected method
|
*/
$this->button_selected = array();
/*
| ----------------------------------------------------------------------
| Add alert message to this module at overheader
| ----------------------------------------------------------------------
| @message = Text of message
| @type = warning,success,danger,info
|
*/
$this->alert = array();
/*
| ----------------------------------------------------------------------
| Add more button to header button
| @label = Name of button
| @url = URL Target
| @icon = Icon from Awesome.
|
*/
$this->index_button = array();
$this->index_button[] = ['label'=>'Get US Products','url'=>"javascript:;","icon"=>"fa fa-check"];
$this->index_button[] = ['label'=>'Get EU Products','url'=>"javascript:;","icon"=>"fa fa-anchor"];
/*
| ----------------------------------------------------------------------
| Customize Table Row Color
| ----------------------------------------------------------------------
| @condition = If condition. You may use field alias. E.g : [id] == 1
| @color = Default is none. You can use bootstrap success,info,warning,danger,primary.
|
*/
$this->table_row_color = array();
/*
| ----------------------------------------------------------------------
| You may use this bellow array to add statistic at dashboard
| ----------------------------------------------------------------------
| @label, @count, @icon, @color
|
*/
$this->index_statistic = array();
/*
| ----------------------------------------------------------------------
| Add javascript at body
| ----------------------------------------------------------------------
| javascript code in the variable
| $this->script_js = "function() { ... }";
|
*/
$this->script_js = NULL;
$this->script_js="
$('#get-us-products').click(function(e) {
$.get(site_url+'/get_us_products', function( data ) {
if(data=='inserted'){
location.reload();
}
});
});
$('#get-eu-products').click(function(e) {
$.get(site_url+'/get_eu_products', function( data ) {
if(data=='inserted'){
location.reload();
}
});
});
";
/*
| ----------------------------------------------------------------------
| Include HTML Code before index table
| ----------------------------------------------------------------------
| html code to display it before index table
| $this->pre_index_html = "<p>test</p>";
|
*/
$this->pre_index_html = null;
/*
| ----------------------------------------------------------------------
| Include HTML Code after index table
| ----------------------------------------------------------------------
| html code to display it after index table
| $this->post_index_html = "<p>test</p>";
|
*/
$this->post_index_html = null;
/*
| ----------------------------------------------------------------------
| Include Javascript File
| ----------------------------------------------------------------------
| URL of your javascript each array
| $this->load_js[] = asset("myfile.js");
|
*/
$this->load_js = array();
/*
| ----------------------------------------------------------------------
| Add css style at body
| ----------------------------------------------------------------------
| css code in the variable
| $this->style_css = ".style{....}";
|
*/
$this->style_css = NULL;
/*
| ----------------------------------------------------------------------
| Include css File
| ----------------------------------------------------------------------
| URL of your css each array
| $this->load_css[] = asset("myfile.css");
|
*/
$this->load_css = array();
}
public function GetUSProducts()
{
# code...
$nikeproducts="https://api.nike.com/commerce/productfeed/products/snkrs/threads?country=US&limit=50&locale=en_US&skip=0&withCards=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $nikeproducts);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
$nikeProducts=json_decode($data);
$description="";
$deletescrapped=DB::table('releases')->where('is_scrapped',1)->where('country','US')->delete();
foreach ($nikeProducts->threads as $nikeProduct) {
$storeid=1;
$country=US;
if(!empty($nikeProduct->product->title)):
$title=$nikeProduct->product->title;
$releasedate=$nikeProduct->product->startSellDate;
$sku= strtoupper($nikeProduct->product->style).'-'.$nikeProduct->product->colorCode;
$imageUrl=$nikeProduct->product->imageUrl.'?&wid=2500&fmt=png-alpha';
$datenow=date('Y-m-d H:s:i');
foreach ($nikeProduct->cards as $nikecard) {
# code...
if(!empty($nikecard->description) && $description==""): $description=$nikecard->description; endif ;
}
$releaseinsert=DB::table('releases')->insertGetId(['store_id' => $storeid, 'country' => $country, 'release_name' => $title,'release_description' => $description, 'release_date' => $releasedate, 'release_code' => $sku,'is_scrapped' =>1, 'release_image' => $imageUrl, 'created_at' => $datenow]
);
$releasesdetail=CRUDBooster::first('releases',['id'=>$releaseinsert]);
$releasedate=$releasesdetail->release_date;
$submission_time='-'.$releasesdetail->submission_time.' hours';
$subtime = date('Y-m-d H:i:s', strtotime($submission_time, strtotime($releasedate)));
DB::table('releases')->where('id',$releaseinsert)->update(['sub_time'=>$subtime]);
endif;
}
echo 'inserted';
} public function GetEUProducts()
{
# code...
$nikeproducts="https://api.nike.com/commerce/productfeed/products/snkrs/threads?country=GB&limit=50&locale=en_GB&skip=0&withCards=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $nikeproducts);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
$nikeProducts=json_decode($data);
$deletescrapped=DB::table('releases')->where('is_scrapped',1)->where('country','EU')->delete();
$description="";
foreach ($nikeProducts->threads as $nikeProduct) {
$storeid=1;
$country=EU;
if(!empty($nikeProduct->product->title)):
$title=$nikeProduct->product->title;
$releasedate=$nikeProduct->product->startSellDate;
$sku= strtoupper($nikeProduct->product->style).'-'.$nikeProduct->product->colorCode;
$imageUrl=$nikeProduct->product->imageUrl.'?&wid=2500&fmt=png-alpha';
$datenow=date('Y-m-d H:s:i');
foreach ($nikeProduct->cards as $nikecard) {
# code...
if(!empty($nikecard->description) && $description==""): $description=$nikecard->description; endif ;
}
$releaseinsert=DB::table('releases')->insertGetId(['store_id' => $storeid, 'country' => $country, 'release_name' => $title,'release_description' => $description, 'release_date' => $releasedate, 'release_code' => $sku,'is_scrapped' =>1, 'release_image' => $imageUrl, 'created_at' => $datenow]
);
$releasesdetail=CRUDBooster::first('releases',['id'=>$releaseinsert]);
$releasedate=$releasesdetail->release_date;
$submission_time='-'.$releasesdetail->submission_time.' hours';
$subtime = date('Y-m-d H:i:s', strtotime($submission_time, strtotime($releasedate)));
DB::table('releases')->where('id',$releaseinsert)->update(['sub_time'=>$subtime]);
endif;
}
echo 'inserted';
}
/*
| ----------------------------------------------------------------------
| Hook for button selected
| ----------------------------------------------------------------------
| @id_selected = the id selected
| @button_name = the name of button
|
*/
public function actionButtonSelected($id_selected,$button_name) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate query of index result
| ----------------------------------------------------------------------
| @query = current sql query
|
*/
public function hook_query_index(&$query) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate row of index table html
| ----------------------------------------------------------------------
|
*/
public function hook_row_index($column_index,&$column_value) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate data input before add data is execute
| ----------------------------------------------------------------------
| @arr
|
*/
public function hook_before_add(&$postdata) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for execute command after add public static function called
| ----------------------------------------------------------------------
| @id = last insert id
|
*/
public function hook_after_add($id) {
//Your code here
$releasesdetail=CRUDBooster::first('releases',['id'=>$id]);
$releasedate=$releasesdetail->release_date;
$submission_time='-'.$releasesdetail->submission_time.' hours';
$subtime = date('Y-m-d H:i:s', strtotime($submission_time, strtotime($releasedate)));
DB::table($this->table)->where('id',$id)->update(['sub_time'=>$subtime]);
}
/*
| ----------------------------------------------------------------------
| Hook for manipulate data input before update data is execute
| ----------------------------------------------------------------------
| @postdata = input post data
| @id = current id
|
*/
public function hook_before_edit(&$postdata,$id) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for execute command after edit public static function called
| ----------------------------------------------------------------------
| @id = current id
|
*/
public function hook_after_edit($id) {
//Your code here
$releasesdetail=CRUDBooster::first('releases',['id'=>$id]);
$releasedate=$releasesdetail->release_date;
$submission_time='-'.$releasesdetail->submission_time.' hours';
$subtime = date('Y-m-d H:i:s', strtotime($submission_time, strtotime($releasedate)));
DB::table($this->table)->where('id',$id)->update(['sub_time'=>$subtime]);
}
/*
| ----------------------------------------------------------------------
| Hook for execute command before delete public static function called
| ----------------------------------------------------------------------
| @id = current id
|
*/
public function hook_before_delete($id) {
//Your code here
}
/*
| ----------------------------------------------------------------------
| Hook for execute command after delete public static function called
| ----------------------------------------------------------------------
| @id = current id
|
*/
public function hook_after_delete($id) {
//Your code here
}
//By the way, you can still create your own method in here... :)
}<file_sep>/app/Http/Controllers/Frontend/PagesController.php
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Pages;
class PagesController extends Controller
{
//
public function index($slug){
$data['pagedetails']=Pages::where('page_slug',$slug)->where('is_blog',0)->where('status',1)->first();
$data['Title']=explode(' ',$data['pagedetails']->page_name);
return view('front.pages',$data);
}
}
<file_sep>/app/Http/Controllers/Frontend/HomeController.php
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Redirect;
class HomeController extends Controller
{
//
public function index(){
if(!Auth::user()):
return view('front.home');
else:
return Redirect::to('/release');
endif;
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', ['uses' => 'Frontend\HomeController@index']);
Route::get('/signup', ['uses' => 'Frontend\SignupController@index']);
Route::get('/verification/{slug}', ['uses' => 'Auth\RegisterController@verification']);
Route::post('/forgotpasswordsubmit', ['uses' => 'Auth\ForgotPasswordController@forgotsubmit']);
Route::get('/changepassword/{slug}', ['uses' => 'Auth\ForgotPasswordController@changepassword']);
Route::post('/passwordsubmit/', ['uses' => 'Auth\ForgotPasswordController@passwordsubmit']);
Route::get('/profile', ['uses' => 'Frontend\ProfileController@index']);
Route::post('/profile/getProfile', ['uses' => 'Frontend\ProfileController@getprofile']);
Route::post('/profile/delProfile', ['uses' => 'Frontend\ProfileController@delprofile']);
Route::post('/profile/insertProfile', ['uses' => 'Frontend\ProfileController@insertprofile']);
Route::post('/profile/submit', ['uses' => 'Frontend\ProfileController@submit']);
Route::get('/settings', ['uses' => 'Frontend\SettingsController@index']);
Route::post('/settingssubmit', ['uses' => 'Frontend\SettingsController@update']);
Route::post('/settings/upgrade', ['uses' => 'Frontend\SettingsController@upgradeplan']);
Route::post('/settings/cancel', ['uses' => 'Frontend\SettingsController@cancelplan']);
Route::post('/changepasswordsubmit', ['uses' => 'Frontend\SettingsController@changepassword']);
Route::get('/release', ['uses' => 'Frontend\ReleaseController@index']);
Route::get('/releases/checkRelease', ['uses' => 'Frontend\ReleaseController@checkrelease']);
Route::get('/tasks', ['uses' => 'Frontend\TasksController@index']);
Route::post('/tasks/getData', ['uses' => 'Frontend\TasksController@getdata']);
Route::post('/tasks/cookie', ['uses' => 'Frontend\TasksController@Cookie']);
Route::get('/tasks/getcookiedata', ['uses' => 'Frontend\TasksController@getCookiedata']);
Route::post('/tasks/submit', ['uses' => 'Frontend\TasksController@submit']);
Route::post('/tasks/newTask', ['uses' => 'Frontend\TasksController@newTask']);
Route::post('/tasks/upTask', ['uses' => 'Frontend\TasksController@upTask']);
Route::post('/tasks/delTask', ['uses' => 'Frontend\TasksController@delTask']);
Route::get('/tasks/deletealltasks', ['uses' => 'Frontend\TasksController@deletealltasks']);
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
Route::post('register/store', 'Auth\RegisterController@store');
Route::post('register/update', 'Auth\RegisterController@updatestripe');
Auth::routes();
Route::get('get_us_products', ['uses' => 'AdminReleasesController@GetUSProducts']);
Route::get('get_eu_products', ['uses' => 'AdminReleasesController@GetEUProducts']);
Route::get('generateexcel/{slug}', ['uses' => 'AdminTasksController@generateExcel']);
Route::post('admin/tasks/exporttasks', ['uses' => 'AdminTasksController@exporttasks']);
Route::get('/{slug}', ['uses' => 'Frontend\PagesController@index']);
Route::get('admin/successorders/import-data', ['uses' => 'AdminSuccessfulOrdersController@ImportExcel']);
Route::post('admin/successorders/submitimport', ['uses' => 'AdminSuccessfulOrdersController@SubmitImport']);
Route::get('/home', 'HomeController@index')->name('home');
<file_sep>/app/Http/Controllers/Frontend/TasksController.php
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;
use Auth;
use DB;
use Cookie;
use Session;
use App\Subscriptions;
use App\Tasks;
use App\Releases;
use App\Sizes;
use App\Profiles;
class TasksController extends Controller
{
public function index(Request $request){
// $data['now'] = date('Y-m-d H:i:s');
// print_r($data['now']);
// die;
if (Auth::user()):
$data['now'] = date('Y-m-d H:i:s');
$data['releases'] = Releases::where('sub_time', '>', $data['now'])->get();
$data['sizes'] = Sizes::all();
$data['profiles'] = Profiles::where('user_id', Auth::user()->id)->where('delivery_fname', '!=', '')->where('delivery_lname', '!=', '')->get();
$data['usertasks'] = DB::table('tasks')->select('tasks.*', 'releases.release_date', 'releases.release_name', 'releases.release_code', 'releases.sub_time', 'releases.id as rid', 'sizes.id as sid', 'sizes.size_name', 'profile.id as pid', 'profile.profile_name')->leftjoin('profile', 'tasks.profile_id', '=', 'profile.id')->leftjoin('releases', 'tasks.release_id', '=', 'releases.id')->leftjoin('sizes', 'tasks.size_id', '=', 'sizes.id')->where('profile.user_id', Auth::user()->id)->get();
$data['usertasksdone'] = count($data['usertasks']);
$data['subscription'] = Subscriptions::where('id', Auth::user()->subscription_id)->first();
return view('front.tasks', $data);
else:
return redirect('/');
endif;
}
public function getdata(){
$now = date('Y-m-d H:i:s');
$releases = Releases::where('sub_time', '>', $now)->get();
$sizes = Sizes::all();
$profiles = Profiles::where('user_id', Auth::user()->id)->where('delivery_fname', '!=', '')->where('delivery_lname', '!=', '')->get();
$usertasksdone = DB::table('tasks')->leftjoin('profile', 'tasks.profile_id', '=', 'profile.id')->where('profile.user_id', Auth::user()->id)->count();
$subscription = Subscriptions::where('id', Auth::user()->subscription_id)->first();
$html = '<div class="col-md-12"><div class="col-md-6"><div class="form-group"> <label >Release</label><select name="release[]" onchange="taskchange()" required class="form-control"><option value="">Please select one</option>';
foreach ($releases as $release):
$html .= '<option data-text="' . $release->release_name . '-' . $release->release_code . '" data-countdown="' . $release->sub_time . '" value="' . $release->id . '">' . $release->release_name . '</option>';
endforeach;
$html .= '</select></div></div><div class="col-md-2"><div class="form-group"><label for="">Size</label><select name="size[]" onchange="taskchange()"class="form-control" required ><option value="">Please select one</option>';
foreach ($sizes as $size):
$html .= '<option value="' . $size->id . '">' . $size->size_name . '</option>';
endforeach;
$html .= '</select></div></div><div class="col-md-2"><div class="form-group"><label for="">Profile</label><select name="profile[]" onchange="taskchange()" class="form-control" required ><option value="">Please select one</option>';
foreach ($profiles as $profile):
$html .= '<option value="' . $profile->id . '">' . $profile->profile_name . '</option>';
endforeach;
$html .= '</select></div></div><div class="col-md-2"><button type="button" onclick="delgRow(this,' . $usertasksdone . ',' . $subscription->number_of_profiles . ')" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-dlt" data-toggle="tooltip" data-placement="right" ><i class="glyphicon glyphicon-minus"></i></button>
<button type="button" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-ins"><i class="glyphicon glyphicon-check"></i></button>
</div></div>';
// <button class="btn btn-primary" style="background:#00bcd4;" type="button" onclick="unsubmit()">UNSUBMIT</button>
// <button class="btn btn-primary" type="button" onclick="submitone()">SUBMIT</button>
echo json_encode($html);
}
public function submit(Request $request){
$release = $request->input('release_db');
for($i=0; $i < count($release); $i++):
$tasks = Tasks::where('id',$request->input('tid')[$i])->first();
$tasks->release_id=$request->input('release_db')[$i];
$tasks->size_id=$request->input('size_db')[$i];
$tasks->profile_id=$request->input('profile_db')[$i];
$tasks->save();
endfor;
$release = $request->input('release');
for($i=0; $i < count($release); $i++):
$tasks = new Tasks;
$tasks->task_id=$request->input('release')[$i];
$tasks->release_id=$request->input('release')[$i];
$tasks->size_id=$request->input('size')[$i];
$tasks->profile_id=$request->input('profile')[$i];
$tasks->save();
$taskid=strtoupper(Str::random(4)).''.$tasks->id;
$tasksup = Tasks::where('id',$tasks->id)->first();
$tasksup->task_id=$taskid;
$tasksup->save();
endfor;
echo 1;
}
public function newTask(Request $request){
$release = $request->input('release');
$size = $request->input('size');
$profile = $request->input('profile');
$task = new Tasks;
$task->release_id = $release;
$task->size_id = $size;
$task->profile_id = $profile;
$task->created_at = date('Y-m-d H:i:s');
$task->save();
$id=$task->id;
$taskid=strtoupper(Str::random(4)).''.$id;
$tasks = Tasks::where('id',$id)->first();
$tasks->task_id=$taskid;
$tasks->save();
echo 1;
}
public function upTask(Request $request){
$returnValue = DB::table('tasks')
->where('id', '=', $request->input('id') )
->update([
'release_id' => $request->input('release'),
'size_id' => $request->input('size'),
'profile_id' => $request->input('profile'),
'updated_at' => date('Y-m-d H:i:s'),
]);
echo 1;
}
public function delTask(Request $request){
DB::table('tasks')->where('id', '=', $request->input('task_id'))->delete();
echo 1;
}
public function Cookie(Request $request){
$release = $request->release;
$size = $request->size;
$profile = $request->profile;
$tasks = array(
'release_id' => $release,
'size_id' => $size,
'profile_id' => $profile
);
$array_json = json_encode($tasks);
echo $array_json;
}
public function deletealltasks(){
$now = date('Y-m-d H:i:s');
$tasks = DB::table('tasks')->leftjoin('profile', 'tasks.profile_id', '=', 'profile.id')->leftjoin('releases', 'tasks.release_id', '=', 'releases.id')->where('profile.user_id', Auth::user()->id)->where('releases.sub_time', '>', $now)->delete();
echo $tasks;
die;
}
public function getCookiedata(Request $request){
$now = date('Y-m-d H:i:s');
$tasks = json_decode($request->tasks);
$tasklen = count($tasks->release_id);
$releases = Releases::where('sub_time', '>', $now)->get();
// print_r($releases);
// echo $now;
// die;
$sizes = Sizes::all();
$profiles = Profiles::where('user_id', Auth::user()->id)->where('delivery_fname', '!=', '')->where('delivery_lname', '!=', '')->get();
$usertasks = DB::table('tasks')->select('tasks.*', 'releases.release_date', 'releases.release_name', 'releases.release_code', 'releases.sub_time', 'releases.id as rid', 'sizes.id as sid', 'sizes.size_name', 'profile.id as pid', 'profile.profile_name')->leftjoin('profile', 'tasks.profile_id', '=', 'profile.id')->leftjoin('releases', 'tasks.release_id', '=', 'releases.id')->leftjoin('sizes', 'tasks.size_id', '=', 'sizes.id')->where('profile.user_id', Auth::user()->id)->where('tasks.successful','!=',2)->get()->toArray();
$usertasksdone = count($usertasks);
$subscription = Subscriptions::where('id', Auth::user()->subscription_id)->first();
$html = '<input type="hidden" id="nowtime" value="'.$now.'">';
if ($usertasksdone > 0):
foreach ($usertasks as $usertask):
$html .= '<div class="col-md-12"><div class="col-md-6"><div class="form-group"> <label >Release</label>
<input type="hidden" name="tid[]" value="' . $usertask->id . '">';
if ($usertask->sub_time < $now || $usertask->successful==1):
$html .= '<p>' . $usertask->release_name . '</p>';
else:
$html .= '<select name="release_db[]" required class="form-control"><option value="">Please select one</option>';
foreach ($releases as $release):
$html .= '<option data-text="' . $release->release_name . '-' . $release->release_code . '" ' . ($usertask->release_id == $release->id ? 'selected' : '') . ' data-countdown="' . $release->sub_time . '" value="' . $release->id . '">' . $release->release_name . '</option>';
endforeach;
$html .= '</select>';
endif;
$html .= '</div></div><div class="col-md-2"><div class="form-group"><label for="">Size</label>';
if ($usertask->sub_time < $now || $usertask->successful==1):
$html .= '<p>' . $usertask->size_name . '</p>
<input type="hidden" value="' . $usertask->sid . '">';
else:
$html .= '<select name="size_db[]" class="form-control" required ><option value="">Please select one</option>';
foreach ($sizes as $size):
$html .= '<option ' . ($usertask->size_id == $size->id ? 'selected' : '') . ' value="' . $size->id . '">' . $size->size_name . '</option>';
endforeach;
$html .= '</select>';
endif;
$html .= '</div></div><div class="col-md-2"><div class="form-group"><label for="">Profile</label>';
if ($usertask->sub_time < $now || $usertask->successful==1):
$html .= '<p>' . $usertask->profile_name . '</p>
<input type="hidden" value="' . $usertask->pid . '">';
else:
$html .= '<select name="profile_db[]" onchange="taskchange()" class="form-control" required ><option value="">Please select one</option>';
foreach ($profiles as $profile):
$html .= '<option ' . ($usertask->profile_id == $profile->id ? 'selected' : '') . ' value="' . $profile->id . '">' . $profile->profile_name . '</option>';
endforeach;
$html .= '</select>';
endif;
$html .= '</div></div>';
if ($usertask->sub_time > $now && $usertask->successful==0):
$html .= '<div class="col-md-2"><button type="button" style="margin-top:59px;" data-taskid="'.$usertask->id.'" onclick="delgRow(this,'.$usertasksdone.','.$subscription->number_of_profiles.')" href="javascript:void(0)" class="btn btn-default btn-circle btn-lg"><i class="glyphicon glyphicon-minus"></i></button>
<button type="button" data-tid="'.$usertask->id.'" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-upd"><i class="glyphicon glyphicon-edit"></i></button></div>';
elseif($usertask->successful==1):
$html .= '<div class="col-md-2">
<button type="button" href="javascript:;" class="btn btn-primary btn-circle btn-lg "><i class="glyphicon glyphicon-check"></i></button></div>';
endif;
$html .= '</div>';
endforeach;
else:
$html .='<div class="col-md-12"><div class="col-md-6"><div class="form-group"> <label >Release</label><select name="release[]" onchange="taskchange()" required class="form-control"><option value="">Please select one</option>';
foreach($releases as $release):
$html .='<option data-text="'.$release->release_name.'-'.$release->release_code.'" data-countdown="'.$release->sub_time.'" value="'.$release->id.'">'.$release->release_name.'</option>';
endforeach;
$html .='</select></div></div><div class="col-md-2"><div class="form-group"><label for="">Size</label><select name="size[]" onchange="taskchange()"class="form-control" required ><option value="">Please select one</option>';
foreach($sizes as $size):
$html .='<option value="'.$size->id.'">'.$size->size_name.'</option>';
endforeach;
$html .='</select></div></div><div class="col-md-2"><div class="form-group"><label for="">Profile</label><select name="profile[]" onchange="taskchange()" class="form-control" required ><option value="">Please select one</option>';
foreach($profiles as $profile):
$html .='<option value="'.$profile->id.'">'.$profile->profile_name.'</option>';
endforeach;
$html .='</select></div></div><div class="col-md-2">
<button type="button" style="margin-top:59px; display:none;" onclick="delgRow(this,' . $usertasksdone . ',' . $subscription->number_of_profiles . ')" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-dlt"><i class="glyphicon glyphicon-minus"></i></button>
<button type="button" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-ins"><i class="glyphicon glyphicon-check"></i></button></div></div>';
endif;
for ($i = 0; $i < $tasklen; $i++) {
$html .= '<div class="col-md-12"><div class="col-md-6"><div class="form-group"> <label >Release</label><select name="release[]" onchange="taskchange()" required class="form-control"><option value="">Please select one</option>';
foreach ($releases as $release):
$html .= '<option data-text="' . $release->release_name . '-' . $release->release_code . '" data-countdown="' . $release->sub_time . '" ' . ($tasks->release_id[$i] == $release->id ? 'selected' : '') . ' value="' . $release->id . '">' . $release->release_name . '</option>';
endforeach;
$html .= '</select></div></div><div class="col-md-2"><div class="form-group"><label for="">Size</label><select name="size[]" onchange="taskchange()"class="form-control" required ><option value="">Please select one</option>';
foreach ($sizes as $size):
$html .= '<option ' . ($tasks->size_id[$i] == $size->id ? 'selected' : '') . ' value="' . $size->id . '">' . $size->size_name . '</option>';
endforeach;
$html .= '</select></div></div><div class="col-md-2"><div class="form-group"><label for="">Profile</label><select name="profile[]" onchange="taskchange()" class="form-control" required ><option value="">Please select one</option>';
foreach ($profiles as $profile):
$html .= '<option ' . ($tasks->profile_id[$i] == $profile->id ? 'selected' : '') . ' value="' . $profile->id . '">' . $profile->profile_name . '</option>';
endforeach;
$html .= '</select></div></div><div class="col-md-2">
<button type="button" style="margin-top:59px;" onclick="delgRow(this,' . $usertasksdone . ',' . $subscription->number_of_profiles . ')" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-dlt"><i class="glyphicon glyphicon-minus"></i></button>
<button type="button" href="javascript:;" class="btn btn-default btn-circle btn-lg btn-ins"><i class="glyphicon glyphicon-check"></i></button>
</div></div></div>';
}
echo json_encode($html);
}
}
| 2296f8e6175c3e45dce74bf2306ce4c0fc00bfb0 | [
"JavaScript",
"PHP"
] | 14 | PHP | saadkhalil/botintel | 6bbfbe648125a6ef92a5d000bcfd61ffaeef2c80 | 945cc7c34e6af589afc5acd6f86a7fff1a95ae24 |
refs/heads/master | <repo_name>alexanderkrusina/Chess-Java<file_sep>/README.md
# Chess
Single client chess implemented in Java
1. git clone
2. Navigate to src folder
3. javac Application.java
3. java application
Alternatively, run the .jar file to start the game.

All icons from https://thenounproject.com/<file_sep>/src/Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class Controller {
private View view;
private Model model;
private JButton oldSpot;
public Controller(View v, Model m) {
view = v;
model = m;
view.setListeners(new ButtonListener());
}
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
boolean isWhitePiece = view.isWhitePiece((JButton)e.getSource());
if(model.getIsOver()) {
//JOptionPane.showMessageDialog(null, "The game is over!", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(!model.getPieceSelected()) {
oldSpot = (JButton) e.getSource();
if(((JButton)e.getSource()).getIcon()!= null) {
if(model.getWhiteTurn() && !isWhitePiece) {
JOptionPane.showMessageDialog(null, "This is not your piece!", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(!model.getWhiteTurn() && isWhitePiece) {
JOptionPane.showMessageDialog(null, "This is not your piece!", "Error", JOptionPane.ERROR_MESSAGE);
}
else {
view.setSelectedButton((JButton)e.getSource());
view.setSelectedIcon(((JButton)e.getSource()).getIcon());
model.setPieceSelected(true);
}
}
}
else { // if a piece IS selected
makeMove((JButton)e.getSource());
}
}
}
public void makeMove(JButton newSpot) {
Icon newSpotIcon = newSpot.getIcon();
// can't move on top of own piece
if(model.getWhiteTurn()) {
if(view.isWhitePiece(newSpot)) {
JOptionPane.showMessageDialog(null, "Illegal move!", "Error", JOptionPane.ERROR_MESSAGE);
model.setPieceSelected(false);
return;
}
}
else {
if(view.isBlackPiece(newSpot)) {
JOptionPane.showMessageDialog(null, "Illegal move!", "Error", JOptionPane.ERROR_MESSAGE);
model.setPieceSelected(false);
return;
}
}
// check if move is legal
if(!checkMovePiece(newSpot)) {
JOptionPane.showMessageDialog(null, "Illegal move!", "Error", JOptionPane.ERROR_MESSAGE);
model.setPieceSelected(false);
return;
}
// if move is legal
newSpot.setIcon(view.getSelectedIcon());
view.getSelectedButton().setIcon(null);
model.setPieceSelected(false);
// check if in check after move
if(checkCheck()) {
oldSpot.setIcon(view.getSelectedIcon());
newSpot.setIcon(newSpotIcon);
JOptionPane.showMessageDialog(null, "Illegal move!", "Error", JOptionPane.ERROR_MESSAGE);
//model.setPieceSelected(false);
return;
}
if((view.getSelectedIcon()==view.getWhitePawn() || view.getSelectedIcon()==view.getBlackPawn()) && view.isEndOfBoard(newSpot)) {
changePawnToPiece(newSpot);
}
// Taking if en passant is enabled
if(model.getEnPassantAvailable()) {
if(model.getWhiteTurn()) {
if(view.getRow(newSpot) == 2 && view.getCol(newSpot) == model.getEnPassantColumn()) {
view.getBoardSpots()[3][model.getEnPassantColumn()].setIcon(null);
}
}
else { // black turn
if(view.getRow(newSpot) == 5 && view.getCol(newSpot) == model.getEnPassantColumn()) {
view.getBoardSpots()[4][model.getEnPassantColumn()].setIcon(null);
}
}
}
// resetting en passant
model.setEnPassantAvailable(false);
// if everything is good - other player's turn
model.setWhiteTurn(!model.getWhiteTurn());
// Enabling en passant if pawn moved 2 spots
if(view.getSelectedIcon() == view.getWhitePawn()) {
if(view.getRow(oldSpot) == 6 && view.getRow(newSpot) == 4) {
model.setEnPassantAvailable(true);
model.setEnPassantColumn(view.getCol(oldSpot));
}
}
else if(view.getSelectedIcon() == view.getBlackPawn()) {
if(view.getRow(oldSpot) == 1 && view.getRow(newSpot) == 3) {
model.setEnPassantAvailable(true);
model.setEnPassantColumn(view.getCol(oldSpot));
}
}
// If in check - check if it's possible to get out
if(checkCheck()) {
if(!canEscape()) {
model.setIsOver(true);
String winner;
if(model.getWhiteTurn()) {
winner = "Black";
}
else {
winner = "White";
}
JOptionPane.showMessageDialog(null, winner + " has won the game!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
}
}
}
/**
* Called after a turn ends if the next player is in check.
* Checks whether it's possible for the player to escape check.
* This is done by checking every possible move for all of the players remaining pieces
* and checking if it is in check after every possible move or not
* @return true if it's possible to escape, false otherwise.
*/
public boolean canEscape() {
// Check every spot on the board and select any pieces
for(int i=0;i<8;i++) {
for(int j=0;j<8;j++) {
oldSpot = view.getBoardSpots()[i][j];
if(model.getWhiteTurn()) { // White turn
if(view.isWhitePiece(oldSpot)) {
if(checkEverySpot(i,j)) {
return true;
}
}
}
else { // black turn
if(view.isBlackPiece(view.getBoardSpots()[i][j])) {
if(view.isBlackPiece(oldSpot)) {
if(checkEverySpot(i,j)) {
return true;
}
}
}
}
}
}
return false;
}
/**
* Checks if the player is in check
* @return true if the player is in check, false otherwise
*/
public boolean checkCheck() {
if(model.getWhiteTurn()) {
int[] kingSpot = view.whiteKingSpot();
int kingRow = kingSpot[0];
int kingCol = kingSpot[1];
// knight
int[][] knightSpots = { // [0-7][0-1]
{kingRow+1,kingCol+2},{kingRow+2,kingCol+1},{kingRow-1,kingCol+2},{kingRow-2,kingCol+1},
{kingRow+1,kingCol-2},{kingRow+2,kingCol-1},{kingRow-1,kingCol-2},{kingRow-2,kingCol-1}
};
for(int i=0;i<8;i++) {
if(knightSpots[i][0] > -1 && knightSpots[i][0] < 8 && knightSpots[i][1] > -1 && knightSpots[i][1] < 8) { // spot is on the board
if(view.getBoardSpots()[knightSpots[i][0]][knightSpots[i][1]].getIcon() == view.getBlackKnight()) {
return true;
}
}
}
// rook or queen
for(int i=kingRow+1;i<8;i++) {
if(view.getBoardSpots()[i][kingCol].getIcon()!=null) {
if(view.getBoardSpots()[i][kingCol].getIcon() == view.getBlackRook() || view.getBoardSpots()[i][kingCol].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
}
for(int i=kingRow-1;i>-1;i--) {
if(view.getBoardSpots()[i][kingCol].getIcon()!=null) {
if(view.getBoardSpots()[i][kingCol].getIcon() == view.getBlackRook() || view.getBoardSpots()[i][kingCol].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
}
for(int i=kingCol+1;i<8;i++) {
if(view.getBoardSpots()[kingRow][i].getIcon()!=null) {
if(view.getBoardSpots()[kingRow][i].getIcon() == view.getBlackRook() || view.getBoardSpots()[kingRow][i].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
}
for(int i=kingCol-1;i>-1;i--) {
if(view.getBoardSpots()[kingRow][i].getIcon()!=null) {
if(view.getBoardSpots()[kingRow][i].getIcon() == view.getBlackRook() || view.getBoardSpots()[kingRow][i].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
}
// bishop or queen
// Down and right
int i = kingRow+1;
int j = kingCol+1;
while(i < 8 && j < 8) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getBlackBishop() || view.getBoardSpots()[i][j].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
i++;
j++;
}
// Down and left
i = kingRow+1;
j = kingCol-1;
while(i < 8 && j > -1) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getBlackBishop() || view.getBoardSpots()[i][j].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
i++;
j--;
}
// Up and left
i = kingRow-1;
j = kingCol-1;
while(i > -1 && j > -1) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getBlackBishop() || view.getBoardSpots()[i][j].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
i--;
j--;
}
// Up and right
i = kingRow-1;
j = kingCol+1;
while(i > -1 && j < 8) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getBlackBishop() || view.getBoardSpots()[i][j].getIcon() == view.getBlackQueen()) {
return true;
}
break;
}
i--;
j++;
}
// pawn
if(kingCol > 0) { // Checking to ensure the king isn't on the edge of the board in order to avoid invalid indices
if(view.getBoardSpots()[kingRow-1][kingCol-1].getIcon() == view.getBlackPawn()) {
return true;
}
}
if(kingCol < 7) { // Checking to ensure the king isn't on the edge of the board in order to avoid invalid indices
if(view.getBoardSpots()[kingRow-1][kingCol+1].getIcon() == view.getBlackPawn()) {
return true;
}
}
// king
int blackKingRow = view.blackKingSpot()[0];
int blackKingCol = view.blackKingSpot()[1];
if(Math.abs(kingRow - blackKingRow) < 2 && Math.abs(kingCol - blackKingCol) < 2) {
return true;
}
// otherwise
return false;
}
else { // if black turn
int[] kingSpot = view.blackKingSpot();
int kingRow = kingSpot[0];
int kingCol = kingSpot[1];
// knight
int[][] knightSpots = { // [0-7][0-1]
{kingRow+1,kingCol+2},{kingRow+2,kingCol+1},{kingRow-1,kingCol+2},{kingRow-2,kingCol+1},
{kingRow+1,kingCol-2},{kingRow+2,kingCol-1},{kingRow-1,kingCol-2},{kingRow-2,kingCol-1}
};
for(int i=0;i<8;i++) {
if(knightSpots[i][0] > -1 && knightSpots[i][0] < 8 && knightSpots[i][1] > -1 && knightSpots[i][1] < 8) { // spot is on the board
if(view.getBoardSpots()[knightSpots[i][0]][knightSpots[i][1]].getIcon() == view.getWhiteKnight()) {
return true;
}
}
}
// rook or queen
for(int i=kingRow+1;i<8;i++) {
if(view.getBoardSpots()[i][kingCol].getIcon()!=null) {
if(view.getBoardSpots()[i][kingCol].getIcon() == view.getWhiteRook() || view.getBoardSpots()[i][kingCol].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
}
for(int i=kingRow-1;i>-1;i--) {
if(view.getBoardSpots()[i][kingCol].getIcon()!=null) {
if(view.getBoardSpots()[i][kingCol].getIcon() == view.getWhiteRook() || view.getBoardSpots()[i][kingCol].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
}
for(int i=kingCol+1;i<8;i++) {
if(view.getBoardSpots()[kingRow][i].getIcon()!=null) {
if(view.getBoardSpots()[kingRow][i].getIcon() == view.getWhiteRook() || view.getBoardSpots()[kingRow][i].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
}
for(int i=kingCol-1;i>-1;i--) {
if(view.getBoardSpots()[kingRow][i].getIcon()!=null) {
if(view.getBoardSpots()[kingRow][i].getIcon() == view.getWhiteRook() || view.getBoardSpots()[kingRow][i].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
}
// bishop or queen
// Down and right
int i = kingRow+1;
int j = kingCol+1;
while(i < 8 && j < 8) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getWhiteBishop() || view.getBoardSpots()[i][j].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
i++;
j++;
}
// Down and left
i = kingRow+1;
j = kingCol-1;
while(i < 8 && j > -1) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getWhiteBishop() || view.getBoardSpots()[i][j].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
i++;
j--;
}
// Up and left
i = kingRow-1;
j = kingCol-1;
while(i > -1 && j > -1) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getWhiteBishop() || view.getBoardSpots()[i][j].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
i--;
j--;
}
// Up and right
i = kingRow-1;
j = kingCol+1;
while(i > -1 && j < 8) {
if(view.getBoardSpots()[i][j].getIcon()!=null) {
if(view.getBoardSpots()[i][j].getIcon() == view.getWhiteBishop() || view.getBoardSpots()[i][j].getIcon() == view.getWhiteQueen()) {
return true;
}
break;
}
i--;
j++;
}
// pawn
if(kingCol > 0) { // Checking to ensure the king isn't on the edge of the board in order to avoid invalid indices
if(view.getBoardSpots()[kingRow+1][kingCol-1].getIcon() == view.getWhitePawn()) {
return true;
}
}
if(kingCol < 7) { // Checking to ensure the king isn't on the edge of the board in order to avoid invalid indices
if(view.getBoardSpots()[kingRow+1][kingCol+1].getIcon() == view.getWhitePawn()) {
return true;
}
}
// king
int whiteKingRow = view.whiteKingSpot()[0];
int whiteKingCol = view.whiteKingSpot()[1];
if(Math.abs(kingRow - whiteKingRow) < 2 && Math.abs(kingCol - whiteKingCol) < 2) {
return true;
}
// otherwise
return false;
}
}
public boolean checkMovePiece(JButton newSpot) {
int newRow = view.getRow(newSpot);
int newCol = view.getCol(newSpot);
int oldRow = view.getRow(oldSpot);
int oldCol = view.getCol(oldSpot);
int rowDif = newRow - oldRow;
int colDif = newCol - oldCol;
// can't move on top of own piece
if(model.getWhiteTurn()) {
if(view.isWhitePiece(newSpot)) {
model.setPieceSelected(false);
return false;
}
}
else {
if(view.isBlackPiece(newSpot)) {
model.setPieceSelected(false);
return false;
}
}
// KING //////////////////////////
//////////////////////////////////
if(oldSpot.getIcon()==view.getBlackKing() || oldSpot.getIcon()==view.getWhiteKing()) {
if(model.getWhiteTurn() && !model.getWhiteKingMoved()) { // White turn and able to castle
if(newRow == 7) {
if(newCol == 2 && view.getBoardSpots()[7][3].getIcon() == null && !model.getWhiteRookAMoved()) {
if(!checkCheck()) { // No check on current position
view.getBoardSpots()[7][3].setIcon(view.getWhiteKing());
view.getBoardSpots()[7][4].setIcon(null);
if(!checkCheck()) { // check check on position it moves through
view.getBoardSpots()[7][2].setIcon(view.getWhiteKing());
view.getBoardSpots()[7][3].setIcon(null);
if(!checkCheck()) {
view.getBoardSpots()[7][0].setIcon(null);
view.getBoardSpots()[7][3].setIcon(view.getWhiteRook());
model.setWhiteKingMoved(true); // need to check check for new spot and spot going through first
model.setWhiteRookAMoved(true);
return true;
}
else { // position it moves to puts it into check - reset king
view.getBoardSpots()[7][2].setIcon(null);
view.getBoardSpots()[7][4].setIcon(view.getWhiteKing());
}
}
else { // position it moves through puts it into check - reset king
view.getBoardSpots()[7][3].setIcon(null);
view.getBoardSpots()[7][4].setIcon(view.getWhiteKing());
}
}
}
else if(newCol == 6 && view.getBoardSpots()[7][5].getIcon() == null && !model.getWhiteRookHMoved()) {
if(!checkCheck()) { // No check on current position
view.getBoardSpots()[7][5].setIcon(view.getWhiteKing());
view.getBoardSpots()[7][4].setIcon(null);
if(!checkCheck()) { // check check on position it moves through
view.getBoardSpots()[7][6].setIcon(view.getWhiteKing());
view.getBoardSpots()[7][5].setIcon(null);
if(!checkCheck()) {
view.getBoardSpots()[7][7].setIcon(null);
view.getBoardSpots()[7][5].setIcon(view.getWhiteRook());
model.setWhiteKingMoved(true); // need to check check for new spot and spot going through first
model.setWhiteRookHMoved(true);
return true;
}
else { // position it moves to puts it into check - reset king
view.getBoardSpots()[7][6].setIcon(null);
view.getBoardSpots()[7][4].setIcon(view.getWhiteKing());
}
}
else { // position it moves through puts it into check - reset king
view.getBoardSpots()[7][5].setIcon(null);
view.getBoardSpots()[7][4].setIcon(view.getWhiteKing());
}
}
}
}
}
else if(!model.getWhiteTurn() && !model.getBlackKingMoved()) { // Black turn and able to castle
if(newRow == 0) {
if(newCol == 2 && view.getBoardSpots()[0][3].getIcon() == null && !model.getBlackRookAMoved()) {
if(!checkCheck()) { // No check on current position
view.getBoardSpots()[0][3].setIcon(view.getBlackKing());
view.getBoardSpots()[0][4].setIcon(null);
if(!checkCheck()) { // check check on position it moves through
view.getBoardSpots()[0][2].setIcon(view.getBlackKing());
view.getBoardSpots()[0][3].setIcon(null);
if(!checkCheck()) {
view.getBoardSpots()[0][0].setIcon(null);
view.getBoardSpots()[0][3].setIcon(view.getBlackRook());
model.setBlackKingMoved(true); // need to check check for new spot and spot going through first
model.setBlackRookAMoved(true);
return true;
}
else { // position it moves to puts it into check - reset king
view.getBoardSpots()[0][2].setIcon(null);
view.getBoardSpots()[0][4].setIcon(view.getBlackKing());
}
}
else { // position it moves through puts it into check - reset king
view.getBoardSpots()[0][3].setIcon(null);
view.getBoardSpots()[0][4].setIcon(view.getBlackKing());
}
}
}
else if(newCol == 6 && view.getBoardSpots()[0][5].getIcon() == null && !model.getBlackRookHMoved()) {
if(!checkCheck()) { // No check on current position
view.getBoardSpots()[0][5].setIcon(view.getBlackKing());
view.getBoardSpots()[0][4].setIcon(null);
if(!checkCheck()) { // check check on position it moves through
view.getBoardSpots()[0][6].setIcon(view.getBlackKing());
view.getBoardSpots()[0][5].setIcon(null);
if(!checkCheck()) {
view.getBoardSpots()[0][7].setIcon(null);
view.getBoardSpots()[0][5].setIcon(view.getBlackRook());
model.setBlackKingMoved(true); // need to check check for new spot and spot going through first
model.setBlackRookHMoved(true);
return true;
}
else { // position it moves to puts it into check - reset king
view.getBoardSpots()[0][6].setIcon(null);
view.getBoardSpots()[0][4].setIcon(view.getBlackKing());
}
}
else { // position it moves through puts it into check - reset king
view.getBoardSpots()[0][5].setIcon(null);
view.getBoardSpots()[0][4].setIcon(view.getBlackKing());
}
}
}
}
}
if(Math.abs(newRow - oldRow) > 1 || Math.abs(newCol - oldCol) > 1) {
return false;
}
// Set king moved flag to true to prevent castling in future turns
if(model.getWhiteTurn()) {
model.setWhiteKingMoved(true);
}
else {
model.setBlackKingMoved(true);
}
return true;
}
// ROOK ////////////////////////////////
////////////////////////////////////////
if(oldSpot.getIcon()==view.getBlackRook() || oldSpot.getIcon()==view.getWhiteRook()) {
int i = 1;
if(Math.abs(newRow - oldRow) > 0 && Math.abs(newCol - oldCol) > 0) {
return false;
}
if(rowDif > 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow+i][oldCol].getIcon() != null) {
return false;
}
i++;
}
}
else if(rowDif < 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow-i][oldCol].getIcon() != null) {
return false;
}
i++;
}
}
else if(colDif > 0) {
while(i<Math.abs(colDif)) {
if(view.getBoardSpots()[oldRow][oldCol+i].getIcon() != null) {
return false;
}
i++;
}
}
else { // colDif < 0
while(i<Math.abs(colDif)) {
if(view.getBoardSpots()[oldRow][oldCol-i].getIcon() != null) {
return false;
}
i++;
}
}
// If move is allowed - set rook status to moved
if(oldRow == 0 && oldCol == 0) {
model.setBlackRookAMoved(true);
}
else if(oldRow == 0 && oldCol == 7) {
model.setBlackRookHMoved(true);
}
else if(oldRow == 7 && oldCol == 0) {
model.setWhiteRookAMoved(true);
}
else if(oldRow == 7 && oldCol == 7){
model.setWhiteRookHMoved(true);
}
return true;
}
// KNIGHT /////////////////////
///////////////////////////////
if(oldSpot.getIcon()==view.getBlackKnight() || oldSpot.getIcon()==view.getWhiteKnight()) {
if(Math.abs(newRow - oldRow) == 1 && Math.abs(newCol - oldCol) == 2) {
return true;
}
else if(Math.abs(newRow - oldRow) == 2 && Math.abs(newCol - oldCol) == 1) {
return true;
}
return false;
}
// BISHOP //////////////////////
////////////////////////////////
if(oldSpot.getIcon()==view.getBlackBishop() || oldSpot.getIcon()==view.getWhiteBishop()) {
// moving diagonal
int i = 1;
if(Math.abs(rowDif) == Math.abs(colDif)) {
// moving down right
if(rowDif > 0 && colDif > 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow+i][oldCol+i].getIcon() != null) {
return false;
}
i++;
}
}
// moving up right
if(rowDif > 0 && colDif < 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow+i][oldCol-i].getIcon() != null) {
return false;
}
i++;
}
}
// moving up left
if(rowDif < 0 && colDif < 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow-i][oldCol-i].getIcon() != null) {
return false;
}
i++;
}
}
// moving down left
if(rowDif < 0 && colDif > 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow-i][oldCol+i].getIcon() != null) {
return false;
}
i++;
}
}
return true;
}
}
// QUEEN /////////////////////////////
//////////////////////////////////////
if(oldSpot.getIcon()==view.getBlackQueen() || oldSpot.getIcon()==view.getWhiteQueen()) {
// moving diagonal
int i = 1;
if(Math.abs(rowDif) == Math.abs(colDif)) {
// moving down right
if(rowDif > 0 && colDif > 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow+i][oldCol+i].getIcon() != null) {
return false;
}
i++;
}
}
// moving up right
if(rowDif > 0 && colDif < 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow+i][oldCol-i].getIcon() != null) {
return false;
}
i++;
}
}
// moving up left
if(rowDif < 0 && colDif < 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow-i][oldCol-i].getIcon() != null) {
return false;
}
i++;
}
}
// moving down left
if(rowDif < 0 && colDif > 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow-i][oldCol+i].getIcon() != null) {
return false;
}
i++;
}
}
return true;
}
// moving horizontal/vertical
else if(Math.abs(newRow - oldRow) > 0 && Math.abs(newCol - oldCol) > 0) {
return false;
}
if(rowDif > 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow+i][oldCol].getIcon() != null) {
return false;
}
i++;
}
}
else if(rowDif < 0) {
while(i<Math.abs(rowDif)) {
if(view.getBoardSpots()[oldRow-i][oldCol].getIcon() != null) {
return false;
}
i++;
}
}
else if(colDif > 0) {
while(i<Math.abs(colDif)) {
if(view.getBoardSpots()[oldRow][oldCol+i].getIcon() != null) {
return false;
}
i++;
}
}
else { // colDif < 0
while(i<Math.abs(colDif)) {
if(view.getBoardSpots()[oldRow][oldCol-i].getIcon() != null) {
return false;
}
i++;
}
}
return true;
}
// BLACK PAWN //////////////////////////////
////////////////////////////////////////////
if(oldSpot.getIcon()==view.getBlackPawn()){
if(Math.abs(newCol - oldCol) == 1 && newRow == oldRow + 1) { // Taking a piece - moving 1 row forward and 1 column sideways
if(view.isWhitePiece(newSpot)) { // Can only move this way if there is a white piece there
return true;
}
}
if(model.getEnPassantAvailable()) {
if(view.getCol(newSpot) == model.getEnPassantColumn() && newRow == oldRow + 1 && Math.abs(newCol - oldCol) == 1) {
return true;
}
}
if(newCol != oldCol) { // If you can't take a piece, you can't move sideways
return false;
}
if(oldRow == 1 && newRow == 2) {
if(newSpot.getIcon()==null) {
return true;
}
}
else if(oldRow == 1 && newRow == 3) {
if(newSpot.getIcon()==null && view.getBoardSpots()[2][oldCol].getIcon()==null) {
return true;
}
}
else {
if(newRow == oldRow + 1) {
if(newSpot.getIcon()==null) {
return true;
}
}
}
return false;
}
// WHITE PAWN ////////////////////////////////////////
//////////////////////////////////////////////////////
if(oldSpot.getIcon()==view.getWhitePawn()){
if(Math.abs(newCol - oldCol) == 1 && newRow == oldRow - 1) { // Taking a piece - moving 1 row forward and 1 column sideways
if(view.isBlackPiece(newSpot)) { // Can only move this way if there is a black piece there
return true;
}
}
if(model.getEnPassantAvailable()) {
if(view.getCol(newSpot) == model.getEnPassantColumn() && newRow == oldRow - 1 && Math.abs(newCol - oldCol) == 1) {
return true;
}
}
if(newCol != oldCol) {
return false;
}
if(oldRow == 6 && newRow == 5) {
if(newSpot.getIcon()==null) {
return true;
}
}
else if(oldRow == 6 && newRow == 4) {
if(newSpot.getIcon()==null && view.getBoardSpots()[5][oldCol].getIcon()==null) {
return true;
}
}
else {
if(newRow == oldRow - 1) {
if(newSpot.getIcon() == null) {
return true;
}
}
}
return false;
}
return false;
}
/**
* Helper function to set an icon at a spot
* @param row - row to set icon at
* @param col - column to set icon at
* @param icon - icon to set
*/
public void setIconMove(int row, int col, Icon icon) {
view.getBoardSpots()[row][col].setIcon(icon);
}
/**
* Helper method called by canEscape
* Checks every spot on the board to see if the piece at the given spot can move there.
* Checking to see if it is possible to escape from check.
* @param i - row of the piece to check moves for
* @param j - column of the piece to check moves for
* @return - true if a move made by the piece at the given spot can break the check
*/
public boolean checkEverySpot(int i, int j) {
// check every spot on the board
for(int k=0;k<8;k++) {
for(int l=0;l<8;l++) {
// If the move is valid
if(checkMovePiece(view.getBoardSpots()[k][l])) {
Icon oldIcon = oldSpot.getIcon();
Icon newSpotIcon = view.getBoardSpots()[k][l].getIcon();
setIconMove(i,j,null);
setIconMove(k,l,oldIcon);
if(!checkCheck()) {
setIconMove(i,j,oldIcon);
setIconMove(k,l,newSpotIcon);
return true;
}
setIconMove(i,j,oldIcon);
setIconMove(k,l,newSpotIcon);
}
}
}
return false;
}
public void changePawnToPiece(JButton spot) {
String[] choices = { "Rook", "Knight", "Bishop", "Queen"};
String input = (String) JOptionPane.showInputDialog(null, "Select a piece:",
"", JOptionPane.QUESTION_MESSAGE, null,
choices,
choices[0]);
if(model.getWhiteTurn()) {
if(input.equals("Rook")) {
spot.setIcon(view.getWhiteRook());
}
else if(input.equals("Knight")) {
spot.setIcon(view.getWhiteKnight());
}
else if(input.equals("Bishop")) {
spot.setIcon(view.getWhiteBishop());
}
else { // queen
spot.setIcon(view.getWhiteQueen());
}
}
else { // black turn
if(input.equals("Rook")) {
spot.setIcon(view.getBlackRook());
}
else if(input.equals("Knight")) {
spot.setIcon(view.getBlackKnight());
}
else if(input.equals("Bishop")) {
spot.setIcon(view.getBlackBishop());
}
else { // queen
spot.setIcon(view.getBlackQueen());
}
}
}
}
| 5c63359137401ff683cf587a6c7511cf3f688c04 | [
"Markdown",
"Java"
] | 2 | Markdown | alexanderkrusina/Chess-Java | fb1ce416ecd1f70c94acc5b2559ec858ec1a91c7 | a81b931e1e8a966a843f1123981be789a98c34fd |
refs/heads/master | <repo_name>aTastyCookie/yandexmoney_shopcms<file_sep>/core/modules/payment/yandexmoney.php
<?php
/**
* @connect_module_class_name CYandexMoney
*
*/
// YandexMoney method implementation
// see also
// http://money.yandex.ru
class CYandexMoney extends PaymentModule {
public $test_mode;
public $org_mode;
public $status;
public $orderId;
public $orderTotal;
public $userId;
public $successUrl;
public $failUrl;
public $reciver;
public $formcomment;
public $short_dest;
public $writable_targets = 'false';
public $comment_needed = 'true';
public $label;
public $quickpay_form = 'shop';
public $payment_type = '';
public $targets;
public $sum;
public $comment;
public $need_fio = 'true';
public $need_email = 'true';
public $need_phone = 'true';
public $need_address = 'true';
public $shopid;
public $scid;
public $account;
public $password;
public $method_ym;
public $method_cards;
public $method_cash;
public $method_mobile;
public $method_wm;
public $method_ab;
public $method_sb;
public $pay_method;
function _initVars(){
$this->title = "YandexMoney";
$this->description = "YandexMoney (money.yandex.ru). ะะพะดัะปั ัะฐะฑะพัะฐะตั ะฒ ัะตะถะธะผะต ะฐะฒัะพะผะฐัะธัะตัะบะพะน ะพะฟะปะฐัั. ะญัะพั ะผะพะดัะปั ะผะพะถะฝะพ ะธัะฟะพะปัะทะพะฒะฐัั ะดะปั ะฐะฒัะพะผะฐัะธัะตัะบะพะน ะฟัะพะดะฐะถะธ ัะธััะพะฒัั
ัะพะฒะฐัะพะฒ.<br/>
<b>ะะฐัััะพะนะบะธ</b>: <br>ะะดัะตั ะฟัะธะตะผะฐ HTTP ัะฒะตะดะพะผะปะตะฝะธะน (paymentAvisoURL / checkURL): <br/> http(s)://ะฐะดัะตั_ะผะฐะณะฐะทะธะฝะฐ/index.php?yandexmoney=yes";
$this->sort_order = 0;
$array_params = array('testmode', 'mode', 'method_ym', 'method_cards', 'method_cash', 'method_phone', 'method_wm', 'password', 'shopid', 'scid', 'account', 'status');
foreach ($array_params as $key => $value) {
$value2 = 'CONF_PAYMENTMODULE_YM_' . strtoupper($value);
$this->Settings[] = $value2;
$this->$value = $this->_getSettingValue($value2);
}
$this->org_mode = ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_MODE') == 2);
$this->test_mode = ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_TESTMODE') == 1);
if (!empty($_POST['ym_method'])) {
$_SESSION['ym_method'] = $_POST['ym_method'];
}
}
function getMethodsHtml(){
$html = "<br/><b>ะกะฟะพัะพะฑ ะพะฟะปะฐัั:</b><br/><select name=\"ym_method\">";
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_YM')) {
$html .= '<option value="PC">ัะปะตะบััะพะฝะฝะฐั ะฒะฐะปััะฐ ะฏะฝะดะตะบั-ะะตะฝัะณะธ</option>';
}
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_CARDS')) {
$html .= '<option value="AC">ะฑะฐะฝะบะพะฒัะบะฐั ะบะฐััะฐ VISA, MasterCard, Maestro</option>';
}
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_CASH') && $this->org_mode) {
$html .= '<option value="GP">ะฝะฐะปะธัะฝัะผะธ ะฒ ะบะฐััะฐั
ะธ ัะตัะผะธะฝะฐะปะฐั
ะฟะฐััะฝะตัะพะฒ</option>';
}
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_PHONE') && $this->org_mode) {
$html .= '<option value="MC">ัะพ ััะตัะฐ ะผะพะฑะธะปัะฝะพะณะพ ัะตะปะตัะพะฝะฐ</option>';
}
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_WM') && $this->org_mode) {
$html .= '<option value="WM">ัะปะตะบััะพะฝะฝะฐั ะฒะฐะปััะฐ WebMoney</option>';
}
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_AB') && $this->org_mode) {
$html .= '<option value="AB">AlphaClick</option>';
}
if ($this->_getSettingValue('CONF_PAYMENTMODULE_YM_METHOD_SB') && $this->org_mode) {
$html .= '<option value="SB">Sberbank Online</option>';
}
$html .= "</select><br/> <br/>";
return $html;
}
function payment_form_html()
{
$text = '';
$payment_methods = payGetAllPaymentMethods(true);
foreach ($payment_methods as $method) {
if ($_GET['paymentMethodID'] == $method['PID']) {
$currentPaymentModule = modGetModuleObj($method['module_id'], PAYMENT_MODULE);
if ( $currentPaymentModule != null ){
if (get_class($currentPaymentModule) == 'CYandexMoney') {
$currentPaymentModule->_initVars();
$text .= $currentPaymentModule->getMethodsHtml();
}
}
}
}
return $text;
}
function _initSettingFields(){
$this->SettingsFields['CONF_PAYMENTMODULE_YM_TESTMODE'] = array(
'settings_value' => '1',
'settings_title' => 'ะขะตััะพะฒัะน ัะตะถะธะผ',
'settings_description' => 'ะัะฟะพะปัะทัะนัะต ัะตััะพะฒัะน ัะตะถะธะผ ะดะปั ะฟัะพะฒะตัะบะธ ะผะพะดัะปั',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 1,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_MODE'] = array(
'settings_value' => '1',
'settings_title' => 'ะัะฑะตัะธัะต ัะฟะพัะพะฑ ะพะฟะปะฐัั',
'settings_description' => '',
'settings_html_function' => 'setting_SELECT_BOX(CYandexMoney::getModes(),',
'sort_order' => 2,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_YM'] = array(
'settings_value' => '',
'settings_title' => 'ะัะฟะพะปัะทะพะฒะฐัั ะดะปั ะพะฟะปะฐัั ัะปะตะบััะพะฝะฝัั ะฒะฐะปััั ะฏะฝะดะตะบั.ะะตะฝัะณะธ ',
'settings_description' => '',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 3,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_CARDS'] = array(
'settings_value' => '',
'settings_title' => 'ะัะฟะพะปัะทะพะฒะฐัั ะดะปั ะพะฟะปะฐัั ะฑะฐะฝะบะพะฒัะบะธะต ะบะฐััั VISA, MasterCard, Maestro',
'settings_description' => '',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 3,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_CASH'] = array(
'settings_value' => '',
'settings_title' => 'ะัะฟะพะปัะทะพะฒะฐัั ะดะปั ะพะฟะปะฐัั ะฝะฐะปะธัะฝัะต ะฒ ะบะฐััะฐั
ะธ ัะตัะผะธะฝะฐะปะฐั
ะฟะฐััะฝะตัะพะฒ',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 4,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_PHONE'] = array(
'settings_value' => '',
'settings_title' => 'ะัะฟะพะปัะทะพะฒะฐัั ะพะฟะปะฐัั ัะพ ััะตัะฐ ะผะพะฑะธะปัะฝะพะณะพ ัะตะปะตัะพะฝะฐ',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 5,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_WM'] = array(
'settings_value' => '',
'settings_title' => 'ะัะฟะพะปัะทะพะฒะฐัั ะดะปั ะพะฟะปะฐัั ัะปะตะบััะพะฝะฝัั ะฒะฐะปััั WebMoney',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 6,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_AB'] = array(
'settings_value' => '',
'settings_title' => 'AlphaClick',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 7,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_METHOD_SB'] = array(
'settings_value' => '',
'settings_title' => 'SberbankOnline',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_CHECK_BOX(',
'sort_order' => 8,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_ACCOUNT'] = array(
'settings_value' => '',
'settings_title' => 'ะะพะผะตั ะบะพัะตะปัะบะฐ ะฏะฝะดะตะบั',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ัะธะทะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_TEXT_BOX(0,',
'sort_order' => 7,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_SHOPID'] = array(
'settings_value' => '',
'settings_title' => 'ะะดะตะฝัะธัะธะบะฐัะพั ะฒะฐัะตะณะพ ะผะฐะณะฐะทะธะฝะฐ ะฒ ะฏะฝะดะตะบั.ะะตะฝัะณะฐั
(ShopID)',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_TEXT_BOX(0,',
'sort_order' => 7,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_SCID'] = array(
'settings_value' => '',
'settings_title' => 'ะะดะตะฝัะธัะธะบะฐัะพั ะฒะธััะธะฝั ะฒะฐัะตะณะพ ะผะฐะณะฐะทะธะฝะฐ ะฒ ะฏะฝะดะตะบั.ะะตะฝัะณะฐั
(scid)',
'settings_description' => 'ะขะพะปัะบะพ ะดะปั ััะธะดะธัะตัะบะธั
ะปะธั',
'settings_html_function' => 'setting_TEXT_BOX(0,',
'sort_order' => 7,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_PASSWORD'] = array(
'settings_value' => '',
'settings_title' => 'ะกะตะบัะตัะฝะพะต ัะปะพะฒะพ (shopPassword) ะดะปั ะพะฑะผะตะฝะฐ ัะพะพะฑัะตะฝะธัะผะธ',
'settings_description' => '',
'settings_html_function' => 'setting_TEXT_BOX(0,',
'sort_order' => 7,
);
$this->SettingsFields['CONF_PAYMENTMODULE_YM_STATUS'] = array(
'settings_value' => '',
'settings_title' => 'ะกัะฐััั ะทะฐะบะฐะทะฐ ะฟะพัะปะต ะพะฟะปะฐัั',
'settings_description' => 'ะฃะบะฐะถะธัะต, ะบะฐะบะพะน ััะฐััั ะฟัะธัะฒะฐะธะฒะฐัั ะทะฐะบะฐะทั ะฟะพัะปะต ัะพะฒะตััะตะฝะธั ะฟะปะฐัะตะถะฐ. ะ ะตะบะพะผะตะฝะดัะตััั ัััะฐะฝะพะฒะธัั ัะพั ะถะต ััะฐััั, ััะพ ัััะฐะฝะพะฒะปะตะฝ ะฒ ะฝะฐัััะพะนะบะฐั
ะผะฐะณะฐะทะธะฝะฐ ะฒ ะบะฐัะตััะฒะต ััะฐัััะฐ ะทะฐะฒะตััะตะฝะฝะพะณะพ ะทะฐะบะฐะทะฐ. ะญัะพ ะฟะพะทะฒะพะปะธั ัะฐะฑะพัะฐัั ะผะณะฝะพะฒะตะฝะฝะพะน ะดะพััะฐะฒะบะต ัะธััะพะฒะพะณะพ ัะพะฒะฐัะฐ.',
'settings_html_function' => 'setting_ORDER_STATUS_SELECT(',
'sort_order' => 1,
);
}
function getModes(){
return array(
array(
'title' => 'ะะฐ ััะตั ัะธะทะธัะตัะบะพะณะพ ะปะธัะฐ ะฒ ัะปะตะบััะพะฝะฝะพะน ะฒะฐะปััะต ะฏะฝะดะตะบั.ะะตะฝะตะณ',
'value' => '1',
),
array(
'title' => 'ะะฐ ัะฐััะตัะฝัะน ััะตั ะพัะณะฐะฝะธะทะฐัะธะธ ั ะทะฐะบะปััะตะฝะธะตะผ ะดะพะณะพะฒะพัะฐ ั ะฏะฝะดะตะบั.ะะตะฝัะณะฐะผะธ',
'value' => '2',
),
);
}
function after_processing_html( $orderID )
{
$order = ordGetOrder( $orderID );
$this->orderId = $orderID;
$this->comment = $order['customers_comment'];
$this->orderTotal = floatval($order["order_amount"] * $order["currency_value"]);
$this->_initVars();
$this->pay_method = $_SESSION['ym_method'];
$this->userId = $order['customerID'];
$this->createFormHtml();
return $res;
}
function before_payment_php( $orderID, $OutSum, $merch)
{
$res = '_before_payment_php_';
return $res;
}
public function createFormHtml(){
if ($this->org_mode){
$html = '
<form method="POST" action="'.$this->getFormUrl().'" id="paymentform" name = "paymentform">
<input type="hidden" name="paymentType" value="'.$this->pay_method.'" />
<input type="hidden" name="shopid" value="'.$this->shopid.'">
<input type="hidden" name="scid" value="'.$this->scid.'">
<input type="hidden" name="shopSuccessURL" value="' . getTransactionResultURL('success') . '&InvId=' . $this->orderId . '" >
<input type="hidden" name="shopFailURL" value="' . getTransactionResultURL('failure') . '&InvId=' . $this->orderId . '" >
<input type="hidden" name="orderNumber" value="'.$this->orderId.'">
<input type="hidden" name="sum" value="'.$this->orderTotal.'" data-type="number" >
<input type="hidden" name="customerNumber" value="'.$this->userId.'" >
<input type="hidden" name="cms_name" value="shopcms" >
</form>';
}else{
$html = '<form method="POST" action="'.$this->getFormUrl().'" id="paymentform" name = "paymentform">
<input type="hidden" name="receiver" value="'.$this->account.'">
<input type="hidden" name="formcomment" value="Order '.$this->orderId.'">
<input type="hidden" name="short-dest" value="Order '.$this->orderId.'">
<input type="hidden" name="writable-targets" value="'.$this->writable_targets.'">
<input type="hidden" name="comment-needed" value="'.$this->comment_needed.'">
<input type="hidden" name="label" value="'.$this->orderId.'">
<input type="hidden" name="quickpay-form" value="'.$this->quickpay_form.'">
<input type="hidden" name="payment-type" value="'.$this->pay_method.'">
<input type="hidden" name="targets" value="ะะฐะบะฐะท '.$this->orderId.'">
<input type="hidden" name="sum" value="'.$this->orderTotal.'" data-type="number" >
<input type="hidden" name="comment" value="'.$this->comment.'" >
<input type="hidden" name="need-fio" value="'.$this->need_fio.'">
<input type="hidden" name="need-email" value="'.$this->need_email.'" >
<input type="hidden" name="need-phone" value="'.$this->need_phone.'">
<input type="hidden" name="need-address" value="'.$this->need_address.'">
</form>';
}
$html .= '<script type="text/javascript">
document.getElementById("paymentform").submit();
</script>';
echo $html; exit;
return $html;
}
public function checkSign($callbackParams){
$string = $callbackParams['action'].';'.$callbackParams['orderSumAmount'].';'.$callbackParams['orderSumCurrencyPaycash'].';'.$callbackParams['orderSumBankPaycash'].';'.$callbackParams['shopId'].';'.$callbackParams['invoiceId'].';'.$callbackParams['customerNumber'].';'.$this->password;
$md5 = strtoupper(md5($string));
return ($callbackParams['md5']==$md5);
}
public function sendAviso($callbackParams, $code){
header("Content-type: text/xml; charset=utf-8");
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<paymentAvisoResponse performedDatetime="'.date("c").'" code="'.$code.'" invoiceId="'.$callbackParams['invoiceId'].'" shopId="'.$this->shopid.'"/>';
echo $xml;
}
public function sendCode($callbackParams, $code){
header("Content-type: text/xml; charset=utf-8");
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<checkOrderResponse performedDatetime="'.date("c").'" code="'.$code.'" invoiceId="'.$callbackParams['invoiceId'].'" shopId="'.$this->shopid.'"/>';
echo $xml;
}
public function checkOrder($callbackParams, $sendCode=FALSE, $aviso=FALSE){
if ($this->checkSign($callbackParams)){
$code = 0;
}else{
$code = 1;
}
if ($sendCode){
if ($aviso){
$this->sendAviso($callbackParams, $code);
}else{
$this->sendCode($callbackParams, $code);
}
exit;
}else{
return $code;
}
}
public function individualCheck($callbackParams){
$string = $callbackParams['notification_type'].'&'.$callbackParams['operation_id'].'&'.$callbackParams['amount'].'&'.$callbackParams['currency'].'&'.$callbackParams['datetime'].'&'.$callbackParams['sender'].'&'.$callbackParams['codepro'].'&'.$this->password.'&'.$callbackParams['label'];
$check = (sha1($string) == $callbackParams['sha1_hash']);
if (!$check){
header('HTTP/1.0 401 Unauthorized');
return false;
}
return true;
}
/* ะพะฟะปะฐัะธะฒะฐะตั ะทะฐะบะฐะท */
public function ProcessResult()
{
$callbackParams = $_POST;
$order_id = false;
if ($this->org_mode){
if ($callbackParams['action'] == 'checkOrder'){
$code = $this->checkOrder($callbackParams);
$this->sendCode($callbackParams, $code);
$order_id = (int)$callbackParams["orderNumber"];
}
if ($callbackParams['action'] == 'paymentAviso'){
$this->checkOrder($callbackParams, TRUE, TRUE);
}
}else{
$check = $this->individualCheck($callbackParams);
if (!$check){
}else{
$order_id = (int)$callbackParams["label"];
}
}
return $order_id;
}
public function getFormUrl(){
if (!$this->org_mode){
return $this->individualGetFormUrl();
}else{
return $this->orgGetFormUrl();
}
}
public function individualGetFormUrl(){
if ($this->test_mode){
return 'https://demomoney.yandex.ru/quickpay/confirm.xml';
}else{
return 'https://money.yandex.ru/quickpay/confirm.xml';
}
}
public function orgGetFormUrl(){
if ($this->test_mode){
return 'https://demomoney.yandex.ru/eshop.xml';
} else {
return 'https://money.yandex.ru/eshop.xml';
}
}
function after_payment_php( $orderID, $params){
$this->_initVars();
$order = ordGetOrder( $orderID );
$order_id = $this->ProcessResult();
if ($order_id) {
ostSetOrderStatusToOrder($order_id, $this->_getSettingValue('CONF_PAYMENTMODULE_YM_STATUS'));
}
exit;
}
}
?> | 96c1f246b0cb4068ee8dc2a6322a056f7cb91bbc | [
"PHP"
] | 1 | PHP | aTastyCookie/yandexmoney_shopcms | 324aca4cd2fbba928bcf74e45cee8897f4362dfa | 6a153ce7cbc6246b83b40886827bf9c81ddd5c63 |
refs/heads/master | <file_sep>def vowelCount(s):
count=0
for x in range(0,len(s)):
if s[x]=='a' or s[x] == 'e' or s[x] == 'i' or s[x] == 'o' or s[x] == 'u':
count=count+1
print(count) | 2e23ecddd0991b8e586c8a854d2baec144a8fb8b | [
"Python"
] | 1 | Python | sivathemonk/python | bb1339e2e96337f9e6b9514b7a94dd265e308a51 | 4470f49d5c0f824713caf4e8cac8df2568903d08 |
refs/heads/master | <file_sep>package org.liyudong;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
/**
* @author liyudong
*/
public class JsonTest {
@Test
public void jsonToMap() {
String strJson = "{\"UserId\":\"LiYuDong\",\"DeviceId\":\"\",\"errcode\":0,\"errmsg\":\"ok\"}\n";
Gson gson = new Gson();
Map<String, String> map = gson.fromJson(strJson, new TypeToken<HashMap<String, String>>() {
}.getType());
map.forEach((k, v) -> System.out.println(k + " " + v));
}
}
<file_sep>package org.liyudong.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
/**
* @author liyudong
*/
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String login(String email, String password) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(email, password);
subject.login(token);
return "redirect:/";
}
}
<file_sep>### ๅฎขๆท็ซฏ้
็ฝฎๆ ๅฐ
็กฎไฟeureka-serverๆญฃๅธธ่ฟ่ก,
config-lientไฝไธบๅพฎๆๅกๅฆไฝ่ทๅeureka-server็้
็ฝฎไฟกๆฏ.<file_sep>group=org.liyudong
version=1.0-SNAPSHOT<file_sep>package org.liyudong.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author liyudong
*/
@Controller
public class LoginController {
@GetMapping("/login")
public String login(HttpServletRequest request) {
System.out.println(request.getRequestURL());
return "login";
}
@PostMapping("/login")
@ResponseBody
public String login(HttpServletRequest request,String username, String password) {
return username + "----" + password;
}
}
<file_sep>package org.liyudong.jaop;
/**
* @author liyudong
*/
public class Dog implements IAnimal {
private String name = "ๅฐ้ป";
public Dog() {
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public void say() {
System.out.println("ๅฐ็:ๆฑชๆฑชๆฑชๆฑช.....");
}
@Override
public void getProperty() {
System.out.println("ๅฐ็ๆฏ้ๅฐๅจ็ฉ,ไฝๆฏไผๆธธๆณณๅฆ");
}
}
<file_sep>package org.liyudong.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.liyudong.entity.UserInfo;
import org.liyudong.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @author liyudong
*/
public class MyShiroRealm extends AuthorizingRealm {
@Autowired
private UserInfoService userInfoService;
/**
* ๆ้
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
/**
* ้ช่ฏ็จๆทๅๅๅฏ็ ๆฏๅฆๆญฃ็กฎ
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
String username = token.getUsername();
UserInfo userInfo = userInfoService.getByUsername(username);
if (null == userInfo) {
return null;
}
return new SimpleAuthenticationInfo(
userInfo,
userInfo.getPassword(),
null,
getName()
);
}
/**
* ่ชๅฎไนๅฏ็ ๅ ๅฏๆ ก้ช, ้ป่ฎคไธๅ ๅฏ
* @param credentialsMatcher
*/
@Override
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
super.setCredentialsMatcher(credentialsMatcher);
}
}
<file_sep>package org.liyudong.controller;
import org.apache.shiro.SecurityUtils;
import org.liyudong.entity.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author liyudong
*/
@Controller
@RequestMapping("/")
public class HelloController {
@ResponseBody
@GetMapping("/")
public String index() {
return "hello: " + ((UserInfo) SecurityUtils.getSubject().getPrincipal()).getUsername();
}
}
<file_sep># simple-office
simple-office
<file_sep>apply plugin: 'war'
dependencies {
compile 'org.springframework.security:spring-security-web:3.2.5.RELEASE'
compile 'org.springframework:spring-webmvc:3.2.8.RELEASE'
compileOnly 'javax.servlet:javax.servlet-api:3.1.0'
compileOnly 'javax.servlet.jsp:jsp-api:2.2'
compile 'javax.servlet:jstl:1.2'
compile 'org.springframework:spring-context:3.2.8.RELEASE'
compile 'org.springframework:spring-context-support:3.2.8.RELEASE'
compile 'org.springframework:spring-core:3.2.8.RELEASE'
compile 'org.springframework:spring-beans:3.2.8.RELEASE'
compile 'org.springframework:spring-aop:3.2.8.RELEASE'
compile 'org.springframework:spring-web:3.2.8.RELEASE'
}<file_sep>#### ๆๅกๆณจๅไธญๅฟ
ๅจ/etc/hosts ๆไปถไธญๆทปๅ ๅฏนpeer1ๅpeer2็่ฝฌๆข, ่ฎฉไธ้ข้
็ฝฎ็hostๅฝขๅผserviceUrl่ฝๅจๆฌๅฐๆญฃ็กฎ่ฎฟ้ฎๅฐ;
windows่ทฏๅพไธบC:\Windows\System32\drivers\etc\hosts
java -jar eureka-server-1.0-SNAPSHOT.jar --spring.profiles.active=peer1
<file_sep>package org.liyudong.service;
import org.liyudong.entity.UserInfo;
import org.springframework.stereotype.Service;
/**
* @author liyudong
*/
@Service
public class UserInfoService {
public UserInfo getByUsername(String username) {
if (!"<EMAIL>".equals(username)) {
return null;
}
UserInfo userInfo = new UserInfo();
userInfo.setUsername("<EMAIL>");
userInfo.setPassword("<PASSWORD>");
userInfo.setId("1");
return userInfo;
}
}
<file_sep>rootProject.name = 'simple'
include 'simple-web'
include 'eureka-server'
include 'config-client'
include 'hello-service'
include 'mybatis-generator-demo'
include 'more'
include 'security-study'
include 'sso-center'
include 'sso-one'
<file_sep>package org.liyudong.daili;
/**
* ็ณๆๆบ
*
* @author liyudong
*/
public class GumballMachine {
/**
* ไฝ็ฝฎ็จString่ฎฐๅฝ
*/
String location;
int count;
public GumballMachine(String location, int count){
this.location = location;
}
public String getLocation() {
return location;
}
}
<file_sep>package org.liyudong.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.type.JdbcType;
import org.liyudong.model.SUser;
public interface SUserMapper {
@Delete({
"delete from s_user",
"where id = #{id,jdbcType=INTEGER}"
})
int deleteByPrimaryKey(Integer id);
@Insert({
"insert into s_user (id, name)",
"values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})"
})
int insert(SUser record);
@Select({
"select",
"id, name",
"from s_user",
"where id = #{id,jdbcType=INTEGER}"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR)
})
SUser selectByPrimaryKey(Integer id);
@Select({
"select",
"id, name",
"from s_user"
})
@Results({
@Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="name", property="name", jdbcType=JdbcType.VARCHAR)
})
List<SUser> selectAll();
@Update({
"update s_user",
"set name = #{name,jdbcType=VARCHAR}",
"where id = #{id,jdbcType=INTEGER}"
})
int updateByPrimaryKey(SUser record);
}<file_sep>#### ็จๆท่ฏทๆฑsso-one็ณป็ป
- ็ณป็ปๅ็ฐๆช็ป้,
- ๆบๅธฆreturnUrl,
- ่ทณ่ฝฌๅฐcenter็ป้็้ข,<file_sep>package org.liyudong.model;
import java.io.Serializable;
/**
* @author liyudong
*/
public class SysUser implements Serializable {
private Integer id;
private String username;
private String wxUserId;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getWxUserId() {
return wxUserId;
}
public void setWxUserId(String wxUserId) {
this.wxUserId = wxUserId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
@Override
public String toString() {
return "SysUser{" +
"id=" + id +
", username='" + username + '\'' +
", wxUserId='" + wxUserId + '\'' +
", password='" + password + '\'' +
'}';
}
}
<file_sep>package org.liyudong.config;
import org.liyudong.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author liyudong
*/
@Configuration
public class OneWebAppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor());
}
}
<file_sep>package org.liyudong.jaop;
/**
* ่ง่ๅจ็ฉ็ไธไบๆนๆณ
*
* @author liyudong
*/
public interface IAnimal {
void setName(String name);
String getName();
void say();
void getProperty();
}
| 71ab78b6e832d04e18fb64c0b44e98a701013925 | [
"Markdown",
"Java",
"INI",
"Gradle"
] | 19 | Java | liyudong1991/simple | cfa9923f760981f022fa0170780f9bf1dbc62b56 | 7fefccab45877dca7b1be30a0f727e6b8a395786 |
refs/heads/master | <repo_name>UnderSourceCode/WebSocketMobile<file_sep>/spec/controllers/application_controller_spec.rb
require 'spec_helper'
describe ApplicationController do
controller do
def index
render :template => 'public/index'
end
end
describe "iphone format, layout" do
before(:each) do
request.user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_6 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B651 Safari/9537.53"
get :index
end
it "should correct format" do
request.format.symbol.should eq(:iphone)
end
it "should correct layout" do
response.should render_template(layout: "mobile")
end
end
describe "android format, layout" do
before(:each) do
request.user_agent = "Mozilla/5.0 (Linux; U; Android 4.0.3; ja-jp; AT570 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30"
get :index
end
it "should correct format" do
request.format.symbol.should eq(:android)
end
it "should correct layout" do
response.should render_template(layout: "mobile")
end
end
describe "non mobile format, layout" do
before(:each) do
get :index
end
it "should correct format" do
request.format.symbol.should eq(:html)
end
it "should correct layout" do
response.should render_template(layout: "application")
end
end
end
<file_sep>/app/assets/javascripts/chat.js
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
jQuery(function() {
return window.chatController = new Chat.Controller($('#chat').data('uri'), true);
});
window.Chat = {};
Chat.User = (function() {
function User(user_name) {
this.user_name = user_name;
this.serialize = __bind(this.serialize, this);
}
User.prototype.serialize = function() {
return {
user_name: this.user_name
};
};
return User;
})();
Chat.Controller = (function() {
Controller.prototype.template = function(message) {
var html;
html = "<div class=\"message\" >\n <label class=\"label label-info\">\n [" + message.received + "] " + message.user_name + " wrote." + "\n </label> \n " + message.msg_body + "\n</div>";
return $(html);
};
Controller.prototype.userListTemplate = function(userList) {
var user, userHtml, _i, _len;
userHtml = "";
for (_i = 0, _len = userList.length; _i < _len; _i++) {
user = userList[_i];
userHtml = userHtml + ("<li>" + user.user_name + "</li>");
}
return $(userHtml);
};
function Controller(url, useWebSockets) {
this.createGuestUser = __bind(this.createGuestUser, this);
this.shiftMessageQueue = __bind(this.shiftMessageQueue, this);
this.updateUserInfo = __bind(this.updateUserInfo, this);
this.sendMessage = __bind(this.sendMessage, this);
this.newMessage = __bind(this.newMessage, this);
this.bindEvents = __bind(this.bindEvents, this);
this.messageQueue = [];
this.dispatcher = new WebSocketRails(url, useWebSockets);
this.dispatcher.on_open = this.createGuestUser;
this.bindEvents();
}
Controller.prototype.bindEvents = function() {
this.dispatcher.bind('new_message', this.newMessage);
$('input#user_name').on('keyup', this.updateUserInfo);
$('#send').on('click', this.sendMessage);
return $('#message').keypress(function(e) {
if (e.keyCode === 13) {
return $('#send').click();
}
});
};
Controller.prototype.newMessage = function(message) {
this.messageQueue.push(message);
if (this.messageQueue.length > 15) {
this.shiftMessageQueue();
}
return this.appendMessage(message);
};
Controller.prototype.sendMessage = function(event) {
var message;
event.preventDefault();
message = $('#message').val();
this.dispatcher.trigger('new_message', {
user_name: this.user.user_name,
msg_body: message
});
return $('#message').val('');
};
Controller.prototype.updateUserInfo = function(event) {
this.user.user_name = $('input#user_name').val();
$('#username').html(this.user.user_name);
return this.dispatcher.trigger('change_username', this.user.serialize());
};
Controller.prototype.appendMessage = function(message) {
var messageTemplate;
messageTemplate = this.template(message);
$('#chat').append(messageTemplate);
return messageTemplate.slideDown(140);
};
Controller.prototype.shiftMessageQueue = function() {
this.messageQueue.shift();
return $('#chat div.messages:first').slideDown(100, function() {
return $(this).remove();
});
};
Controller.prototype.createGuestUser = function() {
var rand_num;
rand_num = Math.floor(Math.random() * 1000);
this.user = new Chat.User("Guest_" + rand_num);
$('#username').html(this.user.user_name);
$('input#user_name').val(this.user.user_name);
return this.dispatcher.trigger('new_user', this.user.serialize());
};
return Controller;
})();
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
layout :set_layout
before_filter :set_format
def set_format
request.format = :iphone if iphone_request?
request.format = :android if android_request?
end
def set_layout
return "mobile" if (iphone_request? || android_request?)
return "application"
end
private
def iphone_request?
request.user_agent =~ /(Mobile.+Safari)/
end
private
def android_request?
request.user_agent =~ /(Android)/
end
end
<file_sep>/README.rdoc
== README
=== About
WebSocketMobile is a sample chat application.
It changes pages with PC, Safari on iPhone, Android.
=== Environments
* Ruby 2.1.0
* Rails 4.0.2
* jQuery Mobile 1.4.2
* websocket-rails
| 8f237bb28ec70c1cba5e05ea22d2e467d87920a7 | [
"JavaScript",
"RDoc",
"Ruby"
] | 4 | Ruby | UnderSourceCode/WebSocketMobile | e30a3c46f1c7cae11741557f6af5146ea89e5411 | 55e19d6844b955c51563ba8b3ef72d0a04fe29c9 |
refs/heads/master | <file_sep><?php require_once('../../../private/initialize.php'); ?>
<?php $page_title = 'Staff: Territories'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="main-content">
<a href="../index.php">Back to Menu</a><br />
<h1>Tarritories</h1>
<a href="new.php">Add a Territory</a><br />
<br />
<?php
$territory_result = find_all_territories();
echo "<table id=\"states\" style=\"width: 500px;\">";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>State ID</th>";
echo "<th>Position</th>";
echo "<th></th>";
echo "</tr>";
while($territory = db_fetch_assoc($territory_result)) {
echo "<tr>";
echo "<td>" . htmlspecialchars($territory['name']) . "</td>";
echo "<td>" . htmlspecialchars($territory['state_id']) . "</td>";
echo "<td>" . htmlspecialchars($territory['position']) . "</td>";
echo "<td>";
echo "<a href=\"show.php?id=".urlencode($territory['id'])."\">Show</a>";
echo "</td>";
echo "<td>";
echo "<a href=\"edit.php?id=".urlencode($territory['id'])."\">Edit</a>";
echo "</td>";
echo "</tr>";
} // end while $states
db_free_result($territory_result);
echo "</table>"; // #states
?>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
<file_sep><?php
// is_blank('abcd')
function is_blank($value='') {
return !isset($value) || trim($value) == '';
}
// has_length('abcd', [ 'max' => 5])
function has_length($value, $options=array()) {
$length = strlen($value);
if(isset($options['max']) && ($length > $options['max'])) {
return false;
} elseif(isset($options['min']) && ($length < $options['min'])) {
return false;
} elseif(isset($options['exact']) && ($length != $options['exact'])) {
return false;
} else {
return true;
}
}
//My custom validation email
// has_valid_email_format('<EMAIL>')
function has_valid_email_format($value) {
// Function can be improved later to check for
// more than just '@'.
if (filter_var($value, FILTER_VALIDATE_EMAIL))
return false; //valid
else {
return true; //invalid
}
}
//My custom validation usersname
// has_valid_username_format
//contain only A-Z, a-z, 0-9, _
function has_valid_username_format($value) {
if(preg_match("/^[a-zA-Z0-9_]+$/",$value)){
return true;
}
else return false;
}
//My custom validation unique usersname
// has_valid_unique username_format
function has_unique_username_format($user) {
global $db;
if(!isset($user['id'])){$user['id']=0;
}
$sql = "SELECT * FROM users WHERE username='" . $user['username'] . "'";
$sql .= "AND id !='" . $user['id'] . "'";
$result = db_query($db, $sql);
if(db_num_rows($result) >0){
return false;
}
else return true;
}
//My custom validation phone number
// has_valid_phonenumber_format
//contain only 0-9, spaces, ()-
function has_valid_phonenumber_format($value) {
if(preg_match("/^[0-9)(-]+$/",$value)){
return true;
}
else return false;
}
function has_valid_number_format($value) {
if(preg_match("/^[0-9]+$/",$value)){
return true;
}
else return false;
}
//My custom validation for name
function has_valid_name_format($value) {
if(preg_match("/^[a-zA-Z]+$/",$value)){
return true;
}
else return false;
}
function has_valid_name_format_with_space($value) {
if(preg_match("/^[a-zA-Z ]+$/",$value)){
return true;
}
else return false;
}
function has_valid_code_format($value) {
if(preg_match("/^[A-Z]+$/",$value)){
return true;
}
else return false;
}
function has_valid_country_id_format($value) {
if(preg_match("/^[0-9]+$/",$value)){
return true;
}
else return false;
}
?>
| 53e6e58c1fe1801dad00e6d6e5e631a34245bf86 | [
"PHP"
] | 2 | PHP | jieunlim/Web-Security-week2 | 0a01fac27394db1bf5392019b80051f441bce2d5 | 08da2090894902f9fb69533d0d210215ceb382a0 |
refs/heads/master | <file_sep>package graph
/*
This is a class representing the hash version of the Graph.
A Graph consists of edges connected to each other by verices.
Author: <NAME>
Completed and modified by <NAME> 22-04-2015
*/
const initialMapSize = 4
type Hash struct {
// The map edges[v] contains the mapping {w:x} if there is an edge
// from v to w; x is the label assigned to this edge.
// The maps may be nil and are allocated only when needed.
edges []map[int]interface{}
numEdges int // total number of directed edges in the graph
}
// NewList constructs a new graph with n vertices and no edges.
func NewHash(n int) *Hash {
return &Hash{edges: make([]map[int]interface{}, n)}
}
// NumVertices returns the number of vertices in this graph.
// Time complexity: O(1).
func (g *Hash) NumVertices() int {
return len(g.edges)
}
// NumEdges returns the number of (directed) edges in this graph.
// Time complexity: O(1).
func (g *Hash) NumEdges() int {
return g.numEdges
}
// Degree returns the degree of vertex v. Time complexity: O(1).
func (g *Hash) Degree(v int) int {
//the degree is how many neighbours the node v has
neighbours_of_v := g.edges[v]
num_of_neighbours_of_v := len(neighbours_of_v)
return num_of_neighbours_of_v
}
// DoNeighbors calls action for each neighbor w of v,
// with x equal to the label of the edge from v to w.
// Time complexity: O(m), where m is the number of neighbors.
func (g *Hash) DoNeighbors(v int, action func(from, w int, x interface{})) {
//first we need to get all the neighbours w of v
//we get the neighbours by looking in the edges
w_plural := g.edges[v]
//w_plural is a map with mapping {w:label}
//we take out w and label and call action
for w, label := range w_plural {
action(v, w, label)
}
}
// HasEdge returns true if there is an edge from v to w.
// Time complexity: O(1).
func (g *Hash) HasEdge(v, w int) bool {
//get all the neighbours of v
neighbours_v := g.edges[v]
for neighbour, _ := range neighbours_v {
//if we have a match - then w and v are connected
if neighbour == w {
return true
}
}
//we've looped through all the neighbours and found no match
return false
}
// Returns the label for the edge from v to w, NoLabel if the edge has no label,
// or nil if no such edge exists.
// Time complexity: O(1).
func (g *Hash) Label(v, w int) interface{} {
//neighbours_v is a map with mapping {w:label}
neighbours_v := g.edges[v]
//check if map contains value and return
if label, hasValue := neighbours_v[w]; hasValue {
//this will be NoLabel if nobody has inserted a label.
//NoLabel is by default inserted in the Add method
return label
} else {
return nil
}
}
// Add inserts a directed edge.
// It removes any previous label if this edge already exists.
// Time complexity: O(1).
func (g *Hash) Add(from, to int) {
neighbours_from := g.edges[from]
//if the map doesnt contain value
if _, hasValue := neighbours_from[to]; !hasValue {
//increase edges
g.numEdges += 1
}
//if no neighbours - init the slice
if neighbours_from == nil {
neighbours_from = make(map[int]interface{}, initialMapSize)
//save to the edges
g.edges[from] = neighbours_from
}
//add connection from 'from' to 'to' with empty label 'NoLabel'
g.edges[from][to] = NoLabel
}
// AddLabel inserts a directed edge with label x.
// It overwrites any previous label if this edge already exists.
// Time complexity: O(1).
func (g *Hash) AddLabel(from, to int, x interface{}) {
m := g.edges[from]
if m == nil {
m = make(map[int]interface{}, initialMapSize)
g.edges[from] = m
}
if _, ok := m[to]; !ok {
g.numEdges++
}
m[to] = x
}
// AddBi inserts edges between v and w.
// It removes any previous labels if these edges already exists.
// Time complexity: O(1).
func (g *Hash) AddBi(v, w int) {
//use add function to add edges in both directions
g.Add(w, v)
g.Add(v, w)
}
// AddBiLabel inserts edges with label x between v and w.
// It overwrites any previous labels if these edges already exists.
// Time complexity: O(1).
func (g *Hash) AddBiLabel(v, w int, x interface{}) {
//use addLabel function to add labels in both directions
g.AddLabel(w, v, x)
g.AddLabel(v, w, x)
}
// Remove removes an edge. Time complexity: O(1).
func (g *Hash) Remove(from, to int) {
//check if the edge exists
if _, hasEdge := g.edges[from][to]; hasEdge {
//if it exists - remove
g.numEdges -= 1
delete(g.edges[from], to)
}
}
// RemoveBi removes all edges between v and w. Time complexity: O(1).
func (g *Hash) RemoveBi(v, w int) {
//use the Remove function above to delete edges in both directions
g.Remove(w, v)
g.Remove(v, w)
}
<file_sep>// <NAME> 2014-04-20
// Radically modified and completed by <NAME> 2015-04-27
/*
You give this program a file containing a graph and two nodes in that graph.
The program will print the shortes path (with as few nodes as possible) between those nodes.
If no path is found, an empty row will be printed.
*/
package main
import (
graph "./graph"
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
/*
This interface describes the hash and matrix classes.
It declares all the methods.
These methods are matched in matrix.go and hash.go
*/
type Grapher interface {
NumVertices() int
NumEdges() int
Degree(int) int
DoNeighbors(int, func(int, int, interface{}))
HasEdge(int, int) bool
Label(int, int) interface{}
Add(int, int)
AddLabel(int, int, interface{})
AddBi(int, int)
AddBiLabel(int, int, interface{})
Remove(int, int)
RemoveBi(int, int)
}
/*
Main function.
Checks the parameters from the Terminal.
Constructs the graph from file.
Prints the path from 'FROM'-node to 'TO'-node.
*/
func main() {
//check so that the arguments aare correct
if len(os.Args) != 4 {
log.Fatalf("usage: FROM TO FILE\n")
}
from, from_error := strconv.Atoi(os.Args[1])
if from_error != nil {
panic("FROM argument is wrong!")
}
to, to_error := strconv.Atoi(os.Args[2])
if to_error != nil {
panic("TO argument is wrong!")
}
//get the pattern from the arguments
filepath := os.Args[3]
if from < 0 {
panic("FROM argument can't be less than zero.")
}
if to < 0 {
panic("TO argument can't be less than zero.")
}
//construct the graph from the file
g := constructGraph(filepath)
if g == nil {
panic("Couldn't build the graph.")
}
getPath(from, to, g)
}
/*
Finds the shortest (as few nodes as possible) way from 'from' node to 'to' node
in the 'g' graph.
Prints out the results if a path is found.
Prints out an empty line if there is no path between the nodes.
*/
func getPath(from, to int, g Grapher) {
const INDEX_HAS_NO_PARENT = -1
visited := make([]bool, g.NumVertices())
stack := make([]int, g.NumEdges())
for i, _ := range stack {
stack[i] = INDEX_HAS_NO_PARENT
}
graph.BFS(g, from, visited, func(parent, w int) {
//save the parent of each node
stack[w] = parent
})
//this array will contain the path to our goal
var path []int
//put the goal as the first value in the path
//we're building this backwards, this will be reversed at the end
index := to
path = append(path, index)
//flag that will be set to false when we've found the goal-node
searching := true
if index > len(stack) {
panic("THE NODE YOU'RE SEARCHING FOR DOESNT EVEN EXIST IN THE GRAPH!")
}
for stack[index] != INDEX_HAS_NO_PARENT {
//get parent of the index
//in the first iteration it will get the parent of the goal
//in the second - the grandparent of the goal, until we reach starting point (from)
prev := stack[index]
index = prev
//save parent to the path
path = append(path, index)
//abort search if we've reached the starting point
//this means we've went backwards from the goal to starting point
if index == from {
searching = false
break
}
}
//if the node is found - we're not longer searching
if searching == false {
reverseSlice(path)
fmt.Println("Path from ", from, " to ", to, ": ", path)
} else {
//node not found - just print empty line.
fmt.Println(" ")
}
}
/*
Reverses the slice passed in as the parameter.
*/
func reverseSlice(slice []int) {
length := len(slice)
//go through the array and switch from both sides.
for i := 0; i < length/2; i++ {
temp := slice[i]
slice[i] = slice[length-i-1]
slice[length-i-1] = temp
}
}
/*
This methods constructs an undirected graph from the file found
at the file path passed in as the parameter.
Returns a Grapher object with a hash graph containing all
the connections as in the file.
*/
func constructGraph(filepath string) (g Grapher) {
//open file
file, errors := os.Open(filepath)
if errors != nil {
panic("error opening file!")
}
graphSize := 0
firstLine := true
//go through each line
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
//ignore all commented lines
if strings.HasPrefix(line, "//") == false {
//split the string
words := strings.Fields(line)
currentWord := 0
var from, to, label int
shouldAttachToGraph := false
//go through all words n this line
for _, s := range words {
//convert string to int
i, err := strconv.Atoi(s)
if err == nil {
//if first line - just get the size
if firstLine == true {
graphSize = i
firstLine = false
//init the graph
g = graph.NewHash(graphSize)
} else {
//if not first line
//get from and to and label
if currentWord == 0 {
from = i
} else if currentWord == 1 {
to = i
} else if currentWord == 2 {
label = i
//if we've come this far, everything worked fine
//we can attach
shouldAttachToGraph = true
}
}
} else {
//string counldt be converted to int
<<<<<<< HEAD
//panic("Error constructing the graph. File is structured in a wrong way. Couldn't convert a value to int.")
=======
panic("Error constructing the graph. File is structured in a wrong way. Couldn't convert a value to int.")
>>>>>>> origin/master
}
currentWord++
}
if shouldAttachToGraph {
//attach the information from this line to the graph
g.AddBiLabel(from, to, label)
}
}
}
file.Close()
return g
}
| 1117929d322e4faf3eb97a64bd3b0fca1ef4950b | [
"Go"
] | 2 | Go | KTH-Ivan-Liljeqvist/Files-Graphs-in-Go | 8eb251190435d5c5af25fb8e12e212e03b52f2af | adf92c3f6648f7125d87037eb1a97a2051b6186a |
refs/heads/master | <file_sep>// ะะฐะฝ ะพะฑัะตะบั, ะฝะฐะฟัะธะผะตั:
// const obj = {name: 'ะผะตัะฝะธะบ', health: 10, level: 2, attack: 80, defence: 40}
// ะะฐะฝ ะฟะพััะดะพะบ ัะพััะธัะพะฒะบะธ ัะฒะพะนััะฒ:
// ["name", "level"]
// ะัะธะผะตั ะฒัะทะพะฒะฐ ะฒะฐัะตะน ััะฝะบัะธะธ:
// orderByProps(obj, ["name", "level"])
export default function orderByProps(obj, order) {
const array = [];
for (const key in obj) {
if (!order.some((item) => item === key)) array.push(key);
}
array.sort();
order.reverse().forEach((item) => {
if (Object.prototype.hasOwnProperty.call(obj, item)) array.unshift(item);
});
const objectsArray = array.map((key) => ({ [key]: obj[key] }));
return objectsArray;
}
// ะะพัะปะต ะพะฑัะฐะฑะพัะบะธ ะฒะฐัะตะน ััะฝะบัะธะตะน:
// [
// {key: "name", value: "ะผะตัะฝะธะบ"}, // ะฟะพััะดะพะบ ะฒะทัั ะธะท ะผะฐััะธะฒะฐ ั ะบะปััะฐะผะธ
// {key: "level", value: 2}, // ะฟะพััะดะพะบ ะฒะทัั ะธะท ะผะฐััะธะฒะฐ ั ะบะปััะฐะผะธ
// {key: "attack", value: 80}, // ะฟะพััะดะพะบ ะฟะพ ะฐะปัะฐะฒะธัั (ั.ะบ. ะฒ ะผะฐััะธะฒะต ั ะบะปััะฐะผะธ ะฝะตั ะทะฝะฐัะตะฝะธั "attack")
// {key: "defence", value: 40}, // ะฟะพััะดะพะบ ะฟะพ ะฐะปัะฐะฒะธัั (ั.ะบ. ะฒ ะผะฐััะธะฒะต ั ะบะปััะฐะผะธ ะฝะตั ะทะฝะฐัะตะฝะธั "defence")
// {key: "health", value: 10} // ะฟะพััะดะพะบ ะฟะพ ะฐะปัะฐะฒะธัั (ั.ะบ. ะฒ ะผะฐััะธะฒะต ั ะบะปััะฐะผะธ ะฝะตั ะทะฝะฐัะตะฝะธั "health")
// ]
// ะข.ะต. ัะฝะฐัะฐะปะฐ ะธะดัั ัะพััะธัะพะฒะบะฐ ะฟะพ ัะพะผั, ะบะฐะบ ัะบะฐะทะฐะฝะพ ะฒ ะผะฐััะธะฒะต ัะพััะธัะพะฒะบะธ, ะดะปั ัะตั
ะบะปััะตะน,
// ะดะปั ะบะพัะพััั
ะฒ ะผะฐััะธะฒะต ัะพััะธัะพะฒะบะธ ะฝะตั ะทะฐะฟะธัะธ, ัะพััะธัะพะฒะบะฐ ะธะดัั ะฒ ะฐะปัะฐะฒะธัะฝะพะผ ะฟะพััะดะบะต.<file_sep>import orderByProps from '../app';
test('Should be ordered', () => {
const character = {
name: 'ะผะตัะฝะธะบ', health: 10, level: 2, attack: 80, defence: 40,
};
const orderedCharacter = [
{ name: 'ะผะตัะฝะธะบ' }, { level: 2 }, { attack: 80 }, { defence: 40 }, { health: 10 },
];
expect(orderByProps(character, ['name', 'level'])).toEqual(orderedCharacter);
});
// ะะฐะฝ ะพะฑัะตะบั, ะฝะฐะฟัะธะผะตั:
// const obj = {name: 'ะผะตัะฝะธะบ', health: 10, level: 2, attack: 80, defence: 40}
// ะะพัะปะต ะพะฑัะฐะฑะพัะบะธ ะฒะฐัะตะน ััะฝะบัะธะตะน:
// [
// {key: "name", value: "ะผะตัะฝะธะบ"}, // ะฟะพััะดะพะบ ะฒะทัั ะธะท ะผะฐััะธะฒะฐ ั ะบะปััะฐะผะธ
// {key: "level", value: 2}, // ะฟะพััะดะพะบ ะฒะทัั ะธะท ะผะฐััะธะฒะฐ ั ะบะปััะฐะผะธ
// {key: "attack", value: 80}, // ะฟะพััะดะพะบ ะฟะพ ะฐะปัะฐะฒะธัั (ั.ะบ. ะฒ ะผะฐััะธะฒะต ั ะบะปััะฐะผะธ ะฝะตั ะทะฝะฐัะตะฝะธั "attack")
// {key: "defence", value: 40}, // ะฟะพััะดะพะบ ะฟะพ ะฐะปัะฐะฒะธัั (ั.ะบ. ะฒ ะผะฐััะธะฒะต ั ะบะปััะฐะผะธ ะฝะตั ะทะฝะฐัะตะฝะธั "defence")
// {key: "health", value: 10} // ะฟะพััะดะพะบ ะฟะพ ะฐะปัะฐะฒะธัั (ั.ะบ. ะฒ ะผะฐััะธะฒะต ั ะบะปััะฐะผะธ ะฝะตั ะทะฝะฐัะตะฝะธั "health")
// ] | 18b02178f3e53bc50390b092a4644d68d601c7db | [
"JavaScript"
] | 2 | JavaScript | CarolineFell/properties-and-wrappers | f41baa4451e004b913048cee175c5c6545c75794 | 5ebfa5f8ae089937e31ca0a2c86803e8b70ef51e |
refs/heads/master | <repo_name>HansikaPerera/TheStationeryManager<file_sep>/app/src/main/java/com/example/stationerymanager/AddSales.java
package com.example.stationerymanager;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Calendar;
public class AddSales extends AppCompatActivity{
public static StationarySalesDatabaseHelper myDb;
EditText etDate;
EditText sCode, sName, sPrice, sQty;
Button addSalesBtn;
Button listSalesBtn;
DatePickerDialog.OnDateSetListener setListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sales);
getSupportActionBar().setTitle("Add Sales");
myDb = new StationarySalesDatabaseHelper(this, "Stationery.db", null, 1);
etDate = findViewById(R.id.editText3);
sCode = findViewById(R.id.SAfill10);
sName = findViewById(R.id.SAfill20);
sPrice = findViewById(R.id.SAfill30);
sQty = findViewById(R.id.SAfill40);
addSalesBtn = findViewById(R.id.SAbtn1);
listSalesBtn = findViewById(R.id.SAbtn);
AddData();
viewAll();
Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
etDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog datePickerDialog = new DatePickerDialog(AddSales.this,android.R.style.Theme_Holo_Dialog_NoActionBar_MinWidth,setListener,year,month,day);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
setListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String date = day+"/"+month+"/"+year;
etDate.setText(date);
}
} ;
}
public void AddData(){
addSalesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (sCode.length() != 0 && sName.length() != 0 && sPrice.length() != 0 && sQty.length() != 0){
boolean isInserted = myDb.insertData(
etDate.getText().toString(),
sCode.getText().toString(),
sName.getText().toString(),
sPrice.getText().toString(),
sQty.getText().toString());
if (isInserted == true){
Toast.makeText(AddSales.this, "Data Inserted", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(AddSales.this, "Data not Inserted", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(AddSales.this, "Please fill out the empty fields", Toast.LENGTH_LONG).show();
}
}
});
}
public void viewAll(){
listSalesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(AddSales.this, SalesListActivity.class));
}
});
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/faxDBHelper.java
package com.example.stationerymanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class faxDBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "FaxInfo.db";
public faxDBHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_ENTRIES = ("CREATE TABLE "+ faxMaster.fax.TABLE_NAME + " (" +
faxMaster.fax._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
faxMaster.fax.COLUMN_NAME_NAME + " TEXT," +
faxMaster.fax.COLUMN_NAME_NUMBER + " INTEGER," +
faxMaster.fax.COLUMN_NAME_HOWMUCH + " FLOAT," +
faxMaster.fax.COLUMN_NAME_NOOFFAX + " INTEGER)");
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + faxMaster.fax.TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name,String no,String howMuch,String noFax){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(faxMaster.fax.COLUMN_NAME_NAME,name);
contentValues.put(faxMaster.fax.COLUMN_NAME_NUMBER,no);
contentValues.put(faxMaster.fax.COLUMN_NAME_HOWMUCH,howMuch);
contentValues.put(faxMaster.fax.COLUMN_NAME_NOOFFAX,noFax);
Long result = db.insert(faxMaster.fax.TABLE_NAME,null,contentValues);
if(result == -1){
return false;
}else {
return true;
}
}
public Cursor getAllData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + faxMaster.fax.TABLE_NAME ,null );
return res;
}
public boolean updateData(String id,String name,String no,String howMuch,String noFax){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(faxMaster.fax._ID,id);
contentValues.put(faxMaster.fax.COLUMN_NAME_NAME,name);
contentValues.put(faxMaster.fax.COLUMN_NAME_NUMBER,no);
contentValues.put(faxMaster.fax.COLUMN_NAME_HOWMUCH,howMuch);
contentValues.put(faxMaster.fax.COLUMN_NAME_NOOFFAX,noFax);
db.update(faxMaster.fax.TABLE_NAME,contentValues,faxMaster.fax._ID + " = ?",new String[]{id});
return true;
}
public int deleteData(String id){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(faxMaster.fax.TABLE_NAME,faxMaster.fax._ID + " = ?",new String[]{id});
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/ExpenseModel.java
package com.example.stationerymanager;
import java.util.ArrayList;
public class ExpenseModel {
int id;
String title;
String type;
String noteDescription;
String timestamp;
String amount;
public ExpenseModel(int id, String title, String type, String amount , String timestamp, String noteDescription) {
this.id = id;
this.title = title;
this.type = type;
this.noteDescription = noteDescription;
this.timestamp = timestamp;
this.amount = amount;
}
public int getId() {
return id;
}
public String getTitle() { return title; }
public String getType() {
return type;
}
public String getNoteDescription() {
return noteDescription;
}
public String getTimestamp() {
return timestamp;
}
public String getAmount() {
return amount;
}
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setType(String type) {
this.type = type;
}
public void setNoteDescription(String noteDescription) {
this.noteDescription = noteDescription;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String[] splitDateTime(){
if (timestamp == "" || timestamp == null){
timestamp = "0000-00-00 00:00";
}
String[] parts = timestamp.split(" ");
return parts;
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/BindingDisplay.java
package com.example.stationerymanager;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import java.util.ArrayList;
public class BindingDisplay extends AppCompatActivity {
ListView mListView;
ArrayList<Model_new> mList;
ServiceAdapterNew mAdapter = null;
ArrayAdapter SpinnerAdapter;
public static DatabaseHelper mDataBaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding_display);
//
// ActionBar actionBar = getSupportActionBar();
// actionBar.setTitle("Record List");
Intent intent = getIntent();
String currentServiceName = intent.getStringExtra("serviceName");
setTitle(currentServiceName +" List");
mListView = findViewById(R.id.listViewNew);
mList = new ArrayList<>();
mAdapter = new ServiceAdapterNew(this, R.layout.row_new, mList);
mListView.setAdapter(mAdapter);
mDataBaseHelper = new DatabaseHelper(this, "STATIONERYDB.sqlite", null, 2);
try {
Cursor cursor = mDataBaseHelper.getDataNew("SELECT * FROM RECORDNew WHERE ServiceName = '"+ currentServiceName +"';");
mList.clear();
while (cursor.moveToNext()) {
int ID = cursor.getInt(0);
String ServiceName = cursor.getString(1);
String ServiceType = cursor.getString(2);
String Description = cursor.getString(3);
String CostPrice = cursor.getString(4);
String SellingPrice = cursor.getString(5);
String Quantity = cursor.getString(6);
mList.add(new Model_new(ID,ServiceName, ServiceType, Description, CostPrice, SellingPrice, Quantity));
}
} catch (SQLiteException e) {
Log.e("DB error", e.toString());
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No Record Found....", Toast.LENGTH_SHORT).show();
}
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) {
final CharSequence[] items = {"Update" , "Delete"};
AlertDialog.Builder dialog = new AlertDialog.Builder(BindingDisplay.this);
dialog.setTitle("choose an action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int j) {
if(j == 0) {
Cursor c = mDataBaseHelper.getDataNew("SELECT ID FROM RECORDNew");
ArrayList<Integer> arrId = new ArrayList<Integer>();
while (c.moveToNext()) {
arrId.add(c.getInt(0));
}
showDialogUpdate(BindingDisplay.this, arrId.get(position));
}
if (j == 1){
//delete
Cursor c = mDataBaseHelper.getDataNew("SELECT ID FROM RECORDNew");
ArrayList<Integer> arrId = new ArrayList<Integer>();
while (c.moveToNext()){
arrId.add(c.getInt(0));
}
showDialogDelete(arrId.get(position));
}
}
});
dialog.show();
return true;
}
});
}
private void showDialogDelete(final int IDRecord){
AlertDialog.Builder dialogDelete = new AlertDialog.Builder(BindingDisplay.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you need to delete?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int j) {
try{
// Cursor cursor = mDataBaseHelper.getDataNew("SELECT * FROM RECORDNew WHERE ServiceName = '"+ currentServiceName +"';");
mDataBaseHelper.deleteDataNew(IDRecord);
Toast.makeText(BindingDisplay.this,"Deleted Successfully",Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Log.e("error",e.getMessage());
}
updateRecordList();
recreate();
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int j) {
dialogInterface.dismiss();
}
});
dialogDelete.show();
}
private void showDialogUpdate(Activity activity, final int position){
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.service_update_dialog);
dialog.setTitle("Update");
final Spinner upspinneradd1 = dialog.findViewById(R.id.upspinneradd1);
final EditText fillup1 = dialog.findViewById(R.id.fillup1);
final EditText fillup2 = dialog.findViewById(R.id.fillup2);
final EditText fillup3 = dialog.findViewById(R.id.fillup3);
final EditText fillup5 = dialog.findViewById(R.id.fillup5);
final EditText fillup4 = dialog.findViewById(R.id.fillup4);
Button btnup1 = dialog.findViewById(R.id.btnup1);
Cursor cursor = mDataBaseHelper.getDataNew("SELECT * FROM RECORDNew WHERE ID="+position);
mList.clear();
while (cursor.moveToNext()) {
int ID = cursor.getInt(0);
String ServiceName = cursor.getString(1);
SpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.comboboxadd1, android.R.layout.simple_spinner_item);
SpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
upspinneradd1.setAdapter(SpinnerAdapter);
upspinneradd1.setSelection(SpinnerAdapter.getPosition(ServiceName));
String ServiceType = cursor.getString(2);
fillup1.setText(ServiceType);
String Description = cursor.getString(3);
fillup2.setText(Description);
String CostPrice = cursor.getString(4);
fillup3.setText(CostPrice);
String SellingPrice = cursor.getString(5);
fillup5.setText(SellingPrice);
String Quantity = cursor.getString(6);
fillup4.setText(Quantity);
mList.add(new Model_new(ID,ServiceName, ServiceType, Description, CostPrice, SellingPrice, Quantity));
}
int width = (int)(activity.getResources().getDisplayMetrics().widthPixels*0.95);
int height= (int) (activity.getResources().getDisplayMetrics().heightPixels*0.7);
dialog.getWindow().setLayout(width,height);
dialog.show();
btnup1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
mDataBaseHelper.updateDataNew(
upspinneradd1.getSelectedItem().toString().trim(),
fillup1.getText().toString().trim(),
fillup2.getText().toString().trim(),
fillup3.getText().toString().trim(),
fillup5.getText().toString().trim(),
fillup4.getText().toString().trim(),
position
);
dialog.dismiss();
recreate();
Toast.makeText(getApplicationContext(),"Updated Successfully",Toast.LENGTH_SHORT).show();
}
catch (Exception error){
Log.e("Update error",error.getMessage());
}
onResume();
updateRecordList();
}
});
}
private void updateRecordList() {
Cursor cursor = mDataBaseHelper.getDataNew("SELECT * FROM RECORDNew");
mList.clear();
while (cursor.moveToNext()) {
int ID = cursor.getInt(0);
String ServiceName = cursor.getString(1);
String ServiceType = cursor.getString(2);
String Description = cursor.getString(3);
String CostPrice = cursor.getString(4);
String SellingPrice = cursor.getString(5);
String Quantity = cursor.getString(6);
mList.add(new Model_new(ID,ServiceName, ServiceType, Description, CostPrice, SellingPrice, Quantity));
}
mAdapter.notifyDataSetChanged();
}
/* public void editBinding(View view){
Intent intent = new Intent(BindingDisplay.this,ServiceUpdate1.class);
startActivity(intent);
}*/
@Override
protected void onRestart() {
super.onRestart();
recreate();
}
@Override
protected void onPause() {
super.onPause();
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/Model_new.java
package com.example.stationerymanager;
public class Model_new {
int ID;
String ServiceName;
String ServiceType;
String Description;
String CostPrice;
String SellingPrice;
String Quantity;
public Model_new(int ID,String serviceName, String serviceType, String description, String costPrice, String sellingPrice, String quantity) {
this.ID = ID;
ServiceName = serviceName;
ServiceType = serviceType;
Description = description;
CostPrice = costPrice;
SellingPrice = sellingPrice;
Quantity = quantity;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getServiceType() {
return ServiceType;
}
public void setServiceType(String serviceType) {
ServiceType = serviceType;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getCostPrice() {
return CostPrice;
}
public void setCostPrice(String costPrice) {
CostPrice = costPrice;
}
public String getSellingPrice() {
return SellingPrice;
}
public void setSellingPrice(String sellingPrice) {
SellingPrice = sellingPrice;
}
public String getQuantity() {
return Quantity;
}
public void setQuantity(String quantity) {
Quantity = quantity;
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/SalesListActivity.java
package com.example.stationerymanager;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.example.stationerymanager.AddSales.myDb;
public class SalesListActivity extends AppCompatActivity {
ListView mListView;
SalesListAdapter mAdapter = null;
ArrayList<sModel> mList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_list);
mListView = findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new SalesListAdapter(this, R.layout.salesrow, mList);
mListView.setAdapter(mAdapter);
Cursor res = AddSales.myDb.getAllData();
mList.clear();
while (res.moveToNext()) {
String ID = res.getString(0);
String DATE = res.getString(1);
String CODE = res.getString(2);
String NAME = res.getString(3);
String PRICE = res.getString(4);
String QUANTITY = res.getString(5);
mList.add(new sModel(ID, DATE, CODE, NAME, PRICE, QUANTITY));
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No DATA Found...", Toast.LENGTH_SHORT).show();
}
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/Model.java
package com.example.stationerymanager;
public class Model {
private int id;
private String Date;
private String ServiceName;
private String Category;
private String price;
private String quantity;
private String profit;
public Model(int id,String Date, String serviceName, String category, String price, String quantity, String profit) {
this.id = id;
this.Date = Date;
ServiceName = serviceName;
Category = category;
this.price = price;
this.quantity = quantity;
this.profit = profit;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getProfit() {
return profit;
}
public void setProfit(String profit) {
this.profit = profit;
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/callMaster.java
package com.example.stationerymanager;
import android.provider.BaseColumns;
public final class callMaster {
private callMaster(){}
protected static class call implements BaseColumns {
public static final String TABLE_NAME = "Calls";
public static final String COLUMN_NAME_NAME = "Name";
public static final String COLUMN_NAME_NUMBER = "Number";
public static final String COLUMN_NAME_HOWMUCH = "How_Much";
public static final String COLUMN_NAME_NOOFMINS = "No_of_Mins";
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/Services.java
package com.example.stationerymanager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import static com.example.stationerymanager.R.id.floatingActionButton_addServices;
public class Services extends Fragment {
View vw;
FloatingActionButton addServices;
Button SbtnNav2;
TextView Stx;
TextView Stx1;
TextView Stx2;
TextView Stx3;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vw = inflater.inflate(R.layout.fragment_services, container, false);
final String[] servicesArr = getContext().getResources().getStringArray(R.array.comboboxadd1);
SbtnNav2 = vw.findViewById(R.id.SbtnNav2);
SbtnNav2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), AddServiceSales.class);
startActivity(intent);
}
});
Stx = (TextView)vw.findViewById(R.id.Stx);
Stx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), BindingDisplay.class);
intent.putExtra("serviceName", servicesArr[0]);
startActivity(intent);
}
});
Stx1 = (TextView)vw.findViewById(R.id.Stx1);
Stx1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), BindingDisplay.class);
intent.putExtra("serviceName", servicesArr[2]);
startActivity(intent);
}
});
Stx2 = (TextView)vw.findViewById(R.id.Stx2);
Stx2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), BindingDisplay.class);
intent.putExtra("serviceName", servicesArr[1]);
startActivity(intent);
}
});
Stx3 = (TextView)vw.findViewById(R.id.Stx3);
Stx3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), BindingDisplay.class);
intent.putExtra("serviceName", servicesArr[3]);
startActivity(intent);
}
});
addServices = vw.findViewById(floatingActionButton_addServices);
addServices.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(vw.getContext(), AddService1.class);
startActivity(intent);
}
});
return vw;
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/ServiceUpdate1.java
package com.example.stationerymanager;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class ServiceUpdate1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_update1);
setTitle("Update Services");
}
// public void sendUpdate(View view){
// Intent intent = new intent(this,)
// }
}
<file_sep>/app/src/main/java/com/example/stationerymanager/ExpensesList.java
package com.example.stationerymanager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ExpensesList extends AppCompatActivity {
ListView listView;
ArrayList<ExpenseModel> expenseList;
ArrayAdapter<String> SpinnerAdaptor;
Spinner expenseType;
SQLiteExpensesHelper sqLiteExpensesHelper;
private String currentType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expenses_list);
setTitle("Previous Expenses");
expenseType = findViewById(R.id.spinnerExpenses);
listView=findViewById(R.id.expenses_list);
loadExpenseTypesToSpinner();
Intent intent = getIntent();
currentType = intent.getStringExtra("expenseType");
expenseType.setSelection(SpinnerAdaptor.getPosition(currentType));
sqLiteExpensesHelper = new SQLiteExpensesHelper( getApplicationContext(), "Stationery.db", null, 1);
loadExpensesList(currentType);
}
//Loads data to ExpenseTypes spinner
private void loadExpenseTypesToSpinner(){
SpinnerAdaptor = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Expenses.expenseTypes);
SpinnerAdaptor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
expenseType.setAdapter(SpinnerAdaptor);
}
@Override
protected void onRestart() {
super.onRestart();
System.out.println("Restarting");
recreate();
}
@Override
protected void onResume() {
super.onResume();
expenseType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
loadExpensesList( expenseType.getItemAtPosition(i).toString().trim());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void loadExpensesList(String expenseType){
expenseList = new ArrayList<>();
ExpensesListAdapter adapter=new ExpensesListAdapter(this, R.layout.expenses_list_layout_single, expenseList );
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Cursor cursor = sqLiteExpensesHelper.getExpenses("SELECT * FROM expenses WHERE type = '"+ expenseType+"';");
// Cursor cursor = sqLiteExpensesHelper.getExpenses("SELECT * FROM expenses");
expenseList.clear();
while (cursor.moveToNext()){
int id = cursor.getInt(0);
String title = cursor.getString(1);
String type = cursor.getString(2);
String amount = cursor.getString(3);
String dateANDtime = cursor.getString(4);
String note = cursor.getString(5);
ExpenseModel expenseModel = new ExpenseModel( id, title, type,amount ,dateANDtime,note );
expenseList.add(expenseModel);
System.out.println("expenseModel ID " + expenseModel.getId());
}
adapter.notifyDataSetChanged();
if(expenseList.size() == 0 ){
Toast.makeText(getApplicationContext(), "No expenses found", Toast.LENGTH_SHORT).show();
}
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/ServiceSaleUpdate1.java
package com.example.stationerymanager;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ServiceSaleUpdate1 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText SeditCategory, SeditPrice, SeditQuantity, SeditProfit;
Button Salebtnup1;
TextView SeditDate;
Spinner SeditServiceName;
public static ServiceHelper nDataBaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_sale_update1);
setTitle("Sale Update");
Salebtnup1=(Button)findViewById(R.id.btnup1);
Spinner spinner = findViewById(R.id.Sspinneradd);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.comboboxadd1, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
SeditDate = (TextView) findViewById(R.id.StextView7);
SeditServiceName = (Spinner) findViewById(R.id.Sspinneradd);
SeditCategory = (EditText) findViewById(R.id.Sfillsale3);
SeditPrice = (EditText) findViewById(R.id.Sfillsale4);
SeditQuantity = (EditText) findViewById(R.id.Sfillsale5);
SeditProfit = (EditText) findViewById(R.id.Sfillsale);
Salebtnup1 = (Button) findViewById(R.id.Sbtnup1);
Intent intent = getIntent();
final Integer saleID = Integer.valueOf(intent.getIntExtra("id", -999));
SeditDate.setText(intent.getStringExtra("Date"));
SeditServiceName.setSelection( adapter.getPosition(intent.getStringExtra("ServiceName")) );
SeditCategory.setText(intent.getStringExtra("category"));
SeditPrice.setText(intent.getStringExtra("Price"));
SeditQuantity.setText(intent.getStringExtra("Quantity"));
SeditProfit.setText(intent.getStringExtra("Profit"));
nDataBaseHelper = new ServiceHelper(this, "STATIONERYDB.sqlite", null, 2);
nDataBaseHelper.queryData("CREATE TABLE IF NOT EXISTS RECORD(id INTEGER PRIMARY KEY AUTOINCREMENT,Date TEXT,ServiceName VARCHAR,Category VARCHAR,price VARCHAR,Quantity VARCHAR,profit VARCHAR)");
// nDataBaseHelper.queryData("DROP TABLE RECORD");
Salebtnup1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
//int selectedID = recint.getIntExtra("ID",0);
boolean isUpdated;
isUpdated = nDataBaseHelper.updateData(SeditDate.getText().toString().trim(), SeditServiceName.getSelectedItem().toString().trim(), SeditCategory.getText().toString().trim(), SeditPrice.getText().toString().trim(), SeditQuantity.getText().toString().trim(), SeditProfit.getText().toString().trim(), saleID );
if (SeditDate.length() != 0 && SeditCategory.length() != 0 && SeditPrice.length() != 0 && SeditQuantity.length() != 0 && SeditProfit.length() != 0) {
if (isUpdated) {
Toast.makeText(getApplicationContext(), "Data Updated!", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(ServiceSaleUpdate1.this, "Data Not Updated!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(ServiceSaleUpdate1.this, "Please enter all details!", Toast.LENGTH_LONG).show();
}
}
}
);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/PhotoCopyDisplay.java
package com.example.stationerymanager;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class PhotoCopyDisplay extends AppCompatActivity {
ImageButton b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_copy_display);
setTitle("Service List");
b1=findViewById(R.id.imageButton6);
}
public void copy(View v){
Intent i = new Intent(PhotoCopyDisplay.this,ServiceUpdate1.class);
startActivity(i);
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/ExpensesListAdapter.java
package com.example.stationerymanager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.ImageViewCompat;
import java.util.ArrayList;
import java.util.List;
public class ExpensesListAdapter extends ArrayAdapter<ExpenseModel> {
private final Context context;
ArrayList<ExpenseModel> expenses;
int layoutRes;
public ExpensesListAdapter(Context context, int layoutRes, ArrayList<ExpenseModel> expenses){
super(context,layoutRes, expenses);
this.context = context;
this.layoutRes = layoutRes;
this.expenses = expenses;
}
@NonNull
@Override
public View getView(int position, View view, final ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(layoutRes, null);
TextView titleView = rowView.findViewById(R.id.title);
TextView descView = rowView.findViewById(R.id.descView);
TextView timeView = rowView.findViewById(R.id.timestampView);
TextView amountView = rowView.findViewById(R.id.amountView);
ImageView update = rowView.findViewById(R.id.editExpenseBtn);
ImageView delete = rowView.findViewById(R.id.deleteExpenseBtn);
final ExpenseModel expenseItem = expenses.get(position);
titleView.setText(expenseItem.getTitle());
descView.setText(expenseItem.getNoteDescription());
timeView.setText(expenseItem.getTimestamp());
amountView.setText(expenseItem.getAmount());
update.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent updateIntent = new Intent(getContext(), UpdateExpense.class);
updateIntent.putExtra("id", expenseItem.getId());
updateIntent.putExtra("title", expenseItem.getTitle());
updateIntent.putExtra("type", expenseItem.getType());
updateIntent.putExtra("amount", expenseItem.getAmount());
updateIntent.putExtra("date", expenseItem.splitDateTime()[0]);
updateIntent.putExtra("time", expenseItem.splitDateTime()[1]);
updateIntent.putExtra("note", expenseItem.getNoteDescription());
view.getContext().startActivity(updateIntent);
}
}
);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage(R.string.delete_alert)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Expenses.sqLiteExpensesHelper.deleteExpense(expenseItem.getId());
Toast.makeText(getContext(),"Deleted Successfully", Toast.LENGTH_SHORT).show();
remove(expenseItem);
}catch (Exception e){
e.printStackTrace();
Log.e("CRUD error", e.toString());
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
}
);
return rowView;
}
@Override
public void remove(@Nullable ExpenseModel object) {
super.remove(object);
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/UpdateProducts.java
package com.example.stationerymanager;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class UpdateProducts extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
EditText uCode, uName, uCPrice, uSPrice, uQty;
Button update;
Spinner uCategory;
public static StationaryProductsDatabaseHelper spDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_products);
Spinner spinner = findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.combo_box1, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
uCategory = findViewById(R.id.spinner2);
uCode = findViewById(R.id.ufill2);
uName = findViewById(R.id.ufill1);
uCPrice = findViewById(R.id.ufill3);
uSPrice = findViewById(R.id.ufill4);
uQty = findViewById(R.id.ufill5);
update = findViewById(R.id.UPbtn1);
Intent intent = getIntent();
final Integer id = Integer.valueOf(intent.getIntExtra("id", -999));
uCategory.setSelection(adapter.getPosition(intent.getStringExtra("category")));
uCode.setText(intent.getStringExtra("code"));
uName.setText(intent.getStringExtra("name"));
uCPrice.setText(intent.getStringExtra("cPrice"));
uSPrice.setText(intent.getStringExtra("sPrice"));
uQty.setText(intent.getStringExtra("quantity"));
spDb = new StationaryProductsDatabaseHelper(this, "Stationery.db", null, 1);
spDb.queryDataProduct("CREATE TABLE IF NOT EXISTS stationeryProductsTable(id INTEGER PRIMARY KEY AUTOINCREMENT, category VARCHAR, code VARCHAR, name VARCHAR, cPrice VARCHAR, sPrice VARCHAR, quantity VARCHAR)");
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean isPUpdated = spDb.updateDataProduct(
uCategory.getSelectedItem().toString().trim(),
uCode.getText().toString().trim(),
uName.getText().toString().trim(),
uCPrice.getText().toString().trim(),
uSPrice.getText().toString().trim(),
uQty.getText().toString().trim(),
id
);
if (isPUpdated) {
Toast.makeText(getApplicationContext(), "Data Updated!", Toast.LENGTH_LONG).show();
finish();
}
else {
Toast.makeText(UpdateProducts.this, "Data Not Updated!", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/DatabaseHelper.java
package com.example.stationerymanager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import androidx.annotation.Nullable;
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryDataNew(String sql){
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertDataNew(String ServiceName,String ServiceType,String Description,String CostPrice,String SellingPrice,String Quantity ){
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO RECORDNew VALUES(NULL,?,?,?,?,?,?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1,ServiceName);
statement.bindString(2,ServiceType);
statement.bindString(3,Description);
statement.bindString(4,CostPrice);
statement.bindString(5,SellingPrice);
statement.bindString(6,Quantity);
statement.executeInsert();
}
public void updateDataNew(String ServiceName,String ServiceType,String Description,String CostPrice,String SellingPrice,String Quantity,int ID){
SQLiteDatabase database = getWritableDatabase();
String sql = "UPDATE RECORDNew SET ServiceName = ?, ServiceType=?, Description=?, CostPrice=?, SellingPrice=?, Quantity=? WHERE ID=?";
SQLiteStatement statement = database.compileStatement(sql);
statement.bindString(1,ServiceName);
statement.bindString(2,ServiceType);
statement.bindString(3,Description);
statement.bindString(4,CostPrice);
statement.bindString(5,SellingPrice);
statement.bindString(6,Quantity);
statement.bindDouble(7,(double)ID);
statement.execute();
database.close();
}
public void deleteDataNew(int ID){
SQLiteDatabase database = getWritableDatabase();
String sql = "DELETE FROM RECORDNew WHERE ID=?";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindDouble(1,(double)ID);
statement.execute();
database.close();
}
public Cursor getDataNew(String sql){
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql,null);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/SalesListAdapter.java
package com.example.stationerymanager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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 android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import java.util.ArrayList;
public class SalesListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<sModel> salesList;
public SalesListAdapter(Context context, int layout, ArrayList<sModel> salesList) {
this.context = context;
this.layout = layout;
this.salesList = salesList;
}
@Override
public int getCount() {
return salesList.size();
}
@Override
public Object getItem(int i) {
return salesList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
public class ViewHolder{
TextView txtDate, txtCode, txtName, txtPrice, txtQty;
ImageView deleteSSalesBtn;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View salesrow = inflater.inflate(layout, null);
holder.txtDate = salesrow.findViewById(R.id.txtDate);
holder.txtCode = salesrow.findViewById(R.id.txtCode);
holder.txtName = salesrow.findViewById(R.id.txtName);
holder.txtPrice = salesrow.findViewById(R.id.txtPrice);
holder.txtQty = salesrow.findViewById(R.id.txtQty);
holder.deleteSSalesBtn = salesrow.findViewById(R.id.deleteSSalesBtn);
salesrow.setTag(holder);
holder = (ViewHolder) salesrow.getTag();
final sModel model = salesList.get(i);
holder.txtDate.setText(model.getDATE());
holder.txtCode.setText(model.getCODE());
holder.txtName.setText(model.getNAME());
holder.txtPrice.setText(model.getPRICE());
holder.txtQty.setText(model.getQUANTITY());
// holder.editSSalesBtn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Toast.makeText(context, "Hi", Toast.LENGTH_SHORT).show();
//
//
// Intent updateSintent = new Intent(context, UpdateSales.class);
// updateSintent.putExtra("ID", model.getID());
// updateSintent.putExtra("DATE", model.getDATE());
// updateSintent.putExtra("CODE", model.getCODE());
// updateSintent.putExtra("NAME", model.getNAME());
// updateSintent.putExtra("PRICE", model.getPRICE());
// updateSintent.putExtra("QUANTITY", model.getQUANTITY());
//
// context.startActivity(updateSintent);
//
// }
// });
holder.deleteSSalesBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder dialogDelete = new AlertDialog.Builder(context);
dialogDelete.setTitle("WARNING!!!");
dialogDelete.setMessage("Are you sure to Delete ?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
AddSales.myDb.deleteData(model.getID());
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show();
salesrow.invalidate();
} catch (Exception e) {
Log.e("Deleting Error", e.getMessage());
}
}
});
dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogDelete.show();
}
});
return salesrow;
}
}
<file_sep>/app/src/main/java/com/example/stationerymanager/Expenses.java
package com.example.stationerymanager;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.view.menu.ActionMenuItem;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import static com.example.stationerymanager.R.id.floatingActionButton_addExpense;
import static com.example.stationerymanager.R.id.gridExpenseTypes;
public class Expenses extends Fragment {
View view;
FloatingActionButton addExpense;
GridView grid;
static String[] expenseTypes = {
"Rent",
"Repair",
"Legal",
"Transport",
"Tax",
"Ads",
"Electricity",
"Other",
};
String[] expenseTypesAmounts = {
"2500.00",
"3000.00",
"524.65",
"600.00",
"451.00",
"200.00",
"2100.00",
"400.00"
};
int[] imageIds = {
R.drawable.ic_rent,
R.drawable.ic_repair,
R.drawable.ic_legal,
R.drawable.ic_transport,
R.drawable.ic_tax,
R.drawable.ic_ads,
R.drawable.ic_electricity,
R.drawable.ic_other
};
public static SQLiteExpensesHelper sqLiteExpensesHelper;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
ExpenseTypesGrid adapter = new ExpenseTypesGrid(context,expenseTypes, expenseTypesAmounts, imageIds );
view = inflater.inflate(R.layout.fragment_expenses, container, false);
grid = view.findViewById(gridExpenseTypes);
addExpense = view.findViewById(floatingActionButton_addExpense);
//db connection creation
sqLiteExpensesHelper = new SQLiteExpensesHelper( context, "Stationery.db", null, 1);
//creating table if not created
sqLiteExpensesHelper.creatExpensesTable("CREATE TABLE IF NOT EXISTS expenses (\n" +
"\texpenseID integer PRIMARY KEY AUTOINCREMENT,\n" +
" \ttitle TEXT,\n" +
" \ttype TEXT,\n" +
" \tamount REAL,\n" +
" \tdateANDtime TEXT,\n" +
" \tnote TEXT\n" +
")");
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getContext(), expenseTypes[i]+ " Clicked", Toast.LENGTH_SHORT).show();
Intent intentToExpensesList = new Intent(getContext(), ExpensesList.class);
intentToExpensesList.putExtra("expenseType", expenseTypes[i]);
startActivity(intentToExpensesList);
}
});
addExpense.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(view.getContext(), AddExpenses.class);
startActivity(intent);
}
});
// Inflate the layout for this fragment
return view;
}
@Override
public void onResume() {
super.onResume();
}
}<file_sep>/README.md
"# TheStationeryManager" - Android App
1. Stationery Management
There are different types of stationery items in a stationery shop such as books, pens, school items and office items. This function can be used to manage stationery products as well as sales details of stationery items.
The shop owner has to add details of all stationery products including their category; books, pens, school items and office items. If the details of a particular product change owner can update those details. If he wants to remove a product from the system, he can delete that particular product.
Also the owner can insert all sales details of stationery products daily or weekly. From that he can calculate his daily income.
2. Photocopy, Laminating & Binding Management
In Book Shops they offer various Services as Binding,Laminating,Photocopying and Printouts.In this Stationery Shop Management App, under Services category shop owner can store the details of these services such as Service name,category,prices and Quantity.When there is a change in those details owner can update those details.He can also delete the unnecessary added records from the system.
If the owner is planning to start a new Service in his shop except for these four Services he can also add that to the system.
When owner make a sale he can add the details of that sale to the system.He also can search the sales by the date.This โsale functionโ will help the owner to calculate the profit he made throughout a month.
3. Fax & Calls Management
Before the customer gets a call or send a fax, the owner can add details about how much for fax and how much for a minute.
Then the Owner needs to add how much time the customer called or how much fax customer sent. Our app will calculate the total at that time and display total to the owner.
Our app will show how much the owner earns in a month.
The owner doesnโt have to add how much for a call or fax in every time.
The owner can search for information about calls and faxes using the phone number.
4. Expenses Management
Different types of expenses can be seen in a Stationery shop. All these expenses affect the growth of the shop. Too much of expenses will decrease the Total Profit. Because of this, the shop owner must keep track of all expenses related to the shop.
This function can be used to manage all the expenses in a systematic way. The shop owner has to add all the expenses daily. Every added expense can be removed or edited.
Our system will keep a record of each added expense and display information such as Daily Total Expense, Monthly Total Expense, Highest Expense, Most Frequent Expenses and chart visualization of every Expense type.
Any time, the owner can add any customized expense type to the Expense Types list. The system will use total Expenses details to calculate Monthly/Weekly Total Profit. Default expense types are Rent,Repairs, Transportation cost, legal fees, Property tax ,Electricity bill ,Advertising.
<file_sep>/app/src/main/java/com/example/stationerymanager/Stationery.java
package com.example.stationerymanager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import static com.example.stationerymanager.R.id.floatingActionButton_addExpense;
import static com.example.stationerymanager.R.id.floatingActionButton_addProducts;
public class Stationery extends Fragment {
View vw;
FloatingActionButton addProducts;
Button btnNav2;
TextView tx;
TextView tx1;
TextView tx2;
TextView tx3;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vw = inflater.inflate(R.layout.fragment_stationery, container, false);
final String[] productsArr = getContext().getResources().getStringArray(R.array.combo_box1);
btnNav2 = vw.findViewById(R.id.btnNav2);
btnNav2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), AddSales.class);
startActivity(intent);
}
});
tx = (TextView)vw.findViewById(R.id.tx);
tx.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), ProductListActivity.class);
intent.putExtra("product_type", productsArr[0] );
startActivity(intent);
}
});
tx1 = (TextView)vw.findViewById(R.id.tx1);
tx1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), ProductListActivity.class);
intent.putExtra("product_type", productsArr[1] );
startActivity(intent);
}
});
tx2 = (TextView)vw.findViewById(R.id.tx2);
tx2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), ProductListActivity.class);
intent.putExtra("product_type", productsArr[2] );
startActivity(intent);
}
});
tx3 = (TextView)vw.findViewById(R.id.tx3);
tx3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(vw.getContext(), ProductListActivity.class);
intent.putExtra("product_type", productsArr[3] );
startActivity(intent);
}
});
addProducts = vw.findViewById(floatingActionButton_addProducts);
addProducts.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(vw.getContext(), AddProducts.class);
startActivity(intent);
}
});
return vw;
}
}
| d3eec8369b08b2f9817abb8729de5b8a3545d34e | [
"Markdown",
"Java"
] | 20 | Java | HansikaPerera/TheStationeryManager | 26eee62b8f54185a9210db16562c4a6bfc4dc054 | a0a0f7b3a46bf1d840702f8cba2c46f739e85fb9 |
refs/heads/master | <file_sep>import sys;
dataToSendBack = {"hi" : "hello"}
print(dataToSendBack)
sys.stdout.flush()<file_sep>import requests
from bs4 import BeautifulSoup
import json
import sys
# get the link of the mainpage and convert it to beautiful soup for parsing
page = "https://seekingalpha.com/market-news/all"
r = requests.get(page)
soup = BeautifulSoup(r.content, "lxml")
data = {}
next_attr = soup.find(attrs={"class" : "next"})
temp_breaker_count = 0
for ticker in soup.find_all(attrs={"class" : "mc"}):
temp_breaker_count += 1
ticker_name = ticker.find(attrs={"class" : "media-left"}).text.strip()
news_title = ticker.find(attrs={"class" : "title"}).text.strip()
bullets_header = ticker.find(attrs={"class" : "bullets"})
bullets = [bullet.text.strip().replace("\'", "`").strip() for bullet in bullets_header.find_all("li")]
internal_json = {"title" : news_title.replace("\'", "`").strip(), "bullets" : bullets}
internal_json = json.dumps(internal_json)
data[ticker_name] = internal_json
if temp_breaker_count >= 1:
break
json_final_data = json.dumps(data)
print(json_final_data)
sys.stdout.flush()
| d86004c40d51c0fbb029fa596ea46edadb6173a4 | [
"Python"
] | 2 | Python | brandonko/StockBot | 26692abf2153bc4c325ea2f6cade7665e2a926a8 | 35f64dfbc129558ab2430d0fef7cd831ab7ccedb |
refs/heads/master | <file_sep>//
// ViewController.swift
//
// Created by nakajijapan on 3/28/15.
// Copyright (c) 2015 net.nakajijapan. All rights reserved.
//
import UIKit
import SDWebImage
@objc public protocol PhotoSliderDelegate:NSObjectProtocol {
optional func photoSliderControllerWillDismiss(viewController: PhotoSlider.ViewController)
optional func photoSliderControllerDidDismiss(viewController: PhotoSlider.ViewController)
}
enum PhotoSliderControllerScrollMode:Int {
case None = 0, Vertical, Horizontal
}
public class ViewController:UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var imageURLs:Array<NSURL>?
var pageControl:UIPageControl!
var backgroundView:UIView!
var closeButton:UIButton?
var scrollMode:PhotoSliderControllerScrollMode = .None
var scrollInitalized = false
var closeAnimating = false
public var delegate: PhotoSliderDelegate? = nil
public var visiblePageControl = true
public var visibleCloseButton = true
public var index:Int = 0
public init(imageURLs:Array<NSURL>) {
super.init(nibName: nil, bundle: nil)
self.imageURLs = imageURLs
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public override func viewDidLoad() {
super.viewDidLoad()
self.view.frame = UIScreen.mainScreen().bounds
self.view.backgroundColor = UIColor.clearColor()
self.view.userInteractionEnabled = true
self.backgroundView = UIView(frame: self.view.bounds)
self.backgroundView.backgroundColor = UIColor.blackColor()
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 {
self.view.addSubview(self.backgroundView)
} else {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let effectView = UIVisualEffectView(effect: blurEffect)
effectView.frame = self.view.bounds
self.view.addSubview(effectView)
effectView.addSubview(self.backgroundView)
}
// scrollview setting for Item
self.scrollView = UIScrollView(frame: CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height))
self.scrollView.pagingEnabled = true
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.delegate = self
self.scrollView.clipsToBounds = false
self.scrollView.alwaysBounceHorizontal = true
self.scrollView.alwaysBounceVertical = true
self.scrollView.scrollEnabled = true
self.view.addSubview(self.scrollView)
self.scrollView.contentSize = CGSizeMake(
CGRectGetWidth(self.view.bounds) * CGFloat(self.imageURLs!.count),
CGRectGetHeight(self.view.bounds) * 3.0
)
let width = CGRectGetWidth(self.view.bounds)
let height = CGRectGetHeight(self.view.bounds)
var frame = self.view.bounds
frame.origin.y = height
for imageURL in self.imageURLs! {
var imageView:PhotoSlider.ImageView = PhotoSlider.ImageView(frame: frame)
self.scrollView.addSubview(imageView)
imageView.loadImage(imageURL)
frame.origin.x += width
}
self.scrollView.contentOffset = CGPointMake(0, height)
// pagecontrol
if self.visiblePageControl {
self.pageControl = UIPageControl(frame: CGRectMake(0.0, CGRectGetHeight(self.view.bounds) - 44, CGRectGetWidth(self.view.bounds), 22))
self.pageControl.numberOfPages = imageURLs!.count
self.pageControl.currentPage = 0
self.pageControl.userInteractionEnabled = false
self.view.addSubview(self.pageControl)
}
if self.visibleCloseButton {
self.closeButton = UIButton(frame: CGRect(
x: CGRectGetWidth(self.view.frame) - 32.0 - 8.0, y: 8.0,
width: 32.0, height: 32.0)
)
var imagePath = self.resourceBundle().pathForResource("PhotoSliderClose", ofType: "png")
self.closeButton!.setImage(UIImage(contentsOfFile: imagePath!), forState: UIControlState.Normal)
self.closeButton!.addTarget(self, action: "closeButtonDidTap:", forControlEvents: UIControlEvents.TouchUpInside)
self.closeButton!.imageView?.contentMode = UIViewContentMode.Center;
self.view.addSubview(self.closeButton!)
}
if self.respondsToSelector("setNeedsStatusBarAppearanceUpdate") {
self.setNeedsStatusBarAppearanceUpdate()
}
}
override public func viewWillAppear(animated: Bool) {
self.scrollView.contentOffset = CGPointMake(self.scrollView.bounds.width * CGFloat(self.index), self.scrollView.bounds.height)
self.scrollInitalized = true
}
public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.dismissViewControllerAnimated(true) { () -> Void in
self.view.removeFromSuperview()
}
}
// MARK: - UIScrollViewDelegate
var scrollPreviewPoint = CGPointZero;
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.scrollPreviewPoint = scrollView.contentOffset
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollInitalized == false {
self.generateCurrentPage()
return
}
let offsetX = fabs(scrollView.contentOffset.x - self.scrollPreviewPoint.x)
let offsetY = fabs(scrollView.contentOffset.y - self.scrollPreviewPoint.y)
if self.scrollMode == .None {
if (offsetY > offsetX) {
self.scrollMode = .Vertical;
} else {
self.scrollMode = .Horizontal;
}
}
if self.scrollMode == .Vertical {
let offsetHeight = fabs(scrollView.frame.size.height - scrollView.contentOffset.y)
let alpha = 1.0 - (fabs(offsetHeight) / (scrollView.frame.size.height / 2.0))
self.backgroundView.alpha = alpha
var contentOffset = scrollView.contentOffset
contentOffset.x = self.scrollPreviewPoint.x
scrollView.contentOffset = contentOffset
let screenHeight = UIScreen.mainScreen().bounds.size.height
if self.scrollView.contentOffset.y > screenHeight * 1.4 {
self.closePhotoSlider(true)
} else if self.scrollView.contentOffset.y < screenHeight * 0.6 {
self.closePhotoSlider(false)
}
} else if self.scrollMode == .Horizontal {
var contentOffset = scrollView.contentOffset
contentOffset.y = self.scrollPreviewPoint.y
scrollView.contentOffset = contentOffset
}
self.generateCurrentPage()
}
func generateCurrentPage() {
if self.visiblePageControl {
if fmod(scrollView.contentOffset.x, scrollView.frame.size.width) == 0.0 {
if self.pageControl != nil {
self.pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
}
}
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if self.scrollMode == .Vertical {
let velocity = scrollView.panGestureRecognizer.velocityInView(scrollView)
if velocity.y < -500 {
self.scrollView.frame = scrollView.frame;
self.closePhotoSlider(true)
} else if velocity.y > 500 {
self.scrollView.frame = scrollView.frame;
self.closePhotoSlider(false)
}
}
}
func closePhotoSlider(up:Bool) {
if self.closeAnimating == true {
return
}
self.closeAnimating = true
let screenHeight = UIScreen.mainScreen().bounds.size.height
let screenWidth = UIScreen.mainScreen().bounds.size.width
var movedHeight = CGFloat(0)
if self.delegate!.respondsToSelector("photoSliderControllerWillDismiss:") {
self.delegate!.photoSliderControllerWillDismiss!(self)
}
if up {
movedHeight = -screenHeight
} else {
movedHeight = screenHeight
}
UIView.animateWithDuration(
0.4,
delay: 0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: { () -> Void in
self.scrollView.frame = CGRectMake(0, movedHeight, screenWidth, screenHeight)
self.backgroundView.alpha = 0.0
self.closeButton?.alpha = 0.0
self.view.alpha = 0.0
},
completion: {(result) -> Void in
self.dissmissViewControllerAnimated(false)
self.closeAnimating = false
}
)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.scrollMode = .None
}
// MARK: - Button Actions
func closeButtonDidTap(sender:UIButton) {
if self.delegate!.respondsToSelector("photoSliderControllerWillDismiss:") {
self.delegate!.photoSliderControllerWillDismiss!(self)
}
self.dissmissViewControllerAnimated(true)
}
// MARK: - Private Methods
func dissmissViewControllerAnimated(animated:Bool) {
self.dismissViewControllerAnimated(animated, completion: { () -> Void in
if self.delegate!.respondsToSelector("photoSliderControllerDidDismiss:") {
self.delegate!.photoSliderControllerDidDismiss!(self)
}
})
}
func resourceBundle() -> NSBundle {
var bundlePath = NSBundle.mainBundle().pathForResource(
"PhotoSlider",
ofType: "bundle",
inDirectory: "Frameworks/PhotoSlider.framework"
)
var bundle = NSBundle(path: bundlePath!)
return bundle!
}
}
| b9182d97ad7247982bc8d3ae52017f04f493905f | [
"Swift"
] | 1 | Swift | valentebruno/PhotoSlider | df92ece94ba283f22436cd89c259e302e5e7e186 | 456d8996bf7b8482f8e4ad0dc602e8ff43b45b2b |
refs/heads/master | <repo_name>abelovq/react-draggable-snap<file_sep>/example/example.js
const { ReactDraggable: Draggable, React, ReactDOM } = window;
// import './drag.css';
class App extends React.Component {
state = {
activeDrags: 0,
deltaPosition: {
x: 0, y: 0
},
// controlledPosition: {
// x: -400, y: 200
// },
isSnapped: false,
isCenteredX: false,
isCenteredY: false,
grid: [1, 1],
posX: 0,
posY: 0,
axis: 'both',
stopdrag: false,
x: undefined,
y: undefined
};
handleDrag = (e, ui) => {
window.console.log('handleDrag', e.clientX, e.clientY);
// console.log('ui', ui);
const { x, y } = this.state.deltaPosition;
// if (e.clientX >= 350 && e.clientY >= 400) {
// console.log('INNER');
// this.setState({ deltaPosition: { x: 400, y: 250 } });
// }
this.setState({
deltaPosition: {
x: x + ui.deltaX,
y: y + ui.deltaY,
}
});
};
onStart = () => {
this.setState({ activeDrags: ++this.state.activeDrags });
};
onStop = () => {
this.setState({ activeDrags: --this.state.activeDrags });
};
// For controlled component
adjustXPos = (e) => {
e.preventDefault();
e.stopPropagation();
const { x, y } = this.state.controlledPosition;
this.setState({ controlledPosition: { x: x - 10, y } });
};
adjustYPos = (e) => {
e.preventDefault();
e.stopPropagation();
const { controlledPosition } = this.state;
const { x, y } = controlledPosition;
this.setState({ controlledPosition: { x, y: y - 10 } });
};
onControlledDrag = (e, position) => {
const { x, y } = position;
// if (e.clientX >= 350 && e.clientY >= 400) {
// console.log('INNER');
// this.setState({ controlledPosition: { x: 400, y: 250 } });
// } else {
// this.setState({ controlledPosition: { x, y } });
// }
// console.log('handleDrag');
// const { isCenteredX, isCenteredY } = this.state;
// this.props.onLineVisible(true);
// const description = this.rnd;
const verticalLine = document.querySelector('.header-lines .vert');
const horizontalLine = document.querySelector('.header-lines .horiz');
const {
x: descX,
y: descY,
width,
height,
top,
left
} = document.querySelector('.box1').getBoundingClientRect();
const { x: verticalLineX } = verticalLine.getBoundingClientRect();
const { y: horizontalLineY } = horizontalLine.getBoundingClientRect();
const descriptionCenterX = descX + width / 2;
const descriptionCenterY = descY + height / 2;
const calcHeight =
Math.abs(descriptionCenterY - horizontalLineY - 320) < 30
? Math.abs(descriptionCenterY - horizontalLineY)
: 30;
const calcWidth =
Math.abs(descriptionCenterX - verticalLineX - 320) < 30
? Math.abs(descriptionCenterX - verticalLineX)
: 30;
const checkDistanceByAxis = (e, axis) => {
if (axis === 'x') {
return Math.abs(e.clientX - this.state.posX) >= calcWidth
? true
: false;
}
if (axis === 'y') {
return Math.abs(e.clientY - this.state.posY) >= calcHeight
? true
: false;
}
if (axis === 'xy') {
return Math.abs(e.clientY - this.state.posY) >= calcWidth ||
Math.abs(e.clientX - this.state.posX) >= calcHeight
? true
: false;
}
};
// console.log('Math.abs(e.clientX - this.state.posX) >= calcWidth', Math.abs(e.clientX - this.state.posX) + '-------' + calcWidth);
if (this.state.isCenteredX && this.state.posX === 0) {
this.setState({ posX: e.clientX });
return;
}
if (this.state.isCenteredY && this.state.posY === 0) {
this.setState({ posY: e.clientY });
return;
}
// if (!this.state.isCenteredX && !this.state.isCenteredY) {
// this.setState({ x, y });
// }
// if (this.state.isCenteredX && !this.state.isCenteredY) {
// this.setState({ x: this.state.x, y });
// }
// if (this.state.isCenteredY && !this.state.isCenteredX) {
// this.setState({ x, y: this.state.y });
// }
// if (this.state.isCenteredY && this.state.isCenteredX) {
// this.setState({ x: this.state.x, y: this.state.y });
// }
if (this.state.isCenteredX && checkDistanceByAxis(e, 'x')) {
// console.log('checkDistanceByAxis');
this.setState({
isCenteredX: false,
posX: 0,
axis: 'both'
});
return;
}
if (this.state.isCenteredY && checkDistanceByAxis(e, 'y')) {
this.setState({
isCenteredY: false,
posY: 0,
axis: 'both'
});
return;
}
if (
this.state.isCenteredX &&
this.state.isCenteredY &&
checkDistanceByAxis(e, 'xy')
) {
this.setState({
isCenteredY: false,
isCenteredX: false,
posY: 0,
posX: 0,
axis: 'both'
});
return;
} else {
if (this.state.isCenteredX && this.state.isCenteredY) {
this.setState({ axis: 'none' }
// , () => {
// once(flag => {
// console.log('flag', flag);
// this.setState({ stopdrag: flag });
// });
// }
);
}
if (
Math.abs(descriptionCenterX - verticalLineX) < calcWidth &&
!this.state.isCenteredX
) {
console.log('X ESLE');
const x = verticalLineX - 61 - width / 2;
const y = top - 157.875;
// window.console.log(x, y);
this.setState({ isCenteredX: true, axis: 'y', x, y }
// , () => {
// once(flag => {
// console.log('flag', flag);
// this.setState({ stopdrag: flag });
// });
// }
);
// return true;
}
if (
Math.abs(descriptionCenterY - horizontalLineY) < calcHeight &&
!this.state.isCenteredY
) {
const x = left - 60;
const y = (horizontalLineY - 159) - height / 2;
console.log('Y ESLE', x, y);
this.setState({ isCenteredY: true, axis: 'x', x, y });
// return true;
}
}
};
onControlledDragStop = (e, position) => {
console.log('onControlledDragStop', position);
if (!this.state.isCenteredX && !this.state.isCenteredY) {
this.setState({ x: position.x, y: position.y });
}
if (this.state.isCenteredX && !this.state.isCenteredY) {
this.setState({ x: this.state.x, y: position.y });
}
if (this.state.isCenteredY && !this.state.isCenteredX) {
this.setState({ x: position.x, y: this.state.y });
}
if (this.state.isCenteredY && this.state.isCenteredX) {
console.log('CENTER');
this.setState({ x: 805.5, y: 192.5 });
}
// this.onControlledDrag(e, position);
this.onStop();
};
handleDragStart = e => {
console.log('handleDragStart', e);
if (this.state.isCenteredX) {
this.setState({ posX: e.clientX });
}
if (this.state.isCenteredY) {
this.setState({ posY: e.clientY });
}
};
render() {
const dragHandlers = { onStart: this.onStart, onStop: this.onStop };
const { deltaPosition, controlledPosition } = this.state;
return (
<div>
<h1>React Draggable</h1>
<p>Active DragHandlers: {this.state.activeDrags}</p>
<p>
<a href="https://github.com/mzabriskie/react-draggable/blob/master/example/index.html">Demo Source</a>
</p>
{/* <Draggable {...dragHandlers} onDrag={this.handleDrag} position={this.state.deltaPosition}>
<div className="box">I can be dragged anywhere</div>
</Draggable> */}
<div className="header-lines">
{/* <span className="vert" hidden={isBlockDragged} />
<span className="horiz" hidden={isBlockDragged} /> */}
<span className="vert" />
<span className="horiz" />
</div>
{/* <Draggable onDrag={this.handleDrag} {...dragHandlers} >
<div className="box">
<div>I track my deltas</div>
<div>x: {deltaPosition.x.toFixed(0)}, y: {deltaPosition.y.toFixed(0)}</div>
</div>
</Draggable> */}
<Draggable position={{ x: this.state.x || 0, y: this.state.y || 0 }} {...dragHandlers} onStart={this.handleDragStart} onDrag={this.onControlledDrag} axis={this.state.axis} bounds=".header-lines" onStop={this.onControlledDragStop} isSnapped={this.state.isSnapped}>
<div className="box1">
My position can be changed programmatically. <br />
I have a drag handler to sync state.
<p>
<a href="#" onClick={this.adjustXPos}>Adjust x ({this.state.x})</a>
</p>
<p>
<a href="#" onClick={this.adjustYPos}>Adjust y ({this.state.y})</a>
</p>
</div>
</Draggable>
{/* <Draggable axis="x" {...dragHandlers}>
<div className="box cursor-x">I can only be dragged horizonally (x axis)</div>
</Draggable>
<Draggable axis="y" {...dragHandlers}>
<div className="box cursor-y">I can only be dragged vertically (y axis)</div>
</Draggable>
<Draggable onStart={() => false}>
<div className="box">I don't want to be dragged</div>
</Draggable>
<Draggable onDrag={this.handleDrag} {...dragHandlers}>
<div className="box">
<div>I track my deltas</div>
<div>x: {deltaPosition.x.toFixed(0)}, y: {deltaPosition.y.toFixed(0)}</div>
</div>
</Draggable>
<Draggable handle="strong" {...dragHandlers}>
<div className="box no-cursor">
<strong className="cursor"><div>Drag here</div></strong>
<div>You must click my handle to drag me</div>
</div>
</Draggable>
<Draggable cancel="strong" {...dragHandlers}>
<div className="box">
<strong className="no-cursor">Can't drag here</strong>
<div>Dragging here works</div>
</div>
</Draggable>
<Draggable grid={[25, 25]} {...dragHandlers}>
<div className="box">I snap to a 25 x 25 grid</div>
</Draggable>
<Draggable grid={[50, 50]} {...dragHandlers}>
<div className="box">I snap to a 50 x 50 grid</div>
</Draggable>
<Draggable bounds={{top: -100, left: -100, right: 100, bottom: 100}} {...dragHandlers}>
<div className="box">I can only be moved 100px in any direction.</div>
</Draggable>
<div className="box" style={{height: '500px', width: '500px', position: 'relative', overflow: 'auto', padding: '0'}}>
<div style={{height: '1000px', width: '1000px', padding: '10px'}}>
<Draggable bounds="parent" {...dragHandlers}>
<div className="box">
I can only be moved within my offsetParent.<br /><br />
Both parent padding and child margin work properly.
</div>
</Draggable>
<Draggable bounds="parent" {...dragHandlers}>
<div className="box">
I also can only be moved within my offsetParent.<br /><br />
Both parent padding and child margin work properly.
</div>
</Draggable>
</div>
</div>
<Draggable bounds="body" {...dragHandlers}>
<div className="box">
I can only be moved within the confines of the body element.
</div>
</Draggable>
<Draggable {...dragHandlers}>
<div className="box" style={{position: 'absolute', bottom: '100px', right: '100px'}}>
I already have an absolute position.
</div>
</Draggable>
<Draggable defaultPosition={{x: 25, y: 25}} {...dragHandlers}>
<div className="box">
{"I have a default position of {x: 25, y: 25}, so I'm slightly offset."}
</div>
</Draggable>
<Draggable positionOffset={{x: '-10%', y: '-10%'}} {...dragHandlers}>
<div className="box">
{'I have a default position based on percents {x: \'-10%\', y: \'-10%\'}, so I\'m slightly offset.'}
</div>
</Draggable>*/}
{/* <Draggable position={{ x: this.state.x || 0, y: this.state.y || 0 }} {...dragHandlers} onDrag={this.onControlledDrag} axis={this.state.axis}>
<div className="box1">
My position can be changed programmatically. <br />
I have a drag handler to sync state.
<p>
<a href="#" onClick={this.adjustXPos}>Adjust x ({this.state.x})</a>
</p>
<p>
<a href="#" onClick={this.adjustYPos}>Adjust y ({this.state.y})</a>
</p>
</div>
</Draggable> */}
{/* <Draggable position={controlledPosition} {...dragHandlers} onStop={this.onControlledDragStop}>
<div className="box">
My position can be changed programmatically. <br />
I have a dragStop handler to sync state.
<p>
<a href="#" onClick={this.adjustXPos}>Adjust x ({controlledPosition.x})</a>
</p>
<p>
<a href="#" onClick={this.adjustYPos}>Adjust y ({controlledPosition.y})</a>
</p>
</div>
</Draggable> */}
</div >
);
}
}
ReactDOM.render(<App />, document.getElementById('container'));
| 1ffbbaebce53156f0ee62a4595a324678e54f8a3 | [
"JavaScript"
] | 1 | JavaScript | abelovq/react-draggable-snap | 5fe1ef09a0d943b2a61f0bcc621bfb62d52399b2 | 82a3588b93210648e8ce0912718aa18f37ff3769 |
refs/heads/master | <file_sep> getTime() {
return (this.data = this.data.items.map(item => ({
...item,
insert_time: new Date(item.insert_time)
.toISOString()
.replace(/T/, " ")
.replace(/\..+/, "")
})));
const today = new Date();
// const das = new Date(Date.parse(item.insert_time)).toUTCString()
return console.log(this.today);
} | 0f31a771c056e7a20931c0d9de9c73976c725f88 | [
"JavaScript"
] | 1 | JavaScript | ArtmenV/Change_data_from_server_example | 904d342baa989301ec5915ae54fbc7b5d1c8d312 | 0d427b1a071b1232f64e3645a98f916190263cd9 |
refs/heads/master | <file_sep>๏ปฟusing TMPro;
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
public class EndOfDay : MonoBehaviour
{
public string nextScene;
public TextAsset textAsset;
private string outputStr;
// This is the total number of redactions so far so for day 1 it is day 1
// for day 2 it is day 1 + day 2, etc.
public double totalNumberOfRedactions;
private void Awake()
{
GameObject textObject = GameObject.Find("DocumentText");
outputStr = textAsset.text + "";
if (GameObject.Find("AudioManager").GetComponent<AudioManager>().dayCount != 3)
{
int incorrect = GameObject.Find("AudioManager").GetComponent<AudioManager>().incorrectCount;
double percent = GameObject.Find("AudioManager").GetComponent<AudioManager>().correctCount / totalNumberOfRedactions * 100.0;
percent = Math.Round(percent, 2);
outputStr = outputStr.Replace("NNN", percent.ToString());
outputStr = outputStr.Replace("MMM", incorrect.ToString());
}
textObject.GetComponent<TextMeshProUGUI>().text = outputStr;
}
public void NextDay()
{
if (GameObject.Find("AudioManager").GetComponent<AudioManager>().dayCount == 3)
{
GameObject.Find("AudioManager").GetComponent<AudioManager>().StopAudio("Day3");
GameObject.Find("AudioManager").GetComponent<AudioManager>().PlayAudio("End");
}
else
{
GameObject.Find("AudioManager").GetComponent<AudioManager>().StopAudio("EndOfDay");
GameObject.Find("AudioManager").GetComponent<AudioManager>().PlayAudio("Whistle");
}
SceneManager.LoadScene(nextScene);
}
}
<file_sep>๏ปฟusing TMPro;
using UnityEngine;
using UnityEditor;
using System.IO;
public class LoadText : MonoBehaviour
{
void Awake()
{
string path = "text_test";
TextAsset test = Resources.Load<TextAsset>(path);
GameObject text = GameObject.Find("TMP_Text");
text.GetComponent<TextMeshProUGUI>().text = test.text;
}
}<file_sep>๏ปฟusing TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using System.Linq;
public class ClickableText : MonoBehaviour, IPointerClickHandler
{
public string textName;
private GameObject text;
public int correctCount = 0;
public int incorrectCount = 0;
// The list of keywords to look for in this text instance
public string[] keywords;
private void Start()
{
text = GameObject.Find(textName);
}
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
// Debug.Log("Left click");
var text_var = text.GetComponent<TextMeshProUGUI>();
int linkIndex = TMP_TextUtilities.FindIntersectingLink(text_var, Input.mousePosition, null);
if (linkIndex > -1)
{
var linkInfo = text_var.textInfo.linkInfo[linkIndex];
var linkId = linkInfo.GetLinkID();
string linkStr = "<link=" + linkId.ToString() + "><color=white>";
string replaceStr = "<link=" + linkId.ToString() + "><color=black>";
string endStr = "</";
string clickedString = getBetween(text.GetComponent<TextMeshProUGUI>().text, linkStr, endStr);
text.GetComponent<TextMeshProUGUI>().text = text.GetComponent<TextMeshProUGUI>().text.Replace(linkStr, replaceStr);
if (keywords.Any(clickedString.Contains))
{
correctCount += 1;
}
else
{
incorrectCount += 1;
}
}
}
else if (eventData.button == PointerEventData.InputButton.Middle)
{
// Debug.Log("Middle click");
}
else if (eventData.button == PointerEventData.InputButton.Right)
{
Debug.Log("Right click");
}
}
string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "111111";
}
}
}<file_sep>๏ปฟusing TMPro;
using UnityEngine;
using UnityEditor;
using System.IO;
public class LoadInaccuracyText : MonoBehaviour
{
public TextAsset inaccuracyTextFile;
void Awake()
{
GameObject text = GameObject.Find("InaccuracyText");
text.GetComponent<TextMeshProUGUI>().text = inaccuracyTextFile.text;
}
}<file_sep># Parse and modify the text
# Save to output text file
import re
def main():
with open('d3_zach.txt') as f:
list_of_words = re.findall(r'\S+|\n',f.read())
c = 0
newline_flag = False
out_str = ""
for w in list_of_words:
if w != "\n":
if newline_flag:
if not re.match("^[a-zA-Z0-9_]*$", w):
out_str += ("<link=" + str(c) + "><color=white>"+ w[:-1] + "</color></link>" + w[-1])
else:
out_str += ("<link=" + str(c) + "><color=white>"+ w + "</color></link>")
out_str += " "
newline_flag = False
else:
if not re.match("^[a-zA-Z0-9_]*$", w):
out_str += ("<link=" + str(c) + "><color=white>"+ w[:-1] + "</color></link>" + w[-1])
else:
out_str += ("<link=" + str(c) + "><color=white>"+ w + "</color></link>")
out_str += " "
c += 1
else:
out_str += w
newline_flag = True
with open("d3_zach_mod.txt", 'r+') as out:
out.write(out_str)
f.close()
out.close()
if __name__ == '__main__':
main()<file_sep>๏ปฟusing TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadDayText : MonoBehaviour
{
public TextAsset[] dayText;
private int clickCount = 0;
private GameObject text;
public string nextScene;
void Awake()
{
text = GameObject.Find("DocumentText");
text.GetComponent<TextMeshProUGUI>().text = dayText[clickCount].text;
}
public void NextClick()
{
clickCount += 1;
if (clickCount < dayText.Length)
{
text.GetComponent<TextMeshProUGUI>().text = dayText[clickCount].text;
}
else
{
GameObject.Find("AudioManager").GetComponent<AudioManager>().dayCount += 1;
GameObject.Find("AudioManager").GetComponent<AudioManager>().correctCount += GameObject.Find("Canvas").GetComponent<ClickableText>().correctCount;
GameObject.Find("AudioManager").GetComponent<AudioManager>().incorrectCount += GameObject.Find("Canvas").GetComponent<ClickableText>().incorrectCount;
if (GameObject.Find("AudioManager").GetComponent<AudioManager>().dayCount == 3)
{
GameObject.Find("AudioManager").GetComponent<AudioManager>().StopAudio("Whistle");
GameObject.Find("AudioManager").GetComponent<AudioManager>().PlayAudio("Day3");
}
else
{
GameObject.Find("AudioManager").GetComponent<AudioManager>().StopAudio("Whistle");
GameObject.Find("AudioManager").GetComponent<AudioManager>().PlayAudio("EndOfDay");
}
SceneManager.LoadScene(nextScene);
}
}
}<file_sep># <REDACTED>
<REDACTED> P.T. P.O.C.
https://judequinn.itch.io/redacted
<file_sep>๏ปฟusing UnityEngine;
using UnityEngine.SceneManagement;
public class Credits : MonoBehaviour {
public void GoToIntroduction()
{
SceneManager.LoadScene("Introduction");
}
public void GoToCredits()
{
SceneManager.LoadScene("Credits");
}
public void GoToMainMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void GoToAbout()
{
SceneManager.LoadScene("About");
}
}
<file_sep>๏ปฟusing TMPro;
using UnityEngine;
using System.Collections;
public class EndScene : MonoBehaviour
{
public float delay;
IEnumerator Start()
{
yield return new WaitForSeconds(delay);
GameObject.Find("UpperText").GetComponent<TextMeshProUGUI>().text = "<REDACTED>";
GameObject.Find("LowerText").GetComponent<TextMeshProUGUI>().enabled = true;
}
}<file_sep>๏ปฟusing TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Introduction : MonoBehaviour
{
private int clickCount = 0;
public GameObject panel1;
public GameObject panel2;
public GameObject text;
public void NextClick()
{
clickCount += 1;
if (clickCount == 1)
{
TextAsset t1= Resources.Load<TextAsset>("IntroText/intro_t_1");
GameObject.Find("TMP_Text").GetComponent<TextMeshProUGUI>().text = t1.text;
panel1.SetActive(true);
panel2.SetActive(true);
text.SetActive(true);
}
if (clickCount == 2)
{
TextAsset t2 = Resources.Load<TextAsset>("IntroText/intro_t_2");
GameObject.Find("TMP_Text").GetComponent<TextMeshProUGUI>().text = t2.text;
GameObject.Find("NextButtonText").GetComponent<TextMeshProUGUI>().text = "Start";
text.GetComponent<TextMeshProUGUI>().text = "Today's Inaccuracy:";
}
if (clickCount == 3)
{
SceneManager.LoadScene("Day1");
GameObject.Find("AudioManager").GetComponent<AudioManager>().StopAudio("MainMenuTheme");
GameObject.Find("AudioManager").GetComponent<AudioManager>().PlayAudio("Whistle");
}
}
}
| 2ebe44938d8f2a62449d3c8a33d5470ecb9f4ea9 | [
"Markdown",
"C#",
"Python"
] | 10 | C# | JosephOHagan/gugamejam6-redacted | 1185adfa1d0436d4c058b1fa1473b2ebb40130e7 | 80e906f9656953b99696355292210b6b65a8c8a0 |
refs/heads/master | <repo_name>pintjuk/MineTD<file_sep>/src/kth/pintjukarlsson/minetd/Stat.java
package kth.pintjukarlsson.minetd;
import com.badlogic.gdx.math.Vector2;
public class Stat {
private int x, y;
private TileType[] tiles = new TileType[4];
public int getX() {
return x;
}
public int getY() {
return y;
}
public Vector2 pos(){
return new Vector2((float)x, (float)y);
}
public Stat(int x, int y, TileType t1, TileType t2,
TileType t3, TileType t4){
this.x=x;
this.y=y;
this.tiles[0] = t1;
this.tiles[1] = t2;
this.tiles[2] = t3;
this.tiles[3] = t4;
}
public boolean containts(int x, int y){
return (x==this.x||x==this.x+1)&&
(y==this.y||y==this.y-1);
}
public TileType getFirstTileType(){
return tiles[0];
}
public float getValue(){
return (tiles[1].getValue()+
tiles[2].getValue()+
tiles[3].getValue())/3;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Stat))
return false;
return ((Stat)obj).x==x&&((Stat)obj).y==y;
}
}
<file_sep>/src/kth/pintjukarlsson/graph/Dijkstra.java
package kth.pintjukarlsson.graph;
import java.util.PriorityQueue;
import java.util.Stack;
public class Dijkstra {
/**
* Returns an int array representing the cheapest path from "from" to "to".
*
* Returns a ziro size array if no path exists,
* for example if from and to are parts of seperet components
* @param graph
* @param from
* @param to
* @return
*/
public static ImmutablePosition[] findPath(PositionGraph graph, ImmutablePosition from, ImmutablePosition to){
if(from.equals(to))
return new ImmutablePosition[]{};
boolean[][] visited = new boolean[graph.getHight()][graph.getWidth()];
PriorityQueue<Path> alternetPaths = new PriorityQueue<Path>(10000);
Path first = Path.make(to);
first.add(from, graph);
alternetPaths.add(first);
float time = 0;
while (!alternetPaths.isEmpty()){
time=System.nanoTime();
Path bestPath = alternetPaths.poll();
visited[bestPath.path.peek().getY()][bestPath.path.peek().getX()]=true;
if(bestPath.path.peek().equals(to))
return bestPath.toArray();
for(VertexIterator iter = graph.neighbors(bestPath.path.peek());iter.hasNext();){
ImmutablePosition next = iter.next();
if(!visited[next.getY()][next.getX()]){
visited[next.getY()][next.getX()]=true;
float tonextcost = calcCost(bestPath.path.peek(), next);
alternetPaths.add(bestPath.clone().add(next, graph));
}
}
}
//System.gc();
return new ImmutablePosition[]{};
}
private static class Path implements Comparable<Path>{
private float cost=0;
private float toGoal=0;
private final float balsnce= 1.2f;
private Stack<ImmutablePosition> path;
private ImmutablePosition goal;
@Override
public int compareTo(Path o) {
//return (int)(cost-o.cost);
return (int)((cost+(toGoal*balsnce))-(o.cost+(o.toGoal*balsnce)));
}
public static Path make(ImmutablePosition g){
Path result = new Path();
result.path = new Stack<ImmutablePosition>();
result.goal = g;
return result;
}
public Path clone() {
Path clone = new Path();
try{
clone.path=(Stack<ImmutablePosition>) path.clone();
}catch (Exception e) {
try {
throw new Exception("WTF, this is IMPOSSIBRUE"); // this is not helpful :3
} catch (Exception e1) {
e1.printStackTrace();
}
}
clone.cost = cost;
clone.goal = goal;
return clone;
}
public Path add(ImmutablePosition node, PositionGraph graph){
if(path.isEmpty()){
this.cost=0;
path.push(node);
toGoal = goal.manhatanDistance(node);
return this;
}
this.cost+= graph.cost(node, path.peek());
toGoal = goal.manhatanDistance(node);
path.push(node);
return this;
}
public ImmutablePosition[] toArray(){
ImmutablePosition[] result = new ImmutablePosition[path.size()];
Object[] array = path.toArray();
for(int i=0;i<array.length; i++)
result[i]=(ImmutablePosition)array[i];
return result;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder("[");
for(ImmutablePosition i: this.path)
s.append(i+", ");
s.append("]");
return s.toString();
}
}
public static float calcCost(ImmutablePosition a, ImmutablePosition b){
return a.manhatanDistance(b);
}
}
<file_sep>/src/kth/pintjukarlsson/graph/DijkstraTest.java
package kth.pintjukarlsson.graph;
import static org.junit.Assert.*;
import org.junit.Test;
public class DijkstraTest {
@Test
public void test() {
PositionGraph g1= new PositionGraph(1, 1);
PositionGraph g2 = new PositionGraph(2, 2);
PositionGraph g3 = new PositionGraph(4, 4);
g1.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(0, 0));
g2.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(1, 0));
g2.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(1, 1));
g2.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(0, 1));
g2.addBi(new ImmutablePosition(1, 1), new ImmutablePosition(0, 1));
g3.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(1, 0));
g3.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(1, 1));
g3.addBi(new ImmutablePosition(0, 0), new ImmutablePosition(0, 1));
g3.addBi(new ImmutablePosition(1, 1), new ImmutablePosition(0, 1));
g3.addBi(new ImmutablePosition(1, 1), new ImmutablePosition(1, 2));
assertEquals(Dijkstra.findPath(g1, new ImmutablePosition(0, 0),
new ImmutablePosition(0, 0)).length,
0);
assertEquals(Dijkstra.findPath(g2, new ImmutablePosition(0, 0),
new ImmutablePosition(1, 1)).length,
2);
assertEquals(Dijkstra.findPath(g3, new ImmutablePosition(0, 0),
new ImmutablePosition(1, 2)).length,
3);
}
}
<file_sep>/src/kth/pintjukarlsson/minetd/BuildingCell.java
package kth.pintjukarlsson.minetd;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
public class BuildingCell extends Cell {
}
<file_sep>/src/kth/pintjukarlsson/minetd/BuildingManager.java
package kth.pintjukarlsson.minetd;
import java.util.ArrayList;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import kth.pintjukarlsson.minetd.listeners.MapInteractionListener;
public class BuildingManager {
private ArrayList<Building> buildings;
private final MineTD game;
private MouseInputAdapter input;
private GameMap map;
private final BuildingManager THIS = this;
public BuildingManager(MineTD game) {
buildings = new ArrayList<>();
this.game = game;
}
public void init(){
input = game.getInput();
map = game.getLevel();
input.setMapInteractionListener(new MapInteractionListener() {
@Override
public void onTileRM(int x, int y, TileType t) {
removeAllStatsAtt(x, y);
}
@Override
public void onTileAdded(int x, int y, TileType t) {
TileType t11 = map.getTileType(x-1, y+1);
TileType t21 = map.getTileType(x, y+1);
TileType t31 = map.getTileType(x+1, y+1);
TileType t12 = map.getTileType(x-1, y);
TileType t32 = map.getTileType(x+1, y);
TileType t13 = map.getTileType(x-1, y-1);
TileType t23 = map.getTileType(x, y-1);
TileType t33 = map.getTileType(x+1, y-1);
/*
* ::
* :*
*/
if( map.hasBuilt(x, y+1)
&&map.hasBuilt(x-1, y)
&&map.hasBuilt(x-1, y+1)){
addToBuildingOreNewBuilding(new Stat(x-1, y+1
, t11, t21, t12, t));
}
/*
* :*
* ::
*/
else
if( map.hasBuilt(x, y-1)
&&map.hasBuilt(x-1, y)
&&map.hasBuilt(x-1, y-1)){
addToBuildingOreNewBuilding(new Stat(x-1, y
, t12, t, t13, t23));
}
/*
* ::
* *:
*/
else
if( map.hasBuilt(x, y+1)
&&map.hasBuilt(x+1, y)
&&map.hasBuilt(x+1, y+1)){
addToBuildingOreNewBuilding(new Stat(x, y+1
, t21, t31, t, t32));
}
/*
* *:
* ::
*/
else
if( map.hasBuilt(x, y-1)
&&map.hasBuilt(x+1, y)
&&map.hasBuilt(x+1, y-1)){
addToBuildingOreNewBuilding(new Stat(x, y
, t, t32, t23, t33));
}
}
private void addToBuildingOreNewBuilding(Stat stat) {
Building b = THIS.getBuildingWithStatAt(stat.getX()-1, stat.getY()+1);
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX(), stat.getY()+1);
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX()+1, stat.getY()+1);
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX()-1, stat.getY());
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX()+1, stat.getY());
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX()-1, stat.getY()-1);
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX(), stat.getY()-1);
if(b ==null)
b = THIS.getBuildingWithStatAt(stat.getX()+1, stat.getY()-1);
if(b ==null){
b = new Building(0, 0, game);
buildings.add(b);
}
b.addStat(stat);
}
});
}
public void removeAllStatsAtt(int x, int y){
ArrayList<Building> torm = new ArrayList<>();
for (Building b : buildings) {
b.removeStatsThahHave(x, y);
if(b.stats.size()==0){
torm.add(b);
}
}
for(Building b : torm)
buildings.remove(b);
}
public Building getBuildingWithStatAt(int x, int y){
for (Building b : buildings) {
if(b.hasStat(x,y))
return b;
}
return null;
}
// Runs the Update method for each existing Building
public void Update() {
for (Building b : buildings) {
b.Update();
}
}
// Runs the Draw method for each existing Building
public void Draw(SpriteBatch batch) {
for (Building b : buildings) {
b.Draw(batch);
}
}
}
<file_sep>/ideas.md
#MineTD
##Map
- tile base, with diferent mineable matereals
- scrol around
- random gerneration.
nothing fancy to begin with, maby a predrawn tununel system that is subtrakted form randumly placed boxes
- generate path graph
##Building
- trace paterns
- shoot enemies
- have effekts on enemies
##Enemies
- graph seach, path finding
- scale
- diferent types
##Wave control
- span enemie waves, scale every wave
##GUI
- klick on catbugs, giv them comands
- klick on buildings, display stats
- display remaining healf
- display resorces
<file_sep>/src/kth/pintjukarlsson/minetd/Building.java
package kth.pintjukarlsson.minetd;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
public class Building extends Entity {
private static class Bullet{
Vector2 pos;
Vector2 dir;
private final float speed=20;
public Bullet(Vector2 pos, Vector2 dir) {
this.pos=pos; this.dir=dir;
}
}
ArrayList<Stat> stats = new ArrayList<>();
ArrayList<Bullet> bullets=new ArrayList<>();
// Creates a new Building object at x, y
final private float defoultFireRate= 1;
final private int defoultRange= 3;
final private float defoultDamage=1;
private static Animation fire;
private static Texture firetile;
private TextureRegion bullet;
private AssetManager assetManager;
private EnemyManager enemies;
private Vector2 ameDir=Vector2.X;
private float internalTime=0;
private float firetime=0;
private float scale=1;
private boolean playfire=false;
private boolean bFire=false;
public Building(int x, int y, MineTD g) {
super(x, y, g);
}
/**
* {@inheritDoc Entity}
*/
@Override
public void Update() {
if (enemies == null)
init();
Enemy target = enemies.getClosestTo(getPos());
if (target != null) {
ameDir = new Vector2(target.getPos()).sub(getPos());
if(target.getPos().epsilonEquals(this.getPos(), this.getRange()))
bFire = true;
else
bFire=false;
} else {
bFire = false;
}
// fier
if (this.bFire) {
firetime += Gdx.graphics.getDeltaTime();
if (firetime > 1 / getFireRate()) {
firetime = 0;
fire();
}
}
// Update Bullets
ArrayList<Bullet> torm = new ArrayList<>();
for (Bullet b : bullets) {
b.pos.add(new Vector2(b.dir).scl(Gdx.graphics.getDeltaTime()
* b.speed));
for (Enemy e : enemies.getEnemies()) {
if (new Rectangle(e.getPos().x, e.getPos().y, 1, 1).contains(
b.pos.x, b.pos.y)) {
e.takeDamage(this.getDamage());
e.setPos(e.getPos().sub(b.dir.nor().scl(-0.3f)));
torm.add(b);
}
}
if (b.pos.x > 100 || b.pos.x < 0 || b.pos.y > 100 || b.pos.y < 0)
torm.add(b);
}
for (Bullet b : torm) {
bullets.remove(b);
}
}
private void fire() {
playfire=true;
bullets.add(new Bullet(new Vector2(getPos()), new Vector2(this.ameDir.nor())));
}
/**
* {@inheritDoc Entity}
*/
@Override
public void Draw(SpriteBatch batch) {
if(fire==null)
init();
if(playfire)
internalTime+=Gdx.graphics.getDeltaTime();
TextureRegion frame = fire.getKeyFrame(internalTime);
if(fire.getKeyFrameIndex(internalTime)==2){
internalTime=0;
playfire=false;
}
batch.draw(frame,getPos().x, getPos().y, 0.4f, 0.4f, 1.2f, 0.9f, scale, scale,((float)Math.atan2(-ameDir.y,-ameDir.x) +(float)Math.PI)*180/(float)Math.PI);
for(Bullet b: bullets)
batch.draw(bullet,b.pos.x, b.pos.y, 0.1f, 0.3f, 0.2f,0.6f, scale, scale,((float)Math.atan2(-b.dir.y,-b.dir.x) +(float)Math.PI/2)*180/(float)Math.PI);
}
private void init() {
assetManager = getGame().getAssetManager();
enemies = getGame().getEnemiesManager();
firetile=assetManager.get("data/gun.png", Texture.class);
TextureRegion[] regions []= TextureRegion.split(firetile, 18, 10);
TextureRegion[] bulletregions []= TextureRegion.split(firetile, 2, 8);
fire = new Animation(0.05f, regions[0][0], regions[1][0], regions[2][0]);
bullet = bulletregions[bulletregions.length-1][bulletregions[bulletregions.length-1].length-1];
fire.setPlayMode(Animation.LOOP);
}
private void updatePos(){
float x = 0;
float y = 0;
for(Stat s: this.stats){
x += s.getX();
y += s.getY();
}
x/=(float)stats.size();
y/=(float)stats.size();
setPos( new Vector2(0.5f+x,-0.5f+ y));
scale = 1+(stats.size()-1)/5;
}
public float getFireRate(){
return defoultFireRate*getGetCombinedPowerOfAllStatsOfType(TileType.STONE);
}
public float getRange(){
return defoultRange*getGetCombinedPowerOfAllStatsOfType(TileType.GOLD);
}
public float getDamage(){
return defoultDamage*getGetCombinedPowerOfAllStatsOfType(TileType.IRON);
}
public float getBulletSpeed(){
return 20*getGetCombinedPowerOfAllStatsOfType(TileType.GRAVEL);
}
public float getGetCombinedPowerOfAllStatsOfType(TileType t){
float total=1;
for(Stat s: this.stats)
if(s.getFirstTileType().equals(t)){
total*=s.getValue();
}
return total;
}
public boolean hasStat(int x, int y){
for(Stat s: this.stats){
if(s.containts(x, y))
return true;
}
return false;
}
public void rmStat(int x, int y){
Stat torm = null;
for(Stat s: this.stats){
if(s.containts(x, y))
torm=s;
}
if(torm!=null)
stats.remove(torm);
}
public void addStat(Stat s){
stats.add(s);
updatePos();
}
public void removeStatsThahHave(int x, int y) {
ArrayList<Stat> torm = new ArrayList<>();
for(Stat s: stats){
if(s.containts(x, y)){
torm.add(s);
}
}
for(Stat s: torm)
stats.remove(s);
}
}
<file_sep>/README.md
MineTD
======
Intro to computer scines project. LibGDX game.
--------------------
**Dependencies:**
* LibGDX
--------------------
**note to self:**
* brows this site: http://code.google.com/p/libgdx/wiki/Introduction
hej
<file_sep>/src/kth/pintjukarlsson/minetd/Enemy.java
package kth.pintjukarlsson.minetd;
import java.util.Random;
import kth.pintjukarlsson.graph.ImmutablePosition;
import kth.pintjukarlsson.minetd.listeners.MapInteractionListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g3d.model.keyframe.Keyframe;
import com.badlogic.gdx.maps.tiled.renderers.BatchTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;
public class Enemy extends Entity {
private float hp;
private int maxhp;
private int speed;
private AssetManager assetManager;
private ImmutablePosition[] path;
private int nextGoal = 0;
private Animation walk;
private Animation explode;
private Texture walkcyle;
private Texture explodetiles;
private boolean facesLeft = true;
private float internalTime = 0;
private float explodeTimer = 0;
private boolean playAnimation = false;
private boolean isDead = false;
private static Random rand = new Random(5454);
boolean findclosestPoint = true;
/**
* Creates a new enemy with full hitpoints at position x, y.
*
*/
public Enemy(int x, int y, int maxhp, int speed, MineTD g,
ImmutablePosition[] path) {
super(x, y, g);
this.maxhp = maxhp;
hp = maxhp;
this.speed = speed;
this.path = path;
}
// Health setters/getters and alive check
/**
* Decrease the enemy's hitpoints by x. (x > 0)
*/
public void damage(int x) {
if (x > 0)
hp -= x;
}
/**
* Increase the enemy's hitpoints by x. (x > 0) Cannot increase past max
* amount.
*/
public void heal(int x) {
if (x > 0)
hp += x;
if (hp > maxhp)
hp = maxhp;
}
/**
* Set hitpoints to x.
*/
public void setHealth(int x) {
hp = x;
}
/**
* Set maximum hitpoints to x.
*/
public void setMaxHealth(int x) {
maxhp = x;
}
/**
* Returns the current number of hitpoints.
*/
public int getHealth() {
return hp;
}
/**
* Returns the maximum number of hitpoints.
*/
public int getMaxHealth() {
return maxhp;
}
public boolean isDead() {
return isDead;
}
public void takeDamage(float damage) {
hp-=damage;
if(hp<0){
playAnimation = true;
}
}
// Speed setters/getters
/**
* Sets the movement speed of the unit.
*/
public void setSpeed(int x) {
speed = x;
}
/**
* Returns the enemy's movement speed.
*/
public int getSpeed() {
return speed;
}
// Update and draw methods
/**
* {@inheritDoc Entity}
*/
@Override
public void Update() {
if( findclosestPoint){
findclosestPoint =false;
float dis= 1000000;
int closest = 0;
for(int i=0; i<path.length; i++){
if(dis>(path[i].manhatanDistance(
new ImmutablePosition((int)this.getPos().x,
(int)this.getPos().y))))
{
dis = (path[i].manhatanDistance(
new ImmutablePosition((int)this.getPos().x,
(int)this.getPos().y)));
closest = i;
}
}
this.nextGoal = closest;
}
Vector2 nextTarget = new Vector2((float) path[nextGoal].getX(),
(float) path[nextGoal].getY());
Vector2 dir = new Vector2(nextTarget);
dir.sub(this.getPos());
dir.nor();
dir.scl(speed * Gdx.graphics.getDeltaTime());
if (dir.x < 0)
facesLeft = true;
else
facesLeft = false;
this.translate(dir);
if (nextTarget.epsilonEquals(getPos(), 0.1f)) {
if ((nextGoal + 1) < path.length) {
nextGoal++;
}
}
}
/**
* {@inheritDoc Entity}
*/
@Override
public void Draw(SpriteBatch batch){
if(walkcyle==null)
init();
internalTime+=Gdx.graphics.getDeltaTime();
TextureRegion frame = walk.getKeyFrame(internalTime);
if(!playAnimation){
if(facesLeft) {
batch.draw(frame, getPos().x, getPos().y, 1, 1);
} else {
batch.draw(frame, getPos().x+1, getPos().y, -1, 1);
}
}
if(playAnimation){
explodeTimer+=Gdx.graphics.getDeltaTime();
frame = explode.getKeyFrame(explodeTimer);
batch.draw(frame, getPos().x, getPos().y, 0.5f, 0.5f, 1, 1, 5, 5, 0);
if( explode.getKeyFrameIndex(explodeTimer)==8){
playAnimation=false;
isDead=true;
}
}
}
private void init() {
assetManager = getGame().getAssetManager();
walkcyle = assetManager.get("data/pony.png", Texture.class);
TextureRegion[] regions = TextureRegion.split(walkcyle, 39, 34)[rand.nextInt(3)];
walk = new Animation(0.15f, regions[0], regions[1], regions[2],
regions[3]);
walk.setPlayMode(Animation.LOOP);
explodetiles = assetManager.get("data/exp.png", Texture.class);
TextureRegion[][] regionsExplosion = TextureRegion.split(explodetiles,
32, 32);
explode = new Animation(1 / 15f, regionsExplosion[0][0],
regionsExplosion[0][1], regionsExplosion[0][2],
regionsExplosion[1][0], regionsExplosion[1][1],
regionsExplosion[1][2], regionsExplosion[2][0],
regionsExplosion[2][1], regionsExplosion[2][2]);
explode.setPlayMode(Animation.LOOP);
ImmutablePosition[] p =getGame().getLevel().getPath(new ImmutablePosition((int)(getPos().x+0.5f), (int)(getPos().y+0.5f)),
getGame().getLevel().getFinish());
path = p==null?path:p.length<=0?path:p;
nextGoal = 0;
findclosestPoint = false;
this.getGame().getInput().setMapInteractionListener(new MapInteractionListener() {
@Override
public void onTileRM(int x, int y, TileType t) {
ImmutablePosition[] p =getGame().getLevel().getPath(new ImmutablePosition((int)(getPos().x+0.5f), (int)(getPos().y+0.5f)),
getGame().getLevel().getFinish());
path = p==null?path:p.length<=0?path:p;
nextGoal = 0;
findclosestPoint = false;
}
@Override
public void onTileAdded(int x, int y, TileType t) {
ImmutablePosition[] p =getGame().getLevel().getPath(new ImmutablePosition((int)(getPos().x+0.5f), (int)(getPos().y+0.5f)),
getGame().getLevel().getFinish());
path = p==null?path:p.length<=0?path:p;
nextGoal = 0;
//path = getGame().getLevel().getPathStartToFinish();
findclosestPoint = false;
}
});
}
} | f08fe57150f80c0098bda2cd7848752e4acaff2b | [
"Markdown",
"Java"
] | 9 | Java | pintjuk/MineTD | a98f7223ffca90648c290c850b78f189568f5e03 | d8749363f188f9cf4c291998204ad0058cdc4ec3 |
refs/heads/main | <file_sep>/**
* Possui a classes principal para a execuรงรฃo do programa.
*/
package br.com.fabrica.app;<file_sep># gestaoDeProducao
Controle de produรงรฃo de uma a fรกbrica de produtos alimentรญcios caseiros. Projeto desenvolvido utilizando a linguagem Java. A persistรชncia de dados รฉ feito a partir de arquivos de acesso aleatรณrio
<file_sep>package br.com.fabrica.modelo;
import br.com.fabrica.validacoes.Data;
/**
* Classe responsรกvel por armazenar os dados da produรงรฃo
* @author Rafaela
*
*/
public class Producao implements Comparable<Producao>{
private int codigo;
private Produto produto;
private Data data;
private float custoProducao;
/**
* Construtor default da classe Producao. Instancia um objeto producao atribuindo
* valores default ao seus atributos.
*/
public Producao() { }
/**
* Construtor sobrecarregado da classe <code>Producao</code>. Instancia um objeto producao atribuindo
* valores passado como parรขmetro.
*
* @param produto -<code>Produto</code> : dados do produto a serem usados na produรงรฃo como o nome do produto
* a quantidade e preรงo
* @param data - <code>String</code> : Data da produรงรฃo do produto.
* @param custoProducao <code>float</code> : Custo da produรงรฃo de determinado produto.
*/
public Producao(Produto produto, Data data, float custoProducao) {
this.produto = produto;
this.data = data;
this.custoProducao = custoProducao;
}
/**
* Obtรฉm um objeto produto com os dados do produto que serรก produzido.
* @return <code>int</code> : Um objeto produto a ser produzido.
*/
public Produto getProduto() {
return produto;
}
/**
* Recebe um parรขmetro com os dados de determinado produto a ser produzido e atribui a variรกvel
* produto da classe Producao.
* @param produto - <code>Produto</code> : valor referente ao produto que serรก produzido.
*/
public void setProduto(Produto produto) {
this.produto = produto;
}
/**
* Obtรฉm a data da produรงรฃo de um produto.
* @return <code>String</code> : String referente a data de uma produรงรฃo.
*/
public Data getData() {
return data;
}
/**
* Atribui ao objeto da classe a string referente a data da produรงรฃo de um produto.
* @param data - <code>String</code> : string referente a data de uma produรงรฃo.
*/
public void setData(Data data) {
this.data = data;
}
/**
* Obtรฉm o cรณdigo de identificaรงรฃo de uma produรงรฃo.
* @return <code>int</code> : cรณdigo de identificaรงรฃo da produรงรฃo de um produto
*/
public int getCodigo() {
return codigo;
}
/**
* Atribui ao objeto da classe um cรณdigo para identificaรงรฃo de uma produรงรฃo
* @param codigo - <code>int</code> : codigo referente a identificacao da produรงรฃo de um produto
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* Obtรฉm o custo da produรงรฃo de um produto.
* @return - <code>float</code> : valor referente ao custo da produรงรฃo de um produto.
*/
public float getCustoProducao() {
return custoProducao;
}
/**
* Atribui ao objeto da classe o valor referente ao custo de produรงรฃo de um produto.
* @param custoProducao - <code>float</code> : valor referente ao custo da produรงรฃo de um produto.
*/
public void setCustoProducao(float custoProducao) {
this.custoProducao = custoProducao;
}
/**
* Representaรงรฃo String dos atributos da classe Produรงรฃo
* @return <code>String</code> : string contendo os atributos da classe Producao.
*/
@Override
public String toString() {
return String.format("Codigo: %d, produto: %s, data: %s, custoProducao:%s",
getCodigo(), produto.getNome(), data, custoProducao);
}
/**
* Compara os nomes dos produtos de uma produรงรฃo
* @return int indicando se รฉ igual maior ou menor o resultado da comparaรงรฃo
*/
@Override
public int compareTo(Producao producao) {
return producao.produto.getNome().compareToIgnoreCase(producao.produto.getNome());
}
}
<file_sep>/**
* Possui classes que fornecem os serviรงos de validaรงรตes necessรกrios.
*/
package br.com.fabrica.validacoes;<file_sep>package br.com.fabrica.modelo;
/**
* Classe responsรกvel por armazenar os dados do orรงamento
* @author Rafaela
*
*/
public class Orcamento {
private int codigo;
private String mes;
private float despesaTotal;
private int quantidadeVendas;
private float valorVendas;
/**
* Construtor default. Instancia um objeto da classe Orcamento
* atribuindo valores default aos atributos da mesma.
*/
public Orcamento() {
}
/**
* Construtor sobrecarregado. Instancia um objeto da classe Orcamento com os valores
* recebidos como parรขmetro.
* @param mes - <code>String</code> : Perรญodo a ser pedido o orรงamento
* @param despesaTotal - <code>float</code> : valor com todas as despesas referentes ao perรญodo
* do orรงamento
* @param quantidadeVendas - <code>int</code> : valor referente ao nรบmero de vendas referentes aquele
* perรญodo.
* @param valorVendas - <code>float</code> : valor referente ao dinheiro arrecadado com
* as vendas.
*/
public Orcamento(String mes, float despesaTotal, int quantidadeVendas, float valorVendas) {
this.mes = mes;
this.despesaTotal = despesaTotal;
this.quantidadeVendas = quantidadeVendas;
this.valorVendas = valorVendas;
}
/**
* Obtรฉm o mรชs a que se pretende fazer o orรงamento.
* @return <code>String</code> : Contรฉm o mรชs do orรงamento requerido.
*/
public String getMes() {
return mes;
}
/**
* Atribui ao objeto da classe o mรชs a que se pretende fazer o orรงamento.
* @param mes - <code>String</code> : valor referente ao mรชs do orรงamento.
*/
public void setMes(String mes) {
this.mes = mes;
}
/**
* Obtรฉm a despesa total referente ao mรชs de orรงamento.
* @return <code>float</code> : valor referente ao total das despesas de determinado mรชs de
* orรงamento.
*/
public float getDespesaTotal() {
return despesaTotal;
}
/**
* Atribui ao objeto da classe Orcamento o valor das despesas totais referentes ao mรชs de orรงamento
* @param despesaTotal - <code>float</code> : valor total das despesas de determinado mรชs
*/
public void setDespesaTotal(float despesaTotal) {
this.despesaTotal = despesaTotal;
}
/**
*Obtรฉm o valor da quantidade de vendas referentes a determinado mรชs.
* @return <code>int</code> : valor do nรบmero de vendas efetivadas em determinado mรชs.
*/
public int getQuantidadeVendas() {
return quantidadeVendas;
}
/**
* Atribui a classe Orcamento o nรบmero de vendas obtidas em determinado mรชs.
* @param quantidadeVendas valor referente ao nรบmero de vendas em um mรชs.
*/
public void setQuantidadeVendas(int quantidadeVendas) {
this.quantidadeVendas = quantidadeVendas;
}
/**
* Obtรฉm o valor em dinheiro das vendas obtidas em determinado mรชs.
* @return <code>float</code> : valor obtido com as vendas em um mรชs.
*/
public float getValorVendas() {
return valorVendas;
}
/**
* Atribui a classe Orcamento o valor total das vendas em um mรชs.
* @param valorVendas valor referente as vendas de determinado mรชs.
*/
public void setValorVendas(float valorVendas) {
this.valorVendas = valorVendas;
}
/**
* Obtรฉm o cรณdigo referente ao cรณdigo de determinado orรงamento em um mรชs.
* @return <code>int</code> : valor referente ao cรณdigo para identificaรงรฃo de um orรงamento.
*/
public int getCodigo() {
return codigo;
}
/**
* Atribui a classe Orcamento um codigo para identificar um orcamento em um mรชs.
* @param codigo - <code>int</code> : valor de cรณdigo para identificar um orcamento.
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* Representaรงรฃo String dos atributos da classe Orcamento.
* @return <code>String</code> : Uma String contendo os atributos da classe Orcamento.
*/
@Override
public String toString() {
return String.format("Codigo: %d, mes: %s, despesaTotal: %.2f, quantidadeVendas: %.2f,"
+ " valorVendas: %.2f", codigo, mes, despesaTotal, quantidadeVendas, valorVendas);
}
}
<file_sep>package br.com.fabrica.arquivos;
import static br.com.fabrica.constantes.Constantes.ARQ_VENDA_PRODUTO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import br.com.fabrica.modelo.Produto;
import br.com.fabrica.modelo.Venda;
/**
* Esta classe fornece uma implementaรงรฃo para as operaรงรตes que permitem manipular um arquivo de acesso
* aleatรณrio para ler e escrever objetos da classe <code>Venda</code>.
* @author <NAME> e Rafaela
*
*/
public class ArquivoVendaProduto extends BinaryFile {
/**
* Obtรฉm o tamanho do registro que รฉ de bytes, pois sรฃo:
* 4 bytes do cรณdigo da venda.
*100 bytes para o nome do produto vendido.
*4 bytes para a quantidade desse produto vendido.
*4 bytes para o preรงo unitรกrio do produto.
*4 bytes para o valor total de cada item da venda
* @return um <code>int</code> com o tamanho, em bytes, do registro.
*/
@Override
public int recordSize() {
return 116;
}
/**
* Escreve o objeto como um registro do arquivo.
*
* @param objeto um <code>Object</code> que serรก armazenado no arquivo.
*
* @throws IOException se ocorrer um erro de E/S;
* @throws ClassCastException se o tipo do objeto a ser escrito no arquivo nรฃo for da classe
* <code>Venda</code>.
*/
@Override
public void writeObject(Object objeto) throws IOException {
Produto produto = new Produto();
if(objeto instanceof Produto)
produto = (Produto) objeto;
else
throw new ClassCastException();
randomAccessFile.writeInt(produto.getCodigo());
randomAccessFile.writeChars(setStringLength(produto.getNome(), 50));
randomAccessFile.writeInt(produto.getQuantidade());
randomAccessFile.writeFloat(produto.getPrecoFabricacao());
randomAccessFile.writeFloat(produto.getPrecoVenda());
}
// Versรฃo sobrecarregada (overload) de writeObject.
public void writeObject(Venda venda) throws IOException {
Object object = venda;
writeObject(object);
}
/**
* Lรช um dado do arquivo de produtos vendidos.
*
* @return Object Retorna um objeto contendo os seus produtos vendidos.
*/
@Override
public Object readObject() throws IOException {
Produto produto = new Produto();
produto.setCodigo(randomAccessFile.readInt());
produto.setNome(readString(50));
produto.setQuantidade(randomAccessFile.readInt());
produto.setPrecoFabricacao(randomAccessFile.readFloat());
produto.setPrecoVenda(randomAccessFile.readFloat());
return produto;
}
/***
* Obtรฉm o cรณdigo sequencial das vendas gravado no arquivo de vendas
* @return retorna o cรณdigo sequencial para o prรณximo dado de registros das vendas.
*/
public int obtemCodigoVenda() {
try {
openFile(ARQ_VENDA_PRODUTO);
if(recordQuantity() == 0)
return 1;
else {
return (int) (recordQuantity() + 1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return 0;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
/**
* Grava os produtos que foram vendidos em determinada venda
* @param venda <code>Venda</code> venda a ser registrada.
* @return Retorna True ou False indicando se a gravaรงรฃo obteve sucesso ou falha.
*/
public boolean gravaProdutosVendidos(Venda venda) {
try {
openFile(ARQ_VENDA_PRODUTO);
setFilePointer(recordQuantity());
for(Produto produto : venda.getProdutos())
writeObject(produto);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Obtรฉm os produtos que foram vendidos.
* @param vendas Lista que contรฉm os produtos que foram vendidos
* @return os produtos vendidos de uma determinada venda.
*/
public List<Produto> produtosVendidos(List<Venda> vendas){
List<Produto> produtosVendidos = new ArrayList<Produto>();
try {
for (Venda venda : vendas) {
openFile(ARQ_VENDA_PRODUTO);
setFilePointer(0);
for (int i = 0; i < recordQuantity(); i++) {
Produto produto = (Produto) readObject();
if(venda.getCodigo() == produto.getCodigo())
produtosVendidos.add(produto);
}
closeFile();
}
return produtosVendidos;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
<file_sep>package br.com.fabrica.gerencia.ig;
import static br.com.fabrica.constantes.Constantes.VALOR_DEFAULT_CB_ORCAMENTO;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import br.com.fabrica.gerencia.modelo.GerenciaOrcamento;
import br.com.fabrica.gui.IgOrcamento;
/**
* Classe responsรกvel por gerenciar as funรงรตes da classe <code>IgOrcamento</code>
* @see IgOrcamento
* @author Rafaela
*
*/
public class GerenciaIgOrcamento {
/**
* Obtรฉm as informaรงรตes referentes ao orรงamento.
* @param comboBox lista de produtos cadastrados
* @param tfValor valor total dos insumos
* @param tfNumero nรบmero total de vendas
* @param tfValorTotal valor total das vendas
* @param tfSaldo saldo obtido no mes
*/
public static void obtemOrcamento(JComboBox<String> comboBox, JTextField tfValor, JTextField
tfNumero, JTextField tfValorTotal, JTextField tfSaldo) {
if(comboBox.getSelectedItem()== VALOR_DEFAULT_CB_ORCAMENTO)
return;
GerenciaOrcamento go = new GerenciaOrcamento();
float valor = go.somaDespedasMes((String) comboBox.getSelectedItem());
tfValor.setText(valor + "");
float numero = go.obtemNumeroTotalDeVendas((String) comboBox.getSelectedItem());
tfNumero.setText(String.format("%.2f", numero));
float valorTotal = go.obtemValorTotalDeVendas((String) comboBox.getSelectedItem());
tfValorTotal.setText(valorTotal + "");
float saldo = go.saldo(valorTotal, valor);
tfSaldo.setText(saldo + "");
}
}
<file_sep>package br.com.fabrica.gui;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import br.com.fabrica.gerencia.ig.GerenciaIgProduto;
import br.com.fabrica.modelo.UnidadeMedida;
/**
* Classe responsavel por criar a tela de cadastro de Produtos.
* @author <NAME> Guilherme
*
*/
@SuppressWarnings("serial")
public class IgProdutos extends JFrame {
private JLabel lblNewLabel;
private JTextField tfNome;
private JSpinner spinner;
private JLabel lblMargemDeLucro;
private JLabel lblNewLabel_1;
private JLabel lblNome;
private JButton btnInsumo;
private JButton btnGravar;
private JButton btnCancelar;
private JFrame jf;
private JComboBox<String> comboBox;
/**
* Create the panel.
*/
public IgProdutos() {
getContentPane().setLayout(null);
jf = new JFrame();
jf.setAutoRequestFocus(false);
jf.getContentPane().setLayout(null);
jf.setTitle("Cadastro de Produtos");
// Define que o programa deve ser finalizado quando o usuรกrio clicar no botรฃo Fechar da janela.
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Define a janela como nรฃo redimensionรกvel.
jf.setResizable(false);
jf.setSize(525, 349);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
btnGravar = new JButton("Gravar");
jf.getContentPane().add(btnGravar);
btnGravar.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnGravar.setBounds(249, 268, 96, 25);
btnInsumo = new JButton("Cadastrar Insumo...");
jf.getContentPane().add(btnInsumo);
btnInsumo.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnInsumo.setBounds(298, 208, 164, 25);
btnCancelar = new JButton("Cancelar");
jf.getContentPane().add(btnCancelar);
btnCancelar.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnCancelar.setBounds(366, 268, 96, 25);
lblNome = new JLabel("Nome:");
jf.getContentPane().add(lblNome);
lblNome.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNome.setBounds(120, 67, 40, 16);
lblNewLabel_1 = new JLabel("Unidade:");
jf.getContentPane().add(lblNewLabel_1);
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNewLabel_1.setBounds(104, 113, 56, 16);
tfNome = new JTextField();
jf.getContentPane().add(tfNome);
tfNome.setBounds(177, 61, 285, 30);
tfNome.setColumns(10);
lblNewLabel = new JLabel("Produto");
jf.getContentPane().add(lblNewLabel);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel.setBounds(234, 25, 59, 19);
lblMargemDeLucro = new JLabel("Margem de lucro:");
jf.getContentPane().add(lblMargemDeLucro);
lblMargemDeLucro.setFont(new Font("Tahoma", Font.BOLD, 13));
lblMargemDeLucro.setBounds(47, 161, 113, 16);
spinner = new JSpinner();
jf.getContentPane().add(spinner);
spinner.setBounds(174, 155, 101, 30);
comboBox = new JComboBox<String>();
comboBox.setBounds(176, 107, 145, 30);
jf.getContentPane().add(comboBox);
for(UnidadeMedida um : UnidadeMedida.values()) {
comboBox.addItem(String.format("%s (%s)", um.getNome(),
um.getUnidade() ));
}
btnGravar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GerenciaIgProduto.cadastrarProdutos(tfNome, comboBox, spinner, jf);
tfNome.setText("");
comboBox.setSelectedIndex(0);
spinner.setValue(Integer.valueOf(0));
}
});
btnCancelar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jf.setVisible(false);
IgMenu igMenu = new IgMenu();
igMenu.getJf().setVisible(true);
}
});
btnInsumo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jf.setVisible(false);
IgInsumosProduto igInsumos = new IgInsumosProduto();
igInsumos.getJf().setVisible(true);
}
});
}
public JFrame getJf() {
return jf;
}
public void setJf(JFrame jf) {
this.jf = jf;
}
}
<file_sep>package br.com.fabrica.gerencia.modelo;
import static br.com.fabrica.validacoes.Data.transformaCalendarEmString;
import java.util.Calendar;
import java.util.List;
import br.com.fabrica.arquivos.ArquivoHistoricoPreco;
import br.com.fabrica.modelo.HistoricoPreco;
/**
* Classe responsรกvel por gerenciar o histรณrico de preรงos referente aos insumos
* e aos produtos.
* @see HistoricoPreco
* @author Rafaela
*
*/
public class GerenciaHistoricoPreco {
/**
* Insere o novo preรงo e a nova data no histรณrico de preรงo. A data a ser
* atribuida sempre serรก a data do dia.
* @param preco - <code>float</code> : novo preรงo a ser cadastrado.
* @param codigo - <code>int</code> : cรณdigo referente a informaรงรฃo que o dado pertence.
* @param arquivo - <code>String</code> : arquivo onde serรฃo salvos os dados.
* @return <code>true</code> caso consiga inserir. <code>false</code> caso nรฃo consiga.
*/
public boolean insereHistoricoPreco(float preco, int codigo, String arquivo) {
ArquivoHistoricoPreco ahp = new ArquivoHistoricoPreco();
Calendar hoje = Calendar.getInstance();
String data = transformaCalendarEmString(hoje);
HistoricoPreco hp = new HistoricoPreco(preco, data);
hp.setCodigoReferenciaDeDado(codigo);
boolean cadastrado = ahp.escreveHistoricoNoArquivo(hp, arquivo);
if(cadastrado)
return true;
return false;
}
/**
* Obtรฉm o preรงo e a data mais antiga.
* @param codigo <code>int</code> cรณdigo Referรชncia relativo ao dado que deseja obter o preรงo
* @return <code>HistoricoPreco</code> : preรงo e data mais recente que foram cadastrados.
*/
public HistoricoPreco obtemPrecoAntigo(int codigo) {
ArquivoHistoricoPreco ahp = new ArquivoHistoricoPreco();
if(ahp.obtemHistorico(codigo).size() > 0) {
HistoricoPreco hp = ahp.obtemHistorico(codigo).get(0);
return hp;
}
return null;
}
/**
* Obtรฉm o preรงo mais recente.
* @param historicoPrecos - <code>List</code> : lista que contรฉm os preรงos
* @return - <code>float</code> :preรงo mais recente que foi cadastrado.
*/
public float obtemPrecoMaisRecente(List<HistoricoPreco> historicoPrecos) {
return historicoPrecos.get(historicoPrecos.size()).getPreco();
}
}
<file_sep>package br.com.fabrica.arquivos;
import static br.com.fabrica.constantes.Constantes.ARQ_INSUMO_PRODUTO;
import static br.com.fabrica.constantes.Constantes.ARQ_PRECO_INSUMO;
import static br.com.fabrica.constantes.Constantes.ARQ_PRODUTO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import br.com.fabrica.modelo.HistoricoPreco;
import br.com.fabrica.modelo.Insumo;
/**
* Esta classe fornece uma implementaรงรฃo para as operaรงรตes que permitem manipular um arquivo de acesso
* aleatรณrio para ler e escrever objetos da classe <code>Insumo</code>.
* @author <NAME> e Rafaela.
*
*/
public class ArquivoInsumoProduto extends BinaryFile{
/**
* Obtรฉm o tamanho do registro que รฉ de 112 bytes, pois sรฃo:
*
* 100 bytes do nome do insumo com 50 caracteres (2 bytes de cada carรกcter UNICODE);
* 4 bytes do cรณdigo do insumo;
* 4 bytes do cรณdigo do produto a que ele pertence
* 4 bytes da quantidade a ser usada do insumo no produto a que ele pertence.
* @return um <code>int</code> com o tamanho, em bytes, do registro.
*/
@Override
public int recordSize() {
return 112;
}
/**
* Escreve o objeto como um registro do arquivo.
*
* @param objeto um <code>Object</code> que serรก armazenado no arquivo.
*
* @throws IOException se ocorrer um erro de E/S;
* @throws ClassCastException se o tipo do objeto a ser escrito no arquivo nรฃo for da classe
* <code>Insumo</code>.
*/
@Override
public void writeObject(Object objeto) throws IOException {
Insumo insumo = new Insumo();
if(objeto instanceof Insumo)
insumo = (Insumo) objeto;
else
throw new ClassCastException();
randomAccessFile.writeInt(insumo.getCodigo());
randomAccessFile.writeInt(insumo.getCodigoProduto());
randomAccessFile.writeChars(setStringLength(insumo.getNome(), 50));
randomAccessFile.writeFloat(insumo.getQuantidade());
}
/**
* Escreve um objeto insumo no arquivo.
* @param insumo objeto insumo que contรฉm as informaรงรตes de um insumo
* @throws IOException Erro relacionada a entrada e saรญda de dados.
*/
public void writeObject(Insumo insumo) throws IOException {
Object object = insumo;
writeObject(object);
}
/**
* Lรช o objeto como um registro do arquivo.
*
* @return um <code>Insumo</code> com os atributos do objeto lido do arquivo.
*
* @throws IOException se ocorrer um erro de E/S.
**/
@Override
public Object readObject() throws IOException {
Insumo insumo = new Insumo();
insumo.setCodigo(randomAccessFile.readInt());
insumo.setCodigoProduto(randomAccessFile.readInt());
insumo.setNome(readString(50));
insumo.setQuantidade(randomAccessFile.readFloat());
return insumo;
}
/**
* Recebe um Objeto com dados de um insumo referente a classe {@link Insumo} a serem gravados
* no arquivo de Insumos.
* @param insumo Um objeto insumo a ser gravado no arquivo.
* @return Retorna True ou False indicando se a gravaรงรฃo obteve sucesso ou falha.
*/
public boolean escreveInsumoNoArquivo(Insumo insumo) {
try {
openFile(ARQ_INSUMO_PRODUTO);
setFilePointer(recordQuantity());
writeObject(insumo);
ArquivoHistoricoPreco ahp = new ArquivoHistoricoPreco();
for(HistoricoPreco hp : insumo.getHistorico())
ahp.escreveHistoricoNoArquivo(hp, ARQ_PRECO_INSUMO);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Recebe uma lista de insumos de determinado produto e escreve os registros
* no arquivo de insumos.
* @param insumos Uma lista com dados referente a classe {@link Insumo} para serem gravados
* no arquivo de insumos.
* @return Retorna True ou False indicando se a gravaรงรฃo teve sucesso ou falha.
*/
public boolean escreveInsumosNoArquivo(List<Insumo> insumos) {
try {
ArquivoHistoricoPreco ahp = new ArquivoHistoricoPreco();
openFile(ARQ_INSUMO_PRODUTO);
setFilePointer(recordQuantity());
for(Insumo insumo : insumos) {
writeObject(insumo);
for(HistoricoPreco hp : insumo.getHistorico())
ahp.escreveHistoricoNoArquivo(hp, ARQ_PRECO_INSUMO);
}
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/***
* Obtรฉm o cรณdigo sequencial dos produtos a partir do nรบmero de registro no arquivo de produtos
* caso esteja vazio este serรก o primeiro produto a ser gravado no arquivo.
* @return retorna o cรณdigo sequencial para o prรณximo dado do registro de produtos.
*/
public int obtemCodigoInsumo() {
int codigo = 0;
try {
openFile(ARQ_PRODUTO);
if(recordQuantity() == 0)
codigo = 1;
else {
codigo = (int) (recordQuantity() + 1);
}
closeFile();
return codigo;
} catch (FileNotFoundException e) {
e.printStackTrace();
return 0;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
/**
* Obtรฉm os insumos que estรฃo cadastrados.
* @return <code>List</code> lista de insumos cadastrados
*/
public List<Insumo> leInsumosNoArquivo() {
List<Insumo> listaInsumos = new ArrayList<>();
try {
openFile(ARQ_INSUMO_PRODUTO);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
Insumo insumo = (Insumo) readObject();
listaInsumos.add(insumo);
}
closeFile();
return listaInsumos;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Altera preรงo de um determinado insumo
* @param codigoProduto <code>int</code> cรณdigo do produto para alteraรงรฃo do insumo
* @param codigoInsumo <code>int</code> codigo do insumo a ser alterado.
* @param novoPreco <code>float</code> preรงo a ser atualizado.
* @return <code>true</code> caso consiga alterar. <code>false</code> caso nรฃo consiga.
*/
public boolean alteraInsumo(int codigoProduto, int codigoInsumo, float novoPreco) {
try {
openFile(ARQ_INSUMO_PRODUTO);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
Insumo insumo = (Insumo) readObject();
if(insumo.getCodigoProduto() == codigoProduto && insumo.getCodigo() == codigoInsumo) {
insumo.setPrecoUnitario(novoPreco);
escreveInsumosNoArquivoPorPosicao(insumo, i);
break;
}
}
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Escreve um insumo em uma determinada posiรงรฃo.
* @param insumo <code>Insumo</code> insumo a ser cadastrado.
* @param posicao <code>int</code> posiรงรฃo que serรก escrito o insumo
* @return Retorna True ou False indicando se a gravaรงรฃo teve sucesso ou falha.
*/
public boolean escreveInsumosNoArquivoPorPosicao(Insumo insumo, int posicao) {
try {
openFile(ARQ_INSUMO_PRODUTO);
setFilePointer(recordQuantity());
writeObject(insumo);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Obtรฉm os insumos referentes a um determinado produto.
* @param codigo <code>int</code> cรณdigo referente ao produto
* @return <code>List</code> lista de insumos do produto
*/
public List<Insumo> obtemInsumosDeUmProduto(int codigo){
List<Insumo> listaDeInsumosDeUmProduto = new ArrayList<Insumo>();
List<Insumo> listaDeInsumos = leInsumosNoArquivo();
for (Insumo insumo : listaDeInsumos)
listaDeInsumosDeUmProduto.add(insumo);
return listaDeInsumosDeUmProduto;
}
}
<file_sep>package br.com.fabrica.arquivos;
import static br.com.fabrica.constantes.Constantes.ARQ_HISTORICO_INSUMO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import br.com.fabrica.modelo.HistoricoPreco;
/**
* Esta classe fornece uma implementaรงรฃo para as operaรงรตes que permitem manipular
* um arquivo de acesso aleatรณrio para ler e escrever objetos da classe
* <code>HistoricoPreco</code>.
* @author GuilhermeMagnus
*
*/
public class ArquivoHistoricoPreco extends BinaryFile{
/**
* Obtรฉm o tamanho do registro que รฉ de 32 bytes, pois sรฃo:
*
* 20 bytes da data de alteraรงรฃo do preรงo do produto ou insumo (2 bytes de cada carรกcter UNICODE);
* 4 bytes do cรณdigo do insumo ou produto;
* 4 bytes do cรณdigo de cada objeto criado para o Histรณrico de preรงo
* 4 bytes do preรงo do insumo ou produto
* @return um <code>int</code> com o tamanho, em bytes, do registro.
*/
@Override
public int recordSize() {
return 32;
}
/**
* Escreve o objeto como um registro do arquivo.
*
* @param objeto um <code>Object</code> que serรก armazenado no arquivo.
*
* @throws IOException se ocorrer um erro de E/S;
* @throws ClassCastException se o tipo do objeto a ser escrito no arquivo nรฃo for da classe
* <code>HistoricoPreco</code>.
*/
@Override
public void writeObject(Object objeto) throws IOException {
HistoricoPreco historicoPreco = new HistoricoPreco();
if(objeto instanceof HistoricoPreco)
historicoPreco = (HistoricoPreco) objeto;
else
throw new ClassCastException();
randomAccessFile.writeInt(obtemCodigoHistorico());
randomAccessFile.writeInt(historicoPreco.getCodigoReferenciaDeDado());
randomAccessFile.writeFloat(historicoPreco.getPreco());
randomAccessFile.writeChars(setStringLength(historicoPreco.getData(), 10));
}
/**
* escreve um histรณrico de preรงo no arquivo
* @param historicoPreco Um objeto que contรฉm um histรณrico de preรงo
* @throws IOException
*/
private void writeObject(HistoricoPreco historicoPreco) throws IOException {
Object object = historicoPreco;
writeObject(object);
}
/**
* Lรช um registro do arquivo historico de preรงos de um produto ou insumo
* e adiciona no objeto HistoricoPreco para ser retornado.
* @return Retorna um objeto referente a classe {@link HistoricoPreco} com dados do preรงo
* de determinado produto ou insumo.
*/
@Override
public Object readObject() throws IOException {
HistoricoPreco historicoPreco = new HistoricoPreco();
historicoPreco.setCodigo(randomAccessFile.readInt());
historicoPreco.setCodigoReferenciaDeDado(randomAccessFile.readInt());
historicoPreco.setPreco(randomAccessFile.readFloat());
historicoPreco.setData(readString(10));
return historicoPreco;
}
/***
* Obtรฉm o cรณdigo sequencial do histรณrico de insumos
* @return retorna o cรณdigo sequencial para o prรณximo dado de histรณrico
*/
public int obtemCodigoHistorico() {
int codigo = 0;
try {
if(recordQuantity() == 0)
codigo = 1;
else {
codigo = (int) (recordQuantity() + 1);
}
return codigo;
} catch (FileNotFoundException e) {
e.printStackTrace();
return 0;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
/**
* Escreve um <code>HistoricoPreco</code> no arquivo referente aos preรงos;
* @param hp preรงo a ser salvo
* @param arquivo arquivo onde serรฃo salvas as informaรงรตes
* @return <code>true</code> caso consiga escrever no arquivo. <code>false</code>
* caso nรฃo consiga escrever no arquivo.
*/
public boolean escreveHistoricoNoArquivo(HistoricoPreco hp, String arquivo) {
try {
openFile(arquivo);
setFilePointer(recordQuantity());
writeObject(hp);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Obtรฉm os histรณricos de preรงos que foram salvos.
* @param codigo <code>int</code> cรณdigo de referencia dos dados a serem obtidos
* @return <code>List</code> lista contendo os preรงos;
*/
public List<HistoricoPreco> obtemHistorico(int codigo) {
HistoricoPreco hp = new HistoricoPreco();
List<HistoricoPreco> hpList = new ArrayList<HistoricoPreco>();
try {
openFile(ARQ_HISTORICO_INSUMO);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
hp = (HistoricoPreco) readObject();
if(hp.getCodigoReferenciaDeDado() != codigo)
continue;
hpList.add(hp);
}
closeFile();
return hpList;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
<file_sep>package br.com.fabrica.arquivos;
import java.io.*;
/**
* Fornece operaรงรตes para um arquivo binรกrio usando os serviรงos de um arquivo com acesso aleatรณrio.
* As operaรงรตes definidas por esta classse sรฃo independentes da estrutura de um arquivo
* especรญfico. Portanto, os serviรงos desta classe abstrata podem ser utilizados por qualquer
* classe que queira implementar a estrutura (atributos) e os serviรงos (mรฉtodos) de um arquivo
* com acesso aleatรณrio.
*
* <p><b>ATENรรO:</b> A estrutura do arquivo em relaรงรฃo a quantidade e os tipos de dados do registro
* รฉ definida pelo cliente da classe. No entanto, exige-se que o tamanho dos registros seja fixo.
* Esta restriรงรฃo รฉ fundamental para o correto funcionamento dos mรฉtodos da classe <code>BinaryFile</code>.</p>
*
* @author Prof. <NAME>
*
* @version 0.3
*/
public abstract class BinaryFile {
private String fileName;
/**
* Arquivo binรกrio de acesso aleatรณrio para escrita e leitura de dados.
*/
protected RandomAccessFile randomAccessFile;
/**
* Calcula o tamanho em bytes do arquivo.
*
* @return um <code>long</code> com o tamanho, em bytes, do arquivo.
*
* @throws IOException se ocorrer um erro ao tentar acessar o arquivo.
**/
public long fileSize() throws IOException {
// Obtรฉm o tamanho, em bytes, do arquivo em disco.
return randomAccessFile.length();
}
/**
* Abre o arquivo para a escrita e a leitura de dados. Se o arquivo nรฃo existir ele serรก criado.
*
* @param fileName um <code>String</code> com o nome do arquivo em disco.
*
* @throws FileNotFoundException se o arquivo nรฃo puder ser aberto ou criado para entrada e saรญda de dados.
**/
public void openFile(String fileName) throws FileNotFoundException {
// Obtรฉm o nome do arquivo.
this.fileName = fileName;
// Abre o arquivo para leitura e gravaรงรฃo.
randomAccessFile = new RandomAccessFile(fileName, "rw");
}
/**
* Fecha o arquivo.
*
* @throws IOException se ocorrer um erro ao tentar fechar o arquivo.
**/
public void closeFile() throws IOException {
if (randomAccessFile != null) randomAccessFile.close();
}
/**
* Ajusta o tamanho da <i>string</i> para um nรบmero fixo de caracteres.
*
* @param str <code>String</code> que terรก o tamanho ajustado para o valor especificado por <code>size</code>.
* @param size um <code>int</code> com o novo tamanho da string <i>str</i>.
*
* @return uma <code>String</code> com o conteรบdo especificado por <i>str</i> e tamanho definido por <i>size</i>.
**/
public String setStringLength(String str, int size) {
StringBuffer buffer = null;
// Cria uma nova string com os caracteres do argumento str.
if (str != null)
{ buffer = new StringBuffer(str);
// Configura o tamanho da nova string para o nรบmero de caracteres desejado.
buffer.setLength(size);
}
else // Cria uma nova string sem caracteres e com a quantidade especificada no argumento size.
buffer = new StringBuffer(size);
return buffer.toString();
}
/**
* Lรช uma <i>string</i> do arquivo com o nรบmero de caracteres definido por <code>size</code>.
*
* @param size quantidade de caracteres da <i>string</i>.
*
* @return a <i>string</i> lida do arquivo.
*
* @throws IOException se ocorrer um erro ao tentar ler do arquivo.
**/
public String readString(int size) throws IOException {
char str[] = new char[size];
// Lรช a string do arquivo, um carรกcter por vez.
for ( int count = 0; count < str.length; count++ )
str[count] = randomAccessFile.readChar();
return new String(str).replace('\0', ' ').trim();
}
/**
* Obtรฉm o nome do arquivo.
*
* @return um <code>String</code> com o nome do arquivo em disco.
**/
public String getFileName() {
return fileName;
}
/**
* Calcula a quantidade de registros do arquivo.
*
* @return um <code>long</code> com o nรบmero de registros do arquivo.
*
* @throws IOException se ocorrer um erro ao tentar obter o nรบmero de registros do arquivo.
**/
public long recordQuantity() throws IOException {
// Obtรฉm a quantidade de registros do arquivo dividindo o tamanho do arquivo pelo tamanho do registro.
return fileSize() / recordSize();
}
/**
* Posiciona o ponteiro do arquivo na posiรงรฃo especificada pelo nรบmero do registro. Considere o
* registro zero como o primeiro registro do arquivo.
*
* @param recordNumber nรบmero inteiro correspondente a um registro do arquivo.
*
* @throws IOException se ocorrer um erro de E/S como, por exempo, acessar um nรบmero do registro invรกlido.
**/
public void setFilePointer(long recordNumber) throws IOException {
/* Valida o nรบmero do registro e se invรกlido dispara a exceรงรฃo. Considera recordNumber como
* menor ou igual ao nรบmero total de registros do arquivo para permitir o mรฉtodo seek posicionar
* no fim do arquivo e possibilitar a inserรงรฃo de novos registros no arquivo.
*/
if (recordNumber >= 0 && recordNumber <= recordQuantity())
randomAccessFile.seek(recordNumber * recordSize());
else
throw new IOException(); // Nรบmero de registro invรกlido.
}
/**
* Exclui um registro do arquivo.
*
* @param recordNumber um nรบmero inteiro correspondente a um registro do arquivo.
* O primeiro registro รฉ de nรบmero zero (0).
*
* @throws IOException se ocorrer um erro de E/S como, por exempo, acessar um nรบmero do registro invรกlido.
**/
public void excludeFileRecord(int recordNumber) throws IOException {
// Posiciona o ponteiro do arquivo no รบltimo registro.
setFilePointer(recordQuantity() - 1);
// Verifica se o registro a ser excluรญdo nรฃo รฉ รบltimo.
if (recordNumber != recordQuantity() - 1) {
// Lรช os dados do objeto armazenado no รบltimo registro do arquivo.
Object objeto = readObject(); // Exemplo de polimorfismo na chamada de readObject.
// Posiciona no รญnicio do registro a ser excluรญdo.
setFilePointer(recordNumber);
// Escreve os dados do รบltimo registro no registro a ser excluรญdo.
writeObject(objeto); // Exemplo de polimorfismo na chamada de writeObject.
}
// Trunca o arquivo, ou seja, apaga o รบltimo registro. Exemplo de polimorfismo na chamada de recordSize.
randomAccessFile.setLength(fileSize() - recordSize());
}
/**
* Calcula o tamanho, em bytes, do registro composto por variรกveis membro do objeto.
*
* @return um <code>int</code> com o tamanho, em bytes, do registro.
*/
public abstract int recordSize();
/**
* Escreve o objeto como um registro do arquivo.
*
* @param objeto um <code>Object</code> que serรก armazenado no arquivo.
*
* @throws IOException se ocorrer um erro de E/S.
**/
public abstract void writeObject(Object objeto) throws IOException;
/**
* Lรช o objeto como um registro do arquivo.
*
* @return um <code>Object</code> com os atributos do objeto lido do arquivo.
*
* @throws IOException se ocorrer um erro de E/S.
**/
public abstract Object readObject() throws IOException;
} // class BinaryFile
<file_sep>package br.com.fabrica.arquivos;
import static br.com.fabrica.constantes.Constantes.ARQ_PRODUTO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import br.com.fabrica.modelo.Produto;
import br.com.fabrica.validacoes.Validacoes;
/**
* Esta classe fornece uma implementaรงรฃo para as operaรงรตes que permitem manipular um arquivo de acesso
* aleatรณrio para ler e escrever objetos da classe <code>Produto</code>.
* @author <NAME> e Rafaela.
*
*/
public class ArquivoProduto extends BinaryFile{
/**
* Obtรฉm o tamanho do registro que รฉ de 124 bytes, pois sรฃo:
* 4 bytes do cรณdigo do produto
*100 bytes do nome do Produto com 50 caracteres (2 bytes de cada carรกcter UNICODE)
*4 bytes para a unidade de medida(quilograma, grama, litro, mililitro)
*4 bytes para a margem de Lucro
*4 bytes para o preรงo da venda
*4 bytes da quantidade do produto
*4 bytes do tamanho da unidade
* @return um <code>int</code> com o tamanho, em bytes, do registro.
*/
@Override
public int recordSize() {
return 124;
}
/**
* Escreve o objeto como um registro do arquivo.
*
* @param objeto um <code>Object</code> que serรก armazenado no arquivo.
*
* @throws IOException se ocorrer um erro de E/S;
* @throws ClassCastException se o tipo do objeto a ser escrito no arquivo nรฃo for da classe
* <code>Produto</code>.
*/
@Override
public void writeObject(Object objeto) throws IOException {
Produto produto;
if(objeto instanceof Produto) {
produto = (Produto) objeto;
}
else
throw new ClassCastException();
randomAccessFile.writeInt(produto.getCodigo());
randomAccessFile.writeChars(setStringLength(produto.getNome(), 50));
randomAccessFile.writeChars(setStringLength(produto.getUnidadeMedida().getUnidade(), 2));
randomAccessFile.writeFloat(produto.getMargemLucro());
randomAccessFile.writeFloat(produto.getPrecoVenda());
randomAccessFile.writeInt(produto.getQuantidade());
randomAccessFile.writeFloat(produto.getTamanhoUnidade());
}
/**
* Escreve no arquivo os dados de um produto.
* @param produto objeto de onde serรฃo armazenadas as informaรงรตes.
* @throws IOException Erro relacionado a entrada e saรญda de dados.
*/
public void writeObject(Produto produto) throws IOException {
Object object = produto;
writeObject(object);
}
/**
* Lรช o objeto como um registro do arquivo.
*
* @return um <code>Produto</code> com os atributos do objeto lido do arquivo.
*
* @throws IOException se ocorrer um erro de E/S.
**/
@Override
public Object readObject() throws IOException {
Produto produto = new Produto();
produto.setCodigo(randomAccessFile.readInt());
produto.setNome(readString(50));
String tipoProduto = readString(2);
produto.setUnidadeMedida(Validacoes.verificaMedida(tipoProduto));
produto.setMargemLucro(randomAccessFile.readFloat());
produto.setPrecoVenda(randomAccessFile.readFloat());
produto.setQuantidade(randomAccessFile.readInt());
produto.setTamanhoUnidade(randomAccessFile.readFloat());
return produto;
}
/**
* Grava as informaรงรตes dos produtos referente a classe {@link Produto}
* no arquivo de acesso aleatรณrio dos produtos.
* @param produto Contรฉm as informaรงรตes de determinado produto que serรฃo gravadas no arquivo.
* @return Retorna true ou false indicando se foi possรญvel escrever no arquivo.
*/
public boolean escreveProdutoNoArquivo(Produto produto) {
try {
openFile(ARQ_PRODUTO);
setFilePointer(recordQuantity());
writeObject(produto);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Percorre o arquivo de produtos e lรช um dado gravado no arquivo
* indicado pela variรกvel indice. Caso encontre retorna um objeto da classe {@link Produto}
* com os dados obtidos ou em falha retorna null.
* @param indice Variรกvel que indica o registro a ser obtido do arquivo.
* @return Retorna um objeto contendo os dados obtidos ou null caso o registro seja invรกlido
*/
public Produto leProdutoNoArquivo(int indice) {
try {
openFile(ARQ_PRODUTO);
setFilePointer(indice);
Produto produto = (Produto) readObject();
closeFile();
return produto;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Percorre todo o arquivo de produtos adicionando cada registro a uma lista do tipo
* da classe {@link Produto} e a retorna.
*
* @return Retorna uma lista com todos os registros do arquivo de Produtos ou null caso
* o arquivo esteja vazio.
*/
public List<Produto> leProdutosNoArquivo() {
List<Produto> listaProdutos = new ArrayList<>();
try {
openFile(ARQ_PRODUTO);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
Produto produto = (Produto) readObject();
listaProdutos.add(produto);
}
closeFile();
return listaProdutos;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/***
* Obtรฉm o cรณdigo sequencial dos produtos a partir do nรบmero de registro no arquivo de produtos
* caso esteja vazio este serรก o primeiro produto a ser gravado no arquivo.
* @return retorna o cรณdigo sequencial para o prรณximo dado do registro de produtos.
*/
public int obtemCodigoProduto() {
int codigo = 0;
try {
openFile(ARQ_PRODUTO);
if(recordQuantity() == 0)
codigo = 1;
else {
codigo = (int) (recordQuantity() + 1);
}
closeFile();
return codigo;
} catch (FileNotFoundException e) {
e.printStackTrace();
return 0;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
/**
* Escreve um produto em uma determinada posiรงรฃo.
* @param produto <code>Produto</code> produto a ser cadastrado.
* @param posicao <code>int</code> posiรงรฃo que serรก escrito o produto
* @return Retorna True ou False indicando se a gravaรงรฃo teve sucesso ou falha.
*/
public boolean escreveProdutoNoArquivoPorPosicao(Produto produto, int posicao) {
try {
openFile(ARQ_PRODUTO);
setFilePointer(posicao);
System.out.println(produto);
writeObject(produto);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* Altera as informaรงรตes de um produto cadastrada.
* @param prod <code>Produto</code> produto a ser alterada.
* @return <code>Produto</code> produรงรฃo alterada.
*/
public Produto alteraProduto(Produto prod) {
Produto produto = null;
try {
openFile(ARQ_PRODUTO);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
produto = (Produto) readObject();
if(produto.getCodigo() == prod.getCodigo()) {
produto.setTamanhoUnidade(prod.getTamanhoUnidade());
escreveProdutoNoArquivoPorPosicao(produto, i);
break;
}
}
closeFile();
return produto;
} catch (FileNotFoundException e) {
e.printStackTrace();
return produto;
} catch (IOException e) {
e.printStackTrace();
return produto;
}
}
/**
* Obtรฉm o produto cadastrado.
* @param codigoProduto <code>int</code> cรณdigo referente ao produto
* @return <code>Produto</code> dados do produto procurado
*/
public Produto obtemProduto(int codigoProduto) {
Produto produto = null;
try {
openFile(ARQ_PRODUTO);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
produto = (Produto) readObject();
if(produto.getCodigo() == codigoProduto) {
break;
}
}
closeFile();
return produto;
} catch (FileNotFoundException e) {
e.printStackTrace();
return produto;
} catch (IOException e) {
e.printStackTrace();
return produto;
}
}
}<file_sep>package br.com.fabrica.gui;
import static javax.swing.JOptionPane.ERROR_MESSAGE;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import static javax.swing.JOptionPane.showMessageDialog;
import java.awt.Component;
public class EntradaESaida {
/**
* Exibe uma mensagem informativa em uma caixa de diรกlogo com o texto da
* barra de tรญtulo definido em titulo.
* @param component Componemte em que a caixa de diรกlogo vai pertencer
* @param mensagem Mensagem que serรก fornecida ao usuรกrio
* @param titulo Titulo da janela de diรกlogo
*/
public static void msgInfo(Component component, String mensagem, String titulo) {
showMessageDialog(component, mensagem, titulo, INFORMATION_MESSAGE);
}
/**
* Exibe um componente em uma caixa de diรกlogo com o texto da barra de tรญtulo
* definido em titulo.
* @param componente Componemte em que a caixa de diรกlogo vai pertencer
* @param titulo Titulo da janela de diรกlogo
*/
public static void msgInfo(Object componente, String titulo) {
showMessageDialog(null, componente, titulo, INFORMATION_MESSAGE);
}
/**
* Exibe uma mensagem de erro em uma caixa de diรกlogo com o texto da barra de
* tรญtulo definido em titulo.
* @param component Componemte em que a caixa de diรกlogo vai pertencer
* @param mensagem Mensagem que serรก fornecida ao usuรกrio
* @param titulo Titulo da janela de diรกlogo
*/
public static void msgErro(Component component, String mensagem, String titulo) {
showMessageDialog(component, mensagem, titulo, ERROR_MESSAGE);
}
} // class EntradaESaida<file_sep>package br.com.fabrica.modelo;
/**
* Enumeraรงรฃo que determina os meses do ano, o nรบmero referente a ele e quantos dias
* eles possuem.
* @author Rafaela
*
*/
public enum MesesAno {
JANEIRO("Janeiro", 1, 31),
FEVEREIRO("Fevereiro", 2, 28),
MARรO("Marรงo", 3, 31),
ABRIL("Abril", 4, 30),
MAIO("Maio", 5, 31),
JUNHO("Junho", 6, 30),
JULHO("Julho", 7, 31),
AGOSTO("Agosto", 8, 31),
SETEMBRO("Setembro", 9, 30),
OUTRUBRO("Outubro", 10, 31),
NOVEMBRO("Novembro", 11, 30),
DEZEMBRO("Dezembro", 12, 31);
private String mes;
private int numeroMes;
private int qtdDias;
private MesesAno(String mes, int numeroMes, int qtdDias) {
this.mes = mes;
this.numeroMes = numeroMes;
this.qtdDias = qtdDias;
}
/**
* Obtรฉm o nome do mรชs do ano
* @return nome do mรชs
*/
public String getMes() {
return mes;
}
/**
* Determina o nome do mรชs
* @param mes Mรชs que estรก sendo determinado
*/
public void setMes(String mes) {
this.mes = mes;
}
/**
* Obtรฉm o nรบmeoro do mรชs do ano
* @return nรบmero do mรชs
*/
public int getNumeroMes() {
return numeroMes;
}
/**
* Determina o nรบmero do mรชs
* @param numeroMes numero do mes que estรก sendo determinado
*/
public void setNumeroMes(int numeroMes) {
this.numeroMes = numeroMes;
}
/**
* Obtรฉm a quantidade de dias mรชs do ano
* @return quantidade de dias do mรชs
*/
public int getQtdDias() {
return qtdDias;
}
/**
* Determina a quantidade de dias do mรชs
* @param qtdDias quantidade de dias do Mรชs que estรก sendo determinado
*/
public void setQtdDias(int qtdDias) {
this.qtdDias = qtdDias;
}
}
<file_sep>package br.com.fabrica.gui;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import br.com.fabrica.gerencia.ig.GerenciaIgInsumo;
/**
* Classe responsavel por criar a tela de cadastro de Insumos.
* @author Rafaela
*
*/
@SuppressWarnings("serial")
public class IgInsumos extends JFrame {
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblNome;
private JButton btnGravar;
private JButton btnCancelar;
private JFrame jf;
private JTextField tfPreco;
private JTextField tfNome;
/**
* Create the panel.
*/
public IgInsumos() {
getContentPane().setLayout(null);
jf = new JFrame();
jf.setAutoRequestFocus(false);
jf.getContentPane().setLayout(null);
// Define que o programa deve ser finalizado quando o usuรกrio clicar no botรฃo Fechar da janela.
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Define a janela como nรฃo redimensionรกvel.
jf.setResizable(false);
jf.setSize(420, 308);
jf.setLocationRelativeTo(null);
jf.setTitle("Cadastro de Insumos");
btnGravar = new JButton("Gravar");
jf.getContentPane().add(btnGravar);
btnGravar.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnGravar.setBounds(167, 217, 96, 25);
btnCancelar = new JButton("Cancelar");
jf.getContentPane().add(btnCancelar);
btnCancelar.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnCancelar.setBounds(273, 217, 91, 25);
lblNome = new JLabel("Nome:");
jf.getContentPane().add(lblNome);
lblNome.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNome.setBounds(65, 70, 40, 16);
lblNewLabel_1 = new JLabel("Quantidade:");
jf.getContentPane().add(lblNewLabel_1);
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNewLabel_1.setBounds(35, 118, 83, 16);
lblNewLabel = new JLabel("Insumo");
jf.getContentPane().add(lblNewLabel);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel.setBounds(188, 22, 83, 19);
tfPreco = new JTextField();
tfPreco.setColumns(10);
tfPreco.setBounds(130, 163, 130, 30);
jf.getContentPane().add(tfPreco);
tfNome = new JTextField();
tfNome.setColumns(10);
tfNome.setBounds(130, 64, 234, 30);
jf.getContentPane().add(tfNome);
JLabel lblPreo = new JLabel("Pre\u00E7o:");
lblPreo.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPreo.setBounds(65, 169, 52, 16);
jf.getContentPane().add(lblPreo);
JSpinner spinner = new JSpinner();
spinner.setBounds(130, 113, 130, 29);
jf.getContentPane().add(spinner);
jf.setVisible(true);
btnGravar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GerenciaIgInsumo.cadastraInsumo(tfNome, spinner, tfPreco, jf);
tfNome.setText("");
spinner.setValue(0);
tfPreco.setText("");
}
});
btnCancelar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jf.setVisible(false);
IgMenu igMenu = new IgMenu();
igMenu.getJf().setVisible(true);
}
});
}
/**
* Obtรฉm a janela
* @return janela contendo
*/
public JFrame getJf() {
return jf;
}
/**
* Fornece a janela
* @param jf Janela
*/
public void setJf(JFrame jf) {
this.jf = jf;
}
}
<file_sep>package br.com.fabrica.modelo;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author <NAME>
*
* Classe responsรกvel por armazenar os dados de um insumo(Tudo que for necessรกrio para
* a produรงรฃo de um produto).
* Exemplos de Insumo:
* -Maquinรกrio, matรฉria-prima(farinha de trigo, leite, aรงรบcar, ovos, etc).
*/
public class Insumo {
private int codigoProduto;
private int codigo;
private String nome;
private float quantidade;
private float precoUnitario;
private List<HistoricoPreco> historico;
/***
* Construtor default da classe Insumo
* instancia um novo objeto da classe Insumo e uma lista referente
* aos histรณricos de preรงo
*/
public Insumo() {
historico = new ArrayList<HistoricoPreco>();
}
/***
* Construtor sobrecarregado da classe insumo onde nรฃo sรฃo atribuรญdos valores default mas
* sim valores passados como parรขmetro.
* @param codigoProduto - <code>int</code>: cรณdigo referente ao produto.
* @param nome - <code>String</code>: nomeaรงรฃo dada a um insumo
* @param quantidade - <code>int</code>: valor inicial do insumo
* @param precoUnitario - <code>float</code>: preรงo inicial do insumo
* @param historico - <code>List</code>: atualizaรงรฃo de preรงos do insumo
*/
public Insumo(int codigoProduto, String nome, float quantidade, float precoUnitario,
List<HistoricoPreco> historico) {
this.codigoProduto = codigoProduto;
this.nome = nome;
this.quantidade = quantidade;
this.precoUnitario = precoUnitario;
this.historico = historico;
}
/***
* Obtรฉm o nome de um insumo
* @return <code>String</code>: o nome do insumo definido atravรฉs de nome.
*/
public String getNome() {
return nome;
}
/***
* Atribui um nome ao objeto da classe Insumo.
* @param nome - <code>String</code>: nomeaรงรฃo do insumo a ser atribuรญda na classe.
*/
public void setNome(String nome) {
this.nome = nome;
}
/***
* Obtรฉm a quantidade de um insumo
* @return <code>float</code> : retorna a quantidade disponรญvel do objeto insumo.
*/
public float getQuantidade() {
return quantidade;
}
/***
* Atribui um valor ao atributo quantidade da classe Insumo.
* @param quantidade - <code>float</code>: variรกvel com o valor a ser atribuรญdo ao objeto quantidade da classe insumo.
*/
public void setQuantidade(float quantidade) {
this.quantidade = quantidade;
}
/***
* Obtรฉm o preรงo unitรกrio do insumo.
* @return <code>float</code>: o valor da unitรกrio do objeto insumo
*/
public float getPrecoUnitario() {
return precoUnitario;
}
/***
* Atribui um preรงo ao atributo precoUnitario da classe Insumo.
* @param precoUnitario - <code>float</code> : Valor a ser atribuรญdo ao precoUnitario da classe Insumo
*/
public void setPrecoUnitario(float precoUnitario) {
this.precoUnitario = precoUnitario;
}
/***
* Obtรฉm o histรณrico de preรงos do objeto insumo
* @return <code>List</code>: Retorna uma lista com todos preรงos jรก cadastrados para aquele objeto da classe Insumo
*/
public List<HistoricoPreco> getHistorico() {
return historico;
}
/***
* Atribui uma lista com todos os preรงos jรก cadastrados para aquele objeto da classe Insumo
* @param historico <code>List</code>: Lista contendo o histรณrico de preรงos a ser atribuรญda ao objeto da classe Insumo
*/
public void setHistorico(List<HistoricoPreco> historico) {
this.historico = historico;
}
/**
* Retorna o cรณdigo na qual aquele insumo pertence.
* @return <code>int</code>: valor que referencia a que produto este insumo pertence.
*/
public int getCodigoProduto() {
return codigoProduto;
}
/**
* Atribui ao insumo o cรณdigo na qual aquele produto ele pertence.
* @param codigoProduto <code>int</code>: contรฉm a referรชncia indicativa de um produto.
*/
public void setCodigoProduto(int codigoProduto) {
this.codigoProduto = codigoProduto;
}
/**
*Obtรฉm o cรณdigo de um insumo.
* @return <code>int</code>: o valor de um cรณdigo do insumo.
*/
public int getCodigo() {
return codigo;
}
/**
* Atribui um cรณdigo de identificaรงรฃo para determinado insumo.
* @param codigo - <code>int</code>: valor a ser atribuรญdo para identificaรงรฃo de um insumo.
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* Representaรงรฃo dos dados do objeto da classe Insumo em forma de Texto.
*/
@Override
public String toString() {
return String.format("Cรณdigo: %d, nome: %s, quantidade: %.3f, precoUnitario: %.2f,"
+ " historico: %s", getCodigo(), nome, quantidade, precoUnitario, historico);
}
}
<file_sep>package br.com.fabrica.gerencia.ig;
import static br.com.fabrica.constantes.Constantes.ALTERACAO;
import static br.com.fabrica.constantes.Constantes.ALTERA_PRECO;
import static br.com.fabrica.constantes.Constantes.ARQ_HISTORICO_INSUMO;
import static br.com.fabrica.constantes.Constantes.ERR_ALTERA_PRECO;
import static br.com.fabrica.gui.EntradaESaida.msgErro;
import static br.com.fabrica.gui.EntradaESaida.msgInfo;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import br.com.fabrica.arquivos.ArquivoHistoricoPreco;
import br.com.fabrica.arquivos.ArquivoInsumo;
import br.com.fabrica.gerencia.modelo.GerenciaHistoricoPreco;
import br.com.fabrica.gui.IgAlteraPrecoInsumo;
import br.com.fabrica.modelo.HistoricoPreco;
import br.com.fabrica.validacoes.Validacoes;
/**
* Classe responsรกvel por gerenciar as funรงรตes da classe <code>IgAlteraPrecoInsumo</code>
* @see IgAlteraPrecoInsumo
* @author <NAME>
*
*/
public class GerenciaIgAlteraPrecoInsumo {
public static ArquivoHistoricoPreco arquivoHistorico = new ArquivoHistoricoPreco();
/**
* Altera o preรงo referente ao insumo
* @param comboInsumo Lista de insumos cadastrados
* @param tfPreco novo preรงo do insumo
* @param jf Janela principal
*/
public static void alteraPreco(JComboBox<String> comboInsumo, JTextField tfPreco, JFrame jf) {
int codigo = Validacoes.obtemCodigo(comboInsumo.getSelectedItem().toString());
float preco = Validacoes.transformaEmFloat(tfPreco.getText());
HistoricoPreco hp = new HistoricoPreco();
hp.setCodigo(codigo);
boolean altera = new ArquivoInsumo().alteraPreco(codigo, preco);
if(altera){
boolean alteracao = new GerenciaHistoricoPreco().insereHistoricoPreco(preco, codigo, ARQ_HISTORICO_INSUMO);
if(alteracao)
msgInfo(jf, ALTERA_PRECO, ALTERACAO);
else
msgErro(jf, ERR_ALTERA_PRECO, ALTERACAO);
}else
msgErro(jf, ERR_ALTERA_PRECO, ALTERACAO);
}
}
<file_sep>package br.com.fabrica.arquivos;
import static br.com.fabrica.constantes.Constantes.ARQ_PRODUCAO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import br.com.fabrica.modelo.Producao;
import br.com.fabrica.modelo.Produto;
import br.com.fabrica.validacoes.Data;
/**
* Esta classe fornece uma implementaรงรฃo para as operaรงรตes que permitem manipular um arquivo de acesso
* aleatรณrio para ler e escrever objetos da classe <code>Produรงรฃo</code>.
*
* @see BinaryFile
* @see Produto
*
* @author <NAME> e Rafaela
*/
public class ArquivoProducao extends BinaryFile{
/**
* Obtรฉm o tamanho do registro que รฉ de 128 bytes, pois sรฃo:
*4 bytes do codigo da produรงรฃo.
*100 bytes do nome do produto com 50 caracteres (2 bytes de cada carรกcter UNICODE);
*20 bytes da data de produรงรฃo
*4 bytes custo produรงรฃo
* @return um <code>int</code> com o tamanho, em bytes, do registro.
*/
@Override
public int recordSize() {
return 128;
}
/**
* Escreve o objeto como um registro do arquivo.
*
* @param objeto um <code>Object</code> que serรก armazenado no arquivo.
*
* @throws IOException se ocorrer um erro de E/S;
* @throws ClassCastException se o tipo do objeto a ser escrito no arquivo nรฃo for da classe
* <code>Producao</code>.
**/
@Override
public void writeObject(Object objeto) throws IOException {
Producao producao = new Producao();
if(objeto instanceof Producao)
producao = (Producao) objeto;
else
throw new ClassCastException();
randomAccessFile.writeInt(producao.getCodigo());
randomAccessFile.writeChars(setStringLength(producao.getProduto().getNome(),50));
randomAccessFile.writeInt(producao.getProduto().getQuantidade());
randomAccessFile.writeFloat(producao.getCustoProducao());
randomAccessFile.writeChars(setStringLength(producao.getData().toString(), 10));
}
/**
* Escreve um objeto com os dados de uma produรงรฃo no arquivo
* @param producao <code>Producao</code> que serรก escrita
* @throws IOException Erro relacionado a entrada e saรญda de dados.
*/
public void writeObject(Producao producao) throws IOException {
Object object = producao;
writeObject(object);
}
/**
* Lรช o objeto como um registro do arquivo.
*
* @return um <code>Produรงรฃo</code> com os atributos do objeto lido do arquivo.
*
* @throws IOException se ocorrer um erro de E/S.
**/
@Override
public Object readObject() throws IOException {
Producao producao = new Producao();
producao.setCodigo(randomAccessFile.readInt());
Produto produto = new Produto();
produto.setNome(readString(50));
produto.setQuantidade(randomAccessFile.readInt());
producao.setProduto(produto);
producao.setCustoProducao(randomAccessFile.readFloat());
Data data = new Data(readString(10));
producao.setData(data);
return producao;
}
/**
* Recebe um Objeto com dados de uma produรงรฃo referente a classe {@link Producao} a serem gravados
* no arquivo de producao.
* @param arquivo uma String contendo o nome do arquivo onde serรฃo gravados os dados.
* @param producao Um objeto producao a ser gravado no arquivo.
* @return Retorna True ou False indicando se a gravaรงรฃo obteve sucesso ou falha.
*/
public Producao escreveProducaoNoArquivo(Producao producao, String arquivo) {
try {
openFile(arquivo);
setFilePointer(recordQuantity());
writeObject(producao);
closeFile();
return producao;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Obtรฉm uma produรงรฃo que foi cadastrada.
* @param indice <code>int</code> referencia ao produto que serรก obtido
* @param arquivo<code>String</code>nome do arquivo onde serรฃo obtidos os dados.
* @return informaรงรตes referentes a produรงรฃo.
*/
public Producao leProducaoNoArquivo(int indice, String arquivo) {
try {
openFile(arquivo);
setFilePointer(indice);
Producao producao = (Producao) readObject();
closeFile();
return producao;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/***
* Obtรฉm o cรณdigo sequencial para a produรงรฃo
* @param arquivo Arquivo de onde serรก obtido o cรณdigo
* @return retorna o cรณdigo sequencial para o prรณximo dado de histรณrico
*/
public int obtemCodigoProducao(String arquivo) {
int codigo = 0;
try {
openFile(arquivo);
if(recordQuantity() == 0)
codigo = 1;
else {
codigo = (int) (recordQuantity() + 1);
}
closeFile();
return codigo;
} catch (FileNotFoundException e) {
e.printStackTrace();
return codigo;
} catch (IOException e) {
e.printStackTrace();
return codigo;
}
}
/**
* Obtรฉm a produรงรฃo de um determinado produto.
* @param codigo <code>int</code> cรณdigo referente a produรงรฃo
* @param arquivo<code>String</code> nome do arquivo de onde serรก obtida a produรงรฃo
* @return <code>Producao</code> dados da produรงรฃo procurada.
*/
public Producao obterProducao(int codigo, String arquivo) {
Producao producao = null;
try {
openFile(arquivo);
for (int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
producao = (Producao) readObject();
if(producao.getCodigo() == codigo)
break;
}
closeFile();
return producao;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Obtรฉm as produรงรตes cadastradas.
* @param arquivo Arquivo de onde irรก obter as informaรงรตes.
* @return <code>List</code> lista de produรงรตes
*/
public List<Producao> leProducoesNoArquivo(String arquivo) {
List<Producao> listaProducao = new ArrayList<>();
try {
openFile(arquivo);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
Producao producao = (Producao) readObject();
listaProducao.add(producao);
}
closeFile();
return listaProducao;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Altera as informaรงรตes de uma produรงรฃo cadastrada.
* @param arquivo <code>String</code> nome do arquivo de onde serรฃo alterados os dados de produรงรฃo
* @param prod <code>Producao</code> produรงรฃo a ser alterada.
* @return <code>Producao</code> produรงรฃo alterada.
*/
public Producao alteraProducao(Producao prod, String arquivo) {
Producao producao = null;
try {
openFile(arquivo);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
producao = (Producao) readObject();
if(producao.getProduto().getNome().equalsIgnoreCase(prod.getProduto().getNome())) {
producao.getProduto().setQuantidade(prod.getProduto().getQuantidade());
escreveProducaoPorPosicao(producao, i, ARQ_PRODUCAO);
break;
}
}
closeFile();
return producao;
} catch (FileNotFoundException e) {
e.printStackTrace();
return producao;
} catch (IOException e) {
e.printStackTrace();
return producao;
}
}
/**
* Altera as informaรงรตes de uma produรงรฃo cadastrada.
* @param prod <code>Producao</code> produรงรฃo a ser alterada.
* @param arquivo <code>String</code> nome do arquivo de onde serรก alterada a quantidade da produรงรฃo
* @return <code>Producao</code> produรงรฃo alterada.
*/
public Producao alteraQuantidadeProducao(Producao prod, String arquivo) {
Producao producao = null;
try {
openFile(arquivo);
for(int i = 0; i < recordQuantity(); i++) {
setFilePointer(i);
producao = (Producao) readObject();
if(!producao.getProduto().getNome().equalsIgnoreCase(prod.getProduto().getNome())) {
System.out.println("No if");
continue;
}else {
producao.getProduto().setQuantidade(producao.getProduto().getQuantidade() +
prod.getProduto().getQuantidade());
escreveProducaoPorPosicao(producao, i, arquivo);
closeFile();
return producao;
}
}
closeFile();
return escreveProducaoNoArquivo(prod, arquivo);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null ;
}
}
/**
* Escreve uma produรงรฃo em uma determinada posiรงรฃo.
* @param producao <code>Producao</code> producao a ser cadastrada.
* @param posicao <code>int</code> posiรงรฃo que serรก escrito a produรงรฃo
* @param arquivo <code>String</code> nome do arquivo de onde serรก escrito os dados de produรงรฃo
* @return Retorna True ou False indicando se a gravaรงรฃo teve sucesso ou falha.
*/
public boolean escreveProducaoPorPosicao(Producao producao, int posicao, String arquivo) {
try {
openFile(arquivo);
setFilePointer(posicao);
writeObject(producao);
closeFile();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
<file_sep>package br.com.fabrica.gerencia.modelo;
import java.util.Calendar;
import static br.com.fabrica.constantes.Constantes.*;
import java.util.List;
import br.com.fabrica.arquivos.ArquivoProducao;
import br.com.fabrica.arquivos.ArquivoVenda;
import br.com.fabrica.modelo.MesesAno;
import br.com.fabrica.modelo.Orcamento;
import br.com.fabrica.modelo.Producao;
import br.com.fabrica.modelo.Venda;
import br.com.fabrica.validacoes.Data;
/**
* Classe responsรกvel por gerenciar o Orcamento
* @see Orcamento
* @author Rafaela
*
*/
public class GerenciaOrcamento {
/**
* Soma as despesas de produรงรฃo de cada mรชs
* @param mes mes que deseja obter as despesas
* @return valor das despesas
*/
public float somaDespedasMes(String mes) {
Data dataI = null;
Data dataF = null;
float valorDespesa = 0;
Calendar cal = Calendar.getInstance();
for(MesesAno mesAno : MesesAno.values()) {
if(mesAno.getMes().equalsIgnoreCase(mes)) {
dataI = new Data(1, mesAno.getNumeroMes(), cal.get(Calendar.YEAR));
dataF = new Data(mesAno.getQtdDias(), mesAno.getNumeroMes(), cal.get(Calendar.YEAR));
}
}
ArquivoProducao ap = new ArquivoProducao();
List<Producao> litaProducao = ap.leProducoesNoArquivo(ARQ_PRODUCAO);
for(Producao producao : litaProducao) {
if(producao.getData().dataDentroDoPeriodo(dataI, dataF)) {
valorDespesa += producao.getCustoProducao();
}
}
return valorDespesa;
}
/**
* Obtรฉm o nรบmero total de vendas em um mรชs
* @param mes mes que deseja obter as informaรงรตes
* @return quantidade de produtos vendidos
*/
public int obtemNumeroTotalDeVendas(String mes) {
Data dataI = null;
Data dataF = null;
int qtdVenda = 0;
Calendar cal = Calendar.getInstance();
for(MesesAno mesesAno : MesesAno.values()) {
if(mesesAno.getMes().equalsIgnoreCase(mes)) {
dataI = new Data(1, mesesAno.getNumeroMes(), cal.get(Calendar.YEAR));
dataF = new Data(mesesAno.getQtdDias(), mesesAno.getNumeroMes(), cal.get(Calendar.YEAR));
}
}
List<Venda> vendas = new ArquivoVenda().leVendasNoArquivo();
for(Venda venda : vendas) {
if(venda.getData().dataDentroDoPeriodo(dataI, dataF)) {
qtdVenda++;
}
}
return qtdVenda;
}
/**
* Obtรฉm o valor total obtido com as vendas
* @param mes mes que deseja obter as informaรงรตes
* @return valor total das vendas
*/
public float obtemValorTotalDeVendas(String mes) {
Data dataI = null;
Data dataF = null;
float valorVenda = 0;
Calendar cal = Calendar.getInstance();
for(MesesAno mesesAno : MesesAno.values()) {
if(mesesAno.getMes().equalsIgnoreCase(mes)) {
dataI = new Data(1, mesesAno.getNumeroMes(), cal.get(Calendar.YEAR));
dataF = new Data(mesesAno.getQtdDias(), mesesAno.getNumeroMes(), cal.get(Calendar.YEAR));
}
}
List<Venda> vendas = new ArquivoVenda().leVendasNoArquivo();
for(Venda venda : vendas) {
if(venda.getData().dataDentroDoPeriodo(dataI, dataF))
valorVenda += venda.getValorTotalVenda();
}
return valorVenda;
}
/**
* Calcula o saldo obtido no mes
* @param valorVenda valor obtido com as vendas
* @param valorDespesa valor gasto com as despesas
* @return saldo obtido no mes
*/
public float saldo(float valorVenda, float valorDespesa) {
return valorVenda - valorDespesa;
}
}
| 91b4827e0a7bd618fb6284801539e2adef9079b0 | [
"Markdown",
"Java"
] | 20 | Java | rafaela/GestaoDeProducao | 6fd92d8fbde0fbe536bed422bb8c63b63fdd921b | 8cc45bb952f303dfc57348c2d9cf3b8f2f655739 |
refs/heads/master | <repo_name>ksyednazir/fwk<file_sep>/hsvc.go
package fwk
import (
"github.com/go-hep/hbook"
)
// HID is a histogram identifier
type HID string
// H1D wraps a hbook.H1D for safe concurrent access
type H1D struct {
ID HID // unique id
Hist *hbook.H1D
}
// HistSvc is the interface providing access to histograms
type HistSvc interface {
Svc
// BookH1D books a 1D histogram.
// name should be of the form: "/fwk/streams/<stream-name>/<path>/<histogram-name>"
BookH1D(name string, nbins int, low, high float64) (H1D, error)
// FillH1D fills the 1D-histogram id with data x and weight w.
FillH1D(id HID, x, w float64)
}
| 7f90a853fc1f8f206c8e4a79ddf6051905e507ee | [
"Go"
] | 1 | Go | ksyednazir/fwk | 10ffd3e82424ff0c1f3a39248ea985ea778acdf8 | b3289f31445616a07f7f9c7b23f98fbed1b98b3c |
refs/heads/master | <file_sep># ----- Birdhouse Bootstrapper
# Should come first in your /Users/rmachen/.zshrc so it can be overridden.
# if test -L ~/.birdhouse/birdhouse_loader; then
# source ~/.birdhouse/birdhouse_loader "/Users/rmachen/local-code/homeaway/birdhouse/lib" "/Users/rmachen/.zshrc"
# fi
# ----- Birdhouse Bootstrapper
# Path to your oh-my-zsh installation.
export ZSH=/Users/rmachen/.oh-my-zsh
# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
# ZSH_THEME="risto"
# risto theme with blue and green swapped
ZSH_THEME="rodsto"
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git node npm osx atom z)
# User configuration
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/npm/bin"
# export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
# export MANPATH="/usr/local/man:$MANPATH"
#PATH=$PATH:/usr/local/bin/; export PATH
eval "$(rbenv init -)"
source $ZSH/oh-my-zsh.sh
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"
# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
alias zs="source ~/.zshrc"
alias sz="code ~/.zshrc"
alias rdm="cd /Users/rmachen/Dropbox/code/projects/rodmachen.com"
alias cdm="cd /Users/rmachen/Dropbox/code/projects/rodmachen.com/code.rodmachen.com"
alias pdm="cd /Users/rmachen/Dropbox/code/projects/rodmachen.com/photo.rodmachen.com"
alias rd="cd /Users/rmachen/Dropbox/code/projects/rodneydean.org"
alias sp="s3_website push"
# alias s.="subl . --command toggle_full_screen"
alias a.="atom ."
alias c.="code ."
# alias ga="git add ."
# alias gc="git commit -m"
# alias gac="git commit -am"
# alias gp="git push"
alias gs="git status"
alias glp="git log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short"
alias gmm="git merge master"
alias gcm="git commit -m"
alias gcom="git checkout master"
alias type="git cat-file -t"
alias dump="git cat-file -p"
alias gpum="git pull upstream master"
alias gpus="git pull --rebase upstream staging"
alias gpos="git push origin staging"
alias gps="git push --set-upstream origin"
alias grs="git rebase staging"
alias gprm="git pull --rebase upstream master"
alias gpom="git push origin master"
# alias vim="/Applications/MacVim.app/Contents/MacOS/Vim"
alias vg="valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes"
alias gn="geeknote show \"*\""
alias gfi="git-fixit"
alias nrg="npm run generate"
alias nrst="npm run start:dev"
alias nrsp="npm run stop:dev"
alias grom="git rebase origin/master"
alias rake='noglob rake'
alias mci="mvn clean install -DskipTests"
alias mcit="mvn clean install"
alias mct="mvn clean test"
alias audio="sudo kextunload /System/Library/Extensions/AppleHDA.kext;sudo kextload /System/Library/Extensions/AppleHDA.kext"
alias mcis='mci && ./start.sh'
alias mcic='mvn test jacoco:report'
alias chmd='chmod +x'
stty -ixon
export PATH="$PATH:$HOME/.rvm/bin" # Add RVM to PATH for scripting
export NPM_TOKEN=<PASSWORD>
# cd ~/local-code/homeaway
function code {
if [[ $# = 0 ]]
then
open -a "Visual Studio Code"
else
local argPath="$1"
[[ $1 = /* ]] && argPath="$1" || argPath="$PWD/${1#./}"
open -a "Visual Studio Code" "$argPath"
fi
}
# echo source $HOME/.bash_profile_bootstrap
| 67a6416d5b9da7b6dcab1a146097bc980e9cb980 | [
"Shell"
] | 1 | Shell | rodmachen/dotfiles | e3fb0b586b18916314e1601aaad86798fb35d2e5 | 2ba3b0b240aa1e265176aded90da455d82694afd |
refs/heads/master | <repo_name>huangjimmy/PKYStepper<file_sep>/PKYDropDownStepper.podspec
Pod::Spec.new do |s|
s.name = "PKYDropDownStepper"
s.version = "0.0.5"
s.summary = "UIControl with label & stepper & dropdown list combined"
s.description = <<-DESC
A customizable UIControl with label & stepper & dropdown selection list combined.
DESC
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "<NAME>" => "<EMAIL>", "<NAME>" => "<EMAIL>" }
s.homepage = "https://github.com/huangjimmy/PKYStepper"
s.platform = :ios
s.ios.deployment_target = "6.0"
s.source = { :git => "https://github.com/huangjimmy/PKYStepper.git", :tag => '0.0.4' }
s.default_subspec = 'Core'
s.frameworks = "Foundation", "UIKit", "QuartzCore"
s.requires_arc = true
s.subspec 'Core' do |ss|
ss.source_files = "PKYStepper/**/*.{h,m}"
ss.frameworks = "Foundation", "UIKit", "QuartzCore"
end
s.subspec 'React' do |ss|
ss.dependency 'PKYDropDownStepper/Core'
ss.frameworks = "JavaScriptCore"
ss.source_files = "RCTPKYStepper/**/*.{h,m}"
end
end
<file_sep>/Podfile
platform :ios,7.0
pod 'React'
| 671a5adaf566985d83de43813a846dd206b51319 | [
"Ruby"
] | 2 | Ruby | huangjimmy/PKYStepper | 8b69cd954f4ad2c295a8b02887f9be1f99f4530a | 964af996674b4d3055199a4c1c48cf3450ff7283 |
refs/heads/master | <repo_name>cascadianrebel/Lab03-Word-Guess-Game<file_sep>/ReadMe.md
# Lab03 - Word Guess Game
A game where the user can guess a random word, one letter at a time.
## Author
<NAME>
## License
MIT License<file_sep>/Lab03-Word-Guess-Game/Program.cs
๏ปฟusing System;
using System.IO;
using System.Text;
using System.Linq;
namespace Lab03_Word_Guess_Game
{
class Program
{
public static string path = "../../../WordBank.txt";
public static string[] initialBank = new string[] { "apple", "banana", "orange", "lemon", "cucumber", "blueberry", "grapes", "plum" };
static void Main(string[] args)
{
//File created
CreateWordBank(initialBank);
// Display the home screen
DisplayHome();
}
public static void DisplayHome()
{
Console.WriteLine("_________________________");
Console.WriteLine("*************************");
Console.WriteLine("`````Word Guess Game`````");
Console.WriteLine("*************************");
Console.WriteLine("Select an option number then press enter");
Console.WriteLine("-----------------------");
Console.WriteLine("1. Start New Game");
Console.WriteLine("2. Game Settings");
Console.WriteLine("3. Quit Game");
Console.WriteLine("------------------------");
try
{
switch (Convert.ToInt32(Console.ReadLine()))
{
case 1:
StartGame();
break;
case 2:
Console.Clear();
OptionsMenu();
break;
case 3:
Console.WriteLine("So long friend :( ");
Environment.Exit(0);
break;
default:
Console.Clear();
Console.WriteLine("Please make valid selection");
DisplayHome();
break;
}
}
catch (FormatException)
{
Console.Clear();
Console.WriteLine("**Please only enter numbers 1-3**");
DisplayHome();
throw;
}
}
public static void StartGame()
{
SelectWord();
}
static string SelectWord()
{
//create the wordBank by reading each line in the wordBank text file
string[] wordBank = File.ReadAllLines(path);
//select a random index position from the wordBank array
Random rand = new Random();
int randomWordIndex = rand.Next(wordBank.Length);
//get the word using the random index
string randomWord = wordBank[randomWordIndex];
GamePlay(randomWord);
return randomWord;
}
static string GamePlay(string Word)
{
//create the blank array using the length of the random word
string[] letterTiles = new string[Word.Length];
string[] guessedLetters = new string[26];
int counter = 0;
string blank = "_";
Console.WriteLine("To Guess the word below, type the letter you've chosen, then press enter");
//loop through the word and replace each letter with an underscore
foreach (var i in letterTiles)
{
Console.Write(blank);
Console.Write(" ");
}
string userGuess = Console.ReadLine();
string letterGuessed = userGuess.ToString();
guessedLetters[counter] = letterGuessed;
foreach (var i in Word)
{
if (Word.Contains(letterGuessed))
{
letterTiles[i] = letterGuessed;
}
else
{
letterTiles[i] = blank;
}
Console.Write(letterTiles[i]);
}
return GamePlay(Word);
}
/// <summary>
/// shows user View, Add, and Delete display screen
/// </summary>
static void OptionsMenu()
{
Console.WriteLine("________________________");
Console.WriteLine("~~~~~~GAME Options~~~~~~");
Console.WriteLine("Select an option number then press enter");
Console.WriteLine("-----------------------");
Console.WriteLine("1. View Word Bank");
Console.WriteLine("2. Add New Word To Bank");
Console.WriteLine("3. Remove Word from Bank");
Console.WriteLine("4. Return to Main Menu");
Console.WriteLine("------------------------");
try
{
switch (Convert.ToInt32(Console.ReadLine()))
{
case 1:
DisplayWordBank();
OptionsMenu();
break;
case 2:
DisplayWordBank();
AddToWordBank();
break;
case 3:
DisplayWordBank();
RemoveFromWordBank();
break;
case 4:
Console.Clear();
DisplayHome();
break;
default:
Console.WriteLine("Please make valid selection");
OptionsMenu();
break;
}
}
catch (FormatException)
{
Console.Clear();
Console.WriteLine("**Please only enter numbers 1-4**");
OptionsMenu();
throw;
}
}
/// <summary>
/// creates the file called WordBank.txt
/// </summary>
static void CreateWordBank(string[] words)
{
// checks if the file already exists
if (!File.Exists(path))
{
//creates the file if it doesn't already exist
using (StreamWriter sw = new StreamWriter(path))
try
{
//iterates through array of words and puts intial words in file, each on its own line
foreach (string s in words)
{
sw.WriteLine(s);
}
}
finally
{
sw.Close();
}
}
else
{
DeleteFile(path);
CreateWordBank(words);
}
}
/// <summary>
/// accesses the content of the WordBank file
/// </summary>
static void DisplayWordBank()
{
Console.Clear();
//displays each element in the word bank
try
{
string[] wordBank = File.ReadAllLines(path);
//iterates through array of words created from each line of the Word Bank
foreach (string value in wordBank)
{
Console.WriteLine(value);
}
}
catch (Exception e)
{
Console.WriteLine("Something went wrong");
Console.WriteLine(e);
}
}
/// <summary>
/// allows user to update Word bank
/// </summary>
static void AddToWordBank()
{
Console.Clear();
DisplayWordBank();
using (StreamWriter sw = File.AppendText(path))
{
//adds word to text file
Console.WriteLine("Please type the word you'd like to add to the Word Bank then press enter ");
string Word2Add = Console.ReadLine();
sw.WriteLine(Word2Add);;
}
Console.Clear();
DisplayWordBank();
OptionsMenu();
}
/// <summary>
/// INCOMPLETE: removing word from word bank
/// </summary>
static void RemoveFromWordBank()
{
string[] wordBank = File.ReadAllLines(path);
string[] updateWordBank = new string[wordBank.Length-1];
int counter = 0;
Console.WriteLine("Please enter the word you'd like removed from the wordBank");
string Word2Remove = Console.ReadLine();
for (int k = 0; k < wordBank.Length; k++)
{
if (wordBank[k] != Word2Remove)
{
updateWordBank[counter] = wordBank[k];
Console.WriteLine($"Counter is {counter}. K is {k}. Updated Bank is '{updateWordBank[counter]}' with a length of {updateWordBank.Length}. Word bank is {wordBank[k]}");
counter++;
}
else
{
Console.WriteLine("else hit");
}
}
CreateWordBank(updateWordBank);
DisplayWordBank();
OptionsMenu();
}
/// <summary>
/// deletes the file
/// </summary>
static void DeleteFile(string FilePath)
{
File.Delete(FilePath);
}
}
}
| e1b44e20e72afd75dc7b2dee6c5806a0aa593e59 | [
"Markdown",
"C#"
] | 2 | Markdown | cascadianrebel/Lab03-Word-Guess-Game | f36164916ffd6cb96aaa9415518f1f820d734413 | e6521a81551575b330baebf9c76abb782cf0d0aa |
refs/heads/master | <file_sep>import tkinter
import cv2
import PIL.Image, PIL.ImageTk
from functools import partial
import threading # to load another image at samae rate
import time
import imutils
SET_WIDTH = 650
SET_HEIGHT = 340
stream = cv2.VideoCapture("clip.mp4")
flag = True
def play(speed):
global flag
print(f"You clicked on play. Speed is {speed}")
# Play the video in reverse mode
frame1 = stream.get(cv2.CAP_PROP_POS_FRAMES)
stream.set(cv2.CAP_PROP_POS_FRAMES, frame1 + speed)
grabbed, frame = stream.read()
if not grabbed:
exit()
frame = imutils.resize(frame, width=SET_WIDTH, height=SET_HEIGHT)
frame = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
canvas.image = frame
canvas.create_image(0,0, image=frame, anchor=tkinter.NW)
if flag:
canvas.create_text(134, 26, fill="black", font="Times 26 bold", text="Decision Pending")
flag = not flag
def pending(decision):
'''
1. Display Decision pending image
2 wait for second
3 display sponsor image
4 wait for 1.5 second
5 Display out/notout image'''
frame = cv2.cvtColor(cv2.imread("pending.png"), cv2.COLOR_BGR2RGB)
frame = imutils.resize(frame, width = SET_WIDTH , height = SET_HEIGHT)
frame = PIL.ImageTk.PhotoImage(image =PIL.Image.fromarray( frame))
canvas.image = frame
canvas.create_image(0, 0 , image=frame , anchor = tkinter.NW)
time.sleep(1)
frame = cv2.cvtColor(cv2.imread("sponsor.png"), cv2.COLOR_BGR2RGB)
frame = imutils.resize(frame, width = SET_WIDTH , height = SET_HEIGHT)
frame = PIL.ImageTk.PhotoImage(image =PIL.Image.fromarray( frame))
canvas.image = frame
canvas.create_image(0, 0 , image=frame , anchor = tkinter.NW)
time.sleep(2.5)
'''
if decision == 'out':
decision_img = 'out.png'
else:
decision_img = 'not_out.png'
frame = cv2.cvtColor(cv2.imread(decision_img), cv2.COLOR_BGR2RGB)
frame = imutils.resize(frame, width = SET_WIDTH , height = SET_HEIGHT)
frame = PIL.ImageTk.PhotoImage(image =PIL.Image.fromarray( frame))
canvas.image = frame
canvas.create_image(0, 0 , image=frame , anchor = tkinter.NW)'''
if decision == 'out':
decisionImg = "out.png"
else:
decisionImg = "not_out.png"
frame = cv2.cvtColor(cv2.imread(decisionImg), cv2.COLOR_BGR2RGB)
frame = imutils.resize(frame, width=SET_WIDTH, height=SET_HEIGHT)
frame = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))
canvas.image = frame
canvas.create_image(0,0, image=frame, anchor=tkinter.NW)
def out():
thread = threading.Thread(target=pending, args=("out",))
thread.daemon = 1
thread.start()
print("Player is out")
def not_out():
thread = threading.Thread(target=pending, args=("not out",))
thread.daemon = 1
thread.start()
print("Player is not out")
window = tkinter.Tk() # to make GUI window
window.title(" Third Umpire Decision Review Kit")
canvas = tkinter.Canvas(window, width = SET_WIDTH, height= SET_HEIGHT)
cv_img = cv2.cvtColor(cv2.imread('welcome.png'), cv2.COLOR_BGR2RGB)
cv_img = imutils.resize(cv_img, width =SET_WIDTH , height = SET_HEIGHT)
#to set image ingui
photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(cv_img))
#to work allthis thing we need to pack in canvas we r packing in canvas
image_on_canvas = canvas.create_image(0, 0, ancho=tkinter.NW, image=photo)
canvas.pack()
#BUTTONS TO CONTRO PLAY BACK
btn = tkinter.Button(window, text="<<Previous (fast)", width=50,command = partial(play, -25))
btn.pack()
btn = tkinter.Button(window, text="<<Previous (slow)",width=50, command = partial(play, -2))
btn.pack()
btn = tkinter.Button(window, text="GiveOut",width=50, command = out)
btn.pack()
btn = tkinter.Button(window, text="Give Not OUT",width=50, command = not_out)
btn.pack()
btn = tkinter.Button(window, text="Next (fast)>>",width=50, command = partial(play, 25))
btn.pack()
btn = tkinter.Button(window, text="Next (slow)>>",width=50, command = partial(play, 2))
btn.pack()
window.mainloop()
<file_sep>import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import random
import sys
import urllib.request
import urllib.parse
import re
from googlesearch import search
engine = pyttsx3.init('sapi5') # to take inbuilt windows api for voices
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voice', voices)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour>= 0 and hour<12:
speak("Good Morning")
elif hour>=12 and hour <18:
speak("Good Afternoon")
else:
speak("Good Evening")
speak('how may i help you sir i am always there for u . Hope u have a good day')
def takeCommand():
#it takes microphone input from user and cinvert it into strings
r = sr.Recognizer()
with sr.Microphone() as source:
print('Listening....')
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognisinh...")
query = r.recognize_google(audio, language= 'en-in')
print(f"User said: {query}\n")
except Exception as e:
print("say that again please..")
return 'None'
return query
def sendEmail(to , content):
server = smyplib.SMTP('smntp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('<EMAIL>','Thakur@447')
server.sendmail('<EMAIL>', to,content)
server.close()
if __name__ == "__main__":
speak("this is going to be awesome batman")
wishMe()
while True:
query = takeCommand().lower()
if 'wikipedia' in query:
speak('Searching wikipedia ...')
query =query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=2)
print(results)
speak("According to wikipedia")
speak(results)
elif 'open youtube' in query:
webbrowser.open('youtube.com')
# search anythoing in youtube
elif 'play from youtube' in query:
speak('What do you want to search in youtube')
youtube_query = takeCommand()
query_string = urllib.parse.urlencode({"search_query" : youtube_query})
html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
print("http://www.youtube.com/watch?v=" + search_results[0])
webbrowser.open("http://www.youtube.com/watch?v=" + search_results[0])
elif 'open google' in query:
webbrowser.open("google.com")
elif 'search google' in query:
speak('What do you want to search')
G_Search = takeCommand()
url = "https://www.google.co.in/search?q=" +(str(G_Search))+ "&oq="+(str(G_Search))+"&gs_l=serp.12..0i71l8.0.0.0.6391.0.0.0.0.0.0.0.0..0.0....0...1c..64.serp..0.0.0.UiQhpfaBsuU"
webbrowser.open_new(url)
elif 'open website' in query:
speak('Which website do you want to visit')
Web_search = takeCommand()
Website=[]
for url in search(Web_search, tld='com.pk', lang='es', stop=5):
Website.append(url)
webbrowser.open(Website[0])
elif 'open stackoverflow' in query:
webbrowser.open('stackoverflow.com')
elif 'play music from playlist' in query:
music_dir = 'C:\\Users\\Nandan\\Music'
songs = os.listdir(music_dir)
#print(songs)
os.startfile(os.path.join(music_dir ,songs[random.randint(0,len(songs)-1)]))
elif 'the time' in query:
strTime = datetime.datetime.strftime("%H:%M:%S")
elif ' send email ' in query:
try:
speak("what should i say?")
content = takeCommand()
to = "<EMAIL>"
sendEmail(to, content)
speak("Email has been sent")
except Exception as e:
print(e)
speak('Email not recognize')
if 'shutdown' in query:
speak('I am shutting u can call me any time')
break
| 4c7b138c431c571aa5713a07a00c293e4d76c7bc | [
"Python"
] | 2 | Python | saurabhkthakur/Python-Projects | 6b3ea3c88f084d88764bc53df87f5b5944149127 | ff9da2a9bc77a2b86f621adadd8ed70ed8120a6f |
refs/heads/master | <repo_name>Yamadads/Employee-Scheduler<file_sep>/src/employeeScheduler/builder/MathSolverBuilder.java
package employeeScheduler.builder;
import employeeScheduler.model.*;
import org.jacop.core.*;
import org.jacop.constraints.*;
import org.jacop.search.*;
import java.util.ArrayList;
/**
* Builder uses an open source math solver to create the final work schedule.
* TO DO in the future or not :)
*/
public class MathSolverBuilder implements ScheduleBuilder{
private ResultingSchedule resultingSchedule;
private EmployeeSchedule employeeSchedule;
private ScheduleModel model;
public void buildSchedule(ScheduleModel model){
this.model = model;
int size = 0;
for (Shift shift: model.getShifts()) {
size +=shift.getMaxEmployeesNumber();
}
int employeeMaxDayNumber = size;
size*=model.getScheduleDaysNumber();
/*
Store store = new Store();
IntVar[][][] x = new IntVar[model.getScheduleDaysNumber()][model.getShifts().size()][model.getEmployeePreferences().size()];
//define domain of result
for (int i=0; i<model.getScheduleDaysNumber(); i++)
for (int j=0;j<model.getShifts().size();j++)
for (int k=0;k<model.getEmployeePreferences().size();k++){
x[i][j][k]= new IntVar(store, "x"+i+j+k, 0,1);
}
//result[i] = new IntVar(store, "result"+i, 0, 1);
//constraints
//working days number (0 is "no employee")
IntVar counts[] = new IntVar[model.getEmployeePreferences().size()];
for (int i=0;i<model.getEmployeePreferences().size()-1; i++){
counts[i]= new IntVar(store, "counts"+i,
model.getEmployeePreferences().get(i+1).getMinWorkingDaysNumber(),
model.getEmployeePreferences().get(i+1).getMaxWorkingDaysNumber());
store.impose(new Among(x[i][][i], new IntervalDomain(i+1,i+1), counts[i]));
}
//diffren people in day
for (int i=0; i<size;i+=employeeMaxDayNumber){
for (int k=i;k<i+employeeMaxDayNumber;k++){
for (int j=k+1;j<i+employeeMaxDayNumber;j++) {
store.impose(new XneqY(result[k], result[j]));
}
}
}
Search<IntVar> search = new DepthFirstSearch<IntVar>();
SelectChoicePoint<IntVar> select =
new InputOrderSelect<IntVar>(store, result,
new IndomainMin<IntVar>());
boolean isResult = search.labeling(store, select);
if ( isResult ){
System.out.println("Solution: ");
for (int i=0;i<size;i++){
System.out.print(result[i]+", ");
}
}
else
System.out.println("*** No");
*/
}
public ResultingSchedule getResultingSchedule(){
return resultingSchedule;
}
public EmployeeSchedule getEmployeeSchedule(){
return employeeSchedule;
}
}
<file_sep>/src/employeeScheduler/model/EmployeePreferences.java
package employeeScheduler.model;
/**
* Employee preferences about specific work shift
*/
public class EmployeePreferences {
private Integer dayNumber;
private Integer shiftNumber;
private Preferences preference;
public EmployeePreferences(Integer dayNumber, Integer shiftNumber, Preferences preference) {
this.dayNumber = dayNumber;
this.shiftNumber = shiftNumber;
this.preference = preference;
}
public Integer getDayNumber() {
return dayNumber;
}
public void setDayNumber(Integer dayNumber) {
this.dayNumber = dayNumber;
}
public Integer getShiftNumber() {
return shiftNumber;
}
public void setShiftNumber(Integer shiftNumber) {
this.shiftNumber = shiftNumber;
}
public Preferences getPreference() {
return preference;
}
public void setPreference(Preferences preference) {
this.preference = preference;
}
}<file_sep>/src/employeeScheduler/model/DayTime.java
package employeeScheduler.model;
/**
* Simple class with hour and minute.
*/
public class DayTime {
private int hour;
private int minute;
public DayTime(int hour, int minute) {
if (hour > 23) {
this.hour = 23;
} else if (hour < 0) {
this.hour = 0;
} else {
this.hour = hour;
}
if (minute > 59) {
this.minute = 59;
} else if (minute < 0) {
this.minute = 0;
} else {
this.minute = minute;
}
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
if (hour > 23) {
this.hour = 23;
} else if (hour < 0) {
this.hour = 0;
} else {
this.hour = hour;
}
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
if (minute > 59) {
this.minute = 59;
} else if (minute < 0) {
this.minute = 0;
} else {
this.minute = minute;
}
}
public int getDifferenceInMinutes(DayTime startTime) {
int endMinutes = hour*60+minute;
int startMinutes= startTime.hour*60+startTime.minute;
if (endMinutes>startMinutes){
return endMinutes-startMinutes;
}
if (startMinutes>endMinutes){
return 1440-startMinutes+endMinutes;
}
return 0;
}
public int getTimeInMinutes(){
return hour*60+minute;
}
}
<file_sep>/src/employeeScheduler/model/ScheduleModel.java
package employeeScheduler.model;
import java.time.DayOfWeek;
import java.util.ArrayList;
/**
* Model representing the characteristics of schedule.
*/
public class ScheduleModel {
private ArrayList<Shift> shifts;
private ArrayList<EmployeeModel> employeePreferences;
private Integer scheduleDaysNumber;
public ScheduleModel(ArrayList<Shift> shifts, ArrayList<EmployeeModel> employeePreferences, Integer scheduleDaysNumber) {
this.shifts = shifts;
this.employeePreferences = employeePreferences;
this.scheduleDaysNumber = scheduleDaysNumber;
}
public ArrayList<Shift> getShifts() {
return shifts;
}
public void setShifts(ArrayList<Shift> shifts) {
this.shifts = shifts;
}
public ArrayList<EmployeeModel> getEmployeePreferences() {
return employeePreferences;
}
public void setEmployeePreferences(ArrayList<EmployeeModel> employeePreferences) {
this.employeePreferences = employeePreferences;
}
public Integer getScheduleDaysNumber() {
return scheduleDaysNumber;
}
public void setScheduleDaysNumber(Integer scheduleDaysNumber) {
this.scheduleDaysNumber = scheduleDaysNumber;
}
}
<file_sep>/src/employeeScheduler/model/AcceptanceLevel.java
package employeeScheduler.model;
import java.util.HashMap;
import java.util.Map;
/**
* Enum helping to use specific acceptance Level
*/
public enum AcceptanceLevel {
VERY_LOW(0.01),
LOW(0.1),
MEDIUM(0.4),
HIGH(0.6),
VERY_HIGH(1);
private double value;
private static Map map = new HashMap<>();
private AcceptanceLevel(double value) {
this.value = value;
}
static {
for (AcceptanceLevel acceptanceLevel : AcceptanceLevel.values()) {
map.put(acceptanceLevel.value, acceptanceLevel);
}
}
public static AcceptanceLevel valueOf(int acceptanceLevel) {
return (AcceptanceLevel) map.get(acceptanceLevel);
}
public double getValue() {
return value;
}
}
<file_sep>/README.md
# Employee-Scheduler
Small Java Library - Scheduling tool that allows you to create employee work schedules in easy way.
<file_sep>/src/employeeScheduler/model/ResultingSchedule.java
package employeeScheduler.model;
import java.util.ArrayList;
/**
* Object created by schedule builder. It contains structure of defined work shifts combined with employees.
*/
public class ResultingSchedule {
private ArrayList<Integer>[][] result;
private ArrayList<EmployeeSchedule> employeesSchedules;
private Integer days;
private Integer shifts;
private ArrayList<Integer> maxEmployeesPerShift;
public ResultingSchedule(Integer days, Integer shifts, Integer employeesNumber) {
this.setDays(days);
this.setShifts(shifts);
maxEmployeesPerShift = new ArrayList<>();
employeesSchedules = new ArrayList<>();
for (int i=0;i<employeesNumber;i++){
getEmployeesSchedules().add(new EmployeeSchedule(i));
}
result = new ArrayList[days][shifts];
for (int i = 0; i < days; i++)
for (int j = 0; j < shifts; j++) {
result[i][j] = new ArrayList<>();
}
}
public void addShiftMaxEmployee(Integer shiftNumber, Integer maxEmployees){
maxEmployeesPerShift.add(shiftNumber,maxEmployees);
}
public Integer getMaxEmployeesPerShift(Integer shiftNumber){
return maxEmployeesPerShift.get(shiftNumber);
}
public String toString() {
String stringSchedule = "";
if (getDays() ==0){
return "No schedule";
}
for (int i = 0; i < getShifts(); i++){
for (int j = 0; j < getDays(); j++) {
stringSchedule += result[j][i].toString();
}
stringSchedule += "\n";
}
return stringSchedule;
}
public ArrayList<Integer> getEmployeeListOnShift(Integer day, Integer shift) {
return result[day][shift];
}
public ArrayList<Integer>[][] getResult() {
return result;
}
public void addEmployee(Integer day, Integer shift, Integer employeeID) {
getEmployeesSchedules().get(employeeID).addShift(day,shift);
result[day][shift].add(employeeID);
}
public ArrayList<EmployeeSchedule> getEmployeesSchedules() {
return employeesSchedules;
}
public Integer getDays() {
return days;
}
public void setDays(Integer days) {
this.days = days;
}
public Integer getShifts() {
return shifts;
}
public void setShifts(Integer shifts) {
this.shifts = shifts;
}
}
<file_sep>/src/employeeScheduler/model/EmployeeModel.java
package employeeScheduler.model;
import java.util.ArrayList;
/**
* Model representing the characteristics and preferences of the employee.
*/
public class EmployeeModel {
private ArrayList<EmployeePreferences> preferences;
private Integer dailyWorkTime;
private Integer minWorkingDaysNumber;
private Integer maxWorkingDaysNumber;
private Integer targetWorkingDaysNumber;
private Integer minDayBreakTime;
private Integer minWeekBreakTime;
private Integer currentOvertime;
private Double preferencesAcceptanceLevel;
public EmployeeModel(ArrayList<EmployeePreferences> preferences, Integer dailyWorkTime, Integer minWorkingDaysNumber, Integer maxWorkingDaysNumber, Integer targetWorkingDaysNumber, Integer minDayBreakTime, Integer minWeekBreakTime, Integer currentOvertime, Double preferencesAcceptanceLevel) {
this.preferences = preferences;
this.dailyWorkTime = dailyWorkTime;
this.minWorkingDaysNumber = minWorkingDaysNumber;
this.maxWorkingDaysNumber = maxWorkingDaysNumber;
this.targetWorkingDaysNumber = targetWorkingDaysNumber;
this.minDayBreakTime = minDayBreakTime;
this.minWeekBreakTime = minWeekBreakTime;
this.currentOvertime = currentOvertime;
this.preferencesAcceptanceLevel = preferencesAcceptanceLevel;
}
public ArrayList<EmployeePreferences> getPreferences() {
return preferences;
}
public void setPreferences(ArrayList<EmployeePreferences> preferences) {
this.preferences = preferences;
}
public Integer getDailyWorkTime() {
return dailyWorkTime;
}
public void setDailyWorkTime(Integer dailyWorkTime) {
this.dailyWorkTime = dailyWorkTime;
}
public Integer getMinWorkingDaysNumber() {
return minWorkingDaysNumber;
}
public void setMinWorkingDaysNumber(Integer minWorkingDaysNumber) {
this.minWorkingDaysNumber = minWorkingDaysNumber;
}
public Integer getMaxWorkingDaysNumber() {
return maxWorkingDaysNumber;
}
public void setMaxWorkingDaysNumber(Integer maxWorkingDaysNumber) {
this.maxWorkingDaysNumber = maxWorkingDaysNumber;
}
public Integer getMinDayBreakTime() {
return minDayBreakTime;
}
public void setMinDayBreakTime(Integer minDayBreakTime) {
this.minDayBreakTime = minDayBreakTime;
}
public Integer getMinWeekBreakTime() {
return minWeekBreakTime;
}
public void setMinWeekBreakTime(Integer minWeekBreakTime) {
this.minWeekBreakTime = minWeekBreakTime;
}
public Integer getCurrentOvertime() {
return currentOvertime;
}
public void setCurrentOvertime(Integer currentOvertime) {
this.currentOvertime = currentOvertime;
}
public Integer getTargetWorkingDaysNumber() {
return targetWorkingDaysNumber;
}
public void setTargetWorkingDaysNumber(Integer targetWorkingDaysNumber) {
this.targetWorkingDaysNumber = targetWorkingDaysNumber;
}
public Double getPreferencesAcceptanceLevel() {
return preferencesAcceptanceLevel;
}
public void setPreferencesAcceptanceLevel(Double preferencesAcceptanceLevel) {
this.preferencesAcceptanceLevel = preferencesAcceptanceLevel;
}
}
<file_sep>/src/employeeScheduler/model/Shift.java
package employeeScheduler.model;
import org.jacop.constraints.In;
/**
* Simple class with information about specific work shift.
*/
public class Shift {
private DayTime startTime;
private DayTime endTime;
private Integer minEmployeesNumber;
private Integer maxEmployeesNumber;
public Shift(DayTime startTime, DayTime endTime, Integer minEmployeesNumber, Integer maxEmployeesNumber) {
this.startTime = startTime;
this.endTime = endTime;
this.minEmployeesNumber = minEmployeesNumber;
this.maxEmployeesNumber = maxEmployeesNumber;
}
public DayTime getStartTime() {
return startTime;
}
public void setStartTime(DayTime startTime) {
this.startTime = startTime;
}
public DayTime getEndTime() {
return endTime;
}
public void setEndTime(DayTime endTime) {
this.endTime = endTime;
}
public Integer getMinEmployeesNumber() {
return minEmployeesNumber;
}
public void setMinEmployeesNumber(Integer minEmployeesNumber) {
this.minEmployeesNumber = minEmployeesNumber;
}
public Integer getMaxEmployeesNumber() {
return maxEmployeesNumber;
}
public void setMaxEmployeesNumber(Integer maxEmployeesNumber) {
this.maxEmployeesNumber = maxEmployeesNumber;
}
public Integer getShiftTime(){
return endTime.getDifferenceInMinutes(startTime);
}
public Boolean isNightShift(){
Integer startTimeMinutes = startTime.getHour()*60+startTime.getMinute();
Integer endTimeMinutes = endTime.getHour()*60+endTime.getMinute();
if (endTimeMinutes<startTimeMinutes){
return true;
}
return false;
}
}
| 474516c971892a52501b0f87671da37eff51f762 | [
"Markdown",
"Java"
] | 9 | Java | Yamadads/Employee-Scheduler | 6251ee99bf896a975b1b8c211aa69ce4f846bfb5 | d388b4c0da7ed0e551a2faedc827235319da7a83 |
refs/heads/master | <repo_name>ldmario1996/SimpleMusicPlayerPart1<file_sep>/SimpleMusicPlayer/ViewController.swift
//
// ViewController.swift
// SimpleMusicPlayer
//
// Created by <NAME> on 7/15/16.
// Copyright ยฉ 2016 <NAME>. All rights reserved.
// play va pause nhac
// UISlider and element
// min image, max image
// min, max track Tint
// thumb tint
// thumb image
// slider duration keo
// repeat
//audio.numberofloops
//audio.on, UISwitch
// on repeat -1, off = 0
// khi het bai if repeat =0 -> button change to play
// avaudioplayerdelegate
import UIKit
import AVFoundation
class ViewController: UIViewController,AVAudioPlayerDelegate
{
@IBOutlet weak var lbl_totalTime: UILabel!
@IBOutlet weak var lbl_timeLeft: UILabel!
@IBAction func btn_changemusic(sender: UISlider)
{
audio.currentTime = Double(sender.value) * audio.duration
Slider_duration.setThumbImage(UIImage(named: "thumb.png"), forState: .Normal)
Slider_duration.setThumbImage(UIImage(named: "thumbHightLight.png"), forState: .Highlighted)
}
@IBAction func button_replay(sender: UISwitch)
{
// if outlet_switch.on{
// audio.numberOfLoops = -1
// audio.play()
//
// }
// else {
// audio.numberOfLoops = 0
// audio.stop()
//}
}
@IBAction func btn_stop(sender: UIButton)
{
audio.stop()
audio.currentTime = 0
changeState = true
btn_Play.setImage(UIImage(named:"play.png"), forState: UIControlState.Normal)
}
var changeState:Bool!
@IBOutlet weak var slider_Volume: UISlider!
@IBOutlet weak var btn_Play: UIButton!
@IBAction func slider_Volume(sender: UISlider)
{
audio.volume = sender.value
}
@IBOutlet weak var outlet_switch: UISwitch!
@IBOutlet weak var Slider_duration: UISlider!
var audio = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
audio = try!
AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("katyperry", ofType: ".mp3")!))
audio.play()
audio.delegate = self
addThumbImgForSlider()
btn_Play.setImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
changeState = false
audio.currentTime = 0
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(updateTimeLeft), userInfo: nil, repeats: true)
totalTime()
}
func updateTimeLeft()
{
self.lbl_timeLeft.text = String(format: "%2.2f",
audio.currentTime / 60)
self.Slider_duration.value = Float(audio.currentTime / audio.duration)
}
func totalTime()
{
self.lbl_totalTime.text = String(format: "%2.2f", audio.duration/60)
}
func addThumbImgForSlider()
{
slider_Volume.setThumbImage(UIImage(named: "thumb.png"), forState: .Normal)
slider_Volume.setThumbImage(UIImage(named: "thumbHightLight.png"), forState: .Highlighted)
}
@IBAction func action_Play(sender: UIButton) {
audio.play()
// play and pause
//
changeStatefunc()
}
func changeStatefunc()
{
if changeState == true
{
audio.play()
changeState = false
btn_Play.setImage(UIImage(named:"pause.png"), forState: UIControlState.Normal)
}
else
{
audio.pause()
changeState = true
btn_Play.setImage(UIImage(named:"play.png"), forState: UIControlState.Normal)
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool){
if outlet_switch.on
{
audio.play()
btn_Play.setImage(UIImage(named:"pause.png"), forState: UIControlState.Normal)
}
else
{
btn_Play.setImage(UIImage(named:"play.png"), forState: UIControlState.Normal)
}
}
}
| f94c950ae16a9c94f11d35c92497f3b213374996 | [
"Swift"
] | 1 | Swift | ldmario1996/SimpleMusicPlayerPart1 | f522b35fe6d33f34d4f7e701b5670c3864be24c7 | 16a98ad349e9afc67d36fcede96bcf0e11ce2a91 |
refs/heads/master | <file_sep># Monitorizacion-viga-voladizo
Monitorizacion viga simple en voladizo-ARDUINO & PROCESSING
<file_sep>float lectura;
float b; // ancho viga (cm)
float h; // altura viga (cm)
float I; // Inercia viga (cm^4)
float D; // distancia (cm)
float Mb; // Momento empotramiento (N*cm)
float Vb; // Cortante (N)
float F; // Fuerza aplicada(N)
float Sigma[5];
float Tau[5];
float VonMises[5]; // (N/cm^2)
float y0=0.2;
float y1=0.1;
float y2=0;
float y3=-0.1;
float y4=-0.2;
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
pinMode(12,OUTPUT);
b=2.0; // (cm)
h=0.5; // (cm)
}
void loop() {
int lectura=analogRead(A1); // posicion
int sensorValue = analogRead(A0); //lectura presion
D=pow(3027.4 / lectura, 1.2134); // conversiรณn a centimetro
F=((0.0033*sensorValue-2.1936)*10)*20; //Newtons -> Escalamos x20 la Fuerza
if (F<0)
{
F=0;
}
I=(b*pow(h,3))/12;
Mb=-F*D;
Vb=-F;
Sigma[0]=-Mb*y0/I;
Sigma[1]=-Mb*y1/I;
Sigma[2]=-Mb*y2/I;
Sigma[3]=-Mb*y3/I;
Sigma[4]=-Mb*y4/I;
Tau[0]=Vb/(2*I)*(pow(h,2)/4-pow(y0,2));
Tau[1]=Vb/(2*I)*(pow(h,2)/4-pow(y1,2));
Tau[2]=Vb/(2*I)*(pow(h,2)/4-pow(y2,2));
Tau[3]=Vb/(2*I)*(pow(h,2)/4-pow(y3,2));
Tau[4]=Vb/(2*I)*(pow(h,2)/4-pow(y4,2));
VonMises[0]=sqrt(pow(Sigma[0],2)+3*pow(Tau[0],2));
VonMises[1]=sqrt(pow(Sigma[1],2)+3*pow(Tau[1],2));
VonMises[2]=sqrt(pow(Sigma[2],2)+3*pow(Tau[2],2));
VonMises[3]=sqrt(pow(Sigma[3],2)+3*pow(Tau[3],2));
VonMises[4]=sqrt(pow(Sigma[4],2)+3*pow(Tau[4],2));
//Serial.print(sensorValue);//presion
//Serial.print(",");
Serial.print(D);//posicion
Serial.print(",");
Serial.print(F);
Serial.print(",");
//Serial.print(Mb);
//Serial.print(",");
//Serial.print(Vb);
//Serial.print(",");
Serial.print(VonMises[0]);
Serial.print(",");
Serial.print(VonMises[1]);
Serial.print(",");
Serial.print(VonMises[2]);
Serial.print(",");
Serial.print(VonMises[3]);
Serial.print(",");
Serial.print(VonMises[4]);
Serial.print(",");
Serial.println();
delay(250); // delay in between reads for stability
if (D > 22.5)
{digitalWrite(13,HIGH);
digitalWrite(12,LOW);// do something here
}
else
{digitalWrite(12,HIGH);
digitalWrite(13,LOW);// do something here
}
}
| 76ebac5b7089a823327b37a7d198c80a0cd4123a | [
"Markdown",
"C++"
] | 2 | Markdown | aalsina/Monitorizacion-viga-voladizo | 2d55cfd4320c87e47aa14374a1544e83afd631db | a1fc368859d5f6b410a324c265ad50b0ac16a174 |
refs/heads/master | <file_sep>package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
const (
ACTIVATION_PERIOD = 750
ENFORCEMENT_PERIOD = 950
TARGET_WINDOW = 1000
)
var (
BlockIndex map[int]int
version, block int
verbose bool
RPCHost string
RPCPort int
RPCUsername string
RPCPassword string
)
func BuildURL() string {
return fmt.Sprintf("http://%s:%s@%s:%d", RPCUsername, RPCPassword, RPCHost, RPCPort)
}
func SendHTTPGetRequest(url string, jsonDecode bool, result interface{}) (err error) {
res, err := http.Get(url)
if err != nil {
return err
}
if res.StatusCode != 200 {
log.Printf("HTTP status code: %d\n", res.StatusCode)
return errors.New("Status code was not 200.")
}
contents, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
defer res.Body.Close()
if jsonDecode {
err := JSONDecode(contents, &result)
if err != nil {
return err
}
} else {
result = &contents
}
return nil
}
func JSONDecode(data []byte, to interface{}) error {
err := json.Unmarshal(data, &to)
if err != nil {
return err
}
return nil
}
func SendRPCRequest(method, req interface{}) (map[string]interface{}, error) {
var params []interface{}
if req != nil {
params = append(params, req)
} else {
params = nil
}
data, err := json.Marshal(map[string]interface{}{
"method": method,
"id": 1,
"params": params,
})
if err != nil {
return nil, err
}
resp, err := http.Post(BuildURL(), "application/json", strings.NewReader(string(data)))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
result := make(map[string]interface{})
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
if result["error"] != nil {
errorMsg := result["error"].(map[string]interface{})
return nil, fmt.Errorf("Error code: %v, message: %v\n", errorMsg["code"], errorMsg["message"])
}
return result, nil
}
func GetBlockVersion(block int) (int, error) {
result, err := SendRPCRequest("getblockhash", block)
if err != nil {
return 0, err
}
blockHash := result["result"].(string)
result, err = SendRPCRequest("getblock", blockHash)
if err != nil {
return 0, err
}
result = result["result"].(map[string]interface{})
version := result["version"].(float64)
return int(version), nil
}
func CheckBlocks(minVersion, height, threshold int) (bool, int, int) {
nFound := 0
blockVer := 0
var ok bool
var err error
lastBlock := 0
for i := 0; i < TARGET_WINDOW && nFound < threshold && i >= 0; i++ {
blockVer, ok = BlockIndex[height]
if !ok {
blockVer, err = GetBlockVersion(height)
if err != nil {
log.Fatal("Failed to obtain block version.")
}
BlockIndex[height] = blockVer
}
if blockVer >= minVersion {
nFound++
}
if blockVer == minVersion-1 {
if height > lastBlock {
lastBlock = height
}
}
height--
}
if nFound >= threshold {
return true, nFound, lastBlock
}
return false, nFound, lastBlock
}
func GetVersionBIPString(version int) string {
versionStr := ""
switch version {
case 2:
versionStr = "BIP34"
case 3:
versionStr = "BIP66"
case 4:
versionStr = "BIP65"
default:
versionStr = "NA"
}
return versionStr
}
func main() {
BlockIndex = make(map[int]int)
flag.StringVar(&RPCHost, "rpchost", "127.0.0.1", "The RPC host to connect to.")
flag.IntVar(&RPCPort, "rpcport", 9333, "The RPC port to connect to.")
flag.StringVar(&RPCUsername, "rpcuser", "user", "The RPC username.")
flag.StringVar(&RPCPassword, "rpcpass", "<PASSWORD>", "The RPC password.")
flag.IntVar(&version, "version", 3, "The block version to check.")
flag.IntVar(&block, "block", 810000, "Block height to start checking from.")
flag.BoolVar(&verbose, "verbose", false, "Toggle verbose reporting.")
flag.Parse()
versionStr := GetVersionBIPString(version)
log.Printf("RPC URL: %s", BuildURL())
log.Printf("Checking for block version %d (%s) activation height with start height %d.\n", version, versionStr, block)
bActivated := false
height := block
percentage := float64(0)
quit := false
for {
if !bActivated {
success, found, _ := CheckBlocks(version, height, ACTIVATION_PERIOD)
percentage = float64(found) / TARGET_WINDOW * 100 / 1
if success {
log.Printf("Block %d reached version %d (%s) activation.\n", height+1, version, versionStr)
bActivated = true
}
} else {
success, found, last := CheckBlocks(version, height, ENFORCEMENT_PERIOD)
percentage = float64(found) / TARGET_WINDOW * 100 / 1
if success {
log.Printf("Block %d reached version %d (%s) enforcement.\n", height+1, version, versionStr)
log.Printf("Last version %d block: %d.\n", version-1, last)
quit = true
}
}
if verbose {
blockVer := BlockIndex[height]
log.Printf("Block height: %d Version: %d Percentage: %.2f%%\n", height, blockVer, percentage)
}
if quit {
break
}
height++
}
}
<file_sep># IsSuperMajority Value Checker for Bitcoin and Litecoin
This tool can be used to find the BIP34, BIP65 and BIP66 activation/enforcement values for both Bitcoin and Litecoin. It replicates the IsSuperMajority softfork activation logic. You will need to run the corresponding daemon to retrieve the block information. An example can be found below for Litecoin:
Values can be cross-checked here: https://github.com/litecoin-project/litecoin/blob/master/src/chainparams.cpp#L77
```
>main -block=810000 -rpcport=9332 -version=3 -verbose=false
2017/03/01 16:58:07 RPC URL: http://user:pass@127.0.0.1:9332
2017/03/01 16:58:07 Checking for block version 3 (BIP66) activation height with start height 810000.
2017/03/01 16:58:11 Block 811252 reached version 3 (BIP66) activation.
2017/03/01 16:58:13 Block 811879 reached version 3 (BIP66) enforcement.
2017/03/01 16:58:13 Last version 2 block: 811818.
>main -block=810000 -rpcport=9332 -version=4 -verbose=false
2017/03/01 16:58:30 RPC URL: http://user:pass@127.0.0.1:9332
2017/03/01 16:58:30 Checking for block version 4 (BIP65) activation height with start height 810000.
2017/03/01 17:01:29 Block 916185 reached version 4 (BIP65) activation.
2017/03/01 17:01:33 Block 918684 reached version 4 (BIP65) enforcement.
2017/03/01 17:01:33 Last version 3 block: 918672.
```
Bitcoin:
Values can be cross-checked here: https://github.com/bitcoin/bitcoin/blob/master/src/chainparams.cpp#L74
```
>main -block=20000 -rpcport=8332 -version=2 -verbose=false
2017/03/01 16:55:57 RPC URL: http://user:pass@127.0.0.1:8332
2017/03/01 16:55:57 Checking for block version 2 (BIP34) activation height with start height 20000.
2017/03/01 18:19:09 Block 224413 reached version 2 (BIP34) activation.
2017/03/01 18:20:07 Block 227931 reached version 2 (BIP34) enforcement.
2017/03/01 18:20:07 Last version 1 block: 227835.
>main -block=290000 -rpcport=8332 -version=3 -verbose=false
2017/03/01 16:53:25 RPC URL: http://user:pass@127.0.0.1:8332
2017/03/01 16:53:25 Checking for block version 3 (BIP66) activation height with start height 290000.
2017/03/01 18:02:45 Block 359753 reached version 3 (BIP66) activation.
2017/03/01 18:06:25 Block 363725 reached version 3 (BIP66) enforcement.
2017/03/01 18:06:25 Last version 2 block: 363689.
>main -block=350000 -rpcport=8332 -version=4 -verbose=false
2017/03/01 16:56:58 RPC URL: http://user:pass@127.0.0.1:8332
2017/03/01 16:56:58 Checking for block version 4 (BIP65) activation height with start height 350000.
2017/03/01 17:46:42 Block 387278 reached version 4 (BIP65) activation.
2017/03/01 17:48:39 Block 388381 reached version 4 (BIP65) enforcement.
2017/03/01 17:48:39 Last version 3 block: 388319.
```
This tool supports the following parameters:
```
Usage of main.exe:
-block int
Block height to start checking from. (default 810000)
-rpchost string
The RPC host to connect to. (default "127.0.0.1")
-rpcpass string
The RPC password. (default "<PASSWORD>")
-rpcport int
The RPC port to connect to. (default 9333)
-rpcuser string
The RPC username. (default "user")
-verbose
Toggle verbose reporting.
-version int
The block version to check. (default 3)
``` | e5e8d349775da179db72e181a25e2de2b09ff898 | [
"Markdown",
"Go"
] | 2 | Go | NirvanaNimbusa/IsSuperMajority-checker | 8656d5a2778322d07e84debd48a5a4a2c8f9ed91 | a661955862e6d814d3f735acd0f20db16c0ba4c4 |
refs/heads/main | <repo_name>danielbldr/udemy-courses<file_sep>/complete-react-developer-2021/mosters-rolodex/src/components/search-box/search-box.component.jsx
import React from 'react';
import './search-box.styles.css';
// This is functional component. It gets props and returns HTML
// vs a class component that has state and lifecycle methods.
export const SearchBox = ({ placeholder, handleChange }) => (
<input
className='search'
type='search'
placeholder={placeholder}
onChange={handleChange}
/>
)
| 0c8a383ab6af3f3916c4cd4edc60b6c65c4e37ce | [
"JavaScript"
] | 1 | JavaScript | danielbldr/udemy-courses | e433ae6c0dfa1735f50faea802b1facf47b420d1 | 27535c3300922f94690a0adcd434044917acbac5 |
refs/heads/master | <repo_name>ElisabethCheston/KitespotsSweden<file_sep>/README.md
# MS2 - Kitespots Sweden
A map to locate all the current kitesurfing spots in Sweden.
### Background
The core focus for this MS2 project was to create functional JavaScript features for user to interact with. Since JavaScript was totally new to me, I wanted to keep it simple and focus on understanding the coding process. This is a resubmission, improving the clarity of the page and its use. Added features;
* Starting popup window with purpose of website.
* Information button of how to use the site in the header.
* Attribution button in the header.
* 3 buttons to external kitesurfing communities in Sweden.
* 2 videos on start popup of kitesurfing and snowkiting.
## UX
This webpage should provide all kitesurfers (and windsurfer/surfer) easy access to all the current functional spots in Sweden where you can surf. Provide maps so user can analyze the conditions of for example lounging area, sea depth, which direction the beach is facing. Also provide regions and cities to give the user a sense of the areas.
### Research
Since there is no updated list of all current functional kitespots, Iโve researched old once as well as new once from word of mouth. Then created a new geojson file for all usable kitespots in geojson.io. Spots that has been excluded are for reasons like private property, unfunctional launching area, rocky water surface, etc.
### User Stories
* As a user, I would like have some basic information on the site, to know how to use it and what its purpose is.
* As a kitesurfer, I want to be presented with an over view of all spots on the map, to get a sense of how they are distributed over the country.
* As a kitesurfer, I want to be able to search for specific spots by name, to easily find it on the map.
* As a kitesurfer, I want to be able to analyze the spots surrounding, to determine if it fits my needs.
* As a kitesurfer, I want to see a scale on maps, to know the proportions of the beach surroundings.
* As a kitesurfer, I would like to know of some surfing communities, to check in and get in contact with other surfers.
* As a kitesurfer, I would like to know what regions the kitespots are locaded in, to get a sense of the areas.
### Wireframes
PDF files for;
* [Desktop Start Modal](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/balsamiqWireframes/MS2%20wireframe%20Desktop%20Start%20View.pdf)
* [Desktop](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/balsamiqWireframes/MS2%20wireframe%20Desktop.pdf)
* [Ipad Start Modal](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/balsamiqWireframes/MS2%20wireframe%20Ipad%20Start%20View.pdf)
* [Ipad](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/balsamiqWireframes/MS2%20wireframe%20Ipad.pdf)
* [Smartphone Start Modal](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/balsamiqWireframes/MS2%20wireframe%20Smartphone%20Start%20View.pdf)
* [Smartphone](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/balsamiqWireframes/MS2%20wireframe%20Smartphone.pdf)
### Features
Feature functions in the project:
#### Existing Features
* **Popup Start Modal** - The first time user visit the site, a popup window appears with information about the site. Includes 2 youtube videos to play in the popup window.
* **Zooms** - On the maps right side user can zoom in and out of the map window to better research the area.
* **Search Control** โ A dropdown list (in the top right corner) that presents all kitespots. Since it can be hard to know the spelling of some places and user could have heard it by word of mouth, a dropdown list is easier to search for the name instead of a control user have to write in the names.
* **Zoom in to selected spots** - Upon selected spot the maps zooms in to the position and the marker popups with information.
* **Cluster spots** - When user first load the page the first thing they can see on the map is cluster spots of all the kitespots. It groups the spots together in groups depending on the projection to make the map less 'messy' or cluttery'. When clicked on the or zoomed in to the cluster divides up to smaller groups until the actual markers shows.
* **Control Layer Toggler** โ That contains all the base layer and overlayers. Upon hovering the icon opens and layers can be selected.
* **Base layers** - Gives the users the option to choose different maps to view the kitespots in. Only one map can be displayed at a time.
* **Overlayer** - Gives the user the option to see cities and regions on map. Both layers can be selected simultaneously and popups work.
* **Kitespot popups with image and link** - Popup opens automatic upon selected.
* **City popups with image and link** - Shows the users the position of Swedish cities. The markers do not have cluster on map. Popup include text, picture and link to google.
* **Region popups** - Shows the users the position of Swedish regions as polygons. In the middle of the regions is a popup with region name.
* **Geolocator** - Shows users position on map if user have given permission to it in browser.
* **Scale** - In the bottom right corner user can see the scale that changes value depending on the zoom level.
* **Image popup fit screen** - In order for the popup not to get cut upon open.
* **bringToFront function** - In order to put the city markers on top of polygon layer to make them selectable.
* **Information Button & Modal** - A button in top left header that opens a popup modal providing the user with information of how to use the page.
* **Home function** - A link in the website name that brings you back to the original view.
* **Attribution Button & Modal** - A button in the top right header that opens a popup modal where user can see the attribution for the website.
* **Link to Surfskolan** - Link at bottom left footer to Surfskolans youtube.
* **Link to Surfzone** - Link at bottom center footer to Surfzone youtube.
* **Link to Kiteboardcenter** - Link at bottom right footer to Kiteboardcenter youtube.
#### Features Left to Implement
* **Weather prognose** โ Some type of weather prognoses would be nice to implement. Current or future weather information like wind speed for kitesurfing, as well as information on weather conditions, water temperature, air temperature preferably for each kitespot. To get accurate information you need to use backend programs as well as payed services.
* **Kitespot information** โ Implement information on the different spots like launching size, beach condition (gras, sand, rocks..), water dept, as well as parking, GPS connection (a lot of areas donโt have a good reception).
### Technologies Used
These are the different languages, frameworks, libraries, and any other tools that you have used to construct this project.
[Leaflet](http://leaflet.com) - Open-source JavaScript library for interactive maps. Works on all major desktops and mobile platforms.
[ESRI](http://esri.com) - Maps and map tools to work with Leaflet.
[GeoJson](http://geojson.io/) - For creating all kitespots in Sweden.
[GeoJSONLint](https://geojsonlint.com/) - For validation of geoJson data.
[HTML](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5) - Used to create map element to show map and to hold and load necessary scripts/css/plugins/apis/etc., files from map and load them in the right order.
[JavaScript](https://www.javascript.com/) - Used to create functions, elements, controls, run json, etc. Tight all the project parts (JS files, geoJson, images, etc.) together in map.js and channel it for viewing with help of map div in HTML page.
[jQuery](http://jquery.com) - The project uses jQuery to simplify DOM manipulation. Also, to make some functions easier to call.
[CSS](https://sv.wikipedia.org/wiki/Cascading_Style_Sheets) - To custom style the maps and controllerโs size, fonts, color and etc.
[Balsamiq](https://balsamiq.com/) - To structure and plan the webpage, and to present it a wireframe for desktops and mobile devices.
[Jigsaw](https://jigsaw.w3.org/css-validator/) - To validate CSS and HTML.
[JSHint](https://jshint.com/) - To validate JavaScript.
[GitPod](http://gitpod.com) - An open-source platform used to create the project with code related programs. Making commit documentation and push them to GitHub.
[GitHub](http://github.com) - For creating and storing the repository as well as deploying the project live.
### Testing
#### Responsive testing
[**Errors in Dev Tool Console.pdf**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/responsiveTesting/errorDevTools.pdf)
[**Errors in Dev Tool Console.png**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/responsiveTesting/errorDevTool.png)
#### Manual testing
[ **UX Tests**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/responsiveTesting/userstories.pdf) - Tests of user stories.
[**Jigsaw CSS Validation Result for Kitespots Sweden.**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jigsawCSS.png)
[**Jigsaw HTML Validation Result for Kitespots Sweden.**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jigsawHTML.png) - And the HTML [Warnings.](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jigsawHTMLwarnings.png)
**JSHint Reports**
[**JSHint Test Result for map.js**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jshintMap.png)
[**JSHint Test Result for kitespots.js**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jshintKitespots.png)
[**JSHint Test Result for cities.js**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jshintCities.png)
[**JSHint Test Result for scale.js**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jshintScale.png)
[**JSHint Test Result for headerModal.js**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jshintHeader.png)
[**JSHint Test Result for startmodal.js**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/validation/jshintStart.png)
#### Describe use on different browsers
[**Browsers and sizes**](https://github.com/ElisabethCheston/KitespotsSweden/blob/8f8a2fd8f4aaac6963aa374dcecf937b641cd26d/responsiveTesting/testingRespons.pdf)
#### Bugs or problems
* [**Deprecation for 'window.webStoreageInfo'**](https://github.com/ElisabethCheston/KitespotsSweden/blob/2cf3f47bca1f22db1c5fee6984cf43a8e539d65e/responsiveTesting/videoStoage.png) - In reguards to the videos showing in start modal. Videos work fine to my knowledge and according to tutors I should just write it up as a bug.
* [**Zoom in to Hybrid/Satellite layer**](https://github.com/ElisabethCheston/KitespotsSweden/blob/2cf3f47bca1f22db1c5fee6984cf43a8e539d65e/responsiveTesting/zoomError.png) - The dev tools through multiple error (as I understod it) due to a bug that wont stop calling on zoom in.
* **Error message for (index):1** - In console error message "Unchecked runtime.lastError: The message port closed before a response was received.". In conversations with tutors, they said it's some type of bug for the <!DOCTYPE html> that can't be solved.
* **Error message** ( "=> only available in ES6 (use 'esversion: 6')" ) in JSHint when => is used in Leaflet. Solved with "// jshint esversion:6" in the JavaScript files for JSHint to ignore the error.
* **Letter "L"** for Leaflet, throught a warning of "undefined" in JSHint.
* **Json files** - In JSHint sees geojson files as undefined.
* **GeoJson files** - Labeled cities and kitespots files as ".json", but got error messages. Mentor told me, just to assign them as ".js" files to avoid error.
* **HTML Validation** When validating index.html I get error messages for "<!DOCTYPE html>" and "</html>" that tutors said was a bug.
### Deployment
To deploy my project on GitHub from Git Pod:
1. Go to Code Institutes gitpod-full-template on Git Hub
2. Click on the button โUse this templateโ to the left of the Gitpod button in button row. to create a new project
3. Create a new repository from template. Make sure that is my gitpod account is selected and shown in the โOwnerโ window.
4. Choose a name of your repository (I choose โKitespotsSwedenโ).
5. I let the โPublicโ button be selected and click โCreate repository from templateโ-button at the bottom of the page.
6. Once the GitHub done creating the project, I push the button โGitPodโ to load the project in GitPod.
7. Run โpython3 -m http.serverโ to connect to server.
8. Initialized Git with writing git init command in the terminal.
9. Create the project and commit often files/folders to GitHub by;
- git add .
- git commit -m "Initial commit"
- git push -u
10. Deployment on GitHub Pages;
11. Go to โSettingsโ of the project in GitHub.
12. Scroll down to GitHub Pages.
13. Under Source click on โNoneโ and select the โmasterโ, and push โSaveโ.
#### Repository Link
Click the link below to run my project in the live environment:
https://elisabethcheston.github.io/KitespotsSweden/
#### Run project locally
1. Go to https://github.com/ElisabethCheston/
2. Click on Repositories in top menu.
3. Find the project you like to open and click on it.
4. In the menu above the project folders/files you have a button called โCodeโ, click on it.
5. Dropdown menu shows options โCloneโ, โOpen with GitHub Desktopโ and โDownload ZIPโ.
6.Clone;
- Choose the HTTPS option under the Clone icon.
- Click on the copy icon to the right of the link address.
- Open the directory in your workstation where you like to store the cloned project.
- In the terminal window write; โgit cloneโ + clone url.
- Push enter.
7. Download ZIP;
- Open the zipped file.
- Move the files to the directory of choice in your workstation project.
#### Run project live
1. Go to โSettingsโ of my project in Git Hub.
2. Scroll down to Git Pages where you see the message โYour site is publishedโฆ. โ
3. Click on the url or copy and paste it in your browser.
### Credits
**Content**
- [Creating geolocator](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API)
- [Creating the basic search engine](https://www.codota.com/code/javascript/functions/leaflet/DomUtil)
- [To modify the search engine](https://stackoverflow.com/questions/35772717/searching-markers-with-leaflet-control-search-from-drop-down-list)
- [Creating clustering markers in Leaflet](https://github.com/Leaflet/Leaflet.markercluster)
- [How to add GeoJson to Leaflet ](https://leafletjs.com/examples/geojson/)
- [Example of editing](https://leafletjs.com/reference-1.7.1.html#geojson)
- [Add markers to control](https://leafletjs.com/examples/layers-control/)
- [Modify the markers in the layer control](https://esri.github.io/esri-leaflet/examples/layers-control.html)
- [Add custom markers](https://leafletjs.com/examples/custom-icons/)
- [Polygon overlay](https://gis.stackexchange.com/a/385670/175494) from [Falke Design](http://falke-design.bplaced.net/)
- [Basemaps in ESRI](https://www.arcgis.com/apps/Cascade/index.html?appid=c777765671c44a21885ff957c6dc2357)
- [Fit popup image on map](https://jsfiddle.net/09pe8ko6/)
- [The popup Start modal](https://www.w3schools.com/jsref/prop_win_localstorage.asp)
- [Information & Attribution modal](https://www.w3schools.com/howto/howto_css_modals.asp)
- [Video playing in start modal](https://leafletjs.com/examples/video-overlay/)
**Media**
* Logo pictures:
- [Surfzone](https://github.com/ElisabethCheston/KitespotsSweden/blob/2cf3f47bca1f22db1c5fee6984cf43a8e539d65e/images/surfzone.png)
- [Surfskolan Crew](https://github.com/ElisabethCheston/KitespotsSweden/blob/2cf3f47bca1f22db1c5fee6984cf43a8e539d65e/images/surfskolan.png)
- [Kiteboardcenter](https://github.com/ElisabethCheston/KitespotsSweden/blob/2cf3f47bca1f22db1c5fee6984cf43a8e539d65e/images/kiteboardcenter.svg)
* Videos:
- [Kitesurfing - Gotland, Sweden by <NAME>](https://www.youtube.com/watch?v=w_CF4NYWq-8)
- [Sweden Snowkite heaven by Surfskolan Crew](https://www.youtube.com/watch?v=q1GcZsnPOhk)
* City pictures:
[Stockholm](https://www.umultirank.org/export/sites/default/.galleries/generic-images/Others/Winter-Calendar/stockholm-3897532_1280.jpg_2040981648.jpg)
[Gรถteborg](https://bokmassan.se/uploads/2019/03/goteborg-foto-anders-wester-1024x600-webb.jpg)
[Malmรถ](https://www.sgbc.se/app/uploads/2020/05/V%C3%A4stra-Hamnen-Malm%C3%B6-Foto-Ossian-K-Olsson.jpg)
[Uppsala](https://uppsalasystemvetare.se/wp-content/uploads/2017/05/53130_sweden_uppsala_sweden.jpg)
[รrebro](https://www.stjarnkliniken.com/web/wp-content/uploads/2020/08/occ88rebro-1080x675.jpg")
[Linkรถping](https://www.linkoping.se/imagevault/publishedmedia/lfuv2nqkwbhmxreq8f9n/DJI_0040_SMALL_MW.jpg)
[Helsingborg](https://hallbartbyggande.com/wp-content/public_html/2018/06/Helsingborg.jpg)
[Jรถnkรถping](https://www.jonkoping.se/images/18.f356a12169ec9d53d461a2/1554896047962/(2)%20(2)%20Jkpg_City_Sunset_Lusare_Kallare_300dpi.jpg)
[Umeรฅ](https://www.dagensinfrastruktur.se/wp-content/uploads/sites/3/2018/03/umeas-bild.jpg)
[Karlstad](https://resources.mynewsdesk.com/image/upload/c_limit,dpr_2.625,f_auto,h_700,q_auto,w_380/lzunurrffxlrae0znft0.jpg)
[Gรคvle](https://svenskpress.se/articles/view/wwwdocs/thumb/thumb.php?src=/wwwdocs/_common_media/article_photos/11344/40924.jpg&w=640)
[Vรคxjรถ](https://imengine.gota.infomaker.io/?uuid=72e85f25-9984-5d0c-9d5c-6ff2b88819c3&width=960&height=480&type=preview&source=false&q=90&z=100&x=0.000&y=0.125&crop_w=1.000&crop_h=0.750&function=cropresize)
[Halmstad](https://resources.mynewsdesk.com/image/upload/c_limit,dpr_2.625,f_auto,h_700,q_auto,w_360/uc9hugazpv5pkimvvjj23g.jpg)
[Luleรฅ](https://www.christineabroad.com/images//2020/04/att-go%CC%88ra-i-lulea%CC%8A.jpg)
[รstersund](https://resources.mynewsdesk.com/image/upload/c_limit,dpr_2.625,f_auto,h_700,q_auto,w_360/v3yxesvrbutxj3er3f9m.jpg)
[Trollhรคttan](https://www.erasweden.com/media/3539/trollhattan2019.jpg?width=1364&height=1000&mode=crop&upscale=true&quality=67)
[Kalmar](https://i.pinimg.com/originals/f2/5c/97/f25c9789abe7e1cf6961929eb555f99c.jpg)
[Falun](https://www.grantthornton.se/globalassets/1.-member-firms/sweden/images/photos/offices/open-graph-image/falun_1200x627.jpg)
[Karlskrona](https://www.karlskrona.se/globalassets/kommun-och-politik/sa-arbetar-vi-med/trygghet-och-sakerhet/karlskrona-stad.jpeg?mode=page-intro-medium)
[Nykรถping](https://drivkraft.ey.se/wp-content/uploads/2018/06/Nyko%CC%88ping-870x489.jpg)
[Visby](https://lp-cms-production.imgix.net/features/2017/03/visby-0c2723f2c195.jpg)
[Jรถnkรถping](https://media.runtvattern.se/Huskvarna-495x389.jpg)
[Hรคrnรถsand](https://resources.mynewsdesk.com/image/upload/ar_16:9,c_fill,dpr_auto,f_auto,g_auto,q_auto,w_864/okqex5jl534n2m6nmubn.jpg)
[Norrkรถping](https://thumb.mp-farm.com/91674072/preview.jpg)
[Sundsvall](https://blog.hotelspecials.se/wp-content/uploads/sites/8/2018/02/shutterstock_512158378-1170x632.jpg")
[Borรฅs](https://www.boras.se/images/18.77edf482158fdcbba45b9e35/1482150364114/flygvybor%C3%A5s.jpg)
[Borlรคnge](https://www.fjellfotografen.se/photo/large/Flygfoto_%C3%B6ver_Borl%C3%A4nge_@20140425_TOJ1082.jpg)
[Mรถlndal](https://upload.wikimedia.org/wikipedia/commons/a/a7/M%C3%B6lndal.jpg)
[Kristianstad](https://www.atea.se/media/5349/9442140-kristianstad.jpg?anchor=center&mode=crop&width=800&height=600&rnd=132513050210000000)
[Skellefteรฅ](https://svv-cdn.azureedge.net/media/Default/News/Skellefte%C3%A5%20flygbild.jpg)
[รrnskรถldsvik](https://www.fjellfotografen.se/photo/large/Flygfoto_%C3%B6ver_%C3%96rnsk%C3%B6ldsvik_@20100906_TOJ7682.jpg)
[Vรคnersborg](https://scanmagazine.co.uk/content/uploads/2016/01/01_TRO1.jpg)
[Kiruna](https://hallbartbyggande.com/wp-content/public_html/2018/09/Kiruna_hogre_medeltemperatur.jpg)
[Hรถganรคs](https://resources.mynewsdesk.com/image/upload/ar_16:9,c_fill,dpr_auto,f_auto,g_auto,q_auto,w_864/udcno8bhfmgrr6ynnt36.jpg)
[Kinna](https://upload.wikimedia.org/wikipedia/commons/f/ff/Town_of_Skene_Sweden.jpg)
[Mariestad](https://static.lokalguiden.se/filter/960x540,,85,cover/uploads/articles/83/2cbdb2f6fd280e7d4b0a6f025001284d.jpg)
[Mjรถlby](https://www.mjolby.se/images/18.2884097b148c203dedf421d/1413969404484/S%C3%B6rby%20flygbild%20beskuren.jpg)
[Bollnรคs](https://www.bollnas.se/images/Aktuellt/2020/Bolln%C3%A4s_framtid_%C3%A4r_din_webb.jpg)
[Mora](https://www.actic.se/app/uploads/2019/02/Morastad-1080x549.jpg)
[Ulricefhamn](https://www.vandrarhem.online/bilder/stad/84/vandrarhem-ulricehamn.jpg)
[Tibro](https://www.fjellfotografen.se/photo/large/Flygfoto_%C3%B6ver_Tibro_@20160601_TOJ9796.jpg)
[Jรถnkรถping](https://media.husmanhagberg.se/cms/2019/11/hero-kontor-mullsjo-habo.jpg)
[Tidaholm](https://www.tidaholm.se/images/18.5a594813169903f99b6c4783/1553516191735/turbinhuson_och_tidan.jpg)
[Strรถmstad](https://drivkraft.ey.se/wp-content/uploads/2018/06/Stro%CC%88mstad-870x489.jpg)
[Haparanda](https://www.fjellfotografen.se/photo/large/Flygbild_%C3%B6ver_Haparanda_@20100907_TOJ8266.jpg)
[Hjo](https://anhede.se/wp-content/uploads/2015/06/aerial-photo-hjo-sweden-drone-photographer.jpg)
[Kungsรถr](https://kungsor.se/images/200.3d6b838b15b14f2118415d1d/1490776416734/20161102_Dronarperspektiv_montage_REX_master-72dpi.jpg)
[Vรฅrgรฅrda](https://brfbjorkangen.se/wp-content/uploads/2019/09/Torget.jpg)
[Hjรคrup](https://i.pinimg.com/originals/27/8b/97/278b97b1378e83b899716eabb12b4ce8.jpg)
**Acknowledgements**
Inspiration for this project from;
* [Kiteboardcenter](http://kiteboardcenter.se/)
* [Surfzone](https://www.surfzone.se/forums/forum/kitesurfing/)
* Kitesurfing friend
### LINKS:
[Example of README.md](https://github.com/Code-Institute-Solutions/readme-template/blob/master/README.md) -As a guideline to write README file.
[Markdown Cheatsheet](https://guides.github.com/features/mastering-markdown/) -For reference
[OpendataSoft](https://public.opendatasoft.com/explore/?sort=modified) -Providing geojson data for Sweden.
[Geographic Information Systems](https://gis.stackexchange.com/) -For tips on features.
[Google](https://google.com/) -To search for pictures and relevant data.
<file_sep>/js/cities.js
const cities = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Stockholm",
"city": "Stockholm",
"capital": "primary",
"population": "972647",
"image": "https://www.umultirank.org/export/sites/default/.galleries/generic-images/Others/Winter-Calendar/stockholm-3897532_1280.jpg_2040981648.jpg",
"cityPic": "stockholm.jpg",
"id": "1752425602"
},
"geometry": {
"type": "Point",
"coordinates": [
18.0686,
59.32
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Gothenburg",
"capital": "admin",
"population": "600473",
"image": "https://bokmassan.se/uploads/2019/03/goteborg-foto-anders-wester-1024x600-webb.jpg",
"cityPic": "goteborg.jpg",
"id": "1752059374"
},
"geometry": {
"type": "Point",
"coordinates": [
11.981,
57.6717
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Skรฅne",
"city": "Malmรถ",
"capital": "admin",
"population": "321845",
"image": "https://www.sgbc.se/app/uploads/2020/05/V%C3%A4stra-Hamnen-Malm%C3%B6-Foto-Ossian-K-Olsson.jpg",
"cityPic": "malmo.jpg",
"id": "1752705818"
},
"geometry": {
"type": "Point",
"coordinates": [
13.0214,
55.5932
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Uppsala",
"city": "Uppsala",
"capital": "admin",
"population": "164535",
"image": "https://uppsalasystemvetare.se/wp-content/uploads/2017/05/53130_sweden_uppsala_sweden.jpg",
"cityPic": "uppsala.jpg",
"id": "1752953686"
},
"geometry": {
"type": "Point",
"coordinates": [
17.6389,
59.8498
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคstmanland",
"city": "Vรคsterรฅs",
"capital": "admin",
"population": "127799",
"image": "https://drivkraft.ey.se/wp-content/uploads/2018/06/Va%CC%88stera%CC%8As-870x489.jpg",
"cityPic": "vasteras.jpg",
"id": "1752826955"
},
"geometry": {
"type": "Point",
"coordinates": [
16.5422,
59.6173
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "รrebro",
"city": "รrebro",
"capital": "admin",
"population": "125817",
"image": "https://www.stjarnkliniken.com/web/wp-content/uploads/2020/08/occ88rebro-1080x675.jpg",
"cityPic": "orebro.jpg",
"id": "1752223019"
},
"geometry": {
"type": "Point",
"coordinates": [
15.1965,
59.2669
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "รstergรถtland",
"city": "Linkรถping",
"capital": "admin",
"population": "114582",
"image": "https://www.linkoping.se/imagevault/publishedmedia/lfuv2nqkwbhmxreq8f9n/DJI_0040_SMALL_MW.jpg",
"cityPic": "linkoping.jpg",
"id": "1752963378"
},
"geometry": {
"type": "Point",
"coordinates": [
15.6257,
58.4094
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Skรฅne",
"city": "Helsingborg",
"capital": "minor",
"population": "112496",
"image": "https://hallbartbyggande.com/wp-content/public_html/2018/06/Helsingborg.jpg",
"cityPic": "helsingborg.jpg",
"id": "1752789933"
},
"geometry": {
"type": "Point",
"coordinates": [
12.721,
56.0424
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Jรถnkรถping",
"city": "Jรถnkรถping",
"capital": "admin",
"population": "89780",
"image": "https://www.jonkoping.se/images/18.f356a12169ec9d53d461a2/1554896047962/(2)%20(2)%20Jkpg_City_Sunset_Lusare_Kallare_300dpi.jpg",
"cityPic": "jkoping.jpg",
"id": "1752079041"
},
"geometry": {
"type": "Point",
"coordinates": [
14.165,
57.7713
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคsterbotten",
"city": "Umeรฅ",
"capital": "admin",
"population": "89607",
"image": "https://www.dagensinfrastruktur.se/wp-content/uploads/sites/3/2018/03/umeas-bild.jpg",
"cityPic": "umea.jpg",
"id": "1752273881"
},
"geometry": {
"type": "Point",
"coordinates": [
20.2706,
63.8285
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคrmland",
"city": "Karlstad",
"capital": "admin",
"population": "74141",
"image": "https://resources.mynewsdesk.com/image/upload/c_limit,dpr_2.625,f_auto,h_700,q_auto,w_380/lzunurrffxlrae0znft0.jpg",
"cityPic": "karlstad.jpg",
"id": "1752502445"
},
"geometry": {
"type": "Point",
"coordinates": [
13.4999,
59.3671
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Gรคvleborg",
"city": "Gรคvle",
"capital": "admin",
"population": "68635",
"image": "https://svenskpress.se/articles/view/wwwdocs/thumb/thumb.php?src=/wwwdocs/_common_media/article_photos/11344/40924.jpg&w=640",
"cityPic": "gavle.jpg",
"id": "1752586931"
},
"geometry": {
"type": "Point",
"coordinates": [
17.1666,
60.667
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Kronoberg",
"city": "Vรคxjรถ",
"capital": "admin",
"population": "59600",
"image": "https://imengine.gota.infomaker.io/?uuid=72e85f25-9984-5d0c-9d5c-6ff2b88819c3&width=960&height=480&type=preview&source=false&q=90&z=100&x=0.000&y=0.125&crop_w=1.000&crop_h=0.750&function=cropresize",
"cityPic": "vaxjo.jpg",
"id": "1752263370"
},
"geometry": {
"type": "Point",
"coordinates": [
14.8167,
56.8837
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Halland",
"city": "Halmstad",
"capital": "admin",
"population": "55657",
"image": "https://resources.mynewsdesk.com/image/upload/c_limit,dpr_2.625,f_auto,h_700,q_auto,w_360/uc9hugazpv5pkimvvjj23g.jpg",
"cityPic": "halmstad.jpg",
"id": "1752392511"
},
"geometry": {
"type": "Point",
"coordinates": [
12.8556,
56.6718
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Norrbotten",
"city": "Luleรฅ",
"capital": "admin",
"population": "48749",
"image": "https://www.christineabroad.com/images//2020/04/att-go%CC%88ra-i-lulea%CC%8A.jpg",
"cityPic": "lulea.jpg",
"id": "1752765449"
},
"geometry": {
"type": "Point",
"coordinates": [
22.1915,
65.5838
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Jรคmtland",
"city": "รstersund",
"capital": "admin",
"population": "46178",
"image": "https://resources.mynewsdesk.com/image/upload/c_limit,dpr_2.625,f_auto,h_700,q_auto,w_360/v3yxesvrbutxj3er3f9m.jpg",
"cityPic": "ostersund.jpg",
"id": "1752026711"
},
"geometry": {
"type": "Point",
"coordinates": [
14.65,
63.1833
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Trollhรคttan",
"capital": "minor",
"population": "44543",
"image": "https://www.erasweden.com/media/3539/trollhattan2019.jpg?width=1364&height=1000&mode=crop&upscale=true&quality=67",
"cityPic": "trollhattan.jpg",
"id": "1752863731"
},
"geometry": {
"type": "Point",
"coordinates": [
12.3,
58.2671
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Kalmar",
"city": "Kalmar",
"capital": "admin",
"population": "41110",
"image": "https://i.pinimg.com/originals/f2/5c/97/f25c9789abe7e1cf6961929eb555f99c.jpg",
"cityPic": "kalmar.jpg",
"id": "1752640618"
},
"geometry": {
"type": "Point",
"coordinates": [
16.3218,
56.6694
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Dalarna",
"city": "Falun",
"capital": "admin",
"population": "36477",
"image": "https://www.grantthornton.se/globalassets/1.-member-firms/sweden/images/photos/offices/open-graph-image/falun_1200x627.jpg",
"cityPic": "falun.jpg",
"id": "1752939220"
},
"geometry": {
"type": "Point",
"coordinates": [
15.647,
60.613
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Blekinge",
"city": "Karlskrona",
"capital": "admin",
"population": "35212",
"image": "https://www.karlskrona.se/globalassets/kommun-och-politik/sa-arbetar-vi-med/trygghet-och-sakerhet/karlskrona-stad.jpeg?mode=page-intro-medium",
"cityPic": "karlskrona.jpg",
"id": "1752316086"
},
"geometry": {
"type": "Point",
"coordinates": [
15.296,
56.203
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Sรถdermanland",
"city": "Nykรถping",
"capital": "admin",
"population": "33546",
"image": "https://drivkraft.ey.se/wp-content/uploads/2018/06/Nyko%CC%88ping-870x489.jpg",
"cityPic": "nykoping.jpg",
"id": "1752377083"
},
"geometry": {
"type": "Point",
"coordinates": [
17.0185,
58.7582
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Gotland",
"city": "Visby",
"capital": "admin",
"population": "24693",
"image": "https://lp-cms-production.imgix.net/features/2017/03/visby-0c2723f2c195.jpg",
"cityPic": "visby.jpg",
"id": "1752027172"
},
"geometry": {
"type": "Point",
"coordinates": [
18.3071,
57.629
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Jรถnkรถping",
"city": "Huskvarna",
"population": "22000",
"image": "https://media.runtvattern.se/Huskvarna-495x389.jpg",
"cityPic": "huskvarna.jpg",
"id": "1752552539"
},
"geometry": {
"type": "Point",
"coordinates": [
14.2756,
57.782
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคsternorrland",
"city": "Hรคrnรถsand",
"capital": "admin",
"population": "18624",
"image": "https://resources.mynewsdesk.com/image/upload/ar_16:9,c_fill,dpr_auto,f_auto,g_auto,q_auto,w_864/okqex5jl534n2m6nmubn.jpg",
"cityPic": "harnosand.jpg",
"id": "1752644953"
},
"geometry": {
"type": "Point",
"coordinates": [
17.9379,
62.6323
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "รstergรถtland",
"city": "Norrkรถping",
"capital": "minor",
"population": "88639",
"image": "https://thumb.mp-farm.com/91674072/preview.jpg",
"cityPic": "norrkoping.jpg",
"id": "1752803583"
},
"geometry": {
"type": "Point",
"coordinates": [
16.1787,
58.5954
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคsternorrland",
"city": "Sundsvall",
"capital": "minor",
"population": "73389",
"image": "https://blog.hotelspecials.se/wp-content/uploads/sites/8/2018/02/shutterstock_512158378-1170x632.jpg",
"cityPic": "sundsvall.jpg",
"id": "1752024232"
},
"geometry": {
"type": "Point",
"coordinates": [
17.3167,
62.4001
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Borรฅs",
"capital": "minor",
"population": "65008",
"image": "https://www.boras.se/images/18.77edf482158fdcbba45b9e35/1482150364114/flygvybor%C3%A5s.jpg",
"cityPic": "boras.jpg",
"id": "1752555835"
},
"geometry": {
"type": "Point",
"coordinates": [
12.92,
57.7304
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Dalarna",
"city": "Borlรคnge",
"capital": "minor",
"population": "39422",
"image": "https://www.fjellfotografen.se/photo/large/Flygfoto_%C3%B6ver_Borl%C3%A4nge_@20140425_TOJ1082.jpg",
"cityPic": "borlange.jpg",
"id": "1752944924"
},
"geometry": {
"type": "Point",
"coordinates": [
15.4167,
60.4833
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Mรถlndal",
"capital": "minor",
"population": "37233",
"image": "https://upload.wikimedia.org/wikipedia/commons/a/a7/M%C3%B6lndal.jpg",
"cityPic": "molndal.jpg",
"id": "1752307790"
},
"geometry": {
"type": "Point",
"coordinates": [
12.0139,
57.6542
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Skรฅne",
"city": "Kristianstad",
"capital": "minor",
"population": "32188",
"image": "https://www.atea.se/media/5349/9442140-kristianstad.jpg?anchor=center&mode=crop&width=800&height=600&rnd=132513050210000000",
"cityPic": "kristianstad.jpg",
"id": "1752606470"
},
"geometry": {
"type": "Point",
"coordinates": [
14.1333,
56.0337
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคsterbotten",
"city": "Skellefteรฅ",
"capital": "minor",
"population": "31311",
"image": "https://svv-cdn.azureedge.net/media/Default/News/Skellefte%C3%A5%20flygbild.jpg",
"cityPic": "skelleftea.jpg",
"id": "1752233025"
},
"geometry": {
"type": "Point",
"coordinates": [
20.95,
64.7721
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคsternorrland",
"city": "รrnskรถldsvik",
"capital": "minor",
"population": "27749",
"image": "https://www.fjellfotografen.se/photo/large/Flygfoto_%C3%B6ver_%C3%96rnsk%C3%B6ldsvik_@20100906_TOJ7682.jpg",
"cityPic": "ornskoldsvik.jpg",
"id": "1752250773"
},
"geometry": {
"type": "Point",
"coordinates": [
18.7167,
63.318
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Vรคnersborg",
"capital": "minor",
"population": "21835",
"image": "https://scanmagazine.co.uk/content/uploads/2016/01/01_TRO1.jpg",
"cityPic": "vandersborg.jpg",
"id": "1752467593"
},
"geometry": {
"type": "Point",
"coordinates": [
12.33,
58.363
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Norrbotten",
"city": "Kiruna",
"capital": "minor",
"population": "18154",
"image": "https://hallbartbyggande.com/wp-content/public_html/2018/09/Kiruna_hogre_medeltemperatur.jpg",
"cityPic": "kiruna.jpg",
"id": "1752001526"
},
"geometry": {
"type": "Point",
"coordinates": [
20.2166,
67.85
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Skรฅne",
"city": "Hรถganรคs",
"capital": "minor",
"population": "15795",
"image": "https://resources.mynewsdesk.com/image/upload/ar_16:9,c_fill,dpr_auto,f_auto,g_auto,q_auto,w_864/udcno8bhfmgrr6ynnt36.jpg",
"cityPic": "hoganas.jpg",
"id": "1752137413"
},
"geometry": {
"type": "Point",
"coordinates": [
12.5769,
56.196
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Kinna",
"capital": "minor",
"population": "15373",
"image": "https://upload.wikimedia.org/wikipedia/commons/f/ff/Town_of_Skene_Sweden.jpg",
"cityPic": "kinna.jpg",
"id": "1752953604"
},
"geometry": {
"type": "Point",
"coordinates": [
12.6805,
57.4954
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Mariestad",
"capital": "minor",
"population": "14891",
"image": "https://static.lokalguiden.se/filter/960x540,,85,cover/uploads/articles/83/2cbdb2f6fd280e7d4b0a6f025001284d.jpg",
"cityPic": "mariestad.jpg",
"id": "1752879298"
},
"geometry": {
"type": "Point",
"coordinates": [
13.828,
58.705
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "รstergรถtland",
"city": "Mjรถlby",
"capital": "minor",
"population": "13914",
"image": "https://www.mjolby.se/images/18.2884097b148c203dedf421d/1413969404484/S%C3%B6rby%20flygbild%20beskuren.jpg",
"cityPic": "mjolby.jpg",
"id": "1752185099"
},
"geometry": {
"type": "Point",
"coordinates": [
15.1312,
58.3321
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Gรคvleborg",
"city": "Bollnรคs",
"capital": "minor",
"population": "13398",
"image": "https://www.bollnas.se/images/Aktuellt/2020/Bolln%C3%A4s_framtid_%C3%A4r_din_webb.jpg",
"cityPic": "bollnas.jpg",
"id": "1752287863"
},
"geometry": {
"type": "Point",
"coordinates": [
16.3666,
61.352
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Dalarna",
"city": "Mora",
"capital": "minor",
"population": "12858",
"image": "https://www.actic.se/app/uploads/2019/02/Morastad-1080x549.jpg",
"cityPic": "mora.jpg",
"id": "1752665392"
},
"geometry": {
"type": "Point",
"coordinates": [
14.5635,
61.0096
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Ulricehamn",
"capital": "minor",
"population": "11443",
"image": "https://www.vandrarhem.online/bilder/stad/84/vandrarhem-ulricehamn.jpg",
"cityPic": "ulricehamn.jpg",
"id": "1752323454"
},
"geometry": {
"type": "Point",
"coordinates": [
13.4186,
57.7917
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Tibro",
"capital": "minor",
"population": "8572",
"image": "https://www.fjellfotografen.se/photo/large/Flygfoto_%C3%B6ver_Tibro_@20160601_TOJ9796.jpg",
"cityPic": "tibro.jpg",
"id": "1752652082"
},
"geometry": {
"type": "Point",
"coordinates": [
14.158,
58.419
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Jรถnkรถping",
"city": "Habo",
"capital": "minor",
"population": "8455",
"image": "https://media.husmanhagberg.se/cms/2019/11/hero-kontor-mullsjo-habo.jpg",
"cityPic": "habo.jpg",
"id": "1752321919"
},
"geometry": {
"type": "Point",
"coordinates": [
14.0856,
57.9066
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Tidaholm",
"capital": "minor",
"population": "8233",
"image": "https://www.tidaholm.se/images/18.5a594813169903f99b6c4783/1553516191735/turbinhuson_och_tidan.jpg",
"cityPic": "tidaholm.jpg",
"id": "1752287671"
},
"geometry": {
"type": "Point",
"coordinates": [
13.9599,
58.1794
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Strรถmstad",
"capital": "minor",
"population": "7355",
"image": "https://drivkraft.ey.se/wp-content/uploads/2018/06/Stro%CC%88mstad-870x489.jpg",
"cityPic": "stromstad.jpg",
"id": "1752574047"
},
"geometry": {
"type": "Point",
"coordinates": [
11.1864,
58.9441
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Norrbotten",
"city": "Haparanda",
"capital": "minor",
"population": "6642",
"image": "https://www.fjellfotografen.se/photo/large/Flygbild_%C3%B6ver_Haparanda_@20100907_TOJ8266.jpg",
"cityPic": "haparanda.jpg",
"id": "1752528595"
},
"geometry": {
"type": "Point",
"coordinates": [
24.117,
65.8342
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Hjo",
"capital": "minor",
"population": "6351",
"image": "https://anhede.se/wp-content/uploads/2015/06/aerial-photo-hjo-sweden-drone-photographer.jpg",
"cityPic": "hjo.jpg",
"id": "1752355806"
},
"geometry": {
"type": "Point",
"coordinates": [
14.2786,
58.3044
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Vรคstmanland",
"city": "Kungsรถr",
"capital": "minor",
"population": "5898",
"image": "https://kungsor.se/images/200.3d6b838b15b14f2118415d1d/1490776416734/20161102_Dronarperspektiv_montage_REX_master-72dpi.jpg",
"cityPic": "kungsor.jpg",
"id": "1752957577"
},
"geometry": {
"type": "Point",
"coordinates": [
16.1059,
59.4227
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "<NAME>",
"city": "Vรฅrgรฅrda",
"capital": "minor",
"population": "5735",
"image": "https://brfbjorkangen.se/wp-content/uploads/2019/09/Torget.jpg",
"cityPic": "vargarda.jpg",
"id": "1752801056"
},
"geometry": {
"type": "Point",
"coordinates": [
12.8083,
58.0341
]
}
},
{
"type": "Feature",
"properties": {
"country": "Sweden",
"iso2": "SE",
"iso3": "SWE",
"admin_name": "Skรฅne",
"city": "Hjรคrup",
"population": "5607",
"image": "https://i.pinimg.com/originals/27/8b/97/278b97b1378e83b899716eabb12b4ce8.jpg",
"cityPic": "hjarup.jpg",
"id": "1752111742"
},
"geometry": {
"type": "Point",
"coordinates": [
13.141,
55.6707
]
}
}
]
};<file_sep>/js/map.js
// - MAPS - //
// - Basemaps variables - //
var hybrid = L.esri.basemapLayer('ImageryClarity');
var topographic = L.esri.basemapLayer('Topographic');
var streets = L.esri.basemapLayer('Streets');
var darkGray = L.esri.basemapLayer('DarkGray');
// - Create an on load ESRI basemap - //
var map = new L.map('map', {
center: [62.45, 17.45],
zoom: 5,
zoomControl: false,
attributionControl: false
});
L.esri.basemapLayer('Topographic').addTo(map);
// - GEOLOCATOR - //
// Reference - https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
$(document).ready(function () {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function (position) {
console.log();
L.circle([position.coords.latitude, position.coords.longitude], {
fillColor: "#FDFF00",
fillOpacity: 0.7,
color: "#FDFF00",
radius: 1100,
weight: 3,
opacity: 0.8
}).addTo(map);
});
} else {
// - geolocation is not available - //
console.log("Geolocation missing");
}
});
// - KITESPOTS DROPDOWNLIST - //
// Reference - https://www.codota.com/code/javascript/functions/leaflet/DomUtil
// References - http://www.java2s.com/example/javascript/leaflet/searching-markers-with-leafletcontrolsearch-from-drop-down-list.html
// - Variable for cluster and search source(kitespots). - //
var clusterSpots = L.markerClusterGroup();
var searchSpots = L.geoJson(kitespots, {
onEachFeature: function (feature, layer) {
var popup = '';
if (feature.properties.name) {
popup += '<h2>' + feature.properties.name + '</h2>' + '<h4> Beach facing : ' + feature.properties.windDirection + '</h4>';
}
layer.bindPopup(popup);
}
});
// - Create search engine and place it on map. - //
var selector = L.control({
position: 'topright',
opacity: 0.8,
size: 10
});
selector.onAdd = function () {
var div = L.DomUtil.create('div', 'list-group-item');
div.innerHTML = '<select id = "selectSpot"><option value = "init">CHOOSE A KITESPOTS</option></select>';
return div;
};
selector.addTo(map);
// - Function to browse and choose spots. - //
searchSpots.eachLayer(function (layer) {
var spotChoice = document.createElement("option");
spotChoice.innerHTML = layer.feature.properties.label + " - " + layer.feature.properties.name;
spotChoice.value = layer._leaflet_id;
L.DomUtil.get("selectSpot").appendChild(spotChoice);
});
// - The selectSpot variable for the DomEvent listener. - //
var selectSpot = L.DomUtil.get("selectSpot");
// - Select kitespot on click. - //
L.DomEvent.addListener(selectSpot, 'click', function (e) {
L.DomEvent.stopPropagation(e);
});
// - ChangeHandler zooms in on choosen spot with popup. - //
L.DomEvent.addListener(selectSpot, 'change', changeHandler);
function changeHandler(e) {
var selected = searchSpots.getLayer(e.target.value);
clusterSpots.zoomToShowLayer(selected, function () {
selected.openPopup();
});
}
clusterSpots.addLayer(searchSpots);
map.addLayer(clusterSpots);
// - CITIES LAYER - //
// - Style city markers. - //
// Refrence: https://leafletjs.com/examples/geojson/
var markerStyle = {
radius: 4,
weight: 3,
color: "#F0E891",
opacity: 0.6,
fillColor: "#A50B5E",
fillOpacity: 0.8,
};
// - Json cities to map. - //
var city = L.geoJson(cities, {
pointToLayer: function (features, latlng) {
return L.circleMarker(latlng, markerStyle)
.bindPopup("<img src='images/cityPic/" + features.properties.cityPic + "'style='width:300px;height:420x;'/><h2>" + features.properties.city + "</h2><h4>County: " + features.properties.admin_name + "<br/>Population: " + features.properties.population + "</h4>");
}
});
// - City popups to fit map. - //
// Reference - https://jsfiddle.net/09pe8ko6/
document.querySelector(".leaflet-popup-pane").addEventListener("load", function (event) {
var target = event.target,
tagName = target.tagName,
popup = map._popup;
// - console.log("got load event from " + tagName); - //
if (tagName === "IMG" && popup) {
popup.update();
}
// - Capture the load event. - //
}, true);
// - POLYGONS LAYER - //
// - Creat variable and fetch json data. - //
// Reference - https://gis.stackexchange.com/a/385670/175494 - Falke Design
var polyRegions = L.featureGroup();
fetch("https://public.opendatasoft.com/api/records/1.0/search/?dataset=sverige-lan-counties-of-sweden&q=&rows=22")
.then(response => response.json())
.then(data => {
// - ..under 'records'.. - //
data.records.forEach((d) => {
// - ... 'fields.geo_shape' where coordinate data is. - //
var polyJson = d.fields.geo_shape;
// - View data in console - //
console.log(polyJson);
var layer = L.GeoJSON.geometryToLayer(polyJson, {
radius: 6,
color: "#f0fff0",
opacity: 0.8,
fillColor: "#ACACE6",
fillOpacity: 0.3,
weight: 1
});
polyRegions.addLayer(layer);
// - Create circleMarker for popup of region name. - //
var regionPoint = L.GeoJSON.coordsToLatLng(d.geometry.coordinates);
var circle = L.circleMarker(regionPoint, {
radius: 5,
weight: 3,
color: "#F8DE7E",
opacity: 0.4,
fillColor: "#30BfBf",
fillOpacity: 0.7
}).bindPopup("<h2><b> " + d.fields.lan_namn + "</b></h2>");
polyRegions.addLayer(circle);
});
});
// - BRING OVERLAY TO FRONT - //
map.on('click', function () {
city.bringToFront();
});
// - CONTROL LAYERS - //
var basemapLayers = {
"Topographic": topographic,
"Hybrid": hybrid,
"Streets": streets,
"DarkGray": darkGray
};
var overlays = {
'Cities': city,
'Regions': polyRegions
};
// - Add it all to the map - //
L.control.layers(basemapLayers, overlays).addTo(map);
<file_sep>/js/headerModal.js
// Reference - https://www.w3schools.com/howto/howto_css_modals.asp
// - HEADER MODAL - //
// Get the modalInfo
var modalInfo = document.getElementById("modalInfo");
// Get the button that opens the modalInfo
var btnInfo = document.getElementById("infoButton");
// Get the <span> element that closes the modalInfo
var spanInfo = document.getElementsByClassName("closeInfo")[0];
// When the user clicks on the button, open the modalInfo
btnInfo.onclick = function () {
modalInfo.style.display = "block";
};
// When the user clicks on <span> (x), close the modalInfo
spanInfo.onclick = function () {
modalInfo.style.display = "none";
};
// When the user clicks anywhere outside of the modalInfo, close it
window.addEventListener("click", function(event) {
if (event.target == modalInfo) {
modalInfo.style.display = "none";
}
});
// - ATTRIBUTE MODAL - //
// Get the modalAttribute
var modalAttribute = document.getElementById("modalAttribute");
// Get the button that opens the modalAttribute
var btnAttribute = document.getElementById("attributeBtn");
// Get the <span> element that closes the modalAttribute
var spanAttribute = document.getElementsByClassName("closeAttribute")[0];
// When the user clicks on the button, open the modalAttribute
btnAttribute.onclick = function () {
modalAttribute.style.display = "block";
};
// When the user clicks on <span> (x), close the modalAttribute
spanAttribute.onclick = function () {
modalAttribute.style.display = "none";
};
// When the user clicks anywhere outside of the modalAttribute, close it
window.addEventListener("click", function(event) {
if (event.target == modalAttribute) {
modalAttribute.style.display = "none";
}
});<file_sep>/js/kitespots.js
const kitespots = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BREDVIKEN",
"label": "NORTH",
"windDirection": "S"
},
"geometry": {
"type": "Point",
"coordinates": [
23.611507415771484,
65.81084897946091
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BODรN",
"label": "NORTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
23.48851203918457,
65.81339861666154
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STORSAND",
"label": "NORTH",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
22.023038864135742,
65.62249644678872
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LULVIKSBADET",
"label": "NORTH",
"windDirection": "NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
22.15444564819336,
65.54606255137291
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LULHรLLAN",
"label": "NORTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
22.15240716934204,
65.5192498070519
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KLUBBVIKEN",
"label": "NORTH",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
22.36687660217285,
65.49920890840932
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STORSNรCK",
"label": "NORTH",
"windDirection": "W/NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
21.184558868408203,
64.7744911104303
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SILLSKATAN",
"label": "NORTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
21.217260360717773,
64.74261155467666
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTH",
"windDirection": "SW/S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
21.611223220825195,
64.43492908208786
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
21.58041000366211,
64.43429941147684
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LILLIS",
"label": "NORTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
20.02532958984375,
63.66987214843851
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LรNKEBOO",
"label": "NORTH",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
19.99958038330078,
63.65235474197827
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STORรNGET",
"label": "NORTH",
"windDirection": "NW"
},
"geometry": {
"type": "Point",
"coordinates": [
19.47747230529785,
63.49141413873825
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SALUSAND",
"label": "NORTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
19.264183044433594,
63.45756728705775
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STUBBSAND",
"label": "NORTH",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.959655761718746,
63.220636696106915
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GULLVIK",
"label": "NORTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.82786273956299,
63.214932082292805
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VANNVIKEN",
"label": "NORTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.815631866455078,
63.20794965080512
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NYรNGET",
"label": "NORTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.685641288757324,
63.25064955421237
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STORSANDEN",
"label": "NORTH",
"windDirection": "N/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.528785705566406,
62.99013053076868
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SรLSTEN",
"label": "NORTHEAST",
"windDirection": "NW/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.97191619873047,
62.64485420666252
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SMITINGE",
"label": "NORTHEAST",
"windDirection": "SE/S"
},
"geometry": {
"type": "Point",
"coordinates": [
18.032941818237305,
62.59942445768768
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SVARTVIK",
"label": "NORTHEAST",
"windDirection": "SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.91222095489502,
62.57594228749241
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "YTTERFรLLE",
"label": "NORTHEAST",
"windDirection": "SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.925631999969482,
62.585744422903055
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "MYCKELรNG",
"label": "NORTHEAST",
"windDirection": "NW/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
17.534780502319336,
62.44946068012924
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GULLFIBER",
"label": "NORTHEAST",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
17.483882904052734,
62.51049555437819
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SMACKEN",
"label": "NORTHEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.474527359008786,
62.50966355942328
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STORNรSET",
"label": "NORTHEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.50019073486328,
62.44942098076193
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "DYRร
SAND",
"label": "NORTHEAST",
"windDirection": "E/SE/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.458176612854004,
62.07770856213146
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SรRFJรRDEN",
"label": "NORTHEAST",
"windDirection": "E/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.422943115234375,
62.026561098560606
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VARPSAND",
"label": "NORTHEAST",
"windDirection": "NE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
17.415218353271484,
62.01806506729427
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Hร
RTE",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.39762306213379,
61.99579703742656
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HALLSBO",
"label": "NORTHEAST",
"windDirection": "NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.875600814819336,
61.81523144939095
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FรNEBO",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
16.71396017074585,
61.921139510833584
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "MALNBADEN",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.176995277404785,
61.716725596166306
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTHEAST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
17.432942390441895,
61.629652028202926
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTHEAST",
"windDirection": "SE/S"
},
"geometry": {
"type": "Point",
"coordinates": [
17.44530200958252,
61.62251399199984
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Tร
NGVIK",
"label": "NORTHEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.46675968170166,
61.6216165223706
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SรRSUNDET",
"label": "NORTHEAST",
"windDirection": "N/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
17.509546279907223,
61.70106395638044
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SNรCKEN",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.176737785339355,
61.41943380537809
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KRร
KNรS",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.152791023254395,
61.416744201264635
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.19433307647705,
61.24681070163888
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ORSUNNDET",
"SW/windDirection/NW": "",
"label": "NORTHEAST",
"windDirection": "S/SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
17.259178161621094,
61.2408440504558
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ENSKรR",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.275056838989258,
61.236012091513985
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTHEAST",
"windDirection": "S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
17.352797985076904,
60.75184245425473
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HOLMUDDEN",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.31819748878479,
60.73193751350746
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BRรDVIKEN",
"label": "NORTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.262074947357178,
60.715589036187716
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KLรCKEN",
"label": "NORTHEAST",
"windDirection": "NW/N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.443993091583252,
60.643800880476675
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RULLSAND",
"label": "NORTHEAST",
"windDirection": "NW/N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.471630573272705,
60.64057127589496
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SALNร",
"label": "MIDEAST",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.992378711700436,
59.90528466157977
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KAPELLSKรR",
"label": "MIDEAST",
"windDirection": "SW/S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
19.06505584716797,
59.71725079037241
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BROMSKรR",
"label": "MIDEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.98782968521118,
59.62659657131834
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "DEGERSAND",
"label": "ร
LAND",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
19.59664821624756,
60.154279012328594
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDMO",
"label": "ร
LAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
19.544527530670166,
60.21805468151456
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SKJULET",
"label": "ร
LAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
19.945592880249023,
60.10777219078806
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LUMPARN",
"label": "ร
LAND",
"windDirection": "N/NW/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
20.141136646270752,
60.09006909172053
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "PRรSTร",
"label": "ร
LAND",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
20.252351760864258,
60.205806310826326
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HรGERNรSBADET",
"label": "MIDEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.130273818969727,
59.44230427475132
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NรSAรNG",
"label": "MIDEAST",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.105039596557617,
59.42598016850304
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STICKLINGE",
"label": "MIDEAST",
"windDirection": "NW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.11173439025879,
59.389790292197006
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Fร
GELรUDDE",
"label": "MIDEAST",
"windDirection": "NE/N"
},
"geometry": {
"type": "Point",
"coordinates": [
18.23082447052002,
59.37626103836555
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SรTRASTRAND",
"label": "MIDEAST",
"windDirection": "W"
},
"geometry": {
"type": "Point",
"coordinates": [
17.891535758972168,
59.286907015650144
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "MJรLKUDDEN",
"label": "MIDEAST",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.302600383758545,
59.313073188611284
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ERSTAVIK",
"label": "MIDEAST",
"windDirection": "SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.26453447341919,
59.269268968486266
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TRINNTORP",
"label": "MIDEAST",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.3566951751709,
59.228218868854746
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDHOLMEN",
"label": "MIDEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.416733741760254,
59.19637281570774
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GRรNSKAN",
"label": "MIDEAST",
"windDirection": "SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
18.48023772239685,
59.22269091300181
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "MIDEAST",
"windDirection": "S/EW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.52410793304443,
59.215410431168
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BJรRKVIK",
"label": "MIDEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.537476062774658,
59.220593678551
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TORPESAND",
"label": "MIDEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.549749851226807,
59.221527018699234
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "DALARร",
"label": "MIDEAST",
"windDirection": "SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
18.398473262786865,
59.137556207182165
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Gร
Lร",
"label": "MIDEAST",
"windDirection": "E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.322019577026367,
59.09876644287373
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "MIDEAST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
17.791242599487305,
58.80142826384218
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "MIDEAST",
"windDirection": "W/SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
17.79158592224121,
58.797204232204024
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "MIDEAST",
"windDirection": "S/SW/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.80986785888672,
58.798893906561524
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VARPET",
"label": "GOTLAND",
"windDirection": "NE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
19.221439361572266,
57.98671907887375
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "EKEVIKEN",
"label": "GOTLAND",
"windDirection": "NW/N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
19.24633026123047,
57.97361262244836
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SKรR",
"label": "GOTLAND",
"windDirection": "NW/N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
19.30400848388672,
57.986173072238756
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SKALASAND",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
19.337310791015625,
57.9565852760702
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SUDERSAND",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
19.26074981689453,
57.9519400506774
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SAXRIV",
"label": "GOTLAND",
"windDirection": "W/NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
18.89373779296875,
57.9285453890267
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SJรKRGEN",
"label": "GOTLAND",
"windDirection": "SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.949828147888184,
57.787216320771336
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.91043186187744,
57.720767154049
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HIDEVIKEN",
"label": "GOTLAND",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.878695964813232,
57.73593619688975
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SLITE",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.80970954895019,
57.72019418037458
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "IREVIKEN",
"label": "GOTLAND",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.60285758972168,
57.84319782592739
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NORDENSTRAND",
"label": "GOTLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.33266258239746,
57.67356959155067
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.303340673446655,
57.65307639899865
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FRIDHEM",
"label": "GOTLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.211727142333984,
57.5998065794433
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ร
MINNE",
"label": "GOTLAND",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.76688003540039,
57.61392296101988
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KATTVIK",
"label": "GOTLAND",
"windDirection": "N/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.854384422302246,
57.43483323184754
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GROGARN",
"label": "GOTLAND",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.89897346496582,
57.436958328679765
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NATVIKSUDD",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.917598724365234,
57.403219401743925
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDVIKEN",
"label": "GOTLAND",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.88103485107422,
57.39466418725904
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VรSTERVIKEN",
"label": "GOTLAND",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.867988586425778,
57.39864145432571
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "JRP",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.85442733764648,
57.396606627428056
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SJAUSTRU",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.797414302825928,
57.374146659910544
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ARDREVIKEN",
"label": "GOTLAND",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.780934810638424,
57.371474141451046
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LJUGARN",
"label": "GOTLAND",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.71568202972412,
57.33557874994003
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LAUSVIKEN",
"label": "GOTLAND",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.66652250289917,
57.28353126700603
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GANSVIKEN",
"label": "GOTLAND",
"windDirection": "N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.430681228637695,
57.12394135881104
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.34193229675293,
57.01555240433014
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
18.37240219116211,
56.99704382794897
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HOLMHรLLAR",
"label": "GOTLAND",
"windDirection": "S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
18.278460502624508,
56.9290299749154
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VALAR",
"label": "GOTLAND",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.236703872680664,
57.03266230446723
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NISSESVIKEN",
"label": "GOTLAND",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
18.217241764068604,
57.1313369287911
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TJURUDDEN",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.166022300720215,
57.396306018421306
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KOVIK",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.155722618103024,
57.40557751507634
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.141968250274658,
57.436923681351566
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.126068115234375,
57.48363310504586
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STRANDPANGET",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.12722682952881,
57.48898465966848
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GNISVรRD",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.113794326782223,
57.500861385987896
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FURILLEN",
"label": "GOTLAND",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
19.00733470916748,
57.75677752432833
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "GOTLAND",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
18.14488649368286,
57.43262715838854
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HALLMARE",
"label": "SOUTHEAST",
"windDirection": "SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
16.74694061279297,
57.87338121551046
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GRรNSร",
"label": "SOUTHEAST",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
16.731233596801758,
57.69083433567423
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HORNSUDDE",
"label": "SOUTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
16.73292875289917,
57.695410121384285
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "รNGJARN",
"label": "รLAND",
"windDirection": "S/SE/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.150001525878906,
57.310485554250235
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TROLLSKOGEN",
"label": "รLAND",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.12820053100586,
57.33963190595921
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BรDA",
"label": "รLAND",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.056145668029785,
57.27361407786608
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BYRUM",
"label": "รLAND",
"windDirection": "W/SW/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.96014404296875,
57.237797176352665
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HรGBY",
"label": "รLAND",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
17.038249969482422,
57.14939454452335
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ALVEDSJร",
"label": "รLAND",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.919846534729004,
57.159077526740205
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDVIK",
"label": "รLAND",
"windDirection": "SW/S/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.85131072998047,
57.068363326753854
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Kร
REHAMN",
"label": "รLAND",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
16.891050338745117,
56.95241715858471
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "รLEKLINTA",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.77035093307495,
56.97067892328818
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KรPINGSVIK",
"label": "รLAND",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.713123321533203,
56.88237572504538
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BJรRBYBADET",
"label": "รLAND",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
16.736812591552734,
56.70337478041814
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BLรSINGE",
"label": "รLAND",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
16.698017120361328,
56.616670762879245
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SAXNรS",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.477088928222656,
56.687633816535474
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TALLUDDEN",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.46052360534668,
56.64884244478331
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.408767700195312,
56.586291401289806
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDBERGEN",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.406235694885254,
56.58064277785898
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KLEVA",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.389198303222656,
56.54685159617412
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GRรNHรGEN",
"label": "รLAND",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
16.397781372070312,
56.27805487819603
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BERGAVIKEN",
"label": "SOUTHEAST",
"windDirection": "E"
},
"geometry": {
"type": "Point",
"coordinates": [
16.366581916809082,
56.69644768215441
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Lร
NGVIKEN",
"label": "SOUTHEAST",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
16.33639097213745,
56.64938509184053
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"windDirectioon": "",
"label": "SOUTHEAST",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
16.092395782470703,
56.37836928500861
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SKรPPEVIK",
"label": "SOUTHEAST",
"windDirection": "NE"
},
"geometry": {
"type": "Point",
"coordinates": [
16.075057983398434,
56.36235000554565
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KRISTIANOPEL",
"label": "SOUTHEAST",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
16.045103073120117,
56.25102776887299
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TORHAMN",
"label": "SOUTHEAST",
"windDirection": "SW"
},
"geometry": {
"type": "Point",
"coordinates": [
15.838508605957031,
56.0750295062246
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GISSELVIK",
"label": "SOUTHEAST",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
15.816836357116697,
56.1030184585898
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STUMHOLMEN",
"label": "SOUTHEAST",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
15.600435733795164,
56.15739981554589
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LINDร",
"label": "SOUTHEAST",
"windDirection": "SW/S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
15.348072052001951,
56.1189910533608
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NABBEN",
"label": "SOUTH",
"windDirection": "SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
14.747085571289062,
56.153199138696685
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NORJE",
"label": "SOUTH",
"windDirection": "N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.678163528442383,
56.125701154469404
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NOGERSUND",
"label": "SOUTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
14.740004539489746,
56.005483995094245
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TORSร",
"label": "SOUTH",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
14.635848999023438,
56.00510008037907
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDVIKEN",
"label": "SOUTH",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
14.604263305664062,
56.01853482587991
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RINKABY",
"label": "SOUTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
14.349517822265625,
55.9601557211219
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
14.323768615722656,
55.93208704528063
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "รSPET",
"label": "SOUTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.309413433074951,
55.91270587089815
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VIK",
"label": "SOUTH",
"windDirection": "E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.285058975219727,
55.6168977538069
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VITEMรLLA",
"label": "SOUTH",
"windDirection": "SE/E/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.205043315887451,
55.7018472583719
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BORRBY",
"label": "SOUTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
14.237079620361328,
55.43363993187514
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LรDERUP",
"label": "SOUTH",
"windDirection": "SW/S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.11245346069336,
55.382621312784806
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SANDHAM",
"label": "SOUTH",
"windDirection": "S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
14.19931411743164,
55.385546795384855
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Kร
SEBERGA",
"label": "SOUTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.064903259277344,
55.38486420213388
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SALTAN",
"label": "SOUTH",
"windDirection": "S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
13.84500503540039,
55.422681601896464
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
13.787240982055662,
55.42414288828562
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "MOSSBYSTRAND",
"label": "SOUTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
13.638410568237305,
55.416835915606164
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "SW/S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
13.565089702606201,
55.3840231335337
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BEDDINGE",
"label": "SOUTH",
"windDirection": "S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
13.435163497924805,
55.36238079953253
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BรSTE",
"label": "SOUTH",
"windDirection": "SW/S/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
13.315000534057617,
55.34247159747172
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KรMINGE",
"label": "SOUTH",
"windDirection": "SW/S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
12.967815399169922,
55.402071707053246
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LJUNGHUSEN",
"label": "SOUTH",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
12.933053970336914,
55.3908608684714
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HรLLVIKEN",
"label": "SOUTH",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.940435409545897,
55.41298703317099
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FALSTERBO",
"label": "SOUTH",
"windDirection": "S/SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
12.844305038452148,
55.38920334432926
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.827911376953125,
55.413766583947975
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KLAGSHAMN",
"label": "SOUTH",
"windDirection": "SW/S"
},
"geometry": {
"type": "Point",
"coordinates": [
12.925758361816404,
55.51716404607938
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RIBERSBRG",
"label": "SOUTH",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.962665557861328,
55.60269329024588
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.974767684936523,
55.61786715419033
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LOMMA",
"label": "SOUTH",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
13.058109283447266,
55.67874588739997
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
13.05544853210449,
55.68890733408554
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SAXTORP",
"label": "SOUTH",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.92266845703125,
55.82057315625548
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LUNDร
KRA",
"label": "SOUTH",
"windDirection": "E/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.855548858642578,
55.85662388762304
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BORSTAHUSEN",
"label": "SOUTH",
"windDirection": "S/SW/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.806539535522461,
55.891558280347866
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FORTUNA",
"label": "SOUTH",
"windDirection": "S/SW/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.757487297058105,
55.95783746193137
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTH",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.748517990112303,
55.98906823661236
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "DOMSTEN",
"label": "SOUTHWEST",
"windDirection": "SW/W/MW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.603206634521483,
56.11771109724269
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HรGANรS",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.54183769226074,
56.21212196189526
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LERHAMN",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.51917839050293,
56.257965117888766
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FARHULT",
"label": "SOUTHWEST",
"windDirection": "NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
12.709808349609375,
56.22359982415448
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KLITTERHUS",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.825851440429688,
56.25126618660775
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.76087760925293,
56.308943437513975
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.862586975097656,
56.431939738088815
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.921981811523436,
56.477661845362285
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.939834594726562,
56.50988086308746
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LAGAOSET",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.94464111328125,
56.55494152637736
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.89022445678711,
56.64037141979106
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.83975601196289,
56.66320816130267
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RINGENรS",
"label": "SOUTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.714271545410154,
56.678582138965815
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name ": "VILSHรRAD",
"label": "SOUTHWEST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.684059143066404,
56.69837985817974
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RINGSEGร
RD",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.542266845703125,
56.86220568341855
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SKREA",
"label": "SOUTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.508964538574219,
56.87965574958993
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "OLOFSBO",
"label": "SOUTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.386999130249023,
56.917108341597256
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BJรRKรNG",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.349190711975098,
57.005785136588045
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LรJET",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.276749610900877,
57.0622969241764
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "APELVIKEN",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.254562377929688,
57.08431789704462
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "W/NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
12.201089859008789,
57.121425363660826
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "SE/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.20306396484375,
57.11830342836152
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.218770980834961,
57.13680986400352
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "KรRRADAL",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.211260795593262,
57.185390322967564
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RINGHALS",
"label": "SOUTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.122297286987305,
57.252587764525046
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STRร
VALLA",
"label": "SOUTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.164783477783203,
57.29407187515724
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "Rร
GELUND",
"label": "SOUTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.154226303100586,
57.33011207121784
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "SOUTHWEST",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.985397338867186,
57.368986557536964
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GOTTKรR",
"label": "SOUTHWEST",
"windDirection": "N/NE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
12.01779842376709,
57.3824290731348
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STENUDDEN",
"label": "SOUTHWEST",
"windDirection": "SE/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.08745002746582,
57.337616964301546
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TORKELSTORP",
"label": "SOUTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
12.094230651855469,
57.43626537588213
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ASKIMBADET",
"label": "NORTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.9256591796875,
57.6248168745992
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ARENDAL",
"label": "NORTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.810688972473145,
57.69309363041959
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LAPPESAND",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.634736061096191,
57.691740364192576
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HUMMERVIKEN",
"label": "NORTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.628921031951904,
57.71775321089061
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SILLVIK",
"label": "NORTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.733956336975096,
57.740849877668666
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BJรRKLANDA",
"label": "NORTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.796183586120605,
57.756685940383576
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GLรSKรR",
"label": "NORTHWEST",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.731424331665039,
57.81998370741737
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LYCKE",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.70992374420166,
57.87716947474566
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TJUVKIL",
"label": "NORTHWEST",
"windDirection": "W/NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
11.714601516723633,
57.90144137604116
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ARรD",
"label": "NORTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.759662628173828,
57.95039150851431
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TRLLENรS",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.813821792602537,
58.05204322470806
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "TRรTTE",
"label": "NORTHWEST",
"windDirection": "E/SE/S"
},
"geometry": {
"type": "Point",
"coordinates": [
11.770305633544922,
58.12608724826084
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "GRENGร
RD",
"label": "NORTHWEST",
"windDirection": "E/SE/S"
},
"geometry": {
"type": "Point",
"coordinates": [
11.775069236755371,
58.12882918690758
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LAGMANSHOLMEN",
"label": "NORTHWEST",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.632204055786133,
58.128761207508916
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SOLLID",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.467666625976562,
58.1162961256368
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FISKEBรCKSVIK",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.40604019165039,
58.33639703106996
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HABYBUKTEN",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.240987777709961,
58.40380279832294
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BOVALLSTRAND",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.328084468841551,
58.4798534914742
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SKEPPSTAD",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.297464370727539,
58.58342245764644
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTHWEST",
"windDirection": "NW/N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
11.197643280029297,
58.78648622397487
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "NORTHWEST",
"windDirection": "S//S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.185970306396484,
58.83093766799037
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "ROSSร",
"label": "NORTHWEST",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
11.153268814086914,
58.841819585875115
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "STENVIK",
"label": "NORTHWEST",
"windDirection": "SE/S"
},
"geometry": {
"type": "Point",
"coordinates": [
11.121361255645752,
58.995797517540915
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "รREKROKEN",
"label": "NORTHWEST",
"windDirection": "SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
11.017398834228516,
59.025229768149586
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "RINGSHAUG",
"label": "NORTHWEST",
"windDirection": "E/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
10.492372512817381,
59.27574864164216
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "LARKOLLEN",
"label": "NORTHWEST",
"windDirection": "SE/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
10.689697265625,
59.30537934448051
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "FRAMNES",
"label": "NORTHWEST",
"windDirection": "E/SE/S"
},
"geometry": {
"type": "Point",
"coordinates": [
10.633177757263184,
59.42036966711743
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "REFSNES",
"label": "NORTHWEST",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
10.61502456665039,
59.44845650619904
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VรNERSNรS",
"label": "VรNERN",
"windDirection": "N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
12.616767883300781,
58.425808357574034
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SIKHALL",
"label": "VรNERN",
"windDirection": "SE/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.435150146484375,
58.49207902266863
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "<NAME>",
"label": "VรNERN",
"windDirection": "NE/E/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
12.520980834960938,
58.686663519301426
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SVALNรS",
"label": "VรNERN",
"windDirection": "SW/W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
12.935714721679688,
58.56323898562774
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "SVANVIK",
"label": "VรNERN",
"windDirection": "NW/N/NE"
},
"geometry": {
"type": "Point",
"coordinates": [
13.270132541656494,
58.49742775634995
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BJรRNRUKAN",
"label": "VรNERN",
"windDirection": "SE/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
13.8057804107666,
59.327016239461834
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BOMSTAD",
"label": "VรNERN",
"windDirection": "SE/S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
13.35688591003418,
59.361632882309166
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "BREDSANDEN",
"label": "VรNERN",
"windDirection": "NE/E/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
13.28174114227295,
59.35833028846304
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VรTTERSTRAND",
"label": "VรTTERN",
"windDirection": "NE/N/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
14.20506477355957,
57.782846612223395
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "NORDVIKEN",
"label": "VรTTERN",
"windDirection": "NE/E/SE"
},
"geometry": {
"type": "Point",
"coordinates": [
14.455261230468748,
58.44916999542082
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VรTTERVIK",
"label": "VรTTERN",
"windDirection": "W/NW/N"
},
"geometry": {
"type": "Point",
"coordinates": [
14.935569763183594,
58.46668104970195
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "VARAMON",
"label": "VรTTERN",
"windDirection": "W/NW"
},
"geometry": {
"type": "Point",
"coordinates": [
15.002861022949217,
58.5496275959733
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "MARICON",
"label": "VรTTERN",
"windDirection": "S/SW/W"
},
"geometry": {
"type": "Point",
"coordinates": [
14.902610778808594,
58.57684508753356
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "รSPENรSET",
"label": "VรTTERN",
"windDirection": "SE/E"
},
"geometry": {
"type": "Point",
"coordinates": [
14.503326416015625,
58.55231447334599
]
}
},
{
"type": "Feature",
"properties": {
"marker-color": "#7e7e7e",
"marker-size": "medium",
"marker-symbol": "./images/flag.png",
"icon": "./images/blueKite.jpg",
"name": "HARGEBADEN",
"label": "VรTTERN",
"windDirection": "S/SW"
},
"geometry": {
"type": "Point",
"coordinates": [
14.967498779296873,
58.78315006897401
]
}
}
]
}; | 3a690c79edeb8e0400b0cc1f9da2367e21a6c22b | [
"Markdown",
"JavaScript"
] | 5 | Markdown | ElisabethCheston/KitespotsSweden | b55fbd4dd2b0d2ecfabab5f49a4b81406c64af3a | 25a72bfac7a9467c72cb27a93516e8f50c52f527 |
refs/heads/main | <file_sep>#!/bin/sh
pandoc pdf-gen/pdf-data.yml docs/indoor-hotspot/overview.md -o docs/pdfs/indoor-overview.pdf --pdf-engine=xelatex --resource-path docs/media/
pandoc pdf-gen/pdf-data.yml docs/indoor-hotspot/quick-start.md -o docs/pdfs/indoor-quick-start.pdf --pdf-engine=xelatex --resource-path docs/media/
pandoc pdf-gen/pdf-data.yml docs/outdoor-hotspot/overview.md -o docs/pdfs/outdoor-overview.pdf --pdf-engine=xelatex --resource-path docs/media/
pandoc pdf-gen/pdf-data.yml docs/outdoor-hotspot/quick-start.md -o docs/pdfs/outdoor-quick-start.pdf --pdf-engine=xelatex --resource-path docs/media/
| 2f333c518e9a5e3bd5d509ce1cbd94d3fbf11d58 | [
"Shell"
] | 1 | Shell | hiddenvs/Helium-Guides | f5021988120c23dc556e4ab43d0842553ea68574 | cf9a3da620fb0286c4a82c10ee00ec5c2dd9f8bb |
refs/heads/master | <file_sep>package Assignment1;
import java.awt.Image;
import javax.swing.ImageIcon;
/**This class contains all parameters and methods asociated with a specific tile, of which there are many in a single map instance*/
public class Tile {
private int type; /**Indicates the whether the tile is 1:scenery, 2:path, 3:tower*/
private int[] coordinates; /**Holds the coordinates of the tile*/
private Image tileImage; /**Holds the image corresponding to the tile type*/
private Tile next; /**Holds the next tile which this current tile is connected to*/
private boolean isStart=false; /**Is true if the tile is assigned as the starting tile*/
private boolean isEnd=false; /**Is true if the tile is assigned as the end tile*/
/**Sets the tile type, the coordinates of the tile and the corresponding tile image*/
public Tile(int type, int x, int y) {
this.type=type;
this.coordinates= new int[2];
this.coordinates[0]=x;
this.coordinates[1]=y;
if(type==1){
tileImage= new ImageIcon(this.getClass().getResource("scenery.png")).getImage();
}
else if(type==2){
tileImage= new ImageIcon(this.getClass().getResource("path.png")).getImage();
}
else if(type==3){
tileImage= new ImageIcon(this.getClass().getResource("tower.png")).getImage();
}
}
/**Returns the x coordinate of the tile*/
public int getXcoord(){
return this.coordinates[0];
}
/**Returns the y coordinate of the tile*/
public int getYcoord(){
return this.coordinates[1];
}
/**Returns the tile type*/
public int tileType(){
return this.type;
}
/**Returns the tile image*/
public Image getTileImage(){
return tileImage;
}
/**Returns the next tile in the path, relevant only if tile is of type path*/
public Tile getNext(){
return this.next;
}
/**Sets the next tile in the path to the provided tile, relevant only if tile is of type path*/
public void setNext(Tile next){
this.next=next;
}
/**Assigns this tile as the starting tile of the map*/
public void setStart(){
this.isStart=true;
}
/**Assigns this tile as the end tile of the map*/
public void setEnd(){
this.isEnd=true;
}
/**Returns true if the tile is a start tile*/
public boolean getStart(){
return this.isStart;
}
/**Return true if the tile is an end tile*/
public boolean getEnd(){
return this.isEnd;
}
}
<file_sep>package Assignment1;
import java.util.Scanner;
/**This class provides all methods for modifying parts of the map and an interface for creating a path through a blank map*/
public class MapDesigner {
private Map custom; /**Contains the map which will be modified by the designer*/
/**Initialises the designer by setting the map to be worked on*/
public MapDesigner(Map custom) {
this.custom=custom;
}
/**This method modifies the node at the specified coordinates to a path by creating a new path tile and overwriting the scenery tile*/
public void modifyNodeToPath(int x, int y){
custom.setTile(new Tile(2,x,y), x,y);
}
/**This method modifies the node at the specified coordinates to a tower by creating a new tower tile and overwriting the scenery tile*/
public void placeTower(int x, int y){
custom.setTile(new Tile(3,x,y), x, y);
}
/**This is an interface with the user to create a path through a blank map*/
public void createPath(){
Scanner keyboard = new Scanner(System.in);
boolean correct=false;
boolean completedPath=false;
while(!completedPath){
while(!correct){ //loop until a valid value is entered
System.out.println("Please enter a valid y coordinate of the starting node");
int y1 = keyboard.nextInt();
if(y1>=0 && y1<custom.getHeight()){ //ensures start node of path is along the leftmost edge of the map
modifyNodeToPath(0,y1);
custom.setStart(custom.getTile(0,y1));//sets the start node of the map
custom.getTile(0,y1).setStart();//assigns the tile at that point as a start node
correct=true; //end loop
}
}
boolean complete=false;
Tile current=custom.getStart();
while(!complete){ //loop until a complete path has been entered
int currentX=current.getXcoord();
int currentY=current.getYcoord();
boolean validX=false;
boolean validY=false;
int x=0;
int y=0;
while(!validX){
System.out.println("Please enter a valid x coordinate of the next path node");
x = keyboard.nextInt();
if(x==currentX || x==(currentX+1)){ //ensures the x value entered is either the same (for up and down movement) or one more (for forward movement) as the current value
validX=true;
}
}
while(!validY){
System.out.println("Please enter a valid y coordinate of the next path node");
y = keyboard.nextInt();
//ensures that the path can only move up or down if the new x value is the same as the current x value to avoid diagonal movement
//as well as preventing a path node from going out of bounds
if((y==currentY && x!=currentX)|| (y==(currentY+1) && (currentY + 1)<custom.getHeight() && x==currentX) || (y==(currentY-1) && (currentY-1)>=0 && x==currentX)){
if(!custom.isPath(x, y)){
validY=true;
}
}
}
//create new path node
modifyNodeToPath(x,y);
Tile newTile=custom.getTile(x, y);
custom.getTile(currentX, currentY).setNext(newTile);
current=newTile;
//if the new path node is adjacent to the rightmost edge of the map, set it as the end node and exit
if(x==custom.getWidth()-1){
custom.setEnd(newTile);
newTile.setEnd();
complete=true;
}
System.out.println("Path node successfully added");
}
//check if the created path is valid
boolean valid= custom.validPath();
if(valid){
System.out.println("A valid path has been created");
completedPath=true;
}
else{
System.out.println("Path is not valid, please start over");
custom.initializeBlankMap();
}
}
}
public void addTower(){
Scanner keyboard = new Scanner(System.in);
boolean validX=false;
boolean validY=false;
boolean isPath=true;
int xT=0;
int yT=0;
while(isPath){
//ensure x coordinate is within the bounds of the map
while(!validX){
System.out.println("Please enter a valid x coordinate of the tower");
xT = keyboard.nextInt();
if(xT>=0 && xT<custom.getWidth()){
validX=true;
}
}
//ensure y coordinate is within the bounds of the map
while(!validY){
System.out.println("Please enter a valid y coordinate of the tower");
yT = keyboard.nextInt();
if(yT>=0 && yT<custom.getHeight()){
validY=true;
}
}
//if the chosen tile is of scenery type, it is valid to place a tower
if(custom.getTile(xT, yT).tileType()==1){
System.out.println("Tower successfully placed");
placeTower(xT, yT);
isPath=false;
}
}
}
}
<file_sep>package Assignment1;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.util.Scanner;
/**This class is the driver which initialises all the other classes and provides the user interface for this test*/
public class MapManager {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter map width");
int widthC = keyboard.nextInt();
System.out.println("Please enter map height");
int heightC = keyboard.nextInt();
JFrame frame = new JFrame();
Map customMap= new Map("customMap", widthC, heightC);
MapDesigner customC= new MapDesigner(customMap);
customC.createPath();
customC.addTower();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Display board = new Display(customMap);
frame.add(board);
frame.setSize(customMap.getWidth()*75, customMap.getHeight()*75);
frame.setVisible(true);
}
}
| 804c3ed39af160d3faa3ad35f0b6d37e4786d8ef | [
"Java"
] | 3 | Java | EGoobie/ECSE-321-Assignments | 27ae348b21ad1a8aca5339fd9f0e15266be04804 | c70634fb2e017cfc4945f1d42fa81115f5579fe2 |
refs/heads/master | <file_sep>import requests
serverId = input("ServerID: ")
Token = input("Token: ")
RoleId = input("RoleID: ")
ChannelId = input("ChannelID: ")
url = f"https://discordapp.com/api/v8/channels/{ChannelId}/permissions/{RoleId}"
headers = {
'Authorization' : Token,
'Content-Type' : 'application/json'
}
payload1 = {
"id": RoleId,
"type": 0,
"allow": "1024",
"deny": "0"
}
payload2 = {
"id": RoleId,
"type": 0,
"allow": "0",
"deny": "1024"
}
while True:
requests.put(url, headers=headers, json=payload1)
requests.put(url, headers=headers, json=payload2)
print("Request has been sent.")
<file_sep>var request = require('request'),
askme = require('readline-sync'),
serverId = process.argv[2],
Token = process.argv[3];
RoleId = process.argv[4];
ChannelId = process.argv[5];
if(process.argv.length <= 2){
ask();
a();
} else {
a();
}
function ask(){
serverId = askme.question("ServerId ID: ");
Token = askme.question("Token: ");
RoleId = askme.question("Role ID: ");
ChannelId = askme.question("Channel ID: ");
}
function a(){
setInterval(() => {
request.put(`https://discordapp.com/api/v8/channels/${ChannelId}/permissions/${RoleId}`, {
headers: {
'Authorization' : Token,
'Content-Type' : 'application/json'
},
body: `{"id":"${RoleId}","type":0,"allow":"1024","deny":"0"}`
}, (err, res, body) => {
request.put(`https://discordapp.com/api/v8/channels/${ChannelId}/permissions/${RoleId}`, {
headers: {
'Authorization' : Token,
'Content-Type' : 'application/json'
},
body: `{"id":"759563389566451752","type":0,"allow":"0","deny":"1024"}`
}, (err, res, body) => {
console.log(body);
});
});
}, 1);
}
<file_sep># ServerOutageExploitV4
LMAO, we're back again, another exploit found to down a server, also intensely crashes discord clients. This is going to be fixed within 24 hours so take this and abuse it, kthnx. I'll just find another method when it does. Requires manage channel permissions to operate.



| 169aa65543ab17cca98bb853216526b4c1d46f88 | [
"JavaScript",
"Python",
"Markdown"
] | 3 | Python | voidlsd/ServerOutageExploitV4 | a0659c8dfb4a150203050725643c452fc6f70885 | 9ad0b839f20dcaaed8bf78cef105113721334ce1 |
refs/heads/master | <file_sep>package com.hlm.view;
import java.util.*;
import com.hlm.DAO.TabletDAO;
import com.hlm.bean.Tablet;
public class View {
public static void main(String[] args) throws Exception {
TabletDAO tabletDAO = new TabletDAO();
Scanner in = new Scanner(System.in);
while (true) {
Menu();
String line = in.nextLine();
switch (line) {
case "1":
System.out.println("่ฏท่พๅ
ฅ่ฆๆๅ
ฅ็ๅนณๆฟ๏ผๆ ผๅผไธบid:size:color:price:grand");
String cinLine = in.nextLine();
String [] arr = cinLine.split(":");
if (arr[0]==null) {
System.out.println("ไธป้ฎไธ่ฝไธบ็ฉบ");
}
else {
Tablet tablet = new Tablet(arr[0], arr[1], arr[2], arr[3], arr[4]);
tabletDAO.addTablet(tablet);
}
break;
case"2":
System.out.println("ไธ้ขๆฏๆๆๅนณๆฟไฟกๆฏ");
List<Tablet> list = tabletDAO.findAll();
for (Tablet tablet : list) {
System.out.println(tablet);
}
break;
case"3":
System.out.println("่ฏท่พๅ
ฅ่ฆๅ ้ค็ๅนณๆฟ็ID");
String id = in.nextLine();
tabletDAO.deleteByID(id);
break;
case"4":
System.out.println("่ฏท่พๅ
ฅ่ฆไฟฎๆนๅนณๆฟ็้ข่ฒ๏ผๆ ผๅผไธบid:color");
String line1 = in.nextLine();
String []arr2 = line1.split(":");
tabletDAO.changeTablet(arr2[0], arr2[1]);
break;
case"5":
System.out.println("**่ฏท่พๅ
ฅไฟฎๆนๅนณๆฟ็ๅฐบๅฏธ๏ผๆ ผๅผไธบid:size**");
String line3 = in.nextLine();
String []arr3 = line3.split(":");
tabletDAO.changeTabletSize(arr3[0], arr3[1]);
break;
case"6":
System.out.println("**่ฏทไฟฎๆนๅนณๆฟ็ไปทๆ ผ๏ผๆ ผๅผไธบid:price**");
String line4 = in.nextLine();
String []arr4 = line4.split(":");
tabletDAO.changeTabletPrice(arr4[0], arr4[1]);
break;
case"7":
System.out.println("**่ฏทไฟฎๆนๅนณๆฟ็ๅ็๏ผๆ ผๅผไธบid:grand**");
String line5 = in.nextLine();
String []arr5 = line5.split(":");
tabletDAO.changeTabletGrand(arr5[0], arr5[1]);
break;
default:
break;
}
}
}
private static void Menu () {
System.out.println("**ๅนณๆฟ็ณป็ป็ฎก็***");
System.out.println("**1.ๆๅ
ฅๅนณๆฟ**");
System.out.println("**2.ๆฅ่ฏขๆๆๅนณๆฟ**");
System.out.println("**3.ๅ ้คๅนณๆฟ**");
System.out.println("**4.ไฟฎๆนๅนณๆฟ็้ข่ฒ**");
System.out.println("**5.ไฟฎๆนๅนณๆฟ็ๅฐบๅฏธ**");
System.out.println("**6.ไฟฎๆนๅนณๆฟ็ไปทๆ ผ**");
System.out.println("**7.ไฟฎๆนๅนณๆฟ็ๅ็**");
}
}
| ad356bfda6e5ca38c3ca50e44ac3071fb28f1b98 | [
"Java"
] | 1 | Java | UbuntuLover/TabletSystem | 588578f08df53c955a1e1d8c42d2f5abfad1276a | 7b15430b0e545a1058c575db8db52fc03d0fea93 |
refs/heads/master | <repo_name>niklaus520/HyberScaner<file_sep>/tea/ConsoleApplication1/ConsoleApplication1/Wingdefines.h
#ifndef WINGDEFINES_H
#define WINGDEFINES_H
typedef unsigned long int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef signed long int int32;
typedef signed short int16;
typedef signed char int8;
//ๅฎไนๅฎ๏ผๅ ้คๅฏน่ฑกๅนถ็ฝฎNULL
#define SAFE_DELETE(p) {if(p) {delete (p);(p)=NULL;}}
//ๅฎไนๅฎ๏ผๅ ้คๅฏน่ฑกๆฐ็ปๅนถ็ฝฎNULL
#define SAFE_DELETE_ARRAY(p) {if(p) {delete[] (p);(p)=NULL;}}
/**********************************************************************/
/*่ฎพ็ฝฎ้ป่ฎค็QQ็ๆฌไธบ qq for linux preview 1.0*/
#define QQ_DEFAULT_VERSION 0X1131
/*ๅฎไน็ง็ฑปQQๅฏ้ฅ็้ฟๅบฆ๏ผ้ฝไธบ16ๅญ่*/
#define QQ_KEY_LENGTH 16
/*QQ Packet ็ๆๅคง้ฟๅบฆ*/
#define QQ_PACKET_MAX_SIZE 65535
/*QQๆฅๆๅผๅงๆ ๅฟ*/
#define QQ_HEAD_TAG 0x02
/*QQๆฅๆ็ปๆๆ ๅฟ*/
#define QQ_TAIL_TAG 0x03
/**********************************************************************/
/* QQๅฝไปคๅญ, unsigned short( 2 bytes) */
/*้ๅบ*/
#define QQ_LOGOUT 0x0001
/*ไฟๆๅจ็บฟ*/
#define QQ_KEEP_ALIVE 0x0002
/*ไฟฎๆนไฟกๆฏ*/
#define QQ_MODIFY_INFO 0x0004
/*็จๆทๆฅๆพ*/
#define QQ_SEARCH_USER 0x0005
/*่ทๅ็จๆทไฟกๆฏ*/
#define QQ_GET_USER_INFO 0x0006
/*ๅขๅ ่็ณปไบบ*/
#define QQ_ADD_FRIEND 0x0009
/*ๅ ้ค่็ณปไบบ*/
#define QQ_DELETE_FRIEND 0x000A
/*ๆทปๅ ๅฅฝๅ้ช่ฏ*/
#define QQ_ADD_FRIEND_AUTH 0x000B
/*ๆนๅ็ถๆ*/
#define QQ_CHANGE_STATUS 0x000D
/**/
#define QQ_ACK_SYS_MSG 0x0012
/*ๅ้ไฟกๆฏ*/
#define QQ_SEND_IM 0x0016
/*ๆฅๆถไฟกๆฏ*/
#define QQ_RECV_IM 0x0017
/*ๅ ้คๆ*/
#define QQ_DELETE_ME 0x001C
/*่ทๅๅฏ้ฅ*/
#define QQ_REQUEST_KEY 0x001D
#define QQ_CELL_PHONE_1 0x0021
/*่ฏทๆฑไผ่ฏๅฏ้ฅ*/
#define QQ_REQUEST_SESSION_KEY 0x0022
/*่ทๅๅฅฝๅๅ่กจ*/
#define QQ_GET_FRIEND_LIST 0x0026
/*่ทๅๅจ็บฟๅฅฝๅ*/
#define QQ_GET_FRIEND_ONLINE 0x0027
#define QQ_CELL_PHONE_2 0x0029
/*QQ็พคๅฝไปค*/
#define QQ_QUN_CMD 0x0030
#define QQ_TEST 0x0031
#define QQ_GROUP_NAME_OP 0x003C
#define QQ_UPLOAD_GROUP_FRIEND 0x003D
/*ๅคๆณจๆไฝ*/
#define QQ_MEMO_OP 0x003E
/*่ทๅๅฅฝๅๅ็ป*/
#define QQ_DOWNLOAD_GROUP_FRIEND 0x0058
#define QQ_GET_LEVEL 0x005C
#define QQ_ADVANCED_SEARCH 0x0061
/*่ฏทๆฑ้ข็ป้ไปค็*/
#define QQ_REQUEST_PRE_LOGIN_TOKEN 0x0062
#define QQ_REQUEST_EXTRA_INFORMATION 0x0065
#define QQ_TEMP_SESSION_OP 0x0066
/*QQ็ญพๅๆไฝ*/
#define QQ_SIGNATURE_OP 0x0067
#define QQ_RECV_MSG_SYS 0x0080
/*ๅฅฝๅๆนๅ็ถๆ*/
#define QQ_FRIEND_CHANGE_STATUS 0x0081
/*ๆกๆ่ฏทๆฑ*/
#define QQ_TOUCH_REQUEST 0x0091
/*่ทๅๅคฉๆฐ้ขๆฅ*/
#define QQ_WEATHER 0x00A6
#define QQ_ADD_FRIEND_EX 0x00A7
#define QQ_ADD_FRIEND_AUTH_EX 0x00A8
#define QQ_ADD_FRIEND_AUTH_INFO 0x00AE
#define QQ_VERIFY_ADDING_MSG 0x00B5
#define QQ_ADD_FRIEND_AUTH_QUESTION 0x00B7
/*่ฏทๆฑ็ป้ไปค็*/
#define QQ_REQUEST_LOGIN_TOKEN 0x00BA
/*QQไธๆฌก็ป้ๆฅๅ*/
#define QQ_LOGIN_LOCATION_CHECK 0x00DA
/*่ฏทๆฑ้ขไผ่ฏๅฏ้ฅ*/
#define QQ_REQUEST_PRE_SESSION_KEY 0X00DD
/** ๆถๆฏๅๅค็ฑปๅ - ๆญฃๅธธๅๅค */
#define QQ_IM_NORMAL_REPLY 0x01
/** ๆถๆฏๅๅค็ฑปๅ - ่ชๅจๅๅค */
#define QQ_IM_AUTO_REPLY 0x02
/** ๆถๆฏ็ๆฅๆบ*/
#define QQ_RECV_IM_NEWS 0x0018
#define QQ_RECV_IM_FROM_BUDDY 0x0084
#define QQ_RECV_IM_FROM_STRANGER 0x0085
#define QQ_RECV_IM_SYS_MESSAGE 0x0030
/**ๆถๆฏๅญ็ฑปๅ๏ผไปๅฑไบQQ_RECV_IM_TO_BUDDY*/
#define QQ_IM_TCP_REQUEST 0x0001
#define QQ_IM_ACCEPT_TCP_REQUEST 0x0003
#define QQ_IM_REJECT_TCP_REQUEST 0x0005
/*ๆฎ้ๆๆฌๆถๆฏ */
#define QQ_IM_NORMAL_TEXT 0x000B
#define QQ_IM_UDP_REQUEST 0x0035
#define QQ_IM_ACCEPT_UDP_REQUEST 0x0037
#define QQ_IM_REJECT_UDP_REQUEST 0x0039
#define QQ_IM_NOTIFY_IP 0x003B
#define QQ_IM_ARE_YOU_BEHIND_FIREWALL 0x003F
#define QQ_IM_ARE_YOU_BEHIND_PROXY 0x0041
#define QQ_IM_YES_I_AM_BEHIND_PROXY 0x0042
#define QQ_IM_NOTIFY_FILE_AGENT_INFO 0x004B
#define QQ_IM_REQUEST_CANCELED 0x0049
#endif //WINGDEFINES_H
<file_sep>/ReadTorrent/ReadTorrent/converter.cpp
#include "stdafx.h"
#include "converter.h"
std::wstring UT2WC(const char* buf)
{
int len = MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0);
std::vector<wchar_t> unicode(len);
MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len);
return std::wstring(&unicode[0]);
}
std::string WC2UT(const wchar_t* buf)
{
int len = WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
std::vector<char> utf8(len);
WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);
return std::string(&utf8[0]);
}
std::wstring MB2WC(const char* buf)
{
int len = MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
std::vector<wchar_t> unicode(len);
MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);
return std::wstring(&unicode[0]);
}
std::string WC2MB(const wchar_t* buf)
{
int len = WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);
std::vector<char> utf8(len);
WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, NULL, NULL);
return std::string(&utf8[0]);
}<file_sep>/tea/ConsoleApplication1/ConsoleApplication1/crypt.h
๏ปฟ/**
* The QQ2003C protocol plugin
*
* for gaim
*
* Copyright ยฉ 2004 Puzzlebird
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
**************************************************
* Reorganized by Minmin <<EMAIL>>, 2005-3-27
**************************************************
*/
#ifndef Crypt_H
#define Crypt_H
#define DECRYPT 0x00
#define ENCRYPT 0x01
#include "Wingdefines.h"
class Crypt
{
public:
Crypt();
~Crypt();
static void encrypt(unsigned char* instr, int32 instrlen, unsigned char* key,
unsigned char* outstr, int32* outstrlen_ptr);
static int decrypt(unsigned char* instr, int32 instrlen, unsigned char* key,
unsigned char* outstr, int32* outstrlen_ptr);
private:
static int rand(void);
static void teaEncipher(unsigned int *const v, const unsigned int *const k,
unsigned int *const w);
static void teaDecipher(unsigned int *const v, const unsigned int *const k,
unsigned int *const w);
static int qq_crypt(unsigned char flag, unsigned char* instr, int32 instrlen,
unsigned char* key, unsigned char* outstr, int32* outstrlen_ptr);
};
#endif
<file_sep>/QQ_TEA/qq_tea/qq_tea.cpp
// qq_tea.cpp : ๅฎไนๆงๅถๅฐๅบ็จ็จๅบ็ๅ
ฅๅฃ็นใ
//
// START OF FILE
/*****************************************************************************/
/*Notes: (OICQ uses 0x10 iterations, and modified something...)
IN : 64 bits of data in v[0] - v[1].
OUT: 64 bits of data in w[0] - w[1].
KEY: 128 bits of key in k[0] - k[3].
delta is chosen to be the real part of
the golden ratio: Sqrt(5/4) - 1/2 ~ 0.618034 multiplied by 2^32.
0x61C88647 is what we can track on the ASM codes.!!
*/
/*****************************************************************************/
void qq_encipher(unsigned long *const v, const unsigned long *const k, unsigned long *const w)
{
register unsigned long y = ntohl(v[0]), z = ntohl(v[1]), a = ntohl(k[0]), b = ntohl(k[1]), c = ntohl(k[2]), d = ntohl(k[3]), n = 0x10, sum = 0, delta = 0x9E3779B9; /* 0x9E3779B9 - 0x100000000 = -0x61C88647 */
while (n-- > 0) {
sum += delta;
y += ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
z += ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
} // while
w[0] = htonl(y);
w[1] = htonl(z);
} // qq_enciper
/*****************************************************************************/
void qq_decipher(unsigned long *const v, const unsigned long *const k, unsigned long *const w)
{
register unsigned long y = ntohl(v[0]), z = ntohl(v[1]), a = ntohl(k[0]), b = ntohl(k[1]), c = ntohl(k[2]), d = ntohl(k[3]), n = 0x10, sum = 0xE3779B90, // why this ? must be related with n value
delta = 0x9E3779B9;
/* sum = delta<<5, in general sum = delta * n */
while (n-- > 0) {
z -= ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
y -= ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
sum -= delta;
}
w[0] = htonl(y);
w[1] = htonl(z);
} // qq_decipher
/********************************************************************
* encrypt part
*******************************************************************/
void qq_encrypt(unsigned char *instr, int instrlen, unsigned char *key, unsigned char *outstr, int *outstrlen_prt)
{
unsigned char plain[8], // plain text buffer
plain_pre_8[8], // plain text buffer, previous 8 bytes
*crypted, // crypted text
*crypted_pre_8, // crypted test, previous 8 bytes
*inp; // current position in instr
int pos_in_byte = 1, // loop in the byte
is_header = 1, // header is one byte
count = 0, // number of bytes being crypted
padding = 0; // number of padding stuff
int rand(void) { // it can be the real random seed function
return 0xdead;
} // override with number, convenient for debug
/*** we encrypt every eight byte ***/
void encrypt_every_8_byte(void) {
for (pos_in_byte = 0; pos_in_byte < 8; pos_in_byte++) {
if (is_header) {
plain[pos_in_byte] ^= plain_pre_8[pos_in_byte];
}
else {
plain[pos_in_byte] ^= crypted_pre_8[pos_in_byte];
}
} // prepare plain text
qq_encipher((unsigned long *)plain, (unsigned long *)key, (unsigned long *)crypted); // encrypt it
for (pos_in_byte = 0; pos_in_byte < 8; pos_in_byte++) {
crypted[pos_in_byte] ^= plain_pre_8[pos_in_byte];
}
memcpy(plain_pre_8, plain, 8); // prepare next
crypted_pre_8 = crypted; // store position of previous 8 byte
crypted += 8; // prepare next output
count += 8; // outstrlen increase by 8
pos_in_byte = 0; // back to start
is_header = 0; // and exit header
} // encrypt_every_8_byte
pos_in_byte = (instrlen + 0x0a) % 8; // header padding decided by instrlen
if (pos_in_byte) {
pos_in_byte = 8 - pos_in_byte;
}
plain[0] = (rand() & 0xf8) | pos_in_byte;
memset(plain + 1, rand() & 0xff, pos_in_byte++);
memset(plain_pre_8, 0x00, sizeof(plain_pre_8));
crypted = crypted_pre_8 = outstr;
padding = 1; // pad some stuff in header
while (padding <= 2) { // at most two byte
if (pos_in_byte < 8) {
plain[pos_in_byte++] = rand() & 0xff;
padding++;
}
if (pos_in_byte == 8) {
encrypt_every_8_byte();
}
}
inp = instr;
while (instrlen > 0) {
if (pos_in_byte < 8) {
plain[pos_in_byte++] = *(inp++);
instrlen--;
}
if (pos_in_byte == 8) {
encrypt_every_8_byte();
}
}
padding = 1; // pad some stuff in tailer
while (padding <= 7) { // at most sever byte
if (pos_in_byte < 8) {
plain[pos_in_byte++] = 0x00;
padding++;
}
if (pos_in_byte == 8) {
encrypt_every_8_byte();
}
}
*outstrlen_prt = count;
} // qq_encrypt
/********************************************************************
* [decrypt part]
* return 0 if failed, otherwise return 1
********************************************************************/
int qq_decrypt(unsigned char *instr, int instrlen, unsigned char *key, unsigned char *outstr, int *outstrlen_ptr)
{
unsigned char decrypted[8], m[8], *crypt_buff, *crypt_buff_pre_8, *outp;
int count, context_start, pos_in_byte, padding;
int decrypt_every_8_byte(void) {
for (pos_in_byte = 0; pos_in_byte < 8; pos_in_byte++) {
if (context_start + pos_in_byte >= instrlen)
return 1;
decrypted[pos_in_byte] ^= crypt_buff[pos_in_byte];
}
qq_decipher((unsigned long *)decrypted, (unsigned long *)key, (unsigned long *)decrypted);
context_start += 8;
crypt_buff += 8;
pos_in_byte = 0;
return 1;
} // decrypt_every_8_byte
// at least 16 bytes and %8 == 0
if ((instrlen % 8) || (instrlen < 16))
return 0;
// get information from header
qq_decipher((unsigned long *)instr, (unsigned long *)key, (unsigned long *)decrypted);
pos_in_byte = decrypted[0] & 0x7;
count = instrlen - pos_in_byte - 10; // this is the plaintext length
// return if outstr buffer is not large enought or error plaintext length
if (*outstrlen_ptr < count || count < 0)
return 0;
memset(m, 0, 8);
crypt_buff_pre_8 = m;
*outstrlen_ptr = count; // everything is ok! set return string length
crypt_buff = instr + 8; // address of real data start
context_start = 8; // context is at the second 8 byte
pos_in_byte++; // start of paddng stuff
padding = 1; // at least one in header
while (padding <= 2) { // there are 2 byte padding stuff in header
if (pos_in_byte < 8) { // bypass the padding stuff, none sense data
pos_in_byte++;
padding++;
}
if (pos_in_byte == 8) {
crypt_buff_pre_8 = instr;
if (!decrypt_every_8_byte())
return 0;
}
} // while
outp = outstr;
while (count != 0) {
if (pos_in_byte < 8) {
*outp = crypt_buff_pre_8[pos_in_byte] ^ decrypted[pos_in_byte];
outp++;
count--;
pos_in_byte++;
}
if (pos_in_byte == 8) {
crypt_buff_pre_8 = crypt_buff - 8;
if (!decrypt_every_8_byte())
return 0;
}
} // while
for (padding = 1; padding < 8; padding++) {
if (pos_in_byte < 8) {
if (crypt_buff_pre_8[pos_in_byte] ^ decrypted[pos_in_byte])
return 0;
pos_in_byte++;
}
if (pos_in_byte == 8) {
crypt_buff_pre_8 = crypt_buff;
if (!decrypt_every_8_byte())
return 0;
}
} // for
return 1;
} // qq_decrypt
/*****************************************************************************/
/* This is the Public Function */
// return 1 is succeed, otherwise return 0
int qq_crypt(unsigned char flag,
unsigned char *instr, int instrlen, unsigned char *key, unsigned char *outstr, int *outstrlen_ptr)
{
if (flag == DECRYPT)
return qq_decrypt(instr, instrlen, key, outstr, outstrlen_ptr);
else if (flag == ENCRYPT)
qq_encrypt(instr, instrlen, key, outstr, outstrlen_ptr);
return 1; // flag must be DECRYPT or ENCRYPT
} // qq_crypt
/*****************************************************************************/
// END OF FILE<file_sep>/http/http/http.cpp
// http.cpp : ๅฎไนๆงๅถๅฐๅบ็จ็จๅบ็ๅ
ฅๅฃ็นใ
//
// Reference : https://casablanca.codeplex.com/wikipage?title=Http%20Client%20Tutorial
// : https://casablanca.codeplex.com/documentation
// : https://casablanca.codeplex.com/wikipage?title=Samples&referringTitle=Documentation
// : http://msdn.microsoft.com/en-us/library/jj950081.aspx
// : http://msdn.microsoft.com/en-us/library/jj950083.aspx
// : http://blog.csdn.net/xxxxxx91116/article/details/7971134
// : http://www.paobuke.com/develop/c/pbk1308.html
// String2Wstring : http://www.cppblog.com/kenwell/archive/2008/05/21/50661.html
// : http://www.cnblogs.com/02xiaoma/archive/2012/07/18/2597576.html
// About L and _T() : http://msdn.microsoft.com/en-us/library/windows/desktop/ff381407(v=vs.85).aspx
// : http://blog.csdn.net/nodeathphoenix/article/details/7733244
// : http://stackoverflow.com/questions/6384118/what-does-the-l-in-front-a-string-mean-in-c
// About lambda : http://blog.csdn.net/saga1979/article/details/7212639
// : http://blog.csdn.net/srzhz/article/details/7934652
// : http://blog.csdn.net/srzhz/article/details/7934483
// : http://www.cnblogs.com/hujian/archive/2012/02/15/2352050.html
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <windows.h>
using namespace concurrency;
using namespace concurrency::streams;
using namespace web::http;
using namespace web::http::client;
pplx::task<void> HTTPStreamingAsync()
{
http_client client(L"http://www.fourthcoffee.com");
// Make the request and asynchronously process the response.
return client.request(methods::GET).then([](http_response response){
// Print the status code
std::wostringstream ss;
ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
std::wcout << ss.str();
// TODO: Perform actions here reading from the response stream.
auto bodyStream = response.body();
// In this example, we print the length of the response to the console.
ss.str(std::wstring());
ss << L"Content length is " << response.headers().content_length() << L" bytes." << std::endl;
std::wcout << ss.str();
});
/* Sample output:
Server returned returned status code 200.
Content length is 63803 bytes.
*/
}
// Builds an HTTP request that uses custom header values
pplx::task<void> HTTPRequestCustomHeadersAsync(std::string hash)
{
auto fileStream = std::make_shared<ostream>();
std::wstring hash_wstr(hash.length(), L' ');
std::copy(hash.begin(), hash.end(), hash_wstr.begin());
//http_client client(L"http://bt.box.n0808.com/05/A5/05153F611B337A378F73F0D32D2C16D362D06BA5.torrent");
std::wstring full_uri(L"http://bt.box.n0808.com/");
full_uri += hash_wstr.substr(0, 2);
full_uri += L"/";
full_uri += hash_wstr.substr(38, 2);
full_uri += L"/";
full_uri += hash_wstr;
full_uri += L".torrent";
http_client client((LPTSTR)(full_uri.c_str()));
// Manually build up an HTTP request with header and request URI.
http_request request(methods::GET);
request.headers().add(L"Accept", L"*/*\r\n");
request.headers().add(L"Connection", L"Keep-Alive\r\n");
request.headers().add(L"Host", L"bt.box.n0808.com\r\n");
request.headers().add(L"Referer", L"http://bt.box.n0808.com/\r\n");
request.headers().add(L"User-Agent", L"Mozilla/4.0 (compatible; MSIE 9.11; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)\r\n");
return client.request(request).then([=](http_response response){
// Print the status code.
std::wostringstream ss;
ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
std::wcout << ss.str();
});
/* Sample output:
Server returned returned status code 200.
*/
}
void download_torrent(std::string hash, BOOL* Download_Suc)
{
auto fileStream = std::make_shared<ostream>();
std::wstring hash_wstr(hash.length(), L' ');
std::copy(hash.begin(), hash.end(), hash_wstr.begin());
std::wstring filename_wstr(L"Torrent\\"+hash_wstr+L".torrent");
pplx::task<void> requestTask = fstream::open_ostream(filename_wstr).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
std::wstring full_uri(L"http://bt.box.n0808.com/");
full_uri += hash_wstr.substr(0, 2);
full_uri += L"/";
full_uri += hash_wstr.substr(38, 2);
full_uri += L"/";
full_uri += hash_wstr;
full_uri += L".torrent";
http_client client((LPTSTR)(full_uri.c_str()));
// Build request URI and start the request.
http_request request(methods::GET);
request.headers().add(L"Accept", L"*/*\r\n");
request.headers().add(L"Connection", L"Keep-Alive\r\n");
request.headers().add(L"Host", L"bt.box.n0808.com\r\n");
request.headers().add(L"Referer", L"http://bt.box.n0808.com/\r\n");
request.headers().add(L"User-Agent", L"Mozilla/4.0 (compatible; MSIE 9.11; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)\r\n");
return client.request(request);
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
if (response.status_code() != status_codes::OK){
//return (pplx::task<size_t>)0;
printf("Error download file!\n");
*Download_Suc = FALSE;
}
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}
if (*Download_Suc == FALSE){
printf("You should delete the torrent file!\n");
int iResult = DeleteFile((LPCTSTR)(filename_wstr.c_str()));
if (iResult == NULL){
printf("Error in delete wrong torrent file, use GetLastError find reason!\n");
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//std::wcout << L"Calling HTTPStreamingAsync..." << std::endl;
//HTTPStreamingAsync().wait();
BOOL Download_Suc;
std::string aa("05153F611B337A378F73F0D32D2C16D362D06BA5");
//std::wcout << L"Calling HTTPRequestCustomHeadersAsync..." << std::endl;
//HTTPRequestCustomHeadersAsync(aa).wait();
download_torrent(aa, &Download_Suc);
system("pause");
return 0;
}
<file_sep>/ReadTorrent/ReadTorrent/metafile.cpp
#include "stdafx.h"
#include "metafile.h"
#include "converter.h"
#include <string.h>
#include <ctype.h>
#include <time.h>
//ๅฎไนๅ
จๅฑๅ้
TrackerList *trackerList = NULL;
Files *file = NULL;
char *metafile_buf = NULL; //ไฟๅญ่ฏปๆ็งๅญๆไปถ็็ผๅฒๅบ
long long metafile_size; //็งๅญๆไปถ้ฟๅบฆ
char dirname[512]; //็ฎๅฝๅ็งฐ(ๅๆไปถ)
long long filesize; //ๆป็ๆไปถๅคงๅฐ๏ผๅคๆไปถๅๆฏๆๆๆไปถๅคงๅฐไนๅ๏ผ
long long piece_length; //ๆฏไธชpiece็้ฟๅบฆ
char *pieces_hash = NULL; //ไฟๅญๆๆpiece hashๅผ็ๅญ็ฌฆไธฒ็็ผๅฒๅบๅฐๅ
long long pieces_hash_length;
int ismulti_file = 0;//ๆฏๅฆไธบๅคๆไปถ
unsigned char info_hash[20]; //ไฟๅญinfo_hash็ๅผ๏ผ่ฟๆฅtrackerๅpeerไฝฟ็จ
unsigned char peer_id[20]; //ไฟๅญๅฎขๆท็ซฏ็peer_id
//่ฏปๅๆไปถๅฐๅฐ็ผๅฒๅบ
int readfile_tobuffer(const char *filename)
{
if(filename == NULL){
return -1;
}
long i;
int res;
FILE *fp = NULL;
res = fopen_s(&fp, filename, "rb"); //ไปฅไบ่ฟๅถๅฝขๅผๆๅผ
if(fp == NULL){
printf("open file fail %s:%d\n",__FILE__,__LINE__);
return -1;
}
//่ทๅ็งๅญๆไปถ้ฟๅบฆ
fseek(fp,0,SEEK_END); //ๅฐๆไปถๆ้็งปๅจๅฐๆไปถๅฐพ
metafile_size = ftell(fp);
if(metafile_size == -1){
printf("get metafile size fail %s:%d\n",__FILE__,__LINE__);
return -1;
}
#ifdef DEBUG
printf("metafile size = %lld\n",metafile_size);
#endif
fseek(fp,0,SEEK_SET);//ๅฐๆไปถๆ้็งปๅจๅฐๆไปถๅคด
metafile_buf = (char*)malloc(metafile_size+1);
if(metafile_buf == NULL){
printf("malloc fail %s:%d \n",__FILE__,__LINE__);
return -1;
}
memset(metafile_buf,0,metafile_size);
for(i = 0;i < metafile_size;i++)
{
metafile_buf[i] = fgetc(fp);
}
metafile_buf[i] = '\0';
return 0;
}
//ๅจ็ผๅฒๅบไธญๆฅๆพๆๅฎ็ๅญ็ฌฆ๏ผ่ฟๅๅ
ถๅฐๅ๏ผๆพๅฐ่ฟๅ1๏ผๆฒกๆพๅฐ่ฟๅ0๏ผๅบ้่ฟๅ-1
int find_buf(const char *key,long long *position)
{
if(key == NULL || position == NULL)
{
return -1;
}
*position = -1;
int len = strlen(key);
int i;
for(i = 0;i < metafile_size;i++)
{
if(memcmp(metafile_buf+i,key,len) == 0){
*position = i;
return 1; //ๆพๅฐ
}
}
return 0; //ๆฒกๆพๅฐ
}
//ๅคๆญๆฏๅฆไธบๅคๆไปถ
int is_multi_file()
{
long long i;
if(find_buf("5:files",&i) == 1)
{
ismulti_file = 1;
}
#ifdef DEBUG
//printf("multi file = %d\n",ismulti_file);
#endif
return ismulti_file;
}
//ไฟๅญtracker็urlๅฐๅๅฐ้พ่กจ
int save_tracker_list()
{
//ๅ
ๆฅ็ๆๆฒกๆๅค็จ็tracker็URL,ๆ็่ฏ็ดๆฅไปannounce-listไนๅๅผๅงๆฅๆพๅนถๆทปๅ ๅฐ้พ่กจ
long long pos = -1;//่ฎฐๅฝๅจmetafile_bufไธญ็็ผๅฒๅบ็ไฝ็ฝฎ
int len = 0; //่ฎฐๅฝๅญ็ฌฆไธฒ็้ฟๅบฆ
char tempUrl[512];
memset(tempUrl,0,sizeof(tempUrl));
if(find_buf("d8:announce",&pos) == 1){
if(find_buf("13:announce-list",&pos) == 1){
pos += strlen("13:announce-list");
pos += 2; //่ทณ่ฟ2ไธชl
while(metafile_buf[pos] != 'e')
{
len = 0;
while(isdigit(metafile_buf[pos]))
{
len = len*10 + metafile_buf[pos] - '0';
pos++;
}
pos++; //pass :
int i;
for(i = 0;i < len;i++){
tempUrl[i] = metafile_buf[pos++];
}
tempUrl[i+1] = '\0';
//่ดจไฟๅญhttp็url
if(memcmp(tempUrl,"http",4) == 0){
add_tracker_list(tempUrl);
}
pos++; //pass e
if(metafile_buf[pos] == 'l'){
pos++; //pass l
}
}
}else{
//ๆฒกๆๅค็จ็tracker็url
pos += strlen("d8:announce");
while(isdigit(metafile_buf[pos]))
{
len = len *10 + metafile_buf[pos] - '0';
pos++;
}
pos++;//ๆปค่ฟ:
int i;
for(i = 0;i < len;i++){
tempUrl[i] = metafile_buf[pos++];
}
tempUrl[i+1] = '\0';
//ๆทปๅ ๅฐ้พ่กจ่็น
add_tracker_list(tempUrl);
}
}else{
printf("parse metafile fail %s:%d\n",__FILE__,__LINE__);
return -1;
}
return 0;
}
//ๅ้พ่กจไธญๆทปๅ ไธไธชurl
int add_tracker_list(const char *url)
{
if(url == NULL){
return -1;
}
TrackerList *tracker = (TrackerList *)malloc(sizeof(TrackerList));
if(tracker == NULL){
printf("malloc fail %s:%d\n",__FILE__,__LINE__);
return -1;
}
memcpy(tracker->url,url,strlen(url)+1);
tracker->next = NULL;
if(trackerList == NULL){
trackerList = tracker;
}else{
TrackerList *p = trackerList;
while(p->next != NULL){
p = p->next;
}
p->next = tracker;
}
return 0;
}
//่ทๅๆไปถๅๅๆไปถๅคงๅฐ๏ผๅฆๆๆฏๅคๆไปถ่ทๅ็ๆฏ็ฎๅฝๅ
int get_filepath_name()
{
char filename[1024];
long long pos;
unsigned long long len = 0;//ไฟๅญ่ทฏๅพๅ็้ฟๅบฆ
unsigned long long len2 = 0;
filesize = 0;
memset(filename,0,sizeof(filename));
//่ทๅพ็ฎๅฝๅ
memset(dirname,0,sizeof(dirname));
if(find_buf("4:name",&pos) == 1)
{
pos += strlen("4:name");
while(isdigit(metafile_buf[pos]))
{
len = len*10 + (metafile_buf[pos++] - '0');
}
pos++; //pass :
int i;
for(i = 0;i < len;i++)
{
dirname[i] = metafile_buf[pos++];
}
dirname[i] = '\0';
//ๅคๆญๆฏๅฆไธบๅค้ฎๆไปถ
if(is_multi_file() == 0){
//ไธๆฏๅคๆไปถ,่ทๅๆไปถ้ฟๅบฆ
if(find_buf("6:length",&pos) == 1){
pos += strlen("6:length");
pos++; //่ทณ่ฟi
while(metafile_buf[pos] != 'e' && isdigit(metafile_buf[pos]))
{
filesize = filesize * 10 + (metafile_buf[pos++] - '0');
}
#ifdef DEBUG
printf("single filesize = %lld\n",filesize);
#endif
}
}else{
//ๅคๆไปถๆจกๅผ filesize ไธบๆๆๆไปถๅคงๅฐไนๅ
if(find_buf("5:files",&pos) == 1){
pos += strlen("5:files");
pos++; //pass l
pos++; //pass d
while(metafile_buf[pos] != 'e')
{
len = 0;
len2 = 0;
memset(filename,0,sizeof(filename));
//็ฐ่ทๅๆไปถ้ฟๅบฆ
pos += strlen("6:length");
pos++; // pass i
while(isdigit(metafile_buf[pos]) && metafile_buf[pos] != 'e')
{
len = len *10 + (metafile_buf[pos++] - '0');
}
pos++; //pass e
//่ทๅๆไปถ่ทฏๅพpath
pos += strlen("4:path");
pos++; //pass l
while(isdigit(metafile_buf[pos])){
len2 = len2 *10 + (metafile_buf[pos++] - '0');
}
pos++; //pass :
int i;
for(i = 0; i < len2;i++)
{
filename[i] = metafile_buf[pos++];
}
filename[i] = '\0';
pos += 2;
if(metafile_buf[pos] == 'd')
{
pos++;
}
filesize += len;
//ๆทปๅ ๅฐFiles้พ่กจไธญ
add_toFiles(filename,len);
}
}
}
}
return 0;
}
//ๆทปๅ ไธไธชๆไปถไฟกๆฏ็ปๆไฝๅฐๆไปถ้พ่กจ
int add_toFiles(const char *filename,long long len)
{
if(filename == NULL)
return -1;
Files *pfile = (Files *)malloc(sizeof(Files));
if(pfile == NULL){
printf("malloc fail\n",__FILE__,__LINE__);
return -1;
}
memcpy(pfile->filename,filename,strlen(filename)+1);
pfile->filesize = len;
pfile->next = NULL;
if(file == NULL){
file = pfile;
}else{
Files *p = file;
while(p->next){
p = p->next;
}
p->next = pfile;
}
return 0;
}
//่ทๅๆฏไธชpiece็้ฟๅบฆ
int get_piece_length()
{
long long pos;
piece_length = 0;
if(find_buf("12:piece length",&pos) == 1){
pos += strlen("12:piece length");
pos++; //pass i
while(isdigit(metafile_buf[pos])&&(metafile_buf[pos] != 'e'))
{
piece_length = piece_length *10 + (metafile_buf[pos++] - '0');
}
}else{
printf("get piece_length fail %s:%d\n",__FILE__,__LINE__);
return -1;
}
return 0;
}
//่ทๅpieces็hashๅผ๏ผไฟๅญๅฐ็ผๅฒๅบไธญ
int get_pieces_hash()
{
//ๅ
่ทๅhashๅผ็ๅญ็ฌฆไธฒ้ฟๅบฆ
pieces_hash_length = 0;
long long pos;
if(find_buf("6:pieces",&pos) == 1)
{
pos += strlen("6:pieces");
while(metafile_buf[pos] != ':') //ๆฐๅญไปฅ๏ผ็ปๆ
{
pieces_hash_length = pieces_hash_length*10 + (metafile_buf[pos++] - '0');
}
#ifdef DEBUG
printf("pieces hash = %lld\n",pieces_hash_length);
#endif
pieces_hash = (char *)malloc(pieces_hash_length+1);
if(pieces_hash == NULL){
printf("malloc fial %s:%d \n",__FILE__,__LINE__);
return -1;
}
memset(pieces_hash,0,sizeof(pieces_hash));
pos++; //pass :
long i;
for(i = 0;i < pieces_hash_length ;i++){
pieces_hash[i] = metafile_buf[pos++];
}
pieces_hash[i] = '\0';
}
return 0;
}
// ่ฎก็ฎinfo_hash็ๅผ
int cal_info_hash()
{
//ๆพๅฐ4:infoๅ้ข็ๅญๅ
ธd็็ปๆๆ ่ฎฐe
long long begin,end,pos;
int push_pop = 0; //็จไบๆ ่ฎฐ๏ผๆพๅฐdๅฏนๅบ็e
//ๆฅๆพ4:info
if(find_buf("4:info",&pos) == 1){
pos += strlen("4:info");
begin = pos; //่ฎฐๅฝinfoๅ
ณ้ฎๅญๅฏนๅบๅผ็ๅผๅงไฝ็ฝฎ
do{
if(metafile_buf[pos] == 'd'){ //ๅญๅ
ธๅผๅคด
push_pop++;
pos++;
}
else if(isdigit(metafile_buf[pos]))
{
int i = 0;
//ๅฆๆๆฏๆฐๅญ๏ผ่ฏดๆๅ้ข่ทไธไธชๅญ็ฌฆไธฒ 5:files ่ทณ่ฟ๏ผๅๅญ็ฌฆไธฒ
while(isdigit(metafile_buf[pos])){
i = i * 10 + (metafile_buf[pos++] - '0');
}
pos++; //pass:
pos += i;
//printf("***%c\n",metafile_buf[pos]);
}
else if(metafile_buf[pos] == 'l') //ๅ่กจๅผๅคด
{
push_pop++;
pos++;
}
else if(metafile_buf[pos] == 'i' && isdigit(metafile_buf[pos+1])) //่ฏดๆๆฏๆฐๅญ
{
push_pop++;
pos++; //pass:i
while(isdigit(metafile_buf[pos])){
//่ทณ่ฟiๅeไน้ด็ๆฐๅญ
pos++;
}
// printf("***%c\n",metafile_buf[pos]);
// printf("push_pop = %d\n",push_pop);
}
else if(metafile_buf[pos == 'e']){ //ๅฆๆๆฏe push_pop-1
push_pop--;
pos++;
}
}while(push_pop > 0);
//้ๅบๅพช็ฏposๆๅe็ไธไธไธชๅญ็ฌฆ
end = pos -1;
#ifdef DEBUG
printf("begin = %c,end = %c,pos = %c\n",metafile_buf[begin],metafile_buf[end],metafile_buf[pos]);
#endif
//่ฎก็ฎinfo ๅฏนๅบไฟกๆฏ็hashๅผ,ไฟๅญๅฐinfo_hashไธญ๏ผ็จไบ่ฟๆฅtrackerๅpeer
memset(info_hash,0,sizeof(info_hash));
SHA1_CTX context;
SHA1Init(&context);
SHA1Update(&context, (unsigned char *)&metafile_buf[begin], end - begin + 1);
SHA1Final(info_hash,&context);
#ifdef DEBUG
printf("info_hash: ");
int j = 0;
for(;j<20;j++){
printf("%.2x",info_hash[j]);
}
printf("\n");
#endif
}else{
printf("get info_hash fail %s:%d\n",__FILE__,__LINE__);
return -1;
}
return 0;
}
//็ๆๅฏไธ็ไธไธชpeer_idๆฅๆ ่ฏๅฎขๆท็ซฏ,peer_idๅๅ
ซไฝๅบๅฎ-TT1000-
int get_peer_id()
{
//่ฎพ็ฝฎ้ๆบๆฐ็งๅญ
srand(time(NULL));
sprintf((char *)peer_id,"-TT1000-%12d",rand());
#ifdef DEBUG
printf("peer_id: %s\n",peer_id);
#endif
return 0;
}
//้ๆพๅจๆๅ
ๅญ
void release_memory()
{
TrackerList *pTracker = trackerList,*p = NULL;
Files *pFile = file , *q = NULL;
while(pTracker){
p = pTracker->next;
free(pTracker);
pTracker = p;
}
trackerList = NULL;
while(pFile)
{
q = pFile->next;
free(pFile);
pFile = q;
}
file = NULL;
if(metafile_buf){
free(metafile_buf);
metafile_buf = NULL;
}
if(pieces_hash){
free(pieces_hash);
pieces_hash = NULL;
}
}
//็งๅญๆไปถ่งฃๆๆจกๅ
int parse_metafile(const char * metafile_name)
{
if(metafile_name == NULL)
return -1;
//่ฏปๅ็งๅญๆไปถๅฐ็ผๅฒๅบ
if(readfile_tobuffer(metafile_name) < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
//ไฟๅญtracker็urlๅฐๅๅฐ้พ่กจ
if(save_tracker_list() < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
//่ทๅๆไปถๅๅๆไปถๅคงๅฐ๏ผๅฆๆๆฏๅคๆไปถ่ทๅ็ๆฏ็ฎๅฝๅ
if(get_filepath_name() < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
else {
test2();
}
//่ทๅๆฏไธชpiece็้ฟๅบฆ
if(get_piece_length() < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
//่ทๅpieces็hashๅผ๏ผไฟๅญๅฐ็ผๅฒๅบไธญ
if(get_pieces_hash() < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
// ่ฎก็ฎinfo_hash็ๅผ
if(cal_info_hash() < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
//็ๆๅฏไธ็ไธไธชpeer_idๆฅๆ ่ฏๅฎขๆท็ซฏ
if(get_peer_id() < 0){
printf("error : %s:%d\n",__FILE__,__LINE__);return -1;}
//้ๆพๅจๆๅ
ๅญ
release_memory();
return 0;
}
//test1
void test1()
{
TrackerList *p = trackerList;
while(p){
printf("%s\n",p->url);
p = p->next;
}
}
//test2()
void test2()
{
setlocale(LC_ALL, "");
//printf("dirpath = %s\n",dirname);
//std::wcout << L"dirpath = " << UT2WC((const char*)dirname).c_str() << std::endl;
wprintf(L"dirpath = %s\n", UT2WC((const char*)dirname).c_str());
//่พๅบๆไปถไฟกๆฏ
//if(is_multi_file()){
if (ismulti_file){
Files *p = file;
while(p){
//printf("filename = %s,filesize = %ld\n",p->filename,p->filesize);
//std::wcout << L"filename =" << UT2WC((const char*)p->filename).c_str() << std::endl;
//printf(" ,filesize = %ld\n", p->filesize);
wprintf(L"filename = %s,filesize = %lld\n", UT2WC((const char*)p->filename).c_str(), p->filesize);
p = p ->next;
}
}else{
printf("single filesize = %lld\n",filesize);
}
printf("piece_length = %lld\n",piece_length);
printf("total filesize = %lld\n",filesize);
}
void test3()
{
long i;
for(i = 0; i < pieces_hash_length;i++)
{
printf("%0x",pieces_hash[i]);
if(i%20 == 0 && i!= 0){
printf("\n");
break;
}
}
}
void test4()
{
cal_info_hash();
get_peer_id();
}
<file_sep>/HyberScaner/HyberScaner/stdafx.h
// stdafx.h : ๆ ๅ็ณป็ปๅ
ๅซๆไปถ็ๅ
ๅซๆไปถ๏ผ
// ๆๆฏ็ปๅธธไฝฟ็จไฝไธๅธธๆดๆน็
// ็นๅฎไบ้กน็ฎ็ๅ
ๅซๆไปถ
//
#pragma once
#include "targetver.h"
#include "metafile.h"
#include "converter.h"
#include "sha1.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace concurrency;
using namespace concurrency::streams;
using namespace web::http;
using namespace web::http::client;
// TODO: ๅจๆญคๅคๅผ็จ็จๅบ้่ฆ็ๅ
ถไปๅคดๆไปถ
<file_sep>/Speed/loveyou/loveyou.cpp
// loveyou.cpp : ๅฎไนๆงๅถๅฐๅบ็จ็จๅบ็ๅ
ฅๅฃ็นใ
//
// Reference : http://hi.baidu.com/roumezalend/item/78a07fad30184f268919d3b9
// : http://blog.csdn.net/pillar_zuo/article/details/8439014
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#define HAVE_REMOTE
#include <pcap.h>
#include <winsock.h>
#include <WinSock2.h>
#include <windows.h>
#pragma comment(lib, "wpcap.lib")
#pragma comment(lib, "ws2_32.lib")
void usage();
void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *);
void SetCursorPosition(int x, int y);
void ClearScreen(void);
void ClearLine(int x);
int _tmain(int argc, _TCHAR* argv[])
{
pcap_if_t *alldevs;
pcap_if_t *d;
//pcap_t *fp;
char errbuf[PCAP_ERRBUF_SIZE];
struct timeval st_ts;
u_int netmask;
int inum;
int i = 0;
pcap_t *adhandle;
struct bpf_program fcode;
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* ๆๅฐๅ่กจ */
for (d = alldevs; d; d = d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if (i == 0)
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):", i);
scanf_s("%d", &inum);
if (inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* ้ๆพ่ฎพๅคๅ่กจ */
pcap_freealldevs(alldevs);
return -1;
}
/* ่ทณ่ฝฌๅฐ้ไธญ็้้
ๅจ */
for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++);
/* ๆๅผ่ฎพๅค */
if ((adhandle = pcap_open(d->name, // ่ฎพๅคๅ
65536, // 65535ไฟ่ฏ่ฝๆ่ทๅฐไธๅๆฐๆฎ้พ่ทฏๅฑไธ็ๆฏไธชๆฐๆฎๅ
็ๅ
จ้จๅ
ๅฎน
PCAP_OPENFLAG_PROMISCUOUS, // ๆททๆๆจกๅผ
1000, // ่ฏปๅ่ถ
ๆถๆถ้ด
NULL, // ่ฟ็จๆบๅจ้ช่ฏ
errbuf // ้่ฏฏ็ผๅฒๆฑ
)) == NULL)
{
fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
/* ้ๆพ่ฎพๅคๅ่กจ */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* ไธ็จๅ
ณๅฟๆฉ็ ๏ผๅจ่ฟไธช่ฟๆปคๅจไธญ๏ผๅฎไธไผ่ขซไฝฟ็จ */
netmask = 0xffffff;
// ็ผ่ฏ่ฟๆปคๅจ
if (pcap_compile(adhandle, &fcode, "tcp", 1, netmask) <0)
{
fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n");
/* ้ๆพ่ฎพๅคๅ่กจ */
return FALSE;
}
//่ฎพ็ฝฎ่ฟๆปคๅจ
if (pcap_setfilter(adhandle, &fcode)<0)
{
fprintf(stderr, "\nError setting the filter.\n");
pcap_close(adhandle);
/* ้ๆพ่ฎพๅคๅ่กจ */
return FALSE;
}
/* ๅฐๆฅๅฃ่ฎพ็ฝฎไธบ็ป่ฎกๆจกๅผ */
if (pcap_setmode(adhandle, MODE_STAT)<0)
{
fprintf(stderr, "\nError setting the mode.\n");
pcap_close(adhandle);
/* ้ๆพ่ฎพๅคๅ่กจ */
return FALSE;
}
ClearScreen();
printf("TCP traffic summary:\n");
/* ๅผๅงไธปๅพช็ฏ */
pcap_loop(adhandle, 0, dispatcher_handler, (PUCHAR)&st_ts);
pcap_close(adhandle);
return TRUE;
}
void dispatcher_handler(u_char *state, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
struct timeval *old_ts = (struct timeval *)state;
u_int delay;
LARGE_INTEGER Bps, Pps;
struct tm *ltime;
char timestr[16];
time_t local_tv_sec;
/* ไปฅๆฏซ็ง่ฎก็ฎไธไธๆฌก้ๆ ท็ๅปถ่ฟๆถ้ด */
/* ่ฟไธชๅผ้่ฟ้ๆ ทๅฐ็ๆถ้ดๆณ่ทๅพ */
delay = (header->ts.tv_sec - old_ts->tv_sec) * 1000000 - old_ts->tv_usec + header->ts.tv_usec;
/* ่ทๅๆฏ็ง็ๆฏ็นๆฐb/s */
Bps.QuadPart = (((*(LONGLONG*)(pkt_data + 8)) * 8 * 1000000) / (delay));
/* ^ ^
| |
| |
| |
ๅฐๅญ่่ฝฌๆขๆๆฏ็น -- |
|
ๅปถๆถๆฏไปฅๆฏซ็ง่กจ็คบ็ --
*/
/* ๅพๅฐๆฏ็ง็ๆฐๆฎๅ
ๆฐ้ */
Pps.QuadPart = (((*(LONGLONG*)(pkt_data)) * 1000000) / (delay));
/* ๅฐๆถ้ดๆณ่ฝฌๅไธบๅฏ่ฏๅซ็ๆ ผๅผ */
local_tv_sec = header->ts.tv_sec;
ltime = localtime(&local_tv_sec);
strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);
SetCursorPosition(0, 1);
ClearLine(1);
SetCursorPosition(0, 1);
/* ๆๅฐๆถ้ดๆณ*/
printf("%s ", timestr);
/* ๆๅฐ้ๆ ท็ปๆ */
printf("BPS=%I64u ", Bps.QuadPart);
printf("PPS=%I64u\n", Pps.QuadPart);
//ๅญๅจๅฝๅ็ๆถ้ดๆณ
old_ts->tv_sec = header->ts.tv_sec;
old_ts->tv_usec = header->ts.tv_usec;
}
void usage()
{
printf("\nShows the TCP traffic load, in bits per second and packets per second.\nCopyright (C) 2002 <NAME>.\n");
printf("\nUsage:\n");
printf("\t tcptop adapter\n");
printf("\t You can use \"WinDump -D\" if you don't know the name of your adapters.\n");
exit(0);
}
void SetCursorPosition(int x, int y)
{
COORD cd;
cd.X = x;
cd.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cd);
}
void ClearScreen(void)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO bInfo;
GetConsoleScreenBufferInfo(hOut, &bInfo);
COORD home = { 0, 0 };
WORD att = bInfo.wAttributes;
unsigned long size = bInfo.dwSize.X * bInfo.dwSize.Y;
FillConsoleOutputAttribute(hOut, att, size, home, NULL);
FillConsoleOutputCharacter(hOut, ' ', size, home, NULL);
SetCursorPosition(0, 0);
}
void ClearLine(int x)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO bInfo;
GetConsoleScreenBufferInfo(hOut, &bInfo);
COORD home = { 0, x };
WORD att = bInfo.wAttributes;
unsigned long size = bInfo.dwSize.X;
FillConsoleOutputAttribute(hOut, att, size, home, NULL);
FillConsoleOutputCharacter(hOut, ' ', size, home, NULL);
}<file_sep>/QQ_TEA/qq_tea/main.cpp
#include "stdafx.h"
#include <windows.h>
#include <string.h>
#include <WinSock2.h>
//#include "QQtea.h"
void QQ_encrypt(BYTE *pPlainData, DWORD len, BYTE *pKey, BYTE *pCryptData); //QQ็teaๅ ๅฏ็ฎๆณ
UINT QQ_decrypt(BYTE *pCryptData, DWORD len, BYTE *pKey, BYTE *pPlainData); //QQ็tea่งฃๅฏ็ฎๆณ
void dec_block(DWORD *v, DWORD *k, DWORD *out); //็จไบ่งฃๅฏ8ๅญ่็ๅฏๆๅ
CHAR * data = "<KEY>";
CHAR * key = "7777772E74656E63656E742E636F6D2E";
CHAR plain[50] = {};
//*************************************************
// ๅฝๆฐdec_blockๅฐ8ๅญ่็ๅฏๆๅ่งฃๅฏ
// ่พๅ
ฅin๏ผๅฏๆๅ็ๆ้
// ่พๅ
ฅk๏ผๅฏ้ฅ็ๆ้
// ่พๅบout๏ผๆๆๅ็ๆ้
//*************************************************
void dec_block(DWORD *in, DWORD *k, DWORD *out)
{
//ๅๆฐๆฃๆฅ
if (in == NULL || k == NULL || out == NULL)
{
return;
}
int round = 16;//่ฟญไปฃ็่ฝฎๆฐ
DWORD y = 0, z = 0, a = 0, b = 0, c = 0, d = 0;
//ๅฆๆ่พๅ
ฅไธบ็ฝ็ปๅญ่ๆต
//ๅฐ่พๅ
ฅ็ๅฏๆไธๅฏ้ฅ่ฟ่กๅญ่้กบๅบ็่ฝฌๆข
if (1)
{
y = ntohl(in[0]); z = ntohl(in[1]);
a = ntohl(k[0]); b = ntohl(k[1]); c = ntohl(k[2]); d = ntohl(k[3]);
}
else
{
y = in[0]; z = in[1];
a = k[0]; b = k[1]; c = k[2]; d = k[3];
}
DWORD delta = 0x9E3779B9; // (sqrt(5)-1)/2*2^32
DWORD sum = 0;
if (round == 32)
sum = 0xC6EF3720; // delta << 5
else if (round == 16)
sum = 0xE3779B90; // delta << 4
//่ฟ่ก่ฟญไปฃ่งฃๅฏ่ฟ็ฎ๏ผround่กจ็คบ่ฟญไปฃ่ฝฎๆฐ
while (round--)
{
z -= ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
y -= ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
sum -= delta;
}
//ๅฆๆ่พๅบไธบ็ฝ็ปๅญ่ๆต
//ๅฐ่พๅบ็ๆๆ่ฟ่กๅญ่้กบๅบ็่ฝฌๆข
if (1)//่ฟ้ไธๅฎไธบ็ฝ็ปๅญ่ๆต๏ผๆ
็ฝฎ1
{
out[0] = ntohl(y); out[1] = ntohl(z);
}
else
{
out[0] = y; out[1] = z;
}
}
//*************************************************
// ๅฝๆฐQQ_encrypt ๏ผๅ ๅฏQQไฟกๆฏ
// ่พๅ
ฅpPlainData ๏ผ้่ฆๅ ๅฏ็ๆๆ
// ่พๅ
ฅlen๏ผๆๆ็้ฟๅบฆ
// ่พๅ
ฅpKey๏ผๅฏ้ฅ
// ่พๅบpCryptData๏ผๅ ๅฏๅ็ๅฏๆ
//*************************************************
void QQ_encrypt(BYTE *pPlainData, DWORD len, BYTE *pKey, BYTE *pCryptData)
{
//implementation
return ;
}
//*************************************************
// ๅฝๆฐQQ_decrypt ๏ผ่งฃๅฏQQไฟกๆฏ
// ่พๅ
ฅpCryptData ๏ผ้่ฆ่งฃๅฏ็ๅฏๆ็ๆ้
// ่พๅ
ฅlen๏ผๅฏๆ็้ฟๅบฆ
// ่พๅ
ฅpKey๏ผๅฏ้ฅ็ๆ้
// ่พๅบpPlainData๏ผ่งฃๅฏๅๆๆ็ๆ้
//*************************************************
UINT QQ_decrypt(BYTE *pCryptData, unsigned int len, BYTE *pKey, BYTE *pPlainData)
{
//ๅๆฐๆฃๆฅ
if (pCryptData == NULL || pKey == NULL)
{
return 0;
}
BYTE plain[8]; //็จๆฅๅญๆพ่งฃๅฏๅ็ๅผ
BYTE precrypt[8]; //็จๆฅๅญๆพไธๆฌก่งฃๅฏ็ๅฏๆ
BYTE *pcrypt, *pre_crypt;
BYTE *pplain; //ไธๆฌก่งฃๅฏๅบ็ๆๆ
pcrypt = pCryptData;
bool header = true;
//ๆฃๆฅๅฏๆ้ฟๅบฆ๏ผๆฏๅฆๆญฃ็กฎ
if (0 != len % 8 || len < 16)
{
//MessageBox(NULL,_T("่งฃๅฏๅคฑ่ดฅ๏ผๅฏๆ้ฟๅบฆไธๆญฃ็กฎ๏ผ"),_T("error!"),MB_OK|MB_ICONWARNING);
return 0;
}
//่ฎก็ฎๆๆ้ฟๅบฆplain_len
dec_block((DWORD*)pCryptData, (DWORD*)pKey, (DWORD*)plain);
DWORD pos = plain[0] & 0x07;
long plain_len = len - pos - 0x0A;
DWORD plainlen = plain_len;
if (plain_len < 0)
{
//MessageBox(NULL,_T("่งฃๅฏๅคฑ่ดฅ๏ผ"),_T("error!"),MB_OK|MB_ICONWARNING);
return 0;
}
pPlainData = new BYTE[plain_len]; //ไธบๆๆๅๅ้
็ฉบ้ด
memset(pPlainData, 0, plain_len);
pplain = pPlainData;
// ่ฟไธชๆฏไธดๆถ็preCrypt๏ผๅๅ ๅฏๆถ็ฌฌไธไธช8ๅญ่ๅๆฒกๆprePlainไธๆ ท
memset(precrypt, 0, 8);
pos++;
int padding = 1;
while (padding < 3)
{
if (pos < 8)//่ฏๆๅคด8ๅญ่ไธญๆๆๆไฟกๆฏ
{
pos++;
padding++;
}
if (pos == 8)//่ฏๆๅคด8ๅญ่้ฝๆฏๆ ็จ็ๅกซๅ
{
//่งฃๅฏ8ๅญ่
memcpy(precrypt, pcrypt, 8);
pre_crypt = pcrypt;
pcrypt += 8;
for (int i = 0; i< 8; i++)
{
plain[i] ^= pcrypt[i];//ไธๆฌกๆๆ ^ ๆญคๆฌกๅฏๆ
}
dec_block((DWORD*)plain, (DWORD*)pKey, (DWORD*)plain);
pos = 0;
}
}
DWORD offset = 0;
while (plain_len != 0)
{
if (pos < 8)//
{
if (header)
{
pPlainData[offset] = plain[pos] ^ precrypt[pos];
}
else
{
//ไฟๅญไฝฟ็จๆญคๆฌกๆๆ^ไธๆฌกๅฏๆ
pPlainData[offset] = plain[pos] ^ pre_crypt[pos];
}
plain_len--;
pos++;
offset++;
}
if (pos == 8)
{
header = false;
pre_crypt = pcrypt;
pcrypt += 8;
for (int i = 0; i< 8; i++)
{
plain[i] ^= pcrypt[i];//ไธๆฌกๆๆ ^ ๆญคๆฌกๅฏๆ
}
dec_block((DWORD*)plain, (DWORD*)pKey, (DWORD*)plain);
pos = 0;
}
}
for (padding = 1; padding <= 7; padding++)
{
if (pos < 8)
{
if ((plain[pos] ^ pre_crypt[pos]) != 0)
{
//MessageBox(NULL,_T("่งฃๅฏๅคฑ่ดฅ๏ผ"),_T("error!"),MB_OK|MB_ICONWARNING);
delete[]pPlainData;
return 0;
}
pos++;
}
if (pos == 8)
{
pre_crypt = pcrypt; pcrypt += 8;
if ((unsigned int)(pcrypt - pCryptData) >= len)
{
return plainlen;
}
for (int i = 0; i< 8; i++)
{
plain[i] ^= pcrypt[i];//ไธๆฌกๆๆ ^ ๆญคๆฌกๅฏๆ
}
dec_block((DWORD*)plain, (DWORD*)pKey, (DWORD*)plain);
pos = 0;
}
}
return plainlen;
}
int _tmain(int argc, _TCHAR* argv[])
{
int res = 0;
res = QQ_decrypt((BYTE*)data, strlen((CHAR *)data), (BYTE*)key, (BYTE*)plain);
return 0;
}<file_sep>/ReadTorrent/ReadTorrent/converter.h
#ifndef __CONVERTER_H__
#define __CONVERTER_H__
// Reference : http://msdn.microsoft.com/en-us/library/windows/desktop/dd319072%28v=vs.85%29.aspx
// : http://www.open-abc.com/ccode-261.html(*****)
// : http://zhidao.baidu.com/link?url=qzoIFpddB_LmNcQvyK673Dhe4YxVZcyWNktNs4PYmDAWgO0WZQUuyENmoX2zazcpynCbT3sRSIW2A9KKHsEknK
// : http://www.cnblogs.com/xiaoyz/archive/2008/10/11/1308860.html
// : http://hi.baidu.com/hehehehello/item/dcc44a4a6afc690e6dc2f08b
// : http://hi.baidu.com/lpzsybgekvbdkrd/item/fe71b323b128834347996251
// : http://blog.csdn.net/vagrxie/article/details/3961417
#include "stdafx.h"
#include <vector>
#include <windows.h>
std::wstring UT2WC(const char* buf);
std::string WC2UT(const wchar_t* buf);
std::wstring MB2WC(const char* buf);
std::string WC2MB(const wchar_t* buf);
#endif<file_sep>/http/http/ReadMe.txt
๏ปฟ========================================================================
ๆงๅถๅฐๅบ็จ็จๅบ๏ผhttp ้กน็ฎๆฆ่ฟฐ
========================================================================
ๅบ็จ็จๅบๅๅฏผๅทฒไธบๆจๅๅปบไบๆญค http ๅบ็จ็จๅบใ
ๆฌๆไปถๆฆ่ฆไป็ป็ปๆ http ๅบ็จ็จๅบ็ๆฏไธชๆไปถ็ๅ
ๅฎนใ
http.vcxproj
่ฟๆฏไฝฟ็จๅบ็จ็จๅบๅๅฏผ็ๆ็ VC++ ้กน็ฎ็ไธป้กน็ฎๆไปถ๏ผๅ
ถไธญๅ
ๅซ็ๆ่ฏฅๆไปถ็ Visual C++ ็็ๆฌไฟกๆฏ๏ผไปฅๅๆๅ
ณไฝฟ็จๅบ็จ็จๅบๅๅฏผ้ๆฉ็ๅนณๅฐใ้
็ฝฎๅ้กน็ฎๅ่ฝ็ไฟกๆฏใ
http.vcxproj.filters
่ฟๆฏไฝฟ็จโๅบ็จ็จๅบๅๅฏผโ็ๆ็ VC++ ้กน็ฎ็ญ้ๅจๆไปถใๅฎๅ
ๅซๆๅ
ณ้กน็ฎๆไปถไธ็ญ้ๅจไน้ด็ๅ
ณ่ไฟกๆฏใๅจ IDE ไธญ๏ผ้่ฟ่ฟ็งๅ
ณ่๏ผๅจ็นๅฎ่็นไธไปฅๅ็ปๅฝขๅผๆพ็คบๅ
ทๆ็ธไผผๆฉๅฑๅ็ๆไปถใไพๅฆ๏ผโ.cppโๆไปถไธโๆบๆไปถโ็ญ้ๅจๅ
ณ่ใ
http.cpp
่ฟๆฏไธปๅบ็จ็จๅบๆบๆไปถใ
/////////////////////////////////////////////////////////////////////////////
ๅ
ถไปๆ ๅๆไปถ:
StdAfx.h, StdAfx.cpp
่ฟไบๆไปถ็จไบ็ๆๅไธบ http.pch ็้ข็ผ่ฏๅคด (PCH) ๆไปถๅๅไธบ StdAfx.obj ็้ข็ผ่ฏ็ฑปๅๆไปถใ
/////////////////////////////////////////////////////////////////////////////
ๅ
ถไปๆณจ้:
ๅบ็จ็จๅบๅๅฏผไฝฟ็จโTODO:โๆณจ้ๆฅๆ็คบๅบๆทปๅ ๆ่ชๅฎไน็ๆบไปฃ็ ้จๅใ
/////////////////////////////////////////////////////////////////////////////
<file_sep>/ReadTorrent/ReadTorrent/ReadTorrent.cpp
// ReadTorrent.cpp : ๅฎไนๆงๅถๅฐๅบ็จ็จๅบ็ๅ
ฅๅฃ็นใ
//
// Reference : http://www.oschina.net/code/snippet_250934_12178
// : http://www.cnblogs.com/xiaoyz/archive/2008/10/11/1308860.html
// : http://hi.baidu.com/hehehehello/item/dcc44a4a6afc690e6dc2f08b
// : http://stackoverflow.com/questions/406695/reading-the-fileset-from-a-torrent
// : https://github.com/kriben/bencode
// : http://stackoverflow.com/questions/11334173/bencode-parser-in-c
// : http://www.open-abc.com/ccode-261.html
#include "stdafx.h"
#include "metafile.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
//parse_metafile("Torrent\\05153F611B337A378F73F0D32D2C16D362D06BA5.torrent");
parse_metafile("Torrent\\18b7e6cae325e9fdc504f6a80332a047.torrent");
//test2();
system("pause");
return 0;
}
<file_sep>/HyberScaner/HyberScaner/HyberScaner.cpp
// HyberScaner.cpp : ๅฎไนๆงๅถๅฐๅบ็จ็จๅบ็ๅ
ฅๅฃ็นใ
//
//
// Reference: http://blog.chinaunix.net/uid-26377420-id-3501511.html
// : http://huaidan.org/archives/1966.html
// : http://www.ferrisxu.com/WinPcap/html/index.html
// : http://www.freesoft.org/CIE/Course/Section4/8.htm
// : http://www.cnblogs.com/blacksword/archive/2012/03/22/2411624.html
// : http://blog.chinaunix.net/uid-26377420-id-3501511.html
// : http://www.binarytides.com/code-packet-sniffer-c-winpcap/
// : http://en.wikipedia.org/wiki/Transmission_Control_Protocol
// : http://en.wikipedia.org/wiki/Ethernet_frame
// : http://en.wikipedia.org/wiki/IPv4_header
// : http://en.wikipedia.org/wiki/List_of_IP_protocol_numbers
// : http://hi.baidu.com/cannotforget/item/661868293e94af3295f62b56
// : http://bbs.csdn.net/topics/390532447
// : http://blog.sina.com.cn/s/blog_48a0f2740100ka71.html
//DLL: : http://www.cnblogs.com/guyan/archive/2012/08/08/2627976.html
// : http://www.cnblogs.com/chio/archive/2007/09/19/897868.html
// : http://www.cnblogs.com/chio/articles/778762.html
// : http://www.cnblogs.com/chio/archive/2007/11/03/948480.html
// : http://www.cnblogs.com/chio/archive/2008/08/05/1261296.html
// : http://www.cnblogs.com/chio/articles/792437.html
// : http://www.cnblogs.com/chio/articles/792366.html
//
//CPU: : http://zhangyafeikimi.iteye.com/blog/378658
//
//Process bar : http://www.oschina.net/code/snippet_124879_6708
// : http://blog.csdn.net/leeshuheng/article/details/6975762
//Console : http://wenku.baidu.com/link?url=jNXCs0gSunEeGLpUspD38ivKQPgX-J_w9CkP1-IjhnnaNjh8PbntDO17KGWJPBVht9DyFy-VIQxOH1d25kQl8CdFiviXW0zmn-LAl0EHU6_
// : http://www.yesky.com/127/1633627.shtml
/*******************************************************************
* IPv4 Header Format
*
* 0 | 1 | 2 | 3
* 0 1 2 3 4 5 6 7|8 9 0 1 2 3 4 5|6 7 8 9 0 1 2 3|4 5 6 7 8 9 0 1
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*|Version| IHL | DSCP |ECN| Total Length |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Identification |0|D|M| Fragment Offset |
*| |0|F|F| |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Time To Live | Protocol | Header Checksum |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Source IP Address |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Destination IP Address |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Options (if IHL > 5) |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* IPv4 Header Format
*
* Note that one tick mark represents one bit position.
*
*******************************************************************/
/*******************************************************************
* TCP Header Format
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Source Port | Destination Port |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Sequence Number |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Acknowledgment Number |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Data | Re |N|C|E|U|A|P|R|S|F| |
*| Offset|serve|S|W|C|R|C|S|S|Y|I| Window Size |
*| | d | |R|E|G|K|H|T|N|N| |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Checksum | Urgent Pointer |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| Options | Padding |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*| data |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* TCP Header Format
*
* Note that one tick mark represents one bit position.
*
*******************************************************************/
#include "stdafx.h"
#define HAVE_REMOTE
#include <pcap.h>
#include <winsock.h>
#include <WinSock2.h>
#include <windows.h>
#include <ntddndis.h>
#include <packet32.h>
#include <signal.h>
//#include "crypt.h"
#pragma comment(lib, "wpcap.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "packet.lib")
#pragma comment(lib, "Advapi32.lib")
//#pragma waring(disable : 4996)
#define ETHER_ADDR_LEN 6
#define ETHERTYPE_IP 0x0800 /* ip protocol */
#define TCP_PROTOCAL 0x0600 /* tcp protocol */
#define ENV_VAR_STRING_COUNT (sizeof(envVarStrings)/sizeof(TCHAR*))
#define INFO_BUFFER_SIZE 32767
#define Max_Num_Adapter 10
typedef struct ether_header {
u_char ether_shost[ETHER_ADDR_LEN]; /* source Ethernet address, 6 bytes */
u_char ether_dhost[ETHER_ADDR_LEN]; /* destination Ethernet address, 6 bytes */
u_short ether_type; /* Ethernet type, 2 bytes */
} ether_header;
typedef struct ip_address{
UCHAR byte1;
UCHAR byte2;
UCHAR byte3;
UCHAR byte4;
} ip_address;
/* --------------------------------------- OLD ----------------------------------------------
typedef struct ip_header{
UCHAR ver_ihl; // ็ๆฌ (4 bits) + ้ฆ้จ้ฟๅบฆ (4 bits)
UCHAR tos; // ๆๅก็ฑปๅ(Type of service)
USHORT tlen; // ๆๅก็ฑปๅ(Type of service)
USHORT identification; // ๆ ่ฏ(Identification)
USHORT flags_fo; // ๆ ๅฟไฝ(Flags) (3 bits) + ๆฎตๅ็งป้(Fragment offset) (13 bits)
UCHAR ttl; // ๅญๆดปๆถ้ด(Time to live)
UCHAR proto; // ๅ่ฎฎ(Protocol)
USHORT crc; // ้ฆ้จๆ ก้ชๅ(Header checksum)
ip_address saddr; // ๆบๅฐๅ(Source address)
ip_address daddr; // ็ฎ็ๅฐๅ(Destination address)
UINT op_pad; // ้้กนไธๅกซๅ
(Option + Padding)
} ip_header;
------------------------------------------- OLD ----------------------------------------------*/
//Ip header (v4)
typedef struct ip_header
{
unsigned char ip_header_len : 4; // 4-bit header length (in 32-bit words) normally=5 (Means 20 Bytes may be 24 also)
unsigned char ip_version : 4; // 4-bit IPv4 version
//unsigned char ip_tos; // IP type of service
unsigned char ip_ecn : 2; // Explicit Congestion Notification
unsigned char ip_dscp : 6; // Differentiated Services Codepoint
unsigned short ip_total_length; // Total length
unsigned short ip_id; // Unique identifier
unsigned char ip_frag_offset : 5; // Fragment offset field
unsigned char ip_more_fragment : 1;
unsigned char ip_dont_fragment : 1;
unsigned char ip_reserved_zero : 1;
unsigned char ip_frag_offset1; //fragment offset
unsigned char ip_ttl; // Time to live
unsigned char ip_protocol; // Protocol(TCP,UDP etc)
unsigned short ip_checksum; // IP checksum
unsigned int ip_srcaddr; // Source address
unsigned int ip_destaddr; // Source address
} ip_header;
typedef struct udp_header{
USHORT sport; // ๆบ็ซฏๅฃ(Source port)
USHORT dport; // ็ฎ็็ซฏๅฃ(Destination port)
USHORT len; // UDPๆฐๆฎๅ
้ฟๅบฆ(Datagram length)
USHORT crc; // ๆ ก้ชๅ(Checksum)
} udp_header;
/* --------------------------------------- OLD ----------------------------------------------
typedef struct tcp_header{
USHORT sport; // ๆบ็ซฏๅฃ(Source port)
USHORT dport; // ็ฎ็็ซฏๅฃ(Destination port)
UINT seq; // Sequence Number
UINT ack_seq; // Acknowledgment Number
UCHAR th_lenres; //
UCHAR flags; //
USHORT win; //
USHORT sum; //
USHORT urp; //
} tcp_header;
------------------------------------------ - OLD----------------------------------------------*/
// TCP header
typedef struct tcp_header{
unsigned short source_port; // source port
unsigned short dest_port; // destination port
unsigned int sequence; // sequence number - 32 bits
unsigned int acknowledge; // acknowledgment number - 32 bits
unsigned char ns :1; //Nonce Sum Flag Added in RFC 3540.
unsigned char reserved_part1:3; //according to RFC
unsigned char data_offset:4; /*The number of 32-bit words in the TCP header.This indicates where the data begins.
The length of the TCP header is always a multiple
of 32 bits.*/
unsigned char fin : 1; //Finish Flag
unsigned char syn : 1; //Synchronize Flag
unsigned char rst : 1; //Reset Flag
unsigned char psh : 1; //Push Flag
unsigned char ack : 1; //Acknowledgment Flag
unsigned char urg : 1; //Urgent Flag
unsigned char ecn : 1; //ECN-Echo Flag
unsigned char cwr : 1; //Congestion Window Reduced Flag
unsigned short window; // window
unsigned short checksum; // checksum
unsigned short urgent_pointer; // urgent pointer
} tcp_header;
typedef struct icmp_header {
BYTE type; // ICMP Error type
BYTE code; // Type sub code
USHORT checksum;
USHORT id;
USHORT seq;
} icmp_header;
TCHAR* envVarStrings[] =
{
TEXT("OS = %OS%"),
TEXT("PATH = %PATH%"),
TEXT("HOMEPATH = %HOMEPATH%"),
TEXT("TEMP = %TEMP%")
};
void pcap_if_print(pcap_if_t* d);
char *iptos(ULONG in);
char *ip6tos(struct sockaddr *sockaddr, char *address, int addrlen);
void get_packet(pcap_t* adhandle);
void packet_handler(UCHAR *prama, const struct pcap_pkthdr *header, const UCHAR *pkt_data);
void process_packet(UCHAR* data, int size);
void print_ethernet_header(UCHAR* buffer);
void print_ip_header(UCHAR* buffer, int size);
void print_tcp_packet(UCHAR* buffer, int size);
void print_udp_packet(UCHAR* buffer, int size);
void print_icmp_packet(UCHAR* buffer, int size);
void print_data(UCHAR* data, int size);
void download_torrent(std::string hash, BOOL* Download_Suc);
void statistics(int sig);
void SetCursorPosition(int x, int y);
void ClearScreen(void);
void ClearLine(int x);
void company(void);
void print_current_time(BOOL);
void print_computer_info(void);
void printError(TCHAR* msg);
void repaint(int line);
//typedef char*(WINAPI *decode_func)(char*, char*);
//#using "RedQ_1.dll"
//using namespace RedQ;
//using namespace System;
//using namespace System::Runtime::InteropServices;
FILE *logfile;
DWORD failed_decrypt_num = 0;
DWORD succeed_decrypt_num = 0;
int _tmain(int argc, _TCHAR* argv[])
{
pcap_if_t *alldevs;
pcap_if_t *d;
pcap_t *adhandle;
int i = 0;
int num;
UINT netmask;
//struct timeval st_ts;
char packet_filter[] = "ip";
char errbuf[PCAP_ERRBUF_SIZE + 1];
char source[PCAP_ERRBUF_SIZE + 1];
struct bpf_program fcode;
int iResult = fopen_s(&logfile, "Log\\Megnet.log", "a");
if (iResult != NULL){
printf("Error in open log file!\n");
return -1;
}
//fprintf(logfile, "My Love\n");
SetConsoleTitle(L"HeheV1.0");
//SYSTEMTIME st, lt;
//GetSystemTime(&st);
//GetLocalTime(<);
//printf("The system time is: %02d:%02d:%02d\n", st.wHour, st.wMinute, st.wSecond);
//printf("The local time is: %02d:%02d:%02d\n", lt.wHour, lt.wMinute, lt.wSecond);
//company();
//print_computer_info();
//HMODULE hDll;
//decode_func decode;
//hDll = LoadLibrary(L"tea.dll");
//if (hDll != NULL){
// decode = (decode_func)GetProcAddress(hDll, "Decode");
//} else {
// printf("Error in LoadLibrary!\n");
// system("pause");
// return FALSE;
//}
//if (decode == NULL){
// printf("Error in GetProcAddress!\n");
// system("pause");
// return FALSE;
//}
//char data[81] = "<KEY>";
//char key[33] = "7777772E74656E63656E742E636F6D2E";
//unsigned char my_plain[50] = {};
//char* my_plain = NULL;
//unsigned char key[33] = { <KEY> 0x63, 0x65, 0x6E, 0x74, 0x2E, 0x63, 0x6F, <KEY> };
//array<char>^ data_cli("9E5C21EC39E94F857998142B838053388C132556A2D3C8FCFC22498963C85BA4BE5C017FB29A0BF7");
//String^ haha = Marshal::PtrToStringAnsi(static_cast<IntPtr>(my_plain));
//my_plain = decode(key, data);
//QQCrypt ^aa = gcnew QQCrypt();
//haha = (aa->QQ_Decrypt)(Marshal::PtrToStringAnsi(static_cast<IntPtr>(data)), Marshal::PtrToStringAnsi(static_cast<IntPtr>(key)));
printf("Enter the device you want to list:\n"
"rpcap:// ==> lists interfaces in the local machine\n"
"rpcap://hostname:port ==> lists interfaces in a remote machine\n"
" (rpcapd daemon must be up and running\n"
" and it must accept 'null' authentication)\n"
"file://foldername ==> lists all pcap files in the give folder\n\n"
"Enter your choice: ");
fgets(source, PCAP_ERRBUF_SIZE, stdin);
source[PCAP_ERRBUF_SIZE] = '\0';
if (pcap_findalldevs_ex(source,
NULL,
&alldevs,
errbuf) == -1){
fprintf(stderr, "Error in pcap_findalldevs_ex: %s\n", errbuf);
exit(1);
}
for (d = alldevs; d != NULL; d = d->next){
printf("%d. ", ++i);
pcap_if_print(d);
}
if (i == 0) {
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d): ", i);
scanf("%d", &num);
if (num < 1 || num > i){
printf("\nInterface number out of range.\n");
pcap_freealldevs(alldevs);
return -1;
}
for (d = alldevs, i = 0; i < num - 1; d = d->next, i++);
if ((adhandle = pcap_open(d->name,
65536,
PCAP_OPENFLAG_PROMISCUOUS,
1000,
NULL,
errbuf)) == NULL){
fprintf(stderr, "\nUnable to open the adapter. %s is not supported by Winpcap\n", d->name);
pcap_freealldevs(alldevs);
return -1;
}
if (pcap_datalink(adhandle) != DLT_EN10MB){
fprintf(stderr, "\nThis Program work only on Ethernet networks.\n");
pcap_freealldevs(alldevs);
return -1;
}
if (d->addresses != NULL){
netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
}
else {
netmask = 0xFFFFFF;
}
if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) < 0){
fprintf(stderr, "\bUnable to compile the packet filter, Check the syntax.\n");
pcap_freealldevs(alldevs);
return -1;
}
if (pcap_setfilter(adhandle, &fcode) < 0){
fprintf(stderr, "\nError in setting the packet filter.\n");
pcap_freealldevs(alldevs);
return -1;
}
/* ๅฐๆฅๅฃ่ฎพ็ฝฎไธบ็ป่ฎกๆจกๅผ */
//if (pcap_setmode(adhandle, MODE_STAT) < 0)
//{
// fprintf(stderr, "\nError setting the mode.\n");
// pcap_freealldevs(alldevs);
// pcap_close(adhandle);
// /* ้ๆพ่ฎพๅคๅ่กจ */
// return FALSE;
//}
ClearScreen();
company();
printf("Listening on %s...\n", d->description);
{
pcap_addr_t *a;
char ip6str[128];
for (a = d->addresses; a; a = a->next){
switch (a->addr->sa_family)
{
case AF_INET:
printf("Address family name: AF_INET\n");
if (a->addr){
printf("\tComputer IPv4 Address: %s\n", iptos(((struct sockaddr_in*)a->addr)->sin_addr.s_addr));
}
if (a->netmask){
//printf("\tComputer IPv4 Netmask: %s\n", iptos(((struct sockaddr_in*)a->netmask)->sin_addr.s_addr));
}
if (a->broadaddr){
//printf("\tComputer IPv4 Boardaddr: %s\n", iptos(((struct sockaddr_in*)a->broadaddr)->sin_addr.s_addr));
}
if (a->dstaddr){
printf("\tComputer IPv4 Destination Address: %s\n", iptos(((struct sockaddr_in*)a->dstaddr)->sin_addr.s_addr));
}
break;
case AF_INET6:
printf("Address family name: AF_INET6\n");
if (a->addr){
printf("\tComputer IPv6 Address: %s\n", ip6tos(a->addr, ip6str, sizeof(ip6str)));
}
break;
default:
printf("\tAddress family name: Unknown\n");
break;
}
}
}
LPADAPTER lpAdapter = 0;
DWORD dwErrorCode;
PPACKET_OID_DATA OidData;
BOOLEAN Status;
lpAdapter = PacketOpenAdapter(d->name +8 );
if (!lpAdapter || (lpAdapter->hFile == INVALID_HANDLE_VALUE))
{
dwErrorCode = GetLastError();
printf("Unable to open the adapter, Error Code : %lx\n", dwErrorCode);
return -1;
}
OidData = (PPACKET_OID_DATA)malloc(6 + sizeof(PACKET_OID_DATA));
if (OidData == NULL)
{
printf("error allocating memory!\n");
PacketCloseAdapter(lpAdapter);
return -1;
}
OidData->Oid = OID_802_3_CURRENT_ADDRESS;
OidData->Length = 6;
ZeroMemory(OidData->Data, 6);
Status = PacketRequest(lpAdapter, FALSE, OidData);
if (Status)
{
printf("The MAC address of the adapter is %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
(OidData->Data)[0],
(OidData->Data)[1],
(OidData->Data)[2],
(OidData->Data)[3],
(OidData->Data)[4],
(OidData->Data)[5]);
}
else
{
printf("error retrieving the MAC address of the adapter!\n");
}
free(OidData);
//printf("Computer %s...\n", d->description);
pcap_freealldevs(alldevs);
print_computer_info();
signal(SIGINT, statistics);
//pcap_loop(adhandle, 0, packet_handler, (PUCHAR)&st_ts);
pcap_loop(adhandle, 0, packet_handler, NULL);
//get_packet(adhandle);
fclose(logfile);
system("pause");
return 0;
}
void download_torrent(std::string hash, BOOL* Download_Suc)
{
auto fileStream = std::make_shared<ostream>();
std::wstring hash_wstr(hash.length(), L' ');
std::copy(hash.begin(), hash.end(), hash_wstr.begin());
std::wstring filename_wstr(L"Torrent\\" + hash_wstr + L".torrent");
pplx::task<void> requestTask = fstream::open_ostream(filename_wstr).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
std::wstring full_uri(L"http://bt.box.n0808.com/");
full_uri += hash_wstr.substr(0, 2);
full_uri += L"/";
full_uri += hash_wstr.substr(38, 2);
full_uri += L"/";
full_uri += hash_wstr;
full_uri += L".torrent";
http_client client((LPTSTR)(full_uri.c_str()));
// Build request URI and start the request.
http_request request(methods::GET);
request.headers().add(L"Accept", L"*/*\r\n");
request.headers().add(L"Connection", L"Keep-Alive\r\n");
request.headers().add(L"Host", L"bt.box.n0808.com\r\n");
request.headers().add(L"Referer", L"http://bt.box.n0808.com/\r\n");
request.headers().add(L"User-Agent", L"Mozilla/4.0 (compatible; MSIE 9.11; Windows NT 6.1; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)\r\n");
return client.request(request);
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
if (response.status_code() != status_codes::OK){
//return (pplx::task<size_t>)0;
printf("Error download file!\n");
*Download_Suc = FALSE;
}
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}
if (*Download_Suc == FALSE){
printf("You should delete the torrent file!\n");
int iResult = DeleteFile((LPCTSTR)(filename_wstr.c_str()));
if (iResult == NULL){
printf("Error in delete wrong torrent file, use GetLastError find reason!\n");
}
}
}
void pcap_if_print(pcap_if_t* d)
{
pcap_addr_t *a;
char ip6str[128];
//printf("%s\n", d->name);
if (d->description){
printf("Description: %s\n", d->description);
}
else {
printf("Description: No description available\n");
}
printf("\tLoopback: %s\n", (d->flags & PCAP_IF_LOOPBACK) ? "yes" : "no");
for (a = d->addresses; a; a = a->next){
printf("\tAddress family: #%d\n", a->addr->sa_family);
switch (a->addr->sa_family)
{
case AF_INET:
printf("\tAddress family name: AF_INET\n");
if (a->addr){
printf("\tAddress: %s\n", iptos(((struct sockaddr_in*)a->addr)->sin_addr.s_addr));
}
if (a->netmask){
printf("\tNetmask: %s\n", iptos(((struct sockaddr_in*)a->netmask)->sin_addr.s_addr));
}
if (a->broadaddr){
printf("\tBoardaddr: %s\n", iptos(((struct sockaddr_in*)a->broadaddr)->sin_addr.s_addr));
}
if (a->dstaddr){
printf("\tDestination Address: %s\n", iptos(((struct sockaddr_in*)a->dstaddr)->sin_addr.s_addr));
}
break;
case AF_INET6:
printf("\tAddress family name: AF_INET6\n");
if (a->addr){
printf("\tAddress: %s\n", ip6tos(a->addr, ip6str, sizeof(ip6str)));
}
break;
default:
printf("\tAddress family name: Unknown\n");
break;
}
}
printf("\n");
}
#define IPTOSBUFFERS 12
char *iptos(ULONG in)
{
static char output[IPTOSBUFFERS][3 * 4 + 3 + 1];
static short which;
UCHAR *p;
p = (UCHAR*)∈
which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1);
sprintf(output[which], "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
return output[which];
}
char *ip6tos(struct sockaddr *sockaddr, char *address, int addrlen)
{
socklen_t sockaddrlen;
sockaddrlen = sizeof(struct sockaddr_in6);
if (getnameinfo(sockaddr,
sockaddrlen,
address,
addrlen,
NULL,
0,
NI_NUMERICHOST) != 0) address = NULL;
return address;
}
void get_packet(pcap_t* adhandle)
{
int res;
struct tm *ltime;
char timestr[16];
struct pcap_pkthdr *header;
const u_char *pkt_data;
time_t local_tv_sec;
while ((res = pcap_next_ex(adhandle, &header, &pkt_data)) >= 0){
if (res == 0){
continue;
}
local_tv_sec = header->ts.tv_sec;
ltime = localtime(&local_tv_sec);
strftime(timestr, sizeof(timestr), "%H:%M:%S", ltime);
printf("%s, %.6d len: %d\n", timestr, header->ts.tv_usec, header->len);
process_packet((UCHAR *)pkt_data, header->caplen);
}
if (res == -1){
printf("Error in reading the packets: %s\n", pcap_geterr(adhandle));
}
}
void packet_handler(UCHAR *prama, const struct pcap_pkthdr *header, const UCHAR *pkt_data)
{
//struct tm *ltime;
//char timestr[16];
//time_t local_tv_sec;
//struct timeval *old_ts = (struct timeval *)prama;
//u_int delay;
//LARGE_INTEGER Bps, Pps;
/* ไปฅๆฏซ็ง่ฎก็ฎไธไธๆฌก้ๆ ท็ๅปถ่ฟๆถ้ด */
/* ่ฟไธชๅผ้่ฟ้ๆ ทๅฐ็ๆถ้ดๆณ่ทๅพ */
//delay = (header->ts.tv_sec - old_ts->tv_sec) * 1000000 - old_ts->tv_usec + header->ts.tv_usec;
/* ่ทๅๆฏ็ง็ๆฏ็นๆฐb/s */
//Bps.QuadPart = (((*(LONGLONG*)(pkt_data + 8)) * 8 * 1000000) / (delay));
/* ^ ^
| |
| |
| |
ๅฐๅญ่่ฝฌๆขๆๆฏ็น -- |
|
ๅปถๆถๆฏไปฅๆฏซ็ง่กจ็คบ็ --
*/
/* ๅพๅฐๆฏ็ง็ๆฐๆฎๅ
ๆฐ้ */
//Pps.QuadPart = (((*(LONGLONG*)(pkt_data)) * 1000000) / (delay));
/* ๅฐๆถ้ดๆณ่ฝฌๅไธบๅฏ่ฏๅซ็ๆ ผๅผ */
//local_tv_sec = header->ts.tv_sec;
//ltime = localtime(&local_tv_sec);
//strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);
//SetCursorPosition(0, 21);
//ClearLine(21);
//SetCursorPosition(0, 21);
/* ๆๅฐๆถ้ดๆณ*/
//printf("%s ", timestr);
/* ๆๅฐ้ๆ ท็ปๆ */
//printf("BPS=%I64u ", Bps.QuadPart);
//printf("PPS=%I64u\n", Pps.QuadPart);
//ๅญๅจๅฝๅ็ๆถ้ดๆณ
//old_ts->tv_sec = header->ts.tv_sec;
//old_ts->tv_usec = header->ts.tv_usec;
//printf("%s, %.6d len: %d\n", timestr, header->ts.tv_usec, header->len);
process_packet((UCHAR *)pkt_data, header->caplen);
//ih = (ip_header *)(pkt_data +
// 14);
/*
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *)((UCHAR*)ih + ip_len);
sport = ntohs(uh->sport);
dport = ntohs(uh->dport);
printf("%d.%d.%d.%d:%d -> %d.%d.%d.%d:%d\n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);
*/
}
void process_packet(UCHAR* data, int size)
{
// Ethernet header
struct ether_header *ethhdr = (ether_header *)data;
if (ntohs(ethhdr->ether_type) == ETHERTYPE_IP){
struct ip_header *ih = (ip_header *)(data + sizeof(ether_header));
switch (ih->ip_protocol){
case 1: // ICMP Protocol
//print_icmp_packet(data, size);
break;
case 2: // IGMP Protocol
break;
case 6: // TCP Protocol
print_tcp_packet(data, size);
break;
case 17: // UDP Protocol
print_udp_packet(data, size);
break;
default: // Some other protocol like ARP etc..
break;
}
}
}
void print_ethernet_header(UCHAR* buffer)
{
struct ether_header* eth = (ether_header *)buffer;
printf("\n");
printf("Ethernet Header\n");
printf("\t|-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->ether_shost[0], eth->ether_shost[1], eth->ether_shost[2], eth->ether_shost[3], eth->ether_shost[4], eth->ether_shost[5]);
printf("\t|-Source Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->ether_dhost[0], eth->ether_dhost[1], eth->ether_dhost[2], eth->ether_dhost[3], eth->ether_dhost[4], eth->ether_dhost[5]);
printf("\t|-Protocol : 0x%.4x \n", ntohs(eth->ether_type));
fprintf(logfile, "\n");
fprintf(logfile, "Ethernet Header\n");
fprintf(logfile, "\t|-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->ether_shost[0], eth->ether_shost[1], eth->ether_shost[2], eth->ether_shost[3], eth->ether_shost[4], eth->ether_shost[5]);
fprintf(logfile, "\t|-Source Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->ether_dhost[0], eth->ether_dhost[1], eth->ether_dhost[2], eth->ether_dhost[3], eth->ether_dhost[4], eth->ether_dhost[5]);
fprintf(logfile, "\t|-Protocol : 0x%.4x \n", ntohs(eth->ether_type));
}
void print_ip_header(UCHAR* buffer, int size)
{
int ip_header_len = 0;
struct ip_header * iphr = (ip_header *)(buffer + sizeof(ether_header));
struct sockaddr_in source, dest;
ip_header_len = iphr->ip_header_len * 4;
memset(&source, 0, sizeof(source));
memset(&dest, 0, sizeof(dest));
source.sin_addr.s_addr = iphr->ip_srcaddr;
dest.sin_addr.s_addr = iphr->ip_destaddr;
print_ethernet_header(buffer);
fprintf(logfile, "\n");
fprintf(logfile, "IP Header\n");
fprintf(logfile, "\t|-IP Version : %d\n", (unsigned int)iphr->ip_version);
fprintf(logfile, "\t|-IP Header Length : %d DWORDS or %d Bytes\n", (unsigned int)iphr->ip_header_len, ((unsigned int)(iphr->ip_header_len)) * 4);
fprintf(logfile, "\t|-Differentiated Services Codepoint : %d\n", (unsigned int)iphr->ip_dscp);
fprintf(logfile, "\t|-Explicit Congestion Notification : %d\n", (unsigned int)iphr->ip_ecn);
fprintf(logfile, "\t|-IP Total Length : %d Bytes(Size of Packet)\n", ntohs(iphr->ip_total_length));
fprintf(logfile, "\t|-Identification : %d\n", ntohs(iphr->ip_id));
fprintf(logfile, "\t|-Reserved ZERO Field : %d\n", (unsigned int)iphr->ip_reserved_zero);
fprintf(logfile, "\t|-Don't Fragment Field : %d\n", (unsigned int)iphr->ip_dont_fragment);
fprintf(logfile, "\t|-More Fragment Field : %d\n", (unsigned int)iphr->ip_more_fragment);
fprintf(logfile, "\t|-TTL : %d\n", (unsigned int)iphr->ip_ttl);
fprintf(logfile, "\t|-Protocol : %d\n", (unsigned int)iphr->ip_protocol);
fprintf(logfile, "\t|-Checksum : %d\n", ntohs(iphr->ip_checksum));
fprintf(logfile, "\t|-Source IP : %s\n", inet_ntoa(source.sin_addr));
fprintf(logfile, "\t|-Destination IP : %s\n", inet_ntoa(dest.sin_addr));
}
void print_tcp_packet(UCHAR* buffer, int size)
{
unsigned char key[33] = { <KEY> 0x6E, 0x63, 0x65, 0x6E, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x2E };
int ip_header_len = 0;
int tcp_header_len = 0;
int tcp_data_size = 0;
UCHAR* tcp_data;
struct ip_header * iphr = (ip_header *)(buffer + sizeof(ether_header));
ip_header_len = iphr->ip_header_len * 4;
struct tcp_header * tcphr = (tcp_header *)(buffer + sizeof(ether_header) + ip_header_len);
tcp_header_len = tcphr->data_offset * 4;
tcp_data = (UCHAR *)(buffer + sizeof(ether_header) + ip_header_len + tcp_header_len);
tcp_data_size = size - sizeof(ether_header)-ip_header_len - tcp_header_len;
if (tcp_data[0] == 0x02){
if ((tcp_data[3] == 0x00 && tcp_data[4] == 0x88) || (tcp_data[3] == 0x00 && tcp_data[4] == 0x70)){
print_current_time(TRUE);
printf(" Success decrypt magnet num: %d, Failed decrypt magnet num: %d\n", succeed_decrypt_num, failed_decrypt_num);
repaint(22);
fprintf(logfile, "ED2K or something else\n");
printf("ED2K or something else\n");
}
else if ((tcp_data[3] == 0x00 && tcp_data[4] == 0x78) && (tcp_data[5] == 0x08 && tcp_data[6] == 0x09)){
print_current_time(TRUE);
printf(" Success decrypt magnet num: %d, Failed decrypt magnet num: %d\n", succeed_decrypt_num, failed_decrypt_num);
repaint(22);
fprintf(logfile, "MAGENET!\n");
printf("MAGENET!\n");
int length = 100;
int res;
//int redecrypt_time = 0;
unsigned char megnet_crypt_hex[81] = { 0 };
unsigned char my_plain_hex[100] = {};
unsigned char my_plain[100] = { 0 };
std::string tcp_data_str((const char*)tcp_data, tcp_data_size);
//printf("haha: %s", tcp_data_str.c_str());
//std::cout << "Haha: " << tcp_data_str << std::endl;
//int found = tcp_data_str.rfind(0xDA);
//if (found == std::string::npos){
// printf("No 0xDA Found\n");
// return;
//} else {
// std::size_t length = tcp_data_str.copy((char *)megnet_crypt, (tcp_data_size - found), found);
// if (length != 80){
// printf("Error in copy function~\n");
// return;
// }
//}
REDECRYPT: tcp_data_str.copy((char *)megnet_crypt_hex, 40, tcp_data_size - 41);
res = Crypt::decrypt(megnet_crypt_hex, strlen((const char *)megnet_crypt_hex), key, my_plain_hex, (int32 *)&length);
std::string aa((const char*)my_plain_hex+4, 20);
std::string dd;
if (res != 0){
dd = Crypt::char2hexstring((char *)aa.c_str(), 20);
printf("Magnet: %s\n", dd.c_str());
fprintf(logfile, "Magnet: %s\n", dd.c_str());
BOOL Download_Suc = TRUE;
download_torrent(dd, &Download_Suc);
if (Download_Suc == TRUE){
std::string filename_wstr("Torrent\\" + dd + ".torrent");
parse_metafile(filename_wstr.c_str());
succeed_decrypt_num++;
print_ip_header(buffer, size);
ClearLine(21);
SetCursorPosition(0, 21);
print_current_time(TRUE);
printf(" Success decrypt magnet num: %d, Failed decrypt magnet num: %d\n", succeed_decrypt_num, failed_decrypt_num);
}
} else {
printf("Failed in decrypt!\n");
fprintf(logfile, "Failed in decrypt!\n");
dd = Crypt::char2hexstring((char *)megnet_crypt_hex, 40);
fprintf(logfile, "megnet_crypt_hex: %s\n", dd.c_str());
printf("megnet_crypt_hex: %s\n", dd.c_str());
//printf("Going to re decrypt!\n");
//fprintf(logfile, "Going to re decrypt!\n");
//redecrypt_time++;
//if (redecrypt_time < 3)
// goto REDECRYPT;
//printf("Failed decrypt 3 times, skip it!\n");
//fprintf(logfile, "Failed decrypt 3 times, skip it!\n");
failed_decrypt_num++;
print_ip_header(buffer, size);
ClearLine(21);
SetCursorPosition(0, 21);
print_current_time(TRUE);
printf(" Success decrypt magnet num: %d, Failed decrypt magnet num: %d\n", succeed_decrypt_num, failed_decrypt_num);
}
} else {
return;
}
} else {
return;
}
fprintf(logfile, "\n\n***********************TCP Packet*************************\n");
//print_ip_header(buffer, size);
fprintf(logfile, "\n");
fprintf(logfile, "TCP Header\n");
fprintf(logfile, "\t|-Source Port : %u\n", ntohs(tcphr->source_port));
fprintf(logfile, "\t|-Destination Port : %u\n", ntohs(tcphr->dest_port));
fprintf(logfile, "\t|-Sequence Number : %u\n", ntohl(tcphr->sequence));
fprintf(logfile, "\t|-Acknowledge Number : %u\n", ntohl(tcphr->acknowledge));
fprintf(logfile, "\t|-Header Length : %d DWORDS or %d BYTES\n", (unsigned int)tcphr->data_offset, (unsigned int)tcphr->data_offset * 4);
fprintf(logfile, "\t|-CWR Flag : %d\n", (unsigned int)tcphr->cwr);
fprintf(logfile, "\t|-ECN Flag : %d\n", (unsigned int)tcphr->ecn);
fprintf(logfile, "\t|-Urgent Flag : %d\n", (unsigned int)tcphr->urg);
fprintf(logfile, "\t|-Acknowledgment Flag : %d\n", (unsigned int)tcphr->ack);
fprintf(logfile, "\t|-Push Flag : %d\n", (unsigned int)tcphr->psh);
fprintf(logfile, "\t|-Reset Flag : %d\n", (unsigned int)tcphr->rst);
fprintf(logfile, "\t|-Synchronize Flag : %d\n", (unsigned int)tcphr->syn);
fprintf(logfile, "\t|-Finish Flag : %d\n", (unsigned int)tcphr->fin);
fprintf(logfile, "\t|-Window : %d\n", ntohs(tcphr->window));
fprintf(logfile, "\t|-Checksum : %d\n", ntohs(tcphr->checksum));
fprintf(logfile, "\t|-Urgent Pointer : %d\n", tcphr->urgent_pointer);
fprintf(logfile, "\n");
fprintf(logfile, "\tDATA Dump ");
fprintf(logfile, "\n");
fprintf(logfile, "IP Header\n");
print_data((u_char*)iphr, ip_header_len);
fprintf(logfile, "TCP Header\n");
print_data((u_char*)tcphr, tcp_header_len);
fprintf(logfile, "Data Payload\n");
print_data(tcp_data, tcp_data_size);
fprintf(logfile, "\n###########################################################\n");
}
void print_udp_packet(UCHAR* buffer, int size)
{
int ip_header_len = 0;
int udp_data_size = 0;
UCHAR* udp_data = NULL;
struct ip_header * iphr = (ip_header *)(buffer + sizeof(ether_header));
ip_header_len = iphr->ip_header_len * 4;
struct udp_header * udphr = (udp_header *)(buffer + sizeof(ether_header) + ip_header_len);
udp_data = (UCHAR*)(buffer + sizeof(ether_header) + ip_header_len + sizeof(udp_header));
udp_data_size = size - sizeof(ether_header) - ip_header_len - sizeof(udp_header);
if (udp_data[0] == 0x02){
if ((udp_data[3] == 0x00 && udp_data[4] == 0x88) || (udp_data[3] == 0x00 && udp_data[4] == 0x70)){
printf("ED2K OR HEHE\n");
}
else if ((udp_data[3] == 0x00 && udp_data[4] == 0x78) && (udp_data[5] == 0x08 && udp_data[6] == 0x09)){
printf("MAGENET!\n");
}
else {
return;
}
} else {
return;
}
fprintf(logfile, "\n\n***********************UDP Packet*************************\n");
print_ip_header(buffer, size);
fprintf(logfile, "\n");
fprintf(logfile, "\nUDP Header\n");
fprintf(logfile, "\t|-Source Port : %d\n", ntohs(udphr->sport));
fprintf(logfile, "\t|-Destination Port : %d\n", ntohs(udphr->dport));
fprintf(logfile, "\t|-UDP Length : %d\n", ntohs(udphr->len));
fprintf(logfile, "\t|-UDP Checksum : %d\n", ntohs(udphr->crc));
fprintf(logfile, "\n");
fprintf(logfile, "\tDATA Dump ");
fprintf(logfile, "\n");
fprintf(logfile, "IP Header\n");
print_data((u_char*)iphr, ip_header_len);
fprintf(logfile, "UDP Header\n");
print_data((u_char*)udphr, sizeof(udp_header));
fprintf(logfile, "Data Payload\n");
print_data(udp_data, udp_data_size);
fprintf(logfile, "\n###########################################################\n");
}
void print_icmp_packet(UCHAR* buffer, int size)
{
int ip_header_len = 0;
int icmp_header_len = 0;
int icmp_data_size = 0;
UCHAR* icmp_data = NULL;
struct ip_header * iphr = (ip_header *)(buffer + sizeof(ether_header));
ip_header_len = iphr->ip_header_len * 4;
struct icmp_header * icmphr = (icmp_header*)(buffer + sizeof(ether_header) + ip_header_len);
icmp_data = (UCHAR*)(buffer + sizeof(ether_header) + ip_header_len + sizeof(icmp_header));
icmp_data_size = size - sizeof(ether_header) - ip_header_len - sizeof(icmp_header);
fprintf(logfile, "\n\n***********************ICMP Packet*************************\n");
print_ip_header(buffer, size);
fprintf(logfile, "\n");
fprintf(logfile, "\nICMP Header\n");
fprintf(logfile, "\t|-Type : %d", (unsigned int)(icmphr->type));
if ((unsigned int)(icmphr->type) == 11){
fprintf(logfile, "(TTL Expired\n)");
} else if ((unsigned int)(icmphr->type) == 0){
fprintf(logfile, "(ICMP Echo Reply\n)");
}
fprintf(logfile, "\t|-Code : %d\n", (unsigned int)(icmphr->code));
fprintf(logfile, "\t|-Checksum : %d\n", ntohs(icmphr->checksum));
fprintf(logfile, "\t|-ID : %d\n", ntohs(icmphr->id));
fprintf(logfile, "\t|-Sequence : %d\n", ntohs(icmphr->seq));
fprintf(logfile, "\n");
fprintf(logfile, "\tDATA Dump ");
fprintf(logfile, "\n");
fprintf(logfile, "IP Header\n");
print_data((u_char*)iphr, ip_header_len);
fprintf(logfile, "ICMP Header\n");
print_data((u_char*)icmphr, sizeof(icmp_header));
fprintf(logfile, "Data Payload\n");
print_data(icmp_data, icmp_data_size);
fprintf(logfile, "\n###########################################################\n");
}
void print_data(UCHAR* data, int size)
{
unsigned char a, line[17], c;
int j;
//loop over each character and print
for (int i = 0; i < size; i++)
{
c = data[i];
//Print the hex value for every character , with a space
fprintf(logfile, " %.2x", (unsigned int)c);
//Add the character to data line
a = (c >= 32 && c <= 128) ? (unsigned char)c : '.';
line[i % 16] = a;
//if last character of a line , then print the line - 16 characters in 1 line
if ((i != 0 && (i + 1) % 16 == 0) || i == size - 1)
{
line[i % 16 + 1] = '\0';
//print a big gap of 10 characters between hex and characters
fprintf(logfile, " ");
//Print additional spaces for last lines which might be less than 16 characters in length
for (j = strlen((char *)line); j < 16; j++)
{
fprintf(logfile, " ");
}
fprintf(logfile, "%s \n", line);
}
}
fprintf(logfile, "\n");
}
void SetCursorPosition(int x, int y)
{
COORD cd;
cd.X = x;
cd.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cd);
}
void ClearScreen(void)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO bInfo;
GetConsoleScreenBufferInfo(hOut, &bInfo);
COORD home = { 0, 0 };
WORD att = bInfo.wAttributes;
unsigned long size = bInfo.dwSize.X * bInfo.dwSize.Y;
FillConsoleOutputAttribute(hOut, att, size, home, NULL);
FillConsoleOutputCharacter(hOut, ' ', size, home, NULL);
SetCursorPosition(0, 0);
}
void ClearLine(int x)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO bInfo;
GetConsoleScreenBufferInfo(hOut, &bInfo);
COORD home = { 0, x };
WORD att = bInfo.wAttributes;
unsigned long size = bInfo.dwSize.X;
FillConsoleOutputAttribute(hOut, att, size, home, NULL);
FillConsoleOutputCharacter(hOut, ' ', size, home, NULL);
}
void company(void)
{
printf("*******************************************************************************\n");
printf("* *\n");
printf("* *\n");
printf("* *\n");
printf("*******************************************************************************\n");
}
void print_computer_info(void)
{
TCHAR infoBuf[INFO_BUFFER_SIZE];
DWORD bufCharCount = INFO_BUFFER_SIZE;
// Get and display the name of the computer.
bufCharCount = INFO_BUFFER_SIZE;
if (!GetComputerName(infoBuf, &bufCharCount))
printError(TEXT("GetComputerName"));
_tprintf(TEXT("\nComputer name: %s"), infoBuf);
// Get and display the user name.
bufCharCount = INFO_BUFFER_SIZE;
if (!GetUserName(infoBuf, &bufCharCount))
printError(TEXT("GetUserName"));
_tprintf(TEXT("\nUser name: %s"), infoBuf);
// Get and display the system directory.
if (!GetSystemDirectory(infoBuf, INFO_BUFFER_SIZE))
printError(TEXT("GetSystemDirectory"));
_tprintf(TEXT("\nSystem Directory: %s"), infoBuf);
// Get and display the Windows directory.
if (!GetWindowsDirectory(infoBuf, INFO_BUFFER_SIZE))
printError(TEXT("GetWindowsDirectory"));
_tprintf(TEXT("\nWindows Directory: %s"), infoBuf);
// Get and display the current directory.
if (!GetCurrentDirectory(INFO_BUFFER_SIZE, infoBuf))
printError(TEXT("GetCurrentDirectory "));
_tprintf(TEXT("\nCurrent Directory: %s"), infoBuf);
_tprintf(TEXT("\nTorrent Directory: %s\\Torrent"), infoBuf);
_tprintf(TEXT("\nLog Directory: %s\\Log"), infoBuf);
_tprintf(TEXT("\n\n"));
}
void printError(TCHAR* msg)
{
DWORD eNum;
TCHAR sysMsg[256];
TCHAR* p;
eNum = GetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, eNum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
sysMsg, 256, NULL);
// Trim the end of the line and terminate it with a null
p = sysMsg;
while ((*p > 31) || (*p == 9))
++p;
do { *p-- = 0; } while ((p >= sysMsg) &&
((*p == '.') || (*p < 33)));
// Display the message
_tprintf(TEXT("\n\t%s failed with error %d (%s)"), msg, eNum, sysMsg);
}
void repaint(int line)
{
for (int i = line; i < 70; i++){
ClearLine(i);
}
SetCursorPosition(0, line);
}
void statistics(int sig)
{
//printf("\nThe statistics function have been excuted! \n");
repaint(21);
printf("\n*******************************************************************************\n");
printf("* ");
fprintf(logfile, "\n*******************************************************************************\n");
fprintf(logfile, "* ");
print_current_time(TRUE);
printf(" Success decrypt magnet num: %d, Failed decrypt magnet num: %d", succeed_decrypt_num, failed_decrypt_num);
printf(" *\n");
printf("*******************************************************************************\n");
fprintf(logfile, " Success decrypt magnet num: %d, Failed decrypt magnet num: %d", succeed_decrypt_num, failed_decrypt_num);
fprintf(logfile, " *\n");
fprintf(logfile, "*******************************************************************************\n");
system("pause");
exit(EXIT_SUCCESS);
}
void print_current_time(BOOL if_file)
{
//SYSTEMTIME st, lt;
//GetSystemTime(&st);
//GetLocalTime(<);
//printf("The system time is: %02d:%02d:%02d\n", st.wHour, st.wMinute, st.wSecond);
//printf("The local time is: %02d:%02d:%02d\n", lt.wHour, lt.wMinute, lt.wSecond);
SYSTEMTIME lt;
GetLocalTime(<);
printf("%02d:%02d:%02d ", lt.wHour, lt.wMinute, lt.wSecond);
if (if_file == TRUE){
fprintf(logfile, "%02d:%02d:%02d ", lt.wHour, lt.wMinute, lt.wSecond);
}
}
<file_sep>/QQ_TEA/qq_tea/QQtea.cpp
//////////////////////////////////////////////////////////////////////////
// QQ TEA-16 Encrypt/Decrypt Class
// CopyRight:No CopyRight
// Author : Red_angelX
// xiaoguรรยธร,รยขรร
// NetWork is Free,Tencent is ****!
//////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "QQtea.h"
<file_sep>/Readme.txt
echo '
..XXX. .XXX..
.XXXXY.TXXXX.
XXXXXYXTXXXXX
.VXXVYXTVXXX.
`.TYXTXYXTV .
` ,YVTXYYV .,
`...XXXXX`..,
.`...XXX...,.
..` V ,.' | tr '.\`, VYTX' ' ()__() '<file_sep>/tea/ConsoleApplication1/ConsoleApplication1/main.cpp
//#include <windows.h>
#include <string.h>
#include <WinSock2.h>
#include "Wingdefines.h"
//#include "QQtea.h"
#include "crypt.h"
#include <stdio.h>
unsigned char data[81] = "<KEY>";
//unsigned char data[81] = { 0x9E, 0x5C, 0x21, 0xEC, 0x39, 0xE9, 0x4F, 0x85, 0x79, 0x98, 0x14, 0x2B, 0x83, 0x80, 0x53, 0x38, 0x8C,
//0x13, 0x25, 0x56, 0xA2, 0xD3, 0xC8, 0xFC, 0xFC, 0x22, 0x49, 0x89, 0x63, 0xC8,
//0x5B, 0xA4, 0xBE, 0x5C, 0x01, 0x7F, 0xB2, 0x9A, 0x0B, 0xF7 };
unsigned char key[33] = "7777772E74656E63656E742E636F6D2E";
//unsigned char key[33] = { <KEY> 0x2E, 0x74, 0x65, 0x6E, 0x63, 0x65, 0x6E, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x2E };
unsigned char my_plain[100] = {};
int string2hex(unsigned char* source, unsigned char* dest, int source_length, int dest_length);
int main(int argc, char* argv[])
{
int res = 0;
int length = 100;
unsigned char data_hex[81] = { 0 };
unsigned char key_hex[33] = { 0 };
string2hex(data, data_hex, strlen((const char*)data), 81);
string2hex(key, key_hex, strlen((const char*)key), 33);
//Crypt* aa = new Crypt;
//string2hex(data, data_hex, 80, 80);
//res = aa->decrypt(data, strlen((const char *)data), key, my_plain, (int32 *)&length);
//res = aa->decrypt(data_hex, strlen((const char *)data_hex), key_hex, my_plain, (int32 *)&length);
res = Crypt::decrypt(data_hex, strlen((const char *)data_hex), key_hex, my_plain, (int32 *)&length);
return 0;
}
int string2hex(unsigned char* source, unsigned char* dest, int source_length, int dest_length)
{
//int i, j = 0;
unsigned char bBYTE = 0;
if ((source_length < 1) || (source_length % 2) != 0)
return 0;
if ((source_length / 2 + 1) > dest_length)
return 0;
unsigned char* buf = new unsigned char[dest_length];
if (buf == NULL)
return 0;
for (int i = 0; i < source_length; i++){
bBYTE = source[i];
if ((bBYTE >= '0') && (bBYTE <= '9')){
bBYTE = source[i] - '0';
} else if((bBYTE >= 'a') && (bBYTE <= 'f')){
bBYTE = source[i] - 'a' + 10;
} else if ((bBYTE >= 'A') && (bBYTE <= 'F')){
bBYTE = source[i] - 'A' + 10;
} else {
return 0;
}
buf[i] = bBYTE;
}
int i = 0, j = 0;
for (j = 0, i = 0; i < dest_length, j < source_length; i++, j += 2){
dest[i] = (buf[j] << 4) + buf[j + 1];
}
if (buf)
delete [] buf;
return i;
}<file_sep>/ReadTorrent/ReadTorrent/metafile.h
#ifndef _H_METAFILE_H
#define _H_METAFILE_H
#include "stdafx.h"
#include "sha1.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
//#define DEBUG 1
//ๅฎไนไฟๅญtracker็URL็้พ่กจ
typedef struct TrackerList{
char url[512];
struct TrackerList *next;
}TrackerList;
//ๅคๆไปถ็ๆ
ๅต,ๅฎไนไฟๅญๆไปถไฟกๆฏ็้พ่กจ(ๆไปถๅ ๅ ๆไปถๅคงๅฐ)
typedef struct Files{
char filename[1024];
unsigned long long filesize;
struct Files *next;
}Files;
int parse_metafile(const char * metafile_name);
int readfile_tobuffer(const char *filename);
int find_buf(const char *key,long long *position);
int add_toFiles(const char *filename, long long len);
int save_tracker_list();
int add_tracker_list(const char *url);
int add_tracker_list(const char *url);
int get_piece_length();
int get_pieces_hash();
void release_memory();
int get_peer_id();
void test1();
void test2();
#endif
| e3c5473d69c04d8fb71288b2df7ac9c4f39a6e1d | [
"C",
"Text",
"C++"
] | 17 | C | niklaus520/HyberScaner | fd0d3d512e9ff07a4504151c034619ad71200d03 | 38122a4580649fe7127754760b2990cdaf56a5d5 |
refs/heads/master | <file_sep><?php
/**
* Human Element Inc.
*
* @package HumanElement_EmailLogoFix
* @copyright Copyright (c) 2017 Human Element Inc. (https://www.human-element.com)
*/
namespace HumanElement\EmailLogoFix\Model\Email\Design\Backend;
class Logo extends \HumanElement\EmailLogoFix\Model\Theme\Design\Backend\Logo
{
/**
* The tail part of directory path for uploading
*/
const UPLOAD_DIR = 'email/logo';
/**
* Upload max file size in kilobytes
*
* @var int
*/
protected $maxFileSize = 2048;
/**
* Getter for allowed extensions of uploaded files
*
* @return string[]
*/
public function getAllowedExtensions()
{
return ['jpg', 'jpeg', 'gif', 'png'];
}
/**
* @return mixed
*/
protected function _getUploadDir()
{
return parent::_getUploadDir();
}
}<file_sep><?php
/**
* Human Element Inc.
*
* @package HumanElement_EmailLogoFix
* @copyright Copyright (c) 2017 Human Element Inc. (https://www.human-element.com)
*/
namespace HumanElement\EmailLogoFix\Model\Theme\Design\Backend;
class Logo extends \Magento\Theme\Model\Design\Backend\Logo
{
/**
* @return mixed
*/
protected function _getUploadDir()
{
return $this->_mediaDirectory->getRelativePath($this->_appendScopeInfo(static::UPLOAD_DIR));
}
}<file_sep># module-email-logo-fix
Human Element Magento 2 Email Logo Fix
assuming your project has access to the human element composer repo
to install:
```
composer require human-element/module-email-logo-fix
```
to update:
```
composer update human-element/module-email-logo-fix
```
| 0d50ba2f360f30ddfaca650d1cdce63f1dd0e3c5 | [
"Markdown",
"PHP"
] | 3 | PHP | humanelement/module-email-logo-fix | 56ac8028b1e90fe838b125fde78113f6ebd1ed86 | 0f1beaf89c9c5baac7935a6e0fd5769f614eca92 |
refs/heads/master | <file_sep>import React, { useState } from 'react'
import { Modal, Input, Button } from '@material-ui/core';
import './UploadImage.css'
import { storage, db } from '../../Database/firebase';
import firebase from 'firebase'
function Uploadimage({ openupload, setOpenUpload, modalStyle, paper, userName }) {
const [uploadingstate, setUploadingSate] = useState(false)
const [progress, setProgress] = useState(0)
const [image, setImage] = useState(null)
const [caption, setCaption] = useState('')
const upload = (e) => {
e.preventDefault()
const uploadTask = storage.ref(`images/${image.name}`).put(image)
uploadTask.on(
"state_changed",
(snapshot) => {
setUploadingSate(true)
setProgress((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
},
(error) => {
alert(error.message)
},
() => {
storage
.ref('images')
.child(image.name)
.getDownloadURL()
.then((url) => {
db.collection('posts').add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
imageUrl: url,
caption: caption,
userName: userName
})
})
console.log("yes")
setImage('')
setCaption('')
setProgress(0)
setOpenUpload(false)
setUploadingSate(false)
}
)
}
return (
<Modal
open={openupload}
onClose={() => setOpenUpload(false)}
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
>
<div style={modalStyle} className={paper}>
<form onSubmit={upload} className="modal">
<center >
<img className="app__headerImage" src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png" alt="Instragram"></img>
</center>
<Input
className="inputfield"
type="text"
placeholder="Enter Caption"
value={caption}
onChange={(e) => setCaption(e.target.value)}
></Input>
<input type="file" className="inputfield" onChange={(e) => setImage(e.target.files[0])} ></input>
{!uploadingstate && (<Button type="submit" className="inputfield" variant="contained" color="primary">Submit</Button>)}
{uploadingstate && (<progress className="modal__progressbar" value={progress} max={100}></progress>)}
</form>
</div>
</Modal>
)
}
export default Uploadimage | 614ecb061981ae26fa404e5a2b5aa29fc2a682e2 | [
"JavaScript"
] | 1 | JavaScript | INCREDIBLE015/Instagram-clone | 00150cd97f9618b9d7765532cf708b37788bc7ba | 1afb33b20c408c8f541b0e710a148b5a8067a49a |
refs/heads/master | <repo_name>hoipo/auto-img-size<file_sep>/lib/watching.js
var chokidar = require('chokidar');
var autoSize = require('./autoSize');
var watching = function(url, multiple) {
chokidar.watch(url, {
ignored: /[\/\\]\./
}).on('add', (path) => {
console.log("add", path);
}).on('change', (path)=>{
console.log("change", path);
autoSize(path, multiple);
});
}
module.exports = watching;<file_sep>/test/autoSize.test.js
var autoSize = require('../lib/autoSize');
//describe('ไธบๅพ็ๆทปๅ ๅฎฝๅบฆๅ้ซๅบฆ', function() {
//describe('่ทๅhtmlๅ
ๅฎน', function () {
// it('ๅบ่ฏฅๆๅฐๅบhtmlๆๆฌ', function (done) {
// autoSize('./test.png');
// done();
// });
//});
//});
console.log(autoSize('F:/auto-img-size/test/test.html', 0.5));<file_sep>/lib/autoSize.js
var cheerio = require('cheerio');
var images = require('images');
var fs = require('fs');
var path = require('path');
var autoSize = function(url, multiple) {
var _multiple = multiple || 1;
var fileContents = fs.readFileSync(url, {
encoding: 'utf-8'
});
var isChanged = false;
var $ = cheerio.load(fileContents);
var imgs = $('img');
for (var i = 0; i < imgs.length; i++) {
var _path = path.resolve(path.dirname(url),$('img')[i].attribs.src);
var _size = images(_path).size();
if (!$('img')[i].attribs.width || !$('img')[i].attribs.height) {
$('img:nth-child(' + (i + 1) + ')').attr('width', _size.width * _multiple);
$('img:nth-child(' + (i + 1) + ')').attr('height', _size.height * _multiple);
console.log("handled \"" + $('img')[i].attribs.src + "\" in file \"" + url + "\"");
isChanged = true;
}
};
if (isChanged) {
fs.writeFileSync(url, $.html());
console.log("write file successfully!");
}
}
module.exports = autoSize;<file_sep>/index.js
#! /usr/bin/env node
var watching = require('./lib/watching');
var program = require('commander');
var path = process.cwd() + "/**/*.html";
program
.version('0.1.0')
.option('-m, --multiple <n>', 'An float argument', parseFloat)
.action(function(options) {
console.log(options)
})
.parse(process.argv);
var m = program.multiple || 1;
watching(path, m);
// console.log(path);
<file_sep>/test/watching.test.js
var watching = require('../lib/watching');
//describe('ไธบๅพ็ๆทปๅ ๅฎฝๅบฆๅ้ซๅบฆ', function() {
//describe('่ทๅhtmlๅ
ๅฎน', function () {
// it('ๅบ่ฏฅๆๅฐๅบhtmlๆๆฌ', function (done) {
//
// done();
// });
//});
//});
watching();
| f5df330ac0ed71cd6c92daf5d42fdfe333d7befb | [
"JavaScript"
] | 5 | JavaScript | hoipo/auto-img-size | dfae439e3e97c1f3909a17fead1b804b6fcb3420 | 046ab58f60f8cad645b06281ebc1fd0ec7deeced |
refs/heads/master | <file_sep>package com.dac.mocs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableTransactionManagement
public class MocsApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
public static void main(String[] args) {
SpringApplication.run(MocsApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(MocsApplication.class);
}
}
<file_sep>package com.dac.mocs.util;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
/**
* https://www.cnblogs.com/moonlightL/p/10020732.html
* ไฝฟ็จjwt็ๆToken๏ผ่ฏฅtokenๆๆๆถ้ดไธบ7ๅคฉ
* 2019-7-18
*/
public class TokenUtil {
private static Key KEY= Keys.secretKeyFor(SignatureAlgorithm.HS256);//ๆๆถๅ
้ๆบ็ๆkey
//private static Key KEY = new SecretKeySpec("test".getBytes(),SignatureAlgorithm.HS256.getJcaName());//ๅบๅฎ็ๆ็ง้ฅ
private static final long EFFECTIVE_TIME = 7 * 24 * 3600 * 1000;//ๆๆๆถ้ดไธบ7ๅคฉ
/**
* ๆ นๆฎ็จๆทidๅๅปบjwt
*/
public static String create(int id) {
String token = Jwts.builder()
.claim("user_id", id)
.claim("expire_time", EFFECTIVE_TIME + System.currentTimeMillis())
.signWith(KEY).compact();
return token;
}
/**
* ่งฃๆjwt,่ฟๅbody,ๆๅผๅธธ่กจ็คบ่ฏฅjwtไธๅๆณ
*
* @return
* @throws
*/
public static Claims parse(String token) throws JwtException {
Jws<Claims> result = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token);
Claims body = result.getBody();
return body;
}
}
<file_sep>package com.dac.mocs.service;
import com.dac.mocs.bean.User;
import com.dac.mocs.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper mUserMapper;
/**
* ๆ นๆฎqqId่ฟ่ก็ปๅฝ๏ผ่ฟๅ็จๆทไฟกๆฏ๏ผๅฆๆๆฒกๆ็่ฏๅๆฐๅปบ็จๆท
* @return
*/
public User QQlogin(String qqId){
User user=mUserMapper.selectSingleByQQId(qqId);
if (user!=null)//ๆฅ่ฏขๅฐ่ฏฅ็จๆท
return user;
//ๆฒกๆ่ฏฅ็จๆทๅๆๅ
ฅไธไธชๆฐ็จๆท
user=new User();
user.setQqId(qqId);
user.setNickname("noname");
mUserMapper.insertQQUser(user);
return user;
}
}
<file_sep>package com.dac.mocs.dao;
import com.dac.mocs.bean.RecordStep;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface RecordStepMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table record_step
*
* @mbg.generated
*/
int insert(RecordStep record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table record_step
*
* @mbg.generated
*/
List<RecordStep> selectAll();
/**
* ๆ นๆฎrecordidๆฅๆพRecordStep
* @param recordId
* @return
*/
List<RecordStep> selectList(int recordId);
}<file_sep>package com.dac.mocs.bean;
import java.io.Serializable;
public class RecordStep implements Serializable {
public RecordStep(Integer recordId, String description, Long createdTime) {
this.recordId = recordId;
this.description = description;
this.createdTime = createdTime;
}
public RecordStep() {
}
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column record_step.record_id
*
* @mbg.generated
*/
private Integer recordId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column record_step.step_id
*
* @mbg.generated
*/
private Integer stepId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column record_step.description
*
* @mbg.generated
*/
private String description;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column record_step.created_time
*
* @mbg.generated
*/
private Long createdTime;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table record_step
*
* @mbg.generated
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column record_step.record_id
*
* @return the value of record_step.record_id
*
* @mbg.generated
*/
public Integer getRecordId() {
return recordId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column record_step.record_id
*
* @param recordId the value for record_step.record_id
*
* @mbg.generated
*/
public void setRecordId(Integer recordId) {
this.recordId = recordId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column record_step.step_id
*
* @return the value of record_step.step_id
*
* @mbg.generated
*/
public Integer getStepId() {
return stepId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column record_step.step_id
*
* @param stepId the value for record_step.step_id
*
* @mbg.generated
*/
public void setStepId(Integer stepId) {
this.stepId = stepId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column record_step.description
*
* @return the value of record_step.description
*
* @mbg.generated
*/
public String getDescription() {
return description;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column record_step.description
*
* @param description the value for record_step.description
*
* @mbg.generated
*/
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column record_step.created_time
*
* @return the value of record_step.created_time
*
* @mbg.generated
*/
public Long getCreatedTime() {
return createdTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column record_step.created_time
*
* @param createdTime the value for record_step.created_time
*
* @mbg.generated
*/
public void setCreatedTime(Long createdTime) {
this.createdTime = createdTime;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table record_step
*
* @mbg.generated
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", recordId=").append(recordId);
sb.append(", stepId=").append(stepId);
sb.append(", description=").append(description);
sb.append(", createdTime=").append(createdTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}<file_sep>package com.dac.mocs.service;
import com.dac.mocs.bean.Record;
import com.dac.mocs.bean.RecordImage;
import com.dac.mocs.bean.RecordInfo;
import com.dac.mocs.bean.RecordStep;
import com.dac.mocs.dao.RecordImageMapper;
import com.dac.mocs.dao.RecordMapper;
import com.dac.mocs.dao.RecordStepMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Service
public class RecordService {
@Autowired
private RecordMapper mRecordMapper;
@Autowired
private RecordImageMapper mRecordImageMapper;
@Autowired
private RecordStepMapper mRecordStepMapper;
@Value("${images.path}")
private String imagesPath;
/**
*
* @param recordId
* @return
*/
public List<RecordStep> selectRecordStep(int recordId){
return mRecordStepMapper.selectList(recordId);
}
/**
* ๅจๆๅ
ฅRecordๅๆๅ
ฅRecordStep,ๅจ็จๆทๆฐๅปบRecordๆถไฝฟ็จ๏ผRecordๅฟ
้กปๆ้ป่ฎค็RecordStep
* @param record
* @return
*/
@Transactional
public boolean insertRecordAndDefaultStep(Record record) {
int r1 = insertRecord(record);
RecordStep recordStep = new RecordStep(record.getRecordId(), "ๅฎกๆ ธไธญ",record.getCreatedTime());
int r2 = insertRecordStep(recordStep);
//่ฟๅๆๅ
ฅ็ปๆ
if (r1 > 0 && r2 > 0)
return true;
else
return false;
}
/**
* ๆๅ
ฅไธๆกrecord,ๆๅ
ฅๆๅๅ recordIdไผๆณจๅ
ฅๅฐๅๆฐไธญ
*
* @param record
* @return 1ไปฃ่กจๆๅ
ฅๆๅ๏ผ0ไปฃ่กจๅคฑ่ดฅ
*/
protected int insertRecord(Record record) {
return mRecordMapper.insert(record);
}
/**
* ๆๅ
ฅไธๆกRecordStep๏ผๅจๆฏๆฌกๆๅ
ฅๆฐRecordๅ่ฐ็จ๏ผๆทปๅ ๆถ้ด่ฝด็็ฌฌไธๆญฅ
*
* @param step
* @return
*/
public int insertRecordStep(RecordStep step) {
return mRecordStepMapper.insert(step);
}
/**
* ไฟๅญๅพ็ๅฐ็กฌ็๏ผๅนถๆ่ทฏๅพๆๅ
ฅๅฐๆฐๆฎๅบไธญ
*
* @param files
* @param recordId
*/
public void saveAndInsertRecordImages(List<MultipartFile> files, int recordId) throws IOException {
File dir = new File(imagesPath);
if (!dir.exists()) {
dir.mkdirs();//ๅฆๆไธๅญๅจ ๅๅปบๆไปถๅคน
}
for (MultipartFile mpFile : files)
if (!mpFile.isEmpty()) {
String s = imagesPath + mpFile.getOriginalFilename();
mpFile.transferTo(new File(s));
RecordImage recordImage = new RecordImage();
recordImage.setRecordId(recordId);
recordImage.setImagePath(s);
mRecordImageMapper.insert(recordImage);//ๆๅ
ฅไธๆก
}
}
/**
* ๆrecord_idๅๅบๆฅ่ฏข
*
* @param userId
* @param offset ๅ็งป้๏ผไป็ฌฌๅ ่กๅผๅง่ฟๅ
* @param rows ๆๅค่ฟๅๅคๅฐ่ก
* @return
*/
public List<RecordInfo> getRecordInfoByUserId(int userId, int offset, int rows) {
return mRecordMapper.selectByUserId(userId, offset, rows);
}
}
<file_sep>package com.dac.mocs.util;
import com.google.gson.Gson;
public class GsonUtil {
public static final Gson INSTANCE =new Gson();
}
<file_sep>package com.dac.mocs.dao;
import com.dac.mocs.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
int insert(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbg.generated
*/
List<User> selectAll();
User selectSingleByQQId(String qqid);
int insertQQUser(User user);
}<file_sep>package com.dac.mocs.controller;
import com.dac.mocs.MocsApplication;
import com.dac.mocs.util.TokenUtil;
import org.apache.el.parser.Token;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MocsApplication.class)
@WebAppConfiguration
public class RecordControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private final int testid=10;
@Before
public void setUp(){
mockMvc= MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* ๆต่ฏๆฅๆพstep
* @throws Exception
*/
@Test
public void getRecordStep() throws Exception {
String token= TokenUtil.create(testid);
String response=mockMvc.perform(MockMvcRequestBuilders.get("/records/step?id=61").header("Authorization",token))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn().getResponse().getContentAsString();
}
} | 82dccd51fe8c0b61096e41734a6e996d7ee04fe3 | [
"Java"
] | 9 | Java | aaa205/mocs-web | 08048019132c17a37f9f9d18185bfe67ea875efa | 5244433e7feed73d87fc87fbcc29da42d79eb6ec |
refs/heads/main | <repo_name>nick0bajaj/traderBot<file_sep>/tdClient.py
import requests
import json
import math
import pandas as pd
td_consumer_key = '<KEY>'
#quote
def getStats(stock):
endpoint = 'https://api.tdameritrade.com/v1/marketdata/{stock_ticker}/quotes?'
full_url = endpoint.format(stock_ticker=stock)
page = requests.get(url=full_url,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)
return content
#historical
def getHistory(stock):
endpoint = 'https://api.tdameritrade.com/v1/marketdata/{stock_ticker}/pricehistory'
full_url = endpoint.format(stock_ticker=stock)
page = requests.get(url=full_url,
params={'apikey' : td_consumer_key})
content = json.loads(page.content)
print(content)
return content['candless']
def parseGetHistory(stock):
history = {}
ema = 0
smoothing = 2
oldhistory = getHistory(stock)
days = len(oldhistory)
for i in oldhistory:
datetime = i["datetime"]
avgPrice = (i['open'] + i['high'] + i['low'] + i['close'])/4
ema = (avgPrice * (smoothing/(1+days))) + ema * (1 - (smoothing/(1 + days)))
history[stock] = (ema, datetime, (i['close'] - ema))
return history
def getReccomendations():
totalEma = {}
topFiveNames = [0,1,2,3,4]
test = math.inf
topFiveValues = [(0,test),(0,test),(0,test),(0,test),(0,test)]
for stock in getSymbols():
i = 0
currEma = parseGetHistory(stock)[stock]
totalEma[stock] = currEma
while(i < 4):
currVal = currEma[0]
currDiff = currEma[1]
if (currVal > topFiveValues[i][0]) and (currVal < topFiveValues[i][1]):
topFiveNames[i] = stock
topFiveValues[i] = (currVal, currDiff)
i = 5
else:
i = i + 1
return topFiveNames
def getSymbols():
table=pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
df = table[0]
df.to_csv('S&P500-Info.csv')
df.to_csv("S&P500-Symbols.csv", columns=['Symbol'])
return df["Symbol"]
print(getReccomendations())
# def getOldFile():
# oldFile = open("stockData.txt","r+")
# oldData = {}
# for line in oldFile:
# symbol, ema, timestamp = line.split(" ")
# oldData[symbol] = (ema, timestamp)
# return oldFile, oldData
# def updateFile():
# symbols = getSymbols()
# oldFile, oldData = getOldFile()
# newData = oldData.copy()
# for symbol in symbols:
# timestamp = getStats(symbol)
# if(oldData(symbol)):
# if(oldData(symbol)[1] != timestamp):
# updateStock(newData, timestamp, symbol)
# oldFile.writelines(newData)
# def updateStock(newData, timestamp, symbol):
# getHistory(symbol)[[timestamp]:]
# emi = calculateEMI(valueLst)
# newData[symbol] = (emi, timestamp)
# return newData
| 3707f3f8fb877f8c7184f0e66af01b47642005e0 | [
"Python"
] | 1 | Python | nick0bajaj/traderBot | 849e8686c4aadd6d02a439baedc141db0b95d023 | 5600469cb6916e9bf0d0164d262a38e2633fb92a |
refs/heads/master | <file_sep>import subprocess
from .base import Base as BaseSource
from ..kind.base import Base as BaseKind
def run_command(commands, cwd, encoding='utf-8'):
try:
p = subprocess.run(commands,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return []
return p.stdout.decode(encoding).split('\n')
class Source(BaseSource):
def __init__(self, vim):
super().__init__(vim)
self.vim = vim
self.name = 'tmuxsessions'
self.kind = TmuxSessionKind(vim)
def gather_candidates(self, context):
command = ['tmux', 'list-sessions']
condidates = []
lines = run_command(command, '.')
self.vim.out_write('gathering candidates')
for line in lines:
condidates.append({ 'word': line.split(':')[0] })
return condidates
class TmuxSessionKind(BaseKind):
def __init__(self, vim):
super().__init__(vim)
self.vim = vim
self.name = 'tmux_session'
self.default_action = 'switch_client'
def action_switch_client(self, context):
target = context['targets'][0]
session = target['word']
run_command(['tmux', 'switch-client', '-t', session], '.')
# self.vim.command('echom "' + session + '"')
<file_sep>import pynvim
@pynvim.plugin
class testPlugin(object):
def __init__(self, nvim):
self.nvim = nvim
@pynvim.autocmd('BufEnter', pattern='*.py', eval='expand("<afile>")', sync=True)
def on_bufenter(self, filename):
pass
# self.nvim.out_write('testplugin is in ' + filename + '\n')
| a59547d5ee52e9d107f8a13e1ef66cd92b38a719 | [
"Python"
] | 2 | Python | purefun/vimrc | ddbefaf27d29a8157eb68ce1b5f080b8f0bc6b5c | 564b7cd9ffa410035711ad27be5e903b3f00823f |
refs/heads/master | <repo_name>ashiqdev/devops-directive<file_sep>/2020-08-10-smaller-docker-containers/go/Makefile
run:
docker run -i -d -p 8081:8081 go-naive
build-naive:
docker build \
-f $(CURDIR)/Dockerfile.naive \
-t go-naive \
.
build-alpine:
docker build \
-f $(CURDIR)/Dockerfile.alpine \
-t go-alpine \
.
build-alpine-multi:
docker build \
-f $(CURDIR)/Dockerfile.alpine-multi \
-t go-alpine-multi \
.
<file_sep>/README.md
# devops-directive
Code samples from the DevOps Directive YouTube channel
<file_sep>/2020-08-10-smaller-docker-containers/node/Makefile
run:
docker run -i -d -p 8080:8080 node-naive
# 918MB
build-naive:
docker build \
-f $(CURDIR)/Dockerfile.naive \
-t node-naive \
.
# 142MB
build-slim:
docker build \
-f $(CURDIR)/Dockerfile.slim \
-t node-slim \
.
# 89.3MB
build-alpine:
docker build \
-f $(CURDIR)/Dockerfile.alpine \
-t node-alpine \
.
<file_sep>/2020-08-31-docker-compose/README.md
# MERN Docker Compose Demo
I followed [this tutorial](https://medium.com/swlh/how-to-create-your-first-mern-mongodb-express-js-react-js-and-node-js-stack-7e8b20463e66) to get basic app working.
I then containerized the api server and react client and created docker-compose to connect them.
---
Run `make build` from root to build containers
Run `make run` from root to run containers with docker-compose
---
**NOTE:** This is a development configuration where the react app is being served by a separate container. We would also want to create a production version where we build a static version of the react site and serve it with something like nginx.
<file_sep>/2020-08-31-docker-compose/client/src/pages/index.js
import MoviesList from './MoviesList'
import MoviesInsert from './MoviesInsert'
import MoviesUpdate from './MoviesUpdate'
export { MoviesList, MoviesInsert, MoviesUpdate }<file_sep>/2020-09-21-docker-compose-cos/README.md
# Using docker-compose on Google's Container Optimized OS (COS)
## Resources
https://cloud.google.com/community/tutorials/docker-compose-on-container-optimized-os
docker compose w/ GCR... https://github.com/fpgaminer/docker-compose-gcr/blob/master/Dockerfile
Potential security issues with mounting docker socket: https://blog.secureideas.com/2018/05/escaping-the-whale-things-you-probably-shouldnt-do-with-docker-part-1.html
<file_sep>/2020-09-21-docker-compose-cos/django-example/README.md
# Docker-compose on container optimized OS
## Customizing Makefile
Replace `PROJECT_ID` and `USER` to match your GCP project id and username
## Creating Static IP address and VM
`make create-static-ip && make create-vm`
## Deleting when done (so you dont keep getting charged)
`make delete-vm` --> `y`
`make delete-static-ip` -> `y`
## SSH onto VM:
`make ssh`
---
## Django docker-compose example
### link
https://docs.docker.com/compose/django/
<file_sep>/2020-09-21-docker-compose-cos/Makefile
PROJECT_ID:=devops-directive-project
REGION:=us-central1
ZONE:=us-central1-a
VM_NAME:=docker-compose
USER:=palas
SSH_STRING:=$(USER)@$(VM_NAME)
HOME_PATH:=/home/$(USER)
create-static-ip:
gcloud compute \
addresses create $(VM_NAME) \
--project=$(PROJECT_ID) \
--region=$(REGION)
delete-static-ip:
gcloud compute \
addresses delete $(VM_NAME) \
--project=$(PROJECT_ID) \
--region=$(REGION) \
create-vm:
gcloud beta compute \
instances create $(VM_NAME) \
--project=$(PROJECT_ID) \
--zone=$(ZONE) \
--address=$(VM_NAME) \
--machine-type=e2-medium \
--subnet=default \
--network-tier=PREMIUM \
--metadata=google-logging-enabled=true \
--maintenance-policy=MIGRATE \
--service-account=1006868470482-compute<EMAIL> \
--scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/trace.append \
--tags=http-server \
--image=cos-stable-81-12871-1196-0 \
--image-project=cos-cloud \
--boot-disk-size=10GB \
--boot-disk-type=pd-standard \
--boot-disk-device-name=$(VM_NAME)
delete-vm:
gcloud compute \
--project=$(PROJECT_ID) \
instances delete $(VM_NAME) \
--zone=$(ZONE) \
#################
ssh:
gcloud compute ssh $(SSH_STRING) --project=$(PROJECT_ID) --zone=$(ZONE)
define send-ssh-command
gcloud compute ssh $(SSH_STRING) \
--project=$(PROJECT_ID) \
--zone=$(ZONE) \
--command $(1)
endef
CONFIGURE_DOCKER_AUTH:="docker-credential-gcr configure-docker"
configure-gcr:
$(call send-ssh-command,$(CONFIGURE_DOCKER_AUTH))
REPO:=https://github.com/sidpalas/devops-directive.git
CLONE_REPO:="docker run -i --rm -v $(HOME_PATH):/root -v $(HOME_PATH):/git alpine/git clone $(REPO)"
clone-repo:
$(call send-ssh-command,$(CLONE_REPO))
define ALIAS_COMMAND
"`cat ./alias.sh`"
endef
alias-docker-compose:
$(call send-ssh-command,$(ALIAS_COMMAND))
<file_sep>/2020-09-21-docker-compose-cos/alias.sh
echo alias docker-compose="'"'docker run --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
-v "$PWD:$PWD" \
-w="$PWD" \
cryptopants/docker-compose-gcr@sha256:a59f0d61e424e52d3fed72a151241bfe6f4f4611f2e4f5e928ef4eeb47662a54'"'" >> ~/.bashrc; \
source ~/.bashrc; | 21154ba2547bbad9fccadf12fbbc62a33fd21c17 | [
"Markdown",
"JavaScript",
"Makefile",
"Shell"
] | 9 | Makefile | ashiqdev/devops-directive | ef75dd73f970a82825c2690fb33541f045ae9bba | f4a0c668de50a1cf652389bfbf93362feebad933 |
refs/heads/master | <repo_name>sochetanie/module-3-backend-1<file_sep>/app/controllers/stocks_controller.rb
class StocksController < ApplicationController
def index
@stocks = Stock.all
render json: @stocks
end
def create
@stock = Stock.create(stock_params)
render json: @stock
end
private
def stock_params
params.require(:stock).permit(:name, :price, :ticker, :date)
end
end
| 66c487cb41f75667a8b3d28b4b62ca9c34f439df | [
"Ruby"
] | 1 | Ruby | sochetanie/module-3-backend-1 | 5e945db3977df8e54a4c96a4bc53c3b549e7071d | 046875d23edbccddeeba58ecb0550442eecea28b |
refs/heads/master | <file_sep>module lukechampine.com/walrus-cli
go 1.13
require (
go.sia.tech/siad v1.5.7
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2
lukechampine.com/flagg v1.1.1
lukechampine.com/sialedger v1.0.1-0.20210924201921-c9e226ec0ca3
lukechampine.com/us v0.19.4
lukechampine.com/walrus v0.10.8
)
<file_sep>package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math/big"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"go.sia.tech/siad/build"
"go.sia.tech/siad/crypto"
"go.sia.tech/siad/types"
"golang.org/x/crypto/ssh/terminal"
"lukechampine.com/flagg"
"lukechampine.com/sialedger"
"lukechampine.com/us/wallet"
"lukechampine.com/walrus"
)
var (
// to be supplied at build time
githash = "?"
builddate = "?"
)
var (
rootUsage = `Usage:
walrus-cli [flags] [action]
Actions:
seed generate a seed
balance view current balance
consensus view blockchain information
addresses list addresses
addr generate an address
txn create a transaction
split create an output-splitting transaction
defrag create an output-merging transaction
sign sign a transaction
broadcast broadcast a transaction
transactions list transactions
`
versionUsage = rootUsage
balanceUsage = `Usage:
walrus-cli balance
Reports the current balance.
`
seedUsage = `Usage:
walrus-cli seed
Generates a random seed.
`
consensusUsage = `Usage:
walrus-cli consensus
Reports the current block height and change ID.
`
addressesUsage = `Usage:
walrus-cli addresses
Lists addresses tracked by the wallet.
`
addrUsage = `Usage:
walrus-cli addr
walrus-cli addr [key index]
Generates an address. If no key index is provided, the lowest unused key index
is used. The address is added to the wallet's set of tracked addresses.
`
txnUsage = `Usage:
walrus-cli txn [outputs] [file]
Creates a transaction with the provided set of outputs, which are specified as a
comma-separated list of address:value pairs, where value is specified in SC. The
inputs are selected automatically, and a change address is generated if needed.
`
splitUsage = `Usage:
walrus-cli split [n] [value] [file]
Creates a transaction that splits the wallet's existing inputs into n outputs,
each with the specified value. The inputs are selected automatically, and a
change address is generated if needed.
`
defragUsage = `Usage:
walrus-cli defrag [value] [file]
Creates a transaction that merges inputs worth less than value into one output.
To avoid exceeding the maximum transaction size, at most 100 inputs will be
selected, so it may be necessary to run this command multiple times.
`
signUsage = `Usage:
walrus-cli sign [txn]
Signs all wallet-controlled inputs of the provided transaction.
`
broadcastUsage = `Usage:
walrus-cli broadcast [txn]
Broadcasts the provided transaction.
`
transactionsUsage = `Usage:
walrus-cli transactions
Lists transactions relevant to the wallet.
`
)
func check(err error, ctx string) {
if err != nil {
log.Fatalf("%v: %v", ctx, err)
}
}
func plural(n int) string {
if n == 1 {
return ""
}
return "s"
}
func currencyUnits(c types.Currency) string {
r := new(big.Rat).SetFrac(c.Big(), types.SiacoinPrecision.Big())
sc := strings.TrimRight(r.FloatString(30), "0")
return strings.TrimSuffix(sc, ".") + " SC"
}
func parseCurrency(s string) types.Currency {
r, ok := new(big.Rat).SetString(strings.TrimSpace(s))
if !ok {
_, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
check(err, "Invalid currency value")
}
return types.SiacoinPrecision.MulRat(r)
}
func readTxn(filename string) types.Transaction {
js, err := ioutil.ReadFile(filename)
check(err, "Could not read transaction file")
var txn types.Transaction
err = json.Unmarshal(js, &txn)
check(err, "Could not parse transaction file")
return txn
}
func writeTxn(filename string, txn types.Transaction) {
js, _ := json.MarshalIndent(txn, "", " ")
js = append(js, '\n')
err := ioutil.WriteFile(filename, js, 0666)
check(err, "Could not write transaction to disk")
}
func getDonationAddr(narwalAddr string) (types.UnlockHash, bool) {
u, err := url.Parse(narwalAddr)
if err != nil {
return types.UnlockHash{}, false
}
path := strings.Split(u.Path, "/")
if len(path) < 2 || path[len(path)-2] != "wallet" {
return types.UnlockHash{}, false
}
path = append(path[:len(path)-2], "donations")
u.Path = strings.Join(path, "/")
resp, err := http.Get(u.String())
if err != nil {
return types.UnlockHash{}, false
}
defer resp.Body.Close()
defer ioutil.ReadAll(resp.Body)
var addr types.UnlockHash
err = json.NewDecoder(resp.Body).Decode(&addr)
return addr, err == nil
}
var getSeed = func() func() wallet.Seed {
var seed wallet.Seed
return func() wallet.Seed {
if seed == (wallet.Seed{}) {
phrase := os.Getenv("WALRUS_SEED")
if phrase != "" {
fmt.Println("Using WALRUS_SEED environment variable")
} else {
fmt.Print("Seed: ")
pw, err := terminal.ReadPassword(int(os.Stdin.Fd()))
check(err, "Could not read seed phrase")
fmt.Println()
phrase = string(pw)
}
var err error
seed, err = wallet.SeedFromPhrase(phrase)
check(err, "Invalid seed")
}
return seed
}
}()
var getNanoS = func() func() *sialedger.NanoS {
var nanos *sialedger.NanoS
return func() *sialedger.NanoS {
if nanos == nil {
var err error
nanos, err = sialedger.OpenNanoS()
check(err, "Could not connect to Nano S")
}
return nanos
}
}()
func main() {
log.SetFlags(0)
var sign, broadcast bool // used by txn and sign commands
var changeAddrStr string // used by the txn and split commands
var showPubkey bool // used by the addr command
rootCmd := flagg.Root
apiAddr := rootCmd.String("a", "http://localhost:9380", "host:port that the walrus API is running on")
ledger := rootCmd.Bool("ledger", false, "use a Ledger Nano S instead of a seed")
rootCmd.Usage = flagg.SimpleUsage(rootCmd, rootUsage)
versionCmd := flagg.New("version", versionUsage)
seedCmd := flagg.New("seed", seedUsage)
balanceCmd := flagg.New("balance", balanceUsage)
consensusCmd := flagg.New("consensus", consensusUsage)
addressesCmd := flagg.New("addresses", addressesUsage)
addrCmd := flagg.New("addr", addrUsage)
addrCmd.BoolVar(&showPubkey, "pubkey", false, "also display the address's public key")
txnCmd := flagg.New("txn", txnUsage)
txnCmd.BoolVar(&sign, "sign", false, "sign the transaction")
txnCmd.BoolVar(&broadcast, "broadcast", false, "broadcast the transaction")
txnCmd.StringVar(&changeAddrStr, "change", "", "use this change address instead of generating a new one")
splitCmd := flagg.New("split", splitUsage)
splitCmd.BoolVar(&sign, "sign", false, "sign the transaction")
splitCmd.BoolVar(&broadcast, "broadcast", false, "broadcast the transaction")
splitCmd.StringVar(&changeAddrStr, "change", "", "use this change address instead of generating a new one")
defragCmd := flagg.New("defrag", defragUsage)
defragCmd.BoolVar(&sign, "sign", false, "sign the transaction")
defragCmd.BoolVar(&broadcast, "broadcast", false, "broadcast the transaction")
defragCmd.StringVar(&changeAddrStr, "change", "", "use this change address instead of generating a new one")
signCmd := flagg.New("sign", signUsage)
signCmd.BoolVar(&broadcast, "broadcast", false, "broadcast the transaction (if true, omit file)")
broadcastCmd := flagg.New("broadcast", broadcastUsage)
transactionsCmd := flagg.New("transactions", transactionsUsage)
cmd := flagg.Parse(flagg.Tree{
Cmd: rootCmd,
Sub: []flagg.Tree{
{Cmd: versionCmd},
{Cmd: seedCmd},
{Cmd: consensusCmd},
{Cmd: balanceCmd},
{Cmd: addressesCmd},
{Cmd: addrCmd},
{Cmd: txnCmd},
{Cmd: splitCmd},
{Cmd: defragCmd},
{Cmd: signCmd},
{Cmd: broadcastCmd},
{Cmd: transactionsCmd},
},
})
args := cmd.Args()
c := walrus.NewClient(*apiAddr)
switch cmd {
case rootCmd:
if len(args) != 0 {
cmd.Usage()
return
}
fallthrough
case versionCmd:
log.Printf("walrus-cli v0.1.0\nCommit: %s\nRelease: %s\nGo version: %s %s/%s\nBuild Date: %s\n",
githash, build.Release, runtime.Version(), runtime.GOOS, runtime.GOARCH, builddate)
case seedCmd:
if len(args) != 0 {
cmd.Usage()
return
}
fmt.Println(wallet.NewSeed())
case consensusCmd:
if len(args) != 0 {
cmd.Usage()
return
}
info, err := c.ConsensusInfo()
check(err, "Could not get consensus info")
fmt.Printf("Height: %v\nChange ID: %v\n", info.Height, info.CCID)
case balanceCmd:
if len(args) != 0 {
cmd.Usage()
return
}
bal, err := c.Balance(true)
check(err, "Could not get balance")
fmt.Println(currencyUnits(bal))
case addressesCmd:
if len(args) != 0 {
cmd.Usage()
return
}
addrs, err := c.Addresses()
check(err, "Could not get address list")
if len(addrs) == 0 {
fmt.Println("No addresses.")
} else {
for _, addr := range addrs {
fmt.Println(addr)
}
}
case addrCmd:
if len(args) > 1 {
cmd.Usage()
return
}
var index uint64
var err error
if len(args) == 0 {
index, err = c.SeedIndex()
check(err, "Could not get next seed index")
fmt.Printf("No index specified; using lowest unused index (%v)\n", index)
} else {
index, err = strconv.ParseUint(args[0], 10, 32)
check(err, "Invalid index")
}
var pubkey types.SiaPublicKey
if *ledger {
nanos := getNanoS()
fmt.Printf("Please verify and accept the prompt on your device to generate address #%v.\n", index)
_, pubkey, err = nanos.GetAddress(uint32(index), false)
check(err, "Could not generate address")
fmt.Println("Compare the address displayed on your device to the address below:")
fmt.Println(" " + wallet.StandardAddress(pubkey).String())
} else {
seed := getSeed()
pubkey = seed.PublicKey(index)
fmt.Println("Derived address from seed:")
fmt.Println(" " + wallet.StandardAddress(pubkey).String())
}
if showPubkey {
fmt.Println("The pubkey for this address is:")
fmt.Println(" " + pubkey.String())
}
// check for duplicate
addrInfo, err := c.AddressInfo(wallet.StandardAddress(pubkey))
if err == nil && addrInfo.KeyIndex == index {
fmt.Println(`The server reported that it is already tracking this address. No further
action is needed. Please be aware that reusing addresses can compromise
your privacy.`)
return
}
fmt.Print("Press ENTER to add this address to your wallet, or Ctrl-C to cancel.")
bufio.NewReader(os.Stdin).ReadLine()
err = c.AddAddress(wallet.SeedAddressInfo{
UnlockConditions: wallet.StandardUnlockConditions(pubkey),
KeyIndex: index,
})
check(err, "Could not add address to wallet")
fmt.Println("Address added successfully.")
case txnCmd:
if !((len(args) == 2) || (len(args) == 1 && broadcast)) {
cmd.Usage()
return
}
// parse outputs
pairs := strings.Split(args[0], ",")
outputs := make([]types.SiacoinOutput, len(pairs))
var recipSum types.Currency
for i, p := range pairs {
addrAmount := strings.Split(p, ":")
if len(addrAmount) != 2 {
check(errors.New("outputs must be specified in addr:amount pairs"), "Could not parse outputs")
}
err := outputs[i].UnlockHash.LoadString(strings.TrimSpace(addrAmount[0]))
check(err, "Invalid destination address")
outputs[i].Value = parseCurrency(addrAmount[1])
recipSum = recipSum.Add(outputs[i].Value)
}
// if using a narwal server, compute donation
var donation types.Currency
donationAddr, ok := getDonationAddr(*apiAddr)
if ok {
// donation is max(1%, 10SC)
donation = recipSum.MulRat(big.NewRat(1, 100))
if tenSC := types.SiacoinPrecision.Mul64(10); donation.Cmp(tenSC) < 0 {
donation = tenSC
}
}
// fund transaction
utxos, err := c.UnspentOutputs(true)
check(err, "Could not get utxos")
inputs := make([]wallet.ValuedInput, len(utxos))
for i, o := range utxos {
info, err := c.AddressInfo(o.UnlockHash)
check(err, "Could not get address info")
inputs[i] = wallet.ValuedInput{
SiacoinInput: types.SiacoinInput{
ParentID: o.ID,
UnlockConditions: info.UnlockConditions,
},
Value: o.Value,
}
}
feePerByte, err := c.RecommendedFee()
check(err, "Could not get recommended transaction fee")
used, fee, change, ok := wallet.FundTransaction(recipSum.Add(donation), feePerByte, inputs)
if !ok {
// couldn't afford transaction with donation; try funding without
// donation and "donate the change" instead
used, fee, change, ok = wallet.FundTransaction(recipSum, feePerByte, inputs)
if !ok {
check(errors.New("insufficient funds"), "Could not create transaction")
}
donation, change = change, types.ZeroCurrency
}
if !donation.IsZero() {
outputs = append(outputs, types.SiacoinOutput{
UnlockHash: donationAddr,
Value: donation,
})
}
// add change (if there is any)
if !change.IsZero() {
var changeAddr types.UnlockHash
if changeAddrStr != "" {
err = changeAddr.LoadString(changeAddrStr)
check(err, "Could not parse change address")
} else {
changeAddr = getChangeFlow(c, *ledger)
}
outputs = append(outputs, types.SiacoinOutput{
Value: change,
UnlockHash: changeAddr,
})
}
txn := types.Transaction{
SiacoinInputs: make([]types.SiacoinInput, len(used)),
SiacoinOutputs: outputs,
MinerFees: []types.Currency{fee},
}
var inputSum types.Currency
for i, in := range used {
txn.SiacoinInputs[i] = in.SiacoinInput
inputSum = inputSum.Add(in.Value)
}
fmt.Println("Transaction summary:")
fmt.Printf("- %v input%v, totalling %v\n", len(used), plural(len(used)), currencyUnits(inputSum))
fmt.Printf("- %v recipient%v, totalling %v\n", len(pairs), plural(len(pairs)), currencyUnits(recipSum))
if !donation.IsZero() {
fmt.Printf("- A donation of %v to the narwal server\n", currencyUnits(donation))
}
fmt.Printf("- A miner fee of %v, which is %v/byte\n", currencyUnits(fee), currencyUnits(feePerByte))
if !change.IsZero() {
fmt.Printf("- A change output, sending %v back to your wallet\n", currencyUnits(change))
}
fmt.Println()
if sign {
if *ledger {
err := signFlowCold(c, &txn)
check(err, "Could not sign transaction")
} else {
err := signFlowHot(c, &txn)
check(err, "Could not sign transaction")
}
} else {
fmt.Println("Transaction has not been signed. You can sign it with the 'sign' command.")
}
if broadcast {
err := broadcastFlow(c, txn)
check(err, "Could not broadcast transaction")
return
}
writeTxn(args[1], txn)
if sign {
fmt.Println("Wrote signed transaction to", args[1])
} else {
fmt.Println("Wrote unsigned transaction to", args[1])
}
case splitCmd:
if !((len(args) == 3) || (len(args) == 2 && broadcast)) {
cmd.Usage()
return
}
// parse
n, err := strconv.Atoi(args[0])
check(err, "Could not parse number of outputs")
per := parseCurrency(args[1])
// fetch utxos and fee
utxos, err := c.UnspentOutputs(true)
check(err, "Could not get utxos")
feePerByte, err := c.RecommendedFee()
check(err, "Could not get recommended transaction fee")
ins, fee, change := wallet.DistributeFunds(utxos, n, per, feePerByte)
if len(ins) == 0 {
check(errors.New("insufficient funds"), "Could not create split transaction")
}
// get change output
var changeAddr types.UnlockHash
if changeAddrStr != "" {
err = changeAddr.LoadString(changeAddrStr)
check(err, "Could not parse change address")
} else {
changeAddr = getChangeFlow(c, *ledger)
}
// create txn
txn := types.Transaction{
SiacoinInputs: make([]types.SiacoinInput, len(ins)),
SiacoinOutputs: make([]types.SiacoinOutput, n, n+1),
MinerFees: []types.Currency{fee},
}
for i, o := range ins {
info, err := c.AddressInfo(o.UnlockHash)
check(err, "Could not get address info")
txn.SiacoinInputs[i] = types.SiacoinInput{
ParentID: o.ID,
UnlockConditions: info.UnlockConditions,
}
}
for i := range txn.SiacoinOutputs {
txn.SiacoinOutputs[i] = types.SiacoinOutput{
UnlockHash: changeAddr,
Value: per,
}
}
if !change.IsZero() {
txn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{
UnlockHash: changeAddr,
Value: change,
})
}
fmt.Println("Transaction summary:")
fmt.Printf("- %v input%v, totalling %v\n", len(ins), plural(len(ins)), currencyUnits(wallet.SumOutputs(ins)))
fmt.Printf("- %v outputs, each worth %v, totalling %v\n", n, per, currencyUnits(per.Mul64(uint64(n))))
fmt.Printf("- A miner fee of %v, which is %v/byte\n", currencyUnits(fee), currencyUnits(feePerByte))
if !change.IsZero() {
fmt.Printf("- A change output, containing the remaining %v\n", currencyUnits(change))
}
fmt.Println()
if sign {
if *ledger {
err := signFlowCold(c, &txn)
check(err, "Could not sign transaction")
} else {
err := signFlowHot(c, &txn)
check(err, "Could not sign transaction")
}
} else {
fmt.Println("Transaction has not been signed. You can sign it with the 'sign' command.")
}
if broadcast {
err := broadcastFlow(c, txn)
check(err, "Could not broadcast transaction")
return
}
writeTxn(args[2], txn)
if sign {
fmt.Println("Wrote signed transaction to", args[2])
} else {
fmt.Println("Wrote unsigned transaction to", args[2])
}
case defragCmd:
if !((len(args) == 2) || (len(args) == 1 && broadcast)) {
cmd.Usage()
return
}
// parse
min := parseCurrency(args[0])
// fetch utxos and fee
utxos, err := c.UnspentOutputs(true)
check(err, "Could not get utxos")
feePerByte, err := c.RecommendedFee()
check(err, "Could not get recommended transaction fee")
// sort by value (descending)
sort.Slice(utxos, func(i, j int) bool {
return utxos[i].Value.Cmp(utxos[j].Value) > 0
})
var ins []wallet.UnspentOutput
for i, u := range utxos {
if u.Value.Cmp(min) < 0 {
ins = utxos[i:]
break
}
}
if len(ins) > 100 {
// use the 100 most valuable
ins = ins[:100]
}
total := wallet.SumOutputs(ins)
// get change output
var changeAddr types.UnlockHash
if changeAddrStr != "" {
err = changeAddr.LoadString(changeAddrStr)
check(err, "Could not parse change address")
} else {
changeAddr = getChangeFlow(c, *ledger)
}
// create txn
txn := types.Transaction{
SiacoinInputs: make([]types.SiacoinInput, len(ins)),
SiacoinOutputs: []types.SiacoinOutput{{
UnlockHash: changeAddr,
Value: types.SiacoinPrecision, // placeholder, for fee calculation
}},
MinerFees: []types.Currency{types.SiacoinPrecision}, // placeholder, for fee calculation
}
for i, o := range ins {
info, err := c.AddressInfo(o.UnlockHash)
check(err, "Could not get address info")
txn.SiacoinInputs[i] = types.SiacoinInput{
ParentID: o.ID,
UnlockConditions: info.UnlockConditions,
}
}
txn.MinerFees[0] = feePerByte.Mul64(uint64(txn.MarshalSiaSize()))
if txn.MinerFees[0].Cmp(total) >= 0 {
check(errors.New("miner fee exceeds value of inputs"), "Could not create defrag transaction")
}
txn.SiacoinOutputs[0].Value = total.Sub(txn.MinerFees[0])
fmt.Println("Transaction summary:")
fmt.Printf("- %v input%v, totalling %v\n", len(ins), plural(len(ins)), currencyUnits(total))
fmt.Printf("- 1 change output, totalling %v\n", currencyUnits(txn.SiacoinOutputs[0].Value))
fmt.Printf("- A miner fee of %v, which is %v/byte\n", currencyUnits(txn.MinerFees[0]), currencyUnits(feePerByte))
fmt.Println()
if sign {
if *ledger {
err := signFlowCold(c, &txn)
check(err, "Could not sign transaction")
} else {
err := signFlowHot(c, &txn)
check(err, "Could not sign transaction")
}
} else {
fmt.Println("Transaction has not been signed. You can sign it with the 'sign' command.")
}
if broadcast {
err := broadcastFlow(c, txn)
check(err, "Could not broadcast transaction")
return
}
writeTxn(args[1], txn)
if sign {
fmt.Println("Wrote signed transaction to", args[1])
} else {
fmt.Println("Wrote unsigned transaction to", args[1])
}
case signCmd:
if len(args) != 1 {
cmd.Usage()
return
}
txn := readTxn(args[0])
if *ledger {
err := signFlowCold(c, &txn)
check(err, "Could not sign transaction")
} else {
err := signFlowHot(c, &txn)
check(err, "Could not sign transaction")
}
if broadcast {
err := broadcastFlow(c, txn)
check(err, "Could not broadcast transaction")
} else {
ext := filepath.Ext(args[0])
signedPath := strings.TrimSuffix(args[0], ext) + "-signed" + ext
writeTxn(signedPath, txn)
fmt.Println("Wrote signed transaction to", signedPath+".")
fmt.Println("You can now use the 'broadcast' command to broadcast this transaction.")
}
case broadcastCmd:
if len(args) != 1 {
cmd.Usage()
return
}
err := broadcastFlow(c, readTxn(args[0]))
check(err, "Could not broadcast transaction")
case transactionsCmd:
if len(args) != 0 {
cmd.Usage()
return
}
txids, err := c.Transactions(-1)
check(err, "Could not get transactions")
if len(txids) == 0 {
fmt.Println("No transactions to display.")
return
}
txns := make([]walrus.ResponseTransactionsID, len(txids))
for i, txid := range txids {
txns[i], err = c.Transaction(txid)
check(err, "Could not get transaction")
}
fmt.Println("Transaction ID Height Gain/Loss")
for i, txn := range txns {
var delta string
if txn.Debit.IsZero() {
delta = "+" + currencyUnits(txn.Credit)
} else {
delta = "-" + currencyUnits(txn.Debit)
}
fmt.Printf("%v %8v %v\n", txids[i], txn.BlockHeight, delta)
}
}
}
func getChangeFlow(c *walrus.Client, ledger bool) types.UnlockHash {
var pubkey types.SiaPublicKey
fmt.Println("This transaction requires a 'change output' that will send excess coins back to your wallet.")
index, err := c.SeedIndex()
check(err, "Could not get next seed index")
if ledger {
fmt.Println("Please verify and accept the prompt on your device to generate a change address.")
fmt.Println("(You may use the --change flag to specify a change address in advance.)")
_, pubkey, err = getNanoS().GetAddress(uint32(index), false)
check(err, "Could not generate address")
fmt.Println("Compare the address displayed on your device to the address below:")
fmt.Println(" " + wallet.StandardAddress(pubkey).String())
} else {
pubkey = getSeed().PublicKey(index)
fmt.Println("Derived address from seed:")
fmt.Println(" " + wallet.StandardAddress(pubkey).String())
}
fmt.Print("Press ENTER to add this address to your wallet, or Ctrl-C to cancel.")
bufio.NewReader(os.Stdin).ReadLine()
err = c.AddAddress(wallet.SeedAddressInfo{
UnlockConditions: wallet.StandardUnlockConditions(pubkey),
KeyIndex: index,
})
check(err, "Could not add address to wallet")
fmt.Println("Change address added successfully.")
fmt.Println()
return wallet.StandardAddress(pubkey)
}
func broadcastFlow(c *walrus.Client, txn types.Transaction) error {
err := c.Broadcast([]types.Transaction{txn})
if err != nil {
return err
}
fmt.Println("Transaction broadcast successfully.")
fmt.Println("Transaction ID:", txn.ID())
return nil
}
func signFlowCold(c *walrus.Client, txn *types.Transaction) error {
nanos := getNanoS()
addrs, err := c.Addresses()
check(err, "Could not get addresses")
addrMap := make(map[types.UnlockHash]struct{})
for _, addr := range addrs {
addrMap[addr] = struct{}{}
}
sigMap := make(map[int]uint64)
for _, in := range txn.SiacoinInputs {
addr := in.UnlockConditions.UnlockHash()
if _, ok := addrMap[addr]; ok {
// get key index
info, err := c.AddressInfo(addr)
check(err, "Could not get address info")
// add signature entry
sig := wallet.StandardTransactionSignature(crypto.Hash(in.ParentID))
txn.TransactionSignatures = append(txn.TransactionSignatures, sig)
sigMap[len(txn.TransactionSignatures)-1] = info.KeyIndex
continue
}
}
if len(sigMap) == 0 {
fmt.Println("Nothing to sign: transaction does not spend any outputs recognized by this wallet")
return nil
}
// request signatures from device
fmt.Println("Please verify the transaction details on your device. You should see:")
for _, sco := range txn.SiacoinOutputs {
fmt.Println(" ", sco.UnlockHash, "receiving", currencyUnits(sco.Value))
}
for _, fee := range txn.MinerFees {
fmt.Println(" A miner fee of", currencyUnits(fee))
}
if len(sigMap) > 1 {
fmt.Printf("Each signature must be completed separately, so you will be prompted %v times.\n", len(sigMap))
}
for sigIndex, keyIndex := range sigMap {
fmt.Printf("Waiting for signature for input %v, key %v...", sigIndex, keyIndex)
sig, err := nanos.SignTxn(*txn, uint16(sigIndex), uint32(keyIndex))
check(err, "Could not get signature")
txn.TransactionSignatures[sigIndex].Signature = sig[:]
fmt.Println("Done")
}
return nil
}
func signFlowHot(c *walrus.Client, txn *types.Transaction) error {
seed := getSeed()
fmt.Println("Please verify the transaction details:")
for _, sco := range txn.SiacoinOutputs {
fmt.Println(" ", sco.UnlockHash, "receiving", currencyUnits(sco.Value))
}
for _, fee := range txn.MinerFees {
fmt.Println(" A miner fee of", currencyUnits(fee))
}
fmt.Print("Press ENTER to sign this transaction, or Ctrl-C to cancel.")
bufio.NewReader(os.Stdin).ReadLine()
old := len(txn.TransactionSignatures)
err := c.ProtoWallet(seed).SignTransaction(txn, nil)
if err != nil {
return err
} else if old == len(txn.TransactionSignatures) {
fmt.Println("Nothing to sign: transaction does not spend any outputs recognized by this wallet")
return nil
}
return nil
}
<file_sep># walrus-cli
`walrus-cli` is a client for [`walrus`](https://github.com/lukechampine/walrus).
It makes it easy to check your balance, generate addresses, and sign and
broadcast transactions using either a "cold" Ledger Nano S hardware wallet or a
traditional "hot" wallet.
## Setup
You will need a synchronized `walrus` server. You can specify the address of the
server with the `-a` flag.
If you are using a Nano S, the [Sia app](https://github.com/LedgerHQ/nanos-app-sia) must be installed and open when
`walrus-cli` commands are run.
If you want to use `walrus-cli` as a hot wallet, run `walrus-cli seed` to
generate a new seed, and pass the `-hot` flag to all future commands. Each
command will prompt you to enter your seed. You can bypass these prompts by
setting the `WALRUS_SEED` environment variable.
## Generating an Address
Run `walrus-cli addr` to generate a new address and add it to your `walrus`
server. By default, `addr` uses the seed index reported by the server's
`/seedindex` endpoint. You can generate a specific address with `walrus-cli addr [index]`.
## Creating a Transaction
Use the `walrus-cli txn` command to construct a transaction. Transactions are
specified in comma-sparated address:amount pairs. For example, to send 100 SC to
one address and 0.1 SC to another, you would write:
```
$ export DEST_ADDR_1=2ce86e0f5c4b282b51508a798ab8f1091c1cfcc0ee0feaa840e514f37af8dd2f3078fa83f125
$ export DEST_ADDR_2=62e4b26fd772a25029b92b4f06e87202b97bd9a214ff458154bb96e350fda2991b4afb1ff8ed
$ walrus-cli txn $DEST_ADDR_1:100,$DEST_ADDR_2:0.1 txn.json
```
`walrus-cli` will figure out which UTXOs to use, select an appropriate fee, and
send any change back to an address you control. If you are using `walrus-cli`
with a `narwal` server, a donation will also be added: either 1% of the
transaction value, or 10 SC, whichever is greater. The resulting transaction
will be written to disk as JSON.
## Signing a Transaction
Run `walrus-cli sign txn.json` to sign the transaction stored in `txn.json`. The
details of the transaction will appear on your Nano S screen, and you will be
prompted to approve signatures for each input you are spending. Unfortunately,
you must scroll through the transaction details for *each* signature. The signed
transaction will be written to `txn-signed.json`.
## Broadcasting a Transaction
Broadcasting a transaction is as simple as `walrus-cli broadcast txn-signed.json`.
## All Together Now
For convenience, you can merge these three steps (creating, signing,
broadcasting) into one. Just pass the `--sign` and `--broadcast` flags to the
`txn` command (or just `--sign` if you don't want to broadcast immediately). The
transaction will be constructed, signed, and broadcast without ever touching
disk. You can also pass the `--broadcast` flag to the `sign` command for the
same effect.
| f9f1686b3d7278c90eaa82a14c16abaed9c9a803 | [
"Go",
"Go Module",
"Markdown"
] | 3 | Go Module | lukechampine/walrus-cli | 0f2399a1163f695082275b83aff9974385c71739 | b6b3a596810f55ccc29878b6b28cf5adc6546185 |
refs/heads/main | <repo_name>ahnananananana/UIBinding<file_sep>/UIBinding/Scripts/Editor/UIWeaver.cs
๏ปฟusing Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityDebug = UnityEngine.Debug;
using UnityAssembly = UnityEditor.Compilation.Assembly;
namespace HDV.UIBinding
{
/// <summary>
/// Manage Weaving UI binding IL code
/// </summary>
public static class UIWeaver
{
/// <summary>
/// Hook complie event
/// </summary>
[InitializeOnLoadMethod]
public static void OnInitializeOnLoadMethod()
{
CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished;
// We only need to run this once per session
// after that, all assemblies will be weaved by the event
if (!SessionState.GetBool("UIBINDER_WEAVED", false))
{
// reset session flag
SessionState.SetBool("UIBINDER_WEAVED", true);
//Weave first time
foreach (UnityAssembly assembly in CompilationPipeline.GetAssemblies())
{
if (File.Exists(assembly.outputPath))
{
OnCompilationFinished(assembly.outputPath, new CompilerMessage[0]);
}
}
#if UNITY_2019_3_OR_NEWER
EditorUtility.RequestScriptReload();
#else
UnityEditorInternal.InternalEditorUtility.RequestScriptReload();
#endif
}
}
private static ModuleDefinition _mainModule;
static HashSet<string> GetDependecyPaths(string assemblyPath)
{
// build directory list for later asm/symbol resolving using CompilationPipeline refs
HashSet<string> dependencyPaths = new HashSet<string>
{
Path.GetDirectoryName(assemblyPath)
};
foreach (UnityAssembly unityAsm in CompilationPipeline.GetAssemblies())
{
if (unityAsm.outputPath != assemblyPath)
continue;
foreach (string unityAsmRef in unityAsm.compiledAssemblyReferences)
{
dependencyPaths.Add(Path.GetDirectoryName(unityAsmRef));
}
}
return dependencyPaths;
}
/// <summary>
/// Callback when compliation finished
/// <paramref name="assemblyPath"/> Path compiled assembly
/// <paramref name="messages"/> Compliation messages
/// </summary>
public static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages)
{
if (assemblyPath.Contains("-Editor"))
return;
List<Type> derivedTypes = new List<Type>();
List<PropertyDefinition> properties = new List<PropertyDefinition>();
bool isModified = false;
#region Cecil
using (AssemblyDefinition currentAssembly = AssemblyDefinition.ReadAssembly(assemblyPath, new ReaderParameters { ReadWrite = true, ReadSymbols = true/*, AssemblyResolver = asmResolver*/ }))
{
_mainModule = currentAssembly.MainModule;
var p = currentAssembly.MainModule.Types.Where(o => o.IsClass).SelectMany(t => t.Properties);
if (p != null)
properties.AddRange(p);
foreach (PropertyDefinition pd in properties)
{
CustomAttribute attr = pd.CustomAttributes.SingleOrDefault(i => i.AttributeType.Name == nameof(UIBindable));
if (attr != null)
{
Mono.Cecil.Cil.MethodBody body = pd.SetMethod.Body;
ILProcessor processor = body.GetILProcessor();
var instructions = body.Instructions;
var targetInst = instructions.Last();
#region Trying Generic
/*// importing the generic type
var eq = _mainModule.ImportReference(typeof(UIBindProxy<>));
// importing the type of T we want to instantiate the generic type
var t = _mainModule.ImportReference(typeof(float));
var genericEq = new GenericInstanceType(eq);
genericEq.GenericArguments.Add(t);
var importedGenericEq = _mainModule.ImportReference(genericEq);
// getting the method we want to call on the generic instance
var td = SafeResolve(importedGenericEq);
td.DeclaringType = SafeResolve(t);
var defaultMethodDef = td.Methods.Single(m => m.Name == "UpdateValue");
var methodRef = _mainModule.ImportReference(defaultMethodDef);
// Important - setting the method declaring type to the correct instantiated type
methodRef.DeclaringType = importedGenericEq;
processor.InsertBefore(targetInst, processor.Create(OpCodes.Nop));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldarg_0));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldstr, pd.Name));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldarg_1));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Call, methodRef));
isModified = true;
continue;
var td2 = _mainModule.GetType("HDV.UIBindProxy`1");
td2.DeclaringType = SafeResolve(_mainModule.ImportReference(typeof(float)));
//td.DeclaringType
// td = _mainModule.GetType("HDV.UIBindProxyTest");
foreach (var md in td2.Methods)
{
if (md.Name == "UpdateValue")
{
processor.InsertBefore(targetInst, processor.Create(OpCodes.Nop));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldarg_0));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldstr, pd.Name));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldarg_1));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Call, md));
isModified = true;
}
}
continue;*/
#endregion
TypeDefinition td = _mainModule.GetType("HDV.UIBinding.UIBindProxy");
string methodName;
switch (pd.PropertyType.MetadataType)
{
case MetadataType.Single:
{
methodName = "UpdateFloatValue";
break;
}
case MetadataType.Int32:
{
methodName = "UpdateIntValue";
break;
}
//TODO: Need Generic
case MetadataType.String:
case MetadataType.Class:
case MetadataType.Object:
{
methodName = "UpdateObjectValue";
break;
}
default:
{
UnityDebug.LogError("Missing type " + pd.PropertyType.MetadataType);
continue;
}
}
MethodDefinition md = td.Methods.Single(m => m.Name == methodName);
processor.InsertBefore(targetInst, processor.Create(OpCodes.Nop));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldarg_0));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldstr, pd.Name));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Ldarg_1));
processor.InsertBefore(targetInst, processor.Create(OpCodes.Call, md));
isModified = true;
}
}
if (isModified)
{
currentAssembly.Write(new WriterParameters { WriteSymbols = true });
}
}
#endregion
}
private static TypeDefinition SafeResolve(TypeReference typeRef)
{
//could also make a static ExtensionMethod with: this ModuleDefinition module
foreach (TypeDefinition typeDefinition in _mainModule.GetTypes())
{
if (typeDefinition.Namespace == typeRef.Namespace &&
typeDefinition.Name == typeRef.Name)
{
return typeDefinition;
}
}
return typeRef.Resolve();
}
}
}<file_sep>/UIBinding/Demo/TestData.cs
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HDV.UIBinding
{
public class TestData : MonoBehaviour
{
[SerializeField] float _testFloat;
[SerializeField] int _testInt;
[SerializeField] Sprite _testImage;
[UIBindable]
public float TestFloat { get => _testFloat; set => _testFloat = value; }
[UIBindable]
public int TestInt { get => _testInt; set => _testInt = value; }
[UIBindable]
public Sprite TestImage { get => _testImage; set => _testImage = value; }
}
}
<file_sep>/UIBinding/Scripts/SliderBinder.cs
๏ปฟusing System;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
namespace HDV.UIBinding
{
/// <summary>
/// UI binder for Slider component
/// </summary>
[RequireComponent(typeof(Slider))]
public class SliderBinder : UIBinder<Slider>
{
private Action<float> _setFloatFunc;
private Action<int> _setIntFunc;
protected override void Init()
{
UIComponent.onValueChanged.AddListener(OnModifyValue);
object initValue = PropertyInfo.GetValue(Target);
if (initValue is float)
{
_setFloatFunc = (Action<float>)Delegate.CreateDelegate(typeof(Action<float>), Target, PropertyInfo.SetMethod);
UIComponent.value = (float)initValue;
}
else if(initValue is int)
{
_setIntFunc = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), Target, PropertyInfo.SetMethod);
UIComponent.value = (int)initValue;
}
}
protected override void OnChangeValue(float newValue)
{
UIComponent.value = newValue;
}
protected override void OnChangeValue(int newValue)
{
UIComponent.value = newValue;
}
private void OnModifyValue(float newValue)
{
if(_setFloatFunc != null)
{
_setFloatFunc(newValue);
}
else if(_setIntFunc != null)
{
_setIntFunc((int)newValue);
}
}
#if UNITY_EDITOR
public override bool CanBind(Type type)
{
return type == typeof(int) || type == typeof(float);
}
#endif
}
}
<file_sep>/UIBinding/Scripts/CustomAttributes.cs
using System;
namespace HDV.UIBinding
{
[AttributeUsage(AttributeTargets.Property)]
public class UIBindable : Attribute
{
public UIBindable()
{}
}
}<file_sep>/UIBinding/Scripts/UIBinder.cs
๏ปฟusing System;
using System.Reflection;
using UnityEngine;
using Object = UnityEngine.Object;
namespace HDV.UIBinding
{
/// <summary>
/// Base Generic class of all UI component binder.
/// Process binding with UIBindProxy
/// T is type of ui component
/// </summary>
public abstract class UIBinder : MonoBehaviour
{
#if UNITY_EDITOR
public abstract bool CanBind(Type type);
#endif
}
public abstract class UIBinder<T> : UIBinder where T : Component
{
private T _uiComponent;
private Object _target;
private string _key;
private Type _targetType;
private PropertyInfo _propertyInfo;
[SerializeField] MonoBehaviour _monoBehaviourModel;
[SerializeField] ScriptableObject _scriptableObjectModel;
[SerializeField] string _propertyName;
protected Object Target => _target;
protected T UIComponent => _uiComponent;
protected PropertyInfo PropertyInfo => _propertyInfo;
private void Awake()
{
_target = _monoBehaviourModel;
if (!_target)
_target = _scriptableObjectModel;
if(!_target)
{
Debug.LogError(name + " has no target!");
return;
}
if (string.IsNullOrEmpty(_propertyName))
{
Debug.LogError(name + " has no property name!");
return;
}
_targetType = _target.GetType().UnderlyingSystemType;
_propertyInfo = _targetType.GetProperty(_propertyName);
if (_propertyInfo == null)
{
Debug.LogError(_target.name + " has no such property " + _propertyName);
return;
}
_uiComponent = GetComponent<T>();
_key = _target.GetInstanceID().ToString() + '.' + _propertyName;
}
private void OnEnable()
{
if (_propertyInfo == null)
return;
switch (_propertyInfo.PropertyType.Name)
{
//TODO: Need Generic!
case "String":
case "Sprite":
case "Object":
{
UIBindProxy.BindObjectField(_key, OnChangeValue);
break;
}
case "Single":
{
UIBindProxy.BindFloatField(_key, OnChangeValue);
break;
}
case "Int32":
{
UIBindProxy.BindIntField(_key, OnChangeValue);
break;
}
default:
{
Debug.LogWarning("Type Missed " + _targetType.Name);
break;
}
}
Init();
}
protected abstract void Init();
private void OnDisable()
{
if (_propertyInfo == null)
return;
switch (_propertyInfo.PropertyType.Name)
{
//TODO: Need Generic!
case "String":
case "Sprite":
case "Object":
{
UIBindProxy.ReleaseObjectField(_key, OnChangeValue);
break;
}
case "Single":
{
UIBindProxy.ReleaseFloatField(_key, OnChangeValue);
break;
}
case "Int32":
{
UIBindProxy.ReleaseIntField(_key, OnChangeValue);
break;
}
default:
{
Debug.LogWarning("Type Missed " + _targetType.Name);
break;
}
}
}
protected virtual void OnChangeValue(float newValue) => throw new NotImplementedException();
protected virtual void OnChangeValue(int newValue) => throw new NotImplementedException();
protected virtual void OnChangeValue(object newValue) => throw new NotImplementedException();
}
}
<file_sep>/UIBinding/Scripts/Editor/UIBinderEditor.cs
๏ปฟusing System;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Object = UnityEngine.Object;
namespace HDV.UIBinding
{
[CustomEditor(typeof(UIBinder), true)]
public class UIBinderEditor : Editor
{
private SerializedProperty _monoBehaviourModel;
private SerializedProperty _scriptableObjectModel;
private SerializedProperty _propertyName;
private UIBinder _target;
private void OnEnable()
{
_monoBehaviourModel = serializedObject.FindProperty("_monoBehaviourModel");
_scriptableObjectModel = serializedObject.FindProperty("_scriptableObjectModel");
_propertyName = serializedObject.FindProperty("_propertyName");
_target = (UIBinder)target;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
//TODO: Object๋ง ๋ฐ๋ก ๋ฐ๋ ๋ณ์๋ฅผ ๋ง๋ค์ด์ ํ ๋นํด์ฃผ๋ฉด ์์์ ScriptableObject๋ MonoBehaivour๋ก ๋ณํ์ํค๊ฒ ํด์ผ
if (_scriptableObjectModel.objectReferenceValue == null)
{
EditorGUILayout.PropertyField(_monoBehaviourModel);
}
if (_monoBehaviourModel.objectReferenceValue == null)
{
EditorGUILayout.PropertyField(_scriptableObjectModel);
}
Object model = _monoBehaviourModel.objectReferenceValue ? _monoBehaviourModel.objectReferenceValue : _scriptableObjectModel.objectReferenceValue;
if (model)
{
Type modelType = model.GetType();
PropertyInfo[] properties = modelType.GetProperties();
List<string> dropdownList = new List<string>();
foreach (PropertyInfo pi in properties)
{
if (pi.GetCustomAttribute<UIBindable>() != null && _target.CanBind(pi.PropertyType))
dropdownList.Add(pi.Name);
}
GUIContent guiContent = new GUIContent("Property Name");
if (dropdownList.Count > 0)
{
int currentIdx = dropdownList.FindIndex(i => i == _propertyName.stringValue);
currentIdx = currentIdx < 0 ? 0 : currentIdx;
int newIdx = EditorGUILayout.Popup(guiContent, currentIdx, dropdownList.ToArray());
_propertyName.stringValue = dropdownList[newIdx];
}
else
{
EditorGUILayout.Popup(guiContent, 0, dropdownList.ToArray());
_propertyName.stringValue = "";
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
<file_sep>/UIBinding/Scripts/TextBinder.cs
using System;
using System.Reflection;
using UnityEngine;
namespace HDV.UIBinding
{
/// <summary>
/// UI binder for Text component
/// </summary>
[RequireComponent(typeof(TMPro.TMP_Text))]
public class TextBinder : UIBinder<TMPro.TMP_Text>
{
protected override void Init()
{
object initValue = PropertyInfo.GetValue(Target);
UIComponent.text = initValue?.ToString();
}
protected override void OnChangeValue(float newValue)
{
UIComponent.text = newValue.ToString();
}
protected override void OnChangeValue(int newValue)
{
UIComponent.text = newValue.ToString();
}
protected override void OnChangeValue(object newValue)
{
UIComponent.text = newValue.ToString();
}
#if UNITY_EDITOR
public override bool CanBind(Type type)
{
return type == typeof(int) || type == typeof(float) || type == typeof(string);
}
#endif
}
}
<file_sep>/README.md
# What is this?
<h3>Simple data binding to UI component for Unity!
# How to use
<h3>1. Set [UIBindable] on property which want to bind.

<h3>2. Initialize value if you want.

<h3>3. Add UIBinder component to UI.

<h3>4. Ready.

<h3>5. Done.

<file_sep>/UIBinding/Scripts/ImageBinder.cs
๏ปฟusing System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
namespace HDV.UIBinding
{
/// <summary>
/// UI binder for Image component
/// </summary>
[RequireComponent(typeof(Image))]
public class ImageBinder : UIBinder<Image>
{
protected override void Init()
{
UIComponent.sprite = PropertyInfo.GetValue(Target) as Sprite;
}
protected override void OnChangeValue(object newValue)
{
UIComponent.sprite = (Sprite)newValue;
}
#if UNITY_EDITOR
public override bool CanBind(Type type)
{
return type == typeof(Sprite);
}
#endif
}
}
<file_sep>/UIBinding/Scripts/UIBindProxy.cs
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using Object = UnityEngine.Object;
namespace HDV.UIBinding
{
//TODO: Need to be Generic!
[DefaultExecutionOrder(100)]
public static class UIBindProxy
{
/// <summary>
/// For thread safe update
/// </summary>
/// <typeparam name="T">Type of data</typeparam>
struct PendingData<T>
{
public Object OwnedObject;
public string DataName;
public T NewValue;
public PendingData(Object ownedObject, string dataName, T newValue)
{
OwnedObject = ownedObject;
DataName = dataName;
NewValue = newValue;
}
}
private static Queue<PendingData<object>> _objectPending = new Queue<PendingData<object>>();
private static Queue<PendingData<float>> _floatPending = new Queue<PendingData<float>>();
private static Queue<PendingData<int>> _intPending = new Queue<PendingData<int>>();
private static Dictionary<string, Action<float>> _floatDic = new Dictionary<string, Action<float>>();
private static Dictionary<string, Action<int>> _intDic = new Dictionary<string, Action<int>>();
private static Dictionary<string, Action<object>> _objectDic = new Dictionary<string, Action<object>>();
static UIBindProxy()
{
Update();
}
/// <summary>
/// Check is pending data from another thread
/// </summary>
private async static void Update()
{
while (Application.isPlaying)
{
await Task.Yield();
while (_objectPending.Count > 0)
{
var data = _objectPending.Dequeue();
UpdateObjectValue(data.OwnedObject, data.DataName, data.NewValue);
}
while (_floatPending.Count > 0)
{
var data = _floatPending.Dequeue();
UpdateFloatValue(data.OwnedObject, data.DataName, data.NewValue);
}
while (_intPending.Count > 0)
{
var data = _intPending.Dequeue();
UpdateIntValue(data.OwnedObject, data.DataName, data.NewValue);
}
}
}
public static void UpdateFloatValue(Object ownedObject, string dataName, float newValue)
{
if (Thread.CurrentThread.ManagedThreadId != 1)
{
_floatPending.Enqueue(new PendingData<float>(ownedObject, dataName, newValue));
return;
}
if (_floatDic.TryGetValue(ownedObject.GetInstanceID().ToString() + '.' + dataName, out Action<float> del))
{
del?.Invoke(newValue);
}
}
public static void UpdateIntValue(Object ownedObject, string dataName, int newValue)
{
if (Thread.CurrentThread.ManagedThreadId != 1)
{
_intPending.Enqueue(new PendingData<int>(ownedObject, dataName, newValue));
return;
}
if (_intDic.TryGetValue(ownedObject.GetInstanceID().ToString() + '.' + dataName, out Action<int> del))
{
del?.Invoke(newValue);
}
}
public static void UpdateObjectValue(Object ownedObject, string dataName, object newValue)
{
if (Thread.CurrentThread.ManagedThreadId != 1)
{
_objectPending.Enqueue(new PendingData<object>(ownedObject, dataName, newValue));
return;
}
if (_objectDic.TryGetValue(ownedObject.GetInstanceID().ToString() + '.' + dataName, out Action<object> del))
{
del?.Invoke(newValue);
}
}
public static void BindFloatField(string key, Action<float> listener)
{
if(_floatDic.TryGetValue(key, out var del))
{
_floatDic[key] = del + listener;
}
else
{
_floatDic[key] = listener;
}
}
public static void BindIntField(string key, Action<int> listener)
{
if (_intDic.TryGetValue(key, out var del))
{
_intDic[key] = del + listener;
}
else
{
_intDic[key] = listener;
}
}
public static void BindObjectField(string key, Action<object> listener)
{
if (_objectDic.TryGetValue(key, out var del))
{
_objectDic[key] = del + listener;
}
else
{
_objectDic[key] = listener;
}
}
public static void ReleaseFloatField(string key, Action<float> listener)
{
if (_floatDic.TryGetValue(key, out var del))
{
_floatDic[key] = del - listener;
}
}
public static void ReleaseIntField(string key, Action<int> listener)
{
if (_intDic.TryGetValue(key, out var del))
{
_intDic[key] = del - listener;
}
}
public static void ReleaseObjectField(string key, Action<object> listener)
{
if (_objectDic.TryGetValue(key, out var del))
{
_objectDic[key] = del - listener;
}
}
}
}
| 9867e78a461d972b4ee57e3cabd0baf5bfdbe5fd | [
"Markdown",
"C#"
] | 10 | C# | ahnananananana/UIBinding | 2fb3834d854b966dd2d9b2c599b3acd3f57b2e60 | 96984eb9eb645dfc5e6ae0efa02d11a5764a5634 |
refs/heads/master | <file_sep>import os
import re
import csv
import sys
import json
import shutil
import pickle
import numpy as np
import pandas as pd
import tensorflow as tf
from datetime import datetime
from nltk import word_tokenize
from nltk.stem import SnowballStemmer
def stemming(x):
stemmer = SnowballStemmer('spanish')
st=[]
ph=[]
for word in x:
ph.append(stemmer.stem(word))
return ph
def limpieza(s):
#s = re.sub(r"[^A-Za-z0-9:(),!?\'\`]", " ", s)
s = re.sub(r":", " : ", s)
s = re.sub(r"\.", " . ", s)
s = re.sub(r",", " , ", s)
s = re.sub(r"!", " ! ", s)
s = re.sub(r"ยก", " ยก ", s)
s = re.sub(r"\(", " ( ", s)
s = re.sub(r"\)", " ) ", s)
s = re.sub(r"\?", " ? ", s)
s = re.sub(r"ยฟ", " ยฟ ", s)
return s.strip().lower()
def padding(x, default="<DUMMY/>", maximo=None):
if maximo is None:
length = max(len(i) for i in x)
else:
length = maximo
padded_x = []
n_padding = length - len(x)
if n_padding < 0:
padded_phrase = x[0:length]
else:
padded_phrase = x + [default] * n_padding
return padded_phrase
def load_trained_params(trained_dir):
params = json.loads(open(trained_dir + 'trained_parameters.json').read())
Voc_Dict = json.loads(open(trained_dir + 'words_index.json').read())
categorias = json.loads(open(trained_dir + 'labels.json').read())
with open(trained_dir + 'embeddings.pickle', 'rb') as input_file:
fetched_embedding = pickle.load(input_file)
M_embedding = np.array(fetched_embedding, dtype = np.float32)
return params, Voc_Dict, categorias, M_embedding
def load_test_data(data, categorias, params, Voc_Dict):
x = (limpieza(data).split(' '))
x = stemming(x)
x = padding(x, maximo=params['sequence_length'])
x_test = map_word_to_RAE(x, Voc_Dict)
x_test = np.array(x_test)
return x_test
def map_word_to_RAE(x, Voc_Dict):
temp = []
for palabra in x:
if palabra in Voc_Dict:
temp.append(Voc_Dict[palabra])
else:
temp.append(0)
return temp
def STEP(x, params, W_m, b_m, dropout):
with tf.device('/cpu:0'):
with tf.name_scope('emedding_layer'):
W_embed = W_m['embed']
EMBED = tf.nn.embedding_lookup(W_embed, x)
x_emb = tf.expand_dims(EMBED, -1)
LEN=x.shape[1]
filter_sizes = params['filter_sizes'].split(',')
x_conv_pool=[]
for i, filter_size in enumerate(filter_sizes):
name='convolutional_layer' + filter_size
with tf.name_scope(name):
filter_size = int(filter_size)
filter_shape = [filter_size, params['embedding_dim'], 1, params['num_filters']]
W_conv = W_m['convolutional'][i]
b_conv = b_m['convolutional'][i]
convolution = tf.nn.conv2d(x_emb, W_conv, strides=[1, 1, 1, 1], padding='VALID', name='convolution')
relu = tf.nn.relu(tf.add(convolution, b_conv, name='add'), name='activation-relu')
pooled = tf.nn.max_pool(relu, ksize=[1, LEN - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name='pool')
x_conv_pool.append(pooled)
num_filters_total = params['num_filters'] * len(filter_sizes)
x_f = tf.concat(x_conv_pool, 3)
x_f_flat = tf.reshape(x_f, [-1, num_filters_total])
# DROPOUT
with tf.name_scope("dropout"):
x_drop = tf.nn.dropout(x_f_flat, dropout)
for i in range(len(W_m['HL'])):
if i==0:
out = tf.nn.xw_plus_b(x_drop, W_m['HL'][i], b_m['HL'][i], name="layer")
else:
out = tf.nn.xw_plus_b(out, W_m['HL'][i], b_m['HL'][i], name="layer")
if i != len(W_m['HL'])-1:
out = tf.nn.relu(out, name='relu')
with tf.name_scope("output"):
scores = out
scores2 = tf.nn.softmax(scores, name='softmax')
return scores2
def predict():
trained_dir = sys.argv[1]
if not trained_dir.endswith('/'):
trained_dir += '/'
params, Voc_Dict, categorias, embed = load_trained_params(trained_dir)
n_cat = len(categorias)
num_filters_total = params['num_filters'] * len(params['filter_sizes'].split(','))
#Define the W and b:
if params['hidden_units']=="":
W_model = {'embed': [], 'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]}
b_model = {'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]}
else:
W_model = {'embed': [], 'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]*(1+len(params['hidden_units'].split(',')))}
b_model = {'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]*(1+len(params['hidden_units'].split(',')))}
W_model['embed'] = tf.Variable(embed, name='W_embed')
for i, filter_size in enumerate(params['filter_sizes'].split(',')):
filter_shape = [int(filter_size), params['embedding_dim'], 1, params['num_filters']]
W_model['convolutional'][i] = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=('W_conv'))
b_model['convolutional'][i] = tf.Variable(tf.constant(0.1, shape=[params['num_filters']]), name=('b_conv'))
for i, n_neurons in enumerate(params['hidden_units'].split(',')):
if params['hidden_units']=="":
break
n_neurons = int(n_neurons)
if i==0:
pre = len(params['filter_sizes'].split(','))*params['num_filters']
post = n_neurons
else:
pre = int((params['hidden_units'].split(','))[i-1])
post = n_neurons
W_model['HL'][i] = tf.Variable(tf.truncated_normal([pre, post], stddev=0.1), name="W_HL")
b_model['HL'][i] = tf.Variable(tf.constant(0.1, shape=[post]), name="b_HL")
if params['hidden_units']=="":
pre = len(params['filter_sizes'].split(','))*params['num_filters']
else:
pre = int((params['hidden_units'].split(','))[-1])
post = n_cat
W_model['HL'][-1] = tf.Variable(tf.truncated_normal([pre, post], stddev=0.1), name="W_HL")
b_model['HL'][-1] = tf.Variable(tf.constant(0.1, shape=[post]), name="b_HL")
print('W_model:\n', W_model)
print('b_model:\n', b_model)
X_feed = tf.placeholder(tf.int32, [None, int(params['sequence_length'])], name="X_feed")
dropout = tf.placeholder(tf.float32, [], name='dropout')
scores = STEP(X_feed, params, W_model, b_model, dropout)
with tf.Session() as sess:
model = trained_dir + 'model.ckpt'
saver = tf.train.Saver(tf.all_variables())
saver = tf.train.import_meta_graph("{}.meta".format(model))
saver.restore(sess, model)
print("\n\nModelo cargado satisfactoriamente\n")
finish=False
while(finish==False):
query = input('Dime tu consulta:\n')
x = load_test_data(query, categorias, params, Voc_Dict)
x = np.reshape(x, (1, params['sequence_length']))
#Placeholders for data
feed_dict = {X_feed: x, dropout: 1}
scores_batch = sess.run(scores, feed_dict)
positions = np.argsort(scores_batch, axis=1)
answer1 = positions[:,-1]
answer2 = positions[:,-2]
answer3 = positions[:,-3]
print('Respuesta 1:', categorias[int(answer1)], '(', scores_batch[0][int(answer1)], ')')
print('Respuesta 2:', categorias[int(answer2)], '(', scores_batch[0][int(answer2)], ')')
print('Respuesta 3:', categorias[int(answer3)], '(', scores_batch[0][int(answer3)], ')')
a = input('ยฟEso es todo? (S/N)\n')
if(a=='S' or a=='s' or a=='si' or a=='SI' or a=='Si'):
finish = True
print('\n')
elif(a=='N' or a=='n' or a=='no' or a=='NO' or a=='No'):
finish = False
print('\n')
else:
print('No he entendido la resupuesta, vuelvo al bucle...\n')
if __name__ == '__main__':
predict()
<file_sep># Clasificador
Clasificador de texto en deep learning
Para entrenar el modelo basta con bajar los scripts ejecutar el siguiente comando:
python train.py ./trained_model
Cuando termine el entrenamiento, en la carpeta trained_model se habrรฑa guardado el modelo. Para comprobar su performane, se ejcuta el siguiente comando:
python resultados.py ./trained_model
<file_sep>import os
import csv
import sys
import json
import shutil
import pickle
import numpy as np
import pandas as pd
from Step import STEP
import tensorflow as tf
from datetime import datetime
from sklearn.metrics import roc_curve, auc
from Auxiliar import limpieza, stemming, PAD_SENTENCES, batch_iter
def load_trained_params(trained_dir):
params = json.loads(open(trained_dir + 'trained_parameters.json').read())
Voc_Dict = json.loads(open(trained_dir + 'words_index.json').read())
categorias = json.loads(open(trained_dir + 'labels.json').read())
with open(trained_dir + 'embeddings.pickle', 'rb') as input_file:
fetched_embedding = pickle.load(input_file)
M_embedding = np.array(fetched_embedding, dtype = np.float32)
return params, Voc_Dict, categorias, M_embedding
def load_test_data(file, categorias, params, Voc_Dict):
data=pd.read_csv(file,header=None, usecols=[0,1]) #0:x, 1:y
num_cat = len(categorias)
one_hot = np.zeros((num_cat, num_cat), int)
np.fill_diagonal(one_hot, 1)
cat_dict = dict(zip(categorias, one_hot))
y = data[1].apply(lambda y: cat_dict[y]).tolist()
y_test = np.array(y)
A=categorias
B=list(set(data[1]))
A.sort()
B.sort()
if(A==B):
print("\n**Test categories succefully loaded\n\n")
else:
print("\n**Test categories succefully loaded, though in", file, "there are only", len(list(set(data[1]))),"out of", len(categorias), "categories\n\n")
x = data[0].apply(lambda x: limpieza(x).split(' ')).tolist()
x = stemming(x, params['stemming'])
x = PAD_SENTENCES(x, max_len=params['sequence_length'])
x_test = map_word_to_RAE(x, Voc_Dict)
x_test = np.array(x_test)
return x_test, y_test
def map_word_to_RAE(x, Voc_Dict):
x_ = []
for frase in x:
temp = []
for palabra in frase:
if palabra in Voc_Dict:
temp.append(Voc_Dict[palabra])
else:
temp.append(0)
x_.append(temp)
return x_
def predict_unseen_data():
trained_dir = sys.argv[1]
if not trained_dir.endswith('/'):
trained_dir += '/'
test_file = 'Test.csv'
params, Voc_Dict, categorias, embed = load_trained_params(trained_dir)
test_file = params['test file']
x, y = load_test_data(test_file, categorias, params, Voc_Dict)
n_cat = len(categorias)
num_filters_total = params['num_filters'] * len(params['filter_sizes'].split(','))
#Define the W and b:
if params['hidden_units']=="":
W_model = {'embed': [], 'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]}
b_model = {'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]}
else:
W_model = {'embed': [], 'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]*(1+len(params['hidden_units'].split(',')))}
b_model = {'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]*(1+len(params['hidden_units'].split(',')))}
W_model['embed'] = tf.Variable(embed, name='W_embed')
for i, filter_size in enumerate(params['filter_sizes'].split(',')):
filter_shape = [int(filter_size), params['embedding_dim'], 1, params['num_filters']]
W_model['convolutional'][i] = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=('W_conv'))
b_model['convolutional'][i] = tf.Variable(tf.constant(0.1, shape=[params['num_filters']]), name=('b_conv'))
for i, n_neurons in enumerate(params['hidden_units'].split(',')):
if params['hidden_units']=="":
break
n_neurons = int(n_neurons)
if i==0:
pre = len(params['filter_sizes'].split(','))*params['num_filters']
post = n_neurons
else:
pre = int((params['hidden_units'].split(','))[i-1])
post = n_neurons
W_model['HL'][i] = tf.Variable(tf.truncated_normal([pre, post], stddev=0.1), name="W_HL")
b_model['HL'][i] = tf.Variable(tf.constant(0.1, shape=[post]), name="b_HL")
if params['hidden_units']=="":
pre = len(params['filter_sizes'].split(','))*params['num_filters']
else:
pre = int((params['hidden_units'].split(','))[-1])
post = n_cat
W_model['HL'][-1] = tf.Variable(tf.truncated_normal([pre, post], stddev=0.1), name="W_HL")
b_model['HL'][-1] = tf.Variable(tf.constant(0.1, shape=[post]), name="b_HL")
print('W_model:\n', W_model)
print('b_model:\n', b_model)
X_feed = tf.placeholder(tf.int32, [None, int(x.shape[1])], name="X_feed")
Y_feed = tf.placeholder(tf.int32, [None, y.shape[1]], name="Y_feed")
dropout = tf.placeholder(tf.float32, [], name='dropout')
loss, acc, scores = STEP(X_feed, Y_feed, params, W_model, b_model, dropout)
with tf.Session() as sess:
model = trained_dir + 'model.ckpt'
saver = tf.train.Saver(tf.all_variables())
saver = tf.train.import_meta_graph("{}.meta".format(model))
saver.restore(sess, model)
print("\n\nModelo cargado satisfactoriamente\n")
batches = batch_iter(list(zip(x, y)), params['batch_size'], 1, random=False)
accuracy1=[]
accuracy2=[]
accuracy3=[]
save_guess=[]
save_true=[]
created = 0
for batch in batches:
x_batch, y_batch = zip(*batch)
x_batch = np.array(x_batch)
y_batch = np.array(y_batch)
#Placeholders for data
feed_dict = {X_feed: x_batch, Y_feed: y_batch, dropout: 1}
scores_batch = sess.run(scores, feed_dict)
if created == 0:
tot_scores = scores_batch
created = 1
else:
tot_scores = np.concatenate((tot_scores, scores_batch), axis=0)
positions = np.argsort(scores_batch, axis=1)
true = np.argmax(y_batch, axis=1)
answer1 = positions[:,-1]
answer2 = positions[:,-2]
answer3 = positions[:,-3]
for i in range(len(answer1)):
save_true.append(categorias[true[i]])
save_guess.append(categorias[answer1[i]])
if(answer1[i]==true[i]):
accuracy1.append(1)
else:
accuracy1.append(0)
if(answer2[i]==true[i]):
accuracy2.append(1)
else:
accuracy2.append(0)
if(answer3[i]==true[i]):
accuracy3.append(1)
else:
accuracy3.append(0)
a1 = round(sum(accuracy1)/len(accuracy1),4)
a2 = round(sum(accuracy2)/len(accuracy2),4)
a3 = round(sum(accuracy3)/len(accuracy3),4)
print("% of accuracy in the three first options:", round(a1+a2+a3,4), '(', a1, '+', a2, '+', a3, ')')
df_train = pd.DataFrame({'Prediction': save_guess,'Real':save_true})
df_train.to_csv(trained_dir+'OUTPUT.txt', sep=',')
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(tot_scores.shape[1]):
fpr[categorias[i]], tpr[categorias[i]], _ = roc_curve(y[:, i], tot_scores[:, i])
roc_auc[categorias[i]] = auc(fpr[categorias[i]], tpr[categorias[i]])
with open(trained_dir + 'AUCROC.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in roc_auc.items():
writer.writerow([key, value])
if __name__ == '__main__':
predict_unseen_data()
<file_sep>import pandas as pd
import numpy as np
import re
from collections import Counter
import itertools
import json
from sklearn.model_selection import train_test_split
import os
import shutil
import tensorflow as tf
from datetime import datetime
import sys
def STEP(x, y, params, W_m, b_m, dropout):
#EMBEDDING LAYER
#--> IN: (RAE, embedding_dim)
#--> OUT: (batch_size, length_phrase, embedding_dim, 1)
with tf.name_scope('emedding_layer'):
W_embed = W_m['embed']
EMBED = tf.nn.embedding_lookup(W_embed, x)
x_emb = tf.expand_dims(EMBED, -1)
#CONVOLUTIONAL LAYER + POOLING
#--> IN: (batch_size, length_phrase, embedding_dim, 1)
#--> OUT: (batch_size, 1, 1, channels)
LEN=x.shape[1]
filter_sizes = params['filter_sizes'].split(',')
x_conv_pool=[]
for i, filter_size in enumerate(filter_sizes):
name='convolutional_layer' + filter_size
with tf.name_scope(name):
filter_size = int(filter_size)
filter_shape = [filter_size, params['embedding_dim'], 1, params['num_filters']]
W_conv = W_m['convolutional'][i]
b_conv = b_m['convolutional'][i]
convolution = tf.nn.conv2d(x_emb, W_conv, strides=[1, 1, 1, 1], padding='VALID', name='convolution')
relu = tf.nn.relu(tf.add(convolution, b_conv, name='add'), name='activation-relu')
pooled = tf.nn.max_pool(relu, ksize=[1, LEN - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name='pool')
x_conv_pool.append(pooled)
num_filters_total = params['num_filters'] * len(filter_sizes)
x_f = tf.concat(x_conv_pool, 3)
x_f_flat = tf.reshape(x_f, [-1, num_filters_total])
# DROPOUT
with tf.name_scope("dropout"):
x_drop = tf.nn.dropout(x_f_flat, dropout)
for i in range(len(W_m['HL'])):
if i==0:
out = tf.nn.xw_plus_b(x_drop, W_m['HL'][i], b_m['HL'][i], name="layer")
else:
out = tf.nn.xw_plus_b(out, W_m['HL'][i], b_m['HL'][i], name="layer")
if i != len(W_m['HL'])-1:
out = tf.nn.relu(out, name='relu')
n_cat = int(y.shape[1])
with tf.name_scope("output"):
scores = out
scores2 = tf.nn.softmax(scores, name='softmax')
predictions = tf.argmax(scores, 1, name="predictions")
# Mean cross-entropy loss
with tf.name_scope("loss"):
losses = tf.nn.softmax_cross_entropy_with_logits(logits=scores, labels=y)
loss = tf.reduce_mean(losses)
# Accuracy
with tf.name_scope("accuracy"):
correct_predictions = tf.equal(predictions, tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
return loss, accuracy, scores2<file_sep># # LOADING DATA
import sys
import pandas as pd
import numpy as np
import re
from collections import Counter
import itertools
import json
from sklearn.model_selection import train_test_split
import os
import shutil
from datetime import datetime
from nltk import word_tokenize
from nltk.stem import SnowballStemmer
# In[2]:
def stemming(x, stem_value):
stemmer = SnowballStemmer('spanish')
st=[]
for phrase in x:
ph=[]
for word in phrase:
if stem_value == 1:
ph.append(stemmer.stem(word))
elif stem_value == 2:
ph.append(stemmer.stem(stemmer.stem(word)))
elif stem_value == 0:
ph.append(word)
else:
print("\n\nERROR: Invalid stemming value, please change it to either 0, 1 or 2\n\n\n")
sys.exit()
st.append(ph)
return st
def limpieza(s):
s = re.sub(r":", " : ", s)
s = re.sub(r"\.", " . ", s)
s = re.sub(r",", " , ", s)
s = re.sub(r"!", " ! ", s)
s = re.sub(r"ยก", " ยก ", s)
s = re.sub(r"\(", " ( ", s)
s = re.sub(r"\)", " ) ", s)
s = re.sub(r"\?", " ? ", s)
s = re.sub(r"ยฟ", " ยฟ ", s)
s = re.sub(r"/", " / ", s)
return s.strip().lower()
def PAD_SENTENCES(x, default="<FAKE>", max_len=None):
if max_len is None:
length = max(len(i) for i in x)
else:
length = max_len
x_padded = []
for phrase in x:
n_paddings = length - len(phrase)
if n_paddings < 0:
phrase_padded = phrase[0:length]
else:
phrase_padded = phrase + [default]*n_paddings
x_padded.append(phrase_padded)
return x_padded
def RAE(x):
wc = Counter(itertools.chain(*x))
vocabulary_sorted = [word[0] for word in wc.most_common()]
vocabulary_dict = {word: index for index, word in enumerate(vocabulary_sorted)}
return vocabulary_dict
def Read_Data(file, stem_value):
data=pd.read_csv(file,header=None, usecols=[0,1], delimiter=';', encoding='utf-8')
data = data.drop(data[data[1] == 'liniaObertaWSLOE'].index)
#Y
categorias = sorted(list(set(data[1].tolist())))
num_cat = len(categorias)
one_hot = np.zeros((num_cat, num_cat), int)
np.fill_diagonal(one_hot, 1)
cat_dict = dict(zip(categorias, one_hot))
y = data[1].apply(lambda y: cat_dict[y]).tolist()
y_train = np.array(y)
print("\n\n------------------------------------------------------")
print("------------------DEBUG Categories-------------------")
print("------------------------------------------------------\n\n")
for i,j in enumerate(np.array(y).sum(axis=0)):
print('----->In', categorias[i], 'there are', j, 'entries')
print("\n**",len(categorias) , "Categories succefully loaded\n\n")
#X
print("\n\n------------------------------------------------------")
print("-------------------DEBUG Variations-------------------")
print("------------------------------------------------------\n\n")
x = data[0].apply(lambda x: limpieza(x).split(' ')).tolist()
x = stemming(x, stem_value)
x = PAD_SENTENCES(x)
vocabulario_dict = RAE(x)
x_train = np.array([[vocabulario_dict[word] for word in variacion] for variacion in x])
print("\n**Variations succefully loaded\n\n")
return x_train, y_train, vocabulario_dict, categorias
def Ini_embeddings(voc):
embeds={}
i=0
for word in voc:
embeds[word] = np.random.uniform(-0.25, 0.25, 300)
return embeds
def batch_iter(data, batch_size, epochs, random=True, cv=False):
data = np.array(data)
batches_epoch = int(len(data)/ batch_size) + 1
for epoch in range(epochs):
if random:
indices = np.random.permutation(np.arange(len(data)))
data_f = data[indices]
else:
data_f = data
for i in range(batches_epoch):
complete=100*i/batches_epoch
if(cv==False):
print("รpoca", epoch, ':', round(complete, 2), '% completado.', i, '/', batches_epoch, 'pasos')
start = i*batch_size
end = min((i+1)*batch_size, len(data))
if(start!=end):
yield data_f[start:end]<file_sep>import re
import os
import sys
import json
import copy
import shutil
import pickle
import itertools
import numpy as np
import pandas as pd
import tensorflow as tf
from Step import STEP
from datetime import datetime
from collections import Counter
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from Auxiliar import limpieza, PAD_SENTENCES, RAE, Read_Data, Ini_embeddings, batch_iter, stemming
def map_word_to_RAE(x, Voc_Dict):
x_ = []
for frase in x:
temp = []
for palabra in frase:
if palabra in Voc_Dict:
temp.append(Voc_Dict[palabra])
else:
temp.append(0)
x_.append(temp)
return x_
def load_test_data(file, categorias, params, Voc_Dict, seq_len):
data=pd.read_csv(file,header=None, usecols=[0,1], delimiter=';', encoding='utf-8')
data = data.drop(data[data[1] == 'liniaObertaWSLOE'].index)
num_cat = len(categorias)
one_hot = np.zeros((num_cat, num_cat), int)
np.fill_diagonal(one_hot, 1)
cat_dict = dict(zip(categorias, one_hot))
y = data[1].apply(lambda y: cat_dict[y]).tolist()
y_test = np.array(y)
A=categorias
B=list(set(data[1]))
A.sort()
B.sort()
if(A==B):
print("\n**Test categories succefully loaded\n\n")
else:
print("\n**Test categories succefully loaded, though in", file, "there are only", len(list(set(data[1]))),"out of", len(categorias), "categories\n\n")
x = data[0].apply(lambda x: limpieza(x).split(' ')).tolist()
x = stemming(x, params['stemming'])
x = PAD_SENTENCES(x, max_len=seq_len)
x_test = map_word_to_RAE(x, Voc_Dict)
x_test = np.array(x_test)
print("\n**Test variations succefully loaded\n\n")
return x_test, y_test
def train(config):
best_acc= 0
ACCURACY_CV = []
ACCURACY_TRAIN = []
LOSS_CV = []
LOSS_TRAIN = []
params = json.loads(open(config).read())
train_file = params["training file"]
test_file = params["test file"]
X_0, Y_0, Voc_Dict, Categorias =Read_Data(train_file, params['stemming'])
embeddings= Ini_embeddings(Voc_Dict)
M_embeddings = [embeddings[word] for index, word in enumerate(Voc_Dict)]
M_embeddings = np.array(M_embeddings, dtype = np.float32)
x_test, y_test = load_test_data(test_file, Categorias, params, Voc_Dict, X_0.shape[1])
X_0, x_test, Y_0, y_test = train_test_split(X_0, Y_0, test_size=0.1)
_, x_train_v, _, y_train_v = train_test_split(X_0, Y_0, test_size=params['train_val'])
x_train = X_0
y_train = Y_0
print("\n\n------------------------------------------------------")
print("Training with", len(x_train), "phrases,", len(x_test), "phrases in the test,", len(x_train_v), "phrases are in the training validation")
print("------------------------------------------------------\n\n")
try:
trained_dir = sys.argv[1]
if not trained_dir.endswith('/'):
trained_dir += '/'
except:
now=datetime.now()
trained_dir = './entrenamiento_' + str(now.day)+'-'+str(now.month)+'-'+str(now.year) + '/'
if os.path.exists(trained_dir):
shutil.rmtree(trained_dir)
os.makedirs(trained_dir)
n_cat = Y_0.shape[1]
num_filters_total = params['num_filters'] * len(params['filter_sizes'].split(','))
#Define the W and b:
if params['hidden_units']=="":
W_model = {'embed': [], 'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]}
b_model = {'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]}
else:
W_model = {'embed': [], 'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]*(1+len(params['hidden_units'].split(',')))}
b_model = {'convolutional': [0]*len(params['filter_sizes'].split(',')), 'HL': [0]*(1+len(params['hidden_units'].split(',')))}
W_model['embed'] = tf.Variable(M_embeddings, name='W_embed')
for i, filter_size in enumerate(params['filter_sizes'].split(',')):
filter_shape = [int(filter_size), params['embedding_dim'], 1, params['num_filters']]
W_model['convolutional'][i] = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=('W_conv'))
b_model['convolutional'][i] = tf.Variable(tf.constant(0.1, shape=[params['num_filters']]), name=('b_conv'))
for i, n_neurons in enumerate(params['hidden_units'].split(',')):
if params['hidden_units']=="":
break
n_neurons = int(n_neurons)
if i==0:
pre = len(params['filter_sizes'].split(','))*params['num_filters']
post = n_neurons
else:
pre = int((params['hidden_units'].split(','))[i-1])
post = n_neurons
W_model['HL'][i] = tf.Variable(tf.truncated_normal([pre, post], stddev=0.1), name="W_HL")
b_model['HL'][i] = tf.Variable(tf.constant(0.1, shape=[post]), name="b_HL")
if params['hidden_units']=="":
pre = len(params['filter_sizes'].split(','))*params['num_filters']
else:
pre = int((params['hidden_units'].split(','))[-1])
post = n_cat
W_model['HL'][-1] = tf.Variable(tf.truncated_normal([pre, post], stddev=0.1), name="W_HL")
b_model['HL'][-1] = tf.Variable(tf.constant(0.1, shape=[post]), name="b_HL")
print('W_model:\n', W_model)
print('b_model:\n', b_model)
X_feed = tf.placeholder(tf.int32, [None, int(X_0.shape[1])], name="X_feed")
Y_feed = tf.placeholder(tf.int32, [None, Y_0.shape[1]], name="Y_feed")
dropout = tf.placeholder(tf.float32, [], name='dropout')
loss, acc, _ = STEP(X_feed, Y_feed, params, W_model, b_model, dropout)
optimizer=tf.train.AdamOptimizer(0.001)
train_op = optimizer.minimize(loss)
saver=tf.train.Saver()
start = tf.global_variables_initializer()
st = [0]
with tf.Session() as sess:
sess.run(start)
#Loop in training batches
batches = batch_iter(list(zip(x_train, y_train)), params['batch_size'], params['num_epochs'])
for i, batch in enumerate(batches):
#Load batch
x_train_batch, y_train_batch = zip(*batch)
x_train_batch = np.array(x_train_batch)
y_train_batch = np.array(y_train_batch)
#Dicts for placeholders
feed_dict = {X_feed: x_train_batch, Y_feed: y_train_batch, dropout: params['dropout_keep_prob']}
#Optimizer
sess.run(train_op, feed_dict)
if(i%10==0):
print('\n---------------------------------------------------')
print('-----------------------DEBUG-----------------------')
print('---------------------------------------------------')
batches_test = batch_iter(list(zip(x_test, y_test)), params['batch_size'], 1, cv=True)
L_cv=0
A_cv=0
for j, batch_test in enumerate(batches_test):
x_cv_batch, y_cv_batch = zip(*batch_test)
x_cv_batch = np.array(x_cv_batch)
y_cv_batch = np.array(y_cv_batch)
feed_dict = {X_feed: x_cv_batch, Y_feed: y_cv_batch, dropout: 1}
L_iter, A_iter = sess.run([loss,acc], feed_dict)
L_cv += L_iter
A_cv += A_iter*x_cv_batch.shape[0]
A_cv = A_cv/x_test.shape[0]
print("Loss (CV):", L_cv)
print("Accuracy (CV):", A_cv)
ACCURACY_CV.append(A_cv)
LOSS_CV.append(L_cv)
if best_acc<A_cv:
best_acc = A_cv
best_W_dict = dict(W_model)
best_b_dict = dict(b_model)
batches_tr = batch_iter(list(zip(x_train_v, y_train_v)), params['batch_size'], 1, cv=True)
L_cv=0
A_cv=0
for j, batch_test in enumerate(batches_tr):
x_cv_batch, y_cv_batch = zip(*batch_test)
x_cv_batch = np.array(x_cv_batch)
y_cv_batch = np.array(y_cv_batch)
feed_dict = {X_feed: x_cv_batch, Y_feed: y_cv_batch, dropout: 1}
L_iter, A_iter = sess.run([loss,acc], feed_dict)
L_cv += L_iter
A_cv += A_iter*x_cv_batch.shape[0]
A_cv = A_cv/x_train_v.shape[0]
print("Loss (train):", L_cv)
print("Accuracy (train):", A_cv)
print('\n---------------------------------------------------')
print('---------------------------------------------------')
print('---------------------------------------------------')
ACCURACY_TRAIN.append(A_cv)
LOSS_TRAIN.append(L_cv)
st.append(st[-1]+1)
W_model = best_W_dict
b_model = best_b_dict
print('Best model had a validation accuracy of', best_acc,'\n\n')
print("\n-->Entrenamiento completado\n\n")
# Save the model files to trained_dir. predict.py needs trained model files.
saver.save(sess, trained_dir + "model.ckpt")
# Save trained parameters and files since predict.py needs them
with open(trained_dir + 'words_index.json', 'w') as outfile:
json.dump(Voc_Dict, outfile, indent=4, ensure_ascii=False)
with open(trained_dir + 'embeddings.pickle', 'wb') as outfile:
pickle.dump(M_embeddings, outfile, pickle.HIGHEST_PROTOCOL)
with open(trained_dir + 'labels.json', 'w') as outfile:
json.dump(Categorias, outfile, indent=4, ensure_ascii=False)
params['sequence_length'] = x_train.shape[1]
params['validation_accuracy'] = best_acc
with open(trained_dir + 'trained_parameters.json', 'w') as outfile:
json.dump(params, outfile, indent=4, sort_keys=True, ensure_ascii=False)
print("Modelo guardado en:", trained_dir)
del st[-1]
st = [x*params['num_epochs']/len(st) for x in st]
plt.figure(1)
plt.subplot(211)
plt.plot(st, ACCURACY_CV, 'r-', st, ACCURACY_TRAIN, 'g-')
plt.xlabel('Step')
plt.ylabel('Accuracy')
plt.title('Accuracy of the model')
plt.legend(('CV', 'Trainning'), loc='upper center', shadow=True)
plt.subplot(212)
plt.plot(st, LOSS_CV, 'r-', st, LOSS_TRAIN, 'g-')
plt.xlabel('Step')
plt.ylabel('Loss')
plt.title('Loss function of the model')
plt.legend(('CV', 'Trainning'), loc='upper center', shadow=True)
plt.show()
df_train = pd.DataFrame({
'Step': st,
'Loss':LOSS_TRAIN,
'Accuracy': ACCURACY_TRAIN
})
df_Test = pd.DataFrame({
'Step': st,
'Loss':LOSS_CV,
'Accuracy': ACCURACY_CV
})
df_train.to_csv(trained_dir+'Trainning.txt', sep='\t')
df_Test.to_csv(trained_dir+'Test.txt', sep='\t')
if __name__ == '__main__':
config="config.json"
train(config)
| 183947c8f43d97be87a7fc2fbd54e58334889a3c | [
"Markdown",
"Python"
] | 6 | Python | jorgepardillos/Clasificador | f7389842be55b9c4d6d40c0d35dada5927638b91 | d620e42fb27f22e230362a5c255fc3ff0347e3b9 |
refs/heads/master | <repo_name>ThorMortensen/temp<file_sep>/Common/stdInfoStrings.h
/*
* File: stdInfoStrings.h
* Author: Thor
*
* Created on March 8, 2015, 2:45 PM
*/
#ifndef STDINFOSTRINGS_H
#define STDINFOSTRINGS_H
//temp -band<X1,X2,ka1> -pol<co,cx> -board<TXIF,RXIF,wg,stalo,psu> -no<1,2,3,4,5,6,7,8,9,10,11,12> --help
const std::string LINK_REFREANCE = "See more at https://docs.google.com/document/d/1BIUsQmMrP50b__kpr-6PevbMRh-TXEwn2vmGn1KDKGg/edit?usp=sharing\n\r";
const std::string USAGE_TEMP = "Usage: No arguments.\n\r" + LINK_REFREANCE;
const std::string USAGE_SETGAIN = "Usage: <number> or (<number> <tx1,tx2,tx3,tx4>) \n\r" + LINK_REFREANCE;
std::string USAGE_STATUS = "Usage: -band <X1,X2,ka1> "
"-pol <co,cx> "
"-board <TXIF,RXIF,wg,stalo,psu> "
"-no <1,2,3,4,5,6,7,8,9,10,11,12> "
"--help \n"
" All case sensitive";
std::string USAGE_WRITEMEM = "Usage: -band <X1,X2,ka1> "
"-pol <co,cx> "
"-board <TXIF,RXIF,wg,stalo,psu> "
"-no <1,2,3,4,5,6,7,8,9,10,11,12> "
"-chain <1,2,3,4>"
"-block <1 to 12>"
"--help \n"
" All case sensitive";
#endif /* STDINFOSTRINGS_H */
<file_sep>/Common/TxifErrors.h
/*
* File: TxifErrors.h
* Author: Thor
*
* Created on 5. maj 2015, 11:19
*/
#ifndef TXIFERRORS_H
#define TXIFERRORS_H
std::string WRONG_PARA_AMOUNT_ERR50 = "ERR50 Wrong number of parameters. Use -help to see usage\n\r";
std::string SPIERROR1_ERR1 = "ERR1 SPI Temp Setup failed\n\r";
#endif /* TXIFERRORS_H */
| 7a64771002485602e3980835d1cf28345f5d54cb | [
"C++"
] | 2 | C++ | ThorMortensen/temp | 637aecb55ceb6b23379b986626c92b66eb54a1cf | 7a41c0a91e382277aa9c2173b1dcfca5eb1b3aba |
refs/heads/master | <repo_name>azmicolejr/ci_ionauth<file_sep>/application/views/auth/create_user.php
<?php $this->load->view('head'); ?>
<?php $this->load->view('header'); ?>
<?php $this->load->view('leftbar'); ?>
<div class="content-wrapper">
<section class="content-header">
<h1><?php echo $title ?></h1>
<ol class="breadcrumb">
<li><a href="<?php echo base_url('dashboard') ?>"><i class="fa fa-dashboard"></i> Home</a></li>
<li>Cuci</li>
<li class="active"><a href="<?php echo current_url() ?>"><?php echo $title ?></a></li>
</ol>
</section>
<section class='content'>
<div class='row'>
<div id="infoMessage"></div>
<?php echo form_open("auth/create_user");?>
<!-- left column -->
<div class="col-md-6">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-body">
<?php echo $message;?>
<div class="row">
<div class="col-xs-6"><label>Nama</label>
<?php echo form_input($nama);?>
</div>
<div class="col-xs-6"><label>Username</label>
<?php echo form_input($username);?>
</div>
</div><br>
<div class="row">
<div class="col-xs-6"><label>Email</label>
<?php echo form_input($email);?>
</div>
<div class="col-xs-6"><label>No. HP</label>
<?php echo form_input($phone);?>
</div>
</div><br>
<div class="form-group"><label>Alamat</label>
<?php echo form_textarea($alamat);?>
</div>
<div class="form-group"><label>Tipe user</label>
<?php echo form_dropdown('usertype', $get_all_users_group, '', $usertype_css); ?>
</div>
<div class="row">
<div class="col-xs-6"><label>Password</label>
<?php echo form_input($password);?>
</div>
<div class="col-xs-6"><label>Konfirmasi Password</label>
<?php echo form_input($password_confirm);?>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submit" class="btn btn-success">Submit</button>
<button type="reset" name="reset" class="btn btn-danger">Reset</button>
</div>
</div><!-- /.box -->
<!-- left column -->
</div>
<?php echo form_close(); ?>
</div>
</section>
</div>
<?php $this->load->view('footer'); ?>
<file_sep>/assets/fungsi/cek_aksi_ubah.php
<?php
include 'cek_session.php';
if($sesen_access == 0)
{
echo "<script>alert('Anda tidak memiliki hak akses apapun, silahkan hubungi Admin!'); location.replace('../index.php')</script>";
session_destroy();
}
if($sesen_access == 1)
{
echo "<script>alert('Anda hanya bisa baca file!'); location.replace('../index.php')</script>";
session_destroy();
}
?><file_sep>/application/views/auth/login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $title ?></title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<!-- Bootstrap 3.3.4 -->
<link href="<?php echo base_url()?>assets/template/backend/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- Theme style -->
<link href="<?php echo base_url()?>assets/template/backend/dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />
<!-- Favicon -->
<link rel="shortcut icon" href="<?php echo base_url() ?>images/fav.ico" />
</head>
<body class="login-page">
<div class="login-box">
<div align="center">
<h1 class="teks"><b>LOGIN</b></h1>
</div><!-- /.login-logo -->
<div class="login-box-body">
<div id="infoMessage"><?php echo $message;?></div>
<?php echo form_open("auth/login");?>
<div class="form-group has-feedback">
<?php echo form_input(array('name' => 'username', 'value' => set_value('username'), 'class' => 'form-control')); ?>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<?php echo form_password(array('name' => '<PASSWORD>', 'value' => set_value('<PASSWORD>'), 'class' => 'form-control')); ?>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<?php echo lang('login_remember_label', 'remember');?>
<?php echo form_checkbox('remember', '1', FALSE, 'id="remember"');?>
<p><a href="forgot_password"><?php echo lang('login_forgot_password');?></a></p>
<div class="row">
<div class="col-xs-4">
<button type="submit" name="submit" class="btn btn-primary btn-block btn-flat">Login</button>
</div><!-- /.col -->
</div>
<?php echo form_close();?>
</div><!-- /.login-box-body -->
</div><!-- /.login-box -->
<!-- jQuery 2.1.4 -->
<script src="<?php echo base_url()?>assets/template/backend/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.2 JS -->
<script src="<?php echo base_url()?>assets/template/backend/css/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!-- iCheck -->
<script src="<?php echo base_url()?>assets/template/backend/plugins/iCheck/icheck.min.js" type="text/javascript"></script>
</body>
</html><file_sep>/application/views/v_dashboard.php
<?php $this->load->view('head'); ?>
<?php $this->load->view('header'); ?>
<?php $this->load->view('leftbar'); ?>
<div class="content-wrapper">
<div class="box-body">
<div class="callout callout-success "><i class='fa fa-bullhorn'></i>
Selamat Datang <b> <?php echo $this->session->userdata('nama') ?>
</div>
</div>
<section class='content'>
<div class='row'>
<!-- -->
</div>
</section>
</div>
<?php $this->load->view('footer'); ?> <file_sep>/readme.rst
###################
Codeigniter v.3.1.0 + AdminLTE v.2.0 + IonAuth by <NAME>
###################
<file_sep>/application/views/auth/users_group_list.php
<?php $this->load->view('head'); ?>
<?php $this->load->view('header'); ?>
<?php $this->load->view('leftbar'); ?>
<div class="content-wrapper">
<section class="content">
<div class="box box-primary">
<div class="box-header with-border">
<h4 class="box-title"><b>Data Group</b></h4>
</div><!-- /.box-header -->
<div class="box-body table-responsive padding">
<a href="<?php echo base_url('auth/create_group') ?>">
<button class="btn btn-success"><i class="fa fa-plus"></i> Tambah Group Baru</button>
</a>
<h4 align="center"><?php echo $message ?></h4>
<hr/>
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th style="text-align: center">No.</th>
<th style="text-align: center">Nama</th>
<th style="text-align: center">Aksi</th>
</tr>
</thead>
<tbody>
<?php $start = 0; foreach ($groups as $group):?>
<tr>
<td style="text-align:center"><?php echo ++$start ?></td>
<td style="text-align:center"><?php echo $group->name ?></td>
<td style="text-align:center">
<?php
echo anchor(site_url('auth/edit_group/'.$group->id_group),'<i class="glyphicon glyphicon-pencil"></i>','title="Edit", class="btn btn-sm btn-warning"'); echo ' ';
echo anchor(site_url('auth/delete_group/'.$group->id_group),'<i class="glyphicon glyphicon-trash"></i>','title="Hapus", class="btn btn-sm btn-danger", onclick="javasciprt: return confirm(\'Apakah Anda yakin ?\')"');
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
</section>
</div>
<!-- DATA TABLES SCRIPT -->
<script src="<?php echo base_url('assets/template/backend/plugins/datatables/jquery.dataTables.min.js') ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/template/backend/plugins/datatables/dataTables.bootstrap.min.js') ?>" type="text/javascript"></script>
<script type="text/javascript">
function confirmDialog() {
return confirm('Apakah anda yakin?')
}
$(document).ready(function () {
$("#mytable").dataTable();
});
</script>
<?php $this->load->view('footer'); ?> <file_sep>/assets/fungsi/cek_aksi_tambah.php
<?php
include 'cek_session.php';
if($sesen_access == 0)
{
echo "<script>alert('Anda tidak memiliki hak akses apapun, silahkan hubungi Admin!'); location.replace('../index.php')</script>";
session_destroy();
}
?><file_sep>/assets/fungsi/cek_hal_superadmin.php
<?php
include 'cek_session.php';
if($sesen_usertype != 'superadmin')
{
echo "<script>alert('Anda tidak berhak masuk ke halaman ini, harap login menjadi Super Admin terlebih dahulu');location.replace('index.php')</script>";
session_destroy();
}
?><file_sep>/application/views/auth/forgot_password.php
<div id="infoMessage"><?php echo $message;?></div>
Harap masukkan username Anda
<?php echo form_open("auth/forgot_password");?>
<p>
<?php echo form_input($identity);?>
</p>
<p><?php echo form_submit('submit', lang('forgot_password_submit_btn'));?></p>
<?php echo form_close();?>
<file_sep>/application/views/leftbar.php
<!-- Kolom <NAME> -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar user panel -->
<div class="user-panel">
<div class="pull-left image"><img src="<?php echo base_url()?>assets/images/admin.png" class="img-circle" alt="User Image"/></div>
<div class="pull-left info">
<p><?php echo $this->session->userdata('nama'); ?></p>
<p>( <?php echo $this->session->userdata('usertype'); ?> )</p>
</div>
</div>
<ul class="sidebar-menu">
<li class="header">MAIN MENU</li>
<li class="treeview">
<a href="<?php echo base_url('dashboard') ?>">
<i class="fa fa-home"></i> <span>Dashboard</span>
</a>
</li>
<li class="header">SETTING</li>
<li class='treeview'>
<a href='<?php $user_id = $this->session->userdata('user_id'); echo base_url('auth/edit_user/'.$user_id.'') ?>'>
<i class='fa fa-user'></i><span> Edit Profil </span>
</a>
</li>
<?php if ($this->ion_auth->is_superadmin()): ?>
<li class='treeview'>
<a href='#'><i class='fa fa-user'></i><span> User </span><i class='fa fa-angle-left pull-right'></i></a>
<ul class='treeview-menu'>
<li><a href='<?php echo base_url() ?>auth/create_user'><i class='fa fa-circle-o'></i> Tambah User</a></li>
<li><a href='<?php echo base_url() ?>auth/user'><i class='fa fa-circle-o'></i> Data User</a></li>
</ul>
</li>
<li class='treeview'>
<a href='#'><i class='fa fa-users'></i><span> Group </span><i class='fa fa-angle-left pull-right'></i></a>
<ul class='treeview-menu'>
<li><a href='<?php echo base_url() ?>auth/create_group'><i class='fa fa-circle-o'></i> Tambah Group</a></li>
<li><a href='<?php echo base_url() ?>auth/users_group'><i class='fa fa-circle-o'></i> Data Group</a></li>
</ul>
</li>
<?php endif ?>
<li>
<a href='<?php echo base_url() ?>auth/logout'>
<i class="fa fa-sign-out"></i> <span>Logout</span>
</a>
</li>
</ul>
</section>
</aside>
<file_sep>/application/controllers/Auth.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->database();
$this->load->library(array('ion_auth','form_validation'));
$this->load->helper(array('url','language'));
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth');
// Load model Ion_auth_model dan buat alias data_user
$this->load->model('Ion_auth_model');
}
public function index(){
$this->data['title'] = "Dashboard";
// Cek sudah/ belum
if (!$this->ion_auth->logged_in()){
redirect('auth/login', 'refresh');
}
// Cek superadmin/ bukan
elseif (!$this->ion_auth->is_superadmin()){
redirect('dashboard', 'refresh');
}
$this->load->view('v_dashboard',$this->data);
}
// Data user
public function user(){
$this->data['title'] = "Data User";
// Cek sudah/ belum
if (!$this->ion_auth->logged_in()){
redirect('auth/login', 'refresh');
}
// Cek superadmin/ bukan
elseif (!$this->ion_auth->is_superadmin()){
redirect('dashboard', 'refresh');
}
else{
// Set pesan flash data error jika ada
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
//Tampilkan data user
$this->data['users'] = $this->ion_auth->users()->result();
$this->_render_page('auth/user', $this->data);
}
}
// Buat user baru
public function create_user(){
$this->data['title'] = "Tambah User";
$tables = $this->config->item('tables','ion_auth');
$identity_column = $this->config->item('identity','ion_auth');
$this->data['identity_column'] = $identity_column;
// validate form input
$this->form_validation->set_rules('nama', $this->lang->line('create_user_validation_fname_label'), 'required');
$this->form_validation->set_rules('username', $this->lang->line('create_username_validation_fname_label'), 'required');
$this->form_validation->set_rules('alamat', $this->lang->line('create_user_validation_lname_label'), 'required');
if($identity_column!=='username'){
$this->form_validation->set_rules('identity',$this->lang->line('create_user_validation_identity_label'),'required|is_unique['.$tables['users'].'.'.$identity_column.']');
}
else{
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'valid_email|is_unique[' . $tables['users'] . '.email]');
}
$this->form_validation->set_rules('alamat', $this->lang->line('create_user_validation_company_label'), 'trim');
$this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'trim|numeric');
$this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');
$this->form_validation->set_message('required', '{field} mohon diisi');
$this->form_validation->set_message('valid_email', 'Format email tidak benar');
$this->form_validation->set_message('numeric', 'No. HP harus angka');
$this->form_validation->set_message('matches', 'Password baru dan konfirmasi harus sama');
$this->form_validation->set_message('is_unique', 'Alamat email telah terpakai, ganti dengan yang lain');
if ($this->form_validation->run() == true){
$email = strtolower($this->input->post('email'));
$identity = ($identity_column==='email') ? $email : $this->input->post('identity');
$password = $<PASSWORD>('<PASSWORD>');
$additional_data = array(
'nama' => $this->input->post('nama'),
'username' => $this->input->post('username'),
'alamat' => $this->input->post('alamat'),
'phone' => $this->input->post('phone'),
'usertype' => $this->input->post('usertype'),
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($identity, $password, $email, $additional_data)){
// check to see if we are creating the user | redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('auth/user', 'refresh');
}
else{
// display the create user form | set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
$this->data['nama'] = array(
'name' => 'nama',
'id' => 'nama',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('nama'),
);
$this->data['username'] = array(
'name' => 'username',
'id' => 'username',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('username'),
);
$this->data['alamat'] = array(
'name' => 'alamat',
'id' => 'alamat',
'type' => 'text',
'class' => 'form-control',
'cols' => '2',
'rows' => '2',
'value' => $this->form_validation->set_value('alamat'),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('email'),
);
$this->data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('phone'),
);
$this->data['usertype'] = array(
'admin' => 'Admin',
'superadmin' => 'Superadmin',
);
$this->data['usertype_css'] = array(
'name' => 'usertype',
'id' => 'usertype',
'type' => 'text',
'class' => 'form-control',
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'class' => 'form-control',
'value' => $this->form_validation->set_value('password'),
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'class' => 'form-control',
'value' => $this->form_validation->set_value('password_confirm'),
);
$this->data['get_all_users_group'] = $this->Ion_auth_model->get_all_users_group();
$this->_render_page('auth/create_user', $this->data);
}
}
// Edit data user
public function edit_user($id){
$this->data['title'] = 'Edit Data User';
// Cek hak akses ubah password user lain (Hanya Superadmin yang dibolehkan)
if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_superadmin() && !($this->ion_auth->user()->row()->id == $id))){
redirect('dashboard', 'refresh');
}
$user = $this->ion_auth->user($id)->row();
if($user == FALSE){
redirect('auth/user', 'refresh');
}
// validate form input
$this->form_validation->set_rules('nama', $this->lang->line('edit_user_validation_fname_label'), 'required');
$this->form_validation->set_rules('username', $this->lang->line('edit_user_validation_username_label'), 'required');
$this->form_validation->set_rules('email', 'Email', 'valid_email|required');
$this->form_validation->set_rules('phone', 'No. HP', 'trim|numeric');
// Validasi form
$this->form_validation->set_message('required', '{field} mohon diisi');
$this->form_validation->set_message('numeric', 'No. HP harus angka');
$this->form_validation->set_message('valid_email', 'Format email salah');
$this->form_validation->set_message('min_length', 'Password minimal 8 huruf');
$this->form_validation->set_message('max_length', 'Password maksimal 20 huruf');
$this->form_validation->set_message('matches', 'Password baru dan konfirmasi harus sama');
$this->form_validation->set_message('is_unique', 'Email telah terpakai, gunakan yang lain');
if (isset($_POST) && !empty($_POST)){
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')){
show_error($this->lang->line('error_csrf'));
}
// update the password if it was posted
if ($this->input->post('password')){
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
}
if ($this->form_validation->run() === TRUE){
$data = array(
'nama' => $this->input->post('nama'),
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'usertype' => $this->input->post('usertype'),
'alamat' => $this->input->post('alamat'),
'phone' => $this->input->post('phone'),
);
// update the password if it was posted
if ($this->input->post('password')){
$data['password'] = $this->input->post('password');
}
// check to see if we are updating the user
if($this->ion_auth->update($user->id, $data)){
// redirect them back to the admin page if admin, or to the base url if non admin
$this->session->set_flashdata('message', $this->ion_auth->messages() );
if ($this->ion_auth->is_superadmin()){
redirect('auth/user', 'refresh');
}
else{
redirect('dashboard', 'refresh');
}
}
else{
// redirect them back to the admin page if admin, or to the base url if non admin
$this->session->set_flashdata('message', $this->ion_auth->errors() );
if ($this->ion_auth->is_superadmin()){
redirect('auth/user', 'refresh');
}
else{
redirect('dashboard', 'refresh');
}
}
}
}
// display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
// set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
// pass the user to the view
$this->data['user'] = $user;
$this->data['nama'] = array(
'name' => 'nama',
'id' => 'nama',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('nama', $user->nama),
);
$this->data['username'] = array(
'name' => 'username',
'id' => 'username',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('username', $user->username),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('email', $user->email),
);
$this->data['alamat'] = array(
'name' => 'alamat',
'id' => 'alamat',
'type' => 'textarea',
'class' => 'form-control',
'rows' => '2',
'cols' => '2',
'value' => $this->form_validation->set_value('alamat', $user->alamat),
);
$this->data['usertype'] = array(
'name' => 'usertype',
'id' => 'usertype',
'type' => 'text',
'class' => 'form-control',
);
$this->data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'type' => 'text',
'class' => 'form-control',
'value' => $this->form_validation->set_value('phone', $user->phone),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'class' => 'form-control',
'placeholder' => 'diisi jika mengubah password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'class' => 'form-control',
'placeholder' => 'diisi jika mengubah password'
);
$this->data['users_group'] = $this->Ion_auth_model->get_users_group();
$this->_render_page('auth/edit_user', $this->data);
}
// Hapus data user
public function delete_user($id) {
$row = $this->Ion_auth_model->get_by_id($id);
if ($row) {
$this->Ion_auth_model->delete_user($id);
$this->session->set_flashdata('message', $this->lang->line('delete_successful'));
redirect(site_url('auth/user'));
}
else {
$this->session->set_flashdata('message', $this->lang->line('delete_unsuccessful'));
redirect(site_url('auth/user'));
}
}
/* CRUD User Group by Harviacode */
// Data User Group
public function users_group(){
$this->data['title'] = "Data Group";
// Cek sudah/ belum
if (!$this->ion_auth->logged_in()){
redirect('auth/login', 'refresh');
}
// Cek superadmin/ bukan
elseif (!$this->ion_auth->is_superadmin()){
redirect('dashboard', 'refresh');
}
else{
// set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
//list the users
$this->data['groups'] = $this->ion_auth->get_all_groups()->result();
$this->_render_page('auth/users_group_list', $this->data);
}
}
// Buat user group baru
public function create_group(){
// Cek sudah/ belum
if (!$this->ion_auth->logged_in()){
redirect('auth/login', 'refresh');
}
// Cek superadmin/ bukan
elseif (!$this->ion_auth->is_superadmin()){
redirect('dashboard', 'refresh');
}
else{
$this->data = array(
'name' => set_value('name'),
'title' => 'Tambah Group'
);
$this->load->view('auth/create_group', $this->data);
}
}
public function create_group_action(){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_message('required', '{field} mohon diisi');
if ($this->form_validation->run() == FALSE) {
$this->create_group();
}
else {
$data = array('name' => $this->input->post('name'));
$this->Ion_auth_model->create_group($data);
$this->session->set_flashdata('message', 'Data berhasil ditambahkan');
redirect(site_url('auth/users_group'));
}
}
// Edit data user group
public function edit_group($id_group){
$row = $this->Ion_auth_model->get_by_id_group($id_group);
if ($row) {
$data = array(
'id_group' => set_value('id_group', $row->id_group),
'name' => set_value('name', $row->name),
'title' => 'Edit Data Group'
);
$this->load->view('auth/users_group_form', $data);
}
else {
$this->session->set_flashdata('message', 'Record Not Found');
redirect(site_url('users_group'));
}
}
public function edit_group_action(){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_message('required', '{field} mohon diisi');
if ($this->form_validation->run() == FALSE) {
$this->update_group($this->input->post('id_group'));
}
else {
$data = array('name' => $this->input->post('name'));
$this->Ion_auth_model->update_group($this->input->post('id_group'), $data);
$this->session->set_flashdata('message', 'Update data berhasil');
redirect(site_url('auth/users_group'));
}
}
// Hapus data user group
public function delete_group($id_group){
$row = $this->Ion_auth_model->get_by_id_group($id_group);
if ($row) {
$this->Ion_auth_model->delete_group($id_group);
$this->session->set_flashdata('message', 'Delete Record Success');
redirect(site_url('auth/users_group'));
} else {
$this->session->set_flashdata('message', 'Record Not Found');
redirect(site_url('auth/users_group'));
}
}
// Proses login
public function login(){
$this->data['title'] = $this->lang->line('login_heading');
//validate form input
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', str_replace(':', '', $this->lang->line('login_password_label')), 'required');
if ($this->form_validation->run() == true){
// check to see if the user is logging in
// check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember)){
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->lang->line('login_successful'));
redirect('dashboard', 'refresh');
}
else{
// if the login was un-successful
// redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors(''));
redirect('auth/login', 'refresh'); // use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else{
// the user is not logging in so display the login page
// set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['username'] = array('name' => 'username',
'id' => 'username',
'type' => 'text',
'value' => $this->form_validation->set_value('username'),
);
$this->data['password'] = array('name' => '<PASSWORD>',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('auth/login', $this->data);
}
}
// Proses logout
public function logout(){
$this->data['title'] = "Logout";
// log the user out
$logout = $this->ion_auth->logout();
// redirect them to the login page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('auth/login', 'refresh');
}
public function username_check($str){
$this->load->model('ion_auth_model');
if ($this->ion_auth_model->username_check($str)){
return TRUE;
}
else{
$this->form_validation->set_message('username_check','Username tidak ditemukan');
return FALSE;
}
}
// Lupa Password
public function forgot_password(){
// setting validation rules by checking whether identity is identity or email
if($this->config->item('identity', 'ion_auth') != 'email' ){
$this->form_validation->set_rules('identity', $this->lang->line('forgot_password_username_label'), 'required');
}
else{
$this->form_validation->set_rules('identity', $this->lang->line('forgot_password_validation_email_label'), 'required|valid_email');
}
if ($this->form_validation->run() == false){
$this->data['type'] = $this->config->item('identity','ion_auth');
// setup the input
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
);
if ( $this->config->item('identity', 'ion_auth') != 'email' ){
$this->data['username_label'] = $this->lang->line('forgot_password_username_label');
}
else{
$this->data['username_label'] = $this->lang->line('forgot_password_email_username_label');
}
// set any errors and display the form
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->_render_page('auth/forgot_password', $this->data);
}
else{
$identity_column = $this->config->item('identity','ion_auth');
$identity = $this->ion_auth->where($identity_column, $this->input->post('identity'))->users()->row();
if(empty($identity)) {
if($this->config->item('identity', 'ion_auth') != 'email'){
$this->ion_auth->set_error('forgot_password_username_not_found');
}
else{
$this->ion_auth->set_error('forgot_password_email_not_found');
}
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/forgot_password", 'refresh');
}
// run the forgotten password method to email an activation code to the user
$forgotten = $this->ion_auth->forgotten_password($identity->{$this->config->item('identity', 'ion_auth')});
if ($forgotten){
// if there were no errors
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("auth/login", 'refresh'); //we should display a confirmation page here instead of the login page
}
else{
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/forgot_password", 'refresh');
}
}
}
// Tahap lanjutan dari lupa password -> reset password
public function reset_password($code = NULL){
if (!$code)
{
show_404();
}
$user = $this->ion_auth->forgotten_password_check($code);
if ($user)
{
// if the code is valid then display the password reset form
$this->form_validation->set_rules('new', $this->lang->line('reset_password_validation_new_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[new_confirm]');
$this->form_validation->set_rules('new_confirm', $this->lang->line('reset_password_validation_new_password_confirm_label'), 'required');
if ($this->form_validation->run() == false)
{
// display the form
// set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['min_password_length'] = $this->config->item('min_password_length', 'ion_auth');
$this->data['new_password'] = array(
'name' => 'new',
'id' => 'new',
'type' => 'password',
'pattern' => '^.{'.$this->data['min_password_length'].'}.*$',
);
$this->data['new_password_confirm'] = array(
'name' => 'new_confirm',
'id' => 'new_confirm',
'type' => 'password',
'pattern' => '^.{'.$this->data['min_password_length'].'}.*$',
);
$this->data['user_id'] = array(
'name' => 'user_id',
'id' => 'user_id',
'type' => 'hidden',
'value' => $user->id,
);
$this->data['csrf'] = $this->_get_csrf_nonce();
$this->data['code'] = $code;
// render
$this->_render_page('auth/reset_password', $this->data);
}
else
{
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE || $user->id != $this->input->post('user_id'))
{
// something fishy might be up
$this->ion_auth->clear_forgotten_password_code($code);
show_error($this->lang->line('error_csrf'));
}
else
{
// finally change the password
$username = $user->{$this->config->item('username', 'ion_auth')};
$change = $this->ion_auth->reset_password($username, $this->input->post('new'));
if ($change)
{
// if the password was successfully changed
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("auth/login", 'refresh');
}
else
{
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('auth/reset_password/' . $code, 'refresh');
}
}
}
}
else
{
// if the code is invalid then send them back to the forgot password page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/forgot_password", 'refresh');
}
}
// Aktivasi user
public function activate($id, $code=false){
if ($code !== false)
{
$activation = $this->ion_auth->activate($id, $code);
}
else if ($this->ion_auth->is_superadmin())
{
$activation = $this->ion_auth->activate($id);
}
if ($activation)
{
// redirect them to the auth page
$this->session->set_flashdata('message', 'Akun berhasil diaktifkan');
redirect("auth/user", 'refresh');
}
else
{
// redirect them to the forgot password page
$this->session->set_flashdata('message', 'Akun gagal diaktifkan');
redirect("auth/forgot_password", 'refresh');
}
}
// Nonaktifkan user
public function deactivate($id = NULL){
$id = (int) $id;
// do we have the right userlevel?
if ($this->ion_auth->logged_in() && $this->ion_auth->is_superadmin())
{
$this->ion_auth->deactivate($id);
}
// redirect them back to the auth page
$this->session->set_flashdata('message', 'Akun berhasil dinonaktifkan');
redirect('auth/user', 'refresh');
}
public function _get_csrf_nonce(){
$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
return array($key => $value);
}
public function _valid_csrf_nonce(){
if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
{
return TRUE;
}
else
{
return FALSE;
}
}
//I think this makes more sense
public function _render_page($view, $data=null, $returnhtml=false){
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $returnhtml);
if ($returnhtml) return $view_html;//This will return html on 3rd argument being true
}
}
<file_sep>/assets/fungsi/cek_aksi_hapus.php
<?php
include 'cek_session.php';
if($sesen_access != 3)
{
echo "<script>alert('Anda tidak memiliki hak untuk menghapus data!'); location.replace('../index.php')</script>";
session_destroy();
}
?><file_sep>/ci_ionauth.sql
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 5.6.14 - MySQL Community Server (GPL)
-- Server OS: Win32
-- HeidiSQL Version: 9.4.0.5125
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table ci_ionauth.login_attempts
CREATE TABLE IF NOT EXISTS `login_attempts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ip_address` varchar(15) NOT NULL,
`login` varchar(100) NOT NULL,
`time` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- Dumping data for table ci_ionauth.login_attempts: ~0 rows (approximately)
/*!40000 ALTER TABLE `login_attempts` DISABLE KEYS */;
/*!40000 ALTER TABLE `login_attempts` ENABLE KEYS */;
-- Dumping structure for table ci_ionauth.users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nama` varchar(50) DEFAULT NULL,
`username` varchar(100) DEFAULT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` varchar(20) DEFAULT NULL,
`alamat` text,
`usertype` char(10) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`salt` varchar(255) DEFAULT NULL,
`active` tinyint(1) unsigned DEFAULT NULL,
`activation_code` varchar(40) DEFAULT NULL,
`forgotten_password_code` varchar(40) DEFAULT NULL,
`forgotten_password_time` datetime DEFAULT NULL,
`remember_code` varchar(40) DEFAULT NULL,
`last_login` datetime DEFAULT NULL,
`created_on` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- Dumping data for table ci_ionauth.users: ~2 rows (approximately)
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`id`, `nama`, `username`, `password`, `email`, `phone`, `alamat`, `usertype`, `ip_address`, `salt`, `active`, `activation_code`, `forgotten_password_code`, `forgotten_password_time`, `remember_code`, `last_login`, `created_on`) VALUES
(1, '<NAME>', 'azmicolejr', <PASSWORD>$08$7<PASSWORD>UUM3bP2rw7TByey44mNS6ju4ksHgluPwiNF2QK6E3v26S', '<EMAIL>', '081228289766', '', 'superadmin', '127.0.0.1', '', 1, '', '8h0.P1tqx8HiRyDvwCGpfu00362d152e9a037a75', '0000-00-00 00:00:00', '79X4VtxEkwElLIF6ZQTtJu', '2016-11-15 12:46:22', '0000-00-00 00:00:00'),
(2, 'Administrator', 'admin', '$2y$08$TNEXjcI7xK2leTyGgrrrNOcZXr2b52.ajUildu5sya.vG4P/JXWbC', '<EMAIL>', '082414214', '', 'admin', '::1', NULL, 1, NULL, NULL, NULL, NULL, NULL, '2016-11-15 12:45:41');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
-- Dumping structure for table ci_ionauth.users_group
CREATE TABLE IF NOT EXISTS `users_group` (
`id_group` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL,
PRIMARY KEY (`id_group`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
-- Dumping data for table ci_ionauth.users_group: ~2 rows (approximately)
/*!40000 ALTER TABLE `users_group` DISABLE KEYS */;
INSERT INTO `users_group` (`id_group`, `name`) VALUES
(1, 'superadmin'),
(2, 'admin');
/*!40000 ALTER TABLE `users_group` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
<file_sep>/application/views/head.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $title;?></title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<!-- Bootstrap 3.3.4 -->
<link href="<?php echo base_url()?>assets/template/backend/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- FontAwesome 4.3.0 -->
<link href="<?php echo base_url()?>assets/addon/font-awesome4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<!-- Theme style -->
<link href="<?php echo base_url()?>assets/template/backend/dist/css/AdminLTE.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url()?>assets/template/backend/dist/css/skins/skin-blue.min.css" rel="stylesheet" type="text/css" />
<!-- jQuery 2.1.4 -->
<script src="<?php echo base_url()?>assets/template/backend/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.2 -->
<script src="<?php echo base_url() ?>assets/template/backend/plugins/jQueryUI/jquery-ui-1.10.3.min.js" type="text/javascript"></script>
<!-- Bootstrap 3.3.2 JS -->
<script src="<?php echo base_url()?>assets/template/backend/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!-- AdminLTE App -->
<script src="<?php echo base_url()?>assets/template/backend/dist/js/app.min.js" type="text/javascript"></script>
<!-- Slim Scroll -->
<script src="<?php echo base_url()?>assets/template/backend/plugins/slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>$.widget.bridge('uibutton', $.ui.button);</script>
<!-- Favicon -->
<link rel="shortcut icon" href="<?php echo base_url() ?>assets/images/fav.ico" />
<!-- DATA TABLES -->
<link href="<?php echo base_url('assets/template/backend/plugins/datatables/dataTables.bootstrap.css') ?>" rel="stylesheet" type="text/css" />
</head>
<body class="skin-blue fixed sidebar-mini">
<div class="wrapper"><file_sep>/application/views/auth/user.php
<?php $this->load->view('head'); ?>
<?php $this->load->view('header'); ?>
<?php $this->load->view('leftbar'); ?>
<div class="content-wrapper">
<section class="content-header">
<h1><?php echo $title ?></h1>
<ol class="breadcrumb">
<li><a href="<?php echo base_url('dashboard') ?>"><i class="fa fa-dashboard"></i> Home</a></li>
<li>User</li>
<li class="active"><a href="<?php echo current_url() ?>"><?php echo $title ?></a></li>
</ol>
</section>
<section class="content">
<div class="box box-primary">
<div class="box-body table-responsive padding">
<a href="<?php echo base_url('auth/create_user') ?>">
<button class="btn btn-success"><i class="fa fa-plus"></i> Tambah User Baru</button>
</a>
<h4 align="center"><?php echo $message ?></h4>
<hr/>
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th style="text-align: center">No.</th>
<th style="text-align: center">Nama</th>
<th style="text-align: center">Username</th>
<th style="text-align: center">Email</th>
<th style="text-align: center">Last Login</th>
<th style="text-align: center">Usertype</th>
<th style="text-align: center">Status</th>
<th style="text-align: center">Aksi</th>
</tr>
</thead>
<tbody>
<?php $start = 0; foreach ($users as $user):?>
<tr>
<td style="text-align:center"><?php echo ++$start ?></td>
<td><?php echo $user->nama ?></td>
<td style="text-align:center"><?php echo $user->username ?></td>
<td style="text-align:center"><?php echo $user->email ?></td>
<td style="text-align:center"><?php echo $user->last_login ?></td>
<td style="text-align:center"><?php echo $user->usertype ?></td>
<td style="text-align:center"><?php echo ($user->active) ? anchor("auth/deactivate/".$user->id, 'ACTIVE','title="ACTIVE", class="btn btn-sm btn-primary"', lang('index_active_link')) : anchor("auth/activate/". $user->id, 'INACTIVE','title="INACTIVE", class="btn btn-sm btn-danger"' , lang('index_inactive_link'));?></td>
<td style="text-align:center">
<?php
echo anchor(site_url('auth/edit_user/'.$user->id),'<i class="glyphicon glyphicon-pencil"></i>','title="Edit", class="btn btn-sm btn-warning"'); echo ' ';
echo anchor(site_url('auth/delete_user/'.$user->id),'<i class="glyphicon glyphicon-trash"></i>','title="Hapus", class="btn btn-sm btn-danger", onclick="javasciprt: return confirm(\'Apakah Anda yakin ?\')"');
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
</section>
</div>
<!-- DATA TABLES SCRIPT -->
<script src="<?php echo base_url('assets/template/backend/plugins/datatables/jquery.dataTables.min.js') ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/template/backend/plugins/datatables/dataTables.bootstrap.min.js') ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#mytable").dataTable();
});
</script>
<?php $this->load->view('footer'); ?>
<file_sep>/application/views/auth/create_group.php
<?php $this->load->view('head'); ?>
<?php $this->load->view('header'); ?>
<?php $this->load->view('leftbar'); ?>
<div class="content-wrapper">
<section class='content'>
<div class='row'>
<div id="infoMessage"></div>
<?php echo form_open("auth/create_group_action");?>
<!-- left column -->
<div class="col-md-6">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h4 class="box-title"><b>Tambah Group</b></h4>
</div><!-- /.box-header -->
<div class="box-body"><?php echo form_error('name') ?>
<div class="form-group"><label>Nama</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Name" value="<?php echo $name; ?>" />
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submit" class="btn btn-success">Submit</button>
<button type="reset" name="reset" class="btn btn-danger">Reset</button>
</div>
</div><!-- /.box -->
<!-- left column -->
</div>
<?php echo form_close(); ?>
</div>
</section>
</div>
<?php $this->load->view('footer'); ?> | b7194c98adc9aedfdf301d762351e66e5119313f | [
"SQL",
"reStructuredText",
"PHP"
] | 16 | PHP | azmicolejr/ci_ionauth | e8dfc3b68722a7d013e8ed00adebcfcd8de662fb | 2f81cca02f3562092d583e97c04f4ed5ad241d06 |
refs/heads/main | <file_sep>USE employee_db;
INSERT INTO departments (name)
VALUE
('Sales'),
('Engineering'),
('Finanace'),
('Legal');
INSERT INTO roles (title, salary, department_id)
VALUE
('Sales Lead', 100000, 1),
('Salesperson', 80000, 1),
('Lead Engineer', 150000, 2),
('Software Engineer', 120000, 2),
('Accountant', 125000, 3),
('Legal Team Lead', 250000, 4),
('Lawyer', 190000, 4);
INSERT INTO employees (first_name, last_name, role_id, manager_id)
VALUE
('Kitty', 'Smith', 1, null),
('Baby', 'Cooper', 3, null),
('Madison', 'Sparkles', 4, 2),
('Jay', 'Malibu', 6, null),
('Frances', 'Little', 2, 1),
('Emma', 'Bender', 5, 1),
('Suki', 'Halloway', 7, 4),
('Dusty', 'Rhodes', 2, 1);<file_sep># Employee Tracker #
Employee Tracker is a command-line content management systems application that can be used to store and track employee data.
## Creation ##
### Created Using ###
* Node.js
* Inquirer
* MySQL
## App Demo ##
<img width="622" alt="Screen Shot 2020-10-19 at 3 24 35 PM" src="https://user-images.githubusercontent.com/68661461/96513342-39ec3680-121f-11eb-8e79-5b2e1c727bf2.png">
<img width="602" alt="Screen Shot 2020-10-19 at 3 27 33 PM" src="https://user-images.githubusercontent.com/68661461/96513635-a0715480-121f-11eb-8605-39aa05419a60.png">
### Link to Full Video ###
https://drive.google.com/file/d/1PwjvGrr0qpHz22UwaNE38d2dUmXPG4AL/view?usp=sharing
## Instructions ##
* From the command line, in the root directory, enter 'npm start' to run the application.
* You will be presented with a menu of options as follows:
- View Departments: when selected, this option will display a table of all departments and their info, including department names and ids.
- View Roles: when selected, this option will display a table of all roles and their info, including ids, job titles, departments, and salary.
- View Employees: when selected, this option will display a table of all employees and their info, including id's, first and last name's, job titles, and managers.
- Add Department/Add Role/Add Employee: when selected, any of these options will allow you to add new data (a department, role, or employee) to the database by answering a series of prompts.
- Update Role: when selected, this option will allow you to change the role for an employee of your choosing.
* To exit the application, simply select the Quit option. All data will remain saved in the database.
| 75074d27344ff1f9c744d88d35bb32a9e309034b | [
"Markdown",
"SQL"
] | 2 | SQL | sfoutz0205/employee-tracker | 410002db3946e0089ac46ccbcd35605d189e708a | 61aaf946e929fe9ee6037320e65cc4dc66840116 |
refs/heads/main | <file_sep>package com.example.dicodinglastproject3
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.dicodinglastproject3.Activity.AboutMeActivity
import com.example.dicodinglastproject3.Adapter.ListWisataSurabayaAdapter
import com.example.dicodinglastproject3.Model.ModelWisata
import com.example.dicodinglastproject3.database.dbWisata
class MainActivity : AppCompatActivity() {
private lateinit var rvWisata:RecyclerView
private var list: ArrayList<ModelWisata> = arrayListOf()
//activity main
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val actionbar = supportActionBar
actionbar!!.title= "Halaman Utama"
rvWisata = findViewById(R.id.rv_wisata_surabaya)
rvWisata.setHasFixedSize(true)
list.addAll(dbWisata.listData)
showRecyclerList()
}
//recycler list
private fun showRecyclerList() {
rvWisata.layoutManager = LinearLayoutManager(this)
val listWisataSurabaya = ListWisataSurabayaAdapter(list)//adapter
rvWisata.adapter = listWisataSurabaya
}
//menu utama
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu,menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
setMode(item.itemId)
return super.onOptionsItemSelected(item)
}
//pindah activity ketika mengklik pilihan
private fun setMode(selectMode:Int)
{
when(selectMode)
{
R.id.about_me -> {
val IAboutMe = Intent(this@MainActivity, AboutMeActivity::class.java)
startActivity(IAboutMe)
}
}
}
}<file_sep>package com.example.dicodinglastproject3.Model
data class ModelWisata (
var nama : String = "",
var operasi: String = "",
var detail : String = "",
var photo : Int = 0
)<file_sep>package com.example.dicodinglastproject3.Activity
import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.dicodinglastproject3.R
//adapter
class DetailWisataActivity : AppCompatActivity() {
companion object {
const val EXTRA_NAME = "extra_name"
const val EXTRA_PHOTO = "extra_photo"
const val EXTRA_DETAIL = "extra_detail"
const val EXTRA_OPERASI = "extra_operasi"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
// val bundle: Bundle? = intent.extras
// val tName: String? = bundle?.getString(EXTRA_NAME)
// val tImg: Int? = bundle?.getInt(EXTRA_PHOTO,0)
// val tDetail: String? = bundle?.getString(EXTRA_DETAIL)
// val tOperasi: String? = bundle?.getString(EXTRA_OPERASI)
val tName = intent.getStringExtra(EXTRA_NAME)
val tImg = intent.getIntExtra(EXTRA_PHOTO,0)
val tDetail = intent.getStringExtra(EXTRA_DETAIL)
val tOperasi = intent.getStringExtra(EXTRA_OPERASI)
//mengarahkan ke layout
val tvName: TextView = findViewById(R.id.tv_item_name)
val imgSetPhoto: ImageView = findViewById(R.id.img_item_photo)
val tvDetail: TextView = findViewById(R.id.tv_item_detail)
val tvOperasi: TextView = findViewById(R.id.tv_item_operasi)
val btnShare : Button = findViewById(R.id.btn_set_share)
//Log
Log.d("Bundle", "tName: $tName")
Log.d("Bundle", "tImg: $tImg")
Log.d("Bundle", "tDetail: $tDetail")
Log.d("Bundle", "tOpearsi: $tOperasi")
val actionbar = supportActionBar
actionbar!!.title = "Detail Wisata"
//ada tombol back
actionbar.setDisplayHomeAsUpEnabled(true)
tvName.text = tName
tvDetail.text = tDetail
tvOperasi.text = tOperasi
Glide.with(this)
.load(tImg)
.apply(RequestOptions())
.into(imgSetPhoto)
btnShare.setOnClickListener {
val link = "https://www.javatravel.net/tempat-wisata-surabaya"
val Share = Intent()
Share.action = Intent.ACTION_SEND
Share.putExtra(Intent.EXTRA_TEXT,"Lihat lebih detail lagi pada link berikut ini: $link")
Share.type = "text/plain"
startActivity(Intent.createChooser(Share, "Share To:"))
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}<file_sep>package com.example.dicodinglastproject3.database
import com.example.dicodinglastproject3.Model.ModelWisata
import com.example.dicodinglastproject3.R
object dbWisata {
private val NamaWisata= arrayOf(
"Air Mancur Menari",
"Ekowisata Mangrove",
"Monumen Kapal Selam",
"Masjid <NAME>",
"Masjid Nasional Al-Akbar",
"Museum De Javasche Bank",
"Monumen Bambu Runcing",
"House of Sampoerna",
"Tugu Pahlawan",
"Taman Bungkul"
)
private val DetailWisata = arrayOf(
"Air Mancur Menari merupakan objek wisata yang terletak di daerah Kenjeran. Tempat ini merupakan spot bagus untuk mengambil foto selfie. Karena terdapat jembatan megah yang di bangun di sepanjang Pantai Kenjeran. Dari jembatan inilah Anda dapat menikmati kecantikan Air Mancur Menari pada malam hari.",
"Ekowisata Mangrove ini begitu digemari oleh para wisatawan karena dapat merasakan daerah hijau di tengah cuaca panas Surabaya yang terik.",
"Monumen Kapal Selam ini begitu edukatif, mengingat monumen kapal selam merupakan KRI Pasopati 410 yang ikut dalam operasi Trikora. Untuk lebih mengenal tentang sejarahnya, para pengunjung disuguhkan sebuah film pendek tentang pertempuran Laut Aru.",
"Masjid <NAME> Surabaya selalu ramai oleh pengunjung. Meski wisata rohani, Anda pun dapat mengabadikan momen dengan berfoto di tempat ini karena terdapat desain Tiongkok yang bercampur denga Arab yang membuatnya begitu indah.",
"Masjid yang sudah dibangun sejak tahun 1995 ini memang memiliki gaya arsitektur yang menarik. Bahkan sejak Anda tiba di pintu gerbangnya, Anda sudah akan dibuat terpukau dengan desainnya.",
"Surabaya memang memiliki banyak wisata sejarah yang begitu menarik untuk dikunjungi. Dan Museum De Javasche Bank menjadi saksi bisu awal mula dunia perbankan yang ada di Indonesia. Bangunan satu ini dikenal juga sebagai cagar budaya karena menyimpan banyak peninggalan bersejarah yang tentunya tidak bernilai harganya.",
"Monumen Bambu Runcing ini tentunya dapat dijadikan tempat edukasi untuk anak-anak hinga pelajar unutk memperdalam sejarah. Mengingat bambu runcing sendiri merupakan senjata ampuh para pahlawan untuk mengusir penjajah.",
"House of Sampoerna ini menjadi destinasi menarik bagi wisatawan yang berkunjung ke Kota Surabaya. Tempat ini memiliki pajangan yang edukatif dan juga unik tentang perkembangan industri rokok Sampoerna mulai awal hingga saat ini.",
"Tempat wisata selanjutnya merupakan ikon Kota Pahlawan yang begitu populer, yaitu Tugu Pahlawan. Tempat ini dipenuhi oleh tanaman hijau yang rindang yang cocok untuk dijadikan tempat singgah setelah berkeliling Kota Surabaya. Anda dapat bersantai sambil menikmati Tugu Pahlawan yang telah berdiri sejak masa penjajahan.",
"Tempat wisata selanjutnya adalah Taman Bungkul yang namanya terinspirasi dari seorang Sunan yang bernama Ki Ageng Supo. Beliau merupakan seorang penyebar agama Islam di Kota Pahlawan tersebut. Panggilan dari Ki Ageng Supo sendiri ialah <NAME>, yang menginspirasi masyarakat untuk menanam tanaman di tempat tersebut."
)
private val OperasiWisata = arrayOf(
"00.00-24.00",
"07.30โ18.00",
"09.00โ17.00",
"00.00-24.00",
"00.00-24.00",
"08.00-16.00",
"00.00-24.00",
"00.00-24.00",
"07.00โ15.00",
"00.00-24.00"
)
private val PhotoWisata = intArrayOf(
R.drawable.air_mancur_menari_surabaya,
R.drawable.mangrove_surabaya,
R.drawable.kapal_selam_surabaya,
R.drawable.cheng_hoo_surabaya,
R.drawable.al_akbar_surabaya,
R.drawable.javasche_bank_surabaya,
R.drawable.bambu_runcing_surabaya,
R.drawable.sampurnahouse_surabaya,
R.drawable.tupal_surabaya,
R.drawable.taman_bungkul_surabaya
)
val listData:ArrayList<ModelWisata>
get()
{
val list = arrayListOf<ModelWisata>()
for(position in NamaWisata.indices)
{
val WisataSurabaya = ModelWisata()
WisataSurabaya.nama = NamaWisata[position]
WisataSurabaya.detail = DetailWisata[position]
WisataSurabaya.operasi = OperasiWisata[position]
WisataSurabaya.photo = PhotoWisata[position]
list.add(WisataSurabaya)
}
return list
}
}<file_sep>package com.example.dicodinglastproject3.Activity
import com.example.dicodinglastproject3.R
import android.media.Image
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
class AboutMeActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.aboutme)
val actionbar = supportActionBar
actionbar!!.title = "About Me"
//ada tombol back
actionbar.setDisplayHomeAsUpEnabled(true)
val myImage : Int = R.drawable.foto_formal
val imgSetPhoto: ImageView = findViewById(R.id.img_item_photo)
Glide.with(this)
.load(myImage)
.apply(RequestOptions().override(300,300))
.into(imgSetPhoto)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
<file_sep>package com.example.dicodinglastproject3.Adapter
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.dicodinglastproject3.Activity.DetailWisataActivity
import com.example.dicodinglastproject3.Model.ModelWisata
import com.example.dicodinglastproject3.R
class ListWisataSurabayaAdapter(private val listWisata: ArrayList<ModelWisata>) :RecyclerView.Adapter<ListWisataSurabayaAdapter.ListViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view:View = LayoutInflater.from(parent.context).inflate(R.layout.activity_rowlist,parent,false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val wisata = listWisata[position]
val mContext = holder.itemView.context
Glide.with(holder.itemView.context)
.load(wisata.photo)
.apply(RequestOptions())
.into(holder.imgPhoto)
holder.tvNama.text = wisata.nama
holder.tvDetail.text = wisata.detail
holder.itemView.setOnClickListener {
val ToDetail = Intent(mContext,DetailWisataActivity::class.java)
ToDetail.putExtra(DetailWisataActivity.EXTRA_NAME,wisata.nama)
ToDetail.putExtra(DetailWisataActivity.EXTRA_PHOTO,wisata.photo)
ToDetail.putExtra(DetailWisataActivity.EXTRA_DETAIL,wisata.detail)
ToDetail.putExtra(DetailWisataActivity.EXTRA_OPERASI,wisata.operasi)
Log.d("Bundle", "tName: ${wisata.nama}")
Log.d("Bundle", "tImg: ${wisata.photo}")
Log.d("Bundle", "tDetail: ${wisata.detail}")
Log.d("Bundle", "tOpearsi: ${wisata.operasi}")
mContext.startActivity(ToDetail)
}
}
override fun getItemCount(): Int {
return listWisata.size
}
inner class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tvNama: TextView = itemView.findViewById(R.id.tv_item_name)
var tvDetail: TextView = itemView.findViewById(R.id.tv_item_detail)
var imgPhoto: ImageView = itemView.findViewById(R.id.img_item_photo)
}
} | 8074d827e8544308b08c2503cc7bef1f3c7f9331 | [
"Kotlin"
] | 6 | Kotlin | mail2418/Dicoding-Android-Pemula-Project | 81f1cf13d9bc30997f0fcf217b5b68aa94ac67d0 | 2d47c1c3177010a1dbee8c8ed9c8196bd9046012 |
refs/heads/master | <file_sep>from setuptools import setup
setup(name = 'jinjaStore',
version = "0.1",
description = "Jinja Store for Templating",
author = "<NAME>",
author_email = "<EMAIL>",
url = "https://github.com/thebinary/jinjaStore",
packages = ['jinjaStore'],
package_data = {
'jinjaStore': [ '*.jinja2' ]
},
install_requires = ['jinja2'],
long_description = "Maintain Store of Jinja Templates for rendering",
)
<file_sep>from jinjaStore import JinjaStore
<file_sep># jinjaStore
Jinja2 Store for rendering Templates
<file_sep>"""
Author : <NAME> <<EMAIL>>
Purpose : Store of Jinja Templates for rendering
"""
import os
import inspect
import jinja2
class FileNotFound(Exception):
pass
class JinjaStore:
"""
JinjaStore for Templating
Render using 3 locations:
- sys : templates included with module
pointed using templateName as 'sys/<templatePath>'
- user : user defined path for templates
pointed using templateName as 'user/<templatePath>'
- cwd : templates inside current working directory
pointed using templateName as 'cwd/<templatePath>'
Note:
Each <templatePath> will have an implicit 'templates' prepended to the
path and '.jinja2' appended to the path.
So, 'cwd/employee/hod' points to file '<cwd>/employee/hod.jinja2'
"""
def __init__(self, userTemplatePath=''):
""" JinjaStore initializor """
modulePath = \
os.path.dirname(os.path.realpath(inspect.getfile(self.__class__)))
currentPath = os.getcwd()
sysTemplatePath = modulePath + os.sep + 'templates'
cwdTemplatePath = currentPath + os.sep + 'templates'
# Template Paths Jinja Environments
userTemplates = None
if userTemplatePath <> '':
userTemplates = userTemplatePath + os.sep + 'templates'
userTemplates = jinja2.Environment()
userTemplates.loader = jinja2.FileSystemLoader(userTemplatePath)
sysTemplates = jinja2.Environment()
sysTemplates.loader = jinja2.FileSystemLoader(sysTemplatePath)
cwdTemplates = jinja2.Environment()
cwdTemplates.loader = jinja2.FileSystemLoader(cwdTemplatePath)
self.sysTemplates = sysTemplates
self.cwdTemplates = cwdTemplates
self.userTemplates = userTemplates
def __renderTemplate(self, templateSelector, templateName, varsDict):
""" Render Template found in given template location selector """
return templateSelector.get_template(templateName).render(varsDict)
def renderTemplate(self, templateName, varsDict):
"""
Render Template using templateName and given variable Dictionary
eg: renderTemplate('sys/employee/hod', {'name': 'Binary'})
"""
selector = templateName.split(os.sep)[0]
actualTemplateName = os.sep.join(templateName.split(os.sep)[1:]) + \
".jinja2"
templator = None
if selector == 'sys':
templator = self.sysTemplates
elif selector == 'cwd':
templator = self.cwdTemplates
elif selector == 'user':
templator = self.userTemplates
result = None
if templator <> None:
try:
result = self.__renderTemplate(templator, actualTemplateName, varsDict)
except jinja2.exceptions.TemplateNotFound as je:
raise FileNotFound(je)
return result
if __name__ == '__main__':
obj = JinjaStore()
print obj.renderTemplate('sys/samples/employee/hod', { 'employee_id': 100,
'employee_name': 'Binary'})
| 76902fbfb5bdb3357e09a3f47ca397b6abc95eef | [
"Markdown",
"Python"
] | 4 | Python | thebinary/jinjaStore | fdb76fd50953491fe11541ad704c62fe15dc8cf0 | 164bf2bb1e26a9b93227b7a1b54090ca948f5c32 |
refs/heads/master | <file_sep>๏ปฟusing FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using MvcMovie;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace MVCMovie.IntegrationTest
{
//[Collection("SystemCollection")]
public class PingTests
{
//public readonly TestContext Context;
//public PingTests(TestContext context)
//{
// Context = context;
//}
//[Fact]
//public async Task PingReturnsOkResponse()
//{
// var response = await Context.Client.GetAsync("/ping");
// response.EnsureSuccessStatusCode();
// response.StatusCode.Should().Be(HttpStatusCode.OK);
//}
[Fact]
public async Task HomeIndexTest()
{
var builder = new WebHostBuilder()
.UseContentRoot(
@"D:\temp\MvcMovie1\MvcMovie1")
.UseEnvironment("Development")
.UseStartup<Startup>()
.UseApplicationInsights();
TestServer testServer = new TestServer(builder);
HttpClient client = testServer.CreateClient();
HttpResponseMessage response = await client.GetAsync("/");
// Fail the test if non-success result
response.EnsureSuccessStatusCode();
// Get the response as a string
string responseHtml = await response.Content.ReadAsStringAsync();
// Assert on correct content
//Assert.Contains("Home Page", responseHtml);
}
//[Fact]
//public async Task RenderApplicationForm()
//{
// var response = await Context.Client.GetAsync("/");
// response.EnsureSuccessStatusCode();
// var responseString = await response.Content.ReadAsStringAsync();
// //response.StatusCode.Should().Be(HttpStatusCode.OK);
//}
}
}
<file_sep>๏ปฟusing Microsoft.EntityFrameworkCore;
using MvcMovie.Core.Models;
using MvcMovie.Infrastructure.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MvcMovie.Infrastructure
{
public class MoviewOrchestrator : IMoviewOrchestrator
{
private MvcMovieContext _context;
public MoviewOrchestrator(MvcMovieContext context)
{
_context = context;
}
public async Task<List<Movie>> GetAllAsync()
{
return await _context.Movie.ToListAsync();
}
public async Task<List<Movie>> FindAllAsync(string searchString)
{
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return await movies.ToListAsync();
}
public async Task<Tuple<List<string>, List<Movie>>> FindAllAsync(string movieGenre, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> genreQuery = from m in _context.Movie
orderby m.Genre
select m.Genre;
var movies = from m in _context.Movie
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (!String.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
return new Tuple<List<string>, List<Movie>>(await genreQuery.Distinct().ToListAsync(), await movies.ToListAsync());
}
public async Task<Movie> FindAsync(int? id)
{
if (id == null)
{
return null;
}
return await _context.Movie
.SingleOrDefaultAsync(m => m.ID == id);
}
public async Task<int> AddAsync(Movie movie)
{
_context.Add(movie);
return await _context.SaveChangesAsync();
}
public async Task<int> UpdateAsync(int id, Movie movie)
{
try
{
Movie movieOrig = await FindAsync(id);
movieOrig.Title = movie.Title;
//_context.Update(movie);
return await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.ID))
{
return 0;
}
else
{
throw;
}
}
}
public async Task<int> DeleteAsync(int? id)
{
var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
_context.Movie.Remove(movie);
return await _context.SaveChangesAsync();
}
private bool MovieExists(int id)
{
return _context.Movie.Any(e => e.ID == id);
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null) _context.Dispose();
}
}
#endregion
public async Task<IEnumerable<Movie>> GetAsync(
Func<IQueryable<Movie>, IQueryable<Movie>> queryShaper,
CancellationToken cancellationToken
)
{
var query = queryShaper(_context.Movie);
return await query.ToArrayAsync(cancellationToken);
}
public async Task<TResult> GetAsync<TResult>(
Func<IQueryable<Movie>, TResult> queryShaper,
CancellationToken cancellationToken
)
{
var set = _context.Movie;
var query = queryShaper;
var factory = Task<TResult>.Factory;
return await factory.StartNew(() => query(set), cancellationToken);
}
}
}
<file_sep>๏ปฟusing System.Threading.Tasks;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
using MvcMovie.Infrastructure;
using MvcMovie.Controllers;
using Microsoft.EntityFrameworkCore;
using MvcMovie.Infrastructure.Data;
using System;
using MvcMovie.Core.Models;
using System.Collections.Generic;
namespace MVCMovie.Tests.Controller
{
public class MovieControllerShould : IClassFixture<DatabaseFixture>
{
private readonly IMoviewOrchestrator _orchestrator;
private readonly MoviesController _controller;
List<int> _ids = new List<int>();
DatabaseFixture fixture;
public MovieControllerShould(DatabaseFixture fixture)
{
_orchestrator = fixture.Orchestrator;
_controller = fixture.Controller;
_ids = fixture.IDs;
}
[Fact]
public async Task ReturnDataForIndexAsync()
{
//Act
Tuple<List<string>, List<Movie>> tuple = await _orchestrator.FindAllAsync(null, null);
List<Movie> movies = tuple.Item2;
//Assert
Assert.Equal(movies.Count, _ids.Count);
}
[Fact]
public async Task ReturnViewForIndex()
{
//Act
IActionResult result = await _controller.Index(null, null);
//Assert
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task ReturnDataForDetailsOK()
{
//Arrange
int id = _ids[0];
//Act
var movie = await _orchestrator.FindAsync(id);
//Assert
Assert.Equal(id, movie.ID);
}
[Fact]
public async Task ReturnDataForDetailsNotOK()
{
//Arrange
int id = _ids[_ids.Count-1] + 100;
//Act
var movie = await _orchestrator.FindAsync(id);
//Assert
Assert.Null(movie);
}
[Fact]
public async Task ReturnViewForDetailsOk()
{
//Arrange
int? id = _ids[0];
//Act
IActionResult result = await _controller.Details(id);
//Assert
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task ReturnViewForDetailsNotOk()
{
//Arrange
int? id = 0;
//Act
IActionResult result = await _controller.Details(id);
//Assert
Assert.IsType<NotFoundResult>(result);
}
}
}
<file_sep>using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using MvcMovie;
using System;
using System.Net.Http;
using Xunit;
namespace MVCMovie.IntegrationTest
{
public class MVCMoviesShould
{
private TestServer _server;
public HttpClient Client { get; private set; }
public MVCMoviesShould()
{
SetUpClient();
}
private void SetUpClient()
{
_server = new TestServer(new WebHostBuilder()
.UseStartup<Startup>());
Client = _server.CreateClient();
}
[Fact]
public void RenderApplicationForm()
{
int a = 8;
//var response = await Client.GetAsync("/Index");
//response.EnsureSuccessStatusCode();
//var responseString = await response.Content.ReadAsStringAsync();
}
}
}
<file_sep>๏ปฟusing MvcMovie.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MvcMovie.Infrastructure
{
public interface IMoviewOrchestrator //:IDisposable
{
Task<List<Movie>> GetAllAsync();
Task<List<Movie>> FindAllAsync(string searchString);
Task<Tuple<List<string>, List<Movie>>> FindAllAsync(string movieGenre, string searchString);
Task<Movie> FindAsync(int? id);
Task<int> AddAsync(Movie movie);
Task<int> UpdateAsync(int id, Movie movie);
Task<int> DeleteAsync(int? id);
}
}
<file_sep>๏ปฟusing Microsoft.EntityFrameworkCore;
namespace MvcMovie.Infrastructure.Data
{
public class MvcMovieContext : DbContext
{
//ira add to satisfy test
public MvcMovieContext()
{
}
public MvcMovieContext (DbContextOptions<MvcMovieContext> options)
: base(options)
{
}
public DbSet<MvcMovie.Core.Models.Movie> Movie { get; set; }
}
}
<file_sep>๏ปฟusing Microsoft.Net.Http.Headers;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;
using System;
using System.Linq;
using Microsoft.Extensions.Primitives;
namespace MVCMovie.IntegrationTests
{
public class MovieControllerShould : IClassFixture<TestServerFixture<MvcMovie.Startup>>
{
private readonly TestServerFixture<MvcMovie.Startup> _fixture;
public MovieControllerShould(TestServerFixture<MvcMovie.Startup> fixture)
{
_fixture = fixture;
}
[Fact]
public async Task MovieIndexGetTest()
{
var response = await _fixture.Client.GetAsync("/Movies/Index");
// Fail the test if non-success result
response.EnsureSuccessStatusCode();
// Get the response as a string
string responseHtml = await response.Content.ReadAsStringAsync();
// Assert on correct content
Assert.Contains("Index - Movie App", responseHtml);
}
[Fact]
public async Task NotAcceptedCreateWithoutTitle()
{
// Get initial response that contains anti forgery tokens
HttpResponseMessage initialResponse = await _fixture.Client.GetAsync("/Movies/Create");
var antiForgeryValues = await _fixture.ExtractAntiForgeryValues(initialResponse);
// Create POST request, adding anti forgery cookie and form field
HttpRequestMessage postRequest = new HttpRequestMessage(HttpMethod.Post, "/Movies/Create");
postRequest.Headers.Add("Cookie",
new CookieHeaderValue(TestServerFixture<MvcMovie.Startup>.AntiForgeryCookieName,
antiForgeryValues.cookieValue).ToString());
var formData = new Dictionary<string, string>
{
{TestServerFixture<MvcMovie.Startup>.AntiForgeryFieldName, antiForgeryValues.fieldValue},
//{"ID","1" },
//{"Title","" },
{"ReleaseDate","10/12/2016" },
{"Genre","Romantic Comedy" },
{"Price","7.99" },
{"Rating","R" }
};
postRequest.Content = new FormUrlEncodedContent(formData);
HttpResponseMessage postResponse= await _fixture.Client.SendAsync(postRequest);
// Fail the test if non-success result
postResponse.EnsureSuccessStatusCode();
// Get the response as a string
string responseHtml = await postResponse.Content.ReadAsStringAsync();
// Assert on correct content
Assert.Contains("Please provide a title", responseHtml);
}
}
}
<file_sep>๏ปฟusing Microsoft.EntityFrameworkCore;
using MvcMovie.Controllers;
using MvcMovie.Infrastructure;
using MvcMovie.Infrastructure.Data;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace MVCMovie.Tests
{
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
var builder = new DbContextOptionsBuilder<MvcMovieContext>();
builder.UseInMemoryDatabase(Guid.NewGuid().ToString());
var options = builder.Options;
MvcMovieContext dbContext = new MvcMovieContext(options);
dbContext.AddRange(SeedData.AddTestData());
dbContext.SaveChanges();
Orchestrator = new MoviewOrchestrator(dbContext);
Controller = new MoviesController(Orchestrator);
PopulateFromInMemoryIds();
}
private async Task PopulateFromInMemoryIds()
{
var movies = await Orchestrator.GetAllAsync();
IDs = movies.Select(x => x.ID).ToList();
}
public void Dispose()
{
// ... clean up test data from the database ...
Controller.Dispose();
Orchestrator = null;
IDs = null;
}
public IMoviewOrchestrator Orchestrator { get; private set; }
public MoviesController Controller { get; private set; }
public List<int> IDs { get; private set; }
}
}
<file_sep>๏ปฟusing Microsoft.AspNetCore.Mvc;
using Moq;
using MvcMovie.Controllers;
using MvcMovie.Core.Models;
using MvcMovie.Infrastructure;
using MvcMovie.Infrastructure.Data;
using MvcMovie.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace MVCMovie.Tests.Controller
{
public class MovieControllerShouldMoq
{
List<Movie> _movies = new List<Movie>();
public MovieControllerShouldMoq()
{
_movies.AddRange(SeedData.AddTestData());
int id = 1;
foreach(Movie item in _movies)
{
item.ID = id;
id++;
}
}
[Fact]
public async Task Index_ReturnsAViewResult_WithAListOfMovies()
{
// Arrange
var mockRepo = new Mock<IMoviewOrchestrator>();
mockRepo.Setup(repo => repo.FindAllAsync(null,null)).Returns(Task.FromResult(GetTestMoviesWithGenres()));
var controller = new MoviesController(mockRepo.Object);
// Act
var result = await controller.Index(null,null);
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<MovieGenreViewModel>(viewResult.ViewData.Model);
Assert.Equal(4, model.movies.Count());
}
[Fact]
public async Task Edit_Get_ReturnsAViewResult_WithAMovie()
{
// Arrange
var mockRepo = new Mock<IMoviewOrchestrator>();
mockRepo.Setup(repo => repo.FindAsync(1)).Returns(Task.FromResult(_movies[0]));
var controller = new MoviesController(mockRepo.Object);
// Act
var result = await controller.Edit(1);
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<Movie>(
viewResult.ViewData.Model);
Assert.Equal(_movies[0].Title, model.Title);
}
[Fact]
public async Task Edit_Post_ReturnsBadRequestResult_WhenModelStateIsInvalid()
{
// Arrange
var mockRepo = new Mock<IMoviewOrchestrator>();
int updateAsyncResultBad = 0;
var newMovie = _movies[0];
newMovie.Title = "A";
mockRepo.Setup(repo => repo.UpdateAsync(1, newMovie)).Returns(Task.FromResult(updateAsyncResultBad));
var controller = new MoviesController(mockRepo.Object);
controller.ModelState.AddModelError("Title", "Required");
// Act
var result = await controller.Edit(1, newMovie);
// Assert
Assert.IsNotType<RedirectToActionResult>(result);
Assert.IsNotType<NotFoundResult>(result);
mockRepo.Verify();
}
[Fact]
public async Task Edit_Post_ReturnsBadRequestResult_FailedSave()
{
// Arrange
var mockRepo = new Mock<IMoviewOrchestrator>();
var newMovie = _movies[0];
newMovie.Title += " A test";
int updateAsyncResultBad = 0;
mockRepo.Setup(repo => repo.UpdateAsync(1,newMovie)).Returns(Task.FromResult(updateAsyncResultBad));
var controller = new MoviesController(mockRepo.Object);
// Act
var result = await controller.Edit(1, newMovie);
// Assert
Assert.IsType<NotFoundResult>(result);
mockRepo.Verify();
}
[Fact]
public async Task Edit_Post_ReturnsGoodRequestResult()
{
// Arrange
int updateAsyncResultGood = 1;
var mockRepo = new Mock<IMoviewOrchestrator>();
var newMovie = _movies[0];
newMovie.Title += " A test";
mockRepo.Setup(repo => repo.UpdateAsync(1, newMovie)).Returns(Task.FromResult(updateAsyncResultGood));
var controller = new MoviesController(mockRepo.Object);
// Act
var result = await controller.Edit(1, newMovie);
// Assert
var redirectToActionResult = Assert.IsType<RedirectToActionResult>(result);
Assert.Null(redirectToActionResult.ControllerName);
Assert.Equal("Index", redirectToActionResult.ActionName);
mockRepo.Verify();
}
private Tuple<List<string>, List<Movie>> GetTestMoviesWithGenres()
{
var genreQuery = _movies.Select(x => x.Genre).Distinct().ToList();
return new Tuple<List<string>, List<Movie>>(genreQuery, _movies);
}
}
}
<file_sep>๏ปฟusing System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace MVCMovie.IntegrationTests
{
public class HomeControllerShould : IClassFixture<TestServerFixture<MvcMovie.Startup>>
{
private readonly HttpClient _client;
public HomeControllerShould(TestServerFixture<MvcMovie.Startup> fixture)
{
_client = fixture.Client;
}
[Fact]
public async Task IndexGetLoadsHomePage()
{
var response = await _client.GetAsync("/");
// Fail the test if non-success result
response.EnsureSuccessStatusCode();
// Get the response as a string
string responseHtml = await response.Content.ReadAsStringAsync();
// Assert on correct content
Assert.Contains("Home Page", responseHtml);
}
[Fact]
public async Task AboutGetLoadsAboutPage()
{
var response = await _client.GetAsync("/Home/About");
// Fail the test if non-success result
response.EnsureSuccessStatusCode();
// Get the response as a string
string responseHtml = await response.Content.ReadAsStringAsync();
// Assert on correct content
Assert.Contains("Your application description page.", responseHtml);
Assert.Contains("About", responseHtml);
}
}
}
<file_sep>๏ปฟusing Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.PlatformAbstractions;
using MvcMovie;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
namespace MVCMovie.IntegrationTest
{
public class TestContext : IDisposable
{
private TestServer _server;
public HttpClient Client { get; private set; }
public TestContext()
{
SetUpClient();
}
private void SetUpClient()
{
var path = PlatformServices.Default.Application.ApplicationBasePath;
var setDir = Path.GetFullPath(Path.Combine(path, @"" ));
_server = new TestServer(new WebHostBuilder()
.UseContentRoot(@"D:\temp\MvcMovie1\MvcMovie1")
.UseEnvironment("Development")
.UseStartup<Startup>()
.UseApplicationInsights()
//.PreferHostingUrls(false)
//.UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002")
);
Client = _server.CreateClient();
}
public void Dispose()
{
_server?.Dispose();
Client?.Dispose();
}
}
}
| ebcb05c4fb7e457bc234f0b3b64d4a6dcca7f6f6 | [
"C#"
] | 11 | C# | irinaaverin/MVCMovie | 89a7037a315ca32267652d1d181d4cbb1ca1a731 | 267252e9dba9d7a4a80ccc216b1b5a3a6e2343d2 |
refs/heads/master | <repo_name>npnkbabu/hackerrank<file_sep>/problem_solving/Exc.py
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 16:32:42 2020
@author: NAIDU
"""
string = ')()()('
count=0
marks=0
lst=[]
for s in string:
print(s)
if s=='(':
lst.append(s)
elif s== ')':
lst.pop()
print((len(string)-len(lst)) //2)<file_sep>/problem_solving/MyCollections/MyCollections.py
#!/usr/bin/env python
# coding: utf-8
# In[35]:
class Stack:
def __init__(self):
self.lst=[]
def push(self,element):
self.lst.append(element)
print('pushed :',element)
def pop(self):
if self.size() > 0:
s= self.lst.pop()
print('popped : ',s)
return s
else:
return None
def size(self):
return len(self.lst)
def peak(self):
if (len(self.lst) >0):
return self.lst[0]
def __str__(self):
returnstr='stack : '
for x in self.lst:
returnstr += str(x)+' '
return returnstr
# In[33]:
class Queue:
def __init__(self):
print('Queue initialized')
self.lst = []
def enqueue(self,element):
self.lst.append(element)
print('Enqueued : ',element)
def dequeue(self):
if self.size() > 0:
element = self.lst.pop(0)
print('Dequeued : ',element)
return element
else:
return None
def size(self):
return len(self.lst)
def peak(self):
if (len(self.lst) >0):
return self.lst[0]
def __str__(self):
returnstring = 'Queue : '
for x in self.lst:
returnstring += str(x)+' '
return returnstring
# In[36]:
from collections import defaultdict
class Graph:
def __init__(self):
print('Graph instatiated')
self.graph = defaultdict(list)
def addVertex(self,parent,child=None):
if child:
self.graph[parent].append(child)
else:
self.graph[parent].append([])
def __str__(self):
returnstr = ''
for k,v in self.graph.items():
returnstr += str(k)+'-->'+''.join([str(x) for x in v]) + '\r\n'
return returnstr
def getparent(self,root):
for k,v in self.graph.items():
if root in v:
return k
# In[ ]:
| c861f7eb9e932fcb087b4b7676f239a754eb5a7f | [
"Python"
] | 2 | Python | npnkbabu/hackerrank | d63aadae48b6334f9db8e5c6f18bfa4b7123549b | 63426fdb709fadc566c26d7c308339a7105cb03f |
refs/heads/master | <repo_name>andrewdavidmackenzie/rust<file_sep>/depend/Cargo.toml
[package]
name = "depend"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
regex = "0.1.41"
<file_sep>/ffi/Cargo.toml
[package]
name = "embed"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
crate-type = ["dylib"]<file_sep>/hello/Cargo.toml
[package]
name = "hello"
version = "0.0.1"
authors = [ "<NAME> <<EMAIL>>" ]
<file_sep>/ffi/README.md
When I compiled with cargo, it compiled a .rlib file into target, but then I couldn't load this from ruby as a shared library.
Despite me adding this to the Cargo.toml file:
crate-type = ["dylib"]
To get it to work I had to compile using:
rustc src/lib.rs --crate-type=dylib
which compiles a liblib.dylib into the current directory.
I modified the embed.rb from the tutorial (book) to load it thus:
``
module Hello
extend FFI::Library
ffi_lib './liblib.dylib'
attach_function :process, [], :void
end
``<file_sep>/ffi/compare.bash
#!/bin/bash
echo "Native from Ruby"
`time ruby pure_ruby.rb | grep "user"`
echo
echo
echo "Pure Ruby"
`time ruby embed.rb | grep "user"`<file_sep>/philosophers/Cargo.toml
[package]
name = "philosophers"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
<file_sep>/README.md
Just code I have written while studying the basics of rust.
| 05b5d7fa957ebc4f17115fee8fb1d15f4c075d3d | [
"TOML",
"Markdown",
"Shell"
] | 7 | TOML | andrewdavidmackenzie/rust | b83fad61916e7e0ff7ffc63f655a8ca4709deb9a | b5f9992bb4417db01a5db8b2f6de48f00133fe76 |
refs/heads/master | <repo_name>ajayda24/internshala_QuadB_first<file_sep>/app.js
const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const app = express()
//Models
//Controllers
const indexController = require('./controllers/index')
const errorController = require('./controllers/error')
//Routes
const indexRoutes = require('./routes/index')
// Views
app.use(express.static('public'))
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({ extended: false }))
app.use('/', indexRoutes)
app.get('/500', errorController.get500)
app.use(errorController.get404)
app.use((error, req, res, next) => {
res.status(500).render('500', {
pageTitle: 'Error!',
path: '/500',
errorMessage: error
})
})
let port = process.env.PORT
if (port == null || port == '') {
port = 3000
}
app.listen(port, function () {
console.log(`Server started on port ${port}`)
})
<file_sep>/controllers/index.js
const fetch = require('node-fetch')
function objSlice(obj, lastExclusive) {
var filteredKeys = Object.keys(obj).slice(0, lastExclusive)
var newObj = {}
filteredKeys.forEach(function (key) {
newObj[key] = obj[key]
})
return newObj
}
exports.getIndex = async (req, res, next) => {
try {
const result = await fetch('https://api.wazirx.com/api/v2/tickers')
const data = await result.json()
var details = objSlice(data, 10)
res.render('home', {
pageTitle: 'Home Page',
path: '/index',
details: details,
})
} catch (err) {
const error = new Error(err)
error.httpStatusCode = 500
return next(error)
}
}
| a24d448565249bf0c06485846f28ba4e92682742 | [
"JavaScript"
] | 2 | JavaScript | ajayda24/internshala_QuadB_first | 07d3c08024fc6a334166913047bbd1649d8ded1f | eda92cc93e7495e59ff28d5eaa8aa0e103b5479c |
refs/heads/main | <file_sep>#!/bin/bash
DEFAULT_HOST="0.0.0.0"
DEFAULT_PORT="9000"
command="${1}"
function error () {
echo "[ERR] " "${1}"
}
function check () {
if [ -z "${PI_HOLE}" ]; then
error "PI_HOLE is not set."
exit -1
fi
if [ -z "${PASSWORD}" ]; then
error "PASSWORD is not set."
exit -1
fi
if [ -z "${HOST}" ]; then
HOST=${DEFAULT_HOST}
fi
if [ -z "${HOST}" ]; then
error "HOST is not set."
exit -1
fi
if [ -z "${PORT}" ]; then
PORT=${DEFAULT_PORT}
fi
if [ -z "${PORT}" ]; then
error "PORT is not set."
exit -1
fi
}
case "${command}" in
"build")
docker build . -t dontcheck
;;
"start")
check
docker run -e PORT=${PORT} -e HOST=${HOST} -e PI_HOLE=${PI_HOLE} -e PASSWORD=${<PASSWORD>} --mount type=bind,source="$(pwd)",target=/dontcheck --name "dontcheck" -d -p ${PORT}:${PORT} dontcheck
;;
"clean")
docker stop dontcheck
docker rm dontcheck
docker rmi dontcheck
;;
"sh")
docker exec -ti dontcheck bash
;;
*)
;;
esac
<file_sep>FROM ubuntu:20.04
RUN apt-get update
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Asia/Tokyo
RUN apt-get install -y nodejs npm nkf jq curl
RUN npm install -g crontab-ui
RUN mkdir /dontcheck
WORKDIR /dontcheck
ENV PATH=$PATH:/dontcheck
CMD crontab-ui
<file_sep>#!/bin/bash
####
#
# Config
#
####
DEFALUT_PI_HOLE=""
DEFAULT_PASSWORD=""
COOKIE="./cookie.txt"
####
#
# Utilities
#
####
function log () {
echo "[LOG]"
}
function error () {
echo "[ERR]" "${1}"
}
function urlencode () {
echo "${1}" | nkf -WwMQ | tr = %
}
####
#
# Main
#
####
# Login
function login () {
curl -o /dev/null -X POST http://${PI_HOLE}/admin/index.php?login= -d "pw=${PASSWORD}" -d "persistentlogin=on" -s -c ${COOKIE}
}
# Get token
function get_token () {
res=$(mktemp)
curl -b ${COOKIE} -X GET http://${PI_HOLE}/admin/groups-domains.php?type=black -o ${res} -s
token=$(cat ${res} | grep -e '<div id=\"token\".*</div>' | sed -e 's/<div id=\"token\" hidden>//' -e 's/<\/div>//')
rm ${res}
echo $token
}
# Add a domain in blacklist
function add () {
domain="${1}"
token=$(get_token)
curl -b ${COOKIE} -X POST http://${PI_HOLE}/admin/scripts/pi-hole/php/groups.php -d "action=add_domain" -d "domain=${domain}" -d "type=1" -d "comment=" -d "token=${token}"
}
# Delete a domain from the blacklist
function delete () {
domain="${1}"
token=$(get_token)
id=$(lookup $domain)
curl -b ${COOKIE} -X POST http://${PI_HOLE}/admin/scripts/pi-hole/php/groups.php -d "action=delete_domain" -d "id=${id}" -d "token=${token}" -s
}
# Get blacklist
function list () {
token=$(get_token)
curl -b ${COOKIE} -X POST http://${PI_HOLE}/admin/scripts/pi-hole/php/groups.php -d "action=get_domains" -d "showtype=black" -d "token=${token}" -s
}
# logout
function logout () {
curl -b ${COOKIE} -X GET http://${PI_HOLE}/admin/index.php?logout= -s
}
# Clean
function clean () {
rm ${COOKIE}
}
function lookup () {
domain="${1}"
ret=$(list)
echo "${ret}" | jq ".data[] | select(.domain == \"${domain}\") | .id"
}
function usage () {
echo "..."
}
# Set PI_HOLE
if [ -z "${PI_HOLE}" ]; then
PI_HOLE=${DEFAULT_PI_HOLE}
fi
if [ -z "${PI_HOLE}" ]; then
error 'You need to specify $PI_HOLE.'
exit -1
fi
# Set PASSWORD
if [ -z "${PASSWORD}" ]; then
PASSWORD=${<PASSWORD>}
fi
PASSWORD=$(urlencode ${PASSWORD})
if [ -z "${PASSWORD}" ]; then
error 'You need to specify $PASSWORD.'
exit -1
fi
command=${1}
if [ -z "${command}" ]; then
usage
exit -1
fi
case ${command} in
"add")
if [ -z "${2}" ]; then
usage
exit -1
fi
add "${2}"
;;
"delete")
if [ -z "${2}" ]; then
usage
exit -1
fi
delete "${2}"
;;
"list")
list
;;
"lookup")
if [ -z "${2}" ]; then
usage
exit -1
fi
lookup "${2}"
;;
"login")
login
;;
"logout")
logout
clean
;;
"get_token")
get_token
;;
"clean")
clean
;;
*)
;;
esac
<file_sep># Dontcheck
Dontcheck is a script for making you stop to check services like Twitter and Youtube, achiving it with Pi-Hole.
Pi-Hole provides functionalities to determine wether some domains can be resolved or not. Dontcheck requests Pi-Hole for adding or deleting domains that you don't check. Also, Dontcheck provides crontab-ui so that you can make config for cron without access to console.
# Setup
You need to set up Pi-Hole beforehand. See https://pi-hole.net/.
When staring Dontcheck, you can/need to set some values:
* (MUST) PI_HOLE
- Host running Pi-Hole
- Example: `192.168.0.2:8080`
* (MUST) PASSWORD
- Password to login Pi-Hole
- Example: `<PASSWORD>`
* (OPTION) HOST
- Host running crontab-ui
- Example: `192.168.0.1`
- Default: `0.0.0.0`
* (OPTION) PORT
- Port number providing access to crontab-ui
- Example: `8080`
- Default: `9000`
`service.sh` is a script for setup. See it for more detail. You need to build an image for Dontcheck and start a container with the image.
```
$ ./service.sh build
$ PI_HOLE=192.168.0.2:8080 PASSWORD=<PASSWORD> ./service.sh start
```
Visit the crontab-ui to confirm that the container is running.
# Commands
`dck` is a script to control Pi-Hole with sub commands below:
* login
- Login and get cookie as a file "cookie.txt"
- You need to login before requesting add/delete domains
- Example: `$ dck login`
* logout
- Logout and remove "cookie.txt"
- Example: `$ dck logout`
* add <domain>
- Add domain that you don't want to check
- Example: `$ dck add twitter.com`
* delete <domain>
- Delete domain from the blacklist
- Example: `$ dck delete twitter.com`
You can run `dck` via console but it is sometimes pain. I recommend that you make configuration of crontab via crontab-ui. Note that `dck` need "cookie.txt" for adding/deleting domains. So the command in crontab should be `dck login && dck add twitter.com && dck logout`.
| 3da9c90455483e1ba6897c36fac7b08726139da8 | [
"Markdown",
"Dockerfile",
"Shell"
] | 4 | Shell | mhorii/dontcheck | 73e70d53874cfd9fb842a9c6cb763845a2661d9b | 54107689904a6ccc56ff1f9308cd30665910e912 |
refs/heads/master | <file_sep>package com.hoxwi.android.sample.resumedetail;
import android.support.annotation.NonNull;
import com.hoxwi.android.sample.data.IResumesDataSource;
import com.hoxwi.android.sample.data.Resume;
import com.hoxwi.android.sample.data.ResumesRepository;
/**
* Created by Cezar on 6/12/2017.
*/
public class ResumeDetailPresenter implements ResumeDetailContract.Presenter{
private ResumesRepository mRepository;
private ResumeDetailContract.View mView;
private String mResumeId;
public ResumeDetailPresenter(@NonNull ResumesRepository mRepository, @NonNull ResumeDetailContract.View mView, @NonNull String resumeId) {
this.mRepository = mRepository;
this.mView = mView;
this.mResumeId = resumeId;
this.mView.setPresenter(this);
}
@Override
public void start() {
mRepository.getResume(mResumeId, new IResumesDataSource.GetResumeCallback() {
@Override
public void onResumeLoaded(Resume resume) {
mView.showResume(resume.getName(), resume.getJobTitle(), resume.getBio());
}
@Override
public void onDataNotAvailable() {
mView.showMessage("Error while fetching the resume.");
}
});
}
@Override
public void deleteResume() {
mRepository.deleteResume(mResumeId, new IResumesDataSource.DeleteResumeCallback() {
@Override
public void onResumeDeleted() {
mView.showResumesList();
}
@Override
public void onError() {
mView.showMessage("Error while deleting the resume.");
}
});
}
}
<file_sep>package com.hoxwi.android.sample.data;
import com.google.gson.annotations.SerializedName;
/**
* Created by Cezar on 22/11/2017.
*/
public class Resume {
@SerializedName("_id")
private String id;
private String name;
private String jobTitle;
private String bio;
public Resume() {
}
public Resume(String name, String jobTitle, String bio) {
this(null, name, jobTitle, bio);
}
public Resume(String id, String name, String jobTitle, String bio) {
this.id = id;
this.name = name;
this.jobTitle = jobTitle;
this.bio = bio;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
}
<file_sep>package com.hoxwi.android.sample.addresume;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.hoxwi.android.sample.R;
public class AddResumeFragment extends Fragment implements AddResumeContract.View {
private AddResumeContract.Presenter mPresenter;
public AddResumeFragment() {
// Required empty public constructor
}
public static AddResumeFragment newInstance() {
AddResumeFragment fragment = new AddResumeFragment();
return fragment;
}
@Override
public void setPresenter(AddResumeContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public boolean isActive() {
return isAdded();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_add_resume, container, false);
Button okButton = root.findViewById(R.id.addResumeOkButton);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText nameEditText = root.findViewById(R.id.addResumeNameEditText);
EditText jobTitleEditText = root.findViewById(R.id.addResumeJobTitleEditText);
EditText bioEditText = root.findViewById(R.id.addResumeBioEditText);
mPresenter.saveResume(nameEditText.getText().toString(),
jobTitleEditText.getText().toString(),
bioEditText.getText().toString());
}
});
return root;
}
@Override
public void showMessage(String msg) {
Snackbar.make(getView(), msg, Snackbar.LENGTH_LONG).show();
}
@Override
public void showSaveError(String msg) {
Snackbar.make(getView(), msg, Snackbar.LENGTH_LONG).show();
}
@Override
public void showResumesList() {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
}
<file_sep>package com.hoxwi.android.sample.data.remote;
import com.hoxwi.android.sample.data.Resume;
import java.util.List;
/**
* Created by Cezar on 19/12/2017.
*/
public class HoxWiResponseBody {
private Boolean success;
private String header;
private String result;
private String error;
private String message;
private List<Resume> results;
public HoxWiResponseBody() {
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Resume> getResults() {
return results;
}
public void setResults(List<Resume> results) {
this.results = results;
}
}
<file_sep>package com.hoxwi.android.sample.constants;
/**
* Created by Cezar on 29/11/2017.
*/
public class Messages {
public static final String RESUME_SUCCESSFULLY_SAVED = "Resume successfully saved!";
public static final String ERROR_LOADING_RESUMES = "An error occurred while loading resumes.";
}
<file_sep># HR-Heroes-Android
<file_sep>package com.hoxwi.android.sample.data.remote;
import android.support.annotation.NonNull;
import com.hoxwi.android.sample.BuildConfig;
import com.hoxwi.android.sample.data.Resume;
import com.hoxwi.android.sample.data.IResumesDataSource;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Cezar on 24/11/2017.
*/
public class ResumesRemoteDataSource implements IResumesDataSource {
private static ResumesRemoteDataSource INSTANCE = null;
private HoxWiService mHoxWiService;
private ResumesRemoteDataSource(){
this.mHoxWiService = new Retrofit.Builder()
.baseUrl(HoxWiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(HoxWiService.class);
}
public static ResumesRemoteDataSource getInstance(){
if(INSTANCE == null) {
INSTANCE = new ResumesRemoteDataSource();
}
return INSTANCE;
}
@Override
public void loadResumes(@NonNull final LoadResumesCallback loadResumesCallback) {
HoxWiRequestBody body = buildRequestBody(new HashMap<>());
Call<HoxWiResponseBody> call = mHoxWiService.searchResumes(body);
call.enqueue(new Callback<HoxWiResponseBody>() {
@Override
public void onResponse(Call<HoxWiResponseBody> call, Response<HoxWiResponseBody> response) {
loadResumesCallback.onResumesLoaded(response.body().getResults());
}
@Override
public void onFailure(Call<HoxWiResponseBody> call, Throwable t) {
loadResumesCallback.onDataNotAvailable();
}
});
}
@Override
public void getResume(@NonNull String id, @NonNull final GetResumeCallback getResumeCallback) {
Resume document = new Resume();
document.setId(id);
HoxWiRequestBody body = buildRequestBody(document);
Call<HoxWiResponseBody> call = mHoxWiService.searchResumes(body);
call.enqueue(new Callback<HoxWiResponseBody>() {
@Override
public void onResponse(Call<HoxWiResponseBody> call, Response<HoxWiResponseBody> response) {
List<Resume> results = response.body().getResults();
if(results == null || results.size() == 0){
getResumeCallback.onDataNotAvailable();
return;
}
getResumeCallback.onResumeLoaded(results.get(0));
}
@Override
public void onFailure(Call<HoxWiResponseBody> call, Throwable t) {
getResumeCallback.onDataNotAvailable();
}
});
}
@Override
public void addResume(@NonNull final Resume resume, @NonNull final AddResumeCallback addResumeCallback) {
HoxWiRequestBody body = buildRequestBody(resume);
Call<HoxWiResponseBody> call = mHoxWiService.addResume(body);
call.enqueue(new Callback<HoxWiResponseBody>() {
@Override
public void onResponse(Call<HoxWiResponseBody> call, Response<HoxWiResponseBody> response) {
HoxWiResponseBody hoxWiResponse = response.body();
if(! hoxWiResponse.getSuccess()){
addResumeCallback.onError();
return;
}
resume.setId(hoxWiResponse.getResult());
addResumeCallback.onResumeAdded(resume);
}
@Override
public void onFailure(Call<HoxWiResponseBody> call, Throwable t) {
addResumeCallback.onError();
}
});
}
@Override
public void deleteResume(@NonNull String id, @NonNull final DeleteResumeCallback deleteResumeCallback) {
Resume document = new Resume();
document.setId(id);
HoxWiRequestBody body = buildRequestBody(document);
Call<HoxWiResponseBody> call = mHoxWiService.deleteResume(body);
call.enqueue(new Callback<HoxWiResponseBody>() {
@Override
public void onResponse(Call<HoxWiResponseBody> call, Response<HoxWiResponseBody> response) {
HoxWiResponseBody hoxWiResponse = response.body();
if(! hoxWiResponse.getSuccess()){
deleteResumeCallback.onError();
return;
}
deleteResumeCallback.onResumeDeleted();
}
@Override
public void onFailure(Call<HoxWiResponseBody> call, Throwable t) {
deleteResumeCallback.onError();
}
});
}
private HoxWiRequestBody buildRequestBody(Object document){
HoxWiRequestBody body = new HoxWiRequestBody.Builder()
.secretKey(BuildConfig.HOX_WI_SECRET_KEY)
.container(HoxWiService.CONTAINER)
.document(document)
.build();
return body;
}
}
<file_sep>package com.hoxwi.android.sample.resumes;
import android.app.Activity;
import android.support.annotation.NonNull;
import com.hoxwi.android.sample.constants.Messages;
import com.hoxwi.android.sample.data.Resume;
import com.hoxwi.android.sample.data.IResumesDataSource;
import com.hoxwi.android.sample.data.ResumesRepository;
import java.util.List;
/**
* Created by Cezar on 22/11/2017.
*/
public class ResumesPresenter implements ResumesContract.Presenter {
private final ResumesRepository mRepository;
private final ResumesContract.View mView;
public ResumesPresenter(@NonNull ResumesRepository mResumesRepository, @NonNull ResumesContract.View mResumesView) {
this.mRepository = mResumesRepository;
this.mView = mResumesView;
this.mView.setPresenter(this);
}
@Override
public void start() {
loadResumes();
}
@Override
public void loadResumes() {
mView.setLoadingIndicator(true);
mRepository.loadResumes(new IResumesDataSource.LoadResumesCallback() {
@Override
public void onResumesLoaded(List<Resume> resumes) {
if(mView.isActive()){
mView.showResumes(resumes);
mView.setLoadingIndicator(false);
}
}
@Override
public void onDataNotAvailable() {
if(mView.isActive()){
mView.showMessage(Messages.ERROR_LOADING_RESUMES);
mView.setLoadingIndicator(false);
}
}
});
}
@Override
public void addNewResume() {
mView.showAddResume();
}
@Override
public void deleteResume(final int position, Resume resume) {
mRepository.deleteResume(resume.getId(), new IResumesDataSource.DeleteResumeCallback() {
@Override
public void onResumeDeleted() {
mView.remove(position);
}
@Override
public void onError() {
mView.showMessage("An error occurred.");
}
});
}
@Override
public void openResumeDetails(@NonNull Resume requestedResume) {
mView.showResumeDetails(requestedResume.getId());
}
}
<file_sep>package com.hoxwi.android.sample.addresume;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.hoxwi.android.sample.R;
import com.hoxwi.android.sample.util.Injection;
public class AddResumeActivity extends AppCompatActivity {
private AddResumeContract.Presenter mAddResumePresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_resume);
AddResumeFragment addResumeFragment =
(AddResumeFragment) getSupportFragmentManager().findFragmentById(R.id.addResumeContentFrame);
if (addResumeFragment == null) {
// Create the fragment
addResumeFragment = AddResumeFragment.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.addResumeContentFrame, addResumeFragment).commit();
}
// Create the presenter
mAddResumePresenter = new AddResumePresenter(Injection.provideResumesRepository(), addResumeFragment);
}
}
<file_sep>package com.hoxwi.android.sample.resumedetail;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.hoxwi.android.sample.R;
import com.hoxwi.android.sample.addresume.AddResumeFragment;
import com.hoxwi.android.sample.addresume.AddResumePresenter;
import com.hoxwi.android.sample.util.Injection;
public class ResumeDetailActivity extends AppCompatActivity {
private ResumeDetailContract.Presenter mPresenter;
static public final String RESUME_ID_INTENT_KEY = "RESUME_ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resume_detail);
ResumeDetailFragment resumeDetailFragment =
(ResumeDetailFragment) getSupportFragmentManager().findFragmentById(R.id.resumeDetailContentFrame);
if (resumeDetailFragment == null) {
// Create the fragment
resumeDetailFragment = ResumeDetailFragment.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.resumeDetailContentFrame, resumeDetailFragment).commit();
}
String resumeId = getIntent().getStringExtra(RESUME_ID_INTENT_KEY);
// Create the presenter
mPresenter = new ResumeDetailPresenter(Injection.provideResumesRepository(), resumeDetailFragment, resumeId);
}
}
<file_sep>package com.hoxwi.android.sample.components;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
/**
* Created by Cezar on 4/12/2017.
*/
public class RecyclerViewEmptySupport extends RecyclerView {
private View mEmptyView;
private AdapterDataObserver mDataObserver = new AdapterDataObserver() {
@Override
public void onChanged() {
Adapter<?> adapter = getAdapter();
if(adapter == null || mEmptyView == null) {
return;
}
if(adapter.getItemCount() == 0) {
mEmptyView.setVisibility(View.VISIBLE);
RecyclerViewEmptySupport.this.setVisibility(View.GONE);
} else {
mEmptyView.setVisibility(View.GONE);
RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
}
}
};
public RecyclerViewEmptySupport(Context context) {
super(context);
}
public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(Adapter adapter) {
super.setAdapter(adapter);
if(adapter != null) {
adapter.registerAdapterDataObserver(mDataObserver);
}
mDataObserver.onChanged();
}
public void setEmptyView(View mEmptyView) {
this.mEmptyView = mEmptyView;
}
}
<file_sep>package com.hoxwi.android.sample.resumes;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hoxwi.android.sample.R;
import com.hoxwi.android.sample.addresume.AddResumeActivity;
import com.hoxwi.android.sample.components.RecyclerViewEmptySupport;
import com.hoxwi.android.sample.data.Resume;
import com.hoxwi.android.sample.resumedetail.ResumeDetailActivity;
import java.util.ArrayList;
import java.util.List;
public class ResumesFragment extends Fragment implements ResumesContract.View, ResumesAdapter.ResumeItemListener {
private ResumesContract.Presenter mPresenter;
private ResumesAdapter mAdapter;
private SwipeRefreshLayout mResumesSwipeRefreshLayout;
private RecyclerViewEmptySupport mResumesRecyclerView;
public ResumesFragment() {
}
public static ResumesFragment newInstance() {
return new ResumesFragment();
}
@Override
public void setPresenter(ResumesContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
mPresenter.start();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_resumes, null);
mResumesSwipeRefreshLayout = root.findViewById(R.id.resumesSwipeRefreshLayout);
mResumesRecyclerView = root.findViewById(R.id.resumesRecyclerView);
mResumesRecyclerView.setHasFixedSize(false);
mResumesRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
TextView mNoResultsTextView = root.findViewById(R.id.noResultsTextView);
mResumesRecyclerView.setEmptyView(mNoResultsTextView);
mAdapter = new ResumesAdapter(null, this);
mResumesRecyclerView.setAdapter(mAdapter);
mResumesSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mPresenter.loadResumes();
}
});
FloatingActionButton fab = getActivity().findViewById(R.id.fab_add_resume);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.addNewResume();
}
});
return root;
}
@Override
public boolean isActive() {
return isAdded();
}
@Override
public void setLoadingIndicator(final boolean active) {
if (getView() == null) {
return;
}
final SwipeRefreshLayout srl = getView().findViewById(R.id.resumesSwipeRefreshLayout);
// Make sure setRefreshing() is called after the layout is done with everything else.
srl.post(new Runnable() {
@Override
public void run() {
srl.setRefreshing(active);
}
});
}
@Override
public void showResumes(List<Resume> resumes) {
mAdapter.replaceData(resumes);
}
@Override
public void showAddResume() {
Intent intent = new Intent(getContext(), AddResumeActivity.class);
startActivity(intent);
}
@Override
public void showResumeDetails(String resumeId) {
Intent intent = new Intent(getContext(), ResumeDetailActivity.class);
intent.putExtra(ResumeDetailActivity.RESUME_ID_INTENT_KEY, resumeId);
startActivity(intent);
}
@Override
public void remove(int position) {
mAdapter.removeItem(position);
}
@Override
public void showMessage(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show();
}
@Override
public void onResumeClick(Resume clickedResume) {
mPresenter.openResumeDetails(clickedResume);
}
@Override
public void onDeleteResumeClick(int position, Resume resume) {
mPresenter.deleteResume(position, resume);
}
}
<file_sep>package com.hoxwi.android.sample.data.remote;
/**
* Created by Cezar on 19/12/2017.
*/
public class HoxWiRequestBody {
private String secretkey;
private String container;
private String storageType;
private Object document;
private String orderby;
private Integer limit;
public HoxWiRequestBody() {
}
public String getSecretkey() {
return secretkey;
}
public void setSecretkey(String secretkey) {
this.secretkey = secretkey;
}
public String getContainer() {
return container;
}
public void setContainer(String container) {
this.container = container;
}
public String getStorageType() {
return storageType;
}
public void setStorageType(String storageType) {
this.storageType = storageType;
}
public Object getDocument() {
return document;
}
public void setDocument(Object document) {
this.document = document;
}
public String getOrderby() {
return orderby;
}
public void setOrderby(String orderby) {
this.orderby = orderby;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public static final class Builder {
private final HoxWiRequestBody body = new HoxWiRequestBody();
public Builder() {
}
public Builder secretKey(String secretKey){
body.setSecretkey(secretKey);
return this;
}
public Builder container(String container){
body.setContainer(container);
return this;
}
public Builder storageType(String storageType){
body.setStorageType(storageType);
return this;
}
public Builder document(Object document){
body.setDocument(document);
return this;
}
public Builder orderby(String orderby){
body.setOrderby(orderby);
return this;
}
public Builder limit(Integer limit){
body.setLimit(limit);
return this;
}
public HoxWiRequestBody build(){
return body;
}
}
}
| f37a8289d4352b2d2ee2464fb5f3b559ff370e91 | [
"Markdown",
"Java"
] | 13 | Java | HoxWi/HR-Heroes-Android | b31608ffa6bf27b5cb6df402bca3c57ed76e1699 | 9a126be1a0a86478ad1ef48c7af5a6ea5b3daada |
refs/heads/master | <file_sep>class VaultError(Exception):
def __init__(self, message=None, errors=None, method=None, url=None):
if errors:
message = ", ".join(errors)
self.errors = errors
self.method = method
self.url = url
super().__init__(message)
def __str__(self):
return f"{self.args[0]}, on {self.method} {self.url}"
class InvalidRequest(VaultError):
pass
class Unauthorized(VaultError):
pass
class Forbidden(VaultError):
pass
class InvalidPath(VaultError):
pass
class RateLimitExceeded(VaultError):
pass
class InternalServerError(VaultError):
pass
class VaultNotInitialized(VaultError):
pass
class VaultDown(VaultError):
pass
class UnexpectedError(VaultError):
pass
class BadGateway(VaultError):
pass
class ParamValidationError(VaultError):
pass
<file_sep>import logging
from unittest import TestCase, skipIf
from hvac import exceptions
from tests import utils
from tests.utils.hvac_integration_test_case import HvacIntegrationTestCase
class IntegrationTest(HvacIntegrationTestCase, TestCase):
def setUp(self):
super().setUp()
if "secret/" not in self.client.sys.list_mounted_secrets_engines()["data"]:
self.client.sys.enable_secrets_engine(
backend_type="kv",
path="secret",
options=dict(version=1),
)
def test_generic_secret_backend(self):
self.client.write("secret/foo", zap="zip")
result = self.client.read("secret/foo")
assert result["data"]["zap"] == "zip"
self.client.delete("secret/foo")
def test_list_directory(self):
self.client.write("secret/test-list/bar/foo", value="bar")
self.client.write("secret/test-list/foo", value="bar")
result = self.client.list("secret/test-list")
assert result["data"]["keys"] == ["bar/", "foo"]
self.client.delete("secret/test-list/bar/foo")
self.client.delete("secret/test-list/foo")
def test_write_with_response(self):
if "transit/" in self.client.sys.list_mounted_secrets_engines()["data"]:
self.client.sys.disable_secrets_engine("transit")
self.client.sys.enable_secrets_engine("transit")
plaintext = "test"
self.client.write("transit/keys/foo")
result = self.client.write("transit/encrypt/foo", plaintext=plaintext)
ciphertext = result["data"]["ciphertext"]
result = self.client.write("transit/decrypt/foo", ciphertext=ciphertext)
assert result["data"]["plaintext"] == plaintext
def test_read_nonexistent_key(self):
assert not self.client.read("secret/I/dont/exist")
def test_auth_token_manipulation(self):
result = self.client.create_token(lease="1h", renewable=True)
assert result["auth"]["client_token"]
lookup = self.client.lookup_token(result["auth"]["client_token"])
assert result["auth"]["client_token"] == lookup["data"]["id"]
renew = self.client.renew_token(lookup["data"]["id"])
assert result["auth"]["client_token"] == renew["auth"]["client_token"]
self.client.revoke_token(lookup["data"]["id"])
try:
lookup = self.client.lookup_token(result["auth"]["client_token"])
assert False
except exceptions.Forbidden:
assert True
except exceptions.InvalidPath:
assert True
except exceptions.InvalidRequest:
assert True
def test_self_auth_token_manipulation(self):
result = self.client.create_token(lease="1h", renewable=True)
assert result["auth"]["client_token"]
self.client.token = result["auth"]["client_token"]
lookup = self.client.lookup_token(result["auth"]["client_token"])
assert result["auth"]["client_token"] == lookup["data"]["id"]
renew = self.client.renew_self_token()
assert result["auth"]["client_token"] == renew["auth"]["client_token"]
self.client.revoke_token(lookup["data"]["id"])
try:
lookup = self.client.lookup_token(result["auth"]["client_token"])
assert False
except exceptions.Forbidden:
assert True
except exceptions.InvalidPath:
assert True
except exceptions.InvalidRequest:
assert True
def test_userpass_auth(self):
if "userpass/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method("userpass")
self.client.sys.enable_auth_method("userpass")
self.client.write(
"auth/userpass/users/testuser", password="<PASSWORD>", policies="not_root"
)
result = self.client.auth_userpass("testuser", "testpass")
assert self.client.token == result["auth"]["client_token"]
assert self.client.is_authenticated()
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method("userpass")
def test_create_userpass(self):
if "userpass/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("userpass")
self.client.create_userpass(
"testcreateuser", "testcreateuserpass", policies="not_root"
)
result = self.client.auth_userpass("testcreateuser", "<PASSWORD>")
assert self.client.token == result["auth"]["client_token"]
assert self.client.is_authenticated()
# Test ttl:
self.client.token = self.manager.root_token
self.client.create_userpass(
"testcreateuser", "<PASSWORD>createuserpass", policies="not_root", ttl="10s"
)
self.client.token = result["auth"]["client_token"]
result = self.client.auth_userpass("testcreateuser", "<PASSWORD>")
assert result["auth"]["lease_duration"] == 10
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method("userpass")
def test_list_userpass(self):
if "userpass/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("userpass")
# add some users and confirm that they show up in the list
self.client.create_userpass(
"testuserone", "<PASSWORD>", policies="not_root"
)
self.client.create_userpass(
"testusertwo", "<PASSWORD>", policies="not_root"
)
user_list = self.client.list_userpass()
assert "testuserone" in user_list["data"]["keys"]
assert "testusertwo" in user_list["data"]["keys"]
# delete all the users and confirm that list_userpass() doesn't fail
for user in user_list["data"]["keys"]:
self.client.delete_userpass(user)
no_users_list = self.client.list_userpass()
assert no_users_list is None
def test_read_userpass(self):
if "userpass/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("userpass")
# create user to read
self.client.create_userpass("readme", "<PASSWORD>", policies="not_root")
# test that user can be read
read_user = self.client.read_userpass("readme")
assert "not_root" in read_user["data"]["policies"]
# teardown
self.client.sys.disable_auth_method("userpass")
def test_update_userpass_policies(self):
if "userpass/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("userpass")
# create user and then update its policies
self.client.create_userpass(
"updatemypolicies", "<PASSWORD>", policies="not_root"
)
self.client.update_userpass_policies(
"updatemypolicies", policies="somethingelse"
)
# test that policies have changed
updated_user = self.client.read_userpass("updatemypolicies")
assert "somethingelse" in updated_user["data"]["policies"]
# teardown
self.client.sys.disable_auth_method("userpass")
def test_update_userpass_password(self):
if "userpass/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("userpass")
# create user and then change its password
self.client.create_userpass("changeme", "<PASSWORD>", policies="not_root")
self.client.update_userpass_password("<PASSWORD>", "<PASSWORD>")
# test that new password authenticates user
result = self.client.auth_userpass("changeme", "<PASSWORD>")
assert self.client.token == result["auth"]["client_token"]
assert self.client.is_authenticated()
# teardown
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method("userpass")
def test_delete_userpass(self):
if "userpass/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("userpass")
self.client.create_userpass(
"testcreateuser", "<PASSWORD>", policies="not_root"
)
result = self.client.auth_userpass("testcreateuser", "<PASSWORD>pass")
assert self.client.token == result["auth"]["client_token"]
assert self.client.is_authenticated()
self.client.token = self.manager.root_token
self.client.delete_userpass("<PASSWORD>")
self.assertRaises(
exceptions.InvalidRequest,
self.client.auth_userpass,
"testcreateuser",
"<PASSWORD>pass",
)
def test_app_id_auth(self):
if "app-id/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method("app-id")
self.client.sys.enable_auth_method("app-id")
self.client.write("auth/app-id/map/app-id/foo", value="not_root")
self.client.write("auth/app-id/map/user-id/bar", value="foo")
result = self.client.auth_app_id("foo", "bar")
assert self.client.token == result["auth"]["client_token"]
assert self.client.is_authenticated()
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method("app-id")
def test_create_app_id(self):
if "app-id/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("app-id")
self.client.create_app_id(
"testappid", policies="not_root", display_name="displayname"
)
result = self.client.read("auth/app-id/map/app-id/testappid")
lib_result = self.client.get_app_id("testappid")
del result["request_id"]
del lib_result["request_id"]
assert result == lib_result
assert result["data"]["key"] == "testappid"
assert result["data"]["display_name"] == "displayname"
assert result["data"]["value"] == "not_root"
self.client.delete_app_id("testappid")
assert self.client.get_app_id("testappid")["data"] is None
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method("app-id")
def test_create_user_id(self):
if "app-id/" not in self.client.sys.list_auth_methods()["data"]:
self.client.sys.enable_auth_method("app-id")
self.client.create_app_id(
"testappid", policies="not_root", display_name="displayname"
)
self.client.create_user_id("testuserid", app_id="testappid")
result = self.client.read("auth/app-id/map/user-id/testuserid")
lib_result = self.client.get_user_id("testuserid")
del result["request_id"]
del lib_result["request_id"]
assert result == lib_result
assert result["data"]["key"] == "testuserid"
assert result["data"]["value"] == "testappid"
result = self.client.auth_app_id("testappid", "testuserid")
assert self.client.token == result["auth"]["client_token"]
assert self.client.is_authenticated()
self.client.token = self.manager.root_token
self.client.delete_user_id("testuserid")
assert self.client.get_user_id("testuserid")["data"] is None
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method("app-id")
def test_missing_token(self):
client = utils.create_client()
assert not client.is_authenticated()
def test_invalid_token(self):
client = utils.create_client(token="not-a-real-token")
assert not client.is_authenticated()
def test_illegal_token(self):
client = utils.create_client(token="<PASSWORD>")
try:
client.is_authenticated()
except ValueError as e:
assert "Invalid header value" in str(e)
def test_broken_token(self):
client = utils.create_client(token="\x1b")
try:
client.is_authenticated()
except exceptions.InvalidRequest as e:
assert "invalid header value" in str(e)
def test_client_authenticated(self):
assert self.client.is_authenticated()
def test_client_logout(self):
self.client.logout()
assert not self.client.is_authenticated()
def test_client_logout_and_revoke(self):
# create a new token
result = self.client.auth.token.create(ttl="1h", renewable=True)
# set the token
self.client.token = result["auth"]["client_token"]
# logout and revoke the token
self.client.logout(revoke_token=True)
# set the original token back
self.client.token = result["auth"]["client_token"]
# confirm that it no longer is able to authenticate
assert not self.client.is_authenticated()
def test_revoke_self_token(self):
if "userpass/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method("userpass")
self.client.sys.enable_auth_method("userpass")
self.client.write(
"auth/userpass/users/testuser", password="<PASSWORD>", policies="not_root"
)
self.client.auth_userpass("testuser", "test<PASSWORD>")
self.client.revoke_self_token()
assert not self.client.is_authenticated()
def test_gh51(self):
key = "secret/http://test.com"
self.client.write(key, foo="bar")
result = self.client.read(key)
assert result["data"]["foo"] == "bar"
def test_token_accessor(self):
# Create token, check accessor is provided
result = self.client.create_token(lease="1h")
token_accessor = result["auth"].get("accessor", None)
assert token_accessor
# Look up token by accessor, make sure token is excluded from results
lookup = self.client.lookup_token(token_accessor, accessor=True)
assert lookup["data"]["accessor"] == token_accessor
assert not lookup["data"]["id"]
# Revoke token using the accessor
self.client.revoke_token(token_accessor, accessor=True)
# Look up by accessor should fail
with self.assertRaises(exceptions.InvalidRequest):
lookup = self.client.lookup_token(token_accessor, accessor=True)
# As should regular lookup
with self.assertRaises(exceptions.Forbidden):
lookup = self.client.lookup_token(result["auth"]["client_token"])
def test_create_token_explicit_max_ttl(self):
token = self.client.create_token(ttl="30m", explicit_max_ttl="5m")
assert token["auth"]["client_token"]
assert token["auth"]["lease_duration"] == 300
# Validate token
lookup = self.client.lookup_token(token["auth"]["client_token"])
assert token["auth"]["client_token"] == lookup["data"]["id"]
def test_create_token_max_ttl(self):
token = self.client.create_token(ttl="5m")
assert token["auth"]["client_token"]
assert token["auth"]["lease_duration"] == 300
# Validate token
lookup = self.client.lookup_token(token["auth"]["client_token"])
assert token["auth"]["client_token"] == lookup["data"]["id"]
def test_create_token_periodic(self):
token = self.client.create_token(period="30m")
assert token["auth"]["client_token"]
assert token["auth"]["lease_duration"] == 1800
# Validate token
lookup = self.client.lookup_token(token["auth"]["client_token"])
assert token["auth"]["client_token"] == lookup["data"]["id"]
assert lookup["data"]["period"] == 1800
def test_token_roles(self):
# No roles, list_token_roles == None
before = self.client.list_token_roles()
assert not before
# Create token role
assert self.client.create_token_role("testrole").status_code == 204
# List token roles
during = self.client.list_token_roles()["data"]["keys"]
assert len(during) == 1
assert during[0] == "testrole"
# Delete token role
self.client.delete_token_role("testrole")
# No roles, list_token_roles == None
after = self.client.list_token_roles()
assert not after
def test_create_token_w_role(self):
# Create policy
self.prep_policy("testpolicy")
# Create token role w/ policy
assert (
self.client.create_token_role(
"testrole", allowed_policies="testpolicy"
).status_code
== 204
)
# Create token against role
token = self.client.create_token(lease="1h", role="testrole")
assert token["auth"]["client_token"]
assert token["auth"]["policies"] == ["default", "testpolicy"]
# Cleanup
self.client.delete_token_role("testrole")
self.client.sys.delete_policy("testpolicy")
def test_auth_gcp_alternate_mount_point_with_no_client_token_exception(self):
test_mount_point = "gcp-custom-path"
# Turn on the gcp backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("gcp", path=test_mount_point)
# Drop the client's token to replicate a typical end user's use of any auth method.
# I.e., its reasonable to expect the method is being called to _retrieve_ a token in the first place.
self.client.token = None
# Load a mock JWT stand in for a real document from GCP.
with open(utils.get_config_file_path("example.jwt")) as fp:
jwt = fp.read()
# When attempting to auth (POST) to an auth backend mounted at a different path than the default, we expect a
# generic 'missing client token' response from Vault.
with self.assertRaises(exceptions.InvalidRequest) as assertRaisesContext:
self.client.auth.gcp.login("example-role", jwt)
expected_exception_message = "missing client token"
actual_exception_message = str(assertRaisesContext.exception)
self.assertIn(expected_exception_message, actual_exception_message)
# Reset test state.
self.client.token = self.manager.root_token
self.client.sys.disable_auth_method(path=test_mount_point)
@skipIf(
utils.if_vault_version("0.10.0"),
"KV version 2 secret engine not available before Vault version 0.10.0",
)
def test_kv2_secret_backend(self):
if "test/" in self.client.sys.list_mounted_secrets_engines()["data"]:
self.client.sys.disable_secrets_engine("test")
self.client.sys.enable_secrets_engine(
"kv", path="test", options={"version": "2"}
)
secret_backends = self.client.sys.list_mounted_secrets_engines()["data"]
assert "test/" in secret_backends
self.assertDictEqual(secret_backends["test/"]["options"], {"version": "2"})
self.client.sys.disable_secrets_engine("test")
def test_create_kubernetes_configuration(self):
expected_status_code = 204
test_mount_point = "k8s"
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
response = self.client.create_kubernetes_configuration(
kubernetes_host="127.0.0.1:80",
pem_keys=[certificate],
mount_point=test_mount_point,
)
self.assertEqual(
first=expected_status_code,
second=response.status_code,
)
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_get_kubernetes_configuration(self):
test_host = "127.0.0.1:80"
test_mount_point = "k8s"
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
self.client.create_kubernetes_configuration(
kubernetes_host=test_host,
pem_keys=[certificate],
mount_point=test_mount_point,
)
# Test that we can retrieve the configuration
response = self.client.get_kubernetes_configuration(
mount_point=test_mount_point
)
self.assertIn(
member="data",
container=response,
)
self.assertEqual(
first=test_host, second=response["data"].get("kubernetes_host")
)
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_create_kubernetes_role(self):
test_role_name = "test_role"
test_mount_point = "k8s"
expected_status_code = 204
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
self.client.create_kubernetes_configuration(
kubernetes_host="127.0.0.1:80",
pem_keys=[certificate],
mount_point=test_mount_point,
)
# Test that we can createa role
response = self.client.create_kubernetes_role(
name=test_role_name,
bound_service_account_names="*",
bound_service_account_namespaces="vault_test",
mount_point=test_mount_point,
)
self.assertEqual(
first=expected_status_code,
second=response.status_code,
)
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_get_kubernetes_role(self):
test_role_name = "test_role"
test_mount_point = "k8s"
test_bound_service_account_namespaces = ["vault-test"]
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
self.client.create_kubernetes_configuration(
kubernetes_host="127.0.0.1:80",
pem_keys=[certificate],
mount_point=test_mount_point,
)
# Test that we can createa role
self.client.create_kubernetes_role(
name=test_role_name,
bound_service_account_names="*",
bound_service_account_namespaces=test_bound_service_account_namespaces,
mount_point=test_mount_point,
)
response = self.client.get_kubernetes_role(
name=test_role_name,
mount_point=test_mount_point,
)
self.assertIn(
member="data",
container=response,
)
self.assertEqual(
first=test_bound_service_account_namespaces,
second=response["data"].get("bound_service_account_namespaces"),
)
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_list_kubernetes_roles(self):
test_role_name = "test_role"
test_mount_point = "k8s"
test_bound_service_account_namespaces = ["vault-test"]
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
self.client.create_kubernetes_configuration(
kubernetes_host="127.0.0.1:80",
pem_keys=[certificate],
mount_point=test_mount_point,
)
# Test that we can createa role
self.client.create_kubernetes_role(
name=test_role_name,
bound_service_account_names="*",
bound_service_account_namespaces=test_bound_service_account_namespaces,
mount_point=test_mount_point,
)
response = self.client.list_kubernetes_roles(
mount_point=test_mount_point,
)
self.assertIn(
member="data",
container=response,
)
self.assertEqual(first=[test_role_name], second=response["data"].get("keys"))
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_delete_kubernetes_role(self):
test_role_name = "test_role"
test_mount_point = "k8s"
expected_status_code = 204
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
self.client.create_kubernetes_configuration(
kubernetes_host="127.0.0.1:80",
pem_keys=[certificate],
mount_point=test_mount_point,
)
self.client.create_kubernetes_role(
name=test_role_name,
bound_service_account_names="*",
bound_service_account_namespaces="vault_test",
mount_point=test_mount_point,
)
# Test that we can delete a role
response = self.client.delete_kubernetes_role(
role=test_role_name,
mount_point=test_mount_point,
)
self.assertEqual(
first=expected_status_code,
second=response.status_code,
)
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_auth_kubernetes(self):
test_role_name = "test_role"
test_host = "127.0.0.1:80"
test_mount_point = "k8s"
# Turn on the kubernetes backend with a custom mount_point path specified.
if f"{test_mount_point}/" in self.client.sys.list_auth_methods()["data"]:
self.client.sys.disable_auth_method(test_mount_point)
self.client.sys.enable_auth_method("kubernetes", path=test_mount_point)
with open(utils.get_config_file_path("client-cert.pem")) as fp:
certificate = fp.read()
self.client.create_kubernetes_configuration(
kubernetes_host=test_host,
pem_keys=[certificate],
mount_point=test_mount_point,
)
self.client.create_kubernetes_role(
name=test_role_name,
bound_service_account_names="*",
bound_service_account_namespaces="vault_test",
mount_point=test_mount_point,
)
# Test that we can authenticate
with open(utils.get_config_file_path("example.jwt")) as fp:
test_jwt = fp.read()
with self.assertRaises(
exceptions.InternalServerError
) as assertRaisesContext:
# we don't actually have a valid JWT to provide, so this method will throw an exception
self.client.auth_kubernetes(
role=test_role_name,
jwt=test_jwt,
mount_point=test_mount_point,
)
expected_exception_message = 'claim "iss" is invalid'
actual_exception_message = str(assertRaisesContext.exception)
self.assertIn(expected_exception_message, actual_exception_message)
# Reset integration test state
self.client.sys.disable_auth_method(path=test_mount_point)
def test_seal_status(self):
seal_status_property = self.client.seal_status
logging.debug("seal_status_property: %s" % seal_status_property)
self.assertIn(
member="sealed",
container=seal_status_property,
)
<file_sep>from unittest import TestCase
from hvac import exceptions
from tests.utils.hvac_integration_test_case import HvacIntegrationTestCase
class TestToken(HvacIntegrationTestCase, TestCase):
def test_auth_token_manipulation(self):
result = self.client.auth.token.create(ttl="1h", renewable=True)
assert result["auth"]["client_token"]
lookup = self.client.auth.token.lookup(result["auth"]["client_token"])
assert result["auth"]["client_token"] == lookup["data"]["id"]
renew = self.client.auth.token.renew(lookup["data"]["id"])
assert result["auth"]["client_token"] == renew["auth"]["client_token"]
self.client.auth.token.revoke(lookup["data"]["id"])
try:
lookup = self.client.auth.token.lookup(result["auth"]["client_token"])
assert False
except exceptions.Forbidden:
assert True
except exceptions.InvalidPath:
assert True
except exceptions.InvalidRequest:
assert True
def test_self_auth_token_manipulation(self):
result = self.client.auth.token.create(ttl="1h", renewable=True)
assert result["auth"]["client_token"]
self.client.token = result["auth"]["client_token"]
lookup = self.client.auth.token.lookup_self()
assert result["auth"]["client_token"] == lookup["data"]["id"]
renew = self.client.auth.token.renew_self()
assert result["auth"]["client_token"] == renew["auth"]["client_token"]
self.client.auth.token.revoke_self()
try:
lookup = self.client.auth.token.lookup(result["auth"]["client_token"])
assert False
except exceptions.Forbidden:
assert True
except exceptions.InvalidPath:
assert True
except exceptions.InvalidRequest:
assert True
def test_token_accessor(self):
# Create token, check accessor is provided
result = self.client.auth.token.create(ttl="1h")
token_accessor = result["auth"].get("accessor", None)
assert token_accessor
# Look up token by accessor, make sure token is excluded from results
lookup = self.client.auth.token.lookup_accessor(token_accessor)
assert lookup["data"]["accessor"] == token_accessor
assert not lookup["data"]["id"]
# Revoke token using the accessor
self.client.auth.token.revoke_accessor(token_accessor)
# Look up by accessor should fail
with self.assertRaises(exceptions.InvalidRequest):
lookup = self.client.auth.token.lookup_accessor(token_accessor)
# As should regular lookup
with self.assertRaises(exceptions.Forbidden):
lookup = self.client.auth.token.lookup(result["auth"]["client_token"])
def test_create_token_explicit_max_ttl(self):
token = self.client.auth.token.create(ttl="30m", explicit_max_ttl="5m")
assert token["auth"]["client_token"]
assert token["auth"]["lease_duration"] == 300
# Validate token
lookup = self.client.auth.token.lookup(token["auth"]["client_token"])
assert token["auth"]["client_token"] == lookup["data"]["id"]
def test_create_token_max_ttl(self):
token = self.client.auth.token.create(ttl="5m")
assert token["auth"]["client_token"]
assert token["auth"]["lease_duration"] == 300
# Validate token
lookup = self.client.auth.token.lookup(token["auth"]["client_token"])
assert token["auth"]["client_token"] == lookup["data"]["id"]
def test_create_token_periodic(self):
token = self.client.auth.token.create(period="30m")
assert token["auth"]["client_token"]
assert token["auth"]["lease_duration"] == 1800
# Validate token
lookup = self.client.auth.token.lookup(token["auth"]["client_token"])
assert token["auth"]["client_token"] == lookup["data"]["id"]
assert lookup["data"]["period"] == 1800
def test_token_roles(self):
# No roles, list_token_roles == None
with self.assertRaises(exceptions.InvalidPath):
self.client.auth.token.list_roles()
# Create token role
assert (
self.client.auth.token.create_or_update_role("testrole").status_code == 204
)
# List token roles
during = self.client.auth.token.list_roles()["data"]["keys"]
assert len(during) == 1
assert during[0] == "testrole"
# Delete token role
self.client.auth.token.delete_role("testrole")
# No roles, list_token_roles == None
with self.assertRaises(exceptions.InvalidPath):
self.client.auth.token.list_roles()
def test_create_token_w_role(self):
# Create policy
self.prep_policy("testpolicy")
# Create token role w/ policy
assert (
self.client.auth.token.create_or_update_role(
"testrole", allowed_policies="testpolicy"
).status_code
== 204
)
# Create token against role
token = self.client.auth.token.create(ttl="1h", role_name="testrole")
assert token["auth"]["client_token"]
assert token["auth"]["policies"] == ["default", "testpolicy"]
# Cleanup
self.client.auth.token.delete_role("testrole")
self.client.sys.delete_policy("testpolicy")
| 4ef040d694acca5e13123158352d8b774375ecb5 | [
"Python"
] | 3 | Python | lparth/hvac | ad6b5d98bb766b8b645ea334b70b395bf3b5c78a | 6651b1b58c2d276b2c48a70a4cef11e896a33f5b |
refs/heads/master | <file_sep>var database = require('./database');
module.exports = {};
//Home
module.exports.addhomeitem = function(req,res){
var rtn = {};
function addhomeitem(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to add object'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('INSERT INTO `object`(`name`, `image`, `category`, `tooltip`, `hyperlink`) VALUES (?,?,?,?,?);', [req.body.name || "null", req.body.image || "null", req.body.category || "null", req.body.tooltip || "null", req.body.hyperlink || "null"], addhomeitem);
};
module.exports.gethomeitems = function(req,res){
var rtn = {};
function gethomeitems(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT `name`, `image`, `category`, `tooltip`, `hyperlink` FROM `object`;', gethomeitems);
};
module.exports.deletehomeitem = function(req,res){
var rtn = {};
function deletehomeitem(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to delete question'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('DELETE FROM `object` WHERE `tooltip` =VALUES (?);', [req.body.tooltip], deletehomeitem);
};
//Quiz
// Not used
module.exports.populatequiz = function(req, res){
var rtn = {};
function populatequiz(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to retrieve quiz information'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT DISTINCT * FROM `question`;', populatequiz);
};
module.exports.getquestions = function(req, res){
var rtn = {};
function getquestions(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT * FROM `question` ORDER BY `question`.`category` ASC;', getquestions);
};
// Not used
module.exports.showquizzes = function(req, res){
var rtn = {};
function showquizzes(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT q.`quizid`, n.`label`, n.`qid`, n.`type` FROM `quiz` as q JOIN `question` as n WHERE n.`quizid` = q.`quizid`;', showquizzes);
};
module.exports.addquestionDB = function(req,res){
var rtn = {};
function addquestionDB(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to add question'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('INSERT INTO `question`(`quizid`, `type`, `label`, `category`) VALUES (?,?,?,?);', [req.body.quizid || "null", req.body.type || "null", req.body.label || "null", req.body.category || "null"], addquestionDB);
};
module.exports.deletequestion = function(req,res){
var rtn = {};
function deletequestion(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to delete question'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('DELETE FROM `question` WHERE `label` =VALUES (?);', [req.body.label], deletequestion);
};
//Shopping Cart
module.exports.additem = function(req,res){
var rtn = {};
function additem(err, result, fields) {
rtn.db_result = result;
if (err){
rtn.error = err;
console.log(err);
}
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to add item'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('INSERT INTO `item`(`name`, `image`, `icon_height`, `monthly_cost`, `eStar`, `object`, `type`, `category`) VALUES (?,?,?,?,?,?,?,?);', [req.body.name || "null", req.body.image || "null", req.body.icon_height || "null", req.body.monthly_cost || "null", req.body.eStar || "null", req.body.object || "null", req.body.type || "null", req.body.category || "null"], additem);
};
module.exports.getshoppingcart = function(req,res){
var rtn = {};
function getshoppingcart(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT * FROM `item`;', getshoppingcart);
};
module.exports.deleteitem = function(req,res){
var rtn = {};
function deleteitem(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to delete item'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('DELETE FROM `item` WHERE `name` = VALUES (?);', [req.body.name], deleteitem);
};
//Information
module.exports.getinformation = function(req,res){
var rtn = {};
function getinformation(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT * FROM `information`;', getinformation);
};
module.exports.addinformation = function(req,res){
var rtn = {};
function addinformation(err, result, fields) {
rtn.db_result = result;
if (err){
rtn.error = err;
console.log(err);
}
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to add information'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('INSERT INTO `information`(`title`, `hyperlink`, `category`) VALUES (?,?,?);', [req.body.title || "null", req.body.info_link || "null", req.body.category || "null"], addinformation);
};
module.exports.deleteinformation = function(req,res){
var rtn = {};
function deleteinformation(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to delete information'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('DELETE FROM `information` WHERE `title` = VALUES (?);', [req.body.title], deleteinformation);
};
//Facts
module.exports.getfacts = function(req,res){
var rtn = {};
function getfacts(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
rtn.ready = true;
res.json(rtn);
}
database.query('SELECT * FROM `fact`;', getfacts);
};
module.exports.addfact = function(req,res){
var rtn = {};
function addfact(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to add fact'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('INSERT INTO `fact`(`name`, `text`, `category`, `hyperlink`, `image`) VALUES (?,?,?,?,?);', [req.body.name || "null", req.body.text || "null", req.body.category || "null", req.body.hyperlink || "null", req.body.image || "null"], addfact);
};
module.exports.deletefact = function(req,res){
var rtn = {};
function deletefact(err, result, fields) {
rtn.db_result = result;
if (err)
rtn.error = err;
if (result.changedRows < 1) {
rtn.error = {
code: 1001,
message: 'failed to delete fact'
}
}
rtn.ready = true;
res.json(rtn);
}
database.query('DELETE FROM `fact` WHERE `text` = VALUES (?);', [req.body.text], deletefact);
};
<file_sep>๏ปฟvar app = angular.module("FactListApp", []);<file_sep>module.exports = {};
var mysql = require("mysql");
var fs = require("fs");
// First you need to create a connection to the db
var con = mysql.createConnection(JSON.parse(fs.readFileSync('mysql_info.json')));
con.connect(function(err){
if(err){
console.log('[Database]: Error connecting to Db');
return;
}
console.log('[Database]: Connection established');
});
/**
* Usage queryText="SELECT * FROM...." & func = function(err, rows){}
*/
function query(queryText, args, func){
con.query(queryText, args, func);
}
function close() {
con.end(function(err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
}
module.exports.query = query;
module.exports.close = close;
<file_sep>๏ปฟangular.module('FactListApp', []).controller('FactController', function ($scope) {
$scope.title = 'Trivia List';
$scope.facts = [
{
fact: 'Buying items for a space can be expensive but it doesnโt have to be. When you buy all new items from bedding to a mini fridge, from a futon to a television, you can easily spend thousands of dollars. It can be eas to buy really cheap as well; but remember that quality is important too. In considering your ecoming sustainability buy an item that is well-made and can last a long time. Save money and reduce your environmental footprint.',
tag: 'greenBuying'
},
{
fact: 'First look for free items. There are often offers of furniture and other items on community swap pages and through community freecycle. Ames Community Swap on Facebook is a local resource for Iowa Staters. Trading with family and friends, especially around the holidays (when people are replacing older items) or during move out when downsizing is happening. Itโs a great way to save money and outfit your dorm.',
tag: 'greenBuying'
},
{
fact: 'Next try to buy used. Instead of buying something that uses brand new resources, you can buy something that just needs a fresh coat of paint to look good as new. Often times items are delivered to second hand shops because a newer looking product is available - vintage is in, however and vintage products can be fun, more durable, and definitely unique!',
tag: 'greenBuying'
},
{
fact: 'As much as you can, try to buy local! Remember that when you spend money in the community your dollar stays in the community supporting local businesses.',
tag: 'greenBuying'
},
{
fact: 'Swapping free items and buying used also makes a huge impact in reduced packaging. Almost 76 million tons of packaging is thrown away every year making a total of almost 50% of the total waste was thrown away! Looking for opportunities from the purchase of new products to reduce your waste print and cut down on packaging by purchasing products without all of the extra packaging is so significant.',
tag: 'greenBuying'
},
{
fact: 'Everyone likes a clean space and now your parents arenโt around to keep things picked up and clean. Be green when you clean by purchasing green cleaning supplies. You can even make your own green cleaning supplies by using vinegar and baking soda - you can also save up to $100 a year by making your own cleaning supplies over buying!',
tag: 'cleanSupplies'
},
{
fact: 'Instead of using a store-bought air-freshener, try using plants instead. Not only will they make your dorm smell nier, but they can also filter the air as well.',
tag: 'cleanSupplies'
},
{
fact: 'Keep your room green by adding a recycling bin! Each residential housing area has recycling or you can recycle on campus in designated buildings and at the single stream recycling solar compactors.',
tag: 'recycling'
},
{
fact: 'When youโre getting a lamp to brighten your space, purchase one that can use an energy efficient compact fluorescent light bulbs (CFLs) or light-emitting diode (LEDs) lighting. If you live off-campus you are eligible for rebates on energy efficient lighting. If you live in Freddy court, you can trade-in your inefficient light bulbs for CFLs. Though costing a little more, they can save over five times their purchase price in reduced electricity usage and last so much longer than traditional light bulbs.',
tag: 'lighting'
},
];
$scope.filters = [
{ name: 'Lighting', filterExpr: { tag: 'lighting' } },
{ name: 'Recycling', filterExpr: { tag: 'recycling' } },
{ name: 'Green Supplies', filterExpr: { tag: 'cleanSupplies' } },
{ name: 'Green Buying', filterExpr: { tag: 'greenBuying' } }
];
$scope.selectedFilter = $scope.filters[0];
$scope.setFilter = function (filter) {
$scope.selectedFilter = filter;
}
});<file_sep>๏ปฟangular.module('ItemListApp', []).controller('ListController', function ($scope) {
$scope.title = 'Item List Test';
$scope.items = [
{
icon: 'img/ledbulb.jpg',
icon_height: "150px",
name: 'Desk Lamp: LED Bulb',
price: 6.99,
object: 'lighting',
type: 'lamp',
eStar: true
},
$scope.FluorLamp = {
icon: 'img/fluorbulb.jpg',
icon_height: "150px",
name: 'Desk Lamp: Fluorescent Bulb',
price: 0.99,
object: 'lighting',
type: 'lamp',
eStar: true
},
$scope.IncanLamp = {
icon: 'img/IncanBulb.png',
icon_height: '150px',
name: 'Desk Lamp: Incandescent Bulb',
price: 1.99,
object: 'lighting',
type: 'lamp',
eStar: false
},
$scope.ESMicrowave = {
icon: 'img/microwave.jpg',
icon_height: "150px",
name: 'Microwave: Energy Star Approved',
price: 199.99,
object: 'appliance',
type: 'microwave',
eStar: true
},
$scope.Refrigerator = {
icon: 'img/miniFridge.jpg',
icon_height: '150px',
name: 'Refrigerator: Stock, Compact',
price: 149.99,
object: 'appliance',
type: 'refrigerator',
eStar: false
}
];
$scope.filters = [
{ name: 'all', filterExpr: '' },
{ name: 'lights', filterExpr: { object: 'lighting' } },
{ name: 'appliances', filterExpr: { object: 'appliance' } },
{ name: 'Energy Star Approved', filterExpr: { eStar: true } }
];
$scope.currentFilter = $scope.filters[0];
$scope.setFilter = function (filter) {
$scope.selectedFilter = filter;
}
});<file_sep>$(function () {
$(".dragged").draggable();
$("#draggable-menu div img").click(function () {
$(".room-container").append("<img src =\"" + $(this).attr("src") + "\">");
$(".room-container img").draggable();
$(".tmp").removeClass("tmp");
});
// Angular App Link
var app = angular.module("ItemListApp", []);
}
<file_sep># ISU-GYR
Senior Design Project for the Iowa State University Department of Sustainability, with the goal of presenting important information about Green Living in new and engaging ways.
<file_sep># ISU-GYR
<p>Group Number: DEC1612</p>
<p>Project Title: Green Your Residence</p>
<p>Team Leader + Key Concept Holder: <NAME><p>
<p>Communication Leader: <NAME><p>
<p>Webmaster: <NAME><p>
Senior Design Project for the Iowa State University Department of Sustainability, with the goal of presenting important information about Green Living in new and engaging ways.
<file_sep>๏ปฟangular.module('ItemListApp', []).controller('ListController', function ($scope) {
$scope.title = 'Item List Test';
$scope.diff = 0;
$scope.initCost = 0;
$scope.newCost = 0;
$scope.firstItem = [];
$scope.secondItem = [];
$scope.diffSet = [];
$scope.items = [
{
icon: '../img/SC/LED Bulb.png',
name: 'LED Bulb',
monthly_cost: 0.77,
object: 'lighting'
},
$scope.FluorLamp = {
icon: '../img/SC/CFL Bulb.png',
name: 'CFL Bulb',
monthly_cost: 1.54,
object: 'lighting'
},
$scope.IncanLamp = {
icon: '../img/SC/Incandecesant Bulb.png',
name: 'Incandescent Bulb',
monthly_cost: 6.60,
object: 'lighting'
},
{
icon: '../img/SC/Mini Fridge Black.png',
name: 'Mini-Fridge (no freezer)',
monthly_cost: 66,
object: 'refrigerator'
},
{
icon: '../img/SC/Mini Fridge Silver.png',
name: 'Micro-Fridge',
monthly_cost: 77,
type: 'refrigerator'
},
{
icon: '../img/SC/Microwave Black.png',
name: 'Microwave',
monthly_cost: 165,
object: 'microwave'
},
{
icon: '../img/SC/Toaster.png',
name: 'Toaster',
monthly_cost: 115.50,
object: 'microwave'
},
{
icon: '../img/SC/ToasterOven.png',
name: 'Toaster Oven',
monthly_cost: 132,
object: 'microwave'
},
{
icon: '../img/SC/Coffee Pot Black.png',
name: 'Traditional (Drip) Coffee Maker',
monthly_cost: 132,
object: 'coffee'
},
{
icon: '../img/SC/Keurig Black.png',
name: 'Keurig Coffee Maker',
monthly_cost: 165,
object: 'coffee'
},
{
icon: '../img/SC/Wii.png',
name: 'Nintendo Wii',
monthly_cost: 2.09,
object: 'gaming'
},
{
icon: '../img/SC/XBOX.png',
name: 'Microsoft Xbox 360',
monthly_cost: 18.70,
object: 'gaming'
},
{
icon: '../img/SC/PS3.png',
name: 'Sony Playstation 3',
monthly_cost: 21.67,
object: 'gaming'
},
{
icon: '../img/SC/MagicBullet.png',
name: 'Magic Bullet',
monthly_cost: 27.50,
object: 'blender'
},
{
icon: '../img/SC/Blender.png',
name: 'Traditional Blender',
monthly_cost: 55,
object: 'blender'
},
{
icon: '../img/SC/NutriBullet.png',
name: 'NutriBullet',
monthly_cost: 66,
object: 'blender'
},
{
icon: '../img/SC/TV Flat Screen Black.png',
name: 'LCD Flatscreen TV',
monthly_cost: 30.25,
object: 'tv'
},
{
icon: '../img/SC/TV Plasma.png',
name: 'Plasma Flatscreen TV',
monthly_cost: 43.89,
object: 'tv'
},
{
icon: '../img/SC/PrinterJet.png',
name: 'Inkjet Printer',
monthly_cost: 19.80,
object: 'printer'
},
{
icon: '../img/SC/PrinterLaser.jpg',
name: 'Laser Printer',
monthly_cost: 88,
object: 'printer'
},
{
icon: '../img/SC/PC.png',
name: 'Desktop Computer',
monthly_cost: 8.25,
object: 'computer'
},
{
icon: '../img/SC/Laptop.png',
name: 'Laptop Computer',
monthly_cost: 2.75,
object: 'computer'
}
];
$scope.filters = [
{ name: 'All', filterExpr: '', icon: '../img/world.png' },
{ name: 'Lighting', filterExpr: { object: 'lighting' }, icon: '../img/SC/CFL Bulb.png' },
{ name: 'Refrigerators', filterExpr: { object: 'refrigerator' }, icon: '../img/SC/Mini Fridge Silver.png' },
{ name: 'Toasters', filterExpr: { object: 'microwave' }, icon: '../img/SC/Microwave Black.png' },
{ name: 'Coffee Makers', filterExpr: { object: 'coffee' }, icon: '../img/SC/Coffee Pot Black.png' },
{ name: 'Gaming Consoles', filterExpr: { object: 'gaming' }, icon: '../img/SC/XBOX.png' },
{ name: 'Blenders', filterExpr: { object: 'blender' }, icon: '../img/SC/Blender.png' },
{ name: 'TVs', filterExpr: { object: 'tv' }, icon: '../img/SC/TV Plasma.png' },
{ name: 'Printers', filterExpr: { object: 'printer' }, icon: '../img/SC/PrinterJet.png' },
{ name: 'Computers', filterExpr: { object: 'computer' }, icon: '../img/SC/PC.png' },
// Commenting this part out for now, bring back when screen 3 filters are changed to match the item, not the filter from screen 1.
//{ name: 'Energy Star Approved', filterExpr: { eStar: true } }
];
$scope.currentFilter = $scope.filters[0];
$scope.setFilter = function (filter) {
$scope.selectedFilter = filter;
}
$scope.switchShopScreens = function (screenClass) {
$(".shop-screen").hide();
$(screenClass).fadeIn();
};
$scope.setFirstCost = function (value, item) {
$scope.initCost = value;
$scope.FI = item;
switchShopScreens(".SecondItemCategory");
}
$scope.setSecondCost = function (value, item) {
$scope.firstItem.push($scope.FI);
$scope.secondItem.push(item);
$scope.newCost = value;
$scope.diff += $scope.initCost - $scope.newCost;
$scope.diffSet.push($scope.initCost - $scope.newCost);
$scope.setFilter('');
switchShopScreens(".InitItemScreen");
}
}); | d62db9fd39969c1e2a1b7fb05e37abaa2cf43ce1 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | deecio/ISU-GYR | 19415a284f9b5d18bd335c3bed8cb615e00b9763 | f97f4c656444557d4f0cf5e54b3a996aa7ac53bd |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int cont, tab;
for(cont=92;cont<=105;cont++){
for(tab=15;tab<=17;tab++){
printf("%i*%i=%i\n",cont,tab,cont*tab);
}
}
return 0;
}
| 89b4b124159341ad098a2b23586900404defdf20 | [
"C"
] | 1 | C | LeonardoRamin/Tabuada | ed04ed1c096b9cc40c5e9e32febbc995e825a408 | ded7043e8bdc709674b5f0b0f5072d4523ac27c0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.