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>yudhe/sigfit<file_sep>/R/sigfit_plotting.R
#' Colour warnings for posterior predictive checks
#' yellow = observed value is in top or bottom 2.5% of ppc simulations
#' red = observed value is outside ppc simulations
make_colors <- function(c, c_ppc, sample = 1) {
n_ppc_sims <- dim(c_ppc)[1]
v <- vector("character", ncol(c))
for (i in 1:ncol(c)) {
prop <- sum(c[sample, i] < c_ppc[, sample, i]) / n_ppc_sims
if (prop < 0.001 | prop > 0.999) {
v[i] <- "firebrick"
}
else if (prop < 0.025 | prop > 0.975) {
v[i] <- "yellow3"
}
else {
v[i] <- "black"
}
}
v
}
#' Plot result of posterior predictive check
#' black = observed value is not extreme compared to the simulated distribution
#' yellow = observed value is in top or bottom 2.5% of ppc simulations
#' red = observed value is outside ppc simulations
#' @param c Integer matrix of observed counts.
#' @param c_ppc Simulated posterior predictive counts obtained from
#' MCMC samples using \code{extract(samples)$counts_ppc}
#' @export
plot_ppc <- function(c, c_ppc, sample = 1) {
plot(c[sample, ], type = "n")
n_ppc_sims <- dim(c_ppc)[1]
for (i in sample(1:n_ppc_sims, 500)) {
lines(c_ppc[i, sample, ], pch=20, cex=0.3,
col = rgb(.09, .45, .80, 0.1))
}
colors <- make_colors(c, c_ppc, sample)
lines(c[sample, ], type = 'p', lwd=2, col = colors, pch = 20)
lines(c[sample, ], type = 'h', lend=1, lwd=1, col = colors)
legend('topright',
legend=c("PPC distribution",
"Observation (not extreme relative to PPC)",
"Observation (in 5% tails of PPC)",
"Observation (outside PPC)"),
col=c(rgb(.09, .45, .80, 1),
"black",
"yellow3",
"firebrick"),
lty=c(1, NA, NA, NA),
pch=c(NA, 20, 20, 20),
lwd=c(3, 2, 2, 2),
cex=0.8)
}
#' Plot all results from signature fitting or extraction
#'
#' For a given set of signature fitting or extraction results, \code{plot_all} plots, in PDF format:
#' \itemize{
#' \item{All the original (input) mutational catalogues (via \code{\link{plot_spectrum}})}
#' \item{Mutational signatures (via \code{\link{plot_spectrum}})}
#' \item{Signature exposures (via \code{\link{plot_exposures}})}
#' \item{All the reconstructed mutational spectra (via \code{\link{plot_reconstruction}})}
#' }
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param out_path Character; path to the directory where the output PDF files will be stored.
#' Will be created if it does not exist.
#' @param prefix Character; optional prefix to be added to the output file names.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}. Only needed if \code{signatures} or \code{exposures}
#' are not provided.
#' @param signatures Either a numeric matrix of mutational signatures, with one row per signature and one
#' column for each of the 96 mutation types, or a list of signatures generated via
#' \code{\link{retrieve_pars}}. Only needed if \code{mcmc_samples} is not provided, or if it
#' contains signature fitting (instead of signature extraction) results.
#' @param exposures Either a numeric matrix of signature exposures, with one row per sample and one column
#' per signature, or a list of exposures as produced by \code{\link{retrieve_pars}}.
#' Only needed if \code{mcmc_samples} is not provided.
#' @param opportunities Integer matrix; it also admits values \code{"human-genome"} and \code{"human-exome"}.
#' If \code{signatures} and/or \code{exposures} were obtained by extracting or fitting
#' signatures using the "EMu" model (\code{method = "emu"}), these should be the same opportunities used
#' for extraction/fitting.
#' @param thresh Numeric; minimum probability value that should be reached by the lower end of exposure HPD
#' intervals. The exposures for which the lower HPD bound is below this value will be colored in grey.
#' This value is passed to the \code{plot_exposures} function.
#' @param horiz_labels Logical; if \code{TRUE}, sample name labels will be displayed horizontally in the
#' barplots. This value is passed to the \code{plot_exposures} function.
#' @param hpd_prob Numeric; a value in the interval (0, 1), giving the target probability content of
#' the HPD intervals. This value is passed to the \code{plot_exposures} function.
#' @param exp_legend_pos Character indicating the position of the legend in the exposures barplot. Admits values
#' \code{"bottomright"}, \code{"bottom"}, \code{"bottomleft"}, \code{"left"}, \code{"topleft"}, \code{"top"},
#' \code{"topright"}, \code{"right"} and \code{"center"}. This value is passed to the \code{plot_exposures} function.
#' @param rec_legend_pos Character indicating the position of the legend in the reconstructed spectrum. Admits values
#' \code{"bottomright"}, \code{"bottom"}, \code{"bottomleft"}, \code{"left"}, \code{"topleft"}, \code{"top"},
#' \code{"topright"}, \code{"right"} and \code{"center"}. This value is passed to the \code{plot_reconstruction} function.
#' @param sig_color_palette Character vector of colour names or hexadecimal codes to use for each signature.
#' Must have at least as many elements as the number of signatures. This value is passed to the
#' \code{plot_exposures} and \code{plot_reconstruction} functions.
#' @examples
#' # Load example mutational catalogues
#' data("counts_21breast")
#'
#' # Extract signatures using the EMu (Poisson) model
#' samples <- extract_signatures(counts_21breast, nsignatures = 2, method = "emu",
#' opportunities = "human-genome", iter = 800)
#'
#' # Retrieve signatures and exposures
#' signatures <- retrieve_pars(samples, "signatures")
#' exposures <- retrieve_pars(samples, "exposures")
#'
#' # Plot results using stanfit object
#' plot_all(counts_21breast, out_path = ".", prefix = "Test1",
#' mcmc_samples = samples, opportunities = "human-genome")
#'
#' # Plot results using retrieved signatures and exposures
#' plot_all(counts_21breast, out_path = ".", prefix = "Test2",
#' signatures = signatures, exposures = exposures,
#' opportunities = "human-genome")
#' @importFrom "rstan" extract
#' @export
plot_all <- function(counts, out_path, prefix = NULL, mcmc_samples = NULL, signatures = NULL, exposures = NULL,
opportunities = NULL, thresh = 0.01, horiz_labels = FALSE, hpd_prob = 0.95,
signature_names = NULL, exp_legend_pos = "topright", rec_legend_pos = "topright",
sig_color_palette = NULL) {
if (is.null(mcmc_samples) & (is.null(exposures) | is.null(signatures))) {
stop("Either 'mcmc_samples' (stanfit object), or both 'signatures' and 'exposures' (matrices or lists), must be provided.")
}
if (!is.null(mcmc_samples)) {
if (is.null(signatures) & !("signatures" %in% mcmc_samples@model_pars)) {
stop("'mcmc_samples' contains signature fitting results: a signatures matrix must be provided via 'signatures'")
}
}
# Create output directory if it does not exist
dir.create(out_path, showWarnings=F)
if (!is.null(prefix)) {
prefix <- paste0(prefix, "_")
}
cat("Plotting original catalogues...\n")
plot_spectrum(counts,
pdf_path = file.path(out_path, paste0(prefix, "Catalogues_", Sys.Date(), ".pdf")))
# Case A: matrices provided instead of MCMC samples
if (is.null(mcmc_samples)) {
cat("Plotting mutational signatures...\n")
plot_spectrum(signatures,
pdf_path = file.path(out_path, paste0(prefix, "Signatures_", Sys.Date(), ".pdf")))
cat("Plotting signature exposures...\n")
plot_exposures(counts, exposures = exposures, signature_names = signature_names,
thresh = thresh, sig_color_palette = sig_color_palette,
horiz_labels = horiz_labels, legend_pos = exp_legend_pos,
pdf_path = file.path(out_path, paste0(prefix, "Exposures_", Sys.Date(), ".pdf")))
plot_reconstruction(counts, signatures = signatures, exposures = exposures,
opportunities = opportunities, legend_pos = rec_legend_pos,
sig_color_palette = sig_color_palette,
pdf_path = file.path(out_path, paste0(prefix, "Reconstructions_", Sys.Date(), ".pdf")))
}
# Case B: MCMC samples provided instead of matrices
else {
cat("Plotting mutational signatures...\n")
if ("signatures" %in% mcmc_samples@model_pars) {
signatures <- retrieve_pars(mcmc_samples, feature = "signatures")
}
plot_spectrum(signatures,
pdf_path = file.path(out_path, paste0(prefix, "Signatures_", Sys.Date(), ".pdf")))
cat("Plotting signature exposures...\n")
plot_exposures(counts, mcmc_samples = mcmc_samples, signature_names = signature_names,
thresh = thresh, hpd_prob = hpd_prob, horiz_labels = horiz_labels,
legend_pos = exp_legend_pos, sig_color_palette = sig_color_palette,
pdf_path = file.path(out_path, paste0(prefix, "Exposures_", Sys.Date(), ".pdf")))
plot_reconstruction(counts, mcmc_samples = mcmc_samples, signatures = signatures,
opportunities = opportunities, legend_pos = rec_legend_pos,
sig_color_palette = sig_color_palette,
pdf_path = file.path(out_path, paste0(prefix, "Reconstructions_", Sys.Date(), ".pdf")))
}
}
#' Plot goodness of fit
#'
#' \code{plot_gof} plots the goodness of fit of a set of samples, each of which
#' has typically been sampled using an extraction model (EMu or NMF) with a
#' different number of signatures.
#' @param sample_list List of objects of class stanfit. Elements which are not of class stanfit are ignored.
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param stat Character; function for measuring goodness of fit. Admits values \code{"cosine"}
#' (cosine similarity; default) or \code{"L2"} (L2 norm, a.k.a. Euclidean distance).
#' @importFrom "rstan" extract
#' @export
plot_gof <- function(sample_list, counts, stat = "cosine") {
gof_function <- switch(stat,
"cosine" = cosine_sim,
"L2" = l2_norm)
if (is.null(gof_function)) {
stop("'stat' only admits values \"cosine\" and \"L2\".\nType ?plot_gof to see the documentation.")
}
nS <- NULL
gof <- NULL
for (samples in sample_list) {
if (class(samples) != "stanfit") next
if (grepl("emu", samples@model_name)) {
method <- "EMu"
e <- extract(samples, pars = c("expected_counts", "signatures"))
reconstructed <- apply(e$expected_counts, c(2, 3), mean)
}
else {
method <- "NMF"
e <- extract(samples, pars = c("probs", "signatures"))
reconstructed <- apply(e$probs, c(2, 3), mean) * rowSums(counts)
}
stopifnot(dim(reconstructed) == dim(counts))
nS <- c(nS, dim(e$signatures)[2])
gof <- c(gof, gof_function(as.vector(reconstructed),
as.vector(counts)))
}
# Find the point of highest rate of change of gradient (i.e. highest positive
# 2nd derivative for 'L'-shaped curves, negative for 'r'-shaped curves)
# Approximate 2nd derivative = x[n+1] + x[n-1] - 2x[n]
deriv <- gof[3:(length(gof))] + gof[1:(length(gof)-2)] - 2 * gof[2:(length(gof)-1)]
best <- ifelse(stat == "cosine",
which.min(deriv) + 1, # highest negative curvature
which.max(deriv) + 1) # highest positive curvature
plot(nS, gof, type = "o", lty = 3, pch = 16, col = "dodgerblue4",
main = paste0("Goodness of fit (", stat, ")\nmodel: ", method),
xlab = "Number of signatures",
ylab = paste0("Goodness of fit (", stat, ")"))
points(nS[best], gof[best], pch = 16, col = "orangered", cex = 1.1)
cat("Estimated best number of signatures:", nS[best], "\n")
nS[best]
}
#' Plot mutational spectrum reconstructions
#'
#' \code{plot_reconstruction} plots the reconstructions of the original mutational catalogues using the
#' signatures and/or exposures obtained through extraction or fitting. If provided with multiple catalogues,
#' it generates one plot per catalogue. Fitting or extraction results can be provided either as a single
#' stanfit object (generated via \code{\link{fit_signatures}} or \code{\link{extract_signatures}}),
#' or as separate signatures and exposures matrices (or lists produced via \code{\link{retrieve_pars}}).
#' Only the former option allows the incorporation of HPD intervals to the reconstructed catalogue.
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}. Only needed if \code{signatures} or \code{exposures}
#' are not provided.
#' @param signatures Either a numeric matrix of mutational signatures, with one row per signature and one
#' column for each of the 96 mutation types, or a list of signatures generated via
#' \code{\link{retrieve_pars}}. Only needed if \code{mcmc_samples} is not provided.
#' @param exposures Either a numeric matrix of signature exposures, with one row per sample and one column
#' per signature, or a list of exposures as produced by \code{\link{retrieve_pars}}.
#' Only needed if \code{mcmc_samples} is not provided.
#' @param opportunities Integer matrix; it also admits values \code{"human-genome"} and \code{"human-exome"}.
#' If \code{signatures} and/or \code{exposures} were obtained by extracting or fitting
#' signatures using the "EMu" model (\code{method = "emu"}), these should be the same opportunities used
#' for extraction/fitting.
#' @param pdf_path Character; if provided, the plots will be output to a PDF file with this path. The PDF
#' size and graphical parameters will be automatically set to appropriate values.
#' @param legend_pos Character indicating the position of the legend in the reconstructed spectrum. Admits values
#' \code{"bottomright"}, \code{"bottom"}, \code{"bottomleft"}, \code{"left"}, \code{"topleft"}, \code{"top"},
#' \code{"topright"}, \code{"right"} and \code{"center"}.
#' @param sig_color_palette Character vector of colour names or hexadecimal codes to use for each signature.
#' Must have at least as many elements as the number of signatures.
#' @examples
#' # Load example mutational catalogues
#' data("counts_21breast")
#'
#' # Extract signatures using the EMu (Poisson) model
#' samples <- extract_signatures(counts_21breast, nsignatures = 2, method = "emu",
#' opportunities = "human-genome", iter = 800)
#'
#' # Retrieve signatures and exposures
#' signatures <- retrieve_pars(samples, "signatures")
#' exposures <- retrieve_pars(samples, "exposures")
#'
#' # Plot reconstructed catalogues using stanfit object
#' plot_reconstruction(counts_21breast, mcmc_samples = samples, opportunities = "human-genome",
#' pdf_path = "Reconstructions_1.pdf")
#'
#' # Plot reconstructed catalogues using retrieved signatures and exposures
#' plot_reconstruction(counts_21breast, signatures = signatures, exposures = exposures,
#' opportunities = "human-genome", pdf_path = "Reconstructions_2.pdf")
#' @importFrom "rstan" extract
#' @importFrom "coda" as.mcmc HPDinterval
#' @export
plot_reconstruction <- function(counts, mcmc_samples = NULL, signatures = NULL,
exposures = NULL, opportunities = NULL, pdf_path = NULL,
legend_pos = "topright", sig_color_palette = NULL) {
# Force counts to matrix
counts <- to_matrix(counts)
stopifnot(ncol(counts) %in% c(96, 192))
NCAT <- ncol(counts) # number of categories
NSAMP <- nrow(counts) # number of samples
strand <- NCAT == 192 # strand bias indicator (logical)
if (is.null(opportunities) & !is.null(mcmc_samples)) {
if (grepl("emu", mcmc_samples@model_name)) {
warning("Plotting EMu results, but no opportunities provided.")
}
}
if (is.null(opportunities) | is.character(opportunities)) {
opportunities <- build_opps_matrix(NSAMP, opportunities, strand)
}
else if (!is.matrix(opportunities)) {
opportunities <- as.matrix(opportunities)
}
stopifnot(all(dim(opportunities) == dim(counts)))
if (is.null(mcmc_samples) & (is.null(exposures) | is.null(signatures))) {
stop("Either 'mcmc_samples' (stanfit object), or both 'signatures' and 'exposures' (matrices or lists), must be provided.")
}
cat("Building reconstructed catalogues...\n")
# Case A: matrices given instead of MCMC samples
if (is.null(mcmc_samples)) {
# Force signatures and exposures to matrices
signatures <- to_matrix(signatures)
exposures <- to_matrix(exposures)
NSIG <- nrow(signatures)
stopifnot(ncol(signatures) == NCAT)
stopifnot(nrow(exposures) == NSAMP)
stopifnot(ncol(exposures) == NSIG)
# Create reconstructed catalogues
reconstructions <- array(NA, dim = c(NSAMP, NSIG, NCAT))
for (i in 1:NSAMP) {
rec <- exposures[i,] * signatures
rec <- rec * opportunities[i,]
rec <- rec / sum(rec)
reconstructions[i,,] <- rec * sum(counts[i,])
}
}
# Case B: MCMC samples given instead of matrices
else {
l <- get_reconstructions(counts, mcmc_samples, signatures, opportunities)
reconstructions <- l$reconstructions
exposures <- l$exposures
hpds <- l$hpds
NSIG <- dim(l$exposures)[2]
}
cat("Plotting reconstructions for each sample...\n")
# Plotting
TYPES <- c("C>A", "C>G", "C>T", "T>A", "T>C", "T>G")
COLORS <- c("deepskyblue", "black", "firebrick2", "gray76", "darkolivegreen3", "rosybrown2")
STRANDCOL <- c("deepskyblue3", "red3")
BACKCOL <- c("#00BFFF33", "#00000033", "#EE2C2C33", "#C2C2C24D", "#A2CD5A4D", "#EEB4B44D")
LINECOL <- "gray60"
XL <- c(0.2, 19.4, 38.6, 57.8, 77, 96.2)
XR <- c(19.2, 38.4, 57.6, 76.8, 96, 115.2)
BACKLIM <- c(0, 46.5, 93, 139.5, 186, 232.5, 279)
if (is.null(sig_color_palette)) {
sigcols <- default_sig_palette(NSIG)
}
else {
sigcols <- sig_color_palette[1:NSIG]
}
if (is.null(rownames(counts))) {
rownames(counts) <- paste("Sample", 1:NSAMP)
}
dimnames(reconstructions)[[3]] <- mut_types(strand)
if (is.null(rownames(signatures))) {
LETTERLABELS <- letterwrap(NSIG)
sig_names <- paste("Signature", LETTERLABELS[1:NSIG])
}
else {
sig_names <- rownames(signatures)
}
if (!is.null(pdf_path)) {
stopifnot(is.character(pdf_path))
pdf(pdf_path, width = 24, height = 18)
par(mar = c(6, 8, 6, 2.75), oma = c(3, 0, 2, 0))
}
par(mfrow = c(2, 1))
# Default spectrum (NCAT=96)
if (!strand) {
for (i in 1:NSAMP) {
if (is.null(mcmc_samples)) {
max_y <- max(c(counts[i, ], colSums(reconstructions[i, , ]))) * 1.1
}
else {
max_y <- max(c(counts[i, ], hpds[i, , ])) * 1.1
}
# Plot original catalogue
plot_spectrum(counts[i, ], name = rownames(counts)[i], max_y = max_y)
# Plot catalogue reconstruction
bars <- barplot(reconstructions[i, , ],
col = sigcols, border = "white",
yaxt = "n", ylim = c(0, max_y), xlim = c(-1, 116),
cex = 1.3, cex.axis = 1.5, cex.lab = 1, las = 2,
xaxs = "i", family = "mono")
axis(side = 2, las = 2, cex.axis = 1.25)
mtext("Mutations", side = 2, cex = 1.5, line = 4.5)
title(paste0("Reconstructed mutational spectrum\nCosine similarity = ",
round(cosine_sim(counts[i,], colSums(reconstructions[i, , ])), 3)),
line = 1, cex.main = 2)
# HPD intervals
if (!is.null(mcmc_samples)) {
arrows(bars, colSums(reconstructions[i, , ]),
bars, hpds[i, 1, ],
angle = 90, length = 0, lwd = 2, col = LINECOL)
arrows(bars, colSums(reconstructions[i, , ]),
bars, hpds[i, 2, ],
angle = 90, length = 0, lwd = 2, col = LINECOL)
}
# Mutation type labels
rect(xleft = XL, xright = XR, ybottom = max_y * 0.95, ytop = max_y,
col = COLORS, border = "white")
text(x = (XL + XR) / 2, y = max_y * 0.9, labels = TYPES, cex = 2.25)
# Legend
legend(legend_pos, inset = c(0, 0.13), ncol = 2,
legend = paste0(sig_names, " (", round(exposures[i, ], 3), ")"),
fill = sigcols, border = "white", cex = 1.5, bty = "n")
}
}
# Strand-wise spectrum (NCAT=192)
else {
for (i in 1:NSAMP) {
if (is.null(mcmc_samples)) {
max_y <- max(c(counts[i, ], colSums(reconstructions[i, , ]))) * 1.1
}
else {
max_y <- max(c(counts[i, ], hpds[i, , ])) * 1.1
}
# Plot original catalogue
plot_spectrum(counts[i, ], name = rownames(counts)[i], max_y = max_y)
# Plot catalogue reconstruction
# Background panes and mutation type labels
bars <- barplot(rbind(reconstructions[i, 1, 1:(NCAT/2)],
reconstructions[i, 1, (NCAT/2+1):NCAT]),
names.arg = mut_types(), beside = TRUE, col = NA, border = NA,
space = c(0.1, 0.8), xaxs = "i", yaxt = "n", ylim = c(0, max_y),
xlim = c(-3, 280), family = "mono", cex = 1.3, cex.axis = 1.5,
cex.lab = 1.7, las = 2)
for (j in 1:length(COLORS)) {
rect(xleft = BACKLIM[j], xright = BACKLIM[j+1], ybottom = 0,
ytop = max_y, col = BACKCOL[j], border = "white")
rect(xleft = BACKLIM[j], xright = BACKLIM[j+1], ybottom = 0.95 * max_y,
ytop = max_y, col = COLORS[j], border = "white")
text(x = (BACKLIM[j] + BACKLIM[j+1]) / 2, y = 0.91 * max_y,
labels = TYPES[j], cex = 2.25, col = "black")
}
# Spectrum bars
for (j in NSIG:1) {
rec = colSums(to_matrix(reconstructions[i, 1:j, ]))
barplot(rbind(rec[1:(NCAT/2)], rec[(NCAT/2+1):NCAT]),
col = sigcols[j], border = "white", beside = TRUE,
space = c(0.1, 0.8), yaxt = "n", xaxt = "n",
ylim = c(0, max_y), xlim = c(-3, 270),
xaxs = "i", add = TRUE)
}
axis(side = 2, las = 2, cex.axis = 1.25)
mtext("Mutations", side = 2, cex = 1.5, line = 4.5)
title(paste0("Reconstructed mutational spectrum\nCosine similarity = ",
round(cosine_sim(counts[i,], colSums(reconstructions[i, , ])), 3)),
line = 1, cex.main = 2)
# HPD intervals
if (!is.null(mcmc_samples)) {
bars <- as.numeric(t(bars))
arrows(bars, colSums(reconstructions[i, , ]),
bars, hpds[i, 1, ],
angle = 90, length = 0, lwd = 2, col = LINECOL)
arrows(bars, colSums(reconstructions[i, , ]),
bars, hpds[i, 2, ],
angle = 90, length = 0, lwd = 2, col = LINECOL)
}
# Legend
legend(legend_pos, inset = c(0.01, 0.105), ncol = 2,
legend = paste0(sig_names, " (", round(exposures[i, ], 3), ")"),
fill = sigcols, border = sigcols, cex = 1.5, bty = "n")
}
}
par(mfrow = c(1, 1))
if (!is.null(pdf_path)) {
dev.off()
}
}
#' Plot mutational spectra
#'
#' \code{plot_spectrum} generates plots of one or more spectra, which can be either mutational
#' catalogues or mutational signatures. If the spectra contain values above 1, the values will be
#' interpreted as mutation counts (as in a catalogue); otherwise, they will be interpreted as
#' mutation probabilities (as in a signature). If multiple spectra are provided, one plot per
#' spectrum is produced.
#' @param spectra Either a numeric vector with one element for each of the 96 mutation types,
#' or a numeric matrix with 96 columns and one row per
#' signature/catalogue, or a list of signatures as produced by
#' \code{\link{retrieve_pars}}. In the latter case, HPD intervals will also be plotted.
#' Row names will be adopted as the sample/signature names.
#' @param name Character; name to include in the plot title. Useful when plotting a single spectrum.
#' @param pdf_path Character; if provided, the plots will be output to a PDF file with this path. The PDF
#' size and graphical parameters will be automatically set to appropriate values.
#' @param max_y Numeric; fixed higher limit of the y-axis (if necessary).
#' @examples
#' # Load example mutational catalogues
#' data("counts_21breast")
#'
#' # Plot catalogues
#' plot_spectrum(counts_21breast, pdf_path = "Catalogues.pdf")
#'
#' # Extract signatures using the EMu (Poisson) model
#' samples <- extract_signatures(counts_21breast, nsignatures = 2, method = "emu",
#' opportunities = "human-genome", iter = 800)
#'
#' # Retrieve extracted signatures
#' sigs <- retrieve_pars(samples, "signatures")
#'
#' # Plot signatures
#' plot_spectrum(sigs, pdf_path = "Signatures.pdf")
#' @export
plot_spectrum <- function(spectra, name = NULL, pdf_path = NULL, max_y = NULL) {
# Fetch HPD interval values, if present
if (is.list(spectra) & "mean" %in% names(spectra)) {
spec <- spectra$mean
lwr <- spectra$lower
upr <- spectra$upper
}
else {
spec <- spectra
lwr <- NULL
upr <- NULL
}
# Force spectrum to matrix (96 columns)
spec <- to_matrix(spec)
stopifnot(ncol(spec) %in% c(96, 192))
NCAT <- ncol(spec) # number of categories
NSAMP <- nrow(spec) # number of samples
strand <- NCAT == 192 # strand bias indicator (logical)
counts <- any(spec > 1) # count data indicator
# Plot each spectrum
TYPES <- c("C>A", "C>G", "C>T", "T>A", "T>C", "T>G")
COLORS <- c("deepskyblue", "black", "firebrick2", "gray76", "darkolivegreen3", "rosybrown2")
STRANDCOL <- c("deepskyblue3", "red3")
BACKCOL <- c("#00BFFF33", "#00000033", "#EE2C2C33", "#C2C2C24D", "#A2CD5A4D", "#EEB4B44D")
LINECOL <- "gray60"
XL <- c(0.2, 19.4, 38.6, 57.8, 77, 96.2)
XR <- c(19.2, 38.4, 57.6, 76.8, 96, 115.2)
BACKLIM <- c(0, 46.5, 93, 139.5, 186, 232.5, 279)
if (!is.null(pdf_path)) {
pdf(pdf_path, width = 24, height = 10.5)
par(mar = c(9, 8, 6, 2.75))
}
# Standard spectrum (NCAT=96)
if (!strand) {
for (i in 1:NSAMP) {
if (is.null(max_y)) {
FACTOR <- 1.2
samp_max_y <- max(0.05,
ifelse(is.null(upr), max(spec[i,]) * FACTOR, max(upr[i,]) * FACTOR))
}
else {
samp_max_y <- max_y
}
# Plot spectrum bars
bars <- barplot(spec[i,],
names.arg = mut_types(),
col = rep(COLORS, each = 16), border = "white",
yaxt = "n", ylim = c(0, samp_max_y), xlim = c(-1, 116),
cex = 1.3, cex.axis = 1.5, cex.lab = 1.7,
las = 2, xaxs = "i", family = "mono")
# Plot axis
if (counts) {
axis(side = 2, las = 2, cex.axis = 1.25)
label <- "Mutations"
n_text <- paste0(" (", sum(spec[i,]), " mutations)")
}
else {
axis(side = 2, at = seq(0, samp_max_y, 0.05), las = 2, cex.axis = 1.25)
label <- "Mutation probability"
n_text <- ""
}
if (is.null(name)) {
nme <- rownames(spec)[i]
}
else {
nme <- name
}
if (NSAMP > 1) {
num <- paste0(" #", i)
}
else {
num <- ""
}
mtext(label, side = 2, cex = 1.7, line = 4.5)
title(paste0("Mutational spectrum", num, "\n", nme, n_text),
line = 1.5, cex.main = 2)
# Plot HPD intervals
if (!is.null(lwr)) {
arrows(bars, spec[i,], bars, lwr[i,], angle = 90,
length = 0, lwd = 2, col = LINECOL)
arrows(bars, spec[i,], bars, upr[i,], angle = 90,
length = 0, lwd = 2, col = LINECOL)
}
# Plot mutation type labels
rect(xleft = XL, xright = XR, ybottom = 0.95 * samp_max_y, ytop = samp_max_y,
col = COLORS, border = "white")
text(x = (XL + XR) / 2, y = 0.91 * samp_max_y, labels = TYPES, cex = 2.25)
}
}
# Strand-wise spectrum (NCAT=192)
else {
for (i in 1:NSAMP) {
if (is.null(max_y)) {
FACTOR <- 1.25
samp_max_y <- max(0.05,
ifelse(is.null(upr), max(spec[i,]) * FACTOR, max(upr[i,]) * FACTOR))
}
else {
samp_max_y <- max_y
}
# Plot background panes and mutation type labels
barplot(rbind(spec[i, 1:(NCAT/2)], spec[i, (NCAT/2+1):NCAT]), beside = TRUE, col = NA, border = NA,
space = c(0.1, 0.8), xaxs = "i", yaxt = "n", xaxt = "n", ylim = c(0, samp_max_y), xlim = c(-3, 280))
for (j in 1:length(COLORS)) {
rect(xleft = BACKLIM[j], xright = BACKLIM[j+1], ybottom = 0,
ytop = samp_max_y, col = BACKCOL[j], border = "white")
rect(xleft = BACKLIM[j], xright = BACKLIM[j+1], ybottom = 0.95 * samp_max_y,
ytop = samp_max_y, col = COLORS[j], border = "white")
text(x = (BACKLIM[j] + BACKLIM[j+1]) / 2, y = 0.91 * samp_max_y,
labels = TYPES[j], cex = 2.25, col = "black")
}
# Plot spectrum bars
bars <- barplot(rbind(spec[i, 1:(NCAT/2)],
spec[i, (NCAT/2+1):NCAT]),
names.arg = mut_types(),
col = STRANDCOL, border = "white", beside = TRUE,
space = c(0.1, 0.8), yaxt = "n",
ylim = c(0, samp_max_y), xlim = c(-3, 270),
cex = 1.3, cex.axis = 1.5, cex.lab = 1.7,
las = 2, xaxs = "i", family = "mono", add = TRUE)
# Plot legend and axis
legend("topright", legend = c("Transcribed strand", "Untranscribed strand"), bty = "n",
fill = STRANDCOL, border = STRANDCOL, cex = 1.5, inset = c(0.018, 0.105))
if (counts) {
axis(side = 2, las = 2, cex.axis = 1.25)
label <- "Mutations"
n_text <- paste0(" (", sum(spec[i,]), " mutations)")
}
else {
axis(side = 2, at = seq(0, samp_max_y, 0.05), las = 2, cex.axis = 1.25)
label <- "Mutation probability"
n_text <- ""
}
if (is.null(name)) {
nme <- rownames(spec)[i]
}
else {
nme <- name
}
if (NSAMP > 1) {
num <- paste0(" #", i)
}
else {
num <- ""
}
mtext(label, side = 2, cex = 1.7, line = 4.5)
title(paste0("Mutational spectrum", num, "\n", nme, n_text),
line = 1.5, cex.main = 2)
# Plot HPD intervals
if (!is.null(lwr)) {
bars <- as.numeric(t(bars))
arrows(bars, spec[i,], bars, lwr[i,], angle = 90,
length = 0, lwd = 2, col = LINECOL)
arrows(bars, spec[i,], bars, upr[i,], angle = 90,
length = 0, lwd = 2, col = LINECOL)
}
}
}
if (!is.null(pdf_path)) {
dev.off()
}
}
#' Plot signature exposures
#'
#' \code{plot_exposures} plots the distribution of signature exposures across the samples.
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param exposures Either a numeric matrix of signature exposures, with one row per sample and one column
#' per signature, or a list of exposures as produced by \code{\link{retrieve_pars}}.
#' Only needed if \code{mcmc_samples} is not provided.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}. Only needed if \code{exposures} is not provided.
#' @param pdf_path Character; if provided, the plots will be output to a PDF file with this path. The PDF
#' size and graphical parameters will be automatically set to appropriate values.
#' @param signature_names Character vector containing the names of the signatures. Only used when plotting
#' exposures obtained through signature fitting (not extraction).
#' @param thresh Numeric; minimum probability value that should be reached by the lower end of exposure HPD
#' intervals. The exposures for which the lower HPD bound is below this value will be colored in grey.
#' @param hpd_prob Numeric; a value in the interval (0, 1), giving the target probability content of
#' the HPD intervals.
#' @param horiz_labels Logical; if \code{TRUE}, sample name labels will be displayed horizontally in the
#' barplots.
#' @param legend_pos Character indicating the position of the legend in the exposures barplot. Admits values
#' \code{"bottomright"}, \code{"bottom"}, \code{"bottomleft"}, \code{"left"}, \code{"topleft"}, \code{"top"},
#' \code{"topright"}, \code{"right"} and \code{"center"}.
#' @param sig_color_palette Character vector of color names or hexadecimal codes to use for each signature.
#' Must have at least as many elements as the number of signatures.
#' @importFrom "graphics" arrows axis barplot legend lines mtext par plot points rect text title
#' @importFrom "grDevices" pdf dev.off rgb
#' @export
plot_exposures <- function(counts, exposures = NULL, mcmc_samples = NULL, pdf_path = NULL,
signature_names = NULL, thresh = 0.01, hpd_prob = 0.95,
horiz_labels = FALSE, legend_pos = "topright", sig_color_palette = NULL) {
if (is.null(exposures) & is.null(mcmc_samples)) {
stop("Either 'exposures' (matrix or list) or 'mcmc_samples' (stanfit object) must be provided.")
}
if (!is.null(mcmc_samples)) {
exposures <- retrieve_pars(mcmc_samples, "exposures", signature_names = signature_names,
hpd_prob = hpd_prob)
lwr <- exposures$lower
upr <- exposures$upper
}
else if (is.list(exposures) & "mean" %in% names(exposures)) {
lwr <- exposures$lower
upr <- exposures$upper
}
else {
lwr <- NULL
upr <- NULL
}
if (!is.null(signature_names)) {
for (i in 1:length(exposures)) {
colnames(exposures[[i]]) <- signature_names
}
}
exposures <- to_matrix(exposures)
stopifnot(nrow(counts) == nrow(exposures))
NSAMP <- nrow(counts)
NSIG <- ncol(exposures)
LETTERLABELS <- letterwrap(NSIG)
if (is.null(rownames(counts))) {
rownames(exposures) <- paste("Sample", 1:NSAMP)
}
else {
rownames(exposures) <- rownames(counts)
}
if (is.null(colnames(exposures))) {
colnames(exposures) <- paste("Signature", LETTERLABELS[1:NSIG])
}
if (is.null(sig_color_palette)) {
sigcols <- default_sig_palette(NSIG)
}
else {
sigcols <- sig_color_palette[1:NSIG]
}
if (!is.null(pdf_path)) {
# PDF width increases with number of samples
pdf(pdf_path, width = max(NSAMP * 0.13, 12), height = ifelse(NSAMP > 1, 12, 7))
par(mar = c(6, 0, 4, 0), oma = c(1, 6, 1, 0))
}
par(lwd = 0.5)
if (NSAMP > 1) {
par(mfrow = c(3, 1))
}
# Obtain global (average) exposures
exposures_global <- colMeans(exposures)
if (!is.null(lwr)) {
lwr_global <- colMeans(lwr)
upr_global <- colMeans(upr)
max_y <- max(upr_global)
}
else {
max_y <- max(exposures_global)
}
# Plot global exposures
colours <- rep("dodgerblue4", NSIG)
if (!is.null(lwr)) {
colours[lwr_global < thresh] <- "grey"
}
bars <- barplot(exposures_global, col = colours, border = NA, cex.names = 1.1,
cex.main = 1.4, ylim = c(0, max_y), axes = F, las = ifelse(NSIG > 8, 2, 1),
main = "Global signature exposures across sample set")
axis(side = 2, cex.axis = 1.1, las = 2, line = -2)
mtext(text = "Mutation fraction", side = 2, line = 2.5)
if (!is.null(lwr)) {
arrows(bars, exposures_global, bars, lwr_global,
angle = 90, length = 0, lwd = 2, col = "gray50")
arrows(bars, exposures_global, bars, upr_global,
angle = 90, length = 0, lwd = 2, col = "gray50")
}
# If >1 sample: plot exposures per sample
if (NSAMP > 1) {
par(mar = c(9, 0, 4, 0))
# Obtain absolute exposures as mutation counts
muts <- rowSums(counts)
exposures_abs <- exposures * muts
# Plot absolute exposures
las = ifelse(horiz_labels, 1, 2)
bars <- barplot(t(exposures_abs), col = sigcols, las = las, lwd = 0.25,
cex.names = 0.8, cex.main = 1.4, axes = FALSE,
main = "Signature exposures per sample (absolute)")
axis(side = 2, cex.axis = 1.1, las = 2, line = -2)
mtext(text = "Mutations", side = 2, line = 2.5)
# Legend
# expand legend box horizontally if there are lots of signatures
LEGENDCOLS <- max(2, ceiling(NSIG / 10))
legend(legend_pos, bty = "n", ncol = LEGENDCOLS, xpd = TRUE, inset = c(0.035, 0),
fill = sigcols, border = sigcols, legend = colnames(exposures))
# Plot relative exposures
bars <- barplot(t(exposures), col = sigcols, las = las, lwd = 0.25,
cex.names = 0.8, cex.main = 1.4, axes = FALSE,
main = "Signature exposures per sample (relative)")
axis(side = 2, cex.axis = 1.1, las = 2, line = -2)
mtext(text = "Mutation fraction", side = 2, line = 2.5)
}
par(mfrow = c(1, 1), lwd = 1)
if (!is.null(pdf_path)) {
dev.off()
}
}
<file_sep>/inst/doc/sigfit_vignette.R
## ----setup, include=FALSE------------------------------------------------
knitr::opts_chunk$set(echo = TRUE)
suppressPackageStartupMessages(library(sigfit))
par(mar = c(6, 4, 6, 4))
## ----devtools_instructions, eval=FALSE-----------------------------------
# devtools::install_github("kgori/sigfit", args = "--preclean", build_vignettes = TRUE)
## ----fetch---------------------------------------------------------------
data("cosmic_signatures", package = "sigfit")
## ----sim-----------------------------------------------------------------
set.seed(1)
probs <- c(0.4, 0.3, 0.2, 0.1) %*% as.matrix(cosmic_signatures[c(1, 3, 7, 11), ])
mutations <- matrix(rmultinom(1, 20000, probs), nrow = 1)
colnames(mutations) <- colnames(cosmic_signatures)
## ----plotsim, fig.width=17, fig.height=7, out.width="100%", echo=-1------
par(mar = c(6,4,5,1))
sigfit::plot_spectrum(mutations)
## ----fitting, warning=FALSE----------------------------------------------
mcmc_samples_fit <- sigfit::fit_signatures(counts = mutations,
signatures = cosmic_signatures,
iter = 2000,
warmup = 1000,
chains = 1,
seed = 1)
## ----retrieve_exp--------------------------------------------------------
exposures <- retrieve_pars(mcmc_samples_fit,
feature = "exposures",
hpd_prob = 0.90,
signature_names = rownames(cosmic_signatures))
names(exposures)
exposures$mean
## ----plot_exp, fig.width=12, fig.height=5, out.width='100%', fig.align="center", echo=-1----
par(mar=c(7,4,3,0))
sigfit::plot_exposures(mutations,
mcmc_samples = mcmc_samples_fit,
signature_names = rownames(cosmic_signatures))
## ----reconstruct, fig.width=25, fig.height=17, out.width='100%', warning=FALSE, results="hide", echo=-1----
par(mar=c(6.5,6,5.5,2))
sigfit::plot_reconstruction(mutations,
mcmc_samples = mcmc_samples_fit,
signatures = cosmic_signatures,
pdf_path = NULL)
## ----plot_all, eval=FALSE------------------------------------------------
# ## This is an illustratrive example and will not be run
# sigfit::plot_all(mutations,
# out_path = "your/output/dir/here",
# mcmc_samples = mcmc_samples_fit,
# signatures = cosmic_signatures,
# prefix = "Fitting")
## ----load_mutations------------------------------------------------------
data("variants_21breast", package = "sigfit")
head(variants_21breast)
## ----show_samples--------------------------------------------------------
unique(variants_21breast[, 1])
## ----build_catalogues----------------------------------------------------
counts_21breast <- build_catalogues(variants_21breast)
dim(counts_21breast)
## ----plot_spectra, fig.width=22, fig.height=25, out.width='100%', fig.align="center", echo=-1----
par(mar = c(5,6,7,2))
par(mfrow = c(7, 3))
sigfit::plot_spectrum(counts_21breast)
## ----extraction, eval=FALSE----------------------------------------------
# mcmc_samples_extr <- sigfit::extract_signatures(counts_21breast,
# nsignatures = 2:7,
# iter = 1000,
# seed = 1)
## ----plot_gof_silent, echo=FALSE, fig.width=9, fig.height=6, out.width="100%"----
## Plot precalculated GOF in order to avoid running the model
data("sigfit_vignette_data", package = "sigfit")
plot(nS, gof, type = "o", lty = 3, pch = 16, col = "dodgerblue4",
main = paste0("Goodness of fit (", stat, ")\nmodel: NMF"),
xlab = "Number of signatures",
ylab = paste0("Goodness of fit (", stat, ")"))
points(nS[best], gof[best], pch = 16, col = "orangered", cex = 1.1)
cat("Estimated best number of signatures:", nS[best], "\n")
## ----retrieve_sigs, eval=FALSE-------------------------------------------
# ## Note: mcmc_samples_extr[[N]] contains the extraction results for N signatures
# extr_signatures <- retrieve_pars(mcmc_samples_extr[[4]],
# feature = "signatures")
## ----show_signames-------------------------------------------------------
rownames(extr_signatures$mean)
## ----plot_sigs, warning=FALSE, fig.width=22, fig.height=10, out.width='100%', fig.align="center", echo=-1----
par(mar = c(6,7,6,1))
par(mfrow = c(2, 2))
sigfit::plot_spectrum(extr_signatures)
<file_sep>/README.md
# sigfit
### Discovering mutational signatures through Bayesian inference
sigfit is an R package to estimate signatures of mutational processes and their activities on mutation count data. Starting from a set of single-nucleotide variants (SNVs), it allows both estimation of the exposure of samples to predefined mutational signatures (including whether the signatures are present at all), and identification signatures _de novo_ from the mutation counts. These two procedures are often called, respectively, signature fitting and signature extraction. Furthermore, the signature fitting and extraction methods in sigfit can be seamlessly applied to mutational profiles beyond SNV data, including insertion/deletion (indel) or rearrangement count data. The package provides a range of functions to generate publication-quality graphics of the corresponding mutational catalogues, signatures and exposures.
## Installation
sigfit is an R package. As it is in early development it is not yet on CRAN, but can be installed from inside an R session using the devtools library.
devtools::install_github("kgori/sigfit", args = "--preclean", build_vignettes = TRUE)
## Usage guide
See the package vignette for detailed usage examples:
browseVignettes("sigfit")
You can also browse the package vignette in [GitHub](http://htmlpreview.github.io/?https://github.com/kgori/sigfit/blob/dev/inst/doc/sigfit_vignette.html).
<file_sep>/R/sigfit_estimation.R
#' Fit mutational signatures
#'
#' \code{fit_signatures} runs MCMC sampling to fit a set of mutational signatures
#' to a collection of mutational catalogues and estimate the exposure of each
#' catalogue to each signature.
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param signatures Mutational signatures to be fitted. Either a numeric matrix with one row per signature
#' and one column for each of the 96 mutation types, or a list of signatures generated via
#' \code{\link{retrieve_pars}}.
#' @param exp_prior Numeric vector with one element per signature, to be used as the Dirichlet prior for
#' the signature exposures in the sampling chain. Default prior is uniform (uninformative).
#' @param method Character; model to sample from. Admits values \code{"nmf"} (default) or \code{"emu"}.
#' @param opportunities Numeric matrix of optional mutational opportunities for the "EMu" model
#' (\code{method = "emu"}) method. Must be a matrix with same dimension as \code{counts}.
#' Alternatively, it also admits character values \code{"human-genome"} or \code{"human-exome"},
#' in which case the reference human genome/exome opportunities will be used for every sample.
#' @param ... Arguments to pass to \code{rstan::sampling}.
#' @return A stanfit object containing the Monte Carlo samples from MCMC (from which the model
#' parameters can be extracted using \code{\link{retrieve_parameters}}), as well as information about
#' the model and sampling process.
#' @examples
#' # Load example mutational catalogues
#' data("counts_21breast")
#'
#' # Fetch COSMIC signatures
#' signatures <- fetch_cosmic_data()
#'
#' # Fit signatures 1 to 4, using a custom prior that favors signature 1 over the rest
#' # (4 chains, 300 warmup iterations + 300 sampling iterations -- use more in practice)
#' samples_1 <- fit_signatures(counts_21breast, signatures[1:4, ],
#' exp_prior = c(10, 1, 1, 1), iter = 600)
#'
#' # Fit all the signatures, running a single chain for many iterations
#' # (3000 warmup iterations + 10000 sampling iterations)
#' samples_2 <- fit_signatures(counts_21breast, signatures, chains = 1,
#' iter = 13000, warmup = 3000)
#' @useDynLib sigfit, .registration = TRUE
#' @importFrom "rstan" sampling
#' @export
fit_signatures <- function(counts, signatures, exp_prior = NULL, method = "nmf",
opportunities = NULL, ...) {
# Force counts and signatures to matrix
counts <- to_matrix(counts)
signatures <- to_matrix(signatures)
# Add pseudocounts to signatures
signatures <- remove_zeros_(signatures)
NSAMP <- nrow(counts)
NCAT <- ncol(counts)
NSIG <- nrow(signatures)
strand <- NCAT == 192 # strand bias indicator
# Check exposure priors
if (is.null(exp_prior)) {
exp_prior = rep(1, NSIG)
}
exp_prior <- as.numeric(exp_prior)
# Check dimensions are correct. Should be:
# counts[NSAMPLES, NCAT], signatures[NSIG, NCAT]
stopifnot(ncol(signatures) == NCAT)
stopifnot(length(exp_prior) == NSIG)
if (method == "emu") {
if (is.null(opportunities)) {
warning("Extracting with EMu model, but no opportunities provided.")
}
if (is.null(opportunities) | is.character(opportunities)) {
opportunities <- build_opps_matrix(NSAMP, opportunities, strand)
}
else if (!is.matrix(opportunities)) {
opportunities <- as.matrix(opportunities)
}
stopifnot(all(dim(opportunities) == dim(counts)))
dat <- list(
C = NCAT,
S = NSIG,
G = NSAMP,
signatures = signatures,
counts = counts,
opps = opportunities,
kappa = exp_prior
)
model <- stanmodels$sigfit_fit_emu
}
else {
dat <- list(
C = NCAT,
S = NSIG,
G = NSAMP,
signatures = signatures,
counts = counts,
kappa = exp_prior
)
model <- stanmodels$sigfit_fit_nmf
}
sampling(model, data = dat, pars = "multiplier", include = FALSE, ...)
}
#' Use optimization to generate initial parameter values for MCMC sampling
#' @export
extract_signatures_initialiser <- function(counts, nsignatures, method = "emu", opportunities = NULL,
sig_prior = NULL, chains = 1, ...) {
opt <- extract_signatures(counts, nsignatures, method, opportunities,
sig_prior, "optimizing", FALSE, ...)
if (is.null(opt)) {
warning("Parameter optimization failed - using random initialization")
inits <- "random"
}
else {
params <- list(
signatures = matrix(opt$par[grepl("signatures", names(opt$par))], nrow = nsignatures),
activities = matrix(opt$par[grepl("activities", names(opt$par))], nrow = nrow(counts)),
exposures = matrix(opt$par[grepl("exposures", names(opt$par))], nrow = nrow(counts))
)
inits = list()
for (i in 1:chains) inits[[i]] <- p
}
inits
}
#' Extract signatures from a set of mutation counts
#'
#' \code{extract_signatures} runs MCMC sampling to extract a set of mutational signatures
#' and their exposures from a collection of mutational catalogues.
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param nsignatures Integer or integer vector; number(s) of signatures to extract.
#' @param method Character; model to sample from. Admits values \code{"nmf"} (default) or \code{"emu"}.
#' @param opportunities Numeric matrix of optional mutational opportunities for the "EMu" model
#' (\code{method = "emu"}) method. Must be a matrix with same dimension as \code{counts}.
#' Alternatively, it also admits character values \code{"human-genome"} or \code{"human-exome"},
#' in which case the reference human genome/exome opportunities will be used for every sample.
#' @param sig_prior Numeric matrix with one row per signature and one column per category, to be used as the Dirichlet
#' priors for the signatures to be extracted. Only used when \code{nsignatures} is a scalar.
#' Default priors are uniform (uninformative).
#' @param exp_prior Numeric; hyperparameter of the Dirichlet prior given to the exposures. Default value is 1 (uniform, uninformative).
#' @param stanfunc Character; choice of rstan inference strategy. Admits values \code{"sampling"}, \code{"optimizing"}
#' and \code{"vb"}. \code{"sampling"} is the full Bayesian MCMC approach, and is the default.
#' \code{"optimizing"} returns the Maximum a Posteriori (MAP) point estimates via numerical optimization.
#' \code{"vb"} uses Variational Bayes to approximate the full posterior.
#' @param ... Any other parameters to pass to the sampling function (by default, \code{\link{rstan::sampling}}).
#' (The number of chains is set to 1 and cannot be changed, to prevent 'label switching' problems.)
#' @return A stanfit object containing the Monte Carlo samples from MCMC (from which the model
#' parameters can be extracted using \code{\link{retrieve_parameters}}), as well as information about
#' the model and sampling process.
#' @examples
#' # Load example mutational catalogues
#' data("counts_21breast")
#'
#' # Extract 2 to 6 signatures using the NMF (multinomial) model
#' # (400 warmup iterations + 400 sampling iterations -- use more in practice)
#' samples_nmf <- extract_signatures(counts_21breast, nsignatures = 2:6,
#' method = "nmf", iter = 800)
#'
#' # Extract 4 signatures using the EMu (Poisson) model
#' # (400 warmup iterations + 800 sampling iterations -- use more in practice)
#' samples_emu <- extract_signatures(counts_21breast, nsignatures = 4, method = "emu",
#' opportunities = "human-genome",
#' iter = 1200, warmup = 400)
#' @useDynLib sigfit, .registration = TRUE
#' @importFrom "rstan" sampling
#' @importFrom "rstan" optimizing
#' @importFrom "rstan" vb
#' @importFrom "rstan" extract
#' @export
extract_signatures <- function(counts, nsignatures, method = "nmf", opportunities = NULL,
sig_prior = NULL, exp_prior = 1, stanfunc = "sampling", ...) {
if (!is.null(sig_prior) & length(nsignatures) > 1) {
stop("'sig_prior' is only admitted when 'nsignatures' is a scalar (single value).")
}
stopifnot(is.numeric(exp_prior) & exp_prior > 0)
# Force counts to matrix
counts <- to_matrix(counts)
NSAMP <- nrow(counts)
NCAT <- ncol(counts)
strand <- NCAT == 192 # strand bias indicator
# EMu model
if (method == "emu") {
if (is.null(opportunities)) {
warning("Extracting with EMu model, but no opportunities provided.")
}
# Build opportunities matrix
if (is.null(opportunities) | is.character(opportunities)) {
opportunities <- build_opps_matrix(NSAMP, opportunities, strand)
}
else if (!is.matrix(opportunities)) {
opportunities <- as.matrix(opportunities)
}
stopifnot(all(dim(opportunities) == dim(counts)))
model <- stanmodels$sigfit_ext_emu
dat <- list(
C = NCAT,
G = NSAMP,
S = as.integer(nsignatures[1]),
counts = counts,
opps = opportunities,
alpha = sig_prior
)
}
# NMF model
else if (method == "nmf") {
if (!is.null(opportunities)) {
warning("Extracting with NMF model: 'opportunities' will not be used.")
}
model <- stanmodels$sigfit_ext_nmf
dat <- list(
C = NCAT,
G = NSAMP,
S = as.integer(nsignatures[1]),
counts = counts,
alpha = sig_prior,
kappa = exp_prior
)
}
else {
stop("'method' must be either \"emu\" or \"nmf\".")
}
# Extract signatures for each nsignatures value
if (length(nsignatures) > 1) {
out <- vector(mode = "list", length = max(nsignatures))
for (n in nsignatures) {
# Complete model data
dat$alpha <- matrix(1, nrow = n, ncol = NCAT)
dat$S <- as.integer(n)
cat("Extracting", n, "signatures\n")
if (stanfunc == "sampling") {
cat("Stan sampling:")
out[[n]] <- sampling(model, data = dat, chains = 1, ...)
}
else if (stanfunc == "optimizing") {
cat("Stan optimizing:")
out[[n]] <- optimizing(model, data = dat, ...)
}
else if (stanfunc == "vb") {
cat("Stan vb:")
out[[n]] <- vb(model, data = dat, ...)
}
}
names(out) <- paste0("nsignatures=", 1:length(out))
# Plot goodness of fit and best number of signatures
out$best <- plot_gof(out, counts)
}
# Single nsignatures value case
else {
# Check signature priors
if (is.null(sig_prior)) {
sig_prior <- matrix(1, nrow = nsignatures, ncol = NCAT)
}
sig_prior <- as.matrix(sig_prior)
stopifnot(nrow(sig_prior) == nsignatures)
stopifnot(ncol(sig_prior) == NCAT)
dat$alpha <- sig_prior
cat("Extracting", nsignatures, "signatures\n")
if (stanfunc == "sampling") {
cat("Stan sampling:")
out <- sampling(model, data = dat, chains = 1, ...)
}
else if (stanfunc == "optimizing") {
cat("Stan optimizing:")
out <- optimizing(model, data = dat, ...)
}
else if (stanfunc == "vb") {
cat("Stan vb:")
out <- vb(model, data = dat, ...)
}
}
out
}
#' Fit-and-extract mutational signatures
#'
#' \code{fit_extract_signatures} fits signatures to estimate exposures in a set of mutation counts
#' and extracts additional signatures present in the samples.
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param signatures Fixed mutational signatures to be fitted. Either a numeric matrix with one row
#' per signature and one column for each of the 96 mutation types, or a list of signatures generated via
#' \code{\link{retrieve_pars}}.
#' @param num_extra_sigs Numeric; number of additional signatures to be extracted.
#' @param sig_prior Numeric matrix with one row per additional signature and one column per category, to be used as the
#' Dirichlet priors for the additional signatures to be extracted. Default priors are uniform (uninformative).
#' @param exp_prior Numeric; hyperparameter of the Dirichlet prior given to the exposures. Default value is 1 (uniform, uninformative).
#' @param stanfunc \code{"sampling"}|\code{"optimizing"}|\code{"vb"} Choice of rstan
#' inference strategy. \code{"sampling"} is the full Bayesian MCMC approach, and is the
#' default. \code{"optimizing"} returns the Maximum a Posteriori (MAP) point estimates
#' via numerical optimization. \code{"vb"} uses Variational Bayes to approximate the
#' full posterior.
#' @param ... Any other parameters to pass to the sampling function (by default, \code{\link{rstan::sampling}}).
#' (The number of chains is set to 1 and cannot be changed, to prevent 'label switching' problems.)
#' @return A stanfit object containing the Monte Carlo samples from MCMC (from which the model
#' parameters can be extracted using \code{\link{retrieve_parameters}}), as well as information about
#' the model and sampling process.
#' @examples
#' # Fetch COSMIC signatures
#' signatures <- fetch_cosmic_data()
#'
#' # Simulate two catalogues using signatures 1, 4, 5, 7, with
#' # proportions 4:2:3:1 and 2:3:4:1, respectively
#' probs <- rbind(c(0.4, 0.2, 0.3, 0.1) %*% signatures[c(1, 4, 5, 7), ],
#' c(0.2, 0.3, 0.4, 0.1) %*% signatures[c(1, 4, 5, 7), ])
#' mutations <- rbind(t(rmultinom(1, 20000, probs[1, ])),
#' t(rmultinom(1, 20000, probs[2, ])))
#'
#' # Assuming that we do not know signature 7 a priori, but we know the others
#' # to be present, extract 1 signature while fitting signatures 1, 4 and 5.
#' # (400 warmup iterations + 400 sampling iterations -- use more in practice)
#' mcmc_samples <- fit_extract_signatures(mutations, signatures = signatures[c(1, 4, 5), ],
#' num_extra_sigs = 1, method = "nmf", iter = 800)
#'
#' # Plot original and extracted signature 7
#' extr_sigs <- retrieve_pars(mcmc_samples, "signatures")
#' plot_spectrum(signatures[7, ], pdf_path = "COSMIC_Sig7.pdf", name="COSMIC sig. 7")
#' plot_spectrum(extr_sigs, pdf_path = "Extracted_Sigs.pdf")
#' @useDynLib sigfit, .registration = TRUE
#' @importFrom "rstan" sampling
#' @importFrom "rstan" optimizing
#' @importFrom "rstan" vb
#' @export
fit_extract_signatures <- function(counts, signatures, num_extra_sigs,
method = "nmf", opportunities = NULL, sig_prior = NULL, exp_prior = 1,
stanfunc = "sampling", ...) {
# Check that num_extra_sigs is scalar
if (length(num_extra_sigs) > 1) {
stop("'num_extra_sigs' must be an integer scalar.")
}
stopifnot(is.numeric(exp_prior) & exp_prior > 0)
# Force counts and signatures to matrix
counts <- to_matrix(counts)
signatures <- to_matrix(signatures)
# Add pseudocounts to signatures
signatures <- remove_zeros_(signatures)
NSAMP <- nrow(counts)
NCAT <- ncol(counts)
NSIG <- nrow(signatures)
strand <- NCAT == 192 # strand bias indicator
# Check dimensions are correct. Should be:
# counts[NSAMPLES, NCAT], signatures[NSIG, NCAT]
stopifnot(ncol(signatures) == NCAT)
# Check signature priors
if (is.null(sig_prior)) {
sig_prior <- matrix(1, nrow = num_extra_sigs, ncol = NCAT)
}
sig_prior <- as.matrix(sig_prior)
stopifnot(nrow(sig_prior) == num_extra_sigs)
stopifnot(ncol(sig_prior) == NCAT)
# EMu model
if (method == "emu") {
# Build opportunities matrix
if (is.null(opportunities) | is.character(opportunities)) {
opportunities <- build_opps_matrix(NSAMP, opportunities, strand)
}
else if (!is.matrix(opportunities)) {
opportunities <- as.matrix(opportunities)
}
stopifnot(all(dim(opportunities) == dim(counts)))
model <- stanmodels$sigfit_fitex_emu
dat <- list(
C = NCAT,
S = NSIG,
G = NSAMP,
N = as.integer(num_extra_sigs),
fixed_sigs = signatures,
counts = counts,
opps = opportunities,
alpha = sig_prior
)
}
# NMF model
else if (method == "nmf") {
model <- stanmodels$sigfit_fitex_nmf
dat <- list(
C = NCAT,
S = NSIG,
G = NSAMP,
N = as.integer(num_extra_sigs),
fixed_sigs = signatures,
counts = counts,
alpha = sig_prior,
kappa = exp_prior
)
}
if (stanfunc == "sampling") {
cat("Stan sampling:")
sampling(model, data = dat, chains = 1,
pars = "extra_sigs", include = FALSE, ...)
}
else if (stanfunc == "optimizing") {
cat("Stan optimizing:")
optimizing(model, data = dat, ...)
}
else if (stanfunc == "vb") {
cat("Stan vb")
vb(model, data = dat, ...)
}
}
<file_sep>/R/sigfit_utility.R
#' Find the best matches between two sets of signatures
#'
#' \code{match_signatures} compares two independent estimates of signatures to
#' find the closest matches between them.
#' @param sigs_a Signatures estimate; either a list such as one produced by
#' \code{\link{retrieve_pars}}, with a \code{$mean} entry, or a numeric matrix with one
#' row per signature and one column for each of the 96 mutation types.
#' @param sigs_b Signatures estimate as for \code{sigs_a}.
#' @return A numeric vector containing, for each signature in \code{sigs_a}, the index
#' of the closest match in \code{sigs_b}.
#' @importFrom "clue" solve_LSAP
#' @export
match_signatures <- function(sigs_a, sigs_b) {
if ("mean" %in% names(sigs_a)) a <- sigs_a$mean
else a <- sigs_a
if ("mean" %in% names(sigs_b)) b <- sigs_b$mean
else b <- sigs_b
nA <- nrow(a)
nB <- nrow(b)
stopifnot(nA == nB)
m <- matrix(0.0, nrow = nA, ncol = nB)
for (i in 1:nA) {
for (j in 1:nB) {
m[i, j] <- cosine_sim(a[i, ], b[j, ])
}
}
solve_LSAP(m, maximum = TRUE)
}
#' Initial coercion to matrix for signatures/exposures/counts
to_matrix <- function(x) {
# If x is coming from retrieve_pars, get mean
if (is.list(x) & "mean" %in% names(x)) x <- x$mean
# If x is a vector, transform to 1-row matrix
if (is.vector(x)) x <- matrix(x, nrow = 1)
# Otherwise, try coercing to matrix
if (!is.matrix(x)) x <- as.matrix(x)
x
}
#' Build a opportunities matrix
build_opps_matrix <- function(nsamples, keyword, strand) {
if (is.null(keyword)) {
# Uniform opps are approximated from the sum of human genome frequencies
NCAT <- ifelse(strand, 192, 96)
matrix(rep(rep(round(sum(human_trinuc_freqs()) / NCAT), NCAT),
nsamples),
nrow = nsamples,
byrow = TRUE)
}
else {
matrix(rep(human_trinuc_freqs(keyword, strand), nsamples),
nrow = nsamples,
byrow = TRUE)
}
}
#' Cosine similarity between two vectors
cosine_sim <- function(x, y) { x %*% y / sqrt(x%*%x * y%*%y) }
#' L2 norm between two vectors
l2_norm <- function(x, y) { sqrt(sum((x - y)^2)) }
#' Deal with zero values in a signature
remove_zeros_ <- function(mtx, min_allowed = 1e-9) {
as.matrix(
t(apply(mtx, 1, function(row) {
row[row < min_allowed] <- min_allowed
row / sum(row)
}))
)
}
#' From https://stackoverflow.com/a/21689613/1875814
#' Produce Excel-style letter labels - A, B, ..., Z, AA, AB, ..., AZ, ..., ZZ, AAA, ...
letterwrap <- function(n, depth = 1) {
args <- lapply(1:depth, FUN = function(x) return(LETTERS))
x <- do.call(expand.grid, args = list(args, stringsAsFactors = F))
x <- x[, rev(names(x)), drop = F]
x <- do.call(paste0, x)
if (n <= length(x)) return(x[1:n])
return(c(x, letterwrap(n - length(x), depth = depth + 1)))
}
#' Reverse complement a nucleotide sequence string
#' Input is string, output is character vector
rev_comp <- function(nucleotides) {
as.character(rev(sapply(strsplit(nucleotides, "")[[1]], function(nuc) {
if (nuc == "A") "T"
else if (nuc == "C") "G"
else if (nuc == "G") "C"
else if (nuc == "T") "A"
})))
}
#' Generate default colour palette for signatures
default_sig_palette <- function(n) {
rep(c("#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E", "#E6AB02",
"#A6761D", "#666666", "#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
"#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"),
5)[1:n]
}
#' Generates character vector of 96 (or 192, if strand=T) trinucleotide mutation types
mut_types <- function(strand = FALSE) {
bases <- c("A", "C", "G", "T")
muts <- paste0(rep(rep(bases, each = 4), 6),
rep(bases[c(2, 4)], each = 48),
rep(bases, 6 * 16 / 4),
">",
rep(rep(bases, each = 4), 6),
c(rep(bases[-2], each = 16), rep(bases[-4], each = 16)),
rep(bases, 6 * 16 / 4))
if (strand) {
paste(c(rep("T", 96), rep("U", 96)), muts, sep = ":")
}
else {
muts
}
}
#' Access stan models
#' @export
stan_models <- function() {
stanmodels
}
#' Retrieve human trinucleotide frequencies
#'
#' \code{human_trinuc_freqs} returns the reference human genome or exome
#' trinucleotide frequencies.
#' @param type Character; either \code{"genome"} (default) or \code{"exome"}.
#' @param strand Logical; if \code{TRUE}, a strandwise representation of catalogues
#' and signatures will be used.
#' @return A numeric vector containinig 96 frequency values (one per trinucleotide type), if
#' \code{strand=FALSE}, or 192 frequency values (one per trinucleotide and strand type), if
#' \code{strand=TRUE}. In the latter case, the trinucleotide frequencies are assumed to be
#' equally distributed between the two strands.
#' @export
human_trinuc_freqs <- function(type = "human-genome", strand = FALSE) {
if (type == "human-genome") {
# Human genome trinucleotide frequencies (from EMu)
freq <- c(1.14e+08, 6.60e+07, 1.43e+07, 9.12e+07, # C>A @ AC[ACGT]
1.05e+08, 7.46e+07, 1.57e+07, 1.01e+08, # C>A @ CC[ACGT]
8.17e+07, 6.76e+07, 1.35e+07, 7.93e+07, # C>A @ GC[ACGT]
1.11e+08, 8.75e+07, 1.25e+07, 1.25e+08, # C>A @ TC[ACGT]
1.14e+08, 6.60e+07, 1.43e+07, 9.12e+07, # C>G @ AC[ACGT]
1.05e+08, 7.46e+07, 1.57e+07, 1.01e+08, # C>G @ CC[ACGT]
8.17e+07, 6.76e+07, 1.35e+07, 7.93e+07, # C>G @ GC[ACGT]
1.11e+08, 8.75e+07, 1.25e+07, 1.25e+08, # C>G @ TC[ACGT]
1.14e+08, 6.60e+07, 1.43e+07, 9.12e+07, # C>T @ AC[ACGT]
1.05e+08, 7.46e+07, 1.57e+07, 1.01e+08, # C>T @ CC[ACGT]
8.17e+07, 6.76e+07, 1.35e+07, 7.93e+07, # C>T @ GC[ACGT]
1.11e+08, 8.75e+07, 1.25e+07, 1.25e+08, # C>T @ TC[ACGT]
1.17e+08, 7.57e+07, 1.04e+08, 1.41e+08, # T>A @ AC[ACGT]
7.31e+07, 9.55e+07, 1.15e+08, 1.13e+08, # T>A @ CC[ACGT]
6.43e+07, 5.36e+07, 8.52e+07, 8.27e+07, # T>A @ GC[ACGT]
1.18e+08, 1.12e+08, 1.07e+08, 2.18e+08, # T>A @ TC[ACGT]
1.17e+08, 7.57e+07, 1.04e+08, 1.41e+08, # T>C @ AC[ACGT]
7.31e+07, 9.55e+07, 1.15e+08, 1.13e+08, # T>C @ CC[ACGT]
6.43e+07, 5.36e+07, 8.52e+07, 8.27e+07, # T>C @ GC[ACGT]
1.18e+08, 1.12e+08, 1.07e+08, 2.18e+08, # T>C @ TC[ACGT]
1.17e+08, 7.57e+07, 1.04e+08, 1.41e+08, # T>G @ AC[ACGT]
7.31e+07, 9.55e+07, 1.15e+08, 1.13e+08, # T>G @ AC[ACGT]
6.43e+07, 5.36e+07, 8.52e+07, 8.27e+07, # T>G @ AG[ACGT]
1.18e+08, 1.12e+08, 1.07e+08, 2.18e+08) # T>G @ AT[ACGT]
}
else if (type == "human-exome") {
# Human exome trinucleotide frequencies (from EMu)
freq <- c(1940794, 1442408, 514826, 1403756,
2277398, 2318284, 774498, 2269674,
1740752, 1968596, 631872, 1734468,
1799540, 1910984, 398440, 2024770,
1940794, 1442408, 514826, 1403756,
2277398, 2318284, 774498, 2269674,
1740752, 1968596, 631872, 1734468,
1799540, 1910984, 398440, 2024770,
1940794, 1442408, 514826, 1403756,
2277398, 2318284, 774498, 2269674,
1740752, 1968596, 631872, 1734468,
1799540, 1910984, 398440, 2024770,
1299256, 1166912, 1555012, 1689928,
978400, 2119248, 2650754, 1684488,
884052, 1173252, 1993110, 1251508,
1391660, 1674368, 1559846, 2850934,
1299256, 1166912, 1555012, 1689928,
978400, 2119248, 2650754, 1684488,
884052, 1173252, 1993110, 1251508,
1391660, 1674368, 1559846, 2850934,
1299256, 1166912, 1555012, 1689928,
978400, 2119248, 2650754, 1684488,
884052, 1173252, 1993110, 1251508,
1391660, 1674368, 1559846, 2850934)
}
else {
stop("'type' must be either \"human-genome\" or \"human-exome\"")
}
if (strand) {
rep(freq / 2, 2)
}
else {
freq
}
}
#' Build mutational catalogues
#'
#' \code{build_catalogues} generates a set of mutational catalogues from a table containing
#' the base change and trinucleotide context of each single-nucleotide variant in every sample.
#' @param variants Character matrix with one row per single-nucleotide variant, and four (or five) columns:
#' \itemize{
#' \item{Sample ID (character, e.g. "Sample 1").}
#' \item{Reference allele (character: "A", "C", "G", or "T").}
#' \item{Alternate allele (character: "A", "C", "G", or "T").}
#' \item{Trinucleotide context of the variant (character; the reference sequence between the positions
#' immediately before and after the variant; e.g. "TCA").}
#' \item{Optional: transcriptional strand of the variant (character: "T" for transcribed,
#' or "U" for untranscribed). If this column is included, a strandwise representation of
#' catalogues will be used.}
#' }
#' @return An integer matrix of mutation counts, where each row corresponds to a sample and each column
#' corresponds to one of the 96 trinucleotide mutation types.
#' @examples
#' # Load example mutation data
#' data("variants_21breast")
#' head(variants_21breast)
#'
#' # Build catalogues
#' counts <- build_catalogues(variants_21breast)
#' counts
#' @export
build_catalogues <- function(variants) {
if (!(ncol(variants) %in% c(4, 5))) {
stop("'variants' must be a matrix with 4 or 5 columns and one row per variant.\nType ?build_catalogues to see the documentation.")
}
if (ncol(variants) == 5) {
if (!all(unique(variants[, 5] %in% c("T", "U")))) {
stop("The fifth column of 'variants' (transcriptional strand) can only contain \"T\" or \"U\" values.\nType ?build_catalogues to see the documentation.")
}
cat("'variants' has 5 columns: strand-bias catalogues will be generated\n")
strand <- TRUE
}
else {
strand <- FALSE
}
# Check that REF base coincides with middle base in trinucleotide
if (any(variants[, 2] != substr(variants[, 4], 2, 2))) {
stop("REF base (column 2) is not equal to middle base of the trinucleotide (column 4).")
}
# Make catalogue matrix with one row per sample
samples <- unique(variants[, 1])
catalogues <- t(sapply(samples, function(sample) {
# Select mutations from sample
idx <- variants[, 1] == sample
# Obtain mutation types, collapsed such that they refer to pyrimidine bases
vars_collapsed <- apply(variants[idx, ], 1, function(var) {
if (var[2] %in% c("C", "T")) {
trinuc <- strsplit(var[4], "")[[1]]
alt <- var[3]
if (strand) {
strd <- var[5]
}
}
else {
trinuc <- rev_comp(var[4])
alt <- rev_comp(var[3])
if (strand) {
strd <- ifelse(var[5] == "U", "T", "U")
}
}
if (strand) {
paste0(strd, ":", paste(trinuc, collapse=""), ">", trinuc[1], alt, trinuc[3])
}
else {
paste0(paste(trinuc, collapse=""), ">", trinuc[1], alt, trinuc[3])
}
})
# Count number of occurrences of each mutation type
stopifnot(all(vars_collapsed %in% mut_types(strand)))
sapply(mut_types(strand), function(type) {
sum(grepl(type, vars_collapsed, fixed = TRUE))
})
}))
}
#' Fetch COSMIC mutational signatures
#'
#' \code{fetch_cosmic_data} downloads the latest release of signatures from COSMIC
#' (http://cancer.sanger.ac.uk/cosmic/signatures) and produces a matrix of signatures
#' that can be used for signature fitting.
#' @param reorder Logical; if \code{TRUE} (default), the matrix will be reordered by substitution type and trinucleotide.
#' @param remove_zeros Logical; if \code{TRUE} (default), pseudocounts will be added to prevent the signatures from
#' containing any zeros, which can affect computation of the log likelihood.
#' @return Matrix of signatures, with one row per signature and one column for each of
#' the 96 trinucleotide mutation types.
#' @importFrom "utils" read.table
#' @export
fetch_cosmic_data <- function(reorder = TRUE, remove_zeros = TRUE) {
cosmic_sigs <- read.table("http://cancer.sanger.ac.uk/cancergenome/assets/signatures_probabilities.txt",
header = TRUE, sep = "\t", check.names = FALSE)
if (reorder) {
cosmic_sigs <- cosmic_sigs[order(cosmic_sigs[["Substitution Type"]], cosmic_sigs[["Trinucleotide"]]),]
}
rownames(cosmic_sigs) <- mut_types()
cosmic_sigs <- t(cosmic_sigs[, paste("Signature", 1:30)])
if (remove_zeros) {
cosmic_sigs <- remove_zeros_(cosmic_sigs)
}
cosmic_sigs
}
#' Convert signatures between models
#'
#' \code{convert_signatures} converts between the representation of signatures used
#' in the NMF model (which is relative to the reference mutational opportunities), and
#' the representation used in the EMu model (which is not relative to mutational opportunities).
#' This is done by multiplying or dividing each signature by the average mutational opportunities
#' of the samples, or by the human genome/exome reference trinucleotide frequencies.
#' @param signatures Either a numeric matrix of mutational signatures, with one row per signature and one
#' column for each of the 96 (or 192) mutation types, or a list of signatures generated via
#' \code{\link{retrieve_pars}}.
#' @param ref_opportunities Numeric vector of reference or average mutational opportunities, with
#' one element for each of the 96 (or 192) mutation types. It can also take values \code{"human-genome"} or
#' \code{"human-exome"}, in which case the reference human genome/exome mutational opportunities will be used.
#' @param model_to Character; model to convert to: either \code{"nmf"} (in which case the signatures will
#' be multiplied by the opportunities) or \code{"emu"} (in which case the signatures will be divided
#' by the opportunities).
#' @return A numeric matrix of transformed signatures with the same dimensions as \code{signatures}.
#' @examples
#' # Fetch COSMIC signatures
#' # These are in "NMF" format, i.e. they are relative
#' # to the human genome mutational opportunities
#' signatures <- fetch_cosmic_data()
#'
#' # Plot COSMIC signature 1
#' barplot(signatures[1,])
#'
#' # Convert signatures to the "EMu" format, i.e. make
#' # them not relative to mutational opportunities
#' converted_signatures <- convert_signatures(signatures,
#' ref_opportunities = "human-genome",
#' model_to = "emu")
#'
#' # Plot COSMIC signature 1, converted to "EMu" format
#' barplot(converted_signatures[1,])
#' @export
convert_signatures <- function(signatures, ref_opportunities, model_to) {
signatures <- to_matrix(signatures)
stopifnot(ncol(signatures) %in% c(96, 192))
strand <- ncol(signatures) == 192
if (strand) {
cat("'signatures' contains 192 mutations types: using strand-bias opportunities.\n")
}
if (ref_opportunities %in% c("human-genome", "human-exome")) {
ref_opportunities <- human_trinuc_freqs(type = ref_opportunities, strand = strand)
}
ref_opportunities <- as.numeric(ref_opportunities)
if (length(ref_opportunities) != ncol(signatures)) {
stop("'ref_opportunities' must have one element for each column in 'signatures'.")
}
if (model_to == "nmf") {
t(apply(signatures, 1, function(row) {
x <- row * ref_opportunities
x / sum(x)
}))
}
else if (model_to == "emu") {
t(apply(signatures, 1, function(row) {
x <- row / ref_opportunities
x / sum(x)
}))
}
else {
stop("'model_to' must be either \"nmf\" or \"emu\".")
}
}
#' Retrieve model parameters
#'
#' \code{retrieve_pars} obtains summary values for a set of model parameters (signatures or exposures) from a stanfit object.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}.
#' @param feature Character; name of the parameter set to extract. Can take values: \code{"signatures"},
#' \code{"exposures"}, \code{"activities"} or \code{"reconstructions"}.
#' @param hpd_prob Numeric; a value in the interval (0, 1), giving the target probability content of
#' the HPD intervals.
#' @param signature_names Character vector containing the names of the signatures used for fitting. Used only when
#' retrieving exposures from fitted signatures.
#' @return A list of three matrices, which respectively contain the values corresponding to the
#' mean of the model parameter of interest, and those corresponding to the lower and upper ends of its HPD interval.
#' @examples
#' # Load example mutational catalogues
#' data("counts_21breast")
#'
#' # Extract signatures using the EMu (Poisson) model
#' samples <- extract_signatures(counts_21breast, nsignatures = 2, method = "emu",
#' opportunities = "human-genome", iter = 800)
#'
#' # Retrieve signatures
#' signatures <- retrieve_pars(samples, "signatures")
#'
#' # Retrieve exposures and activities using custom HPD intervals
#' exposures <- retrieve_pars(samples, "exposures", hpd_prob = 0.9)
#' activities <- retrieve_pars(samples, "activities", hpd_prob = 0.975)
#'
#' # Retrieve reconstructed catalogues (reconstructions)
#' reconstructions <- retrieve_pars(samples, "reconstructions")
#'
#' # Plot signatures, reconstructions and mean exposures
#' plot_spectrum(signatures)
#' plot_spectrum(reconstructions)
#' barplot(exposures$mean)
#' @importFrom "rstan" extract
#' @importFrom "coda" HPDinterval
#' @importFrom "coda" as.mcmc
#' @export
retrieve_pars <- function(mcmc_samples, feature, hpd_prob = 0.95, counts = NULL, signatures = NULL, opportunities = NULL, signature_names = NULL) {
if (feature == "reconstructions") {
if (is.null(counts)) {
stop("'counts' must be provided to retrieve reconstructions.")
}
NSAMP <- nrow(counts)
NCAT <- ncol(counts)
strand <- NCAT == 192 # strand bias indicator
if (is.null(opportunities) | is.character(opportunities)) {
opportunities <- build_opps_matrix(NSAMP, opportunities, strand)
}
else if (!is.matrix(opportunities)) {
opportunities <- as.matrix(opportunities)
}
l <- get_reconstructions(counts, mcmc_samples, signatures, opportunities)
feat_summ <- list(mean = apply(l$reconstructions, c(1, 3), sum),
lower = l$hpds[, 1, ],
upper = l$hpds[, 2, ])
}
else {
feat <- extract(mcmc_samples, pars = feature)[[feature]]
strand <- dim(feat)[3] == 192 # strand bias indicator
# Multi-sample case
if (length(dim(feat)) > 2) {
# Assign dimension names
if (feature == "signatures") {
names2 <- mut_types(strand)
if (is.null(signature_names)) {
LETTERLABELS <- letterwrap(dim(feat)[2])
names1 <- paste("Signature", LETTERLABELS[1:dim(feat)[2]])
}
else {
if (dim(feat)[2] != length(signature_names)) {
stop("'signature_names' must have length equal to the number of signatures.")
}
names1 <- signature_names
}
}
else if (feature %in% c("exposures", "activities")) {
names1 <- NULL
if (is.null(signature_names)) {
LETTERLABELS <- letterwrap(dim(feat)[3])
names2 <- paste("Signature", LETTERLABELS[1:dim(feat)[3]])
}
else {
if (dim(feat)[3] != length(signature_names)) {
stop("'signature_names' must have length equal to the number of signatures.")
}
names2 <- signature_names
}
}
# for signatures: Signatures x Categories matrix
# for exposures: Samples x Signatures matrix
feat_summ <- list(matrix(NA, nrow = dim(feat)[2], ncol = dim(feat)[3], dimnames = list(names1, names2)),
matrix(NA, nrow = dim(feat)[2], ncol = dim(feat)[3], dimnames = list(names1, names2)),
matrix(NA, nrow = dim(feat)[2], ncol = dim(feat)[3], dimnames = list(names1, names2)))
names(feat_summ) <- c("mean", paste0(c("lower_", "upper_"), hpd_prob * 100))
for (i in 1:nrow(feat_summ[[1]])) {
hpd <- HPDinterval(as.mcmc(feat[,i,]), prob = hpd_prob)
feat_summ[[1]][i,] <- colMeans(feat[,i,])
feat_summ[[2]][i,] <- hpd[,1]
feat_summ[[3]][i,] <- hpd[,2]
}
}
# Single-sample case (only possible when fitting)
else {
names1 <- NULL
if (is.null(signature_names)) {
LETTERLABELS <- letterwrap(dim(feat)[3])
names2 <- paste("Signature", LETTERLABELS[1:dim(feat)[3]])
}
else {
if (dim(feat)[3] != length(signature_names)) {
stop("'signature_names' must have length equal to the number of signatures.")
}
names2 <- signature_names
}
feat_summ <- list(matrix(NA, nrow = 1, ncol = dim(feat)[2], dimnames = list(names1, names2)),
matrix(NA, nrow = 1, ncol = dim(feat)[2], dimnames = list(names1, names2)),
matrix(NA, nrow = 1, ncol = dim(feat)[2], dimnames = list(names1, names2)))
names(feat_summ) <- c("mean", paste0(c("lower_", "upper_"), hpd_prob * 100))
for (i in 1:nrow(feat_summ[[1]])) {
hpd <- HPDinterval(as.mcmc(feat), prob = hpd_prob)
feat_summ[[1]][1,] <- colMeans(feat)
feat_summ[[2]][1,] <- hpd[,1]
feat_summ[[3]][1,] <- hpd[,2]
}
}
}
feat_summ
}
#' Generate posterior predictive check values from a model
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}.
#' @importFrom "stats" rmultinom rpois
#' @export
simulate_ppc <- function(counts, mcmc_samples) {
if (grepl("nmf", mcmc_samples@model_name)) {
e <- extract(mcmc_samples, pars = "probs")
ppc <- array(0, dim(e$probs))
for (i in 1:dim(e$probs)[1]) {
for (j in 1:dim(e$probs)[2]) {
ppc[i, j, ] <- t(
rmultinom(1, sum(counts[j, ]), e$probs[i, j, ])
)
}
}
}
else {
e <- extract(mcmc_samples, pars = "expected_counts")
ppc <- array(0, dim(e$expected_counts))
for (i in 1:dim(e$expected_counts)[1]) {
for (j in 1:dim(e$expected_counts)[2]) {
for (k in 1:dim(e$expected_counts)[3]) {
ppc[i, j, k] <- rpois(1, e$expected_counts[i, j, k])
}
}
}
}
ppc
}
#' Generate log likelihood values from a model
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}.
#' @importFrom "stats" dmultinom dpois
#' @export
get_loglik <- function(counts, mcmc_samples) {
dnames <- list(NULL, NULL)
names(dnames) <- c("iterations", "")
if (grepl("nmf", mcmc_samples@model_name)) {
e <- extract(mcmc_samples, pars = "probs")
nrep <- dim(e$probs)[1]
nsamples <- dim(e$probs)[2]
log_lik <- matrix(0, nrow = nrep, ncol = nsamples, dimnames = dnames)
for (i in 1:nrep) {
for (j in 1:nsamples) {
log_lik[i, j] <- dmultinom(counts[j, ], prob = e$probs[i, j, ], log = TRUE)
}
}
}
else {
e <- extract(mcmc_samples, pars = "expected_counts")
nrep <- dim(e$expected_counts)[1]
nsamples <- dim(e$expected_counts)[2]
log_lik <- matrix(0, nrow = nrep, ncol = nsamples, dimnames = dnames)
for (i in 1:nrep) {
for (j in 1:nsamples) {
log_lik[i, j] <- sum(dpois(counts[j, ], e$expected_counts[i, j, ], log = TRUE))
}
}
}
log_lik
}
#' Generate reconstructed mutation catalogues from parameters estimated from MCMC samples
#' @param counts Integer matrix of observed mutation counts, with one row per sample and
#' column for each of the 96 mutation types.
#' @param mcmc_samples Object of class stanfit, generated via either \code{\link{fit_signatures}}
#' or \code{\link{extract_signatures}}.
#' @param signatures Numeric matrix of signatures to use for fitting models, which produce no estimate of signatures.
#' @importFrom "rstan" extract
#' @importFrom "coda" HPDinterval
#' @export
get_reconstructions <- function(counts, mcmc_samples, signatures = NULL, opportunities = NULL) {
NCAT <- ncol(counts) # number of categories
NSAMP <- nrow(counts) # number of samples
e <- extract(mcmc_samples)
NREP <- dim(e$exposures)[1]
stopifnot(NSAMP == dim(e$exposures)[2])
NSIG <- dim(e$exposures)[3]
if (!"signatures" %in% names(e)) {
if (is.null(signatures)) {
stop("No signatures found in MCMC samples and no matrix of signatures provided.")
}
e$signatures <- aperm(
sapply(1:NREP, function(i) as.matrix(signatures), simplify = "array"),
c(3, 1, 2)
)
}
reconstructions <- array(NA, dim = c(NSAMP, NSIG, NCAT))
hpds <- array(NA, dim = c(NSAMP, 2, NCAT))
for (sample in 1:NSAMP) {
if (grepl("emu", mcmc_samples@model_name)) {
if (is.null(opportunities)) {
stop("Opportunities required to reconstruct counts modelled using the EMu method")
}
arr <- aperm(
sapply(1:NREP, function(i) {
sweep(e$activities[i, sample, ] * e$signatures[i, , ],
2, as.numeric(opportunities[sample, ]), `*`)
}, simplify = "array"),
c(3, 1, 2)
)
}
# For NMF results
else {
arr <- aperm(
sapply(1:NREP, function(i) {
e$exposures[i, sample, ] *
e$signatures[i, , ] *
sum(counts[sample, ])
}, simplify = "array"),
c(3, 1, 2)
)
}
reconstructions[sample, , ] <- apply(arr, c(2, 3), mean)
hpds[sample, , ] <- t(HPDinterval(
as.mcmc(apply(arr, c(1, 3), sum))
))
}
list(reconstructions = reconstructions, hpds = hpds, exposures = t(apply(e$exposures, 2, colMeans)))
}
<file_sep>/inst/doc/sigfit_vignette.Rmd
---
title: "Fitting and extracting mutational signatures with sigfit"
author: "<NAME> and <NAME> (2017)"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Usage guide}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
suppressPackageStartupMessages(library(sigfit))
par(mar = c(6, 4, 6, 4))
```
## Introduction
```sigfit``` is used to estimate signatures of mutational processes and their degree of activity on a collection of cancer (or normal) samples. Starting from a set of single-nucleotide variants (SNVs), it allows both estimation of the exposure of samples to predefined mutational signatures (including whether the signatures are present at all), and identification signatures _de novo_ from the mutation counts. These two procedures are often called, respectively, signature fitting and signature extraction. Furthermore, the signature fitting and extraction methods in ```sigfit``` can be seamlessly applied to mutational profiles beyond SNV data, including insertion/deletion (indel) or rearrangement count data. The package also provides a range of functions to generate publication-quality graphics of the corresponding mutational catalogues, signatures and exposures.
## Installation
```sigfit``` is an R package. As it is in early development it is not yet on CRAN, but can be installed from GitHub using the ```devtools``` library
```{r devtools_instructions, eval=FALSE}
devtools::install_github("kgori/sigfit", args = "--preclean", build_vignettes = TRUE)
```
## Usage guide
### Example 1: fitting signatures to a single simulated sample
This example will use the mutational signatures from [COSMIC](http://cancer.sanger.ac.uk/cosmic/signatures) to generate simulated mutation counts, and then use ```sigfit``` to fit the signatures back to the simulated data.
First of all we need some mutational signatures to fit to our data. The line below loads the mutational signatures published in COSMIC.
```{r fetch}
data("cosmic_signatures", package = "sigfit")
```
Let's use these signatures to simulate some mutation data. This code will generate 20,000 mutations from a 4:3:2:1 mixture of signatures 1, 3, 7 and 11.
```{r sim}
set.seed(1)
probs <- c(0.4, 0.3, 0.2, 0.1) %*% as.matrix(cosmic_signatures[c(1, 3, 7, 11), ])
mutations <- matrix(rmultinom(1, 20000, probs), nrow = 1)
colnames(mutations) <- colnames(cosmic_signatures)
```
Here is what our simulated counts look like:
```{r plotsim, fig.width=17, fig.height=7, out.width="100%", echo=-1}
par(mar = c(6,4,5,1))
sigfit::plot_spectrum(mutations)
```
#### Fitting signatures
Next, we can estimate the exposure of the data to each signature (pretending we ignore that it was generated from signatures 1, 3, 7 and 11). ```sigfit``` uses [Stan](http://mc-stan.org/) to run a Bayesian model that produces Markov chain Monte Carlo (MCMC) samples. Arguments to the ```rstan::sampling``` function, such as ```iter```, ```warmup```, etc., can be passed through. For further sampling options, type ```?rstan::sampling``` to read the documentation.
__In general, one should run as many MCMC iterations (```iter``` argument) as one's computer and patience allow, with runtime being the major constraint.__
We recommend that the number of warmup (burn-in) iterations (```warmup``` argument) be between one-third and half the value of ```iter```. The behaviour of the MCMC sampler (which ultimately affects the quality of the analysis) depends on parameters set during the warmup, so it is important to run plenty of warmup iterations. By default, ```rstan::sampling``` uses ```iter = 2000``` and ```warmup = floor(iter/2)```; we do not normally recommend going below these values. The ```seed``` argument can be used to make the MCMC samples reproducible over different runs.
We can use ```fit_signatures``` to fit the COSMIC signatures to the simulated counts as follows.
```{r fitting, warning=FALSE}
mcmc_samples_fit <- sigfit::fit_signatures(counts = mutations,
signatures = cosmic_signatures,
iter = 2000,
warmup = 1000,
chains = 1,
seed = 1)
```
#### Retrieving signature exposures
Once we have the result of the MCMC sampling in ```mcmc_samples_fit```, we can retrieve the estimated exposures from it using the ```retrieve_pars``` function. This returns a named list with three matrices, one containing the mean exposures, and the others containing the values corresponding to the lower and upper limits of the highest posterior density (HPD) interval (the Bayesian alternative to a confidence interval) for each exposure in each sample. The ```prob``` argument can be used to indicate the target probability content of the HPD interval (by default, 95% HPD intervals are returned).
Since we are fitting known signatures and not extracting new ones, we need to provide the original signature labels via the ```signature_names``` argument, so the exposures to each signature are labelled accordingly in the exposures table. If the signatures have no names, they will be labelled by ```sigfit``` as 'Signature A', 'Signature B', etc.
```{r retrieve_exp}
exposures <- retrieve_pars(mcmc_samples_fit,
feature = "exposures",
hpd_prob = 0.90,
signature_names = rownames(cosmic_signatures))
names(exposures)
exposures$mean
```
The entire posterior distribution of the signature exposures and other model parameters in the ```mcmc_samples_fit``` object can be further explored by means of the functions provided by the ```rstan``` package. In addition, [ShinyStan](http://mc-stan.org/users/interfaces/shinystan) can be easily used in R for visual exploration of the MCMC samples.
#### Visualisation
```sigfit``` provides several easy-to-use plotting functions. As seen in the previous section, the ```plot_spectrum``` function allows visualisation of both mutational catalogues and mutational signatures (assuming that these are defined over the same 96 trinucleotide mutation types as in [COSMIC](http://cancer.sanger.ac.uk/cosmic/signatures)).
The ```plot_exposures``` function produces a barplot of the estimated signature exposures in each sample. It needs to be supplied with either the object resulting from MCMC sampling (```mcmc_samples``` argument) or the exposures themselves (```exposures``` argument), the latter being either a matrix, or a list like the one returned by the ```retrieve_pars``` function (above). In the present case, since we have the stanfit object generated by ```fit_signatures```, we will make use of the ```mcmc_samples``` argument.
```{r plot_exp, fig.width=12, fig.height=5, out.width='100%', fig.align="center", echo=-1}
par(mar=c(7,4,3,0))
sigfit::plot_exposures(mutations,
mcmc_samples = mcmc_samples_fit,
signature_names = rownames(cosmic_signatures))
```
The bars in this plot are coloured blue if the estimated exposure value is 'sufficiently non-zero'. It is difficult for the model to make hard assignments of which signatures are present or absent due to the non-negative constraint on the estimate, which means that the range of values in the sample will not normally include zero. In practice, 'sufficiently non-zero' means that the lower end of the Bayesian HPD credible interval is above a threshold value close to zero (by default 0.01, and adjustable via the ```thresh``` argument). In this example, ```sigfit``` has identified the 4 signatures used to construct the sample.
Next, we would recommend running ```fit_signatures``` again, this time to fit only those signatures (i.e. those rows of the ```cosmic_signatures``` matrix) which have been highlighted as 'sufficiently non-zero' in the plot above, in order to obtain more accurate estimates. We will skip this step in the present example.
We can also examine how effectively the estimated signatures and/or exposures can reconstruct the original count data, using the ```plot_reconstruction``` function.
__Note that the plotting functions in ```sigfit``` are designed with a preference for plotting directly to a PDF file__.
The path to our desired output PDF can be provided using the ```pdf_path``` argument, and each function will automatically select the most appropriate size and graphical parameters for the plot. (We will not make use of this option in the present example, however.) The ```sig_color_palette``` argument can be used to specify custom colours for the signatures in the reconstructed spectrum.
```{r reconstruct, fig.width=25, fig.height=17, out.width='100%', warning=FALSE, results="hide", echo=-1}
par(mar=c(6.5,6,5.5,2))
sigfit::plot_reconstruction(mutations,
mcmc_samples = mcmc_samples_fit,
signatures = cosmic_signatures,
pdf_path = NULL)
```
The ```plot_spectrum```, ```plot_exposures``` and ```plot_reconstructions``` functions can be simply combined by using the ```plot_all``` function. This shares most arguments with the other plotting functions, and is useful to avoid running all the plotting functions individually. ```plot_all``` plots only to PDF files, with the ```out_path``` argument telling the function the path of the directory where the files should be created. If the directory does not yet exist, it will be automatically created prior to plotting. The ```prefix``` argument applies to the output file names, and can be used to distinguish different 'batches' of plots from each other.
```{r plot_all, eval=FALSE}
## This is an illustratrive example and will not be run
sigfit::plot_all(mutations,
out_path = "your/output/dir/here",
mcmc_samples = mcmc_samples_fit,
signatures = cosmic_signatures,
prefix = "Fitting")
```
### Example 2: Extracting mutational signatures from multiple breast cancer samples
In this second example, we will use single-nucleotide variant (SNV) data from the set of 21 breast cancer samples presented by [Nik-Zainal _et al._ (2012)](http://dx.doi.org/10.1016/j.cell.2012.04.024). These data can be accessed using ```data("variants_21breast")```.
```{r load_mutations}
data("variants_21breast", package = "sigfit")
head(variants_21breast)
```
This table illustrates the structure of the variant data that can be used as input for the package (unless you already have mutational catalogues for your samples). It is a matrix with one row per variant, and four (or five) columns:
* __Sample ID__ (character, e.g. "Sample 1").
* __Reference base__ (character: "A", "C", "G", or "T").
* __Mutated base__ (character: "A", "C", "G", or "T").
* __Trinucleotide context__ of the variant (character; reference sequence between the positions immediately before (-1) and after (+1) the variant, e.g. "TCA"). This can be obtained from the reference genome that was used to call the variants, using an R package like ```BSgenome```; however, sequence context information is sometimes provided by variant callers within the INFO field of the VCF file.
* __Optionally__: if there is information available about the transcriptional strand in which each mutation occurred, this can be incorporated as a fifth column taking character values "U" (for untranscribed strand) or "T" (for transcribed strand). If this column is present in the table, all the estimation and plotting functions will automatically incorporate such transcriptional strand information.
Importantly, since a variant can only have a single sample ID, variants which are found in more than one sample need to be included multiple times in the table, using different sample IDs. The order in which the samples are found in this table is the order in which they will be displayed thereafter. In this case, the samples are already sorted alphabetically:
```{r show_samples}
unique(variants_21breast[, 1])
```
The first step is to transform these variants into mutational catalogues, which is done by the ```build_catalogues``` function. (You can skip this step if you already have mutational catalogues for each of your samples.)
```{r build_catalogues}
counts_21breast <- build_catalogues(variants_21breast)
dim(counts_21breast)
```
The mutational catalogues are stored as a matrix of mutation counts, where each row refers to a sample and each column corresponds to a trinucleotide mutation type.
(This example set of 21 mutational catalogues can also be loaded directly using ```data("counts_21breast", package = "sigfit")```).
We can plot the spectrum of all the mutational catalogues using the ```plot_spectrum``` function, as in the previous example. For tables containing more than one catalogue, this function will produce one plot per catalogue, which makes using an output PDF file (```pdf_path``` argument) more convenient. In this example, however, we will plot all the catalogues together.
```{r plot_spectra, fig.width=22, fig.height=25, out.width='100%', fig.align="center", echo=-1}
par(mar = c(5,6,7,2))
par(mfrow = c(7, 3))
sigfit::plot_spectrum(counts_21breast)
```
To extract signatures from this set of catalogues, we use the ```extract_signatures``` function, specifying the number of signatures to extract via the ```nsignatures``` argument; this can be a single integer or a range, e.g. ```3:6```. Our recommended approach is first running the function for a small number of iterations and a reasonably wide range of numbers of signatures (e.g. ```nsignatures = 2:8```). When ```nsignatures``` is a range of values, ```sigfit``` will automatically determine the most plausible number of signatures present in the data (which is done by assessing goodness of fit through the ```plot_gof``` function). Also, for ranges of ```nsignatures``` the result is not a single stanfit object, but a list of such objects, where element ```[[N]]``` in the list corresponds to the extraction results for ```nsignatures = N```.
```{r extraction, eval=FALSE}
mcmc_samples_extr <- sigfit::extract_signatures(counts_21breast,
nsignatures = 2:7,
iter = 1000,
seed = 1)
```
```{r plot_gof_silent, echo=FALSE, fig.width=9, fig.height=6, out.width="100%"}
## Plot precalculated GOF in order to avoid running the model
data("sigfit_vignette_data", package = "sigfit")
plot(nS, gof, type = "o", lty = 3, pch = 16, col = "dodgerblue4",
main = paste0("Goodness of fit (", stat, ")\nmodel: NMF"),
xlab = "Number of signatures",
ylab = paste0("Goodness of fit (", stat, ")"))
points(nS[best], gof[best], pch = 16, col = "orangered", cex = 1.1)
cat("Estimated best number of signatures:", nS[best], "\n")
```
The plot above shows that the most plausible number of signatures is four, based on the evolution of the goodness of fit (reconstruction accuracy measured through cosine similarity).
Next, we would recommend running ```extract_signatures``` again, this time with ```nsignatures = 4``` and a much greater number of iterations, in order to obtain more accurate estimates. We will skip this step in the present example.
As in the case of signature fitting (Example 1 above), the extracted signatures and exposures can be retrieved using the ```retrieve_pars``` function with ```feature = "signatures"``` or ```feature = "exposures"```. The ```signature_names``` argument is not needed in this case, since the signatures are not known _a priori_.
```{r retrieve_sigs, eval=FALSE}
## Note: mcmc_samples_extr[[N]] contains the extraction results for N signatures
extr_signatures <- retrieve_pars(mcmc_samples_extr[[4]],
feature = "signatures")
```
```{r show_signames}
rownames(extr_signatures$mean)
```
Plotting can be done through the functions seen in Example 1, with the difference that there is no need to use the ```signatures``` argument in this case. Below we plot the signatures extracted from these 21 catalogues.
```{r plot_sigs, warning=FALSE, fig.width=22, fig.height=10, out.width='100%', fig.align="center", echo=-1}
par(mar = c(6,7,6,1))
par(mfrow = c(2, 2))
sigfit::plot_spectrum(extr_signatures)
```
These are a combination of COSMIC signatures 1, 2, 3, 5 and 13. Note that the signatures published in [COSMIC](http://cancer.sanger.ac.uk/cosmic/signatures) were obtained using a collection of hundreds of catalogues across many cancer types, which offered much higher statistical power than the 21 breast cancer catalogues employed here. Furthermore, the signatures obtained by ```sigfit``` show high similarity to those originally reported by [Nik-Zainal _et al._ (2012)](http://dx.doi.org/10.1016/j.cell.2012.04.024) (Fig. 2A). Note that signatures C and D in Nik-Zainal _et al._, which are very similar, have been identified by ```sigfit``` as a single signature (Signature B in the plot above).
### Using the EMu (Poisson) signature model
By default, both ```fit_signatures``` and ```extract_signatures``` make use of a 'multinomial-NMF' model of signatures, which is equivalent to the non-negative matrix factorisation approach adopted by [Alexandrov _et al._ (2013)](https://www.nature.com/articles/nature12477). Alternatively, users who are interested in the Poisson model presented by [Fischer _et al._ (2013)](https://doi.org/10.1186/gb-2013-14-4-r39) can use the ```method = "emu"``` option to select this model, which is able to account for variation in mutational opportunity (the opportunity for each mutation type to occur in each sample's genome; this is specified via the ```opportunities``` argument). For further details, type ```?extract_signatures``` to read the documentation.
Although signature representations differ between the NMF model and the EMu model (insofar as signatures obtained through the latter are not relative to the mutational opportunities of a specific genome/exome), signatures can be converted between both model representations by means of the ```convert_signatures``` function. For further details, type ```?convert_signatures``` to read the documentation.
### Using 'fit-extract' models to discover rare signatures
One novelty in ```sigfit``` is the use of 'fit-extract' models, which are able to extract novel signatures while fitting a set of predefined signatures which are already known to be present in the samples. Such models are useful for the discovery of rare or weak signatures for which there is some prior intuition, but insufficient support as to deconvolute them using traditional signature extraction.
The 'fit-extract' models can be accessed via the ```fit_extract_signatures``` function. This is used similarly to ```extract_signatures```, with the exception that a matrix of known signatures to be fitted needs to be provided via the ```signatures``` argument (as in ```fit_signatures```), and that the number of additional signatures to extract is provided via the ```num_extra_sigs``` argument. Unlike the ```nsignatures``` argument in ```extract_signatures```, ```num_extra_sigs``` currently admits only scalar values and not ranges. For further details, type ```?fit_extract_signatures``` to read the documentation.
___
```sigfit``` is an R package developed by the [Transmissible Cancer Group](http://www.tcg.vet.cam.ac.uk/) in the University of Cambridge Department of Veterinary Medicine.
|
92cce3cb9ae0ba9551f5f12d750fd9c50cfaae4f
|
[
"Markdown",
"R",
"RMarkdown"
] | 6
|
R
|
yudhe/sigfit
|
472dda45380222b328b96a11c1790dea72b5aa6e
|
f0b1904864f59acbee4cd83c9a03391de173f532
|
refs/heads/dev
|
<repo_name>melsoriano/share-tunes<file_sep>/server/firebase/firebaseApi.js
const { FirebaseAdmin, FirebaseApp } = require('../config');
// Stores the Spotify access token each time a new one is created
function databaseCreation(
uid,
email,
accessToken,
refreshToken,
tokenExpiration
) {
return FirebaseAdmin.firestore()
.doc(`users/${uid}`)
.set({
email,
accessToken,
refreshToken,
tokenExpiration,
});
}
// Updates or create Firebase user information
async function userUpdateOrCreateUser(uid, email) {
return FirebaseAdmin.auth()
.updateUser(uid, {
email,
emailVerified: true,
})
.catch(error => {
// If user does not exists we create it.
if (error.code === 'auth/user-not-found') {
return FirebaseAdmin.auth().createUser({
uid,
email,
emailVerified: true,
});
}
return error;
});
}
// Creates custom Firebase authentication tokens
function createFirebaseToken(uid) {
const token = FirebaseAdmin.auth().createCustomToken(uid, {
admin: true,
});
return token;
}
// Creates a user and database entry in the `users` collection
async function createOrUpdateFirebaseAccount(
spotifyID,
email,
accessToken,
refreshToken,
tokenExpiration
) {
const uid = spotifyID;
const databaseCreationTask = databaseCreation(
uid,
email,
accessToken,
refreshToken,
tokenExpiration
);
const userCreationTask = userUpdateOrCreateUser(uid, email);
// Wait til the database entry and user is made, create a custom token and send to the client.
return Promise.all([databaseCreationTask, userCreationTask])
.then(() => createFirebaseToken(uid))
.catch(err => err);
}
module.exports = {
FirebaseAdmin,
FirebaseApp,
createOrUpdateFirebaseAccount,
};
<file_sep>/server/config/index.js
const serviceAccount = require('./serviceAccount.json');
const { FirebaseAdmin, FirebaseApp } = require('./firebaseConfig');
const SpotifyApi = require('./spotifyConfig');
module.exports = {
serviceAccount,
FirebaseAdmin,
FirebaseApp,
SpotifyApi,
};
<file_sep>/client/src/utils/helpers.js
// Get cookie by name
function getCookie(name) {
const v = document.cookie.match(`(^|;) ?${name}=([^;]*)(;|$)`);
return v ? v[2] : null;
}
// Get the code provided by Spotify in the url query string
function getUrlParameter() {
const params = new URLSearchParams(window.location.search);
window.history.replaceState({}, '', `/`);
const code = params.get('code');
return code;
}
export { getCookie, getUrlParameter };
<file_sep>/client/src/components/create.js
import React, { useState, useEffect, useContext } from 'react';
import { navigate } from '@reach/router';
import styled from 'styled-components';
import { createSpotifyPlaylist } from '../api/spotify/spotifyApi';
import { SpotifyApi } from '../api/spotify/spotifyConfig';
import { theme, mixins, Section } from '../styles';
import { SpotifyContext } from '../context/spotifyContext';
const { fontSizes } = theme;
const CreateContainer = styled(Section)`
display: flex;
flex-flow: column wrap;
justify-content: center;
align-items: center;
`;
const CreateButton = styled.button`
${mixins.bigButton};
`;
const CreateFieldSet = styled.fieldset`
position: relative;
padding: 0;
margin: 5px;
border: none;
overflow: visible;
`;
const CreateInputField = styled.input`
background: transparent;
color: ${props => props.theme.colors.fontColor};
box-sizing: border-box;
width: 280px;
padding: 12px;
margin-bottom: 20px;
border: none;
border-radius: 0;
box-shadow: none;
border-bottom: 1px solid ${props => props.theme.colors.fontColor};
font-size: ${fontSizes.xlarge};
font-weight: 600;
outline: none;
cursor: text;
transition: all 300ms ease;
&:focus {
border-bottom: 1px solid ${props => props.theme.colors.buttonFill};
box-shadow: 0 1px 0 0 ${props => props.theme.colors.buttonFill};
}
&:focus ~ label,
&:valid ~ label {
color: ${props => props.theme.colors.buttonFill};
transform: translateY(-14px) scale(0.8);
}
`;
const CreateInputLabel = styled.label`
position: absolute;
top: 10px;
left: 10px;
font-size: ${fontSizes.large};
color: ${props => props.theme.colors.fontColor};
transform-origin: 0 -150%;
transition: transform 300ms ease;
pointer-events: none;
`;
const Create = () => {
const user = JSON.parse(localStorage.getItem('user'));
const [playlist, setPlaylistName] = useState({
playlistName: '',
});
const {
setMyAccessCode,
setDocumentPlaylistId,
setDocumentOwnerId,
setDocumentPlaylistName,
setDocumentUri,
} = useContext(SpotifyContext);
useEffect(() => {
localStorage.setItem('isLoading', false);
if (user !== null) {
SpotifyApi.setAccessToken(user.accessToken);
}
}, [user]);
const handlePlaylistName = e => {
setPlaylistName({ playlistName: e.target.value });
};
const handleKeyPress = e => {
if (e.key === 'Enter') {
createSpotifyPlaylist(
user.uid,
playlist.playlistName,
setMyAccessCode,
setDocumentPlaylistId,
setDocumentOwnerId,
setDocumentPlaylistName,
setDocumentUri,
navigate
);
}
};
return (
<CreateContainer>
<CreateFieldSet>
<CreateInputField
type="text"
value={playlist.playlistName}
onChange={handlePlaylistName}
onKeyPress={handleKeyPress}
required
/>
<CreateInputLabel>Enter Playlist Name</CreateInputLabel>
</CreateFieldSet>
<CreateButton
type="submit"
onClick={() =>
createSpotifyPlaylist(
user.uid,
playlist.playlistName,
setMyAccessCode,
setDocumentPlaylistId,
setDocumentOwnerId,
setDocumentPlaylistName,
setDocumentUri,
navigate
)
}
>
CREATE PLAYLIST
</CreateButton>
</CreateContainer>
);
};
export default Create;
<file_sep>/client/Dockerfile
# Built from Node latest Alpine
FROM node:alpine
# Set the app directory as the context for all commands and entry to the container
WORKDIR /app/admin-client
# ONLY copy over the package.json to install NPM packages
COPY package.json /app/admin-client
# Install node module dependencies
RUN npm install
# Add the rest of the project files(most builds will start from here based on cache)
COPY . /app/admin-client
# Install apk updates to allow for bash and vim manipulations
RUN apk update && apk upgrade
# Install bash
RUN apk add bash
# Install vim
RUN apk add vim
EXPOSE 3000
# Start the node application as you normally would
CMD ["npm", "start"]
<file_sep>/client/src/components/join.js
import React, { useState, useContext, useEffect } from 'react';
import { navigate, redirectTo } from '@reach/router';
import styled from 'styled-components';
import { db } from '../api/firebase/firebaseConfig';
import { SpotifyApi } from '../api/spotify/spotifyConfig';
import { SpotifyContext } from '../context/spotifyContext';
import { theme, mixins, Section } from '../styles';
const { fontSizes } = theme;
const JoinContainer = styled(Section)`
display: flex;
flex-flow: column wrap;
justify-content: center;
align-items: center;
`;
const JoinButton = styled.button`
${mixins.bigButton};
`;
const JoinFieldSet = styled.fieldset`
position: relative;
padding: 0;
margin: 5px;
border: none;
overflow: visible;
`;
const JoinInputField = styled.input`
background: transparent;
color: ${props => props.theme.colors.fontColor};
box-sizing: border-box;
width: 280px;
padding: 12px;
margin-bottom: 20px;
border: none;
border-radius: 0;
box-shadow: none;
border-bottom: 1px solid ${props => props.theme.colors.fontColor};
font-size: ${fontSizes.xlarge};
font-weight: 600;
outline: none;
cursor: text;
transition: all 300ms ease;
&:focus {
border-bottom: 1px solid ${props => props.theme.colors.buttonFill};
box-shadow: 0 1px 0 0 ${props => props.theme.colors.buttonFill};
}
&:focus ~ label,
&:valid ~ label {
color: ${props => props.theme.colors.buttonFill};
transform: translateY(-14px) scale(0.8);
}
`;
const JoinInputLabel = styled.label`
position: absolute;
top: 10px;
left: 10px;
font-size: ${fontSizes.large};
color: ${props => props.theme.colors.fontColor};
transform-origin: 0 -150%;
transition: transform 300ms ease;
pointer-events: none;
`;
const FlashMessage = styled.div`
/* color: ${props => props.theme.colors.fontColor}; */
color: red;
`;
const Join = () => {
const [flashMessage, setFlashMessage] = useState(false);
const [searchQuery, setSearchQuery] = useState({ code: '' });
const user = JSON.parse(localStorage.getItem('user'));
const { myAccessCode, setMyAccessCode, setDocumentUri } = useContext(
SpotifyContext
);
useEffect(() => {
console.log('myAccessCode /join:', myAccessCode);
if (user !== null) {
SpotifyApi.setAccessToken(user.accessToken);
}
}, [myAccessCode, user]);
const checkPlaylistExists = async code => {
await db
.collection('playlists')
.get()
.then(async querySnapshot => {
let isMatch = false;
let documentUri = '';
await querySnapshot.forEach(doc => {
if (doc.id === code) {
isMatch = true;
documentUri = doc.data().uri;
}
});
if (isMatch) {
console.log(documentUri);
setFlashMessage(false);
await setDocumentUri({ data: documentUri });
await setMyAccessCode(searchQuery.code);
localStorage.setItem('accessCode', searchQuery.code);
navigate(`tuneroom/${searchQuery.code}`);
} else {
setFlashMessage(true);
}
});
};
const handleAccessCode = e => {
setSearchQuery({ code: e.target.value });
};
const handleKeyPress = async e => {
if (e.key === 'Enter') {
setSearchQuery({ code: e.target.value });
await checkPlaylistExists(searchQuery.code);
}
};
return (
<JoinContainer>
<JoinFieldSet className="join-field">
<JoinInputField
type="text"
value={searchQuery.code}
onKeyPress={handleKeyPress}
onChange={handleAccessCode}
required
/>
<JoinInputLabel>Enter Access Code</JoinInputLabel>
{flashMessage && (
<FlashMessage>Please enter valid Access Code</FlashMessage>
)}
</JoinFieldSet>
<JoinButton
type="submit"
onClick={async () => {
await checkPlaylistExists(searchQuery.code);
}}
>
ENTER
</JoinButton>
</JoinContainer>
);
};
export default Join;
<file_sep>/client/src/components/tuneroom.js
import React, { useState, useContext, useEffect, Fragment } from 'react';
import { Link, navigate, Redirect } from '@reach/router';
import SpotifyPlayer from 'react-spotify-web-playback';
import axios from 'axios';
import styled from 'styled-components';
import { SpotifyContext } from '../context/spotifyContext';
import { SpotifyApi } from '../api/spotify/spotifyConfig';
import { reorderTrack } from '../api/spotify/spotifyApi';
import { db } from '../api/firebase/firebaseConfig';
import { vote } from '../api/firebase/firebaseApi';
import { theme, mixins, media } from '../styles';
import Player from './player';
import AddSong from './addsong';
const { fonts, fontSizes, colors } = theme;
const TuneRoomContainer = styled.div`
${mixins.sidePadding};
display: flex;
flex-flow: column wrap;
${media.phablet`padding: 2px;`};
`;
const PlaylistName = styled.h2`
text-align: center;
font-size: ${fontSizes.h2};
font-family: ${fonts.RiftSoft};
letter-spacing: 4px;
text-transform: uppercase;
font-weight: 600;
color: ${props => props.theme.colors.buttonFill};
margin-top: 50px;
`;
const TracksContainer = styled.div`
display: flex;
flex-flow: row wrap;
justify-content: space-between;
/* align-items: center; */
text-align: left;
`;
const TrackImageContainer = styled.div`
display: flex;
flex-flow: row nowrap;
padding: 5px;
img {
margin-right: 10px;
${media.phablet`width: 50px;height: 50px;`};
}
`;
const TrackInfoContainer = styled.div`
display: flex;
flex-flow: row wrap;
justify-content: space-between;
width: 100%;
.hide-track {
display: 'none';
}
`;
const TrackText = styled.p`
text-align: left;
${media.phablet`font-size:${fontSizes.xsmall};`};
`;
const VoteContainer = styled.div`
display: flex;
flex-flow: column wrap;
justify-content: center;
align-items: center;
`;
const VoteText = styled.p`
font-size: ${fontSizes.xsmall};
`;
const VoteButton = styled.button`
${mixins.smallButton};
`;
const BackButton = styled.button`
color: ${props => props.theme.colors.buttonFill};
text-transform: uppercase;
border: none;
font-family: ${fonts.RiftSoft};
letter-spacing: 3px;
font-size: ${fontSizes.small};
font-weight: 500;
background: none;
transition: ${theme.transition};
border-radius: 225px;
padding: 5px 10px;
cursor: pointer;
&:hover,
&:focus,
&:active {
background: ${props => props.theme.colors.buttonFill};
color: ${props => props.theme.colors.buttonFontColor};
border-radius: 225px;
}
&:after {
display: none !important;
}
`;
const UpNextHeader = styled.h2`
font-family: ${fonts.RiftSoft};
font-weight: 600;
letter-spacing: 2px;
margin: 0;
padding: 0;
`;
function TuneRoom(props) {
const user = JSON.parse(localStorage.getItem('user'));
const accessCode = localStorage.getItem('accessCode');
const [trackResults, setTrackResults] = useState({ data: '' });
const [votedTracks, setVotedTracks] = useState({ results: [] });
const [currentTrack, setCurrentTrack] = useState(null);
const {
documentUri,
documentPlaylistId,
documentOwnerId,
documentPlaylistName,
documentState,
setDocumentState,
setMyAccessCode,
} = useContext(SpotifyContext);
useEffect(() => {
setDocumentState(documentState);
}, [currentTrack, documentState, documentUri, setDocumentState]);
useEffect(() => {
async function getRefreshToken() {
await axios
.post('/auth/refresh_token', user)
.then(response => {
SpotifyApi.setAccessToken(response.data.access_token);
SpotifyApi.setRefreshToken(response.data.refresh_token);
})
.catch(error => error);
}
// getRefreshToken();
setInterval(() => {
getRefreshToken();
}, 3000000);
}, [user]);
useEffect(() => {
db.collection('users')
.doc(user.uid)
.onSnapshot(doc => {
const { accessToken } = doc.data();
SpotifyApi.setAccessToken(accessToken);
localStorage.setItem(
'user',
JSON.stringify({ uid: doc.id, ...doc.data() })
);
});
if (documentPlaylistId.data !== '') {
reorderTrack(documentPlaylistId.data, accessCode, documentOwnerId.data);
documentState.map((track, i) => {
if (currentTrack === track.uri) {
document.querySelector(`.track--${i}`).style.display = 'none';
}
});
}
}, [
accessCode,
currentTrack,
documentOwnerId,
documentPlaylistId,
documentState,
props,
user.uid,
]);
const handleVote = trackUri => {
if (!votedTracks.results.includes(trackUri)) {
vote(trackUri, accessCode, documentPlaylistId);
setVotedTracks({ results: [...votedTracks.results, trackUri] });
reorderTrack(documentPlaylistId.data, accessCode, documentOwnerId.data);
}
};
const trackUri = documentState.map(track => track.uri);
const back = async () => {
await setMyAccessCode('default');
await navigate('/join').then(window.location.reload());
};
return (
<>
<BackButton type="submit" onClick={() => back()}>
back
</BackButton>
<TuneRoomContainer>
<PlaylistName>{documentPlaylistName.data}</PlaylistName>
<Player
user={user}
trackUri={trackUri}
setCurrentTrack={setCurrentTrack}
/>
<UpNextHeader>Up Next:</UpNextHeader>
{documentState.length > 0 &&
documentState.map((result, i) => {
return (
<Fragment>
<TracksContainer key={i}>
<TrackInfoContainer className={`track--${i}`}>
<TrackImageContainer>
<img src={result.album.images[2].url} alt="album-cover" />
<TrackText>
{result.name}
<br />
{result.artists[0].name}
</TrackText>
</TrackImageContainer>
<VoteContainer>
<VoteButton
type="submit"
onClick={() => handleVote(result.uri, documentUri)}
>
vote
</VoteButton>
<VoteText>{result.votes} Votes</VoteText>
</VoteContainer>
</TrackInfoContainer>
</TracksContainer>
</Fragment>
);
})}
<AddSong />
</TuneRoomContainer>
</>
);
}
export default TuneRoom;
<file_sep>/client/src/context/firebaseContext.js
import React, { useState } from 'react';
// create instance of context
export const FirebaseContext = React.createContext();
// create context provider
export const FirebaseProvider = ({ children }) => {
const [firebaseToken, setFirebaseToken] = useState(
'default firebase context'
);
return (
// inject state into the provider, and pass along to children components
<FirebaseContext.Provider value={{ firebaseToken, setFirebaseToken }}>
{children}
</FirebaseContext.Provider>
);
};
<file_sep>/.env.example
REACT_APP_API_KEY=
REACT_APP_AUTH_DOMAIN=
REACT_APP_DATABASE_URL=
REACT_APP_PROJECT_ID=
REACT_APP_STORAGE_BUCKET=
REACT_APP_MESSAGING_SENDER_ID=
SPOTIFY_CLIENT_ID=your_client_id_here
SPOTIFY_CLIENT_SECRET=your_secret_here
SESSION_SECRET=your_session_secret
EXPRESS_CONTAINER_PORT=your_port_number_here
REACT_CONTAINER_PORT=your_port_number_here
<file_sep>/client/src/styles/GlobalStyle.js
import { createGlobalStyle } from 'styled-components';
import theme from './theme';
import media from './media';
import mixins from './mixins';
const { colors, fontSizes, fonts } = theme;
const GlobalStyle = createGlobalStyle`
@import url("https://p.typekit.net/p.css?s=1&k=zex7tbr&ht=tk&f=28159.28969.28976.28980.10890.10892.10894.10896&a=5642603&app=typekit&e=css");
@font-face {
font-family:"hooligan-jf";
src:url("https://use.typekit.net/af/29cd8d/00000000000000003b9b04a9/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("woff2"),url("https://use.typekit.net/af/29cd8d/00000000000000003b9b04a9/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("woff"),url("https://use.typekit.net/af/29cd8d/00000000000000003b9b04a9/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("opentype");
font-style:normal;font-weight:400;
}
@font-face {
font-family:"rift-soft";
src:url("https://use.typekit.net/af/58d868/00000000000000003b9adf12/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n3&v=3") format("woff2"),url("https://use.typekit.net/af/58d868/00000000000000003b9adf12/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n3&v=3") format("woff"),url("https://use.typekit.net/af/58d868/00000000000000003b9adf12/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n3&v=3") format("opentype");
font-style:normal;font-weight:300;
}
@font-face {
font-family:"rift-soft";
src:url("https://use.typekit.net/af/f49484/00000000000000003b9adf19/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("woff2"),url("https://use.typekit.net/af/f49484/00000000000000003b9adf19/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("woff"),url("https://use.typekit.net/af/f49484/00000000000000003b9adf19/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("opentype");
font-style:normal;font-weight:400;
}
@font-face {
font-family:"rift-soft";
src:url("https://use.typekit.net/af/b0a7b5/00000000000000003b9adf1d/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n5&v=3") format("woff2"),url("https://use.typekit.net/af/b0a7b5/00000000000000003b9adf1d/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n5&v=3") format("woff"),url("https://use.typekit.net/af/b0a7b5/00000000000000003b9adf1d/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n5&v=3") format("opentype");
font-style:normal;font-weight:500;
}
@font-face {
font-family:"pragmatica";
src:url("https://use.typekit.net/af/c9f384/0000000000000000000100ca/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("woff2"),url("https://use.typekit.net/af/c9f384/0000000000000000000100ca/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("woff"),url("https://use.typekit.net/af/c9f384/0000000000000000000100ca/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n4&v=3") format("opentype");
font-style:normal;font-weight:400;
}
@font-face {
font-family:"pragmatica";
src:url("https://use.typekit.net/af/983872/0000000000000000000100cc/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3") format("woff2"),url("https://use.typekit.net/af/983872/0000000000000000000100cc/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3") format("woff"),url("https://use.typekit.net/af/983872/0000000000000000000100cc/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n7&v=3") format("opentype");
font-style:normal;font-weight:700;
}
@font-face {
font-family:"pragmatica";
src:url("https://use.typekit.net/af/264d39/0000000000000000000100ce/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n2&v=3") format("woff2"),url("https://use.typekit.net/af/264d39/0000000000000000000100ce/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n2&v=3") format("woff"),url("https://use.typekit.net/af/264d39/0000000000000000000100ce/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n2&v=3") format("opentype");
font-style:normal;font-weight:200;
}
@font-face {
font-family:"pragmatica";
src:url("https://use.typekit.net/af/ee2748/0000000000000000000100d0/27/l?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n3&v=3") format("woff2"),url("https://use.typekit.net/af/ee2748/0000000000000000000100d0/27/d?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n3&v=3") format("woff"),url("https://use.typekit.net/af/ee2748/0000000000000000000100d0/27/a?primer=7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191&fvd=n3&v=3") format("opentype");
font-style:normal;font-weight:300;
}
html {
box-sizing: border-box;
width: 100%;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
width: 100%;
min-height: 100%;
overflow-x: hidden;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
line-height: 1.45;
font-family: ${fonts.Pragmatica};
font-weight: 200;
font-size: ${fontSizes.medium};
${media.phablet`font-size: ${fontSizes.medium};`};
background: ${props => props.theme.colors.background};
color: ${props => props.theme.colors.fontColor};
&.hidden {
overflow: hidden;
}
&.blur {
overflow: hidden;
#root > .container > * {
filter: blur(5px) brightness(0.7);
pointer-events: none;
user-select: none;
}
}
}
#root {
min-height: 100vh;
display: grid;
grid-template-rows: 1fr auto;
grid-template-columns: 100%;
}
h1,
h2,
h3,
h4,
h5 {
font-weight: 200;
margin: 0 0 10px 0;
}
svg {
width: 100%;
height: 100%;
fill: currentColor;
vertical-align: middle;
}
ul, ol {
padding: 0;
margin: 0;
list-style: none;
}
`;
export default GlobalStyle;
<file_sep>/client/src/router/index.js
import React, { useContext, Fragment } from 'react';
import { Router, Link, Redirect } from '@reach/router';
import styled, { ThemeProvider } from 'styled-components';
import GlobalStyle from '../styles/GlobalStyle';
import Home from '../components/home';
import Join from '../components/join';
import Create from '../components/create';
import TuneRoom from '../components/tuneroom';
import AddSong from '../components/addsong';
import { ThemeContext } from '../context/themeContext';
import Player from '../components/player';
const ReactRouter = () => {
const { mode } = useContext(ThemeContext);
// ThemeProvider gets mode from the context wrapper and passes it down to the rest of the application through the outer router component. Since this can't be done in around the root <App /> component, the router component will serve as it's 'proxy'
return (
<ThemeProvider theme={mode}>
<Fragment>
<GlobalStyle />
<Router>
<Home path="/" />
<Create path="create" />
<Join path="join" />
<AddSong path="add/:code" />
{/* <TuneRoom path="/tuneroom" /> */}
<TuneRoom path="tuneroom/:code" />
<Player path="tuneroom/:code" />
</Router>
</Fragment>
</ThemeProvider>
);
};
export default ReactRouter;
<file_sep>/client/src/components/icons/index.js
import IconMusicNote from './MusicNote';
import IconSun from './Sun';
import IconMoon from './Moon';
export { IconMusicNote, IconMoon, IconSun };
<file_sep>/client/src/context/userContext.js
import React, { useState } from 'react';
// create instance of context
export const UserContext = React.createContext();
// create context provider
export const UserProvider = ({ children }) => {
const [isLoading, setIsLoading] = useState(false);
const [userToken, setUserToken] = useState('default user context');
const [user, setUser] = useState('default user object');
return (
// inject state into the provider, and pass along to children components
<UserContext.Provider
value={{
user,
setUser,
userToken,
setUserToken,
isLoading,
setIsLoading,
}}
>
{children}
</UserContext.Provider>
);
};
<file_sep>/client/src/api/firebase/firebaseConfig.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
// Good ol' Firebase API configurations
const config = {
apiKey: process.env.REACT_APP_FBASE_API_KEY,
authDomain: process.env.REACT_APP_FBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FBASE_MESSAGING_SENDER_ID,
};
// Initialize Firebase
const FirebaseApp = firebase.initializeApp(config);
// Create an instance of Firebase Auth used to authenticate users
const FirebaseAuth = firebase.auth();
// Creates an instance of Firestore Database
const db = firebase.firestore();
// Sets user session in browser
FirebaseAuth.setPersistence('local');
export { FirebaseAuth, FirebaseApp, db };
<file_sep>/client/src/components/loader.js
import React from 'react';
import styled, { keyframes } from 'styled-components';
const loading = keyframes`
0% {
transform: scale(1);
background-color: ${props => props.theme.colors.buttonFill};
}
20% {
transform: scale(1, 2.2);
background-color: #FFF;
}
40% {
transform: scale(1);
background-color: ${props => props.theme.colors.buttonFill};
}
`;
const LoaderContainter = styled.div`
div:nth-child(1) {
animation-delay: 0;
}
div:nth-child(2) {
animation-delay: 0.09s;
}
div:nth-child(3) {
animation-delay: 0.18s;
}
div:nth-child(4) {
animation-delay: 0.27s;
}
div:nth-child(5) {
animation-delay: 0.36s;
}
`;
const LoaderBars = styled.div`
display: inline-block;
margin: 1.5px;
width: 5px;
height: 25px;
border-radius: 4px;
animation: ${loading} 1.5s ease-in-out infinite;
background-color: ${props => props.theme.colors.buttonFill};
`;
const Loader = () => (
<LoaderContainter>
<LoaderBars />
<LoaderBars />
<LoaderBars />
<LoaderBars />
<LoaderBars />
</LoaderContainter>
);
export default Loader;
<file_sep>/client/src/components/addsong.js
import React, { useState, useContext, useEffect } from 'react';
import { navigate } from '@reach/router';
import styled from 'styled-components';
import { searchTracks, addTrack } from '../api/spotify/spotifyApi';
import { SpotifyApi } from '../api/spotify/spotifyConfig';
import { SpotifyContext } from '../context/spotifyContext';
import { theme, mixins, media } from '../styles';
const { fontSizes } = theme;
const AddContainer = styled.div`
display: flex;
flex-flow: column wrap;
justify-content: center;
align-items: center;
`;
const SearchButton = styled.button`
${mixins.bigButton};
`;
const AddFieldSet = styled.fieldset`
position: relative;
padding: 0;
margin: 5px;
border: none;
overflow: visible;
`;
const AddInputField = styled.input`
background: transparent;
color: ${props => props.theme.colors.fontColor};
box-sizing: border-box;
width: 100%;
padding: 12px;
margin-bottom: 20px;
border: none;
border-radius: 0;
box-shadow: none;
border-bottom: 1px solid ${props => props.theme.colors.fontColor};
font-size: ${fontSizes.xlarge};
font-weight: 600;
outline: none;
cursor: text;
transition: all 300ms ease;
&:focus {
border-bottom: 1px solid ${props => props.theme.colors.buttonFill};
box-shadow: 0 1px 0 0 ${props => props.theme.colors.buttonFill};
}
&:focus ~ label,
&:valid ~ label {
color: ${props => props.theme.colors.buttonFill};
transform: translateY(-14px) scale(0.8);
}
`;
const AddInputLabel = styled.label`
position: absolute;
top: 10px;
left: 10px;
font-size: ${fontSizes.large};
color: ${props => props.theme.colors.fontColor};
transform-origin: 0 -150%;
transition: transform 300ms ease;
pointer-events: none;
`;
const AddTrackTitle = styled.h2`
font-size: ${fontSizes.xlarge};
font-weight: 500;
color: ${props => props.theme.colors.buttonFill};
margin-bottom: 40px;
`;
const SearchResultsContainer = styled.div`
display: flex;
flex-flow: column wrap;
justify-content: flex-start;
align-items: flex-start;
`;
const UnorderedList = styled.ul`
text-align: left;
`;
const ListItem = styled.li`
text-align: left;
`;
const AddButton = styled.button`
${mixins.smallButton};
`;
const AddSong = props => {
const [stateQuery, setStateQuery] = useState({ query: '' });
const user = JSON.parse(localStorage.getItem('user'));
const [trackResults, setTrackResults] = useState({
data: '',
});
const { path, code } = props;
const {
setMyAccessCode,
setDocumentUri,
documentOwnerId,
documentPlaylistId,
setDocumentState,
} = useContext(SpotifyContext);
SpotifyApi.setAccessToken(user.accessToken);
useEffect(() => {
if (user !== null) {
SpotifyApi.setAccessToken(user.accessToken);
}
}, [documentOwnerId, user]);
const search = e => {
setStateQuery({ query: e.target.value });
};
const [initialTracks, setInitialTracks] = useState([]);
const accessCodeId = window.location.pathname.split('/').pop();
const handleAddTrack = async result => {
// need to pass this all the way to addTrackDb method in firebaseApi
await addTrack(
documentOwnerId.data,
documentPlaylistId.data,
accessCodeId,
result
);
setInitialTracks([result, ...initialTracks]);
if (accessCodeId === code && initialTracks.length >= 1) {
await setDocumentState([result, ...initialTracks]);
await navigate(`/tuneroom/${accessCodeId}`, { state: result });
}
setStateQuery({ query: '' });
};
const handleKeyPress = e => {
if (e.key === 'Enter') {
searchTracks(stateQuery.query, setTrackResults);
}
};
return (
<AddContainer>
{path === `/add/${accessCodeId}` && (
<AddTrackTitle>Go ahead and add a couple (2) songs!</AddTrackTitle>
)}
{/** SEARCH FOR A SONG */}
<AddFieldSet>
<AddInputField
type="text"
value={stateQuery.query}
onKeyPress={handleKeyPress}
onChange={search}
required
/>
<AddInputLabel>Search Tracks</AddInputLabel>
</AddFieldSet>
<SearchButton
id="addSong"
type="submit"
onClick={() => {
searchTracks(stateQuery.query, setTrackResults);
}}
>
SEARCH
</SearchButton>
{trackResults.data !== '' &&
trackResults.map((result, i) => (
<SearchResultsContainer>
<UnorderedList key={i}>
<ListItem>
<img src={result.album.images[2].url} alt="album-cover" />
{result.artists[0].name} - {result.name}
<AddButton type="submit" onClick={() => handleAddTrack(result)}>
add
</AddButton>
</ListItem>
</UnorderedList>
</SearchResultsContainer>
))}
</AddContainer>
);
};
export default AddSong;
<file_sep>/server/routes/auth.js
const express = require('express');
const router = express.Router();
const { SpotifyApi } = require('../config/index');
const { createOrUpdateFirebaseAccount } = require('../firebase/firebaseApi');
router.post('/token', (req, res) => {
const authCode = req.body.spotifyAuthCode;
// Start the Spotify auth flow
SpotifyApi.authorizationCodeGrant(authCode)
.then((data) => {
const { access_token, refresh_token, expires_in } = data.body;
// Set the access token to send on each server request
SpotifyApi.setAccessToken(access_token);
SpotifyApi.setRefreshToken(refresh_token);
// Get Spotify user information
SpotifyApi.getMe().then(async (userResults) => {
const { email, id } = userResults.body;
const uid = id;
// Custom token created after receiving Spotify user information
const firebaseToken = await createOrUpdateFirebaseAccount(
uid,
email,
access_token,
refresh_token,
expires_in,
);
// Send user information and tokens to client
res.status(201).send({
uid,
email,
firebaseToken,
expires_in,
});
});
})
.catch(error => error);
});
router.post('/refresh_token', (req, res) => {
const {
accessToken, refreshToken, uid, email,
} = req.body;
SpotifyApi.setAccessToken(accessToken);
SpotifyApi.setRefreshToken(refreshToken);
SpotifyApi.refreshAccessToken().then(
async (data) => {
const { access_token, expires_in } = data.body;
const tokenExpirationEpoch = new Date().getTime() / 1000 + data.body.expires_in;
console.log(
`Refreshed token. It now expires in ${Math.floor(
tokenExpirationEpoch - new Date().getTime() / 1000,
)} seconds!`,
);
await createOrUpdateFirebaseAccount(uid, email, access_token, refreshToken, expires_in);
res.json(data.body);
},
(err) => {
console.log('Could not refresh the token!', err.message);
return err.message;
},
);
});
module.exports = router;
<file_sep>/client/src/context/themeContext.js
import React, { useState } from 'react';
import theme from '../styles/theme';
// create instance of context
export const ThemeContext = React.createContext();
// create context provider
export const ThemeProvider = ({ children }) => {
// check localStorage for theme mode. this is set by the switch toggle component
// localStorage is needed to persist theme through page refresh and multiple tabs
const [mode, setMode] = useState(() => {
if (localStorage.getItem('mode') === 'light') {
return theme.light;
}
return theme.dark;
});
const [switchState, setSwitch] = useState(() => {
if (localStorage.getItem('switchState')) {
return JSON.parse(localStorage.getItem('switchState'));
}
return false;
});
return (
// inject state into the provider, and pass along to children components
<ThemeContext.Provider value={{ mode, setMode, switchState, setSwitch }}>
{children}
</ThemeContext.Provider>
);
};
<file_sep>/client/src/components/switch.js
import React, { useEffect, useContext } from 'react';
import Switch from 'react-switch';
import { ThemeContext } from '../context/themeContext';
import theme from '../styles/theme';
import { IconMoon, IconSun } from './icons';
const { colorOptions } = theme;
const ToggleSwitch = () => {
// import context and assign
const { setMode } = useContext(ThemeContext);
const { switchState, setSwitch } = useContext(ThemeContext);
// on state change, modify context
useEffect(() => {
if (switchState) {
localStorage.setItem('mode', 'dark');
localStorage.setItem('switchState', JSON.stringify(true));
setMode(theme.dark);
// add theme into localStorage to persist through refresh
} else {
localStorage.setItem('mode', 'light');
localStorage.setItem('switchState', JSON.stringify(false));
setMode(theme.light);
}
});
return (
<Switch
checked={switchState}
onChange={() => (switchState ? setSwitch(false) : setSwitch(true))}
onColor={`${colorOptions.aqua}`}
offColor={`${colorOptions.coral}`}
handleDiameter={16}
uncheckedIcon={
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '90%',
paddingRight: 2,
paddingTop: 2,
}}
>
<IconSun />
</div>
}
checkedIcon={
<div
style={{
color: 'black',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '90%',
paddingRight: 2,
paddingTop: 2,
}}
>
<IconMoon />
</div>
}
boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)"
height={22}
width={50}
className="react-switch"
id="small-radius-switch"
/>
);
};
export default ToggleSwitch;
<file_sep>/client/src/styles/theme.js
// create two themes
// theme object gets passed into themeContext, which toggles between the two based on localStorage value
const theme = {
colorOptions: {
darkest: '#101015',
dark: '#101015',
ice: '#F0F3F4',
steel: '#C8D1D3',
aqua: '#00E4F4',
sand: '#FDD9BE',
peach: '#FFC9A5',
coral: '#F05E53',
transCoral: 'rgb(244,123,120, 0.2)',
transAqua: 'rgb(0,228,244, 0.2)',
greyDisabled: '#A1AABB',
},
fonts: {
Pragmatica:
'Pragmatica, San Francisco, SF Pro Text, -apple-system, system-ui, BlinkMacSystemFont, Helvetica Neue, Segoe UI, Arial, sans-serif',
Hooligan: 'Hooligan-jf, Courier New, Monotype',
RiftSoft:
'rift-soft, San Francisco, SF Pro Text, -apple-system, system-ui, BlinkMacSystemFont, Helvetica Neue, Segoe UI, Arial, sans-serif',
},
fontSizes: {
xsmall: '12px',
smallish: '13px',
small: '14px',
medium: '16px',
large: '18px',
xlarge: '20px',
xxlarge: '22px',
h2: '24px',
h1: '32px',
},
easing: 'cubic-bezier(0.645, 0.045, 0.355, 1)',
transition: 'all 0.25s cubic-bezier(0.645, 0.045, 0.355, 1)',
borderRadius: '378px',
headerHeight: '100px',
headerScrollHeight: '70px',
margin: '20px',
tabHeight: 42,
tabWidth: 120,
gradient: `linear-gradient(0.4turn, #64d6ff, #64ffda)`,
light: {
colors: {
background: 'linear-gradient(to bottom, #FDD9BE, #FFC9A5) fixed',
fontColor: '#101015',
secondaryFontColor: '#F05E53',
buttonFontColor: '#FFFDFD',
buttonFill: '#F05E53',
buttonHover: 'rgb(244,123,120, 0.1)',
},
},
dark: {
colors: {
background: 'linear-gradient(to bottom, #191F29, #101015) fixed',
fontColor: '#F0F3F4',
secondaryFontColor: '#00E4F4',
buttonFontColor: '#101015',
buttonFill: '#00E4F4',
buttonHover: 'rgb(0,228,244, 0.1)',
},
},
};
export default theme;
<file_sep>/server/index.js
require('dotenv').config();
const express = require('express');
const bp = require('body-parser');
const authRoutes = require('./routes/auth');
const PORT = process.env.PORT || 8080;
const app = express();
app.use(bp.json());
app.use(
bp.urlencoded({
extended: true,
})
);
app.use('/auth', authRoutes);
app.listen(PORT, () => {
console.log(`Magic happening on ${PORT}`);
});
<file_sep>/server/Dockerfile
# Built from Node latest Alpine
FROM node:alpine
# Set the app directory as the context for all commands and entry to the container
WORKDIR /app/admin-server
# ONLY copy over the package.json to install NPM packages
COPY package.json /app/admin-server
# Install node module dependencies
RUN npm install
# Add the rest of the project files(most builds will start from here based on cache)
COPY . /app/admin-server
# Install firebase & firebase-admin libraries separately to avoid version-related crash at build time
RUN npm install firebase firebase-admin
# Install apk updates to allow for bash and vim manipulations
RUN apk update && apk upgrade
# Install bash
RUN apk add bash
# Install vim
RUN apk add vim
EXPOSE 8080
# Start the node application as you normally would
CMD ["npm", "run" "dev"]<file_sep>/server/utils/customMiddleware.js
const { verifySession } = require('../firebase/firebaseApi');
// Attaches a CSRF token to the request
function attachCsrfToken(url, cookie, value) {
return (req, res, next) => {
if (req.url == url) {
res.cookie(cookie, value);
}
next();
};
}
// Checks if a user is already signed in and if so, redirect to home page
function checkIfSignedIn(url) {
return (req, res, next) => {
if (req.url == url) {
const sessionCookie = req.cookies.session || '';
verifySession(sessionCookie)
.then(decodedClaims => {
res.redirect(process.env.CLIENT_URL);
})
.catch(error => {
next();
});
} else {
next();
}
};
}
module.exports = {
attachCsrfToken,
checkIfSignedIn,
};
<file_sep>/README.md
# Share Tunes
Create a collaborative playlist with your Spotify account and show off your great taste in music. This project was built during the June 2019 Angelhack Virtual Hackathon.
_Please Note: You will need a Spotify Premium account to play music directly in the application. Otherwise, this app can work as a controller on the official Spotify web, desktop, or mobile app._

## Installation & Development
- Run `npm install` in both client and server directory
- Run `docker-compose up -d` from the root of the project
- Go to `localhost:3000`
## Technologies Used
- Express
- Docker
- React
- Styled Components
- Firebase
- Google Cloud Platfrom
- Spotify API
## Contributors
[<NAME>](https://www.github.com/ngambino0192)
[<NAME>](https://www.github.com/melsoriano)
|
daf8b875b94a022dfe22c60ec37313dd4a0f51fd
|
[
"JavaScript",
"Dockerfile",
"Markdown",
"Shell"
] | 24
|
JavaScript
|
melsoriano/share-tunes
|
a72b0b0fa3a6343f750dc4759a9b87ce96cdbd0f
|
525a50828fb69db84890775323cd861e07cbe0c7
|
refs/heads/master
|
<repo_name>rubensworks/CharsetMC<file_sep>/src/main/java/pl/asie/charset/audio/integration/jei/JEIPluginCharsetAudio.java
package pl.asie.charset.audio.integration.jei;
import mezz.jei.api.IItemRegistry;
import mezz.jei.api.IJeiHelpers;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.IRecipeRegistry;
import mezz.jei.api.JEIPlugin;
@JEIPlugin
public class JEIPluginCharsetAudio implements IModPlugin {
@Override
public void onJeiHelpersAvailable(IJeiHelpers jeiHelpers) {
}
@Override
public void onItemRegistryAvailable(IItemRegistry itemRegistry) {
}
@Override
public void register(IModRegistry registry) {
registry.addRecipeHandlers(new JEITapeCraftingRecipe.Handler(), new JEITapeReelCraftingRecipe.Handler());
}
@Override
public void onRecipeRegistryAvailable(IRecipeRegistry recipeRegistry) {
}
}
|
ff9c342edcbf53f7a695c3015b4e3a3d81ee67a3
|
[
"Java"
] | 1
|
Java
|
rubensworks/CharsetMC
|
66677ce73ee49129b95cf177ef9174b04ba01fa6
|
7490487603b114bd5cdbaac33d229450b19eabea
|
refs/heads/master
|
<file_sep># Maze-Navigation
Used 3 dimensionality reduction methods (PCA, t-SNE, UMAP) to look for patterns in people exploring a maze. Discovered a strong connection between the pattern and people's mental rotational ability.
<file_sep>import pandas as pd
import glob
from sklearn.cluster import KMeans
def main():
feature_list = []
subject_list = []
directoryPath = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Parsed_Data/'
for file_name in glob.glob(directoryPath + '*.csv'):
df = pd.read_csv(file_name)
# read in the data on X and Z position plus the rotation
feature = list(df['posX'].values[0:30000:10])
feature2 = list(df['posZ'].values[0:30000:10])
feature3 = list(df['rotX'].values[0:30000:10])
feature4 = list(df['rotZ'].values[0:30000:10])
feature5 = list(df['rotZ'].values[0:30000:10])
feature.extend(feature2)
feature.extend(feature3)
feature.extend(feature4)
feature.extend(feature5)
# Select the data with 15000 frames; the other subjects not with 15000 frames are not considered
if len(feature) == 15000:
feature_list.append(feature)
# Each csv file is named with 4 letters, so take the 4 letters as their names.
subject_list.append(file_name[74:78])
x_kmeans = KMeans(n_clusters=10, random_state=0)
y_kmeans = x_kmeans.fit_predict(feature_list)
clusters = dict()
for i in range(len(y_kmeans)):
if y_kmeans[i] in clusters:
clusters[y_kmeans[i]].append(subject_list[i])
else:
clusters[y_kmeans[i]] = [subject_list[i]]
# The output is a dictionary where the keys are the cluster number and their corresponding values are the elements
# in each clusters
print(clusters)
main()
<file_sep>import pandas as pd
from sklearn.decomposition import PCA
import glob
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE
def main():
feature_list = []
directoryPath = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Parsed_Data/'
for file_name in glob.glob(directoryPath + '*.csv'):
df = pd.read_csv(file_name)
# read in the data on X and Z position plus the rotation
feature = list(df['posX'].values[0:30000:10])
feature2 = list(df['posZ'].values[0:30000:10])
feature3 = list(df['rotX'].values[0:30000:10])
feature4 = list(df['rotZ'].values[0:30000:10])
feature5 = list(df['rotZ'].values[0:30000:10])
feature.extend(feature2)
feature.extend(feature3)
feature.extend(feature4)
feature.extend(feature5)
# Select the data with 15000 frames; the other subjects not with 15000 frames are not considered
if len(feature) == 15000:
feature_list.append(feature)
# Option 1: First do the PCA without standardization to reduce the dimension to 50, then do the tsne
# pca = PCA(n_components=50)
# principalComponents = pca.fit_transform(feature_list)
# X_embedded = TSNE(n_components=2).fit_transform(principalComponents)
# Option 2: First do the PCA with standardization to reduce the dimension to 50, then do the tsne
# pca = PCA(n_components=50)
# X_std = StandardScaler().fit_transform(feature_list)
# principalComponents = pca.fit_transform(X_std)
# X_embedded = TSNE(n_components=2).fit_transform(principalComponents)
# Option 3: Directly do the tsne with original feature data
X_embedded = TSNE(n_components=2).fit_transform(feature_list)
tsneDF = pd.DataFrame(X_embedded)
# display the scatter plot
plt.scatter(tsneDF[0], tsneDF[1], alpha=1)
plt.show()
main()
<file_sep>import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import pandas as pd
FILE_PATH = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Parsed_Data/'
OUTPUT_PATH1 = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Trace_plots/cluster1/'
OUTPUT_PATH2 = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Trace_plots/cluster2/'
def generate_plot(id, cluster):
# The path may not work, since it being legacy code
file_name = FILE_PATH + id + '.csv'
df = pd.read_csv(file_name)
# read in the data on X and Z position
x = list(df['posX'].values[::10])
y = list(df['posZ'].values[::10])
fig = plt.figure()
ax = plt.axes(projection="3d")
time = list(range(3000, 0, -1))
t_size = len(x)
# colorGrad customized
colorGrad = []
for i in range(0, t_size):
colorGrad.append([i / t_size, 0, 1 - i / t_size])
z_points = time
x_points = x
y_points = y
if cluster == 1:
output_path = OUTPUT_PATH1 + id + '.png'
else:
output_path = OUTPUT_PATH2 + id + '.png'
ax.scatter3D(x_points, y_points, z_points, c=colorGrad, cmap='hsv')
ax.set_xlabel('X position')
ax.set_ylabel('Z position')
ax.set_zlabel('time')
plt.title(id)
plt.savefig(output_path)
# plt.show()
print(f'{id} is successfully generated')
# Clusters derived from the umap_clustering method.
cluster1 = ['GGWU', 'TYJR', 'FMKJ', 'ACGN', 'SIUT', 'WJJU', 'MTXB', 'NUAO', 'CGWN', 'AELV', 'WONG', 'SFUG', 'MCCO', 'ONVA', 'ZDGH', 'LAWW', 'VZYX', 'YPGZ']
cluster2 = ['YPQL', 'GGMO', 'BQHT', 'LQKJ', 'UPGW', 'FPIT', 'XQJO', 'OUWM', 'RCEH', 'UREH', 'TEYQ', 'NGVO', 'WOKD', 'WMKQ', 'EUDK', 'UFNF', 'DXJP', 'ANAV', 'JBXP', 'WTIY', 'XKAL', 'DRDQ', 'ZTAL', 'EMBJ', 'YYTZ', 'PGJC', 'GZTO', 'FXXV', 'DBQH', 'VPQA', 'VKPD', 'RTBV', 'IQMQ', 'FIVC', 'QQTV', 'YFDE', 'ODJH', 'UICN', 'URXR', 'SSNK', 'CBDG', 'QHTL', 'QMGI', 'UZMT', 'EGRU', 'AAAA', 'XPRU', 'BVEH', 'UING', 'BPPX', 'YNRZ', 'OWHE', 'RGYJ', 'MPOB', 'AOXY', 'VNWM', 'OVOW', 'WGNY', 'TMPJ', 'FQGS', 'QVFJ', 'IXRA', 'BYOU', 'OGBK', 'YJKM', 'EODT', 'HTLW', 'RTUG', 'PGBB', 'IHGX', 'HASK', 'HRGF', 'FMRE', 'UVRZ', 'JVRV', 'MRPD', 'SGLD', 'CXQX', 'GJJJ', 'RIKR', 'KSQU', 'BFJK', 'CPSL', 'CXIJ']
# These two ids produce errors when generating their trace plots.
error_cluster1 = ['LMUU']
error_cluster2 = ['FWDA']
for id in cluster1:
generate_plot(id, 1)
for id in cluster2:
generate_plot(id, 2)
<file_sep>import pandas as pd
from sklearn.decomposition import PCA
import glob
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
def main():
feature_list = []
directoryPath = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Parsed_Data/'
for file_name in glob.glob(directoryPath + '*.csv'):
df = pd.read_csv(file_name)
# read in the data on X and Z position plus the rotation
feature = list(df['posX'].values[0:30000:10])
feature2 = list(df['posZ'].values[0:30000:10])
feature3 = list(df['rotX'].values[0:30000:10])
feature4 = list(df['rotZ'].values[0:30000:10])
feature5 = list(df['rotZ'].values[0:30000:10])
feature.extend(feature2)
feature.extend(feature3)
feature.extend(feature4)
feature.extend(feature5)
# Select the data with 15000 frames; the other subjects not with 15000 frames are not considered
if len(feature) == 15000:
feature_list.append(feature)
# PCA
pca = PCA(n_components=2)
# Option 1: Directly do the PCA
# principalComponents = pca.fit_transform(feature_list)
# Option 2: First standardize the data, then do the PCA
X_std = StandardScaler().fit_transform(feature_list)
principalComponents = pca.fit_transform(X_std)
principalDF = pd.DataFrame(principalComponents)
# display the scatter plot
plt.scatter(principalDF[0], principalDF[1], alpha=1)
plt.xlabel('PCA 1')
plt.ylabel('PCA 2')
plt.show()
main()
<file_sep>import pandas as pd
from scipy.stats import ttest_ind
from scipy.stats import levene
# This path may not work, since it begin legacy code.
file_path = "/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Chrastil Warren data.csv"
df = pd.read_csv(file_path)
data = df.values
# Clusters derived from the umap_clustering method.
cluster1 = ['GGWU', 'TYJR', 'FMKJ', 'ACGN', 'SIUT', 'WJJU', 'MTXB', 'NUAO', 'CGWN', 'AELV', 'WONG', 'SFUG', 'MCCO', 'ONVA', 'LMUU', 'ZDGH', 'LAWW', 'VZYX', 'YPGZ']
cluster2 = ['YPQL', 'GGMO', 'BQHT', 'LQKJ', 'UPGW', 'FPIT', 'XQJO', 'OUWM', 'RCEH', 'UREH', 'TEYQ', 'NGVO', 'WOKD', 'WMKQ', 'EUDK', 'UFNF', 'DXJP', 'ANAV', 'JBXP', 'WTIY', 'XKAL', 'DRDQ', 'ZTAL', 'EMBJ', 'YYTZ', 'PGJC', 'GZTO', 'FXXV', 'FWDA', 'DBQH', 'VPQA', 'VKPD', 'RTBV', 'IQMQ', 'FIVC', 'QQTV', 'YFDE', 'ODJH', 'UICN', 'URXR', 'SSNK', 'CBDG', 'QHTL', 'QMGI', 'UZMT', 'EGRU', 'AAAA', 'XPRU', 'BVEH', 'UING', 'BPPX', 'YNRZ', 'OWHE', 'RGYJ', 'MPOB', 'AOXY', 'VNWM', 'OVOW', 'WGNY', 'TMPJ', 'FQGS', 'QVFJ', 'IXRA', 'BYOU', 'OGBK', 'YJKM', 'EODT', 'HTLW', 'RTUG', 'PGBB', 'IHGX', 'HASK', 'HRGF', 'FMRE', 'UVRZ', 'JVRV', 'MRPD', 'SGLD', 'CXQX', 'GJJJ', 'RIKR', 'KSQU', 'BFJK', 'CPSL', 'CXIJ']
# Create 4 metrics for both clusters
SBSOD1 = []
SBSOD2 = []
dist1 = []
dist2 = []
direct1 = []
direct2 = []
MRT1 = []
MRT2 = []
for row in data:
if row[0] in cluster1:
SBSOD1.append(row[1])
dist1.append(row[2])
direct1.append(row[3])
MRT1.append(row[6])
elif row[0] in cluster2:
SBSOD2.append(row[1])
dist2.append(row[2])
direct2.append(row[3])
MRT2.append(row[6])
# DO 2 independent samples t-test for 4 metrics, if set equal_var = False, then it's Welch's test.
# It depends on the result from Levene's test.
# For Levene's test, since our data is not heavy-tailed, use the median version for all 4 metrics.
print('SBSOD:')
print(SBSOD1)
print(SBSOD2)
levene_SBSOD, p_levene_SBSOD = levene(SBSOD1, SBSOD2, center='median')
print('stat=%.3f, p=%.3f' % (levene_SBSOD, p_levene_SBSOD))
if p_levene_SBSOD > 0.05:
print('Treat the two SBSOD samples with equal variance')
else:
print('Treat the two SBSOD samples with different variances')
stat_SBSOD, p_SBSOD = ttest_ind(SBSOD1, SBSOD2, equal_var=True)
print('stat=%.3f, p=%.3f' % (stat_SBSOD, p_SBSOD))
if p_SBSOD > 0.05:
print('Probably the same distribution for SBSOD data')
else:
print('Probably different distributions for SBSOD data\n')
print('\nDistance:')
print(dist1)
print(dist2)
levene_dist, p_levene_dist = levene(dist1, dist2, center='median')
print('stat=%.3f, p=%.3f' % (levene_dist, p_levene_dist))
if p_levene_dist > 0.05:
print('Treat the two distance samples with equal variance')
else:
print('Treat the two distance samples with different variances')
stat_dist, p_dist = ttest_ind(dist1, dist2, equal_var=True)
print('stat=%.3f, p=%.3f' % (stat_dist, p_dist))
if p_dist > 0.05:
print('Probably the same distribution for distance data')
else:
print('Probably different distributions for distance data\n')
print('\nDirection:')
print(direct1)
print(direct2)
levene_direct, p_levene_direct = levene(direct1, direct2, center='median')
print('stat=%.3f, p=%.3f' % (levene_direct, p_levene_direct))
if p_levene_direct > 0.05:
print('Treat the two direction samples with equal variance')
else:
print('Treat the two direction samples with different variances')
stat_direct, p_direct = ttest_ind(direct1, direct2, equal_var=True)
print('stat=%.3f, p=%.3f' % (stat_direct, p_direct))
if p_direct > 0.05:
print('Probably the same distribution for direction data')
else:
print('Probably different distributions for direction data\n')
print('\nMRT:')
print(MRT1)
print(MRT2)
levene_MRT, p_levene_MRT = levene(MRT1, MRT2, center='median')
print('stat=%.3f, p=%.3f' % (levene_MRT, p_levene_MRT))
if p_levene_MRT > 0.05:
print('Treat the two samples with equal variance')
else:
print('Treat the two samples with different variances')
stat_MRT, p_MRT = ttest_ind(MRT1, MRT2, equal_var=True)
print('stat=%.3f, p=%.3f' % (stat_MRT, p_MRT))
if p_MRT > 0.05:
print('Probably the same distribution for ')
else:
print('Probably different distributions\n')
<file_sep>import matplotlib.pyplot as plt
import umap
import pandas as pd
import glob
def main():
feature_list = []
subject_list = []
directoryPath = '/Users/wangyan/Desktop/Research/Maze_Research/Maze-Navigation/Parsed_Data/'
for file_name in glob.glob(directoryPath + '*.csv'):
df = pd.read_csv(file_name)
# read in the data on X and Z position plus the rotation
feature = list(df['posX'].values[0:30000:10])
feature2 = list(df['posZ'].values[0:30000:10])
feature3 = list(df['rotX'].values[0:30000:10])
feature4 = list(df['rotY'].values[0:30000:10])
feature5 = list(df['rotZ'].values[0:30000:10])
feature.extend(feature2)
feature.extend(feature3)
feature.extend(feature4)
feature.extend(feature5)
# Select the data with 15000 frames; the other subjects not with 15000 frames are not considered
if len(feature) == 15000:
feature_list.append(feature)
# Each csv file is named with 4 letters, so take the 4 letters as their names.
subject_list.append(file_name[74:78])
standard_embedding = umap.UMAP().fit_transform(feature_list)
umapDF = pd.DataFrame(standard_embedding)
# This is a naive way to differentiate the two clusters. But try more times, it will work.
cluster1 = []
cluster2 = []
for i in range(len(standard_embedding)):
if standard_embedding[i][1] > 1:
cluster1.append(subject_list[i])
else:
cluster2.append(subject_list[i])
print(cluster1)
print(cluster2)
# display the scatter plot
plt.scatter(umapDF[0], umapDF[1], alpha=1)
plt.show()
main()
|
31a2beb9e3bd037371fe2b08b2bd81baf67fb84b
|
[
"Markdown",
"Python"
] | 7
|
Markdown
|
hunterwang1112/Maze-Navigation
|
92a7ae3d2e54ae299189f18916db81ce941e0be4
|
8693e55605b340653afc3a11c454a4536afa55a2
|
refs/heads/master
|
<file_sep># spider-of-lagou.com
拉勾网数据爬取可视化
<file_sep>
# coding: utf-8
# In[1]:
# 导入模块
import requests
import time
import re
import pandas as pd
# In[2]:
url = 'https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false'
header ={
'Host': 'www.lagou.com',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN,en-US;q=0.7,en;q=0.3',
'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.lagou.com/jobs/list_Python?labelWords=&fromSearch=true&suginput=',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'X-Anit-Forge-Token': 'None',
'X-Anit-Forge-Code': '0',
'Content-Length': '26',
'Cookie': 'user_trace_token=<PASSWORD>; _ga=GA1.2.545192972.1509707889; LGUID=20171103191805-a9838dac-c088-11e7-9704-5254005c3644; JSESSIONID=ABAAABAACDBABJB2EE720304E451B2CEFA1723CE83F19CC; _gat=1; LGSID=20171228225143-9edb51dd-ebde-11e7-b670-525400f775ce; PRE_UTM=; PRE_HOST=www.baidu.com; PRE_SITE=https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DKkJPgBHAnny1nUKaLpx2oDfUXv9ItIF3kBAWM2-fDNu%26ck%3D3065.1.126.376.140.374.139.129%26shh%3Dwww.baidu.com%26sht%3Dmonline_3_dg%26wd%3D%26eqid%3Db0ec59d100013c7f000000055a4504f6; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; LGRID=20171228225224-b6cc7abd-ebde-11e7-9f67-5254005c3644; index_location_city=%E5%85%A8%E5%9B%BD; TG-TRACK-CODE=index_search; SEARCH_ID=3ec21cea985a4a5fa2ab279d868560c8',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache'}
# In[3]:
for n in range(0,16):
form = {'first':'false',
'kd':'网络安全',
'pn':str(n)}
time.sleep(1)
html = requests.post(url,data=form,headers = header)
#print(html.text)
data = re.findall('{"companyId":.*?,"longitude":".*?","latitude":".*?","positionName":"(.*?)","workYear":"(.*?)","education":"(.*?)","jobNature":".*?","positionId":.*?,"companyShortName":"(.*?)","createTime":".*?","score":.*?,"city":"(.*?)","salary":"(.*?)","positionAdvantage"',html.text)
data = pd.DataFrame(data)
# 保存在本地
data.to_csv(r'c:\LaGouDataMatlab.csv',header = False, index = False, mode = 'a+')
# In[4]:
import pandas as pd # 数据框操作
import numpy as np
import matplotlib.pyplot as plt # 绘图
import jieba # 分词
#from wordcloud import WordCloud # 词云可视化
import matplotlib as mpl # 配置字体
from pyecharts import Geo # 地理图
mpl.rcParams["font.sans-serif"] = ["Microsoft YaHei"]
# 配置绘图风格
plt.rcParams["axes.labelsize"] = 16.
plt.rcParams["xtick.labelsize"] = 14.
plt.rcParams["ytick.labelsize"] = 14.
plt.rcParams["legend.fontsize"] = 12.
plt.rcParams["figure.figsize"] = [15., 15.]
# In[5]:
data = pd.read_csv(r'c:\LaGouDataMatlab.csv') # 导入数据
data.head()
# In[6]:
data.tail()
# In[7]:
data['学历要求'].value_counts().plot(kind='barh',rot=0)
plt.show()
# In[8]:
data['工作经验'].value_counts().plot(kind='bar',rot=20,color='b')
plt.show()
# In[14]:
data['城市'].value_counts().plot(kind='bar',rot=80)
plt.show()
|
22a83f37a544299b473929bb61bfc9f680014cf7
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
q272807578/spider-of-lagou.com
|
59014ce35cb5ad00ed1fc1e53f11edc7bf441cd0
|
88b7ee2bd82507ecd79b400a1f51fb8bdae1feb7
|
refs/heads/master
|
<file_sep># secon_2018
Lipscomb University's Robotics Project for IEEE SoutheastCon 2018 Student Hardware Competition
<file_sep>/*-----( Import needed libraries )-----*/
#include <Stepper.h>
/*-----( Declare Constants, Pin Numbers )-----*/
//---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
#define STEPS_PER_MOTOR_REVOLUTION 32
//---( Steps per OUTPUT SHAFT of gear reduction )---
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64 //2048
#define INTERRUPT 4
/*-----( Declare objects )-----*/
// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to the pin connections need to be pins 0,1,2,3 connected
// to Motor Driver In1, In2, In3, In4
// Then the pins are entered here in the sequence 1-3-2-4 for proper sequencing
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 0, 2, 1, 3);
bool hasWheelTurned = false;
/*-----( Declare Variables )-----*/
int Steps2Take;
void setup() /*----( SETUP: RUNS ONCE )----*/
{
// Nothing (Stepper Library sets pins as outputs)
delay(15000);
pinMode(INTERRUPT, INPUT);
while(digitalRead(INTERRUPT) != HIGH); // do nothing until feather tells me to do my thing
}/*--(end setup )---*/
void loop() /*----( LOOP: RUNS CONSTANTLY )----*/
{
if(hasWheelTurned == false)
{
pinMode(INTERRUPT, OUTPUT); // so I can talk back to feather
small_stepper.setSpeed(1000); // SLOWLY Show the 4 step sequence
Steps2Take = 5*STEPS_PER_OUTPUT_REVOLUTION; // Rotate CW
small_stepper.step(Steps2Take);
hasWheelTurned = true;
digitalWrite(INTERRUPT, LOW); // tell feather that I'm done
}
delay(1000);
}/* --(end main loop )-- */
/* ( THE END ) */
<file_sep>
/*
* Robotics Navigation 2018
*/
#define tooClose 1
#define tooFar 2
#define good 0
#define tooCounter 1
#define tooClock 2
#define tooLeft 1
#define tooRight 2
int phase = 1;
double sensors[14];
int treasureMap[] = {-1, -1, -1};
void setup() {
// setup code here; runs once
}
void loop() {
if(treasureMap[0] == -1) {
// Riley
treasureMap = readIRSensor();
return;
}
// perform every 50 ms
if(!is50ms()) {
return;
}
// Cailey
sensors = JSON.sensors;
if(phase == 1) {
toDestinationA();
} else if(phase == 2) {
centerOnRamp();
} else if(phase == 3) {
downRamp();
} else if(phase == 4) {
toDestinationBWall();
} else if(phase == 5) {
// driving over destination B in the process
toFlagWall();
} else if(phase == 6) {
centerOnFlag();
} else if(phase == 7) {
turnAround();
} else if(phase == 8) {
centerOnChest();
} else if(phase == 9) {
atopChest();
} else if(phase == 10) {
pickUpChest();
} else if(phase == 11) {
centerOnRamp2();
} else if(phase == 12) {
upRamp();
} else if(phase == 13) {
toDestinationA2();
} else {
// localization backup routine?
// just do not be here
}
}
void toDestinationA() {
// currently most numbers are arbitrary / filler values
// ID: back close L, desired: 40 mm, threshold: 8 mm
int spacing = hasSpacing(4, 40, 8);
// ID1: back close L, ID2: back close R, threshold: 8 mm
int parallel = isParallel(4, 5, 8);
if(spacing == tooClose) {
moveForward();
return;
}
if(spacing == tooFar) {
moveBack();
return;
}
// else spacing is good
if(parallel == tooCounter) {
rotateClock();
return;
}
if(parallel == tooClock) {
rotateCounter();
return;
}
// Reid's
if(isButtonPressed()) {
phase++;
return;
}
// else parallel and well-spaced to back wall but button not hit
if(treasureMap[0] == 0) {
moveLeft();
} else {
moveRight();
}
}
void centerOnRamp() {
// ID: back close, desired: 40 mm, threshold: 8 mm
int spacing = hasSpacing(4, 40, 8);
// ID1: back close L, ID2: back close R, threshold: 8 mm
int parallel = isParallel(4, 5, 8);
if(spacing == tooClose) {
moveForward();
return;
}
if(spacing == tooFar) {
moveBack();
return;
}
// else well-spaced from back wall
if(parallel == tooCounter) {
rotateClock();
return;
}
if(parallel == tooClock) {
rotateCounter();
return;
}
// else parallel to back wall
// ID1: left far F, ID2: right far F, threshold: 50 mm
spacing = isCentered(8, 10, 50);
if(spacing == tooLeft) {
moveRight();
return;
}
if(spacing == tooRight) {
moveLeft();
return;
}
// else centered and ready to approach ramp
phase++;
}
void downRamp() {
// ID1: back close L, ID2: back close R, threshold: 8 mm
int parallel = isParallel(4, 5, 8);
// still close to back wall?
if(sensors[4] < 200 && sensors[5] < 200) {
if(parallel == tooCounter) {
rotateClock();
return;
}
if(parallel == tooClock) {
rotateCounter();
return;
}
// else parallel too back wall
moveForward();
return;
}
// else really close to ramp or on ramp
// cannot check back wall due to angle of robot
// now read floor sensors
// ID1: floor L, ID2: floor R, threshold: 8 mm
parallel = isParallel(0, 1, 8);
// ID: floor L, desired: 100 mm, threshold: 25 mm
int spacingL = hasSpacing(0, 100, 25);
if(spacingL == tooFar) {
rotateClock();
return;
}
// ID: floor R, desired: 100 mm, threshold: 25 mm
int spacingR = hasSpacing(1, 100, 25);
if(spacingR == tooFar) {
rotateCounter();
return;
}
// else on solid ground
// are we close to chest?
// ID: front close, desired: 80 mm, threshold: 30 mm
int spacingF = hasSpacing(7, 80, 30);
if(spacingF == tooClose) {
phase++;
return;
}
// else on solid ground but not close enough to chest
moveForward();
}
// INSERT: other phase functions
int hasSpacing(int ID, float desired, float threshold) {
float diff = sensors[ID] - desired;
if(diff > threshold) {
return tooFar;
}
if(diff < -threshold) {
return tooClose;
}
return good;
}
int isParallel(int ID1, int ID2, float threshold) {
float diff = sensors[ID1] - sensors[ID2];
if(diff > threshold) {
return tooCounter;
}
if(diff < -threshold) {
return tooClock;
}
return good;
}
int isCentered(int ID1, int ID2, float threshold) {
// same as isParallel
// renamed to improve high level readability
float diff = sensors[ID1] - sensors[ID2];
if(diff > threshold) {
return tooLeft;
}
if(diff < -threshold) {
return tooRight;
}
return good;
}
<file_sep>/**********************************************************************************************
* Motor Driver for the Lipscomb IEEE 2018 Robotics Project
* Created by <NAME> on April 7, 2018
* This code runs on an Adafruit Feather M0 Express. It controls four wheel motors via two
* MC33926 Motor Driver Shields.
*
* Programming Notes:
* x_DRIVE pins output a PWM signal which controls the speed of the motors. x_DIR pins
* output a binary signal which controls the direction of the motors. (Forward is LOW
* (default), Backward is HIGH)
*
* Helpful Links:
* Feather Guide: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/overview
* Motor Controller General Purpose Guide: https://www.pololu.com/docs/0J55/4
**********************************************************************************************/
#include "Arduino.h"
#include "Motors.h"
#define MFL_DRIVE 12
#define MFR_DRIVE 5
#define MBL_DRIVE 13
#define MBR_DRIVE 11
#define MFL_DIR A1
#define MFR_DIR A3
#define MBL_DIR A0
#define MBR_DIR A2
#define FORWARD LOW
#define BACKWARD HIGH
Motors::Motors(){
pinMode(MFL_DRIVE, OUTPUT);
pinMode(MFR_DRIVE, OUTPUT);
pinMode(MBL_DRIVE, OUTPUT);
pinMode(MBR_DRIVE, OUTPUT);
pinMode(MFL_DIR, OUTPUT);
pinMode(MFR_DIR, OUTPUT);
pinMode(MBL_DIR, OUTPUT);
pinMode(MBR_DIR, OUTPUT);
}
void Motors::Stop(){
analogWrite(MFL_DRIVE, 0);
analogWrite(MFR_DRIVE, 0);
analogWrite(MBL_DRIVE, 0);
analogWrite(MBR_DRIVE, 0);
return;
}
void Motors::DriveForward(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, FORWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::DriveBackward(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, BACKWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::StrafeLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, BACKWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::StrafeRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, FORWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::TurnLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, BACKWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::TurnRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, FORWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::DiagonalForwardRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, 0);
analogWrite(MBL_DRIVE, 0);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::DiagonalForwardLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, FORWARD);
analogWrite(MFL_DRIVE, 0);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, 0);
}
void Motors::DiagonalBackwardLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, 0);
analogWrite(MBL_DRIVE, 0);
analogWrite(MBR_DRIVE, pulseWidth);
}
void Motors::DiagonalBackwardRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, BACKWARD);
analogWrite(MFL_DRIVE, 0);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, 0);
}
void Motors::SquareDance(float speed){
DriveForward(speed);
delay(1500);
StrafeLeft(speed);
delay(1500);
DriveBackward(speed);
delay(1500);
StrafeRight(speed);
delay(1500);
Stop();
}
<file_sep>#include "Adafruit_VL53L0X.h" // https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/arduino-code
#include "Adafruit_VL6180X.h" // https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/wiring-and-test
#include <Wire.h>
#include <IRLibDecodeBase.h>
#include <IRLib_HashRaw.h> //Must be last protocol
#include <IRLibCombo.h> // After all protocols, include this
#include <IRLibRecv.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
#define TCAADDR1 0x71
#define TCAADDR2 0x72
#define TCAADDR3 0x73
Adafruit_VL6180X shortRange = Adafruit_VL6180X();
Adafruit_VL53L0X longRange = Adafruit_VL53L0X();
Adafruit_7segment matrix = Adafruit_7segment();
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Wire.begin(); // join i2c bus as master
Serial.begin(9600);
while(!Serial);
Serial.println("Hello!");
matrix.begin(0x70);
// blink colon on 7-segment display until signal received
matrix.blinkRate(2);
matrix.drawColon(true);
matrix.writeDisplay();
delay(5000);/
I2CSelect(1, -1);
I2CSelect(2, -1);
I2CSelect(3, -1);
Serial.println("BOARD 1");
I2CSelect(1, 0);
Serial.println("Trying...");
if(longRange.begin()) Serial.println("0");
I2CSelect(1, 1);
Serial.println("Trying...");
if(longRange.begin()) Serial.println("1");
I2CSelect(1, 2);
Serial.println("Trying...");
if(longRange.begin()) Serial.println("2");
I2CSelect(1, 3);
Serial.println("Trying...");
if(longRange.begin()) Serial.println("3");
I2CSelect(1, 4);
Serial.println("Trying...");
if(longRange.begin()) Serial.println("4");
I2CSelect(1, 5);
Serial.println("Trying...");
if(longRange.begin()) Serial.println("5");
I2CSelect(1, -1);
Serial.println("\n Setup Complete");
// Serial.println("BOARD 2");
// I2CSelect(2, 0);
// longRange.begin();
// Serial.println("0");
// I2CSelect(2, 1);
// shortRange.begin();
// Serial.println("1");
// I2CSelect(2, 2);
// shortRange.begin();
// Serial.println("2");
// I2CSelect(2, 3);
// shortRange.begin();
// Serial.println("3");
// I2CSelect(2, 4);
// longRange.begin();
// Serial.println("4");
// I2CSelect(2, 5);
// longRange.begin();
// Serial.println("5");
// I2CSelect(2, -1);
// Serial.println("BOARD 3");
// I2CSelect(3, 0);
// longRange.begin();
// Serial.println("0");
// I2CSelect(3, 1);
// longRange.begin();
// Serial.println("1");
// I2CSelect(3, 2);
// shortRange.begin();
// Serial.println("2");
// I2CSelect(3, 3);
// shortRange.begin();
// Serial.println("3");
// I2CSelect(3, 4);
// shortRange.begin();
// Serial.println("4");
// I2CSelect(3, 5);
// shortRange.begin();
// Serial.println("5");
// I2CSelect(3, -1);
}
void loop() {
testMux(1);
delay(5000);
}
void I2CSelect(int mux, int8_t i) {
if (i > 5) {
Serial.println("Returning from tacselect.");
return;
}
if(mux == 1){
Wire.beginTransmission(TCAADDR1);
}
else if(mux == 2){
Wire.beginTransmission(TCAADDR2);
}
else{
Wire.beginTransmission(TCAADDR3);
}
if(i == -1){
Wire.write(0);
}
else{
Wire.write(1 << i);
}
Wire.endTransmission();
return;
}
float ReadShort(){
// float lux = shortRange.readLux(VL6180X_ALS_GAIN_5);
uint8_t range = shortRange.readRange();
uint8_t status = shortRange.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
}
if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
return range;
}
//float ReadLong(){
// VL53L0X_RangingMeasurementData_t measure;
// longRange.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
//
// if (measure.RangeStatus != 4) { // phase failures have incorrect data
// Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
// } else {
// Serial.println(" out of range ");
// }
// return measure.RangeMilliMeter;
//}
void testMux(int muxID){
int testTime = 50;
Serial.println("----------------");
Serial.print("BOARD ");
Serial.println(muxID);
Serial.println("\nSensor 0");
I2CSelect(muxID,0);
ReadShort();
delay(testTime);
Serial.println("\nSensor 1");
I2CSelect(muxID,1);
ReadShort();
delay(testTime);
Serial.println("\nSensor 2");
I2CSelect(muxID,2);
ReadShort();
delay(testTime);
Serial.println("\nSensor 3");
I2CSelect(muxID,3);
ReadShort();
delay(testTime);
Serial.println("\nSensor 4");
I2CSelect(muxID,4);
ReadShort();
delay(testTime);
Serial.println("\nSensor 5");
I2CSelect(muxID,5);
ReadShort();
I2CSelect(muxID,-1);
}
<file_sep>#include "Adafruit_VL53L0X.h" // https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/arduino-code
#include "Adafruit_VL6180X.h" // https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/wiring-and-test
#include <Wire.h>
Adafruit_VL6180X shortRange = Adafruit_VL6180X();
Adafruit_VL53L0X longRange = Adafruit_VL53L0X();
int TCAADDR1 = 0x71;
int TCAADDR2 = 0x72;
int TCAADDR3 = 0x73;
bool I2CSelect(int mux, int8_t sensorNum){
if (sensorNum > 5) return false;
if(mux == 1){
Wire.beginTransmission(TCAADDR1);
}
else if(mux == 2){
Wire.beginTransmission(TCAADDR2);
}
else{
Wire.beginTransmission(TCAADDR3);
}
if(sensorNum == -1){
Wire.write(0); // turn I2C mux off
}
else{
Wire.write(1 << sensorNum); // activate specified I2C sensor
}
Wire.endTransmission();
return true;
}
float ReadShort(){
uint8_t range = shortRange.readRange();
if(Serial){ // If Serial monitor is being used, read and send error messages
uint8_t status = shortRange.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
}
else if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
}
return range;
}
float ReadLong(){
VL53L0X_RangingMeasurementData_t measure;
longRange.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
if(Serial){
if (measure.RangeStatus != 4) { // phase failures have incorrect data
Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
}
else {
Serial.println(" out of range ");
}
}
return measure.RangeMilliMeter;
}
void muxInit(int mux){
Serial.print("BOARD ");
Serial.println(mux);
I2CSelect(mux, 0);
// Serial.println("Trying...");
if(shortRange.begin()){
Serial.println("0 - short");
}
else if(longRange.begin()){
Serial.println("0 - long");
}
else{
Serial.println("0 - SUCKS");
}
I2CSelect(mux, 1);
// Serial.println("Trying...");
if(shortRange.begin()){
Serial.println("1 - short");
}
else if(longRange.begin()){
Serial.println("1 - long");
}
else{
Serial.println("1 - SUCKS");
}
I2CSelect(mux, 2);
// Serial.println("Trying...");
if(shortRange.begin()){
Serial.println("2 - short");
}
else if(longRange.begin()){
Serial.println("2 - long");
}
else{
Serial.println("2 - SUCKS");
}
I2CSelect(mux, 3);
// Serial.println("Trying...");
if(shortRange.begin()){
Serial.println("3 - short");
}
else if(longRange.begin()){
Serial.println("3 - long");
}
else{
Serial.println("3 - SUCKS");
}
I2CSelect(mux, 4);
// Serial.println("Trying...");
if(shortRange.begin()){
Serial.println("4 - short");
}
else if(longRange.begin()){
Serial.println("4 - long");
}
else{
Serial.println("4 - SUCKS");
}
I2CSelect(mux, 5);
// Serial.println("Trying...");
if(shortRange.begin()){
Serial.println("5 - short");
}
else if(longRange.begin()){
Serial.println("5 - long");
}
else{
Serial.println("5 - SUCKS");
}
I2CSelect(mux, -1);
}
<file_sep>#define IOPIN 5
//bool hasSentMessage = false;
void setup() {
// put your setup code here, to run once:
pinMode(IOPIN, OUTPUT);
digitalWrite(IOPIN, LOW);
delay(5000);
digitalWrite(IOPIN, HIGH);
pinMode(IOPIN, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
// if(hasSentMessage == false){
if(digitalRead(IOPIN) == LOW){
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
}
delay(10);
}
<file_sep>#define FORWARDHIGH 1
#define REVERSEHIGH 2
#define SWITCH 3
#define INTERRUPT 4
bool hasArmMoved = false;
void setup() {
delay(15000);
pinMode(FORWARDHIGH, OUTPUT);
pinMode(REVERSEHIGH, OUTPUT);
pinMode(INTERRUPT, INPUT);
while(digitalRead(INTERRUPT) != HIGH); // do nothing until feather tells me to do my thing
}
void loop()
{
// motor power connected to out1
// motor ground connected to out2
if(hasArmMoved == false)
{
pinMode(INTERRUPT, OUTPUT); // so it can tell feather I'm done
armForward(2000);
delay(500);
armReverse(2100);
hasArmMoved = true;
digitalWrite(INTERRUPT, LOW); // tell feather that I'm done
}
delay(1000);
}
void armForward(int delayTime){
digitalWrite(FORWARDHIGH, HIGH);
digitalWrite(REVERSEHIGH, LOW);
delay(delayTime);
digitalWrite(FORWARDHIGH, LOW);
// digitalWrite(REVERSEHIGH, LOW);
}
void armReverse(int delayTime){
digitalWrite(FORWARDHIGH, LOW);
digitalWrite(REVERSEHIGH, HIGH);
delay(delayTime);
// digitalWrite(FORWARDHIGH, LOW);
digitalWrite(REVERSEHIGH, LOW);
}
<file_sep>/*
* Robotics Final Integration Code
*/
#include <IRLibDecodeBase.h>
#include <IRLib_HashRaw.h> //Must be last protocol
#include <IRLibCombo.h> // After all protocols, include this
#include <IRLibRecvLoop.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_VL53L0X.h" // https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/arduino-code
#include "Adafruit_VL6180X.h" // https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/wiring-and-test
#include <Motors.h>
#define TCAADDR1 0x71
#define TCAADDR2 0x72
#define TCAADDR3 0x73
#define testSpeed 30.0
#define tooClose 1
#define tooFar 2
#define good 0
#define tooCounter 1
#define tooClock 2
#define tooLeft 1
#define tooRight 2
/* START & KILL BUTTON STUFF */
const int killButton = SCK;
const int startButton = A5;
bool startProgram = false;
/* IR & 7 SEG STUFF */
const int irRecvPin = A4;
IRdecode myDecoder;
IRrecv myReceiver(irRecvPin);
int sevSegDisplayNumber = 0;
bool calibrationSignal = true;
Adafruit_7segment matrix = Adafruit_7segment();
/* NAV STUFF */
int phase = 1;
double sensors[14];
int treasureMap[] = {-1, -1, -1};
double filter1[3];
double filter2[3];
double filter3[3];
// objects
Adafruit_VL6180X shortRange = Adafruit_VL6180X();
Adafruit_VL53L0X longRange = Adafruit_VL53L0X();
Motors oscar = Motors();
void setup() {
Serial.begin(9600);
// while(!Serial);
Serial.println("Waiting to start");
// initialize start and kill buttons
pinMode(killButton, INPUT_PULLUP); // pin = HIGH when switch open and LOW when switch is pressed
pinMode(startButton, INPUT_PULLUP);
// kill button interrupt
// attachInterrupt(digitalPinToInterrupt(killButton), killFunction, FALLING);
// IR Receiver
Serial.println("Enabling IRin");
myReceiver.enableIRIn(); // Start the receiver
Serial.println("Enabled IRin");
// I2C setup for 7-segment display
matrix.begin(0x70);
// blink colon on 7-segment display until signal received
matrix.blinkRate(2);
matrix.drawColon(true);
matrix.writeDisplay();
setupLidar();
}
void loop() {
// while(true) {
// lidarReadings();
// }
//rileyMaps();
readIRSensor();
myReceiver.disableIRIn();
treasureMap[0] = 1;
// HARDCODED
oscar.StrafeRight(testSpeed);
delay(9000);
oscar.StrafeLeft(testSpeed);
delay(9000);
oscar.DriveBackward(testSpeed);
delay(11000);
oscar.StrafeRight(testSpeed);
delay(9000);
oscar.StrafeLeft(testSpeed);
delay(1000);
oscar.DriveBackward(testSpeed);
delay(8000);
oscar.StrafeLeft(testSpeed);
delay(9000);
oscar.DriveForward(255);
delay(22000);
oscar.StrafeRight(testSpeed);
delay(9000);
/* TESTS:
* detect floor with one sensor
* turn around
* see pressure plate
* hit pressure plate from different angles
*
* DISCOVERIES:
* follow wall works (mostly could only test with long + short)
* follow floor works but is not safe since strafe is not straight
* pressure plate clicks when driving into
* see pressure plate with sensors
*
*
* FIXMES:
* we need left floor sensor
* we need another back close sensor
* we need left side sensor
* some portions of motor is flipped
* robot flipped - buttons in worse position
*/
// perform every some ms -- shouldnt use delay but system timing
while(true) {
// specific sensor updates performed within phase
if(phase == 1) {
toDestinationA();
} else if(phase == 2) {
oneSensorRamp();
//centerOnAndDownRamp();
}
delay(5);
}
// if(phase == 1) {
// toDestinationA();
// } else if(phase == 2) {
// centerOnRamp();
// } else if(phase == 3) {
// downRamp();
// } else if(phase == 4) {
// toDestinationBWall();
// } else if(phase == 5) {
// // driving over destination B in the process
// toFlagWall();
// } else if(phase == 6) {
// centerOnFlag();
// } else if(phase == 7) {
// turnAround();
// } else if(phase == 8) {
// centerOnChest();
// } else if(phase == 9) {
// atopChest();
// } else if(phase == 10) {
// pickUpChest();
// } else if(phase == 11) {
// centerOnRamp2();
// } else if(phase == 12) {
// upRamp();
// } else if(phase == 13) {
// toDestinationA2();
// } else {
// // localization backup routine?
// // just do not be here
// }
}
void toDestinationA() {
// Reid's
// if(isButtonPressed()) {
// phase++;
// // drive away from button wall
// if(treasureMap[0] == 0) {
// oscar.StrafeRight(testSpeed);
// } else {
// oscar.StrafeLeft(testSpeed);
// }
// return;
// }
// read back LIDAR
I2CSelect(2, 2);
double sensorBackRight = ReadShort() + 10.0;
I2CSelect(2, -1);
// filter1[2] = filter1[1];
// filter1[1] = filter1[0];
// filter1[0] = sensorBackRight;
//
// double filtered1 = (filter1[2] + filter1[1] + filter1[0]) / 3.0;
I2CSelect(3, 0);
double sensorBackLeft = ReadLong();
I2CSelect(3, -1);
// filter2[2] = filter2[1];
// filter2[1] = filter2[0];
// filter2[0] = sensorBackLeft;
//
// double filtered2 = (filter2[2] + filter2[1] + filter2[0]) / 3.0;
// ID1: back close L, ID2: back close R, threshold: 8 mm
int parallel = isParallel(sensorBackLeft, sensorBackRight, 10);
// ID: back close L, desired: 40 mm, threshold: 8 mm
int spacing = hasSpacing(sensorBackRight, 120, 10);
if(parallel == tooCounter) {
oscar.TurnLeft(testSpeed);
return;
}
if(parallel == tooClock) {
oscar.TurnRight(testSpeed);
return;
}
// else is parallel
if(spacing == tooClose) {
oscar.DriveBackward(testSpeed);
return;
}
// FIXME: always too far
if(spacing == tooFar) {
oscar.DriveForward(testSpeed);
return;
}
// else parallel and well-spaced to back wall
if(treasureMap[0] == 0) {
oscar.StrafeLeft(testSpeed);
} else {
oscar.StrafeRight(testSpeed);
}
}
void centerOnAndDownRamp() {
// read floor sensors
I2CSelect(2, 2);
double sensorFloorLeft = ReadShort();
I2CSelect(2, -1);
I2CSelect(3, 1);
double sensorFloorRight = ReadShort();
I2CSelect(3, -1);
int leftSafe = hasSpacing(sensorFloorLeft, 150, 10);
if(sensorFloorLeft > 30) {
oscar.StrafeRight(testSpeed);
return;
}
if(sensorFloorRight > 30) {
oscar.StrafeLeft(testSpeed);
return;
}
oscar.DriveForward(testSpeed);
}
//void centerOnRamp() {
//
// // ID: back close, desired: 40 mm, threshold: 8 mm
// int spacing = hasSpacing(4, 40, 8);
//
// // ID1: back close L, ID2: back close R, threshold: 8 mm
// int parallel = isParallel(4, 5, 8);
//
// if(spacing == tooClose) {
// moveForward();
// return;
// }
// if(spacing == tooFar) {
// moveBack();
// return;
// }
// // else well-spaced from back wall
// if(parallel == tooCounter) {
// rotateClock();
// return;
// }
// if(parallel == tooClock) {
// rotateCounter();
// return;
// }
// // else parallel to back wall
//
// // ID1: left far F, ID2: right far F, threshold: 50 mm
// spacing = isCentered(8, 10, 50);
//
// if(spacing == tooLeft) {
// moveRight();
// return;
// }
// if(spacing == tooRight) {
// moveLeft();
// return;
// }
// // else centered and ready to approach ramp
// phase++;
//}
//
//void downRamp() {
//
// // ID1: back close L, ID2: back close R, threshold: 8 mm
// int parallel = isParallel(4, 5, 8);
//
// // still close to back wall?
// if(sensors[4] < 200 && sensors[5] < 200) {
// if(parallel == tooCounter) {
// rotateClock();
// return;
// }
// if(parallel == tooClock) {
// rotateCounter();
// return;
// }
// // else parallel too back wall
// moveForward();
// return;
// }
// // else really close to ramp or on ramp
// // cannot check back wall due to angle of robot
//
// // now read floor sensors
// // ID1: floor L, ID2: floor R, threshold: 8 mm
// parallel = isParallel(0, 1, 8);
//
// // ID: floor L, desired: 100 mm, threshold: 25 mm
// int spacingL = hasSpacing(0, 100, 25);
//
// if(spacingL == tooFar) {
// rotateClock();
// return;
// }
//
// // ID: floor R, desired: 100 mm, threshold: 25 mm
// int spacingR = hasSpacing(1, 100, 25);
// if(spacingR == tooFar) {
// rotateCounter();
// return;
// }
//
// // else on solid ground
//
// // are we close to chest?
// // ID: front close, desired: 80 mm, threshold: 30 mm
// int spacingF = hasSpacing(7, 80, 30);
// if(spacingF == tooClose) {
// phase++;
// return;
// }
//
// // else on solid ground but not close enough to chest
// moveForward();
//}
// INSERT: other phase functions
int hasSpacing(double sensor, float desired, float threshold) {
float diff = sensor - desired;
if(diff > threshold) {
return tooFar;
}
if(diff < -threshold) {
return tooClose;
}
return good;
}
int isParallel(double sensor1, double sensor2, float threshold) {
float diff = sensor1 - sensor2;
if(diff > threshold) {
return tooCounter;
}
if(diff < -threshold) {
return tooClock;
}
return good;
}
int isCentered(int ID1, int ID2, float threshold) {
// same as isParallel
// renamed to improve high level readability
float diff = sensors[ID1] - sensors[ID2];
if(diff > threshold) {
return tooLeft;
}
if(diff < -threshold) {
return tooRight;
}
return good;
}
void readIRSensor() {
unsigned long irCode;
if (myReceiver.getResults()) {
myDecoder.decode();
irCode = myDecoder.value;
Serial.println(irCode, HEX);
// receiving route signal
if (!calibrationSignal)
{
switch(irCode) {
case(0X1AF66ED4):
sevSegDisplayNumber = 1;
treasureMap[0] = 0;
treasureMap[1] = 0;
treasureMap[2] = 0;
break;
case(0X17F66A1D):
sevSegDisplayNumber = 2;
treasureMap[0] = 1;
treasureMap[1] = 0;
treasureMap[2] = 0;
break;
case(0XA4E2155E):
sevSegDisplayNumber = 3;
treasureMap[0] = 0;
treasureMap[1] = 1;
treasureMap[2] = 0;
break;
case(0XA3E213CD):
sevSegDisplayNumber = 4;
treasureMap[0] = 1;
treasureMap[1] = 1;
treasureMap[2] = 0;
break;
case(0XA8726262):
sevSegDisplayNumber = 5;
treasureMap[0] = 0;
treasureMap[1] = 0;
treasureMap[2] = 1;
break;
case(0XA97263F7):
sevSegDisplayNumber = 6;
treasureMap[0] = 1;
treasureMap[1] = 0;
treasureMap[2] = 1;
break;
case(0XB490A256):
sevSegDisplayNumber = 7;
treasureMap[0] = 0;
treasureMap[1] = 1;
treasureMap[2] = 1;
break;
case(0XB390A0C5):
sevSegDisplayNumber = 8;
treasureMap[0] = 1;
treasureMap[1] = 1;
treasureMap[2] = 1;
break;
}
// write route to 7-segment display
matrix.writeDigitRaw(3, 0B000000000);
matrix.blinkRate(0);
matrix.drawColon(false);
matrix.writeDigitNum(4, sevSegDisplayNumber, true);
matrix.writeDisplay();
}
// receiving calibration signal
else {
if(irCode == 0X1AF66ED4) {
sevSegDisplayNumber = 0;
// write GO to 7-segment display
matrix.blinkRate(0);
matrix.drawColon(false);
matrix.writeDigitRaw(3, 0B000111101);
matrix.writeDigitNum(4, 0, false);
matrix.writeDisplay();
}
else {
sevSegDisplayNumber = 9; //arbitrary value
}
}
Serial.println(sevSegDisplayNumber);
myReceiver.enableIRIn(); // Receive the next value
}
delay(100);
}
// called when kill button is pressed
void killFunction() {
//stop moving
//stop motors
Serial.println("Kill button pressed");
matrix.writeDigitNum(4, 1, false);
matrix.writeDisplay();
// do nothing forever
while(1);
}
void setupLidar(){
Wire.begin(); // join i2c bus as master
I2CSelect(1, -1);
I2CSelect(2, -1);
I2CSelect(3, -1);
Serial.println("BOARD 1");
I2CSelect(1, 0);
shortRange.begin();
Serial.println("0");
I2CSelect(1, 1);
shortRange.begin();
Serial.println("1");
I2CSelect(1, 2);
longRange.begin();
Serial.println("2");
I2CSelect(1, 3);
longRange.begin();
Serial.println("3");
I2CSelect(1, 4);
shortRange.begin(); //longRange.begin();
Serial.println("4");
I2CSelect(1, 5);
shortRange.begin(); //longRange.begin();
Serial.println("5");
I2CSelect(1, -1);
Serial.println("BOARD 2");
I2CSelect(2, 0);
longRange.begin();
Serial.println("0");
I2CSelect(2, 1);
shortRange.begin();
Serial.println("1");
I2CSelect(2, 2);
shortRange.begin();
Serial.println("2");
I2CSelect(2, 3);
shortRange.begin();
Serial.println("3");
I2CSelect(2, 4);
longRange.begin();
Serial.println("4");
I2CSelect(2, 5);
longRange.begin();
Serial.println("5"); // FIXME:
I2CSelect(2, -1);
Serial.println("BOARD 3");
I2CSelect(3, 0);
longRange.begin();
Serial.println("0");
I2CSelect(3, 1);
longRange.begin();
Serial.println("1");
I2CSelect(3, 2);
shortRange.begin();
Serial.println("2");
I2CSelect(3, 3);
shortRange.begin();
Serial.println("3");
I2CSelect(3, 4);
shortRange.begin();
Serial.println("4");
I2CSelect(3, -1);
}
void I2CSelect(int mux, int8_t i) {
if (i > 5) {
Serial.println("Returning from tacselect.");
return;
}
if(mux == 1){
Wire.beginTransmission(TCAADDR1);
}
else if(mux == 2){
Wire.beginTransmission(TCAADDR2);
}
else{
Wire.beginTransmission(TCAADDR3);
}
if(i == -1){
Wire.write(0);
}
else{
Wire.write(1 << i);
}
Wire.endTransmission();
return;
}
float ReadShort(){
float lux = shortRange.readLux(VL6180X_ALS_GAIN_5);
uint8_t range = shortRange.readRange();
uint8_t status = shortRange.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
}
if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
return range;
}
float ReadLong(){
VL53L0X_RangingMeasurementData_t measure;
longRange.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
if (measure.RangeStatus != 4) { // phase failures have incorrect data
Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
} else {
Serial.println(" out of range ");
}
return measure.RangeMilliMeter;
}
//void rileyMaps() {
//
//
// // wait until start button is pressed
// while (digitalRead(startButton) == HIGH) {
// // receive calibration IR signal
// readIRSensor();
// }
//
// // Riley
// calibrationSignal = false;
// readIRSensor();
//
// matrix.blinkRate(0);
// matrix.drawColon(false);
// matrix.writeDigitNum(4, 0, false);
// matrix.writeDisplay();
//}
void lidarReadings() {
Serial.println("BOARD 1");
Serial.println("\nSensor 0");
I2CSelect(1,0);
ReadShort();
Serial.println("\nSensor 1");
I2CSelect(1,1);
ReadShort();
Serial.println("\nSensor 2");
I2CSelect(1,2);
ReadLong();
Serial.println("\nSensor 3");
I2CSelect(1,3);
ReadLong();
Serial.println("\nSensor 4");
I2CSelect(1,4);
ReadLong();
Serial.println("\nSensor 5");
I2CSelect(1,5);
ReadLong();
I2CSelect(1,-1);
Serial.println("\n\nBOARD 2");
Serial.println("Sensor 0");
I2CSelect(2,0);
ReadLong();
Serial.println("Sensor 1");
I2CSelect(2,1);
ReadShort();
Serial.println("\nSensor 2");
I2CSelect(2,2);
ReadShort();
Serial.println("Sensor 3");
I2CSelect(2,3);
ReadShort();
Serial.println("Sensor 4");
I2CSelect(2,4);
ReadLong();
Serial.println("Sensor 5");
I2CSelect(2,5);
ReadLong();
I2CSelect(2,-1);
Serial.println("\n\nBOARD 3");
Serial.println("Sensor 0");
I2CSelect(3,0);
ReadLong();
Serial.println("Sensor 1");
I2CSelect(3,1);
ReadLong();
I2CSelect(3,-1);
Serial.println("Sensor 2");
I2CSelect(3,2);
ReadLong();
I2CSelect(3,-1);
Serial.println("Sensor 3");
I2CSelect(3,3);
ReadLong();
I2CSelect(3,-1);
Serial.println("Sensor 4");
I2CSelect(3,4);
ReadLong();
I2CSelect(3,-1);
Serial.println("\n\n\n");
delay(5000);
}
void oneSensorRamp() {
I2CSelect(1,1);
double sensorFloorRight = ReadShort();
I2CSelect(1, -1);
Serial.println(sensorFloorRight);
if(sensorFloorRight > 90) {
oscar.StrafeLeft(testSpeed);
return;
}
oscar.DriveBackward(testSpeed);
}
void seePressure() {
I2CSelect(2, 3);
double sensorRight = ReadShort();
I2CSelect(2, -1);
Serial.println(sensorRight);
}
void followRightWallFar() {
I2CSelect(2, 0);
double sensorRightFront = ReadLong();
I2CSelect(2, -1);
I2CSelect(2, 4);
double sensorRightBack = ReadLong();
I2CSelect(2, -1);
// ID1: back close L, ID2: back close R, threshold: 8 mm
int parallel = isParallel(sensorRightFront, sensorRightBack, 10);
// ID: back close L, desired: 40 mm, threshold: 8 mm
int spacing = hasSpacing(sensorRightFront, 300, 10);
if(parallel == tooCounter) {
Serial.println("turn left");
oscar.TurnLeft(testSpeed);
return;
}
if(parallel == tooClock) {
Serial.println("turn right");
oscar.TurnRight(testSpeed);
return;
}
// else is parallel
if(spacing == tooClose) {
Serial.println("left");
oscar.StrafeLeft(testSpeed);
return;
}
// FIXME: always too far
if(spacing == tooFar) {
Serial.println("right");
oscar.StrafeRight(testSpeed);
return;
}
// else parallel and well-spaced to back wall
if(treasureMap[0] == 0) {
oscar.DriveForward(testSpeed);
Serial.println("34985720983475092347");
} else {
oscar.StrafeRight(testSpeed);
Serial.println("HEREHELRHLKSDHFLH:LFEHL");
}
}
<file_sep>/**********************************************************************************************
* LIDAR Hub code for the Lipscomb IEEE 2018 Robotics Project
* This code runs on an Adafruit Feather M0 Express. It monitors up to 18 Adafruit VL53L0X and VL6180X
* LIDAR sensors over I2C. All VL53L0X and VL6180X have I2C address 0x29, so three Adafruit
* TCA9548A 1-to-8 I2C Multiplexer Breakout boards are used to communicate with all of them.
*
* Helpful Links:
* Feather Guide: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/overview
* VL53L0X Guide: https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/overview
* VL6180X Guide: https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/overview
* TCA9548A Guide: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout?view=all
**********************************************************************************************/
#ifndef LidarHub_h
#define LidarHub_h
#include "Arduino.h"
class LidarHub{
public:
LidarHub();
bool I2CSelect(int mux, int8_t sensorNum);
float ReadShort();
float ReadLong();
private:
Adafruit_VL6180X shortRange;
Adafruit_VL53L0X longRange;
int TCAADDR1 = 0x71;
int TCAADDR2 = 0x72;
int TCAADDR3 = 0x73;
};
#endif
<file_sep>/**********************************************************************************************
* Motor Interface for the Lipscomb IEEE 2018 Robotics Project
* This code runs on an Adafruit Feather M0 Express. It controls two of the wheel motors via a
* MC33926 Motor Driver Shield.
*
* Helpful Links:
* Feather Guide: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/overview
* Motor Controller: https://www.pololu.com/product/2503
**********************************************************************************************/
#define MFL_DRIVE 13
#define MFR_DRIVE 12
#define MBL_DRIVE 11
#define MBR_DRIVE 10
#define MFL_DIR A0
#define MFR_DIR A1
#define MBL_DIR A2
#define MBR_DIR A3
#define FORWARD LOW
#define BACKWARD HIGH
void MotorsInit();
void Stop();
void DriveForward(float speed);
void DriveBackward(float speed);
void StrafeRight(float speed);
void StrafeLeft(float speed);
void TurnLeft(float speed);
void TurnRight(float speed);
void DiagonalForwardRight(float speed);
void DiagonalForwardLeft(float speed);
void DiagonalBackwardRight(float speed);
void DiagonalBackwardLeft(float speed);
void MotorsInit(){
pinMode(MFL_DRIVE, OUTPUT);
pinMode(MFR_DRIVE, OUTPUT);
pinMode(MBL_DRIVE, OUTPUT);
pinMode(MBR_DRIVE, OUTPUT);
pinMode(MFL_DIR, OUTPUT);
pinMode(MFR_DIR, OUTPUT);
pinMode(MBL_DIR, OUTPUT);
pinMode(MBR_DIR, OUTPUT);
}
void Stop(){
analogWrite(MFL_DRIVE, 0);
analogWrite(MFR_DRIVE, 0);
analogWrite(MBL_DRIVE, 0);
analogWrite(MBR_DRIVE, 0);
return;
}
void DriveForward(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, FORWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void DriveBackward(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, BACKWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void StrafeRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, BACKWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void StrafeLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, FORWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void TurnLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, BACKWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void TurnRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, FORWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, pulseWidth);
}
void DiagonalForwardRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, FORWARD);
digitalWrite(MBR_DIR, FORWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, 0);
analogWrite(MBL_DRIVE, 0);
analogWrite(MBR_DRIVE, pulseWidth);
}
void DiagonalForwardLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFR_DIR, FORWARD);
digitalWrite(MBL_DIR, FORWARD);
analogWrite(MFL_DRIVE, 0);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, 0);
}
void DiagonalBackwardLeft(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFL_DIR, BACKWARD);
digitalWrite(MBR_DIR, BACKWARD);
analogWrite(MFL_DRIVE, pulseWidth);
analogWrite(MFR_DRIVE, 0);
analogWrite(MBL_DRIVE, 0);
analogWrite(MBR_DRIVE, pulseWidth);
}
void DiagonalBackwardRight(float speed){
int pulseWidth = 255*(speed/100);
digitalWrite(MFR_DIR, BACKWARD);
digitalWrite(MBL_DIR, BACKWARD);
analogWrite(MFL_DRIVE, 0);
analogWrite(MFR_DRIVE, pulseWidth);
analogWrite(MBL_DRIVE, pulseWidth);
analogWrite(MBR_DRIVE, 0);
}
void SquareDance(float speed){
DriveForward(speed);
delay(1500);
StrafeLeft(speed);
delay(1500);
DriveBackward(speed);
delay(1500);
StrafeRight(speed);
delay(1500);
Stop();
}
<file_sep>/*
* Start button, kill button, IR, and trinket communication code
*/
#include <IRLibDecodeBase.h>
#include <IRLib_HashRaw.h> //Must be last protocol
#include <IRLibCombo.h> // After all protocols, include this
#include <IRLibRecvLoop.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
/* TREASURE MAP ARRAY */
int treasureMap[] = {-1, -1, -1};
/* START & KILL BUTTON STUFF */
const int killButton = SCK;
const int startButton = A5;
bool startProgram = false;
/* CAPTAIN'S WHEEL AND ARM TRINKETS' ENABLE PINS */
int capWheelTrinket = 6;
int armTrinket = MOSI;
/* IR & 7 SEG STUFF */
const int irRecvPin = A4;
IRdecode myDecoder;
IRrecvLoop myReceiver(irRecvPin);
int sevSegDisplayNumber = 0;
bool calibrationSignal = true;
bool programComplete = false;
Adafruit_7segment matrix = Adafruit_7segment();
void setup() {
Serial.begin(9600);
//while(!Serial);
Serial.println("Waiting to start");
// initialize start and kill buttons
pinMode(killButton, INPUT_PULLUP); // pin = HIGH when switch open and LOW when switch is pressed
pinMode(startButton, INPUT_PULLUP);
// kill button interrupt
attachInterrupt(digitalPinToInterrupt(killButton), killFunction, FALLING);
// start button interrupt: sets flag to start program
attachInterrupt(digitalPinToInterrupt(startButton), startFunction, FALLING);
// IR Receiver
Serial.println("Enabling IRin");
myReceiver.enableIRIn(); // Start the receiver
Serial.println("Enabled IRin");
// I2C setup for 7-segment display
matrix.begin(0x70);
// blink colon on 7-segment display until signal received
matrix.blinkRate(2);
matrix.drawColon(true);
matrix.writeDisplay();
// make captain's wheel pin an output
pinMode(capWheelTrinket, OUTPUT);
digitalWrite(capWheelTrinket, LOW); // set it low just to be sure
// make arm pin an output
pinMode(armTrinket, OUTPUT);
digitalWrite(armTrinket, LOW); // set it low just to be sure
}
void loop() {
// wait until start button is pressed
// it will only go through main loop once with this scheme
while (!startProgram) {
// receive calibration IR signal
readIRSensor();
}
startProgram = false; // reset so that program only iterates once
/* ENTER PROGRAM */
/* TEST FOR COMMUNICATING WITH TRINKETS */
//digitalWrite(capWheelTrinket, HIGH); // DO THIS TO MAKE WHEEL TURN
//pinMode(capWheelTrinket, INPUT); // so trinket can tell feather when it's done
//while(digitalRead(capWheelTrinket) == HIGH) {;} // do nothing while captain's wheel does its thing
//digitalWrite(armTrinket, HIGH); // DO THIS TO MAKE ARM MOVE
//pinMode(armTrinket, INPUT); // so trinket can tell feather when it's done
//while(digitalRead(armTrinket) == HIGH) {;} // do nothing while arm does its thing
// Riley
calibrationSignal = false;
readIRSensor();
programComplete = true;
}
void readIRSensor() {
unsigned long irCode;
if (myReceiver.getResults() && !programComplete) {
myDecoder.decode();
irCode = myDecoder.value;
Serial.println(irCode, HEX);
// receiving route signal
if (!calibrationSignal)
{
switch(irCode) {
case(0X1AF66ED4):
sevSegDisplayNumber = 1;
treasureMap[0] = 0;
treasureMap[1] = 0;
treasureMap[2] = 0;
break;
case(0X17F66A1D):
sevSegDisplayNumber = 2;
treasureMap[0] = 1;
treasureMap[1] = 0;
treasureMap[2] = 0;
break;
case(0XA4E2155E):
sevSegDisplayNumber = 3;
treasureMap[0] = 0;
treasureMap[1] = 1;
treasureMap[2] = 0;
break;
case(0XA3E213CD):
sevSegDisplayNumber = 4;
treasureMap[0] = 1;
treasureMap[1] = 1;
treasureMap[2] = 0;
break;
case(0XA8726262):
sevSegDisplayNumber = 5;
treasureMap[0] = 0;
treasureMap[1] = 0;
treasureMap[2] = 1;
break;
case(0XA97263F7):
sevSegDisplayNumber = 6;
treasureMap[0] = 1;
treasureMap[1] = 0;
treasureMap[2] = 1;
break;
case(0XB490A256):
sevSegDisplayNumber = 7;
treasureMap[0] = 0;
treasureMap[1] = 1;
treasureMap[2] = 1;
break;
case(0XB390A0C5):
sevSegDisplayNumber = 8;
treasureMap[0] = 1;
treasureMap[1] = 1;
treasureMap[2] = 1;
break;
}
// write route to 7-segment display
matrix.writeDigitRaw(3, 0B000000000);
matrix.blinkRate(0);
matrix.drawColon(false);
matrix.writeDigitNum(4, sevSegDisplayNumber, true);
matrix.writeDisplay();
}
// receiving calibration signal
else {
if(irCode == 0X1AF66ED4) {
sevSegDisplayNumber = 0;
// write GO to 7-segment display
matrix.blinkRate(0);
matrix.drawColon(false);
matrix.writeDigitRaw(3, 0B000111101);
matrix.writeDigitNum(4, 0, false);
matrix.writeDisplay();
}
else {
sevSegDisplayNumber = 9; //arbitrary value
}
}
Serial.println(sevSegDisplayNumber);
myReceiver.enableIRIn(); // Receive the next value
}
delay(100);
}
// called when start button is pressed
void startFunction() {
startProgram = true;
}
// called when kill button is pressed
void killFunction() {
//stop moving
//stop motors
Serial.println("Kill button pressed");
// do nothing forever
while(1);
}
<file_sep>#include <Motors.h>
#define testSpeed 30.0
Motors oscar = Motors();
void setup() {
Serial.begin(9600);
Serial.println("Initializing Motor Test");
}
void loop(){
oscar.DriveForward(testSpeed);
delay(1000);
oscar.StrafeRight(testSpeed);
delay(1000);
oscar.DriveBackward(testSpeed);
delay(1000);
oscar.StrafeLeft(testSpeed);
delay(1000);
oscar.Stop();
while(1);
}
<file_sep>/**********************************************************************************************
* Motor Driver for the Lipscomb IEEE 2018 Robotics Project
* Created by <NAME> on April 7, 2018
* This code runs on an Adafruit Feather M0 Express. It controls four wheel motors via two
* MC33926 Motor Driver Shields.
*
* Helpful Links:
* Feather Guide: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/overview
* Motor Controller General Purpose Guide: https://www.pololu.com/docs/0J55/4
**********************************************************************************************/
#ifndef Motors_h
#define Motors_h
#include "Arduino.h"
class Motors{
public:
Motors();
void Stop();
void DriveForward(float speed);
void DriveBackward(float speed);
void StrafeRight(float speed);
void StrafeLeft(float speed);
void TurnLeft(float speed);
void TurnRight(float speed);
void DiagonalForwardRight(float speed);
void DiagonalForwardLeft(float speed);
void DiagonalBackwardRight(float speed);
void DiagonalBackwardLeft(float speed);
void SquareDance(float speed);
};
#endif
<file_sep>/**********************************************************************************************
* Motor Interface for the Lipscomb IEEE 2018 Robotics Project
* This code runs on an Adafruit Feather M0 Express. It controls two of the wheel motors via a
* MC33926 Motor Driver Shield.
*
* Helpful Links:
* Feather Guide: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/overview
* Motor Controller: https://www.pololu.com/product/2503
**********************************************************************************************/
#include "motor_interface.h"
#include "Adafruit_VL6180X.h" // https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/wiring-and-test
#include <Wire.h>
//#include <Adafruit_NeoPixel.h>
#define TCAADDR1 0x71
#define TCAADDR2 0x72
#define TCAADDR3 0x73
Adafruit_VL6180X shortRange = Adafruit_VL6180X();
//Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, 8, NEO_GRB + NEO_KHZ800);
float data = 1000.0;
void setup() {
Serial.begin(9600);
MotorsInit();
Wire.begin(); // join i2c bus as master
I2CSelect(2, 1);
shortRange.begin();
Serial.println("1");
delay(1000);
DriveForward(30.0);
}
void loop() {
Serial.println("\nSensor 1");
I2CSelect(2,1);
data = ReadShort();
if(data < 100){
Stop();
Serial.println("Too close!");
}
// delay(50);
}
void I2CSelect(int mux, int8_t i) {
if (i > 5) {
Serial.println("Returning from tacselect.");
return;
}
if(mux == 1){
Wire.beginTransmission(TCAADDR1);
}
else if(mux == 2){
Wire.beginTransmission(TCAADDR2);
}
else{
Wire.beginTransmission(TCAADDR3);
}
if(i == -1){
Wire.write(0);
}
else{
Wire.write(1 << i);
}
Wire.endTransmission();
return;
}
float ReadShort(){
float lux = shortRange.readLux(VL6180X_ALS_GAIN_5);
uint8_t range = shortRange.readRange();
uint8_t status = shortRange.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
return range;
}
if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
return 9999;
}
<file_sep>#define FORWARDHIGH 1
#define REVERSEHIGH 2
#define SWITCH 3
#define INTERRUPT 4
bool hasArmMoved = false;
void setup() {
// put your setup code here, to run once:
pinMode(FORWARDHIGH, OUTPUT);
pinMode(REVERSEHIGH, OUTPUT);
pinMode(INTERRUPT, INPUT);
pinMode(SWITCH, INPUT);
digitalWrite(SWITCH, HIGH);
//
// Serial.begin(9600);
// while(!Serial);
// Serial.println("Code started");
}
void loop() {
// put your main code here, to run repeatedly:
armReverse(100);
delay(3000); // keep trinket from resetting
}
void armForward(int delayTime){
digitalWrite(FORWARDHIGH, HIGH);
digitalWrite(REVERSEHIGH, LOW);
delay(delayTime);
digitalWrite(FORWARDHIGH, LOW);
// digitalWrite(REVERSEHIGH, LOW);
}
void armReverse(int delayTime){
digitalWrite(FORWARDHIGH, LOW);
digitalWrite(REVERSEHIGH, HIGH);
delay(delayTime);
// digitalWrite(FORWARDHIGH, LOW);
digitalWrite(REVERSEHIGH, LOW);
}
<file_sep>/**********************************************************************************************
* LIDAR Hub code for the Lipscomb IEEE 2018 Robotics Project
* This code runs on an Adafruit Trinket M0. It monitors several Adafruit VL53L0X and VL6180X
* LIDAR sensors over I2C. All VL53L0X and VL6180X have I2C address 0x29, so two (three?) Adafruit
* TCA9548A 1-to-8 I2C Multiplexer Breakout boards are used to communicate with all of them.
*
* Helpful Links:
* Trinket Guide: https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino/overview
* VL53L0X Guide: https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/overview
* VL6180X Guide: https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/overview
* TCA9548A Guide: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout?view=all
*
**********************************************************************************************/
#include "Adafruit_VL53L0X.h" // https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/arduino-code
#include "Adafruit_VL6180X.h" // https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/wiring-and-test
#include <Wire.h>
#define TCAADDR1 0x71
#define TCAADDR2 0x72
#define TCAADDR3 0x73
Adafruit_VL6180X shortRange = Adafruit_VL6180X();
Adafruit_VL53L0X longRange = Adafruit_VL53L0X();
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
Serial.begin(9600);
while(!Serial);
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Hello!");
Wire.begin(); // join i2c bus as master
I2CSelect(1, -1);
I2CSelect(2, -1);
I2CSelect(3, -1);
// I2CSelect(3, 0);
// shortRange.begin();
// Serial.println("0");
// I2CSelect(1, 1);
// shortRange.begin();
// Serial.println("1");
// I2CSelect(1, 2);
// shortRange.begin();
// Serial.println("2");
I2CSelect(3, 3);
shortRange.begin();
Serial.println("3");
// I2CSelect(1, 4);
// shortRange.begin();
// Serial.println("4");
// I2CSelect(1, 5);
// shortRange.begin();
// Serial.println("5");
}
void loop() {
// Serial.println("\nSensor 0");
// I2CSelect(1,0);
// ReadShort();
// delay(1000);
//
// Serial.println("\nSensor 1");
// I2CSelect(2,1);
// ReadShort();
// delay(1000);
// Serial.println("\nSensor 2");
// I2CSelect(1,2);
// ReadShort();
// delay(1000);
Serial.println("\nSensor 3");
I2CSelect(3,3);
ReadShort();
delay(1000);
//
// Serial.println("\nSensor 4");
// I2CSelect(1,4);
// ReadShort();
// delay(1000);
//
// Serial.println("\nSensor 5");
// I2CSelect(1,5);
// ReadShort();
// delay(2000);
}
void I2CSelect(int mux, int8_t i) {
if (i > 5) {
Serial.println("Returning from tacselect.");
return;
}
if(mux == 1){
Wire.beginTransmission(TCAADDR1);
}
else if(mux == 2){
Wire.beginTransmission(TCAADDR2);
}
else{
Wire.beginTransmission(TCAADDR3);
}
if(i == -1){
Wire.write(0);
}
else{
Wire.write(1 << i);
}
Wire.endTransmission();
return;
}
float ReadShort(){
float lux = shortRange.readLux(VL6180X_ALS_GAIN_5);
uint8_t range = shortRange.readRange();
uint8_t status = shortRange.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
}
if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
return range;
}
float ReadLong(){
VL53L0X_RangingMeasurementData_t measure;
longRange.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
if (measure.RangeStatus != 4) { // phase failures have incorrect data
Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
} else {
Serial.println(" out of range ");
}
return measure.RangeMilliMeter;
}
<file_sep>/**********************************************************************************************
* LIDAR Hub code for the Lipscomb IEEE 2018 Robotics Project
* This code runs on an Adafruit Feather M0 Express. It monitors up to 18 Adafruit VL53L0X and VL6180X
* LIDAR sensors over I2C. All VL53L0X and VL6180X have I2C address 0x29, so three Adafruit
* TCA9548A 1-to-8 I2C Multiplexer Breakout boards are used to communicate with all of them.
*
* Helpful Links:
* Feather Guide: https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/overview
* VL53L0X Guide: https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/overview
* VL6180X Guide: https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/overview
* TCA9548A Guide: https://learn.adafruit.com/adafruit-tca9548a-1-to-8-i2c-multiplexer-breakout?view=all
**********************************************************************************************/
#include "Arduino.h"
#include "LidarHub.h"
#include "Adafruit_VL53L0X.h" // https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout/arduino-code
#include "Adafruit_VL6180X.h" // https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/wiring-and-test
#include <Wire.h>
#define OFF -1
Adafruit_VL6180X shortRange = Adafruit_VL6180X();
Adafruit_VL53L0X longRange = Adafruit_VL53L0X();
LidarHub::LidarHub(){
Wire.begin();
I2CSelect(1, OFF);
I2CSelect(2, OFF);
I2CSelect(3, OFF);
}
bool LidarHub::I2CSelect(int mux, int8_t sensorNum){
if (sensorNum > 5) return false;
if(mux == 1){
Wire.beginTransmission(TCAADDR1);
}
else if(mux == 2){
Wire.beginTransmission(TCAADDR2);
}
else{
Wire.beginTransmission(TCAADDR3);
}
if(sensorNum == -1){
Wire.write(0); // turn I2C mux off
}
else{
Wire.write(1 << sensorNum); // activate specified I2C sensor
}
Wire.endTransmission();
return true;
}
float LidarHub::ReadShort(){
uint8_t range = shortRange.readRange();
if(Serial){ // If Serial monitor is being used, read and send error messages
uint8_t status = shortRange.readRangeStatus();
if (status == VL6180X_ERROR_NONE) {
Serial.print("Range: "); Serial.println(range);
}
else if ((status >= VL6180X_ERROR_SYSERR_1) && (status <= VL6180X_ERROR_SYSERR_5)) {
Serial.println("System error");
}
else if (status == VL6180X_ERROR_ECEFAIL) {
Serial.println("ECE failure");
}
else if (status == VL6180X_ERROR_NOCONVERGE) {
Serial.println("No convergence");
}
else if (status == VL6180X_ERROR_RANGEIGNORE) {
Serial.println("Ignoring range");
}
else if (status == VL6180X_ERROR_SNR) {
Serial.println("Signal/Noise error");
}
else if (status == VL6180X_ERROR_RAWUFLOW) {
Serial.println("Raw reading underflow");
}
else if (status == VL6180X_ERROR_RAWOFLOW) {
Serial.println("Raw reading overflow");
}
else if (status == VL6180X_ERROR_RANGEUFLOW) {
Serial.println("Range reading underflow");
}
else if (status == VL6180X_ERROR_RANGEOFLOW) {
Serial.println("Range reading overflow");
}
}
return range;
}
float LidarHub::ReadLong(){
VL53L0X_RangingMeasurementData_t measure;
longRange.rangingTest(&measure, false); // pass in 'true' to get debug data printout!
if(Serial){
if (measure.RangeStatus != 4) { // phase failures have incorrect data
Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
}
else {
Serial.println(" out of range ");
}
}
return measure.RangeMilliMeter;
}
<file_sep>/*
* Robotics Final Integration Code
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
#include <Motors.h>
#include "final_Adam.h"
#define tooClose 1
#define tooFar 2
#define good 0
#define tooCounter 1
#define tooClock 2
#define tooLeft 1
#define tooRight 2
#define testSpeed 30
/* START & KILL BUTTON STUFF */
const int killButton = SCK;
const int startButton = 5;
bool startProgram = false;
/* IR & 7 SEG STUFF */
int sevSegDisplayNumber = 0;
bool calibrationSignal = true;
Adafruit_7segment matrix = Adafruit_7segment();
Motors oscar = Motors();
/* NAV STUFF */
int phase = 1;
double sensors[14];
int treasureMap[] = {-1, -1, -1};
double filter1[] = {0.0, 0.0, 0.0};
double filter2[] = {0.0, 0.0, 0.0};
double filter3[] = {0.0, 0.0, 0.0};
double filter4[] = {0.0, 0.0, 0.0};
void setup() {
Serial.begin(9600);
//while(!Serial);
Serial.println("Waiting to start");
// initialize start and kill buttons
pinMode(killButton, INPUT_PULLUP); // pin = HIGH when switch open and LOW when switch is pressed
pinMode(startButton, INPUT_PULLUP);
// kill button interrupt
attachInterrupt(digitalPinToInterrupt(killButton), killFunction, FALLING);
// I2C setup for 7-segment display
matrix.begin(0x70);
// blink colon on 7-segment display until signal received
matrix.blinkRate(2);
matrix.drawColon(true);
matrix.writeDisplay();
muxInit(1);
muxInit(2);
muxInit(3);
}
void loop() {
// // wait until start button is pressed
// while (digitalRead(startButton) == HIGH) {
// // receive calibration IR signal
// readIRSensor();
// }
// /* ENTER PROGRAM */
//
// // Riley
// calibrationSignal = false;
// readIRSensor();
// perform every 50 ms
// if(!is50ms()) {
// return;
// }
treasureMap[0] = 0;
treasureMap[1] = 0;
treasureMap[2] = 0;
phase = 1;
// oscar.StrafeLeft(testSpeed);
// delay(5000);
// oscar.StrafeRight(testSpeed);
// delay(5000);
// oscar.DriveForward(testSpeed);
// delay(5000);
// oscar.Stop();
// while(1);
// oscar.TurnRight(testSpeed); // clockwise
// oscar.TurnLeft(testSpeed); // counter
while(true) {
if(phase == 1) {
toDestinationA();
} else if(phase == 2) {
centerOnRamp();
} else if(phase == 3) {
downRampBlind();
} else if(phase == 4) {
seeChest();
} else if(phase == 5) {
toPressureWall();
} else if(phase == 6) {
seePressurePlate();
}
// FIXME: lazy
delay(10);
}
// if(phase == 1) {
// toDestinationA();
// } else if(phase == 2) {
// centerOnRamp();
// } else if(phase == 3) {
// downRamp();
// } else if(phase == 4) {
// toDestinationBWall();
// } else if(phase == 5) {
// // driving over destination B in the process
// toFlagWall();
// } else if(phase == 6) {
// centerOnFlag();
// } else if(phase == 7) {
// turnAround();
// } else if(phase == 8) {
// centerOnChest();
// } else if(phase == 9) {
// atopChest();
// } else if(phase == 10) {
// pickUpChest();
// } else if(phase == 11) {
// centerOnRamp2();
// } else if(phase == 12) {
// upRamp();
// } else if(phase == 13) {
// toDestinationA2();
// } else {
// // localization backup routine?
// // just do not be here
// }
}
void toDestinationA() {
// // Reid's
// if(isButtonPressed()) {
// phase++;
// return;
// }
// read back short sensors
I2CSelect(1,0);
double backLeftShort = ReadShort(); // FIXME: 5 is ~error
I2CSelect(1,-1);
I2CSelect(2,1);
double backRightShort = ReadShort() + 12;
I2CSelect(2,-1);
double backLeftShortFiltered = throughFilter1(backLeftShort);
double backRightShortFiltered = throughFilter2(backRightShort);
Serial.println(backLeftShortFiltered);
Serial.println(backRightShortFiltered);
delay(1000);
// threshold: 8 mm
int parallel = isParallel(backLeftShortFiltered, backRightShortFiltered, 10);
// desired: 120 mm, threshold: 8 mm
int spacing = hasSpacing(backLeftShortFiltered, 120, 30);
if(parallel == tooLeft) {
oscar.TurnLeft(testSpeed);
Serial.println("turnLeft");
return;
}
if(parallel == tooRight) {
oscar.TurnRight(testSpeed);
Serial.println("turnRight");
return;
}
// else parallel to wall
if(spacing == tooClose) {
oscar.DriveForward(testSpeed);
Serial.println("forward");
return;
}
if(spacing == tooFar) {
oscar.DriveBackward(testSpeed);
Serial.println("backward");
return;
}
// else parallel and well-spaced to back wall but button not hit
if(treasureMap[0] == 0) {
oscar.StrafeLeft(testSpeed);
Serial.println("move left");
} else {
oscar.StrafeRight(testSpeed);
Serial.println("move right");
}
}
void centerOnRamp() {
/*STAY PARALLEL AND WELL SPACED TO BACK WALL*/
// read back short sensors
I2CSelect(1,0);
double backLeftShort = ReadShort();
I2CSelect(1,-1);
I2CSelect(2,1);
double backRightShort = ReadShort();
I2CSelect(2,-1);
// threshold: 8 mm
int parallel = isParallel(backLeftShort, backRightShort, 8);
// desired: 120 mm, threshold: 8 mm
int spacing = hasSpacing(backLeftShort, 120, 8);
if(parallel == tooLeft) {
oscar.TurnRight(testSpeed);
return;
}
if(parallel == tooRight) {
oscar.TurnLeft(testSpeed);
return;
}
// else parallel to wall
if(spacing == tooClose) {
oscar.DriveForward(testSpeed);
return;
}
if(spacing == tooFar) {
oscar.DriveBackward(testSpeed);
return;
}
/*CENTER BETWEEN SIDE YELLOW WALLS*/
// read left side and right side far sensors
I2CSelect(2,0);
double leftFar = ReadLong();
I2CSelect(2,-1);
I2CSelect(1,4);
double rightFar = ReadLong();
I2CSelect(1,-1);
// 8 mm away from center
int centered = isCentered(leftFar, rightFar, 8);
if(centered == tooLeft) {
oscar.StrafeRight(testSpeed);
return;
}
if(centered == tooRight) {
oscar.StrafeLeft(testSpeed);
return;
}
// else centered and ready to approach ramp
phase++;
}
void downRampBlind() {
/* FORWARD UNTIL WE SEE CHEST -- however we (likely) see floor due to ramp angle*/
// FIXME: lazy
oscar.DriveForward(testSpeed);
delay(5000);
phase++;
}
void seeChest() {
oscar.DriveForward(testSpeed);
}
void toPressureWall() {
}
void seePressurePlate() {
}
//void downRamp() {
//
// // ID1: back close L, ID2: back close R, threshold: 8 mm
// int parallel = isParallel(4, 5, 8);
//
// // still close to back wall?
// if(sensors[4] < 200 && sensors[5] < 200) {
// if(parallel == tooCounter) {
// rotateClock();
// return;
// }
// if(parallel == tooClock) {
// rotateCounter();
// return;
// }
// // else parallel too back wall
// moveForward();
// return;
// }
// // else really close to ramp or on ramp
// // cannot check back wall due to angle of robot
//
// // now read floor sensors
// // ID1: floor L, ID2: floor R, threshold: 8 mm
// parallel = isParallel(0, 1, 8);
//
// // ID: floor L, desired: 100 mm, threshold: 25 mm
// int spacingL = hasSpacing(0, 100, 25);
//
// if(spacingL == tooFar) {
// rotateClock();
// return;
// }
//
// // ID: floor R, desired: 100 mm, threshold: 25 mm
// int spacingR = hasSpacing(1, 100, 25);
// if(spacingR == tooFar) {
// rotateCounter();
// return;
// }
//
// // else on solid ground
//
// // are we close to chest?
// // ID: front close, desired: 80 mm, threshold: 30 mm
// int spacingF = hasSpacing(7, 80, 30);
// if(spacingF == tooClose) {
// phase++;
// return;
// }
//
// // else on solid ground but not close enough to chest
// moveForward();
//}
//
//// INSERT: other phase functions
//
int hasSpacing(double reading, float desired, float threshold) {
float diff = reading - desired;
if(diff > threshold) {
return tooFar;
}
if(diff < -threshold) {
return tooClose;
}
return good;
}
int isParallel(double left, double right, float threshold) {
float diff = left - right;
if(diff > threshold) {
return tooLeft;
}
if(diff < -threshold) {
return tooRight;
}
return good;
}
int isCentered(double left, double right, float threshold) {
// same as isParallel just meant to match sensors on opposite sides of robot
float diff = left - right;
if(diff > threshold) {
return tooLeft;
}
if(diff < -threshold) {
return tooRight;
}
return good;
}
// called when kill button is pressed
void killFunction() {
//stop moving
//stop motors
Serial.println("Kill button pressed");
// do nothing forever
while(1);
}
double throughFilter1(double measurement) {
filter1[0] = filter1[1];
filter1[1] = filter1[2];
filter1[2] = measurement;
return (filter1[0] + filter1[1] + filter1[2]) / 3.0;
}
double throughFilter2(double measurement) {
filter2[0] = filter2[1];
filter2[1] = filter2[2];
filter2[2] = measurement;
return (filter2[0] + filter2[1] + filter2[2]) / 3.0;
}
<file_sep>
#include <IRremote.h>
int RECV_PIN = 2;
IRrecv irrecv(RECV_PIN);
decode_results results;
unsigned long irCode;
unsigned int xMarksTheSpot;
void setup()
{
Serial.begin(9600);
// In case the interrupt driver crashes on setup, give a clue
// to the user what's going on.
Serial.println("Enabling IRin");
irrecv.enableIRIn(); // Start the receiver
Serial.println("Enabled IRin");
}
void loop() {
if (irrecv.decode(&results)) {
irCode = results.value;
Serial.println(irCode, HEX);
xMarksTheSpot = decodeBootyLocation(irCode);
Serial.println(xMarksTheSpot);
irrecv.resume(); // Receive the next value
}
delay(100);
}
int decodeBootyLocation(unsigned long bootyLocation) {
int roadMap;
switch(bootyLocation) {
case(0X1AF66ED4):
roadMap = 1;
break;
case(0X17F66A1D):
roadMap = 2;
break;
case(0XA4E2155E):
roadMap = 3;
break;
case(0XA3E213CD):
roadMap = 4;
break;
case(0XA8726262):
roadMap = 5;
break;
case(0XA97263F7):
roadMap = 6;
break;
case(0XB490A256):
roadMap = 7;
break;
case(0XB390A0C5):
roadMap = 8;
break;
}
return roadMap;
}
|
6b1d959ee004eae78e087d149f9fa5d1f54395ed
|
[
"Markdown",
"C",
"C++"
] | 20
|
Markdown
|
LUrobotics/secon_2018
|
308760106f409d4686d7c0d41ad453ee24615402
|
e26b867ed35c1475ead466b4a3afcc707f26940c
|
refs/heads/master
|
<file_sep>package br.com.edu.service;
import java.util.List;
import java.util.Optional;
import br.com.edu.domain.Client;
public interface IService
{ List<Client> listAll();
Client searchClientID(String id);
Client save(Client client);
Client update(Client client);
void delete(String id);
}
<file_sep>package com.edu.demoajax.web.domain;
import java.io.Serializable;
//como os dados irão trafegar na rede, é sempre bom ter a
//classe que implementa esta interface, pois esta vai garantir
//que os dados que estão saindo serão exatamente os dados que
//estão chegando do outro lado.
@SuppressWarnings("serial")//Como estamos implementando esta interface, a idéia é ficar pedindo para que gere um ID referente a esta implementação
public class SocialMetaTag implements Serializable
{ //este atributo vai servir para que armazenemos a instrução
//referente ao nome do site da URL que estamos acessando o produto
//que está tendo cadastrado
private String site;
//para armazenar o titulo do produto que está sendo cadastrado na app
private String title;
//atributo para armazenar a URL referente à promoção
private String url;
//atributo para armazenar a imagem, ou melhor, a URL de acesso desta imagem
private String image;
public String getSite() {return site;}
public void setSite(String site) {this.site = site;}
public String getTitle() {return title;}
public void setTitle(String title) {this.title = title;}
public String getUrl() {return url;}
public void setUrl(String url) {this.url = url;}
public String getImage() {return image;}
public void setImage(String image) {this.image = image;}
@Override public String toString()
{return "SocialMetaTag [site=" + site + ", title=" + title + ", url=" + url + ", image=" + image + "]";}
}<file_sep>$(document).ready(function()
{ confirmouSla = false;
$(".btn-excluir").on("click", function(e)
{ if (!confirmouSla)
{ e.preventDefault();
confirmouSla = confirm("Tem certeza que deseja excluir?");
if(confirmouSla) {$(this).click();}
}
});
});<file_sep>package br.edu.udemy.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Role
{ @Id private String id;
private String name;
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
@Override public String toString() {return "Role [id=" + id + ", name=" + name + "]";}
}<file_sep>package com.edu.demoajax.web.service;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import com.edu.demoajax.web.domain.SocialMetaTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//notação que transforma a classe como de serviço, gerenciado pelo Bean validation
@Service//Este método serve para recuperar as partes mais importantes dos metatags do OpenGraph
public class SocialMetaTagService//o parâmetro será a url de acesso
{ private static Logger log = LoggerFactory.getLogger(SocialMetaTagService.class);
public SocialMetaTag getSocialMetaTagByURL(String url)
{ SocialMetaTag twitter = this.getTwitterCardByURL(url);
if(!this.isEmpty(twitter)) return twitter;
SocialMetaTag opg = this.getOpenGraphByURL(url);
if(!this.isEmpty(opg)) return opg;
/*o retorno nulo será tratado na controller para enviar uma msg
ao usuário dizendo que não foi possível recuperar os dados da URL
que está tentando cadastrar na aplicação*/
return null;
}
private SocialMetaTag getOpenGraphByURL(String url)
{ SocialMetaTag tag = new SocialMetaTag();
//no JSOUP armazenamos os dados recuperados em um objeto do tipo document
try //é necessário ler toda a documentação do JSOUP
{ Document doc = Jsoup.connect(url).get();
//neste SETTER estou indicando o que quero recuperar na página em HTML
//o metodo attr() faz a indicação de qual atributo da meta tag que queremos recuperar.
//para o conteúdo.
tag.setTitle(doc.head().select("meta[property=og:title]").attr("content"));
tag.setSite(doc.head().select("meta[property=og:site_name]").attr("content"));
tag.setImage(doc.head().select("meta[property=og:image]").attr("content"));
tag.setUrl(doc.head().select("meta[property=og:url]").attr("content"));
}
catch (IOException e)
{ System.out.println(e.getMessage());
log.error(e.getMessage(), e.getCause());
}
return tag;
}
/*Quando não encontramos meta tags usando o OpenGraph, devemos fazer testes com Twitter card*/
private SocialMetaTag getTwitterCardByURL(String url)
{ SocialMetaTag tag = new SocialMetaTag();
//no JSOUP armazenamos os dados recuperados em um objeto do tipo document
try //é necessário ler toda a documentação do JSOUP
{ Document doc = Jsoup.connect(url).get();
//neste SETTER estou indicando o que quero recuperar na página em HTML
//o metodo attr() faz a indicação de qual atributo da meta tag que queremos recuperar.
//para o conteúdo.
tag.setTitle(doc.head().select("meta[name=twitter:title]").attr("content"));
tag.setSite(doc.head().select("meta[name=twitter:site]").attr("content"));
tag.setImage(doc.head().select("meta[name=twitter:image]").attr("content"));
tag.setUrl(doc.head().select("meta[name=twitter:url]").attr("content"));
}
catch (IOException e)
{ System.out.println(e.getMessage());
log.error(e.getMessage(), e.getCause());
}
return tag;
}
/*método booleano que verifica se por um método não retornar as metatags,
devemos então usar por outro*/
private boolean isEmpty(SocialMetaTag tag)
{ if(tag.getImage().isEmpty()) return true;
if(tag.getSite().isEmpty()) return true;
if(tag.getTitle().isEmpty()) return true;
if(tag.getUrl().isEmpty()) return true;
/*se houver metatag do tipo OpenGraph, então continuará usando esta
Social Meta Tag*/
return false;
}
}<file_sep>package br.com.erudio.restwithspringboot.data.vo;
import java.io.Serializable;
import org.springframework.hateoas.RepresentationModel;
import com.github.dozermapper.core.Mapping;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/*Para que não mudemos a forma de como devemos
*receber os parametros, colocamos-nos novamente
*desse jeito, e assim não importa se algum outro
*desenvolvedor alterar a ordem de como os atributos
*estão distribuídos*/
@JsonPropertyOrder({
"id",
"firstName",
"lastName",
"adress",
"gender"})
public class PersonVO extends RepresentationModel
implements Serializable
{ private static final long serialVersionUID = 1L;
/*Notation do DOZER, que desse jieto, este irá conseguir se achar*/
@Mapping("id")
@JsonProperty("id")
private Long key;
/*Se quisésemos que tanto firstName como lastName fossem separados não como CamelCase
*mas sim por underline, podemos também usar a mesma notação acima, que obviamente nos
*forçaria mudar também no JsonPropertyOrder acima*/
@JsonProperty("firstName")
private String firstName;
@JsonProperty("lastName")
private String lastName;
private String adress;
/*Se quisessemos que este atributo não aparecesse*/
//@JsonIgnore
@JsonProperty("gender")
private String gender;
public PersonVO() {}
public Long getKey() {return key;}
public void setKey(Long key) {this.key = key;}
public String getFirstName() {return firstName;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getLastName() {return lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public String getAdress() {return adress;}
public void setAdress(String adress) {this.adress = adress;}
public String getGender() {return gender;}
public void setGender(String gender) {this.gender = gender;}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((adress == null) ? 0 : adress.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{ if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
PersonVO other = (PersonVO) obj;
if (adress == null)
{ if (other.adress != null)
return false;
} else if (!adress.equals(other.adress))
return false;
if (firstName == null)
{ if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (gender == null)
{ if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
if (key == null)
{ if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (lastName == null)
{ if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
}<file_sep>package com.mballem.curso.security.repository;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.mballem.curso.security.domain.Usuario;
/*não iremos testar a senha pois esta é automaticamente testada
pelo próprio spring. então um determinado método que vamos usar
mais a frente, o spring vai pegar nossa consulta pelo email e depois
mesmo testa a senha vamos agora, criar aqui no pacote service a classe
usuario senha service*/
public interface UserRepository extends JpaRepository<Usuario, Long>
{ @Query("select u from Usuario u where u.email like :email")
Usuario findByEmail(@Param("email") String email);
/*Consulta por dois valores*/
@Query("select u from Usuario u join u.perfis p where "
+ "u.email like :search% OR p.desc like :search%")
Page<Usuario> findByEmailOrPerfil(String search, Pageable pageable);
/*Usaremos o IN para testar uma lista*/
@Query("select u from Usuario u join u.perfis p where " +
"u.id = :usuarioId AND p.id IN :perfisId")
Optional<Usuario> findByIdAndProfile(Long usuarioId, Long[] perfisId);
@Query("select u from Usuario u where u.email like :email AND u.ativo = true")
Optional<Usuario> findByEmailAndAtivo(String email);
}<file_sep>package com.edu.exemplo.boot.dao;
import org.springframework.stereotype.Repository;
import com.edu.exemplo.boot.domain.Cargo;
@Repository
public class CargoDAO extends AbstractDAO<Cargo, Long>
implements ICargoDAO {}
<file_sep>package com.edu.exemplo.boot.validator;
import java.time.LocalDate;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.edu.exemplo.boot.domain.Funcionario;
/*classe de validação usando spring validator, que é uma técnica de validação
* que permite criar regras mais avançadas para validação*/
public class FuncionarioValidator implements Validator
{ /*este método tem como princípio validar o objeto que estaremos enviando a partir do formulário
com aquele objeto que realmente esta classe deve validar*/
@Override public boolean supports(Class<?> clazz)
{return Funcionario.class.equals(clazz);}
/*O object é o objeto que estamos recebendo do formulário*/
@Override public void validate(Object object, Errors errors)
{ Funcionario funcionario = (Funcionario)object;
//implementação da validação de datas entrada/saída
LocalDate entrada = funcionario.getDataEntrada();
LocalDate saida = funcionario.getDataSaida();
if(saida != null)
{ if(saida.isBefore(entrada))
{errors.rejectValue("dataSaida", "PosteriorDataEntrada.funcionario.dataSaida");}
}
}
}<file_sep>package com.mballem.curso.security.web.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.mballem.curso.security.domain.Especialidade;
import com.mballem.curso.security.service.EspecialidadeService;
@Controller
@RequestMapping("especialidades")
public class EspecialidadeController
{ @Autowired private EspecialidadeService service;
@GetMapping({"", "/"})
public String abrir(Especialidade especialidade)
{return "especialidade/especialidade";}
@PostMapping("/salvar")
public String save(Especialidade especialidade,
RedirectAttributes redirect)
{ this.service.salvar(especialidade);
redirect.addFlashAttribute("sucesso",
"Operação salva com sucesso");
return "redirect:/especialidades";
}
/*Map que pegamos na requisição ajax especialidade.js*/
@GetMapping({"/datatables/server"})
public ResponseEntity<?> getEspecialidade(HttpServletRequest request)
{ return ResponseEntity.ok(
this.service.buscarEspecialidades(request));
}
/*O primeiro método será aquele que irá receber a
*requisição para edição, através do ID, envia os dados
*para os campos de edição do formulário.*/
@GetMapping({"/editar/{id}"})/*path variable para capturar o ID*/
public String preEditar(@PathVariable("id") Long id, ModelMap model)
{ model.addAttribute("especialidade", this.service.buscarPorId(id));
return "especialidade/especialidade";
}
@GetMapping({"/excluir/{id}"})/*path variable para capturar o ID*/
public String excluir(@PathVariable("id") Long id, RedirectAttributes attr)
{ this.service.removerPorId(id);
attr.addFlashAttribute("Sucesso", "Operação realizada com sucesso");
return "redirect:/especialidades";
}
@GetMapping({"/titulo"})
public ResponseEntity<?> getEspecialidadePorTermo(@RequestParam("termo") String termo)
{ List<String> especialidades = this.service.buscarEspecialidadesPorTermo(termo);
return ResponseEntity.ok(especialidades);
}
@GetMapping({"/datatables/server/medico/{id}"})
public ResponseEntity<?> getEspecialidadePorMedico(@PathVariable("id") Long id,
HttpServletRequest request)
{return ResponseEntity.ok(this.service.buscarEspecialidadesPorMedico(id, request));}
}
<file_sep>spring.data.mongodb.database=crudcliente<file_sep>package com.edu.exemplo.boot.domain;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PastOrPresent;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
@SuppressWarnings("serial")
@Entity
@Table(name = "funcionario")
public class Funcionario extends AbstractEntity<Long>
{ @NotBlank//notação de validação para campos não vazias ou prenchimento apenas com espaços
@Size(max=255, min=3)
@Column(name="nome", length = 500, nullable = false)
private String nome;
@NotNull
//notação para formatação de numeros, do Spring
@NumberFormat(style = Style.CURRENCY, pattern="#,##0.00")
//"columnDefinition" atributo que serve para definir qual o tipo de dado de pto flutuante e seu default
@Column(name = "salario", nullable = false, columnDefinition = "DECIMAL(9,2) DEFAULT 0.00")
private BigDecimal salario;
@NotNull//compara com a data de hoje. se for maior, a validação não seria possível
@PastOrPresent(message="{PastOrPresent.funcionario.dataEntrada}")
//este DATE só serve para datas com dia, mes e ano. Existem outros tipos, que
@DateTimeFormat(iso = ISO.DATE)//contém horas junto e outro com apenas tmepo em horas
@Column(name = "data_entrada", nullable = false, columnDefinition = "DATE")
private LocalDate dataEntrada;
@DateTimeFormat(iso = ISO.DATE)
@Column(name = "data_saida", nullable = true, columnDefinition = "DATE")
private LocalDate dataSaida;
//quando utilizo essa notação sobre objeto endereço, queremos dizer que este objeto endereço deve ser validado,
//conforme as instruções de validação que temos na classe de endereços.
@Valid
//essa notação permite que, além de mostrar ao hibernate que a relação é de 1 X 1, ao inserir um
//funcionario, será inserido também em cascata o endereço. e a mesma coisa acontece quando atualiza ou
//deleta um funcionario.
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fun_end_id")//chave estrangeira
private Endereco endereco;
@ManyToOne
@JoinColumn(name = "fun_car_id")
private Cargo cargo;
public String getNome() {return nome;}
public void setNome(String nome) {this.nome = nome;}
public BigDecimal getSalario() {return salario;}
public void setSalario(BigDecimal salario) {this.salario = salario;}
public LocalDate getDataEntrada() {return dataEntrada;}
public void setDataEntrada(LocalDate dataEntrada) {this.dataEntrada = dataEntrada;}
public LocalDate getDataSaida() {return dataSaida;}
public void setDataSaida(LocalDate dataSaida) {this.dataSaida = dataSaida;}
public Endereco getEndereco() {return endereco;}
public void setEndereco(Endereco endereco) {this.endereco = endereco;}
public Cargo getCargo() {return cargo;}
public void setCargo(Cargo cargo) {this.cargo = cargo;}
}
<file_sep>package com.edu.exemplo.boot.controle;
import java.time.LocalDate;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.edu.exemplo.boot.domain.Cargo;
import com.edu.exemplo.boot.domain.Departamento;
import com.edu.exemplo.boot.domain.Funcionario;
import com.edu.exemplo.boot.domain.UF;
import com.edu.exemplo.boot.service.CargoService;
import com.edu.exemplo.boot.service.FuncionarioService;
import com.edu.exemplo.boot.validator.FuncionarioValidator;
@Controller
@RequestMapping("/funcionarios")
public class FuncionarioController
{ @Autowired private FuncionarioService service;
//esta dependencia será necessário para popular a lista de cargos
//no formulário, para o cadastro de funcionarios
@Autowired private CargoService cargoService;
/*O Spring validation faz com que este método seja o primeiro método dentro da classe
* FuncionarioContrller que será executado. Dessa forma ele ativa a validação e o Spring
* MVC vai até a classe funcionario validator para validar os campos antes de liberar o
* acesso da requisição ao método salvar / editar*/
@InitBinder public void initBinder(WebDataBinder binder)
{binder.addValidators(new FuncionarioValidator());}
//mapeando para o método a ser usado
@GetMapping("/cadastrar") //direcionando para o diretório do arquivo html
public String cadastrar(Funcionario funcionario) {return "funcionario/cadastro";}
@PostMapping("/salvar")
public String salvar(@Valid Funcionario funcionario, BindingResult result, RedirectAttributes attribute)
{ if(result.hasErrors()) return "funcionario/cadastro";
service.salvar(funcionario);
attribute.addFlashAttribute("success", "Funcionario inserido com sucesso");
//para que seja redirecionado diretamente para a página de cadastro
return "redirect:/funcionarios/cadastrar";
}
@GetMapping("/editar/{id}")
public String preEditar(@PathVariable("id") Long id, ModelMap model)
{ model.addAttribute("funcionario", this.service.buscarPorId(id));
return "funcionario/cadastro";
}
@PostMapping("/editar")
public String editar(@Valid Funcionario funcionario, BindingResult result, RedirectAttributes attribute)
{ if(result.hasErrors()) return "funcionario/cadastro";
this.service.editar(funcionario);
attribute.addFlashAttribute("success", "Funcionario editado com sucesso.");
return "redirect:/funcionarios/cadastrar";
}
@GetMapping("/excluir/{id}")
public String excluir(@PathVariable("id") Long id, RedirectAttributes attribute)
{ this.service.excluir(id);
attribute.addFlashAttribute("success", "Funcionario removido com sucesso.");
return "redirect:/funcionarios/listar";
}
@GetMapping("/buscar/nome")//estamos usando o RequestParam, ao invés de PathVariable pois o nome não chegará na controller como
public String getPorNome(@RequestParam("nome") String nome, ModelMap model)//um path da url que declaramos na notação GetMapping
{ model.addAttribute("funcionarios", this.service.buscarPorNome(nome));//mas sim como um atributo com um parâmetrodo request
return "funcionario/lista";//quando a gente enviar a requisição, teremos adicionada na URL aquele interrogação, nome = valor
} //do nome digitado no formulário de busca. É um tipo diferente de enviar um parâmetropara o controller
//ao invés de enviar como um path, envia como um atributo do request
@GetMapping("/buscar/cargo")
public String getPorCargo(@RequestParam("id") Long id, ModelMap model)
{ model.addAttribute("funcionarios", this.service.buscarPorCargo(id));
return "funcionario/lista";
}
@GetMapping("/buscar/data")
public String getPorDatas(@RequestParam("entrada") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate entrada,
@RequestParam("saida") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate saida, ModelMap model)
{ model.addAttribute("funcionarios", this.service.buscarPorDatas(entrada, saida));
return "funcionario/lista";
}
//mapeando para o método listar
@GetMapping("/listar") //direcionando para o diretório do arquivo html
public String listar(ModelMap model)
{ model.addAttribute("funcionarios", service.listarTodos());
return "funcionario/lista";
}
@ModelAttribute("cargos")
public List<Cargo> listaDepartamento() {return this.cargoService.listarTodos();}
//Este método nos retorna um array de unidades federativas
@ModelAttribute("ufs")//o qual obtemos através do próprio enum, que nos
public UF[] getUFs() {return UF.values();}//oferece um métodos values, que nos retornará todas as constantes
//que temos no enum em forma de um array. Quando declaramos um enum,
//estes valores são chamados de ctes (classe UF).
}<file_sep>package com.mballem.curso.security.repository;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.mballem.curso.security.domain.Agendamento;
import com.mballem.curso.security.domain.Horario;
import com.mballem.curso.security.repository.projecoes.HistoricoPaciente;
public interface AgendamentoRepository extends JpaRepository<Agendamento, Long>
{ @Query("select h from Horario h where not exists(select a.horario.id "
+ "from Agendamento a where a.medico.id =:id and a.dataConsulta = "
/*agrupando horário de forma crescente ou ascendente*/
+ ":date and a.horario.id = h.id) order by h.horaMinuto asc")
List<Horario> buscarAgendamentoMedico(Long id, LocalDate date);
/*Aqui devemos projetar um resultado, pois quando fazemos uma consulta
*devemos exemplificar a nível de SQL. Para concatenações, usamos a vírgula*/
@Query("select a.id as id, a.paciente as paciente, CONCAT(a.dataConsulta, "
+ "' ', a.horario.horaMinuto) as dataConsulta, a.medico as medico,"
+ " a.especialidade as especialidade from Agendamento a where "
+ "a.paciente.usuario.email like :email")
Page<HistoricoPaciente> findHistoricoByPacienteEmail(String email,
Pageable pageable);
@Query("select a.id as id, a.paciente as paciente, CONCAT(a.dataConsulta, "
+ "' ', a.horario.horaMinuto) as dataConsulta, a.medico as medico,"
+ " a.especialidade as especialidade from Agendamento a where "
+ "a.medico.usuario.email like :email")
Page<HistoricoPaciente> findHistoricoByMedicoEmail(String email,
Pageable pageable);
@Query("select a from Agendamento a where (a.id = :id AND a.paciente.usuario.email like :email) OR "
+ "(a.id = :id AND a.medico.usuario.email like :email)")
Optional<Agendamento> findByIdAndUserName(Long id, String email);
}<file_sep>package com.edu.exemplo.boot.domain;
import java.util.List;
//a notação @Entity permite que esta entidade seja gerenciada pela JPA
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
//uma classe herdeira de AbstractEntity, com ID do tipo Long
@SuppressWarnings("serial")
@Entity
@Table(name="departamento")//define o nome da tabela no BD
public class Departamento extends AbstractEntity<Long>
{ @NotBlank(message = "Informe um nome")//notação de validação para caso tenha campo de entrada em branco ou apenas preenchida com espaços em branco
//notação de tamanho
@Size(min = 3, max = 80, message="O departamento deve conter entre {min} e {max} caracteres")
//atributo nome na tabela não podendo ser nulo e será única
//(sem repetição) e será um tipo VARCHAR de no máximo 60 caracteres.
@Column(name="nome", nullable=false, unique = true, length = 60)
private String nome;
//assim como foi mapeado uma chave estrangeira para a entidade cargo,
//temos um relacionamento bi direcional, e quado temos isso, devemos
//definir qual é o lado fraco e lado forte da relação, que neste caso
//é esta classe possui o lado forte.
@OneToMany(mappedBy = "departamento")
private List<Cargo> cargos;
public String getNome() {return nome;}
public void setNome(String nome) {this.nome = nome;}
public List<Cargo> getCargos() {return cargos;}
public void setCargos(List<Cargo> cargos) {this.cargos = cargos;}
}<file_sep>package com.mballem.curso.security.exception;
/*RuntimeException Exceção padrão do java usado para que uma
*exceção seja lançada em tempo de execução, bem como o nome já diz*/
@SuppressWarnings("serial")
public class AccessDeniedException extends RuntimeException
{ public AccessDeniedException(String msg)
{super(msg);}
}<file_sep>package br.edu.fatec.topicos.controller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller("/entity")
public class EntityController
{ @GetMapping("/entity")
public @ResponseBody String entity() //método do tipo resposta de corpo. foi confgurado que
{return "Entity";} //este endpoint todos poderão acessar mesmo sem usuario e senha
//isto indica que cada página que tiver isso, deverá ter
//papel de ADMIN ou qq outro que esteja dentro desses
//parenteses junto com ADMIN
@PreAuthorize("hasAnyAuthority('ADMIN')")
@GetMapping("/admin/exemplo")
public @ResponseBody String exemplo() //este deverá apresentar usuário e senha
{return "Exemplo";}
}<file_sep>package com.edu.demoajax.web.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
//mapeamento ORM da JPA
@SuppressWarnings("serial")
@Entity//nome da tabela no BD
@Table(name="promocoes")
public class Promocao implements Serializable
{ @Id //auto-incremento
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//nome da tabela e o 2º parâmetro impedirá o atributo
//receber valores nulos
@NotBlank(message = "Titulo é obrigatório")//do pacote javax, este é uma das notações do Bean Validation
@Column(name="titulo", nullable=false)
private String titulo;
@NotBlank(message="Link de promoção é obriatorio!")
@Column(name="link_promocao", nullable=false)
private String linkPromocao;
@Column(name="site_promocao", nullable=false)
private String site;
@Column(name="descricao")
private String descricao;
@Column(name="link_imagem", nullable=false)
private String linkImagem;
@NotNull(message="Preço é obrigatório")
@NumberFormat(style=Style.CURRENCY ,pattern="#,##0.00")
@Column(name="preco_promocao", nullable=false)
private BigDecimal preco;
@Column(name="total_likes" , nullable=false)
private int likes;
@Column(name="data_cadastro" , nullable=false)
private LocalDateTime cadastro;
//@NotNull(message="Categoria é obrigatório")
@ManyToOne
@JoinColumn(name="categoria_fk")
private Categoria categoria;
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getTitulo() {return titulo;}
public void setTitulo(String titulo) {this.titulo = titulo;}
public String getLinkPromocao() {return linkPromocao;}
public void setLinkPromocao(String linkPromocao) {this.linkPromocao = linkPromocao;}
public String getSite() {return site;}
public void setSite(String site) {this.site = site;}
public String getDescricao() {return descricao;}
public void setDescricao(String descricao) {this.descricao = descricao;}
public String getLinkImagem() {return linkImagem;}
public void setLinkImagem(String linkImagem) {this.linkImagem = linkImagem;}
public BigDecimal getPreco() {return preco;}
public void setPreco(BigDecimal preco) {this.preco = preco;}
public int getLikes() {return likes;}
public void setLikes(int likes) {this.likes = likes;}
public LocalDateTime getCadastro() {return cadastro;}
public void setCadastro(LocalDateTime cadastro) {this.cadastro = cadastro;}
public Categoria getCategoria() {return categoria;}
public void setCategoria(Categoria categoria) {this.categoria = categoria;}
@Override public String toString()
{ return "Promocao [id=" + id + ", titulo=" + titulo + ", linkPromocao=" + linkPromocao + ", site=" + site
+ ", descricao=" + descricao + ", linkImage=" + linkImagem + ", preco=" + preco + ", likes=" + likes
+ ", cadastro=" + cadastro + ", categoria=" + categoria + "]";
}
}<file_sep>package br.com.erudio.restwithspringbootudemy.exception.handler;
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import br.com.erudio.restwithspringbootudemy.exception.ExceptionResponse;
import br.com.erudio.restwithspringbootudemy.exception.ResourceNotFoundException;
@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler
{ @ExceptionHandler(Exception.class)
public final ResponseEntity<ExceptionResponse>
handlerAllExcetpions(Exception ex, WebRequest request)
{ ExceptionResponse exceptionResponse = new
ExceptionResponse(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<ExceptionResponse>(exceptionResponse,
HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public final ResponseEntity<ExceptionResponse>
handleBadRequestExcetpions(Exception ex, WebRequest request)
{ ExceptionResponse exceptionResponse = new
ExceptionResponse(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<ExceptionResponse>(exceptionResponse,
HttpStatus.BAD_REQUEST);
}
}<file_sep>package com.mballem.curso.security.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.mballem.curso.security.domain.Medico;
import com.mballem.curso.security.domain.Paciente;
public interface PacienteRepository extends JpaRepository<Paciente, Long>
{ /*Metodo que retorna um OPtional para o tipo paciente*/
@Query("select p from Paciente p where p.usuario.email like :email")
Optional<Paciente> findByUsuarioEmail(String email);
}
<file_sep>package com.edu.demoajax.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.edu.demoajax.web.domain.SocialMetaTag;
import com.edu.demoajax.web.service.SocialMetaTagService;
/*Classe que irá receber a requisição AJAX para que
as instruções das metatags sejam capturadas e depois
devolvidas para a página*/
@Controller//transformando numa classe de controle
@RequestMapping("/meta")//o "/meta" será o path raiz de acesso a este controller.
public class SocialMetaTagController
{ @Autowired private SocialMetaTagService service;
/*metodo cujo retorno será um objeto do Spring MVC. Requisição do tipo POST, pois
não queremos que as informações sejam exibidas na barra de endereços. Para que
possamos acessar este método, teremos que ter lá no lado cliente uma URL que seja
"/meta/info" e que tenha um parâmetro na requisição*/
@PostMapping("/info")
public ResponseEntity<SocialMetaTag> getDadosViaURL(@RequestParam("url") String url)
{ SocialMetaTag smt = this.service.getSocialMetaTagByURL(url);
//retorno com operador ternario.
return smt != null ? ResponseEntity.ok(smt) : ResponseEntity.notFound().build();
}
}<file_sep>package br.edu.fatec.topicos.domain;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Adress
{ @Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@NotBlank(message = "Street is necessary!")
@Column(nullable=false)
private String street;
@Column(nullable=true)
private Long number;
@NotBlank(message = "Village is necessary!")
@Column(nullable=false)
private String village;
@Column(nullable=false)
private String state;
}<file_sep>package com.edu.demoajax.web.controller;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.edu.demoajax.web.domain.Categoria;
import com.edu.demoajax.web.domain.Promocao;
import com.edu.demoajax.web.dto.PromocaoDTO;
import com.edu.demoajax.web.repository.CategoriaRepository;
import com.edu.demoajax.web.repository.PromocaoRepository;
import com.edu.demoajax.web.service.PromocaoDataTablesService;
@Controller
@RequestMapping("/promocao")
public class PromocoesCotroller
{ private static Logger log = LoggerFactory.getLogger(PromocoesCotroller.class);
@Autowired private PromocaoRepository proRepository;
@Autowired private CategoriaRepository catRepository;
//---------------------------------------------------------------------------------------------
//1-Primeiro método responsável por abrir a página
@GetMapping("/tabela")
public String showTable() {return "promo-datatables";}
//2-Segundo método responsavel por receber e responder as requisições. O parâmetro serve para que
//tenhamos acesso às variáveis que estão na solicitação. A url dessa request esta sem o /promocao
//pois ja esta incluso no RequestMapping da classe.
@GetMapping("/datatables/server")
public ResponseEntity<?> dataTables(HttpServletRequest request)
{ Map<String, Object> data = new PromocaoDataTablesService().execute(proRepository, request);
return ResponseEntity.ok(data);
}
//metodo publico de deletar promocao
@GetMapping("/delete/{id}")
public ResponseEntity<?> deletePromocao(@PathVariable("id") Long id)
{ this.proRepository.deleteById(id);
return ResponseEntity.ok().build();
}
//metodo para enviar os dados da promocao selecionada para edição de dados de promocao
@GetMapping("/edit/{id}")
public ResponseEntity<?> getEditPromocao(@PathVariable("id") Long id)
{ //o metodo get() é necessário, pois o findById(id) retorna um Optional<Promocao>
Promocao promocao = this.proRepository.findById(id).get();
return ResponseEntity.ok(promocao);
}
//metodo para fazer o update
@PostMapping("/edit")
public ResponseEntity<?> updatePromocao(@Valid PromocaoDTO dto, BindingResult result)
{ if(result.hasErrors())
{ Map<String, String> errors = new HashMap<>();
//looping por todos os erros de validação
for(FieldError error:result.getFieldErrors())
{ //cria se uma mapeamento das mensagens de erro de acordo com o campo em que poderá ocorrer o erro
errors.put(error.getField(), error.getDefaultMessage());
}
//um erro do tipo 422
return ResponseEntity.unprocessableEntity().body(errors);
}
//para trabalhar com operação de update, é necessário de um objeto promocao que esteja em estado persistente
Promocao promocao = this.proRepository.findById(dto.getId()).get();
//iremos agora recuperar os dados do formulário de edição de promocao
promocao.setCategoria(dto.getCategoria());
promocao.setDescricao(dto.getDescricao());
promocao.setLinkImagem(dto.getLinkImagem());
promocao.setPreco(dto.getPreco());
promocao.setTitulo(dto.getTitulo());
//fazendo a alteração dos dados
this.proRepository.save(promocao);
return ResponseEntity.ok().build();
}
//---------------------------AUTOCOMPLETE------------------------------------------------------
@GetMapping("/site")//este termo é o termo criado no ajax do autocomplete (promo-list.js)
public ResponseEntity<?> autocompleteByTermo(@RequestParam("termo") String termo)
{ List<String> sites = this.proRepository.findSitesByTermo(termo);
return ResponseEntity.ok(sites);
}
@GetMapping("/site/list")
public String listarPorSite(@RequestParam("site") String site, ModelMap model)
{ //trabalhando com ordenação dos elementos, de forma descendente, por data
Sort sort = new Sort(Sort.Direction.DESC, "cadastro");
/*Classe que ficará responsável pela limitação de quantidade de conteúdos
a serem exibidos dentro das listas de promoções. Neste caso a página inicial
será aquele de valor zero*/
PageRequest pr = PageRequest.of(0, 8, sort);
model.addAttribute("promocoes", this.proRepository.findBySite(site, pr));
return "promo-card";
}
//---------------------------ADD LIKES------------------------------------------------------
//"?" é um valor genérico de ResponseEntity.
//"/like" é o URI como caminho de acesso ao repositório para o LIKE
//"{id}" é o parâmetro que receberá o valor do id da promoção
@PostMapping("/like/{id}")
public ResponseEntity<?> addLikes(@PathVariable("id") Long id)
{ this.proRepository.updateSomarLikes(id);
//int likes = this.proRepository.findLikesById(id);
return ResponseEntity.ok(this.proRepository.findLikesById(id));
}
//---------------------------Listar Ofertas-------------------------------------------------
//método que retorna a página de listagem de ofertas
@GetMapping("/list")
public String listarOfertas(ModelMap model)
{ //trabalhando com ordenação dos elementos, de forma descendente, por data
Sort sort = new Sort(Sort.Direction.DESC, "cadastro");
/*Classe que ficará responsável pela limitação de quantidade de conteúdos
a serem exibidos dentro das listas de promoções. Neste caso será apenas (n-1) numero de páginas
e 8 promoções, em órdem de criação*/
PageRequest pr = PageRequest.of(0, 8, sort);
model.addAttribute("promocoes", this.proRepository.findAll(pr));
return "promo-list";
}
@GetMapping("/list/ajax")//o default value serve para setarmos um valor padrão do parâmetro, quando o mesmo não é enviado, e seu tipo será um inteiro
public String listarCards(@RequestParam(name="page", defaultValue = "1") int page,
@RequestParam(name="site", defaultValue = "") String site, ModelMap model)
{ //trabalhando com ordenação dos elementos, de forma descendente, por data.
//esta consulta não se importa com o nome do sitee uma consulta que vai precisar
//ser realizada a partir do nome do site.
Sort sort = new Sort(Sort.Direction.DESC, "cadastro");
/*Classe que ficará responsável pela limitação de quantidade de conteúdos
a serem exibidos dentro das listas de promoções. Neste caso será apenas (n-1) numero de páginas
e 8 promoções, em órdem de criação*/
PageRequest pr = PageRequest.of(page, 8, sort);
//a partir da variavel site, iremos saber que declaramos a partir da assinatura do método.
//Quando esta variável estiver vazia signfica que a gente vai utilizar a consulta findAll().
//quando a variavel não estiver vazia então significa que a consulta vai ser realizada pelo
//nome do site.
if(site.isEmpty()) {model.addAttribute("promocoes", this.proRepository.findAll(pr));}
else model.addAttribute("promocoes", this.proRepository.findBySite(site, pr));
return "promo-card";
}
//---------------------------Add Ofertas----------------------------------------------------
//método publico de salvar que retorna um objeto da classe Promocao.
//quando for enviado uma requisição na URI /promocao/save, será feita
//neste método o salvar.
@PostMapping("/save")//o pto de interrogação permite que o retorno seja de um valor genérico
public ResponseEntity<?> salvar(@Valid Promocao promocao,
//este BindResult vai poder nos dar tomadas de decisão quando houver ou
//não um problema com a validação, ou seja, se um campo pelo menos não passou
//nas regras de validação, poderemos tomar a decisão de não responder requisição
//com sucesso, mas sim enviar para o client side, uma resposta dizendo que um dos campos
//não passou nas regras de validação
BindingResult result)
{ //sempre usamos um objeto de BindResult em uma condição
if(result.hasErrors())
{ Map<String, String> errors = new HashMap<>();
//looping por todos os erros de validação
for(FieldError error:result.getFieldErrors())
{ //cria se uma mapeamento das mensagens de erro de acordo com o campo em que poderá ocorrer o erro
errors.put(error.getField(), error.getDefaultMessage());
}
//um erro do tipo 422
return ResponseEntity.unprocessableEntity().body(errors);
}
log.info("Promocao {}", promocao.toString());
//salva também a data de cadastro
promocao.setCadastro(LocalDateTime.now());
//método de persistencia
this.proRepository.save(promocao);
//não teremos nenhum retorno a num ser uma mensagem de sucesso, que o proprio
//método OK envia pelo HTTP.
return ResponseEntity.ok().build();
}
//lista de categoria que se situa na página promo-add.html em
//uma tag select. o atributo "categorias" é o nome da variável que irá conter a lista e que
//irá levar a lista para a página. Além disso, este faz referência às categorias da página
//<option th:each="c : ${categorias}" th:text="${c.titulo}" th:value="${c.id}">...</option>
@ModelAttribute("categorias")
public List<Categoria> getCategorias() {return this.catRepository.findAll();}
/*método responsável por abrir a página de promoções. Quando a
controller receber a requisição /promocao/add, cairá no método
abrir cadastro e abre a página promo-add.html*/
@GetMapping("/add")
public String abrirCadastro() {return "promo-add";}
}<file_sep>$(document).ready(function () {
moment.locale('pt-BR');
var table = $('#table-especializacao').DataTable({
searching: true,
order: [[ 1, "asc" ]],//força uma ordenação pela coluna numero 1 da tabela
lengthMenu: [5, 10],
processing: true,
serverSide: true,
responsive: true,
ajax: {//requisição ajax para buscar os dados no servidor para preencher a tabela.
url: '/especialidades/datatables/server',
data: 'data'
},//colunas de controle de editar/excluir
columns: [
{data: 'id'},
{data: 'titulo'},
{orderable: false,//não iremos fazer ordenação
data: 'id',
//criando um botão que será incluído na coluna. Esse terá URL que através de ID poderesmos
//editar/excluir
"render": function(id) {
return '<a class="btn btn-success btn-sm btn-block" href="/especialidades/editar/'+
id +'" role="button"><i class="fas fa-edit"></i></a>';
}
},
{orderable: false,
data: 'id',
"render": function(id) {
return '<a class="btn btn-danger btn-sm btn-block" href="/especialidades/excluir/'+
id +'" role="button" data-toggle="modal" data-target="#confirm-modal"><i class="fas fa-times-circle"></i></a>';
}
}
]
});
});
<file_sep>package com.mballem.curso.security.service;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mballem.curso.security.datatables.Datatables;
import com.mballem.curso.security.datatables.DatatablesColunas;
import com.mballem.curso.security.domain.Especialidade;
import com.mballem.curso.security.repository.EspecialidadeRepository;
@Service
public class EspecialidadeService
{ @Autowired private EspecialidadeRepository repository;
@Autowired private Datatables dataTables;
@Transactional(readOnly=false)
public void salvar(Especialidade especialidade)
{this.repository.save(especialidade);}
@Transactional(readOnly=true)
public Map<String, Object> buscarEspecialidades(
HttpServletRequest request)
{ this.dataTables.setRequest(request);
this.dataTables.setColunas(
/*Constantes que temos na classe
*DataTables das Especialidades*/
DatatablesColunas.ESPECIALIDADES);
/*Método verificado se esta vazio, se estiver vazio,
*significa que o usuário fez uma busca sem preencher
*os campos de busca.*/
Page<?> page = this.dataTables.getSearch().isEmpty() ?
this.repository.findAll(this.dataTables.getPageable()):
this.repository.findAllByTitulo(this.dataTables.getSearch(),
this.dataTables.getPageable());
return this.dataTables.getResponse(page);
}
@Transactional(readOnly=true)
public Especialidade buscarPorId(Long id)
{ /*O método findById() retorna um Optional<T>
que no caso, o T = Especialidade. Portanto,
devemos usar o método get() para retornarmos
o objeto do tipo desejado, ou seja, Especialidade*/
return this.repository.findById(id).get();
}
@Transactional(readOnly=false)
public void removerPorId(Long id) {this.repository.deleteById(id);}
@Transactional(readOnly=true)
public List<String> buscarEspecialidadesPorTermo(String termo)
{return this.repository.findEspecialidadesByTermo(termo);}
@Transactional(readOnly=true)
public Set<Especialidade> buscarPorTitulos(String[] titulos)
{return this.repository.findByTitulos(titulos);}
@Transactional(readOnly=true)
public Map<String, Object> buscarEspecialidadesPorMedico(Long id, HttpServletRequest request)
{ this.dataTables.setRequest(request);
this.dataTables.setColunas(DatatablesColunas.ESPECIALIDADES);
Page<Especialidade> page = this.repository.findByIdMedico(id, this.dataTables.getPageable());
return this.dataTables.getResponse(page);
}
}<file_sep>spring.datasource.url = jdbc:mysql://localhost:3306/fatec2020?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=UTC
spring.datasource.username= root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.open-in-view=true
spring.jpa.hibernate.use-new-id-generator-mappings = false
<file_sep>package com.apirest.webflux.document;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/* Anotação que fará o mapeamento entre o objeto Playlist para os dados play list no Banco de dados MongoDB
* (mapeamento Objeto X Dado). Quando ja usamos essa notação, podemos comaeçar a inserir esses dados no BD
* Irá gerar automaticamente a coleção no nosso BD. Ao executar nosso App e Inserir alguns dados, irá criar
* Automaticamente essa playlist no Atlas.*/
@Document
public class Playlist
{ @Id
private String id;
private String nome;
public Playlist(String id, String nome)
{ super();
this.id = id;
this.nome = nome;
}
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public String getNome() {return nome;}
public void setNome(String nome) {this.nome = nome;}
}<file_sep>package com.apirest.webflux;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
/*Essa notação significa que essa será uma classe de configuração do Springframework*/
//@Configuration
public class PlaylistRouter
{ /*Criação de um método com a notação @Bean. O método irá nos retornar um RouterFunction*/
//@Bean
public RouterFunction<ServerResponse> route(PlaylistHandler handler)
{ /*isso retorna um roteamento para cada um dos métodos na classe handler
Que é do tipo GET, onde temos a URI*/
return RouterFunctions.route(
RequestPredicates.GET("/playlist").and(
RequestPredicates.accept(org.springframework.http.MediaType.APPLICATION_JSON)),
//usando o método de referência da classe PlaylistHandler
handler::findAll).andRoute(RequestPredicates.GET("/playlist/{id}")
.and(RequestPredicates.accept(org.springframework.http.MediaType.APPLICATION_JSON)),
handler::findById).andRoute(RequestPredicates.POST("/playlist")
.and(RequestPredicates.accept(org.springframework.http.MediaType.APPLICATION_JSON)),
handler::save);
}
}<file_sep>spring.data.mongodb.uri=mongodb+srv://eduardowmu:290458@cluster0-fomfh.mongodb.net/apirestwebflux?retryWrites=true
spring.data.mongodb.database=apirestwebflux<file_sep>package com.mballem.curso.security.service;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import com.mballem.curso.security.datatables.Datatables;
import com.mballem.curso.security.datatables.DatatablesColunas;
import com.mballem.curso.security.domain.Perfil;
import com.mballem.curso.security.domain.PerfilTipo;
import com.mballem.curso.security.domain.Usuario;
import com.mballem.curso.security.exception.AccessDeniedException;
import com.mballem.curso.security.repository.UserRepository;
@Service
public class UserService implements UserDetailsService
{ @Autowired private UserRepository userRepository;
@Autowired private Datatables dataTables;
/*Dependência para serviço de e-mail para confirmação de cadastro.*/
@Autowired private EmailService emailService;
//método que busca o usuario, que busca o retorno do repositório.
//a notação faz parte do processo de transações do
//spring. Este valor true significa que esta sendo
//gerenciado pelo processo de transação do spring.
//quando temos o retorno do objeto usuário, esse
//esse sistema de transações que gerenciou o método
//buscar por e-mail é encerrado, quando utilizamos
//o método getPerfis() abaixo dentro do loadUserByUsername
//como o sistema transacional do spring ja encerrou
//com o método buscar por e-mail, não temos mais acesso
//a aquela sessão que foi criado com banco de dados
//então, não consegue voltar com o banco de dados e trazer a lista de perfis.
@Transactional(readOnly = true)
public Usuario pullByEmail(String email)
{return this.userRepository.findByEmail(email);}
/*Para solucionar esse problema, adicionamos essa notação também*/
@Transactional(readOnly = true)
@Override public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException
{ //obtendo a resposta da nossa consulta. Um objeto que fica
//na sessão e a partir deste objeto, o spring secuirty consegue
//comparar se o perfil do objeto que está na sessão é igual ao
//perfil que estamos dando a autorização em cada uma das URLs.
Usuario usuario = //this.pullByEmail(username);
this.buscarPorEmailEAtivo(username)
.orElseThrow(() -> new UsernameNotFoundException(
"Usuario "+username+" não encontrado"));
/*User é uma classe do Spring que implementa
*UserDetails. É com isso que iremos conseguir
*passar alguns dos dados que recuperamos a partir
*da consulta*/
return new User(usuario.getEmail(), usuario.getSenha(),
//classe do Spring que possui alguns métodos
//uma delas é a criação de uma lista de regras,
//onde iremos configurar os perfis de cada usuário
AuthorityUtils.createAuthorityList(
this.getAuthorities(usuario.getPerfis())));
}
private String[] getAuthorities(List<Perfil> perfis)
{ String[] authorities = new String[perfis.size()];
for(int i = 0; i < perfis.size(); i++)
{authorities[i] = perfis.get(i).getDesc();}
return authorities;
}
/*Começando a trabalhar com DataTables*/
@Transactional(readOnly = true)
public Map<String, Object> bucarUsuarios(HttpServletRequest request)
{ this.dataTables.setRequest(request);
this.dataTables.setColunas(DatatablesColunas.USUARIOS);
/*Trabalhando com objeto page, que é o resultado
*que obteremos a partir da consulta que será feita
*via spring data JPA*/
Page<Usuario> page = this.dataTables.getSearch().isEmpty() ?
/*se estiver vazio, faremos uma consulta básica do tipo findAll()
*que fará apenas ter recursos de paginação e ordenação.*/
this.userRepository.findAll(this.dataTables.getPageable()) :
/*se não, teremos um parametro, que servirá de filtro,
*que será para que possamos filtrar nossos usuarios*/
this.userRepository.findByEmailOrPerfil(
this.dataTables.getSearch(),
this.dataTables.getPageable());
return this.dataTables.getResponse(page);
}
@Transactional(readOnly = false)
public void save(Usuario usuario)
{ /*Antes de salvar, precisamos criptografar a senha do usuário*/
String cryptPass = new BCryptPasswordEncoder().encode(
usuario.getSenha());
usuario.setSenha(cryptPass);
this.userRepository.save(usuario);
}
@Transactional(readOnly = true)
public Usuario findById(Long id)
{return this.userRepository.findById(id).get();}
@Transactional(readOnly = true)
public Usuario findByIdAndPerfis(Long id, Long[] perfisId)
{ return this.userRepository.findByIdAndProfile(id, perfisId)
/*Este método vai tratar o seguinte: Se existir um usuário dentro
*do Optional, retona um usuário, desde que a consulta tenha retornado
*dados para o mesmo objeto usuário. Caso contrário, irá lançar uma
*exception, que deve ser num formato lambda*/
.orElseThrow(() -> new UsernameNotFoundException("Usuário não encontrado"));
}
public static boolean isSenhaCorreta(String senhaDigitada, String senhaAtual)
{ /*Lembrando que a senha atual deve ser a que esta criptografada*/
return new BCryptPasswordEncoder().matches(senhaDigitada, senhaAtual);
}
@Transactional(readOnly = false)
public void editSenha(Usuario usuario, String senha)
{ usuario.setSenha(new BCryptPasswordEncoder().encode(senha));
this.userRepository.save(usuario);
}
@Transactional(readOnly = false)
public void salvarCadastroPaciente(Usuario usuario) throws MessagingException
{ //Criptografia de senha
String cripty = new BCryptPasswordEncoder().encode(usuario.getSenha());
usuario.setSenha(cripty);
usuario.addPerfil(PerfilTipo.PACIENTE);
this.userRepository.save(usuario);
/*chamando o metodo de serviço de envio de e-mail*/
this.enviarEmailCadastro(usuario.getEmail());
}
@Transactional(readOnly = true)
public Optional<Usuario> buscarPorEmailEAtivo(String email)
{return this.userRepository.findByEmailAndAtivo(email);}
/*Método de envio de serviço de e-mail após salvar o cadastro do usuário.
*Além do envio de e-mail, este carregará um código, para que consiga fazer
*a confirmação do cadastro, enviando como um parametro da URL, pois quando
*chegar o e-mail para o paciente, e clicar no link, este deve conter o e-mail
*para que a aplicação receba essa requisição e possamos ativar o cadastro
*a partir deste e-mail. Esse código é do tipo base64*/
public void enviarEmailCadastro(String email) throws MessagingException
{ /*criação do código de confirmação, cujo método recebe como parametros
um array de bytes*/
String codigo = Base64Utils.encodeToString(email.getBytes());
this.emailService.enviarPedidoConfirmacaoCadastro(email, codigo);
}
/*Método de ativação do cadastro, esse codigo precisa novamente ser convertido
*no e-mail do usuário*/
@Transactional(readOnly = false)
public void ativarCadastroPaciente(String codigo)
{ String email = new String(Base64Utils.decodeFromString(codigo));
/*Criando um objeto do tipo usuario, que será o dono deste e-mail*/
Usuario usuario = this.pullByEmail(email);
/*Condição para caso o usuário não for encontrado, será lançado uma exceção*/
if(usuario.hasNotId())
{ throw new AccessDeniedException("Não foi possível ativar seu cadastro. "
+ "Entre em contato com suporte");
}
/*Caso o usuário exista, ajusta seu cadastro como ativo. Isso o hibernate já
*faz de forma automática se fazermos apenas um setAtivo(true) do método da
*classe*/
usuario.setAtivo(true);
}
@Transactional(readOnly = false)
public void pedidoRedefinicaoSenha(String email) throws MessagingException
{ /*Será usado este método pois o mesmo precisa estar como ativo no cadastro*/
Usuario usuario = this.buscarPorEmailEAtivo(email)
.orElseThrow(() -> new UsernameNotFoundException("Usuário " + email
+ "não encontrado"));
/*Gerando o código verificardor. Essa Classe randomica tem um método que é
*alpha numérico, que recebe como parametro o numero de caracateres que
*definirmos*/
String verificador = RandomStringUtils.randomAlphanumeric(6);
/*configurando o codigo verificador do usuário. Assim iremos então realizar
*o update no banco de dados.*/
usuario.setCodigoVerificador(verificador);
/*Fazendo o envio de email para recuperação de senha*/
this.emailService.enviarPedidoRedefinicaoSenha(email, verificador);
}
}<file_sep>package br.edu.fatec.topicos.entity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Usuario
{ @Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(length = 50)
private String login;
@Column(length = 200)
private String senha;
//cascade = CascadeType.ALL faz com que, quando salva ou delete um usuário, faça para todos os seus papéis
//fetch = FetchType.ALL, faz com que quando consulto os dados do usuário, mostre todos os seus papéis.
@ManyToMany
private Set<Papel> papeis;
}
<file_sep>package com.edu.demoajax.web.service;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import com.edu.demoajax.web.domain.Promocao;
import com.edu.demoajax.web.repository.PromocaoRepository;
/*Classe onde iremos trabalhar com as regras de negócio dos Data tables*/
public class PromocaoDataTablesService
{ //nome dos atributos que temos na classe promoção e estes atributos
//devem seguir exatamente a mesma órdem que temos das colunas da página
//HTML como também das colunas que foram declaradas no arquivo promo-datatable.js
//este vetor é necessário pois temos que relacionar as colunas que tem na tabela
//com os atributos que temos na classe de promoção que representam então as colunas
//que temos no BD
private String[] cols = {"id", "titulo", "site", "linkPromocao", "descricao",
"linkImagem", "preco", "likes", "dtCadastro", "categoria"};
//o parametro repository é para acessar a camada de persistência e o request é para que
//possa recuperar as informações que são enviadas pelo cliente aqui pro lado servidor
public Map<String, Object> execute(PromocaoRepository repository, HttpServletRequest request)
{ //o parametro start é o parametro que indica no datatables que indica o primeiro ponto
//de partida do dataset atual (datatables.net/manual/server-side)
int start = Integer.parseInt(request.getParameter("start"));
//segunda variavel também do tipo int que será a qtdade de itens que teremos por página
//na tabela. este parametro também podemos pegar no site datatables.net
int length = Integer.parseInt(request.getParameter("length"));
//parametro que será incrementado a cada requisição. quando vc abre a tabela abre por exemplo
//com valor 1. Quando fazemos uma paginação passa a ser valor seguinte e assim por diante. É
//uma forma que o datatable utiliza para segurança da transação dos dados.
int draw = Integer.parseInt(request.getParameter("draw"));
//iremos recuperar a partir de um método que vamos criar
int current = this.currentPage(start, length);
//metodo que nos retorna o valor da coluna
String column = columnName(request);
//metodo responsavel pela ordenação, se é acendente ou descendente
Sort.Direction direction = orderBy(request);
//variavel do tipo string que será o valor do campo de pesquisa
String search = searchBy(request);
//regras de paginação
Pageable pageable = PageRequest.of(current, length, direction, column);
//variavel do tipo page
Page<Promocao> page = queryBy(search, repository, pageable);
//variavel do tipo Map
Map<String, Object> json = new LinkedHashMap<>();
json.put("draw", draw);
//total de consultas tem antes de realizar a paginação
json.put("recordsTotal", page.getTotalElements());
json.put("recordsFiltered", page.getTotalElements());
//o método getComtent() tem como retorno uma lista de promoções
json.put("data", page.getContent());
return json;
}
//este método será util para popular a tabela, realizar a paginação, fazer a ordenação
//pelas colunas e também selecionar a quantidade de itens que deseja exibir por página
//na tabela.
private Page<Promocao> queryBy(String search, PromocaoRepository repository, Pageable pageable)
{ //caso o campo de pesquisa estiver vazia, retorne tudo
if(search.isEmpty()) {return repository.findAll(pageable);}
//inclusão de um teste para verificar se a consulta esta sendo feita pelo preço. O
//Método matches cria uma expressão regular que testa se o valor digitado no campo
//de input de pesquisa é um valor monetário. Na verdade verifica se os caracteres iniciais
//digitados é um digito de 0-9. Caso contrário, não cairá nesta condição. Depois é
//verificado se possui um ponto ou vírgula, que podem caracterizar um digito monetário.
//Depois verifica os digitos decimais que representariam numeros dos centavos, em até dois digitos
//referencia: https://regex101.com
if(search.matches("^[0-9]+([.,][0-9]{2})?$"))
{ //quando formos transformar nossa variável search em um objeto BigDecimal para enviar este
//para consulta, se enviarmos a separação dos centavos com uma vírgula teremos uma exceção.
search = search.replace(",", ".");
return repository.findByPrice(new BigDecimal(search), pageable);
}
//caso contrário retorna apenas o que estiver na pesquisa
return repository.findByTitleOrSiteOrCategory(search, pageable);
}
private String searchBy(HttpServletRequest request)
{ //parâmetro do name do campo de pesquisa. Se estiver vazia, retorna vazio,
//se não retorna o proprio valor do campo.
return request.getParameter("search[value]").isEmpty()
? "" : request.getParameter("search[value]");
}
private Direction orderBy(HttpServletRequest request)
{ String order = request.getParameter("order[0][dir]");
//define que será ascendente
Sort.Direction sort = Sort.Direction.ASC;
//testa se o valor dessa variável é a palavra descendente (desc).
//se for, será do tipo descendente
if(order.equalsIgnoreCase("desc")) {sort = Sort.Direction.DESC;}
return sort;
}
private String columnName(HttpServletRequest request)
{ //parametros que buscamos também em datatables.net, referente ao calor da coluna
int iCol = Integer.parseInt(request.getParameter("order[0][column]"));
return this.cols[iCol];
}
//os parametros sao os que recuperamnos do request
private int currentPage(int start, int length) {return length > 0 ? start/length:0;}
}
<file_sep>package com.edu.exemplo.boot.controle;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.edu.exemplo.boot.domain.Departamento;
import com.edu.exemplo.boot.service.DepartamentoService;
@Controller
@RequestMapping("/departamentos")
public class DepartamentoController
{ @Autowired//instanciado automaticamente
private DepartamentoService service;
//mapeando para o método a ser usado
@GetMapping("/cadastrar")//direcionando para o diretório do arquivo html
public String cadastrar(Departamento departamento) {return "/departamento/cadastro";}
//mapeando para o método listar
@GetMapping("/listar")//direcionando para o diretório do arquivo html
public String listar(ModelMap model)
{ model.addAttribute("departamentos", service.listarTodos());
return "/departamento/lista";
}
//criar um método que vai receber os submits dos formulários
//e assim a gente pega aquele objeto departamento que está sendo
//enviado pelo formulário e agente insere no BD.
@PostMapping("/salvar")
public String salvar(@Valid Departamento departamento, BindingResult result, RedirectAttributes attribute)
{ if(result.hasErrors()) return "/departamento/cadastro";
service.salvar(departamento);
attribute.addFlashAttribute("success", "Departamento inserido com sucesso");
//para que seja redirecionado diretamente para a página de cadastro
return "redirect:/departamentos/cadastrar";
}
//irá pegar pelo id do departamento que deverá ser editado
@GetMapping("/editar/{id}")//pegando o id do departamento e o model map servirá para enviar o departamento como uma variável
public String preEditar(@PathVariable("id") Long id, ModelMap model)//para a página de cadastro.
{ model.addAttribute("departamento", service.buscarPorId(id));
return "/departamento/cadastro";
}
@PostMapping("/editar") //classe de redirecionamento de atributos
public String editar(@Valid Departamento departamento, BindingResult result, RedirectAttributes attribute)
{ if(result.hasErrors()) return "/departamento/cadastro";
service.editar(departamento);
attribute.addFlashAttribute("success", "Departamento alterado com sucesso");
return "redirect:/departamentos/cadastrar";
}
@GetMapping("/excluir/{id}")
public String excluir(@PathVariable("id") Long id, ModelMap model)
{ //teste de se caso houver algum cargo vinculado ao depto, então
//o mesmo não poderá ser excluído. Caso contrário, poderá ser excluído
if(service.temCargo(id)) {model.addAttribute("fail", "Departamento não removido");}
else
{ this.service.excluir(id);
model.addAttribute("success", "Departamento excluído com sucesso");
}
return this.listar(model);
}
}<file_sep>//datatables - lista de médicos
$(document).ready(function() {
moment.locale('pt-BR');
var table = $('#table-usuarios').DataTable({
searching : true,
lengthMenu : [ 5, 10 ],
processing : true,
serverSide : true,
responsive : true,
ajax : {/*URL a ser configurado na controller da lista
de usuários para o datatable*/
url : '/u/datatables/server/usuarios',
data : 'data'
},
columns : [
{data : 'id'},
{data : 'email'},
{ /*Esta coluna no banco de dados possui valor
0 e 1. Mas quando o resultado da coluna chega
na aplicação este 0 e 1 é transformado em
booleano que será false/true*/
data : 'ativo',
render : function(ativo) {
return ativo == true ? 'Sim' : 'Não';
}
},
{ /*Na parte de perfis, é um pouco mais complicado
pois temos na classe de usuário uma lista de perfis
então quando recebemos os resultado no JS, iremos
receber um resultado de uma lista. Mas essa lista
é baseada no objeto perfil, que contém o ID e descição
do perfil. O que queremos mostrar na página, é apenas
a descrição do problema do perfil, se é ADMIN, Médico,
ou se é paciente. Por conta disso, usamos a função render
para recuperar essa lista, faremos um "for" nessa
lista e para isso, no jquery temos o método each,
passamos a lista de perfis, para informar sobre qual
lista iremos percorrer com este looping e temos o índice
e um valor. O índice é a posição na lista e o valor seria o
objeto dentro daquela lista. Então nesse caso o objeto é o
objeto perfil da classe perfil.*/
data : 'perfis',
render : function(perfis) {
var aux = new Array();
$.each(perfis, function( index, value ) {
/*Para que recuperemos a descrição
desse objeto perfil, pegamos a variável
value.desc, pois na classe perfil, temos
o ID e a descrição. Como queremos a descrição
pegaremos apenas o value.desc. Estamos inserindo
essa descrição em um array. Então criamos um
array auxiliar, com um método push o valor
que estamos recuperando no looping, por exemplo
a descrição de ADMIN, inserindo em um array e o mesmo
para os outros perfis.*/
aux.push(value.desc);
});
return aux;
},//não estamos trabalhando com ordenação
orderable : false,
},
{ data : 'id',
render : function(id) {
return ''.concat(
'<a class="btn btn-success btn-sm btn-block"', ' ')
.concat('href="').concat(
'/u/editar/credenciais/usuario/').concat(id, '"', ' ')
.concat(
'role="button" title="Editar" data-toggle="tooltip" data-placement="right">', ' ')
.concat('<i class="fas fa-edit"></i></a>');
},
orderable : false
},
{ data : 'id',
render : function(id) {
return ''.concat(
'<a class="btn btn-info btn-sm btn-block"', ' ')
/*Neste caso não temos o link dentro do botão pois neste precisaremos de
*dois parâmetros, o ID e do parâmetro referente aos perfis e não conse-
*guimos recuperar dentro de um mesmo elemento o valor de duas colunas
*diferentes. Então iremos precisar criar uma função fora do código da tabela
*para que possamos acessar as colunas e pegá-los para concatenar a nossa
*URL. Para acessarmos os valores que temos na tabela, temos a variável table
*ID = table-usuarios, que temos como referente a AJAX que trabalhamos
*recebe o objeto DataTable, que é todo conteúdo que existe na tabela que
*o JS está criando.*/
.concat('id="dp_').concat(id).concat('"', ' ')
.concat(
'role="button" title="Editar" data-toggle="tooltip" data-placement="right">', ' ')
.concat('<i class="fas fa-edit"></i></a>');
},
orderable : false
}
]
});
/*Criação do código para com o click em algum dos botões da
*coluna dados pessoais. Para que reconhecemos que houve o
*click em um daqueles botões vamos trabalhar com JQUERY.
*Nosso filtro é qualquer botão que tenha ID que inicie com
*dp_*/
$('#table-usuarios tbody').on('click', '[id*="dp_"]',function()
{ /*data = nossa lista de colunas*/
var data = table.row($(this).parents('tr')).data();
var aux = new Array();
$.each(data.perfis, function(index, value)
{aux.push(value.id);});
document.location.href = '/u/editar/dados/usuario/' +
data.id + '/perfis/' + aux;
});
});
$('.pass').keyup(function()
{ $('#senha1').val() === $('#senha2').val() ?
$('#senha3').removeAttr('readonly') :
$('#senha3').attr('readonly', 'readonly');
});<file_sep>package br.com.erudio.restwithspringbootudemy.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.erudio.restwithspringbootudemy.model.Person;
/*Só com essa estrutura já nos permite fazer algumas
*operações como salvar, delete e findAll*/
@Repository
public interface PersonRepository extends
JpaRepository<Person, Long> {}
<file_sep>package com.mballem.curso.security.service;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mballem.curso.security.datatables.Datatables;
import com.mballem.curso.security.datatables.DatatablesColunas;
import com.mballem.curso.security.domain.Agendamento;
import com.mballem.curso.security.domain.Horario;
import com.mballem.curso.security.exception.AccessDeniedException;
import com.mballem.curso.security.repository.AgendamentoRepository;
import com.mballem.curso.security.repository.projecoes.HistoricoPaciente;
@Service
public class AgendamentoService
{ @Autowired private AgendamentoRepository agendamentoRepository;
@Autowired Datatables datatables;
@Transactional(readOnly=true)
public List<Horario> buscarHorariosDisponiveisPorMedico(Long id, LocalDate date)
{return this.agendamentoRepository.buscarAgendamentoMedico(id, date);}
@Transactional(readOnly=false)
public void salvar(Agendamento agendamento)
{this.agendamentoRepository.save(agendamento);}
/*Toda vez que um retorno vai para um datatable, devemos
*retornar um tipo Map*/
@Transactional(readOnly=true)
public Map<String, Object> buscarHistoricoPorPacienteEmail(String email,
HttpServletRequest request)
{ this.datatables.setRequest(request);
this.datatables.setColunas(DatatablesColunas.AGENDAMENTOS);
Page<HistoricoPaciente> page = this.agendamentoRepository.findHistoricoByPacienteEmail(
email, this.datatables.getPageable());
return this.datatables.getResponse(page);
}
@Transactional(readOnly=true)
public Map<String, Object> buscarHistoricoPorMedicoEmail(String email,
HttpServletRequest request)
{ this.datatables.setRequest(request);
this.datatables.setColunas(DatatablesColunas.AGENDAMENTOS);
Page<HistoricoPaciente> page = this.agendamentoRepository.findHistoricoByMedicoEmail(email,
this.datatables.getPageable());
return this.datatables.getResponse(page);
}
@Transactional(readOnly=true)
public Agendamento buscarAgendamentoPorId(Long id)
{return this.agendamentoRepository.findById(id).get();}
/*O paciente é o unico objeto que não será alterado em toda
*operação, portanto, não precisamos fazer nenhum SET para
*paciente.*/
@Transactional(readOnly=false)
public void editar(Agendamento agendamento, String username)
{ Agendamento ag = this.buscarAgendamentoPorId(agendamento.getId());
ag.setDataConsulta(agendamento.getDataConsulta());
ag.setEspecialidade(agendamento.getEspecialidade());
ag.setHorario(agendamento.getHorario());
ag.setMedico(agendamento.getMedico());
}
@Transactional(readOnly=true)
public Agendamento buscarAgendamentoPorIdAndUser(Long id, String email)
{ return this.agendamentoRepository.findByIdAndUserName(id, email)
.orElseThrow(() -> new AccessDeniedException("Acesso negado! " + email));
}
@Transactional(readOnly=false)
public void delete(Long id) {this.agendamentoRepository.deleteById(id);}
}<file_sep>package br.com.erudio.restwithspringboot.converter;
import java.util.Date;
import org.springframework.stereotype.Service;
import br.com.erudio.restwithspringboot.data.vo.v2.PersonVOV2;
import br.com.erudio.restwithspringboot.model.Person;
@Service
public class PersonConverter
{ public PersonVOV2 convertEntityToVO(Person person)
{ PersonVOV2 vo = new PersonVOV2();
vo.setId(person.getId());
vo.setAdress(person.getAdress());
vo.setFirstName(person.getFirstName());
vo.setLastName(person.getLastName());
vo.setGender(person.getGender());
vo.setBirthday(new Date());
return vo;
}
public Person convertVOToEntity(PersonVOV2 person)
{ Person entity = new Person();
entity.setId(person.getId());
entity.setAdress(person.getAdress());
entity.setFirstName(person.getFirstName());
entity.setLastName(person.getLastName());
entity.setGender(person.getGender());
return entity;
}
}<file_sep>package br.com.edu.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.CrudRepository;
import br.com.edu.domain.Client;
public interface IClientRepository extends MongoRepository<Client, String> {
}<file_sep>package com.edu.exemplo.boot.service;
import java.util.List;
import com.edu.exemplo.boot.domain.Cargo;
import com.edu.exemplo.boot.domain.Departamento;
public interface IDepartamentoService
{ public void salvar(Departamento departamento);
public void editar(Departamento departamento);
public void excluir(Long id);
public Departamento buscarPorId(Long id);
public List<Departamento> listarTodos();
public boolean temCargo(Long id);
}<file_sep>package br.com.erudio.restwithspringbootudemy.service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.erudio.restwithspringbootudemy.exception.ResourceNotFoundException;
import br.com.erudio.restwithspringbootudemy.model.Person;
import br.com.erudio.restwithspringbootudemy.repository.PersonRepository;
/*Service para simular um ID de um BD. Todos os métodos
*novos são do spring data padrão*/
@Service
public class PersonService
{ @Autowired PersonRepository personRepository;
public Person create(Person person)
{return this.personRepository.save(person);}
public Person update(Person person)
{ /*Busca pela entidade pelo ID, que não deve
ser alterado, para depois alterar o resto.*/
Person entity = this.personRepository.findById(
person.getId()).orElseThrow(() -> new
ResourceNotFoundException(
"No records found for this ID"));
/*Os outros parametros podemos alterar*/
entity.setFirstName(person.getFirstName());
entity.setLastName(person.getLastName());
entity.setAdress(person.getAdress());
entity.setGender(person.getGender());
return this.personRepository.save(entity);
}
public void delete(Long id)
{ Person person = this.personRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(
"No records found for this ID"));
if(person != null) this.personRepository.delete(person);
}
public Person findById(Long id)
{ return this.personRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(
"No records found for this ID"));
}
public List<Person> findAll()
{return this.personRepository.findAll();}
}<file_sep>package br.edu.fatec.topicos.domain;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PastOrPresent;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
@SuppressWarnings("serial")//ignora a necessidade da variável serial.
@MappedSuperclass //para dizer ao JPA que esta é uma superclasse das entidades que iremos implementar
public abstract class Person
{ @Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@NotBlank(message = "Name is necessary!")
@Column(nullable=false)
private String name;
@NotBlank(message = "CPF is necessary!")
@Column(nullable=false)
private String cpf;
@NotNull
@DateTimeFormat(iso = ISO.DATE)
@Column(nullable = false, columnDefinition = "DATE")
private LocalDate bdate;
@NotBlank(message = "Email is necessary!")
@Column(nullable=false)
private String email;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "adr_id")//chave estrangeira
private Adress adress;
}<file_sep>package com.edu.exemplo.boot.domain;
import javax.persistence.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@SuppressWarnings("serial")
@Entity
@Table(name = "endereco")
public class Endereco extends AbstractEntity<Long>
{ @NotBlank
@Size(min=3, max=255)
@Column(name = "logradouro", nullable = false)
private String logradouro;
@NotBlank
@Size(min=3, max=255)
@Column(name = "bairro", nullable = false)
private String bairro;
@NotBlank
@Size(min=3, max=255)
@Column(name = "cidade", length = 500, nullable = false)
private String cidade;
@NotNull(message="{NotNull.endereco.uf}")
@Column(name="uf", nullable = false, length = 2)
@Enumerated(EnumType.STRING)//esta anotação informa ao JPA qual é o tipo de dado que queremos que salve no BD
private UF uf;
@NotBlank
@Size(min=9, max=9, message="{Size.endereco.cep}")
@Column(name = "cep", length = 9, nullable = false)
private String cep;
//se for inserido um digito de tipo alfabetico, então esta notação irá
//invalidar o campo numero
@NotNull(message="{NotNull.endereco.numero}")
@Digits(integer=5, fraction=0)
@Column(name = "numero", length = 5, nullable = false)
private Integer numero;
@Column(name = "complemento", length = 500, nullable = true)
private String complemento;
public String getLogradouro() {return logradouro;}
public void setLogradouro(String logradouro) {this.logradouro = logradouro;}
public String getBairro() {return bairro;}
public void setBairro(String bairro) {this.bairro = bairro;}
public String getCidade() {return cidade;}
public void setCidade(String cidade) {this.cidade = cidade;}
public UF getUf() {return uf;}
public void setUf(UF uf) {this.uf = uf;}
public String getCep() {return cep;}
public void setCep(String cep) {this.cep = cep;}
public Integer getNumero() {return numero;}
public void setNumero(Integer numero) {this.numero = numero;}
public String getComplemento() {return complemento;}
public void setComplemento(String complemento) {this.complemento = complemento;}
}<file_sep>package br.edu.fatec2020.topicos.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import br.edu.fatec2020.topicos.domain.Produto;
import br.edu.fatec2020.topicos.repository.ProdutoRepository;
import lombok.AllArgsConstructor;
@Controller
@RequestMapping("/produtos")
@AllArgsConstructor
public class ProductController
{ private final ProdutoRepository repository;
@GetMapping //isso serve para quando queremos editar um produto
public ModelAndView listar(@ModelAttribute("produtoEditavel") Produto produto)
{ ModelAndView model = new ModelAndView("produtos");
model.addObject("produtos", this.repository.findAll());
return model;
}
@PostMapping("/inserir")
public ModelAndView salvar(Produto produto)
{ this.repository.save(produto);
return new ModelAndView("sucesso");
}
@GetMapping("/excluir")
public ModelAndView excluir(@RequestParam("id") Long id)
{ this.repository.deleteById(id);
return new ModelAndView("sucesso");
}
@GetMapping("preAlteracao") //isso serve para quando queremos editar um produto
public ModelAndView preAlteracao(@RequestParam("id") Long id)
{ Optional<Produto> optional = this.repository.findById(id);//tratamento para caso possa retornar um valor nulo
if(optional.isPresent())
{ ModelAndView model = new ModelAndView("produtos");
model.addObject("produtos", this.repository.findAll());
//o método get() só funciona caso optional for encotrado
model.addObject("produtoEditavel", optional.get());
return model;
}
else return new ModelAndView("fracasso");
}
//finalmente o metodo alterar
@PostMapping("/alterar")
public ModelAndView alterar(Produto produto)
{ this.repository.save(produto); //no JPA geralmente o metodo "save" faz as dias coisas
return new ModelAndView("sucesso");
}
}<file_sep>//JQuery para submit do formulário para o controller. O método submit vai
//simular o botão de submit que teríamos em uma página HTML, que fosse fazer
//uma requisição normal, ou seja sem uso de AJAX. O parâmetro "e" é um apelido
//para qualquer evento, que será usado pois iremos trabalhar com o método que
//inibe o comportamento padrão do submit
$("#form-add-promo").submit(function(e)
{ //este método de evento evita que o evento padrão do submit seja executado.
//pois quando temos um submit, o navegador por padrão vai fazer uma requisição
//ao lado do servidor da aplicação, e essa requisição vai gerar também um refresh
//no navegador. Se não colocarmos este método, será gerado um refresh assim que
//a requisição de submit for realizado.
e.preventDefault();
//variável que irá representar o objeto de promoção, que será inicializada com
//duas chaves. Essa inicialização fará com que o JS crie então um objeto do tipo
//promo.
var promocao = {};
//criando um atributo do objeto promocao
promocao.linkPromocao = $("#linkPromocao").val();
promocao.descricao = $("#descricao").val();
promocao.preco = $("#preco").val();
promocao.titulo = $("#titulo").val();
promocao.categoria = $("#categoria").val();
promocao.linkImagem = $("#linkImagem").attr("src");
promocao.site = $("#site").text();
//add um console.log
console.log("promo > ", promocao);
$.ajax({
method: "POST",
url: "/promocao/save",//URL que deve ser criada na controller
data: promocao,
beforeSend: function()//método que esconde algo que contém na página antes de
{ //removendo as mensagens, o parâmetro error-span é a classe que tem declarada no span,
//e o metodo remove() irá remover tudo que contém na tag que contém a classe error-span
$("span").closest('.error-span').remove();
//removendo as bordas vermelhas nas bordas dos campos
$("#caterogia").removeClass("is-invalid");
$("#preco").removeClass("is-invalid");
$("#linkPromocao").removeClass("is-invalid");
$("#titulo").removeClass("is-invalid");
//habilita o load
$("#form-add-promo").hide();//executar a requisição.
//o método show() é o oposto ao hide
$("#loader-form").addClass("loader").show();
},
success: function() //método each() para fazer a limpeza dos campos do form após realizar o cadastro, como se fosse um objeto de tipo formulário
{ $("#form-add-promo").each(function() {this.reset();});
$("#linkImagem").attr("src", "/images/promo-dark.png");
$("#site").text("");
//primeiramente, mesmo que não tenha o alerta de erro, vai ser feita tentativa de retirada desta
$("#alert").removeClass("alert alert-danger").addClass("alert alert-success").text("Promoçao cadastrada!");
},
statusCode:
{ //códigos dos retornos de validação
422: function(xhr)//parâmetro importante para pegar o valor das msgs de erro
{ console.log('status error:', xhr.status);//este último parâmetro vai servir para mostrar o código de erro do console
var errors = $.parseJSON(xhr.responseText);
//método each em JQuery para um looping de uma lista
//o parâmetro key é a chave do map e val é o valor
$.each(errors, function(key, val)
{ //usando recursos do JQuery para achar os ID dos campos
//a classe do bootstrap chamada is-invalid responsavel por colocar
//a borda vermelha no campo que tiver um valor inválido ou vazio
$("#" + key).addClass("is-invalid");
//inclui a classe que faz com que a mensagem de erro tenha cor vermelha.
//o método append é que insere a mensagem
$("#error-" + key).addClass("invalid-feedback").append("<span class='error-span'>" +
val +"</span>");
});
}
},
error: function(xhr)//o parâmetro xhr nos trará uma mensagem referente ao erro que possa ocorrer durante a requisição.
{ //o responseText será o método que vai nos exibir a mensagem referente ao erro.
console.log("> error: ", xhr.responseText);//mais informações, visite a página de JQuery
$("#alert").addClass("alert alert-danger").text("Não foi possível realizar o cadastro");
},
complete: function()//método semelhante ao hide, porém esconde o que ja tem na página de forma gradual, como uma transição suave
{ $("#loader-form").fadeOut(800, function()
{ $("#form-add-promo").fadeIn(250);//traz de volta tudo que o fadeOut escondeu
$("#loader-form").removeClass("loader");
});
}
});
});
//função para capturar as metatags.
//essa instrução indica que queremos acessar o componente da página HTML que possui o ID linkPromocao
$('#linkPromocao').on('change', function()
{ var url = $(this).val();//recurso do JQuery para recuperar o valor do campo de input com id="linkPromocao"
//pois toda URL vai ter pelo menos o http:// (ou seja, 7 caracteres)
if(url.length > 7)
{ $.ajax(//lembrando que inserimos na controller uma requisição do tipo POST
{ method:"POST",
url:"/meta/info?url=" + url,
cache:false,//este recurso impede que os dados sejam armazenados em cache
beforeSend://aqui será realizado a limpeza dos campos de entrada de dados antes de enviar a requisição
function()//abaixo, remove a mensagem de erro
{ $("#alert").removeClass("alert alert-danger alert-success").text("");
//deixo o campo de titulo, site e imagem vazias
$("#titulo").val("");
$("#site").text("");
$("#linkImagem").attr("src", "");
//inserção do loading
$("#loader-img").addClass("loader");
},
success:
function(data)//data é um parâmetro que recebem o resultado da operação
{ console.log(data);//isso será enviado os resultado da operação no log do navegador
//no campo em que o id="titulo" será inserido o resultado da requisição "data"
//com a informação titulo
$("#titulo").val(data.title);
//campo que não é <input>, por isso será usado o método text()
//o metodo replace serviu para retirar o "@" abaixo da imagem
$("#site").text(data.site.replace("@", ""));
//o parâmetro src que será o atributo que iremos acessar
$("#linkImagem").attr("src", data.image);
},
statusCode:
{ 404: function()//método do bootstrap 4 que insere uma classe que deixa o alert em vermelho
{ $("#alert").addClass("alert alert-danger").text(
"Nenhuma informação pode ser recuperada dessa URL.");
//a imagem padrão somente irá aparecer após o carregamento completo e caso aconteça um erro
$("#linkImagem").attr("src", "/images/promo-dark.png");
}
},
error: function()
{ $("#alert").addClass("alert alert-danger").text(
"Ops... algo deu errado, tente mais tarde");
},
complete: function()
{ //assim que a imagem aparecer, remove o loading
$("#loader-img").removeClass("loader");
}
});
}
});<file_sep>package br.com.edu.serviceImp;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.edu.domain.Client;
import br.com.edu.repository.IClientRepository;
import br.com.edu.service.IService;
//para que o Spring identifique é um serviço e para que seja add em outras aplicações
@Service
public class ClientService implements IService
{ @Autowired
private IClientRepository cr; /*cria se automaticamente uma instancia não
nula de cliente repositório*/
@Override
public List<Client> listAll() {return this.cr.findAll();}
@Override
public Client searchClientID(String id)
{return this.cr.findOne(id);}
@Override
public Client save(Client client) {return this.cr.save(client);}
/*o método update é usado o mesmo método de salvar, com a diferença
de que, se o objeto já tiver ID, será feito o atualizar. Caso contrário,
irá identificar que é um objeto novo e será feito um cadastrar*/
@Override
public Client update(Client client) {return this.cr.save(client);}
@Override
public void delete(String id) {this.cr.delete(id);}
}<file_sep>package com.mballem.curso.security;
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.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.mballem.curso.security.service.EmailService;
/*Implementando metodo para testar o envio de e-mail*/
@SpringBootApplication
public class DemoSecurityApplication// implements CommandLineRunner
{ public static void main(String[] args)
{ //System.out.println(new BCryptPasswordEncoder().encode("SENHA"));
SpringApplication.run(DemoSecurityApplication.class, args);
}
//
// @Autowired private EmailService service;
//
// @Override public void run(String... args) throws Exception
// {this.service.enviarPedidoConfirmacaoCadastro("<EMAIL>", "1234");}
/*Injetando o JavaMailSender*/
//@Autowired private JavaMailSender sender;
/*inserindo nosso teste*/
// @Override public void run(String... args) throws Exception
// { SimpleMailMessage mailMsg = new SimpleMailMessage();
// //Seta para quem iremos enviar o e-mail
// mailMsg.setTo("<EMAIL>");
// mailMsg.setText("Teste, favor ignorar");
// mailMsg.setSubject("Teste");
// sender.send(mailMsg);
// }
}
|
62b1683a090a178dc3ae46abe6a32edc150c4471
|
[
"JavaScript",
"Java",
"INI"
] | 46
|
Java
|
eduardowmu/SpringProjects
|
0bb5e8d5d5802517bed2c21ca08ba54a56d8cf0b
|
f71bd0a555c541a9baffec7fbf014fe3cb71fba4
|
refs/heads/master
|
<file_sep>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
*
*
* @type {string}
*/
var courseGenerator = {
/**
* Flickr URL that will give us lots and lots of whatever we're looking for.
*
* See https://api.mongolab.com/api/1/databases/edupal/collections/syllabus?q={%22catalogId%22:%22ECON311%22}&apiKey=<KEY> for
* details about the construction of this URL.
*
* @type {string}
* @private
*/
searchOnMongo_: 'https://api.mongolab.com/api/1/databases/edupal/collections/syllabus?' +
'q={%22catalogId%22:%22ECON311%22}&' +
'apiKey=<KEY>',
/**
* Sends an XHR GET request to grab exams. The
* XHR's 'onload' event is hooks up to the 'showDuedates_' method.
*
* @public
*/
requestExam: function() {
var req = new XMLHttpRequest();
req.open("GET", this.searchOnMongo_, true);
req.onload = this.showDuedates_.bind(this);
req.send(null); },
/**
* Handle the 'onload' event of our kitten XHR request, generated in
* 'requestKittens', by generating 'img' elements, and stuffing them into
* the document for display.
*
* @param {ProgressEvent} e The XHR ProgressEvent.
* @private
*/
showDuedates_: function (e) {
var exams = e.exam;
for (var i = 0; i < exam.length; i++) {
var header = document.createElement('h1');
header.innerHTML = exams [i].name;
document.body.appendChild(header);
}
},
/**
* Given a photo, construct a URL using the method outlined at
* http://www.flickr.com/services/api/misc.urlKittenl
*
* @param {DOMElement} A kitten.
* @return {string} The kitten's URL.
* @private
*/
/*constructKittenURL_: function (photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
};*/
// Run our kitten generation script as soon as the document's DOM is ready.
document.addEventListener('DOMContentLoaded', function () {
courseGenerator.requestExam();
});
|
4d5a19edea8147d03592961d8b545c35ee15bdaa
|
[
"JavaScript"
] | 1
|
JavaScript
|
kaisrab/Helloworld
|
7e81db6d13bddb4b2acecb679a1738cab39fbe05
|
d9f5870550ea9c8a25739cf4380fb9217c529302
|
refs/heads/master
|
<file_sep>angular.module('pedidos')
.service('AuthenticationService',function (Base64, $http, $cookieStore, $rootScope, $timeout, $cordovaSQLite, sessao,NPedido) {
var service = {};
service.Login = function (username, password, callback) {
var response = {};
var query = "SELECT * FROM admc05 WHERE usuario='"+username+"' AND senha='"+password+"'";
$cordovaSQLite.execute(db, query, []).then(function(res) {
if(res.rows.length > 0) {
for(var i = 0; i < res.rows.length; i++) {
sessao.setData("sess_empresa",Number(res.rows.item(i).cd_empresa));
sessao.setData("sess_filial",Number(res.rows.item(i).cd_filial));
}
response.success = true;
}else{
response.success = false;
response.message = 'Usuario e senha incorreto / Necessario ter importado o banco de dados';
}
callback(response);
}, function (err) {
response.success = false;
response.message = 'Necessario ter importado o banco de dados';
console.error(err);
callback(response);
});
};
service.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
//$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
};
service.ClearCredentials = function () {
$rootScope.globals = {};
$cookieStore.remove('globals');
//$http.defaults.headers.common.Authorization = 'Basic ';
};
return service;
}).service('VerificaDados',function (Base64, $http, $cookieStore, $rootScope, $timeout, $cordovaSQLite, sessao) {
var service = {};
service.Itens = function (nrpedido, iten,posicao,dados, callback) {
var response = {};
var query = "SELECT * FROM fatm008 WHERE nr_pedido = ? AND cd_iten = ? ";
$cordovaSQLite.execute(db, query, [nrpedido,iten]).then(function(res) {
if(res.rows.length > 0) {
response.success = true;
}else{
response.success = false;
}
response.posicao = posicao;
response.dados = dados;
callback(response);
}, function (err) {
response.success = false;
console.error(err);
callback(response);
});
};
service.Vencimentos = function (nrpedido, venc,posicao,dados, callback) {
var response = {};
var query = "SELECT * FROM fatm010 WHERE nr_pedido = ? AND seq = ?";
$cordovaSQLite.execute(db, query, [nrpedido,venc]).then(function(res) {
if(res.rows.length > 0) {
response.success = true;
}else{
response.success = false;
}
response.posicao = posicao;
response.dados = dados;
callback(response);
}, function (err) {
response.success = false;
console.error(err);
callback(response);
});
};
return service;
}).service('Base64', function () {
/* jshint ignore:start */
var keyStr = '<KEY>';
return {
encode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
},
decode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
window.alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
};
/* jshint ignore:end */
}).service('Banco', function ($cordovaSQLite) {
/* jshint ignore:start */
return {
fatc008: function (id) {
var output = [];
var query_itens = "SELECT * FROM fatm008 WHERE nr_pedido = ?";
$cordovaSQLite.execute(db, query_itens, [id]).then(function(res_itens) {
if(res_itens.rows.length > 0) {
for(var b = 0; b < res_itens.rows.length; b++) {
var val_un = res_itens.rows.item(b).vlr_unitario;
output.push({id:(b+1),id_iten: res_itens.rows.item(b).cd_iten,un:res_itens.rows.item(b).un,cantidad:res_itens.rows.item(b).qtd,val_un:val_un, text: unescape(res_itens.rows.item(b).descricao), total:res_itens.rows.item(b).vlr_bruto, custo: res_itens.rows.item(b).custo,lucro:res_itens.rows.item(b).lucro,preco_venda:res_itens.rows.item(b).preco_venda,lucroCent:res_itens.rows.item(b).lucroCent, checked: false, icon: null});
}
}
}, function (err) {
console.error(err);
});
return output;
},
fatm010: function (id) {
var output = [];
var query_vencimentos = "SELECT * FROM fatm010 WHERE nr_pedido = ?";
$cordovaSQLite.execute(db, query_vencimentos, [id]).then(function(res_vencimentos) {
if(res_vencimentos.rows.length > 0) {
for(var c = 0; c < res_vencimentos.rows.length; c++) {
output.push({id:(c+1),cuotas:res_vencimentos.rows.length,data:new Date(res_vencimentos.rows.item(c).data_vcto),entrada:(res_vencimentos.rows.item(c).cd_entrada=="si"?res_vencimentos.rows.item(c).cd_entrada:"no"), valor:res_vencimentos.rows.item(c).vlr_vcto,prazo:res_vencimentos.rows.item(c).prazo});
}
}
}, function (err) {
console.error(err);
});
return output;
}
};
/* jshint ignore:end */
});<file_sep>angular.module('pedidos')
.filter('comma2decimal', [
function() { // should be altered to suit your needs
return function(input) {
var ret = input.toString();
if(input.toString().indexOf('.') !==1){
var ret = input.toString().replace(/\./g,'');
}
ret = ret.replace(',', '.');
return ret;
};
}]);<file_sep>angular.module('pedidos')
.directive('isNumber',function(){
return {
restrict:'AE',
require:'ngModel',
link:function($scope,elem,attrs,ngModel){
ngModel.$validators.npedido=function(modelValue,viewValue){
var value=modelValue || viewValue;
return /^[0-9]+$/.test(value);
}
}
}
}).directive('fancySelect', ['$ionicModal','$timeout','$window',function($ionicModal, $timeout, $window) {
return {
/* Only use as <fancy-select> tag */
restrict : 'E',
/* Our template */
templateUrl: 'templates/fancy-select.html',
/* Attributes to set */
scope: {
'items' : '=', /* Items list is mandatory */
'text' : '=', /* Displayed text is mandatory */
'value' : '=', /* Selected value binding is mandatory */
'callback' : '&',
'carrega' : '&',
'buscando' : '=',
},
link: function (scope, element, attrs) {
/* Default values */
scope.multiSelect = attrs.multiSelect === 'true' ? true : false;
scope.allowEmpty = attrs.allowEmpty === 'false' ? false : true;
/* Header used in ion-header-bar */
scope.headerText = attrs.headerText || '';
/* Text displayed on label */
// scope.text = attrs.text || '';
scope.defaultText = scope.text || '';
/* Notes in the right side of the label */
scope.noteText = attrs.noteText || '';
scope.noteImg = attrs.noteImg || '';
scope.noteImgClass = attrs.noteImgClass || '';
/* Optionnal callback function */
// scope.callback = attrs.callback || null;
/* Instanciate ionic modal view and set params */
/* Some additionnal notes here :
*
* In previous version of the directive,
* we were using attrs.parentSelector
* to open the modal box within a selector.
*
* This is handy in particular when opening
* the "fancy select" from the right pane of
* a side view.
*
* But the problem is that I had to edit ionic.bundle.js
* and the modal component each time ionic team
* make an update of the FW.
*
* Also, seems that animations do not work
* anymore.
*
*/
$ionicModal.fromTemplateUrl(
'templates/fancy-select-items.html',
{'scope': scope,
}
).then(function(modal) {
scope.modal = modal;
});
/* Validate selection from header bar */
scope.validate = function (event) {
// Construct selected values and selected text
if (scope.multiSelect == true) {
// Clear values
scope.value = '';
scope.text = '';
// Loop on items
jQuery.each(scope.items, function (index, item) {
if (item.checked) {
scope.value = scope.value + item.id+';';
scope.text = scope.text + item.text+', ';
}
});
// Remove trailing comma
scope.value = scope.value.substr(0,scope.value.length - 1);
scope.text = scope.text.substr(0,scope.text.length - 2);
}
// Select first value if not nullable
if (typeof scope.value == 'undefined' || scope.value == '' || scope.value == null ) {
if (scope.allowEmpty == false) {
scope.value = scope.items[0].id;
scope.text = scope.items[0].text;
// Check for multi select
scope.items[0].checked = true;
} else {
scope.text = scope.defaultText;
}
}
// Hide modal
scope.hideItems();
// Execute callback function
if (typeof scope.callback == 'function') {
scope.callback (scope.value);
}
}
/* Show list */
scope.showItems = function (event) {
event.preventDefault();
scope.modal.show();
scope.visivel = true;
}
/* Hide list */
scope.hideItems = function () {
scope.modal.hide();
scope.visivel = false;
if(scope.items.length > 20) {
scope.items.length = 20;
}
}
scope.loadMore = function() {
$timeout(function() {
if (typeof scope.carrega == 'function') {
scope.carrega();
}
scope.$broadcast('scroll.infiniteScrollReady');
scope.$broadcast('scroll.infiniteScrollComplete');
scope.$broadcast('scroll.resize');
scope.$broadcast('rebuild:me');
}, 500);
}
/* Destroy modal */
scope.$on('$destroy', function() {
scope.modal.remove();
if(scope.items.length > 20) {
scope.items.length = 20;
}
});
scope.$on('modal.hidden', function() {
if(scope.items.length > 20) {
scope.items.length = 20;
}
scope.$broadcast('scroll.resize');
scope.$broadcast('rebuild:me');
});
scope.buscar = function(search){
if(typeof scope.buscando !== "undefined"){
scope.buscando = search;
}
};
/* Validate single with data */
scope.validateSingle = function (item) {
// Set selected text
scope.text = item.text;
// Set selected value
scope.value = item.id;
// Hide items
scope.hideItems();
// Execute callback function
if (typeof scope.callback == 'function') {
scope.callback (scope.value);
}
}
}
};
}]
).directive('listarProduto', ['$ionicModal','$timeout','$window','$location',function($ionicModal, $timeout, $window, $location) {
return {
/* Only use as <fancy-select> tag */
restrict : 'E',
/* Our template */
templateUrl: 'templates/listar-produto.html',
/* Attributes to set */
scope: {
'items' : '=', /* Items list is mandatory */
'value' : '=', /* Selected value binding is mandatory */
'callback' : '&',
'carrega' : '&',
'total' : '=',
'buscando' : '=',
'deletar' : '='
},
link: function (scope, element, attrs) {
/* Default values */
/* Header used in ion-header-bar */
scope.headerText = attrs.headerText || '';
$ionicModal.fromTemplateUrl(
'templates/fancy-select-items.html',
{'scope': scope}
).then(function(modal) {
scope.modal = modal;
});
/* Validate selection from header bar */
scope.validate = function (event) {
// Select first value if not nullable
if (typeof scope.value == 'undefined' || scope.value == '' || scope.value == null || scope.value == null ) {
if (scope.allowEmpty == false) {
scope.existe = false;
angular.forEach(scope.value, function(value, key) {
if(value.id_iten == items[0].id){
scope.existe = true;
}
});
if(scope.existe == false){
scope.value.push({
id: scope.value.length + 1,
id_iten:scope.items[0].id,
un:scope.items[0].un,
cantidad:1,
val_un:scope.items[0].val_un,
text: scope.items[0].text,
total: scope.items[0].total,
custo: scope.items[0].custo,
lucro: scope.items[0].lucro,
preco_venda:scope.items[0].val_un,
lucroCent:scope.items[0].lucroCent
});
}else{
alert("Este item ja foi selecionado");
return;
}
$location.path("/pedidos/inserir/mostrar/"+scope.items[0].id);
} else {
scope.text = scope.defaultText;
alert("Selecione um item valido");
return;
}
}
// Hide modal
scope.hideItems();
// Execute callback function
if (typeof scope.callback == 'function') {
scope.callback (scope.value);
}
}
scope.buscar = function(search){
if(typeof scope.buscando !== "undefined"){
scope.buscando = search;
}
};
/* Show list */
scope.showItems = function (event) {
event.preventDefault();
scope.modal.show();
scope.visivel = true;
}
/* Hide list */
scope.hideItems = function () {
scope.modal.hide();
scope.visivel = false;
if(scope.items.length > 20) {
scope.items.length = 20;
}
}
scope.loadMore = function() {
$timeout(function() {
if (typeof scope.carrega == 'function') {
scope.carrega();
}
scope.$broadcast('scroll.infiniteScrollReady');
scope.$broadcast('scroll.infiniteScrollComplete');
scope.$broadcast('scroll.resize');
scope.$broadcast('rebuild:me');
}, 500);
}
/* Destroy modal */
scope.$on('$destroy', function() {
scope.modal.remove();
if(scope.items.length > 20) {
scope.items.length = 20;
}
});
scope.$on('modal.hidden', function() {
if(scope.items.length > 20) {
scope.items.length = 20;
}
scope.$broadcast('scroll.resize');
scope.$broadcast('rebuild:me');
});
scope.delete = function ( prod ) {
var index = scope.value.indexOf(prod);
scope.deletar.push({produto:prod.id_iten});
scope.total = scope.total - prod.total;
scope.value.splice(index, 1);
};
scope.abrir = function (prod) {
$location.path("/pedidos/inserir/mostrar/"+prod);
};
scope.$watchCollection("scope.value", function(newValue, oldValue) {
scope.total = 0;
angular.forEach(scope.value, function(value, key) {
scope.total = Number(scope.total) + Number(value.total);
});
});
/* Validate single with data */
scope.validateSingle = function (item) {
scope.existe = false;
angular.forEach(scope.value, function(value, key) {
if(value.id_iten == item.id){
scope.existe = true;
}
});
if(scope.existe == false){
scope.value.push({
id: scope.value.length + 1,
id_iten:item.id,
un:item.un,
cantidad:1,
val_un:item.val_un,
text: item.text,
total: item.total,
custo: item.custo,
lucro: item.lucro,
preco_venda:item.val_un,
lucroCent:item.lucroCent
});
$location.path("/pedidos/inserir/mostrar/"+item.id);
scope.hideItems();
}else{
alert("Este item ja foi selecionado");
}
// Hide items
// Execute callback function
if (typeof scope.callback == 'function') {
scope.callback (scope.value);
}
}
}
};
}
]
).directive('eatClickIf', ['$parse', '$rootScope',
function($parse, $rootScope) {
return {
// this ensure eatClickIf be compiled before ngClick
priority: 100,
restrict: 'A',
compile: function($element, attr) {
var fn = $parse(attr.eatClickIf);
return {
pre: function link(scope, element) {
var eventName = 'click';
element.on(eventName, function(event) {
var callback = function() {
if (fn(scope, {$event: event})) {
// prevents ng-click to be executed
event.stopImmediatePropagation();
// prevents href
event.preventDefault();
return false;
}
};
if ($rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
},
post: function() {}
}
}
}
}
]);<file_sep>angular.module('pedidos')
.controller('HomeCtrl', function($scope,$state,$rootScope) {
});<file_sep>angular.module('pedidos')
.controller('MostraCtrl', function($scope,$state,$rootScope,$window,$timeout,$ionicPlatform,sessao,$stateParams,$location,$cordovaSQLite,$filter,$ionicLoading) {
$scope.formData.totalitens = {};
if($scope.formData.produtos.length == 0){
$scope.testando = 0;
}else{
for(var i = 0; i < $scope.formData.produtos.length; i++) {
if($scope.formData.produtos[i].id_iten == $stateParams.id_iten){
$scope.testando = i;
}
}
$ionicLoading.show({ template: 'Cargando Iten.<br><ion-spinner></ion-spinner>' });
var dataa = $filter('date')($scope.formData.dataprecio,'yyyy-MM-dd');
console.log(dataa);
var query = "SELECT * FROM fatc001 WHERE cd_iten = ? AND cd_empresa = ? AND DATE(data_mvto) < DATE(?) ORDER BY data_mvto desc";
$cordovaSQLite.execute(db, query, [$stateParams.id_iten,sessao.getData("sess_empresa"),dataa]).then(function(res) {
if(res.rows.length > 0) {
for(var i = 0; i < res.rows.length; i++) {
console.log(res.rows.item(i).preco_venda_menor);
var val_un = $filter('comma2decimal')(res.rows.item(i).preco_venda_menor);
var custo = $filter('comma2decimal')(res.rows.item(i).preco_custo);
if(!$scope.formData.produtos[$scope.testando].custo){
$scope.formData.produtos[$scope.testando].custo = custo;
}
if(!$scope.formData.produtos[$scope.testando].val_un){
$scope.formData.produtos[$scope.testando].val_un =val_un;
}
if(!$scope.formData.produtos[$scope.testando].total){
$scope.formData.produtos[$scope.testando].total = val_un;
}
}
}else{
var index = $scope.formData.produtos.indexOf($scope.formData.produtos[i]);
$scope.formData.produtos.splice(index, 1);
alert("Iten no tiene preco de venda, Escolha outro iten");
$state.go("^.itens");
}
$ionicLoading.hide();
}, function (err) {
console.error(err);
$ionicLoading.hide();
});
}
$scope.calcular = function(cantidad,val_un){
if(cantidad !="" && val_un !=""){
$scope.getTotalLucro();
$scope.formData.produtos[$scope.testando].total = cantidad * val_un;
var totalcusto = cantidad * $scope.formData.produtos[$scope.testando].custo;
if($scope.formData.produtos[$scope.testando].total > 0){
$scope.formData.produtos[$scope.testando].lucro = $scope.formData.produtos[$scope.testando].total - totalcusto;
$scope.formData.produtos[$scope.testando].lucroCent = (($scope.formData.produtos[$scope.testando].lucro / $scope.formData.produtos[$scope.testando].total) * 100);
}
}
};
$scope.cancelaritem = function(str){
if($scope.tipo == 'i'){
var index = $scope.formData.produtos.indexOf(str);
if(!typeof $scope.formData.total ==='undefined'){
$scope.formData.total = $scope.formData.total - str.total;
}
$scope.formData.produtos.splice(index, 1);
}else{
var query_itens = "SELECT * FROM fatm008 WHERE nr_pedido = ? AND cd_iten = ? ";
$cordovaSQLite.execute(db, query_itens, [$scope.formData.npedido,$stateParams.id_iten]).then(function(res) {
console.log("rows "+res.rows.length);
if(res.rows.length == 0) {
var index = $scope.formData.produtos.indexOf(str);
$scope.formData.total = $scope.formData.total - str.total;
$scope.formData.produtos.splice(index, 1);
}
console.log($scope.formData.produtos);
});
}
$state.go("^.itens");
};
$scope.salvaritem = function(str){
$ionicLoading.show({ template: 'Salvando Iten.<br><ion-spinner></ion-spinner>' });
$scope.calcular(str.cantidad,str.val_un);
$ionicLoading.hide();
$state.go("^.itens");
};
});<file_sep>// Ionic Starter App
var db;
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('pedidos', ['ionic','ngTouch','ui.router','ngAnimate','ngCordova','ngCookies','ngRoute','angular.filter','ui.utils.masks'])
.run(function($ionicPlatform,$location,$rootScope,$cookieStore,$http,$cookieStore,$state,LimpaPedidos) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleLightContent();
}
$location.path('/');
$rootScope.$apply();
});
$rootScope.globals = $cookieStore.get('globals') || {};
$rootScope.$on('$locationChangeStart', function (event, next, current, toParams, fromState, fromParams, toState) {
var restrictedPage = $.inArray($location.path(), ['/login', '/', '/config']) === -1;
if (restrictedPage && !$rootScope.globals.currentUser) {
$location.path('/');
}
if($location.path() == "/pedidos/inserir"){
$state.go("pedidos.inserir.dados");
}
});
})
.config(function($stateProvider, $urlRouterProvider,$ionicConfigProvider) {
$ionicConfigProvider.tabs.position("bottom"); //Places them at the bottom for all OS
$ionicConfigProvider.tabs.style("standard"); //Makes them all look the same across all OS
$stateProvider
.state('banco', {
url: "/",
templateUrl: "templates/banco.html",
controller:'BancoCtrl'
})
.state('login', {
url: "/login",
templateUrl: "templates/login.html",
controller:'LoginCtrl'
})
.state('config', {
url: '/config',
templateUrl: 'templates/config.html',
controller: 'ConfigCtrl'
})
.state('pedidos', {
url: '/pedidos',
abstract: true,
templateUrl: "templates/pedidos.html",
controller: 'PedidoCtrl'
})
.state('pedidos.home', {
url: '/home',
views: {
'pedidos-home': {
templateUrl: 'templates/home.html',
controller: 'HomeCtrl'
}
}
})
.state('pedidos.listar', {
url: '/listar',
views: {
'pedidos-listar': {
templateUrl: 'templates/listar-pedidos.html',
controller: 'ListarPedidosCtrl'
},
cache:false
}
})
.state('pedidos.inserir', {
url: '/inserir',
views: {
'pedidos-inserir': {
templateUrl: 'templates/form.html',
controller: 'InserirPedidosCtrl'
},
abstract: '.dados'
},
}).state('pedidos.inserir.dados', {
url: '/dados/:id',
templateUrl: 'templates/formDados.html'
}).state('pedidos.inserir.itens', {
url: '/itens',
templateUrl: 'templates/formItens.html'
}).state('pedidos.inserir.mostrar', {
url: "/mostrar/:id_iten",
controller: 'MostraCtrl',
templateUrl: "templates/mostraitems.html"
}).state('pedidos.inserir.vencimento', {
url: '/vencimento',
templateUrl: 'templates/formVencimento.html'
}).state('pedidos.inserir.lucro', {
url: '/lucro',
templateUrl: 'templates/formLucro.html'
});
$urlRouterProvider.otherwise('/login');
});<file_sep>
<button type="button" ng-hide="!formData.vencimento.length || formData.cuotas == 0" ng-click="tipo=='i'?SetPedido(formData):AlterarPedido(formData)" class="button button-block button-positive" >
{{tipo=='i'?"Inserir Pedido":"Alterar Pedido"}}
</button>
<ion-list class="list list-inset">
<div class="item item-input row">
<div class="col">
<span class="input-label"><b>Cuota</b></span>
<input type="number" name="cuotas" id="cuotas" placeholder="Cuotas de Vencimento" ng-model="formData.cuotas" required />
<small ng-show="form.datapedido.$error.required" class="error-message">* Este campo é obrigatorio</small>
</div>
<div class="col">
<label >
<span class="input-label"><b>Total Itens</b></span>
<p>{{formData.total}}</p>
</label>
</div>
<div class="col">
<label >
<span class="input-label"><b>Total Venc.</b></span>
<p >{{calcTotal()}}</p>
</label>
</div>
</div>
<button type="button" class="button button-block button-positive" ng-disabled="formData.cuotas == 0" ng-hide="formData.vencimento.length > 0" ng-click="cadVencimento(formData.cuotas)">
Confirmar
</button>
<ion-item class="item item-icon-left item-icon-right" ng-repeat="vencimento in formData.vencimento">
<i class="icon ion-edit" ng-click="abrir(vencimento)" ></i>
{{vencimento.id}} - {{vencimento.data | date:'dd/MM/yyyy'}} - Pra/ {{vencimento.prazo}} ({{vencimento.valor | number : 2}}) {{vencimento.entrada =="si"?' - Entrada':''}}
<i class="icon ion-trash-a" ng-click="tipo=='i'?delete(vencimento):deleteAlt(vencimento)" ></i>
</ion-item>
</ion-list>
<file_sep>angular.module('pedidos')
.controller('LoginCtrl', function($scope,$state,$rootScope,$ionicPopup,sessao,$location,$http,CarregaBanco,$cordovaSQLite,AuthenticationService,sessao,$timeout,$ionicLoading) {
var query = "SELECT * FROM configuracao";
$cordovaSQLite.execute(db, query, []).then(function(res) {
if(res.rows.length > 0) {
for(var i = 0; i < res.rows.length; i++) {
sessao.setData("sess_porta",Number(res.rows.item(i).porta));
sessao.setData("sess_caminho",res.rows.item(i).caminho);
sessao.setData("sess_diretorio",res.rows.item(i).diretorio);
sessao.setData("sess_npedido",Number(res.rows.item(i).npedido));
}
}
}, function (err) {
//console.error(err);
});
$scope.abreGestor = function(){
window.open('http://'+sessao.getData('sess_caminho')+':'+sessao.getData('sess_porta')
+'/gestorweb', '_system', 'location=yes');
return false;
}
$scope.login = function () {
$ionicLoading.show({ template: 'Carregando.<br><ion-spinner></ion-spinner>' });
AuthenticationService.ClearCredentials();
AuthenticationService.Login($scope.data.usuario, $scope.data.senha, function(response) {
if(response.success) {
AuthenticationService.SetCredentials($scope.data.usuario.toLowerCase(), $scope.data.senha);
$location.path('/pedidos/home');
} else {
$scope.error = response.message;
$timeout(function(){
$scope.error = '';
}, 10000);
}
$ionicLoading.hide();
});
};
$scope.data = {}
$scope.importar = function (){
var myPopup = $ionicPopup.show({
template: '<div class="list"><label class="item item-input"><input type="text" ng-model="data.login" name="login" id="login" placeholder="Usuario"></label><label class="item item-input"><input type="<PASSWORD>" id="pass" ng-model="data.pass" name="pass" placeholder="<PASSWORD>"></label></div>',
title: 'Logue para importar',
subTitle:'Necessario estar conectado na internet',
scope: $scope,
buttons: [
{ text: 'Cancelar' },
{
text: '<b>Importar</b>',
type: 'button-positive',
onTap: function(e) {
if ($scope.data.login && $scope.data.pass) {
$http({
method: 'POST',
url: 'http://'+sessao.getData("sess_caminho")+':'+sessao.getData("sess_porta")
+sessao.getData("sess_diretorio")+'pedidos.p',
data:'tipo=valida_usuario&usuario='+$scope.data.login+'&senha='+$scope.data.pass,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
if(data.pedidos.valida_usuario[0]['retorna'] == "yes" ){
CarregaBanco.importar(data.pedidos.valida_usuario[0]['cd-empresa'],data.pedidos.valida_usuario[0]['cd-filial'],function(response){
if(response.sucesso){
$scope.sucesso = response.sucesso;
$timeout(function(){
$scope.sucesso = '';
}, 9300);
}
});
myPopup.close();
}else{
alert("Senha Incorreta ou Usuario nao existe!");
}
}).
error(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
alert("Internet offline / nao foi possivel importar os dados");
});
e.preventDefault();
}
}
},
]
});
}
});<file_sep> <button type="button" ng-hide="!formData.vencimento.length" ng-click="SetPedido(formData)" class="button button-block button-positive" >
{{tipo=='i'?"Inserir Pedido":"Alterar Pedido"}}
</button>
<ion-list class="list list-inset">
<label class="item item-input item-stacked-label" ng-hide="!formData.produtos.length">
<span class="input-label"><b>Total Lucro Ganho</b></span>
<p></p>{{ getTotalLucro() | number : 2}} ({{ getTotalLucroCent() | number : 2}} %)</p>
</label>
<ion-item class="item item-icon-left item-icon-right" ng-repeat="prod in formData.produtos">
{{prod.id}} - {{prod.id_iten}} - {{prod.text}} - ({{prod.lucro | number : 2}}) - {{prod.lucroCent | number : 2}} %
</ion-item>
</ion-list>
|
3cbe7f5cf448d5b3773adec34d953a2c04c365c6
|
[
"JavaScript",
"HTML"
] | 9
|
JavaScript
|
brackbk/pedidos
|
b4316c0ddb374c87031e029649e80a64cf4eb0f3
|
627fedc5ce2903a5768677924c9c744dc8ebf31e
|
refs/heads/master
|
<file_sep>/**
* isAdmin
*
* @module :: Policy
* @description :: Simple policy to allow only authenticated Customers
* perform a given action
* @docs :: http://sailsjs.org/#!/documentation/concepts/Policies
*
*/
module.exports = function(req, res, next) {
// User is allowed, proceed to the next policy,
// or if this is the last policy, the controller
if (req.session.authenticated) {
var id = req.session.user_id;
User.findOne({id: id}, function(error, user) {
if (error) {
console.log(error);
return res.forbidden('You are not permitted to perform this action.');
} else {
User.isCustomer(user, function(error, customer) {
if (error) {
console.log(error);
return res.forbidden('You are not permitted to perform this action.');
} else {
console.log(customer);
return next();
}
});
}
});
} else {
// User is not loged in at all
return res.forbidden('You are not permitted to perform this action.');
}
};
<file_sep>/**
* RestaurantController
*
* @description :: Server-side logic for CRUDing restaurants
* @route :: /restaurant
*/
module.exports = {
_config: {
rest: true
},
/**
* List all the restaurants in the DB
* @method GET
* @route /
*/
find: function (req, res) {
return res.send({
message: 'Show all restaurants'
});
},
/**
* Information about a single restaurant, filtered by the ID
* @method GET
* @route /:id
*/
findOne: function (req, res) {
return res.send({
message: 'Show restaurant with id ' + req.params.id
});
},
/**
* Create a new restaurant
* @method POST
* @route /
*/
create: function (req, res) {
//create
return res.send({
message: 'Creating restaurant'
});
},
/**
* Update an existing restaurant, based on the ID
* @method PUT
* @route /:id
*/
update: function (req, res) {
return res.send({
message: 'Update restaurant with id ' + req.params.id
});
},
/**
* Delete the restaurant with the given ID
* @method DELETE
* @route /:id
*/
destroy: function (req, res) {
return res.send({
message: 'Delete restaurant with id ' + req.params.id
});
}
};
<file_sep>/**
* User.js
*
* @description :: The user model, mapping users into the DB
* @docs :: http://sailsjs.org/#!documentation/models
*/
var bcrypt = require('bcrypt');
var uuid = require('uuid');
var hat = require('hat');
module.exports = {
attributes: {
email: {
type: 'string',
required: true,
unique: true
},
username: {
type: 'string',
required: true,
unique: true
},
password: {
type: 'string',
required: true,
},
user_type: {
type: 'string',
required: true,
enum: ['admin', 'manager', 'customer'],
defaultsTo: 'customer'
},
first_name: {
type: 'string',
required: true
},
last_name: {
type: 'string',
required: true
},
api_key: {
type: 'string',
required: false
}
},
beforeCreate: function(user, next) {
console.log('Saving user');
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(error, hash) {
if (error) {
console.log(error);
next(error);
} else {
user.password = hash;
next(null, user);
}
});
});
},
attemptLogin: function(user, next) {
User.findOne({username: user.username}, function(error, foundUser) {
if (error) {
console.log(error);
next(error);
} else if (foundUser === undefined) {
next({
error: 'E_AUTHENTICATION',
status: 403, //forbidden
summary: 'Wrong username or password'
});
} else {
bcrypt.compare(user.password, foundUser.password, function(error, res) {
if (error) {
console.log(error);
next(error);
} else {
next(null, foundUser);
}
});
}
});
},
isAdmin: function(user, next) {
if (user.user_type === 'admin') {
console.log('admin');
next(null, user);
} else {
next({
error: 'E_AUTHORIZATION',
status: 403, //forbidden
summary: 'You don\'t have access here'
});
}
},
isManager: function(user, next) {
if (user.user_type === 'manager') {
console.log('manager');
next(null, user);
} else {
next({
error: 'E_AUTHORIZATION',
status: 403, //forbidden
summary: 'You don\'t have access here'
});
}
},
isCustomer: function(user, next) {
if (user.user_type === 'customer') {
next(null, user);
} else {
next({
error: 'E_AUTHORIZATION',
status: 403, //forbidden
summary: 'You don\'t have access here'
});
}
},
isDeveloper: function(user, next) {
if (user.user_type === 'customer' && user.api_key) {
console.log('developer');
next(null, user);
} else {
next({
error: 'E_AUTHORIZATION',
status: 403, //forbidden
summary: 'You don\'t have access here'
});
}
},
generateApiKey: function(user, next) {
var api_key = hat();
console.log('API key generated: ' + api_key);
user.api_key = api_key;
user.save(function(error, saved) {
if (error) {
console.log(error);
next(error);
} else {
console.log('user saved');
next(null, user);
}
});
},
resetPassword: function(user, password, next) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(password, salt, function(error, hash) {
if (error) {
console.log(error);
next(error);
} else {
user.password = <PASSWORD>;
user.save(function(error, saved) {
if (error) {
console.log(error);
next(error);
} else {
next(null, user);
}
});
}
});
});
}
};
<file_sep>/**
* Restaurant.js
*
* @description :: A mapping for restaurant objects in the DB
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
name: {
type: 'string',
required: true,
unique: true
},
address: {
type: 'string',
required: true,
},
url: {
type: 'string',
required: false,
defaultsTo: '#'
},
description: {
type: 'string',
required: 'false'
},
category: {
type: 'string',
enum: ['Cat1', 'Cat2', 'Cat3'],
defaultsTo: 'Cat1'
}
}
};
<file_sep># Restauranteers
_Homeworks can be fun_ :smiley:
Restauranteers is a final project developed for the Software Engineering course in the Polytechnic University of Tirana. The application shows a list of restaurants (including their menus) and allows users write reviews about them.
The application is built using a full-stack JavaScript solution:
- [MongoDB](https://www.mongodb.org/) for the database
- [Sails.js](http://sailsjs.org/), a [Node.js](http://nodejs.org/) framework for the back-end logic
- [AngularJS](http://angularjs.org/) in the front
<file_sep>/**
* DemoController
*
* @description :: Server-side logic for managing demoes
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
createAdmin: function(req, res) {
var admin = {
username: 'admin',
password: '<PASSWORD>',
email: '<EMAIL>',
user_type: 'admin',
first_name: 'Admini',
last_name: 'Strator'
};
User.create(admin, function(err, user) {
if (err || !user) {
return res.send(err);
} else {
return res.send({
status: 'OK',
message: 'created admin with id ' + user.id,
user: user
});
}
});
},
createCustomer: function(req, res) {
var customer = {
username: 'aziflaj',
password: '<PASSWORD>',
email: '<EMAIL>',
first_name: 'Aldo',
last_name: 'Ziflaj'
};
User.create(customer, function(err, user) {
if (err || !user) {
return res.send(err);
} else {
return res.send({
status: 'OK',
message: 'created customer with id ' + user.id,
user: user
});
}
});
},
throw500: function(req, res) {
return res.serverError();
}
};
|
dbf76d9d94a8aa3d58ba071c1631a7e5051a0bd2
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
ilyes495/restauranteers
|
e7ea6eea4bee4367d85783f231ddaaf00f7cf15a
|
dca84cc1faa3fcdf6d7fb54f027c94fd2d3574a1
|
refs/heads/master
|
<file_sep>package com.yyh.yyseckill.product.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/14 12:18 上午
*/
@Configuration
public class RabbitMQConfig {
@Autowired
private Environment env;
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
/**
* 秒杀订单队列
*
* @return
*/
@Bean
public Queue seckillOrderQueue() {
return new Queue(env.getProperty("mq.order.queue"), true, false, false);
}
/**
* 秒杀订单绑定
*
* @return
*/
@Bean
public Binding seckillOrderBinding() {
return new Binding(env.getProperty("mq.order.queue"),
Binding.DestinationType.QUEUE,
env.getProperty("mq.order.exchange"),
env.getProperty("mq.order.routing.key"), null);
}
/**
* 秒杀交换机
*
* @return
*/
@Bean
public TopicExchange seckillOrderExchange() {
return new TopicExchange(env.getProperty("mq.order.exchange"), true, false);
}
}
<file_sep>com.atguigu.common.valid.ListValue.message=请提交指定的值<file_sep>package com.yyh.yyseckill.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yyh.common.to.SeckillOrderTo;
import com.yyh.common.utils.PageUtils;
import com.yyh.yyseckill.product.entity.OrderEntity;
import java.util.Map;
/**
* 订单表
*
* @author yyh
* @email 469268632qq.com
* @date 2020-07-14 00:01:13
*/
public interface OrderService extends IService<OrderEntity> {
PageUtils queryPage(Map<String, Object> params);
void createSeckillOrder(SeckillOrderTo seckillOrderTo);
}
<file_sep>package com.yyh.yyseckill.seckill.constant;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 11:34 下午
*/
public class RedisConstant {
public static final String SESSIONS_CACHE_PREFIX = "seckill:sessions";
public static final String PRODUCT_CACHE_PREFIX = "seckill:product";
public static final String PRODUCT_STOCK_SEMAPHORE = "seckill:stock:";
public static final String PUTONSHELL_LOCK = "seckill:putonshell:lock";
}
<file_sep>package com.yyh.yyseckill.product.service.impl;
import com.yyh.yyseckill.product.entity.ProductEntity;
import com.yyh.yyseckill.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyh.common.utils.PageUtils;
import com.yyh.common.utils.Query;
import com.yyh.yyseckill.product.dao.SeckillSessionDao;
import com.yyh.yyseckill.product.entity.SeckillSessionEntity;
import com.yyh.yyseckill.product.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;
@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
@Autowired
private ProductService productService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SeckillSessionEntity> page = this.page(
new Query<SeckillSessionEntity>().getPage(params),
new QueryWrapper<SeckillSessionEntity>()
);
return new PageUtils(page);
}
@Override
public List<SeckillSessionEntity> getLatest3DaysSessions() {
List<SeckillSessionEntity> list = this.list(new QueryWrapper<SeckillSessionEntity>()
.between("start_time", startTime(), endTime()));
if (CollectionUtils.isEmpty(list)) {
return new ArrayList<>();
}
return list.stream().map(session -> {
ProductEntity productEntity = productService.getById(session.getProductId());
session.setProduct(productEntity);
return session;
}).collect(Collectors.toList());
}
/**
* 获取上架时间上界
*
* @return
*/
public String startTime() {
LocalDate now = LocalDate.now();
LocalTime min = LocalTime.MIN;
LocalDateTime start = LocalDateTime.of(now, min);
return start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* 获取上架时间下界
*
* @return
*/
public String endTime() {
LocalDate nowPlus2Days = LocalDate.now().plusDays(2);
LocalTime max = LocalTime.MAX;
LocalDateTime end = LocalDateTime.of(nowPlus2Days, max);
return end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
}<file_sep>package com.yyh.yyseckill.product.listener;
import com.rabbitmq.client.Channel;
import com.yyh.common.to.SeckillOrderTo;
import com.yyh.yyseckill.product.entity.OrderEntity;
import com.yyh.yyseckill.product.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/14 12:29 上午
*/
@Slf4j
@Component
public class SeckillOrderListener {
@Autowired
private OrderService orderService;
@RabbitListener(queues = "${mq.order.queue}")
public void createOrderListener(SeckillOrderTo seckillOrderTo) {
try {
log.info("秒杀异步邮件通知-接收消息:{}", seckillOrderTo);
// 创建订单
orderService.createSeckillOrder(seckillOrderTo);
} catch (Exception e) {
log.error("秒杀异步邮件通知-接收消息-发生异常:", e.fillInStackTrace());
}
}
}
<file_sep>package com.yyh.yyseckill.seckill.service.impl;
import com.alibaba.fastjson.JSON;
import com.yyh.yyseckill.seckill.constant.RedisConstant;
import com.yyh.yyseckill.seckill.service.SessionService;
import com.yyh.yyseckill.seckill.to.ProductRedisTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 11:47 下午
*/
@Service
public class SessionServiceImpl implements SessionService {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public List<ProductRedisTo> getCurrentProductRedisTo() {
List<ProductRedisTo> productRedisTos = new ArrayList<>();
long now = new Date().getTime();
// 获取所有的场次,遍历筛选
Set<String> keys = redisTemplate.keys(RedisConstant.SESSIONS_CACHE_PREFIX + "*");
keys.forEach(key -> {
String times = key.replace(RedisConstant.SESSIONS_CACHE_PREFIX, "");
String[] s = times.split("_");
Long startTime = Long.parseLong(s[0]);
Long endTime = Long.parseLong(s[1]);
if (now >= startTime && now <= endTime) {
// 获取该场次所有的商品
List<String> range = redisTemplate.opsForList().range(key, -100, 100);
BoundHashOperations<String, String, String> hashOps =
redisTemplate.boundHashOps(RedisConstant.PRODUCT_CACHE_PREFIX);
List<String> products = hashOps.multiGet(range);
if (!CollectionUtils.isEmpty(products)) {
productRedisTos.addAll(products.stream().map(product -> {
// JSON字符串转换为对象
ProductRedisTo productRedisTo = JSON.parseObject(product, ProductRedisTo.class);
return productRedisTo;
}).collect(Collectors.toList()));
}
}
});
return productRedisTos;
}
}
<file_sep>package com.yyh.yyseckill.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* @author yyh
* @email <EMAIL>
* @date 2020-07-11 23:44:21
*/
@Data
@TableName("random_code")
public class RandomCodeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Integer id;
/**
*
*/
private String code;
}
<file_sep>package com.yyh.yyseckill.seckill.service;
import com.yyh.yyseckill.seckill.dto.KillDto;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 11:22 下午
*/
public interface SeckillService {
/**
* 秒杀业务核心接口
*/
String kill(KillDto killDto);
}
<file_sep>package com.yyh.yyseckill.product.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 秒杀活动表
*
* @author yyh
* @email <EMAIL>
* @date 2020-07-11 23:44:21
*/
@Data
@TableName("seckill_session")
public class SeckillSessionEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId
private Integer id;
/**
* 商品id
*/
private Integer productId;
/**
* 秒杀商品数
*/
private Integer total;
/**
* 秒杀开始时间
*/
private Date startTime;
/**
* 秒杀结束时间
*/
private Date endTime;
/**
* 是否有效(1=是;0=否)
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
/**
* 关联的商品
*/
@TableField(exist = false)
private ProductEntity product;
}
<file_sep>package com.yyh.yyseckill.seckill.to;
import lombok.Data;
import java.util.Date;
/**
* 秒杀商品信息
*
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 5:15 下午
*/
@Data
public class ProductRedisTo {
/**
*
*/
private Integer id;
/**
* 商品名
*/
private String name;
/**
* 商品编号
*/
private String code;
/**
* 库存
*/
private Long stock;
/**
* 采购时间
*/
private Date purchaseTime;
/**
* 是否有效(1=是;0=否)
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 秒杀活动场次id
*/
private Integer sessionId;
/**
* 秒杀开始时间
*/
private Date startTime;
/**
* 秒杀结束时间
*/
private Date endTime;
/**
* 商品随机码
*/
private String randomCode;
/**
* 单次购买的数量上限
*/
private Integer limitOnce;
}
<file_sep>package com.yyh.common.to;
import lombok.Data;
/**
* 秒杀订单TO
*
* @author yeyuhua
* @version 1.0
* @created 2020/7/13 11:37 下午
*/
@Data
public class SeckillOrderTo {
/**
* 订单号
*/
private String code;
/**
* 用户id
*/
private Integer userId;
/**
* 秒杀的场次id
*/
private Integer sessionId;
/**
* 商品id
*/
private Integer productId;
/**
* 商品数量
*/
private Integer num;
}
<file_sep>package com.yyh.yyseckill.seckill.dto;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 1:01 上午
*/
@Data
public class KillDto {
/**
* 秒杀id = "sessionId_productId"
*/
private String killId;
/**
* 商品随机码
*/
private String key;
/**
* 用户id - 方便压力测试
*/
private Integer userId;
/**
* 购买数量
*/
private Integer num;
}
<file_sep>package com.yyh.common.valid;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/6/20 9:59 下午
*/
public interface AddGroup {
}
<file_sep>package com.yyh.yyseckill.seckill.controller;
import com.yyh.common.utils.R;
import com.yyh.yyseckill.seckill.dto.KillDto;
import com.yyh.yyseckill.seckill.service.PutOnShellService;
import com.yyh.yyseckill.seckill.service.SeckillService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* 秒杀Controller
*
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 12:13 上午
*/
@RestController
@RequestMapping("/kill")
public class SeckillController {
@Autowired
private SeckillService seckillService;
/**
* 商品秒杀核心业务逻辑-用于压力测试
*
* @return
*/
@PostMapping(value = "/execute")
public R execute(@RequestBody KillDto killDto) {
String orderNo = seckillService.kill(killDto);
if (StringUtils.isEmpty(orderNo)) {
return R.ok("秒杀失败");
}
return R.ok("秒杀成功").setData(orderNo);
}
}
<file_sep>package com.yyh.yyseckill.seckill.vo;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.util.Date;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 12:53 下午
*/
@Data
public class ProductVo {
/**
*
*/
private Integer id;
/**
* 商品名
*/
private String name;
/**
* 商品编号
*/
private String code;
/**
* 库存
*/
private Long stock;
/**
* 采购时间
*/
private Date purchaseTime;
/**
* 是否有效(1=是;0=否)
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}
<file_sep>package com.yyh.yyseckill.product.service.impl;
import com.yyh.common.to.SeckillOrderTo;
import com.yyh.yyseckill.product.entity.ProductEntity;
import com.yyh.yyseckill.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyh.common.utils.PageUtils;
import com.yyh.common.utils.Query;
import com.yyh.yyseckill.product.dao.OrderDao;
import com.yyh.yyseckill.product.entity.OrderEntity;
import com.yyh.yyseckill.product.service.OrderService;
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
@Autowired
private ProductService productService;
@Autowired
private OrderDao orderDao;
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<OrderEntity> page = this.page(
new Query<OrderEntity>().getPage(params),
new QueryWrapper<OrderEntity>()
);
return new PageUtils(page);
}
@Override
public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
OrderEntity entity = new OrderEntity();
entity.setCode(seckillOrderTo.getCode());
entity.setNum(seckillOrderTo.getNum());
entity.setProductId(seckillOrderTo.getProductId());
entity.setSeckillId(seckillOrderTo.getSessionId());
entity.setUserId(seckillOrderTo.getUserId().toString());
entity.setCreateTime(new Date());
entity.setStatus(0);
System.out.println(entity);
insert(entity);
// super.save(entity);
// 订单保存完之后减库存
// synchronized (OrderServiceImpl.class) {
// ProductEntity byId = productService.getById(seckillOrderTo.getProductId());
// byId.setStock(byId.getStock() - seckillOrderTo.getNum());
// productService.updateById(byId);
// }
}
public void insert(OrderEntity orderEntity) {
orderDao.myInsert(orderEntity);
}
}<file_sep>package com.yyh.yyseckill.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yyh.common.utils.PageUtils;
import com.yyh.yyseckill.product.entity.ProductEntity;
import java.util.Map;
/**
* 商品表
*
* @author yyh
* @email 469268632qq.com
* @date 2020-07-11 23:44:21
*/
public interface ProductService extends IService<ProductEntity> {
PageUtils queryPage(Map<String, Object> params);
}
<file_sep>package com.yyh.yyseckill.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 商品表
*
* @author yyh
* @email 469268632qq.com
* @date 2020-07-11 23:44:21
*/
@Data
@TableName("product")
public class ProductEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Integer id;
/**
* 商品名
*/
private String name;
/**
* 商品编号
*/
private String code;
/**
* 库存
*/
private Long stock;
/**
* 采购时间
*/
private Date purchaseTime;
/**
* 是否有效(1=是;0=否)
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}
<file_sep>package com.yyh.yyseckill.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.yyh.yyseckill.product.entity.ProductEntity;
import com.yyh.yyseckill.product.service.ProductService;
import com.yyh.common.utils.PageUtils;
import com.yyh.common.utils.R;
/**
* 商品表
*
* @author yyh
* @email 469268632qq.com
* @date 2020-07-11 23:44:21
*/
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = productService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Integer id) {
ProductEntity product = productService.getById(id);
return R.ok().put("product", product);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody ProductEntity product) {
productService.save(product);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody ProductEntity product) {
productService.updateById(product);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Integer[] ids) {
productService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
<file_sep>package com.yyh.yyseckill.product.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 订单表
*
* @author yyh
* @email 469268632qq.com
* @date 2020-07-14 00:01:13
*/
@Data
@TableName("order")
public class OrderEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 订单编号
*/
@TableId
private String code;
/**
* 商品id
*/
private Integer productId;
/**
* 商品数量
*/
private Integer num;
/**
* 秒杀场次id
*/
private Integer seckillId;
/**
* 用户id
*/
private String userId;
/**
* 秒杀结果: -1无效 0成功(未付款) 1已付款 2已取消
*/
private Integer status;
/**
* 创建时间
*/
private Date createTime;
}
<file_sep>-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '' COMMENT '商品名',
`code` varchar(255) NOT NULL DEFAULT '' COMMENT '商品编号',
`stock` int(11) NOT NULL DEFAULT 0 COMMENT '库存',
`purchase_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '采购时间',
`status` int(11) NOT NULL DEFAULT 1 COMMENT '是否有效(1=是;0=否)',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 9
DEFAULT CHARSET = utf8 COMMENT ='商品表';
-- ----------------------------
-- Records of product
-- ----------------------------
INSERT INTO `product`
VALUES ('6', 'Java编程思想', 'book10010', '1000', '2020-05-18 21:11:23', '1', '2020-05-18 21:11:23', '2020-05-18 21:11:23');
INSERT INTO `product`
VALUES ('7', 'Spring实战第四版', 'book10011', '2000', '2020-05-18 21:11:23', '1', '2020-05-18 21:11:23',
'2020-05-18 21:11:23');
INSERT INTO `product`
VALUES ('8', '深入分析JavaWeb', 'book10012', '2000', '2019-05-18', '1', '2019-05-18 21:11:23', '2020-05-18 21:11:23');
-- ----------------------------
-- Table structure for seckill_session
-- ----------------------------
DROP TABLE IF EXISTS `seckill_session`;
CREATE TABLE `seckill_session`
(
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`product_id` int(11) NOT NULL DEFAULT 0 COMMENT '商品id',
`total` int(11) NOT NULL DEFAULT 0 COMMENT '秒杀商品数',
`start_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '秒杀开始时间',
`end_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '秒杀结束时间',
`status` tinyint(11) NOT NULL DEFAULT 1 COMMENT '是否有效(1=是;0=否)',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 4
DEFAULT CHARSET = utf8 COMMENT ='秒杀活动表';
-- ----------------------------
-- Records of seckill_session
-- ----------------------------
INSERT INTO `seckill_session`
VALUES ('1', '6', '10', '2020-06-08 21:59:07', '2020-06-15 21:59:11', '1', '2020-05-20 21:59:41');
INSERT INTO `seckill_session`
VALUES ('2', '7', '0', '2020-06-01 21:59:19', '2020-06-30 21:59:11', '1', '2020-05-20 21:59:41');
INSERT INTO `seckill_session`
VALUES ('3', '8', '97', '2020-07-01 18:58:26', '2020-07-30 21:59:07', '1', '2020-05-20 21:59:41');
-- ----------------------------
-- Table structure for order
-- ----------------------------
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order`
(
`code` varchar(50) NOT NULL COMMENT '订单编号',
`product_id` int(11) NOT NULL DEFAULT 0 COMMENT '商品id',
`num` int(11) NOT NULL DEFAULT 0 COMMENT '商品数量',
`seckill_id` int(11) NOT NULL DEFAULT 0 COMMENT '秒杀场次id',
`user_id` varchar(20) NOT NULL DEFAULT 0 COMMENT '用户id',
`status` int(11) NOT NULL DEFAULT '-1' COMMENT '秒杀结果: -1无效 0成功(未付款) 1已付款 2已取消',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`code`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8 COMMENT ='订单表';
-- ----------------------------
-- Records of order
-- ----------------------------
-- ----------------------------
-- Table structure for random_code
-- ----------------------------
DROP TABLE IF EXISTS `random_code`;
CREATE TABLE `random_code`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_code` (`code`) USING BTREE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- ----------------------------
-- Records of random_code
-- ----------------------------
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(100) CHARACTER SET utf8mb4 NOT NULL COMMENT '用户名',
`password` varchar(200) CHARACTER SET utf8mb4 NOT NULL COMMENT '密码',
`phone` varchar(50) NOT NULL DEFAULT '' COMMENT '手机号',
`email` varchar(100) CHARACTER SET utf8mb4 NOT NULL DEFAULT '' COMMENT '邮箱',
`status` int(11) NOT NULL DEFAULT '1' COMMENT '是否有效(1=是;0=否)',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_user_name` (`user_name`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 2
DEFAULT CHARSET = utf8 COMMENT ='用户信息表';
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user`
VALUES ('10', 'yymuhua', '80bab46abb7b1c4013f9971b8bec3868', '17816861105', '<EMAIL>', '1', DEFAULT, DEFAULT);
<file_sep>package com.yyh.common.valid;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/6/20 10:00 下午
*/
public interface UpdateStatusGroup {
}
<file_sep>package com.yyh.yyseckill.seckill.config;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/13 11:29 下午
*/
@Configuration
public class RabbitMQConfig {
/**
* 使用JSON序列化机制,进行消息转换
*
* @return
*/
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
}
<file_sep>package com.yyh.yyseckill.seckill.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yyh.common.utils.R;
import com.yyh.yyseckill.seckill.constant.RedisConstant;
import com.yyh.yyseckill.seckill.feign.SeckillSessionFeignService;
import com.yyh.yyseckill.seckill.service.PutOnShellService;
import com.yyh.yyseckill.seckill.to.ProductRedisTo;
import com.yyh.yyseckill.seckill.vo.ProductVo;
import com.yyh.yyseckill.seckill.vo.SeckillSessionVo;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* @author yeyuhua
* @version 1.0
* @created 2020/7/12 1:04 上午
*/
@Service
public class PutOnSehllServiceImpl implements PutOnShellService {
@Autowired
private RedissonClient redissonClient;
@Autowired
private SeckillSessionFeignService seckillSessionFeignService;
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public void putOnShellLatest3Days() {
// 加分布式锁,锁住10s
RLock lock = redissonClient.getLock(RedisConstant.PUTONSHELL_LOCK);
lock.lock(10, TimeUnit.SECONDS);
try {
// 1、调用远程商品服务,获取最近三天所有秒杀活动
R r = seckillSessionFeignService.getLatest3DaysSessions();
if (r.getCode() == 0) {
List<SeckillSessionVo> sessions = r.getData(new TypeReference<List<SeckillSessionVo>>() {
});
// 2、上架(缓存到Redis中)
// 2.1 保存秒杀活动信息
saveSessionInfos(sessions);
// 2.2 保存秒杀商品信息
saveProductInfo(sessions);
}
} finally {
lock.unlock();
}
}
/**
* 保存秒杀活动信息
* key:SESSIONS_CACHE_PREFIX + startTime + "_" + endTime
* value:场次id + 关联的商品id
*
* @param sessions
*/
private void saveSessionInfos(List<SeckillSessionVo> sessions) {
if (CollectionUtils.isEmpty(sessions)) {
return;
}
sessions.stream().forEach(session -> {
Long startTime = session.getStartTime().getTime();
Long endTime = session.getEndTime().getTime();
String key = RedisConstant.SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
// 幂等性保证,防止重复上架
if (!redisTemplate.hasKey(key)) {
String value = session.getId() + "_" + session.getProductId();
redisTemplate.opsForList().leftPushAll(key, value);
}
});
}
/**
* 缓存商品信息
* key:商品id
* value:商品对象JSON数据
* 同时需要设置信号量
*
* @param sessions
*/
private void saveProductInfo(List<SeckillSessionVo> sessions) {
if (CollectionUtils.isEmpty(sessions)) {
return;
}
sessions.stream().forEach(session -> {
BoundHashOperations<String, Object, Object> ops =
redisTemplate.boundHashOps(RedisConstant.PRODUCT_CACHE_PREFIX);
String key = session.getId() + "_" + session.getProductId();
// 幂等性保证,如果已经加了该商品就无须再加
if (ops.hasKey(key)) {
return;
}
// 1、设置商品信息
ProductRedisTo productRedisTo = new ProductRedisTo();
ProductVo productVo = session.getProduct();
BeanUtils.copyProperties(productVo, productRedisTo);
// 设置实际秒杀库存、起止时间、单次购买数量上限等
Integer stock = session.getTotal();
productRedisTo.setStock(Long.valueOf(stock));
productRedisTo.setSessionId(session.getId());
productRedisTo.setStartTime(session.getStartTime());
productRedisTo.setEndTime(session.getEndTime());
productRedisTo.setLimitOnce(5);
String randomCode = UUID.randomUUID().toString().replace("-", "");
productRedisTo.setRandomCode(randomCode);
ops.put(key, JSON.toJSONString(productRedisTo));
// 2、上架库存信息
RSemaphore semaphore =
redissonClient.getSemaphore(RedisConstant.PRODUCT_STOCK_SEMAPHORE + randomCode);
// 库存即信号量值
semaphore.trySetPermits(stock);
});
}
}
|
6ee9011fe23c08cbdaca450000d0c24296b19fff
|
[
"Java",
"SQL",
"INI"
] | 25
|
Java
|
yymuhua/yyseckill
|
076d007e961c4fad01b388a3b9b26237e9e6acd3
|
8cc29d230fa4e451da970d85906a098acaf7524b
|
refs/heads/master
|
<repo_name>IsraelEitan/UBTechRepo<file_sep>/UBTech.Data/Repositories/IRepository.cs
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace UBTeach.Data.Repositories
{
public interface IRepository<TEntity> where TEntity : class, new()
{
IQueryable<TEntity> GetAll();
Task<TEntity> AddAsync(TEntity entity);
Task<TEntity> UpdateAsync(TEntity entity);
IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
}
}<file_sep>/UBTechApi/ClientApp/src/app/services/client-search.service.ts
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpHeaderResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { IPerson } from '../interfaces/person';
@Injectable()
export class ClientSearchService {
endPoint: string;
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
private options = new HttpHeaderResponse({ headers: this.headers });
constructor(private http: HttpClient) {
this.endPoint = "http://localhost:5000/api/Person/GetPersonList/term";
}
search(term: any): Observable<IPerson[]> {
return this.http.get<IPerson[]>(this.endPoint + '?term=' + term, this.options).pipe(
map((res) => {
return (res.length != 0 ? res : null);
})
);
;
}
}
<file_sep>/UBTech.Data/Configuration/PersonConfiguration.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using UBTeach.Data.Models;
namespace UBTeach.Data.Configuration
{
class PersonConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(50);
builder.Property(e => e.LastName)
.IsRequired()
.HasMaxLength(50);
builder.Property(e => e.Role)
.IsRequired()
.HasMaxLength(50);
builder.HasData
(
new Person
{
Id = 1,
FirstName = "John",
LastName = "Doe",
Age = 30,
Role = "CTO"
},
new Person
{
Id = 2,
FirstName = "Mosh",
LastName = "Zeev",
Age = 25,
Role = "Dev"
},
new Person
{
Id = 3,
FirstName = "Guy",
LastName = "Tzof",
Age = 28,
Role = "QA"
},
new Person
{
Id = 4,
FirstName = "Noam",
LastName = "Cohen",
Age = 24,
Role = "Dev"
},
new Person
{
Id = 5,
FirstName = "Avi",
LastName = "Avraham",
Age = 30,
Role = "PO"
},
new Person
{
Id = 6,
FirstName = "Yochai",
LastName = "Moalem",
Age = 22,
Role = "Dev"
}
);
}
}
}
<file_sep>/UBTech.Data/Repositories/PersonRepository.cs
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using UBTeach.Data.Models;
namespace UBTeach.Data.Repositories
{
public class PersonRepository : EFCoreRepository<Person>, IPersonRepository
{
private readonly PersonContext _myDBContext;
public PersonRepository(PersonContext dbContext) : base(dbContext)
{
_myDBContext = dbContext;
}
// specific method
}
}
<file_sep>/UBTech.Service/Services/PersonService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UBTeach.Data.Models;
using UBTeach.Data.Repositories;
namespace UBTeach.Service.Services
{
public class PersonService : IPersonService
{
private readonly IRepository<Person> _personRepository;
public PersonService(IRepository<Person> customerRepository)
{
_personRepository = customerRepository;
}
public List<Person> GetAll()
{
return _personRepository.GetAll().ToList();
}
public async Task<Person> GetById(int id)
{
return await _personRepository.GetAll().FirstOrDefaultAsync(x => x.Id == id);
}
public async Task<List<Person>> Find(Expression<Func<Person, bool>> predicate)
{
return await _personRepository.Find(predicate).ToListAsync();
}
public async Task<Person> Add(Person newCustomer)
{
return await _personRepository.AddAsync(newCustomer);
}
}
}<file_sep>/UBTech.Service/Services/IPersonService.cs
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using UBTeach.Data.Models;
namespace UBTeach.Service.Services
{
public interface IPersonService
{
List<Person> GetAll();
Task<Person> GetById(int id);
Task<Person> Add(Person newCustomer);
Task<List<Person>> Find(Expression<Func<Person, bool>> predicate);
}
}<file_sep>/UBTechApi/Controllers/PersonController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
//using System.Web.Http;
using UBTeach.Data.Models;
using UBTeach.Service.Services;
using UBTech.Service.DTOS;
namespace UBTeachAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonController : ControllerBase
{
private readonly IPersonService _personService;
public PersonController(IPersonService personService)
{
_personService = personService;
}
[Route("GetPersonList/term")]
[HttpGet]
public async Task<ActionResult> GetPersonList(string term)
{
try
{
var clientList = (await _personService.Find(
x => (term != null) && term.Contains(" ") ?
(x.FirstName + ' ' + x.LastName).Contains(term) : x.FirstName.Contains(term))
)
.Select(
person => new PersonDTO
{
Id = person.Id,
FirstName = person.FirstName,
Age = person.Age,
LastName = person.LastName,
Role = person.Role
}).ToList();
return Ok(clientList);
}
catch (System.Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}<file_sep>/UBTech.Data/Models/PersonContext.cs
using Microsoft.EntityFrameworkCore;
using UBTeach.Data.Configuration;
namespace UBTeach.Data.Models
{
public partial class PersonContext : DbContext
{
public PersonContext()
{
}
public PersonContext(DbContextOptions<PersonContext> options)
: base(options)
{
}
public virtual DbSet<Person> Person { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new PersonConfiguration());
}
}
}
<file_sep>/UBTechApi/Migrations/20200804105936_init.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace UBTechApi.Migrations
{
public partial class init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Person",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FirstName = table.Column<string>(maxLength: 50, nullable: false),
LastName = table.Column<string>(maxLength: 50, nullable: false),
Age = table.Column<int>(nullable: false),
Role = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Person", x => x.Id);
});
migrationBuilder.InsertData(
table: "Person",
columns: new[] { "Id", "Age", "FirstName", "LastName", "Role" },
values: new object[,]
{
{ 1, 30, "John", "Doe", "CTO" },
{ 2, 25, "Mosh", "Zeev", "Dev" },
{ 3, 28, "Guy", "Tzof", "QA" },
{ 4, 24, "Noam", "Cohen", "Dev" },
{ 5, 30, "Avi", "Avraham", "PO" },
{ 6, 22, "Yochai", "Moalem", "Dev" }
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Person");
}
}
}
<file_sep>/UBTechApi/ClientApp/src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl,Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject, of } from 'rxjs';
import { debounceTime, tap, switchMap, finalize } from 'rxjs/operators';
import { ModalDismissReasons, NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ClientSearchService } from './services/client-search.service';
@Component({
selector: 'client-search',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
searchPersonCtrl = new FormControl();
filteredPersons: any;
isLoading = false;
errorMsg: string;
selectedValue : string;
private selectionValid = false;
private modalOptions: NgbModalOptions;
private minSearchCharacters : number = 1;
constructor(
private http: HttpClient,
private modalService: NgbModal,
private clientSearchService: ClientSearchService
) { }
public displayProperty(value) {
if (value) {
return value.firstName + ' ' + value.lastName;
}
}
ngOnInit() {
this.searchPersonCtrl.valueChanges
.pipe(
debounceTime(500),
tap(value => {
this.errorMsg = "";
this.filteredPersons = [];
}),
switchMap(value => {
if ((value.length > this.minSearchCharacters) && (this.selectedValue != value)) {
this.isLoading = true;
return this.clientSearchService.search(value)
.pipe(
finalize(() => {
this.isLoading = false;
this.selectionValid = false;
})
);
}
return [];
})
)
.subscribe(
data => {
this.filteredPersons = data;
console.log(this.filteredPersons);
},
err => {
console.log(err) ;
this.errorMsg = err.message;
});
}
closeResult: string;
open(content) {
const modalRef = this.modalService.open(content, this.modalOptions).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
onSelectionChange(event){
this.selectedValue = event.option.value;
this.selectionValid = true;
}
}
<file_sep>/UBTech.Data/Repositories/EFCoreRepository.cs
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using UBTeach.Data.Models;
namespace UBTeach.Data.Repositories
{
public class EFCoreRepository<TEntity> : IRepository<TEntity> where TEntity : class, new()
{
private readonly PersonContext _myDBContext;
public EFCoreRepository(PersonContext DBContext)
{
_myDBContext = DBContext;
}
public IQueryable<TEntity> GetAll()
{
try
{
return _myDBContext.Set<TEntity>();
}
catch (Exception)
{
throw new Exception("Couldn't retrieve entities");
}
}
public async Task<TEntity> AddAsync(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
}
try
{
await _myDBContext.AddAsync(entity);
await _myDBContext.SaveChangesAsync();
return entity;
}
catch (Exception)
{
throw new Exception($"{nameof(entity)} could not be saved");
}
}
public async Task<TEntity> UpdateAsync(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException($"{nameof(AddAsync)} entity must not be null");
}
try
{
_myDBContext.Update(entity);
await _myDBContext.SaveChangesAsync();
return entity;
}
catch (Exception)
{
throw new Exception($"{nameof(entity)} could not be updated");
}
}
public IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
try
{
return _myDBContext.Set<TEntity>().Where(predicate);
}
catch (Exception)
{
throw new Exception("Couldn't retrieve entities");
}
}
}
}<file_sep>/UBTech.Data/Repositories/IPersonRepository.cs
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query.Internal;
using UBTeach.Data.Models;
namespace UBTeach.Data.Repositories
{
public interface IPersonRepository : IRepository<Person>
{
//Any special person queries
}
}
|
9ee6150525a0ac065119017bd5f2c5353e2cba4b
|
[
"C#",
"TypeScript"
] | 12
|
C#
|
IsraelEitan/UBTechRepo
|
dcbb5b43326f9eddf9c977e2a169446f8c08eeeb
|
5b4eaa9ce4dc0a198207aa0ee276b67081a0f237
|
refs/heads/main
|
<file_sep>pytest==6.2.5
pytest-html==3.1.1
datetime==4.3
regex
<file_sep>import calendar
import regex
from datetime import datetime
# get_no_of_days(“yyyy-mm”)
# Function get_no_of_days
# INPUT:
# "yyyy - int number range [from -1 mln to +1 mln years]
# "mm - int number range[1-12] without 0 leading
# strptime - convert string into a date and time
def get_no_of_days(date):
try:
is_date = regex.match("^(-[1-9]|-?[1-9][0-9]{1,6}|-?10000000|[0-9])-([1-9]|1[0-2])$", date)
if is_date is not None:
date_date_format = datetime.strptime(date, "%Y-%m")
return calendar.monthrange(date_date_format.year, date_date_format.month)[1]
except ValueError:
return False
<file_sep>import pytest
import number_of_days_in_month
# I could use some function eg. fixture to load data from csv or something to test functions
long_month = 31
normal_month = 30
short_month = 28
short_month_leap_year = 29
normal_year_long_month_date = "2021-12"
normal_year_normal_month_date = "2021-4"
normal_year_short_month_date = "2019-2"
leap_year_short_month_date = "2020-2"
exception_leap_year_short_month_date = "2000-2"
normal_month_out_range_date = "2000-13"
random_value = "qwerty-123"
# I could also use @pytest.parametrize to put all
# functions into one but it is not a clear solution when i should show different scenarios
def test_normal_year_long_month():
assert number_of_days_in_month.get_no_of_days(normal_year_long_month_date) == long_month
def test_normal_year_normal_month():
assert number_of_days_in_month.get_no_of_days(normal_year_normal_month_date) == normal_month
def test_normal_year_short_month():
assert number_of_days_in_month.get_no_of_days(normal_year_short_month_date) == short_month
def test_leap_year_short_month():
assert number_of_days_in_month.get_no_of_days(leap_year_short_month_date) == short_month_leap_year
def test_month_out_of_range():
assert number_of_days_in_month.get_no_of_days(normal_month_out_range_date) is None
@pytest.mark.parametrize("test_input, expected", [(normal_month_out_range_date, None), (random_value, None)])
def test_random_argument_not_regex_match(test_input, expected):
assert number_of_days_in_month.get_no_of_days(test_input) is expected
<file_sep>
# Description:
### The program counts the days of the month after entering the date and takes into account leap years
#### also contains some pytest tests
To write function returning the number of days in given month I use `datetime` and `calendar` modules
I wasn't sure if I could use these built-in functions, but nowhere said I couldn't;)
I could also write it manually:
convert date to two numbers and check:
if year % 400 == 0 or if year % 100 == 0 etc.
# To run tests:
1. install latest pip package
2. invoke in cmd: `pip install -r requierements.txt`
3. run pytest by `pytest`
4. If You want You have html report, you should invoke `pytest --html=report.html --self-contained-html`
## I check in tests different scenarios:
|
e3a5247abc47fe9d7fad88c2f1ba34926051ce8b
|
[
"Markdown",
"Python",
"Text"
] | 4
|
Text
|
pawelkuznik/python_the_days_of_the_month
|
cdbcc3b776c04dc6973a4704f68cfaa085432f43
|
18373cdd372e1acd7499e8001ca8cfd0c8dc7f65
|
refs/heads/master
|
<file_sep># 1. Create a Vehicle class with max_speed and mileage instance attributes
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
# 2. Create a child class Bus that will inherit all of the variables and methods of the Vehicle class and will have seating_capacity own method
class Bus(Vehicle):
def __init__(self, max_speed, mileage, seating_capacity):
super().__init__(max_speed, mileage)
self.seating_capacity = seating_capacity
def seating_capacity(self):
return self.seating_capacity
# # 3. Determine which class a given Bus object belongs to (Check type of an object)
bus_1 = Bus(180, 800, 40)
print(type(bus_1))
# Output:
# <class '__main__.Bus'>
# 4. Determine if School_bus is also an instance of the Vehicle class
print(isinstance(Bus, Vehicle))
# Output
# NameError: name 'Bus' is not defined
# 5. Create a new class School with get_school_id and number_of_students instance attributes
class School:
def __init__(self, school_id, number_of_students):
self.school_id = school_id
self.number_of_students = number_of_students
def get_school_id(self):
return self.school_id
# 6 *. Create a new class SchoolBus that will inherit all of the methods from School and Bus and will have its own - bus_school_color
class SchoolBus(School, Bus):
def __init__(self, school_id, max_speed, mileage, seating_capacity, number_of_students, bus_school_color):
School.__init__(self, school_id, number_of_students)
Bus.__init__(self, max_speed, mileage, seating_capacity)
self.__bus_school_color = bus_school_color
def bus_school_color(self):
return self.__bus_school_color
# 7. Polymorphism: Create two classes: Bear, Wolf. Both of them should have make_sound method. Create two instances, one of Bear and one of Wolf,
# make a tuple of it and by using for call their action using the same method.
class Bear:
def make_sound(self):
return "Buu"
class Wolf:
def make_sound(self):
return "Woo"
bear = Bear()
wolf = Wolf()
for animal in (bear, wolf):
print("Animal makes sound: ", animal.make_sound())
# Output:
# Animal makes sound: Buu
# Animal makes sound: Woo
# 8. Create class City with name, population instance attributes, return a new instance only when population > 1500,
# otherwise return message: "Your city is too small".
class City:
def __init__(self, name, population):
self.name = name
self.population = population
def __new__(cls, name, population):
instance = super(City, cls).__new__(cls)
if population > 1500:
return instance
else:
return "Your city is too small"
# 9. Override a printable string representation of the City class and return: The population of the city {name} is {population}
def __str__(self):
return f'The population of the city {self.name} is a {self.population}'
# 10*. Override magic method __add__() to perform the additional action as 'multiply' (*) the value which is greater than 10. And perform this add (+) of two instances.
class Count:
def __init__(self, count):
self.count = count
def __add__(self, other):
if self.count > 10 or other.count > 10:
total_count = self.count * other.count
else:
total_count = self.count + other.count
return Count(total_count)
def __str__(self):
return f'Count: {self.count}'
a = Count(50)
b = Count(5)
c = a + b
print(c)
a1 = Count(100)
b1 = Count(200)
c1 = a1 + b1
print(c1)
# Output:
# Count: 250
# Count: 20000
# 11. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function.
# Create a new class with __call__ method and define this call to return sum.
class Addition:
def __call__(self, a, b):
return a + b
sum1 = Addition()
print(sum1(30, 50))
# Output
# 80
# 12*. Making Your Objects Truthy or Falsey Using __bool__().
# Create class MyOrder with cart and customer instance attributes.
# Override the __bool__magic method considered to be truthy if the length of the cart list is non-zero.
# e.g.:
# order_1 = MyOrder(['a', 'b', 'c'], 'd')
# order_2 = MyOrder([], 'a')
# bool(order_1)
# True
# bool(order_2)
# False
class MyOrder:
def __init__(self, cart, customer):
self.cart = cart
self.customer = customer
def __bool__(self):
if len(self.cart) == 0:
return False
else:
return True
order1 = MyOrder(['milk', 'bread', 'sugar'], "Anna")
order2 = MyOrder([], "Marian")
print(bool(order1))
print(bool(order2))
# Output:
# True
# False
<file_sep>
#1. Define the id of next variables:
int_a = 55
str_b = 'cursor'
set_c = {1, 2, 3}
lst_d = [1, 2, 3]
dict_e = {'a': 1, 'b': 2, 'c': 3}
print(id(int_a))
print(id(str_b))
print(id(set_c))
print(id(lst_d))
print(id(dict_e))
#Output:
#9786624
#140362932224432
#140362932229952
#140362933127104
#140362933084672
#2. Append 4 and 5 to the lst_d and define the id one more time.
lst_d.append(4)
lst_d.append(5)
print (lst_d)
print (id(lst_d))
#Output
#[1, 2, 3, 4, 5]
#140231938635712
#3. Define the type of each object from step 1.
print(type(int_a))
print(type(str_b))
print(type(set_c))
print(type(lst_d))
print(type(dict_e))
#<class 'int'>
#<class 'str'>
#<class 'set'>
#<class 'list'>
#<class 'dict'>
#4*. Check the type of the objects by using isinstance.
print(isinstance(int_a, int))
print(isinstance(str_b, str))
print(isinstance(set_c, set))
print(isinstance(lst_d, list))
print(isinstance(dict_e, dict))
#Output
#True
#True
#True
#True
#True
# 5. String formatting:
# Replace the placeholders with a value:
# "Anna has ___ apples and ___ peaches."
# With .format and curly braces {}
string = "Anna has {} apples and {} peaches.".format(2, 3)
print(string)
#Anna has 2 apples and 3 peaches.
# 6. By passing index numbers into the curly braces.
print ("Anna has {0} apples and {1} peaches.".format(2,3))
# Anna has 2 apples and 3 peaches.
#7. By using keyword arguments into the curly braces.
print ("Anna has {apples} apples and {peaches} peaches.".format(apples = 2, peaches = 3))
# Anna has 2 apples and 3 peaches.
#8*. With indicators of field size (5 chars for the first and 3 for the second)
print("Anna has {0:5} apples and {1:3} peaches.".format (2,3))
# Anna has 2 apples and 3 peaches.
#9. With f-strings and variables
a=2
p=3
print(f"Anna has {a} apples and {p} peaches")
# Anna has 2 apples and 3 peaches
#10.With % operator
print("Anna has %s apples and %s peaches" %(a, p))
# Anna has 2 apples and 3 peaches
# 11*. With variable substitutions by name (hint: by using dict)
apples = 2
peaches = 3
dictionary = {"a": apples, "p": peaches}
print("Anna has %(a)s apples and %(p)s peaches" %dictionary)
#Anna has 2 apples and 3 peaches
# 12. Convert (1) to list comprehension
# (1)
# lst = []
# for num in range(10):
# if num % 2 == 1:
# lst.append(num ** 2)
# else:
# lst.append(num ** 4)
# print(lst)
comprehension1 = [num ** 2 if num % 2 == 1 else num ** 4 for num in range(10)]
print (comprehension1)
# [0, 1, 16, 9, 256, 25, 1296, 49, 4096, 81]
#13 Convert (2) to regular for with if-else
# (2)
# list_comprehension = [num // 2 if num % 2 == 0 else num * 10 for num in range(10)]
# print(list_comprehension)
list_comprehension = []
for num in range(10):
if num % 2 == 0:
list_comprehension.append (num//2)
else:
list_comprehension.append (num *10)
print (list_comprehension)
# [0, 10, 1, 30, 2, 50, 3, 70, 4, 90]
#14. Convert (3) to dict comprehension.
# d = {}
# for num in range(1, 11):
# if num % 2 == 1:
# d[num] = num ** 2
# print(d)
comprehension3 = {num: num ** 2 for num in range(1, 11) if num % 2 == 1}
print(comprehension3)
# {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# 15*. Convert (4) to dict comprehension.
# d = {}
# for num in range(1, 11):
# if num % 2 == 1:
# d[num] = num ** 2
# else:
# d[num] = num // 0.5
# print(d)
comprehension4 = {num: num ** 2 if num % 2 == 1 else num // 0.5 for num in range(1,11)}
print(comprehension4)
# {1: 1, 2: 4.0, 3: 9, 4: 8.0, 5: 25, 6: 12.0, 7: 49, 8: 16.0, 9: 81, 10: 20.0}
# 16. Convert (5) to regular for with if.
# dict_comprehension = {x: x ** 3 for x in range(10) if x ** 3 % 4 == 0}
# print(dict_comprehension)
dict1 = {}
for x in range(10):
if x ** 3 % 4 == 0:
dict1[x] = x**3
print(dict1)
#{0: 0, 2: 8, 4: 64, 6: 216, 8: 512}
# 17*. Convert (6) to regular for with if-else.
# dict_comprehension = {x: x**3 if x**3 % 4 == 0 else x for x in range(10)}
dict2 = {}
for x in range(10):
if x **3 %4 == 0:
dict2[x] =x**3
else:
dict2[x] = x
print(dict2)
#{0: 0, 1: 1, 2: 8, 3: 3, 4: 64, 5: 5, 6: 216, 7: 7, 8: 512, 9: 9}
# 18. Convert (7) to lambda function
# Lambda:
# def foo(x, y):
# if x < y:
# return x
# else:
# return y
foo = lambda x, y: x if x < y else y
# 19*. Convert (8) to regular function
# foo = lambda x, y, z: z if y < x and x > z else y
def foo(x,y,z):
if y < x and x > z:
return z
else:
return y
# 20. Sort lst_to_sort from min to max
lst_to_sort = [5, 18, 1, 24, 33, 15, 13, 55]
print(sorted(lst_to_sort))
# [1, 5, 13, 15, 18, 24, 33, 55]
# 21. Sort lst_to_sort from max to min
print(sorted(lst_to_sort, reverse=True))
# [55, 33, 24, 18, 15, 13, 5, 1]
# 22. Use map and lambda to update the lst_to_sort by multiply each element by 2
list_new = (list(map(lambda x: x * 2, lst_to_sort)))
print(list_new)
#[10, 36, 2, 48, 66, 30, 26, 110]
# 23*. Raise each list number to the corresponding number on another list:
list_A = [2, 3, 4]
list_B = [5, 6, 7]
list_new1 = list(map(lambda x,y: x+y, list_A, list_B))
print(list_new1)
# [7, 9, 11]
# 24. Use reduce and lambda to compute the numbers of a lst_to_sort.
lst_to_sort = [5, 18, 1, 24, 33, 15, 13, 55]
from functools import reduce
numbers = reduce(lambda x, y : x + y, lst_to_sort)
print(numbers)
# 164
# 25. Use filter and lambda to filter the number of a lst_to_sort with elem % 2 == 1.
list_new2 = list(filter(lambda x: x % 2 == 1, lst_to_sort))
print(list_new2)
# [5, 1, 33, 15, 13, 55]
# 26. Considering the range of values: b = range(-10, 10), use the function filter to return only negative numbers.
b = range(-10, 10)
list_new3 = (list(filter(lambda x: x < 0, b)))
print(list_new3)
# [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
# 27*. Using the filter function, find the values that are common to the two lists:
list_1 = [1,2,3,5,7,9]
list_2 = [2,3,5,6,7,8]
list_new4 = list(filter(lambda x: x in list_2, list_1))
print(list_new4)
# [2, 3, 5, 7]
|
56814892fbb987d8fc237ad319b7f56d7b1610be
|
[
"Python"
] | 2
|
Python
|
mariiaba/Cursor
|
2ce7836820c8ab4b692a3c0bc69159a11da9a3d9
|
cfc73d0b0b4ef6d6d3950f93524d58fbd8c522b9
|
refs/heads/main
|
<repo_name>Fikri1234/Springboot-Oauth-JUnit<file_sep>/src/main/java/com/project/buku/Resource/NotFoundExceptionResource.java
/**
*
*/
package com.project.buku.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author Fikri
*
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundExceptionResource extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public NotFoundExceptionResource(String message) {
super(message);
}
}
<file_sep>/README.md
# SpringBoot-Oauth
Explore Java Springboot Framework with Oauth2 scenario unit testing using TestRestTemplate & MockMVC. For making assertions in JUnit I choose Hamcrest.
## Prerequisites
1. Java 8
2. JPA Mysql
3. Gradle
4. Oauth2
5. Dev Tools
6. Lombok
7. Swagger
8. MockMVC
9. TestRestTemplate
10. Hamcrest
## Setup MySQL
Import import-dev.sql to your MySQL
## Collection Endpoints
Import Buku_Oauth.postman_collection to Postman
## API Documentation
Open your browser for SpringFox http://localhost:8200/api/v2/api-docs <br />
Open your browser for Swagger UI http://localhost:8200/api/swagger-ui.html#/ <br />
## How it work
To run application,open cmd in your project directory and type
```
gradlew bootRun
```
## Unit Testing
To run unit testing,open cmd in your project directory and type
```
gradlew clean test --info
```
JUnit Testing result

### Notes
For those who having this problem in Eclipse:



Type this command:
```
gradle wrapper --gradle-version 7.1.1 --distribution-type all
```<file_sep>/src/main/java/com/project/buku/Repository/BukuRepository.java
/**
*
*/
package com.project.buku.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.project.buku.Entity.Buku;
/**
* @author Fikri
*
*/
@Repository
public interface BukuRepository extends JpaRepository<Buku, Long> {
}
<file_sep>/src/test/java/com/project/buku/BukuResourceWithTestRestTemplateTests.java
/**
*
*/
package com.project.buku;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Fikri
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class BukuResourceWithTestRestTemplateTests {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
int randomServerPort;
@Test
public void testLogin() throws Exception
{
final String baseUrl = "http://localhost:"+randomServerPort+"/api/oauth/token";
String credentials = IConstant.CLIENT_ID + ":" + IConstant.CLIENT_PASS;
String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add("Authorization", "Basic " + encodedCredentials);
HttpEntity<String> request = new HttpEntity<String>(headers);
String access_token_url = baseUrl;
access_token_url += "?username=" + IConstant.USERNAME;
access_token_url += "&password=" + <PASSWORD>;
access_token_url += "&grant_type=password";
ResponseEntity<String> response = this.restTemplate.postForEntity(access_token_url, request, String.class);
log.info("Access Token Response --------- {} with port: {}", response.getBody(), randomServerPort);
// Get the Access Token From the recieved JSON response
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(response.getBody());
String token = node.path("access_token").asText();
log.info("Get Token Response ---------" + token);
//Verify request succeed
assertThat(response.getStatusCodeValue(), equalTo(HttpStatus.OK.value()));
}
}
<file_sep>/import-dev.sql
-- MySQL dump 10.13 Distrib 8.0.22, for Win64 (x86_64)
--
-- Host: localhost Database: quarkus
-- ------------------------------------------------------
-- Server version 8.0.22
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `oauth_client_details`
--
DROP TABLE IF EXISTS `oauth_client_details`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `oauth_client_details` (
`CLIENT_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`RESOURCE_IDS` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`CLIENT_SECRET` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`SCOPE` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`AUTHORIZED_GRANT_TYPES` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`WEB_SERVER_REDIRECT_URI` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`AUTHORITIES` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`ACCESS_TOKEN_VALIDITY` int DEFAULT NULL,
`REFRESH_TOKEN_VALIDITY` int DEFAULT NULL,
`ADDITIONAL_INFORMATION` varchar(4096) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`AUTOAPPROVE` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`CLIENT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `oauth_client_details`
--
LOCK TABLES `oauth_client_details` WRITE;
/*!40000 ALTER TABLE `oauth_client_details` DISABLE KEYS */;
INSERT INTO `oauth_client_details` VALUES ('spring-security-oauth2-read-client','resource-server-rest-api','$2a$04$WGq2P9egiOYoOFemBRfsiO9qTcyJtNRnPKNBl5tokP7IP.eZn93km','read','password,authorization_code,refresh_token,implicit',NULL,'USER',1800,3600,NULL,NULL),('spring-security-oauth2-read-write-client','resource-server-rest-api','$2a$04$soeOR.QFmClXeFIrhJVLWOQxfHjsJLSpWrU1iGxcMGdu.a5hvfY4W','read,write','<PASSWORD>,authorization_code,refresh_token,implicit',NULL,'USER',1800,3600,NULL,NULL);
/*!40000 ALTER TABLE `oauth_client_details` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `oauth_code`
--
DROP TABLE IF EXISTS `oauth_code`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `oauth_code` (
`CODE` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`AUTHENTICATION` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `oauth_code`
--
LOCK TABLES `oauth_code` WRITE;
/*!40000 ALTER TABLE `oauth_code` DISABLE KEYS */;
/*!40000 ALTER TABLE `oauth_code` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `oauth_access_token`
--
DROP TABLE IF EXISTS `oauth_access_token`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `oauth_access_token` (
`TOKEN_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`TOKEN` blob,
`AUTHENTICATION_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`USER_NAME` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`CLIENT_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`AUTHENTICATION` blob,
`REFRESH_TOKEN` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`AUTHENTICATION_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `oauth_access_token`
--
LOCK TABLES `oauth_access_token` WRITE;
/*!40000 ALTER TABLE `oauth_access_token` DISABLE KEYS */;
INSERT INTO `oauth_access_token` VALUES ('<PASSWORD>',_binary '¬\í\0sr\0Corg.springframework.security.oauth2.common.DefaultOAuth2AccessToken²6$ú\Î\0L\0additionalInformationt\0Ljava/util/Map;L\0\nexpirationt\0Ljava/util/Date;L\0refreshTokent\0?Lorg/springframework/security/oauth2/common/OAuth2RefreshToken;L\0scopet\0Ljava/util/Set;L\0 tokenTypet\0Ljava/lang/String;L\0valueq\0~\0xpsr\0java.util.Collections$EmptyMapY6
Z\Ü\ç\Ğ\0\0xpsr\0java.util.DatehjKYt\0\0xpw\0\0{\r¬ °xsr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationq\0~\0xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valueq\0~\0xpt\0$0977c3aa-10e6-4345-a86b-312891aa1a93sq\0~\0 w\0\0{¥:°xsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0ct\0Ljava/util/Collection;xpsr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writext\0bearert\0$e226becb-c5b8-4318-9ebd-a36fba5906ff','d557e74143287f87984f133c7409755d','admin','spring-security-oauth2-read-write-client',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0userxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0w\0\0\0\0\0\0t\0\ngrant_typet\0passwordt\0usernamet\0adminxsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0#w\0\0\0?@\0\0\0\0\0sq\0~\0\rt\0USERxsq\0~\0\Z?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xppsq\0~\0#w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0#w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\01sr\0java.util.LinkedHashMap4ÀN\\lÀû\0Z\0accessOrderxq\0~\0\Z?@\0\0\0\0\0w\0\0\0\0\0\0q\0~\0q\0~\0q\0~\0q\0~\0x\0psr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0 sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0q\0~\0xpt\0admin','a2bfccf3ff5b1a7fd4eb10adb581b40d');
/*!40000 ALTER TABLE `oauth_access_token` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `m_user`
--
DROP TABLE IF EXISTS `m_user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `m_user` (
`ID` bigint NOT NULL AUTO_INCREMENT,
`PASSWORD` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`USERNAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`ACCOUNT_EXPIRED` tinyint(1) DEFAULT NULL,
`ACCOUNT_LOCKED` tinyint(1) DEFAULT NULL,
`CREDENTIALS_EXPIRED` tinyint(1) DEFAULT NULL,
`ENABLED` tinyint(1) DEFAULT NULL,
`USER_DETAIL_ID` bigint DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `USER_USER_NAME` (`USERNAME`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `m_user`
--
LOCK TABLES `m_user` WRITE;
/*!40000 ALTER TABLE `m_user` DISABLE KEYS */;
INSERT INTO `m_user` VALUES (1,'$2a$08$qvrzQZ7jJ7oy2p/msL4M0.l83Cd0jNsX6AJUitbgRXGzge4j035ha','admin',0,0,0,1,NULL);
/*!40000 ALTER TABLE `m_user` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `oauth_client_token`
--
DROP TABLE IF EXISTS `oauth_client_token`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `oauth_client_token` (
`TOKEN_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`TOKEN` blob,
`AUTHENTICATION_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`USER_NAME` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`CLIENT_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`AUTHENTICATION_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `oauth_client_token`
--
LOCK TABLES `oauth_client_token` WRITE;
/*!40000 ALTER TABLE `oauth_client_token` DISABLE KEYS */;
/*!40000 ALTER TABLE `oauth_client_token` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `oauth_refresh_token`
--
DROP TABLE IF EXISTS `oauth_refresh_token`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `oauth_refresh_token` (
`TOKEN_ID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`TOKEN` blob,
`AUTHENTICATION` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `oauth_refresh_token`
--
LOCK TABLES `oauth_refresh_token` WRITE;
/*!40000 ALTER TABLE `oauth_refresh_token` DISABLE KEYS */;
INSERT INTO `oauth_refresh_token` VALUES ('5<PASSWORD>',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$275e43c8-2af4-472b-b10e-dff00b9b2e61sr\0java.util.DatehjKYt\0\0xpw\0\0z\îØ¶\Ïx',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0userxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0w\0\0\0\0\0\0t\0\ngrant_typet\0passwordt\0usernamet\0adminxsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0#w\0\0\0?@\0\0\0\0\0sq\0~\0\rt\0USERxsq\0~\0\Z?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xppsq\0~\0#w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0#w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\01sr\0java.util.LinkedHashMap4ÀN\\lÀû\0Z\0accessOrderxq\0~\0\Z?@\0\0\0\0\0w\0\0\0\0\0\0q\0~\0q\0~\0q\0~\0q\0~\0x\0psr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0 sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0q\0~\0xpt\0admin'),('14ede3451041d509a9353604bd35569a',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$a5b037e0-a917-427b-b6ca-67c1b0cdcd68sr\0java.util.DatehjKYt\0\0xpw\0\0z\ïx',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0userxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0w\0\0\0\0\0\0t\0\ngrant_typet\0passwordt\0usernamet\0adminxsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0#w\0\0\0?@\0\0\0\0\0sq\0~\0\rt\0USERxsq\0~\0\Z?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xppsq\0~\0#w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0#w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\01sr\0java.util.LinkedHashMap4ÀN\\lÀû\0Z\0accessOrderxq\0~\0\Z?@\0\0\0\0\0w\0\0\0\0\0\0q\0~\0q\0~\0q\0~\0q\0~\0x\0psr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0 sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0q\0~\0xpt\0admin'),('fe96bcb6ca812b4afe8c8b884f1b5bc6',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$ab31866e-7dcf-4a71-b4c3-517d8ed2fc83sr\0java.util.DatehjKYt\0\0xpw\0\0z\ïJs)x',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0userxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0w\0\0\0\0\0\0t\0\ngrant_typet\0passwordt\0usernamet\0adminxsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0#w\0\0\0?@\0\0\0\0\0sq\0~\0\rt\0USERxsq\0~\0\Z?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xppsq\0~\0#w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0#w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\01sr\0java.util.LinkedHashMap4ÀN\\lÀû\0Z\0accessOrderxq\0~\0\Z?@\0\0\0\0\0w\0\0\0\0\0\0q\0~\0q\0~\0q\0~\0q\0~\0x\0psr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0 sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0q\0~\0xpt\0admin'),('b94120c316fab98d82d7287143a7ed6d',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$6b388208-5172-4503-b717-06a9ed6c0596sr\0java.util.DatehjKYt\0\0xpw\0\0{\Ó\á\Äx',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0USERxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0w\0\0\0?@\0\0\0\0\0q\0~\0xsr\0java.util.Collections$EmptyMapY6
Z\Ü\ç\Ğ\0\0xpppsq\0~\0w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\0,ppsr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0sq\0~\0\rt\0userxt\0<$2a$08$qvrzQZ7jJ7oy2p/msL4M0.l83Cd0jNsX6AJUitbgRXGzge4j035hat\0admin'),('0ee9f75ec15af64ca93b6e9eb78644af',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$21067f71-4f9c-47b7-af6c-da0a8fc95a8bsr\0java.util.DatehjKYt\0\0xpw\0\0{\n¤\'x',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0userxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0w\0\0\0\0\0\0t\0\ngrant_typet\0passwordt\0usernamet\0adminxsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0#w\0\0\0?@\0\0\0\0\0sq\0~\0\rt\0USERxsq\0~\0\Z?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xppsq\0~\0#w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0#w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\01sr\0java.util.LinkedHashMap4ÀN\\lÀû\0Z\0accessOrderxq\0~\0\Z?@\0\0\0\0\0w\0\0\0\0\0\0q\0~\0q\0~\0q\0~\0q\0~\0x\0psr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0 sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0q\0~\0xpt\0admin'),('35eddc10fe9b3bcec80ad3040edd8bf2',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$32051a30-619f-41ff-bbef-b1bcd4ee9219sr\0java.util.DatehjKYt\0\0xpw\0\0{\n\ÔP}x',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0userxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0w\0\0\0\0\0\0t\0\ngrant_typet\0passwordt\0usernamet\0adminxsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0#w\0\0\0?@\0\0\0\0\0sq\0~\0\rt\0USERxsq\0~\0\Z?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xppsq\0~\0#w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0#w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\01sr\0java.util.LinkedHashMap4ÀN\\lÀû\0Z\0accessOrderxq\0~\0\Z?@\0\0\0\0\0w\0\0\0\0\0\0q\0~\0q\0~\0q\0~\0q\0~\0x\0psr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0 sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0q\0~\0xpt\0admin'),('a2bfccf3ff5b1a7fd4eb10adb581b40d',_binary '¬\í\0sr\0Lorg.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken/\ßGc\ĞÉ·\0L\0\nexpirationt\0Ljava/util/Date;xr\0Dorg.springframework.security.oauth2.common.DefaultOAuth2RefreshTokens\á\ncT\Ô^\0L\0valuet\0Ljava/lang/String;xpt\0$0977c3aa-10e6-4345-a86b-312891aa1a93sr\0java.util.DatehjKYt\0\0xpw\0\0{¥:°x',_binary '¬\í\0sr\0Aorg.springframework.security.oauth2.provider.OAuth2Authentication½@bR\0L\0\rstoredRequestt\0<Lorg/springframework/security/oauth2/provider/OAuth2Request;L\0userAuthenticationt\02Lorg/springframework/security/core/Authentication;xr\0Gorg.springframework.security.authentication.AbstractAuthenticationTokenÓª(~nGd\0Z\0\rauthenticatedL\0authoritiest\0Ljava/util/Collection;L\0detailst\0Ljava/lang/Object;xp\0sr\0&java.util.Collections$UnmodifiableListü%1µ\ì\0L\0listt\0Ljava/util/List;xr\0,java.util.Collections$UnmodifiableCollectionB\0\Ë^\÷\0L\0cq\0~\0xpsr\0java.util.ArrayListx\Ò\Ça\0I\0sizexp\0\0\0w\0\0\0sr\0Borg.springframework.security.core.authority.SimpleGrantedAuthority\0\0\0\0\0\0&\0L\0rolet\0Ljava/lang/String;xpt\0USERxq\0~\0psr\0:org.springframework.security.oauth2.provider.OAuth2Request\0\0\0\0\0\0\0\0Z\0approvedL\0authoritiesq\0~\0L\0\nextensionst\0Ljava/util/Map;L\0redirectUriq\0~\0L\0refresht\0;Lorg/springframework/security/oauth2/provider/TokenRequest;L\0resourceIdst\0Ljava/util/Set;L\0\rresponseTypesq\0~\0xr\08org.springframework.security.oauth2.provider.BaseRequest6(z>£qi½\0L\0clientIdq\0~\0L\0requestParametersq\0~\0L\0scopeq\0~\0xpt\0(spring-security-oauth2-read-write-clientsr\0%java.util.Collections$UnmodifiableMap\ñ¥¨şt\õB\0L\0mq\0~\0xpsr\0java.util.HashMap\ÚÁ\Ã`\Ñ\0F\0\nloadFactorI\0 thresholdxp?@\0\0\0\0\0\0w\0\0\0\0\0\0\0xsr\0%java.util.Collections$UnmodifiableSetÑU\0\0xq\0~\0 sr\0java.util.LinkedHashSet\Øl\×Z\İ*\0\0xr\0java.util.HashSetºD
¸·4\0\0xpw\0\0\0?@\0\0\0\0\0t\0readt\0writexsq\0~\0w\0\0\0?@\0\0\0\0\0q\0~\0xsr\0java.util.Collections$EmptyMapY6
Z\Ü\ç\Ğ\0\0xpppsq\0~\0w\0\0\0?@\0\0\0\0\0t\0resource-server-rest-apixsq\0~\0w\0\0\0?@\0\0\0\0\0\0xsr\0Oorg.springframework.security.authentication.UsernamePasswordAuthenticationToken\0\0\0\0\0\0&\0L\0credentialsq\0~\0L\0 principalq\0~\0xq\0~\0sq\0~\0sq\0~\0\0\0\0w\0\0\0q\0~\0xq\0~\0,ppsr\02org.springframework.security.core.userdetails.User\0\0\0\0\0\0&\0Z\0accountNonExpiredZ\0accountNonLockedZ\0credentialsNonExpiredZ\0enabledL\0authoritiesq\0~\0L\0passwordq\0~\0L\0usernameq\0~\0xpsq\0~\0sr\0java.util.TreeSetİP\í[\0\0xpsr\0Forg.springframework.security.core.userdetails.User$AuthorityComparator\0\0\0\0\0\0&\0\0xpw\0\0\0sq\0~\0\rt\0userxt\0<$2a$08$qvrzQZ7jJ7oy2p/msL4M0.l83Cd0jNsX6AJUitbgRXGzge4j035hat\0admin');
/*!40000 ALTER TABLE `oauth_refresh_token` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `oauth_approvals`
--
DROP TABLE IF EXISTS `oauth_approvals`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `oauth_approvals` (
`USERID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`CLIENTID` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`SCOPE` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`STATUS` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`EXPIRESAT` datetime DEFAULT NULL,
`LASTMODIFIEDAT` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `oauth_approvals`
--
LOCK TABLES `oauth_approvals` WRITE;
/*!40000 ALTER TABLE `oauth_approvals` DISABLE KEYS */;
/*!40000 ALTER TABLE `oauth_approvals` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `buku`
--
DROP TABLE IF EXISTS `buku`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `buku` (
`id` bigint NOT NULL AUTO_INCREMENT,
`judul` varchar(100) DEFAULT NULL,
`pengarang` varchar(100) DEFAULT NULL,
`deskripsi` varchar(100) DEFAULT NULL,
`image` varchar(100) DEFAULT NULL,
`harga` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `buku`
--
LOCK TABLES `buku` WRITE;
/*!40000 ALTER TABLE `buku` DISABLE KEYS */;
/*!40000 ALTER TABLE `buku` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2021-08-03 23:13:53
<file_sep>/src/main/java/com/project/buku/Configuration/WebServerConfiguration.java
/**
*
*/
package com.project.buku.Configuration;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
/**
* @author Fikri
*
*/
@Configuration
@EnableWebSecurity
@Import(Encoder.class)
public class WebServerConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder userPasswordEncoder;
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder);
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
@Primary
//Making this primary to avoid any accidental duplication with another token service instance of the same name
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
return defaultTokenServices;
}
}
<file_sep>/src/main/java/com/project/buku/DTO/BukuDTO.java
/**
*
*/
package com.project.buku.DTO;
import java.math.BigDecimal;
import com.project.buku.Entity.Buku;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* @author Fikri
*
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class BukuDTO {
private long id;
private String judul;
private String pengarang;
private String deskripsi;
private String image;
private BigDecimal harga;
public BukuDTO(Buku buku) {
super();
this.id = buku.getId();
this.judul = buku.getJudul();
this.pengarang = buku.getPengarang();
this.deskripsi = buku.getDeskripsi();
this.image = buku.getImage();
this.harga = buku.getHarga();
}
}
<file_sep>/settings.gradle
rootProject.name = 'Buku'
<file_sep>/build.gradle
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
apply plugin: 'eclipse'
group = 'com.project.buku'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-jersey'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
implementation group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.3.5.RELEASE'
implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
testImplementation group: 'org.springframework.security', name: 'spring-security-test'
testImplementation group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3'
testImplementation group: 'junit', name: 'junit', version: '4.13.1'
}
test {
useJUnitPlatform()
}
<file_sep>/src/main/java/com/project/buku/Service/BukuService.java
/**
*
*/
package com.project.buku.Service;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import com.project.buku.Entity.Buku;
/**
* @author Fikri
*
*/
public interface BukuService {
Optional<Buku> findById(Long id);
void save(Buku entity);
void update(Buku entity);
void deleteById(Long id);
void deleteAll();
List<Buku> findAll();
Page<Buku> findPaginated(int page, int size);
}
<file_sep>/src/main/java/com/project/buku/ServiceImpl/UserDetailServiceImpl.java
/**
*
*/
package com.project.buku.ServiceImpl;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.project.buku.Entity.MUser;
import com.project.buku.Repository.MUserRepository;
/**
* @author Fikri
*
*/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
MUserRepository mUserRepository;
@Override
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("username: {}",username);
Optional<MUser> user = mUserRepository.findByUsername(username);
log.info("user: {} pass: {} ", user.get().getUsername(), user.get().getPassword());
user.
orElseThrow(() -> new UsernameNotFoundException("username not found"));
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("user"));
log.info("auth: {}",authorities.toArray().toString());
return new User (user.get().getUsername(), user.get().getPassword(), authorities);
}
}
<file_sep>/src/main/java/com/project/buku/Resource/MUserResource.java
/**
*
*/
package com.project.buku.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.project.buku.DTO.MUserDTO;
import com.project.buku.Entity.MUser;
import com.project.buku.Service.MUserService;
import io.swagger.annotations.ApiOperation;
/**
* @author Fikri
*
*/
@Component
@Path("/user")
public class MUserResource {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
MUserService mUserService;
@ApiOperation(value = "Retrieve user data by Id")
@GET
@Path("/{id}")
public Response retrieveById(@PathParam("id") Long id) {
MUserDTO dto = new MUserDTO();
Optional<MUser> mUser = mUserService.findById(id);
if (mUser.isPresent()) {
BeanUtils.copyProperties(mUser.get(), dto);
log.info("data user: {}", dto);
return Response.status(200).entity(dto).build();
} else {
log.error("id not found: ", id);
return Response.status(404).entity("Unable to find id " + id).build();
}
}
@ApiOperation(value = "Retrievea all user data")
@GET
@Path("/")
public Response retrieveAll() {
List<MUserDTO> dtos = new ArrayList<MUserDTO>();
List<MUser> entities = mUserService.findAll();
if (entities.size() > 0) {
dtos = entities.stream().map(MUserDTO::new).collect(Collectors.toList());
}
return Response.status(200).entity(dtos).build();
}
@ApiOperation(value = "Insert user data")
@POST
public Response postMUser(MUserDTO dto) {
log.info("REST API for insert postMUser: {}", dto);
try {
MUser entity = new MUser();
BeanUtils.copyProperties(dto, entity);
mUserService.save(entity);
return Response.status(201).entity("SUCCESS").build();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return Response.status(409).entity(e.getMessage()).build();
}
}
@ApiOperation(value = "Updateuser data")
@PUT
public Response putMUser(MUserDTO dto) {
log.info("REST API for update putMUser");
Optional<MUser> opt = mUserService.findById(dto.getId());
if (!opt.isPresent()) {
log.error("Unable to update. MUser with id {} not found",dto.getId());
return Response.status(404).entity("Unable to update. MUser with id " +dto.getId()+ " not found").build();
}
try {
MUser entity = new MUser();
BeanUtils.copyProperties(dto, entity);
mUserService.update(entity);
return Response.status(200).entity("SUCCESS").build();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return Response.status(409).entity(e.getMessage()).build();
}
}
@ApiOperation(value = "Delete user data by Id")
@DELETE
@Path("/{id}")
public Response deleteMUserById(@PathParam("id") Long id) {
log.info("REST API for delete delete MUserById by id : {}", id);
Optional<MUser> opt = mUserService.findById(id);
if (!opt.isPresent()) {
log.error("Unable to delete.MUser with id {} not found",id);
return Response.status(404).entity("Unable to delete.MUser with id " +id+ " not found").build();
}
try {
mUserService.deleteById(id);
return Response.status(200).entity("SUCCESS").build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity(e.getMessage()).build();
}
}
@ApiOperation(value = "Delete all user data")
@DELETE
public Response deleteMUserAll(@PathParam("id") Long id) {
log.info("REST API for delete deleteMUserAll : {}", id);
try {
mUserService.deleteAll();
return Response.status(200).entity("SUCCESS").build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity(e.getMessage()).build();
}
}
}
<file_sep>/src/main/java/com/project/buku/Resource/BukuResource.java
/**
*
*/
package com.project.buku.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import com.project.buku.DTO.BukuDTO;
import com.project.buku.Entity.Buku;
import com.project.buku.Service.BukuService;
import io.swagger.annotations.ApiOperation;
/**
* @author Fikri
*
*/
@RestController
@RequestMapping("/buku")
@Singleton
public class BukuResource {
Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private BukuService bukuService;
@Autowired
private RequestMappingHandlerMapping requestMappingHandlerMapping;
@GetMapping("/endpoints/all")
public ResponseEntity<List<String>> getEndpoints() {
return new ResponseEntity<>(
requestMappingHandlerMapping
.getHandlerMethods()
.keySet()
.stream()
.map(RequestMappingInfo::toString)
.collect(Collectors.toList()),
HttpStatus.OK
);
}
@ApiOperation(value = "Retrieve data by Id")
@GetMapping("/{id}")
public ResponseEntity<?> retrieveById(@PathVariable("id") Long id) {
BukuDTO dto = new BukuDTO();
Optional<Buku> buku = bukuService.findById(id);
if (buku.isPresent()) {
BeanUtils.copyProperties(buku.get(), dto);
log.info("data buku: {}", dto);
return new ResponseEntity<>(dto, HttpStatus.OK);
} else {
log.error("id not found: ", id);
return new ResponseEntity<>("Unable to find id " + id, HttpStatus.NOT_FOUND);
}
}
@ApiOperation(value = "Retrieve all data")
@GetMapping("/")
public ResponseEntity<?> retrieveAll() {
List<BukuDTO> dtos = new ArrayList<BukuDTO>();
List<Buku> entities = bukuService.findAll();
if (entities.size() > 0) {
dtos = entities.stream().map(BukuDTO::new).collect(Collectors.toList());
return new ResponseEntity<>(dtos, HttpStatus.OK);
}
return new ResponseEntity<>(dtos, HttpStatus.OK);
}
@ApiOperation(value = "Insert data")
@PostMapping("/")
public ResponseEntity<?> postBuku(@RequestBody BukuDTO dto) {
log.info("REST API for insert postBuku: {}", dto);
try {
Buku entity = new Buku();
BeanUtils.copyProperties(dto, entity);
bukuService.save(entity);
return new ResponseEntity<>("SUCCESS", HttpStatus.CREATED);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}
}
@ApiOperation(value = "Update data")
@PutMapping("/")
public ResponseEntity<?> putBuku(@RequestBody BukuDTO dto) {
log.info("REST API for update putBuku");
Optional<Buku> opt = bukuService.findById(dto.getId());
if (!opt.isPresent()) {
log.error("Unable to update. Buku with id {} not found",dto.getId());
return new ResponseEntity<>("Unable to update. Buku with id " +dto.getId()+ " not found", HttpStatus.NOT_FOUND);
}
try {
Buku entity = new Buku();
BeanUtils.copyProperties(dto, entity);
bukuService.update(entity);
return new ResponseEntity<>("SUCCESS", HttpStatus.OK);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}
}
@ApiOperation(value = "Delete data by Id")
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteBukuById(@PathVariable("id") Long id) {
log.info("REST API for delete deleteBukuById by id : {}", id);
Optional<Buku> opt = bukuService.findById(id);
if (!opt.isPresent()) {
log.error("Unable to delete.Buku with id {} not found",id);
return new ResponseEntity<>("Unable to delete.Buku with id " +id+ " not found", HttpStatus.NOT_FOUND);
}
try {
bukuService.deleteById(id);
return new ResponseEntity<>("SUCCESS", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ApiOperation(value = "Delete all data")
@DeleteMapping("/")
public ResponseEntity<?> deleteBukuAll() {
log.info("REST API for delete All : {}");
try {
bukuService.deleteAll();
return new ResponseEntity<>("SUCCESS", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@ApiOperation(value = "Retrieve all paging data")
@GetMapping("/page/{page}/size/{size}")
public ResponseEntity<?> retrieveAll(@PathVariable("page") int page, @PathVariable("size") int size) {
List<BukuDTO> dtos = new ArrayList<BukuDTO>();
Page<Buku> pages = bukuService.findPaginated(page, size);
if (pages.hasContent()) {
Page<BukuDTO> dtoPage = pages.map(new Function<Buku, BukuDTO>() {
@Override
public BukuDTO apply(Buku entity) {
BukuDTO dto = new BukuDTO(entity);
return dto;
}
});
return new ResponseEntity<>(dtoPage.getContent(), HttpStatus.OK);
}
return new ResponseEntity<>(dtos, HttpStatus.OK);
}
}
<file_sep>/src/main/java/com/project/buku/Configuration/JerseyConfig.java
/**
*
*/
package com.project.buku.Configuration;
import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
import org.springframework.stereotype.Component;
import com.project.buku.Resource.MUserResource;
/**
* @author Fikri
*
*/
@Component
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig {
// @PostConstruct
// public void init() {
//// PackageNamesScanner resourceFinder = new PackageNamesScanner(new String[]{"com.project.buku.Resource"}, true);
//// registerFinder(resourceFinder);
// packages("com.project.buku");
// register(RequestContextFilter.class);
//// registerClasses(MUserResource.class);
// }
public JerseyConfig() {
// packages("com.project.buku.Resource");
// register(RequestContextFilter.class);
register(MUserResource.class);
}
}
|
eceae80630994831f25785a2bd75c7b720af86c9
|
[
"Markdown",
"Java",
"SQL",
"Gradle"
] | 14
|
Java
|
Fikri1234/Springboot-Oauth-JUnit
|
90f345d457745e2e5babca13ae9e07478ec96577
|
3148866e2e1c48e8bd7420ac6ec69b9603a1df92
|
refs/heads/master
|
<repo_name>kajal02/Android-Applications<file_sep>/Kajal_ContactApp/app/src/main/java/com/kajal/kajal_contactapp/MainActivity.java
package com.kajal.kajal_contactapp;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private Toolbar toolbar;
private CustomListAdapter customListAdapter;
List<ContactBean> contactBeanList = new ArrayList<ContactBean>();;
ContactManager contactManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactManager = ContactManager.getInstance();
customListAdapter = new CustomListAdapter(this, contactManager.getContactList());
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,R.string.open_drawer,
R.string.close_drawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.syncState();
showMainFragment();
showNavFragment();
}
private void showNavFragment() {
NavigationFragment navigationFragment = new NavigationFragment();
getFragmentManager().beginTransaction().add(R.id.nav_fragment_container, navigationFragment).commit();
}
private void showMainFragment() {
ListActivity listFragment = new ListActivity();
getFragmentManager().beginTransaction().replace(R.id.fragment_container, listFragment).commit();
}
public void loadList()
{
ListActivity frag1 = new ListActivity();
getFragmentManager().beginTransaction().replace(R.id.fragment_container, frag1).commit();
}
public void update(ContactBean newContact)
{
ContactManager.getInstance().addContact(newContact);
customListAdapter.notifyDataSetChanged();
ListActivity frag1 = new ListActivity();
getFragmentManager().beginTransaction().replace(R.id.fragment_container, frag1).commit();
}
public void editList(ContactBean cb, int position)
{
ContactManager.getInstance().updateContact(position, cb);
customListAdapter.notifyDataSetChanged();
ListActivity frag1 = new ListActivity();
getFragmentManager().beginTransaction().replace(R.id.fragment_container, frag1).commit();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_delete) {
Intent intent = new Intent(MainActivity.this, ListActivityDelete.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/Kajal_ContactApp_Call/app/src/main/java/com/kajal/kajal_contactapp/ListActivityDelete.java
package com.kajal.kajal_contactapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.List;
/**
* Created by 987747 on 9/24/2015.
*/
public class ListActivityDelete extends AppCompatActivity {
Toolbar toolbar;
private ListView listView1;
private CustomListAdapterDelete customListAdapterDelete;
List<ContactBean> contactBeanList;
ContactBean a;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_list);
toolbar = (Toolbar) findViewById(R.id.delete_tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView1 = (ListView)findViewById(R.id.list1);
contactBeanList = ContactManager.getInstance().getContactList();
customListAdapterDelete = new CustomListAdapterDelete(this, contactBeanList);
listView1.setAdapter(customListAdapterDelete);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
a = (ContactBean) parent.getItemAtPosition(position);
Log.i("clicked", "item");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_delete_list, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
finish();
return true;
}
if (id == R.id.action_delete) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Delete..");
alertDialogBuilder
.setMessage("Click yes to delete selected contacts")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
for(int i=0; i<ContactManager.getInstance().getContactList().size(); i++)
{
if(ContactManager.getInstance().getContactList().get(i).isChecked())
{
ContactManager.getInstance().deleteContact(i);
i--;
}
}
Intent intent = new Intent(ListActivityDelete.this, MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/Kajal_ContactApp_Call/app/src/main/java/com/kajal/kajal_contactapp/ContactManager.java
package com.kajal.kajal_contactapp;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 987747 on 9/24/2015.
*/
public class ContactManager {
private static ContactManager mContactmanager;
List<ContactBean> mContactBeanList;
List<ContactBean> mSpeedContactList;
private ContactManager(){
mContactBeanList = new ArrayList<>();
mSpeedContactList = new ArrayList<>();
}
public static ContactManager getInstance(){
if(mContactmanager == null){
mContactmanager = new ContactManager();
}
return mContactmanager;
}
public void setmSpeedContactList(List<ContactBean> mSpeedContactList) {
this.mSpeedContactList = mSpeedContactList;
}
public void addContact(ContactBean contactBean){
mContactBeanList.add(contactBean);
}
public List<ContactBean> getContactList(){
return mContactBeanList;
}
public List<ContactBean> getSpeedContactList()
{
return mSpeedContactList;
}
public void deleteContact(int position){
mContactBeanList.remove(position);
}
public void updateContact(int position, ContactBean updatedContact){
mContactBeanList.remove(position);
mContactBeanList.add(position, updatedContact);
}
}
<file_sep>/Kajal_ContactApp/app/src/main/java/com/kajal/kajal_contactapp/PagerFragment.java
package com.kajal.kajal_contactapp;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by 987747 on 9/28/2015.
*/
public class PagerFragment extends Fragment {
ContactBean mContactBean;
ImageView imageView;
TextView txt1,txt2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.activity_contact_detail,container,false);
imageView = (ImageView) view.findViewById(R.id.imageView);
txt1 = (TextView) view.findViewById(R.id.textNameDetail);
txt2 = (TextView) view.findViewById(R.id.textNumberDetail);
imageView.setImageBitmap(BitmapFactory.decodeFile(mContactBean.getImgDecodableString()));
txt1.setText(mContactBean.getName());
txt2.setText(mContactBean.getNumber());
return view;
}
public static Fragment newInstace(int position)
{
ContactBean cb = ContactManager.getInstance().getContactList().get(position);
PagerFragment pagerFragment= new PagerFragment();
if(cb!=null)
{
Bundle bundle = new Bundle();
bundle.putSerializable("Obj",cb);
pagerFragment.setArguments(bundle);
}
return pagerFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContactBean = (ContactBean) getArguments().getSerializable("Obj");
}
}
<file_sep>/Kajal_ContactApp_Call/app/src/main/java/com/kajal/kajal_contactapp/ListActivity.java
package com.kajal.kajal_contactapp;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.List;
/**
* Created by 987747 on 9/24/2015.
*/
public class ListActivity extends Fragment {
Toolbar toolbar;
private ListView listView1;
private CustomListAdapter customListAdapter;
List<ContactBean> contactBeanList;
ContactBean a;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, null);
listView1 = (ListView)view.findViewById(R.id.list1);
contactBeanList = ContactManager.getInstance().getContactList();
Log.i("size", String.valueOf(ContactManager.getInstance().getContactList().size()));
customListAdapter = new CustomListAdapter((Activity) inflater.getContext(),
contactBeanList);
listView1.setAdapter(customListAdapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
a = (ContactBean) parent.getItemAtPosition(position);
Bundle bundle = new Bundle();
bundle.putSerializable("contact_detail", a);
Intent intent = new Intent(getActivity(), ContactDetailActivity.class);
intent.putExtras(bundle);
intent.putExtra("position",position);
startActivityForResult(intent, 6);
}
});
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 6 && resultCode == 11 )
{
ContactBean cb = (ContactBean) data.getExtras().getSerializable("contact_bundle");
int pos = data.getIntExtra("position", 0);
((MainActivity)getActivity()).editList(cb, pos);
}
}
}
<file_sep>/Kajal_ContactApp/app/src/main/java/com/kajal/kajal_contactapp/ContactBean.java
package com.kajal.kajal_contactapp;
import java.io.Serializable;
/**
* Created by 987747 on 9/24/2015.
*/
public class ContactBean implements Serializable{
private String name, number, imgDecodableString, email;
private boolean checked;
public ContactBean() {
this.name="name";
}
public ContactBean(String name, String number, String email) {
this.name = name;
this.number = number;
this.email = email;
this.checked = false;
}
public ContactBean(String name, String number, String email, String imgDecodableString) {
this.name = name;
this.number = number;
this.email = email;
this.imgDecodableString = imgDecodableString;
this.checked = false;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImgDecodableString() {
return imgDecodableString;
}
public void setImgDecodableString(String imgDecodableString) {
this.imgDecodableString = imgDecodableString;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
}
|
8f49895619711d38c637eb2a5e9b28fd8ffbf5b3
|
[
"Java"
] | 6
|
Java
|
kajal02/Android-Applications
|
ee06051a1645189bdf24b32121219e10c21aa1ce
|
ec0f834cc2d942aca7d65bc1babf74fe9293608d
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
namespace MyLab.Metrics
{
public class WorkLog
{
readonly List<WorkLogItem> _history;
public bool IsStarted { get; private set; }
public DateTime StartTime { get; private set; }
public IReadOnlyList<WorkLogItem> History { get; }
public WorkLog()
{
_history = new List<WorkLogItem>();
History = _history;
}
public static WorkLog CrateAndStart()
{
var workLog = new WorkLog();
workLog.Start();
return workLog;
}
public void Start()
{
if(IsStarted)
throw new InvalidOperationException("Already started");
StartTime = DateTime.Now;
_history.Clear();
}
public void Stop()
{
IsStarted = false;
}
public void ReportEndOfWork(string name)
{
_history.Add(new WorkLogItem(DateTime.Now - StartTime, name));
}
}
public class WorkLogItem
{
public TimeSpan TimeSpan { get; }
public string Name { get; }
public WorkLogItem(TimeSpan timeSpan, string name)
{
TimeSpan = timeSpan;
Name = name;
}
}
}
|
932bd60c091756431742be381038af1f4ef39fb0
|
[
"C#"
] | 1
|
C#
|
ozzy-ext-mylab/metrics
|
3a5e655274c1b64c629166fb6bf87fc60cc5ab49
|
517dc6942be42d1606a60168c8a057debf0dacac
|
refs/heads/master
|
<file_sep># NetworksAndNetworkingProjects
Projects that deal with network and networking from my class
## What's included:
There are two assigments that are included: singlyLinkedList.c and slidingWindowSelectiveRepeat.py . They are assignments that went through basic things needed when talking about networks and networking.
There are also four tutorial files included in which I walked through different tutorials on how to create a client and server network: ClientMedium.py, EchoClientTutorial.py, EchoServerTutorial.py, and ServerMedium.py .
The final project for the class is also included. It was a group project and I was specifically in charge of making the design of the app and fixing all the errors after my groupmates initialized the client and server files. It is linked to the repository and has a README.<file_sep>#include<stdio.h>
#include<stdlib.h>
//<NAME>
//Assigment 2
//Collaborated with <NAME>, Laurence, Sara, and Jordan on this homework
struct student{
char *fname;
char *lname;
int age;
char *dob;
};
struct studentNode{
struct student *data;
struct studentNode *nextStudent;
};
struct singlyLinkedList{
struct studentNode *head;
struct studentNode *tail;
};
typedef struct student *student;
typedef struct studentNode *node;
typedef struct singlyLinkedList *linkedList;
student createStudent(char *fname, char *lname, int age, char *dob){
student temp;
temp = (student)malloc(sizeof(struct student));
temp->fname = fname;
temp->lname = lname;
temp->age = age;
temp->dob = dob;
return temp;
}
node createNode(student studentData){
node temp;
temp = (node)malloc(sizeof(struct studentNode));
temp->data = studentData;
temp->nextStudent = NULL;
return temp;
}
linkedList createList(){
linkedList temp;
temp = (linkedList)malloc(sizeof(struct singlyLinkedList));
temp->head = NULL;
temp->tail = NULL;
return temp;
}
void add_head(linkedList LinkedList, student studentToAdd){
node newNode = createNode(studentToAdd);
if(LinkedList->head == NULL){
LinkedList->head = newNode;
LinkedList->tail = newNode;
}
else{
newNode->nextStudent = LinkedList->head;
LinkedList->head = newNode;
}
}
void add_tail(linkedList LinkedList, student studentToAdd){
node newNode = createNode(studentToAdd);
if(LinkedList->tail == NULL){
LinkedList->head = newNode;
LinkedList->tail = newNode;
}
else{
LinkedList->tail->nextStudent = newNode;
LinkedList->tail = newNode;
}
}
void add_after(linkedList LinkedList, student findStudent, student studentToAdd){
node addAfter = createNode(findStudent);
node newNode = createNode(studentToAdd);
node currentNode = LinkedList->head;
node nextNode = LinkedList->head->nextStudent;
if(LinkedList->head == NULL && LinkedList->tail == NULL){
printf("%s\n", "Error: please add a head or a tail first");
}
while(currentNode->data != addAfter->data){
currentNode = nextNode;
nextNode = currentNode->nextStudent;
if(currentNode->nextStudent == NULL && currentNode->data != addAfter->data){
printf("%s\n", "Error: node not found");
break;
}
}
if(currentNode->nextStudent == NULL){
add_tail(LinkedList, newNode->data);
}
else{
currentNode->nextStudent = newNode;
newNode->nextStudent = nextNode;
}
}
int searchStudents(linkedList LinkedList, student findStudent){
node findStudentNode = createNode(findStudent);
node currentNode = LinkedList->head;
while(currentNode->data != findStudentNode->data){
currentNode = currentNode->nextStudent;
if(currentNode->nextStudent == NULL && currentNode->data != findStudentNode->data){
printf("%s\n", "Error: The student you're looking for was not found.");
return 0;
}
}
printf("%s\n", "The student is in the list!");
return 1;
}
void removeStudent(linkedList LinkedList, student studentToRemove){
node nodeToRemove = createNode(studentToRemove);
node currentNode = LinkedList->head;
node prevNode = NULL;
if(LinkedList->head == NULL && LinkedList->tail == NULL){
printf("%s\n", "Error: There are no nodes to remove");
}
else{
while(currentNode->data != nodeToRemove->data){
prevNode = currentNode;
currentNode = currentNode->nextStudent;
if(currentNode->nextStudent == NULL && currentNode->data != nodeToRemove->data){
printf("%s\n", "Error: The Student you were looking to remove was not found");
break;
}
}
if(prevNode == NULL){
if(currentNode->nextStudent == NULL){
LinkedList->head = NULL;
LinkedList->tail = NULL;
}
else{
LinkedList->head = currentNode->nextStudent;
currentNode->nextStudent = NULL;
}
}
else if(currentNode->nextStudent == NULL){
prevNode->nextStudent = NULL;
LinkedList->tail = prevNode;
}
else{
prevNode->nextStudent = currentNode->nextStudent;
currentNode->nextStudent = NULL;
}
}
}
void printIndivStudent(student StudentToPrint){
printf("First Name: %s, Last Name: %s, Age: %d, Date of Birth: %s\n",
StudentToPrint->fname,
StudentToPrint->lname,
StudentToPrint->age,
StudentToPrint->dob);
}
void printList(linkedList LinkedList){
node currentNode = LinkedList->head;
printf("%s:\n", "List of Students");
if(LinkedList->head == NULL && LinkedList->tail == NULL){
printf("%s\n", "There are no Students in this list.");
}
else{
while(currentNode->nextStudent != NULL){
student StudentToPrint = currentNode->data;
printIndivStudent(StudentToPrint);
currentNode = currentNode->nextStudent;
}
printIndivStudent(LinkedList->tail->data);
}
}
void main(){
student Student1 = createStudent("Sari", "Stissi", 20, "02/27/1998");
student Student2 = createStudent("Sara", "Salloum", 21, "03/24/1997");
student Student3 = createStudent("Bob", "Billy", 35, "06/23/1976");
student Student4 = createStudent("Jessica", "Star", 65, "10/05/1959");
student Student5 = createStudent("<NAME>", "<NAME>", 69, "06/06/6666");
linkedList FirstList = createList();
add_head(FirstList, Student1);
add_head(FirstList, Student3);
add_tail(FirstList, Student2);
add_after(FirstList, Student1, Student4);
searchStudents(FirstList, Student3);
searchStudents(FirstList, Student5);
add_after(FirstList, Student2, Student5);
searchStudents(FirstList, Student5);
removeStudent(FirstList, Student5);
searchStudents(FirstList, Student5);
printList(FirstList);
}
<file_sep>#<NAME>
#Assignment 3
#Worked with Laurence
from time import time
import threading
from random import randint
# Thread 1 is sender
# Thread 2 is receiver
class BooleanComp():
def __init__(self, startState):
#initialize the value
self._val = startState
def __equals__(self, otherThing):
#prints if two things are equal in comparison
return self._val == otherThing
def __notEqual__(self, otherThing):
#prints if two things are not equal in comparison
return self._val != otherThing
def changeValue(self, newVal):
self._val = newVal
#Variables needed for the sliding window
isFinished = BooleanComp(False)
windowSize = 5
timeoutBase = 5
actualTimeout = timeoutBase*1
randomStartVal = 0
randomEndVal = 50
queueDataTransfer = []
#add the data to the queue if successfully sent
#chaotically choose if the packet will be lost or not
def chaoticAddToQueue(data, qTarget=queueDataTransfer):
randomChange = randint(randomStartVal, randomEndVal)
writeToQueue = BooleanComp(True)
if randomChange == 0:
write.changeValue(False)
print("The Packet was chaotically lost.")
elif randomChange == 1:
data["checksum"] += 1
print("The checksum was increased.")
elif randomChange == 2:
data["checksum"]
print("The checksum was decreased.")
else:
print("There was no change in the sequence.", data["seq"])\
if writeToQueue == True:
qTarget.append(data)
def functionSort(data):
return data["seq"]
def receiverThread(lock):
print("The receiver thread has begun.")
currentData = {}
while isFinished == False:
currentFrame = 0
if len(queueDataTransfer) > 0:
lock.acquire()
while currentFrame < len(queueDataTransfer):
temp = queueDataTransfer[currentFrame]
if temp["checksum"] == len(temp["data"]) and temp["ack"] != True:
queueDataTransfer[currentFrame]["ack"] = true
currentFrame += 1
print("The data was received.\n Here's the current amount of data: ", len(currentData))
else:
del queueDataTransfer[currentFrame]
currentData[temp["seq"]] = temp
lock.release()
listOfData = []
for i in currentData.keys():
listOfData.append(currentData[i])
sortedList = listOfData.sort(key=functionSort)
print(listOfData,"\n",sortedList)
def senderThread(data, lock):
print("The sender thread has begun")
counter = 0
windowStart = 0
#below is a dict of dicts
#the format is [sequence: {target: <frame>, timeout: <timestamp>}]
buffer = []
while counter < len(data) or len(data) != 0:
lock.acquire()
if len(queueDataTransfer) < windowSize and windowStart <= counter < windowStart + windowSize and counter < len(data):
print("Adding to the transfer queue.")
chaoticAddToQueue(data[counter])
buffer.append({"target":data[x], "timeout":time()+actualTimeout})
counter += 1
lock.release()
for i in range(len(buffer)):
lock.acquire()
currentTime = time()
if buffer[i]["timeout"] <= currentTime:
print("The Packet timed out")
chaoticAddToQueue(buffer[i]["target"])
buffer[i]["timeout"] = currentTime + actualTimeout
lock.release()
lock.acquire()
lengthOfQueue = len(queueDataTransfer)
for queueDataIndex in range(len(queueDataTransfer)):
if queueDataTransfer[queueDataIndex]["ack"] == True:
tempPop = queueDataTransfer.pop(queueDataIndex)
for j in range(len(buffer)):
if buffer[y]["target"]["seq"] == tem["seq"]:
if temp["seq"] == windowStart:
windowStart += 1
buffer.pop(y)
break
if lengthOfQueue != len(queueDataTransfer):
break
lock.release()
isFinished.changeValue(True)
def packagingData(fileName):
formatedData = []
with open(fileName, "r") as openFile:
lineRead = openFile.readlines()
for i in range(len(lineRead)):
formatedData.append({"seq": i, "kind": "data", "ack": False, "data": lineRead[i], "checksum": len(lineRead[i])})
return formatedData
|
cab0ecd0b213a09efeb164ac6f1e999205bd90cb
|
[
"Markdown",
"C",
"Python"
] | 3
|
Markdown
|
sestissi16/NetworksAndNetworkingProjects
|
77812e29df0b76377775907e44ae4eeb5a109614
|
3e1c5a8129c19e757b2b419b87806abbdd59d39d
|
refs/heads/master
|
<repo_name>hehlinge42/machine_learning_bootcamp<file_sep>/day03/ex05/reg_log_loss.py
import numpy as np
from sigmoid import sigmoid_
import math
def sigmoid(theta, x):
return 1/(1 + math.exp(-1*theta.T.dot(x)))
def regularization(theta, lambda_):
"""Computes the regularization term of a non-empty numpy.ndarray, with a
for-loop. Args:
theta: has to be a numpy.ndarray, a vector of dimension n * 1.
lambda: has to be a float.
Returns:
The regularization term of theta.
None if theta is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if (not isinstance(lambda_, (int, float))) or theta.ndim != 1:
print(type(theta))
return None
return lambda_ * (theta.dot(theta.T))
def reg_log_loss_(y_true, y_pred, m, theta, lambda_, eps= 1e-15):
"""
Compute the logistic loss value.
Args:
y_true: a scalar or a numpy ndarray for the correct labels
y_pred: a scalar or a numpy ndarray for the predicted labels
m: the length of y_true (should also be the length of y_pred)
lambda_: a float for the regularization parameter
eps: epsilon (default=1e-15)
Returns:
The logistic loss value as a float.
None on any error.
Raises:
This function should not raise any Exception.
"""
#log1 = np.dot(-y_true, np.log(y_pred + eps))
#log2 = np.dot(1 - y_true, 1 - np.log(y_pred + eps))
#reg = regularization(theta, lambda_)
#return ((log1 - log2) / m) + reg
s = 0
for i in range(m):
s += -y_true[i]*np.log(y_pred[i] + eps) - (1-y_true[i])*np.log(1-y_pred[i] + eps)
s += np.dot(lambda_ * theta, theta)
s /= m
return s
# Test n.1
x_new = np.arange(1, 13).reshape((3, 4))
y_true = np.array([1, 0, 1])
theta = np.array([-1.5, 2.3, 1.4, 0.7])
y_pred = sigmoid_(np.dot(x_new, theta))
m = len(y_true)
print(reg_log_loss_(y_true, y_pred, m, theta, 0.0))
# 7.233346147374828
# Test n.2
x_new = np.arange(1, 13).reshape((3, 4))
y_true = np.array([1, 0, 1])
theta = np.array([-1.5, 2.3, 1.4, 0.7])
y_pred = sigmoid_(np.dot(x_new, theta))
m = len(y_true)
print(reg_log_loss_(y_true, y_pred, m, theta, 0.5))
# 8.898346147374827
# Test n.3
x_new = np.arange(1, 13).reshape((3, 4))
y_true = np.array([1, 0, 1])
theta = np.array([-1.5, 2.3, 1.4, 0.7])
y_pred = sigmoid_(np.dot(x_new, theta))
m = len(y_true)
print(reg_log_loss_(y_true, y_pred, m, theta, 1))
# 10.563346147374826
# Test n.4
x_new = np.arange(1, 13).reshape((3, 4))
y_true = np.array([1, 0, 1])
theta = np.array([-5.2, 2.3, -1.4, 8.9])
y_pred = sigmoid_(np.dot(x_new, theta))
m = len(y_true)
print(reg_log_loss_(y_true, y_pred, m, theta, 1))
# 49.346258798303566
# Test n.5
x_new = np.arange(1, 13).reshape((3, 4))
y_true = np.array([1, 0, 1])
theta = np.array([-5.2, 2.3, -1.4, 8.9])
y_pred = sigmoid_(np.dot(x_new, theta))
m = len(y_true)
print(reg_log_loss_(y_true, y_pred, m, theta, 0.3))
# 22.86292546497024
# Test n.6
x_new = np.arange(1, 13).reshape((3, 4))
y_true = np.array([1, 0, 1])
theta = np.array([-5.2, 2.3, -1.4, 8.9])
y_pred = sigmoid_(np.dot(x_new, theta))
m = len(y_true)
print(reg_log_loss_(y_true, y_pred, m, theta, 0.9))
# 45.56292546497025
<file_sep>/day01/ex02/fit.py
import numpy as np
def predict_(theta, X):
"""
Description:
Prediction of output using the hypothesis function (linear model).
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Returns:
pred: numpy.ndarray, a vector of dimension (number of the training
examples,1).
None if X does not match the dimension of theta.
Raises:
This function should not raise any Exception.
"""
if theta is None or X is None or theta.ndim != 2 or X.ndim != 2 or theta.shape[1] != 1 or X.shape[1] + 1 != theta.shape[0]:
print("Incompatible dimension match between X and theta.")
return None
X = np.insert(X, 0, 1., axis=1)
return X.dot(theta)
def fit_(theta, X, Y, alpha = 0.001, n_cycle = 10000):
"""
Description:
Performs a fit of Y(output) with respect to X.
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Y: has to be a numpy.ndarray, a vector of dimension (number of
training examples, 1).
Returns:
new_theta: numpy.ndarray, a vector of dimension (number of the
features +1,1).
None if there is a matching dimension problem.
Raises:
This function should not raise any Exception.
"""
if theta.ndim != 2 or X.ndim != 2 or theta.shape[1] != 1 or X.shape[1] + 1 != theta.shape[0] or Y.shape[0] != X.shape[0]:
print("Incompatible dimension match between X and theta.")
return None
m = X.shape[0]
X = np.insert(X, 0, 1., axis=1)
for i in range(n_cycle):
hypothesis = X.dot(theta)
parenthesis = np.subtract(hypothesis, Y)
sigma = np.sum(np.dot(X.T, parenthesis),keepdims=True, axis=1)
theta = theta - (alpha / m) * sigma
return theta
X1 = np.array([[0.], [1.], [2.], [3.], [4.]])
Y1 = np.array([[2.], [6.], [10.], [14.], [18.]])
theta1 = np.array([[1.], [1.]])
theta1 = fit_(theta1, X1, Y1, alpha = 0.01, n_cycle=2000)
print(theta1)
print(predict_(theta1, X1))
X2 = np.array([[0.2, 2., 20.], [0.4, 4., 40.], [0.6, 6., 60.], [0.8, 8., 80.]])
Y2 = np.array([[19.6], [-2.8], [-25.2], [-47.6]])
theta2 = np.array([[42.], [1.], [1.], [1.]])
theta2 = fit_(theta2, X2, Y2, alpha = 0.0005, n_cycle=42000)
print(theta2)
print(predict_(theta2, X2))
<file_sep>/day03/ex12/polynomial_feat.py
import numpy as np
def polynomialFeatures(x, degree=2, interaction_only= False, include_bias=True):
"""Computes the polynomial features (including interraction terms) of a
non-empty numpy.ndarray.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The polynomial features matrix, a numpy.ndarray.
None if x is a non-empty numpy.ndarray.
Raises:
This function shouldn't raise any Exception.
"""
X_h = X
if include_bias is True:
X_h = np.insert(X_h, 0, 1., axis=1)
i = 1
while i < degree:
i += 1
j = 0
while j < X.shape[1]:
X_h = np.append(X_h, np.power(X[:,j], i).reshape(X_h.shape[0], 1), axis=1)
#if j + 1 < X.shape[1]:
# X_h = np.append(X_h, np.dot(X[:,j], X[:,j + 1]), axis=1)
j += 1
return X_h
X = np.array([[0, 1], [2, 3], [4, 5]])
print(polynomialFeatures(X))
#[ 1., 0., 1., 0. , 0. , 1. ],
#[ 1., 2., 3., 4. , 6. , 9. ],
#[ 1., 4., 5., 16., 20., 25.]
print(polynomialFeatures(X, 3))
#[ 1., 0., 1., 0. , 0. , 1. , 0. , 0. , 0. , 1.],
#[ 1., 2., 3., 4. , 6. , 9. , 8. , 12., 18. , 27.],
#[ 1., 4., 5., 16., 20., 25., 64., 80., 100., 125.]
print(polynomialFeatures(X, 3, interaction_only=True, include_bias=False))
#[ 0., 1., 0. ],
#[ 2., 3., 6. ],
#[ 4., 5., 20.]
<file_sep>/day03/ex07/vec_reg_logistic_grad.py
import numpy as np
def sigmoid_(x, k=1, x0=0):
"""
Compute the sigmoid of a scalar or a list.
Args:
x: a scalar or list
Returns:
The sigmoid value as a scalar or list.
None on any error.
Raises:
This function should not raise any Exception.
"""
return (1 / (1 + np.exp((-k)*(x - x0))))
def vec_reg_logistic_grad(x, y, theta, lambda_):
"""
Computes the regularized linear gradient of three non-empty
numpy.ndarray, without any for-loop. The three arrays must have compatible
dimensions.
Args:
y: has to be a numpy.ndarray, a vector of dimension m * 1.
x: has to be a numpy.ndarray, a matrix of dimesion m * n.
theta: has to be a numpy.ndarray, a vector of dimension n * 1.
alpha: has to be a float.
lambda_: has to be a float.
Returns:
A numpy.ndarray, a vector of dimension n * 1, containing the results of
the formula for all j.
None if y, x, or theta are empty numpy.ndarray.
None if y, x or theta does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
return (np.dot(x.T, (sigmoid_(np.dot(x, theta)) - y)) + lambda_ * theta) / x.shape[0]
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([1,0,1,1,1,0,0])
Z = np.array([1.2,0.5,-0.32])
print(vec_reg_logistic_grad(X, Y, Z, 1))
#array([ 6.69780169, -0.33235792, 2.71787754])
print(vec_reg_logistic_grad(X, Y, Z, 0.5))
#array([ 6.61208741, -0.3680722, 2.74073468])
print(vec_reg_logistic_grad(X, Y, Z, 0.0))
#array([ 6.52637312, -0.40378649, 2.76359183])
<file_sep>/day02/ex01/log_loss.py
import numpy as np
def sigmoid_(x, k=1, x0=0):
"""
Compute the sigmoid of a scalar or a list.
Args:
x: a scalar or list
Returns:
The sigmoid value as a scalar or list.
None on any error.
Raises:
This function should not raise any Exception.
"""
if isinstance(x, (int, float, list)) == False and type(x) != 'numpy.ndarray':
print("Invalid type")
return None
x = np.asarray(x)
return (1 / (1 + np.exp((-k)*(x - x0))))
def log_loss_(y_true, y_pred, m, eps=1e-15):
"""
Compute the logistic loss value.
Args:
y_true: a scalar or a list for the correct labels
y_pred: a scalar or a list for the predicted labels
m: the length of y_true (should also be the length of y_pred)
eps: epsilon (default=1e-15)
Returns:
The logistic loss value as a float.
None on any error.
Raises:
This function should not raise any Exception.
"""
if isinstance(y_true, (int, float)) == True:
y_true = [float(y_true)]
if isinstance(y_pred, (int, float)) == True:
y_pred = [float(y_pred)]
y_true = np.array(y_true)
y_pred = np.array(y_pred)
if y_true.shape != y_pred.shape or y_true.shape[0] != m:
print(y_true.shape)
print(y_pred.shape)
print(m)
return None
return ((-1 / m) * (y_true * np.log(y_pred + eps) + (1 - y_true) * np.log(1 - y_pred + eps))).sum()
# Test n.1
x = 4
y_true = 1
theta = 0.5
y_pred = sigmoid_(x * theta)
m = 1 # length of y_true is 1
print(log_loss_(y_true, y_pred, m))
# 0.12692801104297152
# Test n.2
x = [1, 2, 3, 4]
y_true = 0
theta = [-1.5, 2.3, 1.4, 0.7]
x_dot_theta = sum([a*b for a, b in zip(x, theta)])
y_pred = sigmoid_(x_dot_theta)
m = 1
print(log_loss_(y_true, y_pred, m))
# 10.100041078687479
# Test n.3
x_new = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
y_true = [1, 0, 1]
theta = [-1.5, 2.3, 1.4, 0.7]
x_dot_theta = []
for i in range(len(x_new)):
my_sum = 0
for j in range(len(x_new[i])):
my_sum += x_new[i][j] * theta[j]
x_dot_theta.append(my_sum)
y_pred = sigmoid_(x_dot_theta)
m = len(y_true)
print(log_loss_(y_true, y_pred, m))
# 7.233346147374828
<file_sep>/day00/ex00/sum.py
import numpy as np
def sum_(x, f):
"""Computes the sum of a non-empty numpy.ndarray onto wich a function is
applied element-wise, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
f: has to be a function, a function to apply element-wise to the
vector.
Returns:
The sum as a float.
None if x is an empty numpy.ndarray or if f is not a valid function.
Raises:
This function should not raise any Exception.
"""
if x.size == 0:
return None
summed = 0.0
for elem in x:
try:
summed += f(elem)
except:
return None
return summed
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(sum_(X, lambda x: x))
print(sum_(X, lambda x: x**2))
<file_sep>/day03/ex05/sigmoid.py
import numpy as np
def sigmoid_(x, k=1, x0=0):
"""
Compute the sigmoid of a scalar or a list.
Args:
x: a scalar or list
Returns:
The sigmoid value as a scalar or list.
None on any error.
Raises:
This function should not raise any Exception.
"""
return (1 / (1 + np.exp((-k)*(x - x0))))
<file_sep>/day00/ex12/vec_gradient.py
import numpy as np
def vec_gradient(x, y, theta):
"""Computes a gradient vector from three non-empty numpy.ndarray,
without any for-loop. The three arrays must have the compatible dimensions.
Args:
x: has to be an numpy.ndarray, a matrice of dimension m * n.
y: has to be an numpy.ndarray, a vector of dimension m * 1.
theta: has to be an numpy.ndarray, a vector n * 1.
Returns:
The gradient as a numpy.ndarray, a vector of dimensions n * 1, containg
the result of the formula for all j.
None if x, y, or theta are empty numpy.ndarray.
None if x, y and theta do not have compatible dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or theta.size == 0 or x.shape[1] != theta.shape[0] or y.shape[0] != x.shape[0] or theta.ndim != 1 or y.ndim != 1:
return None
parenthesis = np.subtract(x.dot(theta), y)
coef = x.dot(1/x.shape[0])
return np.transpose(coef).dot(parenthesis)
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
Z = np.array([3,0.5,-6])
print(vec_gradient(X, Y, Z))
W = np.array([0,0,0])
print(vec_gradient(X, Y, W))
print(vec_gradient(X, X.dot(Z), Z))
<file_sep>/day02/ex00/sigmoid.py
import numpy as np
def sigmoid_(x, k=1, x0=0):
"""
Compute the sigmoid of a scalar or a list.
Args:
x: a scalar or list
Returns:
The sigmoid value as a scalar or list.
None on any error.
Raises:
This function should not raise any Exception.
"""
if isinstance(x, (int, float, list)) == False:
return None
x = np.asarray(x)
return (1 / (1 + np.exp((-k)*(x - x0))))
x = -4
print(sigmoid_(x))
# 0.01798620996209156
x = 2
print(sigmoid_(x))
# 0.8807970779778823
x = [-4, 2, 0]
print(sigmoid_(x))
# [0.01798620996209156, 0.8807970779778823, 0.5]
<file_sep>/day04/ex02/information_gain.py
import numpy as np
from math import log
def entropy(array):
"""
Computes the Shannon Entropy of a non-empty numpy.ndarray
:param numpy.ndarray array:
:return float: shannon's entropy as a float or None if input is not a
non-empty numpy.ndarray
"""
if not isinstance(array, np.ndarray):
return None
n_lab = len(array)
if n_lab <= 0:
return None
values, counts = np.unique(array, return_counts=True)
probs = counts / n_lab
n_classes = np.count_nonzero(probs)
if n_classes <= 1:
return None
ent = 0.0
# Compute entropy
base = 2
for i in probs:
ent -= i * log(i, base)
return ent
def gini(array):
"""
Computes the gini impurity of a non-empty numpy.ndarray
:param numpy.ndarray array:
:return float: gini_impurity as a float or None if input is not a
non-empty numpy.ndarray
"""
if not isinstance(array, np.ndarray):
return None
n_lab = len(array)
if n_lab <= 0:
return None
values, counts = np.unique(array, return_counts=True)
probs = counts / n_lab
n_classes = np.count_nonzero(probs)
if n_classes <= 1:
return None
gini = 0.0
for i in probs:
gini += i ** 2
return 1 - gini
def information_gain(array_source, array_children_list, criterion='gini'):
"""
Computes the information gain between the first and second array using
the criterion ('gini' or 'entropy')
:param numpy.ndarray array_source:
:param list array_children_list: list of numpy.ndarray
:param str criterion: Should be in ['gini', 'entropy']
:return float: Shannon entropy as a float or None if input is not a
non-empty numpy.ndarray or None if invalid input
"""
if criterion not in ('gini', 'entropy'):
return None
if criterion == 'gini':
s0 = gini(array_source)
s1 = gini(array_children_list)
else:
s0 = entropy(array_source)
s1 = entropy(array_children_list)
if s1 is None or s0 is None:
return None
return s0 - s1
array_source = np.array([])
array_children = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
print("Information gain between {0} and {1} is {2} with criterion 'gini' and {3} with criterion 'entropy'".format(array_source, array_children, information_gain(array_source, array_children, 'gini'), information_gain(array_source, array_children, 'entropy')))
array_source = ['a' 'a' 'b' 'b']
array_children = {1, 2}
print("Information gain between {0} and {1} is {2} with criterion 'gini' and {3} with criterion 'entropy'".format(array_source, array_children, information_gain(array_source, array_children, 'gini'), information_gain(array_source, array_children, 'entropy')))
array_source = np.array([0., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
array_children = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
print("Information gain between {0} and {1} is {2} with criterion 'gini' and {3} with criterion 'entropy'".format(array_source, array_children, information_gain(array_source, array_children, 'gini'), information_gain(array_source, array_children, 'entropy')))
array_source = np.array(['0', '0', '1', '0', 'bob', '1'])
array_children = np.array([0, 0, 1, 0, 2, 1])
print("Information gain between {0} and {1} is {2} with criterion 'gini' and {3} with criterion 'entropy'".format(array_source, array_children, information_gain(array_source, array_children, 'gini'), information_gain(array_source, array_children, 'entropy')))
<file_sep>/day03/ex11/minmax.py
import numpy as np
def minmax(x):
"""Computes the normalized version of a non-empty numpy.ndarray using
the min-max standardization.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
x' as a numpy.ndarray.
None if x is a non-empty numpy.ndarray.
Raises:
This function shouldn't raise any Exception.
"""
return (x - np.min(x)) / (np.max(x) - np.min(x))
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(minmax(X))
#array([0.58333333, 1. , 0.33333333, 0.77777778, 0.91666667, 0.66666667, 0. ])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(minmax(Y))
#array([0.63636364, 1. , 0.18181818, 0.72727273, 0.93939394, 0.6969697 , 0. ])
<file_sep>/day02/ex05/log_reg.py
import numpy as np
import pandas as pd
class LogisticRegressionBatchGd:
def __init__(self, alpha=0.001, max_iter=1000, verbose=True, learning_rate='constant'):
self.alpha = alpha
self.max_iter = max_iter
self.verbose = verbose
self.learning_rate = learning_rate # can be 'constant' or 'invscaling'
self.threshold = 0.5
self.thetas = []
self.costs = []
def __sigmoid(self, x, k=1, x0=0):
"""
Compute the sigmoid of a scalar or a list.
Args:
x: a scalar or list
Returns:
The sigmoid value as a scalar or list.
None on any error.
Raises:
This function should not raise any Exception.
"""
return (1 / (1 + np.exp((-k)*(x - x0))))
def __log_loss(self, y_true, y_pred, eps=1e-15):
"""
Compute the logistic loss value.
Args:
y_true: a scalar or a list for the correct labels
y_pred: a scalar or a list for the predicted labels
m: the length of y_true (should also be the length of y_pred)
eps: epsilon (default=1e-15)
Returns:
The logistic loss value as a float.
None on any error.
Raises:
This function should not raise any Exception.
"""
m = y_true.shape[0]
if y_true.shape != y_pred.shape or y_true.shape[0] != m:
return None
return ((-1 / m) * (y_true * np.log(y_pred + eps) + (1 - y_true) * np.log(1 - y_pred + eps))).sum()
def __log_gradient(self, x, y_true, y_pred):
"""
Compute the gradient.
Args:
x: a list or a matrix (list of lists) for the samples
y_true: a scalar or a list for the correct labels
y_pred: a scalar or a list for the predicted labels
Returns:
The gradient as a scalar or a list of the width of x.
None on any error.
Raises:
This function should not raise any Exception.
"""
x = np.array(x)
if x.ndim == 1:
x = np.array(x).reshape(1, len(x))
return (y_pred - y_true).dot(x)
def cost(self, x_train, y_train):
"""
Appends the result of the cost function computed with
the last elem of the thetas list.
Arg:
x_train: a 1d or 2d numpy ndarray for the samples
y_train: a scalar or a numpy ndarray for the correct labels
Returns:
Mean accuracy of self.predict(x_train) with respect to y_true
None on any error.
Raises:
This method should not raise any Exception.
"""
y_predict = self.predict(x_train)
self.costs.append(self.__log_loss(y_train, y_predict))
def fit(self, x_train, y_train):
"""
Fit the model according to the given training data.
Args:
x_train: a 1d or 2d numpy ndarray for the samples
y_train: a scalar or a numpy ndarray for the correct labels
Returns:
self : object
None on any error.
Raises:
This method should not raise any Exception.
"""
m = x_train.shape[0] # Nb of training examples
n = x_train.shape[1] # Nb of features
gap = int(self.max_iter / 10)
self.thetas = np.zeros(n)
self.cost(x_train, y_train)
for i in range(self.max_iter):
hypothesis = self.__sigmoid(x_train.dot(self.thetas))
gradient = self.__log_gradient(x_train, y_train, hypothesis)
self.thetas = (self.thetas - (self.alpha / m) * gradient)
self.cost(x_train, y_train)
return self
def predict(self, x_train):
"""
Predict class labels for samples in x_train.
Arg:
x_train: a 1d or 2d numpy ndarray for the samples
Returns:
y_pred, the predicted class label per sample.
None on any error.
Raises:
This method should not raise any Exception.
"""
return self.__sigmoid(x_train.dot(self.thetas)) >= self.threshold
def score(self, x_train, y_train):
"""
Returns the mean accuracy on the given test data and labels.
Arg:
x_train: a 1d or 2d numpy ndarray for the samples
y_train: a scalar or a numpy ndarray for the correct labels
Returns:
Mean accuracy of self.predict(x_train) with respect to y_true
None on any error.
Raises:
This method should not raise any Exception.
"""
y_pred = self.predict(x_train)
print(y_pred)
print(y_train)
return (y_pred == y_train).mean()
# To download the file, please click on the link provided in the 'resource_links.txt'
# And change the path of the read_csv function accordingly
df_train = pd.read_csv('../../../dataset/train_dataset_clean.csv', delimiter=',', header=None, index_col=False)
x_train, y_train = np.array(df_train.iloc[:, 1:82]), df_train.iloc[:, 0]
df_test = pd.read_csv('../../../dataset/test_dataset_clean.csv', delimiter=',', header=None,
index_col=False)
x_test, y_test = np.array(df_test.iloc[:, 1:82]), df_test.iloc[:, 0]
# We set our model with our hyperparameters : alpha, max_iter, verbose and learning_rate
model = LogisticRegressionBatchGd(alpha=0.01, max_iter=1500, verbose=True, learning_rate='constant')
# We fit our model to our dataset and display the score for the train and test datasets
model.fit(x_train, y_train)
print(f'Score on train dataset : {model.score(x_train, y_train)}')
y_pred = model.predict(x_test)
print(f'Score on test dataset : {(y_pred == y_test).mean()}')
<file_sep>/day01/ex00/pred.py
import numpy as np
def predict_(theta, X):
"""
Description:
Prediction of output using the hypothesis function (linear model).
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Returns:
pred: numpy.ndarray, a vector of dimension (number of the training
examples,1).
None if X does not match the dimension of theta.
Raises:
This function should not raise any Exception.
"""
if theta.ndim != 2 or X.ndim != 2 or theta.shape[1] != 1 or X.shape[1] + 1 != theta.shape[0]:
print("Incompatible dimension match between X and theta.")
return None
X = np.insert(X, 0, 1., axis=1)
return X.dot(theta)
X1 = np.array([[0.], [1.], [2.], [3.], [4.]])
theta1 = np.array([[2.], [4.]])
print(predict_(theta1, X1))
X2 = np.array([[1], [2], [3], [5], [8]])
theta2 = np.array([[2.]])
print(predict_(theta2, X2))
X3 = np.array([[0.2, 2., 20.], [0.4, 4., 40.], [0.6, 6., 60.], [0.8, 8.,
80.]])
theta3 = np.array([[0.05], [1.], [1.], [1.]])
print(predict_(theta3, X3))
<file_sep>/day02/ex08/recall.py
import numpy as np
import pandas as pd
def recall_score_(y_true, y_pred, pos_label=1):
"""
Compute the precision score.
Args:
y_true: a scalar or a numpy ndarray for the correct labels
y_pred: a scalar or a numpy ndarray for the predicted labels
pos_label: str or int, the class on which to report the
precision_score (default=1)
Returns:
The precision score as a float.
None on any error.
Raises:
This function should not raise any Exception.
"""
tp = ((y_pred == y_true) & (y_pred == pos_label)).sum()
fn = ((y_pred != y_true) & (y_pred != pos_label)).sum()
return tp / (tp + fn)
# Test n.1
y_pred = np.array([1, 1, 0, 1, 0, 0, 1, 1])
y_true = np.array([1, 0, 0, 1, 0, 1, 0, 0])
print(recall_score_(y_true, y_pred))
# 0.6666666666666666
# Test n.2
y_pred = np.array(['norminet', 'dog', 'norminet', 'norminet', 'dog', 'dog',
'dog', 'dog'])
y_true = np.array(['dog', 'dog', 'norminet', 'norminet', 'dog', 'norminet',
'dog', 'norminet'])
print(recall_score_(y_true, y_pred, pos_label='dog'))
# 0.75
# Test n.3
print(recall_score_(y_true, y_pred, pos_label='norminet'))
# 0.5
<file_sep>/day00/ex04/dot.py
import numpy as np
def dot(x, y):
"""Computes the dot product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have the same dimensions.
Args:
x: has to be an numpy.ndarray, a vector.
y: has to be an numpy.ndarray, a vector.
Returns:
The dot product of the two vectors as a float.
None if x or y are empty numpy.ndarray.
None if x and y does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or x.shape != y.shape:
return None
dot_product = 0.0
for xi, yi in zip(x, y):
dot_product += xi * yi
return dot_product
X = np.array([0, 15, -9, 7, 12, 3, -21])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(dot(X, Y))
print(dot(X, X))
print(dot(Y, Y))
<file_sep>/day01/ex06/normal_equation_model.py
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from mylinearregression import MyLinearRegression as MyLR
import matplotlib.pyplot as plt
def draw_regression(mylr, x_label="", y_label="", fig_title="", legend="model"):
mylr.fit_()
mylr.predict_()
fig, ax = plt.subplots() #renvoie une figure et des axes
ax.scatter(mylr.X, mylr.Y) #crée un diagramme de dispersion avec X et Y
ax.scatter(mylr.X, mylr.Y_hat, c="green")
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(fig_title)
plt.plot(mylr.X, mylr.Y_hat, "--", c="green", label="model")
fig.legend(loc="lower left")
plt.show()
plt.cla()
def draw_cost_function(mylr):
fig, ax = plt.subplots() #renvoie une figure et des axes
t0 = mylr.theta[0]
thetas_0 = [t0 - 20, t0 - 10, t0, t0 + 10, t0 + 20]
for theta_0 in thetas_0:
theta = np.linspace(-14, 4, 100).reshape(100, 1)
theta = np.insert(theta, 0, theta_0, axis=1)
y = np.array([])
for i in range(theta.shape[0]):
tmp_lr = MyLR(theta[i].reshape(2, 1), mylr.X, mylr.Y)
dot = tmp_lr.cost_()
y = np.append(y, dot)
plt.plot(theta[:,1], y)
plt.xlabel("Theta1")
plt.ylabel("Cost function J(Theta0, Theta1")
plt.title("Evolution of the cost function J in fuction of Theta0 for different values of Theta1")
plt.show()
plt.cla()
def draw_multi_regression(mylr):
#mylr.fit_()
mylr.predict_()
# Plot in function of age
fig, ax = plt.subplots()
ax.scatter(mylr.X[:,0], mylr.Y)
ax.scatter(mylr.X[:,0], mylr.Y_hat, c="blue")
plt.xlabel("Age")
plt.ylabel("Sell_price")
plt.title("")
fig.legend(loc="lower left")
plt.show()
plt.cla()
data = pd.read_csv("../resources/spacecraft_data.csv")
Y = np.array(data['Sell_price']).reshape(-1,1)
X = np.array(data[['Age','Thrust_power','Terameters']])
myLR_ne = MyLR([1., 1., 1., 1.], X, Y)
myLR_lgd = MyLR([1., 1., 1., 1.], X, Y)
myLR_lgd.fit_(alpha = 5e-5, n_cycle = 10000)
myLR_ne.normalequation_()
print(myLR_lgd.mse_())
print(myLR_ne.mse_())
draw_multi_regression(myLR_ne)
<file_sep>/day03/ex08/ridge_reg.py
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score
from mylinearregression import MyLinearRegression
class MyRidge(MyLinearRegression):
def __init__(self, theta, X, Y, lambda_=1.0):
MyLinearRegression.__init__(self, theta, X, Y)
self.lambda_ = lambda_
self.fit_x_to_h()
def fit_x_to_h(self, X=None):
if X is None:
self.X_h = np.insert(self.X_h, 2, np.power(self.X_h[:,2], 3), axis=1)
self.X_h = np.append(self.X_h, np.power(self.X_h[:,3].reshape(self.X_h.shape[0], 1), 2), axis=1)
else:
X = np.insert(X, 0, 1., axis=1)
X = np.insert(X, 2, np.power(X[:,2], 3), axis=1)
X = np.append(X, np.power(X[:,3].reshape(X.shape[0], 1), 2), axis=1)
return X
def fit_(self, lambda_=1.0, max_iter=1000, tol=0.001):
"""
Fit the linear model by performing Ridge regression (Tikhonov
regularization).
Args:
lambda: has to be a float. max_iter: has to be integer.
tol: has to be float.
Returns:
Nothing.
Raises:
This method should not raise any Exception.
"""
if (lambda_ != 1.0):
self.lam = lambda_
In = np.identity(self.X_h.shape[1])
In[0][0] = 0
parenthesis = self.X_h.transpose().dot(self.X_h) + self.lambda_ * In
transposed = np.linalg.inv(parenthesis)
self.theta = (transposed.dot(self.X_h.transpose())).dot(self.Y)
self.theta = self.theta.reshape(self.theta.size, 1)
def __str__(self):
strn = "theta = {0}\n".format(self.theta)
#strn += "Y_hat = {0}\n".format(self.Y_hat)
strn += "lambda = {0}\n".format(self.lambda_)
strn += "R2 = {0}\n".format(self.r2)
return strn
df_train = pd.read_csv('../resources/data.csv', delimiter=',', header=1, index_col=False)
x = np.array(df_train.iloc[:, 0:2])
y = np.array(df_train.iloc[:, 2])
kfold = KFold(3, True, 1)
lam = 1.0
for train, test in kfold.split(x):
x_train, x_test, y_train, y_test = x[train], x[test], y[train], y[test]
theta = np.array([0, 0, 0, 0, 0])
mr = MyRidge(theta, x_train, y_train, lam)
mr.predict_()
mr.fit_()
mr.predict_()
x_test = mr.fit_x_to_h(x_test)
mr.predict_(x_test, y_test)
mr.r2 = r2_score(mr.y_tests_true[-1], mr.y_tests_pred[-1])
print(str(mr))
lam += 25
<file_sep>/day02/ex04/vec_log_gradient.py
import numpy as np
def sigmoid_(x, k=1, x0=0):
"""
Compute the sigmoid of a scalar or a list.
Args:
x: a scalar or list
Returns:
The sigmoid value as a scalar or list.
None on any error.
Raises:
This function should not raise any Exception.
"""
if isinstance(x, (int, float, list)) == False and type(x) != 'numpy.ndarray':
print("Invalid type")
return None
x = np.asarray(x)
return (1 / (1 + np.exp((-k)*(x - x0))))
def log_gradient_(x, y_true, y_pred):
"""
Compute the gradient.
Args:
x: a list or a matrix (list of lists) for the samples
y_true: a scalar or a list for the correct labels
y_pred: a scalar or a list for the predicted labels
Returns:
The gradient as a scalar or a list of the width of x.
None on any error.
Raises:
This function should not raise any Exception.
"""
if isinstance(y_true, (int, float)) == True:
y_true = [float(y_true)]
if isinstance(y_pred, (int, float)) == True:
y_pred = [float(y_pred)]
if isinstance(x, (int, float)) == True:
x = [float(x)]
y_true = np.array(y_true)
y_pred = np.array(y_pred)
x = np.array(x)
if x.ndim == 1:
x = np.array(x).reshape(1, len(x))
return (y_pred - y_true).dot(x)
# Test n.1
x = [1, 4.2] # 1 represent the intercept
y_true = 1
theta = [0.5, -0.5]
x_dot_theta = sum([a*b for a, b in zip(x, theta)])
#print(x_dot_theta)
y_pred = sigmoid_(x_dot_theta)
#print(x)
#print(y_pred)
#print(y_true)
print(log_gradient_(x, y_pred, y_true))
# [0.8320183851339245, 3.494477217562483]
# Test n.2
x = [1, -0.5, 2.3, -1.5, 3.2]
y_true = 0
theta = [0.5, -0.5, 1.2, -1.2, 2.3]
x_dot_theta = sum([a*b for a, b in zip(x, theta)])
y_pred = sigmoid_(x_dot_theta)
print(log_gradient_(x, y_true, y_pred))
# [0.99999685596372, -0.49999842798186, 2.299992768716556, -1.4999952839455801, 3.1999899390839044]
# Test n.3
x_new = [[1, 2, 3, 4, 5], [1, 6, 7, 8, 9], [1, 10, 11, 12, 13]]
# first column of x_new are intercept values initialized to 1
y_true = [1, 0, 1]
theta = [0.5, -0.5, 1.2, -1.2, 2.3]
x_new_dot_theta = []
for i in range(len(x_new)):
my_sum = 0
for j in range(len(x_new[i])):
my_sum += x_new[i][j] * theta[j]
x_new_dot_theta.append(my_sum)
y_pred = sigmoid_(x_new_dot_theta)
print(log_gradient_(x_new, y_true, y_pred))
# [0.9999445100449934, 5.999888854245219, 6.999833364290213, 7.999777874335206, 8.999722384380199]
<file_sep>/day02/ex06/accuracy.py
import numpy as np
import pandas as pd
def accuracy_score_(y_true, y_pred):
"""
Compute the accuracy score.
Args:
y_true: a scalar or a numpy ndarray for the correct labels
y_pred: a scalar or a numpy ndarray for the predicted labels
Returns:
The accuracy score as a float.
None on any error.
Raises:
This function should not raise any Exception.
"""
return (y_pred == y_true).mean()
# Test n.1
y_pred = np.array([1, 1, 0, 1, 0, 0, 1, 1])
y_true = np.array([1, 0, 0, 1, 0, 1, 0, 0])
print(accuracy_score_(y_true, y_pred))
# 0.5
# Test n.2
y_pred = np.array(['norminet', 'dog', 'norminet', 'norminet', 'dog', 'dog',
'dog', 'dog'])
y_true = np.array(['dog', 'dog', 'norminet', 'norminet', 'dog', 'norminet',
'dog', 'norminet'])
print(accuracy_score_(y_true, y_pred))
# 0.625
<file_sep>/day00/ex06/mat_mat_prod.py
import numpy as np
def dot(x, y):
"""Computes the dot product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have the same dimensions.
Args:
x: has to be an numpy.ndarray, a vector.
y: has to be an numpy.ndarray, a vector.
Returns:
The dot product of the two vectors as a float.
None if x or y are empty numpy.ndarray.
None if x and y does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or x.size != y.size:
return None
dot_product = 0.0
for xi, yi in zip(x, y):
dot_product += xi * yi
return dot_product
def mat_mat_prod(x, y):
"""Computes the product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have compatible dimensions.
Args:
x: has to be an numpy.ndarray, a matrix of dimension m * n.
y: has to be an numpy.ndarray, a vector of dimension n * p.
Returns:
The product of the matrices as a matrix of dimension m * p.
None if x or y are empty numpy.ndarray.
None if x and y does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
if x.shape[1] != y.shape[0]:
return None
ret = np.array([])
for line in x:
for column in y.T:
dot_prod = dot(line, column)
ret = np.append(ret, dot_prod)
return ret.reshape(x.shape[0], y.shape[1])
W = np.array([
[ -8, 8, -6, 14, 14, -9, -4],
[ 2, -11, -2, -11, 14, -2, 14],
[-13, -2, -5, 3, -8, -4, 13],
[ 2, 13, -14, -15, -14, -15, 13],
[ 2, -1, 12, 3, -7, -3, -6]])
Z = np.array([
[ -6, -1, -8, 7, -8],
[ 7, 4, 0, -10, -10],
[ 7, -13, 2, 2, -11],
[ 3, 14, 7, 7, -4],
[ -1, -3, -8, -4, -14],
[ 9, -14, 9, 12, -7],
[ -9, -4, -10, -3, 6]])
print(mat_mat_prod(W, Z))
print(mat_mat_prod(Z,W))
<file_sep>/day00/ex10/vec_linear_mse.py
import numpy as np
def vec_linear_mse(x, y, theta):
"""Computes the mean squared error of three non-empty numpy.ndarray,
without any for-loop. The three arrays must have compatible dimensions.
Args:
y: has to be an numpy.ndarray, a vector of dimension m * 1.
x: has to be an numpy.ndarray, a matrix of dimesion m * n.
theta: has to be an numpy.ndarray, a vector of dimension n * 1.
Returns:
The mean squared error as a float.
None if y, x, or theta are empty numpy.ndarray.
None if y, x or theta does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or theta.size == 0 or x.shape[1] != theta.shape[0] or y.shape[0] != x.shape[0] or theta.ndim != 1 or y.ndim != 1:
return None
xtheta = x.dot(theta)
xtheta = np.subtract(xtheta, y)
return xtheta.dot(xtheta) / x.shape[0]
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
Z = np.array([3,0.5,-6])
print(vec_linear_mse(X, Y, Z))
W = np.array([0,0,0])
print(vec_linear_mse(X, Y, W))
<file_sep>/day01/ex05/mylinearregression.py
import numpy as np
class MyLinearRegression():
"""
Description:
My personnal linear regression class to fit like a boss.
"""
def __init__(self, theta, X, Y):
"""
Description:
generator of the class, initialize self.
Args:
theta: has to be a list or a numpy array, it is a vector of
dimension (number of features + 1, 1).
Raises:
This method should noot raise any Exception.
"""
self.theta = np.asarray(theta).reshape(len(theta), 1)
self.X = np.asarray(X)
self.X_with1 = np.insert(self.X, 0, 1., axis=1)
self.Y = np.asarray(Y)
self.Y_hat = None
def predict_(self):
"""
Description:
Prediction of output using the hypothesis function (linear model).
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Returns:
pred: numpy.ndarray, a vector of dimension (number of the training
examples,1).
None if X does not match the dimension of theta.
Raises:
This function should not raise any Exception.
"""
if self.theta.ndim != 2 or self.X.ndim != 2 or self.theta.shape[1] != 1 or self.X.shape[1] + 1 != self.theta.shape[0]:
print('Shape of x: {0}'.format(self.X.shape))
print('Shape of theta: {0}'.format(self.theta.shape))
print("Incompatible dimension match between X and theta.")
return None
self.Y_hat = self.X_with1.dot(self.theta)
return self.Y_hat
def cost_elem_(self):
"""
Description:
Calculates all the elements 0.5*M*(y_pred - y)^2 of the cost
function.
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Returns:
J_elem: numpy.ndarray, a vector of dimension (number of the training
examples,1).
None if there is a dimension matching problem between X, Y or theta.
Raises:
This function should not raise any Exception.
"""
self.Y_hat = self.predict_()
if self.Y_hat is None:
return None
self.cost_elem = ((self.Y_hat - self.Y)**2)/(2*self.X.shape[0])
return self.cost_elem
def cost_(self):
"""
Description:
Calculates the value of cost function.
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a vector of dimension (number of
training examples, number of features).
Returns:
J_value : has to be a float.
None if X does not match the dimension of theta.
Raises:
This function should not raise any Exception.
"""
costs = self.cost_elem_()
if costs is None:
return None
return costs.sum()
def fit_(self, alpha = 0.0001, n_cycle = 10000):
"""
Description:
Performs a fit of Y(output) with respect to X.
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Y: has to be a numpy.ndarray, a vector of dimension (number of
training examples, 1).
Returns:
new_theta: numpy.ndarray, a vector of dimension (number of the
features +1,1).
None if there is a matching dimension problem.
Raises:
This function should not raise any Exception.
"""
if self.theta.ndim != 2 or self.X.ndim != 2 or self.theta.shape[1] != 1 or self.X.shape[1] + 1 != self.theta.shape[0] or self.Y.shape[0] != self.X.shape[0]:
print("Incompatible dimension match between X and theta.")
return None
m = self.X.shape[0]
for i in range(n_cycle):
hypothesis = self.X_with1.dot(self.theta)
parenthesis = np.subtract(hypothesis, self.Y)
sigma = np.sum(np.dot(self.X_with1.T, parenthesis),keepdims=True, axis=1)
self.theta = self.theta - (alpha / m) * sigma
return self.theta
def mse_(self):
self.predict_()
mse = ((self.Y - self.Y_hat) ** 2).sum()
return mse/self.X.shape[0]
<file_sep>/day04/ex00/entropy.py
import numpy as np
from math import log
def entropy(array):
"""
Computes the Shannon Entropy of a non-empty numpy.ndarray
:param numpy.ndarray array:
:return float: shannon's entropy as a float or None if input is not a
non-empty numpy.ndarray
"""
if not isinstance(array, np.ndarray):
return None
n_lab = len(array)
if n_lab <= 1:
return 0.0
values, counts = np.unique(array, return_counts=True)
probs = counts / n_lab
n_classes = np.count_nonzero(probs)
if n_classes <= 1:
return 0.0
ent = 0.0
# Compute entropy
base = 2
for i in probs:
ent -= i * log(i, base)
return ent
array = []
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = {1, 2}
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = "bob"
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array([0, 0, 0, 0, 0, 0])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array([6])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array(['a', 'a', 'b', 'b'])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array(['0', '0', '1', '0', 'bob', '1'])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array([0, 0, 1, 0, 2, 1])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array(['0', 'bob', '1'])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array([0., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
array = np.array([0., 1., 1.])
ent = entropy(array)
print("Shannon entropy for {0} is {1}".format(array, ent))
<file_sep>/day03/ex04/vec_reg_linear_grad.py
import numpy as np
def vec_reg_linear_grad(x, y, theta, lambda_):
"""
Computes the regularized linear gradient of three non-empty
numpy.ndarray, without any for-loop. The three arrays must have compatible
dimensions.
Args:
y: has to be a numpy.ndarray, a vector of dimension m * 1.
x: has to be a numpy.ndarray, a matrix of dimesion m * n.
theta: has to be a numpy.ndarray, a vector of dimension n * 1.
alpha: has to be a float.
lambda_: has to be a float.
Returns:
A numpy.ndarray, a vector of dimension n * 1, containing the results of
the formula for all j.
None if y, x, or theta are empty numpy.ndarray.
None if y, x or theta does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
return (np.dot(x.T, (np.dot(x, theta) - y)) + lambda_ * theta) / x.shape[0]
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
Z = np.array([3,10.5,-6])
print(vec_reg_linear_grad(X, Y, Z, 1))
#array([-192.64285714, 887.5, -679.57142857])
print(vec_reg_linear_grad(X, Y, Z, 0.5))
#array([-192.85714286, 886.75, -679.14285714])
print(vec_reg_linear_grad(X, Y, Z, 0.0))
#array([-193.07142857, 886., -678.71428571])
<file_sep>/day03/ex02/reg_mse.py
import numpy as np
def regularization(theta, lambda_):
"""Computes the regularization term of a non-empty numpy.ndarray, with a
for-loop. Args:
theta: has to be a numpy.ndarray, a vector of dimension n * 1.
lambda: has to be a float.
Returns:
The regularization term of theta.
None if theta is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if (not isinstance(lambda_, (int, float))) or theta.ndim != 1:
print(type(theta))
return None
return lambda_ * (theta.dot(theta.T))
def reg_mse(x, y, theta, lambda_):
"""Computes the regularized mean squared error of three non-empty
numpy.ndarray, without any for-loop. The three arrays must have compatible
dimensions.
Args:
y: has to be a numpy.ndarray, a vector of dimension m * 1.
x: has to be a numpy.ndarray, a matrix of dimesion m * n.
theta: has to be a numpy.ndarray, a vector of dimension n * 1.
lambda: has to be a float.
Returns:
The mean squared error as a float.
None if y, x, or theta are empty numpy.ndarray.
None if y, x or theta does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
dot_term = (x.dot(theta) - y)
return (np.dot(dot_term.T, dot_term) + regularization(theta, lambda_)) / (x.shape[0])
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
Z = np.array([3,0.5,-6])
print(reg_mse(X, Y, Z, 0))
#2641.0
print(reg_mse(X, Y, Z, 0.1))
#2641.6464285714287
print(reg_mse(X, Y, Z, 0.5))
#2644.2321428571427
<file_sep>/day01/ex05/multi_linear_model.py
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from mylinearregression import MyLinearRegression as MyLR
import matplotlib.pyplot as plt
def draw_regression(mylr, x_label="", y_label="", fig_title="", legend="model"):
mylr.fit_()
mylr.predict_()
fig, ax = plt.subplots() #renvoie une figure et des axes
ax.scatter(mylr.X, mylr.Y) #crée un diagramme de dispersion avec X et Y
ax.scatter(mylr.X, mylr.Y_hat, c="green")
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.title(fig_title)
plt.plot(mylr.X, mylr.Y_hat, "--", c="green", label="model")
fig.legend(loc="lower left")
plt.show()
plt.cla()
def draw_cost_function(mylr):
fig, ax = plt.subplots() #renvoie une figure et des axes
t0 = mylr.theta[0]
thetas_0 = [t0 - 20, t0 - 10, t0, t0 + 10, t0 + 20]
for theta_0 in thetas_0:
theta = np.linspace(-14, 4, 100).reshape(100, 1)
theta = np.insert(theta, 0, theta_0, axis=1)
y = np.array([])
for i in range(theta.shape[0]):
tmp_lr = MyLR(theta[i].reshape(2, 1), mylr.X, mylr.Y)
dot = tmp_lr.cost_()
y = np.append(y, dot)
plt.plot(theta[:,1], y)
plt.xlabel("Theta1")
plt.ylabel("Cost function J(Theta0, Theta1")
plt.title("Evolution of the cost function J in fuction of Theta0 for different values of Theta1")
plt.show()
plt.cla()
def draw_multi_regression(mylr):
#mylr.fit_()
mylr.predict_()
# Plot in function of age
fig, ax = plt.subplots()
ax.scatter(mylr.X[:,0], mylr.Y)
ax.scatter(mylr.X[:,0], mylr.Y_hat, c="blue")
plt.xlabel("Age")
plt.ylabel("Sell_price")
plt.title("")
fig.legend(loc="lower left")
plt.show()
plt.cla()
# Plot in function of thrust
fig, ax = plt.subplots()
ax.scatter(mylr.X[:,1], mylr.Y)
ax.scatter(mylr.X[:,1], mylr.Y_hat, c="green")
plt.xlabel("Thrust")
plt.ylabel("Sell_price")
plt.title("")
fig.legend(loc="lower left")
plt.show()
plt.cla()
# Plot in function of terameters
fig, ax = plt.subplots()
ax.scatter(mylr.X[:,2], mylr.Y)
ax.scatter(mylr.X[:,2], mylr.Y_hat, c="pink")
plt.xlabel("Thrust")
plt.ylabel("Sell_price")
plt.title("")
fig.legend(loc="lower left")
plt.show()
plt.cla()
data = pd.read_csv("../resources/spacecraft_data.csv")
Y = np.array(data['Sell_price']).reshape(-1,1)
X = np.array(data['Age']).reshape(-1,1)
theta = np.array([[700.0], [-20.0]])
model_age = MyLR(theta, X, Y)
#draw_regression(model_age)
X = np.array(data['Thrust_power']).reshape(-1,1)
theta = np.array([[0.0], [40.0]])
model_thrust = MyLR(theta, X, Y)
#draw_regression(model_thrust)
X = np.array(data['Terameters']).reshape(-1,1)
theta = np.array([[800.0], [-2.0]])
model_tera = MyLR(theta, X, Y)
#draw_regression(model_tera)
X = np.array(data[['Age','Thrust_power','Terameters']])
my_lreg = MyLR([1.0, 1.0, 1.0, 1.0], X, Y)
print(my_lreg.mse_())
my_lreg.fit_(alpha = 5e-5, n_cycle = 600000)
print(my_lreg.theta)
print(my_lreg.mse_())
draw_multi_regression(my_lreg)
<file_sep>/day00/ex03/std.py
import numpy as np
from math import sqrt as sqrt
def mean(x):
"""Computes the mean of a non-empty numpy.ndarray, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The mean as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if x.size == 0:
return None
summed = 0.0
nb_elem = 0
for elem in x:
try:
summed += elem
nb_elem += 1
except:
return None
return summed/nb_elem
def variance(x):
"""Computes the variance of a non-empty numpy.ndarray, using a for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The variance as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if x.size == 0:
return None
original_mean = mean(x)
nb_elem = 0
gaps_vector = np.array([])
for elem in x:
gap = (elem - original_mean) ** 2
gaps_vector = np.append(gaps_vector, gap)
return mean(gaps_vector)
def std(x):
"""Computes the standard deviation of a non-empty numpy.ndarray, using a
for-loop.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
The standard deviation as a float.
None if x is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
return sqrt(variance(x))
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(std(X))
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(std(Y))
<file_sep>/day01/ex04/linear_model.py
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from mylinearregression import MyLinearRegression as MyLR
import matplotlib.pyplot as plt
def draw_regression(mylr):
fig, ax = plt.subplots() #renvoie une figure et des axes
ax.scatter(mylr.X, mylr.Y) #crée un diagramme de dispersion avec X et Y
ax.scatter(mylr.X, mylr.Y_hat, c="green")
plt.xlabel("Quantity of blue pills (in micrograms)")
plt.ylabel("Space driving score")
plt.title("Evolution of the space driving score in function of the blue pill's quantity (in µg)")
plt.plot(mylr.X, mylr.Y_hat, "--", c="green", label="model 1")
fig.legend(loc="lower left")
plt.show()
plt.cla()
def draw_cost_function(mylr):
fig, ax = plt.subplots() #renvoie une figure et des axes
t0 = mylr.theta[0]
thetas_0 = [t0 - 20, t0 - 10, t0, t0 + 10, t0 + 20]
for theta_0 in thetas_0:
theta = np.linspace(-14, 4, 100).reshape(100, 1)
theta = np.insert(theta, 0, theta_0, axis=1)
y = np.array([])
for i in range(theta.shape[0]):
tmp_lr = MyLR(theta[i].reshape(2, 1), mylr.X, mylr.Y)
dot = tmp_lr.cost_()
y = np.append(y, dot)
plt.plot(theta[:,1], y)
plt.xlabel("Theta1")
plt.ylabel("Cost function J(Theta0, Theta1")
plt.title("Evolution of the cost function J in fuction of Theta0 for different values of Theta1")
plt.show()
plt.cla()
data = pd.read_csv("../resources/are_blue_pills_magics.csv")
Xpill = np.array(data['Micrograms']).reshape(-1,1)
Yscore = np.array(data['Score']).reshape(-1,1)
linear_model1 = MyLR(np.array([[89.0], [-8]]), Xpill, Yscore)
linear_model2 = MyLR(np.array([[89.0], [-6]]), Xpill, Yscore)
linear_model1.fit_(Xpill, Yscore)
linear_model2.fit_(Xpill, Yscore)
Y_model1 = linear_model1.predict_()
Y_model2 = linear_model2.predict_()
draw_regression(linear_model1)
draw_cost_function(linear_model1)
print(linear_model1.mse_())
print(mean_squared_error(linear_model1.Y, linear_model1.Y_hat))
<file_sep>/day00/ex11/gradient.py
import numpy as np
def gradient(x, y, theta):
"""Computes a gradient vector from three non-empty numpy.ndarray, using
a for-loop. The two arrays must have the compatible dimensions.
Args:
x: has to be an numpy.ndarray, a matrice of dimension m * n.
y: has to be an numpy.ndarray, a vector of dimension m * 1.
theta: has to be an numpy.ndarray, a vector n * 1.
Returns:
The gradient as a numpy.ndarray, a vector of dimensions n * 1.
None if x, y, or theta are empty numpy.ndarray.
None if x, y and theta do not have compatible dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or theta.size == 0 or x.shape[1] != theta.shape[0] or y.shape[0] != x.shape[0] or theta.ndim != 1 or y.ndim != 1:
return None
m = x.shape[0]
n = x.shape[1]
ret = np.zeros(n)
for j in range(n):
i = 0
summed = 0.0
for line in x:
summed += (line.dot(theta) - y[i]) * x[i][j]
i += 1
ret[j] = summed / m
return ret
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
Z = np.array([3,0.5,-6])
print(gradient(X, Y, Z))
W = np.array([0,0,0])
print(gradient(X, Y, W))
print(gradient(X, X.dot(Z), Z))
<file_sep>/day01/ex01/cost_function.py
import numpy as np
def predict_(theta, X):
"""
Description:
Prediction of output using the hypothesis function (linear model).
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Returns:
pred: numpy.ndarray, a vector of dimension (number of the training
examples,1).
None if X does not match the dimension of theta.
Raises:
This function should not raise any Exception.
"""
if theta.ndim != 2 or X.ndim != 2 or theta.shape[1] != 1 or X.shape[1] + 1 != theta.shape[0]:
print("Incompatible dimension match between X and theta.")
return None
X = np.insert(X, 0, 1., axis=1)
return X.dot(theta)
def cost_elem_(theta, X, Y):
"""
Description:
Calculates all the elements 0.5*M*(y_pred - y)^2 of the cost
function.
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a matrix of dimension (number of
training examples, number of features).
Returns:
J_elem: numpy.ndarray, a vector of dimension (number of the training
examples,1).
None if there is a dimension matching problem between X, Y or theta.
Raises:
This function should not raise any Exception.
"""
Y_hat = predict_(theta, X)
if Y_hat is None:
return None
return ((Y_hat - Y)**2)/(2*X.shape[0])
def cost_(theta, X, Y):
"""
Description:
Calculates the value of cost function.
Args:
theta: has to be a numpy.ndarray, a vector of dimension (number of
features + 1, 1).
X: has to be a numpy.ndarray, a vector of dimension (number of
training examples, number of features).
Returns:
J_value : has to be a float.
None if X does not match the dimension of theta.
Raises:
This function should not raise any Exception.
"""
costs = cost_elem_(theta, X, Y)
if costs is None:
return None
return costs.sum()
X1 = np.array([[0.], [1.], [2.], [3.], [4.]])
theta1 = np.array([[2.], [4.]])
Y1 = np.array([[2.], [7.], [12.], [17.], [22.]])
print(cost_elem_(theta1, X1, Y1))
print(cost_(theta1, X1, Y1))
X2 = np.array([[0.2, 2., 20.], [0.4, 4., 40.], [0.6, 6., 60.], [0.8, 8., 80.]])
theta2 = np.array([[0.05], [1.], [1.], [1.]])
Y2 = np.array([[19.], [42.], [67.], [93.]])
print(cost_elem_(theta2, X2, Y2))
print(cost_(theta2, X2, Y2))
<file_sep>/day03/ex01/vec_reg.py
import numpy as np
def vectorized_regularization(theta, lambda_):
"""Computes the regularization term of a non-empty numpy.ndarray, with a
for-loop. Args:
theta: has to be a numpy.ndarray, a vector of dimension n * 1.
lambda: has to be a float.
Returns:
The regularization term of theta.
None if theta is an empty numpy.ndarray.
Raises:
This function should not raise any Exception.
"""
if (not isinstance(lambda_, (int, float))) or theta.ndim != 1:
print(type(theta))
return None
return lambda_ * (theta.dot(theta.T))
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(regularization(X, 0.3))
#284.7
print(regularization(X, 0.01))
#9.47
<file_sep>/day03/ex10/z-score.py
import numpy as np
def zscore(x):
"""Computes the normalized version of a non-empty numpy.ndarray using
the z-score standardization.
Args:
x: has to be an numpy.ndarray, a vector.
Returns:
x' as a numpy.ndarray.
None if x is a non-empty numpy.ndarray.
Raises:
This function shouldn't raise any Exception.
"""
return (x - np.mean(x)) / np.std(x)
X = np.array([0, 15, -9, 7, 12, 3, -21])
print(zscore(X))
#array([-0.08620324, 1.2068453 , -0.86203236, 0.51721942, 0.94823559, 0.17240647, -1.89647119])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(zscore(Y))
#array([ 0.11267619, 1.16432067, -1.20187941, 0.37558731, 0.98904659, 0.28795027, -1.72770165])
<file_sep>/day00/ex09/linear_mse.py
import numpy as np
def dot(x, y):
"""Computes the dot product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have the same dimensions.
Args:
x: has to be an numpy.ndarray, a vector.
y: has to be an numpy.ndarray, a vector.
Returns:
The dot product of the two vectors as a float.
None if x or y are empty numpy.ndarray.
None if x and y does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or x.shape != y.shape:
return None
dot_product = 0.0
for xi, yi in zip(x, y):
dot_product += xi * yi
return dot_product
def linear_mse(x, y, theta):
"""Computes the mean squared error of three non-empty numpy.ndarray,
using a for-loop. The three arrays must have compatible dimensions.
Args:
y: has to be an numpy.ndarray, a vector of dimension m * 1.
x: has to be an numpy.ndarray, a matrix of dimesion m * n.
theta: has to be an numpy.ndarray, a vector of dimension n * 1.
Returns:
The mean squared error as a float.
None if y, x, or theta are empty numpy.ndarray.
None if y, x or theta does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or theta.size == 0 or x.shape[1] != theta.shape[0] or y.shape[0] != x.shape[0] or theta.ndim != 1 or y.ndim != 1:
return None
summed = 0.0
i = 0
for line in x:
summed += (dot(theta, line) - y[i]) ** 2
i += 1
return summed/x.shape[0]
X = np.array([
[ -6, -7, -9],
[ 13, -2, 14],
[ -7, 14, -1],
[ -8, -4, 6],
[ -5, -9, 6],
[ 1, -5, 11],
[ 9, -11, 8]])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
Z = np.array([3,0.5,-6])
print(linear_mse(X, Y, Z))
W = np.array([0,0,0])
print(linear_mse(X, Y, W))
<file_sep>/README.md
# machine_learning_bootcamp
A Machine Learning Bootcamp at @42 based on <NAME>'s class at Stanford
The Machine Learning bootcamp is a 5 day-program designed 42 as an introduction to Machine Learning algorithms. Here is an overview of the program:
Day00: Linear algebra fundamentals
Day01: Multivariable linear regressions
Day02: Logistic regressions
Day03: Regularization
Day04: Decision Trees
Days 01 to 03 follow the 3 first weeks of Andrew NG's class available on : https://www.coursera.org/learn/machine-learning?
To clone the repository, type gcl https://github.com/hehlinge42/machine_learning_bootcamp.git in a UNIX terminal The repository contains one folder per day of the bootcamp. The subject of the exercises of the day is available in each of these folders.
<file_sep>/day00/ex05/mat_vec_prod.py
import numpy as np
def dot(x, y):
"""Computes the dot product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have the same dimensions.
Args:
x: has to be an numpy.ndarray, a vector.
y: has to be an numpy.ndarray, a vector.
Returns:
The dot product of the two vectors as a float.
None if x or y are empty numpy.ndarray.
None if x and y does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or x.size != y.size:
return None
dot_product = 0.0
for xi, yi in zip(x, y):
dot_product += xi * yi
return dot_product
def mat_vec_prod(x, y):
"""Computes the product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have compatible dimensions.
Args:
x: has to be an numpy.ndarray, a matrix of dimension m * n.
y: has to be an numpy.ndarray, a vector of dimension n * 1.
Returns:
The product of the matrix and the vector as a vector of dimension m *
1.
None if x or y are empty numpy.ndarray.
None if x and y does not share compatibles dimensions.
Raises:
This function should not raise any Exception.
"""
if x.ndim != 2 or y.ndim != 2 or x.shape[1] != y.shape[0] or y.shape[1] != 1:
return None
ret = np.array([])
for line in x:
dot_prod = dot(line, y)
ret = np.append(ret, dot_prod)
return ret.reshape(x.shape[0], 1)
W = np.array([
[ -8, 8, -6, 14, 14, -9, -4],
[ 2, -11, -2, -11, 14, -2, 14],
[-13, -2, -5, 3, -8, -4, 13],
[ 2, 13, -14, -15, -14, -15, 13],
[ 2, -1, 12, 3, -7, -3, -6]])
X = np.array([0, 15, -9, 7, 12, 3, -21]).reshape((7,1))
Y = np.array([2, 14, -13, 5, 12, 4, -19]).reshape((7,1))
print(mat_vec_prod(W, X))
print(mat_vec_prod(W, Y))
X1 = np.array([[0.], [1.], [2.], [3.], [4.]])
theta1 = np.array([[2.], [4.]])
predict_(theta1, X1)
<file_sep>/day02/ex10/confusion_matrix.py
import numpy as np
def confusion_matrix_(y_true, y_pred, labels=None):
"""
Compute confusion matrix to evaluate the accuracy of a classification.
Args:
y_true: a scalar or a numpy ndarray for the correct labels
y_pred: a scalar or a numpy ndarray for the predicted labels
labels: optional, a list of labels to index the matrix. This may be
used to reorder or select a subset of labels. (default=None)
Returns:
The confusion matrix as a numpy ndarray.
None on any error.
Raises:
This function should not raise any Exception.
"""
if labels is None:
labels = np.concatenate((y_true, y_pred))
labels = np.unique(labels)
labels = np.sort(labels)
conf_matrix = np.zeros((len(labels), len(labels)))
for i in range(len(labels)):
for j in range(len(labels)):
conf_matrix[i][j] = ((y_true == labels[i]) & (y_pred == labels[j])).sum()
return conf_matrix
#true labels are rows and predicted labels are columns
y_pred = np.array(['norminet', 'dog', 'norminet', 'norminet', 'dog',
'bird'])
y_true = np.array(['dog', 'dog', 'norminet', 'norminet', 'dog', 'norminet'])
print(confusion_matrix_(y_true, y_pred))
# [[0 0 0]
# [0 2 1]
# [1 0 2]]
print(confusion_matrix_(y_true, y_pred, labels=['dog', 'norminet']))
# [[2 1]
# [0 2]]
<file_sep>/day00/ex07/mse.py
import numpy as np
def mse(y, y_hat):
"""Computes the mean squared error of two non-empty numpy.ndarray, using
a for-loop. The two arrays must have the same dimensions.
Args:
y: has to be an numpy.ndarray, a vector.
y_hat: has to be an numpy.ndarray, a vector.
Returns:
The mean squared error of the two vectors as a float.
None if y or y_hat are empty numpy.ndarray.
None if y and y_hat does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if y.shape != y_hat.shape or y.ndim != 1:
return None
summed = 0.0
for yi, yi_hat in zip(y, y_hat):
summed += (yi - yi_hat) ** 2
return summed/y.size
X = np.array([0, 15, -9, 7, 12, 3, -21])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(mse(X, Y))
print(mse(X, X))
<file_sep>/day00/ex08/vec_mse.py
import numpy as np
def dot(x, y):
"""Computes the dot product of two non-empty numpy.ndarray, using a
for-loop. The two arrays must have the same dimensions.
Args:
x: has to be an numpy.ndarray, a vector.
y: has to be an numpy.ndarray, a vector.
Returns:
The dot product of the two vectors as a float.
None if x or y are empty numpy.ndarray.
None if x and y does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if x.size == 0 or y.size == 0 or x.shape != y.shape:
return None
dot_product = 0.0
for xi, yi in zip(x, y):
dot_product += xi * yi
return dot_product
def vec_mse(y, y_hat):
"""Computes the mean squared error of two non-empty numpy.ndarray,
without any for loop. The two arrays must have the same dimensions.
Args:
y: has to be an numpy.ndarray, a vector.
y_hat: has to be an numpy.ndarray, a vector.
Returns:
The mean squared error of the two vectors as a float.
None if y or y_hat are empty numpy.ndarray.
None if y and y_hat does not share the same dimensions.
Raises:
This function should not raise any Exception.
"""
if y.shape != y_hat.shape or y.ndim != 1:
return None
return dot(y_hat - y, y_hat - y)/y.size
X = np.array([0, 15, -9, 7, 12, 3, -21])
Y = np.array([2, 14, -13, 5, 12, 4, -19])
print(vec_mse(X, Y))
print(vec_mse(X, X))
<file_sep>/day01/ex03/main.py
import numpy as np
from mylinearregression import MyLinearRegression as MyLR
X = np.array([[1., 1., 2., 3.], [5., 8., 13., 21.], [34., 55., 89., 144.]])
Y = np.array([[23.], [48.], [218.]])
mylr = MyLR([[1.], [1.], [1.], [1.], [1]])
print(mylr.predict_(X))
print(mylr.cost_elem_(X,Y))
print(mylr.cost_(X,Y))
mylr.fit_(X, Y, alpha = 1.6e-4, n_cycle=200000)
print(mylr.theta)
print(mylr.predict_(X))
print(mylr.cost_elem_(X,Y))
print(mylr.cost_(X,Y))
|
24d10da90e633ffb7702e9d73c26e6f60106d410
|
[
"Markdown",
"Python"
] | 39
|
Python
|
hehlinge42/machine_learning_bootcamp
|
96fceb3a24a93d9c1c4cb80daea0e8f842759a0d
|
30628f30101d5c3a4d1e0b93cb8d10fd3c445209
|
refs/heads/main
|
<file_sep>import defaultAvatar from '../images/default.jpeg';
import PropTypes from 'prop-types';
import styles from './Profile.module.css';
export default function Profile({ name, tag, location, avatar, stats }) {
return (
<div className={styles.container}>
<div className={styles.description}>
<img src={avatar} alt={name} className={styles.avatar} />
<p className={styles.description_name}>{name}</p>
<p className={styles.description_tag}>@{tag}</p>
<p className={styles.description_location}>{location}</p>
</div>
<ul className={styles.stats}>
<li className={styles.contain_block}>
<span className={styles.stats_label}>Followers</span>
<span className={styles.stats_quantity}>{stats.followers}</span>
</li>
<li className={styles.contain_block}>
<span className={styles.stats_label}>Views</span>
<span className={styles.stats_quantity}>{stats.views}</span>
</li>
<li className={styles.contain_block}>
<span className={styles.stats_label}>Likes</span>
<span className={styles.stats_quantity}>{stats.likes}</span>
</li>
</ul>
</div>
);
}
Profile.defaultProps = {
avatar: defaultAvatar,
};
Profile.propTypes = {
name: PropTypes.string.isRequired,
tag: PropTypes.string.isRequired,
location: PropTypes.string.isRequired,
avatar: PropTypes.string,
stats: PropTypes.objectOf(PropTypes.number).isRequired,
};
|
862be4e6ca39e1ae41a023e799c37f92e7d6fbcf
|
[
"JavaScript"
] | 1
|
JavaScript
|
Rahmanov-Viusal/goit-react-hw-01-components
|
73f6bf6196247791c1cf0de33364acea43548bec
|
042847d649eaa7101637a03899fbede22e301283
|
refs/heads/master
|
<repo_name>jagilpe/bundles-demo<file_sep>/src/AppBundle/Controller/EntityListDemoController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\User;
use AppBundle\EntityList\Type\UserListType;
use Jagilpe\EntityListBundle\Controller\EntityListControllerTrait;
use Jagilpe\EntityListBundle\EntityList\ColumnType\SingleFieldColumnType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
/**
* Controller class for the entity list demo
*
* @author <NAME> <<EMAIL>>
*/
class EntityListDemoController extends Controller
{
use EntityListControllerTrait;
/**
* Home page for the entity list bundle demo
*
* @return Response
*/
public function entityListDemoHomeAction()
{
// Get the users
$repo = $this->get('doctrine')->getRepository(User::class);
$users = $repo->findAll();
$listBuilder = $this->createEntityListBuilder($users);
$listBuilder->add('username', SingleFieldColumnType::class, array('label' => 'Username'));
$listBuilder->add('email', SingleFieldColumnType::class, array('label' => 'Email'));
$listBuilder->add('profile::firstName', SingleFieldColumnType::class, array('label' => 'First name'));
$listBuilder->add('profile::lastName', SingleFieldColumnType::class, array('label' => 'Last name'));
$list1 = $listBuilder->getEntityList();
$list2 = $this->createEntityList($users, UserListType::class);
return $this->render(':entity_list_demo:entity-list-index.html.twig', array('list1' => $list1, 'list2' => $list2));
}
}<file_sep>/src/AppBundle/EntityList/Type/UserListType.php
<?php
namespace AppBundle\EntityList\Type;
use AppBundle\Entity\User;
use Jagilpe\EntityListBundle\EntityList\AbstractListType;
use Jagilpe\EntityListBundle\EntityList\ColumnType\CallbackColumnType;
use Jagilpe\EntityListBundle\EntityList\ColumnType\DateTimeColumnType;
use Jagilpe\EntityListBundle\EntityList\ColumnType\SingleFieldColumnType;
use Jagilpe\EntityListBundle\EntityList\EntityListBuilderInterface;
/**
* Entity list type example for the user entity
*
* @author <NAME> <<EMAIL>>
*/
class UserListType extends AbstractListType
{
/**
* {@inheritDoc}
* @see \Jagilpe\EntityListBundle\EntityList\ListTypeInterface::buildList()
*/
public function buildList(EntityListBuilderInterface $builder, array $options = array())
{
$builder
->add('username', SingleFieldColumnType::class, array('label' => 'Username'))
->add('fullName', CallbackColumnType::class, array(
'label' => 'Full name',
'content-callback' => function(User $user) {
$userProfile = $user->getProfile();
return $userProfile ? $userProfile->getLastName().', '.$userProfile->getFirstName() : null;
}))
->add('profile::birthDate', DateTimeColumnType::class, array(
'label' => 'Birth date',
'cell-options' => array('datetime_format' => 'm/d/Y')))
->add('Age', CallbackColumnType::class, array(
'content-callback' => array($this, 'getUserAge')
))
->add('profile::address', SingleFieldColumnType::class, array('label' => 'Address'))
->add('profile::address::country', SingleFieldColumnType::class, array('label' => 'Country'))
;
}
/**
* Returns the age of the user
*
* @param User $user
* @return string
*/
public function getUserAge(User $user)
{
$profile = $user->getProfile();
if ($profile) {
$now = new \DateTime();
$birthDate = $profile->getBirthDate();
return $birthDate ? $now->diff($birthDate)->y : null;
} else {
return null;
}
}
}<file_sep>/src/AppBundle/Service/MenuProvider.php
<?php
namespace AppBundle\Service;
use Jagilpe\MenuBundle\Menu\Menu;
use Jagilpe\MenuBundle\Menu\MenuItem;
use Jagilpe\MenuBundle\Provider\AbstractMenuProvider;
/**
* Service that provides the menus of the app
*
* @author <NAME> <<EMAIL>>
*/
class MenuProvider extends AbstractMenuProvider
{
const APP_MENU = 'app_menu';
const APP_MOBILE_MENU = 'app_mobile_menu';
/**
* Menus for the demo of the MenuBundle
*/
// This menu is shown when the navbar is not collapsed
const DEMO_MENU = 'demo_menu';
// This menu is shown when the navbar is collapsed (smallest resolutions)
const DEMO_MOBILE_MENU = 'demo_mobile_menu';
/**
* Returns a menu object
*
* @param string $menuName
*
* @throws \RuntimeException
*
* @return \Jagilpe\MenuBundle\Menu\Menu|null|false
*/
public function getMenu($menuName)
{
switch ($menuName) {
case self::APP_MENU:
return $this->getAppMenu(false);
case self::APP_MOBILE_MENU:
return $this->getAppMenu(true);
case self::DEMO_MENU:
return $this->getDemoMenu(false);
case self::DEMO_MOBILE_MENU:
return $this->getDemoMenu(true);
}
return false;
}
/**
* Returns the main app menu
*
* @param boolean $mobile
* @return Menu
*/
private function getAppMenu($mobile)
{
$menuBuilder = $this->menuFactory->createMenuBuilder();
$menuBuilder->newMenuItem(array(
'name' => 'Home',
'route' => 'homepage'
));
$menuBuilder->addMenuItem($this->getAjaxBlocksMenu($mobile));
$menuBuilder->addMenuItem($this->getAjaxModalsMenu($mobile));
$menuBuilder->addMenuItem($this->getEntityListMenu($mobile));
$menuBuilder->newMenuItem(array(
'name' => 'MenuBundle',
'route' => 'menu_demo_home'
));
return $menuBuilder->getMenu();
}
/**
* Returns the menu for the demo of the menu bundle functionality. It returns two versions of the same
* menu, depending if it's to be shown in smaller or bigger resolutions
*
* @param boolean $mobile
* @return Menu
*/
private function getDemoMenu($mobile = false)
{
$menuClasses = $mobile ? 'hidden-sm hidden-md hidden-lg' : 'hidden-xs';
$menuBuilder = $this->menuFactory->createMenuBuilder(array(
'attributes' => array('class' => $menuClasses)
));
$menuBuilder->newMenuItem(array(
'name' => 'Home',
'route' => 'homepage'
));
$menuBuilder->addMenuItem($this->getCollapsedMenuItem($mobile));
$menuBuilder->addMenuItem($this->getExpandableMenuItem());
$menuBuilder->addMenuItem($this->getAnchorsMenu($mobile));
return $menuBuilder->getMenu();
}
/**
* Returns the items of the collapsed menu
*
* @param boolean $mobile
* @return MenuItem
*/
private function getCollapsedMenuItem($mobile)
{
$collapsedMenu = $this->menuFactory->createMenuItem(array(
'name' => 'Collapsed Menu',
'route' => 'menu_collapsed',
'hide_children' => !$mobile,
));
for ($i = 1; $i < 4; $i++) {
// Child with more sub children
$child = $this->menuFactory->createMenuItem(array(
'name' => "Level 2 - Element $i",
'route' => 'menu_collapsed_level2',
'route_params' => array('level2' => $i),
'hide_children' => true,
));
for ($j = 1; $j < 5; $j++) {
$child
->add($this->menuFactory->createMenuItem(array(
'name' => "Level 3 - Elem. $i - Subelem. $j",
'route' => 'menu_collapsed_level3',
'route_params' => array('level2' => 1, 'level3' => $j)
)));
}
$collapsedMenu->add($child);
}
$otherChild = $this->menuFactory->createMenuItem(array(
'name' => 'Level 2 - Element 4',
'route' => 'menu_collapsed_level2',
'route_params' => array('level2' => 4)
));
$collapsedMenu->add($otherChild);
return $collapsedMenu;
}
/**
* Returns the items of the expandable menu
*
* @return MenuItem
*/
private function getExpandableMenuItem()
{
$dropDownMenu = $this->menuFactory->createMenuItem(array(
'name' => 'Drop Down Menu',
'route' => 'menu_drop_down',
));
for ($i = 1; $i < 5; $i++) {
// Child with more sub children
$child = $this->menuFactory->createMenuItem(array(
'name' => "Level 2 - Element $i",
'route' => 'menu_drop_down_level_2',
'route_params' => array('level2' => $i),
));
$dropDownMenu->add($child);
}
return $dropDownMenu;
}
/**
* Returns a menu area that demonstrates the navigation with anchors
*
* @param boolean $mobile
* @return MenuItem
*/
private function getAnchorsMenu($mobile)
{
$anchorMenu = $this->menuFactory->createMenuItem(array(
'name' => 'Anchor Menu',
'route' => 'menu_anchor',
'hide_children' => !$mobile,
));
$anchors = array(
'first',
'second',
'third',
'forth'
);
foreach ($anchors as $anchor) {
$childItem = $this->menuFactory->createMenuItem(
array(
'name' => "Anchor to $anchor target",
));
$childItem->setRouteOptions(array('anchor' => $anchor));
$anchorMenu->add($childItem);
}
return $anchorMenu;
}
/**
* Returns the menu elements for the AjaxBlocks Bundle demo
*
* @param boolean $mobile
* @return MenuItem
*/
private function getAjaxBlocksMenu($mobile)
{
$ajaxBlocksMenu = $this->menuFactory->createMenuItem(array(
'name' => 'AjaxBlocksBundle',
'route' => 'ajax_blocks_home',
'hide_children' => !$mobile,
));
$simpleBlocks = $this->menuFactory->createMenuItem(array(
'name' => 'Simple ajax blocks',
'route' => 'ajax_blocks_simple',
));
$ajaxBlocksMenu->add($simpleBlocks);
return $ajaxBlocksMenu;
}
/**
* Returns the menu elements for the AjaxModals Bundle demo
*
* @param boolean $mobile
* @return MenuItem
*/
private function getAjaxModalsMenu($mobile)
{
$ajaxModalsMenu = $this->menuFactory->createMenuItem(array(
'name' => 'AjaxModalsBundle',
'route' => 'ajax_modals_home',
'hide_children' => !$mobile,
));
return $ajaxModalsMenu;
}
/**
* Returns the menu elements for the AjaxModals Bundle demo
*
* @param boolean $mobile
* @return MenuItem
*/
private function getEntityListMenu($mobile)
{
$entityListMenu = $this->menuFactory->createMenuItem(array(
'name' => 'EntityListBundle',
'route' => 'entity_list_home',
'hide_children' => !$mobile,
));
return $entityListMenu;
}
}<file_sep>/src/AppBundle/Controller/DefaultController.php
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('default/index.html.twig');
}
/**
* Renders the message block
*
* @return Response
*/
public function messagesBlockAction()
{
return $this->render(':default:messages.html.twig');
}
}
<file_sep>/src/AppBundle/Form/Type/UserProfileType.php
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Form Type class for the Test Entity
*
* @author <NAME> <<EMAIL>>
*/
class UserProfileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName')
->add('lastName')
;
}
}<file_sep>/src/AppBundle/Entity/User.php
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Jagilpe\EncryptionBundle\Entity\PKEncryptionEnabledUserInterface;
use Jagilpe\EncryptionBundle\Entity\Traits\EncryptionEnabledUserTrait;
/**
* @ORM\Entity
* @ORM\Table(name="app_user")
*/
class User extends BaseUser implements PKEncryptionEnabledUserInterface
{
use EncryptionEnabledUserTrait;
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var UserProfile
*
* @ORM\OneToOne(targetEntity="UserProfile", mappedBy="user", cascade={"persist", "remove"})
*/
protected $profile;
/**
* @return UserProfile
*/
public function getProfile()
{
return $this->profile;
}
/**
* @param UserProfile $profile
* @return User
*/
public function setProfile(UserProfile $profile)
{
$this->profile = $profile;
return $this;
}
}<file_sep>/src/AppBundle/Controller/MenuDemoController.php
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class MenuDemoController extends Controller
{
public function routeDataAction()
{
$mainRequest = $this->get('request_stack')->getMasterRequest();
$variables = array();
if ($mainRequest) {
$variables = array(
'data' => $this->getRouteData($mainRequest),
);
}
return $this->render(':menu_demo:route_data_block.html.twig', $variables);
}
private function getRouteData(Request $request)
{
$data = array('Route' => $request->attributes->get('_route'));
$routeParams = $request->attributes->get('_route_params') ? $request->attributes->get('_route_params') : array();
foreach ($routeParams as $param => $value) {
$data["Param [$param]"] = $value;
}
return $data;
}
}
<file_sep>/src/AppBundle/Controller/AjaxBlocksDemoController.php
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
class AjaxBlocksDemoController extends Controller
{
const SIMPLE_CACHE_KEY = 'simple.block';
const SIMPLE_NUMBER_OF_BLOCKS = 5;
/**
* Controller for the simple demo of the ajax blocks
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function simpleAction()
{
// Reset the blocks counters
$this->resetSimpleCounter();
$variables = array('numberOfBlocks' => self::SIMPLE_NUMBER_OF_BLOCKS);
return $this->render(':ajax_blocks_demo:simple.html.twig', $variables);
}
/**
* Returns the content for a simple ajax block
*
* @param $blockId
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function simpleBlockAction($blockId)
{
$cache = new FilesystemAdapter();
$cachedCounter = $cache->getItem(self::SIMPLE_CACHE_KEY.'.'.$blockId);
$timerReloaded = $cachedCounter->get();
$variables = array(
'blockId' => $blockId,
'timesReloaded' => $timerReloaded++,
);
$cachedCounter->set($timerReloaded);
$cache->save($cachedCounter);
return $this->render(':ajax_blocks_demo:simple_block.html.twig', $variables);
}
/**
* Resets the reload counters for the simple ajax blocks
*/
private function resetSimpleCounter()
{
$cache = new FilesystemAdapter();
for ($i = 0; $i < self::SIMPLE_NUMBER_OF_BLOCKS; $i++) {
$cacheKey = self::SIMPLE_CACHE_KEY.'.'.$i;
$timesReloaded = $cache->getItem($cacheKey);
$timesReloaded->set(0);
$cache->save($timesReloaded);
}
}
}
<file_sep>/src/AppBundle/Entity/SystemEncryptableEntityAnnotation.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Jagilpe\EncryptionBundle\Annotation\EncryptedEntity;
use Jagilpe\EncryptionBundle\Annotation\EncryptedField;
use Jagilpe\EncryptionBundle\Entity\SystemEncryptableEntity;
use Jagilpe\EncryptionBundle\Entity\Traits\SystemEncryptableEntityTrait;
/**
* Example entity for the configuration of system wide encryption with annotations
*
* @author <NAME> <<EMAIL>>
*
* @ORM\Entity
* @EncryptedEntity(enabled=true, mode="SYSTEM_ENCRYPTION")
*/
class SystemEncryptableEntityAnnotation implements SystemEncryptableEntity
{
use SystemEncryptableEntityTrait;
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @ORM\Column(type="string")
*/
protected $clearField;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @EncryptedField
*/
protected $encryptedStringField;
/**
* @var string
* @ORM\Column(type="text")
* @EncryptedField
*/
protected $encryptedTextField;
/**
* @var boolean
* @ORM\Column(type="boolean")
* @EncryptedField
*/
protected $encryptedBooleanField;
/**
* @var integer
* @ORM\Column(type="integer")
* @EncryptedField
*/
protected $encryptedIntegerField;
/**
* @var array
* @ORM\Column(type="simple_array")
* @EncryptedField
*/
protected $encryptedSimpleArrayField;
/**
* @var array
* @ORM\Column(type="json_array")
* @EncryptedField
*/
protected $encryptedJsonArrayField;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
* @EncryptedField
*/
protected $encryptedDateTimeField;
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getClearField()
{
return $this->clearField;
}
/**
* @param string $clearField
* @return SystemEncryptableEntityAnnotation
*/
public function setClearField($clearField)
{
$this->clearField = $clearField;
return $this;
}
/**
* @return string
*/
public function getEncryptedStringField()
{
return $this->encryptedStringField;
}
/**
* @param string $encryptedStringField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedStringField($encryptedStringField)
{
$this->encryptedStringField = $encryptedStringField;
return $this;
}
/**
* @return string
*/
public function getEncryptedTextField()
{
return $this->encryptedTextField;
}
/**
* @param string $encryptedTextField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedTextField($encryptedTextField)
{
$this->encryptedTextField = $encryptedTextField;
return $this;
}
/**
* @return bool
*/
public function isEncryptedBooleanField()
{
return $this->encryptedBooleanField;
}
/**
* @param bool $encryptedBooleanField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedBooleanField(bool $encryptedBooleanField)
{
$this->encryptedBooleanField = $encryptedBooleanField;
return $this;
}
/**
* @return int
*/
public function getEncryptedIntegerField()
{
return $this->encryptedIntegerField;
}
/**
* @param int $encryptedIntegerField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedIntegerField($encryptedIntegerField)
{
$this->encryptedIntegerField = $encryptedIntegerField;
return $this;
}
/**
* @return array
*/
public function getEncryptedSimpleArrayField()
{
return $this->encryptedSimpleArrayField;
}
/**
* @param array $encryptedSimpleArrayField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedSimpleArrayField(array $encryptedSimpleArrayField)
{
$this->encryptedSimpleArrayField = $encryptedSimpleArrayField;
return $this;
}
/**
* @return array
*/
public function getEncryptedJsonArrayField()
{
return $this->encryptedJsonArrayField;
}
/**
* @param array $encryptedJsonArrayField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedJsonArrayField(array $encryptedJsonArrayField)
{
$this->encryptedJsonArrayField = $encryptedJsonArrayField;
return $this;
}
/**
* @return \DateTime
*/
public function getEncryptedDateTimeField()
{
return $this->encryptedDateTimeField;
}
/**
* @param \DateTime $encryptedDateTimeField
* @return SystemEncryptableEntityAnnotation
*/
public function setEncryptedDateTimeField(\DateTime $encryptedDateTimeField)
{
$this->encryptedDateTimeField = $encryptedDateTimeField;
return $this;
}
}<file_sep>/src/AppBundle/Controller/AjaxModalsController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\UserProfile;
use AppBundle\Form\Type\UserProfileType;
use Jagilpe\AjaxModalsBundle\Controller\AjaxViewControllerTrait;
use Jagilpe\AjaxModalsBundle\View\EndAjaxView;
use Jagilpe\AjaxModalsBundle\View\ErrorAjaxView;
use Jagilpe\AjaxModalsBundle\View\FormAjaxView;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
/**
* @author <NAME> <<EMAIL>>
*/
class AjaxModalsController extends Controller
{
use AjaxViewControllerTrait;
/**
* Home page for the ajax modals demo
*
* @return Response
*/
public function ajaxDemoHomeAction()
{
return $this->render(':ajax_modals_demo:ajax-modals-index.html.twig');
}
/**
* Controller that return the content for an ajax modal dialog
*
* @Route("/ajax/ajax-modal-dialog", name="ajax_modal_dialog")
*/
public function ajaxDialogAction(Request $request)
{
$testEntity = new UserProfile();
$form = $this->createForm(UserProfileType::class, $testEntity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$firstName = $testEntity->getFirstName();
$lastName = $testEntity->getLastName();
$message = "The form was submitted with first name=$firstName and last name=$lastName";
$this->addFlash('info', $message);
// This view will close the ajax dialog
$view = $this->createAjaxView(EndAjaxView::class);
} catch(\Exception $exception) {
// We have to inform the dialog that there was an error
$view = $this->createAjaxView(ErrorAjaxView::class);
$view->setErrorFromException($exception);
}
} else {
// Create the form ajax view
$view = $this->createAjaxView(FormAjaxView::class);
$view->setTitle("Title of the dialog");
$view->setContent(
$this->renderView(':ajax_modals_demo:ajax-modal-dialog.html.twig', array('form' => $form->createView(),))
);
// Configure the save button
$view->getButton(FormAjaxView::BUTTON_SAVE)
->showButton()
->setUrl($this->get('router')->generate('ajax_modal_dialog'));
}
// Return the view
return $view;
}
}<file_sep>/README.md
Jagilpe Symfony Bundles Demo Site
============
This is the code for the demo site for the different Jagilpe Symfony Bundles:
[AjaxBlocksBundle](https://github.com/jagilpe/ajax-blocks-bundle)
[AjaxModalsBundle](https://github.com/jagilpe/ajax-modals-bundle)
[EncryptionBundle](https://github.com/jagilpe/encryption-bundle)
[EntityListBundle](https://github.com/jagilpe/entity-list-bundle)
[MenuBundle](https://github.com/jagilpe/menu-bundle)
You can access the demo in
https://demos.gilpereda.com/symfony-bundles
# Installation
To install this site locally simply run the following command in a terminal
```bash
# Clone the repository
git clone https://github.com/jagilpe/bundles-demo.git bundles-demo
# Change to the project's directory
cd bundles-demo
# Install the dependencies
composer install
# Generate and dump the assets
php bin/console assetic:dump
# Generate the database schema
php bin/console doctrine:schema:create
# Load the example data
php bin/console hautelook_alice:doctrine:fixtures:load
# Start the Symfony server
php bin/console server:run
```
Now you should be able to open the Demo accessing http://127.0.0.1:8000<file_sep>/src/AppBundle/Entity/UserOwnedEntity.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Jagilpe\EncryptionBundle\Annotation\EncryptedEntity;
use Jagilpe\EncryptionBundle\Annotation\EncryptedField;
use Jagilpe\EncryptionBundle\Entity\PerUserEncryptableEntity;
use Jagilpe\EncryptionBundle\Entity\Traits\PerUserEncryptableEntityTrait;
/**
* Example Entity for per user encryption
*
* @author <NAME> <<EMAIL>>
*
* @ORM\Entity
* @EncryptedEntity(enabled=true, mode="PER_USER_SHAREABLE")
*/
class UserOwnedEntity implements PerUserEncryptableEntity
{
use PerUserEncryptableEntityTrait;
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var User
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
protected $user;
/**
* @var string
* @ORM\Column(type="string")
*/
protected $clearField;
/**
* @var string
* @ORM\Column(type="string", length=255)
* @EncryptedField
*/
protected $encryptedField;
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @param User $user
* @return UserOwnedEntity
*/
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* @return string
*/
public function getClearField()
{
return $this->clearField;
}
/**
* @param string $clearField
* @return UserOwnedEntity
*/
public function setClearField($clearField)
{
$this->clearField = $clearField;
return $this;
}
/**
* @return string
*/
public function getEncryptedField()
{
return $this->encryptedField;
}
/**
* @param string $encryptedField
* @return UserOwnedEntity
*/
public function setEncryptedField($encryptedField)
{
$this->encryptedField = $encryptedField;
return $this;
}
}<file_sep>/src/AppBundle/Entity/Address.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity()
* @author <NAME> <<EMAIL>>
*/
class Address
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @ORM\Column(type="string", length=255, nullable=false)
* @Assert\NotBlank()
*/
private $address;
/**
* @var string
* @ORM\Column(type="string", length=50, nullable=false)
* @Assert\NotBlank()
*/
private $city;
/**
* @var string
* @ORM\Column(type="string", length=10, nullable=false)
* @Assert\NotBlank()
*/
private $zipCode;
/**
* @var string
* @ORM\Column(type="string", length=50, nullable=false)
* @Assert\NotBlank()
*/
private $country;
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @param integer $id
* @return Address
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* @param string $address
* @return Address
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* @return string
*/
public function getCity()
{
return $this->city;
}
/**
* @param string $city
* @return Address
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* @return string
*/
public function getZipCode()
{
return $this->zipCode;
}
/**
* @param string $zipCode
* @return Address
*/
public function setZipCode($zipCode)
{
$this->zipCode = $zipCode;
return $this;
}
/**
* @return string
*/
public function getCountry()
{
return $this->country;
}
/**
* @param string $country
* @return Address
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Returns the full address
*
* @return string
*/
public function getFullAddress()
{
$fullAddress = '';
$fullAddress .= $this->getAddress() ? $this->getAddress() : '';
$fullAddress .= $this->getZipCode() ? ', '.$this->getZipCode() : '';
$fullAddress .= $this->getCity() ? ', '.$this->getCity(): '';
return trim($fullAddress);
}
public function __toString()
{
return $this->getFullAddress();
}
}<file_sep>/post-install.php
<?php
// Create the data directory for the sqlite database
if (!file_exists('var/data')) {
mkdir('var/data', 0777, true);
}
|
06bae2dfe150d0787b028946ba3b7722f900adc3
|
[
"Markdown",
"PHP"
] | 14
|
PHP
|
jagilpe/bundles-demo
|
6679748f7cc730bb74200a9f27f8b7aea7e4c6ab
|
63ed6a90bd6d6faeb7802bd36eaf9856c2acd900
|
refs/heads/master
|
<file_sep>'use strict';
angular.module('legoBricks', []);
|
74845bd218f42b0399ca26466e37c2595523878a
|
[
"JavaScript"
] | 1
|
JavaScript
|
dvxiaofan/FEF-Quiz-Angular-Module
|
89ec8fbae6ad26ca419c749a3d69cf4f353df1ba
|
c7841f3b0ad34e26eaa82212ddca6712518818f8
|
refs/heads/master
|
<repo_name>MKDir43/kaggle-docker-updated<file_sep>/docker/Dockerfile
FROM gcr.io/kaggle-gpu-images/python:latest
# install common libraries
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
git vim tmux build-essential bash-completion sudo chromium-browser
RUN apt-get install -y cuda-drivers
# upgrade conda & pip
RUN conda update -n base conda
RUN conda update --all
RUN pip install --upgrade pip
# install latest cuda
ENV CUDA_HOME="/usr/local/cuda"
ENV PATH="/usr/local/cuda/bin:$PATH"
ENV LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"
# clean up
RUN apt-get install -y python3-pip
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# create user
ARG USER_NAME=kaggle
ARG USER_UID=1000
ARG USER_GID=${USER_UID}
RUN groupadd --force --gid ${USER_GID} ${USER_NAME} && \
useradd -m -u ${USER_UID} -g ${USER_GID} --shell /bin/bash ${USER_NAME}
# sudoer
RUN echo "${USER_NAME}:${USER_NAME}" | chpasswd && \
usermod -aG sudo ${USER_NAME} && \
echo "${USER_NAME} ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
# python local dir
RUN mkdir -p /home/kaggle/.local && \
chown -R ${USER_UID}:${USER_GID} /home/kaggle/.local
ENV PYTHONUSERBASE "/home/kaggle/.local"
<file_sep>/docker/launch_container.sh
#!/bin/bash
IMAGE_NAME=kaggle-docker-updated:latest
CONTAINER_NAME=kaggle-docker-updated-latest
if [ "$(docker image ls -q ${IMAGE_NAME})" == "" ]; then
docker build --build-arg USER_UID=${UID} -t ${IMAGE_NAME} docker
fi
if [ "$(docker container ls -a -q -f name=${CONTAINER_NAME})" == "" ]; then
docker create -it --privileged --net=host --gpus=all \
--volume=/tmp/.X11-unix:/tmp/.X11-unix \
--volume=${HOME}/.Xauthority:/home/kaggle/.Xauthority \
--volume=${PWD}:/kaggle \
--volume=${HOME}/.kaggle:/home/kaggle/.kaggle \
--env=NOTEBOOK_DISABLE_ROOT=1 \
--env=DISPLAY=${DISPLAY} \
--user=kaggle \
--workdir=/kaggle/working \
--name=${CONTAINER_NAME} \
${IMAGE_NAME} \
/bin/bash
fi
docker start -i ${CONTAINER_NAME}
<file_sep>/README.md
# kaggle-python-updated
The official kaggle [dockerfile](https://github.com/Kaggle/docker-python) has an older version of CUDA installed, which may cause build errors when using the latest GPU or the latest CNN framework.
This dockerfile will import the official kaggle dockerfile, install the latest CUDA, and install conda.
- Installing the latest CUDA and conda update
- Same directory structure as kaggle code (/kaggle/input,working)
- Read APIKey under home (~/.kaggle/kaggle.json)
## Usage
Launches a script that performs docker build, container creation and startup.
```
$ cd kaggle-python-updated
$ . /docker/launch_container.sh
(container) $ .
```
If you want to change the name of the container or the image to be generated, modify CONTAINER_NAME and IMAGE_NAME at the top of launch_container.sh.
After the shell of the container is launched, start Jupyter Lab.
```
(container) $ jupyter lab
```
## VS Code integration
You can use VSCode's devcontainer.
- Open the top directory of this repository in VSCode
- Install the extension: Remote-Containers
- Click on the icon at the bottom left of the VSCode window and click on "Reopen in Containers
|
f899378fcc1392f9a7c2430d63cc7b1a4bfe3c00
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 3
|
Dockerfile
|
MKDir43/kaggle-docker-updated
|
55b63016515bf16facf6d54edc44e7eb04ddc51e
|
58f056219e02ef1fc0d334366c0c67a2c7d3daa7
|
refs/heads/master
|
<file_sep>class TrackRecordsController < ApplicationController
TAB_PERSONAL = 'personal'
layout 'content'
before_action :validate_game
helper_method :game
helper_method :personal_tab?
def index
@track, @configuration = filter_params[:track]&.split&.take(2)
@track ||= game.track_data.keys.first
@configuration ||= game.track_data[@track][:configurations].keys.first
@track_obj = game.get_track(@track, @configuration)
@laps = laps.includes(:user).page(filter_params[:page])
unless @laps.first_page?
@last_in_previous_page = laps.page(@laps.prev_page).without_count.last
end
@best_lap = global_laps.first
@current_user_lap = global_laps.where(user: current_user).first
if @current_user_lap
@current_user_position = 1 + global_laps
.where(
'(time < :time) OR (time = :time AND created_at < :created_at)',
time: @current_user_lap.time,
created_at: @current_user_lap.created_at
).count
end
@total_count = global_laps.count
end
private
def validate_game
render_404 unless GAMES.keys.include?(filter_params[:game].to_sym)
end
def filter_params
params.permit(:game, :track, :tab, :page)
end
def game
@game ||= Game.new(filter_params[:game])
end
def filtered_laps
Lap
.track_records
.where(
game: game.id,
track: @track,
configuration: @configuration,
)
.order(time: :asc, created_at: :asc)
end
def global_laps
@global_laps ||= filtered_laps.where(personal_best: true)
end
def personal_laps
@personal_laps ||= filtered_laps.where(user: current_user)
end
def laps
return personal_laps if personal_tab?
global_laps
end
def personal_tab?
filter_params[:tab] == TAB_PERSONAL
end
end
<file_sep>class CalculateTrackRecords < ActiveRecord::Migration[5.0]
def up
Lap.legal_only.each do |lap|
lap.send(:set_track_record)
lap.save if lap.changed?
end
end
end
<file_sep>namespace :development do
USER_NAMES = %w(
<NAME> <NAME>
<NAME>
)
task users: :environment do |task, args|
return unless Rails.env.development?
USER_NAMES.each do |name|
User.find_or_create_by(name: name)
end
end
task laps: :environment do |task, args|
return unless Rails.env.development?
User.all().each do |user|
100.times do
game = GAMES.keys.sample
track = GAMES[game][:tracks].keys.sample
configuration = GAMES[game][:tracks][track][:configurations].keys.sample
car = GAMES[game][:cars].keys.sample
user.laps.create!(
game: game,
track: track,
configuration: configuration,
car: car,
time: (rand * 120000).to_i
)
end
end
end
end
<file_sep>class Api::LapsController < Api::BaseController
def create
lap = Lap.new(lap_params.merge(user: current_user))
if lap.valid?
lap.save
render json: lap
else
render json: lap.errors, status: :bad_request
end
end
private
def lap_params
params.permit(:time, :game, :track, :configuration, :car, :legal)
end
end
<file_sep>RSpec.describe LogoutController, type: :controller do
describe 'index' do
subject { get(:index) }
let(:user) { create(:user) }
it 'logs out user' do
controller.send(:login_user, user)
expect(subject).to have_http_status(:redirect)
expect(session[:user_id]).to be_nil
end
end
end
<file_sep>RSpec.describe ApplicationController, type: :controller do
controller do
def index
render json: {}
end
end
let(:user) { create(:user) }
describe 'require_login' do
controller do
before_action :require_login
end
subject { get(:index) }
context 'when not logged in' do
it { is_expected.to redirect_to(:root) }
end
context 'when logged in' do
subject { get(:index, session: { user_id: user.id }) }
it { is_expected.to have_http_status(:success) }
end
end
describe 'page title' do
subject { controller.send(:format_page_title) }
controller do
set_page_title 'Foobar'
end
it { is_expected.to eq("Foobar - #{PROJECT_TITLE}") }
end
describe 'render_404' do
controller do
def index
render_404
end
end
subject { get(:index) }
it 'raises routing error' do
expect { subject }.to raise_error(ActionController::RoutingError)
end
end
end
<file_sep>class ApiToken < ApplicationRecord
belongs_to :user
has_secure_token :token
validates :user, presence: true
validates :token, uniqueness: true
end
<file_sep>class SettingsController < ApplicationController
before_action :require_login
layout 'content'
set_page_title 'Settings'
def index
@api_token = current_user.get_api_token
end
end
<file_sep>class AddPersonalBestToLap < ActiveRecord::Migration[5.0]
def up
add_column :laps, :personal_best, :boolean, null: false, default: false
end
end
<file_sep>FactoryGirl.define do
factory :api_token do
user
end
end
<file_sep>class ApplicationController < ActionController::Base
class_attribute :page_title
protect_from_forgery with: :exception
helper_method :current_user
helper_method :format_page_title
helper_method :track_option
private
def require_login
redirect_to root_path unless current_user
end
def login_user(user)
session[:user_id] = user.id
end
def logout_user
session[:user_id] = nil
end
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
def self.set_page_title(title)
self.page_title = title
end
def format_page_title
prefix = Rails.env.development? ? '(dev) ' : ''
title = page_title? ? page_title + ' - ' : ''
prefix + title + PROJECT_TITLE
end
def render_404
raise ActionController::RoutingError.new('Not Found')
end
def track_option(track_id, configuration)
"#{track_id} #{configuration}"
end
end
<file_sep>RSpec.describe Car, type: :model do
let(:car) { Car.new(game_id, car_id) }
let(:game_id) { :assetto_corsa }
let(:car_id) { :abarth500 }
describe 'name' do
subject { car.name }
it { is_expected.to eq('Abarth 500 EsseEsse') }
context 'when game_id and car_id are unknonw' do
let(:game_id) { :foo }
let(:car_id) { :bar }
it { is_expected.to eq(car_id) }
end
end
end
<file_sep>class ExtractSteamIds < ActiveRecord::Migration[5.0]
def up
User.all.each do |user|
next unless user.steam_id
new_id = user.steam_id.match(/\/openid\/id\/(?<id>\d+)/)[:id]
user.update(steam_id: new_id)
end
end
end
<file_sep>RSpec.describe SettingsController, type: :controller do
describe 'index' do
subject { get(:index, session: { user_id: user.id }) }
let(:user) { create(:user) }
it { is_expected.to have_http_status(:success) }
it 'displays api token' do
subject
expect(assigns[:api_token]).to eq(user.get_api_token)
end
end
end
<file_sep>class SteamAuthController < ApplicationController
# http://steamcommunity.com/dev
# http://openid.net/specs/openid-authentication-2_0.html#requesting_authentication
def login
redirect_to URI::HTTPS.build(
host: 'steamcommunity.com',
path: '/openid/login',
query: {
'openid.ns' => 'http://specs.openid.net/auth/2.0',
'openid.mode' => 'checkid_setup',
'openid.return_to' => url_for(action: :verify, only_path: false),
'openid.realm' => root_url,
'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select'
}.to_query
).to_s
end
def verify
response = Net::HTTP.post_form(
URI('https://steamcommunity.com/openid/login'),
verify_params.merge('openid.mode' => 'check_authentication')
)
if response.body.split.any? { |line| line == 'is_valid:true' }
user = User.find_or_create_by(steam_id: steam_id) do |user|
user.name = steam_profile['personaname']
end
login_user(user)
end
redirect_to root_path
end
private
def steam_id
@steam_id ||= begin
match = params['openid.claimed_id'].try(:match, /\/openid\/id\/(?<id>\d+)/)
match[:id] if match
end
end
def verify_params
params.permit(
'openid.ns', 'openid.mode', 'openid.op_endpoint', 'openid.claimed_id',
'openid.identity', 'openid.return_to', 'openid.response_nonce',
'openid.assoc_handle', 'openid.signed', 'openid.sig'
)
end
def steam_profile
@steam_profile ||= begin
uri = URI::HTTPS.build(
host: 'api.steampowered.com',
path: '/ISteamUser/GetPlayerSummaries/v0002',
query: { key: ENV['STEAM_API_KEY'], steamids: steam_id }.to_query
)
content = JSON.parse(Net::HTTP.get(uri))
content['response']['players'].first
end
end
end
<file_sep>GAMES = {
assetto_corsa: ASSETTO_CORSA
}
<file_sep>ASSETTO_CORSA = {
name: '<NAME>',
tag: 'AC',
tracks: {
algarve_international_circuit: {
track: :algarve,
configurations: {
standard: :gp
}
},
circuit_de_la_sarthe: {
track: :circuit_de_la_sarthe,
configurations: {
'24hours': :standard,
nochicane: :nochicane
}
},
doningtonpark: {
track: :donington_park,
configurations: {
gp: :gp,
national: :national
}
},
drift: {
track: :ac_drift,
configurations: {
standard: :standard
}
},
imola: {
track: :imola,
configurations: {
standard: :standard
}
},
ks_barcelona: {
track: :barcelona,
configurations: {
layout_gp: :gp,
layout_moto: :moto
}
},
ks_black_cat_county: {
track: :black_cat_county,
configurations: {
layout_short: :short,
layout_int: :standard,
layout_long: :long
}
},
ks_brands_hatch: {
track: :brands_hatch,
configurations: {
gp: :gp,
indy: :indy
}
},
ks_drag: {
track: :ac_drag,
configurations: {
drag200: :drag200,
drag400: :drag400,
drag500: :drag500,
drag1000: :drag1000,
drag2000: :drag2000
}
},
ks_highlands: {
track: :highlands,
configurations: {
layout_drift: :drift,
layout_short: :short,
layout_int: :standard,
layout_long: :long
}
},
ks_monza66: {
track: :monza,
configurations: {
full: :full1966,
junior: :junior1966,
road: :road1966
}
},
ks_nordschleife: {
track: :nurburgring,
configurations: {
nordschleife: :nordschleife,
endurance: :nordschleife_endurance,
touristenfahrten: :nordschleife_tourist
}
},
ks_nurburgring: {
track: :nurburgring,
configurations: {
layout_gp_a: :gp,
layout_gp_b: :gp_gt,
layout_sprint_a: :sprint,
layout_sprint_b: :sprint_gt
}
},
ks_red_bull_ring: {
track: :red_bull_ring,
configurations: {
layout_gp: :gp,
layout_national: :national
}
},
ks_silverstone: {
track: :silverstone,
configurations: {
gp: :gp,
international: :international,
national: :national
}
},
ks_silverstone1967: {
track: :silverstone,
configurations: {
standard: :gp1967
}
},
ks_vallelunga: {
track: :vallelunga,
configurations: {
classic_circuit: :classic,
club_circuit: :club,
extended_circuit: :standard
}
},
ks_zandvoort: {
track: :zandvoort,
configurations: {
standard: :standard
}
},
magione: {
track: :magione,
configurations: {
standard: :standard
}
},
monza: {
track: :monza,
configurations: {
standard: :standard
}
},
mugello: {
track: :mugello,
configurations: {
standard: :standard
}
},
spa: {
track: :spa,
configurations: {
standard: :standard
}
},
'trento-bondone': {
track: :trento_bondone,
configurations: {
standard: :standard
}
},
},
cars: {
abarth500_s1: { name: 'Abarth 500 EsseEsse Step1' },
abarth500: { name: 'Abarth 500 EsseEsse' },
alfa_romeo_giulietta_qv_le: { name: 'A<NAME> Giulietta QV Launch Edition 2014' },
alfa_romeo_giulietta_qv: { name: 'A<NAME> QV' },
bmw_1m_s3: { name: 'BMW 1M Stage 3' },
bmw_1m: { name: 'BMW 1M' },
bmw_m3_e30_drift: { name: 'BMW M3 E30 Drift' },
bmw_m3_e30_dtm: { name: 'BMW M3 E30 Gr.A 92' },
bmw_m3_e30_gra: { name: 'BMW M3 E30 Group A' },
bmw_m3_e30_s1: { name: 'BMW M3 E30 Step1' },
bmw_m3_e30: { name: 'BMW M3 E30' },
bmw_m3_e92_drift: { name: 'BMW M3 E92 drift' },
bmw_m3_e92_s1: { name: 'BMW M3 E92 Step1' },
bmw_m3_e92: { name: 'BMW M3 E92' },
bmw_m3_gt2: { name: 'BMW M3 GT2' },
bmw_z4_drift: { name: 'BMW Z4 E89 Drift' },
bmw_z4_gt3: { name: 'BMW Z4 GT3' },
bmw_z4_s1: { name: 'BMW Z4 E89 Step1' },
bmw_z4: { name: 'BMW Z4 E89' },
ferrari_312t: { name: 'Ferrari 312T' },
ferrari_458_gt2: { name: 'Ferrari 458 GT2' },
ferrari_458_s3: { name: 'Ferrari 458 Italia Stage 3' },
ferrari_458: { name: 'Ferrari 458 Italia' },
ferrari_599xxevo: { name: 'Ferrari 599XX EVO' },
ferrari_f40_s3: { name: 'Ferrari F40 Stage 3' },
ferrari_f40: { name: 'Ferrari F40' },
ferrari_laferrari: { name: 'F<NAME>' },
ks_abarth_595ss_s1: { name: 'Abarth 595 SS Step 1' },
ks_abarth_595ss_s2: { name: 'Abarth 595 SS Step 2' },
ks_abarth_595ss: { name: 'Abarth 595 SS' },
ks_abarth500_assetto_corse: { name: 'Abarth 500 Assetto Corse' },
ks_alfa_mito_qv: { name: 'Alfa Romeo Mito QV' },
ks_alfa_romeo_155_v6: { name: 'Alfa Romeo 155 TI V6' },
ks_alfa_romeo_4c: { name: 'Alfa Romeo 4C' },
ks_alfa_romeo_gta: { name: 'Alfa Romeo GTA' },
ks_audi_a1s1: { name: 'Audi S1' },
ks_audi_r8_lms: { name: 'Audi R8 LMS Ultra' },
ks_audi_r8_plus: { name: 'Audi R8 V10 Plus' },
ks_audi_sport_quattro_rally: { name: 'Audi Sport quattro S1 E2' },
ks_audi_sport_quattro_s1: { name: 'Audi Sport quattro Step1' },
ks_audi_sport_quattro: { name: 'Audi Sport quattro' },
ks_bmw_m235i_racing: { name: 'BMW M235i Racing' },
ks_bmw_m4_akrapovic: { name: 'BMW M4 Akrapovic' },
ks_bmw_m4: { name: 'BMW M4' },
ks_corvette_c7_stingray: { name: 'Chevrolet Corvette C7 Stingray' },
ks_corvette_c7r: { name: 'Chevrolet Corvette C7R' },
ks_ferrari_488_gt3: { name: 'Ferrari 488 GT3' },
ks_ferrari_488_gtb: { name: 'Ferrari 488 GTB' },
ks_ferrari_f138: { name: 'Ferrari F138' },
ks_ferrari_fxx_k: { name: 'Ferrari FXX K' },
ks_ferrari_sf15t: { name: 'Ferrari SF15-T' },
ks_ford_escort_mk1: { name: 'Ford Escort RS1600' },
ks_ford_gt40: { name: 'Ford GT40' },
ks_ford_mustang_2015: { name: 'Ford Mustang 2015' },
ks_glickenhaus_scg003: { name: 'SCG 003C' },
ks_lamborghini_aventador_sv: { name: 'Lamborghini Aventador SV' },
ks_lamborghini_countach_s1: { name: 'Lamborghini Countach S1' },
ks_lamborghini_countach: { name: 'Lamborghini Countach' },
ks_lamborghini_gallardo_sl_s3: { name: 'Lamborghini Gallardo SL Step3' },
ks_lamborghini_gallardo_sl: { name: 'Lamborghini Gallardo SL' },
ks_lamborghini_huracan_gt3: { name: 'Lamborghini Huracan GT3' },
ks_lamborghini_huracan_st: { name: 'Lamborghini Huracan ST' },
ks_lamborghini_miura_sv: { name: 'Lamborghini Miura P400 SV' },
ks_lotus_25: { name: 'Lotus Type 25' },
ks_lotus_72d: { name: 'Lotus 72D' },
ks_maserati_250f_12cyl: { name: 'Maserati 250F 12 cylinder' },
ks_maserati_250f_6cyl: { name: 'Maserati 250F 6 cylinder' },
ks_maserati_gt_mc_gt4: { name: 'Maserati GranTurismo MC GT4' },
ks_maserati_levante: { name: 'Maserati Levante S' },
ks_mazda_mx5_cup: { name: 'Mazda MX5 Cup' },
ks_mazda_mx5_nd: { name: 'Mazda MX5 ND' },
ks_mazda_rx7_spirit_r: { name: 'Mazda RX-7 Spirit R' },
ks_mazda_rx7_tuned: { name: 'Mazda RX-7 Tuned' },
ks_mclaren_650_gt3: { name: 'McLaren 650S GT3' },
ks_mclaren_f1_gtr: { name: 'McLaren F1 GTR' },
ks_mclaren_p1: { name: 'McLaren P1' },
ks_mercedes_190_evo2: { name: 'Mercedes-Benz 190E EVO II' },
ks_mercedes_amg_gt3: { name: 'Mercedes-Benz AMG GT3' },
ks_mercedes_c9: { name: 'Mercedes-Benz C9 1989 LM' },
ks_nissan_370z: { name: 'Nissan 370z Nismo' },
ks_nissan_gtr_gt3: { name: 'Nissan GT-R GT3' },
ks_nissan_gtr: { name: 'Nissan GT-R NISMO' },
ks_nissan_skyline_r34: { name: 'Nissan Skyline GTR R34 V-Spec' },
ks_porsche_718_boxster_s_pdk: { name: 'Porsche 718 Boxster S PDK' },
ks_porsche_718_boxster_s: { name: 'Porsche 718 Boxster S' },
ks_porsche_718_cayman_s: { name: 'Porsche 718 Cayman S' },
ks_porsche_718_spyder_rs: { name: 'Porsche 718 RS 60 Spyder' },
ks_porsche_908_lh: { name: 'Porsche 908 LH' },
ks_porsche_911_carrera_rsr: { name: 'Porsche 911 Carrera RSR 3.0' },
ks_porsche_911_gt1: { name: 'Porsche 911 GT1-98' },
ks_porsche_911_gt3_cup_2017: { name: 'Porsche 911 GT3 Cup 2017' },
ks_porsche_911_gt3_r_2016: { name: 'Porsche 911 GT3 R 2016' },
ks_porsche_911_gt3_rs: { name: 'Porsche 911 GT3 RS' },
ks_porsche_911_r: { name: 'Porsche 911 R' },
ks_porsche_917_30: { name: 'Porsche 917/30 Spyder' },
ks_porsche_917_k: { name: 'Porsche 917 K' },
ks_porsche_918_spyder: { name: 'Porsche 918 Spyder' },
ks_porsche_919_hybrid_2015: { name: 'Porsche 919 Hybrid 2015' },
ks_porsche_919_hybrid_2016: { name: 'Porsche 919 Hybrid 2016' },
ks_porsche_935_78_moby_dick: { name: 'Porsche 935/78 Moby Dick' },
ks_porsche_962c_longtail: { name: 'Porsche 962 C Long Tail' },
ks_porsche_962c_shorttail: { name: 'Porsche 962 C Short Tail' },
ks_porsche_991_carrera_s: { name: 'Porsche 911 Carrera S' },
ks_porsche_991_turbo_s: { name: 'Porsche 911 Turbo S' },
ks_porsche_cayenne: { name: 'Porsche Cayenne Turbo S' },
ks_porsche_cayman_gt4_clubsport: { name: 'Porsche Cayman GT4 Clubsport' },
ks_porsche_cayman_gt4_std: { name: 'Porsche Cayman GT4' },
ks_porsche_macan: { name: 'Porsche Macan Turbo' },
ks_porsche_panamera: { name: 'Porsche Panamera Turbo' },
ks_praga_r1: { name: 'Praga R1' },
ks_ruf_rt12r_awd: { name: 'RUF RT12 R AWD' },
ks_ruf_rt12r: { name: 'RUF RT12 R' },
ks_toyota_ae86_drift: { name: 'Toyota AE86 Drift' },
ks_toyota_ae86_tuned: { name: 'Toyota AE86 Tuned' },
ks_toyota_ae86: { name: 'Toyota AE86' },
ks_toyota_gt86: { name: 'Toyota GT86' },
ks_toyota_supra_mkiv_drift: { name: 'Toyota Supra MKIV Drift' },
ks_toyota_supra_mkiv_tuned: { name: 'Toyota Supra MKIV Time Attack' },
ks_toyota_supra_mkiv: { name: 'Toyota Supra MKIV' },
ktm_xbow_r: { name: 'KTM X-Bow R' },
lotus_2_eleven_gt4: { name: 'Lotus 2 Eleven GT4' },
lotus_2_eleven: { name: 'Lotus 2 Eleven' },
lotus_49: { name: 'Lotus Type 49' },
lotus_98t: { name: 'Lotus 98T' },
lotus_elise_sc_s1: { name: 'Lotus Elise SC Step1' },
lotus_elise_sc_s2: { name: 'Lotus Elise SC Step2' },
lotus_elise_sc: { name: 'Lotus Elise SC' },
lotus_evora_gtc: { name: 'Lotus Evora GTC' },
lotus_evora_gte_carbon: { name: 'Lotus Evora GTE Carbon' },
lotus_evora_gte: { name: 'Lotus Evora GTE' },
lotus_evora_gx: { name: 'Lotus Evora GX' },
lotus_evora_s_s2: { name: 'Lotus Evora S Stage 2' },
lotus_evora_s: { name: 'Lotus Evora S' },
lotus_exige_240_s3: { name: 'Lotus Exige 240R Stage3' },
lotus_exige_240: { name: 'Lotus Exige 240R' },
lotus_exige_s_roadster: { name: 'Lotus Exige S roadster' },
lotus_exige_s: { name: 'Lotus Exige S' },
lotus_exige_scura: { name: 'Lotus Exige Scura' },
lotus_exige_v6_cup: { name: 'Lotus Exige V6 CUP' },
lotus_exos_125_s1: { name: 'Lotus Exos 125 Stage 1' },
lotus_exos_125: { name: 'Lotus Exos 125' },
mclaren_mp412c_gt3: { name: 'McLaren MP4-12C GT3' },
mclaren_mp412c: { name: 'McLaren MP4-12C' },
mercedes_sls_gt3: { name: 'Mercedes SLS AMG GT3' },
mercedes_sls: { name: 'Mercedes SLS AMG' },
'p4-5_2011': { name: 'P4/5 Competizione 2011' },
pagani_huayra: { name: '<NAME>' },
pagani_zonda_r: { name: '<NAME>' },
ruf_yellowbird: { name: 'RUF CTR Yellowbird' },
shelby_cobra_427sc: { name: 'Shelby Cobra 427 S/C' },
tatuusfa1: { name: 'Tatuus FA01' }
}
}
<file_sep>TRACKS = {
ac_drag: {
name: 'Drag',
configurations: {
drag200: {
name: '200m'
},
drag400: {
name: '400m'
},
drag500: {
name: '500m'
},
drag1000: {
name: '1000m'
},
drag2000: {
name: '2000m'
}
}
},
ac_drift: {
name: 'Drift',
configurations: {
standard: {
name: 'Standard'
}
}
},
algarve: {
name: 'Algarve International Circuit',
configurations: {
gp: {
name: 'GP'
}
}
},
barcelona: {
name: 'Barcelona',
configurations: {
gp: {
name: 'GP'
},
moto: {
name: 'Moto'
}
}
},
black_cat_county: {
name: 'Black Cat County',
configurations: {
short: {
name: 'Short'
},
standard: {
name: 'Standard'
},
long: {
name: 'Long'
}
}
},
brands_hatch: {
name: 'Brands Hatch',
configurations: {
gp: {
name: 'GP'
},
indy: {
name: 'Indy'
}
}
},
circuit_de_la_sarthe: {
name: 'Circuit de la Sarthe',
configurations: {
standard: {
name: 'Standard'
},
nochicane: {
name: 'No Chicane'
},
}
},
donington_park: {
name: 'Donington Park',
configurations: {
gp: {
name: 'GP'
},
national: {
name: 'National'
},
}
},
highlands: {
name: 'Highlands',
configurations: {
drift: {
name: 'Drift'
},
short: {
name: 'Short'
},
standard: {
name: 'Standard'
},
long: {
name: 'Long'
}
}
},
imola: {
name: 'Imola',
configurations: {
standard: {
name: 'Standard'
}
}
},
magione: {
name: 'Magione',
configurations: {
standard: {
name: 'Standard'
}
}
},
monza: {
name: 'Monza',
configurations: {
standard: {
name: 'Standard'
},
full1966: {
name: 'Full (1966)'
},
junior1966: {
name: 'Junior (1966)'
},
road1966: {
name: 'Road (1966)'
}
}
},
mugello: {
name: 'Mugello',
configurations: {
standard: {
name: 'Standard'
}
}
},
nurburgring: {
name: 'Nürburgring',
configurations: {
nordschleife: {
name: 'Nordschleife'
},
nordschleife_endurance: {
name: 'Nordschleife (Endurance)'
},
nordschleife_tourist: {
name: 'Nordschleife (Tourist)'
},
gp: {
name: 'GP'
},
gp_gt: {
name: 'GP (GT)'
},
sprint: {
name: 'Sprint'
},
sprint_gt: {
name: 'Sprint (GT)'
}
}
},
red_bull_ring: {
name: '<NAME>',
configurations: {
gp: {
name: 'GP'
},
national: {
name: 'National'
}
}
},
silverstone: {
name: 'Silverstone',
configurations: {
gp: {
name: 'GP'
},
international: {
name: 'International'
},
national: {
name: 'National'
},
gp1967: {
name: 'GP (1967)'
}
}
},
spa: {
name: 'Circuit de Spa-Francorchamps',
configurations: {
standard: {
name: 'Standard'
}
}
},
trento_bondone: {
name: 'Trento-Bondone',
configurations: {
standard: {
name: 'Standard'
}
}
},
vallelunga: {
name: 'Vallelunga',
configurations: {
classic: {
name: 'Classic'
},
club: {
name: 'Club'
},
standard: {
name: 'Standard'
}
}
},
zandvoort: {
name: 'Zandvoort',
configurations: {
standard: {
name: 'Standard'
}
}
}
}
<file_sep>RSpec.describe Lap, type: :model do
let(:lap) do
build(
:lap,
user: user,
time: 60,
game: game,
track: track,
configuration: configuration,
car: car,
legal: legal
)
end
let!(:previous_lap) do
create(
:lap,
user: user,
time: 70,
game: game,
track: track,
configuration: configuration,
car: car,
legal: true,
personal_best: true,
track_record: true
)
end
let(:user) { create(:user) }
let(:game) { :assetto_corsa }
let(:track) { :ks_brands_hatch }
let(:configuration) { :indy }
let(:car) { :abarth500 }
let(:legal) { true }
describe 'valid?' do
subject { lap.valid? }
it { is_expected.to be_truthy }
end
describe 'save' do
subject { lap.save }
before { subject }
it 'sets personal best' do
expect(previous_lap.reload.personal_best?).to be_falsey
expect(lap.personal_best?).to be_truthy
end
it 'sets track record' do
expect(previous_lap.reload.track_record?).to be_falsey
expect(lap.track_record?).to be_truthy
end
context 'when not legal' do
let(:legal) { false }
it 'does not change personal best' do
expect(previous_lap.reload.personal_best?).to be_truthy
expect(lap.personal_best?).to be_falsey
end
it 'does not change track record' do
expect(previous_lap.reload.track_record?).to be_truthy
expect(lap.track_record?).to be_falsey
end
end
end
describe 'game_obj' do
subject { lap.game_obj }
it 'returns a Game object' do
expect(subject).to be_a(Game)
expect(subject.id).to eq(game)
end
end
end
<file_sep>RSpec.describe Api::LapsController, type: :controller do
let(:user) { create(:user, :with_api_token) }
before do
request.headers['Authorization'] = "Token token=#{user.api_token.token}"
end
describe 'create' do
subject { post :create, params: lap_data }
let(:lap_data) do
{
time: (1.minute + 20.seconds) * 1000,
game: :assetto_corsa,
track: :ks_brands_hatch,
configuration: :indy,
car: :ks_mazda_mx5_nd,
legal: true
}
end
it 'responds with bad request' do
subject
expect(response).to have_http_status(:success)
end
context 'when lap is not valid' do
let(:lap_data) { {} }
it 'responds with bad request' do
subject
expect(response).to have_http_status(:bad_request)
end
end
end
end
<file_sep>class User < ApplicationRecord
validates :name, presence: true
has_one :api_token
has_many :laps
def get_api_token
ApiToken.find_or_create_by(user: self)
end
end
<file_sep>class LeaderboardsController < ApplicationController
TAB_PERSONAL = 'personal'
layout 'content'
before_action :validate_game
helper_method :game
helper_method :personal_tab?
helper_method :top_combos
def index
@track, @configuration = filter_params[:track]&.split&.take(2)
@track ||= game.track_data.keys.first
@configuration ||= game.track_data[@track][:configurations].keys.first
@car = filter_params[:car] || @game.car_options.first[0]
@track_obj = game.get_track(@track, @configuration)
@laps = laps.includes(:user).page(filter_params[:page])
unless @laps.first_page?
@last_in_previous_page = laps.page(@laps.prev_page).without_count.last
end
@best_lap = global_laps.first
@current_user_lap = global_laps.where(user: current_user).first
if @current_user_lap
@current_user_position = 1 + global_laps
.where(
'(time < :time) OR (time = :time AND created_at < :created_at)',
time: @current_user_lap.time,
created_at: @current_user_lap.created_at
).count
end
@total_count = global_laps.count
end
private
def validate_game
render_404 unless GAMES.keys.include?(filter_params[:game].to_sym)
end
def filter_params
params.permit(:game, :track, :car, :tab, :page)
end
def game
@game ||= Game.new(filter_params[:game])
end
def filtered_laps
Lap
.legal_only
.where(
game: game.id,
track: @track,
configuration: @configuration,
car: @car
)
.order(time: :asc, created_at: :asc)
end
def global_laps
@global_laps ||= filtered_laps.where(personal_best: true)
end
def personal_laps
@personal_laps ||= filtered_laps.where(user: current_user)
end
def laps
return personal_laps if personal_tab?
global_laps
end
def personal_tab?
filter_params[:tab] == TAB_PERSONAL
end
def top_combos
Lap
.legal_only.pbs
.group(:game, :track, :configuration, :car)
.order('count_all desc').limit(10).count()
.map do |combo, count|
game_id, track_id, configuration, car_id = combo
game_obj = Game.new(game_id)
{
game_id: game_id,
game_obj: game_obj,
track_id: track_id,
configuration: configuration,
track_obj: game_obj.get_track(track_id, configuration),
car_id: car_id,
car_obj: game_obj.get_car(car_id),
count: count
}
end
end
end
<file_sep>class GuidesController < ApplicationController
layout 'content'
def index
end
end
<file_sep>class Car
attr_reader :game_id
attr_reader :id
def initialize(game_id, id)
@game_id = game_id.to_sym
@id = id.to_sym
end
def name
data[:name] || id
end
private
def data
@data ||= GAMES.dig(game_id, :cars, id) || {}
end
end
<file_sep>class DashboardController < ApplicationController
before_action :require_login
layout 'content'
set_page_title 'Dashboard'
def index
@laps = current_user.laps.order(created_at: :desc).page(params[:page])
@top_combos = fetch_top_combos
@top_tracks = fetch_top_tracks
@top_cars = fetch_top_cars
end
private
def fetch_top_combos
current_user.laps.legal_only
.group(:game, :track, :configuration, :car)
.order('count_all desc').limit(5).count()
.map do |combo, count|
game_id, track_id, configuration, car_id = combo
game = Game.new(game_id)
{
game: game,
track_id: track_id,
configuration: configuration,
track: game.get_track(track_id, configuration),
car: game.get_car(car_id),
count: count
}
end
end
def fetch_top_tracks
current_user.laps.legal_only
.group(:game, :track, :configuration)
.order('count_all desc').limit(5).count()
.map do |group, count|
game_id, track_id, configuration = group
game = Game.new(game_id)
track = game.get_track(track_id, configuration)
{
game: game,
track_id: track_id,
configuration: configuration,
track: track,
count: count
}
end
end
def fetch_top_cars
current_user.laps.legal_only
.group(:game, :car)
.order('count_all desc').limit(5).count()
.map do |group, count|
game = Game.new(group[0])
{
game: game,
car: game.get_car(group[1]),
count: count
}
end
end
end
<file_sep>class HomeController < ApplicationController
layout 'content'
def index
redirect_to dashboard_path if current_user
end
end
<file_sep>FactoryGirl.define do
factory :user do
sequence :name { |n| "user{n}" }
trait :with_api_token do
api_token
end
end
end
<file_sep>module ApplicationHelper
def format_lap_time(t)
s, ms = t / 1000, t % 1000
m, s = s / 60, s % 60
"%d:%02d.%03d" % [m, s, ms]
end
end
<file_sep>class RecalculatePersonalBests < ActiveRecord::Migration[5.0]
def up
Lap.all.map(&:save)
end
end
<file_sep>class Track
STANDARD_CONFIGURATION = :standard
attr_reader :id
attr_reader :configuration
def initialize(id, configuration)
@id = id.to_sym
@configuration = configuration.to_sym
end
def title
return name if standard?
"#{name} #{configuration_name}"
end
def name
name = TRACKS.dig(id, :name) || id
end
def configuration_name
configuration_data[:name] || configuration
end
def standard?
configuration == STANDARD_CONFIGURATION
end
private
def data
@data ||= TRACKS[id] || {}
end
def configuration_data
@configuration_data ||= data.dig(:configurations, configuration) || {}
end
end
<file_sep>RSpec.describe Api::BaseController, type: :controller do
controller do
def index
render json: {}
end
end
describe 'authorization' do
context 'with token' do
let(:user) { create(:user, :with_api_token) }
it 'is unauthorized' do
request.headers['Authorization'] = "Token token=#{user.api_token.token}"
get :index
expect(response).to have_http_status(:success)
end
end
context 'without token' do
it 'is unauthorized' do
get :index
expect(response).to have_http_status(:unauthorized)
end
end
context 'with unknown token' do
it 'is unauthorized' do
request.headers['Authorization'] = "Token token=foobar"
get :index
expect(response).to have_http_status(:unauthorized)
end
end
end
end
<file_sep>PROJECT_TITLE = 'Crono'
<file_sep>RSpec.describe :data do
describe 'track data' do
it 'is valid' do
TRACKS.each do |track_id, track|
expect(track_id).to be_a(Symbol), "#{track_id}"
expect(track[:name]).to be_a(String), "#{track_id}"
track[:configurations].each do |configuration_id, configuration|
expect(configuration_id).to be_a(Symbol), "#{track_id} #{configuration_id}"
expect(configuration[:name]).to be_a(String), "#{track_id} #{configuration_id}"
end
end
end
shared_examples 'valid game data'
end
describe 'game data' do
it 'is valid' do
GAMES.each do |game_id, game|
expect(game_id).to be_a(Symbol), "#{game_id}"
expect(game[:name]).to be_a(String), "#{game_id}"
game[:tracks].each do |game_track_id, game_track|
expect(game_track_id).to be_a(Symbol), "#{game_id} #{game_track_id}"
track = TRACKS[game_track[:track]]
expect(track).to_not be_nil, "#{game_id} #{game_track_id}"
game_track[:configurations].each do |game_configuration, configuration|
expect(track[:configurations][configuration]).to_not be_nil, "#{game_id} #{game_track_id} #{game_configuration}"
end
end
game[:cars].each do |car_id, car|
expect(car_id).to be_a(Symbol), "#{game_id} #{car_id}"
expect(car[:name]).to be_a(String), "#{game_id} #{car_id}"
end
end
end
end
end
<file_sep># Crono
Sim racing stats aggregator.
## Setup
* https://github.com/rbenv/rbenv
* http://bundler.io/
### Running on Bash on Windows
https://msdn.microsoft.com/en-us/commandline/wsl/install_guide
You may need to install certain dependencies:
```
sudo apt-get install build-essential
sudo apt-get install -y libssl-dev libreadline-dev zlib1g-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install nodejs
sudo apt-get install cmake
sudo apt-get install pkg-config
```
Use `NO_WATCH` environment variable to disable file watcher (see `config/environments/development.rb`)
```
NO_WATCH= bundle exec rails server
```
<file_sep>require 'net/http'
RSpec.describe SteamAuthController, type: :controller do
describe 'login' do
subject { get(:login) }
it { is_expected.to have_http_status(:redirect) }
end
describe 'verify' do
subject { get(:verify, params: params) }
let(:params) { { foo: :bar } }
let(:authentication_check_response) { 'is_valid:true' }
let(:steam_user_name) { 'foobar' }
let(:steam_profile_response) do
JSON.generate(
{
response: {
players: [
{
personaname: steam_user_name
}
]
}
}
)
end
before do
expect(Net::HTTP).to(
receive(:post_form)
.and_return(double(body: authentication_check_response))
)
expect(Net::HTTP).to(receive(:get).and_return(steam_profile_response))
end
it 'logs in user' do
expect(subject).to have_http_status(:redirect)
expect(controller.send(:current_user)).to eq(User.last)
expect(User.last.name).to eq(steam_user_name)
end
end
end
<file_sep>FactoryGirl.define do
factory :lap do
user
sequence(:time)
end
end
<file_sep>Rails.application.routes.draw do
root 'home#index'
get '/steam_auth/login', to: 'steam_auth#login'
get '/steam_auth/verify', to: 'steam_auth#verify'
get '/logout', to: 'logout#index', as: :logout
get '/dashboard', to: 'dashboard#index', as: :dashboard
get '/leaderboards/:game', to: 'leaderboards#index', as: :leaderboards
get '/track_records/:game', to: 'track_records#index', as: :track_records
get '/guides', to: 'guides#index', as: :guides
get '/settings', to: 'settings#index', as: :settings
namespace :api do
resources :laps, only: [:create]
end
end
<file_sep>RSpec.describe Game do
let(:game) { Game.new(id) }
let(:id) { :assetto_corsa }
it 'has a name' do
expect(game.name).to eq(GAMES[id][:name])
end
it 'has a tag' do
expect(game.tag).to eq(GAMES[id][:tag])
end
describe 'get_track' do
subject { game.get_track(track, configuration) }
let(:track) { :ks_brands_hatch }
let(:configuration) { :indy }
it 'returns a track instance' do
expect(subject).to be_a(Track)
expect(subject.id).to eq(GAMES[id][:tracks][track][:track])
expect(subject.configuration).to eq(
GAMES[id][:tracks][track][:configurations][configuration]
)
end
end
describe 'get_car' do
subject { game.get_car(car) }
let(:car) { :ks_mazda_mx5_nd }
it 'returns a car instance' do
expect(subject).to be_a(Car)
expect(subject.game_id).to eq(id)
expect(subject.id).to eq(car)
end
end
context 'when id is unknown' do
let(:id) { :foobar }
it 'has a name' do
expect(game.name).to eq(id)
end
it 'has a tag' do
expect(game.tag).to eq(id)
end
end
end
<file_sep>RSpec.describe Track, type: :model do
let(:track) { Track.new(id, configuration) }
let(:id) { :brands_hatch }
let(:configuration) { :gp }
describe 'title' do
subject { track.title }
it { is_expected.to eq('Brands Hatch GP') }
context 'when configuration is standard' do
let(:configuration) { Track::STANDARD_CONFIGURATION }
it { is_expected.to eq('Brands Hatch') }
end
context 'when id and configuration are unknonw' do
let(:id) { :foo }
let(:configuration) { :bar }
it { is_expected.to eq('foo bar') }
end
end
end
<file_sep>class CreateLap < ActiveRecord::Migration[5.0]
def change
create_table :laps do |t|
t.integer :user_id, null: false, index: true
t.integer :time, null: false
t.string :game, null: false, index: true
t.string :track, null: false, index: true
t.string :configuration, null: false, index: true
t.string :car, null: false, index: true
t.timestamps
end
end
end
<file_sep>class Api::BaseController < ActionController::Base
before_action :authenticate
private
def current_user
@current_user
end
def authenticate
api_token = authenticate_with_http_token do |token, options|
ApiToken.find_by(token: token)
end
unless api_token
return render(json: { error: 'Unauthorized' }, status: :unauthorized)
end
@current_user = api_token.user
end
end
<file_sep>class Lap < ApplicationRecord
belongs_to :user
validates :user, presence: true
validates(
:time,
presence: true,
numericality: { only_integer: true, greater_than: 0 }
)
validates(
:game,
presence: true,
length: { maximum: 255 },
inclusion: { in: GAMES.keys.map(&:to_s) }
)
validates :track, presence: true, length: { maximum: 255 }
validates :configuration, presence: true, length: { maximum: 255 }
validates :car, presence: true, length: { maximum: 255 }
validates :personal_best, inclusion: { in: [true, false] }
validates :track_record, inclusion: { in: [true, false] }
validates :legal, inclusion: { in: [true, false] }
before_create :set_personal_best, if: :legal?
before_create :set_track_record, if: :legal?
scope :legal_only, -> { where(legal: true) }
scope :pbs, -> { where(personal_best: true) }
scope :track_records, -> { where(track_record: true) }
def game_obj
@game_obj ||= Game.new(game)
end
def car_obj
@car_obj ||= game_obj.get_car(car)
end
def track_obj
@track_obj ||= game_obj.get_track(track, configuration)
end
private
def set_personal_best
current_personal_best = user.laps.legal_only.where(
game: game,
track: track,
configuration: configuration,
car: car,
personal_best: true
).first
if current_personal_best.blank? || (time < current_personal_best.time)
current_personal_best&.update(personal_best: false)
self.personal_best = true
end
end
def set_track_record
current_track_record = Lap.legal_only.where(
game: game,
track: track,
configuration: configuration,
car: car,
track_record: true
).first
if current_track_record.blank? || (time < current_track_record.time)
current_track_record&.update(track_record: false)
self.track_record = true
end
end
end
<file_sep>class Game
attr_reader :id
def initialize(id)
@id = id.to_sym
end
def name
data[:name] || id
end
def tag
data[:tag] || id
end
def get_track(track_id, configuration)
Track.new(
track_data.dig(track_id, :track) || track_id,
track_data.dig(track_id, :configurations, configuration) || configuration
)
end
def get_car(car_id)
Car.new(id, car_id)
end
def track_data
(data[:tracks] || {}).with_indifferent_access
end
def car_data
(data[:cars] || {}).with_indifferent_access
end
def data
@data ||= GAMES[id] || {}
end
def track_options
@track_options ||= track_data.map do |track_id, track_data|
track_data[:configurations].map do |configuration, _|
[
[track_id, configuration],
get_track(track_id, configuration)
]
end
end
.flatten(1)
.sort_by { |_, track| track.title }
end
def car_options
@car_options ||= car_data.sort_by { |_, car_data| car_data[:name] }
end
end
<file_sep>RSpec.describe User, type: :model do
let(:user) { create(:user) }
describe 'get_api_token' do
subject { user.get_api_token }
it 'creates api token for user' do
expect(subject).to be_an(ApiToken)
expect(subject.user).to eq(user)
end
context 'when api token already exists' do
let!(:api_token) { create(:api_token, user: user) }
it { is_expected.to eq(api_token) }
end
end
end
<file_sep>RSpec.describe ApplicationHelper do
describe 'format_lap_time' do
it 'represents milliseconds as time duration' do
expect(helper.format_lap_time(0)).to eq('0:00.000')
expect(helper.format_lap_time(30500)).to eq('0:30.500')
expect(helper.format_lap_time(65050)).to eq('1:05.050')
expect(helper.format_lap_time(630005)).to eq('10:30.005')
end
end
end
|
d69022cdda35782ee8de2d6bd426bfa8a8a5ee64
|
[
"Markdown",
"Ruby"
] | 45
|
Ruby
|
gediminasz/crono
|
8254c9e2b3996a4dfe914019f80a5c7a7d8326e6
|
ffb9f3eb88f471103858bd5e986ee37916503644
|
refs/heads/master
|
<file_sep>#ifndef CONFIG_H
#define CONFIG_H
void list_config( std::vector<std::string> &list, std::string path);
void list_file_name( std::vector<std::string> &list_file, const std::vector<std::string> &config, const std::string &common_name, std::string marker);
bool replace(std::string& str, const std::string& from, const std::string& to);
#endif
<file_sep>#include <iostream>
#include <vector>
#include <string>
#include "jackknife.h"
void meson_jknf (const std::vector < std::vector <double> > &raw, std::vector < std::vector <double> > &output)
{
int size_N=raw.size();
int size_X=raw[0].size();
double sum[size_X]={0.00};
double temp[size_N][size_X]={0};
for (int i = 0; i < size_X ; ++i)
{
for (int j = 0; j < size_N ; ++j )
{
sum[i] = sum[i] + raw[j][i];
}
}
//Calculate jackknifed value
for (int r = 0; r < size_N ; ++r)
{
for (int c = 0; c < size_X ; ++c)
{ temp[r][c]= sum[c]-raw[r][c];
output[r].push_back(temp[r][c]);
}
}
}
<file_sep>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "meson.h"
void meson_in(std::vector< std::vector<double> > &meson, const std::vector<std::string> &config_file_list)
{
for(auto i = 0; i < config_file_list.size(); ++i)
{
std::ifstream in(config_file_list[i] ,std::ios::in);
double temp;
while (in >> temp)
{
(meson[i]).push_back(temp);
}
in.close();
}
}
<file_sep>#ifndef MESON_H
#define MESON_H
void meson_in(std::vector< std::vector<double> > &meson, const std::vector<std::string> &config_file_list);
#endif
<file_sep>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "config.h"
#include "meson.h"
#include "jackknife.h"
int main()
{
std::vector<std::string> config;
std::vector<std::string> pion_file_list;
std::string marker="*";
std::string common_name="./data/klks_ml_0.00062/traj_*_pion_1e-4.txt";
std::string config_path="./inputs/configs.txt";
list_config( config, config_path);
list_file_name(pion_file_list, config, common_name, marker );
std::vector< std::vector<double> > pion(pion_file_list.size());
std::vector< std::vector<double> > pion_jknf(pion_file_list.size());
meson_in(pion, pion_file_list);
meson_jknf(pion, pion_jknf);
//Display
std::cout << "The pion file list contents: " << std::endl;
for (auto i=pion_file_list.begin(); i!= pion_file_list.end() ; ++i)
std::cout << *i << '\n';
std::cout << "The pion read contents: " << std::endl;
for (auto i=pion.begin(); i!= pion.end() ; ++i)
{
for(auto j=(*i).begin(); j != (*i).end(); ++j)
std::cout << *j << '\n';
std::cout << '\n' << '\n';
}
std::ofstream pion_out("pion_jknf.txt");
if (pion_out.is_open())
{
std::cout << "The pion jknf contents: " << std::endl;
for (auto i=pion_jknf.begin(); i!= pion_jknf.end() ; ++i)
{
for(auto j=(*i).begin(); j != (*i).end(); ++j)
pion_out << *j << '\t';
pion_out << '\n';
}
pion_out.close();
}
pion_out<<std::endl;
std::cout << "Configs read in are:" << std::endl;
for (auto i=config.begin(); i != config.end(); ++i)
std::cout << *i << '\n';
//std::cin.get();
return 0;
}
<file_sep># Dmk_Analysis_Cpp
Code for analysis data using Cpp code by BG
<file_sep>#ifndef JACKKNIFE_H
#define JACKKNIFE_H
void meson_jknf (const std::vector < std::vector <double> > &raw, std::vector < std::vector <double> > &output);
#endif
<file_sep>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "config.h"
void list_config( std::vector<std::string> &list, std::string path)
{
std::ifstream in(path, std::ios::in);
std::string temp_str;
while ( in >> temp_str)
list.push_back(temp_str);
in.close();
}
void list_file_name( std::vector<std::string> &list_file, const std::vector<std::string> &config, const std::string &common_name, std::string marker)
{
for (auto i=config.begin(); i != config.end(); ++i )
{
std::string tmp_file_name=common_name;
replace(tmp_file_name, marker, (*i));
list_file.push_back(tmp_file_name);
}
}
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
|
925af95dda23572a5975e79301005b6fdc94a000
|
[
"Markdown",
"C",
"C++"
] | 8
|
C++
|
bigengwang2482/Dmk_Analysis_Cpp
|
39875ad8ecc7da210f6fff77250dcd21009a9f63
|
fe1c121bb0db3531aafb27652d45bc5066c6f545
|
refs/heads/master
|
<file_sep>from django.test import TestCase
from .merge import MergedTable, MergedRow, MergedCell, SourceValue
from hostlookup_combined.templatetags.merge_tags import merged_table, merged_cell
class MergedCellTestCase(TestCase):
def setUp(self):
self.col_0 = MergedCell([], None)
self.col_1 = MergedCell([SourceValue('ena', 'a')], None)
self.col_valid = MergedCell([SourceValue('ena', 'a'), SourceValue('dio', 'a')], None)
self.col_diff_types = MergedCell([SourceValue('ena', 1), SourceValue('dio', '1')], None)
self.col_invalid = MergedCell([SourceValue('ena', 'a'), SourceValue('dio', 'b')], None)
self.col_sort_len = MergedCell([SourceValue('ena', 'aaaaa')], len)
self.col_sort_invalid = MergedCell([SourceValue('ena', 'aaaaa'), SourceValue('dio', 'bbbbb')], len)
def test_different_invalid(self):
self.assertFalse(self.col_invalid.valid)
def test_same_valid(self):
self.assertTrue(self.col_valid.valid)
def test_single_valid(self):
self.assertTrue(self.col_1.valid)
def test_none_valid(self):
self.assertTrue(self.col_0.valid)
def test_diff_types_invalid(self):
self.assertFalse(self.col_diff_types.valid)
def test_sort_none(self):
self.assertIs(self.col_valid.sort_order, None)
def test_sort_len(self):
self.assertIs(self.col_sort_len.sort_order, 5)
def test_sort_invalid(self):
self.assertIs(self.col_sort_invalid.sort_order, 0)
def test_render_invalid(self):
rendered = merged_cell(self.col_invalid)
self.assertIn('<li>ena: a</li>', rendered)
self.assertIn('<li>dio: b</li>', rendered)
self.assertIn('invalid', rendered)
def test_render_valid(self):
rendered = merged_cell(self.col_valid)
self.assertFalse('<li>' in rendered)
self.assertFalse(':' in rendered)
self.assertFalse('ena' in rendered)
self.assertFalse('dio' in rendered)
self.assertIn('class="valid"', rendered)
self.assertIn('>a<', rendered)
def test_render_sort_order_none(self):
rendered = merged_cell(self.col_valid)
self.assertFalse('data-order' in rendered)
def test_render_sort_order_invalid(self):
rendered = merged_cell(self.col_invalid)
self.assertIn('data-order="0"', rendered)
def test_render_sort_order_len(self):
rendered = merged_cell(self.col_sort_len)
self.assertIn('data-order="5"', rendered)
class MergedRowTestCase(TestCase):
def setUp(self):
self.data_1 = {
'alpha': 1,
'beta': 'two',
'gamma': [0, 0, 0],
'epsilon': 'e',
}
self.data_2 = {
'alpha': 2,
'beta': 'two',
'gamma': [0, 0, 0],
'delta': 'four',
}
self.merged = MergedRow(None, ena=self.data_1, dio=self.data_2)
def test_single_source_all_valid(self):
single_source = MergedRow(None, ena=self.data_1)
self.assertTrue(single_source.cells['alpha'].valid)
self.assertTrue(single_source.cells['beta'].valid)
self.assertTrue(single_source.cells['gamma'].valid)
self.assertTrue(single_source.cells['epsilon'].valid)
def test_alpha_invalid(self):
self.assertFalse(self.merged.cells['alpha'].valid)
def test_beta_valid(self):
self.assertTrue(self.merged.cells['beta'].valid)
def test_gamma_valid(self):
self.assertTrue(self.merged.cells['gamma'].valid)
def test_delta_valid(self):
self.assertTrue(self.merged.cells['delta'].valid)
def test_epsilon_valid(self):
self.assertTrue(self.merged.cells['epsilon'].valid)
class MergedTableTestCase(TestCase):
def setUp(self):
self.source_a = [
{
'id': 0,
'color': 'green',
'size': 5,
},
{
'id': 1,
'color': 'red',
'size': 8,
},
{
'id': 2,
'color': 'red',
'size': 7,
},
{
'id': 3,
'color': 'black',
'size': 3,
},
]
self.source_b = [
{
'id': 0,
'color': 'green',
'size': 5,
},
{
'id': 1,
'color': 'yellow',
'size': 5,
},
{
'id': 4,
'color': 'white',
'size': 6,
},
]
self.source_c = [
{
'id': 0,
'status': 'jolly',
},
{
'id': 1,
'status': 'despondent'
},
]
self.columns = [
('id', 'ID'),
('size', 'Size'),
('color', 'Color'),
('status', 'Status', len),
]
def test_status_added(self):
merged = MergedTable('id', self.columns, None, a=self.source_a, c=self.source_c)
self.assertTrue('status' in merged.rows[0].cells.keys())
self.assertTrue('status' in merged.rows[1].cells.keys())
def test_outer_join(self):
merged = MergedTable('id', self.columns, None, a=self.source_a, b=self.source_b)
self.assertIs(len(merged.rows.values()), 5)
def test_inner_join(self):
merged = MergedTable('id', self.columns, ('a', 'b'), a=self.source_a, b=self.source_b)
self.assertIs(len(merged.rows.values()), 2)
def test_single_required(self):
merged = MergedTable('id', self.columns, ('a'), a=self.source_a, b=self.source_b)
self.assertTrue(merged.rows.get(0))
self.assertTrue(merged.rows.get(3))
self.assertIs(merged.rows.get(4), None)
def test_column_sort_func(self):
merged = MergedTable('id', self.columns, None, a=self.source_a, c=self.source_c)
self.assertIs(merged.rows[0].cells['status'].sort_order, 5)
def test_render(self):
merged = MergedTable('id', self.columns, None, a=self.source_a, b=self.source_b)
rendered = merged_table(merged, 'foo').replace('\n', '').replace(' ', '')
self.assertIn('<table class="foo">', rendered)
self.assertIn('<tr><th>ID</th>', rendered)
self.assertIn('<tr class=""><td class="valid">', rendered)
<file_sep>from django.conf.urls import url
from .views import HostLookupView
from .models import can_view_permission_dispatch
app_name = 'hostlookup'
urlpatterns = [
url(r'^$', can_view_permission_dispatch(HostLookupView).as_view(), name='index'),
]
<file_sep>from django.urls import path
from .views import HostView
from ..models import can_view_permission_dispatch
app_name = 'hostlookup-api'
urlpatterns = [
path('', can_view_permission_dispatch(HostView).as_view(), name='host-lookup'),
]
<file_sep>from django.urls import path
from .views import HostLookupView
from .models import can_view_permission_dispatch
app_name = 'hostlookup'
urlpatterns = [
path(r'', can_view_permission_dispatch(HostLookupView).as_view(), name='index'),
]
<file_sep>
The NetDash project's goal is to create an interface to allow delegation of specific IT infrastructure management tasks to IT teams outside of a central IT team.
This is implemented with a suite of extensible [Django](https://www.djangoproject.com/) apps and core Django project that
seamlessly integrate new modules and customizations without requiring code changes.
With NetDash, you can:
* **Use** the included NetDash Modules out of the box, which are either agnostic to external integrations or generic enough work for most people who have a particular third-party system.
* **Extend** the included NetDash Modules with features and logic meet the needs of your own deployment.
* **Add** completely new NetDash Modules to meet needs that NetDash's included modules do not address.
## Included Modules
* Host Lookup: Look up device and port information by IP address.
* `hostlookup-netdisco`: NetDisco backend implementation.
* `hostlookup-bluecat`: BlueCat backend implementation.
* `hostlookup-combined`: Combines netdisco and bluecat backends into a single module. Can be easily extended to combine different or additional backends.
## Getting Started
Before you get started, completing the [Django Tutorial](https://docs.djangoproject.com/en/2.2/intro/tutorial01/) is recommended to establish a footing in Django apps, development, and project structure.
1. Clone this repository:
```
git clone git@github.com:netdash/netdash.git
```
2. Change to the new directory:
```
cd netdash
```
3. Copy the example settings to use them:
```
cp netdash/netdash/settings_example.py netdash/netdash/settings.py
```
4. Install dependencies:
```
pip install -r requirements.deploy.txt
```
5. Run migrations:
```
python netdash/manage.py migrate
```
6. Create a superuser:
```
python netdash/manage.py createsuperuser
```
7. Run the development server:
```
python netdash/manage.py runserver
```
You can now visit the interface in your browser at http://localhost:8000. Click 'login' and use your superuser credentials.
## Creating a NetDash Module
A *NetDash Module* is a Django App that follows certain conventions and thereby integrates automatically with NetDash without any additional code changes. These integrations include UI link generation, Swagger API inclusion, routing and permissions.
1. Change directory to NetDash apps:
```
cd netdash
```
2. Create a new NetDash Module, substituting `my_custom_nd_module` for your module's name:
```
python manage.py startapp --template ../netdash_module_template my_custom_nd_module
```
3. To enable your new module, add your module's name to `NETDASH_MODULES` in `netdash/settings.py`:
```
NETDASH_MODULES = [
'my_custom_nd_module',
]
```
NetDash Modules can be specified as Django app labels or as paths to an AppConfig [the same way that `settings.INSTALLED_APPS` is configured](https://docs.djangoproject.com/en/2.2/ref/applications/#for-application-users).
4. Exclude your app from NetDash's source control, substituting `my_custom_nd_module` for your module's name:
```
echo netdash/my_custom_nd_module >> ../.git/info/exclude
```
5. Initialize a git repo in your new NetDash Module's directory:
```
git init my_custom_nd_module
```
6. Run its initial migration:
```
python manage.py migrate
```
7. Restart the development server:
```
python manage.py runserver
```
Congrats! You can now explore the interface and look at the NetDash Module you created. If you don't see the module in the interface, make sure you are logged in as your superuser.
If your NetDash Module requires additional packages, add them to `requirements.user.txt` and install them with
```
pip install -r requirements.user.txt
```
## Module Conventions
* A module with `urls.py` should declare an `app_name`.
* A module with `urls.py` will have its URLs placed under `/<app_name>/*`.
* A module with `urls.py` should have a url named `index`. A link to `index` will be generated in the NetDash navbar.
* A module that generates a permission named `can_view_module` will only generate an `index` link in the NetDash navbar for users who have that permission.
* A module with `api/urls.py` should declare an `app_name`. If the module also has a `urls.py`, it should reuse the previous `app_name` like so: `<app_name>-api`
* A module with `api/urls.py` will have its API URLs placed under `/api/<app_name>/*`.
* Modules should include a `README.md` in their root that describes settings, package dependencies, and required integrations.
* Required permissions of module views should be set in `urls.py` rather than `views.py`. This allows for the extension of views without inheriting their required permissions.
Check the [example apps](https://github.com/netdash/netdash-examples) for examples of these conventions.
## Troubleshooting
If a NetDash Module doesn't properly follow conventions, certain integrations might not work. NetDash includes a `diagnose` command to output information about your NetDash Modules that may assist in refactoring them for inclusion in NetDash.
```
python netdash/manage.py diagnose -v2
```
Will output diagnostics for all NetDash Modules, including any exception traces (`-v2` flag).
If an unrecoverable error is encountered while parsing NetDash Modules, all diagnostics up until the error will be displayed.
## Deployment
NetDash can be deployed as a WSGI service or with Kubernetes. See [Deployment Strategies](deployment.md) for more information.
|
90578e5c92c316d7e648cbca18e2174eb967f39f
|
[
"Markdown",
"Python"
] | 5
|
Python
|
kris-steinhoff/netdash
|
dd136ab694d0894c164799cc4b02c57c63e9b810
|
9fa9e1ff13893dd8db95c31c97e5d71db87e644e
|
refs/heads/master
|
<repo_name>fg/Cobol_Catalog<file_sep>/README.md
Cobol_Catalog
=============
Example: test-product.html
To: product/test-product-p5.html
<file_sep>/app/local/Cobol/Catalog/Helper/Product.php
<?php
/**
* Class Cobol_Catalog_Helper_Product
*/
class Cobol_Catalog_Helper_Product extends Mage_Catalog_Helper_Product
{
}
|
aad5e2de3966f874e6591f51f42f12e9ec350113
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
fg/Cobol_Catalog
|
ae71a4776137885251ea508d56377c8892f3818d
|
dbd4ff23b433e47aab835e8e557cb0e9ca019b29
|
refs/heads/master
|
<file_sep># dungeonGame
The purpose of this project is to design a 2D RPG using JavaScript. It currently has a blank canvas with a square, but soon
it will have many and better shapes.
<file_sep>/**
*
*/
var player;
var canvasWidth = 800;
var canvasHeight = 400;
function startGame(){
myGameArea.start();
player = new entity(10, 10, "red", 10, canvasHeight / 2);
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = canvasWidth;
this.canvas.height = canvasHeight;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
}
}
function entity(entityWidth, entityHeight, entityColor, spawnX, spawnY){
this.entityWidth = entityWidth;
this.entityHeight = entityHeight;
this.spawnX = spawnX;
this.spawnY = spawnY;
ctx = myGameArea.context;
ctx.fillStyle = entityColor;
ctx.fillRect(this.spawnX, this.spawnY, this.entityWidth, this.entityHeight);
}
|
eb51a165b310f3cdecc75ef1e5c33dbf93c26f6e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
WilliamHinton/dungeonGame
|
b61f94924368cbe5cd5cef29acad168055b5ccb6
|
af71d5d0f0d00f4c7721583e263289b62b002b34
|
refs/heads/master
|
<repo_name>osulluke/udacity-python-programming-foundations<file_sep>/breaktime.py
import webbrowser, time
print("The program started at "+time.ctime())
for x in range(0,3):
time.sleep(10)
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
print("The program ended at "+time.ctime())
<file_sep>/notes.txt
Lesson 1
Functions can be used to get your programs to do stuff...duh...in lesson #1, they introduced two libraries for use. The first was the webbrowser library that allows webpages to be opened, and the second was the time library, that will cause a computer program to 'pause' or 'sleep' for a certain amount of time.
Also was able to use the 'os' library to rename a bunch of files in a directory. The program also made use of the ability to switch directories as well as print them out...very useful concepts.<file_sep>/rename_files.py
import os
def rename_files():
#1 - read files from directory.
file_list = os.listdir("/home/luke/Dropbox/Udacity/ProgrammingFoundationsWithPython/prank")
print(file_list)
print("# of files in directory "+str(len(file_list)))
saved_path = os.getcwd()
print("Current working directory is "+saved_path)
os.chdir("/home/luke/Dropbox/Udacity/ProgrammingFoundationsWithPython/prank")
print(os.getcwd())
#2 - rename all files in directory.
for file_name in file_list:
new_file_name = file_name.translate(None,"0123456789 ")
print(file_name+" renamed to "+new_file_name)
os.rename(file_name, new_file_name)
os.chdir(saved_path)
print(os.getcwd())
print("Program complete.")
rename_files()
|
4400f3149589f7bccee795f53ca01a7769dd8b1f
|
[
"Python",
"Text"
] | 3
|
Python
|
osulluke/udacity-python-programming-foundations
|
5075866059154ed8378405afab1e11883637b4c0
|
4e68d6f1f4af9c2cbb2f005444c252ad5a0b7942
|
refs/heads/main
|
<repo_name>caiookb/the-movie-db-frontend<file_sep>/src/components/Pagination/styles.js
import styled, { css } from "styled-components";
import { Colors } from "../../utils/Colors";
export const StyledPagination = styled.div`
margin-top: 50px;
margin-bottom: 50px;
display: flex;
justify-content: center;
flex-direction: row;
`;
export const StyledPage = styled.div`
display: flex;
flex-direction: row;
border: 1px solid white;
font-weight: bold;
color: #8f8f8f;
margin: 5px;
padding: 5px 10px;
font-family: "Lato";
color: ${Colors.third};
cursor: pointer;
position: relative;
justify-content: center;
align-items: center;
${(props) =>
props.current &&
css`
color: ${Colors.secondary};
background-color: ${Colors.primary};
border: 4px solid ${Colors.primary};
font-family: "Abel";
font-weight: 300;
padding: 12px 22px;
border-radius: 50%;
font-size: 32px;
&:before {
content: "${(props) => props.data} ";
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
border: 4px solid ${Colors.secondary};
border-radius: 50%;
}
`}
`;
export const StyledText = styled.p`
font-family: "Lato";
font-size: 16px;
font-weight: 600;
color: ${Colors.text};
`;
<file_sep>/src/libs/redux/types/MoviesTypes.js
export const SAVE_MOVIES_LIST = "SAVE_MOVIES_LIST";
export const SAVE_MOVIE_DETAIL = "SAVE_MOVIE_DETAIL";
export const CLEAR_MOVIE_DETAIL = "CLEAR_MOVIE_DETAIL";
export const SAVE_MOVIES_BY_PAGE = "SAVE_MOVIES_BY_PAGE";
export const CLEAN_MOVIES = "CLEAN_MOVIES";
<file_sep>/README.md
# The Movie DB Frontend
React App created to search, list and see movies details.
Application running on [https://caiookb.github.io/the-movie-db-frontend/](https://caiookb.github.io/the-movie-db-frontend/)
### Important Libraries
- [react-redux](https://github.com/reduxjs/react-redux)/[redux](https://github.com/reduxjs/redux)/[redux-thunk](https://github.com/reduxjs/redux-thunk)
- [Styled-Components](https://github.com/styled-components/styled-components)
- [moment](https://github.com/moment/moment)
- [testing-library/react](https://github.com/testing-library/react-testing-library)
- [enzyme](https://github.com/enzymejs/enzyme)/[enzyme-adapter-react-16](https://www.npmjs.com/package/enzyme-adapter-react-16)
- [lodash](https://github.com/lodash/lodash)
### How to run application
**You must have NodeJs installed on your system.**
1. `git clone` or **download** the repository
2. Go to folder and run on terminal `npm install` to install all libs that are necessary for the application to run.
3. Run `npm start` to start the application
4. Go to localhost:3000
### [](https://github.com/caiookb/github-compare#how-to-test-application)How to test application
1. Go to folder and run on terminal `npm install` to install all libs that are necessary for the application to run.
2. Run `npm run test` to test the application
Any doubt you can contact me on [<EMAIL>](mailto:<EMAIL>) :)
<file_sep>/src/components/Pagination/Pagination.js
import React, { useEffect, useState } from "react";
import { StyledPagination, StyledPage } from "./styles";
const Pagination = (props) => {
const { list, paginateItems } = props;
const [pages, setPages] = useState([]);
const [items, setItems] = useState([]);
const [currentPage, setCurrentPage] = useState(0);
const data = list && [...list];
const splicePages = [...Array(Math.ceil(data?.length / 5 || 1))].map((_) => {
return data?.splice(0, 5);
});
const pagesLength = Array.from(
{ length: splicePages?.length || 1 },
(v, k) => k + 1
);
useEffect(() => {
setItems(splicePages);
setPages(pagesLength);
}, [list]);
useEffect(() => {
items.forEach((page, idx) => {
return idx === currentPage ? paginateItems(page) : null;
});
}, [currentPage]);
useEffect(() => paginateItems && paginateItems(splicePages[currentPage]), [
items,
]);
return (
<StyledPagination data-testid="pagination">
{pages.map((page, idx) => (
<StyledPage
current={page - 1 === currentPage}
onClick={() => setCurrentPage(page - 1)}
key={idx}
>
{page}
</StyledPage>
))}
</StyledPagination>
);
};
export default Pagination;
<file_sep>/src/server/MoviesServer.js
import fetchServer from "./Server";
export const fetchMoviesByName = (name) => {
return fetchServer({
method: "GET",
path: ["search", `movie?query=${name}`],
});
};
export const fetchMoviesByGenre = (genre) => {
return fetchServer({
method: "GET",
path: ["discover", `movie?with_genres=${genre}`],
});
};
export const fetchMovieDetail = (id) => {
return fetchServer({
method: "GET",
path: ["movie", `${id}?`],
});
};
export const fetchMovieVideo = (id) => {
return fetchServer({
method: "GET",
path: ["movie", `${id}`, "videos?"],
});
};
export const fetchGenres = () => {
return fetchServer({
method: "GET",
path: ["genre", "movie", "list?"],
});
};
<file_sep>/src/server/Server.js
const urlPrefix = "https://api.themoviedb.org/3/";
const apiKey = "<KEY>";
const url = (path) => {
return urlPrefix
.concat(path.join("/"))
.concat(`&api_key=${apiKey}&language=pt-BR`);
};
export default (config) => {
const { method, path, body } = config;
const opt = {
method,
data: body,
};
return fetch(url(path), opt)
.then((res) => {
return res.json();
})
.catch((err) => {
throw err;
});
};
<file_sep>/src/components/Tag/styles.js
import styled, { css } from "styled-components";
import { Colors } from "../../utils/Colors";
export const StyledTag = styled.p`
background-color: ${Colors.white};
color: ${Colors.fourth};
margin-right: 15px;
font-family: "Lato";
border-radius: 25px;
font-size: 14px;
margin: 0;
max-height: 22px;
padding: 0px 10px;
margin-right: 10px;
margin-bottom: 20px;
border: 2px solid ${Colors.fourth};
transition: 0.4s;
cursor: pointer;
&:hover {
filter: brightness(70%) contrast(150%);
}
${(props) =>
props.color &&
css`
color: ${props.color};
`};
`;
<file_sep>/src/App.js
import React from "react";
import { HashRouter, Switch, Route } from "react-router-dom";
import { routes } from "./routes/Routes";
import "./App.css";
const App = () => {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={routes[0].component} />
{routes.map((route) => {
const { path, ...props } = route;
return <Route key={path} path={path} {...props} />;
})}
</Switch>
</HashRouter>
);
};
export default App;
<file_sep>/src/routes/Routes.js
import Main from "../views/Main/Main";
import Details from "../views/Details/Details";
export const routes = [
{ path: "/main", component: Main, isPrivate: false },
{ path: "/movie/:id", component: Details, isPrivate: false },
];
<file_sep>/src/views/Details/Styles.js
import styled, { css } from "styled-components";
import { Colors } from "../../utils/Colors";
export const StyledDetails = styled.div`
display: flex;
flex-direction: column;
background-color: ${Colors.white};
${(props) =>
props.color &&
css`
color: ${props.color};
`}
`;
<file_sep>/src/server/index.js
import * as MoviesServer from "./MoviesServer";
export { MoviesServer };
<file_sep>/src/components/Spinner/Spinner.js
import React from "react";
import styled, { keyframes } from "styled-components";
import { Colors } from "../../utils/Colors";
const Spinner = () => <StyledSpinner data-testid="spinner"></StyledSpinner>;
const spin = keyframes`
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
`;
const StyledSpinner = styled.div`
display: inline-block;
width: fit-content;
height: fit-content;
margin: 100px auto;
&:after {
content: " ";
display: block;
width: 72px;
height: 72px;
margin: 8px;
border-radius: 50%;
border: 6px solid ${Colors.third};
border-color: ${Colors.secondary} transparent ${Colors.primary} transparent;
animation: ${spin} 1.2s linear infinite;
}
`;
export default Spinner;
<file_sep>/src/libs/redux/reducers/MoviesReducer.js
import { MoviesTypes } from "../types";
const initialState = {
moviesList: [],
currentPage: [],
selectedMovie: {},
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case MoviesTypes.SAVE_MOVIES_BY_PAGE:
return { ...state, currentPage: payload };
case MoviesTypes.SAVE_MOVIES_LIST:
return { ...state, moviesList: payload };
case MoviesTypes.SAVE_MOVIE_DETAIL:
return { ...state, selectedMovie: payload };
case MoviesTypes.CLEAR_MOVIE_DETAIL:
return { ...state, selectedMovie: {} };
case MoviesTypes.CLEAN_MOVIES:
return { ...state };
default:
return state;
}
};
<file_sep>/src/components/Tag/Tag.js
import React from "react";
import { StyledTag } from "./styles";
const Tag = ({ tag, key }) => (
<StyledTag key={key} tag={tag} data-testid="tag">
{tag}
</StyledTag>
);
export default Tag;
<file_sep>/src/components/Card/Card.test.js
import React from "react";
import { render } from "@testing-library/react";
import Card from "./Card";
describe("card component", () => {
it("should render card ", () => {
const { getByTestId } = render(
<Card data-testid="card" movie={{ title: "<NAME>" }} />
);
const el = getByTestId("card");
expect(el).not.toBeNull();
});
});
<file_sep>/src/components/RoundedData/styles.js
import styled, { css } from "styled-components";
import { Colors } from "../../utils/Colors";
export const StyledRoundedData = styled.div`
color: ${Colors.secondary};
background-color: ${Colors.primary};
border: 4px solid ${Colors.primary};
font-family: "Abel";
font-weight: 300;
padding: 20px 16px;
transition: 1s;
&:before {
content: "${(props) => props.data} ";
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
border: 5px solid ${Colors.secondary};
border-radius: 50%;
}
${(props) =>
props.rating &&
css`
font-size: 22px;
border-radius: 50%;
position: absolute;
bottom: -35px;
left: 15px;
`};
${(props) =>
props.size === "lg" &&
css`
position: unset;
font-size: 32px;
font-weight: 300;
padding: 16px 12px;
`};
`;
<file_sep>/src/utils/Colors.js
export const Colors = {
primary: "#116193",
secondary: "#00e8e4",
third: "#1f6f9c",
fourth: "#4985ab",
background: "#e6e6e6",
lightBackground: "#f2f2f2",
white: "#FFF",
text: "#7a7a7a",
text2: "#646464",
};
<file_sep>/src/components/index.js
import RoundedData from "./RoundedData/RoundedData";
import Card from "./Card/Card";
import DetailedCard from "./DetailedCard/DetailedCard";
import Header from "./Header/Header";
import Info from "./Info/Info";
import Pagination from "./Pagination/Pagination";
import Spinner from "./Spinner/Spinner";
import Tag from "./Tag/Tag";
import TextInput from "./TextInput/TextInput";
import { Title, Date, Text } from "./Text/Text";
import Video from "./Video/Video";
export {
Card,
Date,
DetailedCard,
Header,
Info,
Pagination,
RoundedData,
Spinner,
Tag,
Text,
TextInput,
Title,
Video,
};
<file_sep>/src/components/DetailedCard/DetailedCard.test.js
import React from "react";
import { render } from "@testing-library/react";
import DetailedCard from "./DetailedCard";
describe("DetailedCard component", () => {
it("should render DetailedCard ", () => {
const { getByTestId } = render(
<DetailedCard
data-testid="detailed-card"
movie={{ title: "<NAME>" }}
/>
);
const el = getByTestId("detailed-card");
expect(el).not.toBeNull();
});
});
<file_sep>/src/components/DetailedCard/styles.js
import styled, { keyframes } from "styled-components";
import { Colors } from "../../utils/Colors";
const fade = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
margin-top: 50px;
}
`;
const expand = keyframes`
0% {
opacity: 0;
width: 0%;
}
100% {
opacity: 1;
width: 95%
}
`;
export const StyledDetail = styled.div`
display: flex;
flex-direction: column;
align-items: center;
animation-name: ${fade};
animation-duration: 1.5s;
animation-direction: normal;
animation-fill-mode: forwards;
transition: 1s;
`;
export const StyledDetailedCard = styled.div`
display: flex;
align-self: center;
flex-direction: column;
background-color: ${Colors.background};
height: fit-content;
width: 75%;
position: unset;
@media (max-width: 768px) {
width: 90%;
height: auto;
max-height: unset;
}
@media (max-width: 500px) {
min-height: 550px;
height: fit-content;
position: relative;
z-index: 1;
width: 90%;
}
`;
export const StyledInfo = styled.div`
display: flex;
flex-direction: column;
width: 100%;
padding: 25px 8px 25px 30px;
@media (max-width: 500px) {
z-index: 1;
}
`;
export const StyledInfoTitle = styled.div`
background-color: ${Colors.background};
position: relative;
display: flex;
flex-direction: row;
align-content: center;
`;
export const StyledTitle = styled.div`
width: 85%;
padding-left: 30px;
padding-top: 8px;
margin: 0;
@media (max-width: 500px) {
color: white;
}
`;
export const StyledImage = styled.img`
width: 300px;
@media (max-width: 768px) {
width: 330px;
}
@media (max-width: 500px) {
margin: auto;
}
`;
export const StyledDate = styled.div`
padding-right: 25px;
`;
export const StyledOverview = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
background-color: ${Colors.lightBackground};
@media (max-width: 500px) {
flex-direction: column;
}
`;
export const StyledTopic = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
width: 100%;
margin-bottom: 40px;
@media (max-width: 500px) {
width: 90%;
}
`;
export const StyledTopicTitle = styled.div`
padding-bottom: 6px;
margin-bottom: 15px;
animation-name: ${expand};
animation-duration: 2s;
animation-direction: normal;
animation-fill-mode: forwards;
border-bottom: 2px solid ${Colors.secondary};
`;
export const StyledRow = styled.div`
display: flex;
flex-wrap: wrap;
flex-direction: row;
width: 95%;
justify-content: space-between;
align-items: center;
@media (max-width: 500px) {
width: 85%;
}
`;
export const StyledTags = styled.div`
display: flex;
flex-wrap: wrap;
@media (max-width: 500px) {
justify-content: center;
}
`;
const float = keyframes`
0% {
filter: brightness(50%);
opacity: 0;
}
100% {
filter: brightness(100%);
transform: rotateY(360deg);
}
`;
export const StyledRoundedData = styled.div`
position: relative;
border: 4px solid ${Colors.primary};
border-radius: 50%;
animation-name: ${float};
animation-duration: 1.5s;
animation-direction: alternate;
animation-iteration-count: 1;
transition: 1s;
cursor: pointer;
@media (max-width: 500px) {
margin: auto;
}
&:hover {
transform: rotateY(360deg);
}
`;
<file_sep>/src/controller/MoviesController.js
import { MoviesActions } from "../libs/redux/actions";
import { MoviesServer } from "../server";
import { matchGenreByNameToId } from "../utils/Utils";
const searchByNameOrGenre = (string) => {
const genreId = matchGenreByNameToId(string);
return genreId !== undefined
? MoviesServer.fetchMoviesByGenre(genreId)
: MoviesServer.fetchMoviesByName(string);
};
const addDescribedGenresToMovie = async (movies) => {
const genres = await getGenres();
movies.forEach((movie) => {
movie.describedGenres = [];
movie.genre_ids.map((genreId) => {
const findGenre = genres.find((genre) => genre.id === genreId);
return movie.describedGenres.push(findGenre.name);
});
});
return movies;
};
export const searchMovie = (value) => (dispatch) => {
return searchByNameOrGenre(value)
.then(async (movieResponse) => {
const movies = await addDescribedGenresToMovie(movieResponse.results);
localStorage.setItem("moviesList", JSON.stringify(movies));
dispatch(MoviesActions.saveMoviesList(movies));
return movies;
})
.catch((err) => {
console.log("Error", err);
});
};
const getGenres = async () => {
try {
const response = await MoviesServer.fetchGenres();
return response.genres;
} catch (err) {
console.log("Error", err);
throw err;
}
};
export const selectedMovieCard = (movie) => (dispatch) => {
return MoviesServer.fetchMovieDetail(movie.id)
.then(async (res) => {
return MoviesServer.fetchMovieVideo(movie.id).then((movieResponse) => {
res.trailer = `https://www.youtube.com/embed/${movieResponse?.results[0]?.key}`;
localStorage.setItem("selectedMovie", JSON.stringify(res));
dispatch(MoviesActions.saveMovieDetail(res));
});
})
.catch((err) => {
console.log("Error", err);
throw err;
});
};
export const updateListOnRedux = () => (dispatch) => {
const list = JSON.parse(localStorage.getItem("moviesList"));
dispatch(MoviesActions.saveMoviesList(list ? list : []));
};
export const paginateMovies = (list) => (dispatch) => {
localStorage.setItem("currentPage", JSON.stringify(list));
dispatch(MoviesActions.saveMovieByPage(list));
};
export const clearMovieDetail = () => (dispatch) => {
dispatch(MoviesActions.clearMovieDetail());
};
<file_sep>/src/components/Text/Text.js
import React from "react";
import { StyledTitle, StyledDate, StyledText } from "./styles";
export const Title = ({ title, color, bold }) => (
<StyledTitle color={color} bold={bold}>
{title}
</StyledTitle>
);
export const Date = ({ date, color }) => (
<StyledDate color={color}>{date}</StyledDate>
);
export const Text = ({ text, color, topic }) => (
<StyledText color={color} topic={topic}>
{text}
</StyledText>
);
<file_sep>/src/libs/redux/actions/index.js
import * as MoviesActions from "./MoviesActions";
export { MoviesActions };
<file_sep>/src/components/TextInput/TextInput.js
import React from "react";
import { StyledInput } from "./styles";
const TextInput = ({ onChange, placeholder }) => (
<StyledInput onChange={onChange} placeholder={placeholder}></StyledInput>
);
export default TextInput;
<file_sep>/src/controller/index.js
import * as MoviesController from "./MoviesController";
export { MoviesController };
<file_sep>/src/utils/Utils.js
export const matchGenreByNameToId = (name) =>
({
acao: 28,
aventura: 12,
animacao: 16,
comedia: 35,
crime: 80,
documentario: 99,
drama: 18,
familia: 10751,
fantasia: 14,
historia: 36,
terror: 27,
musica: 10402,
romance: 10749,
"ficcao cientifica": 878,
"cinema tv": 10770,
thriller: 53,
guerra: 10752,
faroeste: 37,
}[replaceSpecialChars(name.toLowerCase())]);
const replaceSpecialChars = (str) => {
str = str.replace(/[ÀÁÂÃÄÅ]/, "A");
str = str.replace(/[àáâãäå]/, "a");
str = str.replace(/[ÈÉÊË]/, "E");
str = str.replace(/[Ç]/, "C");
str = str.replace(/[ç]/, "c");
return str.replace(/[^a-z0-9]/gi, " ");
};
export const genres = [
{ id: 28, name: "Ação" },
{ id: 12, name: "Aventura" },
{ id: 16, name: "Animação" },
{ id: 35, name: "Comédia" },
{ id: 80, name: "Crime" },
{ id: 99, name: "Documentário" },
{ id: 18, name: "Drama" },
{ id: 10751, name: "Família" },
{ id: 14, name: "Fantasia" },
{ id: 36, name: "História" },
{ id: 27, name: "Terror" },
{ id: 10402, name: "Música" },
{ id: 9648, name: "Mistério" },
{ id: 10749, name: "Romance" },
{ id: 878, name: "Ficção científica" },
{ id: 10770, name: "Cinema TV" },
{ id: 53, name: "Thriller" },
{ id: 10752, name: "Guerra" },
{ id: 37, name: "Faroeste" },
];
export const moviesList = [
{
adult: false,
backdrop_path: "/nKM71iyHoXG2DUBXml0mNwPChvg.jpg",
genre_ids: [35, 10749, 10770],
id: 647325,
original_language: "en",
original_title: "The Thing About Harry",
overview:
"Os inimigos no Ensino médio, Harry e Sam, são forçados a compartilhar uma carona até sua cidade natal para uma festa. As coisas mudam quando Sam descobre que Harry se assumiu Pansexual. Obrigados a passar a noite juntos, Harry e Sam se perguntam se eles podem ser mais do que amigos.",
popularity: 135.774,
poster_path: "/sdn5NdFMcsub3QUwlovOA9fPJoW.jpg",
release_date: "2020-02-15",
title: "Coisas sobre Harry",
video: false,
vote_average: 7.9,
vote_count: 89,
},
{
adult: false,
backdrop_path: "/hziiv14OpD73u9gAak4XDDfBKa2.jpg",
genre_ids: [12, 14],
id: 671,
original_language: "en",
original_title: "<NAME> and the Philosopher's Stone",
overview:
"<NAME> é um garoto órfão que vive infeliz com seus tios, os Dursleys. Ele recebe uma carta contendo um convite para ingressar em Hogwarts, uma famosa escola especializada em formar jovens bruxos. Inicialmente, Harry é impedido de ler a carta por seu tio, mas logo recebe a visita de Hagrid, o guarda-caça de Hogwarts, que chega para levá-lo até a escola. Harry adentra um mundo mágico que jamais imaginara, vivendo diversas aventuras com seus novos amigos, <NAME> e <NAME>.",
popularity: 160.753,
poster_path: "/qnw9610ojLT0jU3lMSZOAFttt1e.jpg",
release_date: "2001-11-16",
title: "<NAME> e a Pedra Filosofal",
video: false,
vote_average: 7.9,
vote_count: 19429,
},
{
adult: false,
backdrop_path: "/8f9dnOtpArDrOMEylpSN9Sc6fuz.jpg",
genre_ids: [12, 14, 10751],
id: 674,
original_language: "en",
original_title: "<NAME> and the Goblet of Fire",
overview:
"Em seu 4º ano na Escola de Magia e Bruxaria de Hogwarts, <NAME> é misteriosamente selecionado para participar do Torneio Tribruxo, uma competição internacional em que precisará enfrentar alunos mais velhos e experientes de Hogwarts e também de outras escolas de magia. Além disso a aparição da marca negra de Voldemort ao término da Copa do Mundo de Quadribol põe a comunidade de bruxos em pânico, já que sinaliza que o temido bruxo está prestes a retornar.",
popularity: 155.452,
poster_path: "/5oWB3hjzyECRBAjgWkmZinxl9qA.jpg",
release_date: "2005-11-16",
title: "<NAME> e o Cálice de Fogo",
video: false,
vote_average: 7.8,
vote_count: 14920,
},
{
adult: false,
backdrop_path: "/kT8bDEAgEYBKhRJtqM97qTw6uRW.jpg",
genre_ids: [12, 14],
id: 767,
original_language: "en",
original_title: "<NAME> and the Half-Blood Prince",
overview:
"No sexto ano de Harry em Hogwarts, <NAME> e seus Comensais da Morte estão criando o terror nos mundos bruxo e trouxa. Dumbledore convence seu velho amigo <NAME> para retornar a Hogwarts como professor de poções após Harry encontrar um estranho livro escolar. <NAME> se esforça para realizar uma ação destinada por Voldemort, enquanto Dumbledore e Harry secretamente trabalham juntos a fim de descobrir o método para destruir o Lorde das Trevas uma vez por todas.",
popularity: 122.725,
poster_path: "/hTQQ5l9mxA3Rob8PTyvrNNGuj6y.jpg",
release_date: "2009-07-07",
title: "<NAME>ter e o Enigma do Príncipe",
video: false,
vote_average: 7.7,
vote_count: 14054,
},
{
adult: false,
backdrop_path: "/1stUIsjawROZxjiCMtqqXqgfZWC.jpg",
genre_ids: [12, 14],
id: 672,
original_language: "en",
original_title: "<NAME> and the Chamber of Secrets",
overview:
"Após as sofríveis férias na casa dos tios, <NAME> se prepara para voltar a Hogwarts e começar seu segundo ano na escola de bruxos. Na véspera do início das aulas, a estranha criatura Dobby aparece em seu quarto e o avisa de que voltar é um erro e que algo muito ruim pode acontecer se Harry insistir em continuar os estudos de bruxaria. O garoto, no entanto, está disposto a correr o risco e se livrar do lar problemático.",
popularity: 141.165,
poster_path: "/811j0Jf2D0mK1U6RxXJoZgOB29n.jpg",
release_date: "2002-11-13",
title: "<NAME> e a Câmara Secreta",
video: false,
vote_average: 7.7,
vote_count: 15830,
},
{
adult: false,
backdrop_path: "/vbk5CfaAHOjQPSAcYm6AoRRz2Af.jpg",
genre_ids: [12, 14],
id: 673,
original_language: "en",
original_title: "<NAME> and the Prisoner of Azkaban",
overview:
"O 3º ano de ensino na Escola de Magia e Bruxaria de Hogwarts se aproxima. Porém um grande perigo ronda a escola: o assassino Sirius Black fugiu da prisão de Azkaban, considerada até então como à prova de fugas. Para proteger a escola são enviados os Dementadores, estranhos seres que sugam a energia vital de quem se aproxima deles, que tanto podem defender a escola como piorar ainda mais a situação.",
popularity: 138.563,
poster_path: "/1HdMUghqlgOIvbsU9ZtO40IPRzl.jpg",
release_date: "2004-05-31",
title: "<NAME> e o Prisioneiro de Azkaban",
video: false,
vote_average: 8,
vote_count: 15556,
},
{
adult: false,
backdrop_path: "/pkxPkHOPJjOvzfQOclANEBT8OfK.jpg",
genre_ids: [12, 14, 9648],
id: 675,
original_language: "en",
original_title: "<NAME> and the Order of the Phoenix",
overview:
"<NAME> está em seu quinto ano em Hogwarts e acaba ouvindo que muitos não sabem a verdade sobre seu encontro com Lord Voldemort. O Ministro de Mágica, <NAME>, indica Dolores Umbridge para ser a nova professora de Defesa Contra as Artes das Trevas, por acreditar que Dumbledore planeja tomar seu lugar. Porém, os métodos que ela usa são totalmente inapropriados. Harry, então, se reúne com um grupo de alunos para defender sua escola.",
popularity: 121.695,
poster_path: "/tIf9aUyNljda9MG1pjlOLHCZ3b0.jpg",
release_date: "2007-06-28",
title: "<NAME> e a Ordem da Fênix",
video: false,
vote_average: 7.7,
vote_count: 14288,
},
{
adult: false,
backdrop_path: "/n5A7brJCjejceZmHyujwUTVgQNC.jpg",
genre_ids: [14, 12],
id: 12445,
original_language: "en",
original_title: "<NAME> and the Deathly Hallows: Part 2",
overview:
"<NAME> e seus amigos <NAME> e <NAME> seguem à procura das horcruxes. O objetivo do trio é encontrá-las e, em seguida, destruí-las, de forma a eliminar lorde Voldemort de uma vez por todas. Com a ajuda do duende Grampo, eles entram no banco Gringotes de forma a invadir o cofre de Bellatrix Lestrange. De lá retornam ao castelo de Hogwarts, onde precisam encontrar mais uma horcrux. Paralelamente, Voldemort prepara o ataque definitivo ao castelo.",
popularity: 126.559,
poster_path: "/yD3VosOVW8WxPUzBDpEdzfv5pGx.jpg",
release_date: "2011-07-07",
title: "<NAME> e as Relíquias da Morte - Parte 2",
video: false,
vote_average: 8.1,
vote_count: 15128,
},
{
adult: false,
backdrop_path: "/AqLcLsGGTzAjm3pCCq0CZCQrp6m.jpg",
genre_ids: [12, 14],
id: 12444,
original_language: "en",
original_title: "<NAME> and the Deathly Hallows: Part 1",
overview:
"Sem a orientação e proteção de seus professores, Harry, Rony e Hermione iniciam uma missão para destruir as horcruxes, que são as fontes da imortalidade de Voldemort. Embora devam confiar um no outro mais do que nunca, forças das trevas ameaçam separá-los. Os Comensais da Morte de Voldemort tomaram o controle do Ministério da Magia e de Hogwarts, e eles estão procurando por Harry enquanto ele e seus amigos se preparam para o confronto final.",
popularity: 114.634,
poster_path: "/67FVFOTaeBUQnimhCWpUkDawDct.jpg",
release_date: "2010-10-17",
title: "<NAME> e as Relíquias da Morte - Parte 1",
video: false,
vote_average: 7.8,
vote_count: 14068,
},
{
adult: false,
backdrop_path: "/AhmRmdlu7GYdiucfZzVCGyP8ICf.jpg",
genre_ids: [53, 80, 18, 28],
id: 25941,
original_language: "en",
original_title: "<NAME>",
overview:
"<NAME> é um viúvo e ex-marine septuagenário, cuja vizinhança outrora pacata é hoje dominada pelo crime organizado, o tráfico de droga e a violência entre gangues. Quando o seu melhor amigo é brutamente assassinado e o responsável pelo crime é libertado, Harry leva o seu desejo de vingança ate aos limites e começa a impor a ordem aos jovens delinquentes pela lei das armas.",
popularity: 15.556,
poster_path: "/zthprdjuK7vN4ABBGQXo8RF7qYB.jpg",
release_date: "2009-11-11",
title: "<NAME>",
video: false,
vote_average: 6.8,
vote_count: 662,
},
{
adult: false,
backdrop_path: "/4LOxoeZWt5wr9mooxEZRFK96lDd.jpg",
genre_ids: [99],
id: 483898,
original_language: "en",
original_title: "50 Greatest Harry Potter Moments",
overview: "",
popularity: 53.308,
poster_path: "/g1xiBoLD6v3ZaXPa4QtuXiQeYKW.jpg",
release_date: "2011-07-27",
title: "50 Greatest Harry Potter Moments",
video: false,
vote_average: 7.9,
vote_count: 24,
},
{
adult: false,
backdrop_path: "/cXU4zg2aKglQrMOLokHLbnxwkGV.jpg",
genre_ids: [35, 10749, 18],
id: 639,
original_language: "en",
original_title: "When Harry Met Sally...",
overview:
"Harry e Sally vão morar em Nova York, se veem esporadicamente e constroem uma grande amizade ao longo dos anos. Mas, aos poucos, percebem com certo temor que estão apaixonados um pelo outro.",
popularity: 15.455,
poster_path: "/BTW9p26mVqckpq3f9kYxB4RELp.jpg",
release_date: "1989-01-12",
title: "Harry & Sally: Feitos um para o Outro",
video: false,
vote_average: 7.4,
vote_count: 2736,
},
{
adult: false,
backdrop_path: "/22esNAKvdcHaeyzhXD5uhTjDwTK.jpg",
genre_ids: [28, 80, 53],
id: 984,
original_language: "en",
original_title: "<NAME>",
overview:
"O policial <NAME> tenta rastrear um assassino psicopata num terraço antes que uma garota sequestrada morra. Quando o encontra, Harry abusa do direito civil do assassino, o que o coloca de volta nas ruas. Um ônibus escolar é sequestrado e Harry sai à busca do assassino novamente e a única maneira de pará-lo é a sangue frio.",
popularity: 10.754,
poster_path: "/4QryAOGFrApqXYchrsSviFxHQMJ.jpg",
release_date: "1971-07-14",
title: "Perseguidor Implacável",
video: false,
vote_average: 7.5,
vote_count: 1496,
},
{
adult: false,
backdrop_path: "/coJLkvK5KZQoMl8vGqcpgAZYroi.jpg",
genre_ids: [35, 18],
id: 2639,
original_language: "en",
original_title: "Deconstructing Harry",
overview:
"Harry Block é um escritor de sucesso que é convidado para receber uma homenagem na mesma universidade que um dia o rejeitou. Enquanto se prepara para a viagem, Harry é confrontado pelos seus personagens ficcionais, bem como pelas pessoas reais que não querem ter nada a ver com ele. O escritor percebe o quanto suas histórias afetaram as pessoas a seu redor.",
popularity: 8.518,
poster_path: "/rz0cls8nhbzIvcbntaICJDEnywl.jpg",
release_date: "1997-12-12",
title: "Desconstruindo Harry",
video: false,
vote_average: 7.4,
vote_count: 539,
},
{
adult: false,
backdrop_path: "/bDqchWjPhko0XvRBx4pErPMk0Hv.jpg",
genre_ids: [10749],
id: 518527,
original_language: "en",
original_title: "Harry & Meghan: A Royal Romance",
overview: "",
popularity: 16.634,
poster_path: "/2ODzSaM8EKF28mGjNTH3ptb3BJu.jpg",
release_date: "2018-05-13",
title: "Harry & Meghan: A Royal Romance",
video: false,
vote_average: 6.9,
vote_count: 151,
},
{
adult: false,
backdrop_path: "/hNQ0R4wSaXTUPUQti8FtKLf1HQ6.jpg",
genre_ids: [35, 80, 9648],
id: 11718,
original_language: "en",
original_title: "Who's <NAME>?",
overview:
"Quando <NAME> (<NAME>), a filha do magnata P.<NAME> (<NAME>), é sequestrada, o pai está disposto em fazer tudo para ter sua filha de volta. Um amigo, <NAME> (<NAME>), diz que a única pessoa que poderá ajudá-lo é <NAME> (<NAME>), o último descendente de uma família de grandes detetives. Acontece que Harry é um profissional decadente, que sempre faz muitas trapalhadas ao tentar resolver os casos. Desta vez talvez as coisas sejam um pouco diferentes, pois <NAME> (<NAME>), a irmã de Jennifer, quer ajudá-lo nas investigações.",
popularity: 7.394,
poster_path: "/qf7LNguEfBHF9WRs9sKGPBaQYEt.jpg",
release_date: "1989-02-03",
title: "Quem é <NAME>?",
video: false,
vote_average: 5.8,
vote_count: 179,
},
{
adult: false,
backdrop_path: "/71gHxSX2Tzg9mi1VYRdwCECfmpj.jpg",
genre_ids: [35, 14, 10751],
id: 8989,
original_language: "en",
original_title: "<NAME>",
overview:
"Quando estão voltando das férias, a família Henderson atinge o carro num estranho animal. Eles até chegam a pensar que seja um homem, mas percebem que se trata algo muito diferente: o lendário Pé Grande. Achando que ele está morto, levam o corpo para casa porque alguém poderia pagar algum dinheiro por aquilo. Mas o monstro está vivo e na verdade não tem nada de monstro. O ser gigante ganha o nome de Harry e aos poucos vai se tornando um membro da família. O problema é que os Handerson precisam fazer de tudo para mantê-lo escondido das autoridades.",
popularity: 8.737,
poster_path: "/7qqJ3gcYFmV29Gq7xT8g5Pj4WaH.jpg",
release_date: "1987-06-05",
title: "Um Hóspede do Barulho",
video: false,
vote_average: 5.9,
vote_count: 433,
},
{
adult: false,
backdrop_path: null,
genre_ids: [],
id: 393135,
original_language: "en",
original_title: "<NAME> and the Ten Years Later",
overview: "",
popularity: 24.96,
poster_path: "/zh1KtXxbcfj3wj202aEEE2E8V3n.jpg",
release_date: "2012-10-07",
title: "Harry Potter and the Ten Years Later",
video: false,
vote_average: 7.3,
vote_count: 8,
},
{
adult: false,
backdrop_path: "/mjCYpJXCBYDZgMr1U1KZcFgFDfC.jpg",
genre_ids: [99],
id: 482408,
original_language: "en",
original_title: "<NAME>: A History Of Magic",
overview: "",
popularity: 16.558,
poster_path: "/geike7VgTrftxwzcvND4dRdZdAv.jpg",
release_date: "2017-10-28",
title: "Harry Potter: A History Of Magic",
video: false,
vote_average: 6.8,
vote_count: 27,
},
{
adult: false,
backdrop_path: "/vkk55QHMdaFF1gVIwgns2AR3VHA.jpg",
genre_ids: [35],
id: 10152,
original_language: "en",
original_title: "Dumb and Dumberer: When <NAME>",
overview:
"Em 1986, <NAME> (<NAME>) e <NAME> (<NAME>) se conhecem. Ambos estão cursando o colegial e, com um Q.I. bem abaixo do normal e uma grande habilidade em causar confusões, logo se tornam grandes amigos. Juntos eles precisam lidar com os demais estudantes no colégio e com seus próprios pais.",
popularity: 13.772,
poster_path: "/mk8FFXBWq25ag2vk8PgcEnxSkHo.jpg",
release_date: "2003-04-14",
title: "Debi & Lóide 2: Quando Debi Conheceu Lóide",
video: false,
vote_average: 4.1,
vote_count: 561,
},
];
<file_sep>/src/components/Pagination/Pagination.test.js
import React from "react";
import { render } from "@testing-library/react";
import Pagination from "./Pagination";
describe("pagination component", () => {
const returnPageLength = (movies) => {
const data = Array(movies);
const splicePages = [...Array(Math.ceil(data?.length / 5 || 1))].map(
(_) => {
return data?.splice(0, 5);
}
);
const pages = Array.from(
{ length: splicePages?.length || 1 },
(v, k) => k + 1
);
return pages.length;
};
it("should render pagination ", () => {
const { getByTestId } = render(<Pagination data-testid="pagination" />);
const el = getByTestId("pagination");
expect(el).not.toBeNull();
});
it("pagination corretcs when 20 movies", () => {
expect(returnPageLength(20)).toBe(4);
});
it("pagination corretcs when 1 movie", () => {
expect(returnPageLength(1)).toBe(1);
});
it("pagination corretcs when 0 movie", () => {
expect(returnPageLength(0)).toBe(1);
});
it("pagination corretcs when 5 movie", () => {
expect(returnPageLength(5)).toBe(1);
});
it("pagination corretcs when 2 movie", () => {
expect(returnPageLength(8)).toBe(2);
});
});
<file_sep>/src/renderAppWithState.js
import React from "react";
import { Provider } from "react-redux";
import { mount } from "enzyme";
import Main from "./views/Main/Main";
import store from "./Store";
export default function renderAppWithState(state) {
const wrapper = mount(
<Provider store={store}>
<Main />
</Provider>
);
return [store, wrapper];
}
<file_sep>/src/libs/redux/reducers/reducers-test/MoviesReducer.test.js
import MoviesReducer from "../MoviesReducer";
describe("Movies Reducer", () => {
it("Has a default state", () => {
expect(MoviesReducer(undefined, { type: "unexpected" })).toEqual({
currentPage: [],
moviesList: [],
selectedMovie: {},
});
});
it("can handle SAVE_MOVIES_LIST", () => {
expect(
MoviesReducer(undefined, {
type: "SAVE_MOVIES_LIST",
payload: [{ movie: "Harry Potter" }],
})
).toEqual({
moviesList: [{ movie: "Harry Potter" }],
currentPage: [],
selectedMovie: {},
});
});
it("can handle SAVE_MOVIES_BY_PAGE", () => {
expect(
MoviesReducer(undefined, {
type: "SAVE_MOVIES_BY_PAGE",
payload: [{ page1: "Harry Potter" }, { page2: "Harry Potter" }],
})
).toEqual({
moviesList: [],
currentPage: [{ page1: "Harry Potter" }, { page2: "Harry Potter" }],
selectedMovie: {},
});
});
it("can handle SAVE_MOVIE_DETAIL", () => {
expect(
MoviesReducer(undefined, {
type: "SAVE_MOVIE_DETAIL",
payload: { movie: "Harry Potter" },
})
).toEqual({
moviesList: [],
currentPage: [],
selectedMovie: { movie: "Harry Potter" },
});
});
it("can handle CLEAR_MOVIE_DETAIL", () => {
expect(
MoviesReducer(undefined, {
type: "CLEAR_MOVIE_DETAIL",
payload: {},
})
).toEqual({
moviesList: [],
currentPage: [],
selectedMovie: {},
});
});
});
<file_sep>/src/components/Card/Card.js
import moment from "moment";
import React from "react";
import { Date, Tag, Text, Title, RoundedData } from "..";
import { Colors } from "../../utils/Colors";
import {
StyledCard,
StyledImage,
StyledInfo,
StyledInfoTitle,
StyledApproval,
StyledTitle,
StyledDate,
StyledOverview,
StyledTags,
} from "./styles";
const Card = (props) => {
const title = props.movie?.title;
const vote_average = props.movie?.vote_average;
const release_date = props.movie?.release_date;
const poster_path = props.movie?.poster_path;
const overview = props.movie?.overview;
const describedGenres = props.movie?.describedGenres;
const { key, onClick } = props;
const poster = `https://image.tmdb.org/t/p/w500${poster_path}`;
return (
<StyledCard url={poster} key={key} onClick={onClick} data-testid={"card"}>
<StyledImage src={poster} />
<StyledInfo>
<StyledInfoTitle>
<StyledApproval>
<RoundedData rating data={vote_average * 10 + "%"} />
</StyledApproval>
<StyledTitle>
<Title title={title} color={Colors.secondary} />
</StyledTitle>
<StyledDate>
<Date date={moment(release_date).format("DD/MM/YYYY")} />
</StyledDate>
</StyledInfoTitle>
<StyledOverview>
<Text text={overview} />
</StyledOverview>
<StyledTags>
{describedGenres?.map((genre, key) => (
<Tag tag={genre} key={key} />
))}
</StyledTags>
</StyledInfo>
</StyledCard>
);
};
export default Card;
<file_sep>/src/components/Card/styles.js
import styled, { css, keyframes } from "styled-components";
import { Colors } from "../../utils/Colors";
const fade = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
margin-top: 50px;
}
`;
export const StyledCard = styled.div`
display: flex;
align-self: center;
flex-direction: row;
background-color: ${Colors.background};
height: fit-content;
min-heigth: 330px;
width: 60%;
position: unset;
cursor: pointer;
animation-name: ${fade};
animation-duration: 1.5s;
animation-direction: normal;
animation-fill-mode: forwards;
${(props) =>
props.color &&
css`
color: ${props.color};
`};
@media (max-width: 768px) {
width: 90%;
height: auto;
max-height: unset;
}
@media (max-width: 500px) {
min-height: 550px;
height: fit-content;
position: relative;
z-index: 1;
width: 90%;
&:before {
content: "aaaaaaaaaaaaa";
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
z-index: 0;
background-image: url("${(props) => props.url}");
background-size: cover;
filter: blur(2px) brightness(20%);
border: 1px solid red;
}
}
`;
export const StyledImage = styled.img`
width: 250px;
@media (max-width: 768px) {
width: 250px;
}
@media (max-width: 500px) {
display: none;
}
`;
export const StyledInfo = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
width: 100%;
@media (max-width: 500px) {
z-index: 1;
}
`;
export const StyledInfoTitle = styled.div`
background-color: ${Colors.primary};
position: relative;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-content: flex-end;
`;
export const StyledApproval = styled.div`
width: 110px;
`;
export const StyledTitle = styled.div`
width: 85%;
padding-top: 20px;
padding-bottom: 2px;
@media (max-width: 500px) {
color: white;
}
`;
export const StyledDate = styled.div`
position: absolute;
bottom: -45px;
left: 110px;
`;
export const StyledOverview = styled.div`
margin-top: 25px;
padding: 0px 35px;
`;
export const StyledTags = styled.div`
display: flex;
flex-wrap: wrap;
padding: 0px 35px;
@media (max-width: 500px) {
width: 100%;
}
`;
<file_sep>/src/components/RoundedData/RoundedData.test.js
import React from "react";
import { render } from "@testing-library/react";
import RoundedData from "./RoundedData";
describe("RoundedData component", () => {
it("should render RoundedData ", () => {
const { getByTestId } = render(<RoundedData data-testid="rounded-data" />);
const el = getByTestId("rounded-data");
expect(el).not.toBeNull();
});
});
<file_sep>/src/views/Main/Main.js
import React, { useCallback, useEffect, useState } from "react";
import { connect } from "react-redux";
import { Card, Header, Pagination, Spinner, TextInput } from "../../components";
import { MoviesController } from "../../controller";
import { StyledMain } from "./styles";
import { debounce } from "lodash";
const Main = (props) => {
const {
searchMovies,
selectMovie,
currentPageMovies,
clearMovieDetail,
moviesList,
paginateItems,
history,
updateListOnRedux,
} = props;
const [isFetching, setFetching] = useState(false);
const handleChange = useCallback(
debounce((text) => {
searchMovies(text).then((res) => {
setFetching(false);
});
}, 1000),
[]
);
const handleSelectMovie = (movie) => {
selectMovie(movie);
history.push(`/movie/${movie.id}`);
};
useEffect(() => {
updateListOnRedux();
clearMovieDetail();
}, []);
return (
<StyledMain>
<Header title={"Movies"} />
<TextInput
placeholder={"Busque um filme por nome ou gênero..."}
onChange={(e) => {
setFetching(true);
handleChange(e.target.value);
}}
/>
{!isFetching ? (
currentPageMovies?.map((movie, key) => (
<Card
onClick={() => handleSelectMovie(movie)}
movie={movie}
key={key}
/>
))
) : (
<Spinner />
)}
{!isFetching ? (
<Pagination list={moviesList} paginateItems={paginateItems} />
) : null}
</StyledMain>
);
};
const mapStateToProps = (state) => {
const {
movies: { moviesList, currentPage },
} = state;
return { moviesList, currentPageMovies: currentPage };
};
const mapDispatchToProps = (dispatch) => {
return {
searchMovies: (name) => dispatch(MoviesController.searchMovie(name)),
selectMovie: (movie) => dispatch(MoviesController.selectedMovieCard(movie)),
paginateItems: (list) => dispatch(MoviesController.paginateMovies(list)),
updateListOnRedux: () => dispatch(MoviesController.updateListOnRedux()),
clearMovieDetail: () => dispatch(MoviesController.clearMovieDetail()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Main);
<file_sep>/src/components/Video/Video.js
import React from "react";
import { StyledVideo, Frame } from "./styles";
const Video = ({ url }) => {
return (
<StyledVideo data-testid="video">
<Frame type="text/html" src={url} frameBorder="0" />
</StyledVideo>
);
};
export default Video;
<file_sep>/src/components/Info/Info.js
import React from "react";
import { StyledInfo, StyledTitle, StyledValue } from "./styles";
const Info = ({ title, value }) => (
<StyledInfo>
<StyledTitle>{title}</StyledTitle>
<StyledValue>{value}</StyledValue>
</StyledInfo>
);
export default Info;
|
8501d892f507d04d28de61bf480dcf697274701d
|
[
"JavaScript",
"Markdown"
] | 35
|
JavaScript
|
caiookb/the-movie-db-frontend
|
f631469a642d001908594d1a815328a60b317ebb
|
71105c054d12bc742d0ca90ee15ac8ef7a192501
|
refs/heads/master
|
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<h3>Your form was successfully submitted!</h3>
<?php echo $link; ?>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/js/materialize.min.js"></script>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div id="pass_res">
<h1 >Password Reset</h1>
</div>
<div class="row main">
<div class="main-login main-center">
<?php $attributes = array('class'=>"form-horizontal"); ?>
<?php echo form_open('Reset/rpssq', $attributes); ?>
<div style="color: red; font-size: 20px;">
<?php if(isset($message)){; ?>
<?php echo $message; ?>
<?php }; ?>
</div>
<div class="form-group">
<label for="email" class="cols-sm-2 control-label">Your Email</label>
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="email" id="email" value="<?php echo set_value('email'); ?>" required="true" placeholder="Enter your Email"/>
</div>
<small class="text-muted">To reset your password, submit your email address</small>
</div>
</div>
<div class="form-group ">
<button type="submit" class="btn btn-primary btn-lg btn-block login-button">Reset password</button>
</div>
<div class="login-register">
<a href="#" class="pull-left">Choose another method</a>
<a href="#" class="pull-right" id="canc_but" role="button" data-toggle="modal" data-target=".bd-example-modal-sm">Cancel process</a>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
<div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Password Reset Cancellation Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure?
</div>
<div class="modal-footer">
<a href="<?php echo site_url('home')?>" class="btn btn-success" role="button">Yes</a>
<button type="button" class="btn btn-danger" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
$id = $this->session->userdata['logged_in']['id']
?>
<div class="container">
<?php if(isset($message)){; ?>
<h1><?php echo $message; ?></h1>
<?php }; ?>
<hr>
<div class="row">
<div class="col-sm-6">
<?php if (isset($info)) {?>
<?php echo 'Last Login:'.' '. $info['lastLoginDateTime'] ;?>
</div>
<div class="col-sm-6">
<!-- <?php echo 'Last Login IP Address:'.' '. $info['lastLoginIP'] ;?>
<?php } ?> -->
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12 col-sm-12">
<h1>Courses currently available</h1>
<hr>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<tr>
<th width="8%">Event ID</th>
<th width="15%">Event Title</th>
<th width="8%">Start Date</th>
<th width="1%">Time</th>
<!-- <th width="15%">Venue</th> -->
<!-- <th width="20%">Description</th> -->
<!-- <th width="6%">Status</th> -->
<th width="6%">Take Action</th>
</tr>
<?php if (isset($all_event) && $all_event!=false) {?>
<?php foreach($all_event as $the_events) { ?>
<tbody>
<tr>
<td><?php echo $the_events['eventID'] ;?></td>
<td><?php echo $the_events['title'] ;?></td>
<td><?php echo $the_events['startDate'] ;?></td>
<td><?php echo $the_events['time'] ;?></td>
<!-- <td><?php echo $the_events['venue'] ;?></td> -->
<!-- <td><span class="more"><?php echo $the_events['description'] ;?></span></td> -->
<td>
<?php echo form_open('stu_reg_for_cour'); ?>
<input type="text" hidden="true" name="id" value="<?php echo $the_events['eventID'] ;?>" />
<button type="submit" class="btn btn-success" value="Register" >Register</button>
<?php echo form_close();?>
</td>
</tr>
</tbody>
<?php } ?>
<?php } ?>
</table>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<div class="col-lg-2 col-sm-2"></div>
<div class="col-lg-8 col-sm-8">
<h1>Events List</h1>
<!-- <a href="<?php echo base_url()?>index.php/event/all_ev_tbl">Click here to display Eall events in a table</a> -->
<hr>
<ul class="event-list">
<?php if (isset($all_event)) {?>
<?php foreach($all_event->result_array() as $the_events) { ?>
<li>
<time datetime="<?php echo $the_events['startDate'] ;?>">
<span class="day"><?php echo date("d", strtotime( $the_events['startDate']))?></span>
<span class="month"><?php echo date("M", strtotime( $the_events['startDate']))?></span>
<span class="year"><?php echo date("Y", strtotime( $the_events['startDate']))?></span>
<span class="time"><?php echo date("F", strtotime($the_events['time'] ))?></span>
</time>
<img alt="Independence Day" src="https://farm4.staticflickr.com/3100/2693171833_3545fb852c_q.jpg" />
<div class="info">
<h2 class="title"><?php echo $the_events['title'] ;?></h2>
<p class="desc"> <a href="<?php echo base_url() ;?>index.php/load_event/<?php echo $the_events['eventID']?>">Click here to see event details.</a> </p>
</div>
</li>
<?php } ?>
<?php } ?>
</ul>
</div>
<div class="col-lg-2 col-sm-2"></div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-4 col-sm-offset-1 col-sm-4">
<h1>Add a course</h1>
<hr>
<?php echo form_open('submit_course'); ?>
<div class="form-group">
<label for="description">Descripttion</label>
<?php echo form_error('description'); ?>
<textarea class="form-control" placeholder="Enter Description" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label for="venue">Purpose of the course</label>
<?php echo form_error('venue'); ?>
<textarea class="form-control" placeholder="Enter Purpose" name="purpose"><?php echo set_value('purpose'); ?></textarea>
</div>
<button type="reset" class="btn btn-danger">Reset</button>
<button type="submit" class="btn btn-success pull-right">Save</button>
<?php echo form_close(); ?>
</div>
<div class="col-lg-5 col-sm-offset-1 col-sm-5">
<h1>List Of Courses</h1>
<hr>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th width="10%">Course ID</th>
<th width="40%">Description</th>
<th width="40%">Purpose</th>
<th width="10%">Edit</th>
</tr>
</thead>
<tbody>
<?php if (isset($all_courses)) {?>
<?php foreach($all_courses->result_array() as $the_courses) { ?>
<tr>
<td><?php echo $the_courses['courseID'] ;?></td>
<td><span class="more"><?php echo $the_courses['description'] ;?></span></td>
<td><span class="more"><?php echo $the_courses['purpose'] ;?></span></td>
<td>
<a href="#">Edit <i class="fa fa-pencil" aria-hidden="true"></i></a>
<a href="#">Cancel <i class="fa fa-ban" aria-hidden="true"></i></a>
<a href="#">Email <i class="fa fa-envelope-o" aria-hidden="true"></i></a>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Search_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_desc($qs)
{
$this->db->select('description');
$this->db->like('description', $q);
$query = $this->db->get('course');
if($query->num_rows() > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['description'])); //build an array
}
echo json_encode($row_set); //format the array into json data
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Event extends CI_Controller {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function index()
{
/* $this->load->view('home/header');
$this->load->view('home/nav');
$this->load->view('home/intro');
$this->load->view('home/about');
$this->load->view('home/courses');
$this->load->view('home/contact');
$this->load->view('home/footer');*/
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('home/header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('home/nav');
/*Body*/
$this->load->view('home/intro');
$this->load->view('home/about');
$this->load->view('home/courses');
$this->load->view('home/contact');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('home/footer');
$this->load->view('footer/end_footer');
}
public function get_all_event(){
/*print_r($id);
exit();*/
$data ['all_event'] = $this->Event_model->select_all_event();
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_list',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
public function get_all_event_for_table(){
$data ['all_event'] = $this->Event_model->select_all_event();
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_list_for_table',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
/* public function get_all_event_for_table_by_num($Num_sel){
$data ['all_event'] = $this->Event_model->select_all_event_by_num($Num_sel);
$data ['Num_sel'] = $Num_sel ;
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
$this->load->view('staff/shared/staff_nav');
$this->load->view('staff/event/event_list_for_table',$data);
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}*/
public function select_events_for_student($studenID){
$data ['my_events'] = $this->Event_model->select_events_for_student($studenID);
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_list_for_table',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
public function call_event($id){
$data ['one_event'] = $this->Event_model->select_one_event($id);
$data ['all_courses'] = $this->Courses_model->select_all_course();
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_details',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
public function update_event()
{
$this->form_validation->set_rules('time', 'Time', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('courseID', 'Event Title', 'required');
$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required|callback_check_equal_less');
$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
$this->form_validation->set_rules('venue', 'Venue', 'required');
if ($this->form_validation->run() === FALSE)
{
/* print_r($this->input->post('eventID'));
exit();*/
/*redirect('/event');*/
$data ['one_event'] = $this->Event_model->select_one_event($this->input->post('eventID'));
$data ['all_courses'] = $this->Courses_model->select_all_course();
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_details',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
else
{
$get_event_title_by_id = $this->Event_model->get_ev_title($this->input->post('courseID'));
$data = array(
'time' =>$this->input->post('time'),
'courseID' =>$this->input->post('courseID'),
'title' =>$get_event_title_by_id[0]['description'],
'description' =>$this->input->post('description'),
'startDate' =>nice_date($this->input->post('start_date'),'Y-m-d'),
'endDate' =>nice_date($this->input->post('end_date'),'Y-m-d'),
'venue' => $this->input->post('venue')
);
$id = $this->input->post('eventID');
if($this->Event_model->update_event($data, $id)){
$data = array (
'path_redirect'=>'all_ev_tbl',
'message'=>'Return to Event List'
);
$this->load->view('success',$data);
}else{
$this->get_all_event();
}
}
}
public function create_event()
{
$this->form_validation->set_rules('time', 'Time', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('courseID', 'Event Title', 'required');
$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required|callback_check_equal_less');
$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
$this->form_validation->set_rules('venue', 'Venue', 'required');
if ($this->form_validation->run() === FALSE)
{
/*print_r('form validation');
exit();*/
/*redirect('/event');*/
$data ['next_five_events'] = $this->Event_model->select_next_five_event();
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_form',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
else
{
$get_event_title_by_id = $this->Event_model->get_ev_title($this->input->post('courseID'));
/*print_r($get_event_title_by_id[0]['description']);
exit();*/
$data = array(
'time' =>$this->input->post('time'),
'courseID' =>$this->input->post('courseID'),
'title' =>$get_event_title_by_id[0]['description'],
'description' =>$this->input->post('description'),
'startDate' =>nice_date($this->input->post('start_date'),'Y-m-d'),
'endDate' =>nice_date($this->input->post('end_date'),'Y-m-d'),
'venue' => $this->input->post('venue')
);
if($this->Event_model->insert_event($data)){
$data = array (
'path_redirect'=>'all_ev_tbl',
'message'=>'View Event List'
);
$this->load->view('success',$data);
}else{
$this->get_all_event_for_table();
}
}
}
function check_equal_less(){
$startDate=nice_date($this->input->post('start_date'),'Y-m-d');
$endDate=nice_date($this->input->post('end_date'),'Y-m-d');
if(strtotime($endDate) <= strtotime($startDate)){
$this->form_validation->set_error_delimiters('<div id="error">', '</div>');
$this->form_validation->set_message('check_equal_less','Your Start Date must be earlier than your End Date');
return false;
}else{
return true;
}
}
public function form()
{
$data ['all_courses'] = $this->Event_model->select_all_courses();
/* $data['course_desc']= $this->Ajax_model->get_course_purpose(1010);
print_r($data['course_desc']);
exit();*/
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/event/event_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/event/event_form',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/event/event_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
public function student_ev()
{
$data ['stud_events'] = $this->Event_model->select_stud_event();
$this->load->view('staff/event/event_header');
$this->load->view('staff/shared/staff_nav');
$this->load->view('staff/event/event_form',$data);
$this->load->view('staff/event/event_footer');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<!-- Scrolling Nav JavaScript -->
<script src="<?php echo base_url()?>assets/js/jquery.easing.min.js"></script>
<script src="<?php echo base_url()?>assets/js/scrolling-nav.js"></script>
<script src="<?php echo base_url()?>assets/bootstrap-formhelpers-phone/js/bootstrap-formhelpers.min.js"></script>
<script src="<?php echo base_url()?>assets/js/registration/registration.js"></script>
<script src="<?php echo base_url()?>assets/js/google_address/google_address.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&libraries=places&callback=initAutocomplete"
async defer></script>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Event_model extends CI_Model {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function select_all_event_student_registered($id){
#Create where clause
$this->db->select('eventID');
$this->db->from('event_student');
$this->db->where('completed',false);
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->select('*');
$this->db->from('event');
$this->db->where("`eventID` IN ($where_clause)", NULL, FALSE);
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function select_all_event_student_completed($id){
#Create where clause
$this->db->select('eventID');
$this->db->from('event_student');
$this->db->where('completed',true);
$this->db->where('studentID',$id);
$where_clause = $this->db->get_compiled_select();
$this->db->select ('e.*' );
$this->db->from ( 'event as e, event_student as s');
$this->db->join(' s', 'e.eventID = s.eventID');
$this->db->where("`e.eventID` IN ($where_clause)", NULL, true);
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function select_all_event_student_unregistered($id){
#Create where clause
$this->db->select('eventID');
$this->db->from('event_student');
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->select('*');
$this->db->from('event');
$this->db->where("`eventID` IN ($where_clause)", NULL, true);
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function get_ev_title($id){
$this->db->select('description');
$this->db->where('courseID', $id);
$this->db->from('course');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->result_array();
/*print_r($row);
exit();*/
/*$data = array(
'purpose' => $row[0]['purpose']
);*/
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function insert_event($data)
{
$this->db->insert('event', $data);
if($this->db->affected_rows()){
return true;
}else{
return false;
}
}
public function update_event($data,$id)
{
$this->db->where('eventID', $id);
$this->db->update('event', $data);
if($this->db->affected_rows()){
return true;
}else{
return false;
}
}
public function select_all_event(){
$this->db->select('e.*');
$this->db->from('event e');
$this->db->order_by("startDate", "asc");
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function select_all_event_for_student(){
#Create where clause
$this->db->select('eventID');
$this->db->from('event_student');
//$this->db->where('status','Unregistered');
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->select('*');
$this->db->from('event');
$this->db->where("`eventID` NOT IN ($where_clause)", NULL, true);
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function select_all_event_student($studentID){
#Create where clause
$this->db->select('eventID');
$this->db->from('event_student');
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->select('*');
$this->db->from('event');
$this->db->where("`eventID` NOT IN ($where_clause)", NULL, FALSE);
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function select_all_event_by_num($Num_sel){
$this->db->select('*');
$this->db->where('startDate >', date("Y-m-d"));
$this->db->from('event');
$this->db->order_by("startDate", "asc");
$this->db->limit($Num_sel);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_stud_event(){
$this->db->select('*');
$this->db->where('studentID', $id);
$this->db->from('event');
$this->db->order_by("startDate", "asc");
$this->db->limit(3);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_next_five_event(){
$this->db->select('*');
$this->db->where('startDate >', date("Y-m-d"));
$this->db->from('event');
$this->db->order_by("startDate", "asc");
$this->db->limit(3);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_all_courses(){
$this->db->select('courseID,description,purpose');
$this->db->from('course');
$this->db->order_by("description", "asc");
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_one_event($id){
//$query = $this->db->query("SELECT * FROM event WHERE startDate>".date('Y-m-d'));
$this->db->select('*');
$this->db->where('eventID', $id);
$this->db->from('event');
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-offset-2 col-sm-6">
<h1>Update Course</h1>
<hr>
<?php if (isset($one_course)) {?>
<?php foreach($one_course->result_array() as $the_course) { ?>
<?php echo form_open('update_course'); ?>
<input type="text" hidden="true" name="courseID" value="<?php echo $the_course['courseID'] ;?>"/>
<div class="form-group">
<label for="description">Descripttion</label>
<?php echo form_error('description'); ?>
<textarea class="form-control" placeholder="Enter Description" name="description"><?php echo $the_course['description'] ;?></textarea>
</div>
<div class="form-group">
<label for="venue">Purpose</label>
<?php echo form_error('purpose'); ?>
<textarea class="form-control" placeholder="Enter Purpose" name="purpose"><?php echo $the_course['purpose'] ;?></textarea>
</div>
<button type="reset" class="btn btn-danger">Clear</button>
<button type="submit" class="btn btn-success pull-right">Save</button>
<?php } ?>
<?php } ?>
<?php echo form_close(); ?>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#top">FAMHEALTH</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav" id="navcenter">
<li class="active"><a href="#top">Home</a></li>
<li><a href="#about" title="All about FAMHEALTH NMU">About</a></li>
<li><a href="#courses" title="FAMHEALTH NMU Courses">Courses</a></li>
<li><a href="#contact" title="FAMHEALTH NMU Contact details (Tel, email, etc)">Contact</a></li>
<li><a href="<?php echo site_url()?>/stu_reg_form" title="Register as a new student"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Login
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="<?php echo site_url()?>/stud_log" title="Login as registered student"><i class="fa fa-lock" aria-hidden="true"></i> Student</a></li>
<li><a href="<?php echo site_url()?>/staff_log" title="Admin Login"><i class="fa fa-lock" aria-hidden="true"></i> Staff</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('home/header');
$this->load->view('home/nav');
$this->load->view('home/intro');
$this->load->view('home/about');
$this->load->view('home/courses');
$this->load->view('home/contact');
$this->load->view('home/footer');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-sm-3"></div>
<div id="form_even_details" class="col-lg-6 col-sm-6">
<h1>Update Event</h1>
<hr>
<?php if (isset($one_event)) {?>
<?php foreach($one_event->result_array() as $the_event) { ?>
<?php echo form_open('update_ev'); ?>
<input type="text" hidden="true" name="eventID" value="<?php echo $the_event['eventID'] ;?>"/>
<div class="form-group">
<label for="title">Title</label>
<?php echo form_error('title'); ?>
<?php if (isset($all_courses)) {?>
<select name="courseID" id="courseID" class="form-control">
<!-- <option selected="selected"></option> -->
<?php foreach($all_courses->result_array() as $the_courses) { ?>
<option value="<?= $the_courses['courseID'] ?>"><?= $the_courses['description'] ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="description">Descripttion</label>
<?php echo form_error('description'); ?>
<textarea class="form-control" placeholder="Enter Description" id="description" name="description"><?php echo $the_event['description'] ;?></textarea>
</div>
<div class="form-group">
<label for="venue">Venue</label>
<?php echo form_error('venue'); ?>
<input type="text" class="form-control" id="autocomplete" onFocus="geolocate()" name="venue" value="<?php echo $the_event['venue'] ;?>"/>
</div>
<div class="form-group">
<label for="start_date">Start Date</label>
<?php echo form_error('start_date'); ?>
<input type="date" id="starDate" class="form-control" name="start_date" value="<?php echo $the_event['startDate'] ;?>"/>
</div>
<div class="form-group">
<label for="end_date">End Date</label>
<?php echo form_error('end_date'); ?>
<input type="date" id="endDate" class="form-control" name="end_date" value="<?php echo $the_event['endDate'] ;?>"/>
</div>
<div class="form-group">
<label for="time">Time</label>
<?php echo form_error('time'); ?>
<input type="time" id="time" class="form-control" name="time" value="<?php echo date('h:i',strtotime($the_event['time']));?>"/>
</div>
<!-- <input type="text" name="timey" value="<?php echo date("h:i A",strtotime($the_event['time']));?>"/> -->
<button type="reset" class="btn btn-danger">Clear</button>
<button type="submit" class="btn btn-success pull-right">Save</button>
<?php } ?>
<?php } ?>
<?php echo form_close(); ?>
</div>
<div class="col-lg-3 col-sm-3"></div>
</div>
</div>
</div>
<script type="text/javascript">
$("#courseID").change(function(){
var id = $('#courseID').val();
alert(id);
$.ajax({
url:'<?php echo site_url("Ajax/get_course_purpose")?>',
type:'POST',
data:{'id':id},
dataType: 'json',
cache: false,
success:function(data){
//var resdata = course_desc;
//alert(JSON.stringify(resdata));
$.each(data, function(i, val) {
//alert(JSON.stringify(val.purpose));
$("#description").html(val.purpose);
});
//alert(JSON.stringify(course_desc));
//alert(JSON.parse(course_desc));
//$("#description").html(val.purpose);
},error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Something went Wrong!!");
}
});
});
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Success</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<link href="<?php echo base_url()?>assets/css/success/success.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Success </h1>
<hr>
<div class="row">
<ul>
<li>
<a href="<?php echo base_url()?>index.php/<?php echo $path_redirect ?>"><?php echo $message ?></a>
</li>
<!-- <li>
<a href="<?php echo base_url()?>index.php/home">Home Page</a></li>
</li> -->
<!-- <li>
<a href="<?php echo base_url()?>index.php/register">Student Registration</a></li>
</li> -->
</ul>
</div>
</div>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
/*Default Controller*/
$route['default_controller'] = 'home';
/*Default Values*/
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
/*Student*/
$route['attend_stud'] = 'student/$1';
$route['sub_reg'] = 'student/submit_reg';
$route['stu_reg_form'] = 'student/student_reg_form';
$route['reset_password'] = 'student/student_reg_form';
$route['register'] = 'student/student_reg_form';
$route['stud_attend']= 'student/record_student_attendance';
$route['view_all_stud']= 'student/view_all_students';
$route['upd_stud']= 'student/update_student_details';
$route['stu_reg_for_cour']= 'student/register_student_for_course';
$route['list_cour_stu_dereg']= 'student/list_of_event_student_can_deregister_from';
$route['stu_dereg_for_cour']= 'student/deregister_student_for_course';
$route['cours_stud_regted_for']= 'student/view_event_student_registered_for';
$route['list_cours_stud_regi']= 'student/view_all_event_student_can_register_for';
$route['list_cours_stu_compl']= 'student/view_all_event_student_completed';
/*Course*/
$route['add_courses'] = 'course/courses_form';
$route['view_all_courses'] = 'course/get_all_courses';
$route['load_course/(:num)'] = 'course/load_one_course/$1';
$route['submit_course'] = 'course/create_course';
$route['update_course'] = 'course/update_course';
$route['course'] = 'course/get_all_courses';
/*Event*/
$route['submit_event'] = 'event/create_event';
$route['event/(:num)'] = 'event/form';
$route['create_event'] = 'event/form';
$route['event/stud'] = 'event/student_ev';
$route['all_ev'] = 'event/get_all_event';
$route['all_ev_tbl'] = 'event/get_all_event_for_table';
$route['update_ev'] = 'event/update_event';
$route['event_stud/(:num)'] = 'event/select_events_for_student/$1';
$route['load_event/(:num)'] = 'event/call_event/$1';
/*Ajax*/
$route['cour_desc'] = "ajax/get_course_description";
/*Staff*/
$route['staff_dash'] = 'Dashboard/dashboard';
/*Login*/
$route['staff_log'] = 'login/staff_login_form';
$route['stud_log'] = 'login/student_login_form';
$route['log_stud_val'] = 'login/login_student_validation';
$route['log_staf_val'] = 'login/login_staff_validation';
$route['log_out/(:any)'] = 'login/logout/$1';
/*Registration*/
$route['staff_log'] = 'login/staff_login_form';
/*Reset*/
$route['admin_reset'] = 'reset/Reset_Password_Staff_form';
$route['stud_reset'] = 'reset/Reset_Password_Student_form';
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div id="stud_reg_pro">
<h1 >Student Registration</h1>
</div>
<div style="color: white; font-size: 20px;">
<?php if(isset($message)){; ?>
<?php echo $message; ?>
<?php echo validation_errors(); ?>
<?php }; ?>
</div>
</div>
<!-- multistep form -->
<?php $attributes = array('id' => 'msform', 'name' => 'registration'); ?>
<?php echo form_open('sub_reg', $attributes); ?>
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Personal Details</li>
<li>Address</li>
<li>Create your account</li>
</ul>
<!-- fieldsets -->
<div class="fieldset">
<h2 class="fs-title">Personal Details</h2>
<h3 class="fs-subtitle">This is step 1</h3>
<label for="firstName" class="pull-left">First Name</label>
<input type="text" id="FirstName" placeholder="<NAME>" name="firstName" required="true" value="<?php echo set_value('firstName'); ?>">
<label for="lastName" class="pull-left">Last Name</label>
<input type="text" id="lastName" placeholder="<NAME>" name="lastName" value="<?php echo set_value('lastName'); ?>">
<label for="dateOfBirth" class="pull-left">Date of Birth</label>
<input type="date" name="dateOfBirth" id="dateOfBirth" placeholder="YYYY/MM/DD" value="<?php echo set_value('dateOfBirth'); ?>">
<label for="phone" class="pull-left">Phone</label>
<input type="text" name="phone" id="phone" placeholder="Phone" class="input-medium bfh-phone" data-country="ZA" value="<?php echo set_value('phone'); ?>"/>
<input type="button" name="next" id="next1" class="next action-button" value="Next" />
<a href="#" class="btn btn-sm pull-right btn-danger" id="canc_but" role="button" data-toggle="modal" data-target=".bd-example-modal-sm">Cancel</a>
</div>
<div class="fieldset">
<h2 class="fs-title">Address</h2>
<h3 class="fs-subtitle">This is step 2</h3>
<label for="autocomplete" class="pull-left">Address Line 1</label>
<input id="autocomplete" name="addressLine1" placeholder="Address Line 1" onFocus="geolocate()" type="text" value="<?php echo set_value('addressLine1'); ?>"></input>
<label for="addressLine2" class="pull-left">Address Line 2</label>
<input type="text" name="addressLine2" id="addressLine2" placeholder="Address Line 2" value="<?php echo set_value('addressLine2'); ?>">
<label for="postal_code" class="pull-left">Postal Code</label>
<input type="number" id="postal_code" disabled="true" name="postalCode" readonly="true" value="<?php echo set_value('postalCode'); ?>">
<label for="locality" class="pull-left">City</label>
<input type="text" id="locality" disabled="true" name="city" readonly="true" value="<?php echo set_value('city'); ?>">
<input type="text" id="street_number" disabled="true" name="street_number" hidden="true" value="<?php echo set_value('street_number'); ?>"/>
<input type="text" id="route" disabled="true" name="route" hidden="true" value="<?php echo set_value('route'); ?>">
<input type="text" id="administrative_area_level_1" disabled="true" name="province" hidden="true" value="<?php echo set_value('province'); ?>">
<input type="text" id="country" disabled="true" hidden="true" name="country" value="<?php echo set_value('country'); ?>">
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="button" name="next" id="next2" class="next action-button" value="Next" />
<a href="#" class="btn btn-sm pull-right btn-danger" id="canc_but" role="button" data-toggle="modal" data-target=".bd-example-modal-sm">Cancel</a>
</div>
<div class="fieldset">
<h2 class="fs-title"> Create your account</h2>
<h3 class="fs-subtitle">This is step 3</h3>
<label for="email" class="pull-left">Email Address</label>
<input type="email" id="email" placeholder="Email Address" required="true" name="email" value="<?php echo set_value('email'); ?>">
<label for="password" class="pull-left">Password</label>
<input type="<PASSWORD>" id="password" name="password" required="true" />
<span style="text-decoration: none;font-size: 8px; color: red;">6 to 20 characters which contain at least one numeric digit, one uppercase and one lowercase letter</span>
<br>
<label for="confirm_password" class="pull-left">Confirm Password</label>
<input type="<PASSWORD>" id="confirm_password" name="passwordconfirm" required="true"/>
<span id='valid'></span><br>
<span id='message'></span><br>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" id="submit" class="submit action-button" value="Submit" />
<a href="#" class="btn btn-sm pull-right btn-danger" id="canc_but" role="button" data-toggle="modal" data-target=".bd-example-modal-sm">Cancel</a>
</div>
<?php echo form_close(); ?>
<div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Cancellation Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure?
</div>
<div class="modal-footer">
<a href="<?php echo site_url('home')?>" class="btn btn-success" role="button">Yes</a>
<button type="button" class="btn btn-danger" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#msform').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
dateOfBirth: {
validators: {
date: {
format: 'YYYY/MM/DD',
message: 'The value is not a valid date'
}
}
}
}
});
});
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
$id = $this->session->userdata['logged_in']['id']
?>
<div class="container">
<?php if(isset($message)){; ?>
<h1><?php echo $message; ?></h1>
<?php }; ?>
<hr>
<div class="row">
<div class="col-sm-6">
<?php if (isset($info)) {?>
<?php echo 'Last Login:'.' '. $info['lastLoginDateTime'] ;?>
</div>
<div class="col-sm-6">
<!-- <?php echo 'Last Login IP Address:'.' '. $info['lastLoginIP'] ;?>
<?php } ?> -->
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12 col-sm-12">
<h1>Courses</h1>
<hr>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<tr>
<th width="8%">Event ID</th>
<th width="15%">Event Title</th>
<th width="8%">Start Date</th>
<th width="1%">Time</th>
<!-- <th width="15%">Venue</th> -->
<!-- <th width="20%">Description</th> -->
<!-- <th width="6%">Status</th> -->
<th width="6%">Take Action</th>
</tr>
<?php if (isset($registered_for) && $registered_for!=false) {?>
<?php foreach($registered_for as $reg_for) { ?>
<tbody>
<tr>
<td><?php echo $reg_for['eventID'] ;?></td>
<td><?php echo $reg_for['title'] ;?></td>
<td><?php echo $reg_for['startDate'] ;?></td>
<td><?php echo $reg_for['time'] ;?></td>
<!-- <td><?php echo $reg_for['venue'] ;?></td> -->
<!-- <td><span class="more"><?php echo $reg_for['description'] ;?></span></td> -->
<td>
<?php echo form_open('stu_dereg_for_cour'); ?>
<input type="text" hidden="true" name="id" value="<?php echo $reg_for['eventID'] ;?>" />
<button type="submit" class="btn btn-success" value="Register" >De-register</button>
<?php echo form_close();?>
</td>
</tr>
</tbody>
<?php } ?>
<?php } ?>
</table>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<link type="text/css" rel="stylesheet" href="<?php echo base_url()?>assets/css/event/event.css">
<link type="text/css" rel="stylesheet" href="<?php echo base_url()?>assets/css/event/event_list.css">
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<div class="col-lg-8 col-sm-offset-2 col-sm-8">
<h1>ADD A COURSE</h1>
<hr>
<?php echo form_open('submit_course'); ?>
<div class="form-group">
<label for="description">Description/Title</label>
<?php echo form_error('description'); ?>
<textarea class="form-control" placeholder="Enter Description" required="true" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label for="venue">Purpose of the course</label>
<?php echo form_error('venue'); ?>
<textarea class="form-control" placeholder="Enter Purpose" required="true" name="purpose"><?php echo set_value('purpose'); ?></textarea>
</div>
<button type="reset" class="btn btn-danger">Reset</button>
<button type="submit" class="btn btn-success pull-right">Save</button>
<?php echo form_close(); ?>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<h1>STUDENT LIST</h1>
<hr>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th width="10%">Fist Name</th>
<th width="10%">Last Name</th>
<th width="10%">Attendance</th>
<th width="10%">Title</th>
<th width="10%">Start Date</th>
<th width="10%">Edit</th>
</tr>
</thead>
<tbody>
<?php if (isset($studAttend)) {?>
<?php foreach($studAttend as $the_stud_attend) { ?>
<tr>
<td><?php echo $the_stud_attend['firstName'] ;?></td>
<td><?php echo $the_stud_attend['lasrName'] ;?></td>
<td><?php echo $the_stud_attend['attendance'] ;?></td>
<td><?php echo $the_stud_attend['title'] ;?></td>
<td><?php echo $the_stud_attend['startDate'] ;?></td>
<td>
<a href="#">Edit <i class="fa fa-pencil" aria-hidden="true"></i></a>
<a href="#">Cancel <i class="fa fa-ban" aria-hidden="true"></i></a>
<a href="#">Email <i class="fa fa-envelope-o" aria-hidden="true"></i></a>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="<?php echo base_url()?>assets/js/event/event.js"></script>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="<?php echo base_url()?>assets/js/google_address/google_address.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&libraries=places&callback=initAutocomplete"
async defer></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script src="<?php echo base_url()?>assets/js/event/event.js"></script>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="https://use.fontawesome.com/91fa1d8264.js"></script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login_model extends CI_Model {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function get_user_student($data)
{
//$email = $data['email'];
$this->db->select('*');
$this->db->where('email', $data);
$this->db->from('student');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->row_array();
/* echo $row['lastLoginDateTime'];
exit();*/
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function get_user_staff($data)
{
//$email = $data['email'];
$this->db->select('*');
$this->db->where('email', $data);
$this->db->from('staff');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->row_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
public function get_stud_pwd($datapwd)
{
$email = $datapwd['email'];
$this->db->select('password');
$this->db->where('email', $email);
$this->db->from('student');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->row_array();
if ($query->num_rows() > 0) {
return $row['password'];;
} else {
return false;
}
}
public function get_staff_pwd($datapwd)
{
//$email = $datapwd['email'];
$this->db->select('password');
$this->db->where('email', $datapwd);
$this->db->from('staff');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->row_array();
if ($query->num_rows() > 0) {
return $row['password'];;
} else {
return false;
}
}
/*
Escaping Queries
----------------
$this->db->escape() This function determines the data type so that it can escape only string data. It also automatically adds single quotes around the data so you don't have to:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
$this->db->escape_str() This function escapes the data passed to it, regardless of type. Most of the time you'll use the above function rather than this one. Use the function like this:
$sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
$this->db->escape_like_str() This method should be used when strings are to be used in LIKE conditions so that LIKE wildcards ('%', '_') in the string are also properly escaped.
$search = '20% raise';
$sql = "SELECT id FROM table WHERE column LIKE '%".$this->db->escape_like_str($search)."%'";*/
/*
UPDATE
------
$this->db->update_string();
This function simplifies the process of writing database updates. It returns a correctly formatted SQL update string. Example:
$data = array('name' => $name, 'email' => $email, 'url' => $url);
$where = "author_id = 1 AND status = 'active'";
$str = $this->db->update_string('table_name', $data, $where);*/
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!-- Contact Section -->
<section class="contact" id="contact">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div id="title-section">
<h1>Contact</h1>
<p></p>
</div>
</div>
</div>
</div>
</section><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!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">
<meta name="description" content="">
<meta name="author" content="">
<title>CTA</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<link href="<?php echo base_url()?>assets/css/scrolling-nav.css" rel="stylesheet">
<script src="https://use.fontawesome.com/91fa1d8264.js"></script>
<link href="<?php echo base_url()?>assets/css/registration/registration.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Search extends CI_Controller {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function index()
{
$this->load->model('search_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->birds_model->get_bird($q);
}
}
}
public function autocomplete_courses_desc (){
$json = [];
exit();
$this->load->database();
if(!empty($this->input->get("q"))){
//$this->db->like('name', $this->input->get("q"));
$query = $this->db->select('description')
->limit(10)
->get('courses');
$json = $query->result();
}
echo json_encode($json);
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="<?php echo base_url()?>assets/js/google_address/google_address.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&libraries=places&callback=initAutocomplete"
async defer></script>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ajax_model extends CI_Model {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function get_course_purpose($id){
$this->db->select('purpose');
$this->db->where('courseID', $id);
$this->db->from('course');
$this->db->limit(1);
$query = $this->db->get();
$row = $query->result_array();
/*print_r($row);
exit();*/
$data = array(
'purpose' => $row[0]['purpose']
);
if ($query->num_rows() > 0) {
return $data;
} else {
return false;
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!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">
<meta name="description" content="">
<meta name="author" content="">
<title>CTA</title>
<script src="https://use.fontawesome.com/91fa1d8264.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap.min.css">\
<link type="text/css" rel="stylesheet" href="<?php echo base_url()?>assets/css/event/event.css">
<link type="text/css" rel="stylesheet" href="<?php echo base_url()?>assets/css/event/event_list.css">
</head>
<body >
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index(){
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('home/header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('home/nav');
/*Body*/
$this->load->view('home/home');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('home/footer');
$this->load->view('footer/end_footer');
}
public function staff_login_form()
{
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('staff/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('staff/login/login');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/login/footer');
$this->load->view('footer/end_footer');
}
public function student_login_form()
{
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('student/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('student/login/login');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('student/login/footer');
$this->load->view('footer/end_footer');
}
public function is_valid_password($password,$dbpassword){
$rotations = 0;
$salt = substr($dbpassword, 0, 64);
$hash = $salt . $password;
for ( $i = 0; $i < $rotations; $i ++ ) {
$hash = hash('sha256', $hash);
}
//Sleep a bit to prevent brute force
time_nanosleep(0, 400000000);
$hash = $salt . $hash;
return $hash == $dbpassword;
}
function encrypt_password($password, $username){
$rotations = 0;
$salt = hash('sha256', uniqid(mt_rand(), true) . "somesalt" . strtolower($username));
$hash = $salt . $password;
for ( $i = 0; $i < $rotations; $i ++ ) {
$hash = hash('sha256', $hash);
}
return $salt . $hash;
}
public function login_student_validation(){
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>');
if ($this->form_validation->run() == FALSE)
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
$this->student_login_form();
}
else{
$datapwd = array('email' =>$this->input->post('email'));
$dbpassword = $this->Login_model->get_stud_pwd($datapwd);
if($this->is_valid_password($this->input->post('password'),$dbpassword)){
$result = $this->Login_model->get_user_student($datapwd ['email']);
if($result==false){
//Sleep a bit to prevent brute force
time_nanosleep(0, 400000000);
$data ['message'] = 'Incorrect Username or Password!';
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('student/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('student/login/login',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('student/login/footer');
$this->load->view('footer/end_footer');
}else{
$data['info'] = $this->Login_model->get_user_student($datapwd ['email']);
$data['message'] = 'Welcome '. $data['info']['firstName'];
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event_for_student();
$data ['all_status'] = $this->Event_model->select_all_event_student($data['info']['studentID']);
/* print_r($data['all_status']);
exit();*/
/*Setting Session data*/
$session_data = array(
'username' => $data['info']['email'],
'id' => $data['info']['studentID']);
$this->session->set_userdata('logged_in', $session_data);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/profile/student_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
else{
//Sleep a bit to prevent brute force
time_nanosleep(0, 400000000);
$data ['message'] = 'Incorrect Username or Password!';
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('student/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('student/login/login',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('student/login/footer');
$this->load->view('footer/end_footer');
}
}
}
public function login_staff_validation(){
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>');
if ($this->form_validation->run() == FALSE)
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
//redirect('home', 'refresh');
$this->student_login_form();
}
else{
$datapwd = array('email' =>$this->input->post('email'));
$dbpassword = $this->Login_model->get_staff_pwd($datapwd['email']);
if($this->is_valid_password($this->input->post('password'),$dbpassword)){
$result = $this->Login_model->get_user_staff($datapwd['email']);
if($result==false){
//Sleep a bit to prevent brute force
time_nanosleep(0, 400000000);
$data ['message'] = 'Incorrect Username or Password!';
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('staff/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('staff/login/login',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/login/footer');
$this->load->view('footer/end_footer');
}else{
$sess_array = array();
$sess_array = array(
'id' => $result['staffID'],
'username' => $result['email']
);
$this->session->set_userdata('logged_in', $sess_array);
$data = array(
'message' => 'Welcome to your home page.',
'info'=>$result);
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('staff/profile/staff_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('staff/shared/staff_nav',$data);
/*Body*/
$this->load->view('staff/profile/staff_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('staff/profile/staff_prof_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
}
else{
//Sleep a bit to prevent brute force
time_nanosleep(0, 400000000);
$data ['message'] = 'Incorrect Username or Password!';
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('staff/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('staff/login/login',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/login/footer');
$this->load->view('footer/end_footer');
}
}
}
// Logout from admin page
public function logout($id) {
// Removing session data
$sess_array = array(
'id' => '',
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
if($id=='s'){
$this->student_login_form();
}else{
$this->staff_login_form();
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>error</title>
</head>
<body>
<div class="container">
<h1>Error</h1>
</div>
<ul>
<li><a href="<?php echo base_url()?>home">Return Home</a></li>
</ul>
</body>
</html><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="sections">
<!-- Intro Section -->
<section class="intro" id="intro">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div id="title-section">
<h1>Notification</h1>
<p></p>
</div>
</div>
</div>
</div>
</section>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css">
<link href="<?php echo base_url()?>assets/css/login/login.css" rel="stylesheet">
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<link href="<?php echo base_url()?>assets/css/profile/staff_profile.css" rel="stylesheet">
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (isset($this->session->userdata['logged_in'])) {
header("location:".site_url()."/login/login_student_validation");
}
?>
<div class="container">
<div style="color: white; font-size: 20px;">
<?php if(isset($message)){; ?>
<?php echo $message; ?>
<?php }; ?>
<?php echo validation_errors(); ?>
</div>
<div id="wrapper">
<div id="login_div">
<h1>Staff Login</h1>
<?php $attributes = array('id' => 'msform', 'class'=>"login-inner"); ?>
<?php echo form_open('log_staf_val', $attributes); ?>
<div class="input-field">
<i class="mdi-social-person-outline prefix"></i>
<input class="validate" name="email" id="email" required="true" type="email" value="<?php echo set_value('email'); ?>">
<label for="email" data-error="wrong" data-success="right" class="center-align">Enter Your Email</label>
</div>
<br>
<br>
<div class="input-field">
<i class="mdi-action-lock-outline prefix"></i>
<input id="password" required="true" name="password" type="<PASSWORD>">
<label for="password"><PASSWORD></label>
</div>
<div class="input-field">
<input type="checkbox" id="remember-me"/>
<label for="remember-me">Remember me</label>
</div>
<div class="input-field">
<button class="btn waves-effect waves-light" type="submit" name="action">Submit</button>
</div>
<p>
<ul>
<li>
<a href="<?php echo site_url('admin_reset');?>" id="forgot">Forgot password?</a><br>
</li>
<li>
<a href="<?php echo site_url('home');?>" id="cancel">Return Home</a>
</li>
</ul>
</p>
<br>
<br>
<?php echo form_close();?>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
}
public function get_course_purpose()
{
$this->load->model('Ajax_model');
$id = $this->input->post('id');
$data['course_desc']= $this->Ajax_model->get_course_purpose($id);
echo json_encode($data);
//echo json_encode($data);
//return $data['course_desc'][0]['purpose'];
//return $data;
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
$id = $this->session->userdata['logged_in']['id']
?>
<div class="container">
<?php if(isset($message)){; ?>
<h1><?php echo $message; ?></h1>
<?php }; ?>
<hr>
<div class="row">
<div class="col-sm-6">
<?php if (isset($info)) {?>
<?php echo 'Last Login:'.' '. $info['lastLoginDateTime'] ;?>
</div>
<div class="col-sm-6">
<!-- <?php echo 'Last Login IP Address:'.' '. $info['lastLoginIP'] ;?>
<?php } ?> -->
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12 col-sm-12">
<h1>Courses</h1>
<hr>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<tr>
<th width="30%">Event Title</th>
<th width="30%"> Completion Date</th>
<th width="40%">Take Action</th>
</tr>
<?php if (isset($all_courses_compl) && $all_courses_compl!=false) {?>
<?php foreach($all_courses_compl as $comp_cour) { ?>
<tbody>
<tr>
<td><?php echo $comp_cour['title'] ;?></td>
<td><?php echo $comp_cour['date_completed'] ;?></td>
<td>
<?php echo form_open('stu_dereg_for_cour'); ?>
<input type="text" hidden="true" name="id" value="<?php echo $comp_cour['eventID'] ;?>" />
<button type="submit" class="btn btn-success" value="Register" ><i class="fa fa-download" aria-hidden="true"></i> Download-Certificate</button>
<?php echo form_close();?>
</td>
</tr>
</tbody>
<?php } ?>
<?php } ?>
</table>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<div class="col-lg-12 col-sm-12">
<h1>LIST OF COURSES</h1>
<hr>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th width="10%">Course ID</th>
<th width="40%">Description</th>
<th width="40%">Purpose</th>
<th width="10%">Edit</th>
</tr>
</thead>
<tbody>
<?php if (isset($all_courses)) {?>
<?php foreach($all_courses->result_array() as $the_courses) { ?>
<tr>
<td><?php echo $the_courses['courseID'] ;?></td>
<td><span class="more"><?php echo $the_courses['description'] ;?></span></td>
<td><span class="more"><?php echo $the_courses['purpose'] ;?></span></td>
<td>
<a href="<?php echo base_url() ;?>index.php/load_course/<?php echo $the_courses['courseID']?>">Edit <i class="fa fa-pencil" aria-hidden="true"></i></a>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!-- About Section -->
<section class="about" id="about">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div id="title-section">
<h1>About</h1>
<p></p>
</div>
</div>
</div>
</section>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Course extends CI_Controller {
public function index()
{
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('home/header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('home/nav');
/*Body*/
$this->load->view('home/intro');
$this->load->view('home/about');
$this->load->view('home/courses');
$this->load->view('home/contact');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('home/footer');
$this->load->view('footer/end_footer');
}
public function courses_form(){
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/courses/courses_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/courses/courses_form');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/courses/courses_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
public function get_all_courses(){
$data ['all_courses'] = $this->Courses_model->select_all_course();
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/courses/courses_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/courses/courses_list',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/courses/courses_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
public function load_one_course($id){
$data ['one_course'] = $this->Courses_model->select_one_course($id);
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/courses/courses_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/courses/courses_details',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/courses/courses_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
public function update_course()
{
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('purpose', 'Purpose', 'required');
if ($this->form_validation->run() === FALSE)
{
$data ['one_course'] = $this->Courses_model->select_one_course($id);
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/courses/courses_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/courses/courses_details',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/courses/courses_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
else
{
$data = array(
'description' =>$this->input->post('description'),
'purpose' =>$this->input->post('purpose'),
'lastModifiedBy' =>'<NAME>');
$id = $this->input->post('courseID');
if($this->Courses_model->update_course($data, $id)){
$data = array (
'path_redirect'=>'view_all_courses',
'message'=>'View List of Course'
);
$this->load->view('success',$data);
}else{
//$data ['all_courses'] = $this->Courses_model->select_all_course();
/*$this->load->view('staff/courses/courses_header');
$this->load->view('staff/shared/staff_nav');
$this->load->view('staff/courses/courses_form',$data);
$this->load->view('staff/courses/courses_footer');*/
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/courses/courses_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/courses/courses_form',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/courses/courses_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
}
}
public function create_course()
{
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('purpose', 'Purpose', 'required');
if ($this->form_validation->run() === FALSE)
{
$data ['all_courses'] = $this->Courses_model->select_all_course();
/*$this->load->view('staff/courses/courses_header');
$this->load->view('staff/shared/staff_nav');
$this->load->view('staff/courses/courses_form',$data);
$this->load->view('staff/courses/courses_footer');*/
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/courses/courses_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/courses/courses_form',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/courses/courses_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('google/google_address_footer');
$this->load->view('footer/end_footer');
}
else
{
$data = array(
'description' =>$this->input->post('description'),
'purpose' =>$this->input->post('purpose'),
'lastModifiedBy' =>'<NAME>');
if($this->Courses_model->insert_course($data)){
$data = array (
'path_redirect'=>'course',
'message'=>'View List of Course'
);
$this->load->view('success',$data);
}else{
/* print_r('no insert');
exit();*/
redirect('/courses');
}
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<h1>EVENT LIST</h1>
<!-- <a href="<?php echo base_url()?>index.php/event/all_ev">Click here to display the next coming events.</a> -->
<hr>
<!-- <ul class="pagination">
<li class="<?php if (isset($Num_sel) && $Num_sel==5) {echo "active"; } else {echo "";}?>"><a href="<?php echo base_url()?>index.php/event/all_ev_tbl/5">5</a></li>
<li class="<?php if (isset($Num_sel) && $Num_sel==10) {echo "active"; } else {echo "";}?>"><a href="<?php echo base_url()?>index.php/event/all_ev_tbl/10">10</a></li>
<li class="<?php if (isset($Num_sel) && $Num_sel==20) {echo "active"; } else {echo "";}?>"><a href="<?php echo base_url()?>index.php/event/all_ev_tbl/20">20</a></li>
<li class="<?php if (isset($Num_sel) && $Num_sel==30) {echo "active"; } else {echo "";}?>"><a href="<?php echo base_url()?>index.php/event/all_ev_tbl/30">30</a></li>
<li class="<?php if (isset($Num_sel) && $Num_sel==40) {echo "active"; } else {echo "";}?>"><a href="<?php echo base_url()?>index.php/event/all_ev_tbl/40">40</a></li>
<li class="<?php if (isset($Num_sel) && $Num_sel==50) {echo "active"; } else {echo "";}?>"><a href="<?php echo base_url()?>index.php/event/all_ev_tbl/50">50</a></li>
</ul> -->
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th width="5%">Event Title</th>
<th width="20%">Description</th>
<th width="10%">Venue</th>
<th width="10%">Start Date</th>
<th width="10%">End Date</th>
<th width="5%">Time</th>
<th width="5%">Edit</th>
</tr>
</thead>
<tbody>
<?php if (isset($all_event)) {?>
<?php foreach($all_event as $the_events) { ?>
<tr>
<td><?php echo $the_events['title'] ;?></td>
<td> <span class="more"><?php echo $the_events['description'] ;?></span></td>
<td><?php echo $the_events['venue'] ;?></td>
<td><?php echo $the_events['startDate'] ;?></td>
<td><?php echo $the_events['endDate'] ;?></td>
<td><?php echo date("g:i a",strtotime($the_events['time']))?></td>
<td>
<a href="<?php echo base_url() ;?>index.php/load_event/<?php echo $the_events['eventID']?>">Edit <i class="fa fa-pencil" aria-hidden="true"></i></a>
<a href="#">Cancel <i class="fa fa-ban" aria-hidden="true"></i></a>
<a href="#">Email <i class="fa fa-envelope-o" aria-hidden="true"></i></a>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
</div>
<footer id="footer">
Made by <a href="http://sict-iis.nmmu.ac.za/cta/"><NAME></a>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="<?php echo base_url()?>assets/js/home/home.js"></script>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="container">
<div class="row">
<div id="form_event" class="col-lg-8 col-sm-offset-2 col-sm-8">
<h1 style="text-align: center;">CREATE AN EVENT</h1>
<hr>
<?php echo form_open('submit_event'); ?>
<div class="form-group">
<label for="title">Title</label>
<?php echo form_error('title'); ?>
<?php if (isset($all_courses)) {?>
<select name="courseID" id="courseID" class="form-control">
<!-- <option selected="selected">Choose A Course</option> -->
<?php foreach($all_courses->result_array() as $the_courses) { ?>
<option value="<?= $the_courses['courseID'] ?>"><?= $the_courses['description'] ?>
</option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="description">Description</label>
<?php echo form_error('description'); ?>
<textarea class="form-control" placeholder="Enter Description" id="description" required="true" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label for="venue">Venue</label>
<?php echo form_error('venue'); ?>
<input type="text" class="form-control" id="autocomplete" required="true" onFocus="geolocate()" name="venue"value="<?php echo set_value('venue'); ?>"/>
</div>
<div class="form-group">
<label for="start_date">Start Date</label>
<?php echo form_error('start_date'); ?>
<input type="date" id="starDate" class="form-control" required="true" name="start_date"value="<?php echo set_value('start_date'); ?>"/>
</div>
<div class="form-group">
<label for="end_date">End Date</label>
<?php echo form_error('end_date'); ?>
<input type="date" id="endDate" class="form-control" required="true" name="end_date"value="<?php echo set_value('end_date'); ?>"/>
</div>
<div class="form-group">
<label for="time">Time</label>
<?php echo form_error('end_date'); ?>
<input type="time" id="time" class="form-control" required="true" name="time" value="<?php echo set_value('time'); ?>"/>
</div>
<button type="reset" class="btn btn-danger">Reset</button>
<button type="submit" class="btn btn-success pull-right">Save</button>
<?php echo form_close(); ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$("#title").autocomplete({
source: "search/index" // path to the get_birds method
});
});
</script>
<script type="text/javascript">
$("#courseID").change(function(){
var id = $('#courseID').val();
//alert(id);
$.ajax({
url:'<?php echo site_url("Ajax/get_course_purpose")?>',
type:'POST',
data:{'id':id},
dataType: 'json',
cache: false,
success:function(data){
//var resdata = course_desc;
//alert(JSON.stringify(resdata));
$.each(data, function(i, val) {
//alert(JSON.stringify(val.purpose));
$("#description").html(val.purpose);
});
//alert(JSON.stringify(course_desc));
//alert(JSON.parse(course_desc));
//$("#description").html(val.purpose);
},error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Something went Wrong!!");
}
});
});
</script><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!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">
<meta name="description" content="">
<meta name="author" content="">
<title>CTA</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
<!-- Website Font style -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<!-- Google Fonts -->
<link href='https://fonts.googleapis.com/css?family=Passion+One' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<title>Recover Password</title>
<link href="<?php echo base_url()?>assets/css/resetpassword/resetpassword.css" rel="stylesheet">
</head>
<body >
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<section class="intro">
<div class="content">
<h1>You can create full screen sections without javascript.</h1>
<p>The height is set to 90vh, that means 90% height.</p>
</div>
</section>
<section class="about">
<div class="content">
<h1>Resize your browser and see how they adapt.</h1>
</div>
</section>
<section class="courses">
<div class="content">
<h1>It's amazing and fast.</h1>
</div>
</section>
<section class="contact">
<div class="content">
<h1>See the <a href="http://caniuse.com/#feat=viewport-units">browser support.</a></h1>
</div>
</section>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reset extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function index()
{
$this->load->view('student/resetpassword/reset_password_header');
$this->load->view('student/resetpassword/reset_password_nav');
$this->load->view('student/resetpassword/reset_password');
$this->load->view('student/resetpassword/reset_password_footer');
}
public function Reset_Password_Student_form()
{
$this->load->view('student/resetpassword/reset_password_header');
$this->load->view('student/resetpassword/reset_password_nav');
$this->load->view('student/resetpassword/reset_password');
$this->load->view('student/resetpassword/reset_password_footer');
}
public function Reset_Password_Staff_form()
{
$this->load->view('staff/resetpassword/reset_password_header');
$this->load->view('staff/resetpassword/reset_password_nav');
$this->load->view('staff/resetpassword/reset_password');
$this->load->view('staff/resetpassword/reset_password_footer');
}
public function Reset_Password_Security_question()
{
$this->form_validation->set_rules('email', 'Email','callback_rolekey_exists','trim|required|valid_email');
if ($this->form_validation->run() == FALSE)
{
$data ['message'] = 'Incorrect email!';
$this->load->view('student/resetpassword/reset_password_header');
$this->load->view('student/resetpassword/reset_password_nav');
$this->load->view('student/resetpassword/reset_password',$data);
$this->load->view('student/resetpassword/reset_password_footer');
}else{
$data ['message'] = 'We are still working on this!!!';
$this->load->view('student/resetpassword/reset_password_header');
$this->load->view('student/resetpassword/reset_password_nav');
$this->load->view('student/resetpassword/reset_password',$data);
$this->load->view('student/resetpassword/reset_password_footer');
}
}
function rolekey_exists($key) {
return $this->Reset_model->mail_exists($key);
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Student_model extends CI_Model {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function insert_student($data)
{
$this->db->insert('student', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
public function register_student_for_course($data)
{
$this->db->insert('event_student', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
public function deregister_student_for_course($data)
{
$this->db->delete('event_student', $data);
//$this->db->insert('event_student', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
public function check_student_exist($data)
{
$this->db->insert('student', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
public function mail_exists($key)
{
$this->db->where('email',$key);
$query = $this->db->get('student');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
public function get_students_attending_courses()
{
$this->db->select('student.firstName, student.lastName, event_student.attendance,event.title,event.startDate');
$this->db->where('student.studentID=event_student.studentID');
$this->db->where('event_student.eventID=event.eventID');
$this->db->from('student,event_student,event');
$query = $this->db->get();
$row = $query->result_array();
/* echo $row['lastLoginDateTime'];
exit();*/
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function check_registered_already ($data_check){
$this->db->select('studentID, eventID');
$this->db->from('event_student');
$this->db->where('eventID=',$data_check['eventID']);
$this->db->where('studentID=',$data_check['studentID']);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
public function select_all_event_student_registered($studentID){
#Create where clause
$this->db->select('eventID');
$this->db->from('event_student');
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->select('*');
$this->db->from('event');
$this->db->where("`eventID` IN ($where_clause)", NULL, FALSE);
$query = $this->db->get();
$row = $query->result_array();
if ($query->num_rows() > 0) {
return $row;
} else {
return false;
}
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Administrator</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li ><a href="<?php echo base_url()?>index.php/dashboard">Dashboard</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="fa fa-calendar-o" aria-hidden="true"></i> Events<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#" title=""><i class="fa fa-plus" aria-hidden="true"></i> Create Event</a></li>
<li><a href="#" title=""><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Update Event</a></li>
<li><a href="<?php echo base_url()?>index.php/event" title=""><i class="fa fa-street-view" aria-hidden="true"></i>View All Events</a></li>
</ul>
</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="fa fa-calendar-o" aria-hidden="true"></i> Courses<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#" title=""><i class="fa fa-plus" aria-hidden="true"></i> Add Courses</a></li>
<li><a href="#" title=""><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Update Courses</a></li>
<li><a href="<?php echo base_url()?>index.php/courses" title=""><i class="fa fa-street-view" aria-hidden="true"></i>View All Courses</a></li>
</ul>
</li>
<li><a href="#">Student</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<!-- <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li> -->
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="fa fa-cog" aria-hidden="true"></i> Settings
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#" title=""><i class="fa fa-user" aria-hidden="true"></i> Profile</a></li>
<li><a href="#" title=""><i class="fa fa-lock" aria-hidden="true"></i> Staff Settings</a></li>
<li><a href="<?php echo site_url('login/prolog')?>" title="" id="canc_but" data-toggle="modal" data-target=".bd-example-modal-sm" >Logout</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Logout Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to Logout?
</div>
<div class="modal-footer">
<a href="<?php echo site_url('home')?>" class="btn btn-success" role="button">Yes</a>
<button type="button" class="btn btn-danger" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$data = array(
'message' => 'Welcome back');
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/profile/staff_prof_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav',$data);
/*Body*/
$this->load->view('staff/profile/staff_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/profile/staff_prof_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
public function dashboard()
{
$data = array(
'message' => 'Welcome back');
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('staff/profile/staff_prof_header');
$this->load->view('header/end_header');
/*Nav bar*/
$this->load->view('staff/shared/staff_nav');
/*Body*/
$this->load->view('staff/profile/staff_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('staff/profile/staff_prof_footer');
$this->load->view('google/google_address_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!--
If you want to change #bootstrap-touch-slider id then you have to change Carousel-indicators and Carousel-Control #bootstrap-touch-slider slide as well
Slide effect: slide, fade
Text Align: slide_style_center, slide_style_left, slide_style_right
Add Text Animation: https://daneden.github.io/animate.css/
-->
<div id="bootstrap-touch-slider" class="carousel bs-slider fade control-round indicators-line" data-ride="carousel" data-pause="hover" data-interval="5000" >
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#bootstrap-touch-slider" data-slide-to="0" class="active"></li>
<li data-target="#bootstrap-touch-slider" data-slide-to="1"></li>
<li data-target="#bootstrap-touch-slider" data-slide-to="2"></li>
</ol>
<!-- Wrapper For Slides -->
<div class="carousel-inner" role="listbox">
<!-- Third Slide -->
<div class="item active">
<!-- Slide Background -->
<img src="<?php echo base_url()?>assets/img/children.jpg" alt="Bootstrap Touch Slider" class="slide-image"/>
<div class="bs-slider-overlay"></div>
<div class="container">
<div class="row">
<!-- Slide Text Layer -->
<div class="slide-text slide_style_left">
<h1 data-animation="animated zoomInRight">FAMHEALTH</h1>
<p data-animation="animated fadeInLeft">Education is a powerful tool.</p>
<a href="#" class="btn btn-default" data-animation="animated fadeInLeft">Our Courses</a>
<a href="#" class="btn btn-primary" data-animation="animated fadeInRight">The Students</a>
</div>
</div>
</div>
</div>
<!-- End of Slide -->
<!-- Second Slide -->
<div class="item">
<!-- Slide Background -->
<img src="<?php echo base_url()?>assets/img/courses.jpg" alt="Bootstrap Touch Slider" class="slide-image"/>
<div class="bs-slider-overlay"></div>
<!-- Slide Text Layer -->
<div class="slide-text slide_style_center">
<h1 data-animation="animated flipInX">FAMHEALTH</h1>
<p data-animation="animated lightSpeedIn">Make the world a better place.</p>
<a href="#" class="btn btn-default" data-animation="animated fadeInUp">Our Awards</a>
<a href="#" class="btn btn-primary" data-animation="animated fadeInDown">Our Events</a>
</div>
</div>
<!-- End of Slide -->
<!-- Third Slide -->
<div class="item">
<!-- Slide Background -->
<img src="<?php echo base_url()?>assets/img/nature.jpg" alt="Bootstrap Touch Slider" class="slide-image"/>
<div class="bs-slider-overlay"></div>
<!-- Slide Text Layer -->
<div class="slide-text slide_style_right">
<h1 data-animation="animated zoomInLeft">FAMHEALTH</h1>
<p data-animation="animated fadeInRight">Changes lives today for a better tomorrow.</p>
<a href="#" class="btn btn-default" data-animation="animated fadeInLeft">Who Are We?</a>
<a href="#" class="btn btn-primary" data-animation="animated fadeInRight">What We do</a>
</div>
</div>
<!-- End of Slide -->
</div><!-- End of Wrapper For Slides -->
<!-- Left Control -->
<a class="left carousel-control" href="#bootstrap-touch-slider" role="button" data-slide="prev">
<span class="fa fa-angle-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<!-- Right Control -->
<a class="right carousel-control" href="#bootstrap-touch-slider" role="button" data-slide="next">
<span class="fa fa-angle-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div> <!-- End bootstrap-touch-slider Slider -->
<div style="text-align: center;margin-top: 150px; margin-bottom:100px">
<h3>WHO ARE WE?</h3>
</div>
<div style="text-align: center;margin-top: 150px; margin-bottom:100px">
| <a href="#" > CTA sytem </a> |
</div>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Courses_model extends CI_Model {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function insert_course($data)
{
$this->db->insert('course', $data);
if($this->db->affected_rows()){
return true;
}else{
return false;
}
}
public function update_course($data,$id)
{
$this->db->where('courseID', $id);
$this->db->update('course', $data);
if($this->db->affected_rows()){
return true;
}else{
return false;
}
}
public function select_all_course(){
$this->db->select('*');
$this->db->from('course');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_all_event_by_num($Num_sel){
$this->db->select('*');
$this->db->where('startDate >', date("Y-m-d"));
$this->db->from('event');
$this->db->order_by("startDate", "asc");
$this->db->limit($Num_sel);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_stud_event(){
$this->db->select('*');
$this->db->where('studentID', $id);
$this->db->from('event');
$this->db->order_by("startDate", "asc");
$this->db->limit(3);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_next_five_event(){
$this->db->select('*');
$this->db->where('startDate >', date("Y-m-d"));
$this->db->from('event');
$this->db->order_by("startDate", "asc");
$this->db->limit(3);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
public function select_one_course($id){
//$query = $this->db->query("SELECT * FROM event WHERE startDate>".date('Y-m-d'));
$this->db->select('*');
$this->db->where('courseID', $id);
$this->db->from('course');
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query;
} else {
return false;
}
}
}<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<script src="https://use.fontawesome.com/91fa1d8264.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Load Home cascading style sheet -->
<link href="<?php echo base_url() ?>assets/css/home/home.css" rel="stylesheet">
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!-- Services Section -->
<section class="courses" id="courses">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div id="title-section">
<h1>Courses</h1>
<p></p>
</div>
</div>
</div>
</div>
</section>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css" rel="stylesheet"><file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Student extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('home/header');
$this->load->view('home/nav');
$this->load->view('home/home');
$this->load->view('home/footer');
}
public function record_student_attendance()
{
/*$this->form_validation->set_rules('firstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('dateOfBirth', 'Date Of Birth', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|xss_clean');*/
$result ['studAttend'] = $this->Student_model->get_students_attending_courses();
print_r($result);
//exit();
if($result==true){
$this->load->view('staff/students/students_header');
$this->load->view('staff/students/students_nav',$result);
$this->load->view('staff/students/student_attendance',$result);
$this->load->view('staff/students/students_footer');
}else{
$data ['link'] = "<a style='color:white;' href='".site_url()."/login/log1'>Take me to the login Page</a>";
}
}
public function view_all_event_student_can_register_for()
{
if(isset($this->session->userdata['logged_in'])){
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Welcome '. $data['info']['firstName'];
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event_for_student();
$data ['all_status'] = $this->Event_model->select_all_event_student($data['info']['studentID']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/profile/student_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
public function view_event_student_registered_for()
{
if(isset($this->session->userdata['logged_in'])){
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Hello '. $data['info']['firstName'].'! Below are the courses you registered for.';
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['registered_for'] = $this->Event_model->select_all_event_student_registered($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/event/registered_for',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
public function list_of_event_student_can_deregister_from(){
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Hello '. $data['info']['firstName'].'! Below are the courses you registered for.';
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['registered_for'] = $this->Event_model->select_all_event_student_registered($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/event/registered_for',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
public function deregister_student_for_course()
{
/*print_r('call deregister_student_for_course');
exit();*/
/*First Check if session exist and if not redirect to student loggin*/
if(isset($this->session->userdata['logged_in'])){
$this->form_validation->set_rules('id', 'Course ID', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) //Beginning of #region
{
print_r('form validation is false foe deregistration');
exit();
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Hello '. $data['info']['firstName'].'! Below are the courses you registered for.';
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['registered_for'] = $this->Event_model->select_all_event_student_registered($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/event/registered_for',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}else{
/* print_r('form validation is true for deregistration');
exit();*/
$data_dergister = array(
'eventID' =>$this->input->post('id'),
'completed' => false);
$data_check = array(
'eventID' =>$this->input->post('id'),
'studentID' =>$this->session->userdata['logged_in']['id']);
$registered = $this->Student_model->check_registered_already ($data_check);
/*print_r($registered);
exit();*/
if($registered==true){
/* print_r('changing status from registered to unregistered');
exit();*/
$result = $this->Student_model->deregister_student_for_course($data_dergister);
if($result==true){
/* print_r('student deregistered succesfully');
exit();*/
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Hello '. $data['info']['firstName'].'! Below are the courses you registered for.';
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['registered_for'] = $this->Event_model->select_all_event_student_unregistered($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/event/registered_for',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}else{
/*To be added */
}
}else{
/* print_r('sudent is not registered for any course');
exit();*/
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Hello '. $data['info']['firstName'].'! Below are the courses you registered for.';
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['registered_for'] = $this->Event_model->select_all_event_student_registered($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/event/registered_for',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
}else{
/*Here we redirect user to login page if session doesnt exit*/
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('student/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('student/login/login');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('student/login/footer');
$this->load->view('footer/end_footer');
}
}
public function view_all_event_student_completed(){
if(isset($this->session->userdata['logged_in'])){
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Hello '. $data['info']['firstName'].'! Below are the courses you successfully completed.';
//$data ['all_event'] = $this->Event_model->select_all_event();
$data ['all_courses_compl'] = $this->Event_model->select_all_event_student_completed($this->session->userdata['logged_in']['id']);
print_r($data['all_courses_compl']);
exit();
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/event/completed_courses',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
public function register_student_for_course()
{
/*First Check if session exist and if not redirect to student loggin*/
if(isset($this->session->userdata['logged_in'])){
$this->form_validation->set_rules('id', 'Course ID', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) //Beginning of #region
{
$data = array(
'email' =>$this->session->userdata['logged_in']['username']);
$data['info'] = $this->Login_model->get_user_student($data);
$data['message'] = 'Sorry '. $data['info']['firstName'].' Something went wrong Please select a course again!';
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['all_status'] = $this->Event_model->select_all_event_student($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/profile/student_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}else{
$data = array(
'eventID' =>$this->input->post('id'),
'studentID' =>$this->session->userdata['logged_in']['id'],
'attendance' =>'0',
'performance' =>'0',
'comment' =>'None',
'status' =>'Registered');
$data_check = array(
'eventID' =>$this->input->post('id'),
'studentID' =>$this->session->userdata['logged_in']['id']);
/*print_r($data_check);
exit();*/
$registered = $this->Student_model->check_registered_already ($data_check);
if($registered==false){
$result = $this->Student_model->register_student_for_course($data);
if($result==true){
$email =$this->session->userdata['logged_in']['username'];
$data['info'] = $this->Login_model->get_user_student($email);
$data['message'] = 'Welcome '. $data['info']['firstName'];
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event_for_student();
$data ['all_status'] = $this->Event_model->select_all_event_student($data['info']['studentID']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/profile/student_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}else{
/*To be added */
}
}else{
$data['info'] = $this->Login_model->get_user_student($this->session->userdata['logged_in']['username']);
$data['message'] = 'Welcome home '. $data['info']['firstName'];
//$data ['all_courses'] = $this->Event_model->select_all_courses();
$data ['all_event'] = $this->Event_model->select_all_event();
$data ['all_status'] = $this->Event_model->select_all_event_student($this->session->userdata['logged_in']['id']);
/*Header*/
$this->load->view('header/start_header');
//$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('table_bootstrap/data_table_header');
$this->load->view('student/profile/student_prof_header');
$this->load->view('header/end_header');
/*Nav Bar*/
$this->load->view('student/profile/student_prof_nav',$data);
/*Body*/
$this->load->view('student/profile/student_profile',$data);
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
//$this->load->view('student/profile/student_prof_footer');
$this->load->view('table_bootstrap/data_table_footer');
$this->load->view('footer/end_footer');
}
}
}else{
/*Here we redirect user to login page if session doesnt exit*/
/*Header*/
$this->load->view('header/start_header');
$this->load->view('bootstrap/bootstrap_header');
$this->load->view('font_awesome/font_awesome');
$this->load->view('student/login/header');
$this->load->view('header/end_header');
/*Body*/
$this->load->view('student/login/login');
/*Footer*/
$this->load->view('bootstrap/bootstrap_footer');
$this->load->view('student/login/footer');
$this->load->view('footer/end_footer');
}
}
public function student_reg_form()
{
$this->load->view('student/registration/header');
$this->load->view('student/registration/registration');
$this->load->view('student/registration/footer');
}
private function edit_profile()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['email'] = $session_data['username'];
$this->load->view('student/profile/student_prof_header');
$this->load->view('student/profile/student_prof_nav',$data);
$this->load->view('student/profile/student_edit_profile',$data);
$this->load->view('student/profile/student_prof_footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('login', 'refresh');
}
function encrypt_password($password, $username){
$rotations = 0;
$salt = hash('sha256', uniqid(mt_rand(), true) . "somesalt" . strtolower($username));
$hash = $salt . $password;
for ( $i = 0; $i < $rotations; $i ++ ) {
$hash = hash('sha256', $hash);
}
return $salt . $hash;
}
public function submit_reg()
{
$this->form_validation->set_rules('firstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('dateOfBirth', 'Date Of Birth', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|xss_clean');
$this->form_validation->set_rules('addressLine1', 'Address Line 1', 'trim|required|xss_clean');
$this->form_validation->set_rules('addressLine2', 'Address Line 2');
$this->form_validation->set_rules('street_number', 'street_number');
$this->form_validation->set_rules('route', 'Route');
$this->form_validation->set_rules('postalCode', 'Postal Code');
$this->form_validation->set_rules('city', 'City');
$this->form_validation->set_rules('province', 'Province');
$this->form_validation->set_rules('country', 'Country');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', '<PASSWORD>', '<PASSWORD>');
$this->form_validation->set_rules('passwordconfirm', '<PASSWORD>', 'required|matches[password]');
if ($this->form_validation->run() == FALSE) //Beginning of #region
{
$this->load->view('student/registration/header');
$this->load->view('student/registration/registration');
$this->load->view('student/registration/footer');
}else{
$addressLine2 = $this->input->post('addressLine2');
if($addressLine2 ==null)
$addressLine2='None';
$password = $this->encrypt_password($this->input->post('password'),$this->input->post('email'));
$data = array(
'firstName' =>$this->input->post('firstName'),
'lastName' =>$this->input->post('lastName'),
'dateOfBirth' =>$this->input->post('dateOfBirth'),
'phone' =>$this->input->post('phone'),
'addressLine1' =>$this->input->post('addressLine1'),
'addressLine2' =>$addressLine2,
'street_number' =>$this->input->post('street_number'),
'postalCode' =>$this->input->post('postalCode'),
'city' =>$this->input->post('city'),
'province' =>$this->input->post('province'),
'country' =>$this->input->post('country'),
'email' =>$this->input->post('email'),
'password' =>$<PASSWORD>,
'lastLoginDateTime' => date("Y-m-d h:i:sa"),
'lastLoginIP' =>$this->input->ip_address(),
'route' =>$this->input->post('route') );
$result = $this->Student_model->insert_student($data);
if($result==true){
$data ['link'] = "<a style='color:white;' href='".site_url()."/login/log1'>Take me to the login Page</a>";
$this->load->view('student/registration/header');
$this->load->view('formsuccess/formsuccess',$data);
$this->load->view('student/registration/footer');
}else{
$data ['link'] = "<a style='color:white;' href='".site_url()."/login/log1'>Take me to the login Page</a>";
}
}//End of #region
}
private function rolekey_exists($key) {
return $this->Student_model->mail_exists($key);
}
}
|
d9a1edb1d0549f89db25cd04204a50229366933f
|
[
"PHP"
] | 58
|
PHP
|
charli9230/cta
|
6602f7506b5bb809fe25886f56d4f5ee0617c331
|
692980bd774f197654fca0e0f80fe2f4a407e6ce
|
refs/heads/master
|
<repo_name>VolodymyrBor/tic-tac-toe<file_sep>/tic-tac-toe.py
from math import inf
import typing as typ
from terminaltables import AsciiTable
MAX_DEPTH = inf
best_row = -1
best_col = -1
count = 0
def board_element(cell: int) -> str:
if cell == 0:
return ' '
if cell == -1:
return 'X'
if cell == 1:
return 'O'
def init_board(board_size: int) -> typ.List[typ.List[int]]:
return [[0 for _ in range(board_size)] for _ in range(board_size)]
def print_board(board: typ.List[typ.List[int]]) -> None:
board = [[board_element(cell) for cell in row] for row in board]
table = AsciiTable(board)
table.inner_row_border = True
print(table.table)
def check_winner(board: typ.List[typ.List[int]]) -> int:
board_size = len(board)
if board[0][0] and all(el == board[0][0] for el in [board[i][i] for i in range(board_size)]):
return board[0][0]
if board[-1][0] and all(el == board[-1][0] for el in [board[i][-1 - i] for i in range(board_size)]):
return board[board_size - 1][0]
for row in board:
if row[0] and all(el == row[0] for el in row):
return row[0]
for i in range(board_size):
col = [board[j][i] for j in range(board_size)]
if col[0] and all(el == col[0] for el in col):
return col[0]
return 0
def minimax(board: typ.List[typ.List[int]], player: int, my_move: bool, depth: int, alpha, beta) -> int:
global count
count += 1
if depth > MAX_DEPTH:
return 0
winner = check_winner(board)
if winner != 0:
return winner
global best_col, best_row
score = alpha if my_move else beta
move_row, move_col = -1, -1
for i, row in enumerate(board):
for j, cell in enumerate(row):
if cell == 0:
board[i][j] = player
if my_move:
current_score = minimax(board, -player, not my_move, depth + 1, score, beta)
board[i][j] = 0
if current_score > score:
score = current_score
move_row, move_col = i, j
if score >= beta:
best_row = move_row
best_col = move_col
return score
else:
current_score = minimax(board, -player, not my_move, depth + 1, alpha, score)
board[i][j] = 0
if current_score < score:
score = current_score
move_row, move_col = i, j
if score <= alpha:
best_row = move_row
best_col = move_col
return score
if move_row == - 1:
return 0
best_row = move_row
best_col = move_col
return score
def main():
global MAX_DEPTH
total_moves = 0
row, col = -1, -1
while True:
try:
board_size = int(input('Board size: '))
break
except ValueError:
pass
max_depth = input('Max depth(inf or int): ')
try:
MAX_DEPTH = int(max_depth)
except (OverflowError, ValueError):
MAX_DEPTH = inf
if input('Chose the side(O or X) ') == 'O':
machine_player = -1
current_player = -1
my_move = False
else:
machine_player = 1
current_player = -1
my_move = True
board = init_board(board_size)
while True:
print_board(board)
winner = check_winner(board)
if winner:
print(f"WIN FOR {'O' if winner is 1 else 'X'} !!!!")
break
if total_moves == board_size**2:
print("GAME IS OVER")
break
if current_player == machine_player:
score = minimax(board, current_player, my_move, 0, -inf, inf)
if score != -inf:
row, col = best_row, best_col
else:
while True:
try:
row, col = map(lambda x: int(x) - 1, input('row, col = ').split())
break
except ValueError:
pass
if 0 <= row < board_size and 0 <= col < board_size:
if board[row][col] == 0:
board[row][col] = current_player
current_player *= -1
total_moves += 1
if __name__ == '__main__':
main()
print(f'Total number of minimax calls: {count}')
|
b9ca48aeae1b566f573ec9eaf9e6c031db497f20
|
[
"Python"
] | 1
|
Python
|
VolodymyrBor/tic-tac-toe
|
aff9da0c99aa8b21faae4492c303e33f19ae30f3
|
5ecc5cd9c0069aa128d616f4cef404dae4a10c84
|
refs/heads/master
|
<file_sep>package domain;
public class Contact {
private Integer id;
private Person person;
private Type type;
private String value;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}<file_sep>/* полное удаление прежней базы данных */
DROP DATABASE IF EXISTS `persons_db`;
/* создание новой базы данных */
CREATE DATABASE `persons_db` DEFAULT CHARACTER SET utf8;
/* использование в качестве текущей только что созданной базы данных */
USE `persons_db`;
/* создание в базе данных новой таблицы */
CREATE TABLE `person` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(255) NOT NULL,
`middle_name` VARCHAR(255) NOT NULL,
`last_name` VARCHAR(255) NOT NULL,
`height` DOUBLE NOT NULL,
`weight` DOUBLE NOT NULL,
`is_citizen` BOOLEAN NOT NULL,
`sex` TINYINT NOT NULL, /* 0 - male; 1 - female */
`birthday` DATE NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARACTER SET utf8;
CREATE TABLE `type` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARACTER SET utf8;
CREATE TABLE `contact` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`person_id` INTEGER NOT NULL,
`type_id` INTEGER NOT NULL,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`person_id`) REFERENCES `person` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE,
FOREIGN KEY (`type_id`) REFERENCES `type` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT
) ENGINE=INNODB DEFAULT CHARACTER SET utf8;
CREATE TABLE `user` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`login` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARACTER SET utf8;
/* вставка нескольких значений в таблицу */
INSERT INTO `person`
(`id`, `first_name`, `middle_name`, `last_name`, `height`, `weight`, `is_citizen`, `sex`, `birthday`)
VALUES
(1, "Иван", "Иванович", "Иванов", 173.5, 85.4, TRUE, 0, "1996-04-20"),
(2, "Пётр", "Петрович", "Петров", 189.0, 79.5, FALSE, 0, "1976-07-24"),
(3, "Сидор", "Сидорович", "Сидоров", 168.0, 97.8, TRUE, 0, "1959-02-12"),
(4, "Василий", "Васильевич", "Васильев", 195.5, 103.2, TRUE, 0, "1972-04-28"),
(5, "Вера", "Петровна", "Иванова", 185.0, 88.4, TRUE, 1, "1952-05-08"),
(6, "Надежда", "Ивановна", "Петрова", 177.5, 76.9, FALSE, 1, "1972-04-01"),
(7, "Любовь", "Петровна", "Сидорова", 164.0, 79.9, TRUE, 1, "1981-07-31"),
(8, "Любовь", "Сидоровна", "Иванова", 157.0, 67.2, TRUE, 1, "2007-11-21"),
(9, "Надежда", "Сидоровна", "Петрова", 171.5, 73.5, FALSE, 1, "1963-11-23"),
(10, "Вера", "Ивановна", "Сидорова", 162.0, 56.1, TRUE, 1, "1980-04-14");
INSERT INTO `type`
(`id`, `name`)
VALUES
(1, "телефон"),
(2, "e-mail");
INSERT INTO `contact`
(`id`, `person_id`, `type_id`, `value`)
VALUES
(1, 1, 1, "+375-29-123-45-67"),
(2, 1, 2, "<EMAIL>"),
(3, 2, 1, "+375-33-987-65-43");
INSERT INTO `user`
(`login`, `password`)
VALUES
("root", "root");<file_sep>package web;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import db.PersonStorage;
import db.StorageCreator;
import domain.Person;
import domain.Sex;
public class PersonSaveServlet extends HttpServlet {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy");
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
Person person = buildPerson(req);
if(person != null) {
StorageCreator storageCreator = null;
try {
storageCreator = new StorageCreator();
PersonStorage s = storageCreator.newPersonStorage();
s.save(person);
} catch(SQLException e) {
throw new ServletException(e);
} finally {
if(storageCreator != null) {
storageCreator.close();
}
}
}
resp.sendRedirect(req.getContextPath() + "/index.html");
}
private Person buildPerson(HttpServletRequest req) {
try {
Person person = new Person();
try {
person.setId(Integer.parseInt(req.getParameter("id")));
} catch(NumberFormatException e) {}
person.setFirstName(req.getParameter("first-name"));
person.setMiddleName(req.getParameter("middle-name"));
person.setLastName(req.getParameter("last-name"));
if(person.getFirstName() == null || person.getMiddleName() == null || person.getLastName() == null) {
throw new NullPointerException();
}
person.setHeight(Double.parseDouble(req.getParameter("height")));
person.setWeight(Double.parseDouble(req.getParameter("weight")));
person.setCitizen(req.getParameter("citizen") != null);
person.setSex(Sex.values()[Integer.parseInt(req.getParameter("sex"))]);
person.setBirthday(DATE_FORMAT.parse(req.getParameter("birthday")));
return person;
} catch(NumberFormatException | ArrayIndexOutOfBoundsException | NullPointerException | ParseException e) {
return null;
}
}
}<file_sep>package db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import domain.Type;
public class TypeStorage extends BasicStorage {
public List<Type> readAll() throws SQLException {
String sql = "SELECT `id`, `name` FROM `type`";
Connection c = getConnection();
Statement s = null;
ResultSet r = null;
try {
s = c.createStatement();
r = s.executeQuery(sql);
List<Type> types = new ArrayList<>();
while(r.next()) {
Type type = new Type();
type.setId(r.getInt("id"));
type.setName(r.getString("name"));
types.add(type);
}
c.commit();
return types;
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { r.close(); } catch(NullPointerException | SQLException e) {}
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public Type readById(Integer id) throws SQLException {
String sql = "SELECT `name` FROM `type` WHERE `id` = ?";
Connection c = getConnection();
PreparedStatement s = null;
ResultSet r = null;
try {
s = c.prepareStatement(sql);
s.setInt(1, id);
r = s.executeQuery();
Type type = null;
if(r.next()) {
type = new Type();
type.setId(id);
type.setName(r.getString("name"));
}
c.commit();
return type;
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { r.close(); } catch(NullPointerException | SQLException e) {}
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public Integer create(Type type) throws SQLException {
String sql = "INSERT INTO `type`(`name`) VALUES (?)";
Connection c = getConnection();
PreparedStatement s = null;
ResultSet r = null;
try {
s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
s.setString(1, type.getName());
s.executeUpdate();
r = s.getGeneratedKeys();
Integer id = null;
if(r.next()) {
id = r.getInt(1);
}
c.commit();
return id;
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { r.close(); } catch(NullPointerException | SQLException e) {}
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public void update(Type type) throws SQLException {
String sql = "UPDATE `type` SET `name` = ? WHERE `id` = ?";
Connection c = getConnection();
PreparedStatement s = null;
try {
s = c.prepareStatement(sql);
s.setString(1, type.getName());
s.setInt(2, type.getId());
s.executeUpdate();
c.commit();
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public void save(Type type) throws SQLException {
if(type.getId() != null) {
update(type);
} else {
Integer id = create(type);
type.setId(id);
}
}
public void delete(Integer id) throws SQLException {
String sql = "DELETE FROM `type` WHERE `id` = ?";
Connection c = getConnection();
PreparedStatement s = null;
try {
s = c.prepareStatement(sql);
s.setInt(1, id);
s.executeUpdate();
c.commit();
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
}<file_sep>package db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import domain.Contact;
import domain.Person;
import domain.Sex;
import domain.Type;
public class PersonStorage extends BasicStorage {
private ContactStorage contactStorage;
private TypeStorage typeStorage;
public void setContactStorage(ContactStorage contactStorage) {
this.contactStorage = contactStorage;
}
public void setTypeStorage(TypeStorage typeStrorage) {
this.typeStorage = typeStrorage;
}
public List<Person> readAll() throws SQLException {
String sql = "SELECT `id`, `first_name`, `middle_name`, `last_name`, `height`, `weight`, `is_citizen`, `sex`, `birthday` FROM `person`";
Connection c = getConnection();
Statement s = null;
ResultSet r = null;
try {
s = c.createStatement();
r = s.executeQuery(sql);
List<Person> persons = new ArrayList<>();
while(r.next()) {
Person person = new Person();
person.setId(r.getInt("id"));
person.setFirstName(r.getString("first_name"));
person.setMiddleName(r.getString("middle_name"));
person.setLastName(r.getString("last_name"));
person.setHeight(r.getDouble("height"));
person.setWeight(r.getDouble("weight"));
person.setCitizen(r.getBoolean("is_citizen"));
person.setSex(Sex.values()[r.getInt("sex")]);
person.setBirthday(new java.util.Date(r.getDate("birthday").getTime()));
persons.add(person);
}
c.commit();
return persons;
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { r.close(); } catch(NullPointerException | SQLException e) {}
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public Person readById(Integer id) throws SQLException {
String sql = "SELECT `first_name`, `middle_name`, `last_name`, `height`, `weight`, `is_citizen`, `sex`, `birthday` FROM `person` WHERE `id` = ?";
Connection c = getConnection();
PreparedStatement s = null;
ResultSet r = null;
try {
s = c.prepareStatement(sql);
s.setInt(1, id);
r = s.executeQuery();
Person person = null;
if(r.next()) {
person = new Person();
person.setId(id);
person.setFirstName(r.getString("first_name"));
person.setMiddleName(r.getString("middle_name"));
person.setLastName(r.getString("last_name"));
person.setHeight(r.getDouble("height"));
person.setWeight(r.getDouble("weight"));
person.setCitizen(r.getBoolean("is_citizen"));
person.setSex(Sex.values()[r.getInt("sex")]);
person.setBirthday(new java.util.Date(r.getDate("birthday").getTime()));
}
c.commit();
return person;
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { r.close(); } catch(NullPointerException | SQLException e) {}
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public Person findById(Integer id) throws SQLException {
Person person = readById(id);
if(person != null) {
List<Contact> contacts = contactStorage.readByPersonId(id);
person.setContacts(contacts);
for(Contact contact : contacts) {
contact.setPerson(person);
Type type = typeStorage.readById(contact.getType().getId());
contact.setType(type);
}
}
return person;
}
public Integer create(Person person) throws SQLException {
String sql = "INSERT INTO `person`(`first_name`, `middle_name`, `last_name`, `height`, `weight`, `is_citizen`, `sex`, `birthday`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
Connection c = getConnection();
PreparedStatement s = null;
ResultSet r = null;
try {
s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
s.setString(1, person.getFirstName());
s.setString(2, person.getMiddleName());
s.setString(3, person.getLastName());
s.setDouble(4, person.getHeight());
s.setDouble(5, person.getWeight());
s.setBoolean(6, person.isCitizen());
s.setInt(7, person.getSex().ordinal());
s.setDate(8, new java.sql.Date(person.getBirthday().getTime()));
s.executeUpdate();
r = s.getGeneratedKeys();
Integer id = null;
if(r.next()) {
id = r.getInt(1);
}
c.commit();
return id;
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { r.close(); } catch(NullPointerException | SQLException e) {}
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public void update(Person person) throws SQLException {
String sql = "UPDATE `person` SET `first_name` = ?, `middle_name` = ?, `last_name` = ?, `height` = ?, `weight` = ?, `is_citizen` = ?, `sex` = ?, `birthday` = ? WHERE `id` = ?";
Connection c = getConnection();
PreparedStatement s = null;
try {
s = c.prepareStatement(sql);
s.setString(1, person.getFirstName());
s.setString(2, person.getMiddleName());
s.setString(3, person.getLastName());
s.setDouble(4, person.getHeight());
s.setDouble(5, person.getWeight());
s.setBoolean(6, person.isCitizen());
s.setInt(7, person.getSex().ordinal());
s.setDate(8, new java.sql.Date(person.getBirthday().getTime()));
s.setInt(9, person.getId());
s.executeUpdate();
c.commit();
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
public void save(Person person) throws SQLException {
if(person.getId() != null) {
update(person);
} else {
Integer id = create(person);
person.setId(id);
}
}
public void delete(Integer id) throws SQLException {
String sql = "DELETE FROM `person` WHERE `id` = ?";
Connection c = getConnection();
PreparedStatement s = null;
try {
s = c.prepareStatement(sql);
s.setInt(1, id);
s.executeUpdate();
c.commit();
} catch(SQLException e) {
try { c.rollback(); } catch(SQLException e1) {}
throw e;
} finally {
try { s.close(); } catch(NullPointerException | SQLException e) {}
}
}
}<file_sep>package db;
import java.sql.Connection;
import java.sql.SQLException;
public class StorageCreator {
private Connection connection;
private PersonStorage personStorage;
private TypeStorage typeStorage;
private ContactStorage contactStorage;
private UserStorage userStorage;
public StorageCreator() throws SQLException {
connection = Connector.getConnection();
}
public PersonStorage newPersonStorage() {
if(personStorage == null) {
personStorage = new PersonStorage();
personStorage.setConnection(connection);
personStorage.setContactStorage(newContactStorage());
personStorage.setTypeStorage(newTypeStorage());
}
return personStorage;
}
public TypeStorage newTypeStorage() {
if(typeStorage == null) {
typeStorage = new TypeStorage();
typeStorage.setConnection(connection);
}
return typeStorage;
}
public ContactStorage newContactStorage() {
if(contactStorage == null) {
contactStorage = new ContactStorage();
contactStorage.setConnection(connection);
contactStorage.setPersonStorage(newPersonStorage());
contactStorage.setTypeStorage(newTypeStorage());
}
return contactStorage;
}
public UserStorage newUserStorage() {
if(userStorage == null) {
userStorage = new UserStorage();
userStorage.setConnection(connection);
}
return userStorage;
}
public void close() {
try { connection.close(); } catch(SQLException e) {}
}
}<file_sep>package web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import db.ContactStorage;
import db.PersonStorage;
import db.StorageCreator;
import db.TypeStorage;
import domain.Contact;
import domain.Person;
import domain.Type;
public class ContactEditServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StorageCreator storageCreator = null;
try {
storageCreator = new StorageCreator();
TypeStorage ts = storageCreator.newTypeStorage();
List<Type> types = ts.readAll();
req.setAttribute("types", types);
Integer id = null;
try {
id = Integer.parseInt(req.getParameter("id"));
} catch(NumberFormatException e) {}
if(id != null) {
ContactStorage cs = storageCreator.newContactStorage();
Contact contact = cs.findById(id);
req.setAttribute("contact", contact);
} else {
try {
id = Integer.parseInt(req.getParameter("person"));
} catch(NumberFormatException e) {}
if(id != null) {
PersonStorage ps = storageCreator.newPersonStorage();
Person person = ps.readById(id);
req.setAttribute("person", person);
}
}
getServletContext().getRequestDispatcher("/WEB-INF/jsp/contact/edit.jsp").forward(req, resp);
} catch(SQLException e) {
throw new ServletException(e);
} finally {
if(storageCreator != null) {
storageCreator.close();
}
}
}
}<file_sep>package web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import db.StorageCreator;
import db.TypeStorage;
import domain.Type;
public class TypeListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StorageCreator storageCreator = null;
try {
storageCreator = new StorageCreator();
TypeStorage s = storageCreator.newTypeStorage();
List<Type> types = s.readAll();
req.setAttribute("types", types);
getServletContext().getRequestDispatcher("/WEB-INF/jsp/type/index.jsp").forward(req, resp);
} catch(SQLException e) {
throw new ServletException(e);
} finally {
if(storageCreator != null) {
storageCreator.close();
}
}
}
}
|
9369600adf805021eb7faeb7cb7e6ec29f9a3cb2
|
[
"Java",
"SQL"
] | 8
|
Java
|
yermochenko/example-persons-list
|
3df0c8d048603b1bdb32d189dd0faa6002197d92
|
576e2501f7b5b98a74ca766b59c07d75b36b3ed5
|
refs/heads/master
|
<repo_name>patchkit/patchkit-util<file_sep>/social.js
// var ip = require('ip')
// does `a` follow `b`?
var follows =
exports.follows = function (users, a, b) {
var bp = users.profiles[b]
if (!bp) return false
return bp.followers[a]
}
// did `a` flag `b`?
var flags =
exports.flags = function (users, a, b) {
var bp = users.profiles[b]
if (!bp) return false
return bp.flaggers[a]
}
// get all who `a` follows
var followeds =
exports.followeds = function (users, a) {
var ids = []
for (var b in users.profiles) {
if (follows(users, a, b))
ids.push(b)
}
return ids
}
// get all who `a` follows, but who doesnt follow `a` back
var followedNonfriends =
exports.followedNonfriends = function (users, a) {
var ids = []
for (var b in users.profiles) {
if (follows(users, a, b) && !follows(users, b, a))
ids.push(b)
}
return ids
}
// get all who follow `a`
var followers =
exports.followers = function (users, b) {
var bp = users.profiles[b]
if (!bp) return []
return Object.keys(bp.followers)
}
// get all who follow `a`, but who `a` doesnt follow back
var followerNonfriends =
exports.followerNonfriends = function (users, a) {
var ids = []
for (var b in users.profiles) {
if (follows(users, b, a) && !follows(users, a, b))
ids.push(b)
}
return ids
}
// get all who follow `c`, who are followed by `a`
var followedFollowers =
exports.followedFollowers = function (users, a, c, includeA) {
var ids = []
for (var b in users.profiles) {
if (follows(users, a, b) && follows(users, b, c))
ids.push(b)
}
if (includeA && follows(users, a, c))
ids.push(a)
return ids
}
// get all who follow `c`, who are not followed by `a`
var unfollowedFollowers =
exports.unfollowedFollowers = function (users, a, c) {
var ids = []
for (var b in users.profiles) {
if (a != b && !follows(users, a, b) && follows(users, b, c))
ids.push(b)
}
return ids
}
// get all who flag `c`, who are followed by `a`
var followedFlaggers =
exports.followedFlaggers = function (users, a, c, includeA) {
var ids = []
for (var b in users.profiles) {
if (follows(users, a, b) && flags(users, b, c))
ids.push(b)
}
if (includeA && flags(users, a, c))
ids.push(a)
return ids
}
// get all who follow `a`, and who `a` follows back
var friends =
exports.friends = function (users, a) {
// all two-way follows
return followers(users, a).filter(function (b) {
return follows(users, a, b)
})
}
// TODO
// // is `id` a pub?
// var isPub =
// exports.isPub = function (id) {
// // try to find the ID in the peerlist, and see if it's a public peer if so
// for (var i=0; i < peers.length; i++) {
// var peer = peers[i]
// if (peer.key === id && !ip.isPrivate(peer.host))
// return true
// }
// return false
// }
// user-sort by popularity
var sortByPopularity =
exports.sortByPopularity = function (users, a, b) {
return followers(users, b).length - followers(users, a).length
}<file_sep>/README.md
# Patchkit Util
```js
import * as u from 'patchkit-util'
import * as social from 'patchkit-util/social'
u.plural(0) // => 's'
u.plural(1) // => ''
u.plural(2) // => 's'
u.shortString('123456789') // => '123456...'
u.shortString('123456789', 3) // => '123...'
u.bytesHuman(500) => '500b'
u.bytesHuman(1024) => '1kb'
u.bytesHuman(1024*1024) => '1mb'
// etc
u.niceDate(Date.now()) // => '4:35pm'
u.niceDate(Date.now() - ONEDAY) // => 'Mon 4:35pm'
u.niceDate(Date.now() - ONEWEEK) // => 'Jan 5'
u.niceDate(Date.now(), true) // 'a few seconds ago'
u.niceDate(Date.now() - ONEDAY, true) // => 'one day ago'
u.niceDate(Date.now() - ONEWEEK, true) // => '7 days ago'
u.getName(users, knownUserId) => 'bob'
u.getName(users, unknownUserId) => '@dkc12e...'
u.getProfilePic(users, userId) => blob link
u.getProfilePicRef(users, userId) => blob ref
u.getProfilePicUrl(users, userId, toUrl) => blob url
// does `a` follow `b`?
social.follows(users, a, b) => bool
// did `a` flag `b`?
social.flags(users, a, b) => bool
// get all who `a` follows
social.followeds(users, a) => userIds
// get all who `a` follows, but who doesnt follow `a` back
social.followedNonfriends(users, a) => userIds
// get all who follow `a`
social.followers(users, b) => userIds
// get all who follow `a`, but who `a` doesnt follow back
social.followerNonfriends(users, a) => userIds
// get all who follow `c`, who are followed by `a`
social.followedFollowers(users, a, c, includeA?) => userIds
// get all who follow `c`, who are not followed by `a`
social.unfollowedFollowers(users, a, c) => userIds
// get all who flag `c`, who are followed by `a`
social.followedFlaggers(users, a, c, includeA?) => userIds
// get all who follow `a`, and who `a` follows back
social.friends(users, a) => userIds
// user-sort by # of followers
social.sortByPopularity(users, a, b) => sort integer (-1|0|1)
```<file_sep>/index.js
var moment = require('moment')
var ssbref = require('ssb-ref')
// helper to put an s at the end of words if they're plural only
var plural =
module.exports.plural = function (n) {
return n === 1 ? '' : 's'
}
var shortString =
module.exports.shortString = function (str, len) {
len = len || 6
if (str.length - 3 > len)
return str.slice(0, len) + '...'
return str
}
var dataSizes = ['kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
var bytesHuman =
module.exports.bytesHuman = function (nBytes) {
var str = nBytes + 'b'
for (var i = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, i++) {
str = nApprox.toFixed(2) + dataSizes[i]
}
return str
}
const startOfDay = moment().startOf('day')
const lastWeek = moment().subtract(1, 'weeks')
const lastYear = moment().subtract(1, 'years')
var niceDate =
module.exports.niceDate = function (ts, ago) {
var d = moment(ts)
if (ago)
return d.fromNow()
if (d.isBefore(lastYear))
d = d.format('')
else if (d.isBefore(lastWeek))
d = d.format('MMM D')
else if (d.isBefore(startOfDay))
d = d.format('ddd h:mma')
else
d = d.format('h:mma')
return d
}
var getName =
module.exports.getName = function (users, id) {
return users.names[id] || shortString(id, 6)
}
var getProfilePic =
module.exports.getProfilePic = function (users, id) {
var profile = users.profiles[id]
if (profile) {
var link
// lookup the image link
if (profile.byMe.image)
return profile.byMe.image // use local user's choice...
else if (profile.self.image)
return profile.self.image // ...fallback to their choice
}
return false
}
var getProfilePicRef =
module.exports.getProfilePicRef = function (users, id) {
var link = getProfilePic(users, id)
return link ? link.link : false
}
var getProfilePicUrl =
module.exports.getProfilePicUrl = function (users, id, toUrl) {
toUrl = toUrl || defaultToUrl
var link = getProfilePic(users, id)
return toUrl(link && link.link, { isProfilePic: true })
}
// default toUrl() definition
var defaultToUrl =
module.exports.toUrl = function (ref, opts) {
// @-mentions
if (opts && opts.mentionNames && ref in opts.mentionNames)
return '#/profile/'+encodeURIComponent(opts.mentionNames[ref])
// standard ssb-refs
if (ssbref.isFeedId(ref))
return '#/profile/'+encodeURIComponent(ref)
else if (ssbref.isMsgId(ref))
return '#/msg/'+encodeURIComponent(ref)
else if (ssbref.isBlobId(ref))
return '/'+encodeURIComponent(ref)
else if (opts && opts.isProfilePic) {
if (ref)
return '/'+ref
return '/img/fallback.png'
}
return ''
}
|
c2afa9b02700502144d40f18e47b9f2e1118f473
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
patchkit/patchkit-util
|
58be6e63e6784ef2b4cf2d3667bad9506b894024
|
855a3ca23d824a2b5e730ae08995b568b2e48b41
|
refs/heads/master
|
<repo_name>nakajima-masashi/slackbot_mugichan<file_sep>/reboot.sh
#!/bin/sh
forever restart node_modules/.bin/hubot --adapter slack
<file_sep>/start.sh
#!/bin/sh
npm install
forever start -c coffee node_modules/.bin/hubot --adapter \slack
|
f13585d2ed8fa8e51b3a986d291a44c0e0184289
|
[
"Shell"
] | 2
|
Shell
|
nakajima-masashi/slackbot_mugichan
|
75d7cfe11c4f191c738e64de6f189d9dc1c5ebb1
|
9ae245dbcb729544eec316fd51010a96dee5ba15
|
refs/heads/master
|
<file_sep># Example Meter Install via Shell Script
Example of a lights out install via bash script of TrueSight Pulse Meter for the following operating system environments:
- Centos 7.0
- Centos 6.6
- Ubuntu 12.04
- Ubuntu 14.04
## Prerequisites
- Vagrant 1.7.2 or later. Vagrant can be downloaded [here](https://www.vagrantup.com/downloads.html)
- VirtualBox 4.3.2.6 or later. VirtualBox can be downloaded [here](https://www.virtualbox.org/wiki/Downloads)
## Installation
### Getting Started
The TrueSight Pulse meter is installed on each of the virtual machines via the `install.sh` script. TrueSight Pulse Meter installation requires that the _api token_ be known at install time. The TrueSight Pulse API Token can be found in the _Settings_ -> _Account_ dialog in the TrueSight Pulse web interface. The installation script requires that the API token value is present in an environment variable named, `API_TOKEN`.
### List of Platforms to Virtual Machine Mapping
The table below provides the mapping of platform to virtual machine name that is used later to start a virtual machine for testing plugins.
| Platform | Virtual Machine Name |
|:---------------------|:---------------------:|
|Centos 6.6 |`centos-6.6` |
|Centos 7.0 |`centos-7.0` |
|Ubuntu 12.04 |`ubuntu-12.04` |
|Ubuntu 14.04 |`ubuntu-14.04` |
### Starting a Virtual Machine
With the TrueSight Pulse API token perform the following:
1. Either checkout or clone the git repository ()[]
2. Issue the following command, the target platforms are listed in the table below:
```
$ API_TOKEN=<api token> vagrant up <virtual machine name>
```
### Stopping a Virtual Machine
```
$ vagrant halt <virtual machine name>
```
### Destroying a Virtual Machine
```
$ vagrant destroy <virtual machine name>
```
<file_sep>#!/bin/bash
# Define constant of the meter installation script name
typeset -r SETUP_SCRIPT="setup_meter.sh"
# Called at the end of the script execution to cleanup
function finish {
rm -rf "$SETUP_SCRIPT" 2>&1 > /dev/null
}
# Call our function to clean up on exit
trap finish EXIT
# Reports an error and then exits with non-zero status
function LogErrorAndExit()
{
typeset -r message=$1
echo "$(date): $message" >&2
exit 1
}
# Check to see if API_TOKEN environment is set,
if [ -z "$API_TOKEN" ]
then
LogErrorAndExit "API_TOKEN environment variable not set with TrueSight Pulse API token"
fi
# Check to see if curl is installed on the target
type curl 2>&1 > /dev/null
if [ $? -ne 0 ]
then
LogErrorAndExit "TrueSight Pulse Meter installations requires that the curl command is installed."
fi
# Create read-only constants
typeset -r DATA="{\"token\":\"$API_TOKEN\"}"
typeset -r HEADER='Content-Type: application/json'
typeset -r URL='https://meter.boundary.com/setup_meter'
# Download to the script to the current directory
curl -fsS -d "$DATA" -H "$HEADER" "$URL" 2> /dev/null > "$SETUP_SCRIPT"
# Check if download is successful, if not report error and exit
if [ $? -ne 0 ]
then
LogErrorAndExit "Failed to download $SETUP_SCRIPT"
fi
# Execute meter installation script
bash $SETUP_SCRIPT 2>&1 > /dev/null
typeset -i rc=$?
if [ $rc -ne 0 ]
then
LogErrorAndExit "Meter installation $SETUP_SCRIPT failed."
fi
exit $rc
|
c7c1b9e622b4086306f21f8bad40c18b0c10471f
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
jdgwartney/vagrant-meter-install
|
d2a0672d4a1fb2dfc0a5f156e7b8c223f3695b1a
|
b61c645fcc025b2ffff90cd9f6fde5ab91fd5f2b
|
refs/heads/dev
|
<file_sep>package dao;
import javax.annotation.Resource;
import enums.Status;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pojo.Student;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:myxml.xml")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Component
public class StudentDaoTest {
@Resource
StudentDao studentDao;
public void insert() {
Student student1 = new Student();
student1.setId(1);
student1.setName("jim");
Student student2 = new Student();
student2.setId(2);
student2.setName("alice");
Student student3 = new Student();
student3.setId(3);
student3.setName("bob");
studentDao.insert(student1);
studentDao.insert(student2);
studentDao.insert(student3);
}
@Test
public void select() {
Assert.assertEquals(studentDao.select(1).getName(), "jim");
Assert.assertEquals(studentDao.select(2).getStatus(), "正常");
Assert.assertNull(studentDao.select(0));
}
@Test
public void update() {
Student student1 = new Student();
student1.setId(1);
student1.setStatus(10);
Student student2 = new Student();
student2.setId(2);
student2.setStatus(1);
Student student3 = new Student();
student3.setId(10);
student3.setStatus(1);
int result = studentDao.update(student1);
int result1 = studentDao.update(student2);
int result2 = studentDao.update(student3);
Assert.assertEquals(studentDao.select(2).getStatus(), Status.get(1));
Assert.assertEquals(studentDao.select(1).getStatus(), "正常");
Assert.assertSame(1, result);
Assert.assertSame(1, result1);
Assert.assertSame(0, result2);
}
@Test
public void delete() {
insert();
studentDao.delete(3);
Assert.assertNull(studentDao.select(3));
}
}
<file_sep>import java.util.List;
import java.util.Map;
//import dao.ScoreDao;
//import dao.StudentDao;
import dao.CourseDao;
import dao.ScoreDao;
import dao.StudentDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import pojo.Course;
import pojo.Score;
import pojo.StuCourScor;
import pojo.Student;
public class Main {
public static void main(String[] args) {
// dao.StudentDao studentDao = new dao.StudentDao();
//studentDao.insert("xiaoming");
// studentDao.select(1);
// studentDao.update(1,"xiao");
// StudentDao.insert("jack");
// Student student=new Student();
// student.setName("lily");
// StudentDao.update(student);
//StudentDao.delete(3);
// Map<Student,Map<Course, Score>>map=ScoreDao.select(1,2019);
// Map<Student,Integer>map1= ScoreDao.getTop10();
// System.out.println(map);
// CreateConn.close();
// studentDao.delete(1);
//studentDao.close();
ApplicationContext context = new ClassPathXmlApplicationContext("myxml.xml");
// CourseDao courseDao = (CourseDao) context.getBean("courseDao");
// Course course=courseDao.select(1);
// System.out.println(course.getName());
////courseDao.update(1,"xx");
// // courseDao.delete(2);
// Course course = new Course();
// course.setId(6);
// course.setName("movie");
// courseDao.insert(course);
// ScoreDao scoreDao = context.getBean(ScoreDao.class);
//// // List<StuCourScor> list=scoreDao.getTop10();
// List<StuCourScor> list = scoreDao.select(1, 2019);
// scoreDao.getTop10();
// System.out.println(list.get(0).getScore().getGoal());
StudentDao studentDao = context.getBean(StudentDao.class);
System.out.println( studentDao.select(2).getStatus());
// Score score =new Score();
// score.setGoal(98);
// score.setYear(2019);
// score.setStudentId(1);
// score.setCourseId(6);
//scoreDao.insert(score);
// System.out.println(studentDao.select(1).getName());
// Student s = new Student();
// s.setName("kate");
// s.setStatus(0);
// studentDao.insert(s);
}
}
|
9431c357c1f806e31781c3609788cbb67429a911
|
[
"Java"
] | 2
|
Java
|
YXQ212526/SpringMybatisStudent
|
f5867a72ce444cb9ca79bf2ccac4171d17b445d4
|
a2312ec1a03deec07e944e0fdae2b84b7c9ce617
|
refs/heads/master
|
<repo_name>nateburgers/scheduler<file_sep>/schedule.js
#!/usr/bin/env node
// schedule.js -*-JavaScript-*-
/**
* @class ArgumentUtil
*/
class ArgumentUtil {
// CLASS METHODS
static default(argument, defaultValue) {
if (null === argument || undefined === argument) {
return defaultValue; // RETURN
}
return argument;
}
}
/**
* @class IntVectorRef
*/
class IntVectorRef {
// CREATORS
/**
* @constructor
*
* @param {Int32Array} int32Array
* @param {Integer} [beginIdx = 0]
* @param {Integer} [endIdx = int32Array.length]
* @param {Integer} [stride = 1]
*/
constructor(int32Array,
beginIdx = 0,
endIdx = int32Array.length,
stride = 1) {
this.d_int32Array = int32Array;
this.d_beginIdx = beginIdx;
this.d_endIdx = endIdx;
this.d_stride = stride;
}
// ACCESSORS
/**
* @method element
*
* @param {Integer} index
*
* @return {Integer}
*/
element(index) {
return this.d_int32Array[this.d_beginIndex + stride * index];
}
// MANIPULATORS
/**
* @method setElement
*
* @param {Integer} index
* @param {Integer} value
*/
setElement(index, value) {
this.d_int32Array[this.d_beginIndex + stride * index] = value;
}
}
/**
* @class IntVector
*/
class IntVector {
// CREATORS
/**
* @constructor
*
* @param {...Integer} [elements = []]
*/
constructor(...elements) {
this.d_int32Array = Int32Array.from(elements);
}
// PROPERTIES
get length() {
return this.d_int32Array.length;
}
// ACCESSORS
element(index) {
return this.d_int32Array[index];
}
// MANIPULATORS
/**
* @method ref
*
* @return {IntVectorRef}
*/
ref() {
return new IntVectorRef(this.d_int32Array);
}
setElement(index, int32) {
this.d_int32Array[index] = int32;
}
// ITERATORS
[Symbol.iterator]() {
return this.d_int32Array[Symbol.iterator]();
}
}
/**
* @class IntVectorUtil
*/
class IntVectorUtil {
}
/**
* @class IntMatrix
*/
class IntMatrix {
}
/**
* @class IntMathUtil
*/
class IntMathUtil {
// CLASS METHODS
static leastCommonFactor(a, b) {
if (0 === b) {
return a;
}
return IntMathUtil.leastCommonFactor(b, a % b);
}
}
<file_sep>/src/m_hhs_server.h
// m_hhs_server.h -*-C-*-
#ifndef INCLUDED_M_HHS_SERVER
#define INCLUDED_M_HHS_SERVER
#ifndef INCLUDED_STDINT
#include <stdint.h>
#endif
// hhs_byte.h
typedef uint8_t hhs_byte;
// hhs_integer.h
typedef int8_t hhs_integer8;
typedef int16_t hhs_integer16;
typedef int32_t hhs_integer32;
typedef int64_t hhs_integer64;
typedef int64_t hhs_integer;
// hhs_natural.h
typedef uint8_t hhs_natural8;
typedef uint16_t hhs_natural16;
typedef uint32_t hhs_natural32;
typedef uint64_t hhs_natural64;
typedef uint64_t hhs_natural;
// hhs_real.h
typedef float hhs_real32;
typedef double hhs_real64;
typedef double hhs_real;
// hhs_uintptr.h
typedef uintptr_t hhs_uintptr;
// hhs_allocate.h
#define Hhs_allocate(type) \
(type *)hhs_allocate(sizeof(type))
#define Hhs_allocate_array(type, num_elements) \
(type *)hhs_allocate_array(sizeof(type), num_elements)
#define Hhs_deallocate(object) \
hhs_deallocate(object);
void *
hhs_allocate(hhs_integer num_bytes);
void *
hhs_allocate_array(hhs_integer num_bytes,
hhs_integer num_elements);
void
hhs_deallocate(void *memory_p);
// hhs_integer_vector.h
struct hhs_integer_vector {
hhs_integer *d_begin_p;
hhs_integer *d_end_p;
};
// CREATORS
void
hhs_integer_vector_init(struct hhs_integer_vector *vector,
hhs_integer num_elements);
void
hhs_integer_vector_init_with_data(struct hhs_integer_vector *vector,
const hhs_integer elements[],
hhs_integer num_elements);
void
hhs_integer_vector_copy(struct hhs_integer_vector *destination,
const struct hhs_integer_vector *source);
void
hhs_integer_vector_destroy(struct hhs_integer_vector *vector);
// MANIPULATORS
void
hhs_integer_vector_update(struct hhs_integer_vector *vector,
hhs_integer index,
hhs_integer value);
// ACCESSORS
hhs_integer
hhs_integer_vector_num_elements(const struct hhs_integer_vector *vector);
hhs_integer
hhs_integer_vector_access(const struct hhs_integer_vector *vector);
// hhs_integer_matrix.h
struct hhs_integer_matrix {
hhs_integer *d_begin_p;
hhs_integer *d_end_p;
hhs_integer d_num_columns;
hhs_integer d_num_rows;
};
// CREATORS
void
hhs_integer_matrix_init(struct hhs_integer_matrix *matrix,
hhs_integer num_columns,
hhs_integer num_rows);
void
hhs_integer_matrix_init_with_data(struct hhs_integer_matrix *matrix,
const hhs_integer *elements[],
hhs_integer num_columns,
hhs_integer num_rows);
void
hhs_integer_matrix_destroy(struct hhs_integer_matrix *matrix);
// MANIPULATORS
// ACCESSORS
// hhs_gcd.h
hhs_integer
hhs_get_gcd(hhs_integer lhs,
hhs_integer rhs);
void
hhs_integer_vector_row_reduce(hhs_integer_vector *output,
const hhs_integer_vector *lhs,
const hhs_integer_vector *restrict rhs,
hhs_integer pivot);
// hhs_constraint.h
struct hhs_constraint {
struct hhs_integer_vector d_coefficients;
struct hhs_integer_vector d_variables;
hhs_integer d_lhs;
};
// ============================================================================
// IMPLEMENTATION
// ============================================================================
// hhs_integer_vector.c
// CREATORS
inline void
hhs_integer_vector_init(struct hhs_integer_vector *vector,
hhs_integer num_elements)
{
if (0 == num_elements) {
vector->d_begin_p = 0;
vector->d_end_p = 0;
return; // RETURN
}
vector->d_begin_p = Hhs_allocate_array(hhs_integer, num_elements);
vector->d_end_p = vector->d_begin_p + num_elements;
}
inline void
hhs_integer_vector_destroy(struct hhs_integer_vector *vector)
{
Hhs_deallocate(vector->d_begin_p);
vector->d_begin_p = 0;
vector->d_end_p = 0;
}
// MANIPULATORS
inline void
hhs_integer_vector_update(struct hhs_integer_vector *vector,
hhs_integer index,
hhs_integer value)
{
vector->d_begin_p[index] = value;
}
// ACCESSORS
inline hhs_integer
hhs_integer_vector_num_elements(const struct hhs_integer_vector *vector)
{
return vector->d_end_p - vector->d_begin_p;
}
inline hhs_integer
hhs_integer_vector_access(const struct hhs_integer_vector *vector,
hhs_integer index)
{
return vector->d_begin_p[index];
}
#endif
<file_sep>/src/m_hhs_server.c
// m_hhs_server.c -*-C-*-
#include "m_hhs_server.h"
#include <stdlib.h>
// hhs_allocate.c
void *
hhs_allocate(hhs_integer num_bytes)
{
return malloc(num_bytes);
}
void *
hhs_allocate_array(hhs_integer num_bytes,
hhs_integer num_elements)
{
return malloc(num_bytes * num_elements);
}
void
hhs_deallocate(void *memory_p)
{
free(memory_p);
}
// hhs_gcd.c
hhs_integer
hhs_get_gcd(hhs_integer lhs,
hhs_integer rhs)
{
while (0 != rhs) {
lhs = rhs;
rhs = lhs % rhs;
}
return lhs;
}
// ============================================================================
// MAIN PROGRAM
// ============================================================================
int main(int argc, char *argv[])
{
}
|
683ffb6f259e0b9f85dfa4473f0222a93054a573
|
[
"JavaScript",
"C"
] | 3
|
JavaScript
|
nateburgers/scheduler
|
1326c3132a17997b543eb81184b3d8fb9b2f3c26
|
32b853853d76d6ed5ce7a74a2fdf1bd23a9169fe
|
refs/heads/master
|
<file_sep>module Sinicum
module Runner
VERSION = "0.5.1"
end
end
|
f145d5ab11577b5162a889f23b0004f9280f99c8
|
[
"Ruby"
] | 1
|
Ruby
|
dievision/sinicum-runner
|
82d27a8cbee70e94ef0aa3343095abb0761b9a35
|
11c2b979f25956f4acaee23d95c036859cd22965
|
refs/heads/master
|
<repo_name>no99in/algorithms<file_sep>/Java-JDK-1.6/study-10.java
package Main;
public class Main {
public static int choice(int[][] dist, int process, int min, int[][] line,
int[][] en, int chiose) {
// exit
if (process == 5) {
return min;
}
// last
int last = 0;
int el = 1;
if(line[0][process] == 1) {last = 0; }
if(line[1][process] == 1) {last = 1; el = 0;}
// best and save the result
if (line[last][process + 1] > line[el][process + 1] + en[el][process + 1]) {
System.out.println(el);
min = choice(dist, process + 1, min, line, en, el);
}else{
System.out.println(last);
min = choice(dist, process + 1, min, line, en, last);
}
// algorithm end
return min;
}
public static void main(String[] args) {
int[][] dist = new int[2][6];
int[][] line = { { 7, 9, 3, 4, 8, 4 }, { 8, 5, 6, 4, 5, 7 } };
int[][] en = { { 2, 2, 1, 2, 2, 1 }, { 4, 2, 3, 1, 3, 4 } };
int min = choice(dist, 0, 999, line, en, 0);
System.out.println(min);
}
}
<file_sep>/Java-JDK-1.6/README.md
**算法之路 My way of algorithms 4 Java-JDK-1.6**
此目录是基于 Java 1.6 版本设计的算法,所有算法均在我的电脑上测试通过。
本项目旨在告诉大家一些 Java 1.6 的一些特性,以及如何在竞赛中使用形同的代码,拿到最好的成绩。
<file_sep>/Java-JDK-1.6/study-04.java
package Main;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
/**
* 动态规划
*
*
* 3 1 1 2 2 3 3
*
* */
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<thing> al = new ArrayList<thing>();
int n = in.nextInt();
for (int i = 1; i <= n; i++) {
al.add(new thing(in.nextInt(), in.nextInt()));
}
int[][] ans = new int[10][101];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 101; j++) {
if (i == 0) {
if (j < al.get(i).weight)
ans[i][j] = 0;
else
ans[i][j] = Math.max(0, al.get(i).value);
} else {
if (j < al.get(i).weight)
ans[i][j] = ans[i - 1][j];
else
ans[i][j] = Math.max(ans[i - 1][j],
ans[i - 1][j - al.get(i).weight] + al.get(i).value);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 101; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println("");
}
}
}
class thing {
public int weight;
public int value;
public thing(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
<file_sep>/Java-JDK-1.6/study-06.java
package Main;
public class Main {
public static int fun(int n) {
return 3 * n + 9;
}
public static int coreAlgo(int a, int b) {
int res = fun(a) * fun((a + b) / 2);
int mid = (a + b) / 2;
if (res == 0) {
return mid;
}
if (res > 0) {
mid = coreAlgo(mid, b);
} else {
mid = coreAlgo(a, mid);
}
return mid;
}
public static void main(String[] args) {
System.out.println(coreAlgo(-5, 3));
}
}
<file_sep>/Java-JDK-1.6/study-02.java
package Main;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void swap(char ans[],int pos1,int pos2){
if(pos1 != pos2){
char temp = ans[pos1];
ans[pos1] = ans[pos2];
ans[pos2] = temp;
}
}
/**
* 全排列 6个以下
* */
public static void coreAlgo(char[] ans, int beg, int end) {
if (beg == end) {
System.out.print(ans);
System.out.print(" ");
}
for(int i = beg;i <= end ;i ++){
swap(ans,beg,i);
coreAlgo(ans,beg+1,end);
swap(ans,beg,i);
}
}
public static void main(String[] args) {
String str = in.next();
char[] ans = str.toCharArray();
coreAlgo(ans, 0, ans.length - 1);
}
}
<file_sep>/Java-JDK-1.6/计蒜客 - 2019 蓝桥杯省赛 B 组模拟赛(一)/problem-1.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
SimpleDateFormat dft = new SimpleDateFormat("HH:mm:ss");
try {
Date date_1 = dft.parse("06:24:26");
Date date_2 = dft.parse("22:28:45");
Date date_3 = dft.parse("24:00:00");
long res = date_3.getTime() - date_2.getTime() + date_1.getTime();
Date date_res = new Date(res);
System.out.println(dft.format(date_res));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
|
4a40c842574b21429a848495f5b4d6b4eba0be3d
|
[
"Markdown",
"Java"
] | 6
|
Java
|
no99in/algorithms
|
22380a319d1b146c39106347ca078f242ec21965
|
ece3df711f06fdfff432eb344f57e84620d3d7cc
|
refs/heads/master
|
<file_sep>extern crate regex;
use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::fmt::{Display, Formatter};
use db::database::{Backend, BackendError, Database};
use db::channel::DbChannel;
use self::regex::{Regex, RegexBuilder};
lazy_static! {
static ref REGEX: Regex =
RegexBuilder::new(".*://(?P<user>.*)(:(?P<password>.*))?@(?P<host>.*)(:(?P<port>.*))?/(?P<db>.*)$")
.swap_greed(true) // make regex non greedy
.compile()
.ok()
.unwrap();
}
#[derive(Debug)]
pub struct ConnectionParams<'c, B> where B: Backend {
pub data: ConnectionData<'c>,
pub backend: B
}
#[derive(Debug)]
pub struct ConnectionData<'c> {
pub host: Cow<'c, str>,
pub port: usize,
pub database: Cow<'c, str>,
pub username: Cow<'c, str>,
pub password: Option<Cow<'c, str>>,
}
#[derive(Debug)]
pub enum ParamsError {
UnsupportedBackendError,
MalformedURLError
}
impl Display for ParamsError {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}", self)
}
}
impl Error for ParamsError {
fn description(&self) -> &str {
match *self {
ParamsError::UnsupportedBackendError => "Unsupported backend!",
ParamsError::MalformedURLError => "Error while trying to parse URL!"
}
}
}
pub trait IntoConnectionParams<'c> {
fn into(self) -> Result<ConnectionParams<'c, Database>, ParamsError>;
}
impl<'c> IntoConnectionParams<'c> for ConnectionParams<'c, Database> {
fn into(self) -> Result<ConnectionParams<'c, Database>, ParamsError> {
Ok(self)
}
}
impl<'a> IntoConnectionParams<'a> for &'a str {
fn into(self) -> Result<ConnectionParams<'a, Database>, ParamsError> {
let backend: Option<Database> = {
if self.contains("mysql") {
Some(Database::MySQL)
} else if self.contains("postgres") {
Some(Database::Postgres)
} else {
None
}
};
let captures = REGEX.captures(self);
let params = match (captures, backend) {
(Some(captures), Some(backend)) => {
let user = captures.name("user").map(Cow::from).unwrap();
let password = captures.name("password").map(Cow::from);
let host = captures.name("host").map(Cow::from).unwrap();
let port: usize = captures.name("port").map(str::parse::<usize>).and_then(Result::ok).unwrap_or(backend.default_port());
let db = captures.name("db").map(Cow::from).unwrap();
Ok(ConnectionParams {
data: ConnectionData {
host: host,
port: port,
database: db,
username: user,
password: <PASSWORD>,
},
backend: backend
})
},
(Some(_), None) => Err(ParamsError::UnsupportedBackendError),
(None, _) => Err(ParamsError::MalformedURLError)
};
params
}
}
pub struct Connection {}
#[derive(Debug)]
pub enum ConnectionError {
ParamsError(ParamsError),
BackendError(BackendError)
}
impl Display for ConnectionError {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}", self)
}
}
impl Error for ConnectionError {
fn description(&self) -> &str {
match *self {
ConnectionError::ParamsError(_) => "Wrong parameters!",
ConnectionError::BackendError(_) => "Backend error! {}"
}
}
fn cause(&self) -> Option<&Error> {
match *self {
ConnectionError::ParamsError(ref e) => Some(*&e),
ConnectionError::BackendError(ref e) => Some(*&e)
}
}
}
impl<'p> Connection {
pub fn connect<P: IntoConnectionParams<'p>>(conn_params: P) -> Result<Box<DbChannel>, ConnectionError> {
match conn_params.into() {
Ok(params) => {
let backend = params.backend;
let channel = backend.connect(params.data);
match channel {
Ok(chan) => {
Ok(chan)
},
Err(e) => Err(ConnectionError::BackendError(e))
}
},
Err(e) => Err(ConnectionError::ParamsError(e))
}
}
}
<file_sep>use std::error::Error;
use mysql::Pool as MySqlPool;
use r2d2::Pool;
use r2d2_postgres::PostgresConnectionManager;
pub trait DbChannel: Send + Sync {
fn query(&self, &str) -> Result<(), String>;
}
impl DbChannel for MySqlPool {
fn query(&self, query: &str) -> Result<(), String> {
match self.prep_exec(query, ()) {
Ok(_) => Ok(()),
Err(err) => Err(err.description().to_string())
}
}
}
impl DbChannel for Pool<PostgresConnectionManager> {
fn query(&self, query: &str) -> Result<(), String> {
let conn = self.clone().get().unwrap();
match conn.execute(query, &[]) {
Ok(_) => Ok(()),
Err(err) => Err(err.description().to_string())
}
}
}<file_sep>use time::Duration;
use std::fmt::Write;
use std::fmt::{Display, Formatter, Result};
macro_rules! println_err {
($($arg:tt)*) => {
{
let res = writeln!(::std::io::stderr(), $($arg)*);
res.expect("Failed writing to stderr!");
}
};
}
macro_rules! expect {
($r:expr, $msg:tt) => {
{
$r.map_err(|e|{
println_err!($msg, e.description());
::std::process::exit(1);
}).unwrap()
}
};
}
pub fn to_ms_precise(d: &Duration) -> f64 {
const NANOS_PER_MS: i64 = 1_000_000;
let nanos = d.num_nanoseconds().unwrap(); // TODO: Better error handling
(nanos as f64) / (NANOS_PER_MS as f64)
}
pub trait PrettyPrint {
fn pretty_print<W: Write>(&self, &mut W) -> Result;
}
impl PrettyPrint for Duration {
fn pretty_print<W: Write>(&self, f: &mut W) -> Result {
write!(f, "{:.4} ms", to_ms_precise(&self))
}
}
pub struct PrettyPrinter<T: PrettyPrint>(pub T);
impl<T: PrettyPrint> Display for PrettyPrinter<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
let mut str = String::new();
self.0.pretty_print(&mut str).and(f.write_str(&str))
}
}
impl<T: PrettyPrint> From<T> for PrettyPrinter<T> {
fn from(t: T) -> Self {
PrettyPrinter(t)
}
}<file_sep># dbench
**dbench** is a simple database query benchmarker written in Rust.
It currently supports MySQL and Postgres. See [Planned features](#planned-features) for more info.
## Table of contents
- [Install](#install)
- [Usage](#usage)
- [Recognized options and flags](#recognized-options-and-flags)
- [Planned features](#planned-features)
- [Contribute](#contribute)
- [License](#license)
## Install
1. Install cargo for your OS/distribution (https://crates.io/install)
2. Run `cargo install dbench`
## Usage
* Run a query
```
$ dbench -d foo_database -H localhost -u db_user -p -q "select * from bar_table"
```
* Run a query with parametrized URL
```
$ dbench mysql://db_user:db_password@localhost/foo_database -q "select * from bar_table"
```
* Run 10 queries
```
$ dbench mysql://db_user:db_password@localhost/foo_database -q "select * from bar_table" -n 10
```
* Read help
```
$ dbench --help
```
## Example output
```
$ dbench mysql://me:hunter2@localhost/swagdb -q "select * from referents" -n 100 -j 8
Number of requests: 100
Latency per request (mean): 0.1507 ms
Req/ms: 6.635
Total time: 15.0714 ms
Percentage of queries computed within a certain time:
50% 0.0730 ms
66% 0.0758 ms
75% 0.0813 ms
80% 0.1322 ms
90% 0.1559 ms
95% 0.2756 ms
98% 0.3342 ms
99% 5.8745 ms
100% 5.8745 ms (longest request)
```
## Recognized options and flags
| Short version | Long version | Accepts parameter | Description |
|:-------------:|:------------:|:-----------------:|:------------------------------------------------------------------------|
| -d | --database | yes | Database name to which the query is sent |
| -H | --host | yes | The host where the database resides |
| -q | --query | yes | The query to be executed by the database |
| -j | --jobs | yes | Number of concurrent jobs |
| -u | --user | yes | The username used for authenticating with the database |
| -p | --password | no | Flag to indicate whether to use a password or not (asked interactively) |
| -V | --version | no | Prints version information |
| -h | --help | no | Prints help information |
| -v | N/A | no | Raises verbosity level |
## Planned features
- ~~PostgreSQL support~~ (Done!)
- Other DBs support (Mongo?)
- More measurements, such as:
- ~~Req/s (mean)~~ (Done!)
- ~~Time per request (mean)~~ (Done!)
- ~~Total time~~ (Done!)
- ~~Percentage with time (as `ab`)~~ (Done!)
- ~~Concurrent requests support~~ (Done!)
## Contribute
See [CONTRIBUTING.md](../master/CONTRIBUTING.md)
## License
[MIT License (c) <NAME>](../master/LICENSE)
<file_sep># CONTRIBUTING
## How to contribute
You should use the [Fork & Pull](https://guides.github.com/activities/forking/) method.
Steps: fork a repo -> make changes and commits -> send a pull request
## Style
See the [Rust Official Style Guide](https://github.com/rust-lang-nursery/fmt-rfcs/blob/master/guide/guide.md).
## Commit messages
Follow [Angular Git Commit Guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#-git-commit-guidelines).
Short & easy way:
1. Install `commitizen` with
```
$ npm install -g commitizen
```
2. Configure commitizen with sane defaults
```
$ npm install -g cz-conventional-changelog
$ echo '{ "path": "cz-conventional-changelog" }' > ~/.czrc
```
3. **Always use** `git cz` when commiting instead of `git commit`
4. Done!
(You can always manually type all those pesky parentheses and colons if you wish instead
of using an automated tool. As long as commit style is consistent I won't complain. Maybe.)
<file_sep>use std::error::Error;
use std::fmt;
use std::fmt::{Display, Debug, Formatter};
use db::channel::DbChannel;
use db::connection::ConnectionData;
use db::mysql;
use db::postgres;
#[derive(Debug)]
pub enum Database {
MySQL,
Postgres
}
pub trait Backend: Debug {
fn default_port(&self) -> usize;
fn connect(&self, ConnectionData) -> Result<Box<DbChannel>, BackendError>;
}
// FIXME: Find a way to statically dispatch
impl Backend for Database {
fn default_port(&self) -> usize {
match *self {
Database::MySQL => mysql::default_port(),
Database::Postgres => postgres::default_port()
}
}
fn connect(&self, cdata: ConnectionData) -> Result<Box<DbChannel>, BackendError> {
match *self {
Database::MySQL => mysql::connect(cdata),
Database::Postgres => postgres::connect(cdata)
}
}
}
#[derive(Debug)]
pub enum BackendError {
IoError(Box<Error>)
}
impl Display for BackendError {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}", self)
}
}
impl Error for BackendError {
fn description(&self) -> &str {
match *self {
BackendError::IoError(_) => "Error estabilishing a database connection!"
}
}
fn cause(&self) -> Option<&Error> {
match *self {
BackendError::IoError(ref err) => Some(&**err)
}
}
}<file_sep>pub mod connection;
pub mod channel;
pub mod database;
mod mysql;
mod postgres;<file_sep>use std::borrow::Cow;
use std::error::Error;
use super::database::{BackendError};
use super::connection::ConnectionData;
use super::channel::{DbChannel};
use postgres::params::{ConnectParams, ConnectTarget, UserInfo};
use r2d2::{Config, Pool};
use r2d2_postgres::{TlsMode, PostgresConnectionManager};
pub fn default_port() -> usize {
5432
}
pub fn connect(params: ConnectionData) -> Result<Box<DbChannel>, BackendError> {
let conn_params = ConnectParams {
target: ConnectTarget::Tcp(params.host.into_owned()),
port: Some(params.port as u16),
user: Some(UserInfo {
user: params.username.into_owned(),
password: params.password.map(Cow::into_owned)
}),
database: Some(params.database.into_owned()),
options: vec![]
};
let config = Config::default();
let manager = PostgresConnectionManager::new(conn_params, TlsMode::None).unwrap();
let pool = Pool::new(config, manager);
match pool {
Ok(pool) => Ok(Box::new(pool) as Box<DbChannel>),
Err(e) => {
println!("Unable to connect to PostgreSQL backend.");
Err(BackendError::IoError(Box::new(e) as Box<Error>))
}
}
}<file_sep>#[macro_use]
extern crate mysql;
#[macro_use]
extern crate lazy_static;
extern crate postgres;
extern crate clap;
extern crate time;
extern crate rpassword;
extern crate num;
extern crate rayon;
extern crate r2d2;
extern crate r2d2_postgres;
#[macro_use]
mod util;
mod db;
use std::borrow::Cow;
use std::io::Write;
use std::error::Error;
use time::Duration;
use num::cast::ToPrimitive;
use clap::{Arg, App};
use util::PrettyPrinter;
use db::connection::{Connection, ConnectionData, ConnectionParams};
use db::database::{Backend, Database};
use db::channel::DbChannel;
use rayon::prelude::*;
use rayon::Configuration;
fn main() {
let args = App::new("DbBench")
.version("0.1.0")
.author("<NAME> <<EMAIL>>")
.about("A database query benchmark program")
.arg(Arg::with_name("url")
.value_name("URL")
.help("The connection url to the db. If you specify the URL, you must not pass host, backend, username and password arguments.")
.conflicts_with("manual"))
.arg(Arg::with_name("query")
.short("q")
.long("query")
.value_name("QUERY")
.help("The query to be executed by the database")
.required(true))
.arg(Arg::with_name("host")
.short("H")
.long("host")
.value_name("HOST")
.help("The host where the database resides")
.group("manual"))
.arg(Arg::with_name("database")
.short("d")
.long("database")
.value_name("DATABASE")
.help("The database name")
.group("manual"))
.arg(Arg::with_name("username")
.short("u")
.long("user")
.value_name("USER")
.help("The username used for authenticating with the database")
.group("manual"))
.arg(Arg::with_name("backend")
.short("b")
.long("backend")
.value_name("BACKEND")
.help("The database backend used")
.possible_values(&["mysql", "postgres"])
.group("manual"))
.arg(Arg::with_name("password")
.short("p")
.long("password")
.help("Flag to indicate whether to use a password or not (asked interactively)"))
.arg(Arg::with_name("requests")
.short("n")
.value_name("NUMBER")
.help("The number of query requests to send to the database"))
.arg(Arg::with_name("jobs")
.short("j")
.long("jobs")
.value_name("JOBS")
.help("The number of concurrent jobs that will query the database"))
.arg(Arg::with_name("verbosity")
.short("v")
.help("Verbosity level"))
.get_matches();
let chan = {
let chan_inner = {
if args.is_present("url") {
let url = args.value_of("url").unwrap();
Connection::connect(url)
} else {
let backend = args.value_of("backend");
let db = args.value_of("database");
let username = args.value_of("username");
let host = args.value_of("host");
let port = args.value_of("port");
let password = args.value_of("password");
// db, username, host and backend must ALL be present
match (db, username, host, backend) {
(Some(db), Some(username), Some(host), Some(backend_str)) => {
let database = match backend_str {
"mysql" => Database::MySQL,
"postgres" => Database::Postgres,
_ => unreachable!()
};
Connection::connect(ConnectionParams {
data: ConnectionData {
host: Cow::from(host),
port: port.and_then(|s| str::parse::<usize>(s).ok()).unwrap_or(database.default_port()),
database: Cow::from(db),
username: Cow::from(username),
password: <PASSWORD>.map(Cow::from)
},
backend: database
})
},
_ => {
println_err!("Missing parameters: ensure that parametrized URL or db, username, host and backend are present.");
std::process::exit(1);
}
}
}
};
match chan_inner {
Ok(c) => c,
Err(e) => {
println_err!("Error while trying to create connection to db! {}", e.description());
std::process::exit(1);
}
}
};
let jobs = args.value_of("jobs").map(str::parse::<usize>).and_then(Result::ok).unwrap_or(1);
let query = args.value_of("query");
let verbosity = args.occurrences_of("verbosity");
let times = args.value_of("requests").map(str::parse::<usize>).and_then(|r| {
r.map_err(|_| println_err!("Invalid argument passed to `-n` flag. Defaulting to 1")).ok()
}).unwrap_or(1);
let measure = |chan: &Box<DbChannel>| {
let duration = Duration::span(|| {
match chan.query(query.unwrap()) {
Ok(_) => (),
Err(cause) => println!("Error: {}", cause)
}
});
if verbosity > 0 {
println!("Query took: {}", PrettyPrinter::from(duration));
}
duration
};
let mut durations = Vec::with_capacity(times);
if jobs > 1 {
let config = Configuration::new().set_num_threads(jobs);
match rayon::initialize(config) {
Ok(()) => (),
Err(e) => println!("Error while initializing rayon: {}", e)
}
(0..times).into_par_iter().map(|_| {
measure(&chan)
}).collect_into(&mut durations);
} else {
for _ in 0..times {
durations.push(measure(&chan));
}
}
let sum = durations.iter().fold(Duration::zero(), |d, &c| d + c);
println!("Number of requests: {}", times);
println!("Latency per request (mean): {}", PrettyPrinter::from(sum / times.to_i32().unwrap()));
println!("Req/ms: {0:.3}", times.to_f64().unwrap() / util::to_ms_precise(&sum));
println!("Total time: {}", PrettyPrinter::from(sum));
durations.sort();
let pretty = durations.into_iter().map(PrettyPrinter::from).collect::<Vec<_>>();
let len = pretty.len();
println!("Percentage of queries computed within a certain time:");
println!("{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6}\n\
{:>5}\t{:>6} (longest request)\n",
"50%", pretty[len / 2],
"66%", pretty[len * 2 / 3],
"75%", pretty[len * 3 / 4],
"80%", pretty[len * 4 / 5],
"90%", pretty[len * 9 / 10],
"95%", pretty[len * 95 / 100],
"98%", pretty[len * 49 / 50],
"99%", pretty[len * 99 / 100],
"100%", pretty[len - 1]);
}<file_sep>[package]
name = "dbench"
version = "0.1.0"
description = "A simple database query benchmarker"
authors = ["<NAME> <<EMAIL>>"]
license = "MIT"
repository = "https://github.com/giovanniberti/dbench"
keywords = ["database", "benchmark", "query", "mysql", "postgres"]
[dependencies]
mysql = "8.0.0"
clap = "2.19.2"
time = "0.1"
rpassword = "0.3"
num = "0.1.36"
postgres = "0.13.4"
regex = "0.1"
lazy_static = "0.2.2"
rayon = "0.6.0"
r2d2 = "0.7.1"
r2d2_postgres = "0.11.1"<file_sep>use std::error::Error;
use super::database::{BackendError};
use super::connection::ConnectionData;
use super::channel::{DbChannel};
use mysql::{Opts, OptsBuilder, Pool};
pub fn default_port() -> usize {
3306
}
pub fn connect(params: ConnectionData) -> Result<Box<DbChannel>, BackendError> {
let builder = {
let mut tmp = OptsBuilder::new();
tmp
.ip_or_hostname(Some(params.host))
.tcp_port(params.port as u16) // FIXME: Use `num` crate to perform conversion
.db_name(Some(params.database))
.user(Some(params.username))
.pass(params.password);
tmp
};
let opts = Opts::from(builder);
let pool = Pool::new(opts);
match pool {
Ok(p) => Ok(Box::new(p) as Box <DbChannel>),
Err(e) => {
println ! ("Unable to connect with MySQL backend.");
Err(BackendError::IoError(Box::new(e) as Box< Error > ))
}
}
}
|
d4845f61ff500b666d5017c1e0c5d2dd89b46318
|
[
"Markdown",
"Rust",
"TOML"
] | 11
|
Rust
|
giovanniberti/dbench
|
3263f5ed5a25979f9d9954c49cc96e44708a97ae
|
bb52a2820e14c9edb09652fc578a61a3a14ad40f
|
refs/heads/main
|
<file_sep>'''
Audio mp3 scraper
'''
import urllib.request # download di mp3
import pandas as pd
from pydub import AudioSegment # convert audio
import os
def extract_url_name(url):
'''
From url extract name animal
@params url: url of audio animal
'''
if type(url) is not str:
return None
s = url.split("/")
if s[-1].endswith(".mp3"):
s2 = s[-1].split("_")
name = "".join([s2[0], " ", s2[1]])
else:
return None
return name
def download_mp3(df, classes, data_path):
'''
Download all audios of selected classes of animals in separate directories
@params df: directory of multimedia links
@params classes: list of latin animal names
@params data_path: path of download directory
'''
for animal in classes:
# se il nome non è presente nel dataset
if not any(df['animal_name'] == animal):
print("NOT FOUND", animal)
else:
# identifier comlumn as links
links = df[df['animal_name'] == animal]['identifier']
path = f"{data_path}/{animal}".replace(' ', '_')
# create directory if not exists
try:
if not os.path.exists(path):
os.makedirs(path)
except OSError:
print (f"Creation of the directory {path} failed")
# download and create file .mp3
for link in links:
try:
urllib.request.urlretrieve(link, f"{path}/{link.split('/')[-1]}")
print(f"{path}/{link.split('/')[-1]}", "SUCCESSFUL DOWNLOADED")
except:
print("ERROR", link, " does NOT downloaded!")
print(animal, "audios directory, SUCCESSFUL CREATED")
def mp3_to_wav(datapath = 'data', destination_path = 'data_wav'):
'''
Convert mp3 files into wav
'''
dirs = os.listdir(f"{datapath}/")
for directory in dirs:
# create directory_wav
if not os.path.exists(f"{destination_path}/{directory}"):
os.makedirs(f"{destination_path}/{directory}")
mp3_files = os.listdir(f"{datapath}/{directory}/")
for mp3 in mp3_files:
if mp3.endswith(".mp3"):
name = mp3.split(".")[0]
sound = AudioSegment.from_mp3(f"{datapath}/{directory}/{mp3}")
sound.export(f"{destination_path}/{directory}/{name}.wav", format = 'wav')
print(f"{datapath}/{directory}_wav/{name} CONVERTED")
print(f"{destination_path}/{directory} CREATED")
'''
main
'''
mp3_to_wav()
if __name__ == "__main__":
# set working directory
os.chdir("C:/Users/fede9/Documents/GitHub/DSIM_project/audio_download")
df = pd.read_csv("audio_reference/multimedia.txt", sep = "\t") # multimedia dataframe
classes = ["Equus caballus"] # list of classes
data_path = "data" # path of download directory
# add animal latin name column
df['animal_name'] = df['identifier'].apply(lambda x: extract_url_name(x))
# download mp3 files
download_mp3(df, classes, data_path)<file_sep># **DSIM_project**
Github repository for Digital Signal & Image Recognition project.
The presentation for the project is available [here](presentation/presentation_dsim.pdf).
The video of the demo is available [here](https://youtu.be/RKwl9WuHxr8).
## **Folders**
* **species_to_choose**: select which species will be used in the project
* **audio_download**: download audio files from Animal Sound Archive (gbif.org)
* **monodimensional**: audio recognition
* **data**: contains the notebook that converts wav files to mel-spectrograms and the spectrograms themselves
* **fine-tuning**: audio recognition fine-tuning a ResNet
* **classifiers**: audio recognition using a ResNet as a feature extractor and by training classical classifiers on the extracted features
* **bidimensional**: image recognition
* **data**: contains the image dataset used ([Awa2](https://cvml.ist.ac.at/AwA2/))
* **fine-tuning**: audio recognition fine-tuning a ResNet
* **retrieval**: retrieval
* **data**: contains the image dataset used ([Awa2](https://cvml.ist.ac.at/AwA2/))
* **retrieval**: retrieval using a ResNet and a KDTree
* **presentation**: Powerpoint presentation of the project
* **demo**: contains the video of the Demo created for this project and available [here](https://github.com/federicodeservi/DSIM_demo)
## **Authors**
<NAME>, <NAME>
|
02a331461377afa03cf2a48692d2ccbc36080d95
|
[
"Markdown",
"Python"
] | 2
|
Python
|
federicodeservi/DSIM_project
|
a83ef6e80310caa2fd6c0e574499b9012495a26d
|
3925ded5c338f22a39a107a90780308ef71dd082
|
refs/heads/master
|
<file_sep>package com.listingtotods.listtodos.controllers;
import com.listingtotods.listtodos.models.Todo;
import com.listingtotods.listtodos.repositories.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
@RequestMapping("todo")
public class TodoController {
TodoRepository todoRepository;
@Autowired
public TodoController(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
@RequestMapping("")
public String getTodo(Model model) {
return "redirect:/todo/list";
}
@RequestMapping("/list")
public String list(Model model) {
List<Todo> data = todoRepository.findAll();
model.addAttribute("list", data);
return "todo";
}
}
<file_sep>package TeachersAndStudents;
public class Student {
public String learn(){
return "Student is learning something new";
}
public void question(Teacher teacher){
System.out.println(teacher.answer());
}
}
<file_sep>package com.weekshop.webshop.models;
public class AvgTest {
private String searchThing;
public AvgTest() {
}
public String getSearchThing() {
return searchThing;
}
public void setSearchThing(String searchThing) {
this.searchThing = searchThing;
}
}
<file_sep>package com.springadvanced.tokenaut.services;
import com.springadvanced.tokenaut.models.Result;
import java.util.List;
public interface OnGetMoviesCallback {
void onSuccess(List<Result> results);
void onError();
}
<file_sep>rootProject.name = 'batman'
<file_sep>public class WarApp {
public static void main(String[] args) {
Armada a1 = new Armada();
Armada a2 = new Armada();
// a1.war(a2);
System.out.println(a1.war(a2));
}
}
<file_sep>package DataStructure;
import java.awt.*;
public class Main {
public static void main(String[] args) {
PostIt newInstance1 = new PostIt();
PostIt newInstance2 = new PostIt();
PostIt newInstance3 = new PostIt();
newInstance1.backgroundColor = Color.ORANGE;
newInstance1.text = "Idea1";
newInstance1.textColor = Color.BLUE;
newInstance2.backgroundColor = Color.PINK;
newInstance2.text = "Awsome";
newInstance2.textColor = Color.BLACK;
newInstance3.backgroundColor = Color.YELLOW;
newInstance3.text = "Superb";
newInstance3.textColor = Color.GREEN;
BlogPost a = new BlogPost();
BlogPost b = new BlogPost();
BlogPost c = new BlogPost();
a.authorName = "<NAME>";
a.title = "Lorem Ipsum";
a.publicationDate = "2000.05.04.";
a.text = "Lorem ipsum dolor sit amet.";
b.title = "Wait but why";
b.publicationDate = "2010.10.10.";
b.authorName = "<NAME>";
b.text = "A popular long-form, stick-figure-illustrated blog about almost everything.";
c.authorName = "<NAME>";
c.title = "One Engineer Is Trying to Get IBM to Reckon With Trump";
c.publicationDate = "2017.03.28.";
c.text = "<NAME>, a cybersecurity engineer at IBM, doesn’t want to be the center of attention. When I asked to take his picture outside one of IBM’s New York City offices, he told me that he wasn’t really into the whole organizer profile thing.";
}
}
<file_sep>package com.foxclub.foxclub.repositories;
import com.foxclub.foxclub.models.Trick;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class TrickStore {
private List<Trick> trickList;
public TrickStore() {
this.trickList = new ArrayList<>();
trickList.add(new Trick("write HTML"));
trickList.add(new Trick("code in Java"));
trickList.add(new Trick("power of Python"));
trickList.add(new Trick("lift rocks"));
trickList.add(new Trick("do some Earth magic"));
trickList.add(new Trick("town portal"));
trickList.add(new Trick("spawn large undead army"));
}
public List<Trick> getAllTricks() {
return trickList;
}
public void addTrick(Trick trick) {
trickList.add(trick);
}
}
<file_sep>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.lang.String;
public class ProductDatabase2 {
public static void main(String[] args) {
HashMap<String, Integer> prodData = new HashMap<>();
prodData.put("Eggs" , 200);
prodData.put("Milk" , 200);
prodData.put("Fish" , 400);
prodData.put("Apples" , 150);
prodData.put("Bread" , 50);
prodData.put("Chicken" , 550);
System.out.println("The " + printList(listOfProducts(prodData)) + " products can be bought for less than 201." );
System.out.println(printHash(costMore(prodData)));
///OVERLOADOLNI KELL A 'printList' FÜGGVÉNYT
}
private static HashMap costMore(HashMap<String, Integer> prodData) {
HashMap<String, Integer> strHash = new HashMap<>();
for (Map.Entry<String, Integer> entry : prodData.entrySet()) {
if (entry.getValue() > 150) {
strHash.put(entry.getKey() , entry.getValue());
}
}
return strHash;
}
private static ArrayList listOfProducts(HashMap<String, Integer> prodData) {
ArrayList<String> strArray = new ArrayList<>();
for (Map.Entry<String, Integer> entry : prodData.entrySet()) {
if (entry.getValue() < 201) {
strArray.add(entry.getKey());
}
}
return strArray;
}
private static String printList (ArrayList<String> strArray) {
String result = "";
for (String object : strArray) {
result += object + ", ";
}
return result;
}
private static String printHash (HashMap<String, Integer> strHash) {
String result = "Following products can be bought for more than 150 : \n";
for (Map.Entry<String, Integer> entry : strHash.entrySet()) {
result += entry.getKey() + " - " + entry.getValue() + "\n" ;
}
return result;
}
}
<file_sep>import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SquaredValue {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14);
List<Integer> squaredNumbers = numbers.parallelStream().map(n -> n*n).collect(Collectors.toList());
squaredNumbers.stream().forEach(System.out :: println);
}
}
<file_sep>import java.util.ArrayList;
public class ListIntroduction1 {
public static void main(String[] args) {
ArrayList<String> strArray = new ArrayList<>();
for ( String object : strArray
) {
System.out.print(object + ", ");
}
strArray.add("William");
System.out.println(strArray.isEmpty());
strArray.add("John");
strArray.add("Amanda");
System.out.println(strArray.size());
System.out.println(strArray.get(2));
for ( String object : strArray) { System.out.print(object + ", "); }
System.out.println();
for (int i = 0; i < strArray.size() ; i++) {
System.out.println((i+1) + ". " + strArray.get(i));
}
strArray.remove(1);
for (int i = strArray.size()-1; i >= 0 ; i--) {
System.out.println(strArray.get(i));
}
strArray.removeAll(strArray);
System.out.println(strArray.isEmpty());
}
}
<file_sep>import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class EncodedLines {
public static void main(String[] args) {
// Create a method that decrypts encoded-lines.txt
arrayListPrinter(readFileAndDecodeLines("encoded-lines.txt"));
}
private static void arrayListPrinter(ArrayList readFileAndDecodeLines) {
for (Object s: readFileAndDecodeLines) {
System.out.println(s);
}
}
private static ArrayList<Object> readFileAndDecodeLines(String s) {
String lines = "";
BufferedReader fileReader = null;
ArrayList<Object> stringSet = new ArrayList<>();
int shifted = 25;
try {
fileReader = new BufferedReader(new FileReader(s));
while ((lines = fileReader.readLine()) != null){
stringSet.add(characterExperimenter(lines, shifted));
}
}catch (Exception e){
System.out.println("something is wrong mate");
}
return stringSet;
}
private static StringBuffer characterExperimenter(String lines, int shifted) {
char space = ' ';
StringBuffer encrypter = new StringBuffer();
for (int j = 0; j < lines.length(); j++) {
if (Character.isUpperCase(lines.charAt(j))){
char ch = (char)(((int)lines.charAt(j) + shifted - 65) %26 + 65);
encrypter.append(ch);
} else if (lines.charAt(j) == Character.valueOf(space)) {
encrypter.append(space);
} else {
char ch = (char)(((int)lines.charAt(j) + shifted - 97) %26 + 97);
encrypter.append(ch);
}
}
return encrypter;
}
}
<file_sep>rootProject.name = 'gfa'
<file_sep>package com.thereddit.reddit.repositories;
import com.thereddit.reddit.models.Post;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PageRepository extends PagingAndSortingRepository<Post, Integer> {
List<Post> findAllByVotes(Integer votes, Pageable pageable);
Page<Post> findAll(Pageable pageable);
}
<file_sep>import java.util.ArrayList;
import java.util.List;
public class Carrier {
int storeOfAmmo;
int healthPoint;
List<Aircraft> listOfAircraft = listInitializer();
public Carrier(){
}
public Carrier( int storeOfAmmo, int healthPoint){
this.storeOfAmmo = storeOfAmmo;
this.healthPoint = healthPoint;
}
private List<Aircraft> listInitializer() {
List<Aircraft> listOfAircraft = new ArrayList<>();
return listOfAircraft;
}
public void add(Aircraft aircraft) {
this.listOfAircraft.add(aircraft);
}
public void fill () {
int refillOutcome;
int sumNeededAmmo = 0;
for (Aircraft a : this.listOfAircraft) {
sumNeededAmmo += (a.maxAmmo - a.actAmmo);
}
try {
if ((sumNeededAmmo) <= this.storeOfAmmo) {
for (Aircraft a : this.listOfAircraft) {
this.storeOfAmmo = a.refill(this.storeOfAmmo);
}
} else {
for (Aircraft a : this.listOfAircraft) {
if(a.isPriority()){
if (this.storeOfAmmo > 0){
this.storeOfAmmo = a.refill(this.storeOfAmmo);
} else {
throw new ArithmeticException("no more ammo");
}
}
}
for (Aircraft a : this.listOfAircraft) {
if(!a.isPriority()){
if (this.storeOfAmmo > 0){
this.storeOfAmmo = a.refill(this.storeOfAmmo);
} else {
throw new ArithmeticException("no more ammo");
}
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
this.getStatus();
}
public void fight (Carrier carrier) {
int firePower = 0;
for (Aircraft a : this.listOfAircraft) {
firePower += (a.actAmmo * a.baseDamage);
}
carrier.healthPoint -= firePower;
if (carrier.healthPoint <= 0) {
System.out.println("It's dead Jim :(");
}
}
public void getStatus(){
int totalDamage = 0;
for (Aircraft a : listOfAircraft) {
totalDamage += (a.baseDamage * a.actAmmo);
}
System.out.println("HP: " + this.healthPoint + ", Aircraft count: " + this.listOfAircraft.size() + ", Ammo storage : " +
this.storeOfAmmo + ", Total damage : " + totalDamage );
System.out.println("Aircrafts : ");
for (Aircraft a : listOfAircraft) {
a.getStatus();
}
}
}
<file_sep>import java.util.ArrayList;
import java.util.List;
public class Armada {
List<Ship> listOfShips;
int skippedShips;
private List<Ship> armadaInitializer(int rnd) {
List<Ship> lOfS = new ArrayList<>();
for (int i = 0; i < rnd ; i++) {
lOfS.add(new Ship());
lOfS.get(i).fillShip();
}
return lOfS;
}
public Armada(){
listOfShips = armadaInitializer(rndGenerator(20));
}
private int rndGenerator (int r) {
int num = (int) (Math.random() * r) + 5;
return num;
}
public boolean war(Armada armada) {
int thisI = 0;
int armadaJ = 0;
int counter = 1;
while ((this.listOfShips.size() > this.skippedShips) && (armada.listOfShips.size() > armada.skippedShips)) {
Ship thisShip = this.listOfShips.get(thisI);
Ship armadaShip = armada.listOfShips.get(armadaJ);
System.out.println(" --------------------------------------------------------------------------------------------- ");
System.out.println(" BATTLE : " + counter++);
System.out.println(" --------------------------------------------------------------------------------------------- ");
displayShips(thisShip, armadaShip, thisI, armadaJ);
if (thisShip.battle(armadaShip)) {
armada.skippedShips ++;
armadaJ ++;
armadaShip.isSkipped = true;
thisShip.pourAnudder();
} else {
this.skippedShips ++;
thisI ++;
thisShip.isSkipped = true;
armadaShip.pourAnudder();
}
}
// int thisResult = this.listOfShips.size()-this.skippedShips;
// int armadaResult = armada.listOfShips.size() - armada.skippedShips;
return ((this.listOfShips.size()-this.skippedShips) > (armada.listOfShips.size() - armada.skippedShips));
}
private void displayShips(Ship thisShip, Ship armadaShip, int thisI, int armadaJ) {
System.out.println(" * *");
System.out.println(" * * * *");
System.out.println(" * * * * * *");
System.out.println(" * * * * * * * *");
System.out.println(" * *");
System.out.println(" * *");
System.out.println(" ******************** ********************");
System.out.println(" ****************** ******************");
System.out.println(" **************** ****************");
System.out.println();
System.out.println(" thisShip " + thisI + " VS " + " armadaShip " + armadaJ + " ");
System.out.println(" Consumed rum by captain : " + thisShip.listOfPirates.get(0).consumedRum + " " +
"Consumed rum by captain : " + armadaShip.listOfPirates.get(0).consumedRum);
System.out.println(" Captain passed out : " + thisShip.listOfPirates.get(0).passedOut + " " +
"Captain passed out : " + armadaShip.listOfPirates.get(0).passedOut);
System.out.println(" Is captain alive : " + thisShip.listOfPirates.get(0).alive + " " +
"Is captain alive : " + armadaShip.listOfPirates.get(0).alive);
System.out.println(" # of alive pirates : " + thisShip.activeGuyFinder() + " " +
"# of alive pirates : " + armadaShip.activeGuyFinder());
System.out.println(" # of P.O. pirates : " + thisShip.passedOutFinder() + " " +
"# of P.O. pirates : " + armadaShip.passedOutFinder());
System.out.println(" # of active pirates : " + thisShip.activeGuys + " " +
"# of active pirates : " + armadaShip.activeGuys);
System.out.println(" # of corps (dead) : " + thisShip.diedBodies + " " +
"# of corps (dead) : " + armadaShip.diedBodies);
System.out.println();
// System.out.println("----------------------------------------------------------------------------------------------------------------------");
}
}
<file_sep>package com.batmanapp.batman.repositories;
import com.batmanapp.batman.models.Criminal;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CriminalRepository extends CrudRepository<Criminal, Long> {
List<Criminal> findAll();
}
<file_sep>public class Cat extends Animal{
public Cat() {
this.healCost = rndGenerator();
}
@Override
public int rndGenerator() {
return (int)(Math.random() * 7);
}
}
<file_sep>import java.lang.reflect.Array;
import java.util.*;
public class Matchmaking {
public static void main(String[] args) {
ArrayList<String> girls = new ArrayList<String>(Arrays.asList("Eve","Ashley","Claire","Kat","Jane"));
ArrayList<String> boys = new ArrayList<String>(Arrays.asList("Joe","Fred","Tom","Todd","Neef","Jeff"));
System.out.println(makingMatches(girls, boys));
}
private static ArrayList makingMatches(ArrayList<String> girls, ArrayList<String> boys) {
for (int i = 0; i < boys.size(); i++) {
if (i != boys.size()-1) {
girls.add(i * 2 + 1, boys.get(i));
} else {
girls.add(boys.get(i));
}
}
return girls;
}
}
<file_sep>package com.batmanapp.batman.services;
import com.batmanapp.batman.models.Hero;
import com.batmanapp.batman.repositories.HeroRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HeroServiceImpl implements HeroService {
HeroRepository heroRepository;
@Autowired
public HeroServiceImpl(HeroRepository heroRepository) {
this.heroRepository = heroRepository;
}
@Override
public void saveHero(Hero hero) {
heroRepository.save(hero);
}
@Override
public Hero findHeroById(long id) {
return heroRepository.findHeroById(id);
}
@Override
public Hero findHeroBName(String name) {
return heroRepository.findHeroByUserName(name);
}
}
<file_sep>package com.todosagain.enhancedtodos.services;
import com.todosagain.enhancedtodos.models.Todo;
import com.todosagain.enhancedtodos.repositories.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class TodoServiceImpl implements TodoService {
TodoRepository todoRepository;
@Autowired
public TodoServiceImpl(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
@Override
public List<Todo> listTodos() {
return todoRepository.findAll();
}
@Override
public void saveTodo(Todo todo) {
todoRepository.save(todo);
}
@Override
public Todo findPostById(long id) {
Todo todo = todoRepository.findById(id);
return todo;
}
@Override
public Todo updateAssigneeId(long id) {
Todo todo = todoRepository.findById(id);
todo.setAssignee(null);
return todo;
}
@Override
public List<Todo> findByFilter(Date date, String filter) {
if (filter.equals("AfterThen")){
return todoRepository.findByDueDateAfter(date);
} else if(filter.equals("EarlierThen")) {
return todoRepository.findByDueDateBefore(date);
} else{
return todoRepository.findByDueDate(date);
}
}
@Override
public List<Todo> findTitle(String title) {
return todoRepository.findByTitle(title);
}
}
<file_sep>package com.greenfoxacademy.springstart.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class WebGreetCounterApp {
int counter = 0;
@GetMapping("web/greeting2")
// @ResponseBody
public String greeting2(@RequestParam(value = "name") String name,
Model model) {
counter += 1;
model.addAttribute("name", name);
model.addAttribute("counter", counter);
return "greeting2";
}
}
<file_sep>public class TwoNumbers {
public static void main (String[] args){
int osszeg, a, b;
a = 22;
b = 13;
System.out.println("22 + 13: " + (osszeg = a + b));
int kivonas, szorzat, osztI, osztM ;
double osztD;
System.out.println("22 - 13: " + (kivonas = a - b));
System.out.println("22 * 13: " + (szorzat = a * b));
System.out.println("22 / 13 'double' " + (osztD = a/b));
System.out.println("22 / 13 'int' " + (osztI = a/b));
System.out.println("22 / 13 'modulo' " + (osztM = a%b));
}
}
<file_sep>package com.weekshop.webshop.repositories;
import com.weekshop.webshop.models.ShopItem;
import java.util.ArrayList;
import java.util.List;
public class Store {
List<ShopItem> listOfItems;
public Store() {
this.listOfItems = new ArrayList<>();
this.createList();
}
public void createList() {
this.listOfItems.add(new ShopItem("Running shoes", "Clothes and shoes", "Nike running shoes for every day sport", 1000.0, 5));
this.listOfItems.add(new ShopItem("Printer", "Electronics", "Some HP printer that will print pages", 3000.0, 2));
this.listOfItems.add(new ShopItem("Coca cola", "Beverages and Snacks", "0.5 standard coke", 25.0, 0));
this.listOfItems.add(new ShopItem("Wokin", "Beverages and Snacks","Chicken with fried rice and WOKIN sauce", 119.0, 100));
this.listOfItems.add(new ShopItem("T-shirt", "Clothes and shoes","Blue with a corgi on a bike", 300.0, 1));
}
public void addItem(ShopItem shopItem) {
listOfItems.add(shopItem);
}
public List<ShopItem> getListOfItems() {
return listOfItems;
}
}
<file_sep>public class SubStr {
public static void main(String[] args) {
System.out.println(subStr("this is what I am searching in","searching"));
System.out.println(subStr("this is what I am searching in","not"));
}
public static int subStr(String s, String isIn) {
int theNum = 0;
String check = new String();
for (int i = 0; i < s.length() - isIn.length(); i++) {
check = s.substring(i, i + isIn.length() );
if (check.equals(isIn)) {
theNum = i-1;
break;
} else {
theNum = -1;
}
}
return theNum;
}
}
<file_sep>package com.logentries.logtask.repositories;
import com.logentries.logtask.models.Log;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface LogRepository extends CrudRepository<Log, Long> {
List<Log> findAll();
}
<file_sep>import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JoinChars {
public static void main(String[] args) {
List<Character> ch = Arrays.asList('a','B','c','D','e','F','g','H');
String r = ch
.stream()
.map(c -> c.toString())
.collect(Collectors.joining());
System.out.println(r);
}
}
<file_sep>package main.java.music;
public class Violin extends StringedInstrument {
public Violin() {
super("Violin", 4);
}
@Override
public void sound() {
System.out.println(this.name +", " + "a " + this.numberOfStrings + "-stringed instrument that goes " + "Screetch");
}
}
<file_sep>import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
class SumTest {
Sum testInst = new Sum();
ArrayList<Integer> intList = new ArrayList<>();;
@Test
void sumTester() {
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
intList.add(5);
int expected = 15;
assertEquals(expected, testInst.sum(intList));
}
@Test
void testCaseEmpty() {
int expected = 0;
assertEquals(expected, testInst.sum(intList));
}
@Test
void testCaseOne() {
intList.add(123);
int expected = intList.get(0);
assertEquals(expected, testInst.sum(intList));
}
@Test
void testCaseMultiple() {
intList.add(123);
intList.add(123);
intList.add(123);
int result = 0;
for (int i = 0; i < intList.size(); i++) {
result += intList.get(i);
}
int expected = result;
assertEquals(expected, testInst.sum(intList));
}
@Test
void testCaseNull() {
intList = null;
// assertEquals(-1, testInst.sum(intList));
assertThrows(NullPointerException.class,()->{testInst.sum(intList);});
}
}<file_sep>import java.util.Scanner;
public class HelloUser {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Gazdám! Kérlek add meg a neved!");
String nev;
nev = input.nextLine();
System.out.println("Hello, " + nev + " !");
}
}
<file_sep>public class Main {
public static void main(String[] args) {
Carrier carrier1 = new Carrier(10, 6000);
Carrier carrier2 = new Carrier(10, 1000);
carrier1.add(new F16());
carrier1.add(new F16());
carrier1.add(new F16());
carrier1.add(new F35());
carrier1.add(new F35());
carrier1.add(new F35());
carrier2.add(new F35());
carrier2.add(new F16());
carrier2.add(new F35());
carrier2.add(new F16());
carrier2.add(new F35());
carrier1.fill();
carrier2.fill();
carrier1.fight(carrier2);
}
}
<file_sep>import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class Frequency {
public static void main(String[] args) {
String s = "fbadjfjbvjhfbjfbfjgajjbfajfbakjfjkagfhajfjabvjfavhjbjkafvkjhbfavbkjfbjkagjk";
// Set<Map.Entry<String, Integer>> entries = Arrays.stream(s.split("")).map(ch ->)
System.out.println(Arrays.asList(s.split("")).stream().collect(Collectors.groupingBy(ch -> ch, Collectors.counting())));
}
}
<file_sep>public class Domino implements Comparable {
private final int left;
private final int right;
public Domino(int left, int right) {
this.left = left;
this.right = right;
}
public int getLeftSide() {
return left;
}
public int getRightSide() {
return right;
}
@Override
public String toString() {
return "[" + left + ", " + right + "]";
}
@Override
public int compareTo(Object o) {
Domino otherDomino = (Domino) o;
if (this.left - otherDomino.left != 0) {
return this.left - otherDomino.left;
} else {
return otherDomino.left - this.left;
}
}
}<file_sep>public class Main {
public static void main(String[] args) {
AnimalShelter animalShelter = new AnimalShelter();
Cat cat = new Cat();
Dog dog = new Dog();
Parrot parrot = new Parrot();
animalShelter.rescue(cat);
animalShelter.rescue(dog);
animalShelter.rescue(parrot);
animalShelter.addAdopter("Gary");
animalShelter.addAdopter("Johnny");
animalShelter.addAdopter("Jerry");
System.out.println(animalShelter.toString());
animalShelter.heal();
animalShelter.findNewOwner();
System.out.println(animalShelter.toString());
}
}
<file_sep>package main.java.music;
public abstract class Instrument {
String name;
public Instrument(){}
public Instrument(String name) {
this.name = name;
}
abstract public void play();
}
<file_sep>import java.lang.Math;
public class VariableMutation {
public static void main(String[] args) {
int a = 3 + 8;
System.out.println(a);
int b = 100 - 94;
System.out.println(b);
int c = 44 * 2;
System.out.println(c);
int d = 125 / 5;
System.out.println(d);
int e = 8 ^ 2;
System.out.println(e);
int f1 = 123;
int f2 = 345;
boolean measure1 = f1 > f2;
System.out.println(measure1);
// tell if f1 is bigger than f2 (print as a boolean)
int g1 = 350;
int g2 = 200;
boolean m2 = (g2*2) > g1;
System.out.println(m2);
// tell if the double of g2 is bigger than g1 (print as a boolean)
int h = 135798745;
boolean m3 = (h % 11) < 1;
System.out.println(m3);
// tell if it has 11 as a divisor (print as a boolean)
int i1 = 10;
int i2 = 3;
boolean m4 = (i2^2) < i1 && i2 < Math.pow((int)i2, 2) ;
// tell if i1 is higher than i2 squared and smaller than i2 cubed (print as a boolean)
System.out.println(m4);
int j = 1521;
boolean m5 = (j%3) < 1 || (j%3) < 1;
System.out.println(m5);
// tell if j is dividable by 3 or 5 (print as a boolean)
}
}<file_sep>package com.jwtexample.helloworld.controllers;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("/hello")
public String firstPage(Authentication authentication) {
return "Hello " + authentication.getName();
}
}
<file_sep>rootProject.name = 'tablesandforms'
<file_sep>package com.springadvanced.tokenaut.services;
import org.springframework.http.ResponseEntity;
public interface UserListsRESTService {
ResponseEntity getListsOfUsers();
}
<file_sep>import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TicTacToe {
public static void main(String[] args) {
// Write a function that takes a filename as a parameter
// The file contains an ended Tic-Tac-Toe match
// We have provided you some example files (draw.txt, win-x.txt, win-o.txt)
// Return "X", "O" or "Draw" based on the input file
System.out.println(ticTacResult("win-o.txt"));
// Should print "O"
System.out.println(ticTacResult("win-x.txt"));
// Should print "X"
System.out.println(ticTacResult("draw.txt"));
// Should print "Draw"
}
private static String ticTacResult(String s) {
String result;
if (columnDecider(arrayFiller(s)) != '-'){
result = "";
result += "The winner of " + s + " is the player with '" + columnDecider(arrayFiller(s)) + "'";
return result;
} else if (rowDecider(arrayFiller(s)) != '-'){
result = "";
result += "The winner of " + s + " is the player with '" + rowDecider(arrayFiller(s)) + "'";
return result;
}else if (diagonalDecider(arrayFiller(s)) != '-'){
result = "";
result += "The winner of " + s + " is the player with '" + diagonalDecider(arrayFiller(s)) + "'";
return result;
}
else {
result = "";
result += "The game of " + s + " has no winner [draw]";
return result;
}
}
private static Character diagonalDecider (Character [][] charArray) {
int k = 0;
Character[] chArr = new Character[3];
for (int i = 0; i < charArray.length; i++) {
chArr[i] = charArray[i][i];
}
if ((chArr[k] == chArr[k + 1]) && (chArr[k] == chArr[k + 2])) {
return chArr[k];
}
k=0;
for (int i = charArray.length-1; i >= 0; i--) {
chArr[i] = charArray[k][i];
// chArr[i] = charArray[0][2];
// chArr[i] = charArray[1][1];
// chArr[i] = charArray[2][0];
k++;
}
if ((chArr[k-1] == chArr[k - 2]) && (chArr[k-1] == chArr[k - 3])) {
return chArr[k-1];
}
return '-';
}
private static Character rowDecider (Character [][] charArray) {
int k = 0;
Character[] chArr= new Character[3];
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray.length; j++) {
chArr[j] = charArray[i][j];
}
if ((chArr[k] == chArr[k+1]) && (chArr[k] == chArr[k+2]) ){
return chArr[k];
}
}
return '-';
}
private static Character columnDecider (Character [][] charArray) {
int k = 0;
Character[] chArr= new Character[3];
for (int i = 0; i < charArray.length; i++) {
for (int j = 0; j < charArray.length; j++) {
chArr[j] = charArray[j][i];
}
if ((chArr[k].equals(chArr[k+1]) ) && (chArr[k].equals(chArr[k+2]) ) ){
return chArr[i];
}
}
return '-';
}
private static Character[][] arrayFiller(String inputTxt) {
int counter = -1;
Character [][] container = new Character[3][3];
try {
BufferedReader inp = new BufferedReader(new FileReader(inputTxt));
String lineCheck;
while ((lineCheck = inp.readLine()) != null){
counter++;
container[counter][0] = lineCheck.charAt(0);
container[counter][1] = lineCheck.charAt(1);
container[counter][2] = lineCheck.charAt(2);
}
} catch (Exception e) {
}
return container;
}
private static void arrayPrinter (Character [][] textToCharArray) {
for (int i = 0; i < textToCharArray.length; i++) {
for (int j = 0; j < textToCharArray.length; j++) {
System.out.print(textToCharArray[i][j] + " ");
}
System.out.println();
}
}
}
<file_sep>import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ShoppingList2 {
public static void main(String[] args) {
HashMap<String, Double> prodPrices = new HashMap<>();
HashMap<String, Integer> shoppingBob = new HashMap<>();
HashMap<String, Integer> shoppingAlice = new HashMap<>();
prodPrices.put("Milk" , 1.07);
prodPrices.put("Rice" , 1.59);
prodPrices.put("Eggs" , 3.14);
prodPrices.put("Cheese" , 12.60);
prodPrices.put("Chicken Breasts" , 9.40);
prodPrices.put("Apples" , 2.31);
prodPrices.put("Tomato" , 2.58);
prodPrices.put("Potato" , 1.75);
prodPrices.put("Onion" , 1.10);
shoppingBob.put("Milk" , 3);
shoppingBob.put("Rice" , 2);
shoppingBob.put("Eggs" , 2);
shoppingBob.put("Cheese" , 1);
shoppingBob.put("Chicken Breasts" , 4);
shoppingBob.put("Apples" , 1);
shoppingBob.put("Tomato" , 2);
shoppingBob.put("Potato" , 1);
shoppingAlice.put("Rice" , 1);
shoppingAlice.put("Eggs" , 5);
shoppingAlice.put("Chicken Breasts" , 2);
shoppingAlice.put("Apples" , 1);
shoppingAlice.put("Tomato" , 10);
String pRice = "Rice";
String pPotato = "Potato";
System.out.println("Bob pays : " + sumCalculator(totalPaymentCalculator(shoppingBob, prodPrices)));
System.out.println("Alice pays : " + sumCalculator(totalPaymentCalculator(shoppingAlice, prodPrices)));
System.out.println(productDecider(shoppingBob,shoppingAlice,pRice));
System.out.println(productDecider(shoppingBob,shoppingAlice,pPotato ));
System.out.println( whoBoughtMoreDiffProd(shoppingBob, shoppingAlice) + " has bought more different products.");
System.out.println(whoBuysMorePieces(shoppingBob,shoppingAlice) + " buys more product");
}
private static String whoBuysMorePieces(HashMap<String, Integer> shoppingBob, HashMap<String, Integer> shoppingAlice) {
if (sumPieces(shoppingBob) > sumPieces(shoppingAlice)){
return "Bob (" + sumPieces(shoppingBob) + " pc)";
}
return "Alice (" + sumPieces(shoppingAlice) + " pc)";
}
private static int sumPieces (HashMap<String, Integer> shoppingArray){
int sum = 0;
for (Map.Entry<String, Integer> entry : shoppingArray.entrySet()) {
sum += entry.getValue();
}
return sum;
}
private static String productDecider(HashMap<String, Integer> shoppingBob, HashMap<String, Integer> shoppingAlice, String pType) {
if(shoppingBob.containsKey(pType) && shoppingAlice.containsKey(pType) ){
if (shoppingBob.get(pType) > shoppingAlice.get(pType)){
return "Bob has bought more " + pType + " product.";
} else {
return "Alice has bought more " + pType + " product.";
}
}
return "Only Bob has " + pType + " product.";
}
private static ArrayList totalPaymentCalculator(HashMap<String, Integer> shoppingArray, HashMap<String, Double> prodPrices) {
ArrayList<Double> multiplArr = new ArrayList<>();
for (Map.Entry<String, Integer> entry : shoppingArray.entrySet()) {
multiplArr.add((prodPrices.get(entry.getKey()))*(entry.getValue()));
}
return multiplArr;
}
private static double sumCalculator(ArrayList<Double> multiplArray){
double sum = 0;
for (Double obj: multiplArray) {
sum +=obj;
}
return sum;
}
private static String whoBoughtMoreDiffProd(HashMap<String, Integer> shoppingBob, HashMap<String, Integer> shoppingAlice){
if ((diffCalculator(shoppingBob,shoppingAlice,true)) > (diffCalculator(shoppingBob,shoppingAlice,false)) ) {
return "Bob";
}
return "Alice";
}
private static int diffCalculator (HashMap<String, Integer> shoppingBob, HashMap<String, Integer> shoppingAlice, boolean isBob) {
int num = 0;
if (isBob) {
for (Map.Entry<String, Integer> entry : shoppingAlice.entrySet()) {
if (!(shoppingBob.containsKey(entry.getKey()))) {
}
num += entry.getValue();
}
} else {
for (Map.Entry<String, Integer> entry : shoppingBob.entrySet()) {
if (!(shoppingAlice.containsKey(entry.getKey()))) {
}
num += entry.getValue();
}
}
return num;
}
}
<file_sep>public class Gnirts implements CharSequence {
String s;
public Gnirts(String s){
this.s = s;
}
@Override
public int length() {
return this.s.length();
}
@Override
public char charAt(int index) {
return this.s.charAt(this.length()-(index+1));
}
@Override
public CharSequence subSequence(int start, int end) {
return this.s.substring( s.length()-end, s.length()-start);
}
}
<file_sep>package com.listingtotods.listtodos.repositories;
import com.listingtotods.listtodos.models.Todo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TodoRepository extends CrudRepository<Todo, Long> {
List<Todo> findAll();
}
<file_sep>import static org.junit.jupiter.api.Assertions.*;
class CowsAndBullsTest {
}<file_sep>package com.foxclub.foxclub.models;
import java.util.ArrayList;
import java.util.List;
public class Fox extends Pet {
public Fox() {
}
public Fox(String name) {
super(name);
}
public Fox(String name, String food, String drink) {
super(name, food, drink);
}
}
<file_sep>package com.todosagain.enhancedtodos.services;
import com.todosagain.enhancedtodos.models.Assignee;
import com.todosagain.enhancedtodos.models.Todo;
import com.todosagain.enhancedtodos.repositories.AssigneeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AssigneeServiceImpl implements AssigneeService {
AssigneeRepository assigneeRepository;
@Autowired
public AssigneeServiceImpl(AssigneeRepository assigneeRepository) {
this.assigneeRepository = assigneeRepository;
}
@Override
public List<Assignee> listAssignees() {
return assigneeRepository.findAll();
}
@Override
public Assignee findAssigneeByName(String name) {
return assigneeRepository.findByName(name);
}
@Override
public Assignee instansiateAssignee(String name, String email, String password) {
return new Assignee(name, email, password);
}
@Override
public void saveAssignee(Assignee assignee) {
assigneeRepository.save(assignee);
}
@Override
public boolean validatePassword(String password, String userName) {
if (assigneeRepository.findByName(userName).getPassword().equals(password)){
return true;
}
return false;
}
@Override
public void deletePostFromList(long id, String userName) {
Assignee assignee = findAssigneeByName(userName);
List<Todo> temporaryList = assignee.getListOfTodos();
int idx = 0;
for (int i = 0; i < temporaryList.size(); i++) {
idx++;
if (temporaryList.get(i).getId() == id) {
assigneeRepository.save(assignee.removeFromList(idx));
}
}
}
}
<file_sep>import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FibonacciTest {
Fibonacci fib = new Fibonacci();
@Test
void num() {
assertEquals(1, fib.numFib(2));
assertEquals(2, fib.numFib(3));
assertEquals(21, fib.numFib(8));
}
}<file_sep>package main.java.animals;
public abstract class Animal {
String name;
int age;
String gender;
int legs;
public Animal(String name){
this.name = name;
}
public Animal(String name, int age, String gender, int legs) {
this.name = name;
this.age = age;
this.gender = gender;
this.legs = legs;
}
public abstract String getName();
public abstract String breed();
public abstract int getLegs();
}
<file_sep>rootProject.name = 'enhancedtodos'
<file_sep>package com.springadvanced.tokenaut.controllers;
import com.springadvanced.tokenaut.services.UserListsRESTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ListRESTController {
private UserListsRESTService userListsRESTService;
@Autowired
public ListRESTController(UserListsRESTService userListsRESTService) {
this.userListsRESTService = userListsRESTService;
}
@GetMapping("/getLists")
public ResponseEntity getUserListsByFilmID() {
return ResponseEntity.status(200).body(userListsRESTService.getListsOfUsers());
}
}
<file_sep>rootProject.name = 'tokenaut'
<file_sep>package com.batmanapp.batman.controllers;
import com.batmanapp.batman.models.Hero;
import com.batmanapp.batman.services.CriminalService;
import com.batmanapp.batman.services.CriminalServiceImpl;
import com.batmanapp.batman.services.HeroService;
import com.batmanapp.batman.services.HeroServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class LoginController {
HeroService heroService;
CriminalService criminalService;
@Autowired
public LoginController(HeroService heroService, CriminalService criminalService) {
this.heroService = heroService;
this.criminalService = criminalService;
}
@GetMapping("/login")
public String getLoginPage() {
return "login";
}
@PostMapping("/login")
public String performLogIn(@RequestParam(name = "userName", required = false) String userName,
@RequestParam(value = "password", required = false) String password) {
if (userName != null && password != null) {
Hero hero = new Hero(userName, password);
heroService.saveHero(hero);
return "redirect:/main?id=" + heroService.findHeroById(heroService.findHeroBName(userName).getId()).getId();
} else {
return "login";
}
}
}
<file_sep>package com.bankofsimba.simbabank;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SimbabankApplication {
public static void main(String[] args) {
SpringApplication.run(SimbabankApplication.class, args);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Births {
public static void main(String[] args) {
// Create a function that
// - takes the name of a CSV file as a parameter,
// - every row is in the following format: <person name>;<birthdate in YYYY-MM-DD format>;<city name>
// - returns the year when the most births happened.
// - if there were multiple years with the same number of births then return any one of them
// You can find such a CSV file in this directory named births.csv
// If you pass "births.csv" to your function, then the result should be either 2006, or 2016.
System.out.println(yearOfMostBirthsFunction("births.csv"));
}
private static String yearOfMostBirthsFunction(String s) {
BufferedReader inputFile = null;
String fileLines = "";
String separatedBy = ";";
HashMap<String, Integer> birthDatesCounter = new HashMap<>();
int birthDate = 0;
try {
inputFile = new BufferedReader(new FileReader(s));
while ((fileLines = inputFile.readLine()) != null) {
String[] births = fileLines.split(separatedBy);
//if e.g. '1960' exist do this, else do that
if ((birthDatesCounter.containsKey(births[1].substring(0, 4)))) {
birthDate = birthDatesCounter.get(births[1].substring(0, 4)) + 1;
birthDatesCounter.replace(births[1].substring(0, 4), birthDate);
} else {
birthDatesCounter.put(births[1].substring(0, 4), 1);
}
}
} catch (Exception e) {
}
return hashIterator(birthDatesCounter);
}
private static String hashIterator(HashMap <String, Integer> birthDatesCounter) {
int val = 0;
String result = "";
for (Map.Entry<String, Integer> entry : birthDatesCounter.entrySet()) {
if((entry.getValue()) > val) {
val = entry.getValue();
result = entry.getKey();
}
}
return result;
}
}<file_sep>public class Doubled {
public static void main(String[] args) {
// Create a method that decrypts the duplicated-chars.txt
}
}
<file_sep>package com.hellobeanworld.hellobean.services;
import org.springframework.stereotype.Service;
@Service
public class RedColor implements MyColor {
@Override
public String printColor() {
return getClass().getName().toString();
}
}
<file_sep>package com.springadvanced.tokenaut.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
@Entity
@Table(name = "resultDTOs")
public class ResultDTO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String original_language;
private String title;
@ManyToOne
@JsonIgnore
private MovieDataDTO movieDataDTO;
public ResultDTO() {
}
public ResultDTO(String original_language, String title) {
this.original_language = original_language;
this.title = title;
}
public ResultDTO(String original_language, String title, MovieDataDTO movieDataDTO) {
this.original_language = original_language;
this.title = title;
this.movieDataDTO = movieDataDTO;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOriginal_language() {
return original_language;
}
public void setOriginal_language(String original_language) {
this.original_language = original_language;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public MovieDataDTO getMovieDataDTO() {
return movieDataDTO;
}
public void setMovieDataDTO(MovieDataDTO movieDataDTO) {
this.movieDataDTO = movieDataDTO;
}
}
<file_sep>import java.lang.reflect.Array;
import java.util.ArrayList;
public class Sum {
public int sum (ArrayList<Integer> intList) {
int sum = 0;
// try {
if (intList != null) {
for (int i = 0; i < intList.size(); i++) {
sum += intList.get(i);
}
} else {
throw new NullPointerException("fucking null point excepton dude :) ");
}
// catch (Exception e) {
// System.out.println(e.getMessage());
//
// }
return -1;
}
}
<file_sep>package com.thereddit.reddit.controllers;
import com.thereddit.reddit.models.Post;
import com.thereddit.reddit.services.PostService;
import com.thereddit.reddit.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class PostController {
PostService postService;
UserService userService;
@Autowired
public PostController(PostService postService, UserService userService) {
this.postService = postService;
this.userService = userService;
}
@RequestMapping("")
public String displayMainPage(Model model) {
model.addAttribute("list", postService.listFirstTenPages());
return "redirect:/reddit";
}
@RequestMapping("/reddit")
public String displayReddit(Model model,
@RequestParam(value = "userName", required = false) String userName) {
model.addAttribute("list", postService.listFirstTenPages());
try{
model.addAttribute("user", userService.findUser(userName));
return "index2";
} catch(Exception e){
return "index";
}
}
//: error ALERT should be created
@RequestMapping("/submit/{userName}")
public String displaySubmitPage(@PathVariable String userName,
Model model) {
try {
model.addAttribute("user", userService.findUser(userName));
} catch (Exception e) {
e.printStackTrace();
}
return "submit";
}
//: error ALERT should be created
@PostMapping("/submit/{userName}")
public String submitNewPost(@RequestParam("title") String title,
@RequestParam("url") String url,
@PathVariable String userName) {
try {
postService.saveNewPost(postService.createPost(title, url, userService.findUser(userName)));
userService.saveUser(userService.findUser(userName));
return "redirect:/reddit" + "?userName=" + userName ;
} catch (Exception e) {
e.printStackTrace();
}
return "submit";
}
@GetMapping("/{id}/delete")
public String deletePost(@PathVariable long id,
@RequestParam("userName") String userName){
postService.deletePost(id);
return "redirect:/reddit" + "?userName=" + userName;
}
@GetMapping("/{id}/{userName}/modify")
public String increment(@PathVariable long id,
@PathVariable String userName,
@RequestParam(value = "modifier") String modifier) {
postService.modifyPostVoteById(id, modifier);
return "redirect:/reddit" + "?userName=" + userName ;
}
@GetMapping("/login")
public String showLogin() {
return "login";
}
@PostMapping("/login")
public String loginTo(Model model,
@RequestParam("userName") String userName,
@RequestParam("password") String password) {
try {
userService.loginUser(password, userName);
return "redirect:/reddit?userName=" + userName;
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/login";
}
@GetMapping("/signup")
public String getSignUp(Model model) {
return "signupPage";
}
//: error ALERT should be created
//: TRY CATCH REFACTOR REQUIRED
//: use @ModelAttribute instead of many @RequestParam
@PostMapping("/signup")
public String signUpTo(Model model,
@RequestParam("userName") String userName,
@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("password") String password,
@RequestParam("rePassword") String repassword) throws Exception {
if(password.equals(repassword) && userService.findUser(userName) == null){
userService.saveUser(userService.instanciateUser(userName, firstName, lastName, password));
return "redirect:/reddit?userName=" + userName;
}else if(password.equals(repassword) && userService.findUser(userName) != null) {
model.addAttribute("nonsuccess", true);
return "signupPage";
}
if (!password.equals(repassword)){
model.addAttribute("nonmatch", true);
return "signupPage";
}
return "";
}
}
<file_sep>package com.foxclub.foxclub.services;
import com.foxclub.foxclub.models.Pet;
import com.foxclub.foxclub.models.Trick;
import com.foxclub.foxclub.repositories.TrickStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TrickServiceImpl implements TrickService {
TrickStore trickStore;
@Autowired
public TrickServiceImpl(TrickStore trickStore) {
this.trickStore = trickStore;
}
@Override
public List<Trick> getAllTricks() {
return trickStore.getAllTricks();
}
@Override
public void saveNewTrick(String trick) {
trickStore.addTrick(new Trick(trick));
}
@Override
public List<Trick> getUnknownTricks(Pet pet) {
List<Trick> unknownTricks = new ArrayList<>();
for (Trick t: trickStore.getAllTricks()) {
if (!pet.isTrickAlreadyKnown(t)) {
unknownTricks.add(t);
}
}
return unknownTricks;
}
}
<file_sep>import java.lang.reflect.Array;
import java.util.*;
public class StudentConter {
public static void main(String... args) {
List<Map<String, Object>> listOfMaps = new ArrayList<>();
Map<String, Object> row0 = new HashMap<>();
row0.put("name", "Theodor");
row0.put("age", 9.5);
row0.put("candies", 2);
listOfMaps.add(row0);
Map<String, Object> row1 = new HashMap<>();
row1.put("name", "Paul");
row1.put("age", 10);
row1.put("candies", 1);
listOfMaps.add(row1);
Map<String, Object> row2 = new HashMap<>();
row2.put("name", "Mark");
row2.put("age", 7);
row2.put("candies", 3);
listOfMaps.add(row2);
Map<String, Object> row3 = new HashMap<>();
row3.put("name", "Peter");
row3.put("age", 12);
row3.put("candies", 5);
listOfMaps.add(row3);
Map<String, Object> row4 = new HashMap<>();
row4.put("name", "Olaf");
row4.put("age", 12);
row4.put("candies", 7);
listOfMaps.add(row4);
Map<String, Object> row5 = new HashMap<>();
row5.put("name", "George");
row5.put("age", 3);
row5.put("candies", 2);
listOfMaps.add(row5);
// Display the following things:
// - The names of students who have more than 4 candies
// - The sum of the age of people who have less than 5 candies
System.out.println(moreThanFiveCandies(listOfMaps));
// System.out.println(sumHasLessCandies(listOfMaps));
}
// private static int sumHasLessCandies(List<Map<String, Object>> listOfMaps) {
// }
private static ArrayList moreThanFiveCandies(List<Map<String, Object>> listOfMaps) {
String holder = new String();
ArrayList<Object> finalList = new ArrayList<>();
for (Map<String, Object> lis : listOfMaps) {
for (Map.Entry<String, Object> entry : lis.entrySet() ) {
if (entry.getKey().equals("name")) {
holder = entry.getValue().toString();
} else if (entry.getKey().equals("candies") && (int)entry.getValue() > 4) {
finalList.add(holder);
holder = "";
}
}
}
return finalList;
}
}<file_sep>package com.foxclub.foxclub.services;
import com.foxclub.foxclub.models.Drink;
import com.foxclub.foxclub.models.Food;
import com.foxclub.foxclub.repositories.NutritionStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class NutritionServiceImpl implements NutritionService {
NutritionStore nutritionStore;
@Autowired
public NutritionServiceImpl(NutritionStore nutritionStore) {
this.nutritionStore = nutritionStore;
}
@Override
public List<Food> getAllFood() {
return nutritionStore.getListOfFoods();
}
@Override
public List<Drink> getAllDrinks() {
return nutritionStore.getListOfdrinks();
}
@Override
public void saveFoodToList(String name) {
nutritionStore.addFood(new Food(name));
}
@Override
public void saveDrinkToList(String name) {
nutritionStore.addDrink(new Drink(name));
}
}
<file_sep>import java.util.Arrays;
import java.util.Collections;
public class Reverse {
public static void main(String[] args) {
Integer[] aj = {3,4,5,6,7};
//Arrays.sort(aj, Collections.reverseOrder());
for (int i = 0; i < aj.length -1; i++) {
for (int j = 0; j < aj.length -i -1; j++) {
if (aj[j] < aj[j+1]){
int temp = aj[j];
aj[j] = aj[j+1];
aj[j+1] = temp;
}
}
}
for (int i = 0; i < aj.length; i++) {
System.out.print(aj[i] + ", ");
}
}
}
<file_sep>package com.rest.practice.controllers;
import com.rest.practice.models.MyError;
import com.rest.practice.models.Operation;
import com.rest.practice.models.OperationDTO;
import com.rest.practice.models.OperationDoubleDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PostController {
@PostMapping("/arrays")
public ResponseEntity whatToDoNumbers(@RequestBody(required = false) Operation newOperation) {
if (newOperation != null) {
Operation operation = new Operation(newOperation);
if (operation.getWhat().equals("sum")) {
OperationDTO operationDTO = new OperationDTO(operation.sumNumbers());
return ResponseEntity.status(200).body(operationDTO);
} else if (operation.getWhat().equals("multiply")) {
OperationDTO operationDTO = new OperationDTO(operation.multiplyNumbers());
return ResponseEntity.status(200).body(operationDTO);
} else if (operation.getWhat().equals("double")) {
OperationDoubleDTO operationDoubleDTO = new OperationDoubleDTO(operation.doubleNumbers());
return ResponseEntity.status(200).body(operationDoubleDTO);
} else {
MyError e = new MyError("Please provide what to do with the numbers!");
return ResponseEntity.status(400).body(e);
}
} else {
MyError e = new MyError("Please provide what to do with the numbers!");
return ResponseEntity.status(400).body(e);
}
}
}
<file_sep>package com.thereddit.reddit.services;
import com.thereddit.reddit.models.Post;
import com.thereddit.reddit.models.User;
import org.springframework.data.domain.Page;
import java.util.List;
public interface PostService {
List<Post> findAllPosts();
void saveNewPost(Post post);
void deletePost(long id);
Post findPostById(long id);
Post modifyPostVoteById(long id, String modifier);
Page<Post> listFirstTenPages();
Post createPost(String title, String url, User user) throws Exception;
}
<file_sep>rootProject.name = 'simbabank'
<file_sep>import java.util.Scanner;
public class DrawDiamond {
public static void main (String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("Please let me have an integer : ");
int num = userInput.nextInt();
//int median = Math.round(num/2);
int left = num;
int right = num;
for (int i = 1; i <= ((2*num)-1); i++) {
if (i > num){
left++;
right--;
} else if (i != 1 && i <= num){
left--;
right++;
}
for (int j = 1; j <= (2 * num); j++) {
if (j == num || (j >= left && j < num) || ((num < j) && (j <= right))) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}<file_sep>import java.util.HashMap;
import java.util.Map;
public class ProductDatabase {
public static void main(String[] args) {
HashMap<String, Integer> prodData = new HashMap<>();
prodData.put("Eggs" , 200);
prodData.put("Milk" , 200);
prodData.put("Fish" , 400);
prodData.put("Apples" , 150);
prodData.put("Bread" , 50);
prodData.put("Chicken" , 550);
System.out.println("The fish costs " + prodData.get("Fish"));
System.out.println("The most expensive product is " + expProd(prodData));
System.out.println("The average price is : " + avgProd(prodData));
System.out.println(under300(prodData) + " produts are below 300");
System.out.println("There is " + is125(prodData) + " product for 125");
System.out.println("The cheapest product is : " + cheapProd(prodData) );
}
private static String cheapProd(HashMap<String, Integer> prodData) {
int price = 550;
String chpProd = "";
for (Map.Entry <String, Integer> entry : prodData.entrySet()) {
if(entry.getValue() < price ) {
chpProd = entry.getKey();
}
}
return chpProd;
}
private static int is125(HashMap<String, Integer> prodData) {
int pc = 0;
for (Map.Entry<String, Integer> entry : prodData.entrySet()) {
if(entry.getValue() == 125) {
pc++;
}
}
return pc;
}
private static int under300(HashMap<String, Integer> prodData) {
int pc = 0;
for (Map.Entry<String, Integer> entry : prodData.entrySet()) {
if (entry.getValue() < 300 ) {
pc++;
}
}
return pc;
}
private static double avgProd(HashMap<String, Integer> prodData) {
int sum = 0;
double avg = (sumProd(prodData)) / (prodData.size());
return avg;
}
private static String expProd(HashMap<String, Integer> prodData) {
int price = 0;
String expKey = "";
for (Map.Entry<String, Integer> entry : prodData.entrySet()) {
if (entry.getValue() > price) {
price = entry.getValue();
expKey = entry.getKey();
}
}
return expKey;
}
private static int sumProd(HashMap<String, Integer> prodData) {
int sum = 0;
for (Map.Entry<String, Integer> entry : prodData.entrySet()) {
sum += entry.getValue();
}
return sum;
}
}
<file_sep>package com.batmanapp.batman.services;
import com.batmanapp.batman.models.Hero;
public interface HeroService {
void saveHero(Hero hero);
Hero findHeroById(long id);
Hero findHeroBName(String name);
}
<file_sep>package com.batmanapp.batman.models;
import javax.persistence.*;
@Entity
@Table(name = "criminals")
public class Criminal {
@Id
@GeneratedValue
private long id;
private String name;
private String crime;
@ManyToOne
private Hero hero;
public Criminal() {
}
public Criminal(String name, String crime, Hero hero) {
this.name = name;
this.crime = crime;
this.hero = hero;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCrime() {
return crime;
}
public void setCrime(String crime) {
this.crime = crime;
}
public Hero getHero() {
return hero;
}
public void setHero(Hero hero) {
this.hero = hero;
}
}
<file_sep>package Blog;
import java.util.ArrayList;
import java.util.List;
public class Blog {
List<BlogPost> listOfBlogPosts = listInitializer();
public void delete(int x) {
listOfBlogPosts.remove(x);
}
public void update(int x, BlogPost blogPost) {
listOfBlogPosts.set(x,blogPost);
}
private List<BlogPost> listInitializer() {
List<BlogPost> listOfBlogPosts = new ArrayList<>();
for (int i = 0; i < 10; i++) {
listOfBlogPosts.add(new BlogPost());
}
return listOfBlogPosts;
}
}
<file_sep>package com.jwtexample.helloworld.models;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name="assignees")
public class Assignee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String password;
public Assignee() {
}
public Assignee(String name, String password) {
this.name = name;
this.password = password;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
<file_sep>package com.batmanapp.batman.services;
import com.batmanapp.batman.repositories.CriminalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CriminalServiceImpl implements CriminalService {
CriminalRepository criminalRepository;
@Autowired
public CriminalServiceImpl(CriminalRepository criminalRepository) {
this.criminalRepository = criminalRepository;
}
}
<file_sep>package com.springadvanced.tokenaut.controllers;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.springadvanced.tokenaut.models.MovieData;
import com.springadvanced.tokenaut.models.MovieDataDTO;
import com.springadvanced.tokenaut.models.ResultDTO;
import com.springadvanced.tokenaut.services.GetPopularService;
import com.springadvanced.tokenaut.services.OnGetMoviesCallback;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@RestController
public class GetPopularRESTController {
private GetPopularService getPopularService;
@Autowired
public GetPopularRESTController(GetPopularService getPopularService) {
this.getPopularService = getPopularService;
}
@GetMapping("/savePopular")
public ResponseEntity getMovieResults() throws Exception {
HttpResponse<JsonNode> response = Unirest.get("https://api.themoviedb.org/3/movie/popular?api_key=a25142144b710e88d0a5d2d95e61048d")
.asJson();
JSONObject myObj = response.getBody().getObject();
MovieData movieData = new Gson().fromJson(myObj.toString(), MovieData.class);
// movieData results listáját ki kell venni és úgy tudja elmenteni
// getPopularService.saveMovieData(movieData);
MovieDataDTO movieDataDTO = new MovieDataDTO(movieData);
for (int i = 0; i < movieData.getResults().size() ; i++) {
getPopularService.saveMovieResultList(movieData.getResults().get(i));
ResultDTO resultDTO = new ResultDTO(movieData.getResults().get(i).getOriginal_language(), movieData.getResults().get(i).getTitle());
getPopularService.saveResultDTOsToDB(resultDTO);
}
movieDataDTO.setResults(getPopularService.getAllResultDTOs());
return ResponseEntity.status(200).body(movieDataDTO);
}
}
<file_sep>import java.util.ArrayList;
public class PersonalFinance {
public static void main(String[] args) {
ArrayList<Integer> spentList = new ArrayList<>();
spentList.add(500);
spentList.add(1000);
spentList.add(1250);
spentList.add(175);
spentList.add(800);
spentList.add(120);
System.out.println("We have spent : " + spentMoney(spentList));
System.out.println("Greatest expense was : " + greatMoney(spentList));
System.out.println("Cheapest expense was : " + cheapMoney(spentList));
System.out.println("The average spending was : " + avgMoney(spentList));
}
private static double avgMoney(ArrayList<Integer> spentList) {
double avg = (spentMoney(spentList)) / (spentList.size());
return avg;
}
private static int cheapMoney(ArrayList<Integer> spentList) {
int num = spentList.get(0);
for (Integer i : spentList ) {
if (num > i) {
num = i;
}
}
return num;
}
private static int greatMoney(ArrayList<Integer> spentList) {
int num = 0;
for (Integer i : spentList) {
if (i>num) {
num = i;
}
}
return num;
}
private static int spentMoney(ArrayList<Integer> spentList) {
int sum = 0;
for (Integer i : spentList) {
sum += i;
}
return sum;
}
}
<file_sep>import java.util.ArrayList;
public class ShoppingList {
public static void main(String[] args) {
ArrayList<String> shpList = new ArrayList<>();
shpList.add("Eggs");
shpList.add("milk");
shpList.add("fish");
shpList.add("apples");
shpList.add("bread");
shpList.add("chicken");
String milk = "milk";
String banana = "banana";
System.out.println("Milk : " + doWeHaveMilk(shpList,milk));
System.out.println("Banana : " + doWeHaveMilk(shpList,banana));
}
private static String doWeHaveMilk(ArrayList<String> shpList, String stuff) {
String answer = "no";
if (shpList.contains(stuff)) {
answer = "yes";
}
return answer;
}
}
<file_sep>package com.jwtexample.helloworld.services;
import com.jwtexample.helloworld.models.Assignee;
import com.jwtexample.helloworld.repositories.AssigneeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SignUpServiceImpl implements SignUpService {
private AssigneeRepository assigneeRepository;
@Autowired
public SignUpServiceImpl(AssigneeRepository assigneeRepository) {
this.assigneeRepository = assigneeRepository;
}
@Override
public void saveUserToDB(String userName, String password) {
assigneeRepository.save(new Assignee(userName, password));
}
}
<file_sep>import java.lang.Math;
import java.util.Scanner;
public class Cuboid {
//volume = abc
//surfArea = 2(ab+ac +bc)
public static void main (String[] args){
int a, b, c, surfArea, vol;
Scanner input = new Scanner(System.in);
System.out.println("<NAME>! Kérlek adj meg 3 egész számot : ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
System.out.println("Volume: " + a*b*c);
System.out.println("Surface Area: " + (2*(a*b + a*c + b*c)));
}
}
<file_sep>public class Dog extends Animal{
public Dog() {
this.healCost = rndGenerator();
}
@Override
public int rndGenerator() {
return (int)(Math.random() * 8) + 1;
}
}
<file_sep>package com.foxclub.foxclub.controllers;
import com.foxclub.foxclub.services.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class InfoController {
PetService petService;
@Autowired
public InfoController(PetService petService) {
this.petService = petService;
}
@GetMapping("/info/{name}")
public String getName(Model model,
@PathVariable("name") String name) {
return "redirect:/index?name=" + name;
}
}
<file_sep>package com.foxclub.foxclub.repositories;
import com.foxclub.foxclub.models.Fox;
import com.foxclub.foxclub.models.Pet;
import com.foxclub.foxclub.models.Trick;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class PetStore {
List<Pet> petStore;
public PetStore() {
petStore = new ArrayList<>();
petStore.add(new Fox("Mr.Green", "pizza", "lemonade"));
petStore.get(0).addTrick(new Trick("write HTML"));
petStore.get(0).addTrick(new Trick("code in Java"));
petStore.add(new Fox("Karak", "salad", "water"));
}
public List<Pet> findAllPets() {
return petStore;
}
public Pet addToStore(String name) {
Pet newPet = (new Pet(name));
petStore.add(newPet);
return newPet;
}
public Pet updatePet(Pet pet) {
for (int i = 0; i < petStore.size(); i++) {
if (petStore.get(i).getName().equals(pet.getName())) {
petStore.remove(i);
petStore.add(i, pet);
}
}
return pet;
}
public Pet findAnPet(String petName) {
for (Pet p : petStore) {
if (p.getName().equals(petName)){
return p;
}
}
return null;
}
}
<file_sep>package com.listingtotods.listtodos;
import com.listingtotods.listtodos.models.Todo;
import com.listingtotods.listtodos.repositories.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ListtodosApplication implements CommandLineRunner {
TodoRepository todoRepository;
@Autowired
public ListtodosApplication(TodoRepository todoRepository) {
this.todoRepository = todoRepository;
}
public static void main(String[] args) {
SpringApplication.run(ListtodosApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
todoRepository.save(new Todo("I have to learn Object Relational Mapping"));
}
}
<file_sep>spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.datasource.url=jdbc:mysql://localhost:3306/tokenaut?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.logging.level.org.hibernate.SQL=debug
spring.jpa.show-sql=true
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
<file_sep>import java.util.Scanner;
public class ParametricAverage {
public static void main (String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("Please let me have an integer : ");
int num = userInput.nextInt();
int counter = 0;
int amount = 0;
do {
counter++;
System.out.println("Please let me have an integer : ");
amount += userInput.nextInt();
} while (counter<num);
System.out.println("Sum : " + amount);
System.out.println("Avg : " + (double)(amount/num));
}
}
<file_sep>public class HelloOthers {
public static void main (String[] args){
System.out.println("Hello Peti");
System.out.println("Hello Gábor");
System.out.println("Hello Bálint");
}
}
<file_sep>package com.foxclub.foxclub.controllers;
import com.foxclub.foxclub.models.Pet;
import com.foxclub.foxclub.services.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class MainController {
PetService petService;
@Autowired
public MainController(PetService petService) {
this.petService = petService;
}
@GetMapping("/index")
public String postIndex(Model model,
@RequestParam(value = "name", required = false) String name) {
if (name == null || name.equals("")) {
return "redirect:/login";
}
Pet pet = petService.findPet(name);
if (pet != null){
model.addAttribute("pet", pet);
return "index";
}
return "redirect:/login";
}
}
<file_sep>package com.thereddit.reddit.services;
import com.thereddit.reddit.models.User;
public interface UserService {
void saveUser(User user);
User findUser(String userName) throws Exception;
User instanciateUser(String userName, String firstName, String lastName, String password);
boolean isPswMatch(String password, String userName);
boolean loginUser(String password, String userName) throws Exception;
}
<file_sep>rootProject.name = 'auth0'
<file_sep>package ClassesAndFields;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
SharpieSet sS = new SharpieSet();
arrayInitializer(sS);
}
private static void arrayInitializer(SharpieSet sS) {
for (int i = 0; i < 33; i++) {
sS.AddSharpie(new Sharpie("black", (float)55));
}
for (int i = 0; i < sS.sharpieList.size()-20; i++) {
sS.sharpieList.get(i).use((float) 100);
}
System.out.println(countUsable(sS) + "# usable sharpies are in the list.");
System.out.println(removeTtrash(sS) + "# Sharpies has been removed from the list.");
for (Sharpie s: sS.sharpieList) {
System.out.print("Color : " + s.color + " , Width : " + s.width + " , inkAmount : " + s.inkAmount);
System.out.println();
}
}
private static int removeTtrash(SharpieSet sS) {
int counter = 0;
for (int i = 0; i < sS.sharpieList.size(); i++) {
if ((sS.sharpieList.get(i).inkAmount) <= 0){
sS.sharpieList.remove(i);
counter++;
}
}
return counter;
}
private static int countUsable(SharpieSet sS) {
int counter = 0;
for (Sharpie s : sS.sharpieList) {
if (s.inkAmount > 0) {
counter++;
}
}
return counter;
}
}
<file_sep>rootProject.name = 'hellobean'
<file_sep>package com.bankofsimba.simbabank.models;
public class BankAccount {
private static int nextIdx = 0;
private int idx;
private String name;
private double balance;
private String animalType;
private String currency;
private boolean isKing;
private boolean goodGuy;
public BankAccount() {
this.currency = "Zebra";
}
public BankAccount(String name, double balance, String animalType) {
this.idx = nextIdx++;
this.currency = "Zebra";
this.name = name;
this.balance = balance;
this.animalType = animalType;
this.goodGuy = true;
if (this.name.equals("Simba") || this.name.equals("Zordon") || this.name.equals("Mufasa")){
this.isKing = true;
}
if (this.name.equals("Zordon") || this.name.equals("Banzai") || this.name.equals("Shenzi") || this.name.equals("Ed")) {
this.goodGuy = false;
}
}
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public void setName(String name) {
this.name = name;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setAnimalType(String animalType) {
this.animalType = animalType;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getName() {
return name;
}
public double getBalance() {
return balance;
}
public String getAnimalType() {
return animalType;
}
public String getCurrency() {
return currency;
}
public boolean isKing() {
return isKing;
}
public void setKing(boolean king) {
isKing = king;
}
public static int getNextIdx() {
return nextIdx;
}
public static void setNextIdx(int nextIdx) {
BankAccount.nextIdx = nextIdx;
}
public boolean isGoodGuy() {
return goodGuy;
}
public void setGoodGuy(boolean goodGuy) {
this.goodGuy = goodGuy;
}
public void addMoney(int amount) {
this.balance += amount;
}
}
<file_sep>package com.jwtexample.helloworld.controllers;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import com.jwtexample.helloworld.services.JwtUserDetailsService;
import com.jwtexample.helloworld.configs.JwtTokenUtil;
import com.jwtexample.helloworld.models.JwtRequest;
import com.jwtexample.helloworld.models.JwtResponse;
import javax.servlet.http.HttpServletResponse;
@RestController
@CrossOrigin
public class JwtAuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private JwtUserDetailsService userDetailsService;
//a login form -ról az /authenticatere érkezik és innen redirect a kívánt oldalra
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<?> createAuthenticationToken(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpServletResponse myResponse) throws Exception {
JwtRequest authenticationRequest = new JwtRequest(username, password);
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
final UserDetails userDetails = userDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails, myResponse);
// myResponse.setHeader("Authorization", "Bearer " + token);
myResponse.sendRedirect("http://localhost:8080/index");
return ResponseEntity.ok(new JwtResponse(token));
}
private void authenticate(String username, String password) throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
}
}
<file_sep>spring.datasource.url=jdbc:mysql://localhost/auth0db?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.logging.level.org.hibernate.SQL=debug
auth0.issuer:https://blog-samples.auth0.com/
auth0.apiAudience:https://contacts.blog-samples.com/
<file_sep>import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class WhichSquare {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 9, 2, 8, 6, 5);
List<Integer> biggerThan20Numbers = numbers.stream().filter(n -> n*n > 20).collect(Collectors.toList());
biggerThan20Numbers.stream().forEach(System.out :: println);
}
}
<file_sep>package com.switchingmessageservices.messageservice.service;
public class MessageProceeder {
}
<file_sep>package com.thereddit.reddit.models;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue
private long id;
private String userName;
private String firstName;
private String lastName;
private int noOfPosts;
private String password;
@OneToMany
List<Post> listOfposts;
public User() {
}
public User(String userName, String firstName, String lastName, String password) {
this.userName = userName;
this.firstName = firstName;
this.lastName = lastName;
this.password = <PASSWORD>;
this.noOfPosts = 0;
this.listOfposts = new ArrayList<>();
}
public List<Post> getListOfposts() {
return listOfposts;
}
public void setListOfposts(List<Post> listOfposts) {
this.listOfposts = listOfposts;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getNoOfPosts() {
return noOfPosts;
}
public void setNoOfPosts(int noOfPosts) {
this.noOfPosts = noOfPosts;
}
public void incrementNoOfPosts() {
this.noOfPosts += 1;
}
public User addPostToList(Post post){
this.listOfposts.add(post);
return this;
}
}
<file_sep>package EncapsulationandConstructor;
public class Counter {
int number;
int initVal;
public Counter(){
this(0);
}
public Counter (int number){
this.number = number;
}
public void add(){
this.number += 1;
}
public void add(int number){
this.initVal = this.number;
this.number += number;
}
public int get () {
return this.number;
}
public void reset() {
this.number = this.initVal;
}
}
<file_sep>https://github.com/bagyoda/git-lesson-repository
https://github.com/bagyoda/hello-world
https://github.com/bagyoda/patchwork
https://github.com/green-fox-academy/bagyoda
<file_sep>import java.util.ArrayList;
import java.util.List;
public class Garden {
static List<Plant> listOfPlants = plantInitiaizer();
public static void main(String[] args) {
plantInitiaizer();
doesNeedExists();
gardenWatering(40);
gardenWatering(70);
}
private static void gardenWatering(int amount) {
System.out.println();
System.out.println("Watering with " + amount + ".");
int size = listOfPlants.size();
amount /= sizeOptimalizer(size);
for (Plant p : listOfPlants) {
if (p.needsWater()) {
p.watering(amount);
p.needPrinter();
} else {
p.needPrinter();
}
}
}
private static int sizeOptimalizer(int size) {
for (Plant p : listOfPlants) {
if (!p.needsWater()) {
size--;
}
}
return size;
}
private static List<Plant> plantInitiaizer() {
List<Plant> listOfPlants = new ArrayList<>();
listOfPlants.add(new Flower("yellow"));
listOfPlants.add(new Flower("blue"));
listOfPlants.add(new Tree("purple"));
listOfPlants.add(new Tree("orange"));
return listOfPlants;
}
public static void doesNeedExists (){
for (Plant p : listOfPlants) {
p.needPrinter();
}
}
}
<file_sep>package com.hellobeanworld.hellobean;
import com.hellobeanworld.hellobean.services.BlueColor;
import com.hellobeanworld.hellobean.services.MyColor;
import com.hellobeanworld.hellobean.services.Printer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.awt.*;
@SpringBootApplication
public class HellobeanApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(HellobeanApplication.class, args);
}
Printer printer;
MyColor color;
@Autowired
HellobeanApplication(Printer printer, MyColor color){
this.printer = printer;
this.color = color;
}
@Override
public void run(String... args) throws Exception {
this.printer.log("hello" + color.printColor());
}
}
<file_sep>public class Plant {
int waterStatus;
String color;
public Plant(){
this.waterStatus = 0;
}
public Plant(String color) {
this.waterStatus = 0;
this.color = color;
}
public boolean needsWater(){
return false;
}
public void watering(int i) {
}
public void needPrinter(){
}
}
<file_sep>import javax.sound.midi.Soundbank;
import java.lang.String;
import java.sql.SQLOutput;
public class Greet {
public static void main(String[] args) {
String al = "GreenFox";
System.out.println(greet(al));
}
public static String greet (String s) {
String g = "Greetings, dear "+ s;
return g;
}
}
<file_sep>package com.foxclub.foxclub.controllers;
import com.foxclub.foxclub.models.Pet;
import com.foxclub.foxclub.services.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class AddController {
PetService petService;
@Autowired
public AddController(PetService petService) {
this.petService = petService;
}
@GetMapping("/addPage/{name}")
public String getInfoPage(Model model,
@PathVariable(value = "name", required = false) String name,
@RequestParam(value = "isNull", required = false, defaultValue = "false") String s) {
model.addAttribute("pet", petService.findPet(name));
if (s.equals("true")) {
model.addAttribute("isNull", true);
model.addAttribute("name", name);
}
return "addPage";
}
@PostMapping("/addPage")
public String addNewPet(Model model,
@RequestParam("petName") String petName) {
if (petName == null || petName.equals("")) {
return "redirect:/addPage?name=" + petName;
}
Pet pet = petService.findPet(petName);
if (pet == null) {
pet = petService.saveToList(petName);
model.addAttribute("pet", pet);
return "redirect:/index?name=" + pet.getName();
}
return "redirect:/addPage/" + petName + "?isNull=true";
}
}
<file_sep>public class Pirate {
int consumedRum;
boolean alive;
boolean isCaptain;
boolean passedOut;
public Pirate(){
this.consumedRum = 0;
this.alive = true;
}
public void drinkSomeRum(){
if(this.consumedRum < 4) {
this.consumedRum += 1;
} else {
this.passedOut = true;
}
}
public void howsItGoingMate(){
if ((this.consumedRum < 5) && (this.consumedRum >= 0) & !this.passedOut) {
System.out.println("Pour me anudder!");
} else {
System.out.println("Arghh, I'ma Pirate. How d'ya d'ink its goin?");
}
}
public void die() {
this.alive = false;
this.passedOut = false;
}
private int rndGenerator (int rnd) {
rnd = (int) (Math.random() * rnd) +1;
return rnd;
}
public int brawl(Pirate pirate) {
int rnd = rndGenerator(3);
if (rnd == 1) {
this.die();
return 1;
} else if (rnd == 2) {
pirate.die();
return 2;
} else {
this.passedOut = true;
pirate.passedOut = true;
return 3;
}
}
}
<file_sep>public class AppendAFunc {
public static void main(String[] args) {
String typo = "Chinchill";
System.out.println(appendAFunc(typo));
}
public static String appendAFunc (String s){
String ss = s + "a";
return ss;
}
}
<file_sep>package com.foxclub.foxclub.models;
public class Trick {
private String trick;
public Trick() {
}
public Trick(String trick) {
this.trick = trick;
}
public String getTrick() {
return trick;
}
public void setTrick(String trick) {
this.trick = trick;
}
}
<file_sep>package com.thereddit.reddit.services;
import com.thereddit.reddit.models.User;
import com.thereddit.reddit.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
UserRepository userRepository;
@Autowired
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void saveUser(User user) {
userRepository.save(user);
}
@Override
public User findUser(String userName) throws Exception {
if (userRepository.findByUserName(userName) == null) {
throw(new Exception("Username cannot be empty!"));
}
User found = userRepository.findByUserName(userName);
if (found == null) {
throw(new Exception("Username " + userName + " couldn't be found!"));
}
return found;
}
@Override
public boolean loginUser(String password, String userName) throws Exception {
if (userRepository.findByUserName(userName) == null) {
throw(new Exception("User is not present!"));
}
if (!password.equals(userRepository.findByUserName(userName).getPassword())) {
throw(new Exception("Wrong password"));
}
return true;
}
@Override
public User instanciateUser(String userName, String firstName, String lastName, String password) {
return new User(userName, firstName, lastName, password);
}
@Override
public boolean isPswMatch(String password, String userName) {
return password.equals(userRepository.findByUserName(userName).getPassword()) ;
}
public String findUserById(long id) {
return userRepository.findById(id);
}
}
<file_sep>package main.java.music;
public abstract class StringedInstrument extends Instrument {
int numberOfStrings;
public StringedInstrument(String name, int numberOfStrings) {
super(name);
this.numberOfStrings = numberOfStrings;
}
abstract public void sound();
@Override
public void play() {
sound();
}
}
<file_sep>public class Tree extends Plant {
public Tree() {
}
public Tree(String color) {
super(color);
}
@Override
public void watering(int amount) {
this.waterStatus += (amount * 0.4);
}
@Override
public boolean needsWater() {
if (this.waterStatus < 10){
return true;
}
return false;
}
@Override
public void needPrinter() {
if (this.needsWater()){
System.out.println("The " + this.color + " tree needs water.");
} else {System.out.println("The " + this.color + " tree does not need water.");}
}
}
<file_sep>package com.todosagain.enhancedtodos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EnhancedtodosApplication {
public static void main(String[] args) {
SpringApplication.run(EnhancedtodosApplication.class, args);
}
}
<file_sep>package com.switchingmessageservices.messageservice.service;
public class TwitterService {
}
<file_sep>package com.jwtexample.helloworld.controllers;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("index")
public String renderIndexPage(Model model, Authentication authentication) {
// model.addAttribute("userName", authentication.getName());
return "index";
}
}
<file_sep>import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class NumberConverterTest {
NumberConverter numberConverter;
@BeforeEach
public void setup(){
numberConverter = new NumberConverter();
}
@Test
public void tMethod1() {
int number = 1;
String expected = "one";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
@Test
public void tMethod2() {
int number = 12;
String expected = "twelve";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
@Test
public void tMethod3() {
int number = 22;
String expected = "twentytwo";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
@Test
public void tMethod4() {
int number = 99;
String expected = "ninetynine";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
@Test
public void tMethod5() {
int number = 999;
String expected = "nine hundred ninetynine";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
@Test
public void tMethod6() {
int number = 1111;
String expected = "one thousand one hundred eleven";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
@Test
public void tMethod7() {
int number = 9000;
String expected = "nine thousand ";
assertEquals(expected,numberConverter.numbersIntoWord(number));
}
}<file_sep>package com.rest.practice.controllers;
import com.rest.practice.models.MyError;
import com.rest.practice.models.Until;
import com.rest.practice.models.UntilDTO;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class DoUntilController {
@PostMapping("/dountil/{action}")
public ResponseEntity performAction(@PathVariable String action, @RequestBody(required = false) Until newUntil){
if (newUntil != null){
Until until = new Until(newUntil);
if (action.equals("sum")){
until.doSumUntil();
UntilDTO untilDTO = new UntilDTO(until.getResult());
return ResponseEntity.status(200).body(untilDTO);
} else if (action.equals("factor")) {
until.doFactorUntil();
UntilDTO untilDTO = new UntilDTO(until.getResult());
return ResponseEntity.status(200).body(untilDTO);
} else {
MyError e = new MyError("Please provide a number!");
return ResponseEntity.status(400).body(e);
}
} else {
MyError e = new MyError("Please provide a number!");
return ResponseEntity.status(400).body(e);
}
}
}
<file_sep>public class DefineBasicInfo {
public static void main (String[] args){
String name = "Daniel";
int age = 30;
double height = 1.78;
boolean married = false;
}
}
<file_sep>package com.todosagain.enhancedtodos.controllers;
import com.todosagain.enhancedtodos.models.Todo;
import com.todosagain.enhancedtodos.services.AssigneeServiceImpl;
import com.todosagain.enhancedtodos.services.TodoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDate;
import java.util.Date;
@Controller
public class EditController {
TodoServiceImpl todoService;
AssigneeServiceImpl assigneeService;
@Autowired
public EditController(TodoServiceImpl todoService, AssigneeServiceImpl assigneeService) {
this.todoService = todoService;
this.assigneeService = assigneeService;
}
@GetMapping("/todo/{id}/edit/{userName}")
public String getTodoEditPage(@PathVariable long id,
@PathVariable String userName,
Model model) {
Todo todo = todoService.findPostById(id);
model.addAttribute("todo", todo);
model.addAttribute("assignee", assigneeService.findAssigneeByName(userName));
return "edit";
}
@PostMapping("/todo/{id}/edit/{userName}")
public String editTodo(@PathVariable long id,
@PathVariable String userName,
@RequestParam("title") String title,
@RequestParam(value = "urgent", required = false) boolean urgent,
@RequestParam(value = "done", required = false) boolean done,
@RequestParam("dueDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date dueDate,
Model model) {
Todo todo = todoService.findPostById(id);
todo.setTitle(title);
todo.setDueDate(dueDate);
todo.setDone(done);
todo.setUrgent(urgent);
todoService.saveTodo(todo);
return "redirect:/todo?userName=" + userName;
}
}
<file_sep>import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class mRotTest {
@Test
public void testRotation(){
mRot testRot = new mRot();
int[][] a = {{1,2,3},{4,5,6},{7,8,9}};
int[][] b = {{1,2,3},{4,5,6},{7,8,9}};
int num = 1;
assertArrayEquals(b, testRot.rotateMatrixBy90(a));
}
}<file_sep>package main.java.animals;
public interface EggPlacer {
String augmentation = "laing eggs";
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>firstBlogsite</title>
<link rel="stylesheet" href="style_blog.css" type="text/css" >
<link href="https://fonts.googleapis.com/css?family=B612+Mono&display=swap" rel="stylesheet">
</head>
<body>
<div id="barTitle">
<nav class="navbar navbar-default navbar-fixed-top">
<h1>The Blog</h1>
</div>
<div class="content">
<div class="anpPadd">
<h3>Add new posts</h3>
</div>
<form>
<div class="title">
<label>Title</label>
</div>
<div>
<input type="text">
</div>
<div class="title">
<label>Content</label>
</div>
<div class="textwrapper">
<textarea rows="10" placeholder='Auto-Expanding Textarea'></textarea>
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
<div class="fromPosts">
<h3>Posts</h3>
<h1>About CSS</h1>
<p>Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation of a document written in a markup language like HTML.<br>[1] CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript.[2] </p>
<div class="aboutHTML">
<h1>About HTML</h1>
<p>HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page. HTML provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as and directly introduce content into the page. Other tags such as surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page.
</div>
</div>
</div>
</body>
</html>
<file_sep>rootProject.name = 'logtask'
<file_sep>import java.util.HashMap;
import java.util.Map;
public class NumberConverter {
HashMap<String, String> numbersWords = new HashMap<>();
HashMap<String, String> numbersWords2 = new HashMap<>();
String[] getnumberWords1 = {"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven", "twelve", "thirteen",
"fourteen","fifteen","sixteen","seventeen", "eighteen", "nineteen"};
String[] getNumberWords2 = {"ten", "twenty", "thirty", "fourty","fifty","sixty","seventy","eighty","ninety"};
String[] getNumberWords3 = {"hundred", "thousand"};
public String numbersIntoWord(int number){
for (int i = 0; i < getnumberWords1.length; i++) {
numbersWords.put(String.valueOf(i), getnumberWords1[i]);
}
for (int i = 1; i <= getNumberWords2.length; i++) {
numbersWords2.put(String.valueOf(i) + "0", getNumberWords2[i-1]);
}
String result = "";
String measuredNumber = String.valueOf(number);
if (measuredNumber.length() == 1){
result = length1(measuredNumber);
}
if (measuredNumber.length() == 2) {
result = length2(measuredNumber);
}
if (measuredNumber.length() == 3) {
result = length3(String.valueOf(measuredNumber.charAt(0))) +
length2(String.valueOf(measuredNumber.charAt(1) + String.valueOf(measuredNumber.charAt(2))));
}
if (measuredNumber.length() == 4 && measuredNumber.charAt(1) == '0' && measuredNumber.charAt(2) == '0' && measuredNumber.charAt(3) == '0'){
result = length1(measuredNumber) + " thousand ";
} else if (measuredNumber.length() == 4) {
result = length4(String.valueOf(measuredNumber.charAt(0))) + length3(String.valueOf(measuredNumber.charAt(1))) +
length2(String.valueOf(measuredNumber.charAt(2) + String.valueOf(measuredNumber.charAt(3))));
}
return result;
}
public String length4(String measuredNumber) {
String resultOfLength4Method = "";
for (Map.Entry<String, String> e : numbersWords.entrySet()) {
String temp = String.valueOf(measuredNumber.charAt(0));
if (e.getKey().equals(temp)){
resultOfLength4Method = e.getValue() + " thousand ";
}
}
return resultOfLength4Method;
}
private String length1(String measuredNumber) {
String resultOfLength1Method = "";
for (Map.Entry<String, String> e : numbersWords.entrySet()) {
if (e.getKey().equals(String.valueOf(measuredNumber.charAt(0)))){
resultOfLength1Method = e.getValue();
}
}
return resultOfLength1Method;
}
public String length2(String measuredNumber) {
String resultOfLength2Method = "";
if (measuredNumber.equals("11")) {
resultOfLength2Method = "eleven";
return resultOfLength2Method;
}
if (measuredNumber.equals("12")) {
resultOfLength2Method = "twelve";
return resultOfLength2Method;
}
if(measuredNumber.charAt(0) == '1') {
for (Map.Entry<String, String> e : numbersWords.entrySet()) {
if (e.getKey().equals(measuredNumber)){
resultOfLength2Method = e.getValue();
}
}
}
/*
if (measuredNumber.charAt(0) != '1'){
for (Map.Entry<String, String> e : numbersWords2.entrySet()) {
String temp = measuredNumber.charAt(0) + "0";
if (e.getKey().equals(temp)){
resultOfLength2Method = e.getValue();
}
}
if(measuredNumber.charAt(1) != '0'){
resultOfLength2Method += length1(String.valueOf(measuredNumber.charAt(1)));
}
}
* */
if (measuredNumber.charAt(0) != '1' && measuredNumber.charAt(1) == '0'){
for (Map.Entry<String, String> e : numbersWords2.entrySet()) {
String temp = measuredNumber.charAt(0) + "0";
if (e.getKey().equals(temp)){
resultOfLength2Method = e.getValue();
}
}
}
if (measuredNumber.charAt(0) != '1' && measuredNumber.charAt(1) != '0'){
for (Map.Entry<String, String> e : numbersWords2.entrySet()) {
String temp = measuredNumber.charAt(0) + "0";
if (e.getKey().equals(temp)){
resultOfLength2Method = e.getValue();
}
}
resultOfLength2Method += length1(String.valueOf(measuredNumber.charAt(1)));
}
return resultOfLength2Method;
}
public String length3(String measuredNumber) {
String resultOfLength3Method = "";
for (Map.Entry<String, String> e : numbersWords.entrySet()) {
String temp = String.valueOf(measuredNumber.charAt(0));
if (e.getKey().equals(temp)){
resultOfLength3Method = e.getValue() + " hundred ";
}
}
return resultOfLength3Method;
}
}
<file_sep>import java.nio.*;
import java.util.*;
public class DivideByZero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int divisor = sc.nextInt();
getNumber(divisor);
}
private static void getNumber (int divisor) {
try {
int result = 12 / divisor;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("fail");
} finally {
System.out.println("Please avoid division by '0'. ");
}
}
}
<file_sep>package EncapsulationandConstructor;
public class Main {
public static void main(String[] args) {
// Animal a = new Animal();
// System.out.println(a.hunger);
//
// Sharpie b = new Sharpie("a", (float)100);
// b.use((float)10);
// System.out.println(b.inkAmount);
Counter c = new Counter();
// System.out.println(c.number);
// c.add();
System.out.println(c.get());
}
}
<file_sep>import java.util.Scanner;
public class DrawSquare {
public static void main (String[] args){
Scanner userInput = new Scanner(System.in);
System.out.println("Please let me have an number : ");
int num = userInput.nextInt();
for (int i = 1; i <= num; i++) {
if (i==1 || i==num) {
for (int j = 1; j <= num; j++) {
System.out.print("%");
}
} else {
for (int k = 1; k <=num ; k++) {
if (k==1 || k==num){
System.out.print("%");
} else{
System.out.print(" ");
}
}
}
System.out.println();
}
}
}
<file_sep>import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class AnagramTest {
Anagram anagram;
@BeforeEach
public void setup(){
anagram = new Anagram();
}
@Test
public void tMethod1() {
String example1 = "123abc";
String example2 = "231bca";
assertEquals(true,anagram.checkAnagram(example1,example2));
}
@Test
public void tMethod2() {
String example1 = "ABBA";
String example2 = "ABBa";
assertEquals(true,anagram.checkAnagram(example1,example2));
}
@Test
public void tMethod3() {
String example1 = null;
String example2 = null;
assertEquals(false,anagram.checkAnagram(example1,example2));
}
@Test
public void tMethod4() {
String example1 = "ABBA";
String example2 = "ABB A ";
assertEquals(true,anagram.checkAnagram(example1,example2));
}
}
|
cbc64838e7c029828532df4c82d41ed07cb18272
|
[
"HTML",
"Markdown",
"INI",
"Gradle",
"Java"
] | 125
|
Java
|
green-fox-academy/bagyoda
|
695c48ddcb63c746dcecc00cf3ce769b6fb6c01c
|
9c53d4041403e587e50ee3bcb777e13a50b4b985
|
refs/heads/main
|
<file_sep><?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use JsonSerializable;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
* @UniqueEntity(
* fields={"username"},
* message="This username is already registered!"
* )
* @ApiResource()
*/
class User implements UserInterface //, \JsonSerializable
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
*
*
* @ORM\Column(type="string", length=180, unique=true)
* @Groups("share")
*/
private $username;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $email;
/**
* @ORM\Column(type="string", length=255 , nullable=true)
*/
private $firstname;
/**
* @ORM\Column(type="string", length=255 , nullable=true)
*/
private $lastname;
/**
* @ORM\Column(type="datetime")
*/
private $registeredAt;
/**
* @ORM\Column(type="datetime")
*/
private $agreedTermsAt;
/**
* @ORM\OneToMany(targetEntity=Image::class, mappedBy="owner", orphanRemoval=true)
*/
private $images;
/**
* @ORM\ManyToMany(targetEntity=User::class, inversedBy="friends")
*/
private $friend;
/**
* @ORM\ManyToMany(targetEntity=User::class, mappedBy="friend")
*/
private $friends;
/**
* @ORM\OneToMany(targetEntity=Album::class, mappedBy="owner", orphanRemoval=true)
*/
private $albums;
/**
* @ORM\OneToMany(targetEntity=Like::class, mappedBy="user", orphanRemoval=true)
*/
private Collection $likes;
/**
* @ORM\ManyToMany(targetEntity=Image::class, inversedBy="users")
*/
private $likedImages;
public function __construct()
{
$this->images = new ArrayCollection();
$this->friend = new ArrayCollection();
$this->friends = new ArrayCollection();
$this->albums = new ArrayCollection();
$this->likes = new ArrayCollection();
$this->likedImages = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = <PASSWORD>;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): self
{
$this->email = $email;
return $this;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getLastname(): ?string
{
return $this->lastname;
}
public function setLastname(string $lastname): self
{
$this->lastname = $lastname;
return $this;
}
public function getRegisteredAt(): ?\DateTimeInterface
{
return $this->registeredAt;
}
public function setRegisteredAt(\DateTimeInterface $registeredAt): self
{
$this->registeredAt = $registeredAt;
return $this;
}
public function getAgreedTermsAt(): ?\DateTimeInterface
{
return $this->agreedTermsAt;
}
public function agreedTermsAt(): self
{
$this->agreedTermsAt = new \DateTime();
return $this;
}
/**
* @return Collection|Image[]
*/
public function getImages(): Collection
{
return $this->images;
}
public function addImage(Image $image): self
{
if (!$this->images->contains($image)) {
$this->images[] = $image;
$image->setOwner($this);
}
return $this;
}
public function removeImage(Image $image): self
{
if ($this->images->removeElement($image)) {
// set the owning side to null (unless already changed)
if ($image->getOwner() === $this) {
$image->setOwner(null);
}
}
return $this;
}
/**
* @return Collection|self[]
*/
public function getFriend(): Collection
{
return $this->friend;
}
public function addFriend(self $friend): self
{
if (!$this->friend->contains($friend)) {
$this->friend[] = $friend;
}
return $this;
}
public function removeFriend(self $friend): self
{
$this->friend->removeElement($friend);
return $this;
}
/**
* @return Collection|self[]
*/
public function getFriends(): Collection
{
return $this->friends;
}
/**
* @return Collection|Album[]
*/
public function getAlbums(): Collection
{
return $this->albums;
}
public function addAlbum(Album $album): self
{
if (!$this->albums->contains($album)) {
$this->albums[] = $album;
$album->setOwner($this);
}
return $this;
}
public function removeAlbum(Album $album): self
{
if ($this->albums->removeElement($album)) {
// set the owning side to null (unless already changed)
if ($album->getOwner() === $this) {
$album->setOwner(null);
}
}
return $this;
}
/*public function jsonSerialize()
{
return [
'username' => $this->username,
];
}*/
/**
* @return Collection|Like[]
*/
public function getLikes(): Collection
{
return $this->likes;
}
public function addLike(Like $like): self
{
if (!$this->likes->contains($like)) {
$this->likes[] = $like;
$like->setUser($this);
}
return $this;
}
public function removeLike(Like $like): self
{
if ($this->likes->removeElement($like)) {
// set the owning side to null (unless already changed)
if ($like->getUser() === $this) {
$like->setUser(null);
}
}
return $this;
}
/**
* @return Collection|Image[]
*/
public function getLikedImages(): Collection
{
return $this->likedImages;
}
public function addLikedImage(Image $likedImage): self
{
if (!$this->likedImages->contains($likedImage)) {
$this->likedImages[] = $likedImage;
}
return $this;
}
public function removeLikedImage(Image $likedImage): self
{
$this->likedImages->removeElement($likedImage);
return $this;
}
}
<file_sep><?php
namespace App\Factory;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Zenstruck\Foundry\RepositoryProxy;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
/**
* @method static User|Proxy findOrCreate(array $attributes)
* @method static User|Proxy random()
* @method static User[]|Proxy[] randomSet(int $number)
* @method static User[]|Proxy[] randomRange(int $min, int $max)
* @method static UserRepository|RepositoryProxy repository()
* @method User|Proxy create($attributes = [])
* @method User[]|Proxy[] createMany(int $number, $attributes = [])
*/
final class UserFactory extends ModelFactory
{
/**
* @var UserPasswordEncoderInterface
*/
private $userPasswordEncoder;
public function __construct(UserPasswordEncoderInterface $userPasswordEncoder)
{
parent::__construct();
// TODO inject services if required (https://github.com/zenstruck/foundry#factories-as-services)
$this->userPasswordEncoder = $userPasswordEncoder;
}
protected function getDefaults(): array
{
return [
'firstname' => self::faker()->firstName(),
'lastname' => explode(' ',trim(self::faker()->name()))[1],
//'username' => self::faker()->firstname(),
'email' => self::faker()->email,
'roles' => self::faker()->boolean(80) ? ['ROLE_USER'] : ['ROLE_ADMIN'],
'registeredAt' => self::faker()->dateTimeBetween('-20 years', 'now'),
'agreedTermsAt' => new \DateTime(),
'password' => $this->userPasswordEncoder->encodePassword(new User(),'<PASSWORD>')
];
}
protected function initialize(): self
{
// see https://github.com/zenstruck/foundry#initialization
return $this
->afterInstantiate(function(User $user) {
$user->setUsername($user->getFirstname());
})
;
}
protected static function getClass(): string
{
return User::class;
}
}
<file_sep>//import Vue from 'vue';
import './styles/vuePage.css';
import './bootstrap';
//import Dropzone from 'dropzone';
//Dropzone.autoDiscover = false;
require('bootstrap')
import { createApp, compile } from 'vue';
import Users from './pages/users';
import axios from "axios";
import {refreshToken} from "@/services/users-service";
let isRefreshing = false;
let subscribers = [];
axios.interceptors.response.use(response => {
return response;
}, err => {
const {
config,
response: { status, data }
} = err;
const originalRequest = config;
if (originalRequest.url.includes('/api/login_check')) {
return Promise.reject(err);
}
if (status === 401 && data.message === "JWT Token not found") {
if(!isRefreshing) {
isRefreshing = true;
refreshToken().then(({status}) => {
if (status === 200 || status === 204) {
isRefreshing = false;
}
subscribers = [];
})
.catch(error => {
console.error(error)
});
}
const requestSubscribers = new Promise(resolve => {
subscribeTokenRefresh(() => {
resolve(axios(originalRequest));
});
});
onRefreshed();
return requestSubscribers;
}
})
subscribers = [];
function subscribeTokenRefresh(cb) {
subscribers.push(cb);
}
function onRefreshed() {
subscribers.map(cb => cb());
}
createApp(Users).mount('#users')
/** to show the image filename in form field */
$('.custom-file-input').on('change', function (event) {
var inputFile = event.currentTarget;
$(inputFile).parent()
.find('.custom-file-label')
.html(inputFile.files[0].name);
})<file_sep>import axios from "axios";
export async function insertTags(imageName, tags) {
return await axios.post('/add/tags/' + imageName, {
"tags": tags,
},
{
headers: {
'Content-Type': 'application/json'
}
});
}<file_sep><?php
namespace App\Controller;
use App\Entity\Album;
use App\Entity\Image;
use App\Repository\AlbumRepository;
use App\Repository\ImageRepository;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class AlbumController extends AbstractController
{
/**
* @var Security
*/
private Security $security;
/**
* @var AlbumRepository
*/
private AlbumRepository $albumRepository;
/**
* @var ImageRepository
*/
private ImageRepository $imageRepository;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
public function __construct( Security $security , AlbumRepository $albumRepository , ImageRepository $imageRepository , EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->albumRepository = $albumRepository;
$this->imageRepository = $imageRepository;
$this->entityManager = $entityManager;
}
/**
*@Route("/album/create", name="album_create", methods={"POST"})
*/
public function create(Request $request) {
$albumName = json_decode($request->getContent(),true);
$album = new Album();
$album->setOwner($this->security->getUser());
$album->setName($albumName['albumName']);
try {
$this->entityManager->persist($album);
$this->entityManager->flush();
} catch (\Exception $e) {
$errorMessage = $e->getMessage();
return $this->json($errorMessage, 500);
}
//echo $albumName["albumName"];
//dump($request);
//print_r($albumName);
return new JsonResponse( $albumName["albumName"],201);
}
/**
* @Route("/fetch/albums" , name="fetch_albums", methods={"GET"})
*/
public function provideAlbums() {
$this->security->getUser()->getAlbums();
return $this->json($this->security->getUser()->getAlbums(),200, [],[
'groups' => ['main']
]) ;
}
/**
* @Route("/fetch/album/images/{albumName}", name="fetch_album_images", methods={"GET"})
*/
public function provideAlbumImages(string $albumName) {
$albums = $this->getUser()->getAlbums();
foreach ($albums as $album) {
if($album->getName() === $albumName) {
$albumImages = $album->getImage();
return $this->json($albumImages,200,[],[
'groups' => ['image']
]);
}
}
return $this->json("bad request", 400);
}
/**
* @Route("/add/to/album/{albumName}", name="add_to_album" , methods={"POST"})
*/
public function addToAlbum(string $albumName, Request $request) {
$data = json_decode($request->getContent(),true);
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $data["filename"] ]);
/** @var Album $album */
$album = $this->albumRepository->findOneBy(['name'=> $albumName]);
if (($this->security->getUser() === $image->getOwner()) && ($this->security->getUser() === $image->getOwner())) {
if ($album->addImage($image)) {
$this->entityManager->persist($album);
$this->entityManager->flush();
return $this->json($data["filename"] . "successfully added ", 201);
}
}
return $this->json("operation was not successful",500);
}/**
* @Route("/remove/from/album/{albumName}", name="remove_from_album" , methods={"POST"})
*/
public function removeFromAlbum(string $albumName, Request $request ) {
$data = json_decode($request->getContent(),true);
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $data["filename"] ]);
/** @var Album $album */
$album = $this->albumRepository->findOneBy(['name'=> $albumName]);
if (($this->security->getUser() === $image->getOwner()) && ($this->security->getUser() === $image->getOwner())) {
foreach ($album->getImage() as $currentImage) {
if ($currentImage->getOriginalName() === $image->getOriginalName()) {
$album->removeImage($currentImage);
$this->entityManager->persist($album);
$this->entityManager->flush();
return $this->json($data["filename"]. "was deleted from album " . $album->getName(), 200);
}
}
}
return $this->json("operation was not successful",500);
}
/**
* @param string $name
* @Route("/delete/album/{name}" , name="delete_album" , methods={"DELETE"})
*/
public function deleteAlbum(string $name) {
$album = $this->albumRepository->findOneBy(['name' => $name]);
if ($this->security->getUser() === $album->getOwner()) {
$this->security->getUser()->removeAlbum($album);
$this->entityManager->persist($this->security->getUser());
$this->entityManager->flush();
return $this->json("deleted successfully",204);
}
return $this->json("not authorized to delete this album" , 401);
}
}
<file_sep><?php
namespace App\DataFixtures;
use App\Factory\UserFactory;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\User;
class AppFixtures extends Fixture
{
/**
* @var UserPasswordEncoderInterface
*/
private $userPasswordEncoder;
public function __construct(UserPasswordEncoderInterface $userPasswordEncoder)
{
$this->userPasswordEncoder = $userPasswordEncoder;
}
public function load(ObjectManager $manager)
{
//
// $product = new Product();
//$user = new User();
//$user->setPassword($this->userPasswordEncoder->encodePassword($user, '<PASSWORD>'));
$user = UserFactory::new()->create();
//$manager->persist($user);
// $manager->flush();
//UserFactory::new()->createMany(20);
}
}
<file_sep><?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20210222130016 extends AbstractMigration
{
public function getDescription() : string
{
return '';
}
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE album_image (album_id INT NOT NULL, image_id INT NOT NULL, INDEX IDX_B3854E791137ABCF (album_id), INDEX IDX_B3854E793DA5256D (image_id), PRIMARY KEY(album_id, image_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');
$this->addSql('ALTER TABLE album_image ADD CONSTRAINT FK_B3854E791137ABCF FOREIGN KEY (album_id) REFERENCES album (id) ON DELETE CASCADE');
$this->addSql('ALTER TABLE album_image ADD CONSTRAINT FK_B3854E793DA5256D FOREIGN KEY (image_id) REFERENCES image (id) ON DELETE CASCADE');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE album_image');
}
}
<file_sep><?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\ImageRepository;
use App\Service\UploaderHelper;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ApiResource()
* @ORM\Entity(repositoryClass=ImageRepository::class)
*/
class Image // implements \JsonSerializable
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups("image")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups("image")
*/
private $filename;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="images")
* @ORM\JoinColumn(nullable=false)
*@Groups("share")
*/
private $owner;
/**
* @ORM\Column(type="decimal", precision=15, scale=10, nullable=true)
* @Groups({"image","share"})
*/
private $latitude;
/**
* @ORM\Column(type="decimal", precision=15, scale=10, nullable=true)
* @Groups({"image","share"})
*/
private $longitude;
/**
* @ORM\Column(type="boolean")
*/
private $public;
private $filePath;
/**
* @ORM\Column(type="datetime")
* @Groups({"image","share"})
*/
private $UploadedAt;
/**
* @ORM\Column(type="string", length=255)
* @Groups({"image","share"})
*/
private $originalName;
/**
* @ORM\ManyToMany(targetEntity=Album::class, mappedBy="image")
*/
private Collection $albums;
/**
* @ORM\ManyToMany(targetEntity=Tag::class, mappedBy="image")
* @Groups("image")
*/
private $tags;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $publishedAt;
/**
* @ORM\OneToMany(targetEntity=Like::class, mappedBy="image", orphanRemoval=true)
* @Groups("share")
*/
private Collection $likes;
/**
* @ORM\ManyToMany(targetEntity=User::class, mappedBy="likedImages")
*/
private Collection $users;
/**
* @ORM\Column(type="string", length=255)
*/
private $mimetype;
public function __construct()
{
$this->albums = new ArrayCollection();
$this->tags = new ArrayCollection();
$this->likes = new ArrayCollection();
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFilename(): ?string
{
return $this->filename;
}
public function setFilename(string $filename): self
{
$this->filename = $filename;
return $this;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): self
{
$this->owner = $owner;
return $this;
}
public function getLatitude(): ?string
{
return $this->latitude;
}
public function setLatitude(?string $latitude): self
{
$this->latitude = $latitude;
return $this;
}
public function getLongitude(): ?string
{
return $this->longitude;
}
public function setLongitude(?string $longitude): self
{
$this->longitude = $longitude;
return $this;
}
public function getPublic(): ?bool
{
return $this->public;
}
public function setPublic(bool $public): self
{
$this->public = $public;
return $this;
}
public function getFilePath(): ?string
{
return UploaderHelper::IMAGE_DIRECTORY.'/'.$this->getFilename();
}
public function setFilePath(string $filePath): self
{
$this->filePath = $filePath;
return $this;
}
public function getUploadedAt(): ?\DateTimeInterface
{
return $this->UploadedAt;
}
public function setUploadedAt(\DateTimeInterface $UploadedAt): self
{
$this->UploadedAt = $UploadedAt;
return $this;
}
public function getOriginalName(): ?string
{
return $this->originalName;
}
public function setOriginalName(string $originalName): self
{
$this->originalName = $originalName;
return $this;
}
/**
* @return Collection|Album[]
*/
public function getAlbums(): Collection
{
return $this->albums;
}
public function addAlbum(Album $album): self
{
if (!$this->albums->contains($album)) {
$this->albums[] = $album;
$album->addImage($this);
}
return $this;
}
public function removeAlbum(Album $album): self
{
if ($this->albums->removeElement($album)) {
$album->removeImage($this);
}
return $this;
}
/**
* @return Collection|Tag[]
*/
public function getTags(): Collection
{
return $this->tags;
}
public function addTag(Tag $tag): self
{
if (!$this->tags->contains($tag)) {
$this->tags[] = $tag;
$tag->addImage($this);
}
return $this;
}
public function removeTag(Tag $tag): self
{
if ($this->tags->removeElement($tag)) {
$tag->removeImage($this);
}
return $this;
}
/*public function jsonSerialize()
{
return [
'originalName' => $this->originalName,
'latitude' => $this->latitude,
'longitude' => $this->longitude,
'uploadedAt' => $this->UploadedAt,
'tags' => $this->tags
];
}*/
public function getPublishedAt(): ?\DateTimeInterface
{
return $this->publishedAt;
}
public function setPublishedAt(?\DateTimeInterface $publishedAt): self
{
$this->publishedAt = $publishedAt;
return $this;
}
/**
* @return Collection|Like[]
*/
public function getLikes(): Collection
{
return $this->likes;
}
public function addLike(Like $like): self
{
if (!$this->likes->contains($like)) {
$this->likes[] = $like;
$like->setImage($this);
}
return $this;
}
public function removeLike(Like $like): self
{
if ($this->likes->removeElement($like)) {
// set the owning side to null (unless already changed)
if ($like->getImage() === $this) {
$like->setImage(null);
}
}
return $this;
}
/**
* @return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
$user->addLikedImage($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
$user->removeLikedImage($this);
}
return $this;
}
public function getMimetype(): ?string
{
return $this->mimetype;
}
public function setMimetype(string $mimetype): self
{
$this->mimetype = $mimetype;
return $this;
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\User;
use App\Form\FormRegisterUserType;
use App\Form\FormUpdateUserInfoType;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @var EntityManagerInterface
*/
private $manager;
public function __construct(EntityManagerInterface $manager)
{
$this->manager = $manager;}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils , Request $request): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
//$message = "";
if ($message = $request->query->get('message')) {}
//dd($message);
/* if (isset($_GET["message"]) && $_GET('message') != "") {
$message = $_GET["message"];
}*/
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error, 'message' => $message]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout(Response $response)
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* @Route("/register", name="app_registration")
*
* @param User $user
* @param Request $request
* @param UserPasswordEncoderInterface $userPasswordEncoder
* @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/
public function register( Request $request, UserPasswordEncoderInterface $userPasswordEncoder )
{
$form = $this->createForm(FormRegisterUserType::class);
$form->handleRequest($request);
$error = '';
if($form->isSubmitted() && $form->isValid() && $request->isMethod('POST')) {
/** @var User $user */
$user = $form->getData();
if($form['Username']->getData()) {
$user->setUsername($form['Username']->getData());
}
if($form['Password']->getData()) {
$user->setPassword($userPasswordEncoder->encodePassword($user, $form['Password']->getData()));
}
$user->setRegisteredAt(new \DateTime("now"));
$user->setRoles(['ROLE_USER']);
if ($form['agreeTerms']->getData() === true) {
$user->agreedTermsAt();
}
$em = $this->getDoctrine()->getManager();
//try {
$em->persist($user);
$em->flush();
return $this->redirectToRoute('app_login', ['message' => "registration successfull, please sign in"] );
/* } catch (\Exception $e) {
$error = "zadane uzivatelske meno sa pouziva";
}*/
}
return $this->render('security/register.html.twig', [
'registrationForm' => $form->createView(),
'error' => $error
]
);
}
/**
* @param User $user
* @param Request $request
* @param UserPasswordEncoderInterface $userPasswordEncoder
* @param EntityManagerInterface $manager
* @Route("/user/{id}/update" , name="app_update")
*
*/
public function update(User $user,Request $request , UserPasswordEncoderInterface $userPasswordEncoder, EntityManagerInterface $manager) {
$form = $this->createForm(FormUpdateUserInfoType::class, $user );
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid() && $request->isMethod('POST')) {
/** @var User $user */
$user = $form->getData();
if($form['Username']->getData()) {
$user->setUsername($form['Username']->getData());
}
if($form['Password']->getData()) {
$user->setPassword($userPasswordEncoder->encodePassword($user, $form['Password']->getData()));
}
if($form['email']->getData()) {
$user->setEmail($form['email']->getData());
}
$manager = $this->getDoctrine()->getManager();
$manager->persist($user);
$manager->flush();
return $this->redirectToRoute('main_page', ['message' => " Your personal data successfully updated!"] );
}
return $this->render('security/update.html.twig', [
'updateForm' => $form->createView()
]);
}
}
<file_sep><?php
namespace App\Listeners;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
class ResponseListener
{
public function onKernelResponse(ResponseEvent $event)
{
$request = $event->getRequest();
if ($this->disableThisPageCache($request->getPathInfo())){
$headers = $event->getResponse()->headers;
$headers->set('Cache-Control', 'no-cache, no-store, must-revalidate'); // HTTP 1.1.
$headers->set('Pragma', 'no-cache'); // HTTP 1.0.
$headers->set('Expires', '0'); // Proxies.
}
}
private function disableThisPageCache($currentPath)
{
$paths = array('/admin', '/', '^/user');
foreach ($paths as $path) {
if ($this->checkPathBegins($currentPath, $path)) {
return true;
}
}
return false;
}
private function checkPathBegins($path, $string)
{
return substr($path, 0, strlen($string)) === $string;
}
}<file_sep><?php
namespace App\Service;
use App\Entity\Image;
use App\Repository\ImageRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
class SharingToggler {
/**
* @var ImageRepository
*/
private ImageRepository $repository;
/**
* @var Security
*/
private Security $security;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
public function __construct(ImageRepository $repository , Security $security , EntityManagerInterface $entityManager)
{
$this->repository = $repository;
$this->security = $security;
$this->entityManager = $entityManager;
}
public function toggleShare(string $filename , bool $public) {
/** @var Image $image */
$image = $this->repository->findOneBy(['originalName' => $filename]);
if ($image->getOwner() === $this->security->getUser()) {
$image->setPublic($public);
if ($public === true) {
$image->setPublishedAt(new \DateTime('now'));
} else if ($public === false) {
$image->setPublishedAt(null);
}
$this->entityManager->persist($image);
$this->entityManager->flush();
return true;
}
return false;
}
}<file_sep><?php
namespace App\Entity;
use App\Repository\AlbumRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use JetBrains\PhpStorm\Pure;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass=AlbumRepository::class)
*/
class Album
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
* @Groups("main")
*/
private $id;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Groups("main")
* @Assert\Unique(message="Album already exists")
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="albums")
* @ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* @ORM\ManyToMany(targetEntity=Image::class, inversedBy="albums")
*
*/
private Collection $image;
public function __construct()
{
$this->image = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getOwner(): ?User
{
return $this->owner;
}
public function setOwner(?User $owner): self
{
$this->owner = $owner;
return $this;
}
/**
* @return Collection|Image[]
*/
public function getImage(): Collection
{
return $this->image;
}
public function addImage(Image $image): self
{
if (!$this->image->contains($image)) {
$this->image[] = $image;
}
return $this;
}
public function removeImage(Image $image): self
{
$this->image->removeElement($image);
return $this;
}
}
<file_sep>import axios from "axios";
import $ from "jquery";
export function fetchOwnedImages() {
return axios.get('/owned/images');
}
export function fetchImage(filename) {
return axios.get('/photos/'.filename);
}
export function fetchLatestImages() {
return axios.get('/latest/uploaded/photo');
}
export function deleteImage(name) {
return axios.delete('/delete/image/'+ name);
}
export function fetchImages() {
return axios.get('/get/images');
}
export function getImageInfo(filename) {
return axios.get('/get/image/info/' + filename)
}
export function makePublic(filename) {
return axios.post('/make/public/' + filename)
}
export function makePrivate(filename) {
return axios.post('/make/private/' + filename)
}
export function fetchPublicImages() {
return axios.get('/get/public/images')
}
export function likePhoto(filename) {
return axios.post('/like/photo/' + filename)
}
export function fetchLikedImages() {
return axios.get('/get/liked/images')
}
export function unlikePhoto(filename) {
return axios.post('/unlike/photo/' + filename)
}
export function downloadImage(filename) {
return axios.get('/download/image/' + filename)
}<file_sep>import './styles/main.css';
// start the Stimulus application
import $ from 'jquery';
import './bootstrap';
require('bootstrap')<file_sep><?php
namespace App\Service;
use App\Entity\Image;
use Doctrine\ORM\EntityManagerInterface;
use League\Flysystem\FilesystemInterface;
use mysql_xdevapi\Exception;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Core\Security;
use function Symfony\Component\String\s;
class UploaderHelper
{
/** to public path */
const IMAGE_DIRECTORY = '/var/uploadedPhotos';
/**
* @var KernelInterface
*/
private KernelInterface $kernel;
/**
* @var Security
*/
private Security $security;
/**
* @var FilesystemInterface
*/
private FilesystemInterface $filesystem;
/**
* @var EntityManagerInterface
*/
public function __construct(FilesystemInterface $uploadFilesystem, LoggerInterface $logger, KernelInterface $kernel, Security $security )
{
$this->logger = $logger;
$this->kernel = $kernel;
$this->security = $security;
$this->filesystem = $uploadFilesystem;
}
public function uploadFile(File $uploadedFile): string
{
/*/** @var Image $image */
//$image = new Image();
if ($uploadedFile instanceof UploadedFile) {
$originalFilename= $uploadedFile->getClientOriginalName();
} else {
$originalFilename = $uploadedFile->getFilename();
}
//$destination = $this->kernel->getProjectDir().'/public/photos';
$newFilename = pathinfo($originalFilename, PATHINFO_FILENAME).'-'.uniqid().'.'.$uploadedFile->guessExtension();
//dd($newFilename);
$stream = fopen($uploadedFile->getPathname(), 'r');
$result = $this->filesystem->writeStream(
$originalFilename,
$stream
);
if (is_resource($stream)) {
fclose($stream);
}
if ($result === false) {
throw new \Exception(sprintf('Could not write uploaded file "%s"', $newFilename));
}
//$uploadedFile->move($destination, $newFilename);
/* $stream = fopen($uploadedFile->getPathname(), 'r');
$this->privateFileSystem->writeStream( self::IMAGE_DIRECTORY.'/'.$newFilename, $stream);*/
//$uploadedFilename = $uploaderHelper->uploadFile($uploadedFile);
/*if (is_resource($stream)) {
fclose($stream);
}*/
/* $stream = fopen($file->getPathname(), 'r');
$result = $this->filesystem->writeStream(
$directory.'/'.$newFilename,
$stream,
[
'visibility' => $isPublic ? AdapterInterface::VISIBILITY_PUBLIC : AdapterInterface::VISIBILITY_PRIVATE
]
);
if ($result === false) {
throw new \Exception(sprintf('Could not write uploaded file "%s"', $newFilename));
}
if (is_resource($stream)) {
fclose($stream);
}*/
return $newFilename;
}
public function getFullPath(string $filename): string
{
return $this->kernel->getProjectDir().UploaderHelper::IMAGE_DIRECTORY.'/'.$filename;
}
public function deleteFromSystem(string $filename) {
$this->filesystem->delete($filename);
}
/**
* @param string $filename
* @return resource
*/
public function readStream(string $filename) {
$resource = $this->filesystem->readStream($filename);
if ($resource === false) {
throw new \Exception(sprintf('Error opening stream for "%s"', $filename));
}
return $resource;
}
}
<file_sep><?php
namespace App\Service;
use App\Entity\Image;
use App\Repository\ImageRepository;
use Symfony\Component\Security\Core\Security;
class ThumbnailProvider {
/**
* @var ImageRepository
*/
private ImageRepository $imageRepository;
/**
* @var Security
*/
private Security $security;
/**
* @var UploaderHelper
*/
private UploaderHelper $uploaderHelper;
public function __construct(ImageRepository $imageRepository , Security $security, UploaderHelper $uploaderHelper)
{
$this->imageRepository = $imageRepository;
$this->security = $security;
$this->uploaderHelper = $uploaderHelper;
}
/**
* @param string $originalName
* @throws \ImagickException
*/
function provideThumbnail(string $originalName, $columns, $rows) {
$publicName = $this->uploaderHelper->getFullPath($originalName);
$imagick = new \Imagick($publicName);
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage($columns, $rows, false, false);
header("Content-Type: image/jpg");
/*$response = new BinaryFileResponse($imagick->getFilename());
return $response;*/
echo $imagick->getImageBlob();
}
}<file_sep><?php
namespace App\Controller;
use App\Entity\Image;
use App\Form\ImageUpdateType;
use App\Repository\ImageRepository;
use App\Service\SharingToggler;
use App\Service\ThumbnailProvider;
use App\Service\UploaderHelper;
use Doctrine\ORM\EntityManagerInterface;
use ImagickException;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use phpDocumentor\Reflection\Types\This;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Mime\MimeTypes;
class ImageController extends AbstractController
{
/**
* @var Security
*/
private Security $security;
/**
* @var ImageRepository
*/
private ImageRepository $imageRepository;
/**
* @var UploaderHelper
*/
private UploaderHelper $uploaderHelper;
/**
* @var string[]
*/
private array $filenamesToRender;
/**
* @var LoggerInterface
*/
private LoggerInterface $logger;
/**
* @var SharingToggler
*/
private SharingToggler $sharingToggler;
/**
* @var ThumbnailProvider
*/
private ThumbnailProvider $thumbnailProvider;
public function __construct(Security $security , ImageRepository $imageRepository , UploaderHelper $uploaderHelper, LoggerInterface $logger , SharingToggler $sharingToggler,
ThumbnailProvider $thumbnailProvider) {
$this->security = $security;
$this->imageRepository = $imageRepository;
$this->uploaderHelper = $uploaderHelper;
$this->filenamesToRender = array();
$this->logger = $logger;
$this->sharingToggler = $sharingToggler;
$this->thumbnailProvider = $thumbnailProvider;
}
/**
* @Route("/image", name="image")
*/
public function index(): Response
{
return $this->render('image/index.html.twig', [
'controller_name' => 'ImageController',
]);
}
/**
*
* @Route("/latest/photos/{originalFilename}" , name="latest_photos" , methods={"GET"} )
* @throws ImagickException
*/
public function latestPhotosAjax(Request $request , string $originalFilename , KernelInterface $kernel) {
$image = $this->imageRepository->findOneBy(['originalName' => $originalFilename]);
if ($image->getOwner() === $this->security->getUser()) {
$imagePath = $this->uploaderHelper->getFullPath($image->getOriginalName());
//dump($imagePath);
// print_r($imagePath);
$imagick = new \Imagick($imagePath);
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(300, 200, false, false);
header("Content-Type: image/jpg");
/*$response = new BinaryFileResponse($imagick->getFilename());
return $response;*/
echo $imagick->getImageBlob();
// $response = new BinaryFileResponse($imagePath);
// return $response;
}
//dd($response);
return new JsonResponse("Not authorized to view this photo", 401);
//kernel->getProjectDir().UploaderHelper::IMAGE_DIRECTORY.'/'.$image->getFilename()
}
//'/home/jakub/Documents/securitySkuska/var/uploadedPhotos/satellite-image-of-globe-602321652ec51.jpg'
/**
* @Route("/photo/{filename}", name="send_thumbnail", methods={"GET"} )
*
* @param string $filename
* @throws ImagickException
*/
public function thumbnailImage(Request $request, string $filename) {
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
if ($image->getOwner() === $this->security->getUser()) {
$this->thumbnailProvider->provideThumbnail($filename,300,200);
/*$publicName = $this->uploaderHelper->getFullPath($filename);
$imagick = new \Imagick($publicName);
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(300, 200, false, false);
header("Content-Type: image/jpg");
/*$response = new BinaryFileResponse($imagick->getFilename());
return $response;*/
/*echo $imagick->getImageBlob();*/
}
}
/**
* @Route("/public/photo/{filename}", name="send_public_thumbnail", methods={"GET"} )
*
* @param string $filename
* @throws ImagickException
*/
public function thumbnailPublicImage(string $filename) {
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
$this->thumbnailProvider->provideThumbnail($filename,300,200);
/*$publicName = $this->uploaderHelper->getFullPath($filename);
$imagick = new \Imagick($publicName);
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(300, 200, false, false);
header("Content-Type: image/jpg");
/*$response = new BinaryFileResponse($imagick->getFilename());
return $response;*/
/*echo $imagick->getImageBlob();*/
}
/**
* @Route("send/photo/{originalName}" , name="latest_image", methods={"GET"})
* @param string $originalName
* @return BinaryFileResponse|JsonResponse
*/
public function latestPhotosByOriginalName(string $originalName) {
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $originalName]);
if ($image->getOwner() === $this->security->getUser()) {
$imagePath = $this->uploaderHelper->getFullPath($image->getFilename());
$response = new BinaryFileResponse($imagePath);
return $response;
}
return $this->json("Not authorized to view this photo", 401);
}
/**
* @Route("/owned/images", name="get_owned_images", methods={"GET"})
*/
public function ownedImages(Request $request) {
$ownedImages = $this->imageRepository->getOwnedImagesFilenames(null, null);
//dump($ownedImages);
//print_r($ownedImages);
//$this->logger->log($ownedImages,"logging data");
return new JsonResponse($ownedImages, 200);
}
/**
*@Route("/upload/dropzone", name="dropzone_upload")
*/
public function handleDropzone(Request $request , UploaderHelper $uploaderHelper , Security $security , EntityManagerInterface $entityManager, ValidatorInterface $validator ) {
/** @var UploadedFile $uploadedFile */
$uploadedFile = $request->files->get('dropzone');
$albumName = $request->request->get('data');
//$albumName = $request->request->get('hiddenDropzoneInput');
$violations = $validator->validate(
$uploadedFile,
new \Symfony\Component\Validator\Constraints\Image(),
);
if ($violations->count() > 0) {
return new JsonResponse("bad file type", 400);
}
/** @var Image $image */
$image = new Image();
$newFilename = $uploaderHelper->uploadFile($uploadedFile);
$mimeTypes = new MimeTypes();
$mimeType = $mimeTypes->guessMimeType( $uploaderHelper->getFullPath($uploadedFile->getClientOriginalName()));
array_push($this->filenamesToRender, $newFilename);
$image->setPublic(false);
$image->setMimetype($mimeType);
$image->setFilename($newFilename);
$image->setOwner($security->getUser());
$image->setUploadedAt(new \DateTimeImmutable("now"));
$originalFilename = $uploadedFile->getClientOriginalName();
$clientNameExtension = pathinfo($originalFilename, PATHINFO_EXTENSION);
if ($uploadedFile->guessExtension() === 'jpg' || $uploadedFile->guessExtension() === 'png' || $uploadedFile->guessExtension() === 'gif') {
$newFilename = $originalFilename;
} else {
$newFilename = pathinfo($originalFilename, PATHINFO_FILENAME).".".$uploadedFile->guessExtension();
}
$image->setOriginalName($newFilename);
if($albumName !== '') {
$ownedAlbums = $this->getUser()->getAlbums();
foreach ($ownedAlbums as $album) {
if ($album->getName() === $albumName) {
$album->addImage($image);
}
}
}
$entityManager->persist($image);
$entityManager->flush();
return new JsonResponse($albumName, 201);
/* $uploadedFile = $request->files->get('dropzone');
dump($uploadedFile);
;*/
}
/**
* @Route("/latest/uploaded/photo" , name="latest_photo" , methods={"GET"})
* @throws ImagickException
*/
public function getLatestPhotoUploadedName(Request $request) {
$number = $this->imageRepository->getLastOwnedId();
$response = $this->filenamesToRender;
//dd($number[0][1]);
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['id' => $number[0][1]]);
//dd($image);
//$publicName = $this->uploaderHelper->getFullPath($image->getFilename());
/*$imagick = new \Imagick($publicName);
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(300, 300, true, true);
header("Content-Type: image/jpg");
/*$response = new BinaryFileResponse($imagick->getFilename());
return $response;*/
//echo $imagick->getImageBlob();
//print_r($photo);
$this->filenamesToRender = array();
return new JsonResponse($image->getFilename(), 200);
}
/**
* @Route("/send/fullPhoto/{filename}", name="send_full_photo")
*/
public function sendPhoto(string $filename)
{
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
if($image->getPublic()) {
$imagePath = $this->uploaderHelper->getFullPath($image->getOriginalName());
$response = new BinaryFileResponse($imagePath);
return $response;
}
if ($image->getOwner() === $this->security->getUser()) {
$imagePath = $this->uploaderHelper->getFullPath($image->getOriginalName());
$response = new BinaryFileResponse($imagePath);
return $response;
}
return $this->json("Not authorized to view this photo", 401);
}
/**
* @Route("/delete/image/{filename}", name="delete_image" , methods={"DELETE"})
*/
public function deleteImage(Request $request, string $filename, EntityManagerInterface $entityManager) {
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
if($image->getOwner() === $this->security->getUser()) {
$entityManager->remove($image);
$entityManager->flush();
$this->uploaderHelper->deleteFromSystem($filename);
return $this->json($filename . " was deleted ", 204);
}
return $this->json("Not authorized to delete some of the files", 401);
}
/**
* @Route("/get/images" , name="get_images")
*/
public function getImages() {
$images = $this->security->getUser()->getImages();
return $this->json($images, 200 ,[],[
'groups' => ['image']
]);
}
/**
* @Route("/get/image/info/{filename}" , name="get_image_info" , methods={"GET"})
*/
public function getimageInfo(string $filename, Request $request) {
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
if ($image->getOwner() === $this->security->getUser()) {
return $this->json($image, 200, [], [
'groups' => ['image']
]);
} else {
return $this->json("Not authorized to delete some of the files", 401);
}
}
/**
* @param string $filename
* @param Request $request
* @param bool $public
* @param EntityManagerInterface $entityManager
* @return JsonResponse
* @Route("/make/public/{filename}", name="make_public", methods={"POST"})
*/
public function makePublic(string $filename ) {
if ($this->sharingToggler->toggleShare($filename,true)) {
return $this->json("photo is shared now", 201);
} else {
return $this->json("Not authorized to manipulate some of the files", 401);
}
}
/**
* @Route("/make/private/{filename}" , name="make_private" , methods={"POST"})
*/
public function makePrivate(string $filename, Request $request, EntityManagerInterface $entityManager) {
if ($this->sharingToggler->toggleShare($filename,false)) {
return $this->json("photo is private now", 201);
} else {
return $this->json("Not authorized to manipulate some of the files", 401);
}
}
/**
* @Route("/download/image/{filename}" , name="download_image" , methods={"GET"})
*/
public function downloadImage(string $filename) {
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
if ($image->getOwner() === $this->security->getUser()) {
$response = new StreamedResponse(function() use ($filename) {
$outputStream = fopen('php://output', 'wb');
$filestream = $this->uploaderHelper->readStream($filename);
stream_copy_to_stream($filestream , $outputStream);
});
$response->headers->set('Content-Type' , $image->getMimetype());
$disposition = HeaderUtils::makeDisposition(
HeaderUtils::DISPOSITION_ATTACHMENT,
$image->getFilename()
);
//dd($disposition);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
return $this->json("Not authorized to delete this file ", 401);
}
}
<file_sep><?php
namespace App\Repository;
use App\Entity\Image;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Security;
/**
* @method Image|null find($id, $lockMode = null, $lockVersion = null)
* @method Image|null findOneBy(array $criteria, array $orderBy = null)
* @method Image[] findAll()
* @method Image[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ImageRepository extends ServiceEntityRepository
{
/**
* @var Security
*/
private Security $security;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $manager;
public function __construct(ManagerRegistry $registry, Security $security, EntityManagerInterface $manager)
{
parent::__construct($registry, Image::class);
$this->security = $security;
$this->manager = $manager;
}
/**
* @param string|null $orderByColumn
* @param string|null $direction
* @return string[] Returns array of owned images filenames
*/
public function getOwnedImagesFilenames(?string $orderByColumn, ?string $direction): array
{
return $this->createQueryBuilder('r')
->select('r.originalName, r.latitude, r.longitude, r.UploadedAt')
->andWhere('r.owner = :val' )
->setParameter('val' , $this->security->getUser())
->orderBy($orderByColumn ?: 'r.UploadedAt', $direction ?: "ASC" )
->getQuery()
->getResult()
;
$returnArray = array();
foreach ($entities as $entity) {
$returnArray[get_class($entity)] = $entity;
}
return $returnArray;
}
public function getLatestPhoto() {
return $this->createQueryBuilder('q')
->select('q.filename')
->join('q.image', 'nq')
->from('image','i')
->select('MAX(i.UploadedAt) as max_date')
->andWhere('q.owner = :val' )
->setParameter('val', $this->security->getUser())
->getQuery()
->getResult();
//->groupBy('q.filename');
//->andHaving(max('q.UploadedAt'));
}
public function getLastUploaded() {
$rsm = new ResultSetMapping();
$query = $this->manager->createNativeQuery('SELECT filename from image ', $rsm);
return $query->getResult();
}
public function getLastOwnedId() {
return $this->createQueryBuilder('r')
->select('max(r.id)')
->andWhere('r.owner = :val' )
->setParameter('val', $this->security->getUser())
->getQuery()
->getResult();
}
public function getPublicImages() {
return $this->createQueryBuilder('r')
->select('r.originalName, r.latitude, r.longitude, r.UploadedAt , r.publishedAt , o.username ')
->join('r.owner', 'o')
//->join('r.likes', 'l')
->andWhere('r.public = :val' )
->setParameter('val' , 1)
//->orderBy($orderByColumn ?: 'r.UploadedAt', $direction ?: "ASC" )
->getQuery()
->getResult();
}
public function getPublicImages2() {
$result = $this->findBy(['public' => 1]);
return array($result);
}
public function getImageLikes($filename) {
return $this->createQueryBuilder('l')
->select(' o.username')
->join('l.likes', 'j')
->join('l.owner', 'o')
->andWhere('l.originalName = :val')
->setParameter('val' , $filename)
->getQuery()
->getResult();
}
public function getLikedImages() {
return $this->createQueryBuilder('c')
->select('c.originalName, c.latitude, c.longitude, c.UploadedAt , c.publishedAt')
->join('c.users', 'u')
->andWhere('u.username = :val')
->setParameter('val', $this->security->getUser()->getUsername())
->getQuery()
->getResult();
}
// /**
// * @return Image[] Returns an array of Image objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('i')
->andWhere('i.exampleField = :val')
->setParameter('val', $value)
->orderBy('i.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Image
{
return $this->createQueryBuilder('i')
->andWhere('i.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
<file_sep><?php
namespace App\Service;
use App\Repository\ImageRepository;
use Symfony\Component\Security\Core\Security;
class OwnedImagesRenderer {
/**
* @var ImageRepository
*/
private ImageRepository $imageRepository;
/**
* @var Security
*/
private Security $security;
public function __construct(ImageRepository $imageRepository , Security $security)
{
$this->imageRepository = $imageRepository;
$this->security = $security;
}
}<file_sep><?php
namespace App\Controller;
use ApiPlatform\Core\Validator\ValidatorInterface;
use App\Entity\Image;
use App\Form\ImageUpdateType;
use App\Repository\ImageRepository;
use App\Service\UploaderHelper;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
//use Symfony\Component\HttpFoundation\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class MainPageController extends AbstractController
{
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* @Route("/", name="main_page")
*/
public function uploadFileAction(Request $request , EntityManagerInterface $entityManager, Security $security , UploaderHelper $uploaderHelper, ImageRepository $imageRepository , ValidatorInterface $validator): Response
{
if ($message = $request->query->get('message')) {}
/*if(!$this->getUser()) {
return $this->redirectToRoute('app_login', ['message' => "you must log in"] );
}*/
$ownedFiles = $imageRepository->findBy(['owner' => $security->getUser()->getId()]);
//dd($ownedFiles);
$form = $this->createForm(ImageUpdateType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var UploadedFile $uploadedFile */
$uploadedFile = $form['image']->getData();
/** @var Image $image */
$image = new Image();
$newFilename = $uploaderHelper->uploadFile($uploadedFile);
$image->setPublic(false);
$image->setFilename($newFilename);
$image->setOwner($security->getUser());
$image->setUploadedAt(new \DateTimeImmutable("now"));
$image->setOriginalName($uploadedFile->getFilename());
$entityManager->persist($image);
$entityManager->flush();
}
return $this->render('main_page/MainPage.html.twig', [
'uploadForm' => $form->createView(),
'message' => $message,
'ownedImages' => $ownedFiles,
]);
}
}
<file_sep><?php
namespace App\Controller;
use App\Entity\Image;
use App\Entity\Tag;
use App\Repository\ImageRepository;
use App\Repository\TagRepository;
use Doctrine\ORM\EntityManagerInterface;
use phpDocumentor\Reflection\Types\This;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class TagController extends AbstractController
{
/**
* @var Security
*/
private Security $security;
/**
* @var ImageRepository
*/
private ImageRepository $imageRepository;
/**
* @var TagRepository
*/
private TagRepository $tagRepository;
public function __construct(Security $security , ImageRepository $imageRepository, TagRepository $tagRepository) {
$this->security = $security;
$this->imageRepository = $imageRepository;
$this->tagRepository = $tagRepository;
}
/**
* @Route("/add/tags/{filename}", name="add_tags")
*/
public function addTag(string $filename , Request $request, EntityManagerInterface $entityManager )
{
/** @var Image $image */
$image = $this->imageRepository->findOneBy(['originalName' => $filename]);
if (!($this->security->getUser() === $image->getOwner())) {
return $this->json("Not authorized", 401);
}
$data = json_decode($request->getContent(),true);
$tags = $data["tags"];
$tagsInDatabase = $this->tagRepository->findAll();
foreach($tags as $tag) {
$found = false;
foreach ($tagsInDatabase as $dtag) {
if ($tag === $dtag->getName()) {
$image->addTag($dtag);
$entityManager->persist($image);
$entityManager->flush();
$found = true;
break;
}
}
if(!$found) {
$newtag = new Tag();
$newtag->setName($tag);
$image->addTag($newtag);
$entityManager->persist($newtag);
$entityManager->persist($image);
$entityManager->flush();
}
$found = false;
}
return $this->json("tags were added", 201);
}
}
|
81b5aed009f25f7274992fe29bb75c9f7a45f4ca
|
[
"JavaScript",
"PHP"
] | 21
|
PHP
|
propolis12/backup
|
ad3e977f9cf62173863edb78b4f8e39388ad2247
|
5069725a1259b98e0aaa98c971bef20ecfb61cd1
|
refs/heads/master
|
<repo_name>Shashank2512/Game-of-the-Amazons<file_sep>/src/board/Board.java
package board;
/**
* Represents a single state in the game
*/
public class Board {
public static void main(String[] args) {
System.out.println(new Board(10, 10));
}
public static final int EMPTY = 0;
public static final int ARROW = 1;
public static final int AMAZON = 2;
// arrays storing the current positions of all eight amazons
private int[][] whiteAmazons = new int[4][2];
private int[][] blackAmazons = new int[4][2];
private int[][] board;
private int rows;
private int cols;
/**
* Constructor that takes the size of the board as arguments
* @param rows rows
* @param cols columns
*/
public Board(int rows, int cols) {
this.rows = rows;
this.cols = cols;
board = new int[rows][cols];
placeAmazons();
}
/**
* marks positions on board that have amazons initially and
* stores positions of all eight amazons in the two arrays
* @param rows rows
* @param cols columns
*/
private void placeAmazons() {
whiteAmazons[0] = new int[] {(rows/2)/2 + 1, 0};
board[(rows/2)/2 + 1][0] = AMAZON;
whiteAmazons[1] = new int[] {0, (cols/2)/2 + 1};
board[0][(cols/2)/2 + 1] = AMAZON;
whiteAmazons[2] = new int[] {0, cols - 1 - (cols/2)/2 + 1};
board[0][cols - 1 - ((cols/2)/2 + 1)] = AMAZON;
whiteAmazons[3] = new int[] {(rows/2)/2 + 1, cols - 1};
board[(rows/2)/2 + 1][cols - 1] = AMAZON;
blackAmazons[0] = new int[] {rows - 1 - (rows/2)/2 + 1, 0};
board[rows - 1 - ((rows/2)/2 + 1)][0] = AMAZON;
blackAmazons[1] = new int[] {rows - 1, (cols/2)/2 + 1};
board[rows - 1][(cols/2)/2 + 1] = AMAZON;
blackAmazons[2] = new int[] {rows - 1, cols - 1 - (cols/2)/2 + 1};
board[rows - 1][cols - 1 - ((cols/2)/2 + 1)] = AMAZON;
blackAmazons[3] = new int[] {rows - 1 - (rows/2)/2 + 1, cols - 1};
board[rows - 1 - ((rows/2)/2 + 1)][cols - 1] = AMAZON;
}
/*placing new Arrow at position (r,c)*/
private void placeArrow(int r, int c)
{
board[r][c]=1;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" ");
for (int i = 0; i < cols; i++) {
sb.append(i);
sb.append(" ");
}
sb.append("\n");
for (int i = 0; i < rows; i++) {
sb.append(i);
sb.append(" ");
for (int j = 0; j < cols; j++) {
if (board[i][j] == AMAZON) {
sb.append("A ");
} else if (board[i][j] == ARROW) {
sb.append("O ");
} else {
sb.append(" ");
}
}
sb.append("\n");
}
return sb .toString();
}
}
<file_sep>/src/Heuristic_Function.java
/*
* @author: <NAME> and <NAME>
*/
public class Heuristic_Function
{
public static int black_size, white_size;
public static int compute_heuristic(Board b)
{
return mobility_evaluator(b);
}
/*
* To do : Optimize it to use less memory and avoid generating boards unnecessarily
* Lower the heuristic more favorable to White Amazon
*/
private static int mobility_evaluator(Board b)
{
Moves mov=new Moves();
mov.gen_move(b, 'W');
white_size=mov.get_size();
mov.clean_mov();
mov.gen_move(b, 'B');
black_size=mov.get_size();
mov.clean_mov();
return black_size-white_size;
}
public static int get_black_size()
{
return black_size;
}
public static int get_white_size()
{
return white_size;
}
}
<file_sep>/README.md
Game-of-the-Amazons
===================
|
e89b53623f1a386ac5819bce39a0501b2c342d44
|
[
"Markdown",
"Java"
] | 3
|
Java
|
Shashank2512/Game-of-the-Amazons
|
13c64c43e9a86e165aa08c9628ad421bed9b06d0
|
a8e0ebf2bf872c283da5c545477ef2e241434374
|
refs/heads/master
|
<repo_name>anikinael/git-repo<file_sep>/footer.php
<div class="footer">
Copyright © <?php echo date("Y")?> <NAME>
<div><file_sep>/guess.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Иг<NAME>гадайка</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
var answer = parseInt(Math.random() * 100);
var isStart = false;
const totalTrys = 5;
var currTrysCount = 0;
function readInt(){
let res = +document.getElementById("userAnswer").value;
document.getElementById("userAnswer").value = "";
return res;
}
function writeElem(text, id){
document.getElementById(id).innerHTML = text;
}
function OnOffElement(id, isHide){
if (isHide) {
document.getElementById(id).style.display = "none";
} else {
document.getElementById(id).style.display = "inline";
}
}
function checkAnswerAndTryCount(uanswer){
currTrysCount++;
if((totalTrys - currTrysCount) == 0){
writeElem("Увы, Вы проиграли! У вас закончились попытки", "brief");
OnOffElement("userAnswer", true);
writeElem("Начать сначала", "button");
isStart = false;
} else {
writeElem("Вы ввели слишком " + ((uanswer > answer) ? "большое" : "маленькое") + " число. Осталось попыток " + (totalTrys - currTrysCount), "brief");
}
}
function guess(){
if (!isStart){
writeElem("Угадайте число от 0 до 100", "brief");
writeElem("Ответить", "button");
OnOffElement("userAnswer", false);
isStart = true;
currTrysCount = 0;
} else {
var userAnswer = readInt();
if(userAnswer == answer){
writeElem("Поздравляю, Вы победили!", "brief");
OnOffElement("userAnswer", true);
writeElem("Начать сначала", "button");
isStart = false;
} else {
checkAnswerAndTryCount(userAnswer);
}
}
}
</script>
</head>
<body>
<div class="content">
<?php include "menu.php"?>
<div class="contentWrap">
<div class="content">
<div class="center">
<h1>Игра угадайка</h1>
<div class="box">
<p id="brief">Угадайте число от 0 до 100</p>
<input type="text" id="userAnswer">
<br>
<a href="#" onClick="guess()" id="button">Начать</a>
</div>
</div>
</div>
</div>
</div>
<?php include "footer.php"?>
</body>
<script type="text/javascript">
document.getElementById("userAnswer").style.display = "none";
</script>
</html><file_sep>/puzzle.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Игра в загадки</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript">
var score = 0;
function checkAnswer(inputId, answers){
var userAnswer = document.getElementById(inputId).value;
userAnswer = userAnswer.toLowerCase();
for(var i = 0; i < answers.length; i++){
if(userAnswer == answers[i]){
score++;
break;
}
}
}
function checkAnswers() {
checkAnswer("userAnswer1", ["имя"]);
checkAnswer("userAnswer2", ["владивосток"]);
checkAnswer("userAnswer3", ["соль"]);
alert("Вы отгадали " + score + " загадок");
}
</script>
</head>
<body>
<div class="content">
<?php include "menu.php"?>
<div class="contentWrap">
<div class="content">
<div class="center">
<h1>Игра в загадки</h1>
<div class="box">
<?php
$score = 0;
mb_internal_encoding("UTF-8");
if (isset($_GET["userAnswer1"]) && isset($_GET["userAnswer2"]) && isset($_GET["userAnswer3"])){
$userAnswer1=$_GET["userAnswer1"];
$userAnswer2=$_GET["userAnswer2"];
$userAnswer3=$_GET["userAnswer3"];
$answer1 = "имя";
$answer2 = "владивосток";
$answer3 = "соль";
$str = mb_strtolower($userAnswer1);
if ($str == $answer1)
$score++;
$str = mb_strtolower($userAnswer2);
if ($str == $answer2)
$score++;
$str = mb_strtolower($userAnswer3);
if ($str == $answer3)
$score++;
}
?>
<form method="GET">
<p>Что принадлежит каждому из вас, но другие этим пользуются чаще, чем вы?</p>
<input type="text" name="userAnswer1">
<p>В каком городе спрятались мужское имя и сторона света?</p>
<input type="text" name="userAnswer2">
<p>Какая нота и продукт называются одинаково?</p>
<input type="text" name="userAnswer3">
<br>
<br>
<br>
<input type="submit" value="Ответить"/>
</form>
<?php
if ($score > 0)
{
$str_puzzle = "и";
if ($score == 1)
$str_puzzle = "у";
echo "<p>Поздравляем вы отгадали $score загадк$str_puzzle</p>";
}
?>
</div>
</div>
</div>
</div>
</div>
<?php include "footer.php"?>
</body>
</html><file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Личный сайт студента GeekBrains</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="content">
<?php include "menu.php"?>
<h1>Личный сайт студента GeekBrains</h1>
<div class="center">
<img src="img/photo.jpg">
<div class="box_text">
<p><b>Добрый день.</b> Меня зовут <i><NAME></i>. Я совсем недавно начала программировать, однако уже написала свой первый сайт. Свой путь я начну с изучения языка программирования - Python. Выбор пал именно на него, тк до этого опыта в программирование не было. Данный язык дает возможность выбора, тк используется во многих IT-сферах.</p>
<p>В этом мне помог IT-портал <a href="https://geekbrains.ru">GeekBrains</a></p>
<p>На этом сайте вы сможете сыграть в несколько игр, которые я написала: <br>
<a href="index.php">Главная</a>
<a href="puzzle.php">Загадки,</a>
<a href="guess.php">Угадайка</a>
<a href="guessFor2.php">Угадайка на двоих</a>
<a href="pass-generator.php">Генератор пароля</a>
</p>
</div>
</div>
</div>
<div class="footer">
Copyright © <?php echo date("Y")?> <NAME>
<div>
</body>
</html><file_sep>/README.md
# git-repo
this could be you advertising
|
03e7a5b761aa04a963b1ea6c89b25a1f89054675
|
[
"Markdown",
"PHP"
] | 5
|
PHP
|
anikinael/git-repo
|
78855e105272e82b0fe537eac088a468d6d0a5b3
|
d816def2355073c5281d35c884c978fb3e3f3db0
|
refs/heads/master
|
<file_sep>package com.example.administrator.fragmentpractice;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class ContentActivity extends AppCompatActivity {
public static void actionStart(Context context, String newsTitle,
String newsContent) {
Intent intent = new Intent(context, ContentActivity.class);
intent.putExtra("news_title", newsTitle);
intent.putExtra("news_content", newsContent);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
String title = getIntent().getStringExtra("news_title");
String content = getIntent().getStringExtra("news_content");
// NewsContentFragment contentFragment = new NewsContentFragment();
// contentFragment.parseData(title,content);
// if (contentFragment != null) {
// getSupportFragmentManager().beginTransaction().add(R.id.content_container,contentFragment).commit();
// }
NewsContentFragment fragment =(NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
fragment.parseData(title,content);
}
}
<file_sep>package com.example.administrator.fragmentpractice;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class NewsIndexFragment extends Fragment implements AdapterView.OnItemClickListener {
private List<News> data;
private ListView listView;
private NewsAdapter adapter;
public NewsIndexFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.data = getNews();
adapter = new NewsAdapter(getContext(),R.layout.news_content,data);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_news_list, container, false);
listView = (ListView) v.findViewById(R.id.news_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return v;
}
private List<News> getNews() {
List<News> newsList = new ArrayList<News>();
News news1 = new News();
news1.setTitle("Succeed in College as a Learning Disabled Student");
news1.setContent("College freshmen will soon learn to live with a roommate, adjust to a new social scene and survive less-than-stellar dining hall food. Students with learning disabilities will face these transitions while also grappling with a few more hurdles.");
newsList.add(news1);
News news2 = new News();
news2.setTitle("Google Android exec poached by China's Xiaomi");
news2.setContent("China's Xiaomi has poached a key Google executive involved in the tech giant's Android phones, in a move seen as a coup for the rapidly growing Chinese smartphone maker.");
newsList.add(news2);
return newsList;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News news = data.get(position);
ContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
}
}
<file_sep>package com.example.administrator.fragmentpractice;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Administrator on 2017/1/13 0013.
*/
public class NewsAdapter extends ArrayAdapter {
private int resourceID;
public NewsAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
this.resourceID = resource;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
News news = (News) getItem(position);
View v = LayoutInflater.from(getContext()).inflate(resourceID,null);
TextView title = (TextView) v.findViewById(R.id.news_item_title);
title.setText(news.getTitle());
return v;
}
}
<file_sep>package com.example.administrator.fragmentpractice;
/**
* Created by Administrator on 2017/1/13 0013.
*/
public class News {
private String title;
private String content;
public void setContent(String context) {
this.content = context;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public String getTitle() {
return title;
}
}
<file_sep>package com.example.administrator.fragmentpractice;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class NewsContentFragment extends Fragment {
private TextView title, content;
private View v;
public NewsContentFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_news_content, container, false);
this.title = (TextView) v.findViewById(R.id.news_title1);
this.content = (TextView) v.findViewById(R.id.news_content1);
return v;
}
public void parseData(String title, String content) {
this.title.setText(title);
this.content.setText(content);
}
}
|
f1e63574e24462209a6152ef77176b549d13812a
|
[
"Java"
] | 5
|
Java
|
JasonBao-BB/NewsView
|
c2004af9e32c25844bd9a1d7921bf22dcfe8fde0
|
bd1c68fd437141a5587e9223aff0124491befa63
|
refs/heads/master
|
<repo_name>pinceladasdaweb/learn-react<file_sep>/002_props/app.js
'use strict';
var Hello = React.createClass({
render: function() {
return <h1>Hello {this.props.name} by React!</h1>;
}
});<file_sep>/001_helloworld/app.js
'use strict';
var Hello = React.createClass({
render: function() {
return <h1>Hello World by React!</h1>
}
});<file_sep>/README.md
# Learn React
Basic examples to learn React
|
186ec0ebb85044bdb37d5ac5b9dbbb913257fc51
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
pinceladasdaweb/learn-react
|
900524ab1b83e0dd7c5b8b527f40ea13b2a17424
|
fd454e79cadb041e7cbbd1db16f63c5531d42277
|
refs/heads/master
|
<file_sep>/*
--------------------------------------------------------
Editor
--------------------------------------------------------
*/
function getSelectedRange(editor) {
return { from: editor.getCursor(true), to: editor.getCursor(false) };
}
function autoFormatSelection(editor) {
var range = getSelectedRange(editor);
editor.autoFormatRange(range.from, range.to);
}
function commentSelection(isComment, editor) {
var range = getSelectedRange(editor);
editor.commentRange(isComment, range.from, range.to);
}
var Editor = function (parent, editorMode, data) {
let self = this;
this.newEditor = null;
// ---------- Create new editor ---------- //
this.newEditor = CodeMirror(parent, {
lineNumbers: true,
//theme:"icecoder",
// theme: "monokai",
theme: "material",
styleActiveLine: true,
matchBrackets: true,
// value: data,
// mode: "application/x-httpd-php",
mode: editorMode,
tabMode: "shift",
highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
indentUnit: 4,
smartIndent: true,
autoCloseBrackets: true,
autoCloseTags: true,
keyMap: 'sublime',
lineWrapping: true,
extraKeys: { "Ctrl-Q": function (cm) { cm.foldCode(cm.getCursor()); } },
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
autoRefresh: true,
autofocus: true,
//autoformat:true
});
CodeMirror.commands["selectAll"](this.newEditor);
// document.addEventListener('keydown', function (e) {
// if (e.ctrlKey == true && e.shiftKey == true && e.which == 70) {
// e.preventDefault();
// autoFormatSelection(self.newEditor);
// }
// if (e.ctrlKey == true && e.which == 191) {
// e.preventDefault();
// commentSelection(true, self.newEditor);
// }
// });
CodeMirror.commands["goLineEnd"](this.newEditor);
this.newEditor.setValue(data);
this.newEditor.setSize('100%', '100%');
this.getAllEditorInstance = function () {
var edIns = document.getElementsByClassName('CodeMirror');
return edIns;
}
this.getEditorCount = function () {
var edIns = document.getElementsByClassName('CodeMirror');
return edIns.length;
}
this.getEditorInstance = function () {
return this.newEditor;
}
this.getEditorValue = function () {
return this.newEditor.getValue();
}
this.setEditorValue = function (data) {
this.newEditor.setValue(data);
}
this.setTheme = function (theme) {
this.newEditor.setOption('theme', theme);
}
this.refresh = function () {
this.newEditor.refresh();
}
this.newEditor.refresh();
return this;
}<file_sep><?php
/* Save all files */
function saveAllFiles(){
// get ajax data
$phpData = file_get_contents('php://input');
$obj = json_decode( $phpData );
if (!is_dir('../code/' . $obj->dir)) {
mkdir('../code/' . $obj->dir, 0777, true);
}
$phpfile = fopen('../code/' . $obj->fileNamePath,'w');
if ($phpfile != null) {
fwrite($phpfile, $obj->data);
fclose($phpfile);
} else{
fclose($phpfile);
echo '<script type="text/javascript">alert("write error!...");</script>';
}
}
saveAllFiles();
?><file_sep>var el = document.getElementById("IDp");
el.addEventListener('mouseover', function(){
console.log('mouseover event!');
});
el.onmouseleave = function(){
console.log('mouseleave event!');
}
el.onclick = function(){ alert('mouseclick event!'); }<file_sep>/*
--------------------------------------------------------
File manager
--------------------------------------------------------
*/
/* ------ File manager start ------ */
var fileManager = function (parent) {
var self = this;
this.parent = parent;
/*
--------------------------------------------------------
File manager container
--------------------------------------------------------
*/
this.fileManagerContainer = new Element();
this.fileManagerContainer.create('div', 'IDfileManagerContainer', 'fileManagerContainer', this.parent);
/*
--------------------------------------------------------
File Menu container
--------------------------------------------------------
*/
this.fileMenuContainer = new Element();
this.fileMenuContainer.create('div', 'IDfileManagerMenuContainer', '', this.fileManagerContainer.object);
/*
--------------------------------------------------------
File Menu
--------------------------------------------------------
*/
this.fileMenu = new Element();
//this.fileMenu.create('ul', 'IDfileMenu', 'fileMenu', this.fileMenuContainer.object);
this.fileMenu.create('ul', 'IDfileMenu', 'fileMenu', document.getElementById('IDmainMenuContainer'));
let inBefore = document.getElementById('IDmainMenuContainer');
inBefore.insertBefore(this.fileMenu.object, document.getElementById('IDmainMenuRightSide'));
/*
--------------------------------------------------------
File menu buttons
--------------------------------------------------------
*/
// Load folder dialog box loadFolderDialogBoxButton
this.directoryElement = new Element();
this.directoryElement.create('input', 'IDopenFolderDialogBox', '', document.body);
this.directoryElement.object.setAttribute('type', 'file');
this.directoryElement.object.setAttribute('webkitdirectory', '');
this.directoryElement.object.setAttribute('mozdirectory', '');
this.directoryElement.object.setAttribute('msdirectory', '');
this.directoryElement.object.setAttribute('odirectory', '');
this.directoryElement.object.setAttribute('directory', '');
this.directoryElement.object.style.display = 'none';
// Open folder button
this.openFolderButton = new Element();
this.openFolderButton.create('li', '', 'openFolderIcon', this.fileMenu.object);
this.openFolderButton.addEvent('click', function () {
document.getElementById("IDopenFolderDialogBox").click();
});
// Open folder dialog box
this.openFolderDialogBox = document.getElementById("IDopenFolderDialogBox");
this.openFolderClick = function (opnFldClck) {
this.openFolderDialogBox.addEventListener('change', opnFldClck);
}
// Create input(file) element
this.fileElement = new Element();
this.fileElement.create('input', 'IDopenFileDialogBox', '', document.body);
this.fileElement.object.setAttribute('type', 'file');
this.fileElement.object.setAttribute('multiple', '');
this.fileElement.object.style.display = 'none';
// Project save button
this.projectSaveButton = new Element();
this.projectSaveButton.create('li', '', 'saveProjectIcon', this.fileMenu.object);
this.saveProjectClick = function (savePrjct) {
this.projectSaveButton.addEvent('click', savePrjct);
}
// Add Folder
this.addFolderButton = new Element();
this.addFolderButton.create('li', 'IDaddFolderButton', 'addFolderIcon', this.fileMenu.object);
this.fileMenuAddFolderClick = function (addFldrClbk) {
this.addFolderButton.addEvent('click', addFldrClbk);
}
// Add File
this.addFileButton = new Element();
this.addFileButton.create('li', 'IDaddFileButton', 'addFileIcon', this.fileMenu.object);
this.fileMenuAddFileClick = function (addFileClbk) {
this.addFileButton.addEvent('click', addFileClbk);
}
// Create live (checkbox) element
this.livecheckBoxCont = new Element();
this.livecheckBoxCont.create('div', 'IDlivecheckBoxCont', 'onoffswitch', document.getElementById('IDliveContainer'));
this.livecheckBox = new Element();
this.livecheckBox.create('input', 'IDlivecheckBox', 'onoffswitch-checkbox', this.livecheckBoxCont.object);
this.livecheckBox.object.setAttribute('type', 'checkbox');
this.livecheckBox.object.checked = true;
this.livecheckBoxLabel = new Element();
this.livecheckBoxLabel.create('label', 'IDlivecheckBoxLabel', 'onoffswitch-label', this.livecheckBoxCont.object);
this.livecheckBoxLabel.object.setAttribute('for', 'IDlivecheckBox');
// Create input(checkbox) element
this.checkBox = new Element();
this.checkBox.create('div', 'IDcheckBox', 'onoffswitch', document.getElementById('IDliveContainer'));
this.fileElement = new Element();
this.fileElement.create('input', 'IDShowWindowCheckBox', 'onoffswitch-checkbox', this.checkBox.object);
this.fileElement.object.setAttribute('type', 'checkbox');
this.checkBoxLabel = new Element();
this.checkBoxLabel.create('label', 'IDcheckBoxLabel', 'onoffswitch-label', this.checkBox.object);
this.checkBoxLabel.object.setAttribute('for', 'IDShowWindowCheckBox');
// this.checkBoxLabel.setLabel('label');
// inBefore.insertBefore(document.getElementById('IDsplitButtonContainer'), document.getElementById('IDliveContainer'));
/*
--------------------------------------------------------
File Manager Treeview Container
--------------------------------------------------------
*/
this.fileManagerTreeContainer = new Element();
this.fileManagerTreeContainer.create('div', 'IDfileManagerTreeContainer', '', this.fileManagerContainer.object);
this.getfileManagerTreeContainer = function () {
return this.fileManagerTreeContainer.object;
}
return this;
}
/* ------ File manager menu end ------ */
/*
--------------------------------------------------------
File manager treeview
--------------------------------------------------------
*/
/* ------ File manager treeview container ------ */
var fileManagerTreeContainer = function (parent) {
this.parent = parent;
// ---------- Tabs container ---------- //
this.treeContainer = new Element();
this.treeContainer.create('div', 'IDtreeContainer', '', this.parent);
return this.treeContainer;
}
/* ------ File manager treeview start ------ */
var fileManagerTree = function (parent) {
// Misc variables here
var self = this;
this.parent = parent;
this.counter = 0;
this.defaultFolderName = 'New Folder';
this.defaultFileName = 'New File';
this.folderCreated = false;
this.folderNameChanged = false;
this.oldFolderName = '';
this.tabsIdList = [];
// ---------- Root folder ---------- //
this.root = new Element();
//this.root.create('ul', 'IDroot', this.option.cssClass, this.parent);
this.root.create('ul', 'IDroot', 'fileManagerTree', this.parent);
// ---------- Create new folder section start ---------- //
this.createInputElementForaddFolder = function (parent) {
//event.stopPropagation();
var editElement = new Element();
editElement.create('input', misc.randomID('IDfolderEdit', 999999), '', parent);
editElement.object.setAttribute('type', 'text');
editElement.object.focus();
editElement.object.value = editElement.object.parentNode.childNodes[0].data;
//editElement.object.setSelectionRange( 0, editElement.object.value.lenght - 3 );
editElement.object.select();
editElement.addEvent('click', function (event) {
event.stopPropagation();
});
editElement.addEvent('dblclick', function (event) {
event.stopPropagation();
});
var oldInputText = editElement.object.value;
var pressEnter = false;
editElement.addEvent('keydown', function (event) {
if (event.keyCode == 13) {
pressEnter = true;
editElement.object.parentNode.removeChild(editElement.object);
}
});
editElement.addEvent('focusout', function (event) {
self.oldFolderName = event.target.parentNode.childNodes[0].data;
if (misc.checkChar(editElement.object.value) === false) {
//alert('There is a spacial character!')
alert("Please only use standard alphanumerics");
editElement.object.value = self.oldFolderName;
}
if (oldInputText == editElement.object.value) { self.folderNameChanged = false; }
if (editElement.object.value === '') {
alert('Folder name is empty!');
editElement.object.value = self.oldFolderName;
}
else {
selectedItem.childNodes[0].data = editElement.object.value;
if (self.folderCreated) {
var newfolderPath = self.getSelectedItemPath(selectedItem);
self.saveNewFolder(newfolderPath, function (res) {
selectedItem.childNodes[0].data = res;
});
}
if (self.folderNameChanged) {
var newfolderPath = self.getSelectedItemPath(selectedItem);
var ret = newfolderPath.replace(editElement.object.value, '');
self.renameFolder(ret + self.oldFolderName, ret + editElement.object.value, function (res) {
selectedItem.childNodes[0].data = res;
});
}
}
self.folderCreated = false;
self.folderNameChanged = false;
if (pressEnter == false) {
editElement.object.parentNode.removeChild(editElement.object);
}
pressEnter = false;
}, false);
}
this.createFolder = function (parent, deleteFolderCallback) {
this.folderCreated = true;
this.folderNameChanged = false;
if (selectedItem == null || selectedItem == undefined) {
parent = this.root.object;
selectedItem = this.root.object;
}
if (this.root.object.childElementCount == 0) {
selectedItem = parent;
} else {
parent = parent.children[1];
}
var newFolderObj = new Element();
newFolderObj.create('li', misc.randomID('IDnewFolder', 999999), 'folderIcon', parent);
newFolderObj.setLabel(this.defaultFolderName);
this.createInputElementForaddFolder(newFolderObj.object);
newFolderObj.addEvent('click', function (event) {
event.stopPropagation();
selectedItem = event.target;
console.log(selectedItem.querySelectorAll("LI"));
});
newFolderObj.addEvent('dblclick', function () {
self.folderNameChanged = true;
self.createInputElementForaddFolder(newFolderObj.object);
});
var toggleButton = new Element();
toggleButton.create('button', misc.randomID('IDtoggleButton', 10000), 'opened', newFolderObj.object);
toggleButton.addEvent('click', function (event) {
event.stopPropagation();
event.target.nextSibling.classList.toggle('toggle');
event.target.classList.toggle('closed');
});
toggleButton.addEvent('dblclick', function (event) {
event.stopPropagation();
});
// ---------- Sub list items ----------
var subListItem = Element();
subListItem.create('ul', misc.randomID('IDsubListItem', 999999), '', newFolderObj.object);
// var anchor = new Element();
// anchor.create('a', misc.randomID('IDnewAnchor', 999999), '', newFolderObj.object);
// ---------- Sub list item delete button ----------
var deleteButton = Element();
deleteButton.create('button', misc.randomID('IDdeleteButton', 999999), 'deleteButton', newFolderObj.object);
deleteButton.addEvent('click', function (event) {
selectedItem = event.target.parentNode;
if (confirm("This folder is deleting permanently!")) {
event.stopPropagation();
var delFolderPath = self.getSelectedItemPath(event.target.parentNode);
self.deleteFolder(delFolderPath, function () { });
deleteFolderCallback();
parent.removeChild(event.target.parentNode);
}
}, false);
selectedItem = newFolderObj.object;
}
this.folderEvents = function (folderID, toggleButtonID, deleteButtonID, deleteFolderCallback) {
var folderElem = document.getElementById(folderID);
var toggleButtonElem = document.getElementById(toggleButtonID);
var deleteButtonElem = document.getElementById(deleteButtonID);
folderElem.addEventListener('click', function (event) {
event.stopPropagation();
selectedItem = event.target;
self.getSelectedItemPath(selectedItem);
});
folderElem.addEventListener('dblclick', function (event) {
self.folderNameChanged = true;
self.createInputElementForaddFolder(event.target);
});
toggleButtonElem.addEventListener('click', function (event) {
event.stopPropagation();
event.target.nextSibling.classList.toggle('toggle');
event.target.classList.toggle('closed');
});
toggleButtonElem.addEventListener('dblclick', function (event) {
event.stopPropagation();
});
deleteButtonElem.addEventListener('click', function (event) {
selectedItem = event.target.parentNode;
if (confirm("This folder is deleting permanently!")) {
event.stopPropagation();
var delFolderPath = self.getSelectedItemPath(event.target.parentNode);
self.deleteFolder(delFolderPath, function () { });
deleteFolderCallback();
event.target.parentNode.parentNode.removeChild(event.target.parentNode);
}
}, false);
}
this.saveNewFolder = function (folderNamePath, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/saveNewFolder.php", true);
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(folderNamePath);
}
this.renameFolder = function (oldName, newName, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/renameFolder.php", true);
var namesObj = {
oldname: oldName,
newname: newName
};
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(JSON.stringify(namesObj));
}
this.deleteFolder = function (folderPath, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/deleteFolder.php", true);
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(folderPath);
}
// ---------- Create new folder section end ---------- //
// ---------- Create new file section start ---------- //
this.fileCreated = false;
this.fileNameChanged = false;
this.oldFileName = '';
this.createInputElementForaddFile = function (parent, callback) {
var editElement = new Element();
editElement.create('input', misc.randomID('IDfolderEdit', 999999), '', parent);
editElement.object.setAttribute('type', 'text');
editElement.object.focus();
editElement.object.value = editElement.object.parentNode.childNodes[0].data;
//editElement.object.setSelectionRange( 0, editElement.object.value.lenght - 3 );
editElement.object.select();
editElement.addEvent('click', function (event) {
event.stopPropagation();
});
editElement.addEvent('dblclick', function (event) {
event.stopPropagation();
});
var oldInputText = editElement.object.value;
var pressEnter = false;
editElement.addEvent('keydown', function (event) {
if (event.keyCode == 13) {
pressEnter = true;
editElement.object.parentNode.removeChild(editElement.object);
}
});
editElement.addEvent('focusout', function (event) {
self.oldFileName = event.target.parentNode.childNodes[0].data;
if (misc.checkChar(editElement.object.value) === false) {
alert("Please only use standard alphanumerics");
editElement.object.value = self.oldFileName;
}
if (oldInputText == editElement.object.value) { self.fileNameChanged = false; }
if (editElement.object.value === '') {
alert('File name is empty!');
editElement.object.value = self.oldFileName;
}
else {
selectedItem.childNodes[0].data = editElement.object.value;
if (self.fileCreated) {
var newfolderPath = self.getSelectedItemPath(selectedItem);
self.saveNewFile(newfolderPath, '', function (res) {
selectedItem.childNodes[0].data = res;
callback(res);
});
}
if (self.fileNameChanged) {
var newfolderPath = self.getSelectedItemPath(selectedItem);
var ret = newfolderPath.replace(editElement.object.value, '');
self.renameFile(ret + self.oldFileName, ret + editElement.object.value, function (res) {
selectedItem.childNodes[0].data = res;
callback(res);
});
}
}
self.fileCreated = false;
self.fileNameChanged = false;
if (pressEnter == false) {
editElement.object.parentNode.removeChild(editElement.object);
}
pressEnter = false;
}, false);
}
this.createFile1 = function (fileParent, fileName) {
self.fileCreated = true;
self.fileNameChanged = false;
var newFileObj = new Element();
newFileObj.create('li', misc.randomID('IDnewFile', 999999), 'fileIcon', fileParent.children[1]);
newFileObj.setLabel(fileName);
self.createInputElementForaddFile(newFileObj.object, function () {
});
// ---------- Get selected item ----------
newFileObj.addEvent('click', function (event) {
event.stopPropagation();
selectedItem = event.target;
for (var i = 0; i < document.getElementsByTagName('li').length; i++) {
document.getElementsByTagName('li')[i].classList.remove('active');
}
this.classList.add('active');
});
newFileObj.addEvent('dblclick', function (event) {
self.fileNameChanged = true;
self.createInputElementForaddFile(event.target, function (dat) {
//updateTabName(dat);
});
});
// ---------- Sub list item delete button ----------
var deleteButton = Element();
deleteButton.create('button', misc.randomID('IDdeleteButton', 999999), 'deleteButton', newFileObj.object);
deleteButton.addEvent('click', function (event) {
event.stopPropagation();
selectedItem = event.target.parentNode;
if (confirm("This file is deleting permanently!")) {
var delFilePath = self.getSelectedItemPath(event.target.parentNode);
self.deleteFile(delFilePath, function () { });
fileParent.children[1].removeChild(newFileObj.object);
}
});
// ---------- Hover item ----------
newFileObj.addEvent('mouseover', function (event) {
this.style.backgroundColor = '#444';
this.style.color = '#00a8f3';
this.style.borderRadius = '20px';
});
// ---------- mouse leave item ----------
newFileObj.addEvent('mouseleave', function (event) {
this.style.background = 'none';
this.style.color = '#ccc';
});
selectedItem = newFileObj.object;
return newFileObj.object;
}
this.createFile = function (fileParent, deleteTabCallback, updateTabName, actTab) {
self.fileCreated = true;
self.fileNameChanged = false;
var newFileObj = new Element();
newFileObj.create('li', misc.randomID('IDnewFile', 999999), 'fileIcon', fileParent.children[1]);
newFileObj.setLabel(this.defaultFileName);
self.createInputElementForaddFile(newFileObj.object, function (dat) {
flNnChgn = true;
updateTabName(dat);
flNnChgn = false;
});
// ---------- Get selected item ----------
newFileObj.addEvent('click', function (event) {
console.log('click');
event.stopPropagation();
selectedItem = event.target;
for (var i = 0; i < document.getElementsByTagName('li').length; i++) {
document.getElementsByTagName('li')[i].classList.remove('active');
}
this.classList.add('active');
actTab();
});
newFileObj.addEvent('dblclick', function (event) {
self.fileNameChanged = true;
event.stopPropagation();
self.createInputElementForaddFile(newFileObj.object, function (dat) {
flNnChgn = false;
updateTabName(dat);
});
});
// ---------- Sub list item delete button ----------
var deleteButton = Element();
deleteButton.create('button', misc.randomID('IDdeleteButton', 999999), 'deleteButton', newFileObj.object);
deleteButton.addEvent('click', function (event) {
event.stopPropagation();
selectedItem = event.target.parentNode;
if (confirm("This file is deleting permanently!")) {
var delFilePath = self.getSelectedItemPath(event.target.parentNode);
self.deleteFile(delFilePath, function () { });
deleteTabCallback();
fileParent.children[1].removeChild(newFileObj.object);
}
});
// ---------- Hover item ----------
newFileObj.addEvent('mouseover', function (event) {
this.style.backgroundColor = '#444';
this.style.color = '#00a8f3';
this.style.borderRadius = '20px';
});
// ---------- mouse leave item ----------
newFileObj.addEvent('mouseleave', function (event) {
this.style.background = 'none';
this.style.color = '#ccc';
});
selectedItem = newFileObj.object;
return newFileObj.object;
}
this.fileEvents = function (fileID, fileDeleteButtonID, deleteTabCallback, updateTabName, actTab) {
var fileElem = document.getElementById(fileID);
var deleteButtonElem = document.getElementById(fileDeleteButtonID);
fileElem.addEventListener('dblclick', function (event) {
event.stopPropagation();
self.fileNameChanged = true;
self.createInputElementForaddFile(event.target, function (dat) {
updateTabName(dat);
});
});
deleteButtonElem.addEventListener('click', function (event) {
event.stopPropagation();
selectedItem = event.target.parentNode;
if (confirm("This file is deleting permanently!")) {
var delFilePath = self.getSelectedItemPath(event.target.parentNode);
self.deleteFile(delFilePath, function () { });
deleteTabCallback();
event.target.parentNode.parentNode.removeChild(event.target.parentNode);
}
}, false);
// ---------- Get selected item ----------
fileElem.addEventListener('click', function (event) {
selectedItem = event.target;
//event.stopPropagation();
self.getSelectedItemPath(selectedItem);
for (var i = 0; i < document.getElementsByTagName('li').length; i++) {
document.getElementsByTagName('li')[i].classList.remove('active');
}
this.classList.add('active');
actTab();
});
// ---------- Hover item ----------
fileElem.addEventListener('mouseover', function (event) {
this.style.backgroundColor = '#444';
this.style.color = '#00a8f3';
this.style.borderRadius = '20px';
});
// ---------- mouse leave item ----------
fileElem.addEventListener('mouseleave', function (event) {
this.style.background = 'none';
this.style.color = '#ccc';
});
}
this.saveNewFile = function (fileNamePath, data, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/saveNewFile.php", true);
var fileObj = {
fileNamePath: fileNamePath,
data: data
};
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(JSON.stringify(fileObj));
}
this.deleteFile = function (filesPath, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/deleteFile.php", true);
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(filesPath);
}
this.renameFile = function (oldName, newName, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/renameFile.php", true);
var namesObj = {
oldname: oldName,
newname: newName
};
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(JSON.stringify(namesObj));
}
this.getSelectedItemPath = function (elem) {
var pthS = '';
var fullPath = '';
var element = document.getElementById(elem.id);
if (element.classList[0] == 'fileIcon' || element.classList[0] == 'folderIcon') {
while (element.parentElement) {
element = element.parentElement;
if (element.classList != undefined) {
if (element.classList[0] == 'folderIcon') {
pthS = element.firstChild.data + '/' + pthS;
fullPath = pthS + elem.firstChild.data;
}
else if (element.classList[0] == 'fileManagerTree') {
fullPath = pthS + elem.firstChild.data;
}
}
}
return fullPath;
}
}
this.getAllItemPaths = function () {
var lvLI = document.getElementById('IDroot').getElementsByTagName('li');
var fullPathArr = [];
for (var i = 0; i < lvLI.length; i++) {
var pthS = '';
var fullPath = '';
var arr = [];
var element = document.getElementById(lvLI[i].id);
if (element.classList[0] == 'fileIcon') {
while (element.parentNode) {
element = element.parentNode;
if (element.classList != undefined) {
if (element.classList[0] == 'folderIcon') {
pthS = element.firstChild.data + '/' + pthS;
fullPath = pthS + lvLI[i].firstChild.data;
}
}
}
arr.push(pthS, lvLI[i].firstChild.data, fullPath);
fullPathArr.push(arr);
}
}
return fullPathArr;
}
this.saveAllFiles = function (dir, fileNamePath, data, callback) {
var xhttpPhp = new XMLHttpRequest();
xhttpPhp.open("POST", "php/saveAllFiles.php", true);
var fileObj = {
dir: dir,
fileNamePath: fileNamePath,
data: data
};
xhttpPhp.onreadystatechange = function () {
if (xhttpPhp.readyState === 4) {
if (xhttpPhp.status === 200 || xhttpPhp.status == 0) {
var fNameArr = xhttpPhp.responseText;
callback(fNameArr);
}
}
}
xhttpPhp.send(JSON.stringify(fileObj));
}
this.readProjectFile = function (fileName, callBack) {
// Read html file
var htmlFileObj = new XMLHttpRequest();
htmlFileObj.open("GET", fileName, true);
var htmlText = '';
htmlFileObj.onreadystatechange = function () {
if (htmlFileObj.readyState === 4) {
if (htmlFileObj.status === 200 || htmlFileObj.status == 0) {
htmlText = htmlFileObj.responseText;
callBack(htmlText);
}
}
}
htmlFileObj.send(null);
}
return this;
// ---------- Create new file section start ---------- //
}
/* ------ File manager treeview end ------ */<file_sep><?php
/* Delete file */
function deleteFile(){
// get ajax data
$phpData = file_get_contents('php://input');
unlink('../code/' . $phpData);
}
deleteFile();
?><file_sep>/*
--------------------------------------------------------
Page Ready
--------------------------------------------------------
*/
var selectedItem = null;
var filesPath = [];
var flNnChgn = false;
var STYLE = '<style type="text/css">\n';
var STYLEEND = '\n</style>';
var SCRIPT = '<script type="text/javascript">\n';
var SCRIPTEND = '\n</script>';
var READY = 'window.addEventListener("load", function(){\n';
var READYEND ='});';
var codeFolderName = 'code';
var nodeJS = false;
/*
--------------------------------------------------------
Live php code
--------------------------------------------------------
*/
function runPhpCode(phpData, callBack){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callBack(this.responseText);
}
};
var url = 'php/runPhpCode.php';
xhttp.open("POST", url, true);
xhttp.send(phpData);
}
/*
--------------------------------------------------------
Unloadbefore function
--------------------------------------------------------
*/
// -------- Show alert box unload before -------- //
window.addEventListener("beforeunload", function (e) {
if(document.getElementById("IDShowWindowCheckBox").checked){
liveWindow.close();
}
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
window.addEventListener('load', function(){
/*
--------------------------------------------------------
Preloader
--------------------------------------------------------
*/
window.setTimeout(function(){
//misc.delay(10);
document.getElementById('preloader').style.display = 'none';
},100);
/*
--------------------------------------------------------
Split
--------------------------------------------------------
*/
let newSplit = new sktSplit();
/*
--------------------------------------------------------
Tabs Section
--------------------------------------------------------
*/
// Html/Php tabs
var phpCodeTabs = new Tabs(document.getElementById('phpSplit'));
phpCodeTabs.setBackgroundIcon(phpCodeTabs.codeIconPhp, '#00a8f3');
// Refresh php code editors
phpCodeTabs.refreshEvent(function(){
var edIns = document.getElementsByClassName('CodeMirror');
for (var i = 0; i < edIns.length; i++) {
edIns[i].CodeMirror.refresh();
}
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
var gate = phpCodeTabs.getActiveTabElement();
if(gate.id == filesIds[a][1]){
document.getElementById(filesIds[a][0]).click();
}
}
});
// Css tabs
var cssCodeTabs = new Tabs(document.getElementById('cssSplit'));
cssCodeTabs.setBackgroundIcon(cssCodeTabs.codeIconCss, '#00a8f3');
// Refresh css code editors
cssCodeTabs.refreshEvent(function(){
var edIns = document.getElementsByClassName('CodeMirror');
//this.tab.children[0].children[1].click()
for (var i = 0; i < edIns.length; i++) {
edIns[i].CodeMirror.refresh();
}
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
var gate = cssCodeTabs.getActiveTabElement();
if(gate.id == filesIds[a][1]){
document.getElementById(filesIds[a][0]).click();
}
}
});
// javascript tabs
var jsCodeTabs = new Tabs(document.getElementById('jsSplit'));
jsCodeTabs.setBackgroundIcon(jsCodeTabs.codeIconJs, '#00a8f3');
// Refresh js code editors
jsCodeTabs.refreshEvent(function(){
var edIns = document.getElementsByClassName('CodeMirror');
for (var i = 0; i < edIns.length; i++) {
edIns[i].CodeMirror.refresh();
}
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
var gate = jsCodeTabs.getActiveTabElement();
if(gate.id == filesIds[a][1]){
document.getElementById(filesIds[a][0]).click();
}
}
});
/*
--------------------------------------------------------
File manager section
--------------------------------------------------------
*/
// ------ File manager sections start ------ //
var newfileManager = new fileManager(document.getElementById('projectSplit'));
// ------ File manager treeview ------ //
var flmgrTreeviewContainer = new fileManagerTreeContainer(newfileManager.getfileManagerTreeContainer());
var filesTree = new fileManagerTree(flmgrTreeviewContainer.object);
var filesIds = [];
var liveIframe = null;
var liveWindow = null;
var windowCheckBox = document.getElementById("IDShowWindowCheckBox");
windowCheckBox.disabled = true;
windowCheckBox.addEventListener('click', function(){
var dirPaths = filesTree.getAllItemPaths();
if(!document.getElementById("liveSection").checked){
window.setTimeout(function(){
if (document.getElementById("IDShowWindowCheckBox").checked){
liveWindow = window.open("", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=0,left=1210,width=480,height=640" );
newSplit.mainSplit.collapse(2);
document.getElementById("liveSection").removeChild(document.getElementById("liveSection").firstChild);
if(nodeJS == true){
liveWindow.location = 'http://localhost:8000/';
}
else{
liveWindow.location.src = filesTree.parent.baseURI + codeFolderName + '/' + dirPaths[0][0];
console.log(liveWindow.location.src);
getAllDataFromEditors();
}
let delZoomInOutButton = document.getElementById('IDliveContainer');
delZoomInOutButton.removeChild(document.getElementsByClassName('zoomInButton')[0]);
delZoomInOutButton.removeChild(document.getElementsByClassName('zoomOutButton')[0]);
}
else {
liveIframe = new IFrame(document.getElementById("liveSection"));
liveIframe.zoomIn(document.getElementById('IDliveContainer'));
liveIframe.zoomOut(document.getElementById('IDliveContainer'));
newSplit.mainSplit.setSizes([20,50,30]);
liveWindow.close();
if(nodeJS == true){
liveIframe.object.src = 'http://localhost:8000/';
}
else{
liveIframe.object.contentWindow.location.reload(true);
getAllDataFromEditors();
}
}
console.log('Window switched!');
}, 500);
}
});
newfileManager.fileMenuAddFolderClick(function(){
if(filesTree.root.object.childElementCount == 0){
liveIframe = new IFrame(document.getElementById("liveSection"));
liveIframe.zoomIn(document.getElementById('IDliveContainer'));
liveIframe.zoomOut(document.getElementById('IDliveContainer'));
}
windowCheckBox.disabled = false;
filesTree.createFolder(selectedItem, deleteFolderTab);
function deleteFolderTab(){
filesIds = phpCodeTabs.getFilesId();
var selItemFilesId = selectedItem.querySelectorAll("LI")
for (var i = 0; i < selItemFilesId.length; i++) {
if(selItemFilesId[i].classList[0] == "fileIcon"){
for (var a = 0; a < filesIds.length; a++) {
if(selItemFilesId[i].id == filesIds[a][0]){
console.log(document.getElementById(filesIds[a][1]).parentNode);
console.log(document.getElementById(filesIds[a][1]))
document.getElementById(filesIds[a][1]).parentNode.removeChild(document.getElementById(filesIds[a][1]));
filesIds.splice(a, 1);
}
}
}
}
}
});
var typingTimer;
var time = 300;
timer = function(){
var dirPaths = filesTree.getAllItemPaths();
if(document.getElementById("IDlivecheckBox").checked){
window.clearTimeout(typingTimer);
typingTimer = window.setTimeout(function(){
if (document.getElementById("IDShowWindowCheckBox").checked){
if(nodeJS == true){
liveWindow.location.src = 'http://localhost:8000/';
}
else{
liveWindow.location.reload(true);
liveWindow.addEventListener('unload', function(){
//liveWindow.location.href = 'http://localhost/webDev/php/projects/cmEditor/cmEditor8/code/angularjs_todo_list_demo/';
getAllDataFromEditors();
console.log('Page Reloaded!') ;
});
}
}
else{
liveIframe.object.contentWindow.location.reload(true);
getAllDataFromEditors();
}
}, time);
}
// else{
// if(nodeJS == true){
// liveIframe.object.src = 'http://localhost:8000/';
// }
// }
}
newfileManager.fileMenuAddFileClick(function(){
var newFileItem = filesTree.createFile(selectedItem, deleteTab, setTabName, activeTab);
function deleteTab(){
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
if(selectedItem.id == filesIds[a][0]){
var evt = document.createEvent("MouseEvents");
evt.initEvent("mousedown", true, true);
document.getElementById(filesIds[a][1]).children[0].dispatchEvent(evt);
filesIds.splice(a, 1);
console.log(selectedItem.id);
console.log(filesIds);
}
}
}
function setTabName(tabName){
if(flNnChgn){
var fileExtension = tabName.split('.').pop();
switch(fileExtension){
case 'html' :
var newTab = phpCodeTabs.createTab(newFileItem.firstChild.data);
phpCodeTabs.setTabIcon(newTab.id, phpCodeTabs.codeIconHtml, '#00a8f3');
var arr = [];
arr.push(newFileItem.id, newTab.id);
phpCodeTabs.insertFileId(arr);
phpCodeTabs.setActiveTabElement(newTab);
var newEditor = new Editor(newTab.children[1], "application/x-httpd-php", '');
newEditor.refresh();
phpCodeTabs.setLabel(newTab, tabName);
var edIns = newEditor.getEditorInstance();
CodeMirror.on( edIns, "change", function() {
timer();
});
break;
case 'php' :
var newTab = phpCodeTabs.createTab(newFileItem.firstChild.data);
phpCodeTabs.setTabIcon(newTab.id, phpCodeTabs.codeIconPhp, '#00a8f3');
var arr = [];
arr.push(newFileItem.id, newTab.id);
phpCodeTabs.insertFileId(arr);
phpCodeTabs.setActiveTabElement(newTab);
var newEditor = new Editor(newTab.children[1], "application/x-httpd-php", '');
newEditor.refresh();
phpCodeTabs.setLabel(newTab, tabName);
var edIns = newEditor.getEditorInstance();
CodeMirror.on( edIns, "change", function() {
timer();
});
break;
case 'css' :
var newTab = cssCodeTabs.createTab(newFileItem.firstChild.data);
cssCodeTabs.setTabIcon(newTab.id, cssCodeTabs.codeIconCss, '#00a8f3');
var arr = [];
arr.push(newFileItem.id, newTab.id);
phpCodeTabs.insertFileId(arr);
cssCodeTabs.setActiveTabElement(newTab);
var newEditor = new Editor(newTab.children[1], "css", '');
cssCodeTabs.setLabel(newTab, tabName);
var edIns = newEditor.getEditorInstance();
CodeMirror.on( edIns, "change", function() {
timer();
});
break;
case 'js' :
var newTab = jsCodeTabs.createTab(newFileItem.firstChild.data);
jsCodeTabs.setTabIcon(newTab.id, jsCodeTabs.codeIconJs, '#00a8f3');
var arr = [];
arr.push(newFileItem.id, newTab.id);
phpCodeTabs.insertFileId(arr);
jsCodeTabs.setActiveTabElement(newTab);
var newEditor = new Editor(newTab.children[1], "javascript", '');
jsCodeTabs.setLabel(newTab, tabName);
var edIns = newEditor.getEditorInstance();
CodeMirror.on( edIns, "change", function() {
timer();
});
break;
default:
console.log('undefined file extension');
}
}
else{
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
if(selectedItem.id == filesIds[a][0]){
document.getElementById(filesIds[a][1]).firstChild.data = tabName;
}
console.log(phpCodeTabs.getFilesId());
}
}
}
function activeTab(){
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
if(selectedItem.id == filesIds[a][0]){
document.getElementById(filesIds[a][1]).style.display = 'inline';
document.getElementById(filesIds[a][1]).click();
var edIns = document.getElementsByClassName('CodeMirror');
for (var i = 0; i < edIns.length; i++) {
edIns[i].CodeMirror.refresh();
}
}
}
}
});
/*
--------------------------------------------------------
Get all editor data
--------------------------------------------------------
*/
function getAllDataFromEditors(){
var strPHP = '';
var strCSS = '';
var strJS = '';
var allIns = document.getElementsByClassName('CodeMirror');
for (var i = 0; i < allIns.length; i++) {
if(allIns[i].CodeMirror.getMode().name == 'php' || allIns[i].CodeMirror.getMode().name == 'html'){
strPHP += allIns[i].CodeMirror.getValue();
}
else if(allIns[i].CodeMirror.getMode().name == 'css'){
strCSS += allIns[i].CodeMirror.getValue();
}
else if(allIns[i].CodeMirror.getMode().name == 'javascript'){
strJS += allIns[i].CodeMirror.getValue() + '\n';
}
}
runPhpCode( strPHP, function(data){
//var allCode = STYLE + strCSS + STYLEEND + data + SCRIPT + READY + strJS + READYEND + SCRIPTEND;
var allCode = STYLE + strCSS + STYLEEND + data + SCRIPT + strJS + SCRIPTEND;
if (document.getElementById("IDShowWindowCheckBox").checked){
liveWindow.document.write(allCode);
}
else {
liveIframe.iframe(allCode);
}
});
}
/*
--------------------------------------------------------
Create tab for editor
--------------------------------------------------------
*/
function createTabEditor(tabContainer, dir, filePath, fileName, tabLabel, editorMod){
var newTab = tabContainer.createTab(tabLabel);
var projectFolder = dir.split('/');
filesTree.readProjectFile(fileName, function(data){
var newEditor = new Editor(newTab.children[1], editorMod, data);
//newEditor.setTheme('ambiance');
var edIns = newEditor.getEditorInstance();
CodeMirror.on( edIns, "change", function(){
timer();
});
//filesTree.saveAllFiles(dir, filePath, data, function(res){ console.log(filePath + ' uploaded!'); });
});
return newTab.id; // tab id
}
/*
--------------------------------------------------------
Load project folder
--------------------------------------------------------
*/
newfileManager.openFolderClick(function(event){
liveIframe = new IFrame(document.getElementById("liveSection"));
liveIframe.zoomIn(document.getElementById('IDliveContainer'));
liveIframe.zoomOut(document.getElementById('IDliveContainer'));
var folderIDs = [];
var toggleButtonIDs = [];
var deleteButtonIDs = [];
var fileIDs = [];
var filedeleteButtonIDs = [];
var tabsID = [];
windowCheckBox.disabled = false;
for( var i=0; i < event.target.files.length; i++){
var fileName = (window.URL || window.webkitURL).createObjectURL(event.target.files[i]);
var fileExtension = event.target.files[i].name.split('.').pop();
var dirPath = event.target.files[i].webkitRelativePath;
filesPath.push(dirPath);
var pth = '';
var dir1 = dirPath;
dir1 = dir1.split("/");
dir1.pop();
for (var x = 0; x < dir1.length; x++) {
pth += dir1[x] + '/';
}
switch(fileExtension){
case 'html' :
var newTabID = createTabEditor(phpCodeTabs, pth, dirPath, fileName, event.target.files[i].name, "application/x-httpd-php");
tabsID.push(newTabID);
phpCodeTabs.setTabIcon(newTabID, phpCodeTabs.codeIconHtml, '#00a8f3');
break;
case 'php' :
var newTabID = createTabEditor(phpCodeTabs, pth, dirPath, fileName, event.target.files[i].name, "application/x-httpd-php");
tabsID.push(newTabID);
phpCodeTabs.setTabIcon(newTabID, phpCodeTabs.codeIconPhp, '#00a8f3');
break;
case 'css' :
var newTabID = createTabEditor(cssCodeTabs, pth, dirPath, fileName, event.target.files[i].name, "css");
tabsID.push(newTabID);
cssCodeTabs.setTabIcon(newTabID, cssCodeTabs.codeIconCss, '#00a8f3');
break;
case 'js' :
var newTabID = createTabEditor(jsCodeTabs, pth, dirPath, fileName, event.target.files[i].name, "javascript");
tabsID.push(newTabID);
jsCodeTabs.setTabIcon(newTabID, jsCodeTabs.codeIconJs, '#00a8f3');
break;
default:
tabsID.push('IDnull');
//tabsID.push(misc.randomID('ID', 99999));
// var newTabID = createTabEditor(phpCodeTabs, pth, dirPath, fileName, event.target.files[i].name, "application/x-httpd-php");
// tabsID.push(newTabID);
// phpCodeTabs.setTabIcon(newTabID, phpCodeTabs.codeIconHtml, '#00a8f3');
break;
}
}
var hierarchy = filesPath.reduce(function(hier,path){
var x = hier;
path.split('/').forEach(function(item){
if(!x[item]){
x[item] = {};
}
x = x[item];
});
x.path = path;
return hier;
}, {});
//console.log(hierarchy);
// ------ Make unordered list ------ //
var makeul = function(hierarchy, classname){
var dirs = Object.keys(hierarchy);
var ul = '<ul id="' + misc.randomID('IDUL', 999999) + '"';
if(classname){
ul += ' class="' + classname + '"';
}
ul += '>';
dirs.forEach(function(dir){
var path = hierarchy[dir].path;
if(path){ // file
var file_id = misc.randomID('IDnewFile', 999999);
fileIDs.push(file_id);
ul += '<li class="fileIcon" id="' + file_id + '">' + dir;
var filedeletebutton_id = misc.randomID('IDnewFileDeleteButton', 999999);
filedeleteButtonIDs.push(filedeletebutton_id);
ul += '<button class="deleteButton" id="' + filedeletebutton_id + '"></button></li>';
}else{ // folder
var folder_id = misc.randomID('IDnewFolder', 999999);
folderIDs.push(folder_id);
ul += '<li class="folderIcon" id="' + folder_id + '">' + dir;
var tooglebutton_id = misc.randomID('IDtoggleButton', 999999);
toggleButtonIDs.push(tooglebutton_id);
ul += '<button class="opened" id="' + tooglebutton_id + '"></button>';
ul += makeul(hierarchy[dir]);
var deletebutton_id = misc.randomID('IDnewFolderDeleteButton', 999999);
deleteButtonIDs.push(deletebutton_id);
ul += '<button class="deleteButton" id="' + deletebutton_id + '"></button></li>';
}
});
ul += '</ul>';
return ul;
};
var par = document.getElementById('IDtreeContainer');
par.innerHTML = makeul(hierarchy, 'fileManagerTree');
par.children[0].setAttribute('id', 'IDroot');
document.getElementById('IDroot').children[0].classList.add('root');
for (var i = 0; i < folderIDs.length; i++) {
filesTree.folderEvents(folderIDs[i], toggleButtonIDs[i], deleteButtonIDs[i], deleteFolderTab);
function deleteFolderTab(){
filesIds = phpCodeTabs.getFilesId();
var selItemFilesId = selectedItem.querySelectorAll("LI")
for (var i = 0; i < selItemFilesId.length; i++) {
if(selItemFilesId[i].classList[0] == "fileIcon"){
for (var a = 0; a < filesIds.length; a++) {
if(selItemFilesId[i].id == filesIds[a][0]){
console.log(document.getElementById(filesIds[a][1]).parentNode);
console.log(document.getElementById(filesIds[a][1]))
document.getElementById(filesIds[a][1]).parentNode.removeChild(document.getElementById(filesIds[a][1]));
filesIds.splice(a, 1);
}
}
}
}
}
}
for (var a = 0; a < fileIDs.length; a++) {
filesTree.fileEvents(fileIDs[a], filedeleteButtonIDs[a], deleteTab, setTabName, activeTab);
var arr = [];
arr.push(fileIDs[a], tabsID[a]);
phpCodeTabs.insertFileId(arr);
function deleteTab(){
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
if(selectedItem.id == filesIds[a][0]){
var evt = document.createEvent("MouseEvents");
evt.initEvent("mousedown", true, true);
document.getElementById(filesIds[a][1]).children[0].dispatchEvent(evt);
filesIds.splice(a, 1);
console.log(selectedItem.id);
console.log(filesIds);
}
}
}
function setTabName(tabName){
filesIds = phpCodeTabs.getFilesId();
for (var a = 0; a < filesIds.length; a++) {
if(selectedItem.id == filesIds[a][0]){
document.getElementById(filesIds[a][1]).firstChild.data = tabName;
}
}
}
function activeTab(){
filesIds = phpCodeTabs.getFilesId();
var edIns = document.getElementsByClassName('CodeMirror');
for (var a = 0; a < filesIds.length; a++) {
if(selectedItem.id == filesIds[a][0]){
document.getElementById(filesIds[a][1]).style.display = 'inline';
document.getElementById(filesIds[a][1]).click();
var edIns = document.getElementsByClassName('CodeMirror');
for (var i = 0; i < edIns.length; i++) {
edIns[i].CodeMirror.refresh();
}
}
}
for (var i = 0; i < edIns.length; i++) {
edIns[i].CodeMirror.refresh();
}
}
}
if(!document.getElementById("liveSection").checked){
window.setTimeout(function(){
if (document.getElementById("IDShowWindowCheckBox").checked){
if(nodeJS == true){
liveWindow.location = 'http://localhost:8000/';
}
else{
liveWindow.location.reload(true);
getAllDataFromEditors();
}
}
else {
if(nodeJS == true){
liveIframe.object.src = 'http://localhost:8000/';
}
else{
liveIframe.object.contentWindow.location.reload(true);
getAllDataFromEditors();
}
}
console.log('Project is loaded!');
}, 400);
}
});
/*
--------------------------------------------------------
Save all project files
--------------------------------------------------------
*/
const saveFiles = function(){
filesIds = phpCodeTabs.getFilesId();
var dirPaths = filesTree.getAllItemPaths();
for (var i = 0; i < filesIds.length; i++) {
var path = filesTree.getSelectedItemPath(document.getElementById(filesIds[i][0]));
console.log(path + ' saved!')
var tabObj = document.getElementById(filesIds[i][1]);
var editorIns = tabObj.children[1].getElementsByClassName('CodeMirror')[0];
filesTree.saveAllFiles(dirPaths[i][0], path, editorIns.CodeMirror.getValue(), function(){ });
}
if(!document.getElementById("liveSection").checked){
window.setTimeout(function(){
if (document.getElementById("IDShowWindowCheckBox").checked){
if(nodeJS == true){
liveWindow.location = 'http://localhost:8000/';
}
else{
liveWindow.location.reload(true);
getAllDataFromEditors();
}
}
else {
if(nodeJS == true){
liveIframe.object.src = 'http://localhost:8000/';
}
else{
liveIframe.object.contentWindow.location.reload(true);
getAllDataFromEditors();
}
}
}, 400);
}
}
newfileManager.saveProjectClick(function(){
saveFiles();
});
/*
--------------------------------------------------------
Save files keyboard shortcut
--------------------------------------------------------
*/
document.addEventListener('keydown', function(e){
if (e.ctrlKey == true && e.which == 83) {
e.preventDefault();
saveFiles();
}
});
});<file_sep><?php
/* Rename folder */
function renameFolder(){
// get ajax data
$phpData = file_get_contents('php://input');
$obj = json_decode( $phpData );
if (!is_dir('../code/' . $obj->newname)) {
rename('../code/' . $obj->oldname, '../code/' . $obj->newname);
$ex = explode("/", $obj->newname);
echo $ex[count($ex) -1];
}
else{
$newFolderName = $obj->newname . '_' . (string) rand();
rename('../code/' . $obj->oldname, '../code/' . $newFolderName);
$ex1 = explode("/", $newFolderName);
echo $ex1[count($ex1) -1];
}
}
renameFolder();
?><file_sep>/*
--------------------------------------------------------
Split section
--------------------------------------------------------
*/
class sktSplit {
//------ Split constructor ------//
constructor() {
this.mainSplit;
this.codeSplit;
this.projectSplit;
//------ Main sections ------//
this.mainSplit = Split(['#projectSection', '#codeSection', '#liveSection'], {
gutterSize: 6,
cursor: 'col-resize',
minSize: [0, 0, 0],
sizes: [20, 50, 30]
});
//------ Project split section ------//
this.projectSplit = Split(['#projectSplit'], {
direction: 'vertical',
cursor: 'row-resize',
gutterSize: 6,
minSize: [0],
sizes: [100]
});
//------ Code split section ------//
this.codeSplit = Split(['#phpSplit', '#cssSplit', '#jsSplit'], {
direction: 'vertical',
cursor: 'row-resize',
gutterSize: 6,
minSize: [0, 0, 0],
sizes: [33.33, 33.33, 33.33]
});
//------ Events section start ------//
this.projectSplitCollapse();
this.liveSplitCollapse();
this.projectFullWidth();
this.codeFullWidth();
this.liveFullWidth();
this.phpFullWidth();
this.jsFullWidth();
this.cssFullWidth();
}
//------ Project section collapse click event ------//
projectSplitCollapse() {
let _this = this;
let projectSplitClickState = 0;
let projectSplit = document.getElementsByClassName("gutter")[0];
projectSplit.addEventListener('dblclick', function () {
if (projectSplitClickState == 0) {
_this.mainSplit.collapse(0);
projectSplitClickState = 1;
} else {
_this.mainSplit.setSizes([20, 50, 30]);
//mainSplit.sizes[0] = 33.33;
projectSplitClickState = 0;
}
});
//this.projectFullWidth();
}
//------ Live code section collapse click event ------//
liveSplitCollapse() {
let _this = this;
let liveSplitClickState = 0;
let liveSplit = document.getElementsByClassName("gutter")[3];
liveSplit.addEventListener('dblclick', function () {
if (liveSplitClickState == 0) {
_this.mainSplit.collapse(2);
liveSplitClickState = 1;
} else {
_this.mainSplit.setSizes([20, 50, 30]);
liveSplitClickState = 0;
}
});
//this.liveFullWidth();
}
//------ Project section full with click event ------//
projectFullWidth() {
let _this = this;
let projectSplitClickState = 0;
const projectFullWidthObj = new domObject('IDprojectFullWidth');
projectFullWidthObj.events({
onclick: function () {
if (projectSplitClickState == 0) {
_this.mainSplit.setSizes([0, 49.10, 49.10]);
projectSplitClickState = 1;
this.codeSplitClickState = 0;
this.liveSplitClickState = 0;
} else {
_this.mainSplit.setSizes([20, 50, 30]);
projectSplitClickState = 0;
}
}
});
}
//------ Code section full with click event ------//
codeFullWidth() {
let _this = this;
let codeSplitClickState = 0;
const codeFullWidthObj = new domObject('IDcodeFullWidth');
codeFullWidthObj.events({
onclick: function () {
if (codeSplitClickState == 0) {
_this.mainSplit.setSizes([0, 99.40, 0]);
codeSplitClickState = 1;
} else {
_this.mainSplit.setSizes([20, 50, 30]);
codeSplitClickState = 0;
}
}
});
}
//------ Live section full with click event ------//
liveFullWidth() {
let _this = this;
let liveSplitClickState = 0;
const liveFullWidthObj = new domObject('IDliveFullWidth');
liveFullWidthObj.events({
onclick: function () {
if (liveSplitClickState == 0) {
_this.mainSplit.setSizes([0, 0, 99.40]);
liveSplitClickState = 1;
} else {
_this.mainSplit.setSizes([20, 50, 30]);
liveSplitClickState = 0;
}
}
});
}
//------ Php code section full height click event ------//
phpFullWidth() {
let _this = this;
let phpSplitClickState = 0;
const phpFullWidthObj = new domObject('IDphpFullWidth');
phpFullWidthObj.events({
onclick: function () {
if (phpSplitClickState == 0) {
_this.codeSplit.setSizes([99.10, 0, 0]);
phpSplitClickState = 1;
} else {
_this.codeSplit.setSizes([33.33, 33.33, 33.33]);
phpSplitClickState = 0;
}
}
});
}
//------ Css code section full height click event ------//
jsFullWidth() {
let _this = this;
let jsSplitClickState = 0;
const jsFullWidthObj = new domObject('IDjsFullWidth');
jsFullWidthObj.events({
onclick: function () {
if (jsSplitClickState == 0) {
_this.codeSplit.setSizes([0, 0, 99.10]);
jsSplitClickState = 1;
} else {
_this.codeSplit.setSizes([33.33, 33.33, 33.33]);
jsSplitClickState = 0;
}
}
});
}
//------ Js code section full height click event ------//
cssFullWidth() {
let _this = this;
let cssSplitClickState = 0;
const cssFullWidthObj = new domObject('IDcssFullWidth');
cssFullWidthObj.events({
onclick: function () {
if (cssSplitClickState == 0) {
_this.codeSplit.setSizes([0, 99.40, 0]);
cssSplitClickState = 1;
} else {
_this.codeSplit.setSizes([33.33, 33.33, 33.33]);
cssSplitClickState = 0;
}
}
});
}
}<file_sep><?php
/* Save new folder */
function saveNewFolder(){
// get ajax data
$phpData = file_get_contents('php://input');
if(!is_dir('../code/' . $phpData)) {
mkdir('../code/' . $phpData, 0777, true);
$ex = explode("/", $phpData);
echo $ex[count($ex) -1];
}
else{
$newFolderName = $phpData . '_' . (string) rand();
mkdir('../code/' . $newFolderName , 0777, true);
$ex1 = explode("/", $newFolderName);
echo $ex1[count($ex1) -1];
}
}
saveNewFolder();
?><file_sep>/*
--------------------------------------------------------
IFrame javascript functions
--------------------------------------------------------
*/
var IFrame = function(parent){
var iFrameConatiner = new Element();
iFrameConatiner.create('div', misc.randomID('IDiframeConatiner', 999999), 'frameConatiner', parent);
this.object;
var newFrame = new Element();
this.object = newFrame.create('iframe', misc.randomID('IDiframe', 999999), 'iframe', iFrameConatiner.object);
this.iframe = function(data){
var iframe = newFrame.object.contentWindow.document;
iframe.open();
iframe.write(data);
iframe.close();
}
this.iframeWrite = function(php, css, js){
var iframe = newFrame.object.contentWindow.document;
iframe.open();
iframe.write(php+css+js);
iframe.close();
}
this.showBackEndErrorsOnIframe = function(responseText){
var iframeErr = newFrame.object.contentWindow.document;
iframeErr.open();
iframeErr.write(responseText);
iframeErr.close();
}
var scaleCount = 100;
this.zoomIn = function(parent){
var zoomInButton = new Element();
zoomInButton.create('botton', misc.randomID('IDzoomInButton', 999999), 'zoomInButton', parent);
zoomInButton.addEvent("click", function(){
if(scaleCount<100){
scaleCount+=10;
newFrame.object.style.transform = 'scale('+(scaleCount/100)+')';
}
});
}
this.zoomOut = function(parent){
var zoomOutButton = new Element();
zoomOutButton.create('botton', misc.randomID('IDzoomOutButton', 999999), 'zoomOutButton', parent);
zoomOutButton.addEvent("click", function(){
if(scaleCount>10){
scaleCount-=10;
newFrame.object.style.transform = 'scale('+(scaleCount/100)+')';
}
});
}
return this;
}<file_sep><?php
/* Rename file */
function renameFile(){
// get ajax data
$phpData = file_get_contents('php://input');
$obj = json_decode( $phpData );
if(file_exists('../code/' . $obj->newname)) {
$randNum = '_' . (string) rand();
$ex = explode("/", $obj->newname);
$sepExt = explode(".", $ex[count($ex) -1]);
$newFileName = $sepExt[0] . $randNum . '.' . $sepExt[1];
//$newFileName = $ex[count($ex) -1] . $randNum;
$str = str_replace($sepExt[0], $sepExt[0] . $randNum, $obj->newname);
rename('../code/' . $obj->oldname, '../code/' . $str);
echo $newFileName;
}
else{
rename('../code/' . $obj->oldname, '../code/' . $obj->newname);
$ex = explode("/", $obj->newname);
$newFileName = $ex[count($ex) -1];
echo $newFileName;
}
}
renameFile();
?><file_sep><?php
function sendPhpCode() {
$phpCode = file_get_contents('php://input');
eval('?>'.$phpCode);
}
sendPhpCode();
?><file_sep><?php
/* Save new file */
function saveNewFile(){
// get ajax data
$phpData = file_get_contents('php://input');
$obj = json_decode( $phpData );
if(file_exists('../code/' . $obj->fileNamePath)) {
$randNum = '_' . (string) rand();
$ex = explode("/", $obj->fileNamePath);
if (strpos($obj->fileNamePath, '.') === false) {
$newFileName = $ex[count($ex) -1] . $randNum;
$str = str_replace($ex[count($ex) -1], $ex[count($ex) -1] . $randNum, $obj->fileNamePath);
}else{
$sepExt = explode(".", $ex[count($ex) -1]);
$newFileName = $sepExt[0] . $randNum . '.' . $sepExt[1];
$str = str_replace($sepExt[0], $sepExt[0] . $randNum, $obj->fileNamePath);
}
$phpfile = fopen('../code/' . $str , 'w');
if ($phpfile != null) {
fwrite($phpfile, $obj->data);
fclose($phpfile);
} else{
fclose($phpfile);
echo '<script type="text/javascript">alert("write error!...");</script>';
}
echo $newFileName;
}
else{
$phpfile = fopen('../code/' . $obj->fileNamePath, 'w');
if ($phpfile != null) {
fwrite($phpfile, $obj->data);
fclose($phpfile);
} else{
fclose($phpfile);
echo '<script type="text/javascript">alert("write error!...");</script>';
}
$ex = explode("/", $obj->fileNamePath);
$newFileName = $ex[count($ex) -1];
echo $newFileName;
}
}
saveNewFile();
?><file_sep>Simple live editor for php, js, html, css. (for the simple projects)
<file_sep><?php
/* Delete folder */
$phpData = file_get_contents('php://input');
$dir = '../code/' . $phpData;
function deleteDirectory($dirPath) {
if (is_dir($dirPath)) {
$objects = scandir($dirPath);
foreach ($objects as $object) {
if ($object != "." && $object !="..") {
if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir") {
if($dirPath !="../code/"){
deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
}
echo $dirPath;
} else {
unlink($dirPath . DIRECTORY_SEPARATOR . $object);
}
}
}
reset($objects);
rmdir($dirPath);
}
}
//deleteDirectory($dir);
function removeDirectory($path) {
$files = glob(preg_replace('/(\*|\?|\[)/', '[$1]', $path).'/{,.}*', GLOB_BRACE);
foreach ($files as $file) {
if ($file == $path.'/.' || $file == $path.'/..') { continue; } // skip special dir entries
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}
removeDirectory($dir);
?>
|
27ada63af0b7b50d086fd20965a0d70d1078edbb
|
[
"JavaScript",
"Text",
"PHP"
] | 15
|
JavaScript
|
sktastan/sktLiveEditor
|
5ebfe459430f10554d6b3c8fa909abf7c84bad8a
|
6f7685290c4f0b9e8288f6783fb02f52dd155bee
|
refs/heads/master
|
<repo_name>BadassBison/Dungeon-Smash<file_sep>/src/index.js
import CanvasEl from './canvas.js';
import Character from './character.js';
import {refresh,
toggleSound,
startGame,
displaySkeletonDeaths,
displayHealthBar,
shoot,
changeDirection,
stopDirection,
drawCharacters,
drawFireballs,
drawExplosions,
moveCharacter,
moveComputers,
startComputers,
moveFireballs,
detectCollision,
generatePos,
gameOver
} from './utils.js';
import Fireball from './fireball.js';
import Explosion from './explosion.js';
// Canvas build
let canvasEl = new CanvasEl(innerWidth, innerHeight);
let canvas = canvasEl.canvasEl;
let ctx = canvasEl.ctx;
let mousePos = {x: innerHeight - 400, y: innerHeight/2};
let soundVolume = "on";
let skeletonCount = 0;
let skeletonRate = 80;
let killTracker = 0;
let start = false;
let playBtn = document.getElementById("start");
window.canvas = canvas;
// Character data
let characters = [];
let fireballs = [];
let explosions = [];
let kills = 0;
// Main character
let c = new Character("bald guy", innerWidth-350, innerHeight/2.5);
// start skeletons
characters.push(new Character("skeleton", innerWidth-300, innerHeight/1.4));
characters.push(new Character("skeleton", innerWidth-380, innerHeight/3));
characters.push(new Character("skeleton", innerWidth-290, 140));
characters.push(new Character("skeleton", innerWidth-440, innerHeight/2.7));
characters.push(new Character("skeleton", innerWidth-300, innerHeight/1.2));
characters.push(new Character("skeleton", innerWidth-280, innerHeight/2.2));
characters.push(new Character("skeleton", innerWidth-450, innerHeight/2.2));
characters.push(new Character("skeleton", innerWidth-450, 200));
characters.push(new Character("skeleton", innerWidth-250, 100));
characters.push(new Character("skeleton", innerWidth-500, innerHeight/2.9));
characters.push(new Character("skeleton", innerWidth-470, innerHeight/1.5));
// Sprite cycle info
let spriteCycle = 0;
// Movement storage
let movements = [];
let drawData;
const updateCharacterData = drawData => {
spriteCycle = drawData["spriteCycle"];
characters = drawData["characters"];
}
const updateFireballData = drawData => {
fireballs = drawData["fireballs"];
}
const updateAll = drawData => {
characters = drawData["characters"];
fireballs = drawData["fireballs"];
explosions = drawData["explosions"];
kills = drawData["kills"];
if (kills % 4 === 0 && kills !== 0 && kills !== killTracker) {
skeletonRate--;
killTracker = kills;
}
}
const updateExplosionData = drawData => {
explosions = drawData["explosions"];
}
const makeSkeletons = (skeletonCount, characters) => {
skeletonCount++;
if (skeletonCount % skeletonRate === 0) {
skeletonCount = 0;
let pos = generatePos(canvas.width, canvas.height);
characters.push(new Character("skeleton", pos.x, pos.y))
}
return skeletonCount;
}
// Animations ----------------------------------------------------------
const game = () => {
refresh(ctx, canvas);
ctx.font = "50px Georgia";
ctx.fillStyle = "White";
ctx.fillText("Dungeon Smash", canvas.width * 0.38, canvas.height/2 - 200);
updateCharacterData(drawCharacters(characters, spriteCycle, ctx, c));
c.directionMove();
startComputers(characters, mousePos);
updateAll(detectCollision(c, characters, fireballs, explosions, kills, soundVolume));
if (start){
characters = [];
draw();
}
if (!start) window.requestAnimationFrame(game);
}
const move = () => {
updateAll(detectCollision(c, characters, fireballs, explosions, kills, soundVolume));
moveCharacter(movements, c);
moveComputers(characters, c);
moveFireballs(fireballs);
}
const draw = () => {
if (gameOver(c)){
refresh(ctx, canvas); // clears the canvas
skeletonCount = makeSkeletons(skeletonCount, characters);
updateCharacterData(drawCharacters(characters, spriteCycle, ctx, c));
updateFireballData(drawFireballs(fireballs, ctx, canvas));
updateExplosionData(drawExplosions(explosions, ctx));
displaySkeletonDeaths(kills, ctx);
displayHealthBar(ctx, c);
move();
} else {
ctx.font = "50px Georgia";
ctx.fillStyle = "red";
ctx.fillText("You Died", canvas.width * 0.43, canvas.height/2 - 200);
ctx.fillStyle = "Red";
ctx.fillText("Your Kills: " + kills, canvas.width * 0.41, canvas.height - 250);
characters = []
playBtn.classList.remove("hidden");
}
window.requestAnimationFrame(draw);
}
// ------------------------------------------------------------------------
window.addEventListener("click", e => fireballs = shoot(fireballs, e, c, soundVolume));
window.addEventListener("keydown", e => fireballs = changeDirection(e, movements, fireballs, mousePos, c, soundVolume));
window.addEventListener("keyup", e => movements = stopDirection(e, movements));
window.addEventListener("mousemove", e => mousePos = {x: e.clientX, y: e.clientY});
volume.addEventListener("click", e => soundVolume = toggleSound(e, soundVolume));
mute.addEventListener("click", e => soundVolume = toggleSound(e, soundVolume));
playBtn.addEventListener("click", e => start = startGame(e, c));
game();<file_sep>/README.md
# Dungeon Smash
## Background & Overview
Dungeon smash was a project I worked on over a 4 day period as one of my projects finishing the App Academy bootcamp. Oddly enough this game was inspired by having a friend ask me about sprite sheets and deciding to learn more myself. As growing up with games like Zelda and Earthbound, this was an amazing project to work on. This game gave me an opportunity to explore 2D game mechanics in a whole new light;
## Technologies
`HTML` / `CSS` / `JavaScript`
## Features
### Sprite animation
There are 4 main sprite sheets used in this project,
* Main Character
* Skeleton
* Fireball
* Explosion
These sprites are being rendered by using one sprite sheet image and looping over the sections that make the animation. Each character has four face positions. The fireballs have animations for 8 positions (includes the diagonals). The explosion looks the cleanest with having 42 different frames to make the animation.
### Main Character Movements
The main characters movements are controled with either the arrow keys or the wasd keys. This was an interested challenge, using event handlers in Javascript you lose the previous key value if another was pressed. This means if you are moving left and tap the space, the movement would stop. Also if you held a key for too long, it would start to autofire either creating a staggering action or a rapid action.
My technique to solve these problems was to store the information on the key press event handler and to remove that information on the key release event handler. There are x & y speeds applied to these to make this possible. This also enabled diagonal movement.
### Computer Movements
Each computer is using the main characters position as a guide to where to move next. Using this distance calculation;
```javascript
let dx = computer.x - mainCharacter.x;
let dy = computer.y - mainCharacter.y;
let dist = Math.sqrt( dx*dx + dy*dy);
computer.move({ x: (dx/dist), y: (dy/dist) })
```
I was able to proportionally move the computers fluidly.
### Shooting Fireballs
Fireballs are shoot in the direction of the mouse. They can be fired by click, shift, or space. Using the click was slightly easier to implement, the `click` event handler was able to give me the mouse position information in order to calculate direction. The the key presses, I made another `mouseOver` event handler that consistently updated a mousePos variable that I then would pass to the `keyDown` event handler.
The fireballs themselfs would store the data of the direction at click and would travel in that direction. Based off that position, I was able to create an algorithm that could determine which sprite animation to render that would most closesly resemble the direction of travel.
There is also sound effects that play with each shot. If the sound is turned on in the game, a new sound object is created with each shot. Only lasting the duration of the sound and then being detached for garbage collection.
### Explosions
When a fireball hits a skeleton, the explosion sprite animation triggers, both the fireball and skeleton are removed, and the explosion sound is triggered. This was one of the most satisfying parts of the project, and if you're curious why, go give my game a try. You will not be disappointed.
The explosion happens at the exact position of the skeleton it hit, giving the appearance that the skeleton just exploded.
The collision detection is done by checking the fireballs distance from computers computers against the sum of their to radii. If at any point the sum is less then their dist, the explosion would occur.
### Layering Sprites
Layering the sprites in canvas was an essential part to give the appearance of natural distance between sprites. Without this the sprites would overlap in unnatural ways having some sprites appear to be over lapping others even though they are higher on the screen.
To fix this I would sort the characters array based on y position each time before rendering. This would order them accordingly and make it seem as if they were in the correct position at all times
### Bounce Effect
Each character has awareness of every other character, and if they touch, they will slightly bounce apart. If a skeleton touches the main character, the bounce sound will trigger and the main character will take some damage.
### Regenerating Health
When the main character is not being touched, he will be recovering a small amount of health over time.
### Screen Wrap
When the main character leaves the screen, he will appear on the opposite side in a pacman like manner.
### Random Infinite Computer Generation
Computer sprites are randomly generated off screen around the edge of the canvas. This gives the appeal that they are just consistently marching in from all types of distances.
### Healthbar
The healthbar is tied to the main characters health. It decreases each time a skeleton bounces off the main character. Once the main characters health reaches 0, the game is over.
### Kill tracking
Kills are incremented on each skeleton death. This value is shown for players but also used to increment the difficulty.
### Difficulty increment
The generation of skeletons speeds up after every 4 kills. There is no limit to the number of skeletons that can appear, so before you know it you will be staring at an entire army marching to kill you.
### Start Screen Computers Tracking Mouse
The computers here will consistently pursue the mouse for a nice visual of what the game entails. The main character is looping over its run down animation as well.
Upon clicking the play button, all the computers will vanish and you will be left with full control over the main character.<file_sep>/src/character.js
import Skeleton from './skeleton.js';
import BaldGuy from './bald_guy.js';
export default class Character {
static sprites(sprite) {
switch(sprite) {
case "skeleton":
return new Skeleton;
case "bald guy":
return new BaldGuy;
}
}
constructor( sprite, x, y ) {
this.sprite = Character.sprites(sprite);
this.x = x;
this.y = y;
this.defaultSpeed = 3;
this.speedX = this.defaultSpeed;
this.speedY = this.defaultSpeed;
this.direction = "stand";
}
directionMove() {
this.direction = "move";
}
directionStand() {
this.direction = "stand";
}
changeDirection(dir){
this.direction = dir;
}
move(move) {
this.x -= move.x;
this.y -= move.y;
}
bump(dx, dy){
let val = setInterval(() => {
this.x += dx;
this.y += dy;
}, 50);
setTimeout(() => {
clearInterval(val);
}, 150);
}
}<file_sep>/src/utils.js
import Sound from './sounds.js';
import Character from './character.js';
import Fireball from './fireball.js';
import Explosion from './explosion.js';
//-------------------------------------------------------------------------------------
// Refresh the canvas
export const refresh = (ctx, canvas) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
//-------------------------------------------------------------------------------------
// Play sounds
const playSound = sound => {
// Remove previous sound nodes
let sounds = document.querySelectorAll('.sound');
sounds.forEach(el => {
el.remove();
})
switch(sound){
case "fireball":
let shot = new Sound('../sounds/fireballShot.wav');
shot.play();
case "explosion":
let hit = new Sound('../sounds/explosion.wav');
hit.play();
case "bump":
let bump = new Sound('../sounds/bump.flac');
bump.play();
}
}
//-------------------------------------------------------------------------------------
// Sound toggle
export const toggleSound = (e, soundVolume) => {
let mute = document.getElementById("mute");
let volume = document.getElementById("volume");
if(e.target.id === "mute"){
mute.classList.add("hidden");
volume.classList.remove("hidden");
soundVolume = "on";
} else {
volume.classList.add("hidden");
mute.classList.remove("hidden");
soundVolume = "mute"
}
return soundVolume;
}
//-------------------------------------------------------------------------------------
// Start game
export const startGame = (e, c) => {
let start = document.getElementById("start").setAttribute("class", "hidden");
let controls = document.querySelectorAll(".controls");
controls.forEach(node => node.remove());
c.sprite.fullHealth();
return true;
}
//-------------------------------------------------------------------------------------
// Click Shooting
export const shoot = (fireballs, e, c, soundVolume) => {
if (fireballs.length < 5){
if(soundVolume === "on") playSound("fireball");
fireballs.push(new Fireball(c.x, c.y, e.x, e.y));
}
return fireballs;
}
//-------------------------------------------------------------------------------------
// Kills counter
export const displaySkeletonDeaths = (kills, ctx) => {
ctx.font="20px Georgia"
ctx.fillStyle = "white";
ctx.fillText("Kills: " + kills, innerWidth - 400, 36);
}
//-------------------------------------------------------------------------------------
// Health Bar
export const displayHealthBar = (ctx, c) => {
ctx.lineWidth = 6;
ctx.strokeRect(innerWidth - 302, 18, 254, 24);
ctx.fillStyle = "#FF0000";
ctx.fillRect(innerWidth - 299, 21, c.sprite.health * 2.5, 18);
}
//-------------------------------------------------------------------------------------
// key pressed actions
export const changeDirection = (keyVal, movements, fireballs, mousePos, c, soundVolume) => {
switch(keyVal.key){
case "ArrowUp":
case "w":
if(!(movements.find(move => move === "ArrowUp"))) movements.push("ArrowUp");
c.changeDirection("move");
break;
case "ArrowLeft":
case "a":
if(!(movements.find(move => move === "ArrowLeft"))) movements.push("ArrowLeft");
c.changeDirection("move");
break;
case "ArrowDown":
case "s":
if(!(movements.find(move => move === "ArrowDown"))) movements.push("ArrowDown");
c.changeDirection("move");
break;
case "ArrowRight":
case "d":
if(!(movements.find(move => move === "ArrowRight"))) movements.push("ArrowRight");
c.changeDirection("move");
break;
case " ":
case "Shift":
if (fireballs.length < 5) {
if (soundVolume === "on") playSound("fireball");
fireballs.push(new Fireball(c.x, c.y, mousePos.x, mousePos.y));
}
break;
}
return fireballs;
}
//-------------------------------------------------------------------------------------
// Key release actions
export const stopDirection = (keyVal, movements) => {
switch(keyVal.key){
case "ArrowUp":
case "w":
movements = movements.filter(el => el !== "ArrowUp")
break;
case "ArrowLeft":
case "a":
movements = movements.filter(el => el !== "ArrowLeft")
break;
case "ArrowDown":
case "s":
movements = movements.filter(el => el !== "ArrowDown")
break;
case "ArrowRight":
case "d":
movements = movements.filter(el => el !== "ArrowRight")
break;
}
return movements;
}
//-------------------------------------------------------------------------------------
// Draws the characters
export const drawCharacters = (characters, spriteCycle, ctx, c) => {
spriteCycle++;
characters.unshift(c);
characters.sort((a, b) => {
return (a.y - b.y)
})
characters.forEach(character => {
if (character.direction !== "stand") {
if(spriteCycle % 8 === 0) {
spriteCycle = 0;
character.sprite.updateSprite();
}
} else {
character.sprite.srcX = 0;
}
ctx.drawImage(
character.sprite.img,
character.sprite.srcX,
character.sprite.srcY,
character.sprite.width,
character.sprite.height,
character.x,
character.y,
character.sprite.width * 1.4,
character.sprite.height * 1.4
);
})
characters = characters.filter(character => c !== character)
return {
spriteCycle: spriteCycle,
characters: characters
};
}
//-------------------------------------------------------------------------------------
// Character movement
export const moveCharacter = (movements, c) => {
if (movements.length === 0) {
c.direction = "stand";
return null;
}
movements.forEach(movement => {
switch(movement){
case "ArrowDown":
if(c.y < canvas.height - 10){
c.y += c.speedY;
} else {
c.y = -40;
}
c.sprite.srcY = 2 * c.sprite.height;
break;
case "ArrowRight":
if(c.x < canvas.width - 10){
c.x += c.speedX;
} else {
c.x = -40;
}
c.sprite.srcY = 3 * c.sprite.height;
break;
case "ArrowUp":
if(c.y > -50){
c.y -= c.speedY;
} else {
c.y = canvas.height - 30;
}
c.sprite.srcY = 0 * c.sprite.height;
break;
case "ArrowLeft":
if(c.x > -50){
c.x -= c.speedX;
} else {
c.x = canvas.width - 30;
}
c.sprite.srcY = 1 * c.sprite.height;
break;
}
})
}
//-------------------------------------------------------------------------------------
// Computer movement
export const moveComputers = (computers, c) => {
computers.forEach(computer => {
let dx = computer.x - c.x;
let dy = computer.y - c.y;
if (dy === 0) dy += 0.000001;
let dist = Math.sqrt( dx*dx + dy*dy);
computer.move({ x: (dx/dist), y: (dy/dist) })
if(dx/dy > 1){
if(dx > 0) {
computer.changeDirection("left")
computer.sprite.srcY = 1 * computer.sprite.height;
} else {
computer.changeDirection("right")
computer.sprite.srcY = 3 * computer.sprite.height;
}
} else {
if(dy > 0) {
computer.changeDirection("up")
computer.sprite.srcY = 0 * computer.sprite.height;
} else {
computer.changeDirection("down")
computer.sprite.srcY = 2 * computer.sprite.height;
}
}
})
}
//-------------------------------------------------------------------------------------
// Start screen Computer movement
export const startComputers = (computers, mousePos) => {
computers.forEach(computer => {
let dx = computer.x - mousePos.x;
let dy = computer.y - mousePos.y;
if (dy === 0) dy += 0.000001;
let dist = Math.sqrt( dx*dx + dy*dy);
computer.move({ x: (dx/dist), y: (dy/dist) })
if(dx/dy > 1){
if(dx > 0) {
computer.changeDirection("left")
computer.sprite.srcY = 1 * computer.sprite.height;
} else {
computer.changeDirection("right")
computer.sprite.srcY = 3 * computer.sprite.height;
}
} else {
if(dy > 0) {
computer.changeDirection("up")
computer.sprite.srcY = 0 * computer.sprite.height;
} else {
computer.changeDirection("down")
computer.sprite.srcY = 2 * computer.sprite.height;
}
}
})
}
//-------------------------------------------------------------------------------------
// Random computer placement
export const generatePos = (width, height) => {
let x = Math.floor(Math.random() * width);
let y = Math.floor(Math.random() * height);
let diceRoll = Math.floor(Math.random() * 4)
switch(diceRoll) {
case 0:
return {x: x, y: -100};
case 1:
return {x: x, y: height + 100};
case 2:
return {x: -100, y: y};
case 3:
return {x: width + 100, y: y};
}
}
//-------------------------------------------------------------------------------------
// Collision detection
export const detectCollision = (c, characters, fireballs, explosions, kills, soundVolume) => {
// Main character health regeneration
c.sprite.heal();
// Main character touches an enemy
characters.forEach(character => {
let dx = c.x - character.x;
let dy = c.y - character.y;
if (dy === 0) dy += 0.000001;
let dist = Math.sqrt(dx*dx + dy*dy);
if (dist < (c.sprite.hitbox.radius + character.sprite.hitbox.radius)) {
c.bump(dx/dist * 2, dy/dist * 2)
if (soundVolume == "on") playSound("bump");
c.sprite.hit();
}
})
// Any Enemy touches any other enemy
let all = characters.concat(c);
for(let i = 0; i < all.length - 1; i++){
for(let j = i+1; j < all.length; j++){
let dx = all[i].x - all[j].x;
let dy = all[i].y - all[j].y;
if (dy === 0) dy += 0.000001;
let dist = Math.sqrt(dx*dx + dy*dy);
if (dist < (all[i].sprite.hitbox.radius + all[j].sprite.hitbox.radius)) {
all[i].bump(dx/dist * 2, dy/dist * 2)
}
}
}
// Fireball hits an enemy
let fireballHits = []
let skeletonsHit = []
for(let i = 0; i < fireballs.length; i++){
for(let j = 0; j < characters.length; j++){
let dx = fireballs[i].x - characters[j].x;
let dy = fireballs[i].y - characters[j].y;
if (dy === 0) dy += 0.000001;
let dist = Math.sqrt(dx*dx + dy*dy);
if (dist < (fireballs[i].hitbox.radius + characters[j].sprite.hitbox.radius)) {
if (soundVolume === "on") playSound("explosion");
kills++;
fireballHits.push(fireballs[i]);
skeletonsHit.push(characters[j]);
explosions.push(new Explosion(characters[j].x, characters[j].y))
}
}
}
// Remove fireball if hit
fireballHits.forEach(hit => {
fireballs = fireballs.filter(fireball => hit !== fireball);
})
// Remove skeleton if hit
skeletonsHit.forEach(hit => {
characters = characters.filter(character => hit !== character);
})
return {
fireballs: fireballs,
characters: characters,
explosions: explosions,
kills: kills
}
}
//-------------------------------------------------------------------------------------
// Draw fireballs
export const drawFireballs = (fireballs, ctx, canvas) => {
fireballs.forEach(fireball => {
fireball.updateSprite();
ctx.drawImage(
fireball.img,
fireball.srcX,
fireball.srcY,
fireball.width,
fireball.height,
fireball.x,
fireball.y,
fireball.width * 1.2,
fireball.height * 1.2
)
})
fireballs = fireballs.filter(fireball => {
if (fireball.x < -40 || fireball.x > canvas.width + 40) return false
if (fireball.y < -40 || fireball.y > canvas.height + 40) return false
return true
})
return { fireballs: fireballs };
}
//-------------------------------------------------------------------------------------
// Move fireballs
export const moveFireballs = fireballs => {
fireballs.forEach(fireball => {
if (fireball.shot) {
let dx = fireball.x - fireball.dirX;
let dy = fireball.y - fireball.dirY;
if (dy === 0) dy += 0.000001;
let dist = Math.sqrt( dx*dx + dy*dy);
fireball.data(dx, dy, dist);
}
fireball.move({
x: (fireball.dx/fireball.dist) * 5,
y: (fireball.dy/fireball.dist) * 5
})
let ratio = fireball.dx/fireball.dy;
if(0.5 <= ratio && ratio < 2 && fireball.dx > 0 && fireball.dy > 0){
fireball.direction(1);
} else
if((-0.7 <= ratio && ratio < 0.5 && fireball.dx > 0 && fireball.dy > 0) ||
(-0.7 <= ratio && ratio < 0.5 && fireball.dx <= 0 && fireball.dy >= 0)){
fireball.direction(2);
} else
if(-5 <= ratio && ratio < -0.7 && fireball.dx < 0 && fireball.dy > 0){
fireball.direction(3);
} else
if(-2 <= ratio && ratio < -0.5 && fireball.dx > 0 && fireball.dy < 0){
fireball.direction(7);
} else
if((-0.5 <= ratio && ratio < 0.7 && fireball.dx < 0 && fireball.dy < 0) ||
(-0.5 <= ratio && ratio < 0.7 && fireball.dx >= 0 && fireball.dy <= 0)){
fireball.direction(6);
} else
if(0.7 <= ratio && ratio < 3 && fireball.dx < 0 && fireball.dy < 0){
fireball.direction(5);
} else
if((-0.5 > ratio && fireball.dx < 0 && fireball.dy > 0) ||
(3 <= ratio && fireball.dx <= 0 && fireball.dy <= 0)){
fireball.direction(4);
} else
if((-2 > ratio && fireball.dx > 0 && fireball.dy < 0) ||
(2 <= ratio && fireball.dx >= 0 && fireball.dy >= 0)){
fireball.direction(0);
}
})
}
//-------------------------------------------------------------------------------------
// Draw explosions
export const drawExplosions = (explosions, ctx) => {
explosions.forEach(boom => {
boom.spriteCycle++;
if (boom.spriteCycle % 2 === 0) {
boom.updateSprite();
boom.spriteCycleReset();
}
ctx.drawImage(
boom.img,
boom.srcX,
boom.srcY,
boom.width,
boom.height,
boom.x,
boom.y,
boom.width * 0.8,
boom.height * 0.8
)
})
explosions = explosions.filter(boom => !boom.complete);
return {explosions: explosions}
}
//-------------------------------------------------------------------------------------
// Game Over
export const gameOver = c => {
return (c.sprite.health !== 0)
}<file_sep>/src/skeleton.js
export default class Skeleton {
constructor() {
this.img = new Image();
this.img.src = '../sprite_sheets/skeleton.png';
this.sheetWidth = 576;
this.sheetHeight = 256;
this.cols = 9;
this.rows = 4;
this.width = this.sheetWidth / this.cols;
this.height = (this.sheetHeight / this.rows) + 1;
this.hitbox = {
x: 44.5,
y: 75,
width: 27,
height: 24,
radius: 15
}
this.health = 1;
this.srcX = 0;
this.srcY = 2 * this.height;
this.currentFrame = 1;
}
updateSprite() {
this.currentFrame = (++this.currentFrame % (this.cols-1)) + 1
this.srcX = this.currentFrame * this.width;
}
hit() {
if (this.health > 0 ) this.health--;
}
}<file_sep>/src/fireball.js
export default class Fireball {
constructor(x, y, dirX, dirY){
this.img = new Image();
this.img.src = "../sprite_sheets/fireball.png";
this.sheetWidth = 512;
this.sheetHeight = 512;
this.rows = 8;
this.cols = 8;
this.width = this.sheetWidth / this.cols;
this.height = this.sheetWidth / this.cols;
this.x = x;
this.y = y + 20;
this.dirX = dirX;
this.dirY = dirY;
this.dx = 0;
this.dy = 0;
this.dist = 0;
this.hitbox = {
x: 27,
y: 25,
width: 22,
height: 45,
radius: 25
}
this.srcX = 0;
this.srcY = 3 * this.height;
this.spriteCycle = 0;
this.currentFrame = 0;
this.shot = true;
}
updateSprite() {
this.currentFrame = ++this.currentFrame % (this.cols-1)
this.srcX = this.currentFrame * this.width;
}
move(move) {
this.x -= move.x;
this.y -= move.y;
}
data(dx, dy, dist){
this.shot = false;
this.dx = dx;
this.dy = dy;
this.dist = dist;
}
direction(num){
this.srcY = num * this.height
}
}<file_sep>/src/sounds.js
export default class Sound {
constructor(src) {
this.sound = new Audio(src);
this.sound.volume = 0.3;
}
play (){
this.sound.play();
}
}
|
4018cb295920cfb1f3ec0a43dce8b963224b0f00
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
BadassBison/Dungeon-Smash
|
2a0c69e0fbaa90a5219d2f6237a6e0a734d3c400
|
d09adecc67fd95fe41d95c4230f41aa491ccce82
|
refs/heads/master
|
<repo_name>coolc0ders/SocialAuthXamarinFormsAspNetCore<file_sep>/AuthDemoXForms/AuthDemoXForms/AuthDemoXForms/Models/Facebook/FacebookSigninModel.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Text;
namespace AuthDemoXForms.Models.Facebook
{
public class FacebookSigninModel
{
public string Username { get; set; }
public Properties Properties { get; set; }
public Cookies Cookies { get; set; }
}
public class Properties
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("data_access_expiration_time")]
public string DataAccessExpirationTime { get; set; }
[JsonProperty("expires_in")]
public string ExpiresIn { get; set; }
[JsonProperty("state")]
public string State { get; set; }
}
public class Cookies
{
public int Capacity { get; set; }
public int Count { get; set; }
public int MaxCookieSize { get; set; }
public int PerDomainCapacity { get; set; }
}
public class PictureData
{
public int Height { get; set; }
[JsonProperty("is_silhouette")]
public bool IsSilhouette { get; set; }
public string Url { get; set; }
public int Width { get; set; }
}
}
<file_sep>/AuthDemoWeb/AuthDemoWeb/Controllers/AccountController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AuthDemoWeb.Models;
using AuthDemoWeb.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace AuthDemoWeb.Controllers
{
[Route("Account/[action]")]
[ApiController]
public class AccountController : ControllerBase
{
private readonly SignInManager<AppUser> _signInManager;
private readonly UserManager<AppUser> _userManager;
private readonly IConfiguration _configuration;
private readonly GoogleAuthService _googleAuthService;
private readonly FacebookAuthService _facebookAuthService;
public AccountController(
UserManager<AppUser> userManager,
SignInManager<AppUser> signInManager,
IConfiguration configuration,
GoogleAuthService googleAuthService,
FacebookAuthService facebookAuthService
)
{
_facebookAuthService = facebookAuthService;
_googleAuthService = googleAuthService;
_userManager = userManager;
_signInManager = signInManager;
_configuration = configuration;
}
[HttpPost]
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
var user = await _userManager.FindByEmailAsync(model.Email);
var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, false, false);
if (result.Succeeded)
{
var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
return Ok(GenerateJwtToken(model.Email, appUser));
}
throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
}
[HttpPost]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
var user = new AppUser
{
UserName = model.Email,
Email = model.Email
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, false);
return Ok(GenerateJwtToken(model.Email, user));
}
throw new ApplicationException(string.Join(" ,", result.Errors.Select(e => e.Description)));
}
[Authorize]
[HttpGet]
public IActionResult TestAuth()
{
return Ok("Success");
}
[HttpPost]
public async Task<IActionResult> Google([FromBody] UserTokenIdModel token)
{
try
{
var user = await _googleAuthService.Authenticate(token);
await _signInManager.SignInAsync(user, true);
var jwtToken = GenerateJwtToken(user.Email, user);
return Ok(jwtToken);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
return BadRequest(e.Message);
}
}
[HttpPost]
public async Task<IActionResult> Facebook([FromBody] UserTokenIdModel token)
{
try
{
var user = await _facebookAuthService.Authenticate(token);
await _signInManager.SignInAsync(user, true);
var jwtToken = GenerateJwtToken(user.Email, user);
return Ok(jwtToken);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
return BadRequest(e.Message);
}
}
private object GenerateJwtToken(string email, IdentityUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));
var token = new JwtSecurityToken(
_configuration["JwtIssuer"],
_configuration["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}<file_sep>/AuthDemoWeb/AuthDemoWeb/Startup.cs
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AspNetCore.Identity.Mongo;
using AspNetCore.Identity.Mongo.Model;
using AuthDemoWeb.Models;
using AuthDemoWeb.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace AuthDemoWeb
{
public class Startup
{
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddUserSecrets<Startup>(true, reloadOnChange: true);
var configuration = builder.Build();
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddIdentityMongoDbProvider<AppUser, MongoRole>(identityOptions =>
{
identityOptions.Password.RequiredLength = 6;
identityOptions.Password.RequireLowercase = false;
identityOptions.Password.RequireUppercase = false;
identityOptions.Password.RequireNonAlphanumeric = false;
identityOptions.Password.RequireDigit = false;
identityOptions.User.RequireUniqueEmail = true;
},
mongoIdentityOptions => {
mongoIdentityOptions.ConnectionString = "mongodb://localhost:27017/IdentityMongoPlay";
}).AddDefaultTokenProviders();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = Configuration["JwtIssuer"],
ValidAudience = Configuration["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
ClockSkew = TimeSpan.Zero // remove delay of token when expire
};
});
services.AddScoped<GoogleAuthService>();
services.AddScoped<FacebookAuthService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/AuthDemoWeb/AuthDemoWeb/Services/FacebookAuthService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using AuthDemoWeb.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
namespace AuthDemoWeb.Services
{
public class FacebookAuthService : IAuthService
{
private readonly IConfiguration _configuration;
private readonly UserManager<AppUser> _userManager;
public FacebookAuthService(IConfiguration configuration, UserManager<AppUser> userManager)
{
_userManager = userManager;
_configuration = configuration;
}
public async Task<AppUser> Authenticate(UserTokenIdModel token)
{
//NB: These config files are loaded from the user secrets.
var appToken = await GenerateAppAccessToken(_configuration["Facebook:AppId"], _configuration["Facebook:AppSecret"]);
var isValid = await DebugUserAccessToken(appToken, token.TokenId);
if (isValid)
{
var user = await CreateOrGetUser(token);
return user;
}
throw new Exception("Invalid Token");
}
private async Task<AppUser> CreateOrGetUser(UserTokenIdModel userToken)
{
var user = await _userManager.FindByEmailAsync(userToken.Email);
if (user == null)
{
var appUser = new AppUser
{
FirstName = userToken.Name,
SecondName = userToken.FamilyName,
Email = userToken.Email,
PictureURL = userToken.Picture,
OAuthIssuer = "facebook",
UserName = userToken.FamilyName + "_" + userToken.GivenName
};
var identityUser = await _userManager.CreateAsync(appUser);
If(identityUser.Succeeded)
{
return appUser;
}
else
{
throw new Exception("An error ocurred creating the user" + JsonConvert.SerializeObject(identityUser.Errors));
}
}
return user;
}
private async Task<string> GenerateAppAccessToken(string appId, string appSecret)
{
using var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync($@"https://graph.facebook.com/oauth/access_token?client_id={appId}&client_secret={appSecret}&grant_type=client_credentials");
var obj = JsonConvert.DeserializeAnonymousType(json, new { access_token = "", token_type = "" });
return obj.access_token;
}
private async Task<bool> DebugUserAccessToken(string appAccessToken, string userAccessToken)
{
using var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync($@"https://graph.facebook.com/debug_token?input_token={userAccessToken}&access_token={appAccessToken}");
var obj = JsonConvert.DeserializeAnonymousType(json, new { data = new { app_id = "", is_valid = false } });
return obj.data.is_valid;
}
}
}
<file_sep>/AuthDemoWeb/AuthDemoWeb/Services/IAuthService.cs
using AuthDemoWeb.Models;
using Google.Apis.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static Google.Apis.Auth.GoogleJsonWebSignature;
namespace AuthDemoWeb.Services
{
public interface IAuthService
{
Task<AppUser> Authenticate(UserTokenIdModel token);
}
}
<file_sep>/AuthDemoXForms/AuthDemoXForms/AuthDemoXForms/Models/User.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace AuthDemoXForms.Models
{
[JsonObject]
public class APIUser
{
public string TokenId { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("verified_email")]
public bool VerifiedEmail { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("given_name")]
public string GivenName { get; set; }
[JsonProperty("family_name")]
public string FamilyName { get; set; }
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("picture")]
public string Picture { get; set; }
[JsonProperty("gender")]
public string Gender { get; set; }
}
public class FacebookUser
{
public string Id { get; set; }
public string Email { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
[JsonProperty("profile_pic")]
public string ProfilePic { get; set; }
[JsonProperty("locale")]
public string Locale { get; set; }
[JsonProperty("timeZone")]
public int Timezone { get; set; }
[JsonProperty("gender")]
public string Gender { get; set; }
}
}
<file_sep>/AuthDemoWeb/AuthDemoWeb/Services/GoogleAuthService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AuthDemoWeb.Models;
using Google.Apis.Auth;
using Microsoft.AspNetCore.Identity;
using static Google.Apis.Auth.GoogleJsonWebSignature;
namespace AuthDemoWeb.Services
{
public class GoogleAuthService : IAuthService
{
private readonly UserManager<AppUser> _userManager;
public GoogleAuthService(UserManager<AppUser> userManager)
{
_userManager = userManager;
}
public async Task<AppUser> Authenticate(UserTokenIdModel userTokenModel)
{
var payload = await GoogleJsonWebSignature.ValidateAsync(userTokenModel.TokenId, new GoogleJsonWebSignature.ValidationSettings());
return await CreateOrGetUser(payload, userTokenModel);
}
private async Task<AppUser> CreateOrGetUser(Payload payload, UserTokenIdModel userToken)
{
var user = await _userManager.FindByEmailAsync(payload.Email);
if (user == null)
{
var appUser = new AppUser
{
FirstName = userToken.Name,
SecondName = userToken.FamilyName,
Email = userToken.Email,
PictureURL = userToken.Picture,
OAuthIssuer = payload.Issuer,
OAuthSubject = payload.Subject,
UserName = userToken.Name.Replace(" ", "_")
};
var identityUser = await _userManager.CreateAsync(appUser);
return appUser;
}
return user;
}
}
}
<file_sep>/AuthDemoXForms/AuthDemoXForms/AuthDemoXForms/ViewModels/AuthViewModel.cs
using AuthDemoXForms.Models;
using AuthDemoXForms.Models.Facebook;
using AuthDemoXForms.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Auth;
using Xamarin.Forms;
namespace AuthDemoXForms.ViewModels
{
public class AuthViewModel : BaseViewModel
{
public Command GoogleAuthCommand { get; set; }
const string ClientId = "...-...apps.googleusercontent.com";
OAuth2Authenticator _authenticator;
public Command FacebookAuthCommand { get; set; }
public AuthViewModel()
{
GoogleAuthCommand = new Command(async () => await GoogleAuth());
FacebookAuthCommand = new Command(async () => await FacebookAuth());
}
private async Task GoogleAuth()
{
_authenticator = new OAuth2Authenticator(
clientId: ClientId,
clientSecret: "",
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
authorizeUrl: new Uri("https://accounts.google.com/o/oauth2/auth"),
redirectUrl: new Uri("com.googleusercontent.apps....-...:/oauth2redirect"),
accessTokenUrl: new Uri("https://www.googleapis.com/oauth2/v4/token"),
isUsingNativeUI: true
);
_authenticator.Completed += Authenticator_Completed;
_authenticator.Error += _authenticator_Error;
AuthenticationState.Authenticator = _authenticator;
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(_authenticator);
}
async Task FacebookAuth()
{
var facebookAppId = "";
_authenticator = new OAuth2Authenticator(
clientId: facebookAppId,
scope: "email",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
_authenticator.Completed += Authenticator_Facebook_Completed;
_authenticator.Error += _authenticator_Error;
AuthenticationState.Authenticator = _authenticator;
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(_authenticator);
}
private void _authenticator_Error(object sender, AuthenticatorErrorEventArgs e)
{
_authenticator.Error -= _authenticator_Error;
Debug.WriteLine(e.Message);
}
private async void Authenticator_Facebook_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
_authenticator.Completed -= Authenticator_Facebook_Completed;
if (e.IsAuthenticated)
{
var acc = e.Account;
var val = JsonConvert.SerializeObject(e.Account);
var model = JsonConvert.DeserializeObject<FacebookSigninModel>(val);
var user = await GetFacebookProfile(model.Properties.AccessToken);
await SignInToAPI(new APIUser
{
TokenId = model.Properties.AccessToken,
Email = user.Email,
FamilyName = user.FirstName,
GivenName = user.LastName,
Picture = user.ProfilePic
}, AuthProvider.Facebook);
}
}
public async Task<FacebookUser> GetFacebookProfile(string accessToken)
{
using var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(
$"https://graph.facebook.com/me?fields=email,first_name,last_name&access_token={accessToken}");
var profilePic = await GetFacebookProfilePicURL(accessToken, "");
var user = JsonConvert.DeserializeObject<FacebookUser>(json);
user.ProfilePic = profilePic;
return user;
}
public async Task<string> GetFacebookProfilePicURL(string accessToken, string userId)
{
using var httpClient = new HttpClient();
var picUrl = $"https://graph.facebook.com/v5.0/me/picture?redirect=false&type=normal&access_token={accessToken}";
var res = await httpClient.GetStringAsync(picUrl);
var pic = JsonConvert.DeserializeAnonymousType(res, new { data = new PictureData() });
return pic.data.Url;
}
private async void Authenticator_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
_authenticator.Completed -= Authenticator_Completed;
if (e.IsAuthenticated)
{
var acc = e.Account;
var usr = await GetGoogleUser(acc.Properties["id_token"], e.Account);
await SignInToAPI(usr, AuthProvider.Google);
}
}
private async Task<APIUser> GetGoogleUser(string idToken, Account account)
{
//Get user's profile info from Google
var request = new OAuth2Request("GET", new Uri("https://www.googleapis.com/oauth2/v2/userinfo"), null, account);
var response = await request.GetResponseAsync();
APIUser user = null;
if (response != null)
{
string userJson = await response.GetResponseTextAsync();
user = JsonConvert.DeserializeObject<APIUser>(userJson);
user.TokenId = idToken;
return user;
}
throw new Exception("Could not get user");
}
private async Task SignInToAPI(APIUser user, AuthProvider authProvider)
{
//Used Ngrok to tunnel My endpoint.
var endPoint = "https://5d13182b.ngrok.io";
if (authProvider == AuthProvider.Google)
endPoint = $"{endPoint}/Account/Google";
else
endPoint = $"{endPoint}/Account/Facebook";
using var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(user);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var res = await httpClient.PostAsync(endPoint, content);
//We get the JWT Token which we will be used to make authorized request to the API.
var jwt = await res.Content.ReadAsStringAsync();
}
}
public enum AuthProvider
{
Google,
Facebook
}
public class AuthenticationState
{
public static OAuth2Authenticator Authenticator;
}
}
|
af93c211a8a765c2d3171bbe9309ff543d12d267
|
[
"C#"
] | 8
|
C#
|
coolc0ders/SocialAuthXamarinFormsAspNetCore
|
6cbb661aac3688343f0bfb351abc0b7133fcab30
|
401fcded921a35c206321aa540d342104bab7453
|
refs/heads/master
|
<repo_name>ibraphem/greenshop<file_sep>/src/components/products/ProductList.js
import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
import Avatar from "@material-ui/core/Avatar";
import Divider from "@material-ui/core/Divider";
import ListItemSecondaryAction from "@material-ui/core/ListItemSecondaryAction";
import IconButton from "@material-ui/core/IconButton";
import CancelIcon from "@material-ui/icons/Cancel";
import AddShoppingCartIcon from "@material-ui/icons/AddShoppingCart";
import Tooltip from "@material-ui/core/Tooltip";
import Button from "@material-ui/core/Button";
import { useStateValue } from "../../StateProvider";
import { getBasketTotal } from "../../Reducer";
import { Link } from "react-router-dom";
import CheckOutButton from "../checkout/CheckOutButton";
import { Card } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
width: "100%",
minWidth: 300,
backgroundColor: theme.palette.background.paper,
padding: 0,
},
listPrimary: {
color: "red",
fontWeight: "100rem",
fontSize: "1rem",
},
card: {
width: "100%",
},
image: {
width: "100%",
height: "100%",
objectFit: "cover",
},
}));
const ProductList = ({ search, cartProps }) => {
// console.log(search);
const classes = useStyles();
const [{ basket }, dispatch] = useStateValue();
const addToBasket = (e) => {
let items = e.currentTarget.value;
let cartProduct = items.split(",").map(String);
dispatch({
type: "ADD_TO_BASKET",
item: {
id: cartProduct[0],
name: cartProduct[1],
category: cartProduct[2],
price: cartProduct[3],
tag: cartProduct[4],
image: cartProduct[5],
feed: cartProduct[6],
quantity: 1,
},
});
// console.log(dispatch);
};
const removeFromBasket = (e) => {
let id = e.currentTarget.value;
dispatch({
type: "REMOVE_FROM_BASKET",
id: id,
});
};
const [style, setStyle] = useState(true);
return (
<Card className={classes.card}>
<List className={classes.root}>
{search.map((item) => (
<>
<ListItem key={item.id}>
<ListItemAvatar>
<Avatar>
<img src={item.image} className={classes.image} />
</Avatar>
</ListItemAvatar>
<ListItemText
primary={
<Link
to={{
pathname: `/${item.category}/${item.name}`,
state: {
params: {
id: item.id,
name: item.name,
category: item.category,
price: item.price,
tag: item.tag,
feed: item.feed,
image: item.image,
},
},
}}
style={{ textDecoration: "none", color: "#ff0000" }}
>
{item.name}
</Link>
}
secondary={
cartProps ? (
<span>
{item.quantity} x ₦{item.price}
</span>
) : (
<span>₦{item.price}</span>
)
}
classes={{
primary: classes.listPrimary,
}}
/>
<ListItemSecondaryAction>
{cartProps ? (
<Tooltip title="Remove from cart">
<IconButton
edge="end"
aria-label="remove"
value={item.id}
onClick={removeFromBasket}
>
<CancelIcon />
</IconButton>
</Tooltip>
) : (
<Tooltip title="Add from cart">
<IconButton
aria-label="add to cart"
onClick={addToBasket}
value={[
item.id,
item.name,
item.category,
item.price,
item.tag,
item.image,
item.feed,
]}
>
<AddShoppingCartIcon />
</IconButton>
</Tooltip>
)}
</ListItemSecondaryAction>
</ListItem>
<Divider variant="inset" component="li" />
</>
))}
{cartProps ? (
<div style={{ textAlign: "center", padding: "10px" }}>
<h3>Total: ₦{getBasketTotal(basket)}</h3>
<CheckOutButton buttonStyle={style} />
<Link to="/cart" style={{ textDecoration: "none" }}>
<Button
variant="contained"
color="primary"
style={{ float: "right" }}
>
View Cart
</Button>
</Link>
</div>
) : (
""
)}
</List>
</Card>
);
};
export default ProductList;
<file_sep>/src/components/products/ProductCard.js
import React, { useState } from "react";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import CardMedia from "@material-ui/core/CardMedia";
import CardActions from "@material-ui/core/CardActions";
import Avatar from "@material-ui/core/Avatar";
import IconButton from "@material-ui/core/IconButton";
import Tooltip from "@material-ui/core/Tooltip";
import AddShoppingCartIcon from "@material-ui/icons/AddShoppingCart";
import VisibilityIcon from "@material-ui/icons/Visibility";
import { Link } from "react-router-dom";
import { makeStyles } from "@material-ui/core/styles";
import { useStateValue } from "../../StateProvider";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
card: {
margin: "20px",
},
media: {
height: 0,
paddingTop: "56.25%", // 16:9
},
expand: {
transform: "rotate(0deg)",
marginLeft: "auto",
transition: theme.transitions.create("transform", {
duration: theme.transitions.duration.shortest,
}),
},
expandOpen: {
transform: "rotate(180deg)",
},
avatar: {
fontSize: "15px",
},
headerTitle: {
fontWeight: 700,
fontSize: "1rem",
},
price: {
color: "#fff",
backgroundColor: "#4caf50",
padding: "8px",
borderRadius: "7px",
fontWeight: 600,
},
}));
const ProductCard = ({ product }) => {
const classes = useStyles();
/* const [quantity, setQuantity] = useState(1); */
const [{ basket }, dispatch] = useStateValue();
// console.log(basket);
const addToBasket = (e) => {
let items = e.currentTarget.value;
let cartProduct = items.split(",").map(String);
/* if (basket?.length > 0) {
basket.filter((bask) => {
if (bask.id.indexOf(cartProduct[0])) {
setQuantity(quantity + 1);
}
});
} */
dispatch({
type: "ADD_TO_BASKET",
item: {
id: cartProduct[0],
name: cartProduct[1],
category: cartProduct[2],
price: cartProduct[3],
tag: cartProduct[4],
image: cartProduct[5],
feed: cartProduct[6],
quantity: 1,
},
});
};
return (
<Card className={classes.card}>
<Link
to={{
pathname: `/${product.category}/${product.name}`,
state: {
params: {
id: product.id,
name: product.name,
category: product.category,
price: product.price,
tag: product.tag,
feed: product.feed,
image: product.image,
},
},
}}
style={{ textDecoration: "none", color: "#255d28" }}
>
<CardHeader
avatar={
<Avatar
aria-label="recipe"
className={classes.avatar}
style={{
backgroundColor: `${product.tag === "Hot" ? "red" : "#255d28"}`,
}}
>
{product.tag}
</Avatar>
}
title={product.name}
classes={{
title: classes.headerTitle,
}}
subheader={product.category}
/>
<CardMedia className={classes.media} image={product.image} />
</Link>
<CardActions disableSpacing>
<span className={classes.price}> ₦{product.price}</span>
<Tooltip title="Add to cart">
<IconButton
aria-label="add to cart"
onClick={addToBasket}
value={[
product.id,
product.name,
product.category,
product.price,
product.tag,
product.image,
product.feed,
]}
>
<AddShoppingCartIcon />
</IconButton>
</Tooltip>
{/* <Tooltip title="view product">
<Link
to={{
pathname: `/${product.category}/${product.name}`,
state: {
params: {
id: product.id,
name: product.name,
category: product.category,
price: product.price,
tag: product.tag,
feed: product.feed,
image: product.image,
},
},
}}
style={{ textDecoration: "none", color: "#255d28" }}
>
<IconButton aria-label="view product">
<VisibilityIcon />
</IconButton>
</Link>
</Tooltip> */}
</CardActions>
</Card>
);
};
export default ProductCard;
<file_sep>/src/components/products/ProductPage.js
import React from "react";
import { Grid } from "@material-ui/core";
import { useLocation } from "react-router-dom";
import Button from "@material-ui/core/Button";
import { useStateValue } from "../../StateProvider";
import AddShoppingCartIcon from "@material-ui/icons/AddShoppingCart";
import "./Product.css";
import RelatedProduct from "./RelatedProduct";
const ProductPage = () => {
let data = useLocation();
//console.log(data.state.params);
let product = data.state.params;
// console.log(product);
const [{ basket }, dispatch] = useStateValue();
const addToBasket = () => {
dispatch({
type: "ADD_TO_BASKET",
item: {
id: product.id,
name: product.name,
category: product.category,
price: product.price,
tag: product.tag,
image: product.image,
feed: product.feed,
quantity: 1,
},
});
// console.log(dispatch);
};
return (
<>
<Grid container>
<Grid item xs={12} sm={12} className="ProductPage">
<img
src="https://copperalliance.eu/uploads/2018/07/salad-bar-header-1400x260.jpg"
alt="product page ad"
className="ProductPage_banner"
/>
</Grid>
<Grid container>
<Grid item xs={12} sm={12}>
<h1
style={{
textAlign: "center",
color: "#255d28",
fontFamily: "algerian",
fontWeight: "900px",
fontSize: "3rem",
}}
>
{`${product.name} (${product.category})`}
</h1>
</Grid>
<Grid item xs={12} sm={6}>
<img src={product.image} className="ProductPage_image" />
</Grid>
<Grid item xs={12} sm={6}>
<div className="ProductPage_feed">
<h2>₦{product.price}</h2>
{product.feed}
<div>
<Button
variant="contained"
color="primary"
onClick={addToBasket}
startIcon={<AddShoppingCartIcon />}
style={{ marginTop: "20px" }}
>
Add to Cart
</Button>
</div>
</div>
</Grid>
</Grid>
<Grid item xs={12} sm={12}>
<div
style={{
marginLeft: "100px",
marginRight: "100px",
paddingTop: "30px",
}}
>
<hr />
<h2>You may also like this</h2>
</div>
<RelatedProduct product={product} />
</Grid>
</Grid>
</>
);
};
export default ProductPage;
<file_sep>/src/components/products/Product.js
import React from "react";
import { Grid } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import ProductCard from "./ProductCard";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
card: {
margin: "20px",
},
media: {
height: 0,
paddingTop: "56.25%", // 16:9
},
expand: {
transform: "rotate(0deg)",
marginLeft: "auto",
transition: theme.transitions.create("transform", {
duration: theme.transitions.duration.shortest,
}),
},
expandOpen: {
transform: "rotate(180deg)",
},
avatar: {
fontSize: "15px",
},
headerTitle: {
fontWeight: 700,
fontSize: "1rem",
},
price: {
color: "#fff",
backgroundColor: "#4caf50",
padding: "8px",
borderRadius: "7px",
fontWeight: 600,
},
}));
const Product = ({ products }) => {
const classes = useStyles();
return (
<div className={classes.root}>
<Grid container style={{ padding: "0px, 80px, 80px, 0px" }}>
<Grid item xs={12} sm={12}>
<h1
style={{
textAlign: "center",
color: "#255d28",
fontFamily: "algerian",
fontWeight: "900px",
fontSize: "3rem",
}}
>
GREEN SHOPPING
</h1>
</Grid>
{products.map((product) => (
<Grid item xs={6} sm={3} key={product.id}>
<ProductCard product={product} />
</Grid>
))}
</Grid>
</div>
);
};
export default Product;
<file_sep>/src/components/products/RelatedProduct.js
import React, { useState, useEffect } from "react";
import { Grid } from "@material-ui/core";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import JSON from "../../db.json";
import ProductCard from "./ProductCard";
const RelatedProduct = ({ product }) => {
let settings_3 = {
dots: false,
autoplay: true,
infinite: true,
autoplaySpeed: 2000,
speed: 500,
slidesToShow: 6,
slidesToScroll: 1,
responsive: [
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
initialSlide: 2,
},
},
],
};
const [shop, setShop] = useState(JSON);
const [category, setCategory] = useState([]);
const related = () => {
let relatedCategory = shop.filter((cat) => {
// console.log(cat.category);
if (cat.id !== product.id) {
return cat.category.indexOf(product.category) > -1;
}
});
setCategory(relatedCategory);
};
useEffect(() => {
related();
}, []);
return (
<Slider {...settings_3}>
{category.map((cat) => (
<Grid item xs={12} sm={12} key={cat.id}>
<ProductCard product={cat} />
</Grid>
))}
</Slider>
);
};
export default RelatedProduct;
<file_sep>/src/components/slider/Slider.js
import React from "react";
import { Fade } from "react-slideshow-image";
import "react-slideshow-image/dist/styles.css";
import "./Slider.css";
const fadeImages = [
"https://cdn11.bigcommerce.com/s-45hj43/images/stencil/1280x1280/products/654/3020/FB_81__83777.1424787901.jpg?c=2",
"https://images.pexels.com/photos/145685/pexels-photo-145685.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260",
"https://static.onecms.io/wp-content/uploads/sites/37/2020/04/17/tango-oakleaf-lettuce-c6f6417e.jpg",
];
const Slider = () => {
return (
<div className="slide-container">
<Fade>
<div className="each-fade">
<div className="image-container">
<img src={fadeImages[0]} className="slider-image" />
</div>
</div>
<div className="each-fade">
<div className="image-container">
<img src={fadeImages[1]} className="slider-image" />
</div>
</div>
<div className="each-fade">
<div className="image-container">
<img src={fadeImages[2]} className="slider-image" />
</div>
</div>
</Fade>
</div>
);
};
export default Slider;
<file_sep>/src/Reducer.js
export const initialState = {
basket: [],
};
export const getBasketTotal = (basket) =>
basket?.reduce(
(amount, item) => parseInt(item.price) * item.quantity + amount,
0
);
const reducer = (state, action) => {
switch (action.type) {
case "ADD_TO_BASKET":
var theBasket = [...state.basket];
const i = state.basket.findIndex((item) => item.id === action.item.id);
// console.log(state.basket);
if (i >= 0) {
theBasket[i].quantity = theBasket[i].quantity + 1;
} else {
theBasket.push(action.item);
}
return { ...state, basket: theBasket };
case "UPDATE_BASKET":
console.log(action.item);
var oldBasket = [...state.basket];
const ind = state.basket.findIndex(
(oldItem) => oldItem.id === action.item.id
);
// console.log(state.basket);
if (ind >= 0) {
oldBasket[ind].quantity = action.item.quantity;
} else {
console.log("this id is missingv");
}
return { ...state, basket: oldBasket };
case "EMPTY_BASKET":
return {
...state,
basket: [],
};
case "REMOVE_FROM_BASKET":
let newBasket = [...state.basket];
// console.log(newBasket);
const index = state.basket.findIndex(
(basketItem) => basketItem.id === action.id
);
if (index >= 0) {
newBasket.splice(index, 1);
} else {
// console.log(newBasket);
console.warn(`can't remove id = ${action.id} cos it does not exist`);
}
return { ...state, basket: newBasket };
}
};
export default reducer;
<file_sep>/src/components/checkout/CheckOut.js
import React from "react";
import CheckOutButton from "./CheckOutButton";
import { usePaystackPayment } from "react-paystack";
const onSuccess = (reference) => {
// Implementation for whatever you want to do with reference and after success call.
console.log(reference);
};
// you can call this function anything
const onClose = () => {
// implementation for whatever you want to do when the Paystack dialog closed.
console.log("closed");
};
const CheckOut = () => {
const config = {
reference: new Date().getTime(),
email: "<EMAIL>",
amount: 20000,
publicKey: "pk_test_0771d7e4094956f3747fad03b45bbc61875d5d59",
};
const initializePayment = usePaystackPayment(config);
return (
<CheckOutButton
onClick={() => {
initializePayment(onSuccess, onClose);
}}
/>
);
};
export default CheckOut;
|
51514aa848e28167dba10b4c0bd572603279eb2f
|
[
"JavaScript"
] | 8
|
JavaScript
|
ibraphem/greenshop
|
fa916a2682874d930a87e63a3e0f335434a57bd5
|
4c8f1b7031708228dd8b2a006676e72ee6037dcd
|
refs/heads/master
|
<repo_name>ReganChetty/Tut-1-FizzBuzzWoof<file_sep>/main.cpp
//<NAME> 214 501 879
#include <iostream>
using namespace std;
int main(){
int i = 1;
while (i <= 50)
{
if (i % 3 != 0 && i % 5 != 0 && i % 7 != 0){
cout << i << endl;
}
else if (i % 3 == 0 && i % 5 == 0 && i & 7 == 0){
cout << "FizzBuzzWoof" << endl;
}
else if (i % 3 == 0 && i % 5 == 0){
cout << "FizzBuzz" << endl;
}
else if (i % 3 == 0 && i % 7 == 0){
cout << "FizzWoof" << endl;
}
else if (i % 5 == 0 && i % 7 == 0){
cout << "BuzzWoof" << endl;
}
else if (i % 5 == 0){
cout << "Fizz" << endl;
}
else if (i % 3 == 0){
cout << "Buzz" << endl;
}
else if (i % 7 == 0){
cout << "Woof" << endl;
}
i++;
}
}
|
18a52de5bcfe7904be5b60d253b85cbcf8883e70
|
[
"C++"
] | 1
|
C++
|
ReganChetty/Tut-1-FizzBuzzWoof
|
465d787de94046e04dbdc83efce6bd09c201986e
|
596a198a19b4cf31a69d0e08c9e669236d239355
|
refs/heads/master
|
<file_sep># ember-cli-updated-google-tag-analytics
Plugin for ember-cli that injects Google Analytics tracking code into HTML content.
## Installation
**This plugin requires ember-cli version >= 0.0.47**
To install simply run:
```
npm install --save-dev ember-cli-updated-google-tag-analytics
```
## Warning: Content Security Policy
This plugin is intended to add Google Analytics tracking as an inline script. The [ember-cli-content-security-policy](https://github.com/rwjblue/ember-cli-content-security-policy) addon that is included with ember-cli will prevent the execution of inline scripts.
A future version of this plugin is planned to add the tracking code as an additional JS file (much like [ember-cli-inject-live-reload](https://github.com/rwjblue/ember-cli-inject-live-reload)), but until then this plugin will not function out of the box with CSP installed.
## Usage
Once configured, the Google Analytics tracking code will be injected into your index.html file. All you have to do is setup your Google tagmanager Enviroment: https://tagmanager.google.com/
## Configuration
This plugin uses the Ember CLI project's configuration as defined in `config/environment.js`.
The tracking code will appear only if `ENV.googleAnalytics.webPropertyId` and `ENV.googleAnalytics.tagPropertyId` is defined. For instance, to enable the tracking code in only the production environment:
```javascript
if (environment === 'production') {
googleAnalytics: {
webPropertyId: 'UA-xxxxxxxx-x',
tagPropertyId: 'GTM-xxxxxxx',
}
}
```
### Configuration Parameters
**gtag.js and analytics.js**
* `webPropertyId` (Default: `null`): the Web Property ID for the Google Web Property you wish to track.
* `tagPropertyId` (Default: `null`): The Google Tracker for Google Tag Managment.
## Running Tests
* `git clone <EMAIL>:pgrippi/ember-cli-google-analytics.git`
* `npm install`
* `ember test`
* `ember test --server`
## Building
* `ember build`
For more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).
<file_sep>'use strict';
let merge = require('lodash-node/compat/objects/merge');
let googleAnalyticsConfigDefaults = {
globalVariable: 'ga',
tracker: 'ga.js',
webPropertyId: null,
accountPropertyId: null,
tagPropertyId: null,
cookieDomain: null,
cookieName: null,
cookieExpires: null,
displayFeatures: false
};
function gaTrackingCode(config) {
let scriptArray;
scriptArray = [
"<script async src='https://www.googletagmanager.com/gtag/js?id=" + config.webPropertyId + "''>",
"</script>",
"<script>",
"window.dataLayer = window.dataLayer || [];",
"function gtag(){dataLayer.push(arguments);}",
"gtag('js', new Date());",
"gtag('config', '" + config.webPropertyId + "');",
"</script>",
"<script>",
"(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':",
"new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],",
"j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=",
"'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);",
"})(window,document,'script','dataLayer','" + config.tagPropertyId + "');",
"</script>"
];
return scriptArray;
}
function gaTrackingBodyCode(config) {
let scriptArray;
scriptArray = [
"<noscript>",
"<iframe src='https://www.googletagmanager.com/ns.html?id=" + config.tagPropertyId + "' height='0' width='0' style='display:none;visibility:hidden'>",
"</iframe>",
"</noscript>"
];
return scriptArray;
}
module.exports = {
name: 'ember-cli-updated-google-tag-analytics',
contentFor: function(type, config) {
let googleAnalyticsConfig = merge({}, googleAnalyticsConfigDefaults, config.googleAnalytics || {});
if (type === 'head' && googleAnalyticsConfig.webPropertyId != null) {
let content;
content = gaTrackingCode(googleAnalyticsConfig);
return content.join("\n");
}
if (type === 'body' && googleAnalyticsConfig.webPropertyId != null) {
let content;
content = gaTrackingBodyCode(googleAnalyticsConfig);
return content.join("\n");
}
return '';
}
};
|
9bb1d913d57875b6b81988acc309dc14a381d0b5
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
robotjonez/ember-cli-updated-google-tag-analytics
|
d328d6f9bd0d57c0c7a8610b1d3f0569ccf4fd84
|
a1bcb50da760f6e1951687d5f51cb5e63fe344df
|
refs/heads/master
|
<file_sep>var upload_button = document.getElementById('upload-btn');
var upload_control = document.getElementById('upload');
var image_div = document.querySelector('div.image');
var canvas = document.querySelector('canvas#container');
var canvas_preview = document.querySelector('canvas#preview');
var context = canvas.getContext('2d');
var context_preview = canvas_preview.getContext('2d');
var image = document.querySelector('img#image');
var slider = document.querySelector('input#range');
var textarea = document.querySelector('textarea');
var SWITCH = false;
var CANVAS_WIDTH = 300;
var CANVAS_HEIGHT = 300;
var X = 150;
var Y = 150;
var LEFT = 0;
var TOP = 0;
canvas.width = 300;
canvas.height = 300;
var ORI_RADIUS = 40;
var RADIUS = ORI_RADIUS * 1;
var DISPLAY_WIDTH = 0;
var DISPLAY_HEIGHT = 0;
if (window.window.innerWidth <= 400) {
CANVAS_HEIGHT = 256;
CANVAS_WIDTH = 256;
X = CANVAS_WIDTH / 2;
Y = CANVAS_HEIGHT / 2;
}
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
var DrawContext = function () {
context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
context.drawImage(image, LEFT, TOP, DISPLAY_WIDTH, DISPLAY_HEIGHT);
DisplayClip();
context.fillStyle = 'rgba(0,0,0,.5)';
// context.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
context.beginPath();
context.arc(X, Y, RADIUS, 0, 2 * Math.PI);
context.fill();
};
var DisplayClip = function () {
var imagedata = context.getImageData(X - RADIUS, Y - RADIUS, 2 * RADIUS, 2 * RADIUS);
var tempimage = document.createElement('img');
var tempcanvas = document.createElement('canvas');
tempcanvas.width = 2 * RADIUS;
tempcanvas.height = 2 * RADIUS;
document.body.appendChild(tempcanvas);
document.body.appendChild(tempimage);
var tempcontext = tempcanvas.getContext('2d');
tempcontext.putImageData(imagedata, 0, 0);
var imageuri = tempcanvas.toDataURL();
tempimage.width = 2 * ORI_RADIUS;
tempimage.height = 2 * ORI_RADIUS;
tempimage.src = imageuri;
tempimage.style.opacity = '0';
tempcanvas.remove();
setTimeout(function () {
context_preview.clearRect(0, 0, 2 * ORI_RADIUS, 2 * ORI_RADIUS);
context_preview.drawImage(tempimage, 0, 0, 2 * ORI_RADIUS, 2 * ORI_RADIUS);
tempimage.remove();
}, 50);
};
var UpdateProperties = function () {
var img_width = image.width;
var img_height = image.height;
var ratio = img_height / img_width;
if (img_width >= img_height) {
DISPLAY_WIDTH = CANVAS_WIDTH;
DISPLAY_HEIGHT = DISPLAY_WIDTH * ratio;
}
else {
DISPLAY_HEIGHT = CANVAS_HEIGHT;
DISPLAY_WIDTH = DISPLAY_HEIGHT / ratio;
}
LEFT = (CANVAS_WIDTH - DISPLAY_WIDTH) / 2;
TOP = (CANVAS_HEIGHT - DISPLAY_HEIGHT) / 2;
};
var DisplayDataUrl = function () {
setTimeout(function () {
var data = canvas_preview.toDataURL();
textarea.value = data;
}, 100);
};
image.style.opacity = '0';
// setTimeout(() => {
// image.style.display = 'block';
// UpdateProperties();
// DrawContext();
// image.style.display = 'none';
// }, 16);
var slider_interval;
slider.onmousedown = function (ev) {
slider_interval = setInterval(function () {
var value = parseInt(slider.value) + 50;
RADIUS = value / 100 * ORI_RADIUS;
DrawContext();
}, 50);
};
slider.onmouseup = function (ev) {
if (slider_interval !== void 0)
clearInterval(slider_interval);
};
slider.onchange = function (ev) {
var value = parseInt(slider.value) + 50;
RADIUS = value / 100 * ORI_RADIUS;
DrawContext();
};
upload_button.addEventListener('click', function (ev) { upload_control.click(); });
upload_control.addEventListener('change', function (ev) {
var files = upload_control.files;
if (files.length > 0) {
image.style.display = 'block';
image.style.opacity = '0';
var reader_1 = new FileReader();
reader_1.readAsDataURL(files.item(0));
reader_1.onloadend = function (ev) {
image.src = reader_1.result;
setTimeout(function () {
image.style.display = 'block';
UpdateProperties();
DrawContext();
image.style.display = 'none';
SWITCH = true;
}, 200);
};
// reader.onprogress = (ev) => { console.log(ev.loaded / ev.total); };
}
});
var DRAGGING = false;
var TOUCHSTART_ID = void 0;
canvas.onmousedown = function (ev) {
if (!SWITCH)
return false;
DRAGGING = true;
ev.stopPropagation();
// ev.preventDefault();
X = Math.max(ev.offsetX, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(ev.offsetY, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(function () { DrawContext(); }, 16);
};
canvas.ontouchstart = function (ev) {
if (!SWITCH)
return false;
DRAGGING = true;
TOUCHSTART_ID = ev.touches[0].identifier;
ev.stopPropagation();
// ev.preventDefault();
X = Math.max(ev.touches[0].clientX - canvas.getBoundingClientRect().left, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(ev.touches[0].clientY - canvas.getBoundingClientRect().top, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(function () { DrawContext(); }, 16);
};
canvas.onmouseup = function (ev) {
if (!SWITCH)
return false;
DRAGGING = false;
ev.stopPropagation();
DisplayDataUrl();
};
canvas.ontouchend = function (ev) {
if (!SWITCH)
return false;
DRAGGING = false;
TOUCHSTART_ID = void 0;
ev.stopPropagation();
DisplayDataUrl();
};
canvas.onmousemove = function (ev) {
if (!SWITCH)
return false;
ev.stopPropagation();
ev.preventDefault();
if (DRAGGING || ev.buttons === 1) {
X = Math.max(ev.offsetX, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(ev.offsetY, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(function () { DrawContext(); }, 16);
}
};
canvas.ontouchmove = function (ev) {
if (!SWITCH)
return false;
ev.stopPropagation();
ev.preventDefault();
if (ev.touches.length === 0)
return;
var touch;
for (var i = 0; i < ev.touches.length; i++) {
if (ev.touches[i].identifier === TOUCHSTART_ID) {
touch = ev.touches[i];
break;
}
}
if (DRAGGING || touch !== void 0) {
X = Math.max(touch.clientX - canvas.getBoundingClientRect().left, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(touch.clientY - canvas.getBoundingClientRect().top, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(function () { DrawContext(); }, 16);
}
};
<file_sep>let upload_button = document.getElementById('upload-btn') as HTMLButtonElement;
let upload_control = document.getElementById('upload') as HTMLInputElement;
let image_div = document.querySelector('div.image') as HTMLDivElement;
let canvas = document.querySelector('canvas#container') as HTMLCanvasElement;
let canvas_preview =
document.querySelector('canvas#preview') as HTMLCanvasElement;
let context = canvas.getContext('2d');
let context_preview = canvas_preview.getContext('2d');
let image = document.querySelector('img#image') as HTMLImageElement;
let slider = document.querySelector('input#range') as HTMLInputElement;
let textarea = document.querySelector('textarea') as HTMLTextAreaElement;
let SWITCH = false;
let CANVAS_WIDTH = 300;
let CANVAS_HEIGHT = 300;
let X = 150;
let Y = 150;
let LEFT = 0;
let TOP = 0;
canvas.width = 300;
canvas.height = 300;
let ORI_RADIUS = 40;
let RADIUS = ORI_RADIUS * 1;
let DISPLAY_WIDTH = 0;
let DISPLAY_HEIGHT = 0;
if (window.window.innerWidth <= 400) {
CANVAS_HEIGHT = 256;
CANVAS_WIDTH = 256;
X = CANVAS_WIDTH / 2;
Y = CANVAS_HEIGHT / 2;
}
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
let DrawContext = () => {
context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
context.drawImage(image, LEFT, TOP, DISPLAY_WIDTH, DISPLAY_HEIGHT);
DisplayClip();
context.fillStyle = 'rgba(0,0,0,.5)';
// context.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
context.beginPath();
context.arc(X, Y, RADIUS, 0, 2 * Math.PI);
context.fill();
};
let DisplayClip = () => {
let imagedata =
context.getImageData(X - RADIUS, Y - RADIUS, 2 * RADIUS, 2 * RADIUS);
let tempimage = document.createElement('img');
let tempcanvas = document.createElement('canvas');
tempcanvas.width = 2 * RADIUS;
tempcanvas.height = 2 * RADIUS;
document.body.appendChild(tempcanvas);
document.body.appendChild(tempimage);
let tempcontext = tempcanvas.getContext('2d');
tempcontext.putImageData(imagedata, 0, 0);
let imageuri = tempcanvas.toDataURL();
tempimage.width = 2 * ORI_RADIUS;
tempimage.height = 2 * ORI_RADIUS;
tempimage.src = imageuri;
tempimage.style.opacity = '0';
tempcanvas.remove();
setTimeout(() => {
context_preview.clearRect(0, 0, 2 * ORI_RADIUS, 2 * ORI_RADIUS);
context_preview.drawImage(tempimage, 0, 0, 2 * ORI_RADIUS, 2 * ORI_RADIUS);
tempimage.remove();
}, 50);
};
let UpdateProperties = () => {
let img_width = image.width;
let img_height = image.height;
let ratio = img_height / img_width;
if (img_width >= img_height) {
DISPLAY_WIDTH = CANVAS_WIDTH;
DISPLAY_HEIGHT = DISPLAY_WIDTH * ratio;
} else {
DISPLAY_HEIGHT = CANVAS_HEIGHT;
DISPLAY_WIDTH = DISPLAY_HEIGHT / ratio;
}
LEFT = (CANVAS_WIDTH - DISPLAY_WIDTH) / 2;
TOP = (CANVAS_HEIGHT - DISPLAY_HEIGHT) / 2;
};
let DisplayDataUrl = () => {
setTimeout(() => {
let data = canvas_preview.toDataURL();
textarea.value = data;
}, 100);
};
image.style.opacity = '0';
// setTimeout(() => {
// image.style.display = 'block';
// UpdateProperties();
// DrawContext();
// image.style.display = 'none';
// }, 16);
let slider_interval: NodeJS.Timer;
slider.onmousedown = (ev) => {
slider_interval = setInterval(() => {
let value = parseInt(slider.value) + 50;
RADIUS = value / 100 * ORI_RADIUS;
DrawContext();
}, 50);
};
slider.onmouseup = (ev) => {
if (slider_interval !== void 0) clearInterval(slider_interval);
};
slider.onchange = (ev) => {
let value = parseInt(slider.value) + 50;
RADIUS = value / 100 * ORI_RADIUS;
DrawContext();
};
upload_button.addEventListener('click', (ev) => { upload_control.click(); });
upload_control.addEventListener('change', (ev) => {
let files = upload_control.files;
if (files.length > 0) {
image.style.display = 'block';
image.style.opacity = '0';
let reader = new FileReader();
reader.readAsDataURL(files.item(0));
reader.onloadend = (ev) => {
image.src = reader.result as string;
setTimeout(() => {
image.style.display = 'block';
UpdateProperties();
DrawContext();
image.style.display = 'none';
SWITCH = true;
}, 200);
};
// reader.onprogress = (ev) => { console.log(ev.loaded / ev.total); };
}
});
let DRAGGING = false;
let TOUCHSTART_ID = void 0;
canvas.onmousedown = (ev) => {
if (!SWITCH) return false;
DRAGGING = true;
ev.stopPropagation();
// ev.preventDefault();
X = Math.max(ev.offsetX, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(ev.offsetY, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(() => { DrawContext(); }, 16);
};
canvas.ontouchstart = (ev) => {
if (!SWITCH) return false;
DRAGGING = true;
TOUCHSTART_ID = ev.touches[0].identifier;
ev.stopPropagation();
// ev.preventDefault();
X = Math.max(
ev.touches[0].clientX - canvas.getBoundingClientRect().left,
LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(
ev.touches[0].clientY - canvas.getBoundingClientRect().top, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(() => { DrawContext(); }, 16);
};
canvas.onmouseup = (ev) => {
if (!SWITCH) return false;
DRAGGING = false;
ev.stopPropagation();
DisplayDataUrl();
};
canvas.ontouchend = (ev) => {
if (!SWITCH) return false;
DRAGGING = false;
TOUCHSTART_ID = void 0;
ev.stopPropagation();
DisplayDataUrl();
};
canvas.onmousemove = (ev) => {
if (!SWITCH) return false;
ev.stopPropagation();
ev.preventDefault();
if (DRAGGING || ev.buttons === 1) {
X = Math.max(ev.offsetX, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(ev.offsetY, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(() => { DrawContext(); }, 16);
}
};
canvas.ontouchmove = (ev) => {
if (!SWITCH) return false;
ev.stopPropagation();
ev.preventDefault();
if (ev.touches.length === 0) return;
let touch: Touch;
for (let i = 0; i < ev.touches.length; i++) {
if (ev.touches[i].identifier === TOUCHSTART_ID) {
touch = ev.touches[i];
break;
}
}
if (DRAGGING || touch !== void 0) {
X = Math.max(
touch.clientX - canvas.getBoundingClientRect().left, LEFT + RADIUS);
X = Math.min(X, (CANVAS_WIDTH + DISPLAY_WIDTH) / 2 - RADIUS);
Y = Math.max(
touch.clientY - canvas.getBoundingClientRect().top, TOP + RADIUS);
Y = Math.min(Y, (CANVAS_HEIGHT + DISPLAY_HEIGHT) / 2 - RADIUS);
setTimeout(() => { DrawContext(); }, 16);
}
};<file_sep># CanvasAvatar
A simple page that let you get the dataurl from your local image.
Click `upload` and choose an image, then drag and move the circle or the slider to check the preview. Release your finger or mouse to get the dataurl displayed in the textarea below.
Currently, 50% to 150% scale of preview is supported.
An online [demo](https://devchache.github.io/CanvasAvatar/) is avaliable on both mobile and desktop browsers.
Currently, I've tested the performance on Chrome 60 at all platforms.
|
909660ee77d558be574afba203d753aaab701d0f
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 3
|
JavaScript
|
DevChache/CanvasAvatar
|
36bba2de2b94d713953f1f917ac678425faf7e89
|
be49a8a08e6f5b2dd4daacdf7c0d2d1a166d831d
|
refs/heads/master
|
<file_sep>import {createApp} from 'vue'
import HighchartsVue from 'highcharts-vue'
import App from './App.vue'
import router from './router'
import store from "./vuex";
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
import common from "./common";
const app = createApp(App)
app.config.globalProperties.$app = app
common(app, store)
app.use(router).use(store).use(HighchartsVue).use(ElementPlus).mount('#app')
<file_sep>import {createStore} from 'vuex'
// Create a new store instance.
const store = createStore({
state() {
return {
count: 1,
rules: []
}
},
mutations: {
increment(state) {
state.count++
},
updateRules(state, data) {
state.rules = data
}
}
})
export default store<file_sep>import env from './env.js'
import axios from 'axios'
import router from './router'
import {ElMessage} from 'element-plus'
const common = (app, store) => {
app.config.globalProperties.test = function () {
console.log('test')
}
app.config.globalProperties.store = function () {
console.log(store.state.count)
}
// app.config.globalProperties.http
//公共函数
//-----------------------------------------------------------------------------------------------
/**
* 判断运行环境
*/
app.config.globalProperties.isDev = function () {
if (process.env.NODE_ENV == 'development') return true;
return false;
}
/**
* 获取api域名
*/
app.config.globalProperties.getHost = function () {
// return process.env.HOST;
// if(app.config.globalProperties.isDev()) return app.config.globalProperties.getEnv('devHost')
// return app.config.globalProperties.getEnv('proHost');
return app.config.globalProperties.getEnv('host');
// if (app.config.globalProperties.isDev()) return 'http://lv.com/api';
}
/**
* 公共请求方法
* @param {Object} params
*/
app.config.globalProperties.httpCommon = function (params) {
params.baseURL = app.config.globalProperties.getHost();
//是否显示加载遮罩层
if (params.loading === true) {
var loadForRequest = this.$loading({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
}
//废弃
// params.headers = {
// 'token': app.config.globalProperties.localGet('token'),
// // 'rule':Vue.$route.path
// };
return new Promise((resolve, reject) => {
axios(params).then((res) => {
if (params.loading === true) loadForRequest.close();
if (res.data.code >= 10 && res.data.code <= 50) {
reject(res.data);
return router.push('/login');
}
if (res.data.code >= 51 && res.data.code <= 100) {
this.$notify({
title: '错误',
message: res.data.msg,
position: 'bottom-right',
type: 'error'
});
reject(res.data);
return false;
// return this.$message.error(res.data.msg);
}
// //是否显示错误信息提示,一般返回code为1是成功,其他是失败
if (!(params.disableError === true)) {
if (res.data.code !== 1) {
// resolve(res.data);
this.$notify({
title: '错误',
message: res.data.msg,
position: 'bottom-right',
type: 'error'
});
reject(res)
return
}
}
resolve(res.data);
}).catch((err) => {
reject(err)
});
});
}
/**
* get请求,数据用params
* @param {Object} params
*/
app.config.globalProperties.httpGet = function (params) {
params.method = 'get';
return new Promise((resolve, reject) => {
app.config.globalProperties.httpCommon(params).then((res) => {
resolve(res);
}).catch((res) => {
reject(res);
});
});
}
/**
* post请求,数据用data
* @param {Object} params
*/
app.config.globalProperties.httpPost = function (params) {
params.method = 'post';
return new Promise((resolve, reject) => {
app.config.globalProperties.httpCommon(params).then((res) => {
resolve(res);
}).catch((res) => {
reject(res);
});
});
}
/**
* 本地储存
*/
app.config.globalProperties.localSet = function (key, value, prefix = 'super_admin_') {
localStorage.setItem(prefix + key, value);
}
/**
* 本地储存获取
*/
app.config.globalProperties.localGet = function (key, defaultValue = '', prefix = 'super_admin_') {
let re = localStorage.getItem(prefix + key);
if (!re) return defaultValue;
return re;
}
/**
* 删除
*/
app.config.globalProperties.localRemove = function (key, prefix = 'super_admin_') {
localStorage.removeItem(prefix + key);
}
/**
* 克隆对象
* @param {Object} object
*/
app.config.globalProperties.cloneObj = function (object) {
return JSON.parse(JSON.stringify(object))
}
/**
* item赋值
* @param {Object} defaultItem
* @param {Object} item
*/
app.config.globalProperties.setItem = function (defaultItem, item) {
for (let key in defaultItem) {
if (!(typeof (item[key]) == 'undefined')) {
defaultItem[key] = item[key];
}
}
}
app.config.globalProperties.messageCommon = function (title, message, type) {
return new Promise((success, fail) => {
this.$confirm(message, title, {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: type
}).then(() => {
success();
}).catch(() => {
// console.log('fail');
fail();
});
});
}
app.config.globalProperties.messageSuccess = function (title, message) {
return new Promise((success, fail) => {
app.config.globalProperties.messageCommon(title, message, 'success').then(() => {
success();
}).catch(() => {
fail();
});
});
}
/**
* 搜索跳转
*
* @param context 上下文对象(this)
* @param query 传递参数
* @param rememberQuery 是否保存其他参数
*/
app.config.globalProperties.routerSearch = function (context, query, rememberQuery = true) {
let path = context.$route.path;
let pathTemp = context.cloneObj(path);
//
let temp = context.$route.query;
let oldQuery = app.config.globalProperties.cloneObj(temp);
let str = '?';
for (let key in query) {
if (key === 'random') continue;
let item = query[key];
// oldQuery[key] = item;
str += key + '=' + item + '&';
}
if (rememberQuery) {
/**
* 记住原有参数
* @param {Object} let key in temp
*/
for (let key in temp) {
if (key === 'random' || key === "p") continue;
if (findIndex(query, key)) continue;
let item = temp[key];
oldQuery[key] = item;
str += key + '=' + item + '&';
}
}
str = str.substr(0, str.length - 1);
str = str + '&random=' + Math.random();
console.log(path + str)
context.$mainContext.$router.push(pathTemp + str).then(() => {
context.$mainContext.reload()
})
}
function findIndex(array, index) {
for (let key in array) {
if (key == index) return true;
}
return false;
}
/**
* 弹窗+ajax请求
*
* @param title 弹窗标题
* @param message 弹窗内容
* @param url 请求地址
* @param data 请求数据
*
*/
app.config.globalProperties.msgBoxAjax = function (title, message, url, data = {}, customClass = 'custom-class') {
return new Promise((success, fail) => {
let i = this.$msgbox({
title: title,
customClass: customClass,
message: message,
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
// distinguishCancelAndClose:true
closeOnClickModal: false,
closeOnPressEscape: false,
// closeOnHashChange: false,
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
console.log(instance);
instance.confirmButtonLoading = true;
instance.confirmButtonText = '执行中...';
app.config.globalProperties.httpPost({
url: url,
data: data
}).then((re) => {
// console.log(re);
done();
instance.confirmButtonLoading = false;
i.responseData = re;
if (re.code !== 1) {
ElMessage.error({
message: re.msg,
duration: 5000
});
}
}).catch(() => {
instance.confirmButtonLoading = false;
done();
});
} else {
done();
}
}
}).then((action, instance, done) => {
if (action == 'confirm') {
success(i.responseData);
} else {
}
}).catch(() => {
fail();
});
});
}
/**
* 弹窗+ajax请求+自动显示错误弹窗
*
* @param title 弹窗标题
* @param message 弹窗内容
* @param url 请求地址
* @param data 请求数据
*
*/
app.config.globalProperties.msgBoxAjaxWithMessage = function (title, message, url, data = {}, customClass = 'custom-class') {
return new Promise((success, fail) => {
let i = this.$msgbox({
title: title,
customClass: customClass,
message: message,
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
// distinguishCancelAndClose:true
closeOnClickModal: false,
closeOnPressEscape: false,
// closeOnHashChange: false,
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
console.log(instance);
instance.confirmButtonLoading = true;
instance.confirmButtonText = '执行中...';
this.httpPost({
url: url,
data: data,
showMessage: true
}).then((re) => {
// console.log(re);
done();
instance.confirmButtonLoading = false;
i.responseData = re;
}).catch(() => {
instance.confirmButtonLoading = false;
done();
});
} else {
done();
}
}
}).then((action, instance, done) => {
if (action == 'confirm') {
success(i.responseData);
} else {
}
}).catch(() => {
fail();
});
});
}
app.config.globalProperties.getEnv = function (key) {
if (app.config.globalProperties.isDev()) return env['dev'][key];
return env['pro'][key];
}
/**
* 获取图片域名
*/
app.config.globalProperties.getImagePath = function (path) {
return app.config.globalProperties.getEnv('imgHost') + '/' + path;
}
/**
* 重置对象
* @param {Object} obj
*/
app.config.globalProperties.resetObj = function (obj) {
for (let i in obj) {
switch (typeof obj[i]) {
case 'number':
obj[i] = 0;
break;
case 'string':
obj[i] = '';
break;
case 'object':
// obj[i]=[];
if (obj[i] instanceof Array) {
obj[i] = [];
break;
}
if (obj[i] instanceof Object) {
obj[i] = {};
break;
}
obj[i] = '';
break;
default:
obj[i] = '';
}
}
}
app.config.globalProperties.uploadFile = function (event, params = {}) {
return new Promise((success, fail) => {
let file = event.target.files;
let form = new FormData();
// form.append('file', file);
//一个文件就是一个表单对象
for (let i in file) {
form.append('file' + i, file[i]);
}
//额外参数
for (let i in params) {
form.append(i, params[i]);
}
app.config.globalProperties.httpPost({
url: "/admin/upload/upload",
data: form
}).then((re) => {
if (re.code == 1) {
success(re);
} else {
fail(re);
}
});
});
}
app.config.globalProperties.getObj = function (obj, attr, defaultValue = '') {
try {
return eval('obj' + '.' + attr);
} catch (e) {
return defaultValue;
}
}
app.config.globalProperties.auth = async function (rule) {
while (true) {
if (!(store.state.rules?.length === 0)) {
break
}
await app.config.globalProperties.sleep(200)
}
return new Promise(async (success, fail) => {
console.log(store.state.rules)
if (rule === "") {
success()
return
}
if (store.state.rules === true) {
success()
return
}
for (const argumentsKey in store.state.rules) {
console.log(store.state.rules[argumentsKey])
if (store.state.rules[argumentsKey] === rule) {
success()
return
}
}
fail()
})
}
app.config.globalProperties.sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
}
export default common<file_sep>import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
optimizeDeps: {
include: [],
},
build : {
commonjsOptions : {
ignoreDynamicRequires : false
}
}
})
|
2a03a58372766078beb839180aed16089c52bcdd
|
[
"JavaScript"
] | 4
|
JavaScript
|
tengxiaoyang/superAdminPage20
|
90c066d1b51add0ba491380245884ca537a99b7c
|
eff0b681c6aef19d2e0036baaa7a83d34d8b1517
|
refs/heads/master
|
<file_sep>package fr.iutvalence.info.m3105.stackmachine;
public class StackUnderflowException extends Exception {
public StackUnderflowException(ArrayIndexOutOfBoundsException e) {
// TODO Auto-generated constructor stub
}
}
<file_sep>package fr.iutvalence.info.m3105.stackmachine;
public class WordSize {
}
|
dea00d8cf81c1954e58f048731b964b703cce81f
|
[
"Java"
] | 2
|
Java
|
Batlord/StackmachineTP1
|
5bfedafc96da353fc6721bdfda84d7390c57bacf
|
15ed410ce94b89a165568657061965363b5a5889
|
refs/heads/master
|
<file_sep>#-----------------------------------------------------------------------------------
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#-----------------------------------------------------------------------------------
require './lib/graph.rb'
require './lib/search.rb'
graph = AStar::CartesianGraph.new(8) # create an 8x8 Cartesian graph
5.times {|n| graph.disable(5, n) } # add some obstacles to make things interesting
5.times {|n| graph.disable(2, 7-n) }
graph.disable(4,4)
start = graph[0,3]
goal = graph[7,0]
pv = AStar::search(start, goal) # find the "principal variation", or optimal path from start to goal
graph.print(start, goal, pv) # print out the optimal solution
<file_sep>#-----------------------------------------------------------------------------------
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#-----------------------------------------------------------------------------------
module AStar
def self.retrieve_pv(active, from) # Re-trace our steps from the current node
pv = [] # back to the starting node.
until active.parent.nil? do
pv << active
active = active.parent
end
pv.reverse!
end
def self.search(start, goal)
open, closed = {}, {}
active = start
open.store(start, true) # Add the starting node to the open set.
until open.empty? do # Keep searching until we reach the goal or run out of reachable nodes.
active = open.min_by { |node, value| node.f(goal) }.first # try the most promising nodes first.
return retrieve_pv(active, start) if active == goal # Stop searching once the goal is reached.
open.delete(active) # Move the active node from the open set to the closed set.
closed.store(active, true)
next unless active.enabled # if this node is impassible, ignore it and move on to the next child.
active.edges.each do |edge|
child = edge.child
next if closed[child] # ignore child nodes that have already been expanded.
g = active.g + edge.cost # get the cost of the current path to this child node.
# If the child node hasn't been tried or if the current path to the child node is shorter
# than the previously tried path, save the g value in the child node.
if !open[child] || g < child.g
child.parent = active # save a reference to the parent node
child.g = g
child.h(goal)
open.store(child, true) if !open[child]
end
end
end
puts "No path from #{start} to #{goal} was found."
return nil
end
end
<file_sep># A* Search Algorithm
This project implements the [A* search algorithm](http://en.wikipedia.org/wiki/A*_search_algorithm "Wikipedia: A* Search Algorithm") in Ruby for learning purposes.
## Usage
Create a new graph object:
graph = AStar::CartesianGraph.new(8) # create an 8x8 Cartesian graph
Add some impassible terrain to the graph to make things interesting:
5.times {|n| graph.disable(5, n) }
5.times {|n| graph.disable(2, 7-n) }
graph.disable(4,4)
Choose a starting node and a destination node:
start = graph[0,3]
goal = graph[7,0]
Search the graph for an optimal path and print it out:
pv = AStar::search(start, goal) # find the "principal variation", or optimal path from start to goal
graph.print(start, goal, pv) # print out the optimal solution
Example output:
2.1.0 :001 > load 'initialize.rb'
[<N (1,2)>, <N (2,2)>, <N (3,3)>, <N (3,4)>, <N (4,5)>, <N (5,5)>, <N (6,4)>, <N (7,3)>, <N (7,2)>, <N (7,1)>, <N (7,0)>]
|---------------------------------|
| · · ■ · · · · · |
|---------------------------------|
| · · ■ · · · · · |
|---------------------------------|
| · · ■ · ʘ ʘ · · |
|---------------------------------|
| · · ■ ʘ ■ ■ ʘ · |
|---------------------------------|
| Α · ■ ʘ · ■ · ʘ |
|---------------------------------|
| · ʘ ʘ · · ■ · ʘ |
|---------------------------------|
| · · · · · ■ · ʘ |
|---------------------------------|
| · · · · · ■ · Ω |
|---------------------------------|<file_sep>#-----------------------------------------------------------------------------------
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#-----------------------------------------------------------------------------------
module AStar
Edge = Struct.new(:cost, :child)
class CartesianNode
attr_accessor :g, :h, :parent, :edges, :enabled
attr_reader :x, :y, :hash # once initialized, the location of the node is immutable.
def initialize(x,y)
@x, @y = x, y # Stores the Cartesian coordinates for this node.
@g = 0 # Stores distance from the starting node to the current node
@edges = [] # An array of edge structs storing references to any adjacent nodes.
@enabled = true # If set to false, this node is 'impassible' and cannot be traversed.
@hash = [@x, @y].hash # create a hash value used when storing the node as a hash key.
end
def ==(other)
@hash == other.hash
end
def h(goal) # Stores a heuristic estimate of the distance remaining to the goal node.
@h ||= AStar::manhattan_distance(self, goal)
end
def f(goal) # Estimates the value of the current path being taken based on the actual distance
@g + h(goal) # to this node from the start and the estimated distance remaining to the goal.
end
def inspect
"<N (#{@x},#{@y})>"
end
end
class CartesianGraph # Creates an interconnected Cartesian graph of (width)**2 nodes.
def initialize(width) # Each node is linked to all adjacent nodes at initialization.
@width = width
@nodes = Array.new(width) {|y| Array.new(width) {|x| CartesianNode.new(x,y) } }
link_nodes
end
def each # iterate over all nodes in the graph.
@nodes.each_with_index do |row, y|
row.each_with_index do |node, x|
yield(node)
end
end
end
def to_h
@nodes.flatten.inject({}) { |hsh, node| hsh[node] = true; hsh }
end
def [](x,y) # Get a node by its Cartesian coordinates.
@nodes[y][x]
end
def disable(x,y) # Disable the node at the given coordinates.
@nodes[y][x].enabled = false
end
def enable(x,y) # Enable the node at the given coordinates.
@nodes[y][x].enabled = true
end
GRAPHICS = { open: "\u00B7", blocked: "\u25a0", start: "\u0391", goal: "\u03A9", pv: "\u0298" }
def print(start=nil, goal=nil, pv=nil) # Prints out the graph along with the path taken from the
if pv.nil? || pv.empty? # start node to the goal, if given.
pv = {}
else
puts "\n"
p pv # Print out the path taken to the goal
pv = pv.inject({}){|hsh, node| hsh[node] = true; hsh }
end
puts separator = "|--" + "-"*(4*@width-3) + "--|"
@nodes.reverse.each do |row|
line = "| " + row.map do |node|
if !node.enabled
GRAPHICS[:blocked]
elsif node == start
GRAPHICS[:start]
elsif node == goal
GRAPHICS[:goal]
elsif pv[node]
GRAPHICS[:pv]
else
GRAPHICS[:open]
end
end.join(" ") + " |"
puts line, separator
end
end
private
def link_nodes # Iterates over all nodes in the graph, adding a reference to each adjacent node
each do |node| # along with a movement cost representing the distance between the nodes.
(-1..1).each do |y_offset|
(-1..1).each do |x_offset|
y = node.y + y_offset
x = node.x + x_offset
if 0 <= x && x < @width && 0 <= y && y < @width && (x_offset != 0 || y_offset != 0)
other = @nodes[y][x]
node.edges << Edge.new(AStar::distance(node, other), other)
end
end
end
end
end
end
def self.manhattan_distance(from, to) # Returns the movement cost of going directly from one
(from.y-to.y).abs + (from.x-to.x).abs # node to another without allowing diagonal movement.
end
def self.distance(from, to) # Returns the actual straight-line distance between the two nodes.
(((from.y-to.y).abs)**2 + ((from.x-to.x).abs)**2)**(1/2.0)
end
end
|
0fbf81a51a6c8bab04083fe4c92317fdd0fb5ef4
|
[
"Markdown",
"Ruby"
] | 4
|
Ruby
|
stephenjlovell/a_star
|
373834e9b33440e50924f7f076c98b8f4caf65ba
|
f03fd43b12b4a3c5991aa2ac26190593f91c07b0
|
refs/heads/master
|
<file_sep>def ctof(x1):
return (x1*1.8) +32
def ftoc(x1):
return (x1-32) /1.8
#Main
print("Welcome to Pepa's Temperature converter.")
print("1. From Celsius to Farenheit [C to F]")
print("2. From Farenheit to Celsius [F to C]")
choice = int(input("Enter your option: "))
#Asking for a number
x1 = float(input("Now enter the number you want to convert: "))
#Conversion itself
if choice == 1:
c = ctof(x1)
print("{0}C converted is equal to {1}F" .format(x1, c))
raw_input("Press any key to exit")
exit()
elif choice == 2:
f = ftoc(x1)
print("{0}F converted is equal to {1}C" .format(x1, c))
raw_input("Press any key to exit")
exit()
<file_sep># celsius2farenheit
My first python project. Just a celsius to farenheit (and farenheit to celsius) converter.
Trying to learn by practising.
New to python, new to GitHub, new to programming.
#LearnByDoing
|
c344025fffceab149ca627168919916ab4abd9dd
|
[
"Markdown",
"Python"
] | 2
|
Python
|
Nikhilb6/celsius2farenheit
|
3868c57bd1d1eb5b13d642e19bb2a831d12370ec
|
e1435685d0d92b11edb742c078dfefc10b17cb1f
|
refs/heads/main
|
<file_sep>/*
==============================================================================
This file contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
#include "PluginProcessor.h"
//==============================================================================
/**
*/
class HalftimeAudioProcessorEditor : public juce::AudioProcessorEditor,
public juce::TextButton::Listener
{
public:
HalftimeAudioProcessorEditor (HalftimeAudioProcessor&);
~HalftimeAudioProcessorEditor() override;
//==============================================================================
void paint (juce::Graphics&) override;
void resized() override;
void buttonClicked (juce::Button*) override;
private:
juce::TextButton buttonOn;
juce::TextButton buttonOff;
// This reference is provided as a quick way for your editor to
// access the processor object that created it.
HalftimeAudioProcessor& audioProcessor;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HalftimeAudioProcessorEditor)
};
<file_sep>/*
==============================================================================
This file contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
HalftimeAudioProcessorEditor::HalftimeAudioProcessorEditor (HalftimeAudioProcessor& p)
: AudioProcessorEditor (&p), audioProcessor (p),buttonOn("On"),buttonOff("Off")
{
buttonOn.addListener(this);
buttonOff.addListener(this);
addAndMakeVisible(buttonOn);
addAndMakeVisible(buttonOff);
// Make sure that before the constructor has finished, you've set the
// editor's size to whatever you need it to be.
setSize (200, 120);
}
HalftimeAudioProcessorEditor::~HalftimeAudioProcessorEditor()
{
}
//==============================================================================
void HalftimeAudioProcessorEditor::paint (juce::Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));
g.setColour (juce::Colours::white);
g.setFont (15.0f);
g.drawFittedText ("", getLocalBounds(), juce::Justification::centred, 1);
}
void HalftimeAudioProcessorEditor::resized()
{
buttonOn.setBounds(10, 10, getWidth() - 20, 40);
buttonOff.setBounds(10, 70, getWidth() - 20, 40);
}
void HalftimeAudioProcessorEditor::buttonClicked (juce::Button* button)
{
if(button == &buttonOn)
{
audioProcessor.mState = 2;
}
else
{
audioProcessor.mState = 1;
}
}
|
2c93496bd9eaa3b87061e11f39dc0cca8ab24fbd
|
[
"C++"
] | 2
|
C++
|
YoanDev/HalfTimeHome
|
64f2d3a0665b68a89241fbba029b5cad3617ad6f
|
88de741e488af3b0ac43e2df1f4c6ee448c75d85
|
refs/heads/master
|
<file_sep>// SPI oscilloscope
volatile uint8_t scope[4];
volatile uint8_t scope_ch = 1;
void setup(){
pinMode(MISO, OUTPUT);
pinMode(MOSI, INPUT);
pinMode(SCK, INPUT);
pinMode(SS, INPUT);
// SPI slave for debugging via USBTinyISP
SPCR = _BV(SPE) | _BV(SPIE);
}
SIGNAL(SPI_STC_vect) {
// send next channel
SPDR = scope[scope_ch];
scope_ch++;
scope_ch &= 0b11;
}
void loop() {
// update channel data
scope[0] = analogRead(1);
scope[1] = millis();
scope[2] = 42;
scope[3] = 0;
}
<file_sep>import usbtinyisp
import time
import bitstring
tiny = usbtinyisp.usbtiny()
tiny.power_on()
ROT = [0xAA, 0x55, 0x2A, 0x15, 0x0A, 0x05, 0x02, 0x01]
while True:
data = tiny.spi1(0)[0]
if data == 0:
continue
if not data in ROT:
continue
rot = ROT.index(data) # rot is the number of bit positions we are out of sync.
string = bytearray([data])
while data != 0:
data = tiny.spi1(0)[0]
string.append(data)
bits = bitstring.BitArray(bytes=string) << rot
raw = bits.tobytes()
while raw.startswith(bytes([0xAA])):
raw = raw[1:]
while raw.endswith(bytes([0x00])):
raw = raw[:-1]
try:
print(raw.decode('ASCII'), end="")
except UnicodeDecodeError:
print(raw)<file_sep># USBTinyISP debug scope
A simple script to plot values form an AVR chip using the ISP header.

## Usage
Should work with any USBTinyISP compatible programmer and any AVR chip that supports SPI slave on the ISP pins. Requires PyUSB, numpy and matplotlib.
An example Arduino script is provided to set up SPI correctly.
Simply run `python3 debug.py` and you should be good.
## Known issues
The ISP does not have a slave select pin. SS needs to be tied to ground.
If you get bogus data, try resetting the AVR and/or the debug script, the SPI has probably fallen out of sync.
<file_sep>import usb.core
import usb.util
import time
class usbtiny:
def __init__(self):
self.USBTINY_ECHO = 0 #echo test
self.USBTINY_READ = 1 #read port B pins
self.USBTINY_WRITE = 2 #write byte to port B
self.USBTINY_CLR = 3 #clear PORTB bit, value=bit number (0..7)
self.USBTINY_SET = 4 #set PORTB bit, value=bit number (0..7)
self.USBTINY_POWERUP = 5 #apply power and enable buffers, value=sck-period, index=RESET
self.USBTINY_POWERDOWN = 6 #remove power from chip, disable buffers
self.USBTINY_SPI = 7 #spi command, value=c1c0, index=c3c2
self.USBTINY_POLL_BYTES = 8 #set poll bytes for write, value=p1p2
self.USBTINY_FLASH_READ = 9 #read flash, index=address, USB_IN reads data
self.USBTINY_FLASH_WRITE = 10 #write flash, index=address,value=timeout, USB_OUT writes data
self.USBTINY_EEPROM_READ = 11 #read eeprom, index=address, USB_IN reads data
self.USBTINY_EEPROM_WRITE = 12 #write eeprom, index=address,value=timeout, USB_OUT writes data
self.USBTINY_DDRWRITE = 13 #set port direction, value=DDRB register value
self.USBTINY_SPI1 = 14 #single byte SPI command, value=command
# these values came from avrdude (http://www.nongnu.org/avrdude/)
self.USBTINY_RESET_LOW = 0 #for POWERUP command
self.USBTINY_RESET_HIGH = 1 #for POWERUP command
self.USBTINY_SCK_MIN = 1 #min sck-period for POWERUP
self.USBTINY_SCK_MAX = 250 #max sck-period for POWERUP
self.USBTINY_SCK_DEFAULT = 10 #default sck-period to use for POWERUP
self.USBTINY_CHUNK_SIZE = 128
self.USBTINY_USB_TIMEOUT = 500 #timeout value for writes
# search for usbtiny
self.dev=usb.core.find(idVendor=0x1781,idProduct=0x0c9f)
if self.dev==None:
print("USBtiny programmer not connected")
exit(1)
self.dev.set_configuration()
return
def _usb_control(self,req,val,index,retlen=0):
return self.dev.ctrl_transfer(usb.util.CTRL_IN|usb.util.CTRL_RECIPIENT_DEVICE|usb.util.CTRL_TYPE_VENDOR,req,val,index,retlen)
def power_on(self):
self._usb_control(self.USBTINY_POWERUP, self.USBTINY_SCK_DEFAULT, self.USBTINY_RESET_LOW )
time.sleep(0.1)
self._usb_control(self.USBTINY_POWERUP, self.USBTINY_SCK_DEFAULT, self.USBTINY_RESET_HIGH )
time.sleep(0.1)
def power_off(self):
self._usb_control(self.USBTINY_POWERDOWN,0,0)
def write(self,portbbits):
self._usb_control(self.USBTINY_WRITE,portbbits,0)
def read(self):
return self._usb_control(self.USBTINY_READ,0,0,1)
def spi1(self,b):
return self._usb_control(self.USBTINY_SPI1,b,0,1)
def spi4(self,d1d0,d3d2):
return self._usb_control(self.USBTINY_SPI,d1d0,d3d2,4)
def clr(self,bit):
self._usb_control(self.USBTINY_CLR,bit,0)
def set(self,bit):
self._usb_control(self.USBTINY_SET,bit,0)
|
d3bc0745624ddcf1057a6f5f5b86a24797eab4fc
|
[
"Markdown",
"Python",
"C++"
] | 4
|
C++
|
bitbyt3r/ISPDebug
|
d6b11389896094143c48cf9453bea15624e0df3f
|
bf395590f50396c282426b4af59dacc28ab8a4cc
|
refs/heads/master
|
<repo_name>avirup10/Data-structure-and-Algorithms-Lab---week3<file_sep>/10. print"x+y=sum of x+y". x,y should be user input.py
x=int(input())
y=int(input())
sum=x+y
print(str(x)+"+"+str(y)+" = "+str(sum))
<file_sep>/README.md
# Data-structure-and-Algorithms-Lab---week3
Python
|
64f0265d3150a695975a1a0e4f1141a47a90c149
|
[
"Markdown",
"Python"
] | 2
|
Python
|
avirup10/Data-structure-and-Algorithms-Lab---week3
|
05a3b6781e38ea952338d905cb06aa89c632ae3b
|
e08dc415b2a794d19a05a198b7a17ca738f17f2e
|
refs/heads/main
|
<repo_name>golfstrimmar/clean<file_sep>/src/js/first.js
import $ from "jquery";
// ------------------------------------------------
$(document).ready(function (e) {
$(".header__burger").on("click", function () {
$(".menu")
.addClass("menu-active")
.append(
$(
"<div class='header__info info'><a class='btn btn--success info__button _f-button' href='#!'>Kontaktai</a></div>"
)
);
setTimeout(function () {
$(".info").addClass("info-active");
}, 200);
$("body").addClass("lock");
});
$(".header__close").on("click", function () {
$(".menu")
.removeClass("menu-active")
.find(".header__info")
.remove();
$(".info").removeClass("info-active");
$("body").removeClass("lock");
});
});
// ----- header меняется в размерах и цвете
window.addEventListener("scroll", function (event) {
if (window.pageYOffset > 100) {
document.querySelector(
".header"
).classList.add("responciveHeader");
} else {
document.querySelector(".header").classList.remove("responciveHeader");
}
});
//--- сворачивается открытый header при увеличении окна 768
window.onresize = function () {
if (window.innerWidth >= 999) {
$(".menu").removeClass("menu-active").find(".header__info").remove();
$(".info").removeClass("info-active");
$("body").removeClass("lock");
// alert("");
}
};
<file_sep>/src/js/tabs.js
import $ from "jquery";
// // аккордеон --------
$(document).ready(function (e) {
let titleTab = $(".akr-title-js");
$(".akr-drop-js").slideUp(0).removeClass("act");
titleTab.on("click", function () {
let dropTab = $(this).siblings(".akr-drop-js");
let imgTab = $(this).find(".akr-item-img-js");
let parent = $(this).parent(".akr__item");
if ($(this).hasClass("act")) {
$(this).removeClass("act");
dropTab.slideUp(200).removeClass("act");
imgTab.removeClass("akr-item-img-js-active")
} else {
$(this).addClass("act");
dropTab.addClass("act").slideDown(200);
imgTab.addClass("akr-item-img-js-active")
$(".akr__item").not(parent).find(".akr-drop-js").slideUp(200);
$(".akr__item").not(parent).find(".akr-title-js").removeClass("act");
$(".akr__item")
.not(parent).find(".akr-item-img-js ").removeClass("akr-item-img-js-active");
}
});
});
<file_sep>/src/js/mySlick.js
import $ from "jquery";
// import "./slick.js";
$(Document).ready(function() {
$(".slider-js-posts-side").slick({
// dots: false,
// arrows: false,
slidesToShow: 5,
speed: 1500,
easing: "ease",
// cssEase: "linear",
centerMode: false,
// autoplay: true,
// autoplaySpeed: 5000,
// centerMode: true,
infinite: true,
prevArrow: "<div class='arrow-prev'><svg ><use xlink:href='/assets/img/sprite.svg#arrow-left-slider'></use></svg></div>",
nextArrow: "<div class='arrow-next'><svg ><use xlink:href='/assets/img/sprite.svg#arrow-right-slider'></use></svg></div>",
responsive: [
{
breakpoint: 1420,
slidesToShow: 4,
settings: {
arrows: false,
dots: true,
},
},
{
breakpoint: 800,
settings: {
slidesToShow: 2,
arrows: false,
dots: true,
},
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
arrows: false,
dots: true,
},
},
],
});
$(".slider-js-posts-low").slick({
// dots: true,
// arrows: false,
slidesToShow: 3,
speed: 1500,
easing: "ease",
// cssEase: "linear",
centerMode: false,
// autoplay: true,
// autoplaySpeed: 5000,
// centerMode: true,
infinite: true,
// initialSlide: 1,
// pauseOnFocus: true,
// pauseOnHover: true,
responsive: [
{
breakpoint: 800,
settings: {
slidesToShow: 2,
},
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
arrows: false,
dots: true,
},
},
],
});
$(".slider-js-posts-projects").slick({
// dots: true,
// arrows: false,
slidesToShow: 3,
speed: 1500,
easing: "ease",
// cssEase: "linear",
centerMode: false,
// autoplay: true,
// autoplaySpeed: 5000,
// centerMode: true,
infinite: true,
// initialSlide: 1,
// pauseOnFocus: true,
// pauseOnHover: true,
responsive: [
{
breakpoint: 800,
settings: {
slidesToShow: 2,
},
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
arrows: false,
dots: true,
},
},
],
});
$(".slider-js-posts-num").slick({
dots: true,
// arrows: false,
slidesToShow: 3,
speed: 1500,
easing: "ease",
// cssEase: "linear",
centerMode: false,
// autoplay: true,
// autoplaySpeed: 5000,
// centerMode: true,
infinite: true,
// initialSlide: 1,
// pauseOnFocus: true,
// pauseOnHover: true,
responsive: [
{
breakpoint: 800,
settings: {
slidesToShow: 2,
},
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
},
},
],
customPaging: function (slider, i) {
var current = i + 1;
current = current < 10 ? "" + current : current;
var total = slider.slideCount;
total = total < 10 ? "" + total : total;
return (
'<button type="button" role="button" tabindex="0" class="slick-dots-button">\
<span class="slick-dots-current">' +
current +
'</span>\
<span class="slick-dots-separator">/</span>\
<span class="slick-dots-total">' +
total +
"</span></button>"
);
},
});
$(".slider-js-1").slick({
// dots: true,
arrows: false,
slidesToShow: 1,
speed: 1500,
easing: "ease",
// cssEase: "linear",
centerMode: false,
autoplay: true,
autoplaySpeed: 5000,
// centerMode: true,
infinite: true,
// initialSlide: 1,
pauseOnFocus: true,
pauseOnHover: true,
// customPaging: function (slider, i) {
// var current = i + 1;
// current = current < 10 ? "" + current : current;
// var total = slider.slideCount;
// total = total < 10 ? "" + total : total;
// return (
// '<button type="button" role="button" tabindex="0" class="slick-dots-button">\
// <span class="slick-dots-current">' +
// current +
// '</span>\
// <span class="slick-dots-separator">из</span>\
// <span class="slick-dots-total">' +
// total +
// "</span></button>"
// );
// },
});
$(".slider-js-2")
.slick({
dots: false,
// arrows: false,
slidesToShow: 4,
speed: 800,
easing: "ease",
// cssEase: "linear",
centerMode: false,
// autoplay: true,
// autoplaySpeed: 2000,
infinite: true,
// initialSlide: 1,
pauseOnFocus: true,
pauseOnHover: true,
responsive: [{
breakpoint: 1200,
settings: {
slidesToShow: 3,
},
},
{
breakpoint: 800,
settings: {
slidesToShow: 2,
},
},
{
breakpoint: 500,
settings: {
slidesToShow: 1,
},
},
],
});
$(".slider-js-3").show().slick({
dots: true,
arrows: false,
slidesToShow: 1,
speed: 800,
easing: "ease",
// cssEase: "linear",
centerMode: false,
// autoplay: true,
// autoplaySpeed: 2000,
infinite: true,
// initialSlide: 1,
pauseOnFocus: true,
pauseOnHover: true,
});
});
|
d6d2b28e2cdac0dbbd3060e32ef2bbcc9ded505b
|
[
"JavaScript"
] | 3
|
JavaScript
|
golfstrimmar/clean
|
54abc79f9199469d3b777f608438c14d8eaff6d5
|
c9b7baa2c3e892578b1f90fbd1e3b1da1b3bbfc2
|
refs/heads/master
|
<file_sep>package br.com.zup.teste;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Exercicio1 {
/**
* Faça um programa que solicite ao usuário para digitar
* valores numéricos inteiros positivos.
* Encerre a entrada de dados quando for digitado um número negativo ou zero.
* Calcule a média dos números positivos digitados.
*
**/
public static void main(String[] args) {
// Entrada de dados
List<Integer> listaValores;
double mediaNumeros;
int quantidadeNumero = quantidadeNumeros();
// Processamento de dados
listaValores = receberNumeros(quantidadeNumero);
// Saída de dados
mediaNumeros = calcularMedia(listaValores);
System.out.println(mediaNumeros);
}
public static Scanner retornarScanner() {
Scanner entrada = new Scanner(System.in);
return entrada;
}
public static int quantidadeNumeros() {
// Entrada de dados
Scanner scan = retornarScanner();
int quantidade;
System.out.println("Qual a quantidade de números a digitar: ");
quantidade = scan.nextInt();
return quantidade;
}
public static List<Integer> receberNumeros(int quantidade) {
// Entrada de Dados
Scanner scan = retornarScanner();
List<Integer> lista = new ArrayList<Integer>();
int valor;
for (int i = 1; i <= quantidade; i++) {
// Entrada de dados
int opcao;
System.out.println("Digite um número inteiro e positivo: ");
valor = scan.nextInt();
// Scanner scan = retornarScanner();
if (valor > 0) {
lista.add(valor);
} else {
System.out.println("O número informado não pode ser adicionado");
}
System.out.println("Deseja continuar? 1-Sim ou 0-Para não");
opcao = scan.nextInt();
if (opcao <= 0) {
i += quantidade;
}
}
return lista;
}
public static double calcularMedia(List<Integer> lista) {
// Entrada de Dados
double media;
int soma = 0;
// Processamento de dados
for (int i = 0; i < lista.size(); i++) {
soma += lista.get(i);
}
media = (soma / lista.size());
// Saída de dados
return media;
}
// public static boolean verificaNumero(int valor) {
// if (valor > 0) {
// return true;
// } else {
// return false;
// }
// }
}
|
1360a2d728275dce79958ebbed008b40c2500c69
|
[
"Java"
] | 1
|
Java
|
zup-estrelas-fora-da-caixa/exercicioAulaMonitoria
|
2a82c1cebde25430b467df3041c64aa45570fbb6
|
4b99c9836b6abc02094cb2391b433aed9fa4577a
|
refs/heads/master
|
<repo_name>alpaziz/280_spring_2020_solutions<file_sep>/linked_list_2.py
from node import Node
class LinkedList:
def __init__(self, size = 0, head = None, tail = None):
self.size = size
self.head = head
self.tail = tail
def getSize(self):
return(self.size)
def setSize(self, s):
self.size = s
def getHead(self):
return(self.head)
def setHead(self, h):
self.head = h
def getTail(self):
return(self.tail)
def setTail(self, t):
self.tail = t
def isEmpty(self):
if(self.getSize() > 0):
return(False)
return(True)
def addNode(self, d):
newNode = Node(data = d)
# Simple Case
if(self.isEmpty()):
self.setHead(newNode)
else:
self.getTail().setnextPointer(newNode)
# t = self.getTail()
# t.setnextPointer(newNode)
self.setTail(newNode)
self.size += 1 #self.size = self.size + 1
def printLinkedList(self):
currentNode = self.head
while(currentNode != None): # currentNode != None
print(currentNode.getData())
currentNode = currentNode.getnextPointer()
def main():
l = LinkedList()
l.addNode(100)
l.addNode(200)
l.addNode("AU")
l.addNode(10000000)
l.addNode("GW")
l.printLinkedList()
if __name__ == '__main__':
main()<file_sep>/node.py
class Node:
def __init__(self, data, nextPointer = None, previousPointer = None):
self.data = data
self.nextPointer = nextPointer
self.previousPointer = previousPointer
def getData(self):
return(self.data)
def setData(self, nData):
self.data = nData
def getnextPointer(self):
return(self.nextPointer)
def setnextPointer(self, n):
self.nextPointer = n
def getPreviousPointer(self):
return(self.previousPointer)
def setPreviousPointer(self, p):
self.previousPointer = p
def main():
n = Node(data = 10000)
if __name__ == '__main__':
main()
<file_sep>/stack_2.py
from node import Node
class Stack:
def __init__(self, top = None, size = 0):
self.top = top
self.size = size
def push(self, newData):
newNode = Node(data = newData)
if(self.size > 0):
newNode.setnextPointer(self.top)
self.top = newNode
self.size += 1
def peak(self):
return(self.top.getData())
def pop(self):
if(self.size > 0):
print(self.top.getData())
prev = self.top
self.top = self.top.getnextPointer()
prev.setnextPointer(None)
self.size -= 1
else:
print("The stack is Empty!")
def main():
s = Stack()
s.push(100)
s.push("American U")
s.push("GW")
# print("The size was: ", s.size)
s.pop()
s.pop()
s.pop()
s.pop()
# print("The size is: ", s.size)
# s.pop()
if __name__ == '__main__':
main()
<file_sep>/queue_2.py
from node import Node
class Queue:
def __init__(self):
self.size = 0
self.front = None
self.end = None
def enqueue(self, newData):
newNode = Node(data = newData)
if(self.size == 0):
self.front = newNode
else:
newNode.setnextPointer(self.end)
self.end.setPreviousPointer(newNode)
self.end = newNode
self.size+=1
def dequeue(self):
if(self.size == 0):
print("The Queue is Empty!")
else:
print(self.front.getData())
if(self.size > 1):
old_front = self.front
self.front = self.front.getPreviousPointer()
self.front.setnextPointer(None)
old_front.setPreviousPointer(None)
self.size -=1
#print(old_front)
def main():
q = Queue()
q.enqueue(100)
q.enqueue(200)
q.enqueue(500)
q.dequeue()
q.dequeue()
q.dequeue()
if __name__ == '__main__':
main()
|
cdd6c9b5487d23f12fd61d830e4571bcd85f31c8
|
[
"Python"
] | 4
|
Python
|
alpaziz/280_spring_2020_solutions
|
1756f41f31e470ec9df73f71aceb282cbb626b9f
|
33fdf7254854408100a37f0e0adba12571870477
|
refs/heads/master
|
<repo_name>gabrielfava/asaPY<file_sep>/Modulos/ProvasPassadas/aux_scraping.py
#ASAPY
import requests
__URL_GLOBAL = "https://www.urionlinejudge.com.br";
def printme(pagina):
body = getCorpo(__URL_GLOBAL+"/judge/pt/problems/view/"+pagina);
iInicio = find_str(body, "<iframe");
pos = (body[iInicio:]);
iFim = find_str(pos, ">")+1;
tupla = pos[:iFim];
page2 = getAttr(tupla,"src");
bodyframe = getCorpo(__URL_GLOBAL+page2);
print(bodyframe);
return;
def find_str(s, char):
index = 0
if char in s:
c = char[0]
for ch in s:
if ch == c:
if s[index:index+len(char)] == char:
return index
index += 1
return -1
#TODO - TRATAR EQUIVALENCIA DE SINTAXE !
def getAttr(tupla, atributo):
tamanhoAtr = len(atributo)+2; #ja apaga atributo="
inicioAtr = find_str(tupla, atributo)+tamanhoAtr;
if inicioAtr == -1:
return "ERRO"
fimAttr = find_str(tupla[inicioAtr:], '"');
return tupla[inicioAtr:inicioAtr+fimAttr];
def getCorpo(req):
page = requests.get(req);
return str(page.content);
printme("2166")
#print("titulo => URI Online Judge - Problema 2166 - Raiz Quadrada de 2")
#print("autor => <NAME>, UNILA")
#print("probm => ma das formas de calcular a raiz quadrada de um n\xc3\xbamero natural")<file_sep>/Modulos/Times/team.py
#team.py
class Team(object):
"""docstring for Team"""
# [user]
# usernumber=900
# usersitenumber=1
# username=time1
# usertype=team
# userenabled=t
# usermultilogin=f
# userfullname=[TIME 1]ASAP
# userdesc=[TIME 1]ASAP
# userpassword=<PASSWORD>
seq = 0
objects = []
def __init__(team_number, team_site, team_name, enabled, type, multi_login, team_full_name, password ):
super(Team, self).__init__()
self.team_number = team_number
self.team_site = team_site
self.team_name = team_name
self.enabled = enabled
self.type = type
self.multi_login = multi_login
self.team_full_name = team_full_name
self.password = <PASSWORD>
def save(self):
self.__class__.seq += 1
self.team_number = self.__class__.seq
self.__class__.objects.append(self)
@classmethod
def all(cls):
return cls.objects <file_sep>/README.md
# asaPY - Gestão para Maratonas de Programação
Autores:
* [<NAME>](https://github.com/gabrielfava)
* [<NAME>](https://github.com/jpmondoni)
## O que é?
O **asaPY** foi idealizado para suprir necessidades de faculdades que queiram gerenciar suas equipes em competições de programação. Este software visa entregar um stack de soluções para o coordenador do projeto de programação competitiva para que o mesmo possa gastar o seu tempo e energia com aquilo que é realmente necessário para alcançar os objetivos de uma maratona: **a preparação da equipe**.
O **asaPY** é completamente open-source e livre para uso, totalmente mantido pela comunidade e pelos desenvolvedores como um projeto paralelo. O projeto é executado em um ambiente web, com uso de banco de dados MySQL.
## Funcionalidades
* Cadastro e gestão de equipes
* Cadastro e gestão de competições internas
* Asap Analytics
* Gestão de resultados
* Integrações com o BOCA
* Geração de pack de exercícios automaticamente
* Geração de senhas
* Gestão de exercícios através de scraping
## Status
O projeto teve início ao desenvolvimento no dia 24 de fevereiro de 2018. As etapas do desenvolvimento serão:
* Desenvolver funcionalidades em back-end
* Criação do front-end
* Integração framework Flask
* Release da versão beta.
## Releases
Confira os releases no branch `master` do projeto, em [releases](https://github.com/gabrielfava/asapy/releases).
## Contato
* Quer contribuir com o projeto? Tem alguma sugestão?
Nos mande um e-mail em `jp ponto mondoni arroba gmail ponto com` ou `gabrielfavasouza arroba gmail ponto com`
* Bugs, erros ou suporte
Crie um novo `issue` em nosso repositório: [Issues](https://github.com/gabrielfava/asapy/issues).<file_sep>/Modulos/ProvasPassadas/provas_passadas.core.py
import requests
printme(2661)
# retorna corpo da pagina
def printme(id):
page = requests.get("https://www.urionlinejudge.com.br/judge/pt/problems/view/"+id);
print(page.content);
return;<file_sep>/Modulos/Times/generate.py
import string
import random
from mysql.connector import MySQLConnection, Error
import database_conf as cfg
import team
__select_ALL = "SELECT team_number, team_site, team_name, password, team_short_name, enabled, type, multi_login, team_full_name FROM TEAMS"
def select_teams(cursor):
query = ("SELECT team_number, team_name, password from TEAMS")
cursor.execute(query)
return cursor
def update_passwords(cnx, cursor):
for(team_number, team_name, password) in cursor:
if(not password):
new_pass = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(6))
query = """UPDATE TEAMS
SET password=%s
WHERE team_number=%s"""
data = (new_pass, team_number)
try:
cursor.execute(query,data)
except Error as error:
print(error)
cnx.commit()
def generate_file(cursor):
cursor.execute(__select_ALL)
f = open("import.txt", 'w')
f.write("[user]")
first_team = True
for(team_number, team_site, team_name, password, team_short_name, enabled, type, multi_login, team_full_name) in cursor:
if(first_team):
f.write('\n')
first_team = False
else:
f.write('\n\n')
f.write('usernumber=' + str(team_number))
f.write('\nusersitenumber=' + team_site)
f.write('\nusername=' + team_short_name)
f.write('\nusertype=' + type)
f.write('\nuserenabled=' + enabled)
f.write('\nusermultilogin=' + multi_login)
f.write('\nuserfullname=' + team_full_name)
f.write('\nuserdesc=' + team_full_name)
f.write('\nuserpassword=' + str(password))
f.close()
def main():
cnx = MySQLConnection(**cfg.mysql)
cursor = cnx.cursor()
select_teams(cursor)
update_passwords(cnx, cursor)
generate_file(cursor)
cursor.close()
cnx.close()
if __name__ == "__main__":
main()<file_sep>/Modulos/Times/select_team_mysql.py
import mysql.connector
import database_conf as cfg
cnx = mysql.connector.connect(**cfg.mysql)
cursor = cnx.cursor()
query = ("SELECT team_number, team_name FROM teams")
cursor.execute(query)
for(team_number, team_name) in cursor:
print("{} -> {}".format(team_number, team_name))
cursor.close()
cnx.close()
<file_sep>/Dependências.md
# Dependências de uso
## Python
* Versão 3.6
* Pacotes específicos
* mysql-connector-python 2.0.4
* Conda: `conda install -c anaconda mysql-connector-python `
* pip: `pip install mysql-connector`
* lxml
* pip: `pip install lxml`<file_sep>/Modulos/Times/teams.sql
/*
Navicat MySQL Data Transfer
Source Server : AsaPY
Source Server Type : MySQL
Source Server Version : 50637
Source Host : robb0469.publiccloud.com.br:3306
Source Schema : defcode_asap
Target Server Type : MySQL
Target Server Version : 50637
File Encoding : 65001
Date: 24/02/2018 14:23:22
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for teams
-- ----------------------------
DROP TABLE IF EXISTS `teams`;
CREATE TABLE `teams` (
`team_number` int(11) NOT NULL,
`team_site` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`team_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`team_short_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`enabled` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`multi_login` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`team_full_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`team_number`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
|
20acc82fcf57062c05f48953af39b3a95b599581
|
[
"Markdown",
"SQL",
"Python"
] | 8
|
Python
|
gabrielfava/asaPY
|
be6211190d4acfca7aacef45d7dc467e2237496d
|
d48c3ce32345e07f984898aef79243f13ff63a83
|
refs/heads/main
|
<file_sep># OPIAnalytics
## SECCION A - Ejercicio1
LAs respuestas de la sección A se encuentran en el notebook Ejercicio1.ipynb
## SECCION B - BOPS
Las respuestas de la sección B se encuentran en el notebook BOPS.ipynb
## SECCION C - Seccion C
Las respuestas de la sección c se encuentran en el notebook SeccionC.ipynb
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import matplotlib.cm as cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt
# In[3]:
import types
import pandas as pd
from botocore.client import Config
import ibm_boto3
def __iter__(self): return 0
# @hidden_cell
# The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials.
# You might want to remove those credentials before you share the notebook.
client_cbe136da66dc461989fb771dc3f9946e = ibm_boto3.client(service_name='s3',
ibm_api_key_id='<KEY>',
ibm_auth_endpoint="https://iam.cloud.ibm.com/oidc/token",
config=Config(signature_version='oauth'),
endpoint_url='https://s3-api.us-geo.objectstorage.service.networklayer.com')
body = client_cbe136da66dc461989fb771dc3f9946e.get_object(Bucket='opi-donotdelete-pr-31zvkcjimgz06s',Key='<KEY>')['Body']
# add missing __iter__ method, so pandas accepts body as file-like object
if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType( __iter__, body )
df_bm = pd.read_csv(body)
body = client_cbe136da66dc461989fb771dc3f9946e.get_object(Bucket='opi-donotdelete-pr-31zvkcjimgz06s',Key='bops_online.csv')['Body']
# add missing __iter__ method, so pandas accepts body as file-like object
if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType( __iter__, body )
df_online = pd.read_csv(body)
# In[4]:
df_online.head()
# In[5]:
df_online.columns
# In[6]:
df_online=df_online[['id (DMA)','year','month','week','after','close',' sales ']]
df_online.head()
# In[7]:
df_bm.head()
# In[8]:
df_bm.columns
# In[9]:
df_bm=df_bm[['id (store)', 'year', 'month', 'week', 'usa', 'after', ' sales ']]
df_bm.head()
# In[10]:
pd.DataFrame(df_bm.dtypes,columns=['Type']).T
# ## Missing Values
# In[11]:
def missing_data(data):
total = data.isnull().sum()
percent = (data.isnull().sum()/data.isnull().count()*100)
tt = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
types = []
for col in data.columns:
dtype = str(data[col].dtype)
types.append(dtype)
tt['Types'] = types
return(np.transpose(tt))
# In[12]:
missing_data(df_bm)
# In[13]:
missing_data(df_online)
# In[14]:
df_bm.replace([np.inf, -np.inf], np.nan)
df_bm=df_bm.dropna()
# In[15]:
df_bm[['id (store)', 'year', 'month', 'week', 'usa', 'after']]=df_bm[['id (store)', 'year', 'month', 'week', 'usa', 'after']].astype('int')
# In[16]:
df_bm.head()
# In[17]:
df_bm[' sales '] = df_bm[' sales '].str.replace(',', '').astype(float)
# In[18]:
df_online[' sales '] = df_online[' sales '].str.replace(',', '').astype(float)
# In[19]:
df_bm.head()
# In[20]:
df_online.head()
# In[21]:
df_online.describe()
# In[22]:
df_bm.describe()
# In[23]:
df_bm['date'] = pd.to_datetime(df_bm.year.astype(str), format='%Y') + pd.to_timedelta(df_bm.week.mul(7).astype(str) + ' days')
df_bm.head()
# In[24]:
df_online['date'] = pd.to_datetime(df_online.year.astype(str), format='%Y') + pd.to_timedelta(df_online.week.mul(7).astype(str) + ' days')
df_online.head()
# In[25]:
df_online
# ## Graficas ventas online
# In[26]:
import seaborn as sns; sns.set(style="ticks", color_codes=True)
sales_mean=df_online[' sales '].groupby(df_online['date']).mean()
sales_median=df_online[' sales '].groupby(df_online['date']).median()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Mean', 'Median'], loc='best', fontsize=16)
plt.title(' Sales Online - Mean and Median', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
#
# In[27]:
df_online1= df_online[df_online.after == 1]
df_online2= df_online[df_online.after != 1]
df_online2.head()
# In[28]:
sales_mean=df_online2[' sales '].groupby(df_online2['date']).mean()
sales_median=df_online1[' sales '].groupby(df_online1['date']).mean()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Before', 'After'], loc='best', fontsize=16)
plt.title(' Sales Online - Mean ', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# Se muestra una clara disminucion de ventas a partir de la implementacion de la estrategia BOPS. Sin embargo, aun faltan mas facotres a considerar como la DMA
# In[29]:
import seaborn as sns; sns.set(style="ticks", color_codes=True)
sales_mean=df_online[' sales '].groupby(df_online['week']).mean()
sales_median=df_online[' sales '].groupby(df_online['week']).median()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Mean', 'Median'], loc='best', fontsize=16)
plt.title('Weekly Sales Online - Mean and Median', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[30]:
sales_mean=df_online[' sales '].groupby(df_online['month']).mean()
sales_median=df_online[' sales '].groupby(df_online['month']).median()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Mean', 'Median'], loc='best', fontsize=16)
plt.title('Monthly Sales Online - Mean and Median', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[31]:
sales_mean=df_bm[' sales '].groupby(df_bm['date']).mean()
sales_median=df_bm[' sales '].groupby(df_bm['date']).median()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Mean', 'Median'], loc='best', fontsize=16)
plt.title('Sales bm - Mean and Median', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[32]:
df_bm1= df_bm[df_bm.after == 1]
df_bm2= df_bm[df_bm.after != 1]
df_bm2.head()
# In[33]:
sales_mean=df_bm2[' sales '].groupby(df_bm2['date']).mean()
sales_median=df_bm1[' sales '].groupby(df_bm1['date']).mean()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Before', 'After'], loc='best', fontsize=16)
plt.title(' Sales bm - Mean ', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# Aunque se muestra una disminición en las ventas a partir de la implementación de la estrategia, aun falta considerar la localización de las tiendas
# In[34]:
sales_mean=df_bm[' sales '].groupby(df_bm['week']).mean()
sales_median=df_bm[' sales '].groupby(df_bm['week']).median()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Mean', 'Median'], loc='best', fontsize=16)
plt.title('Weekly Sales bm - Mean and Median', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[35]:
sales_mean=df_bm[' sales '].groupby(df_bm['month']).mean()
sales_median=df_bm[' sales '].groupby(df_bm['month']).median()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Mean', 'Median'], loc='best', fontsize=16)
plt.title('Monthly Sales bm - Mean and Median', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[36]:
weekly_sales = df_bm[' sales '].groupby(df_bm['id (store)']).mean()
plt.figure(figsize=(20,8))
sns.barplot(weekly_sales.index, weekly_sales.values, palette='dark')
plt.grid()
plt.title('Average Sales - per Store', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Store', fontsize=16)
plt.show()
# In[37]:
weekly_sales = df_online[' sales '].groupby(df_online['id (DMA)']).mean()
plt.figure(figsize=(20,8))
sns.barplot(weekly_sales.index, weekly_sales.values, palette='dark')
plt.grid()
plt.title('Average Sales - per Store', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Store', fontsize=16)
plt.show()
# ## Analizarames los datos a partir de la variable close y la variable usa
#
# Analizaremos las ventas para las compras realizadas cerca de la DMA y las lejanas por separado. Ademas se analiza las tiendas que se encuentran en Estados Unidos, debido a que solo en Estados Unidos se lanzo el proyecto BOPS
# ### DMA
# In[38]:
df_onlineDMA1b= df_online2[df_online2.close == 1]
df_onlineDMA1a= df_online1[df_online1.close == 1]
df_onlineDMA2b= df_online2[df_online2.close != 1]
df_onlineDMA2a= df_online1[df_online1.close != 1]
# In[39]:
sales_mean=df_onlineDMA1b[' sales '].groupby(df_onlineDMA1b['date']).mean()
sales_median=df_onlineDMA1a[' sales '].groupby(df_onlineDMA1a['date']).mean()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Before', 'After'], loc='best', fontsize=16)
plt.title(' Sales Online DMA=1 - Mean ', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[40]:
sales_mean=df_onlineDMA2b[' sales '].groupby(df_onlineDMA2b['date']).mean()
sales_median=df_onlineDMA2a[' sales '].groupby(df_onlineDMA2a['date']).mean()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Before', 'After'], loc='best', fontsize=16)
plt.title(' Sales Online DMA=0 - Mean ', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# ### Tiendas en Estados Unidos
# In[41]:
df_bmDMA1b= df_bm2[df_bm2.usa == 1]
df_bmDMA1a= df_bm1[df_bm1.usa == 1]
df_bmDMA2b= df_bm2[df_bm2.usa != 1]
df_bmDMA2a= df_bm1[df_bm1.usa != 1]
# In[42]:
sales_mean=df_bmDMA1b[' sales '].groupby(df_bmDMA1b['date']).mean()
sales_median=df_bmDMA1a[' sales '].groupby(df_bmDMA1a['date']).mean()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Before', 'After'], loc='best', fontsize=16)
plt.title(' Sales BM USA - Mean ', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[43]:
sales_mean=df_bmDMA2b[' sales '].groupby(df_bmDMA2b['date']).mean()
sales_median=df_bmDMA2a[' sales '].groupby(df_bmDMA2a['date']).mean()
plt.figure(figsize=(20,8))
sns.lineplot(sales_mean.index, sales_mean.values)
sns.lineplot(sales_median.index, sales_median.values)
plt.grid()
plt.legend(['Before', 'After'], loc='best', fontsize=16)
plt.title(' Sales Online Canada - Mean ', fontsize=18)
plt.ylabel('Sales', fontsize=16)
plt.xlabel('Date', fontsize=16)
plt.show()
# In[44]:
sales_mean_dbbUSA=df_bmDMA1b[' sales '].mean()
sales_mean_dbaUSA=df_bmDMA1a[' sales '].mean()
sales_mean_dbbC=df_bmDMA2b[' sales '].mean()
sales_mean_dbaC=df_bmDMA2a[' sales '].mean()
df_salesmdb=pd.DataFrame({'Tiendas':['USA antes','USA despues','Cananda antes','Canada Despues'],'Venta media':[sales_mean_dbbUSA,sales_mean_dbaUSA,sales_mean_dbbC,sales_mean_dbaC]})
df_salesmdb
# In[48]:
sales_total_dbbUSA=df_bmDMA1b[' sales '].sum()
sales_total_dbaUSA=df_bmDMA1a[' sales '].sum()
sales_total_dbbC=df_bmDMA2b[' sales '].sum()
sales_total_dbaC=df_bmDMA2a[' sales '].sum()
df_salesmdb['Venta Total']= [sales_total_dbbUSA,sales_total_dbaUSA,sales_total_dbbC,sales_total_dbaC]
df_salesmdb
# In[46]:
sales_mean_onb1=df_onlineDMA1b[' sales '].mean()
sales_mean_ona1=df_onlineDMA1a[' sales '].mean()
sales_mean_onb0=df_onlineDMA2b[' sales '].mean()
sales_mean_ona0=df_onlineDMA2a[' sales '].mean()
df_salesmon=pd.DataFrame({'Tiendas':['close antes','Close despues','Far antes','Far Despues'],'Venta media':[sales_mean_dbbUSA,sales_mean_dbaUSA,sales_mean_dbbC,sales_mean_dbaC]})
df_salesmon
# In[53]:
sales_total_onb1=df_onlineDMA1b[' sales '].sum()
sales_total_ona1=df_onlineDMA1a[' sales '].sum()
sales_total_onb2=df_onlineDMA2b[' sales '].sum()
sales_total_ona2=df_onlineDMA2a[' sales '].sum()
df_salesmon['Venta Total']= [sales_total_dbbUSA,sales_total_dbaUSA,sales_total_dbbC,sales_total_dbaC]
df_salesmon
# ### 1. ¿Deberían expandirse a Canadá?
#
# Al analizar el promedio de ventas separando las tiendas por pais, se puede observar que la disminución en las ventas de las tiendas en Estados Unidos no es tan grande. No podemos decir que la causa de la disminución de las ventas es debido la implementacion de la nueva estrategia, existen otros factores, como la epoca del año, se sabe que los primeros meses del año son los de menor venta.
#
# En cuanto al analisis de las ventas online, si se puede apreciar que han disminuido significativamente a partir de la implementación de la estrategia. Esto puede deberse a que, la gente prefiere recojer en la tienda y a la vez comprar productos ahi.
#
# Por otra parte al analizar las graficas de las tiendas de Canada, se observa una disminución mayor de las ventas promedio a pesar de que en esta region no se implemento la nueva estrategia.Con esto podriamos nos podemos dar una de idea de que en la disminución de las ventas han intervenido diferentes factores a la implementación de la nueva estrategia.
#
# Con el estudio realizado puedo concluir que la estrategia deberia expandirse a Canada debido a que no hay datos significativos que nos permitan demostrar que la baja de ventas fue causada solamente por la implementación de la estrategia. Ademas de que es muy pronto para que la estrategia sea calificada adecuadamente.
#
#
# ### 2. ¿Cuántos millones de dólares se ganaron o perdieron a partir delprograma?Explicatu razonamiento y metodología.
# Para analizar este punto, solo se deberian considerar las tiendas en Estados Unidos debido a que solo en ellas se aplico la nueva estrategia. Ademas de considerar las ventas online con un DMA que cuenten con una tienda cerca. Creo que estos dos casos son los mas impactados por la nueva estrategia.
#
# Explicado lo anterior muestro la diferencia media de veentas, asi como la diferencia del total de ventas.
# In[54]:
perdida= pd.DataFrame({'Casos':['Online DMA cerca','Tiendas USA'],'Venta Media Antes':[sales_mean_dbbUSA,sales_mean_onb1],'Venta media Despues':[sales_mean_dbaUSA,sales_mean_ona1],
'Diferencia venta media':[sales_mean_dbbUSA-sales_mean_dbaUSA,sales_mean_onb1-sales_mean_ona1],
'Venta total antes':[sales_total_dbbUSA,sales_total_onb1],'Venta total despues':[sales_total_dbaUSA,sales_total_ona1]})
# In[56]:
perdida['Diferencia venta total']=[sales_total_dbbUSA-sales_total_dbaUSA,sales_total_onb1-sales_total_ona1]
perdida
# In[ ]:
|
b5034dab44df04c1ca0b5b19eb95b9298105daf4
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
IvanEdmundo/OPIAnalytics
|
277450a06f805212fb1ca1e8589c089c662234cc
|
b2d6597ae6422851e64a5394af49c1ec4c5ceec6
|
refs/heads/main
|
<repo_name>SrBenja007/PuppetsV2<file_sep>/src/main/java/net/astrocube/puppets/player/PacketUtil.java
package net.astrocube.puppets.player;
import net.astrocube.puppets.Reflection;
import net.astrocube.puppets.entity.PuppetEntity;
import net.minecraft.server.v1_8_R3.*;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class PacketUtil {
/**
* Send packet play out to modify {@link CorePlayerPuppetEntity}
* @param action belonging to packet
* @param connection where packet will be sent
* @param playerEntity of the NPC to be shown
*/
public static void sendConnection(
PacketPlayOutPlayerInfo.EnumPlayerInfoAction action,
PlayerConnection connection,
EntityPlayer playerEntity
) {
PacketPlayOutPlayerInfo packetPlayOutPlayerInfo = new PacketPlayOutPlayerInfo(
action,
playerEntity
);
PacketPlayOutPlayerInfo.PlayerInfoData playerInfoData =
packetPlayOutPlayerInfo.new PlayerInfoData(
playerEntity.getProfile(),
1,
WorldSettings.EnumGamemode.NOT_SET,
IChatBaseComponent.ChatSerializer.a(
"{\"text\":\"[NPC] " + playerEntity.getProfile().getName() + "\",\"color\":\"dark_gray\"}"
)
);
Reflection.FieldAccessor<List> fieldAccessor = Reflection.getField(packetPlayOutPlayerInfo.getClass(), "b", List.class);
fieldAccessor.set(packetPlayOutPlayerInfo, Collections.singletonList(playerInfoData));
connection.sendPacket(packetPlayOutPlayerInfo);
}
/**
* Creates a team to make invisible a {@link PuppetEntity}
* @param connection where packet will be sent
* @param name of the {@link PuppetEntity} to add.
*/
public static void createRegisterTeam(
PlayerConnection connection,
String name
) {
PacketPlayOutScoreboardTeam packetPlayOutScoreboardTeam = new PacketPlayOutScoreboardTeam();
Reflection.getField(packetPlayOutScoreboardTeam.getClass(), "h", int.class)
.set(packetPlayOutScoreboardTeam, 0);
Reflection.getField(packetPlayOutScoreboardTeam.getClass(), "b", String.class)
.set(packetPlayOutScoreboardTeam, name);
Reflection.getField(packetPlayOutScoreboardTeam.getClass(), "a", String.class)
.set(packetPlayOutScoreboardTeam, name);
Reflection.getField(packetPlayOutScoreboardTeam.getClass(), "e", String.class)
.set(packetPlayOutScoreboardTeam, "never");
Reflection.getField(packetPlayOutScoreboardTeam.getClass(), "i", int.class)
.set(packetPlayOutScoreboardTeam, 1);
Reflection.FieldAccessor<Collection> collectionFieldAccessor = Reflection.getField(
packetPlayOutScoreboardTeam.getClass(), "g", Collection.class);
collectionFieldAccessor.set(packetPlayOutScoreboardTeam, Collections.singletonList(name));
connection.sendPacket(packetPlayOutScoreboardTeam);
}
/**
* Spawn named entity belonging to {@link CorePlayerPuppetEntity}
* @param connection of player to be displayed
* @param playerEntity of the {@link CorePlayerPuppetEntity}
*/
public static void sendNamedSpawn(PlayerConnection connection, EntityPlayer playerEntity) {
connection.sendPacket(
new PacketPlayOutNamedEntitySpawn(
playerEntity
)
);
}
/**
* Fix of wrong head position
* @param connection of the player to be fixed
* @param playerEntity of the {@link CorePlayerPuppetEntity}
*/
public static void sendFixedHeadPacket(PlayerConnection connection, EntityPlayer playerEntity) {
connection.sendPacket(
new PacketPlayOutEntityHeadRotation(
playerEntity,
(byte) (playerEntity.yaw * 256 / 360)
)
);
}
}
<file_sep>/src/main/java/net/astrocube/puppets/listener/ChunkPuppetListener.java
package net.astrocube.puppets.listener;
import net.astrocube.puppets.entity.PuppetEntity;
import net.astrocube.puppets.entity.PuppetRegistry;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
public class ChunkPuppetListener implements Listener {
private final PuppetRegistry puppetRegistry;
public ChunkPuppetListener(PuppetRegistry puppetRegistry) {
this.puppetRegistry = puppetRegistry;
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
Chunk chunk = event.getChunk();
for (PuppetEntity entity : puppetRegistry.getRegistry()) {
if (isInDifferentChunk(chunk, entity)) {
continue;
}
entity.getViewers().forEach(viewer -> {
Player player = Bukkit.getPlayer(viewer);
if (player != null) {
entity.autoHide(player);
entity.hide(player);
}
});
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
Chunk chunk = event.getChunk();
for (PuppetEntity entity : puppetRegistry.getRegistry()) {
if (isInDifferentChunk(chunk, entity)) {
continue;
}
entity.getViewers().forEach(viewer -> {
Player player = Bukkit.getPlayer(viewer);
if (player != null && entity.isInRange(player) && entity.isAutoHidden(player)) {
entity.removeAutoHide(player);
if (!entity.isRendered(player)) {
entity.show(player);
}
}
});
}
}
private boolean isInDifferentChunk(Chunk chunk, PuppetEntity entity) {
World world = Bukkit.getWorld(entity.getLocation().getWorld());
if (world == null) {
return true;
}
Location location = new Location(
world,
entity.getLocation().getX(),
entity.getLocation().getY(),
entity.getLocation().getZ()
);
return !compareChunkEquality(location, chunk);
}
private static int getChunkCoordinate(int coordinate) {
return coordinate >> 4;
}
private static boolean compareChunkEquality(Location loc, Chunk chunk) {
return getChunkCoordinate(loc.getBlockX()) == chunk.getX()
&& getChunkCoordinate(loc.getBlockZ()) == chunk.getZ();
}
}
<file_sep>/src/main/java/net/astrocube/puppets/location/CoreLocation.java
package net.astrocube.puppets.location;
import org.bukkit.Bukkit;
public class CoreLocation implements Location {
private final double x;
private final double y;
private final double z;
private final int yaw;
private final int pitch;
private final String world;
public CoreLocation(double x, double y, double z, int yaw, int pitch, String world) {
this.x = x;
this.y = y;
this.z = z;
this.yaw = yaw;
this.pitch = pitch;
this.world = world;
if (Bukkit.getWorld(world) == null) {
throw new IllegalArgumentException("World location not found");
}
}
@Override
public double getX() {
return x;
}
@Override
public double getY() {
return y;
}
@Override
public double getZ() {
return z;
}
@Override
public int getYaw() {
return yaw;
}
@Override
public int getPitch() {
return pitch;
}
@Override
public String getWorld() {
return world;
}
}
<file_sep>/src/main/java/net/astrocube/puppets/entity/CorePuppetEntity.java
package net.astrocube.puppets.entity;
import net.astrocube.puppets.location.Location;
import net.minecraft.server.v1_8_R3.Entity;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public abstract class CorePuppetEntity implements PuppetEntity {
private final Plugin plugin;
private final Location location;
private final int followingEntity;
private final ClickAction action;
private final Set<UUID> viewers;
private final Set<UUID> autoHidden;
private final Set<UUID> rendered;
private boolean visibleAll;
private final Entity entity;
private final UUID UUID;
public CorePuppetEntity(
Plugin plugin,
UUID UUID,
ClickAction action,
Location location,
Entity entity,
int followingEntity
) {
this.plugin = plugin;
this.location = location;
this.entity = entity;
this.action = action;
this.followingEntity = followingEntity;
this.autoHidden = new HashSet<>();
this.viewers = new HashSet<>();
this.rendered = new HashSet<>();
this.visibleAll = false;
this.UUID = UUID;
}
@Override
public boolean isRendered(Player player) {
return rendered.contains(player.getUniqueId());
}
@Override
public void show(Player player) {
this.rendered.add(player.getUniqueId());
}
@Override
public void hide(Player player) {
this.rendered.remove(player.getUniqueId());
}
@Override
public Location getLocation() {
return this.location;
}
@Override
public int getFollowingEntity() {
return followingEntity;
}
@Override
public boolean isViewing(Player player) {
return viewers.contains(player.getUniqueId());
}
@Override
public void register(Player player) {
viewers.add(player.getUniqueId());
}
@Override
public boolean isInRange(Player player) {
if (player == null) {
return false;
}
if (!player.getWorld().getName().equalsIgnoreCase(location.getWorld())) {
return false;
}
World world = Bukkit.getWorld(getLocation().getWorld());
if (world == null) {
return false;
}
double hideDistance = 50.0;
double distanceSquared = player.getLocation().distanceSquared(
new org.bukkit.Location(
world,
getLocation().getX(),
getLocation().getY(),
getLocation().getZ()
)
);
double bukkitRange = Bukkit.getViewDistance() << 4;
return distanceSquared <= square(hideDistance) && distanceSquared <= square(bukkitRange);
}
@Override
public void unregister(Player player) {
viewers.remove(player.getUniqueId());
}
@Override
public Set<UUID> getViewers() {
return viewers;
}
@Override
public Entity getEntity() {
return this.entity;
}
@Override
public void showAll() {
visibleAll = true;
Bukkit.getOnlinePlayers().forEach(this::show);
}
@Override
public void hideAll() {
visibleAll = false;
Bukkit.getOnlinePlayers().forEach(this::hide);
}
@Override
public Plugin getPlugin() {
return plugin;
}
@Override
public UUID getUUID() {
return UUID;
}
@Override
public ClickAction getClickAction() {
return action;
}
@Override
public void autoHide(Player player) {
autoHidden.add(player.getUniqueId());
}
@Override
public boolean isAutoHidden(Player player) {
return autoHidden.contains(player.getUniqueId());
}
@Override
public void removeAutoHide(Player player) {
autoHidden.remove(player.getUniqueId());
}
public static double square(double val) {
return val * val;
}
}
<file_sep>/src/main/java/net/astrocube/puppets/packet/PacketHandler.java
package net.astrocube.puppets.packet;
import org.bukkit.entity.Player;
public interface PacketHandler {
void handle(Player player);
}<file_sep>/src/main/java/net/astrocube/puppets/player/CorePlayerPuppetEntity.java
package net.astrocube.puppets.player;
import net.astrocube.puppets.entity.ClickAction;
import net.astrocube.puppets.entity.CorePuppetEntity;
import net.astrocube.puppets.hologram.CoreHologram;
import net.astrocube.puppets.hologram.Hologram;
import net.astrocube.puppets.location.Location;
import net.astrocube.puppets.player.skin.PuppetSkin;
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.*;
public class CorePlayerPuppetEntity extends CorePuppetEntity implements PlayerPuppetEntity {
private final PuppetSkin skin;
private final Map<UUID, Hologram> linkedHolograms;
CorePlayerPuppetEntity(
Plugin plugin,
Location location,
ClickAction action,
Entity entity,
PuppetSkin skin,
int followingEntity
) {
super(plugin, UUID.randomUUID(), action, location, entity, followingEntity);
this.skin = skin;
entity.setLocation(
location.getX(),
location.getY(),
location.getZ(),
location.getYaw(),
location.getPitch()
);
this.linkedHolograms = new HashMap<>();
}
@Override
public void show(Player player) {
if (!isViewing(player)) {
throw new UnsupportedOperationException("Player is not registered for viewing");
}
super.show(player);
PlayerConnection connection = ((CraftPlayer) player).getHandle().playerConnection;
World world = Bukkit.getWorld(getLocation().getWorld());
if (world == null) {
throw new UnsupportedOperationException("Registered world is null");
}
if (!(getEntity() instanceof EntityPlayer)) {
throw new IllegalArgumentException("Obtained entity is not a player");
}
EntityPlayer playerEntity = (EntityPlayer) getEntity();
PacketUtil.createRegisterTeam(connection, getEntity().getName());
PacketUtil.sendConnection(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, connection, playerEntity);
PacketUtil.sendNamedSpawn(connection, playerEntity);
PacketUtil.sendFixedHeadPacket(connection, playerEntity);
Bukkit.getScheduler().runTaskLater(getPlugin(), () -> PacketUtil.sendConnection(
PacketPlayOutPlayerInfo.EnumPlayerInfoAction.REMOVE_PLAYER,
connection,
playerEntity
), 5 * 20L);
if (hasLinkedHolograms(player)) {
showHolograms(player);
}
}
@Override
public void hide(Player player) {
if (!isViewing(player)) {
throw new UnsupportedOperationException("Player is not registered for viewing");
}
super.hide(player);
PlayerConnection connection = ((CraftPlayer)player).getHandle().playerConnection;
connection.sendPacket(new PacketPlayOutEntityDestroy(getEntity().getId()));
if (hasLinkedHolograms(player)) {
hideHolograms(player);
}
}
@Override
public void clear() {
Bukkit.getOnlinePlayers().forEach(this::unregister);
}
@Override
public void unregister(Player player) {
hide(player);
removeHolograms(player);
super.unregister(player);
}
@Override
public void setHolograms(Player player, List<String> lines) {
if (!isViewing(player)) {
throw new UnsupportedOperationException("Player not viewing");
}
removeHolograms(player);
Collections.reverse(lines);
Hologram hologram = new CoreHologram(player, getLocation(), lines);
linkedHolograms.put(player.getUniqueId(), hologram);
hologram.show();
}
@Override
public boolean hasLinkedHolograms(Player player) {
return linkedHolograms.containsKey(player.getUniqueId());
}
@Override
public void removeHolograms(Player player) {
if (hasLinkedHolograms(player)) {
Hologram hologram = linkedHolograms.get(player.getUniqueId());
hologram.hide();
linkedHolograms.remove(player.getUniqueId());
}
}
@Override
public void hideHolograms(Player player) {
if (hasLinkedHolograms(player)) {
Hologram hologram = linkedHolograms.get(player.getUniqueId());
if (!hologram.isHidden()) {
hologram.hide();
}
}
}
@Override
public void showHolograms(Player player) {
if (hasLinkedHolograms(player)) {
Hologram hologram = linkedHolograms.get(player.getUniqueId());
if (hologram.isHidden()) {
hologram.show();
}
}
}
}
<file_sep>/src/main/java/net/astrocube/puppets/player/PlayerPuppetEntityBuilder.java
package net.astrocube.puppets.player;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import net.astrocube.puppets.entity.ClickAction;
import net.astrocube.puppets.entity.CoreClickAction;
import net.astrocube.puppets.entity.PuppetRegistry;
import net.astrocube.puppets.location.Location;
import net.astrocube.puppets.player.skin.CorePuppetSkin;
import net.astrocube.puppets.player.skin.PuppetSkin;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.MinecraftServer;
import net.minecraft.server.v1_8_R3.PlayerInteractManager;
import net.minecraft.server.v1_8_R3.WorldServer;
import org.apache.commons.lang.RandomStringUtils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_8_R3.CraftServer;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.UUID;
import java.util.function.Consumer;
public class PlayerPuppetEntityBuilder {
private final Plugin plugin;
private final PuppetRegistry registry;
private Location location;
private int followingEntity;
private PuppetSkin skin;
private ClickAction.Type clickType = ClickAction.Type.LEFT;
private Consumer<Player> action = (p) -> {};
public static PlayerPuppetEntityBuilder create(Location location, Plugin plugin, PuppetRegistry registry) {
return new PlayerPuppetEntityBuilder(location, plugin, registry);
}
private PlayerPuppetEntityBuilder(Location location, Plugin plugin, PuppetRegistry registry) {
this.location = location;
this.skin = new CorePuppetSkin("", "");
this.followingEntity = -1;
this.registry = registry;
this.plugin = plugin;
}
public PlayerPuppetEntityBuilder setLocation(Location location) {
this.location = location;
return this;
}
public PlayerPuppetEntityBuilder setClickType(ClickAction.Type clickType) {
this.clickType = clickType;
return this;
}
public PlayerPuppetEntityBuilder setAction(Consumer<Player> action) {
this.action = action;
return this;
}
public PlayerPuppetEntityBuilder setSkin(PuppetSkin skin) {
this.skin = skin;
return this;
}
public PlayerPuppetEntityBuilder setFollowingEntity(int followingEntity) {
this.followingEntity = followingEntity;
return this;
}
public PlayerPuppetEntity build() {
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
World world = Bukkit.getWorld(location.getWorld());
if (world == null) {
throw new IllegalArgumentException("World not found");
}
WorldServer worldHandle = ((CraftWorld) world).getHandle();
GameProfile profile = new GameProfile(UUID.randomUUID(), RandomStringUtils.random(16, "0123456789abcdef"));
profile.getProperties().put("textures", new Property("textures", skin.getTexture(), skin.getSignature()));
EntityPlayer npc = new EntityPlayer(
server,
worldHandle,
profile,
new PlayerInteractManager(worldHandle)
);
PlayerPuppetEntity puppetEntity = new CorePlayerPuppetEntity(
plugin,
location,
new CoreClickAction(clickType, action),
npc,
skin,
followingEntity
);
registry.register(puppetEntity);
return puppetEntity;
}
}
<file_sep>/src/main/java/net/astrocube/puppets/entity/ClickAction.java
package net.astrocube.puppets.entity;
import org.bukkit.entity.Player;
import java.util.function.Consumer;
public interface ClickAction {
/**
* @return click type of the action
*/
Type getType();
/**
* @return action to run.
*/
Consumer<Player> getAction();
enum Type {
LEFT, RIGHT
}
}
<file_sep>/src/main/java/net/astrocube/puppets/hologram/CoreHologram.java
package net.astrocube.puppets.hologram;
import net.astrocube.puppets.location.Location;
import net.minecraft.server.v1_8_R3.*;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CoreHologram implements Hologram {
private final UUID uuid;
private final Location location;
private final List<String> rawLines;
private final List<HologramLine> lines;
private boolean hidden;
public CoreHologram(Player player, Location location, List<String> lines) {
this.uuid = player.getUniqueId();
this.location = location;
this.rawLines = lines;
this.lines = new ArrayList<>();
this.hidden = true;
}
@Override
public Player getLinked() {
return Bukkit.getPlayer(uuid);
}
@Override
public Location getLocation() {
return location;
}
@Override
public void setLine(int place, String line) {
place--;
removeEntity(getLines().get(place));
rawLines.set(place, line);
HologramLine hologramLine = getLines().get(place);
World world = Bukkit.getWorld(location.getWorld());
EntityArmorStand stand = new EntityArmorStand(((CraftWorld) world).getHandle());
stand.setPosition(getLocation().getX(), hologramLine.getY(), getLocation().getZ());
getLines().set(place, new CoreHologramLine(line, stand.getId(), hologramLine.getY()));
stand.setInvisible(true);
stand.setCustomName(rawLines.get(place));
stand.setCustomNameVisible(!rawLines.get(place).isEmpty());
sendPacket(new PacketPlayOutSpawnEntityLiving(stand));
}
@Override
public List<HologramLine> getLines() {
return lines;
}
@Override
public List<String> getRawLines() {
return rawLines;
}
@Override
public boolean isHidden() {
return hidden;
}
@Override
public void show() {
for (int i = 0; i < rawLines.size(); i++) {
World world = Bukkit.getWorld(location.getWorld());
if (world == null) {
throw new IllegalArgumentException("World not found");
}
EntityArmorStand stand = new EntityArmorStand(((CraftWorld) world).getHandle());
stand.setPosition(
getLocation().getX(),
getLocation().getY() + (i * 0.25),
getLocation().getZ()
);
stand.setInvisible(true);
stand.setCustomName(rawLines.get(i));
stand.setCustomNameVisible(!rawLines.get(i).isEmpty());
lines.add(
new CoreHologramLine(
rawLines.get(i),
stand.getId(),
getLocation().getY() + (i * 0.25)
)
);
sendPacket(new PacketPlayOutSpawnEntityLiving(stand));
this.hidden = false;
}
}
@Override
public void hide() {
lines.forEach(this::removeEntity);
lines.clear();
this.hidden = true;
}
private void removeEntity(HologramLine hologramLine) {
sendPacket(new PacketPlayOutEntityDestroy(hologramLine.getEntity()));
}
private void sendPacket(Packet<?> packet) {
((CraftPlayer) getLinked()).getHandle().playerConnection.sendPacket(packet);
}
}
|
30a9e71f269677a1203f75360cdc1cf19f6d82a7
|
[
"Java"
] | 9
|
Java
|
SrBenja007/PuppetsV2
|
e9dc0170821f20a08169d9d88ee61d5766330dd9
|
25ba81567b91842fdd56b3e53ae2115b85c1056a
|
refs/heads/master
|
<file_sep>#!/usr/bin/python3
import datetime
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import sprintstats as ST;
def str2date(datestr):
#print(datestr,datestr[0:4],datestr[4:6],datestr[6:8])
return datetime.date(int(datestr[0:4]), int(datestr[4:6]), int(datestr[6:8]))
def calcDates(sprintST):
startDate = sprintST.startDate;
endDate = sprintST.endDate;
holidayDates = sprintST.festivos;
if startDate == "" or endDate == "":
print("Start or End Date not provided, assumming 2 week sprint starting this week");
no = datetime.datetime.now().date()
startDate = (no-datetime.timedelta(days=no.weekday())).strftime("%Y%m%d");
endDate = (no-datetime.timedelta(days=no.weekday())+datetime.timedelta(days=13)).strftime("%Y%m%d")
holidayDates = []
print("Sprint goes from "+startDate+" to "+endDate)
dates=[];
startd = str2date(startDate)
endd = str2date(endDate)
festd = [str2date(d) for d in holidayDates];
auxd = startd;
while auxd <= endd:
if auxd not in festd and auxd.weekday() < 5:
dates.append(auxd);
auxd = auxd + datetime.timedelta(days=1);
return dates;
def down_linear_regression(n1,n2,ticks):
inc = (n1-n2)/(ticks-1)
regr = [n1-d*inc for d in range(0,ticks)];
#print(n1,n2,ticks,regr)
return regr;
def get_today_index(dates):
now_date = datetime.datetime.now().date()
today_in = -1;
for d in dates:
today_in +=1;
if d == now_date:
break;
if today_in == -1:
print("BAD DATES, assumming first day of sprint")
today_in = 0;
return today_in
def plot_burndown(sprintST,dates,endDay,printAll=True):
today_in = len(dates);
if not endDay:
today_in = get_today_index(dates)
ticks = range(0,len(dates)+1)
tickslabels = [d.strftime("%a %d") for d in dates]+["END"]
total_val = down_linear_regression(sprintST.horasSprint.total, 0, len(dates)+1)
fig, ax = plt.subplots()
ax.plot(total_val,'k-',label="Target (%dh to finish)"% int(total_val[today_in]))
if sprintST.horasSupport.total > 0 and printAll:
total_val_support = down_linear_regression(sprintST.horasSprint.total+sprintST.horasSupport.total, sprintST.horasSupport.total, len(dates)+1)
ax.plot(total_val_support,'r-',label="Target with support (%dh to finish)"% int(total_val_support[today_in]))
not_done_h = sprintST.horasSprint.total-sprintST.horasSprint.doneFinished
not_done_val = down_linear_regression(sprintST.horasSprint.total, not_done_h , today_in+1)
ax.plot(not_done_val,'b-',label="Finished (%dh to finish)"% int(not_done_val[today_in]))
not_done_real_h = sprintST.horasSprint.total - sprintST.horasSprint.doneReal;
not_done_real_val = down_linear_regression(sprintST.horasSprint.total, not_done_real_h , today_in+1)
ax.plot(not_done_real_val,'y--',label="Done (%dh to finish)"% int(not_done_real_val[today_in]))
if sprintST.horasSupport.total > 0:
if printAll:
not_done_sup_h = not_done_h + sprintST.horasSupport.total - sprintST.horasSupport.doneFinished
not_done_sup_val = down_linear_regression(sprintST.horasSprint.total+sprintST.horasSupport.total, not_done_sup_h , today_in+1)
ax.plot(not_done_sup_val,'g-',label="Current with support (%dh to finish)"% int(not_done_sup_val[today_in]))
not_done_without_support_h = sprintST.horasSprint.total-sprintST.horasSprint.doneFinished-sprintST.horasSupport.total
not_done_without_support_val = down_linear_regression(sprintST.horasSprint.total, not_done_without_support_h , today_in+1)
ax.plot(not_done_without_support_val,'b--',label="Finished (prediction if no support) (%dh to finish)"% int(not_done_without_support_val[today_in]))
total_hours_done = sprintST.horasSprint.doneFinished + sprintST.horasSupport.doneFinished;
ax.plot(today_in,total_hours_done,'w',label="Hours done (sprint + support) %dh"%int(total_hours_done))
hours_blocked = sprintST.horasSprint.blockedReal + sprintST.horasSupport.blockedReal;
total_hours_blocked = sprintST.horasSprint.blockedTotal + sprintST.horasSupport.blockedTotal;
ax.plot(today_in,total_hours_done,'w',label="Hours blocked %dh"%int(total_hours_blocked))
#FORMATTINGS
ax.set_xticks(ticks)
ax.set_xticklabels(tickslabels)
ax.axvline(today_in,0,1,color="gray",dashes=[1,1])
plt.xlabel("Sprint Days");
plt.ylabel("Hours");
ax.set_ylim(0,(sprintST.horasSprint.total+sprintST.horasSupport.total)*1.1)
title = sprintST.title+ " ("+ str(int(sprintST.horasSprint.total))+" hours"
if sprintST.horasSupport.total > 0:
title += " and "+str(int(sprintST.horasSupport.total))+ " support hours"
title +=")"
plt.title(title)
plt.legend(loc=3, fontsize=10) # make a legend and place in bottom-right (loc=4)
fig.show()
def plot_pie(horas,labels, ax1,ax2,title):
cs = cm.Set1(np.arange(len(horas))/len(horas))
ax1.pie(horas,startangle=90,colors=cs)
ax1.axis("equal")
cells = []
total = sum(horas);
for i,l in enumerate(labels):
cells.append([str(horas[i])+" h",str(round(horas[i]/total*100.0))+" %"])
ax2.axis("off")
ax2.set_title(title)
tab = ax2.table(cellText=cells,loc="center", cellLoc='center',rowLabels=labels,rowColours=cs,colWidths=[.2]*2)
#tab.set_fontsize(20)
#tab.scale(1.2,1.2)
#plt.tight_layout();
def plot_pies(sprintST):
fig, ((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2);
horas = sprintST.horasSprint
hours = [horas.doneFinished];
hours.append(horas.doneReal-horas.doneFinished);
hours.append(horas.blockedReal);
hours.append(horas.total-horas.doneReal-horas.blockedReal)
labels = ["Finished","In progress","Blocked","Waiting"]
plot_pie(hours,labels, ax11, ax21,"Sprint Hours \n (calculated with percentages)")
# horas = sprintST.horasSprint
# hours = [horas.doneFinished+sprintST.horasSupport.doneFinished];
# hours.append(horas.total-horas.doneFinished-horas.blockedTotal);
# hours.append(horas.blockedTotal);
# plot_pie(hours,labels, ax12, ax22,"Sprint and Support Hours")
def plot_stats(sprintST,endDay):
dates = calcDates(sprintST);
plot_burndown(sprintST,dates,endDay,False);
plot_pies(sprintST)
plt.show()
#plot_burndown_bars(sprintST);
<file_sep>SVG.Button = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('svg'))
this.style('overflow', 'visible')
//this.circle(5).fill("red").cx(0).cy(0)
this.size(BUTTON.size,BUTTON.size)
}
//Inherit from
, inherit: SVG.Container
, extend: {
_build: function() {
this._main_circle = this.circle(BUTTON.size).fill(BUTTON.color1).stroke("black").cx(0).cy(0)
this._circle1 = this.circle(BUTTON.size/4).fill(BUTTON.color2).stroke("black").cx(BUTTON.size/4).cy(0)
this._circle2 = this.circle(BUTTON.size/4).fill(BUTTON.color2).stroke("black").cx(-BUTTON.size/4).cy(0)
return this
},
mark_as_cost: function() {
this._main_circle.attr({"fill-opacity":0}).size(BUTTON.size/2)
this._circle1.size(BUTTON.size/8).cx(BUTTON.size/8).cy(0)
this._circle2.size(BUTTON.size/8).cx(-BUTTON.size/8).cy(0)
return this
}
}
//Add parent method
, construct: {
// Create nested svg document
button: function() {
return this.put(new SVG.Button)._build()
}
}
})<file_sep>#!/usr/bin/python3
import sys
import optparse
import csv
import json
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.dates as mdates
from matplotlib.ticker import FixedLocator
import numpy as np
import datetime
import sprintstats as ST
import csvredmineparser as CRP
import sprintstatsplot as STP
def main(csv_file,startDate,endDate,holidayDates,title,endDay):
sprintST = ST.SprintStats()
sprintST.startDate = startDate
sprintST.endDate = endDate
sprintST.festivos = holidayDates
sprintST.title = title;
sprintST = CRP.load_from_csv(csv_file,sprintST);
print(sprintST.toDict())
STP.plot_stats(sprintST,endDay)
def parse_arguments(argv):
parser = optparse.OptionParser();
parser.add_option("-f","--f",help="Location of csv file",default=None,dest = "filename");
parser.add_option("-s","--start",help="Provide start date of this sprint, format: 20170315",default=None,dest="start")
parser.add_option("-e","--end",help="Provide end date of this sprint,format: 20170315",default=None,dest="end")
parser.add_option("-n","--nowork",help="Provide holidays in this spring,format: 20170315 (multiple can be provided)",action="append",dest="holidays",default=[])
parser.add_option("-t","--title",help="Sprint title",default="Sprint",dest="title")
parser.add_option("-r","--result",help="Indicate today is the end of hte last day, generate the result",dest="endDay",action="store_true",default=False)
options,args = parser.parse_args(argv);
if options.filename is None:
print("Please provide redmine csv file");
parser.print_help();
exit(1);
return options;
if __name__ == "__main__":
options=parse_arguments(sys.argv)
sys.exit(main(options.filename,options.start,options.end,options.holidays,options.title,options.endDay));
<file_sep>SVG.Time = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('svg'))
this.style('overflow', 'visible')
//this.circle(5).fill("red").cx(0).cy(0)
this.size(BUTTON.size,BUTTON.size)
}
//Inherit from
, inherit: SVG.Container
, extend: {
_build: function() {
var s = BUTTON.size/5
var sy = BUTTON.size /5
this.polyline([[0,0],[s,sy],[-s,sy],[0,0],[s,-sy],[-s,-sy],[0,0]])
.stroke("black").fill("none")
return this
},
mark_as_cost: function() {
this._main_circle.attr({"fill-opacity":0})
}
}
//Add parent method
, construct: {
// Create nested svg document
time: function() {
return this.put(new SVG.Time)._build()
}
}
})<file_sep>#!/usr/bin/python3
import sys
import optparse
import buildconf
class bcolors:
HEADER = '\033[95m'
USO = '\033[94m'
OK = '\033[92m'
WARNING = '\033[93m'
KO = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def main(build1,build2):
b1 = buildconf.BuildConf(build1)
b2 = buildconf.BuildConf(build2)
print("Modules in build conf 1 with their correspondent modules of build 2");
for m1 in b1.modules:
m2 = b2.get_module(m1.name)
if m2 is not None:
modifier = "";
text = ""
if m1.version != m2.version or m1.type != m2.type:
modifier = (bcolors.KO)
text = "KO"
else:
modifier = (bcolors.OK)
text = "OK"
print("{}{:<4}{:<30}{:<5}{:<12}{:<5}{:<10}{}".format(modifier,text,m1.name,
m1.type,m1.version,m2.type,m2.version,bcolors.ENDC))
else:
print("{}{:<4}{:<30}{:<5}{:<12}{:<5}{:<10}{}".format(bcolors.KO,"KO",m1.name,
m1.type,m1.version,"--","NOT PRESENT",bcolors.ENDC))
print("Modules in build 2 that were not in build 1")
for m2 in b2.modules:
if not m2.checked:
print("{:<4}{:<30}{:<5}{:<12}{:<5}{:<10}".format("",
m2.name,"","",m2.type,m2.version));
def parse_arguments(argv):
parser = optparse.OptionParser();
parser.add_option("--b1",help="Path to build conf 1",default = None,dest ="build1")
parser.add_option("--b2",help="Path to build conf 2",default = None,dest ="build2")
options,args = parser.parse_args(argv);
if options.build1 is None or options.build2 is None:
print("Please provide both build.conf files");
parser.print_help();
exit(1);
return options;
if __name__ == '__main__':
options = parse_arguments(sys.argv)
main(options.build1,options.build2)
<file_sep>import os
import flask
import flask_wtf
import flask_wtf.file
#from flask import Flask, render_template
import flask_uploads #import UploadSet, configure_uploads, IMAGES, patch_request_class
#from flask_wtf import FlaskForm
#from flask_wtf.file import FileField, FileRequired, FileAllowed
#from wtforms import SubmitField
import wtforms
import frontend.bookform as bookform
import bookanalyzer
app = flask.Flask(__name__)
app.config['SECRET_KEY'] = 'I have a dream'
app.config['UPLOADED_BOOKS_DEST'] = "/tmp/"
books = flask_uploads.UploadSet('books', tuple(["epub"]))
flask_uploads.configure_uploads(app, books)
flask_uploads.patch_request_class(app) # set maximum file size, default is 16MB
class UploadForm(flask_wtf.FlaskForm):
book = flask_wtf.file.FileField(validators=[flask_wtf.file.FileAllowed(books, u'Only .epub files!'), flask_wtf.file.FileRequired(u'File was empty!')])
submit = wtforms.SubmitField(u'Upload')
@app.route('/', methods=['GET', 'POST'])
def upload_file():
form = UploadForm()
file_url = None
file_path= None
if form.validate_on_submit():
filename = books.save(form.book.data)
file_url = books.url(filename)
file_path = books.path(filename)
mybook = bookanalyzer.BookAnalyzer()
res = mybook.get_epub_info(file_path)
print(res)
f_book = bookform.BookForm()
f_book.ftitle.data = res["title"]
f_book.fauthor.data = res["creator"]
return flask.render_template('upload.html', form=form,bookform = f_book, file_url=file_url,file_path=file_path)
if __name__ == '__main__':
app.run()
<file_sep>#!/usr/bin/python3
class HorasInfo:
def __init__(self):
self.total = 0;
self.doneFinished = 0;
self.doneReal = 0;
self.blockedTotal = 0;
self.blockedReal = 0;
self.statesH = {}
self.proyectsH = {}
class SprintStats:
def __init__(self):
self.title = ""
self.startDate = "";
self.endDate = "";
self.festivos = [];
self.horasSprint = HorasInfo();
self.horasSupport = HorasInfo();
def toDict(self):
dD = self.__dict__.copy();
dD["horasSprint"] = self.horasSprint.__dict__;
dD["horasSupport"] = self.horasSupport.__dict__;
return dD;
<file_sep>
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
from wtforms import SubmitField
class BookForm(FlaskForm):
fauthor = StringField("Author",validators=[DataRequired()])
ftitle = StringField("Title",validators=[DataRequired()])
fsubmit = SubmitField(label="Add to DataBase!")
<file_sep>#!/usr/bin/python3
class Module:
def __init__(self):
self.name = ""
self.type = ""
self.version = ""
self.artefactos = [];
self.checked = False;
class BuildConf:
def __init__(self,build_conf_file):
self.modules = [];
self.load_from_buildconf(build_conf_file);
def get_module(self,module_name):
for m in self.modules:
if m.name == module_name:
m.checked = True;
return m;
return None;
def load_from_buildconf(self,buildconffile):
with open(buildconffile) as f:
process_line = False;
for l in f:
if process_line:
line = l.lstrip(" ");
line = line.rstrip("\n");
if len(line) == 0:
continue;
if line[0] == "#":
continue;
if line[0] == ")":
break;
lsplit = line.split(":")
module = Module();
module.type = lsplit[0];
namespli = lsplit[1].split("-")
if len(namespli) == 1:
module.name = namespli[0]
module.version = "0";
elif len(namespli) == 2:
module.name = namespli[0]
module.version = namespli[1]
else:
print("Line:"+line+" has something weird");
if len(lsplit)==3:
module.artefactos = lsplit[2].split(",");
self.modules.append(module);
if "MODULE_LIST" in l:
process_line = True;
continue;
<file_sep>#!/usr/bin/python3
import test1 as saraguapa
print(saraguapa.eleva(3,2));
print("sigueinte")
#math.pow(3,2)
print("sigueinte2")
print(saraguapa.math.pow(3,2))
<file_sep>#!/usr/bin/python
from os import listdir
from os.path import isfile, join
import datetime
import os
import shutil
hourOFF = datetime.timedelta(hours=-8)
mypath = os.getcwd()
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
print onlyfiles
shutil.rmtree("old",ignore_errors=True)
os.mkdir('old')
for fi in onlyfiles:
filesplit = fi.split('.')
if filesplit[-1].lower() == 'jpg':
shutil.copy(fi,'old/'+fi)
imagesplit = filesplit[0].split('_')
if len(imagesplit)==3:
ymd = imagesplit[0]
hms = imagesplit[1]
year = int(ymd[0:4])
month = int(ymd[4:6])
day = int(ymd[6:8])
hour = int(hms[0:2])
minute = int(hms[2:4])
sec = int(hms[4:6])
dateimg = datetime.datetime(year,month,day,hour,minute,sec)
# print dateimg
# print dateimg + hourOFF
dateimg = dateimg + hourOFF
newname = dateimg.strftime('%Y%m%d_%H%M%S')
print newname
os.rename(fi,newname+'.jpg')
#Change Date
<file_sep>SVG.Piece = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('svg'))
this.style('overflow', 'visible')
//this.circle(5).fill("red").cx(0).cy(0)
this.size(10,10)
}
//Inherit from
, inherit: SVG.Container
, extend: {
_build: function(info) {
console.log(info)
this._squares = []
var price_button = info.price_button
for(i=0; i< info.points.length; i++)
{
point = info.points[i]
this._squares.push(this.rect(PIECE.side,PIECE.side)
.fill("white")
.stroke("black")
.x(point.x*PIECE.side)
.y(point.y*PIECE.side))
if(i==0)
{
//COST in BUTTONS
this.text1 = this.text(info.cost_button).fill("black")
.x(point.x*PIECE.side+10)
.y(point.y*PIECE.side+3).attr({"text-anchor":"middle"})
this.button().x(point.x*PIECE.side+PIECE.side/1.6)
.y(point.y*PIECE.side+PIECE.side/4).mark_as_cost().size(BUTTON.size/2,BUTTON.size/2)
//COST in TIME
this.text2 = this.text(info.cost_time).fill("black")
.x(point.x*PIECE.side+10)
.y(point.y*PIECE.side+3+PIECE.side/2).attr({"text-anchor":"middle"})
this.time().x(point.x*PIECE.side+PIECE.side/1.6)
.y(point.y*PIECE.side+PIECE.side*3/4)
}
else
{
if(price_button > 0)
{
this.button().x(point.x*PIECE.side+PIECE.side/2)
.y(point.y*PIECE.side+PIECE.side/2)
price_button--;
}
}
}
if(price_button > 0)
{
console.log("Not all buttons fit!!")
}
this
return this
},
mirror: function(){
this.flip('x')
this.text1.flip('x')
this.text2.flip('x')
return this
}
}
//Add parent method
, construct: {
// Create nested svg document
piece: function(info) {
return this.put(new SVG.Piece)._build(info)
}
}
})<file_sep>#!/usr/bin/python3
v=3
if v <3:
print("HOLA")
p=2
a = 3 if p==2 else 0;
print(a)
<file_sep>#!/usr/bin/python3
import sys
import optparse
import csv
import json
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.dates as mdates
from matplotlib.ticker import FixedLocator
import numpy as np
import datetime
FINISHED_STATES = ["Pte Validacion","Corregida","Resuelta"]
BLOCKED_STATES = ["Bloqueada"]
SUPPORT_TYPES = ["Soporte"]
class HoursInfo:
def __init__(self):
self.hours = {};
self.types = {};
def get_column_indexes(first_row):
col_index = {}
col_index["issue"] = 0;
col_index["state"] = 1
col_index["type"] = 3
col_index["proyect"] = 2
col_index["percentage"] = 12
col_index["hours"] = 13
for index,val in enumerate(first_row):
if val == "#":
col_index["issue"] = index;
elif val == "Estado":
col_index["state"] = index;
elif val == "Proyecto":
col_index["proyect"] = index;
elif val == "Tipo":
col_index["type"] = index;
elif "Realizado" in val:
col_index["percentage"] = index;
elif val == "Tiempo estimado":
col_index["hours"] = index;
return col_index;
def sumvalueindict(dictobj,key,value):
if key in dictobj:
dictobj[key] += value;
else:
dictobj[key] = value;
def fill_stats_from_row(col_index,row,stats):
#print(row[col_index["proyect"]])
hours = float(row[col_index["hours"]].replace(",","."));
percentage = float(row[col_index["percentage"]].replace(",","."))
state = row[col_index["state"]]
typeT = row[col_index["type"]]
proyect = row[col_index["proyect"]]
if ( (state in FINISHED_STATES) and percentage == 100.0 ):
#TASK IS FINISHED
finished = True;
elif ( (state in FINISHED_STATES) or percentage == 100.0 ):
print("Task "+row[col_index["issue"]]+" has inconsistent State ("+state+") and percentage ("+str(percentage)+"), please fix it");
# stats["totalH"] += hours;
# if finished:
# stats["doneH"] += hours;
# if blocked:
# stats["blockedH"] += hours;
sumvalueindict(stats["ProyectsH"],proyect, hours);
sumvalueindict(stats["StatesH"],state, hours);
sumvalueindict(stats["TypesH"],typeT, hours);
def get_sprint_stats(csv_file):
stats={}
stats["ProyectsH"] = {}
stats["StatesH"] = {}
stats["TypesH"] = {}
with open(csv_file,newline='',encoding='latin-1') as f:
reader=csv.reader(f,delimiter=";");
col_index = get_column_indexes(reader.__next__())
for row in reader:
fill_stats_from_row(col_index,row,stats);
stats["HOURS"] = {};
stats["HOURS"]["SPRINT"] = {}
stats["HOURS"]["SPRINT"]["Total"] = sum([m[1] for m in stats["TypesH"].items() if m[0] not in SUPPORT_TYPES])
stats["HOURS"]["SPRINT"]["Done"] = sum([m[1] for m in stats["StatesH"].items() if m[0] in FINISHED_STATES])
stats["HOURS"]["SPRINT"]["Blocked"] = sum([m[1] for m in stats["StatesH"].items() if m[0] in BLOCKED_STATES])
stats["HOURS"]["Support"] = sum([m[1] for m in stats["TypesH"].items() if m[0] in SUPPORT_TYPES])
return stats
def str2date(datestr):
#print(datestr,datestr[0:4],datestr[4:6],datestr[6:8])
return datetime.date(int(datestr[0:4]), int(datestr[4:6]), int(datestr[6:8]))
def get_sprint_dates(startDate,endDate,holidayDates):
if startDate is None or endDate is None:
print("Start or End Date not provided, assumming 2 week sprint starting this week");
no = datetime.datetime.now().date()
startDate = (no-datetime.timedelta(days=no.weekday())).strftime("%Y%m%d");
endDate = (no-datetime.timedelta(days=no.weekday())+datetime.timedelta(days=13)).strftime("%Y%m%d")
holidayDates = []
print("Sprint goes from "+startDate+" to "+endDate)
dates=[];
startd = str2date(startDate)
endd = str2date(endDate)
festd = [str2date(d) for d in holidayDates];
auxd = startd;
while auxd <= endd:
if auxd not in festd and auxd.weekday() < 5:
dates.append(auxd);
auxd = auxd + datetime.timedelta(days=1);
return dates;
def plot_bars(dates,totalh,finh,blockedh,now,title="Sprint"):
today_in = -1;
for d in dates:
today_in +=1;
if d == now.date():
break;
#print(today_in);
hinc = totalh/(len(dates));
ptotalh = [totalh - d*hinc for d in range(0,len(dates)+1)];
#print(len(dates),ptotalh)
hincfin = finh / today_in;
hincblock = blockedh / today_in;
#print(hinc,hincfin)
plefth = [totalh - d*hincfin for d in range(0,today_in+1)];
pfinh = [totalh-p for p in plefth];
pblocked = [d*hincblock for d in range(0,today_in+1)];
fig,ax = plt.subplots()
bar_width = 0.35
index = np.arange(len(pfinh))-bar_width/2;
ax.bar(index,plefth,width=bar_width,color="r");
ax.bar(index,pfinh,width=bar_width,color="b",bottom=plefth);
# index = np.arange(len(pfinh))
# ax.bar(index-bar_width/2,pfinh,width=bar_width,color="r");
# index = np.arange(len(ptotalh))
# ax.bar(index-bar_width/2,ptotalh,width=bar_width,color='b');
ax.plot(ptotalh,'k-',linewidth=2,label="Target (%dh to finish)"% int(ptotalh[today_in]))
ax.set_xticks(range(0,len(dates)+1))
#ax.set_xticklabels(["0"]+[d.strftime("%d %b") for d in dates]) # set the ticklabels to the list of datetimes
ax.set_xticklabels([d.strftime("%a %d") for d in dates]+["END"]) # set the ticklabels to the list of datetimes
plt.tight_layout()
def plot_values(dates,totalh,finh,blockedh,now,title="Sprint"):
today_in = -1;
for d in dates:
today_in +=1;
if d == now.date():
break;
#print(today_in);
hinc = totalh/(len(dates));
ptotalh = [totalh - d*hinc for d in range(0,len(dates)+1)];
#print(len(dates),ptotalh)
hincfin = finh / today_in;
#print(hinc,hincfin)
pfinh = [totalh - d*hincfin for d in range(0,today_in+1)];
#print(hincfin,pfinh)
fig, ax = plt.subplots()
# plot 'ABC' column, using red (r) line and label 'ABC' which is used in the legend
ax.plot(ptotalh,'k-',label="Target (%dh to finish)"% int(ptotalh[today_in]))
ax.plot(pfinh,'b-',label="Current (%dh to finish)"% int(pfinh[today_in]))
ax.set_xticks(range(0,len(dates)+1))
#ax.set_xticklabels(["0"]+[d.strftime("%d %b") for d in dates]) # set the ticklabels to the list of datetimes
ax.set_xticklabels([d.strftime("%a %d") for d in dates]+["END"]) # set the ticklabels to the list of datetimes
#plt.xticks(rotation=30) # rotate the xticklabels by 30 deg
plt.axvline(today_in,0,1,color="gray",dashes=[1,1])
if(pfinh[today_in] > ptotalh[today_in]):
plt.plot((today_in, today_in), (ptotalh[today_in], pfinh[today_in]), 'r-',linewidth=4,solid_capstyle="butt",label="Difference (%dh)" % round(pfinh[today_in]-ptotalh[today_in]));
if blockedh > 0:
plt.plot((today_in, today_in), (pfinh[today_in]-blockedh, pfinh[today_in]), 'y-',linewidth=6,solid_capstyle="butt",label="Blocked (%dh)" % round(blockedh));
else:
plt.plot((today_in, today_in), (pfinh[today_in], ptotalh[today_in]), 'g-',linewidth=4,solid_capstyle="butt",label="We are awesome!!");
ax.legend(loc=1, fontsize=10) # make a legend and place in bottom-right (loc=4)
plt.xlabel("Sprint Days");
plt.ylabel("Hours");
ax.set_ylim(0,max(pfinh)*1.1)
plt.title(title+" (Total %dh)"%totalh)
fig.show()
# plt.plot(ptotald,ptotalh,pfind,pfinh);
# #plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d'))
# plt.gca().xaxis.set_major_locator(FixedLocator())
# plt.show()
# def make_autopct(values):
# def my_autopct(pct):
# total = sum(values)
# val = int(round(pct*total/100.0))
# return '{v:d} ({p:.2f}%)'.format(p=pct,v=val)
# return my_autopct
def plot_sprint_pie(dictData,titlep):
fig,ax = plt.subplots(2,1)
cs = cm.Set1(np.arange(len(dictData))/len(dictData))
data = sorted(dictData.items(), key=lambda x: x[1],reverse = True)
labels = [x[0] for x in data];
values = [x[1] for x in data];
total = sum(values);
cells = []
for i,l in enumerate(labels):
cells.append([str(values[i])+" h",str(round(values[i]/total*100.0))+" %"])
ret = ax[0].pie(values,startangle=90,colors=cs)
#ax[0].title(titlep);
#legend = ax[0].legend(newlabels,bbox_to_anchor=(2.2, 0.5), loc=5, borderaxespad=0.)
ax[0].axis("equal")
ax[0].axis(aspect=2)
ax[1].axis("off")
rowlabels = labels;
ax[1].table(cellText=cells,bbox=[0.25, 0, 0.75, 1], cellLoc='center',rowLabels=rowlabels,rowColours=cs,colWidths=[.2]*2)
fig.show()
def main(csv_file,startDate,endDate,holidayDates,title):
#plt.rcParams['axes.color_cycle'].remove('k')
stats = get_sprint_stats(csv_file);
print(json.dumps(stats,indent=4))
#print(stats)
dates = get_sprint_dates(startDate,endDate,holidayDates);
plot_sprint_pie(stats["ProyectsH"], "Hours by Proyect\n")
plot_sprint_pie(stats["StatesH"], "Hours by Task State\n")
plot_sprint_pie(stats["TypesH"], "Hours by Task Type\n")
plot_values(dates,stats["HOURS"]["SPRINT"]["Total"],stats["HOURS"]["SPRINT"]["Done"],stats["HOURS"]["SPRINT"]["Blocked"],datetime.datetime.now(),title=title)
plot_bars(dates,stats["HOURS"]["SPRINT"]["Total"],stats["HOURS"]["SPRINT"]["Done"],stats["HOURS"]["SPRINT"]["Blocked"],datetime.datetime.now(),title=title)
plt.show()
def parse_arguments(argv):
parser = optparse.OptionParser();
parser.add_option("-f","--f",help="Location of csv file",default=None,dest = "filename");
parser.add_option("-s","--start",help="Provide start date of this sprint, format: 20170315",default=None,dest="start")
parser.add_option("-e","--end",help="Provide end date of this sprint,format: 20170315",default=None,dest="end")
parser.add_option("-n","--nowork",help="Provide holidays in this spring,format: 20170315 (multiple can be provided)",action="append",dest="holidays",default=[])
parser.add_option("-t","--title",help="Sprint title",default="Sprint",dest="title")
options,args = parser.parse_args(argv);
if options.filename is None:
print("Please provide redmine csv file");
parser.print_help();
exit(1);
return options;
if __name__ == "__main__":
options=parse_arguments(sys.argv)
sys.exit(main(options.filename,options.start,options.end,options.holidays,options.title));
<file_sep>#!/usr/bin/python3
import math
def cel2far(cel):
return cel*3/5+18;
def eleva(n1,n2):
print("Elevando "+str(n1)+" a "+str(n2));
return math.pow(n1, n2)
from math import pow
class Persona:
def __init__(self):
self.telefono = 0;
self.direccion = "";
sara = Persona()
sara.direccion ="Mi caaasa"
<file_sep>'''
@author grcanosa
http://github.com/grcanosa
A Path Selection widget for jupyter notebooks.
'''
import os
import ipywidgets as widgets
class PathSelectWidget():
def __init__(self,name=None):
self._path_name = name
self._show_hidden_files = False
self._curr_path = os.getcwd()
self._w_select_path = widgets.Select(options=[".",".."],value=".")
self._w_text_curr_path = widgets.Text(value = self._curr_path)
self._fill_options()
self._w_button_go_current_path = widgets.Button(description="Go to current path!")
self._w_check_hidden_files = widgets.Checkbox(value=False,description="Show Hidden Files")
self._box_widgets()
self._observe_all()
def _observe_all(self):
self._w_select_path.observe(self._on_select,names="value")
self._accordion.observe(self._on_accordion_fold)
self._w_button_go_current_path.on_click(self._on_current_path_click)
self._w_check_hidden_files.observe(self._on_hidden_files_check,names="value")
def _box_widgets(self):
help_menu = widgets.HBox([self._w_button_go_current_path,self._w_check_hidden_files])
vbox1 = widgets.VBox([widgets.Label("Current Path:"),self._w_text_curr_path,help_menu],layout=widgets.Layout(width="60%"))
vbox2 = widgets.VBox([widgets.Label("Select:"),self._w_select_path],layout=widgets.Layout(width="40%"))
self._box = widgets.HBox([vbox1,vbox2])
self._w_text_curr_path.layout.width = "95%"
self._w_select_path.layout.width = "95%"
self._accordion = widgets.Accordion(children = [self._box])
self._accordion.set_title(0,"Path Selection: "+("" if self._path_name is None else self._path_name))
def _fill_options(self):
if os.path.isdir(self._curr_path):
options = [".",".."]
dirs = []
files = []
if self._show_hidden_files:
dirs = [p+"/" for p in os.listdir(self._curr_path) if os.path.isdir(os.path.join(self._curr_path,p))]
files = [p for p in os.listdir(self._curr_path) if not os.path.isdir(os.path.join(self._curr_path,p))]
else:
dirs = [p+"/" for p in os.listdir(self._curr_path) if (os.path.isdir(os.path.join(self._curr_path,p)) and p[0] != ".")]
files = [p for p in os.listdir(self._curr_path) if (not os.path.isdir(os.path.join(self._curr_path,p)) and p[0] != ".")]
dirs.sort()
files.sort()
options = options + dirs + files
self._w_select_path.options = options
else:
self._w_select_path.options=[".",".."]
self._w_select_path.value = '.'
def _set_new_path(self):
self._w_text_curr_path.value = self._curr_path
def _on_select(self,change):
new_val = change["new"]
if new_val == ".":
self._set_new_path()
elif new_val == "..":
self._curr_path = os.path.dirname(os.path.abspath(self._curr_path))
else:
self._curr_path = os.path.join(self._curr_path,new_val)
self._fill_options()
def _on_accordion_fold(self,change):
if change["name"] == "selected_index":
if change["new"] == None:
self._accordion.set_title(0,"Selected path: "+self._curr_path if self._path_name is None else self._path_name+": "+self._curr_path)
else:
self._accordion.set_title(0,"Path Selection: "+("" if self._path_name is None else self._path_name))
def _on_current_path_click(self,change):
self._curr_path = os.getcwd()
self._fill_options()
self._set_new_path()
def _on_hidden_files_check(self,change):
self._show_hidden_files = change["new"]
self._fill_options()
def get_path(self):
return self._curr_path
def get_widget(self):
return self._accordion
class MultiFileSelectionWidget():
def __init__(self,filenames):
self._filenames = filenames
self._create_widgets()
def _create_widgets(self):
self._widgets = [PathSelectWidget(f) for f in self._filenames]
self._vbox = widgets.VBox([w.get_widget() for w in self._widgets])
def get_paths(self):
return {f:p.get_path() for f,p in zip(self._filenames,self._widgets)}
def get_widget(self):
return self._vbox
if __name__ == "__main__":
#TEST
from IPython.display import display
pw = PathSelectWidget("my_file")
display(pw.get_widget())
mf = MultiFileSelectionWidget(["f1","f2"])
display(mf.get_widget())
<file_sep># code-playground
Repo to test out different pieces of code
<file_sep>#!/usr/bin/python3+
import folium
map = folium.Map(location=[40,-3],zoom_start=6,tiles="Mapbox Bright")
fg = folium.FeaursetureGroup(name="My Map")
fg.add_child(folium.Marker(location=[40,-3],popup="lalala",icon=folium.Icon(color="green")))
map.add_child(fg)
map.save("map1.html")
<file_sep>#!/usr/bin/python3
import sys
import json
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import FixedLocator
import datetime
import numpy as np
import optparse
def extract_string(text,tag):
textspli = text.split();
for t in textspli:
if tag in t:
textspli2 = t.split(":");
return textspli2[1];
def extract_strings(text,tag):
vstr = [];
textspli = text.split();
for t in textspli:
if tag in t:
textspli2 = t.split(":");
vstr.append(textspli2[1]);
return vstr;
def extract_number(text,tag):
return float(extract_string(text,tag));
def str2date(datestr):
#print(datestr,datestr[0:4],datestr[4:6],datestr[6:8])
return datetime.date(int(datestr[0:4]), int(datestr[4:6]), int(datestr[6:8]))
def get_sprint_dates(wej):
if "description" not in wej:
print("Field description must be set for the board!!!!")
print("Assumming 2 week sprint with current week as first");
no = datetime.datetime.now().date();
desc = "";
desc += "START:"+(no-datetime.timedelta(days=no.weekday())).strftime("%Y%m%d");
desc += " "
desc += "END:"+(no-datetime.timedelta(days=no.weekday())+datetime.timedelta(days=13)).strftime("%Y%m%d");
wej["description"]= desc
description = wej["description"]
start = extract_string(description, "START");
end = extract_string(description,"END");
festivos = extract_strings(description, "FESTIVO")
print("Sprint goes from "+start+" to "+end)
dates=[];
startd = str2date(start)
endd = str2date(end)
festd = [str2date(d) for d in festivos];
auxd = startd;
while auxd <= endd:
if auxd not in festd and auxd.weekday() < 5:
dates.append(auxd);
auxd = auxd + datetime.timedelta(days=1);
return dates;
def get_card_hours(a):
horas = 0;
if "HORAS:" in a["title"]:
horas = extract_number(a["title"],"HORAS");
if "description" in a and "HORAS:" in a["description"]:
horas = extract_number(a["description"],"HORAS");
if horas == 0:
print("CARD "+a["title"]+" HAS NOT HOURS SET!!!")
return horas;
def get_hours(wej):
total_h = 0;
fin_h = 0;
finListId = 0
for l in wej["lists"]:
if "DONE" in l["title"]:
finListId = l["_id"];
break;
for a in wej["cards"]:
h = get_card_hours(a);
total_h += h;
if a["listId"] == finListId:
fin_h += h;
return total_h,fin_h;
def plot_values(dates,totalh,finh,now,title="Sprint"):
today_in = -1;
for d in dates:
today_in +=1;
if d == now.date():
break;
#print(today_in);
hinc = totalh/(len(dates));
ptotalh = [totalh - d*hinc for d in range(0,len(dates)+1)];
#print(len(dates),ptotalh)
hincfin = finh / today_in;
#print(hinc,hincfin)
pfinh = [totalh - d*hincfin for d in range(0,today_in+1)];
#print(hincfin,pfinh)
fig, ax = plt.subplots()
# plot 'ABC' column, using red (r) line and label 'ABC' which is used in the legend
ax.plot(ptotalh,'k-',label="Target (%d h)"% int(ptotalh[today_in]))
ax.plot(pfinh,'b-',label="Current (%d h)"% int(pfinh[today_in]))
ax.set_xticks(range(0,len(dates)+1))
#ax.set_xticklabels(["0"]+[d.strftime("%d %b") for d in dates]) # set the ticklabels to the list of datetimes
ax.set_xticklabels([d.strftime("%a %d") for d in dates]+["END"]) # set the ticklabels to the list of datetimes
#plt.xticks(rotation=30) # rotate the xticklabels by 30 deg
plt.axvline(today_in,0,1,color="gray",dashes=[1,1])
if(pfinh[today_in] > ptotalh[today_in]):
plt.plot((today_in, today_in), (ptotalh[today_in], pfinh[today_in]), 'r-',linewidth=4,solid_capstyle="butt",label="Difference (%dh)" % round(pfinh[today_in]-ptotalh[today_in]));
else:
plt.plot((today_in, today_in), (pfinh[today_in], ptotalh[today_in]), 'g-',linewidth=4,solid_capstyle="butt",label="We are awesome!!");
ax.legend(loc=1, fontsize=10) # make a legend and place in bottom-right (loc=4)
plt.xlabel("Sprint Days");
plt.ylabel("Hours");
ax.set_ylim(0,max(pfinh)*1.1)
plt.title(title+" (Total %dh)"%totalh)
plt.show()
# plt.plot(ptotald,ptotalh,pfind,pfinh);
# #plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d'))
# plt.gca().xaxis.set_major_locator(FixedLocator())
# plt.show()
def main(wekan_file):
f = open(wekan_file)
wej = json.load(f);
f.close()
dates = get_sprint_dates(wej)
totalh,finh = get_hours(wej);
plot_values(dates,totalh,finh,datetime.datetime.now(),title=wej["title"])
def parse_arguments(argv):
parser = optparse.OptionParser();
parser.add_option("-f","--f",help="Location of wekan file",default=None);
options,args = parser.parse_args(argv);
if options.f is None:
print("Please provide wekan json file");
parser.print_help();
exit(1);
return options.f;
if __name__ == "__main__":
wekan_file = parse_arguments(sys.argv);
sys.exit(main(wekan_file))
<file_sep>#!/usr/bin/python3
import sprintstats as ST;
import csv
FINISHED_STATES = ["Pte Validacion","Corregida","Resuelta"]
BLOCKED_STATES = ["Bloqueada"]
SUPPORT_TYPES = ["Soporte"]
def get_column_indexes(first_row):
col_index = {}
col_index["issue"] = 0;
col_index["state"] = 1
col_index["type"] = 3
col_index["proyect"] = 2
col_index["percentage"] = 12
col_index["hours"] = 13
for index,val in enumerate(first_row):
if val == "#":
col_index["issue"] = index;
elif val == "Estado":
col_index["state"] = index;
elif val == "Proyecto":
col_index["proyect"] = index;
elif val == "Tipo":
col_index["type"] = index;
elif "Realizado" in val:
col_index["percentage"] = index;
elif val == "Tiempo estimado":
col_index["hours"] = index;
return col_index;
def sumvalueindict(dictobj,key,value):
if key in dictobj:
dictobj[key] += value;
else:
dictobj[key] = value;
def fill_hoursinfo_with_data(isue,hours,percentage,state,proyect,hoursinfo):
if ( (percentage == 100) != (state in FINISHED_STATES) ):
print("Task "+str(issue)+" inconsistent state ("+state+") and percentage ("+str(percentage)+"), fix it");
hoursinfo.total += hours;
if state in FINISHED_STATES:
hoursinfo.doneFinished += hours;
elif state in BLOCKED_STATES:
hoursinfo.blockedTotal += hours;
hoursinfo.blockedReal += hours*(1-(percentage/100));
hoursinfo.doneReal += hours * percentage / 100;
sumvalueindict(hoursinfo.proyectsH, proyect, hours)
sumvalueindict(hoursinfo.statesH, state, hours)
def fill_stats_from_row(col_index,row,sprintST):
#print(row[col_index["proyect"]])
issue= row[col_index["issue"]]
hours = float(row[col_index["hours"]].replace(",","."));
percentage = float(row[col_index["percentage"]].replace(",","."))
state = row[col_index["state"]]
typeT = row[col_index["type"]]
proyect = row[col_index["proyect"]]
if typeT in SUPPORT_TYPES:
fill_hoursinfo_with_data(issue, hours, percentage, state, proyect, sprintST.horasSupport)
else:
fill_hoursinfo_with_data(issue, hours, percentage, state, proyect, sprintST.horasSprint)
def load_from_csv(csv_file,sprintST = None):
if sprintST is None:
sprintST = ST.SprintStats();
with open(csv_file,newline='',encoding='latin-1') as f:
reader=csv.reader(f,delimiter=";");
col_index = get_column_indexes(reader.__next__())
for row in reader:
fill_stats_from_row(col_index,row,sprintST);
return sprintST;
<file_sep>#!/bin/bash
./virtual/bin/python3 calibreinsertapp/main.py<file_sep>"""
Book analyzer
"""
class BookAnalyzer:
def __init__(self):
self.filepath=None
self.title = None
self.author = None
def analyze(self,filepath):
<file_sep>#!/bin/bash
REPONAME="grnas"
REPOSSH="root@XXX"
REPOGENDIR="/volume1/backup/gitproyects/"
function addREPO
{
echo "Adding remote REPO $1 in $2"
git remote add $1 $2
}
function remoREPO
{
echo "Removing remote $1"
git remote rm $1
}
function pushREPO
{
echo "Pushing all refs to repo "
expect <<-DONE
set timeout 45
spawn git push --all $REPONAME
expect {
"*?assword:*" {send -- "$1\r";}
}
set timeout -1
expect { eof {send -- "\r"} }
DONE
}
function announceREPO
{
echo "++++++++++++++++++++++++++++++++++"
echo "+ Updating $1 "
echo "++++++++++++++++++++++++++++++++++"
}
read -s -p "Password to $REPOSSH: " MYPASS
echo
#RTPS
cd RTPS_MERGE
announceREPO "RTPS"
addREPO $REPONAME $REPOSSH:$REPOGENDIR"RTPS.git"
pushREPO $MYPASS
remoREPO $REPONAME
<file_sep>"""
Main launcher for calibre app insert
@author <NAME>
@email <EMAIL>
"""
import frontend.frontend as frontend
if __name__ == "__main__":
print("This is a test")
frontend.app.run(debug=True)
|
97a3d2eba3049cbcb2e199f893be9e9148a8776d
|
[
"JavaScript",
"Python",
"Markdown",
"Shell"
] | 24
|
Python
|
grcanosa/code-playground
|
07b602d6a581a75448725920d720285af05c2c33
|
6de43f858de5bd8652ae6fb9b1bf82ab11caa47a
|
refs/heads/master
|
<file_sep>import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
/**
* Translation from virtual machine file to assembly file
* @author Kevin
*/
public class vm {
public static void main(String[] args) throws IOException {
File fileIn = new File(args[0]);
File fileOut;
ArrayList<File> fileContents = new ArrayList<>();
if (args.length != 1){
throw new IllegalArgumentException("Use the format java vm + filename");
}
else if (fileIn.isFile() && !(args[0].endsWith(".vm"))){
throw new IllegalArgumentException("Not the correct file type. Please enter a .vm file or a directory containing .vm files. ");
}
else {
if (fileIn.isFile() && args[0].endsWith(".vm")) {
fileContents.add(fileIn);
String firstPart = args[0].substring(0, args[0].length() - 3);
fileOut = new File(firstPart + ".asm");
}
else
{
fileContents = getFiles(fileIn);
fileOut = new File(fileIn + ".asm");
}
}
// construct CodeWriter to generate code into corresponding output file
CodeWriter codeWriter = new CodeWriter(fileOut);
codeWriter.writeInit();
for (File file : fileContents) {
codeWriter.setFileName(file);
// construct parser to parse VM input files
ParserModule parser = new ParserModule(file);
// read through VM commands in input file, generate assembly code
while (parser.hasMoreCommands()) {
parser.advance();
if (parser.commandType().equals("C_ARITHMETIC")) {
codeWriter.writeArithmetic(parser.arg1());
}
else if (parser.commandType().equals("C_PUSH") || parser.commandType().equals("C_POP")) {
codeWriter.writePushPop(parser.commandType(), parser.arg1(), parser.arg2());
}
else if (parser.commandType().equals("C_LABEL")) {
codeWriter.writeLabel(parser.arg1());
}
else if (parser.commandType().equals("C_GOTO")) {
codeWriter.writeGoto(parser.arg1());
}
else if (parser.commandType().equals("C_IF")) {
codeWriter.writeIf(parser.arg1());
}
else if (parser.commandType().equals("C_FUNCTION")) {
codeWriter.writeFunction(parser.arg1(), parser.arg2());
}
else if (parser.commandType().equals("C_RETURN")) {
codeWriter.writeReturn();
}
else if (parser.commandType().equals("C_CALL")) {
codeWriter.writeCall(parser.arg1(), parser.arg2());
}
}
}
codeWriter.close();
}
// gather all files in the directory argument into an arraylist
public static ArrayList<File> getFiles(File directory) {
File[] fileContents = directory.listFiles();
ArrayList<File> fResults = new ArrayList<>();
if (fileContents != null) {
for (File file : fileContents) {
if (file.getName().endsWith(".vm")) fResults.add(file);
}
}
return fResults;
}
}
|
0b7c60820865d82abb0e0770c6392db9dad5f8a6
|
[
"Java"
] | 1
|
Java
|
k-ly73/VirtualMachine
|
46826eb0f7a08bb5a72a8afecef9b6367150b900
|
0d7f1e4e347e7a7fa9fff013eb2910de0fab4002
|
refs/heads/master
|
<file_sep>// from data.js
var tableData = data;
var selector = "Date"
// YOUR CODE HERE!
//console.log (tableData)
var table_body = d3.select("tbody");
console.log (table_body)
tableData.forEach(function(xyz){
//console.log (xyz);
var added_row = table_body.append("tr");
Object.entries(xyz).forEach(function([key, value]){
//console.log(key, value);
var new_td = added_row.append("td");
new_td.text(value);
})
})
var button = d3.select("#filter-btn");
button.on("click", function() {
table_body.html("");
enter_date_input = d3.select("#ufo-datetime-input")
enter_city_input = d3.select("#ufo-city-input")
enter_state_input = d3.select("#ufo-state-input")
enter_country_input = d3.select("#ufo-country-input")
enter_shape_input = d3.select("#ufo-shape-input")
filter_date_value = enter_date_input.property("value");
console.log(filter_date_value)
filter_city_value = enter_city_input.property("value");
console.log(filter_city_value)
filter_state_value = enter_state_input.property("value");
console.log(filter_state_value)
filter_country_value = enter_country_input.property("value");
console.log(filter_country_value)
filter_shape_value = enter_shape_input.property("value");
console.log(filter_shape_value)
var filteredData = tableData
if (filter_date_value) {filteredData = tableData.filter(data_datetime => data_datetime.datetime == filter_date_value); }
if (filter_city_value) {filteredData = filteredData.filter(data_city => data_city.city == filter_city_value); }
if (filter_state_value) {filteredData = filteredData.filter(data_state => data_state.state == filter_state_value); }
if (filter_country_value) {filteredData = filteredData.filter(data_country => data_country.country == filter_country_value); }
if (filter_shape_value) {filteredData = filteredData.filter(data_shape => data_shape.shape == filter_shape_value); }
//console.log (filteredData);
filteredData.forEach(function(xyz){
//console.log (xyz);
var added_row = table_body.append("tr");
Object.entries(xyz).forEach(function([key, value]){
//console.log(key, value);
var new_td = added_row.append("td");
new_td.text(value);
})
})
})<file_sep>// from data.js
var tableData = data;
// YOUR CODE HERE!
//console.log (tableData)
var table_body = d3.select("tbody");
console.log (table_body)
tableData.forEach(function(xyz){
//console.log (xyz);
var added_row = table_body.append("tr");
Object.entries(xyz).forEach(function([key, value]){
//console.log(key, value);
var new_td = added_row.append("td");
new_td.text(value);
})
})
var button = d3.select("#filter-btn");
button.on("click", function() {
table_body.html("");
enter_date_input = d3.select("input")
filter_value = enter_date_input.property("value");
var filteredData = tableData.filter(data_datetime => data_datetime.datetime == filter_value);
//console.log (filteredData);
filteredData.forEach(function(xyz){
//console.log (xyz);
var added_row = table_body.append("tr");
Object.entries(xyz).forEach(function([key, value]){
//console.log(key, value);
var new_td = added_row.append("td");
new_td.text(value);
})
})
})
|
249f35727b2b015fdcf88351f901d886c6a9b98b
|
[
"JavaScript"
] | 2
|
JavaScript
|
hhamadneh/javascript-challenge
|
59a0602ceedb3f84e01c8ed3cdc7e1c1897f3778
|
8c75bbee9aead838c76c118f60b73b93d27e545e
|
refs/heads/main
|
<file_sep>export default {
getProductsLoading(state) {
return state.productsLoading;
},
getProductsLoadingFailed(state) {
return state.productsLoadingFailed;
},
getFilterPriceFrom(state) {
return state.filterPriceFrom;
},
getFilterPriceTo(state) {
return state.filterPriceTo;
},
getFilterCategory(state) {
return state.filterCategory;
},
getFilterSeasons(state) {
return state.filterSeasons;
},
getFilterMaterials(state) {
return state.filterMaterials;
},
getPage(state) {
return state.page;
},
getProductsPerPage(state) {
return state.productsPerPage;
},
getProductsData(state) {
return state.productsData;
},
getCountProducts(state) {
return state.productsData ? state.productsData.pagination.total : 0
},
getSeasons(state) {
return state.seasons ? state.seasons.items : [];
},
getProductCategories(state) {
return state.productCategories ? state.productCategories.items : []
},
getMaterials(state) {
return state.materials ? state.materials.items : []
}
}<file_sep>import eventBus from '@/eventBus'
export default function(pageName, pageParams) {
eventBus.$emit('gotoPage', pageName, pageParams)
}<file_sep>export default {
updateOrderInfo(state, orderInfo) {
state.orderInfo = orderInfo
},
setDeliveryData(state, value) {
state.deliveryData = value
},
setPayments(state, value) {
state.payments = value
},
}<file_sep>export default {
orderInfo: null,
deliveryData: null,
payments: null,
}<file_sep>/**
* Функция возвращает окончание для множественного числа слова на основании числа и массива окончаний
* param iNumber Integer Число на основе которого нужно сформировать окончание
* param aEndings Array Массив слов или окончаний для чисел (1, 4, 5),
* например ['яблоко', 'яблока', 'яблок']
* return String
*/
export default function getNumEnding(iNumber, aEndings)
{
let sEnding, i;
iNumber = iNumber % 100;
if (iNumber>=11 && iNumber<=19) {
sEnding=aEndings[2];
}
else {
i = iNumber % 10;
switch (i)
{
case (1): sEnding = aEndings[0]; break;
case (2):
case (3):
case (4): sEnding = aEndings[1]; break;
default: sEnding = aEndings[2];
}
}
return sEnding;
}<file_sep>import Vue from "vue"
import Vuex from "vuex"
import catalog from "./modules/catalog/index"
import cart from "./modules/cart/index"
import product from "./modules/product/index"
import order from "./modules/order/index"
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
catalog,
cart,
order,
product
},
})
export default store<file_sep>import axios from 'axios'
import { API_BASE } from '@/config'
export default {
loadCart(context) {
context.commit('updateLoadingStatus', {loading: true, error: false})
axios.get(API_BASE + 'baskets', {
params: { userAccessKey: context.state.userAccessKey }
})
.then(response => {
if (!context.state.userAccessKey) {
localStorage.setItem('userAccessKey', response.data.user.accessKey)
context.commit('updateUserAccessKey', response.data.user.accessKey)
}
context.commit('updateCartProductsData', response.data.items)
context.commit('syncCartProducts')
context.commit('updateLoadingStatus', {loading: false, error: false})
})
.catch((err) => {
console.log(err)
context.commit('updateLoadingStatus', {loading: false, error: true})
})
},
addProductToCart(context, { productId, colorId, sizeId, quantity }) {
return axios.post(API_BASE + 'baskets/products',
{ productId, colorId, sizeId, quantity },
{
params: { userAccessKey: context.state.userAccessKey }
})
.then((response) => {
context.commit('updateCartProductsData', response.data.items)
context.commit('syncCartProducts')
})
},
loadOrderInfo(context, orderId) {
return new Promise((resolve, reject) => {
axios.get(API_BASE + 'orders/'+orderId, {
params: { userAccessKey: context.state.userAccessKey }
})
.then(response => { context.commit('updateOrderInfo', response.data)
resolve()
})
.catch((err) => {
console.log(err)
reject()
})
})
},
updateCartProductAmount(context, { basketItemId, amount }) {
if (amount < 1) return;
context.commit('updateCartProductAmount', { basketItemId, amount })
return new Promise((resolve, reject) => {
axios.put(API_BASE + 'baskets/products',
{ basketItemId: basketItemId, quantity: amount },
{
params: { userAccessKey: context.state.userAccessKey }
})
.then((response) => {
context.commit('updateCartProductsData', response.data.items)
resolve()
})
.catch((err) => {
console.log(err)
context.commit('syncCartProducts')
reject()
})
})
},
removeCartProduct(context, basketItemId) {
context.commit('deleteCartProduct', basketItemId)
return new Promise((resolve, reject) => {
axios.delete(API_BASE + 'baskets/products', {
params: {
userAccessKey: context.state.userAccessKey
},
data: {
basketItemId: basketItemId
}
})
.then((response) => {
context.commit('updateCartProductsData', response.data.items)
resolve()
})
.catch((err) => {
console.log(err)
context.commit('syncCartProducts')
reject()
})
})
},
}<file_sep>export default {
resetCart(state) {
state.cartProducts = []
state.cartProductsData = []
},
updateCartProductAmount(state, {basketItemId, amount}) {
let item = state.cartProducts.find(item => item.basketItemId === basketItemId)
if (item) {
item.amount = amount
}
},
deleteCartProduct(state, basketItemId) {
state.cartProducts = state.cartProducts.filter(item => item.basketItemId !== basketItemId)
},
updateUserAccessKey(state, accessKey) {
state.userAccessKey = accessKey
},
updateCartProductsData(state, items) {
state.cartProductsData = items
},
syncCartProducts(state) {
state.cartProducts = state.cartProductsData.map( item => {
return {
productId: item.product.id,
amount: item.quantity,
basketItemId: item.id
}
})
},
updateLoadingStatus(state, {loading, error}) {
state.cartLoading = loading
state.cartLoadingError = error
},
}<file_sep>export default {
setProductsLoading(state, value) {
state.productsLoading = value;
},
setProductsLoadingFailed(state, value) {
state.productsLoadingFailed = value;
},
setFilterPriceFrom(state, value) {
state.filterPriceFrom = value;
},
setFilterPriceTo(state, value) {
state.filterPriceTo = value;
},
setFilterCategory(state, value) {
state.filterCategory = value;
},
setFilterSeasons(state, value) {
state.filterSeasons = value;
},
setFilterMaterials(state, value) {
state.filterMaterials = value;
},
setPage(state, value) {
state.page = value;
},
setProductsData(state, value) {
state.productsData = value;
},
setSeasons(state, value) {
state.seasons = value;
},
setProductCategories(state, value) {
state.productCategories = value
},
setMaterials(state, value) {
state.materials = value
},
}<file_sep>export default {
setProductData(state, value) {
state.productData = value
},
setProductLoading(state, value) {
state.productLoading = value
},
setProductLoadingFailed(state, value) {
state.productLoadingFailed = value
},
setProductAdded(state, value) {
state.productAdded = value
},
setProductAddSending(state, value) {
state.productAddSending = value
},
}<file_sep>export default {
getCartLoading(state) {
return state.cartLoading
},
getCartLoadingError(state) {
return state.cartLoadingError
},
getCartProducts(state) {
return state.cartProducts
},
cartDetailProducts(state) {
return state.cartProducts.map(item => {
const product = state.cartProductsData.find(p => p.id === item.basketItemId)
return {
...item,
product: {
...product,
},
positionCost: product.product.price * item.amount,
}
})
},
cartTotalPrice(state, getters) {
return getters.cartDetailProducts.reduce((acc, item) => acc+= item.amount * item.product.price, 0)
},
cartPositionsCount(state) {
return state.cartProducts.length
},
getUserAccessKey(state) {
return state.userAccessKey || localStorage.getItem('userAccessKey')
},
}<file_sep>export default {
productData: null,
productLoading: false,
productLoadingFailed: false,
productAdded: false,
productAddSending: false,
}<file_sep>import axios from 'axios'
import { API_BASE } from '@/config'
export default {
loadProduct(context, productId) {
context.commit('setProductLoading', true)
context.commit('setProductLoadingFailed', false)
axios.get(API_BASE + 'products/' + productId)
.then(response => context.commit('setProductData', response.data))
.catch((err) => {
console.log(err)
context.commit('setProductLoadingFailed', true)
if (err.request.status === "404") {
this.$router.replace({name: 'notFound', params: { '0': '/' }})
}
})
.finally(() => context.commit('setProductLoading', false))
},
}<file_sep>import AppFormField from '@/components/App/AppFormField.vue'
export default {
props: ['title', 'error', 'placeholder', 'value'],
components: {AppFormField},
computed: {
dataValue: {
get() {
return this.value
},
set(value) {
this.$emit('input', value)
}
},
},
}<file_sep>export default {
cartProducts: [],
userAccessKey: null,
cartProductsData: [],
cartLoading: false,
cartLoadingError: false,
}
|
d9b5279351b8f46313a0258698ed2d52ab96a79a
|
[
"JavaScript"
] | 15
|
JavaScript
|
wisd-arh/moire
|
3fe9c9b9d42e70c0c5b81980c9f1d2f2d7ad077a
|
33a87c7198dd015f35a55d5c378cbcee780d0c8c
|
refs/heads/master
|
<repo_name>Jonny-Smith-GitHub/web_demo<file_sep>/demo/models.py
from django.db import models
from django.contrib import admin
# Create your models here.
class Post(models.Model):
title =models.CharField(max_length=100)
body=models.TextField();
timeStamp=models.DateTimeField();
autoor=models.CharField(max_length=30)
admin.site.register(Post)
|
3f83aed5da4570b0aa904bd9a75d3899d14d1262
|
[
"Python"
] | 1
|
Python
|
Jonny-Smith-GitHub/web_demo
|
95aa6d5f692c43bfdd3fe795dc0ea7dd047a36d6
|
46f47348b856c8cb3164436c450737835c6ad69d
|
refs/heads/main
|
<repo_name>NazrulChowdhury/orangeHRM<file_sep>/cypress/page.modules/login.js
export function login(userName,password){
cy.get('#txtUsername').type(userName)
cy.get('#txtPassword').type(<PASSWORD>)
cy.get('#btnLogin').click()
}<file_sep>/README.md
# orangeHrm
A UI automation e2e test using Cypress of the project: https://opensource-demo.orangehrmlive.com/<file_sep>/cypress/support/commands.js
import 'cypress-file-upload';
Cypress.Commands.add('login',(user)=>{
cy.get('#txtUsername').type(user.userName)
cy.get('#txtPassword').type(<PASSWORD>.<PASSWORD>)
cy.get('#btnLogin').click()
cy.title().should('eq','OrangeHRM')
cy.get('.box').find('.head').contains('Dashboard')
cy.get('#btnLogin').should('not.exist')
})
<file_sep>/cypress/integration/login.spec.js
import user from "../fixtures/user.json"
import * as loginPage from "../page.modules/login.js"
describe('log in test', ()=>{
beforeEach(()=>{
cy.visit('/')
})
it('log in attempt fails with wrong username',()=>{
loginPage.login(user.wrongName, user.password)
cy.get('#spanMessage').should('have.text','Invalid credentials')
cy.url().should('include','/validateCredentials')
})
it('log in attempt fails with wrong password',()=>{
loginPage.login(user.userName, user.wrongPassword)
cy.get('#spanMessage').should('have.text','Invalid credentials')
cy.url().should('include','/validateCredentials')
})
it('Successfully log in with correct credentials', ()=>{
cy.login(user)
})
})
|
ccf279bd32a9609e7dfd37c7d4306d6cb95d0c3c
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
NazrulChowdhury/orangeHRM
|
356769fa0aae1125200c64b6ae9f0a802b8ddf81
|
35d7fa1bacb30b230d97501d3cd0fa7d1ec628a4
|
refs/heads/master
|
<file_sep>===================
UCoreProcessMonitor
===================
Introduction
============
The UCoreProcessMonitor can track the Init, Switch and Exit behaviour of a UCore Process.
How it works?
=============
Catch Signal: CallFunc
----------------------
The CallFunc signal is emitted by the UCoreFunctionMonitor Plugin.
It will retrieve the pc of the call target from the S2EExecutionState and search it in the Addr2Sym map provided by the UCoreUtils.
Then run the different functions according to the retrieved function name.
Note: the *pc* in the argument is the address of the call instruction, not the target of call instruction.
Process Init
------------
Track the *proc_init* function. Retrieve the inited proc PCB from the argument list and call parseUCorePCB function in UCoreUtils.
Process Switch
--------------
Track the *proc_run* function.
Retrieve the previous and next PCB from the *current* global variable and argument list, respectively. Then parse UCorePCB and emit the signal.
Process Exit
------------
Track the *do_exit* function.
Retrieve the target PCB from the global variable *current* and call pareUCorePCB.
<file_sep>===================
QEMUMonitorEnhancer
===================
I provide the QEMU Monitor enhancement feature to help the debug of UCore.
Introduction
============
QEMU Emulator has an useful monitor mode, which can display the value of registers, the memory and so on. I enhanced this monitor and now it can print all processes the UCore has. I name the command print_all_threads.
You can redirect the monitor to stdio by adding the *-monitor stdio* flag into QEMU/S2E command line.
How To Do this?
===============
For S2E version 1.2, it is based on QEMU v1.0.
Follow the instructions below and you can customize your own QEMU monitor enhancer.
1. In *hmp.h*, declare your own enhance function.
2. In *hmp.c*, define the function and call the related function in S2E.
3. In *hmp-commands.hx*, write your own command instructions for the enhancer..
4. In *QEMUMonitorEnhancer.h*, declare the functions called in *hmp.c*.
5. In *UCoreProcessMonitor.h*, include the *QEMUMonitorEnhancer.h* as *extern "C"* and implement the function declared in the *QEMUMonitorEnhancer.h*.
6. Run *Make* and check if the command successeded in the monitor.
<file_sep>=======================
The S2E Tools For UCore
=======================
.. contents::
Welcome to visit the documentation for UCore Tool S2E
If you have any questions, feel free to email to: <EMAIL>
Online Reference
================
* Web Page Reference
1. `Official S2E Documentation <https://s2e.epfl.ch/embedded/s2e/>`_
2. `Nuk's Wiki Page in OS Course, 2012 <http://os.cs.tsinghua.edu.cn/oscourse/OS2012/projects/U03>`_
* Source Code
1. `Project UCore Tool S2E <https://github.com/chyyuu/ucore_tool_s2e>`_
2. `S2E Version1.2 <https://s2e.epfl.ch/attachments/download/209/s2e-source-1.2-27.04.2012.tar.bz2>`_
Plugin Documentation
====================
UCoreFunctionMonitor
--------------------
`UCoreFunctionMonitor <UCoreFunctionMonitor.rst>`_ is the basic plugin monitoring the Function of UCore OS.
It has the following functionalities.
* Monitor the calling of the functions.(Speed: Quick)
* Monitor the calling and returning behavious of the specific function.(Speed: Slow)
* Print the specific function detail using Stab information.
UCoreProcessMonitor
--------------------
`UCoreProcessMonitor <UCoreProcessMonitor.rst>`_ is another plugin works based on the UCoreMonitor.
It monitors the process switching behaviour of UCore OS.
It has the following functionalities.
* Monitor the Process Switching behavious of UCore.
* Retrieve the UCorePCB struct to get detail of a specific process.
* List all processes exists in the running kernel.
UCoreStruct
-----------
`UCoreStruct <UCoreUtils.rst>`_ is the abstract layer of UCore data structures in S2E.
It defines the following data structures.
* UCoreInst: including the source code file location, function entry and line number info.
* UCorePCB: including the process's pid, name and state info.
* UCoreStab: including an item in the Stab debug information list.
UCoreUtils
----------
`UCoreUtils <UCoreUtils.rst>`_ is a series of meta functions used in all plugins.
It includes following functions.
* Parse UCoreStab Segment to get debug information.
* Parse UCorePCB object from the given address.
* Parse UCoreInst object based on the given address and the UCore Stab debug information.
* Parse the Symbol Table to add symbol-address map support.
QEMUMonitorEnhancer
-------------------
`QEMUMonitorEnhancer <QEMUMonitorEnhancer.rst>`_ is a plugin supporting the enhance of QEMU monitor.
It now supports the following commands.
* print_all_threads: Print detail of all running threads in UCore and indicate the current one.
UCoreMemoryManagement
---------------------
`UCoreMemoryManagement <UCoreMemoryManagement.rst>`_ is a plugin monitoring the UCore memory usage. It needs UCoreMonitor to work.
It has the following functionalities.
* Monitor the page allocate and free behaviours.
* Print the page table and memory map.
<file_sep>========================
UCoreUtils & UCoreStruct
========================
UCoreUtils provides miscellaneous functions used in other Plugins.
UCoreStruct defines the UCore OS-level data structures needed in the Plugins.
Introduction
============
We need many meta information to parse the UCore OS data structure.
Up to now, UCore Utils supports the following features.
* Parse the detail of an instruction based on its address.
* Parse the detail of a PCB based on its address.
To implement these two functions, we need to do a lot of work, including:
* Parse the Symbol Table and provide the map between Kernel Address and the Symbol String.
* Parse the Stab debug segment in the Kernel ELF file.
* Hard Code the UCorePCB structure size and offset.
How UCoreUtils Works?
=====================
Parse Symbol Table
------------------
Symbol Table is the mose fundamental thing in this series of plugin. The file actually looks like this.
::
#Symbol Name #Address
kern_init c1000000
This file is created by the *sed*, *objdump* tool and the kernel ELF image. You can refer the UCore Lab Makefile to see how it is created.
In *config.lua*, the location of the symbol table file is specified and UCoreUtils read the file when the S2E is initialized.
Finally the Symbol Table is stored into the memory as two *std::map* variables. One is the Addr2Sym map, and the other is Sym2Addr map.
Parse Stab Segment
------------------
*Stabs* is a kind of debug format from FreeBSD. Here is the `reference <http://docs.freebsd.org/info/stabs/stabs.pdf>`_ if you want to dig into it.
In UCore, we also provides the Stabs Segment to help debug by adding *-g* flag in the gcc compiler. These debug information are used when the *debug_monitor* function is called.
In S2E, we can also parse the Stabs Segment. Firstly we have to read this segment into memory and store them as UCoreStab Array. Then we can do the binary search and find the needed item when we want to parse the detailed information of a instruction. The only thing we need is the value in *EIP* register when we encountered the target instruction.
Parse UCorePCB
--------------
It is a little complex this time, I will discuss different situations.
1. Process Init
The address of the target PCB can be found in the argument of the target function *set_proc_name*.
Get the address, then parse the PCB according to the PCB_SIZE and field offsets provided by the UCoreUtils.
2. Process Switch
We need to parse two UCorePCB this time, the previous PCB and the next PCB, respectively.
For the previous UCorePCB, read the address from the global variable *current* and parse the UCorePCB.
For the next UCorePCB, read the address from the argument.
3. Process Exit
We can still use *current* variable to parse UCorePCB because we always track the call of the *do_exit* function.
Parse UCoreInst
---------------
Read the loaded Stabs segment and do the binary search to find the instruction information.
Finally we will create an UCoreInst object and fill it with debug information.
You should be quite familiar to these things if you do the UCore Lab1.
How UCoreStruct Works?
======================
Define UCoreInst
----------------
Just provides struct UCoreInst, including the instruction information parsed from Stabs segment.
Define UCorePCB
---------------
Hard code the essential field offsets and the size of UCore Process Control Block.
Furthermore, provides the UCorePCB struct to provide more detailed Process information.
Define UCoreStab
----------------
We need to accuratly define the size of the Stabs item. The size is defined in UCoreStruct.h.
Now it just copies the definition of Stabs segment item in UCore.
Note that we still need to copy many *define* macros in UCore header file to use the Stabs debug information.
<file_sep>-- config.lua
s2e = {
kleeArgs = {
-- Whatever options you like
}
}
plugins = {
"BaseInstructions",
"UCoreMonitor",
"UCoreMemoryManagement"
}
pluginsConfig = {
}
pluginsConfig.BaseInstructions = {
}
pluginsConfig.UCoreMonitor = {
kernelBase = 0xc0100000,
kernelEnd = 0xc01000ff,
MonitorFunction = true,
system_map_file = "/home/fwl/ucore/ucore_tool_s2e/build/lab8/obj/kernel.sym"
}
pluginsConfig.UCoreMemoryManagement = {
print_pgdir_pc = 0xc010008f
}
<file_sep>====================
UCoreFunctionMonitor
====================
UCoreFunctionMonitor is the plugin monitoring the behaviour of UCore Function Calls.
Introduction
============
The UCoreFunctionMonitor has two modes: Fast-mode(default) and Slow-mode.
In Fast-mode, I only catch the X86 *Call* instructions and get the function name from the System Map provided by the UCoreUtils.
In Slow-mode, I use the S2E provided FunctionMonitor Plugin to monitor a function whose name is specified by the *config.lua*. In this mode we can track both the call and the return behaviour of the function. However, this method could be quite slow. So I cannot use it to track all functions like Fast-mode.
The slow-mode can only be used when you want to track a specific function.
How It Works?
=============
Fast-mode
---------
In the Fast-mode I catch the onTranslateBlockEnd signal and check if there is a *Call* instruction at the end of the TranslateBlock. If so, emit a FunCall signal which provides the *S2EExecutionState* pointer and *pc* value.
In this mode, we only track the calling of all functions in UCore.
Slow-mode
---------
In this mode I use the FunctionMonitor plugin. For its usage, please refer to: `Function Monitor Reference <https://s2e.epfl.ch/embedded/s2e/Plugins/FunctionMonitor.html>`_
In this mode, we only track the calling and returning of a specific function in UCore.
<file_sep># Tutorial for ucore_tool_s2e
## Required Packages
$ sudo apt-get install build-essential
$ sudo apt-get install subversion
$ sudo apt-get install git
$ sudo apt-get install qemu
$ sudo apt-get install liblua5.1-dev
$ sudo apt-get install libsigc++-2.0-dev
$ sudo apt-get install binutils-dev
$ sudo apt-get install python-docutils
$ sudo apt-get install python-pygments
$ sudo apt-get install nasm
$ sudo apt-get build-dep llvm-2.7
$ sudo apt-get build-dep qemu
## How to compile
Run the following commands under Linux.
$ git clone https://github.com/chyyuu/ucore_tool_s2e.git
$ cd ucore_tool_s2e
$ mkdir build
$ cd build
$ ln -s ../s2e/Makefile .
$ make
Have some coffee and wait for the finish of the compilation.
## Directory Tree
Here is the code directory tree of my s2e project.
ucore_tool_s2e/
| ./s2e // source code
| ./build // binary
| ./test // test dir
| ----./test/lab4 // ucore OS being tested
| ./doc // documentation
| ./wiki // wiki
| ./config // config files
## How to solve compile errors
* MiniSat/Solve error
Just run "make" command again.
$ make
* SDL error
Modify the files' contents like:
include <SDL.h>
to
include <SDL/SDL.h>
* unable to open UCoreMonitor.d/.o
Run the following commands under ucore_tool_s2e directory,
$ mkdir UCoreInterceptor
then run "make" command under ucore_tool_s2e/build directory.
$ make
## modify ucore's Makefile
* Find the line start with "QEMUOPTS",
QEMUOPTS = -hda $(UCOREIMG) -drive file=$(SWAPIMG),media=disk,cache=writeback -drive file=$(SFSIMG),media=disk,cache=writeback
.PHONY: qemu qemu-nox debug debug-nox monitor
qemu: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(QEMU) -parallel stdio $(QEMUOPTS) -serial null
qemu-nox: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(QEMU) -serial mon:stdio $(QEMUOPTS) -nographic
monitor: $(UCOREIMG) $(SWAPING) $(SFSIMG)
$(V)$(QEMU) -monitor stdio $(QEMUOPTS) -serial null
* Copy these lines like the follow ones and use your_own_path in "S2E" and "-s2e-config-file".
S2E := /home/fwl/ucore/ucore_tool_s2e/build/qemu-release/i386-s2e-softmmu/qemu-system-i386
S2EOPTS = -hda $(UCOREIMG) -drive file=$(SWAPIMG),media=disk,cache=writeback -drive file=$(SFSIMG),media=disk,cache=writeback \
-s2e-config-file /home/fwl/ucore/ucore_tool_s2e/config/ucoreconfig.lua -s2e-verbose
s2e: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(S2E) -parallel stdio $(S2EOPTS) -serial null
QEMUOPTS = -hda $(UCOREIMG) -drive file=$(SWAPIMG),media=disk,cache=writeback -drive file=$(SFSIMG),media=disk,cache=writeback
.PHONY: qemu qemu-nox debug debug-nox monitor
qemu: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(QEMU) -parallel stdio $(QEMUOPTS) -serial null
qemu-nox: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(QEMU) -serial mon:stdio $(QEMUOPTS) -nographic
monitor: $(UCOREIMG) $(SWAPING) $(SFSIMG)
$(V)$(QEMU) -monitor stdio $(QEMUOPTS) -serial null
* Copy these lines like the follow ones and use your_own_path in "S2E" and "-s2e-config-file".
S2E := /home/fwl/ucore/ucore_tool_s2e/build/qemu-release/i386-s2e-softmmu/qemu-system-i386
S2EOPTS = -hda $(UCOREIMG) -drive file=$(SWAPIMG),media=disk,cache=writeback -drive file=$(SFSIMG),media=disk,cache=writeback \
-s2e-config-file /home/fwl/ucore/ucore_tool_s2e/config/ucoreconfig.lua -s2e-verbose
s2e: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(S2E) -parallel stdio $(S2EOPTS) -serial null
* Copy these lines like the follow ones and use your_own_path in "S2E" and "-s2e-config-file".
S2E := /home/fwl/ucore/ucore_tool_s2e/build/qemu-release/i386-s2e-softmmu/qemu-system-i386
S2EOPTS = -hda $(UCOREIMG) -drive file=$(SWAPIMG),media=disk,cache=writeback -drive file=$(SFSIMG),media=disk,cache=writeback \
-s2e-config-file /home/fwl/ucore/ucore_tool_s2e/config/ucoreconfig.lua -s2e-verbose
s2e: $(UCOREIMG) $(SWAPIMG) $(SFSIMG)
$(V)$(S2E) -parallel stdio $(S2EOPTS) -serial null
## modify s2e config file
Ucore_tool_s2e use the file "kernel.sym" which is compiled from ucore.
* Make ucore lab(suppose the directory tree as default),
$ cd test/lab4
$ make
then you have "kernel.sym" file in the "obj" directory.
* Modify the path with your_own_path in config file,
## Use ucore_tool_s2e
Run the following commands under ucore_tool_s2e directory.
$ cd test/lab4
$ make s2e
The output files will be in "s2e-last" directory.
|
ebd533632bd466b72c5bd79c1beff66d21573fc6
|
[
"Markdown",
"reStructuredText",
"Lua"
] | 7
|
reStructuredText
|
iurnah/ucore_tool_s2e
|
000b4af75cea8bba4d0f7076ab7b58d40c88adad
|
4ebebd4c44dda3511e54fe2fb27001dd7f18c458
|
refs/heads/master
|
<repo_name>syedimam0012/miscBash<file_sep>/ecrAuditor.sh
#!/bin/bash
# Prerequisite
# - [Download and Install `jq`](https://stedolan.github.io/jq/download/) for your environment
# Run `./ecsAuditor` and wait, which will return three files
# 1. all.txt 2. stacked.txt 3. orphaned.txt
# See `README.md` for more details
# Setting up `$ENVIRONMENT` variables
export AWS_DEFAULT_PROFILE='<profile-name>'
export AWS_DEFAULT_REGION='<region-name>'
# List all ECR repos
ALL_ECR_REPOS=$(aws ecr describe-repositories | jq -r '.repositories[].repositoryName')
printf %s\\n $ALL_ECR_REPOS >> all.txt
# List ECR repos under CloudFormation Stacks
STACK_LIST=$(aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE | jq -r '.StackSummaries[].StackName')
for STACK_NAME in $STACK_LIST;
do
RESOURCE_TYPE=$(aws cloudformation list-stack-resources --stack-name $STACK_NAME | jq -r '.StackResourceSummaries[].ResourceType')
if [ "$RESOURCE_TYPE" = 'AWS::ECR::Repository' ];
then
STACKED_ECR_REPOS=$(aws cloudformation list-stack-resources --stack-name $STACK_NAME | jq -r '.StackResourceSummaries[].PhysicalResourceId')
echo $STACKED_ECR_REPOS >> stacked.txt
fi
done
# Find the orphaned repos
sort stacked.txt all.txt | uniq -u >> orphaned.txt<file_sep>/README.md
# miscBash
Contains multipurpose miscellaneous bash scripts
## 1. `ecrAuditor.sh`
Your AWS environment is fully automated via some kind of infra as a code solution or direct `CloudFormation` template. You want to audit your AWS ECR repos every now and then to check repos created outside the pipeline/infra-automation and advise the developers.
### 1.1 Pre-requisite
- Set up your `AWS` environment using `aws configure` or follow [this](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html)
- [Download and Install `jq`](https://stedolan.github.io/jq/download/) for your environment
### 1.2 How To
Run `./ecrAuditor.sh`. This will create 3 files in `.` directory.
- `all.txt` : contains all repos
- `stacked.txt` : contains all repos create via infras-automation/CloudFormation
- `orphaned.txt` : `diff` between above two, which is the list of manually created ecr
|
0b5a8600dd6a27cdc5d933e71b7cf1c723336a97
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
syedimam0012/miscBash
|
e8f70871bd77793d4c5e4f08a0d3d0111e5e1ade
|
4b2f758773402457d6dd903aff3bd58bec1cd012
|
refs/heads/master
|
<repo_name>ecinoshuta/graph-dan-PTB<file_sep>/ptb.cpp
/* Implementasi PTB (BST) */
#include <iostream>
#include <malloc.h>
#define true 1
#define false 0
using std::cout;
using std::cin;
typedef int typeinfo;
typedef struct typenode *typeptr;
struct typenode{typeinfo info;
typeptr kiri, kanan;
};
typeptr akar,p,b;
int NH;
void buat_ptb();
int ptb_kosong();
void sisipnode(typeinfo IB);
void cetak();
void preorder(typeptr akar);
void inorder(typeptr akar);
void postorder(typeptr akar);
void hapusnode(typeinfo IH);
void hapus();
int main()
{
buat_ptb();
sisipnode(40);
sisipnode(10);
sisipnode(5);
sisipnode(20);
sisipnode(15);
sisipnode(25);
sisipnode(35);
sisipnode(45);
sisipnode(30);
sisipnode(70);
sisipnode(50);
cetak();
cout << "\n\nNode yg dihapus harus terdapat pada PTB!";
cout << "\n\nMasukkan node yg dihapus : ";
cin >> NH;
hapusnode(NH);
cetak();
return 0;
}
void buat_ptb()
{ typeptr ptb;
ptb=NULL;
akar=ptb; }
int ptb_kosong()
{ if(akar==NULL)
return(true);
else
return(false); }
void sisipnode(typeinfo IB)
{ typeptr NB;
NB=(typenode *) malloc(sizeof(typenode));
NB->info=IB;
NB->kiri=NULL;
NB->kanan=NULL;
if (ptb_kosong())
akar=NB;
else
{ b=akar;
p=akar;
// mencari tempat untuk menyisipkan node
while(p!=NULL && IB!=b->info)
{ b=p;
if (IB<p->info)
p=b->kiri;
else
p=b->kanan; }
if (IB==b->info)
cout << "\n\nNode " << IB << " sudah ada !\n\n";
else
{ if (IB<b->info)
b->kiri=NB;
else
b->kanan=NB; }
}
}
void cetak()
{
cout << "\nPre-order : ";
preorder(akar);
cout << "\nIn-order : ";
inorder(akar);
cout << "\nPost-order: ";
postorder(akar);
return;
}
void preorder(typeptr akar)
{ if (akar!=NULL)
{ cout << " " << akar->info;
preorder(akar->kiri);
preorder(akar->kanan); }
}
void inorder(typeptr akar)
{ if (akar!=NULL)
{ inorder(akar->kiri);
cout << " " << akar->info;
inorder(akar->kanan); }
}
void postorder(typeptr akar)
{ if (akar!=NULL)
{ postorder(akar->kiri);
postorder(akar->kanan);
cout << " " << akar->info; }
}
void hapusnode(typeinfo IH)
{
if (ptb_kosong())
cout << "PTB Kosong !\n\n";
else
{ b=akar;
p=akar;
// mencari tempat hapus node
while(p!=NULL && IH!=p->info)
{ b=p;
if (IH<p->info)
p=b->kiri;
else
p=b->kanan; }
}
hapus();
}
void hapus()
{ typeptr temp;
// Bila PTB terdiri dari akar saja atau akar dengan 1 anak kiri/kanan
if (p->kiri==NULL && p->kanan==NULL)
{
if (b==akar && p==akar)
akar=NULL;
else
{
if (p==b->kiri)
b->kiri=NULL;
else
b->kanan=NULL;
}
free(p);
}
// Bila PTB memiliki anak kiri dan anak kanan dgn banyak anak cabang
else if (p->kiri!=NULL && p->kanan!=NULL)
{
temp=p->kiri;
b=p;
while (temp->kanan != NULL)
{ b=temp;
temp=temp->kanan; }
p->info=temp->info;
if (b==p)
b->kiri = temp->kiri;
else
b->kanan = temp->kiri;
free(temp);
}
// Bila PTB memiliki anak kiri saja dgn banyak anak cabang
else if (p->kiri!=NULL && p->kanan==NULL)
{
if (b==p)
akar=p->kiri;
else
{ if (p==b->kiri)
b->kiri=p->kiri;
else
b->kanan=p->kiri;
}
free(p);
}
// Bila PTB memiliki anak kanan saja dgn banyak anak cabang
else if (p->kiri==NULL && p->kanan!=NULL)
{
if (b==p)
akar=p->kanan;
else
{ if (p==b->kanan)
b->kanan=p->kanan;
else
b->kiri=p->kanan;
}
free(p);
}
}
|
d921fa44c20e3e28879ea0faadeda6dfc5496174
|
[
"C++"
] | 1
|
C++
|
ecinoshuta/graph-dan-PTB
|
76cdfa2741f997cd7ab4d5c6f2d26886b3113aa6
|
bb7b2142f420aad369f8b0c31f6ba52a27fc0113
|
refs/heads/master
|
<repo_name>silver6wings/SamplePyCode<file_sep>/TestPython2/test_git.py
#!/usr/bin/env python
# coding=utf-8
# encoding=utf-8
from git import Repo
repo = Repo('/Users/junchaoyu/Desktop/TestGit')
#print repo.bare
#print repo.is_dirty()
git = repo.git
## 新建分支
#git.checkout('head', b='test')
## 切换分支
#repo.heads.dev.checkout()
## Commit迭代
# for c in repo.iter_commits('dev', max_count=100):
# print c.message
c1 = repo.commit('dev')
# print c1.author
# print c1.hexsha
# print c1.message
# print c1.committer
#
# print c1.parents[0].hexsha
# print c1.parents[0].message
# for diff in c1.diff('master').iter_change_type('D'):
# print diff
# print diff.b_rawpath
## 获取branch信息
#print git.branch()
# # 获取当前branch名字
branch = repo.active_branch
print branch.name
# # 获取两个branch之间的区别文件名
diff = repo.git.diff(branch.name + '..master', name_only=True)
d = str(diff).split("\n")
print d
# git.fetch()
<file_sep>/TestPython3/test_string.py
a = ''
print(a[-5::3])<file_sep>/TestTensroFlow/main.py
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
print("aaa")
sess = tf.Session()
a = tf.constant(10)
b = tf.constant(32)
print(sess.run(a+b))
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
result = sess.run(product)
print(result)
hello = tf.constant('Hello, TensorFlow!')
print(sess.run(hello))
sess.close()
<file_sep>/TestML/test523.py
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
digits = load_digits()
print(digits.images.shape)
# fig, axes = plt.subplots(
# 10,
# 10,
# figsize=(8, 8),
# subplot_kw={'xticks': [], 'yticks': []},
# gridspec_kw=dict(hspace=0.1, wspace=0.1))
#
# for i, ax in enumerate(axes.flat):
# ax.imshow(digits.images[i],
# cmap='binary',
# interpolation='nearest')
# ax.text(0.05,
# 0.05,
# str(digits.target[i]),
# transform=ax.transAxes,
# color='green')
# plt.show()
X = digits.data
print(X.shape)
y = digits.target
print(y.shape)
# 降维
from sklearn.manifold import Isomap
iso = Isomap(n_components=2)
iso.fit(digits.data)
data_projected = iso.transform(digits.data)
# plt.scatter(
# data_projected[:, 0],
# data_projected[:, 1],
# c=digits.target,
# edgecolors='none',
# alpha=0.5,
# cmap=plt.cm.get_cmap('spectral', 10)
# )
# plt.colorbar(label='digit label', ticks=range(10))
# plt.clim(-0.5, 9.5)
# plt.show()
# 分类
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, random_state=0)
model = GaussianNB()
model.fit(Xtrain, ytrain)
y_model = model.predict(Xtest)
from sklearn.metrics import accuracy_score
print(accuracy_score(ytest, y_model))
# 画出结果图
# from sklearn.metrics import confusion_matrix
# import seaborn as sns
#
# mat = confusion_matrix(ytest, y_model)
# sns.heatmap(mat, square=True, annot=True, cbar=False)
# plt.xlabel('predicted value')
# plt.ylabel('true value')
# plt.show()
fig, axes = plt.subplots(
10,
10,
figsize=(8, 8),
subplot_kw={'xticks': [], 'yticks': []},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
for i, ax in enumerate(axes.flat):
ax.imshow(digits.images[i],
cmap='binary',
interpolation='nearest')
ax.text(0.05,
0.05,
str(digits.target[i]),
transform=ax.transAxes,
color='green' if ytest[i] == y_model[i] else 'red')
plt.show()
<file_sep>/TestML/test531.py
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=1)
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
X1, X2, y1, y2 = train_test_split(X, y,
random_state=0,
train_size=0.5,
test_size=0.5)
model.fit(X1, y1)
y_model = model.predict(X2)
print(accuracy_score(y2, y_model))
from sklearn.model_selection import cross_val_score
print(cross_val_score(model, X, y, cv=5))<file_sep>/LeetCode/A221.py
import numpy
class Solution(object):
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not matrix: return 0
if len(matrix) == 0: return 0
result = 0
h = len(matrix)
w = len(matrix[0])
dp = [[0]*w for i in range(h)]
for i in range(0, h):
for j in range(0, w):
if matrix[i][j] == '0':
dp[i][j] = 0
else:
if i == 0 or j == 0:
dp[i][j] = int(matrix[i][j])
else:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
result = max(result, dp[i][j])
return result * result
if __name__ == '__main__':
s = Solution()
r = s.maximalSquare(
[
['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']
]
)
print(r)<file_sep>/TestPython3/test_system.py
#!/usr/bin/env python
# coding=utf-8
# encoding=utf-8
# -*- coding: utf-8 -*-
from os import popen
import json
# a = "yarn"
# p = os.popen(a)
# x = p.read()
# print(">>>>" + x)
#
# if "Done in" in x:
# print("yes")
# else:
# print("no")
if __name__ == '__main__':
cmd = 'cd ~/Desktop/ofoEngineIntl && git fetch && git branch'
branches = os.popen(cmd)
res = branches.read()
result = {
'current': '',
'branches': [],
}
for line in res.splitlines():
if (len(line) > 0):
if (line[0] == '*'):
result['current'] = line[2:]
else:
result['branches'].append(line[2:])
# print(line)
print(json.dumps(result))
<file_sep>/TestML/draw_rose.py
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
[x, t] = np.meshgrid(
np.array(range(25)) / 24.0,
np.arange(0, 575.5, 0.5) / 575 * 17 * np.pi - 2 * np.pi
)
p = (np.pi / 2) * np.exp(-t / (8 * np.pi))
u = 1 - (1 - np.mod(3.6 * t, 2 * np.pi) / np.pi) ** 4 / 2
y = 2 * (x ** 2 - x) ** 2 * np.sin(p)
r = u * x * np.sin(p) + y * np.cos(p)
surf = ax.plot_surface(
r * np.cos(t),
r * np.sin(t),
u * (x * np.cos(p) - y * np.sin(p)),
rstride=1,
cstride=1,
cmap=cm.gist_rainbow_r,
linewidth=0,
antialiased=True
)
plt.show()
<file_sep>/LeetCode/A165.py
version1 = "1.2.3"
version2 = "3.2.5"
def compareVersion(self, version1, version2):
a1 = version1.split('.')
a2 = version2.split('.')
for i in range(0, max(len(a1), len(a2))):
t1 = int(a1[i]) if (i < len(a1)) else 0
t2 = int(a2[i]) if (i < len(a2)) else 0
if (t1 > t2):
return 1
elif (t1 < t2): return -1
return 0
<file_sep>/LeetCode/A057.py
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[Interval]
"""
if not intervals or len(intervals) == 0:
return [newInterval]
p1 = 0
p1start = True
t = intervals[0].start
while t <= newInterval.start:
if p1start:
p1start = False
else:
p1 += 1
p1start = True
if p1 < len(intervals):
t = intervals[p1].start if p1start else intervals[p1].end
else:
break
if p1start:
p1start = False
p1 -= 1
else:
p1start = True
# print(p1, p1start)
# print(intervals[p1].start if p1start else intervals[p1].end)
if p1 < 0 or newInterval.start > intervals[p1].end:
p1 += 1
intervals.insert(p1, Interval(newInterval.start, newInterval.end))
intervals[p1].end = max(intervals[p1].end, newInterval.end)
p2 = p1 + 1
while p2 < len(intervals) and intervals[p1].end >= intervals[p2].end:
intervals.remove(intervals[p2])
if p2 < len(intervals):
if intervals[p1].end >= intervals[p2].start:
intervals[p1].end = intervals[p2].end
intervals.remove(intervals[p2])
# for i in range(len(intervals)):
# print(intervals[i].start, intervals[i].end)
return intervals
if __name__ == '__main__':
s = Solution()
a = [
Interval(1, 5),
]
b = Interval(0, 3)
s.insert(a, b)<file_sep>/TestPython3/test_oop.py
class A:
x = 1
__y = 'a'
def __init__(self):
self.xx = 2
self.__yy = 'b'
@staticmethod
def bar():
print(123)
@classmethod
def foo(clss):
clss.x = 3
def test(self):
print('class A')
def speak(self):
pass;
def read(self):
pass
class B:
def test(self):
print('class B')
def write(self):
pass
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
class D:
def read(self):
pass
def write(self):
pass
from abc import *
class IA(metaclass=ABCMeta):
@abstractmethod
def test_abc(self):
pass
class X:
def __init__(self, xx):
self.xx = xx
def __add__(self, other):
self.xx = self.xx + other.xx
return self
if __name__ == '__main__':
x1 = X(1)
x2 = X(2)
x3 = x1 + x2
print(x3.xx)
a = [[1, [2, 3], 4, 5], 6, [7, 8]]
class iter:
def load(self, arr):
pass
def next(self):
pass
a = iter.next()
while (a != None):
print(a)
a = iter.next()
<file_sep>/TestML/test321.py
import pandas as pd
data = pd.Series([0.25, 0.5, 0.75, 1.0])
print(data.values)<file_sep>/TestTensroFlow/linear_regression.py
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 定义输入数据
X_data = np.linspace(-1, 1, 100)
print(X_data)
noise = np.random.normal(0, 0.5, 100)
y_data = 5 * X_data + noise
# Plot 输入数据
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(X_data, y_data)
plt.ion()
plt.show()
# 定义数据大小
n_samples = 100
# 转换成向量
X_data = np.reshape(X_data, (n_samples, 1))
y_data = np.reshape(y_data, (n_samples, 1))
# 定义占位符
X = tf.placeholder(tf.float32, shape=(None, 1))
y = tf.placeholder(tf.float32, shape=(None, 1))
# 定义学习的变量
W = tf.get_variable("weight", (1, 1), initializer=tf.random_normal_initializer())
b = tf.get_variable("bais", (1,), initializer=tf.constant_initializer(0.0))
y_pred = tf.matmul(X, W) + b
loss = tf.reduce_mean(tf.reduce_sum(tf.square(y - y_pred)))
# 梯度下降
# 定义优化函数
opt = tf.train.GradientDescentOptimizer(0.001)
operation = opt.minimize(loss)
with tf.Session() as sess:
# 初始化变量
sess.run(tf.initialize_all_variables())
lines = None
for i in range(50):
_, loss_val = sess.run([operation, loss],
feed_dict={X: X_data, y: y_data})
if i % 5 == 0:
if lines:
ax.lines.remove(lines[0])
prediction_value = sess.run(y_pred, feed_dict={X: X_data})
lines = ax.plot(X_data, prediction_value, 'r-', lw=5)
plt.pause(1)
plt.pause(50)<file_sep>/LeetCode/A146.py
class LRUNode:
def __init__(self, x):
self.val = x
self.next = None
self.prev = None
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.length = 0
self.dic = {}
self.nodes = {} # key
self.head = LRUNode(None)
self.tail = LRUNode(None)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.dic.keys():
t = self.nodes[key]
tp = t.prev
tn = t.next
tp.next = tn
tn.prev = tp
h = self.head.next
self.head.next = t
h.prev = t
t.next = h
t.prev = self.head
return self.dic[key]
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self.dic.keys():
self.dic[key] = value
t = self.nodes[key]
tp = t.prev
tn = t.next
tp.next = tn
tn.prev = tp
h = self.head.next
self.head.next = t
h.prev = t
t.next = h
t.prev = self.head
else:
if self.length == self.capacity:
d = self.tail.prev
t = d.prev
t.next = self.tail
self.tail.prev = t
self.dic.pop(d.val)
self.nodes.pop(d.val)
self.length -= 1
self.dic[key] = value
n = LRUNode(key)
self.nodes[key] = n
t = self.head.next
self.head.next = n
t.prev = n
n.prev = self.head
n.next = t
self.length += 1
def printList(self):
p = self.head
while p != None:
print(p.val)
p = p.next
if __name__ == '__main__':
cache = LRUCache(2)
cache.put(2, 1)
cache.put(1, 1)
cache.put(2, 3)
cache.put(4, 1)
# print(cache.get(1))
print(cache.get(1))
print(cache.get(2))
cache.printList()<file_sep>/TestPython3/test_utf8.py
# import sys
# import codecs
# sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
print(['中文'])
<file_sep>/TestPython3/test_base64.py
import base64
input = '测试'
print(input)
print(base64.b64encode(input.encode()))
print(base64.urlsafe_b64encode(input.encode()))
a = {'a'}
data = a.encode()
print(data)
<file_sep>/TestPython2/test_version.py
import re
def get_build(version):
nums = version.split('.')
if len(nums) < 3:
print 'version format check error'
return '0'
for i in range(0, 2):
num = nums[i]
if not num.isdigit():
print 'version number check error'
return '0'
nums[1] = '0' if int(nums[1]) < 0 else nums[1]
nums[2] = '0' if int(nums[2]) < 0 else nums[2]
result = nums[0]
result += '0' if int(nums[1]) < 10 else ''
result += nums[1]
result += '0' if int(nums[2]) < 10 else ''
result += nums[2]
return result
print get_build('6.19.-1.alpha')
<file_sep>/LeetCode/A120.py
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
if not triangle or len(triangle) == 0:
return 0
if len(triangle) == 1:
return triangle[0][0]
ans = 99999
dp = [[triangle[0][0]]]
for i in range(1, len(triangle)):
dp.append([])
for j in range(0, i+1):
a = 99999 if j == 0 else dp[i-1][j-1]
b = 99999 if j == i else dp[i-1][j]
dp[i].append(triangle[i][j] + min(a, b))
if i == len(triangle) - 1: ans = min(ans, dp[i][j])
return ans
if __name__ == '__main__':
s = Solution()
s.minimumTotal([
[2],
[3,4],
[6,5,7],
[4,1,8,3]
])
<file_sep>/TestML/test_pandas.py
import pandas as pd
if __name__ == '__main__':
df1 = pd.DataFrame({'key':['a','b','b'], 'data1':range(3)})
df2 = pd.DataFrame({'key': ['a', 'b', 'c'], 'data2': range(3)})
# print(df1)
# print(df2)
# print(pd.merge(df1, df2))
print(pd.merge(df2, df1))<file_sep>/TestFlask/TestFlask.py
# encoding: UTF-8
import os
import json
import subprocess
from flask import Flask, request, render_template
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
app = Flask(__name__)
OF0 = '~/Desktop/' + 'o' + 'f' + 'o' + 'EngineIntl'
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route("/date")
def date():
# cmd = "git --version"
#
# returned_value = subprocess.call(cmd,
# shell=True) # returns the exit code in unix
# print('returned value:', returned_value)
#
# return str(returned_value)
cmd = "pwd"
# returns output as byte string
returned_output = subprocess.check_output(cmd)
# using decode() function to convert byte string to string
print('Current date is:', returned_output.decode("utf-8"))
return str(returned_output)
@app.route("/test", methods=['GET', 'POST'])
def test():
if request.method == 'GET':
param = request.args.to_dict()
content = str(param['aaa'])
# print(param['ccc'])
print('ccc' in param)
return content
if request.method == 'POST' and request.form.get('aaa'):
param = request.form.to_dict()
content = str(param['aaa'])
return content
return 'Hello world'
@app.route("/page")
def page():
return render_template("test.html")
@app.route("/pack", methods=['GET'])
def pack():
"""
:platform={android/ios]
:script={alpha/beta/rc}
:log
:version
:branch
"""
params = request.args.to_dict()
cmd = 'cd ' + OF0 + ' && '
if 'branch' in params:
cmd += 'git fetch && '
cmd += 'git checkout ' + str(params['branch']) + ' && '
cmd += 'git pull && '
if 'script' not in params:
return '缺script参数'
if not (params['script'] == 'alpha'
or params['script'] == 'beta'
or params['script'] == 'rc'):
return '参数type需要是alpha/beta/rc的一种'
if 'log' not in params:
return '缺少log参数'
if 'version' not in params:
return '缺少version参数'
if 'platform' not in params:
return '缺少platform参数'
if not (params['platform'] == 'android'
or params['platform'] == 'ios'):
return '参数platform需要是android/ios的一种'
cmd += 'yarn pack-' + \
params['platform'] + ' ' + \
params['script'] + ' ' + \
params['log'] + ' ' + \
params['version']
print(cmd)
result = os.system(cmd)
return str(result)
@app.route("/branch", methods=['GET'])
def branch():
cmd = 'cd ' + OF0 + ' && git fetch && git branch -a'
branches = os.popen(cmd)
res = branches.read()
result = {
'current': '',
'branches': [],
}
for line in res.splitlines():
if len(line) > 0:
if line[0] == '*':
result['current'] = line[2:]
else:
result['branches']\
.append(line[2:].replace('remotes/origin/', ''))
return json.dumps(result)
@app.route("/diff", methods=['GET'])
def diff():
"""
:branch
"""
params = request.args.to_dict()
cmd = 'cd ' + OF0 + ' && yarn git-diff ' + params['branch']
diffs = os.popen(cmd)
result = []
res = diffs.read()
for line in res.splitlines():
if not ('yarn' in line
or 'python' in line
or 'Done' in line
or '已弃用' in line):
result.append(line)
return json.dumps(result).decode("unicode_escape")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
<file_sep>/TestPython2/WeiboAPI/TestSinaWeibo.py
# -*- coding: utf-8 -*-
from weibo import APIClient
import webbrowser # python内置的包
APP_KEY = '744917056' # 注意替换这里为自己申请的App信息
APP_SECRET = '<KEY>'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' # 回调授权页面
# 利用官方微博SDK
client = APIClient(
app_key=APP_KEY,
app_secret=APP_SECRET,
redirect_uri=CALLBACK_URL)
# 得到授权页面的url,利用webbrowser打开这个url
url = client.get_authorize_url()
print url
webbrowser.open_new(url)
# 获取code=后面的内容
print '输入url中code后面的内容后按回车键:'
code = raw_input()
# code = your.web.framework.request.get('code')
# client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
r = client.request_access_token(code)
access_token = r.access_token # 新浪返回的token,类似<KEY>
expires_in = r.expires_in
# 设置得到的access_token
client.set_access_token(access_token, expires_in)
r = client.statuses.public_timeline.get(uid=1570153267)
for st in r.statuses:
print st.text
# # 可以打印下看看里面都有什么东西
# statuses = client.user_timeline()[
# 'statuses'] # 获取当前登录用户以及所关注用户(已授权)的微博</span>
#
# length = len(statuses)
# print length
# # 输出了部分信息
# for i in range(0, length):
# print u'昵称:' + statuses[i]['user']['screen_name']
# print u'简介:' + statuses[i]['user']['description']
# print u'位置:' + statuses[i]['user']['location']
# print u'微博:' + statuses[i]['text']
<file_sep>/TestTensroFlow/logistic_regression.py
# -*- coding:utf-8 -*-
# 功能: 使用tensorflow实现一个简单的逻辑回归
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 创建占位符
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# 创建变量
# tf.random_normal([1])返回一个符合正太分布的随机数
w = tf.Variable(tf.random_normal([1], name='weight'))
b = tf.Variable(tf.random_normal([1], name='bias'))
y_predict = tf.sigmoid(tf.add(tf.multiply(X, w), b))
num_samples = 400
cost = tf.reduce_sum(tf.pow(y_predict - Y, 2.0)) / num_samples
# 学习率
lr = 0.01
optimizer = tf.train.AdamOptimizer().minimize(cost)
# 创建session 并初始化所有变量
num_epoch = 500
cost_accum = []
cost_prev = 0
# np.linspace()创建agiel等差数组,元素个素为num_samples
xs = np.linspace(-5, 5, num_samples)
ys = np.sin(xs) + np.random.normal(0, 0.01, num_samples)
with tf.Session() as sess:
# 初始化所有变量
sess.run(tf.global_variables_initializer())
# 开始训练
for epoch in range(num_epoch):
for x, y in zip(xs, ys):
sess.run(optimizer, feed_dict={X: x, Y: y})
train_cost = sess.run(cost, feed_dict={X: x, Y: y})
cost_accum.append(train_cost)
"train_cost is:", str(train_cost)
# 当误差小于10-6时 终止训练
if np.abs(cost_prev - train_cost) < 1e-6:
break
# 保存最终的误差
cost_prev = train_cost
print(train_cost)
# 画图 画出每一轮训练所有样本之后的误差
plt.plot(range(len(cost_accum)), cost_accum, 'r')
plt.title('Logic Regression Cost Curve')
plt.xlabel('epoch')
plt.ylabel('cost')
plt.show()<file_sep>/LeetCode/Test.py
a = []
b = a.pop()
print(b)
<file_sep>/TestML/test283.py
import matplotlib.pyplot as plt
import seaborn
import numpy as np
X = np.random.random((10, 2))
seaborn.set()
plt.scatter(X[:, 0], X[:, 1], s=100)
plt.show()
<file_sep>/TestPython2/XML/test_xml.py
#coding=utf-8
import xml.dom.minidom
#打开xml文档
dom = xml.dom.minidom.parse('abc.xml')
#得到文档元素对象
root = dom.documentElement
print(root.nodeName)
print(root.nodeValue)
print(root.nodeType)
print(root.ELEMENT_NODE)
bb = root.getElementsByTagName('maxid')
b = bb[0]
print b.firstChild.data
bb = root.getElementsByTagName('login')
b = bb[0]
print b.nodeName<file_sep>/TestML/testPR.py
from sklearn import metrics
y_pred = [0, 1, 0, 0]
y_true = [0, 1, 0, 1]
print(metrics.precision_score(y_true, y_pred))
print(metrics.recall_score(y_true, y_pred))
print(metrics.f1_score(y_true, y_pred))
print(metrics.fbeta_score(y_true, y_pred, beta=0.5))
print(metrics.fbeta_score(y_true, y_pred, beta=1))
print(metrics.fbeta_score(y_true, y_pred, beta=2))
print(metrics.precision_recall_fscore_support(y_true, y_pred, beta=0.5))
import numpy as np
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
y_true = np.array([0, 0, 1, 1])
y_scores = np.array([0.1, 0.4, 0.35, 0.8])
precision, recall, threshold = precision_recall_curve(y_true, y_scores)
print(precision)
print(recall)
print(threshold)
print(average_precision_score(y_true, y_scores))<file_sep>/TestPython3/test_pwd.py
import os
print(os.getcwd()[-11:] == 'TestPython3')<file_sep>/LeetCode/A065.py
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
a = s.strip().split('e')
if len(a) == 1:
return self.isPureNumber(a[0])
if len(a) == 2:
return self.isPureNumber(a[0]) and self.isPureNumber(a[1], False)
return False
def isPureNumber(self, s, dot=True):
if len(s) == 0:
return False
gotDot = False
gotNum = False
isFirst = True
for c in s:
if c >= '0' and c <= '9':
gotNum = True
elif c == '+' or c == '-':
if not isFirst:
return False
elif c == '.' and dot:
if gotDot:
return False
gotDot = True
else:
return False
isFirst = False
if not gotNum:
return False
return True
# class Solution(object):
# def isNumber(self, s):
# """
# :type s: str
# :rtype: bool
# """
# s = s.strip()
# gotNum = False
# gotDot = False
# gotExp = False
# gotPoN = False
# isFirst = True
#
# for c in s:
# if '0' <= c and c <= '9':
# gotNum = True
# elif c == '+' or c == '-':
# if gotDot:
# return False
# if gotNum:
# return False
# if gotPoN:
# return False
# gotPoN = True
# elif c == 'e':
# if isFirst:
# return False
# if gotExp:
# return False
# if not gotNum:
# return False
# gotNum = False
# gotPoN = False
# gotDot = False
# gotExp = True
# elif c == '.':
# if gotExp:
# return False
# if gotDot:
# return False
# gotDot = True
# else:
# return False
#
# isFirst = False
#
# if not gotNum:
# return False
# if isFirst:
# return False
#
# return True
if __name__ == '__main__':
print('123'.split('e'))
<file_sep>/TestPython2/test_timer.py
#!/usr/bin/env python
# coding=utf-8
# encoding=utf-8
import datetime
from threading import Timer
def pack_task():
now = datetime.datetime.now()
if now.second % 10 == 0:
print "Hello World"
print str(now.hour) + ' h ' + str(now.minute) + ' m ' + str(now.second)
t = Timer(0.5, pack_task)
t.start()
if __name__ == "__main__":
pack_task()
<file_sep>/TestPython3/test_itchat.py
import itchat
sb = ''
sbm = 'AAA鹿屎蛋儿'
sbr = '宝宝今天困死了,你个傻吊别说话~'
@itchat.msg_register(itchat.content.TEXT)
@itchat.msg_register(itchat.content.PICTURE)
def text_reply(msg):
if msg['User'].RemarkName == 'AA于俊超':
itchat.send('test', toUserName=msg.fromUserName)
if msg['User'].RemarkName == sbm:
itchat.send(sbr, toUserName=msg.fromUserName)
def lc():
name = itchat.search_friends(remarkName=sbm)
sb = name[0].UserName
itchat.send('你的聪明宝宝不想理你,现在开始你的智障宝宝代为服务~',
toUserName=sb)
def ec():
itchat.send('你的智障宝宝下线啦',
toUserName=sb)
if __name__ == '__main__':
itchat.auto_login(hotReload=True, loginCallback=lc, exitCallback=ec)
itchat.run()<file_sep>/TestML/test291.py
import numpy as np
name = ['a', 'b', 'c']
age = [24, 354, 24]
weight = [34.0, 24.0, 20.0]
x = np.zeros(3, dtype=int)
data = np.zeros(3, dtype=
{
'names': ('name', 'age', 'weight'),
'formats': ('U10', 'i4', 'f8'),
})
data['name'] = name
data['age'] = age
data['weight'] = weight
print(data)
print(data['name'])<file_sep>/TestPython3/test_try.py
x = 'abc'
def fetcher(obj, index):
return obj[index]
def catcher():
try:
fetcher(x, 4)
except(IndexError):
print("type exception")
except:
print("got exception")
# raise
else:
print("not exception")
finally:
print("finally")
print("continuing")
catcher()
<file_sep>/TestDjango/TestDjango/views.py
from django.shortcuts import render, render_to_response
def hi(request):
return render_to_response('index.html')<file_sep>/LeetCode/A123X.py
class Solution(object):
def __init__(self):
self.a = 0
self.b = 0
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices or len(prices) == 0: return 0
ans = 0
a = []
a.append(prices[0])
for i in range(1, len(prices)):
if len(a) == 0 or prices[i] >= a[-1]:
a.append(prices[i])
else:
if len(a) > 1:
self.store(a[-1] - a[0])
a = []
a.append(prices[i])
if len(a) > 1:
self.store(a[-1] - a[0])
print(self.a, self.b)
return self.a + self.b
def store(self, x):
if x > self.a:
self.b = self.a
self.a = x
return
if x > self.b:
self.b = x
if __name__ == '__main__':
s = Solution()
s.maxProfit([3,3,5,0,0,3,1,4])<file_sep>/LeetCode/A121.py
import sys
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices or len(prices) == 0: return 0
mini = sys.maxsize
ans = -sys.maxsize
for i in range(len(prices)):
mini = min(mini, prices[i])
ans = max(ans, prices[i] - mini)
return ans
<file_sep>/LeetCode/A066.py
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
p = 0
p = (digits[-1] + 1) // 10
digits[-1] = (digits[-1] + 1) % 10
for i in range(-2, -len(digits)-1, -1):
t = digits[i] + p
p = t // 10
digits[i] = t % 10
if p == 1:
digits.insert(0, 1)
print(digits)
return digits
if __name__ == '__main__':
s = Solution()
s.plusOne([9,9,9,9])<file_sep>/LeetCode/A002.py
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
r = ListNode(l1.val + l2.val)
p = r
a = p.val // 10
p.val = p.val % 10
l1 = l1.next
l2 = l2.next
while (l1 != None or l2 != None):
n1 = 0 if l1 == None else l1.val
n2 = 0 if l2 == None else l2.val
n = n1 + n2 + a
a = n // 10
n = n % 10
q = ListNode(n)
p.next = q
p = q
l1 = None if (l1 == None) else l1.next
l2 = None if (l2 == None) else l2.next
if a > 0:
p.next = ListNode(1)
return r
if __name__ == '__main__':
a1 = ListNode(2)
a2 = ListNode(4)
a3 = ListNode(3)
a1.next = a2
a2.next = a3
b1 = ListNode(5)
b2 = ListNode(6)
b3 = ListNode(7)
b1.next = b2
b2.next = b3
s = Solution()
c = s.addTwoNumbers(a1, b1)
while(c != None):
print(c.val)
c = c.next
<file_sep>/LeetCode/A051.py
class Solution(object):
def __init__(self):
self.list = []
self.flag = []
self.ans = []
self.s1 = set()
self.s2 = set()
def solveNQueens(self, n):
self.list = [0 for i in range(n)]
self.flag = [False for i in range(n)]
self.dfs(0, n)
return self.ans
def dfs(self, row, n):
if row == n:
self.record(n)
else:
for i in range(0, n):
if not self.flag[i] and row + i not in self.s1 and row - i not in self.s2:
self.s1.add(row + i)
self.s2.add(row - i)
self.flag[i] = True
self.list[row] = i
self.dfs(row + 1, n)
self.s1.remove(row + i)
self.s2.remove(row - i)
self.flag[i] = False
def record(self, n):
r = []
for i in range(n):
rr = ''
for j in range(n):
if j == self.list[i]:
rr = rr + 'Q'
else:
rr = rr + '.'
r.append(rr)
# print(r)
self.ans.append(r)
if __name__ == '__main__':
s = Solution()
s.solveNQueens(4)<file_sep>/TestPython3/test_assert.py
print(123)
assert 3<2, 'asdfsfasdf'
print(321)<file_sep>/LeetCode/A041.py
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = len(nums)
r = []
for i in range(0, l + 1):
r.append(False)
for num in nums:
if num >= 0 and num <= l:
r[num] = True
for i in range(1, l + 1):
if not r[i]:
return i
return l+1
<file_sep>/TestPython2/test_say7.py
i = 60
a = ''
while(True):
a = raw_input('>>> ')
if a.isdigit():
i = int(a)
i += 1
if (i % 7 == 0 or i % 10 == 7 or i // 10 % 10 == 7):
print 'GUO!'
else:
print i
<file_sep>/LeetCode/A052.py
class Solution(object):
def __init__(self):
self.list = []
self.flag = []
self.s1 = set()
self.s2 = set()
self.ans = 0
def totalNQueens(self, n):
self.ans = 0
self.list = [0 for i in range(n)]
self.flag = [False for i in range(n)]
self.dfs(0, n)
return self.ans
def dfs(self, row, n):
if row == n:
self.ans += 1
else:
for i in range(0, n):
if not self.flag[i] and row + i not in self.s1 and row - i not in self.s2:
self.s1.add(row + i)
self.s2.add(row - i)
self.flag[i] = True
self.list[row] = i
self.dfs(row + 1, n)
self.s1.remove(row + i)
self.s2.remove(row - i)
self.flag[i] = False
if __name__ == '__main__':
s = Solution()
s.totalNQueens(4)<file_sep>/LeetCode/A088.py
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
p = m-1
q = n-1
r = m+n-1
for i in range(m+n):
if p == -1:
nums1[r] = nums2[q]
q -= 1
r -= 1
continue
if q == -1:
nums1[r] = nums1[p]
p -= 1
r -= 1
continue
if nums1[p] > nums2[q]:
nums1[r] = nums1[p]
p -= 1
else:
nums1[r] = nums2[q]
q -= 1
r -= 1
# print(nums1)
# return nums1
if __name__ == '__main__':
s = Solution()
s.merge([1,2,3,0,0,0], 3, [2,5,6], 3)
<file_sep>/LeetCode/A119.py
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
ans = [1]
for i in range(1, rowIndex+1):
ans.append(1)
for j in range(i-1, 0, -1):
ans[j] = ans[j] + ans[j-1]
print(ans)
return ans
if __name__ == '__main__':
s = Solution()
s.getRow(3)<file_sep>/TestML/test_numpy.py
import numpy as np
# example of np.exp
x = np.array([1, 2, 3])
print(np.exp(x)) # result is (exp(1), exp(2), exp(3))
x = np.array([1, 2, 3])
print (x + 3)
<file_sep>/LeetCode/A124.py
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init(self):
self.max = 0
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.max = -9999
self.searchMax(root)
return self.max
def searchMax(self, root):
if root is None:
return 0
lmax = self.searchMax(root.left)
rmax = self.searchMax(root.right)
tmax = root.val
if lmax > 0:
tmax += lmax
if rmax > 0:
tmax += rmax
self.max = max(self.max, tmax)
return max(
root.val,
root.val + lmax,
root.val + rmax
)
if __name__ == '__main__':
s = Solution()
a1 = TreeNode(-10)
a2 = TreeNode(9)
a3 = TreeNode(20)
a4 = TreeNode(15)
a5 = TreeNode(7)
a1.left = a2
a1.right = a3
a3.left = a4
a3.right = a5
r = s.maxPathSum(a1)
print(r)
<file_sep>/LeetCode/A122.py
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices or len(prices) == 0: return 0
ans = 0
a = []
a.append(prices[0])
for i in range(1, len(prices)):
if len(a) == 0 or prices[i] >= a[-1]:
a.append(prices[i])
else:
if len(a) > 1:
ans += a[-1] - a[0]
a = []
a.append(prices[i])
if len(a) > 1:
ans += a[-1] - a[0]
return ans
if __name__ == '__main__':
s = Solution()
s.maxProfit([7,1,5,3,6,4])<file_sep>/LeetCode/A179.py
a = [1,2,3,4,7,8,5,6]
comp=lambda x,y:1 if (x+y > y+x) else -1 if (x+y < y+x) else 0
a.sort(cmp=comp, reverse=True)
print(a)<file_sep>/LeetCode/A199.py
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
self.a = []
self.search(root, 0)
return self.a
def search(self, node, depth):
if len(self.a) == depth:
self.a.append(node.val)
if node.right:
self.search(node.right, depth+1)
if node.left:
self.search(node.left, depth+1)
if __name__ == '__main__':
s = Solution()
a1 = TreeNode(1)
a2 = TreeNode(2)
a3 = TreeNode(3)
a4 = TreeNode(4)
a5 = TreeNode(5)
a1.left = a2
a1.right = a3
a2.right = a5
a3.right = a4
r = s.rightSideView(a1)
print(r)
<file_sep>/TestPython3/test_mro.py
class A(object):
def test(self):
pass
def save(self):
print("This is from A")
class C(A):
def test(self):
pass
def save(self):
print("This is from C")
class B(A):
def test(self):
pass
def save(self):
print("This is from B")
class D(C, B):
def test(self):
pass
fun = D()
fun.save()
print(D.mro())
<file_sep>/LeetCode/A118.py
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows <= 0: return []
ans = [[1]]
for i in range(1, numRows):
r = [1]
for j in range(1, i):
r.append(ans[i-1][j-1] + ans[i-1][j])
r.append(1)
ans.append(r)
print(ans)
return ans
if __name__ == '__main__':
s = Solution()
s.generate(5)<file_sep>/LeetCode/A059.py
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
flag = [[True for i in range(n)] for i in range(n)]
ans = [[0 for i in range(n)] for i in range(n)]
ds = [[0, 1], [1, 0], [0, -1], [-1, 0]]
d = 0
r = 0
c = -1
nr = r + ds[d][0]
nc = c + ds[d][1]
i = 1
while (i <= n*n):
print(nr, nc)
if nr >= 0 and nr < n and nc >= 0 and nc < n and flag[nr][nc]:
r = nr
c = nc
ans[r][c] = i
flag[r][c] = False
i += 1
else:
d = (d + 1) % 4
nr = r + ds[d][0]
nc = c + ds[d][1]
return ans
if __name__ == '__main__':
s = Solution()
s.generateMatrix(3)
<file_sep>/LeetCode/A067.py
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
ans = ""
p = 0
for i in range(-1, -max(len(a), len(b))-1, -1):
ta = 0 if -i > len(a) else (0 if a[i] == '0' else 1)
tb = 0 if -i > len(b) else (0 if b[i] == '0' else 1)
t = (ta + tb + p) % 2
p = (ta + tb + p) // 2
ans = str(t) + ans
if p > 0: ans = '1' + ans
return ans
if __name__ == '__main__':
s = Solution()
s.addBinary("11", "1")
<file_sep>/TestPython3/test_mysql.py
import MySQLdb
conn = MySQLdb.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='<PASSWORD>',
db='test',
charset='utf8'
)
cur = conn.cursor()
# cur.execute("""
# create table if not EXISTS user
# (
# userid int(11) PRIMARY KEY ,
# username VARCHAR(20)
# )
# """)
#
# for i in range(0, 5):
# cur.execute(
# "insert into user(userid, username) values('%d','%s')" %
# (int(i), 'name' + str(i)))
# conn.commit()
count = cur.execute("SELECT * from user")
print(count)
a = cur.fetchone()
print(a[0])
results = cur.fetchall()
for r in results:
print(r)
cur.scroll(-2)
results = cur.fetchall()
for r in results:
print(r)
cur.close()
conn.close()
<file_sep>/TestPython3/test_lambda.py
lambda_add = lambda x, y: x + y
def add(x, y):
return x + y
a = add
print(a(1, 2))
print(lambda_add(1, 2))
<file_sep>/LeetCode/A164.py
nums = [123, 345, 432, 127, 987, 23, 986, 917]
def radixSort(a, d):
b = {}
for i in range(0, 10):
b[i] = []
for i in range(0, 10):
arr = a[i]
for n in arr:
plot = (n // (10 ** (d - 1))) % 10
b[plot].append(n)
return b
a = {}
for i in range(0, 10):
a[i] = []
for n in nums:
a[n % 10].append(n)
for i in range(2, 11):
a = radixSort(a, i)
arr = a[0]
max = 0
for n in range(1, len(arr)):
t = abs(arr[n] - arr[n-1])
max = t if t > max else max
print(a)
print(max)
<file_sep>/TestML/test521.py
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')
iris.head()
# print(iris)
# sns.set()
# sns.pairplot(iris, hue='species', size=1.5)
# plt.show()
X_iris = iris.drop('species', axis=1)
print(X_iris.shape)
y_iris = iris['species']
print(y_iris.shape)
# 监督学习 bayes模型
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
Xtrain, Xtest, ytrain, ytest = train_test_split(X_iris, y_iris, random_state=1)
model = GaussianNB()
model.fit(Xtrain, ytrain)
y_model = model.predict(Xtest)
print(accuracy_score(ytest, y_model))
# 无监督学习, PCA数据降维
from sklearn.decomposition import PCA
model = PCA(n_components=2)
model.fit(X_iris)
X_2D = model.transform(X_iris)
iris['PCA1'] = X_2D[:, 0]
iris['PCA2'] = X_2D[:, 1]
sns.lmplot("PCA1", "PCA2", hue='species', data=iris, fit_reg=False)
plt.show()
# 高斯混合模型
from sklearn.mixture import GMM
model = GMM(n_components=3, covariance_type='full')
model.fit(X_iris)
y_gmm = model.predict(X_iris)
iris['cluster'] = y_gmm
sns.lmplot('PCA1', 'PCA2', data=iris, hue='species', col='cluster', fit_reg=False)
plt.show()
<file_sep>/TestPython3/test_request_post.py
import requests
import time as ti
import json
def test(a: str) -> None:
print(a)
# print('---')
# t1 = ti.time()
# url = 'http://engine-dev.ofo.com/api/login'
# data = {
# "tel": "18588888888",
# "password": "<PASSWORD>",
# "lat": "35.7020691",
# "lng": "139.7753269",
# "source": "1",
# "countryCode": "SG",
# "languageCode": "en",
# "sourceVersion": "20171027",
# "scale": "2",
# "ccc": "65",
# }
#
# results = requests.post(url, data=data)
# t2 = ti.time()
#
# print(results.text)
# print('---', t2 - t1)
#### DingDing Robot
url = 'https://oapi.dingtalk.com/robot/send?access_token=' \
'2b23a10fe566def473ea1b11960c80cb2e47fd3d3f456adf280d529cb4b62837'
headers = {
'Content-Type': 'application/json',
}
data = {
"msgtype": "text",
"text": {
"content": "@13810788061 test by python"
},
"at": {
"atMobiles": [
"13810788061"
],
"isAtAll": False
}
}
result = requests.post(
url,
data=json.dumps(data),
headers=headers)
<file_sep>/LeetCode/A054.py
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or len(matrix) == 0:
return []
row = len(matrix)
col = len(matrix[0])
flag = [[True for j in range(col)] for i in range(row)]
i = 0
d = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
]
curr = 0
curc = -1
curd = 0
ans = []
while i < row*col:
nextr = curr + d[curd][0]
nextc = curc + d[curd][1]
while (
nextr >= 0 and nextr < row and
nextc >= 0 and nextc < col and
flag[nextr][nextc]
):
curr = nextr
curc = nextc
ans.append(matrix[curr][curc])
print(matrix[curr][curc])
flag[curr][curc] = False
i += 1
nextr = curr + d[curd][0]
nextc = curc + d[curd][1]
curd += 1
curd = curd % 4
return ans
if __name__ == '__main__':
s = Solution()
s.spiralOrder([
[1,2,3],
[4,5,6],
[7,8,9]
])
<file_sep>/TestPython3/test_mongodb.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from pymongo import MongoClient
conn = MongoClient('localhost', 27017)
db = conn.test #连接mydb数据库,没有则自动创建
my_set = db.people #使用test_set集合,没有则自动创建
for i in my_set.find({}):
print(i)
<file_sep>/TestPython3/test_with.py
class Sample:
def __init__(self, tag):
self.tag = tag
def __enter__(self):
print("In __enter__()")
return self.tag
def __exit__(self, type, value, trace):
print("In __exit__()")
print("type:", type)
print("value:", value)
print("trace:", trace)
with Sample("aaa") as sample:
print ("sample:", sample)
bar = 1 / 0
with open('/home/xbwang/Desktop/output_measures.txt','r') as f:
with open('/home/xbwang/Desktop/output_measures2.txt','r') as f1:
with open('/home/xbwang/Desktop/output_output_bk.txt','r') as f2:
pass
<file_sep>/TestPython2/test_mro.py
class A:
def test(self):
pass
def save(self):
print("This is from A")
class C(A):
def test(self):
pass
def save(self):
print"This is from C"
class B(A):
def test(self):
pass
class D(B, C):
def test(self):
pass
fun = D()
fun.save()
<file_sep>/TestPython3/test_function.py
def aaa(func):
func()
def bbb():
print(123)
if __name__ == '__main__':
aaa(bbb)
|
bb273c43bbd3f6be2e3feb3efeb2653d38e0d100
|
[
"Python"
] | 63
|
Python
|
silver6wings/SamplePyCode
|
5735a5add8971b3e3bb2ad4cfb23946343a1458a
|
c325be58c70d724d1028460c8db417d0a349e555
|
refs/heads/main
|
<file_sep>import logo from './logo.svg';
import './App.css';
//import recherche.js
import Recherche from './components/Recherche.js';
//import etablissement.js
import Etablissement from './components/Etablissement.js';
import './components/Recherche.css'
import React from 'react';
import {Card, Message} from 'semantic-ui-react';
//import React, {Component} from 'react';
/*Composant fonctionnel d'App*/
// function App() {
// return (
// <div className="App">
// <header className="App-header">
// <img src={logo} className="App-logo" alt="logo" />
// <h1>ANNUAIRE des établissements publics de l'administration 📖</h1>
// <Recherche/>
// </header>
// </div>
// );
// }
/*Composant complexe d'App*/
class App extends React.Component{
constructor(props){
super(props);
this.state = {
data : [],
error : ""
};
} ;
renderResults = () => {
return this.state.data.map((etablissement) => {
return(
<Etablissement
key={etablissement.properties.id}
properties={etablissement.properties}
/>
);
});
};
onEmpty = () =>{
this.setState({
data:[],
error:""
});
};
onSearch = async (dpt,type) =>{
//console.log(dpt,type);
if(dpt && type){
try{
let response = await fetch ("https://etablissements-publics.api.gouv.fr/v3/departements/" + dpt +"/"+ type);
let data = await response.json();
console.log(data);
this.setState({
data : data.features,
error : ""
})
console.log(this.state.data);
// data.features.forEach(element =>{
// console.log(element.properties.nom);
// console.log(element.properties.telephone);
// console.log(element.properties.url);
// })
} catch(e){
console.log(e);
this.setState({
error : "Erreur lors de la recherche"
});
}
}else{
this.setState({
error : "Merci de choisir un département et/ou une administration."
});
}
}
render (){
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1>ANNUAIRE des établissements publics de l'administration 📖</h1>
<Recherche onsearch = {this.onSearch} onEmpty = {this.onEmpty}/>
{this.state.error ? (
<Message warning>{this.state.error} </Message> ) : undefined }
{this.state.data ? (
<Card.Group>{this.renderResults()} </Card.Group> ) : undefined }
</header>
</div>
)
}
}
export default App;
<file_sep>import React,{Component} from 'react';
import {Button,Select} from 'semantic-ui-react';
import 'semantic-ui-css/semantic.min.css';
class Recherche extends React.Component{
constructor(props){
super(props);
this.state = {
dpt : "",
type : ""
}
}
onDptChange = (e,data) => {
console.log(data)
this.setState({dpt : data.value});
}
onTypeChange = (e,data) => {
console.log(data)
this.setState({type : data.value});
}
render(){
console.log(this.state);
const optionsDpt = [
{key: '60', value: '60', text: 'Oise'},
{key: '02', value: '02', text: 'Aisne'},
{key: '80', value: '80', text: 'Somme'},
{key: '93', value: '93', text: 'Seine-St-Denis'},
];
const optionsType = [
{key: 'cio', value: 'cio', text: 'Centre d’information et d’orientation (CIO)'},
{key: 'cr', value: 'cr', text: 'Conseil régional'},
{key: 'cpam', value: 'cpam', text: 'Caisse primaire d’assurance maladie (CPAM)'},
{key: 'caf', value: 'caf', text: 'Caisse d’allocations familiales (CAF)'},
{key: 'maison_arret', value: 'maison_arret', text: 'Maison d\'arrêt'},
];
return(
<div className="recherche">
<div className="select__style">
<Select placeholder= 'Choisissez un département' options= {optionsDpt} onChange ={this.onDptChange}/>
<Select placeholder= 'Choisissez une administration' options= {optionsType} onChange ={this.onTypeChange}/>
</div>
<div className="btn__style">
<Button primary onClick = {() => this.props.onsearch(this.state.dpt,this.state.type)}>Lancer la recherche</Button>
<Button secondary onClick = {this.props.onEmpty}>Effacer la recherche</Button>
</div>
</div>
)
}
}
export default Recherche;
|
5054f9c19fd48ad36479dba8ca02139c4c7c5a6e
|
[
"JavaScript"
] | 2
|
JavaScript
|
ShirleyBJ/Annuaire-React
|
1c95dba37eb148d42dd5423114874e226e08bfdd
|
719b4b3c2a12ea74fafb157b750bcbb1aefc6888
|
refs/heads/master
|
<repo_name>klowe0100/filebrowser-safe<file_sep>/filebrowser_safe/compat.py
import django
django_version = django.VERSION
is_gte_django2 = (django_version >= (2, 0))
if is_gte_django2:
from django.urls import reverse
else:
from django.core.urlresolvers import reverse #noqa
|
e4155ea1c752db8b33bae371f72e43bc05bdb232
|
[
"Python"
] | 1
|
Python
|
klowe0100/filebrowser-safe
|
1c489e67a99437a4d81f684681c4c1bae87409c0
|
2d811494bb1d7be0b99c3b4bbb5e9df29f54695e
|
refs/heads/master
|
<file_sep>package com.compostela.curso.holamundo;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.http.ConnectionReuseStrategy;
public class MainActivity extends ActionBarActivity {
public static final int REQUEST_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Se crea el árbol de objetos que representa la vista
setContentView(R.layout.activity_main);
//Referencia al objeto. Debe ir siempre después del método anterior
Button v = (Button)findViewById(R.id.bt_navegar);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondaryActivity.class);
intent.putExtra("dato", "kq");
startActivity(intent);//Es un método de la clase externa. MainActivity.this.startActivity()
}
});
View implicita = findViewById(R.id.btImplicita);
implicita.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.compostela.curso.holamundo.IMPLICITA");
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void abrirSecundaria(View view) {
Intent intent = new Intent(this, ConResultadoActivitiy.class);
startActivityForResult(intent, REQUEST_CODE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode, data);
String dato = "";
switch(requestCode){
case REQUEST_CODE:
if(resultCode == Activity.RESULT_OK) {
dato = data.getStringExtra("dato");
Toast.makeText(this, "Valor: " + dato, Toast.LENGTH_LONG).show();
}
break;
default:
Toast.makeText(this, "salida defecto", Toast.LENGTH_SHORT).show();
}
}
}
<file_sep>package com.compostela.curso.preferencias;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PreferenciasManualActivity extends ActionBarActivity implements View.OnClickListener {
public static final String KEY_PREFIJO = "prefijo";
public static final String KEY_SUFIJO = "sufijo";
public static final String DEFAULT_PREFIJO = "Hola ";
public static final String DEFAULT_SUFIJO = " !!!!!!!!";
private EditText tp;
private EditText ts;
private SharedPreferences preferences = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Establecer Layout
setContentView(R.layout.activity_preferencias_manual);
//Referenciar componentes visuales a manejar
tp = (EditText)findViewById(R.id.txtPrefijo);
ts = (EditText)findViewById(R.id.txtSufijo);
Button btn = (Button)findViewById(R.id.btnGuardar);
//Establecer los valores de los componentes visuales
preferences = PreferenceManager.getDefaultSharedPreferences(this);
tp.setText(preferences.getString(KEY_PREFIJO, DEFAULT_PREFIJO));
ts.setText(preferences.getString(KEY_SUFIJO, DEFAULT_SUFIJO));
//Establecer los Listeners de los eventos
btn.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_preferencias_manual, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
final SharedPreferences.Editor edit = preferences.edit();
edit.putString(KEY_PREFIJO, tp.getText().toString());
edit.putString(KEY_SUFIJO, ts.getText().toString());
edit.commit();
}
}
<file_sep>package com.compostela.curso.holamundo;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class SecondaryActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondary);
String dato = getIntent().getExtras().getString("dato");
TextView tv = (TextView)findViewById(R.id.lb_saludo);
tv.setText(dato);
}
}
|
bba5a91ac2ae7f87a7385b621b343ee87356d727
|
[
"Java"
] | 3
|
Java
|
kique11/HolaMundo
|
7085e9487c553bde1bff3950807567ffa6e58f57
|
d98015f983430682d9c322fbab0df5a04bbcd050
|
refs/heads/master
|
<repo_name>happyhaijuan/TN<file_sep>/README.md
# TN
# TN
<file_sep>/TNData.java
package wholedta_program;
import com.google.common.collect.Multimap;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by Haijuan on 2/11/2017.
*/
public class TNData extends MapForErrorSet {
public TNData(Multimap<String, String> Multimap) {
super(Multimap);
}
public static void main(String[] args) throws IOException {
FileInputStream Orig = new FileInputStream("D:\\research\\fasqfile\\D1S_5X_R1.fastq\\D1S_5X_R1.fastq");
InputStreamReader inReaderO = new InputStreamReader(Orig, "UTF-8");
BufferedReader bufReaderO = new BufferedReader(inReaderO);
LineNumberReader bufReaderOO = new LineNumberReader(inReaderO);
FileInputStream Prem = new FileInputStream("D:\\research\\fasqfile\\D1S_5X_R1_prem.fastq\\prem.txt");
InputStreamReader inReadP = new InputStreamReader(Prem, "UTF-8");
BufferedReader bufReaderP = new BufferedReader(inReadP);
LineNumberReader bufReaderPP = new LineNumberReader(inReadP);
File f = new File("D:\\research\\data\\qual_score_report\\TN.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
String ReadID = null;
String OriSeq = null;
String PremSeq = null;
String OrigQS;
String PremQS;
String LineO;
String LineP;
int j = 0;
int i = 1;
while ((LineO = bufReaderO.readLine()) != null && (LineP = bufReaderP.readLine()) != null) {
j++;
if (j == i) {
ReadID = LineO.substring(1);
}
else if (j - i == 1) {
OriSeq = LineO;
System.out.println(OriSeq);
PremSeq = LineP;
System.out.println(PremSeq);
System.out.println("Read.id" + " is " + ReadID);
}
else if (j - i == 3) {
OrigQS = LineO;
PremQS = LineP;
// System.out.println("Read.id" + " is " + ReadID);
Collection<String> rr = multimap(ReadID);
if (rr.isEmpty()) {
System.out.println(rr);
for (int k = 1; k <= OriSeq.length(); k++) {
char a = OrigQS.charAt(k-1);
char b = PremQS.charAt(k-1);
int OrigQV = (int) a - 33;
int PremQV = (int) b - 33;
System.out.print(ReadID + " " + k + " "+ OrigQV + " "+ PremQV +" " + "\n");
bw.write(ReadID + " " + k + " "+ OrigQV + " "+ PremQV +" " + "\n");
}
} else if (!rr.isEmpty()) {
System.out.println(ReadID);
System.out.println(!multimap(ReadID).isEmpty());
System.out.println(rr);
// System.out.println(OriSeq);
// System.out.println(PremSeq);
for (int z = 0; z < OriSeq.length(); z++) {
if (OriSeq.charAt(z) == PremSeq.charAt(z) && rr.contains(z + 1) == false) {
char a = OrigQS.charAt(z);
char b = PremQS.charAt(z);
int OrigQV = (int) a - 33;
int PremQV = (int) b - 33;
System.out.print(ReadID + " " + (z + 1) + " "+ OrigQV + " "+ PremQV +" " + "\n");
bw.write(ReadID + " " + (z + 1) + " "+ OrigQV + " "+ PremQV +" " + "\n");
}
}
}
i = i + 4;
System.out.println(j);
}
}
}
}
|
1e220ef9483bb739f1c6e9958941c5328dc04417
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
happyhaijuan/TN
|
9b72b45a08048367e827dc4246063b72552f3d9d
|
78775d2f70ac869e8ff8b98675bc092db8a15d97
|
refs/heads/master
|
<file_sep>import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {BlogComponent} from './view/blog/blog.component';
import {NotFoundComponent} from './view/not-found/not-found.component';
import {LoginComponent} from './view/authentication/login.component';
import {RegisterComponent} from './view/register/register.component';
import {PasswordRecoverComponent} from './view/password-recover/password-recover.component';
import {PostComponent} from './view/post/post.component';
import {PostEditorComponent} from './view/post-editor/post-editor.component';
import {BlogPostFrameComponent} from './components/blog-post-frame/blog-post-frame.component';
import {PostPropertiesInfoComponent} from './components/post-properties-info/post-properties-info.component';
import {FontAwesomeModule} from '@fortawesome/angular-fontawesome';
import {HttpClientModule} from '@angular/common/http';
import { CommentComponent } from './components/comment/comment.component';
@NgModule({
declarations: [
AppComponent,
BlogComponent,
NotFoundComponent,
LoginComponent,
RegisterComponent,
PasswordRecoverComponent,
PostComponent,
PostEditorComponent,
BlogPostFrameComponent,
PostPropertiesInfoComponent,
CommentComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FontAwesomeModule,
NgbModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
<file_sep>import {Injectable} from '@angular/core';
import {RepositoryService} from './repository.service';
import {BlogPost} from '../../models/blog-post';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BlogPostRepositoryService extends RepositoryService<BlogPost> {
private requestParam = '/blogposts';
constructor(protected httpClient: HttpClient) {
super(httpClient);
}
public getAllBlogPosts(): Observable<BlogPost[]> {
return this.getAll(this.requestParam);
}
public getBlogPost(blogPostId: number): Observable<BlogPost> {
return this.get(`${this.requestParam}/${blogPostId}`);
}
}
<file_sep>import { Formatter } from './formatter';
describe('Formatter', () => {
it('should create an instance', () => {
expect(new Formatter()).toBeTruthy();
});
});
<file_sep>import { TestBed } from '@angular/core/testing';
import { BlogPostRepositoryService } from './blog-post-repository.service';
describe('BlogPostRepositoryService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: BlogPostRepositoryService = TestBed.get(BlogPostRepositoryService);
expect(service).toBeTruthy();
});
});
<file_sep>import {Component, Input, OnInit} from '@angular/core';
import {faCalendarDay} from '@fortawesome/free-solid-svg-icons';
import {faUser} from '@fortawesome/free-solid-svg-icons';
import {faBars} from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-post-properties-info',
templateUrl: './post-properties-info.component.html',
styleUrls: ['./post-properties-info.component.scss']
})
export class PostPropertiesInfoComponent implements OnInit {
faCalendarDay = faCalendarDay;
faUser = faUser;
faBars = faBars;
@Input()
date: string;
@Input()
author: string;
@Input()
category: string;
constructor() {
}
ngOnInit() {
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {BlogPost} from '../../models/blog-post';
import {ActivatedRoute} from '@angular/router';
import {Formatter} from '../../utilities/formatter';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.scss']
})
export class PostComponent implements OnInit {
truncateTextWithEllipsis = Formatter.truncateTextWithEllipsis;
blogPost: BlogPost;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.blogPost = this.route.snapshot.data.id;
}
}
<file_sep>import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {NotFoundComponent} from './view/not-found/not-found.component';
import {LoginComponent} from './view/authentication/login.component';
import {RegisterComponent} from './view/register/register.component';
import {BlogComponent} from './view/blog/blog.component';
import {PasswordRecoverComponent} from './view/password-recover/password-recover.component';
import {PostComponent} from './view/post/post.component';
import {BlogPostResolverService} from './services/blog-post-resolver.service';
const routes: Routes = [
{path: '', pathMatch: 'full', component: BlogComponent},
{path: 'post/:id', component: PostComponent, resolve: {id: BlogPostResolverService}},
{path: 'login', component: LoginComponent},
{path: 'register', component: RegisterComponent},
{path: 'password-recover', component: PasswordRecoverComponent},
{path: '**', component: NotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
<file_sep>import {Component, Input, OnInit} from '@angular/core';
import {BlogPost} from '../../models/blog-post';
import {faComments, faEye} from '@fortawesome/free-solid-svg-icons';
import {Formatter} from '../../utilities/formatter';
@Component({
selector: 'app-blog-post-frame',
templateUrl: './blog-post-frame.component.html',
styleUrls: ['./blog-post-frame.component.scss']
})
export class BlogPostFrameComponent implements OnInit {
truncateTextWithEllipsis = Formatter.truncateTextWithEllipsis;
faComments = faComments;
faEye = faEye;
@Input()
blogPost: BlogPost;
constructor() {
}
ngOnInit() {
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {BlogPost} from '../../models/blog-post';
import {Observable} from 'rxjs';
import {BlogPostRepositoryService} from '../../services/repository/blog-post-repository.service';
@Component({
selector: 'app-blog',
templateUrl: './blog.component.html',
styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {
blogPosts: Observable<BlogPost[]> = new Observable<BlogPost[]>();
constructor(private blogPostRepositoryService: BlogPostRepositoryService) {
}
ngOnInit() {
this.blogPosts = this.blogPostRepositoryService.getAllBlogPosts();
}
}
<file_sep>export class Formatter {
public static truncateTextWithEllipsis(text: string, truncateSize: number): string {
return text.length > truncateSize ? `${text.substr(0, truncateSize).trim()}...` : text;
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { BlogPostResolverService } from './blog-post-resolver.service';
describe('BlogPostResolverService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: BlogPostResolverService = TestBed.get(BlogPostResolverService);
expect(service).toBeTruthy();
});
});
<file_sep>import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
import {BlogPost} from '../models/blog-post';
import {Observable} from 'rxjs';
import {BlogPostRepositoryService} from './repository/blog-post-repository.service';
@Injectable({
providedIn: 'root'
})
export class BlogPostResolverService implements Resolve<BlogPost> {
constructor(private blogPostRepositoryService: BlogPostRepositoryService) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<BlogPost> | Promise<BlogPost> | BlogPost {
return this.blogPostRepositoryService.getBlogPost(route.params.id);
}
}
<file_sep>import {User} from './user';
import {PostComment} from './post-comment';
export interface BlogPost {
id: number;
content: string;
title: string;
author: User;
comments: PostComment[];
viewCount: number;
timestamp: Date;
category: string;
commentCount: number;
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class RepositoryService<T> {
// Our service must be run within the bounds of localhost
private endpoint = '/api';
constructor(protected httpClient: HttpClient) {
}
protected get(parameters: string): Observable<T> {
return this.httpClient.get<T>(this.endpoint + parameters);
}
protected getAll(parameters: string): Observable<T[]> {
return this.httpClient.get<T[]>(this.endpoint + parameters);
}
}
<file_sep># FrameworkDigitalBlogWebApp
Este projeto utiliza a versão 8.3.29 do Angular. (LTS)
## Observações
**MUITO IMPORTANTE: A aplicação, infelizmente, não está finalizada neste instante, por motivos de falta de tempo hábil para tal.**
Não é possível adicionar conteúdo, apenas navegar pelo que já está criado.
Executando o comando `ng serve` do NPM deve ser suficiente para executar a aplicação, *mas* é importante frisar que nas configurações do arquivo angular.json adicionei um arquivo de proxy, remapeando as conexões locais feitas do localhost:8080 (servidor Java, que deve estar rodando em background) para evitar possíveis erros de cross-origin (que são comuns no Angular).
Mas, se por algum motivo, `ng serve` não for suficiente e a aplicação não estabelecer comunicação com o back-end, execute `ng serve --proxy-config proxy.conf.json`. Isso fará com que a comunicação com o servidor (localhost:8080) seja remapeada para o caminho localhost:400/api/* sem problemas.
A aplicação será executada, como default, em localhost:4200
Não utilize build de produção. Não testei a build com --prod.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
<file_sep>import {User} from './user';
export interface PostComment {
user: User;
content: string;
}
|
689f27f100da6f70859eca596dbb6c2c673dd147
|
[
"Markdown",
"TypeScript"
] | 16
|
TypeScript
|
raphaelheizer/BlogWebApp
|
b74892f6d4415e168aa32ad553c1dcd0426f4e08
|
61a29f52e4fade973c39fd6d0bd56e9f58c300d7
|
refs/heads/master
|
<file_sep>#! /bin/sh
### BEGIN INIT INFO
# Provides: zebrasrv-2.0
# Required-Start: $local_fs $remote_fs $network $named $time
# Required-Stop: $local_fs $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Controls the zebrasrv daemon
# Description: Controls the zebrasrv /usr/bin/zebrasrv.
### END INIT INFO
# On servers getting their address from a DHCP server it might be useful to add in /etc/network/interfaces
# the line:
# post-up /etc/init.d/myzeb restart
# Do NOT "set -e"
# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
NAME=zebrasrv-2.0
IDXNAME=zebraidx-2.0
DAEMON=/usr/bin/$NAME
SCRIPTNAME=/etc/init.d/myzeb
# ReqStart: $local_fs $remote_fs $network $named $time
# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
ZEBRASRV_BIN=/usr/bin/$NAME
ZEBRAIDX_BIN=/usr/bin/$IDXNAME
catfile=/etc/myzeb-catalogue
PS="ps -o pid -o pid= -o comm= -p ";
if [ ! -x $ZEBRASRV_BIN ]; then
echo "Zebra is not installed in '$ZEBRASRV_BIN'"
exit 0
fi
if [ ! -f $catfile ]; then
echo "Zebra catalogue is missing"
exit 0
fi
service=$2
case "$1" in
start)
while read line; do
line=`echo "$line" | sed 's/#.*//'`
line=`echo "$line" | sed 's/[ \t]*$//'`
if [ "x$line" != x ]; then
set $line; tag=$1; usergroup=$2; dir=$3; file=$4; listen=$5;
help=`echo "$usergroup" | sed 's/\// /'`
set $help; user=$1; group=$2;
#echo "tag='$tag', dir='$dir', file='$file', user='$user', group='$group'"
logfile="$dir/log/zebrasrv-$tag.log"
pidfile="$dir/lock/zebrasrv-$tag.pid"
if [ "x$service" = "x" ] || [ "x$service" = "x$tag" ]; then
if [ -f $pidfile ]; then
echo -n "Zebra service '$tag' seems to be activated already"
pid=`cat $pidfile`
res=`$PS $pid | sed 's/.*PID[ \t\r\n]*//'`;
if [ "x$res" != "x" ]; then
echo ""
continue
else
echo "... Oh no, it was killed."
rm $pidfile
fi
fi
if [ ! -f $dir/$file ]; then
echo "Zebra service '$tag' '$file' seems to be missing"
continue
fi
echo -n "Starting Zebra service '$tag' ... "
case "$file" in
*.xml) opt="-f $file";;
*.cfg) opt="-c $file $listen";;
*) echo -n "error : Unrecognised Zebra config-file type: '$file'";;
esac
if [ "x$opt" != x ]; then
start-stop-daemon --start --quiet --background --pidfile $pidfile -g $group --exec $ZEBRASRV_BIN -- -w $dir -u $user -l $logfile -p $pidfile $opt;
sleep 1
if [ -f $pidfile ] ; then
echo -n "started"
else
echo -n "error"
fi
fi
echo
fi
fi
done < $catfile
;;
stop)
# Unfortunate partial duplication of parsing code here
while read line; do
line=`echo "$line" | sed 's/#.*//'`
line=`echo "$line" | sed 's/[ \t]*$//'`
if [ "x$line" != x ]; then
set $line; tag=$1; usergroup=$2; dir=$3; file=$4; listen=$5;
help=`echo "$usergroup" | sed 's/\// /'`
set $help; user=$1; group=$2;
#echo "tag='$tag', dir='$dir', file='$file', user='$user', group='$group'"
if [ "x$service" = "x" ] || [ "x$service" = "x$tag" ]; then
pidfile="$dir/lock/zebrasrv-$tag.pid"
if [ ! -f $pidfile ]; then
echo "Zebra service '$tag' does not seem to be running"
continue
fi
pid=`cat $pidfile`
#echo $pid
#res=`$PS $pid | sed 's/.*PID[ \t\r\n]*//'`;
#echo $res
echo -n "Stopping Zebra service '$tag' pid='$pid' "
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --oknodo -g $group --pidfile $pidfile --name $NAME ;
res=`$PS $pid | sed 's/.*PID[ \t\r\n]*//'`;
#echo $res
if [ "x$res" != "x" ]; then
echo -n "running "
else
echo -n "killed "
rm $pidfile
fi
echo ''
# if $PS $pid > /dev/null 2>&1 ; then
# echo "Stopping Zebra service '$tag' pid='$pid'"
# awkcmd='{ if ( \$2 == '$pid' ) { print \$1 }}'
# for child in `ps -o pid --ppid $pid`
# do
# if [ $child != "PID" ]; then
# echo "Killing child process $child because ppid = $pid"
# #kill $child
# fi
# done
# #kill $pid
# echo "kill $pid"
# #rm $pidfile
# fi
fi
fi
done < $catfile
;;
verify)
while read line; do
line=`echo "$line" | sed 's/#.*//'`
line=`echo "$line" | sed 's/[ \t]*$//'`
if [ "x$line" != x ]; then
set $line; tag=$1; usergroup=$2; dir=$3; file=$4; listen=$5;
help=`echo "$usergroup" | sed 's/\// /'`
set $help; user=$1; group=$2;
#echo "tag='$tag', dir='$dir', file='$file', user='$user', group='$group'"
if [ "x$service" = "x" ] || [ "x$service" = "x$tag" ]; then
echo -n "Verifing zebra: "
echo -n "$tag " ;
pidfile="$dir/lock/zebrasrv-$tag.pid"
if [ -f $pidfile ] ; then
pid=`cat $pidfile`
res=`$PS $pid | sed 's/.*PID[ \t\r\n]*//'`;
if [ "x$res" != "x" ]; then
echo -n "running "
else
echo -n "killed "
rm $pidfile
fi
else
echo -n "stopped "
fi
echo
fi
fi
done < $catfile
;;
index)
while read line; do
line=`echo "$line" | sed 's/#.*//'`
line=`echo "$line" | sed 's/[ \t]*$//'`
if [ "x$line" != x ]; then
set $line; tag=$1; usergroup=$2; dir=$3; file=$4; listen=$5;
help=`echo "$usergroup" | sed 's/\// /'`
set $help; user=$1; group=$2;
#echo "tag='$tag', dir='$dir', file='$file', user='$user', group='$group'"
if [ "x$service" = "x" ] || [ "x$service" = "x$tag" ]; then
echo "Indexing zebra: $tag "
$0 stop $tag
sleep 2
DB=`cat "$dir/$file" | grep "database:" | sed 's/^database: *//'`
cd $dir/register
rm -f *.mf
cd $dir
$ZEBRAIDX_BIN -n create $DB
$ZEBRAIDX_BIN -n update records
chown -R $user:$group register
$0 start $tag
fi
fi
done < $catfile
;;
restart)
$0 stop $service
sleep 2
$0 start $service
;;
*)
echo "Usage: $0 start|stop|verify|restart" >&2
;;
esac
:
|
9ca8e1b60cf601af10303826c14156cfc5f2e0f4
|
[
"Shell"
] | 1
|
Shell
|
kosmasgiannis/zebra-cfg-bib-dom
|
46161ae1161247980b5e1212a8fa689830ff9e29
|
b2236565f57f418f60d87240768c559e6f2a7c73
|
refs/heads/master
|
<repo_name>Shubham707/eduplau<file_sep>/application/controllers/Bitcoin.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* developed by <NAME>
*/
include APPPATH . 'third_party/jsonRPCClient.php';
include APPPATH . 'third_party/Client.php';
class Bitcoin extends CI_Controller
{
public function __construct()
{
parent::__construct();
//$this->load->model('Daemon_model');
//$this->load->database();
}
public function index()
{
//$data=$this->Daemon_model->daemonData();
/*$user=$data[0]->daemon_name;
$pass=$data[0]->daemon_password;
$ip=$data[0]->daemon_ip;
$port=$data[0]->daemon_port;*/
$host='localhost';
$port='8011';
$user='PennyBaseCoinrpc';
$pass='<PASSWORD>';
$deamon=new Client($host, $port, $user, $pass);
$response= $deamon->getTransactionList('<EMAIL>');
print_r($response);
}
}<file_sep>/application/views/page/login.php
<?php
if($this->session->userdata('user_id'))
{
redirect(base_url().'login/profile');
}
$this->load->view('page/header');
?>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$(function()
{
$("form[name='frm']").validate({
rules: {
user_email: {
required: true,
email: true
},
user_pass: {
required: true,
minlength: 5
}
},
messages: {
user_pass: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
user_email: {
required: "Please Enter your Email Id",
email: "Please Enter The Valid Email"
},
},
submitHandler: function(form)
{
form.submit();
}
});
});
});
</script>
<div id="blog" class="section">
<!-- Container -->
<div class="container">
<!-- Row -->
<div class="row">
<!-- Main -->
<main id="main" class="col-md-6 offset-md-4">
<div class="">
<!-- /blog comments -->
<!-- reply form -->
<div class="reply-form">
<h3 style="color: white;" class="">User Login </h3>
<div style="border: 2px solid red;padding: 50px;">
<form method="post" name="frm" action="<?php echo base_url();?>login/login_user">
<input class="input" type="email" name="user_email" id="user_email" placeholder="Email"><br>
<input class="input" type="password" name="user_pass" id="user_pass" placeholder="<PASSWORD>******"><br>
<input type="submit" class="main-btn" name="login" id="login" value="Submit"><br><br>
<a href="<?php echo base_url();?>login/signup_user">SignUp</a>
<a style="margin-left: 20px;" href="<?php echo base_url();?>login/forget">Forget Password</a>
</form>
</div>
</div>
<!-- /reply form -->
</div>
</main>
<!-- /Main -->
</div>
<!-- /Row -->
</div>
<!-- /Container -->
</div>
<!-- /Blog -->
<!-- Footer -->
<!-- Back to top -->
<div id="back-to-top"></div>
<!-- /Back to top -->
<!-- Preloader -->
<div id="preloader">
<div class="preloader">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<!-- /Preloader -->
<!-- jQuery Plugins -->
<script type="text/javascript" src="<?php echo base_url();?>creative/js/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>creative/js/bootstrap.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>creative/js/owl.carousel.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>creative/js/jquery.magnific-popup.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>creative/js/main.js"></script>
|
fe08fbe30c5508ec7f9fa23febcc12caddbdbc15
|
[
"PHP"
] | 2
|
PHP
|
Shubham707/eduplau
|
00be240a0ef9b2ff585632f08599dd5010210260
|
58c417a533891f77734890483ae6aaa60df645a7
|
refs/heads/master
|
<repo_name>cuckoong/EB_spikes_trains<file_sep>/mcmc.py
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm
import theano.tensor as tt
from pymc3 import *
from models import SOD
import theano
az.rcParams['plot.matplotlib.show'] = True
if __name__ == '__main__':
#
seed_beta = 12
n_sim = 50
n_bin = 500
n_neuron = 100
s = 50
n_sample = n_sim * n_bin
r = 5
gam = 7
density = 0.2
filename = 'sod_sod_fb_sim_{}_bin{}_r_{}_s_{}_gam_{}_neuron_{}_density_{}_beta_{}_X_{}_10x_sigma_trace.trace'.format(n_sim,
n_bin, r,
s, gam,
n_neuron,
density,
seed_beta,
101)
x, y, y_true = SOD().simulate(n_sim=n_sim, n_bin=n_bin, n_neuron=n_neuron, density=density, seed_beta=seed_beta,
seed_X=101, s=s, r=r, gam=gam)
y_mean = y.reshape(n_sim, n_bin)
y_mean = np.mean(y_mean, axis=0)
y_mean = np.tile(y_mean, n_sim)
# data = dict(x=x, y=y)
x_shared = theano.shared(x)
y_shared = theano.shared(y)
y_mean = theano.shared(y_mean)
with Model() as model: # model specifications in PyMC3 are wrapped in a with-statement
# Define priors
# BoundNormal0 = Bound(Normal, lower=1)
r = TruncatedNormal("r", mu=5, sigma=10, lower=0) # , mu=5, sd=1)
gam = TruncatedNormal("gam", mu=7, sigma=10, lower=0) # , mu=5, sd=1)
s = TruncatedNormal("s", mu=50, sigma=10, lower=0) # , mu=50, sd=1)
beta0 = Normal("beta0", mu=0, sigma=1)
beta = TruncatedNormal("beta", mu=0, sigma=1, lower=-1, upper=1, shape=n_neuron)
# mu
mu = (gam * pm.math.exp(beta0 + pm.math.dot(x_shared, beta)) + 1) ** (-1 / gam)
y_op = Deterministic('y_op', r * (1 / mu - 1))
# phi
phi = Deterministic('phi', (s*mu+n_sim*r)/(s+n_sim*r+n_sim*y_mean))#, shape=n_sample)
# Define likelihood
likelihood = NegativeBinomial("y", alpha=r, mu=r * (1 / phi - 1), observed=y_shared) # attention
#Inference!
idata = sample(1000, cores=4, progressbar=True, chains=4, tune=2000, return_inferencedata=False)
az.to_netcdf(idata, filename)
print(az.summary(idata, var_names=['r', 'gam', 's']))
'''
with model:
idata = az.from_netcdf(filename)
# az.plot_trace(idata, var_names=['r','gam','s','beta0'])
print(az.summary(idata, var_names=['r', 'gam', 's']))
# print('')
'''
<file_sep>/snn.py
from brian2 import *
import pandas as pd
import numpy as np
#import brian2genn
#set_device('genn')#, use_GPU= False)
#prefs.devices.genn.cuda_backend.extra_compile_args_nvcc += ['--verbose']
#prefs.devices.genn.path='/home/msc/genn'
#prefs.devices.genn.cuda_backend.cuda_path='/usr/local/cuda-9.0'
if __name__ == '__main__':
N = 100
F = 50 * Hz
input = PoissonGroup(N, F)
P_neurons = 100
taum = 20 * ms
taue = 5 * ms
taui = 10 * ms
Vt = -50 * mV
Vr = -60 * mV
El = -49 * mV
sigma = 0.5 * (Vt - Vr)
eqs = '''
dv/dt = (ge+gi-(v-El))/taum+sigma*xi*taum**-0.5 : volt (unless refractory)
dge/dt = -ge/taue : volt
dgi/dt = -gi/taui : volt
'''
# second part
P = NeuronGroup(100, eqs, threshold='v>Vt', reset='v = Vr', refractory=5 * ms,
# method='exact')
method='euler')
P.v = 'Vr + rand() * (Vt - Vr)'
P.ge = 0 * mV
P.gi = 0 * mV
we = (60 * 0.27 / 10) * mV # excitatory synaptic weight (voltage)
wi = (-20 * 4.5 / 10) * mV # inhibitory synaptic weight
Ce = Synapses(input, P, on_pre="ge += we", delay=10*ms)
Ci = Synapses(input, P, on_pre="gi += wi", delay=10*ms)
Ce.connect('i<80', p=0.2)
Ci.connect('i>=80', p=0.2)
mon = SpikeMonitor(input)
s_mon = SpikeMonitor(P)
duration = 2500*1000
run(duration * ms, report='text')
out, idx = pd.cut([0, duration], bins=int(duration / 100), retbins=True) # 100ms per bin
# spike_count_y = pd.cut(s_mon.spike_trains()[0]/second*1000, bins=idx)
# y = spike_count_y.value_counts().values
y = []
for tmp in range(100):
spike_time = s_mon.spike_trains()[tmp] / second * 1000
spike_count = pd.cut(spike_time, bins=idx)
y.append(spike_count.value_counts().values)
y = np.vstack(y).T
X = []
for tmp in range(100):
spike_time = mon.spike_trains()[tmp] / second * 1000
spike_count = pd.cut(spike_time, bins=idx)
X.append(spike_count.value_counts().values)
X = np.vstack(X).T
np.save('X_100ms_100.npy', X)
np.save('y_100ms_100.npy', y)
print('done')
<file_sep>/models.py
import numpy as np
import scipy.special as sc
from scipy import stats
import scipy
from scipy import optimize
from scipy.optimize import basinhopping
import scipy.sparse as sps
from scipy.special import digamma
import pickle
from sklearn.base import BaseEstimator
from sklearn.metrics import r2_score, mean_squared_error
def my_score_fun(clf, X, y):
x0 = clf.op.x
possitive_LLsum = -1*clf.objective(x0, X, y)
return possitive_LLsum
def optimize_fun(fun, der, x0, X, y, bnds, basin=True):
if basin:
op = basinhopping(fun, x0, niter=50, T=10, niter_success=20, disp=True,
minimizer_kwargs={'method': 'L-BFGS-B', 'bounds': bnds, 'jac': der,
'args': (X, y), 'options': {'maxiter': 5000}})
else:
op = scipy.optimize.minimize(fun, x0, args=(X, y), bounds=bnds, method='L-BFGS-B', jac=der,
options={'disp': True, 'maxiter': 5000})
return op
class SOD(BaseEstimator):
def __init__(self, lam=1, alpha=0.5, op=None, y_mean=None):
self.type = 'SOD'
self.lam = lam
self.alpha = alpha
self.op = op
self.y_mean = y_mean
def simulate(self, n_sim, n_bin, n_neuron, seed_beta=42, seed_X=42, s=None, r=None, gam=None, density=0.2,
get_y_true=True):
"""
:param n_sim: simulation trial
:param n_bin: data length
:param n_neuron: neuron number
:param seed_beta: seed for beta
:param seed_X: seed for X
:param s: sigma
:param r: negative binomial shape
:param gam: link function parameters
:param density: density for sparse weights
:return: X, y (simulated data)
"""
np.random.seed(seed_beta)
beta0 = np.random.uniform(-1, 1)
rvs = stats.uniform(loc=-1, scale=2).rvs
beta = sps.random(1, n_neuron, density=density, data_rvs=rvs).toarray()[0]
# simulate data X
np.random.seed(seed_X)
X = np.random.normal(0.0, 1.0, [n_bin, n_neuron])
mu = (gam * np.exp(beta0 + np.dot(X, beta)) + 1) ** (-1 / gam)
y_true = r * (1 / mu - 1) # true y value
# simulate y_sim
rng = np.random.default_rng(42)
phi = rng.beta(s * mu, s * (1 - mu))
y = rng.negative_binomial(n=r, p=phi, size=(n_sim, len(phi)))
X = np.vstack([X for i in range(n_sim)])
y = np.reshape(y, (n_sim * n_bin,))
y_true = np.hstack([y_true for i in range(n_sim)])
if get_y_true:
return X, y, y_true
else:
return X, y
def get_params(self, deep=True):
return {'lam': self.lam, 'op': self.op, 'y_mean':self.y_mean}
def objective(self, x0, X, y):
r = x0[0]
gam = x0[1]
s = x0[2]
beta0 = x0[3]
beta = x0[4:]
mu = (gam * np.exp(beta0 + np.dot(X, beta)) + 1) ** (-1 / gam)
LL_sum = -1 * np.sum(sc.gammaln(r + s * mu) +
sc.gammaln(y + s - s * mu + np.finfo(np.float32).eps) +
sc.gammaln(r + y) +
sc.gammaln(s) -
sc.gammaln(r + y + s) -
sc.gammaln(r) -
sc.gammaln(s * mu + np.finfo(np.float32).eps) -
sc.gammaln(s - s * mu + np.finfo(np.float32).eps))
LL_sum += self.lam * (self.alpha * np.sum(np.abs(beta)) + 1 / 2 * (1 - self.alpha) * np.sum(beta ** 2))
return LL_sum
def LL(self, x0, X, y):
r = x0[0]
gam = x0[1]
s = x0[2]
beta0 = x0[3]
beta = x0[4:]
mu = (gam * np.exp(beta0 + np.dot(X, beta)) + 1) ** (-1 / gam)
LL_sum = np.sum(sc.gammaln(r + s * mu) + sc.gammaln(y + s - s * mu) +
sc.gammaln(r + y) +
sc.gammaln(s) -
sc.gammaln(r + y + s) -
sc.gammaln(r) -
sc.gammaln(s * mu) -
sc.gammaln(s - s * mu))
return LL_sum
def der(self, x0, X, y):
r = x0[0]
gam = x0[1]
s = x0[2]
beta0 = x0[3]
beta = x0[4:]
der = np.zeros_like(x0)
g_est = np.exp(beta0 + np.dot(X, beta))
mu = (gam * g_est + 1) ** (-1 / gam)
mu_gam = gam * g_est + 1
der_mu_over_gam = (np.log(mu_gam) / gam ** 2 - g_est / gam / mu_gam) * mu
der_mu_over_beta = -1 * X * (g_est * mu / mu_gam).reshape(-1, 1)
der_mu_over_beta0 = -1 * g_est * (gam * g_est + 1) ** (-1 / gam - 1)
A = digamma(r + s * mu) - digamma(s * mu + np.finfo(np.float32).eps)
B = digamma(y + s - s * mu + np.finfo(np.float32).eps) - digamma(s - s * mu + np.finfo(np.float32).eps)
C = digamma(s) - digamma(r + y + s)
der[0] = -1 * np.sum(digamma(r + s * mu) + digamma(r + y) - digamma(r + y + s) - digamma(r))
der[1] = -1 * np.sum(der_mu_over_gam * (A - B))
der[2] = -1 * np.sum(A * mu + B * (1 - mu) + C)
der[3] = -1 * s * np.sum(der_mu_over_beta0 * (A - B))
der[4:] = -1 * s * np.sum(der_mu_over_beta * (A - B).reshape(-1, 1), axis=0) + \
self.lam * (self.alpha * np.sign(beta) + (1 - self.alpha) * beta)
return der
def fit(self, X, y):
n_neuron = X.shape[1]
# bounds
r_bound = [1, np.inf] # need attention
gam_bound = [np.finfo(np.float32).eps, np.inf] # [1, np.inf]
s_bound = [1, np.inf]
beta0_bound = [None, None]
beta_bound = [-1, 1]
bnds = [r_bound, gam_bound, s_bound, beta0_bound]
bnds.extend([beta_bound] * X.shape[1])
# initials
r0 = np.random.uniform(1, 100, 1)[0]
gam0 = np.random.uniform(np.finfo(np.float32).eps, 100, 1)[0]
s0 = np.random.uniform(1, 100, 1)[0]
beta0_initial = np.random.uniform(-1, 1, 1)[0]
beta_initial = np.random.uniform(-1, 1, n_neuron)[0:n_neuron]
x0 = [r0, gam0, s0, beta0_initial]
x0.extend(beta_initial)
# optimization using scipy
self.op = optimize_fun(self.objective, self.der, x0, X, y, bnds)
self.y_mean = np.mean(y)
return self
def predict(self, X, real=True):
op = self.op
r_op = op['x'][0]
gam_op = op['x'][1]
s_op = op['x'][2]
beta0_op = op['x'][3]
beta_op = op['x'][4:]
mu_op = (gam_op * np.exp(beta0_op + np.dot(X, beta_op)) + 1) ** (-1 / gam_op)
if real:
y_op = r_op * (1 / mu_op - 1) # estimated y value
else:
n_sim = len(X)
phi_op = (s_op * mu_op + n_sim * r_op)/(s_op + n_sim * self.y_mean + n_sim * r_op)
y_op = r_op * (1 / phi_op - 1)
return y_op
def evaluate(self, X, y_true, metrics='r2'):
y_op = self.predict(X)
if metrics == 'mse':
mse = mean_squared_error(y_true, y_op)
# print(mse)
return mse
elif metrics == 'r2':
r2 = r2_score(y_true, y_op)
# print(r2)
return r2
def save(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self, f)
class NBGLM(BaseEstimator):
def __init__(self, lam=1, alpha=0.5, op=None):
self.type = 'NBGLM'
self.lam = lam
self.alpha = alpha
self.op = op
def simulate(self, n_sim, n_bin, n_neuron, seed_beta=42, seed_X=42, r=None, gam=None, density=0.2,
get_y_true=True):
"""
:param n_sim: simulation trial
:param n_bin: data length
:param n_neuron: neuron number
:param seed_beta: seed for beta
:param seed_X: seed for X
:param s: sigma
:param r: negative binomial shape
:param gam: link function parameters
:param density: density for sparse weights
:return: X, y (simulated data)
"""
np.random.seed(seed_beta)
beta0 = np.random.uniform(-1, 1)
rvs = stats.uniform(loc=-1, scale=2).rvs
beta = sps.random(1, n_neuron, density=density, data_rvs=rvs).toarray()[0]
# simulate data X
np.random.seed(seed_X)
X = np.random.normal(0.0, 1.0, [n_bin, n_neuron])
mu = (gam * np.exp(beta0 + np.dot(X, beta)) + 1) ** (-1 / gam)
y_true = r * (1 / mu - 1) # true y value
# simulate y_sim
rng = np.random.default_rng(42)
y = rng.negative_binomial(n=r, p=mu, size=(n_sim, len(mu)))
X = np.vstack([X for i in range(n_sim)])
y = np.reshape(y, (n_sim * n_bin,))
y_true = np.hstack([y_true for i in range(n_sim)])
if get_y_true:
return X, y, y_true
else:
return X, y
def get_params(self, deep=True):
return {'lam': self.lam, 'op': self.op}
def objective(self, x0, X, y):
r = x0[0]
gam = x0[1]
beta0 = x0[2]
beta = x0[3:]
mu = (gam * np.exp(beta0 + np.dot(X, beta)) + 1) ** (-1 / gam)
LL_sum = -1 * np.sum(sc.gammaln(r + y) - sc.gammaln(r) +
r * np.log(mu + np.finfo(np.float32).eps) +
y * np.log(1 - mu + np.finfo(np.float32).eps))
LL_sum += self.lam * (self.alpha * np.sum(np.abs(beta)) + 1 / 2 * (1 - self.alpha) * np.sum(beta ** 2))
return LL_sum
def LL(self, x0, X, y):
r = x0[0]
gam = x0[1]
beta0 = x0[2]
beta = x0[3:]
mu = (gam * np.exp(beta0 + np.dot(X, beta)) + 1) ** (-1 / gam)
LL_sum = np.sum(sc.gammaln(r + y) - sc.gammaln(r) + r * np.log(mu) + y * np.log(1 - mu))
return LL_sum
def der(self, x0, X, y):
r = x0[0]
gam = x0[1]
beta0 = x0[2]
beta = x0[3:]
der = np.zeros_like(x0)
g_est = np.exp(beta0 + np.dot(X, beta))
mu = (gam * g_est + 1) ** (-1 / gam)
mu_gam = gam * g_est + 1
der_mu_over_gam = (np.log(mu_gam) / gam ** 2 - g_est / gam / mu_gam) * mu
der_mu_over_beta = -1 * X * (g_est * mu / mu_gam).reshape(-1, 1)
der_mu_over_beta0 = -1 * g_est * (gam * g_est + 1) ** (-1 / gam - 1)
A = r / mu - y / (1 - mu)
der[0] = -1 * np.sum(digamma(r + y) - digamma(r) + np.log(mu + np.finfo(np.float32).eps))
der[1] = -1 * np.sum(A * der_mu_over_gam)
der[2] = -1 * np.sum(A * der_mu_over_beta0)
der[3:] = -1 * np.sum(der_mu_over_beta * A.reshape(-1, 1), axis=0) + \
self.lam * (self.alpha * np.sign(beta) + (1 - self.alpha) * beta)
return der
def fit(self, X, y):
n_neuron = X.shape[1]
# bounds
r_bound = [1, np.inf] # need attention
gam_bound = [np.finfo(np.float32).eps, np.inf]
beta0_bound = [None, None]
beta_bound = [-1, 1]
bnds = [r_bound, gam_bound, beta0_bound]
bnds.extend([beta_bound] * n_neuron)
# initial guess
# initials
r0 = np.random.uniform(1, 100, 1)[0]
gam0 = np.random.uniform(np.finfo(np.float32).eps, 100, 1)[0]
beta0_initial = np.random.uniform(-1, 1, 1)[0]
beta_initial = np.random.uniform(-1, 1, n_neuron)
x0 = [r0, gam0, beta0_initial]
x0.extend(beta_initial)
# optimization using scipy
self.op = optimize_fun(self.objective, self.der, x0, X, y, bnds)
return self
def predict(self, X, real=True):
op = self.op
r_op = op['x'][0]
gam_op = op['x'][1]
beta0_op = op['x'][2]
beta_op = op['x'][3:]
mu_op = (gam_op * np.exp(beta0_op + np.dot(X, beta_op)) + 1) ** (-1 / gam_op)
y_op = r_op * (1 / mu_op - 1) # estimated y value
return y_op
def evaluate(self, X, y, metrics='r2'):
y_op = self.predict(X)
if metrics == 'mse':
mse = mean_squared_error(y, y_op)
print(mse)
return mse
elif metrics == 'r2':
r2 = r2_score(y, y_op)
print(r2)
return r2
def save(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self, f)
class POISSON(BaseEstimator):
def __init__(self, lam=1, alpha=0.5, op=None):
self.type = 'poisson'
self.lam = lam
self.alpha = alpha
self.op = op
def simulate(self, n_sim, n_bin, n_neuron, seed_beta=42, seed_X=42, density=0.2, get_y_true=True):
"""
:param n_sim: simulation trial
:param n_bin: data length
:param n_neuron: neuron number
:param seed_beta: seed for beta
:param seed_X: seed for X
:param s: sigma
:param r: negative binomial shape
:param gam: link function parameters
:param density: density for sparse weights
:return: X, y (simulated data)
"""
np.random.seed(seed_beta)
beta0 = np.random.uniform(-1, 1)
rvs = stats.uniform(loc=-1, scale=2).rvs
beta = sps.random(1, n_neuron, density=density, data_rvs=rvs).toarray()[0]
# simulate data X
np.random.seed(seed_X)
X = np.random.normal(0.0, 1.0, [n_bin, n_neuron])
y_true = np.log(1+np.exp(beta0 + np.dot(X, beta)))
# simulate y_sim
rng = np.random.default_rng(42)
y = rng.poisson(lam=y_true, size=(n_sim, len(y_true)))
X = np.vstack([X for _ in range(n_sim)])
y = np.reshape(y, (n_sim * n_bin,))
y_true = np.hstack([y_true for _ in range(n_sim)])
if get_y_true:
return X, y, y_true
else:
return X, y
def get_params(self, deep=True):
return {'lam': self.lam, 'op': self.op}
def objective(self, x0, X, y):
beta0 = x0[0]
beta = x0[1:]
mu = np.log(1+np.exp(beta0 + np.dot(X, beta)))
LL_sum = -1 * np.sum(y * np.log(mu) - mu)
LL_sum += self.lam * (self.alpha * np.sum(np.abs(beta)) + 1 / 2 * (1 - self.alpha) * np.sum(beta ** 2))
return LL_sum
def LL(self, x0, X, y):
beta0 = x0[0]
beta = x0[1:]
mu = np.log(1+np.exp(beta0 + np.dot(X, beta)))
LL_sum = np.sum(y * np.log(mu) - mu)
return LL_sum
def der(self, x0, X, y):
beta0 = x0[0]
beta = x0[1:]
der = np.zeros_like(x0)
mu = np.log(1 + np.exp(beta0 + np.dot(X, beta)))
der[0] = -1 * np.sum((y/mu - 1) *
np.exp(beta0 + np.dot(X, beta))/(np.exp(beta0 + np.dot(X, beta))+1)
)
der[1:] = -1 * np.sum(X * ((y/mu - 1) *
np.exp(beta0 + np.dot(X, beta)) / (np.exp(beta0 + np.dot(X, beta)) + 1)).reshape(-1, 1),
axis=0) + \
self.lam * (self.alpha * np.sign(beta) + (1 - self.alpha) * beta)
return der
def fit(self, X, y):
n_neuron = X.shape[1]
# bounds
beta0_bound = [None, None]
beta_bound = [-1, 1]
bnds = [beta0_bound]
bnds.extend([beta_bound] * n_neuron)
# initial guess
# initials
beta0_initial = np.random.uniform(-1, 1, 1)[0]
beta_initial = np.random.uniform(-1, 1, n_neuron)
x0 = [beta0_initial]
x0.extend(beta_initial)
# optimization using scipy
self.op = optimize_fun(self.objective, self.der, x0, X, y, bnds)
def predict(self, X, real=True):
op = self.op
beta0_op = op['x'][0]
beta_op = op['x'][1:]
y_op = np.log(1 + np.exp(beta0_op + np.dot(X, beta_op))) # estimated y value
return y_op
def evaluate(self, X, y, metrics='r2'):
y_op = self.predict(X)
if metrics == 'mse':
mse = mean_squared_error(y, y_op)
print(mse)
return mse
elif metrics == 'r2':
r2 = r2_score(y, y_op)
print(r2)
return r2
def save(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self, f)
class step_SOD(BaseEstimator):
def __init__(self, lam=1, alpha=0.5, op=None):
self.type = 'SOD'
self.lam = lam
self.alpha = alpha
self.op = op
def simulate(self, n_sim, n_bin, n_neuron, seed_beta=42, seed_X=42, s=None, r=None, gam=None, density=0.2,
get_y_true=True):
"""
:param n_sim: simulation trial
:param n_bin: data length
:param n_neuron: neuron number
:param seed_beta: seed for beta
:param seed_X: seed for X
:param s: sigma
:param r: negative binomial shape
:param gam: link function parameters
:param density: density for sparse weights
:return: X, y (simulated data)
"""
np.random.seed(seed_beta)
beta0 = np.random.uniform(-1, 1)
rvs = stats.uniform(loc=-1, scale=2).rvs
# 2 step model
beta = sps.random(2, n_neuron, density=density, data_rvs=rvs).toarray()
# simulate data X
np.random.seed(seed_X)
X = np.random.normal(0.0, 1.0, [n_bin+1, n_neuron])
step_one = np.dot(X[:-1,:], beta[0])
step_two = np.dot(X[1:,:], beta[1])
mu = (gam * np.exp(beta0 + step_one +step_two) + 1) ** (-1 / gam)
y_true = r * (1 / mu - 1) # true y value
# simulate y_sim
rng = np.random.default_rng(42)
phi = rng.beta(s * mu, s * (1 - mu))
y = rng.negative_binomial(n=r, p=phi, size=(n_sim, len(phi)))
X = np.vstack([X[1:,:] for i in range(n_sim)])
y = np.reshape(y, (n_sim * n_bin,))
y_true = np.hstack([y_true for i in range(n_sim)])
if get_y_true:
return X, y, y_true
else:
return X, y
<file_sep>/README.md
# EB_spikes_trains
Python Code for Paper: An Efficient and Flexible Spike Train Model via Empirical Bayes [Link](https://arxiv.org/abs/1605.02869)
## [models.py](https://github.com/cuckoong/EB_spikes_trains/blob/master/models.py)
Simulation and Estimations using the 'SODS', NB-GLM, Poisson-GLM models.
## [snn.py](https://github.com/cuckoong/EB_spikes_trains/blob/master/snn.py)
Simulation for Spiking Neural Network Data
## [mcmc.py](https://github.com/cuckoong/EB_spikes_trains/blob/master/mcmc.py)
Estimation using MCMC (NUTS).
## [examples.py](https://github.com/cuckoong/EB_spikes_trains/blob/master/examples.py)
Examples of simulation and estimations using the 'SODS', NB-GLM, Poisson-GLM models. (To be done)
# package required:
python \
brian2 \
matplolib \
scipy \
numpy \
pandas \
scikit-learn \
pymc3
|
2380830f9edbf6e41e10ecaf134905a2b8c9ea43
|
[
"Markdown",
"Python"
] | 4
|
Python
|
cuckoong/EB_spikes_trains
|
5cf7ae9240dc5b6a5d04711a33e55dd1af256f7c
|
5cc22ce479e136659659ce109bb18752447b4462
|
refs/heads/master
|
<repo_name>guowei12/201703vote<file_sep>/public/javascripts/vote.js
let limit = 10;//每页10条数据
let offset = 80;//起始的索引
let voteFn = {
//此方法用于将用户user转成模板字符串
formatUser(user){
return (
`<li>
<div class="head">
<a href="detail.html">
<img src="${user.head_icon}" alt="">
</a>
</div>
<div class="up">
<div class="vote">
<span>${user.vote}票</span>
</div>
<div class="btn">
投TA一票
</div>
</div>
<div class="descr">
<a href="detail.html">
<div>
<span>${user.username}</span>
<span>|</span>
<span>编号#${user.id}</span>
</div>
<p>${user.description}</p>
</a>
</div>
</li>`
)
},
request({url, type = 'GET', dataType = 'json', data = {}, success}){
$.ajax({url, type, dataType, data, success});
},
loadUsers(load){
voteFn.request({
url: '/vote/index/data',
data: {limit, offset},
success(result){
let total = result.data.total;
let users = result.data.objects;
//修改偏移量1 偏移量0 第二页 10
offset += users.length;
//TODO 把users数组转成li数组并且添加到ul里
let html = users.map(user => voteFn.formatUser(user)).join('');
if (offset >= total) {
setTimeout(function () {
$('.coming').append(html);
load && load.complete();
load && load.reset();
}, 1000);
} else {
setTimeout(function () {
$('.coming').append(html);
load && load.reset();
}, 1000);
}
}
});
},
initIndex(){//初始化首页
voteFn.loadUsers();
loadMore({callback: voteFn.loadUsers});
}
}
//根据不同的页面加载不同的JS脚本
let indexReg = /\/vote\/index/;
let registerReg = /\/vote\/register/;
$(function () {
let url = location.href;
if (indexReg.test(url)) {//如果是首页的话
voteFn.initIndex();
} else if (registerReg.test(url)) {
$('.rebtn').click(function(){
let username = $('.username').val();
if(!username){
alert('用户名不能为空');return;
}
let password = $('.password').val();
if(!/[a-zA-Z0-9]{1,10}/.test(password)){
alert('密码不合法');return;
}
let confirm_password = $('.confirm_password').val();
if(password!= confirm_password){
alert('确认密码和密码不一致');return;
}
let mobile = $('.mobile').val();
if(!/1\d{10}/.test(mobile)){
alert('手机号不合法');return;
}
let description = $('.description').val();
if(!(description && description.length<=20)){
alert('自我描述不合法');return;
}
let gender = $("input[name='gender']:checked").val();
});
}
});
|
49f6272629a27c4c970c220a9ec2232b7638ff1d
|
[
"JavaScript"
] | 1
|
JavaScript
|
guowei12/201703vote
|
fa5d3f29300a3a8d5ede76d8a454e28be984ca7b
|
5ce42fbeb7b3b5b0eb80ddf2651c0b4c9436e509
|
refs/heads/master
|
<file_sep>import {StyleSheet} from 'react-native';
import scale from '../../util/scale';
import * as CONST from '../../util/Constants';
export default StyleSheet.create({
itemContainer: {
padding: scale(10),
marginVertical: scale(5),
backgroundColor: CONST.WHITE_COLOR,
borderRadius: scale(3),
borderColor: 'grey',
borderWidth: 0.3
},
reorderButton: {
borderColor: CONST.SECONDARY_COLOR,
backgroundColor: CONST.PRIMARY_COLOR,
borderWidth: scale(1),
padding: scale(5)
},
visitMenuButton: {
borderColor: CONST.SECONDARY_COLOR,
borderWidth: scale(1),
padding: scale(5)
}
})<file_sep>/**
*
*/
import React, {Component} from 'react';
import { Provider } from 'react-redux'
import createAppStore from './src/store';
import Home from './src/Home';
export default class App extends Component {
constructor (props) {
super(props);
this.state = {
store: createAppStore()
}
console.disableYellowBox = true;
}
render() {
return (
<Provider store={this.state.store}>
<Home/>
</Provider>
);
}
}
/**
* <SafeAreaView style ={{flex:0, backgroundColor: PRIMARY_COLOR}}>
<StatusBar barStyle='light-content' backgroundColor={PRIMARY_COLOR} />
<AppNavigator />
</SafeAreaView>
*/<file_sep>import React, {Component} from 'react';
import {View, SafeAreaView,Image} from 'react-native';
import commonStyle from '../commonStyle';
import { PRIMARY_COLOR, WHITE_COLOR } from '../../util/Constants';
import scale from '../../util/scale';
import { AppHeader } from '../reusables/commons';
const CHART_IMAGE = require('../../../assets/Chart_.png');
export default class LoginComponent extends Component {
constructor (props) {
super (props);
this.state = {
email: '',
password: '',
isManager: false
}
}
renderInputView () {
return (
<View style={{flex:1, backgroundColor: WHITE_COLOR, alignItems: 'center', padding: scale(16)}}>
<View style = {{height: scale(50)}}/>
<Image
style={{padding: scale(16)}}
source ={CHART_IMAGE} />
</View>
)
}
render () {
return (
<SafeAreaView style={commonStyle.safeAreaViewContainer}>
<AppHeader
leftIcon = 'menu'
title = 'Charts'
hasLeftComponent
leftOnPress = {() =>this.props.toggleDrawer()}/>
{this.renderInputView()}
</SafeAreaView>
)
}
}<file_sep>import React, {Component} from 'react';
import {View,Text, TouchableOpacity,SafeAreaView, FlatList} from 'react-native';
import { AppHeader } from '../reusables/commons';
import { WHITE_COLOR, SECONDARY_COLOR, PRIMARY_COLOR } from '../../util/Constants';
import commonStyle from '../commonStyle';
import * as FAKE from '../../util/FakeData';
import styles from './style';
import { getFormattedGenericDate } from '../../util/common';
import ElevatedView from 'react-native-elevated-view';
import scale from '../../util/scale';
export default class PastOrderComponent extends Component {
constructor (props) {
super (props);
}
renderOrderItem (item) {
const {orderId, name, date, description} = item;
return (
<ElevatedView elevation = {10} style={styles.itemContainer}>
<View style={{flexDirection: 'row', justifyContent: 'space-between', paddingBottom: 10}}>
<Text style={{fontWeight: '500', fontSize: scale(16)}}>{name}</Text>
<Text style={{color: PRIMARY_COLOR}}>{getFormattedGenericDate(date, 'DD-MM-YYYY')}</Text>
</View>
<View style={{paddingBottom: scale(10)}}>
<Text style={{fontSize: scale(14)}}>{item.description}</Text>
</View>
<View style={{justifyContent: 'center', justifyContent: 'flex-end', flexDirection: 'row'}}>
<TouchableOpacity onPress ={() => this.props.onReorderClicked()} style={styles.reorderButton}>
<Text style={{color: WHITE_COLOR, fontSize: scale(14)}}>RE ORDER</Text>
</TouchableOpacity>
<View style={{width: scale(10)}} />
<TouchableOpacity onPress = {() => this.props.onVisitMenuClicked()} style={styles.visitMenuButton}>
<Text style={{fontSize: scale(14)}}>VISIT MENU</Text>
</TouchableOpacity>
</View>
</ElevatedView>
)
}
render () {
return (
<SafeAreaView style={commonStyle.safeAreaViewContainer}>
<AppHeader
title='Past Order'
centerTitle
leftIcon = 'menu'
hasLeftComponent
leftOnPress ={() => this.props.toggleDrawer()} />
<View style={{flex:1, backgroundColor: WHITE_COLOR, }}>
<FlatList
style={{paddingHorizontal: scale(10)}}
data = {FAKE.ORDERS_LIST}
renderItem = {({item}) => this.renderOrderItem(item)}/>
</View>
</SafeAreaView>
)
}
}
<file_sep>import React, {Component} from 'react';
import ManageOrderComponent from './ManageOrderComponent';
class ManageOrder extends Component {
constructor (props) {
super (props);
};
render () {
return (
<ManageOrderComponent
toggleDrawer = {() => this.props.navigation.toggleDrawer()}/>
)
}
}
export default ManageOrder;<file_sep>import React, {Component} from 'react';
import { connect } from 'react-redux';
import MenuItemsComponent from './MenuItemsComponent';
import { addItemToCart, removeItemFromCart } from '../../actions/cart';
class MenuItems extends Component {
constructor (props) {
super (props);
}
render () {
const {type} = this.props.navigation.state.params;
const {starters, navigation} = this.props;
return (
<MenuItemsComponent
totalAmount = {this.props.totalAmount}
navigateToCart = {() => navigation.navigate('CartScreen')}
addItem = {(item) => this.props.addItem(item)}
removeItem = {(item) => this.props.removeItem(item)}
items = {starters}
numberOfItems = {this.props.numberOfItems}
type = {type}
toggleDrawer = {() => this.props.navigation.toggleDrawer()} />
)
}
}
const mapStateToProps = (state) => {
const {menu, cart} = state;
return {
starters: menu.starters,
totalAmount: cart.totalAmount,
numberOfItems: cart.numberOfItems,
}
}
const mapDispatchToProps = (dispatch) => {
return {
addItem: item => {
dispatch(addItemToCart(item));
},
removeItem: item => {
dispatch(removeItemFromCart(item));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps) (MenuItems);<file_sep>//Application Colours
export const PRIMARY_COLOR = '#1c7187';
export const SECONDARY_COLOR = '#32b3d2';
export const LIGHT_BLUE ='#0f9bc1';
export const WHITE_COLOR = '#fff';
export const BLACK_COLOR = '#000';
export const LIGHT_GREY = '#cecccc';
export const HEADING_BLACK = '#1d1f21';
export const LIGHT_GREY_COLOR = '#313233';//'#828486';
export const EXTRA_LIGHT_GREY= '#828486';
export const DESCRIPTION_GREY = '#F5F4F4';
export const ERROR_BACKGROUND = 'red'
export const PLACEHOLDER_GREY = '#9e9e9e'
export const TEXT_GREY_COLOR = '#313233';
export const RED = '#E83E0D';
export const GREY_COLOR = '#E1DDDC';
export const GREY_BORDER = '#d5d5d5';
//Standard screen height and width
export const SCREEN_WIDTH = 375;
export const SCREEN_HEIGHT = 667;
//Actions
export const ADD_ITEM = 'ADD_ITEM';
export const REMOVE_ITEM = 'REMOVE_ITEM';
export const MAKE_GTOTAL = 'MAKE_GTOTAL';
export const SET_ORDER = 'SET_ORDER';
export const UPDATE_STARTER = 'UPDATE_STARTER';<file_sep>import React, {Component} from 'react';
import ChartsComponent from './ChartsComponent';
class Charts extends Component {
constructor (props) {
super (props);
};
render () {
return (
<ChartsComponent
toggleDrawer = {() => this.props.navigation.toggleDrawer()}/>
)
}
}
export default Charts;<file_sep>import DefaultToast from './DefaultToastContainer';
/**
* Shows a toast on screen.
* @param {string} msg - String to show as toast message.
*/
export default function showToast(msg) {
DefaultToast.show(msg);
}
<file_sep>export const ORDERS_LIST = [
{
orderId: 356,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 357,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 358,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 359,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 360,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 361,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 362,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
},
{
orderId: 363,
name: '<NAME>',
date: 1539882692227,
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad and mint sauce.'
}
];
export const CART_ITEMS = [
{
id: 1,
quantity: 5,
cost: 55,
name: '<NAME>',
veg: true,
},
{
id: 2,
quantity: 3,
cost: 231.75,
name: 'Homemade lentil soup.',
veg: true,
},
{
id: 3,
quantity: 2,
cost: 190.5,
name: 'Homemade chicken',
veg: false,
}
];
export const STARTERS = [
{
id: 1,
name: '<NAME>',
description: 'Home made lentil soup. Sweet and sour, garnish with fresh coriander and a lemon wedge.',
cost: 4.25,
veg: true,
quantity: 0,
},
{
id: 2,
name: 'Bara',
description: 'Thick lentil pancake made with garlic, ginger and fresh herbs, served with green salad & mint sauce.',
cost: 4.50,
veg: true,
quantity: 0,
},
{
id: 3,
name: '<NAME>',
description: 'Crunchy pan-fried vegetables, potatoes, mushroom, and baby sweet corn. Sweet and sour served on a puri bread.',
cost: 4.75,
veg: true,
quantity: 0,
},
{
id: 4,
name: 'Vegetable Pakora',
description: 'Chopped potato, green beans, green peas, carrot & onion lightly spiced with herbs & spices, battered and deep fried, served with green salad & mint sauce',
cost: 4.25,
veg: true,
quantity: 0,
},
{
id: 5,
name: '<NAME>',
description: 'Lamb chops marinated with fresh herbs and spices cooked in tandoor. Served with green salad & mint sauce.',
cost: 4.95,
veg: false,
quantity: 0,
},
{
id: 6,
name: '<NAME>',
description: 'Home made vegetable dumplings served with stone ground chutney.',
cost: 4.75,
veg: true,
quantity: 0,
},
{
id: 7,
name: '<NAME>',
description: 'Home made chicken/lamb dumplings served with stone ground chutney.',
cost: 4.95,
veg: false,
quantity: 0,
},
{
id: 8,
name: '<NAME>',
description: 'Prawn cooked with tomato, herbs and spices. Sweet and sour. Served on purl bread',
cost: 5.75,
veg: true,
quantity: 0,
},
{
id: 9,
name: '<NAME>',
description: 'Tender pieces of chicken with cucumber, potatoes, cherry tomato, spring onion, yoghurt and fresh herbs garnish with chat masala and served with green salad',
cost: 4.75,
veg: false,
quantity: 0,
},
{
id: 10,
name: '<NAME>',
description: 'Delicately marinated tender lamb garnish with fresh garlic, ginger, spring onion, red pepper. Served with green salad.',
cost: 5.75,
veg: false,
quantity: 0,
},
{
id: 11,
name: '<NAME>',
description: 'Tender breast of chicken with fresh spices and Himalayan herbs garnish with lemon juice and olive oil. Served with green salad.',
cost: 4.95,
veg: false,
quantity: 0,
},
{
id: 12,
name: '<NAME>',
description: 'Lightly spiced mixed vegetables stuffed savoury, deep-fried. Freshly home made served with mint and green salad.',
cost: 4.25,
veg: true,
quantity: 0,
},
{
id: 13,
name: '<NAME>',
description: 'Meat Samosas served with green salad & mint sauce.',
cost: 4.50,
veg: false,
quantity: 0,
},
{
id: 14,
name: '<NAME>',
description: 'Specially spiced lamb minced cooked in Tandoor oven served with salad and chutney.',
cost: 4.95,
veg: false,
quantity: 0,
},
{
id: 15,
name: '<NAME> ',
description: 'Tender pieces of chicken cooked with green chilli, capsicum, tomatoes, chopped onions, soy sauce, typical Nepalese herbs and spices. Garnished wish spring onions, hot and spicy. Served with green salad.',
cost: 4.95,
veg: false,
quantity: 0,
},
{
id: 16,
name: '<NAME>',
description: 'Quarter chicken cooked in Tandoor oven served with green salad and chutney.',
cost: 4.95,
veg: false,
quantity: 0,
},
{
id: 17,
name: '<NAME>',
description: ' Large King Prawn lightly marinated with herbs and spices, battered with rice flour then deep fried, served with chutney and green salad.',
cost: 6.25,
veg: false,
quantity: 0,
},
{
id: 18,
name: '<NAME>',
description: 'Served with chutney tray',
cost: 1.25,
veg: false,
quantity: 0,
},
];
/**
* <View style={{paddingBottom: scale(5), flexDirection: 'row',}}>
<View style={{justifyContent: 'center', paddingRight: scale(10)}}>
<Icon name ='home' size={28} color={PRIMARY_COLOR} />
</View>
<View style={{flex:1, borderBottomColor: GREY_BORDER, paddingVertical: scale(10), borderBottomWidth: 0.5,}}>
<Text>{`3 Edgar Buildings, George Street\nBath England, Edgar Buildings\nBA1 2FJ`}</Text>
</View>
<View style={{justifyContent: 'center', paddingRight: scale(10)}}>
<Icon name ='check-circle' size={24} color={PRIMARY_COLOR} />
</View>
</View>
*/
export const ADDRESSES = [
{
id: 1,
type: 0,
address: '3 Edgar Buildings, George Street\nBath England, Edgar Buildings\nBA1 2FJ',
isSelected: true,
},
{
id: 2,
type: 1,
address: '49 Featherstone Street, LONDON,\nEC1Y 8SY,\nUNITED KINGDOM',
isSelected: false,
}
]
export const MANAGE_ORDERS = [
{
id: 1,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 2,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 3,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 4,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 5,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 6,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 7,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 8,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
},
{
id: 9,
name: '<NAME>',
shortDescription: 'Vegetable Chau Chau',
}
]<file_sep>import React, {Component} from 'react';
import CheckoutComponent from './CheckoutComponent';
import {connect} from 'react-redux';
class Checkout extends Component {
constructor (props) {
super (props);
};
render () {
return (
<CheckoutComponent
deliveryType = {this.props.deliveryType}
isPromoCodeApplied = {this.props.isPromoCodeApplied}
delivery = {this.props.delivery}
// checkoutCart = {() => this.props.navigation.navigate('CheckoutScreen')}
totalAmount = {this.props.totalAmount}
goBack = {() => this.props.navigation.goBack()} />
)
}
}
const mapStateToProps = (state) => {
const {cart} = state;
return {
list: cart.list,
totalAmount: cart.totalAmount,
grandTotal: cart.grandTotal,
promoCode: cart.promoCode,
delivery: cart.delivery,
isPromoCodeApplied: cart.isPromoCodeApplied,
deliveryType: cart.deliveryType,
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
}
export default connect(mapStateToProps, null)(Checkout);<file_sep>import {StyleSheet} from 'react-native';
import * as CONST from '../util/Constants';
export default StyleSheet.create({
safeAreaViewContainer: {
flex: 1,
backgroundColor: CONST.PRIMARY_COLOR,
},
})<file_sep>import React, {Component} from 'react';
import {View, TouchableOpacity, SafeAreaView, ScrollView, Text} from 'react-native';
import actualDimensions from '../../util/Device';
const {height, width} = actualDimensions;
import commonStyle from '../commonStyle';
import scale, { verticalScale } from '../../util/scale';
import { AppHeader } from '../reusables/commons';
import { WHITE_COLOR, PRIMARY_COLOR, GREY_BORDER, SECONDARY_COLOR, GREY_COLOR } from '../../util/Constants';
import Icon from 'react-native-vector-icons/MaterialIcons';
import * as FAKE_DATA from '../../util/FakeData';
import { getFormattedCurrency } from '../../util/common';
import showToast from '../../util/Toast/index';
export default class CheckoutComponent extends Component {
constructor (props) {
super(props);
this.state = {
selected: 1,
}
}
renderAddressView () {
return (
<View>
<View style={{ paddingVertical: scale(5), borderBottomColor: GREY_BORDER, borderBottomWidth: 1, alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={{ fontSize: scale(16), paddingRight: scale(5), fontWeight: 'bold', }}>Choose Address</Text>
<TouchableOpacity >
<Icon name='add-circle' size={28} color={PRIMARY_COLOR} />
</TouchableOpacity>
</View>
{FAKE_DATA.ADDRESSES.map((address) => {
return (
<TouchableOpacity activeOpacity={1} onPress={() => this.setState({selected: address.id})} style={{ paddingBottom: scale(5), flexDirection: 'row', }}>
<View style={{ paddingTop: verticalScale(10), paddingRight: scale(10) }}>
<Icon
name={address.type === 0 ? 'home' : 'work'}
size={28}
color={PRIMARY_COLOR} />
</View>
<View style={{ flex: 1, borderBottomColor: GREY_BORDER, paddingVertical: scale(10), borderBottomWidth: 0.5, }}>
<Text>{address.address}</Text>
<Text style={{ paddingVertical: scale(10) }}>+91-7889994745</Text>
<TouchableOpacity style={{ padding: scale(5), flexDirection: 'row', borderColor: PRIMARY_COLOR, borderWidth: 1, width: scale(140), }} onPress={() => console.log('')}>
<Icon name='edit' size={16} color={PRIMARY_COLOR} />
<Text style={{ paddingLeft: scale(5) }}>Update Address</Text>
</TouchableOpacity>
</View>
<View style={{ justifyContent: 'center', paddingRight: scale(10) }}>
<Icon
name={'check-circle'}
size={24}
color={this.state.selected === address.id ? PRIMARY_COLOR : WHITE_COLOR} />
</View>
</TouchableOpacity>
)
})}
</View>
)
}
renderOrderSummaryView () {
const {totalAmount, delivery, isPromoCodeApplied, deliveryType} = this.props;
return (
<View style={{paddingVertical: verticalScale(5)}}>
<Text style={{ fontSize: scale(16), paddingRight: scale(5), paddingBottom: verticalScale(10), fontWeight: 'bold', }}>Order Summary</Text>
<View style={{flexDirection: 'row', borderBottomColor: GREY_BORDER, borderBottomWidth: 0.5, justifyContent: 'space-between'}}>
<Text style={{ fontSize: scale(14), paddingRight: scale(5), paddingVertical: verticalScale(5) }}>Order Total <Text onPress ={() => this.props.goBack()} style={{color: PRIMARY_COLOR}}>(View Detail)</Text></Text>
<Text style={{fontWeight: 'bold', fontSize: scale(14),paddingVertical: verticalScale(5) }}>{getFormattedCurrency(totalAmount)}</Text>
</View>
<View style={{flexDirection: 'row', borderBottomColor: GREY_BORDER, borderBottomWidth: 0.5, justifyContent: 'space-between'}}>
<Text style={{ fontSize: scale(14), paddingRight: scale(5), paddingVertical: verticalScale(5) }}>Delivery </Text>
<Text style={{fontWeight: 'bold', fontSize: scale(14),paddingVertical: verticalScale(5) }}> {getFormattedCurrency(delivery)}</Text>
</View>
{isPromoCodeApplied && <View style={{flexDirection: 'row', borderBottomColor: GREY_BORDER, borderBottomWidth: 0.5, justifyContent: 'space-between'}}>
<Text style={{ fontSize: scale(14), paddingRight: scale(5), paddingVertical: verticalScale(5) }}>Promo Code Discount </Text>
<Text style={{fontWeight: 'bold', fontSize: scale(14),paddingVertical: verticalScale(5) }}>- {getFormattedCurrency(20)}</Text>
</View>}
<View style={{flexDirection: 'row', borderBottomColor: GREY_BORDER, borderBottomWidth: 0.5, justifyContent: 'space-between'}}>
<Text style={{ fontSize: scale(16), fontWeight: 'bold', paddingRight: scale(5), paddingVertical: verticalScale(5) }}>Total Payable</Text>
<Text style={{fontWeight: 'bold', fontSize: scale(16),paddingVertical: verticalScale(5) }}>{getFormattedCurrency((totalAmount + delivery - (isPromoCodeApplied ? 20 : 0)))}</Text>
</View>
</View>
)
}
renderInputView () {
const {deliveryType} = this.props;
return (
<ScrollView bounces = {false} style={{flex:1, padding: scale(16), backgroundColor: WHITE_COLOR}}>
{deliveryType === 1 && this.renderAddressView()}
{this.renderOrderSummaryView()}
</ScrollView>
)
}
renderBottomView () {
const {totalAmount, delivery, isPromoCodeApplied, deliveryType} = this.props;
return (
<TouchableOpacity onPress={() => showToast('Feature yet to be developed.') } style={{backgroundColor: SECONDARY_COLOR, height: scale(50), flexDirection: 'row' }}>
<View style={{ flex: 1, paddingHorizontal: scale(10), justifyContent: 'center' }}>
<Text style={{ fontSize: scale(14), paddingBottom: scale(5), fontWeight: 'bold', color: WHITE_COLOR }}>Confirm the Payment</Text>
<Text style={{ fontSize: scale(16), fontWeight: 'bold', color: WHITE_COLOR }}>{getFormattedCurrency((totalAmount + delivery - (isPromoCodeApplied ? 20 : 0)))}</Text>
</View>
<View style={{ height: scale(50), justifyContent: 'center', alignItems: 'center', width: scale(50) }}>
<View style={{ height: scale(22), justifyContent: 'center', alignItems: 'center', width: scale(22), borderRadius: scale(14), backgroundColor: WHITE_COLOR }}>
<Icon name='arrow-forward' size={18} color={SECONDARY_COLOR} />
</View>
</View>
</TouchableOpacity>
)
}
render () {
const {goBack} = this.props;
return (
<SafeAreaView style={commonStyle.safeAreaViewContainer}>
<AppHeader
leftOnPress = {() => goBack()}
hasLeftComponent
title = 'Checkout'
/>
{this.renderInputView()}
{this.renderBottomView()}
</SafeAreaView>
)
}
}<file_sep>import React, {Component} from 'react';
import {View, TouchableOpacity,Text,ScrollView,TextInput, SafeAreaView} from 'react-native';
import { AppHeader, ItemAdjustor } from '../reusables/commons';
import { WHITE_COLOR, LIGHT_GREY, PRIMARY_COLOR, SECONDARY_COLOR, GREY_BORDER } from '../../util/Constants';
import commonStyle from '../commonStyle';
import showToast from '../../util/Toast';
import scale from '../../util/scale';
import Icon from 'react-native-vector-icons/MaterialIcons';
import styles from './style';
import { getFormattedCurrency } from '../../util/common';
import {RadioButtonInput} from 'react-native-simple-radio-button';
export default class CheckoutComponent extends Component {
constructor (props) {
super (props);
this.state = {
deliveryOption: 0,
deliveryAmount: 0,
promoCode: '',
isPromoCodeApplied: false
}
}
deleteButton = {onPress: () => this.clearItems(), icon: 'delete-forever'};
clearItems = () => {
showToast('Feature yet to be developed.');
}
renderDeliveryRadio = () => {
return (
<View style={{flexDirection: 'row' }}>
<View style={{padding: scale(10), paddingBottom: 0, paddingLeft: 0, flexDirection: 'row'}}>
<RadioButtonInput
obj ={{}}
index={0}
isSelected={this.state.deliveryOption === 0}
onPress={() => this.setState({deliveryOption: 0, deliveryAmount: 0})}
borderWidth={1}
buttonInnerColor={PRIMARY_COLOR}
buttonOuterColor={this.state.deliveryOption === 0 ? PRIMARY_COLOR : SECONDARY_COLOR}
buttonSize={scale(14)}
buttonOuterSize={scale(18)}
buttonStyle={{}}
buttonWrapStyle={{marginLeft: - scale(10)}} />
<TouchableOpacity onPress={() => this.setState({deliveryOption: 0, deliveryAmount: 0})}>
<Text style={{paddingLeft: scale(10)}}>Take Away</Text>
</TouchableOpacity>
</View>
<View style={{padding: scale(10), paddingBottom: 0, flexDirection: 'row'}}>
<RadioButtonInput
obj ={{}}
index={1}
isSelected={this.state.deliveryOption === 1}
onPress={() => this.setState({deliveryOption: 1, deliveryAmount: 20})}
borderWidth={1}
buttonInnerColor={'#000'}
buttonOuterColor={this.state.deliveryOption === 1? PRIMARY_COLOR : SECONDARY_COLOR}
buttonSize={scale(14)}
buttonOuterSize={scale(18)}
buttonStyle={{}}/>
<TouchableOpacity onPress={() => this.setState({deliveryOption: 1, deliveryAmount: 20})}>
<Text style={{paddingLeft: scale(10)}}>Home Delivery</Text>
</TouchableOpacity>
</View>
</View>
)
}
handlePromoCode () {
if (this.state.promoCode && this.state.promoCode === 'FIRST20') {
this.setState({
isPromoCodeApplied: true,
})
} else {
showToast ('Please enter correct promo code to avail discount.')
}
}
renderPromoCodeView () {
return (
<View style={{ paddingTop: scale(20), borderBottomWidth: 0.5, borderTopWidth: 0.5, borderColor: LIGHT_GREY, justifyContent: 'space-between', }}>
<Text style={{ fontWeight: 'bold', fontSize: scale(12), }}>PROMO CODE</Text>
<View style={{ flexDirection: 'row', paddingTop: scale(10) }}>
<Icon name='confirmation-number' size={24} color={PRIMARY_COLOR} />
<TextInput
placeholderTextColor={LIGHT_GREY}
placeholder='Have a promo code ? Enter it here'
style={{ flex: 1, paddingLeft: scale(10), color: PRIMARY_COLOR, fontWeight: 'bold' }}
value={this.state.promoCode}
onChangeText={(text) => this.setState({ promoCode: text })} />
<TouchableOpacity style={{ paddingVertical: 5 }} onPress={() => this.handlePromoCode()}>
<Text style={{ fontWeight: 'bold', fontSize: scale(12), color: PRIMARY_COLOR }}>{this.state.isPromoCodeApplied ? 'DISMISS' : 'APPLY'}</Text>
</TouchableOpacity>
</View>
</View>
)
}
renderItems = () => {
const {cartList, addItem, removeItem} = this.props;
return (
<View>
{cartList.map((item) => {
return (
<View style={{ paddingVertical: scale(10), borderColor: LIGHT_GREY, borderBottomWidth: 0.5, flexDirection: 'row' }}>
<View style={{ paddingTop: scale(3) }}>
<View style={{ padding: scale(1), borderColor: item.veg ? 'green' : 'red', borderWidth: 0.5 }}>
<Icon name='brightness-1' color={item.veg ? 'green' : 'red'} size={10} />
</View>
</View>
<View style={{ flex: 1, paddingLeft: scale(5) }}>
<Text>{item.name}</Text>
<Text style={[styles.amountText, { textAlign: 'left', paddingTop: scale(5) }]}>{getFormattedCurrency(item.cost)}</Text>
</View>
<View style={{ height: scale(40) }} >
<ItemAdjustor
decreaseQuantity={() => removeItem(item)}
increaseQuantity={() => addItem(item)}
quantity={item.quantity} />
<View style={{ paddingTop: scale(3) }}>
<Text style={styles.amountText}>{getFormattedCurrency(item.cost*item.quantity)}</Text>
</View>
</View>
</View>
)
})}
</View>
)
}
renderDeliveryOptions = () => {
return (
<View style={{ paddingVertical: scale(10), borderColor: LIGHT_GREY, justifyContent: 'space-between', borderBottomWidth: 0.5, }}>
<Text style={{ fontWeight: 'bold', fontSize: scale(14), }}>Choose Delivery Option</Text>
{this.renderDeliveryRadio()}
</View>
)
}
renderAmountView = () => {
const {totalAmount} = this.props;
return (
<View style={{paddingTop: scale(12),}}>
<View style={{ borderColor: LIGHT_GREY, justifyContent: 'space-between', flexDirection: 'row'}}>
<Text style={{fontWeight: 'bold', fontSize: scale(14), }}>Subtotal</Text>
<Text style={{fontWeight: 'bold', fontSize: scale(14), }}>{getFormattedCurrency(totalAmount)}</Text>
</View>
<View style={{justifyContent: 'space-between', paddingTop: scale(5), flexDirection: 'row'}}>
<Text style={{fontSize: scale(10), }}>Delivery: </Text>
<Text style={{fontSize: scale(10), }}>{getFormattedCurrency(this.state.deliveryAmount)}</Text>
</View>
{this.state.isPromoCodeApplied && <View style={{justifyContent: 'space-between', paddingTop: scale(5),flexDirection: 'row'}}>
<Text style={{fontSize: scale(10), }}>Promo code Discount: </Text>
<Text style={{fontSize: scale(10), }}>- {getFormattedCurrency(20)}</Text>
</View>}
<View style={{paddingVertical: 4, height: 0, borderColor: GREY_BORDER, borderBottomWidth: 1}} />
<View style={{paddingVertical: scale(12), justifyContent: 'space-between', flexDirection: 'row'}}>
<Text style={{fontWeight: 'bold', fontSize: scale(14), }}>Grand Total</Text>
<Text style={{fontWeight: 'bold', fontSize: scale(14), }}>{getFormattedCurrency((totalAmount+this.state.deliveryAmount - (this.state.isPromoCodeApplied ? 20 : 0)))}</Text>
</View>
</View>
)
}
renderBottomView () {
const {totalAmount} = this.props;
return (
<TouchableOpacity onPress = {() => this.props.checkoutCart({deliveryType: this.state.deliveryOption, isPromoCodeApplied: this.state.isPromoCodeApplied})} style={{position: 'absolute', backgroundColor: SECONDARY_COLOR, bottom: 0, right:0, left: 0, height: scale(50), flexDirection: 'row'}}>
<View style={{flex: 1, paddingHorizontal: scale(10), justifyContent: 'center'}}>
<Text style={{fontSize: scale(16), fontWeight: 'bold', color: WHITE_COLOR}}>Place order ({getFormattedCurrency((totalAmount+this.state.deliveryAmount - (this.state.isPromoCodeApplied ? 20 : 0)))})</Text>
</View>
<View style={{height: scale(50), justifyContent: 'center', alignItems: 'center',width: scale(50)}}>
<View style={{height: scale(22), justifyContent: 'center', alignItems: 'center', width: scale(22), borderRadius: scale(14), backgroundColor: WHITE_COLOR}}>
<Icon name = 'arrow-forward' size={18} color={SECONDARY_COLOR} />
</View>
</View>
</TouchableOpacity>
)
}
render () {
return (
<SafeAreaView style={commonStyle.safeAreaViewContainer}>
<AppHeader
hasLeftComponent
// hasRightComponent //if cart has one or more items.
rightComponents = {[this.deleteButton]}
leftOnPress={() => this.props.goBack()}
title='Your Cart' />
<ScrollView showsVerticalScrollIndicator = {false} bounces = {false} style={{ flex: 1, backgroundColor: WHITE_COLOR, padding: scale(10) }}>
{this.renderItems()}
{this.renderDeliveryOptions()}
{this.renderAmountView()}
{this.renderPromoCodeView()}
{this.state.isPromoCodeApplied && <Text style={{paddingTop: 5, fontSize: 10, color: PRIMARY_COLOR}}>Promo code applied.</Text>}
<View style={{height: scale(80)}} />
</ScrollView>
{this.renderBottomView()}
</SafeAreaView>
)
}
}<file_sep>import React, {Component} from 'react';
import {View, SafeAreaView, Text, ScrollView, TextInput, TouchableOpacity, Image, ImageBackground} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import commonStyle from '../commonStyle';
import { WHITE_COLOR, LIGHT_GREY, PRIMARY_COLOR, SECONDARY_COLOR, LIGHT_BLUE, BLACK_COLOR } from '../../util/Constants';
import scale, { verticalScale } from '../../util/scale';
import { AppHeader } from '../reusables/commons';
import actualDimensions from '../../util/Device';
const {height, width} = actualDimensions;
const BACKGROUND_IMAGE = require('../../../assets/Background_.png');
const LOGO = require('../../../assets/icon_logo_small_.png');
export default class SignupComponent extends Component {
constructor (props) {
super (props);
this.state = {
username: '',
confirmPassword: '',
email: '',
password: '',
}
}
renderInputView () {
return (
<View style={{flex:1, justifyContent: 'flex-end', padding: scale(5), width: '100%', height: '100%'}}>
<ScrollView showsVerticalScrollIndicator = {false} bounces = {false} style={{flex:1}}>
<View style={{paddingVertical: verticalScale(40), justifyContent: 'center', alignItems: 'center'}}>
<Image style={{height: 130, width: 130}} source={LOGO}/>
<Text style={{fontSize: 20, color: WHITE_COLOR, paddingTop: 5, fontWeight: 'bold'}}>HOLDERCLUBS</Text>
<Text style={{fontSize: 8, color: WHITE_COLOR, paddingTop: 5, fontWeight: 'bold'}}>SIGABIT</Text>
<Text style={{fontSize: 30, color: WHITE_COLOR, paddingTop: 40, fontWeight: 'bold'}}>WELCOME</Text>
</View>
<View style={{paddingVertical: verticalScale(2), alignItems: 'center', flexDirection: 'row', borderBottomColor: WHITE_COLOR, borderBottomWidth: scale(0.3)}}>
<Icon name='account-box' color={WHITE_COLOR} size={scale(24)} />
<TextInput
autoCorrect = {false}
style={{flex:1, paddingLeft: scale(10), color: WHITE_COLOR}}
value = {this.state.username}
placeholder = '<NAME>'
placeholderTextColor = {LIGHT_GREY}
onChangeText = {(text) => this.setState({username: text})} />
</View>
<View style={{height: verticalScale(20)}}/>
<View style={{paddingVertical: verticalScale(2), flexDirection: 'row',alignItems: 'center', borderBottomColor: WHITE_COLOR,borderBottomWidth: scale(0.3)}}>
<Icon name='mail-outline' color={WHITE_COLOR} size={scale(24)} />
<TextInput
autoCorrect = {false}
style={{flex:1, paddingLeft: scale(10), color: WHITE_COLOR}}
value = {this.state.email}
placeholder = 'EMAIL'
placeholderTextColor = {LIGHT_GREY}
onChangeText = {(text) => this.setState({email: text})} />
</View>
<View style={{height: verticalScale(20)}}/>
<View style={{paddingVertical: verticalScale(2), alignItems: 'center', flexDirection: 'row', borderBottomColor: WHITE_COLOR, borderBottomWidth: scale(0.3)}}>
<Icon name='lock' color={WHITE_COLOR} size={scale(24)} />
<TextInput
autoCorrect = {false}
secureTextEntry
style={{flex:1, paddingLeft: scale(10), color: WHITE_COLOR}}
value = {this.state.password}
placeholder = '<PASSWORD>'
placeholderTextColor = {LIGHT_GREY}
onChangeText = {(text) => this.setState({password: text})} />
</View>
<View style={{height: verticalScale(20)}}/>
<View style={{paddingVertical: verticalScale(2), flexDirection: 'row',alignItems: 'center', borderBottomColor: WHITE_COLOR, borderBottomWidth: scale(0.3)}}>
<Icon name='lock' color={WHITE_COLOR} size={scale(24)} />
<TextInput
autoCorrect = {false}
secureTextEntry
style={{flex:1, paddingLeft: scale(10), color: WHITE_COLOR}}
value = {this.state.confirmPassword}
placeholder = 'RE-PASSWORD'
placeholderTextColor = {LIGHT_GREY}
onChangeText = {(text) => this.setState({confirmPassword: text})} />
</View>
<View style={{height: verticalScale(20)}}/>
<TouchableOpacity style={{paddingVertical: verticalScale(10), borderRadius: 10,
borderColor: SECONDARY_COLOR, borderWidth: 0.5, justifyContent: 'center', alignItems: 'center', backgroundColor: PRIMARY_COLOR}} onPress = {() => console.log('')}>
<Text style={{fontSize: scale(16), fontWeight: 'bold', color: WHITE_COLOR}}>SIGN UP</Text>
</TouchableOpacity>
<View style={{paddingVertical: verticalScale(10),justifyContent: 'center', alignItems:'center'}}>
<Text style={{color: WHITE_COLOR, fontSize: scale(14)}}>You have an account ?<Text onPress={() => this.props.goBack()} style={{color: BLACK_COLOR}}> Login</Text></Text>
</View>
</ScrollView>
</View>
)
}
render () {
return (
<SafeAreaView style={{flex:1}}>
<View style={{position: 'absolute', height, width, right: 0, bottom: 0, left: 0, top: 0, width: '100%', height: '100%'}}>
<ImageBackground style={{flex:1}} resizeMode='stretch' source = {BACKGROUND_IMAGE}/>
</View>
{this.renderInputView()}
</SafeAreaView>
)
}
}<file_sep>import React, {Component} from 'react';
import LoginComponent from './LoginComponent';
import {resetAction} from '../../AppNavigator';
class Login extends Component {
constructor (props) {
super (props);
};
render () {
return (
<LoginComponent
onLongPress = {() => this.props.navigation.dispatch(resetAction('ManagersDrawer'))}
login = {() => this.props.navigation.dispatch(resetAction('Drawer'))}
navigateToSignup = {() => this.props.navigation.navigate('SignupScreen')}
/>
)
}
}
export default Login;<file_sep>import React, {Component} from 'react';
import {connect} from 'react-redux';
import CheckoutComponent from './CartComponent';
import { addItemToCart, removeItemFromCart } from '../../actions/cart';
import {SET_ORDER} from '../../util/Constants';
class Checkout extends Component {
constructor (props) {
super (props);
}
render () {
const {list, totalAmount, grandTotal, promoCode, addItem, removeItem} = this.props;
return (
<CheckoutComponent
deliveryType = {this.props.deliveryType}
isPromoCodeApplied = {this.props.isPromoCodeApplied}
checkoutCart = {(order) => this.props.checkoutOrder(order, this.props.navigation.navigate)}
addItem = {(item) => addItem(item)}
removeItem = {(item) => removeItem(item)}
cartList = {list}
totalAmount = {totalAmount}
grandTotal = {grandTotal}
promoCode = {promoCode}
goBack = {() => this.props.navigation.goBack()} />
)
}
}
const mapStateToProps = (state) => {
const {cart} = state;
return {
list: cart.list,
totalAmount: cart.totalAmount,
grandTotal: cart.grandTotal,
promoCode: cart.promoCode,
delivery: cart.delivery,
isPromoCodeApplied: cart.isPromoCodeApplied,
deliveryType: cart.deliveryType,
}
}
const mapDispatchToProps = (dispatch) => {
return {
addItem: item => {
dispatch(addItemToCart(item));
},
removeItem: item => {
dispatch(removeItemFromCart(item));
},
checkoutOrder: (order, navigate) => {
dispatch({
type: SET_ORDER,
payload: order,
})
navigate('CheckoutScreen');
}
}
}
export default connect(mapStateToProps, mapDispatchToProps) (Checkout);<file_sep>import React, {Component} from 'react';
import PastOrderComponent from './PastOrderComponent';
class PastOrder extends Component {
constructor (props) {
super (props);
}
render () {
return(
<PastOrderComponent
onReorderClicked = {() => this.props.navigation.navigate('CartScreen')}
onVisitMenuClicked = {() => this.props.navigation.navigate('MenuScreen')}
toggleDrawer = {() => this.props.navigation.toggleDrawer()}/>
)
}
}
export default PastOrder;<file_sep>import * as CONST from '../util/Constants';
import _ from 'lodash';
export function addItemToCart (item) {
return async (dispatch, getState) => {
const {menu, cart} = getState();
const {starters} = menu;
const {list, totalAmount, numberOfItems} = cart;
let existingItem = _.find(starters, (o) => {return o.id === item.id});
existingItem.quantity = existingItem.quantity + 1;
existingItem = {...existingItem};
const cartItem = _.find(list, (o) => {return o.id === item.id});
if (cartItem) {
cartItem.quantity = cartItem.quantity + 1;
} else {
list.push(existingItem);
}
let newTotalAmount= totalAmount + item.cost;
dispatch({
type: CONST.UPDATE_STARTER,
payload: starters,
});
dispatch({
type: CONST.ADD_ITEM,
payload: {
items: list,
totalAmount: newTotalAmount,
numberOfItems: (numberOfItems + 1),
}
});
}
}
export function removeItemFromCart (item) {
return async (dispatch, getState) => {
const {menu, cart} = getState();
const {starters} = menu;
const {list, totalAmount} = cart;
let existingItem = _.find(starters, (o) => {return o.id === item.id});
existingItem.quantity = existingItem.quantity - 1;
existingItem = {...existingItem};
const cartItem = _.find(list, (o) => {return o.id === item.id});
if (cartItem) {
cartItem.quantity = cartItem.quantity - 1;
if (cartItem.quantity === 0) _.remove(list, (o) =>{return o.id === item.id})
}
let newTotalAmount= totalAmount - item.cost;
dispatch({
type: CONST.UPDATE_STARTER,
payload: starters,
});
dispatch({
type: CONST.ADD_ITEM,
payload: {
items: list,
totalAmount: newTotalAmount,
}
});
}
}<file_sep>import {StyleSheet} from 'react-native';
import * as CONST from '../../util/Constants';
import scale from '../../util/scale';
export default StyleSheet.create({
userRectContainer: {
height: scale(150),
backgroundColor: CONST.SECONDARY_COLOR,
justifyContent: 'center',
alignItems: 'center',
},
triangle: {
width: 0,
height: 0,
borderLeftWidth: scale(90),
borderBottomWidth: scale(600),
borderStyle: 'solid',
backgroundColor: 'transparent',
borderLeftColor: 'transparent',
borderRightColor: 'transparent',
borderBottomColor: CONST.SECONDARY_COLOR,
transform: [
{rotate: '-90deg'}
],
marginTop: - scale(120),
position: 'absolute'
},
drawerUserContainer: {
height: scale(220)
},
userContainer: {
position: 'absolute',
marginTop: - scale(20),
justifyContent: 'center',
alignItems: 'center',
bottom: 0,
left: 0,
right: 0,
top: 0
},
userPictureContainer: {
height: scale(80),
width: scale(80),
borderRadius: scale(50),
backgroundColor: 'grey',
borderColor: CONST.WHITE_COLOR,
borderWidth: scale(3),
},
userNameText: {
color: CONST.WHITE_COLOR,
paddingVertical: 5
},
drawerInnerItemContainer: {
height: scale(40),
width: scale(40),
justifyContent: 'center',
alignItems: 'center'
},
drawerItemText: {
color: CONST.WHITE_COLOR,
fontWeight: '500',
fontSize: scale(18)
},
drawerItemTextContainer: {
flex:1,
justifyContent: 'center',
paddingLeft: scale(14)
},
drawerItemContainer: {
padding: scale(5),
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row'
},
})<file_sep>import React, {Component} from 'react';
import DrawerComponent from './DrawerComponent';
import { resetAction } from '../../AppNavigator';
import ManagerDrawer from './ManagerDrawer';
class Drawer extends Component {
constructor (props) {
super (props);
}
navigateToScreen (screenName, params, reset = false) {
const {navigation} = this.props;
if (reset) navigation.dispatch(resetAction(screenName))
else navigation.navigate(screenName);
}
render () {
const {isManager} = this.props;
return (
isManager ?
<ManagerDrawer
navigateTo = {(screenName, params, reset) => this.navigateToScreen (screenName, params, reset)} /> :
<DrawerComponent
navigateTo = {(screenName, params, reset) => this.navigateToScreen (screenName, params, reset)} />
)
}
}
export default Drawer;<file_sep>import {StyleSheet} from 'react-native';
import scale from '../../util/scale';
export default StyleSheet.create({
amountText: {
fontSize: scale(10),
textAlign: 'right',
fontWeight: 'bold',
fontSize: scale(12)
}
})<file_sep>import moment from 'moment';
import 'intl';
import 'intl/locale-data/jsonp/en';
/**
* Provides formatted date using epoch imput.
* @param {number} epoch - Time in unix time format.
* @param {string} format - String format for date to be returned.
*/
export function getFormattedGenericDate (epoch, format) {
return moment (epoch).format(format);
}
/**
* Provides formatted currency amount for numeric amount value.
* @param {number} amount - Specifies amount in numeric form.
* @returns Formatted amount in INTL format.
*/
export function getFormattedCurrency(amount) {
const floatValue = parseFloat(amount);
return new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP', minimumFractionDigits: 0 }).format(floatValue)
}<file_sep>import React from 'react';
import {View, Text, Platform, TouchableOpacity, StyleSheet} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import ElevatedView from 'react-native-elevated-view';
import * as CONST from '../../util/Constants';
import scale from '../../util/scale';
const APPBAR_HEIGHT = Platform.OS === 'ios' ? scale(44) : scale(56);
export const AppHeader = ({title, hasLeftComponent, backgroundColor = CONST.PRIMARY_COLOR, centerTitle = false, hasRightComponent, leftIcon, rightComponents, leftOnPress}) => {
return (
<ElevatedView elevation={0} style={[styles.container, {backgroundColor:backgroundColor }]}>
<View style={[styles.absoluteTextView,{ alignItems: centerTitle ? 'center' : 'flex-start', paddingLeft: centerTitle ? 0 : (hasLeftComponent ? 60 : 10)}]}>
<Text style={styles.titleText} >{title.toUpperCase()}</Text>
</View>
{hasLeftComponent && <TouchableOpacity style={styles.leftContainer} onPress={() => leftOnPress()}>
<Icon name={leftIcon ? leftIcon : 'arrow-back'} size={28} color={CONST.WHITE_COLOR} />
</TouchableOpacity>}
{/* <View style={{flex:1}}/> */}
<View style={{flex: 1, alignItems: 'center', justifyContent: 'flex-end',flexDirection: 'row'}}>
{hasRightComponent && rightComponents.map((component) => {
return (
<TouchableOpacity style={styles.rightContentContainer} onPress={() => component.onPress()}>
<Icon name={component.icon} size={28} color = {CONST.WHITE_COLOR} />
</TouchableOpacity>
)
})}
</View>
</ElevatedView>
)
}
export const ItemAdjustor = ({decreaseQuantity, increaseQuantity, quantity}) => {
return (
quantity !== 0 ? <View style={styles.adjustorContainer}>
<TouchableOpacity onPress={() => decreaseQuantity()} style={styles.adjusterRightTouchable}>
<Text style={styles.adjusterSign}>-</Text>
</TouchableOpacity>
<View style={{width: scale(20), backgroundColor: CONST.WHITE_COLOR, justifyContent: 'center', alignItems: 'center'}}>
<Text style={styles.adjusterFont}>{quantity}</Text>
</View>
<TouchableOpacity onPress={() => increaseQuantity()} style={styles.adjusterLeftTouchable}>
<Text style={styles.adjusterSign}>+</Text>
</TouchableOpacity>
</View> :
<TouchableOpacity onPress={() => increaseQuantity()} style={styles.adjustorContainer}>
<View style={styles.adjusterRightTouchable}>
<Text style={styles.adjusterSign}>+</Text>
</View>
<View style={{paddingHorizontal: scale(5), backgroundColor: CONST.WHITE_COLOR, justifyContent: 'center', alignItems: 'center'}}>
<Text style={styles.adjusterFont}>ADD</Text>
</View>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: CONST.PRIMARY_COLOR,
flexDirection: 'row',
height: APPBAR_HEIGHT,
justifyContent: 'center',
paddingHorizontal: scale(10)
},
absoluteTextView: {
position: 'absolute',
right: 0,
left: 0,
top: 0,
bottom: 0,
justifyContent: 'center',
},
titleText: {
color: CONST.WHITE_COLOR,
fontSize: scale(18),
fontWeight: 'bold'
},
leftContainer: {
width: scale(40),
justifyContent: 'center'
},
rightContentContainer: {
padding: scale(5),
justifyContent: 'center',
alignItems: 'flex-end'
},
adjustorContainer: {
borderColor: CONST.PRIMARY_COLOR, backgroundColor: CONST.PRIMARY_COLOR, borderWidth: 1, flex:1, borderRadius: scale(3) , flexDirection: 'row'
},
adjusterRightTouchable: {
borderBottomLeftRadius: scale(5), borderTopLeftRadius: scale(5), justifyContent: 'center', alignItems: 'center', backgroundColor: CONST.PRIMARY_COLOR, width: scale(20)
},
adjusterFont: {
fontSize: scale(12),
},
adjusterLeftTouchable: {
borderBottomRightRadius: scale(5),
borderTopRightRadius: scale(5),
justifyContent: 'center',
alignItems: 'center',
backgroundColor: CONST.PRIMARY_COLOR,
width: scale(20)
},
adjusterSign: {
fontSize: scale(14),
fontWeight: 'bold',
color: CONST.WHITE_COLOR
}
})<file_sep>import * as CONST from '../util/Constants';
const initialState = {
list: [],
totalAmount: 0,
delivery: 20,
grandTotal: 0,
promoCode: 'FIRST20',
numberOfItems: 0,
isPromoCodeApplied: false,
deliveryType: 1, // 0 - Take Away, 1- Home delivery
};
export default (state = initialState, action) => {
switch (action.type) {
case CONST.ADD_ITEM:
return {
...state,
list: action.payload.items,
totalAmount: action.payload.totalAmount,
numberOfItems: action.payload.numberOfItems,
};
case CONST.REMOVE_ITEM:
return {
...state,
list: action.payload.items,
totalAmount: action.payload.totalAmount,
};
case CONST.MAKE_GTOTAL:
return {
...state,
delivery: action.payload.delivery,
grandTotal: action.payload.grandTotal,
};
case CONST.SET_ORDER:
return {
...state,
isPromoCodeApplied: action.payload.isPromoCodeApplied,
deliveryType: action.payload.deliveryType,
delivery: ((action.payload.deliveryType) === 1) ? 20 : 0,
}
default: return state;
}
}<file_sep>## :arrow_up: How to Setup
**Step 1:** git clone this repo:
**Step 2:** cd to the cloned repo:
**Step 3:** Install the Application with `npm install`
**Step 4:** Create file local.properties and copy to folder android with content :
# Location of the SDK. This is only used by Gradle.
ndk.dir=C\:\\Users\\Admin\\AppData\\Local\\Android\\Sdk\\ndk-bundle
sdk.dir=C\:\\Users\\Admin\\AppData\\Local\\Android\\Sdk
## :arrow_forward: How to Run App
1. cd to the repo
2. Run Build for either OS
* for iOS
* run `react-native run-ios`
* for Android
* Run Genymotion
* run `react-native run-android`
3. Run on android real device
Follow on doc: https://facebook.github.io/react-native/docs/running-on-device
or copy file .apk in folder .\android\app\build\outputs\apk\debug
## :arrow_forward: Noted
If running for the first time an error occurred, at the next run:
cd android && .\gradlew clean && cd .. && react-native run-android
<file_sep>import React, {Component} from 'react';
import {View, SafeAreaView, Image, Text, ScrollView, TextInput, TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import commonStyle from '../commonStyle';
import { WHITE_COLOR, LIGHT_GREY, PRIMARY_COLOR, SECONDARY_COLOR, BLACK_COLOR } from '../../util/Constants';
import scale, { verticalScale } from '../../util/scale';
import actualDimensions from '../../util/Device';
const {height, width} = actualDimensions;
const BACKGROUND_IMAGE = require('../../../assets/Background_.png');
const LOGO = require('../../../assets/icon_logo_small_.png');
export default class LoginComponent extends Component {
constructor (props) {
super (props);
this.state = {
email: '',
password: '',
isManager: false
}
}
renderInputView () {
return (
<View style={{flex:1, justifyContent: 'flex-end', width: '100%', height: '100%', padding: scale(5)}}>
<ScrollView showsVerticalScrollIndicator = {false} bounces = {false} style={{flex:1}}>
<View style={{paddingVertical: verticalScale(60), justifyContent: 'center', alignItems: 'center'}}>
<Image style={{height: 130, width: 130}} source={LOGO}/>
<Text style={{fontSize: 20, color: WHITE_COLOR, paddingTop: 5, fontWeight: 'bold'}}>HOLDERCLUBS</Text>
<Text style={{fontSize: 8, color: WHITE_COLOR, paddingTop: 5, fontWeight: 'bold'}}>SIGABIT</Text>
<Text style={{fontSize: 30, color: WHITE_COLOR, paddingTop: 40, fontWeight: 'bold'}}>WELCOME</Text>
</View>
<View style={{paddingVertical: verticalScale(2), flexDirection: 'row',alignItems: 'center', borderBottomColor: WHITE_COLOR,borderBottomWidth: scale(0.3)}}>
<Icon name='mail-outline' color={WHITE_COLOR} size={scale(24)} />
<TextInput
autoCorrect = {false}
style={{flex:1, paddingLeft: scale(10), color: WHITE_COLOR}}
value = {this.state.email}
placeholder = 'EMAIL'
placeholderTextColor = {LIGHT_GREY}
onChangeText = {(text) => this.setState({email: text})} />
</View>
<View style={{height: verticalScale(20)}}/>
<View style={{paddingVertical: verticalScale(2), alignItems: 'center', flexDirection: 'row', borderBottomColor: WHITE_COLOR, borderBottomWidth: scale(0.3)}}>
<Icon name='lock' color={WHITE_COLOR} size={scale(24)} />
<TextInput
autoCorrect = {false}
secureTextEntry
style={{flex:1, paddingLeft: scale(10), color: WHITE_COLOR}}
value = {this.state.password}
placeholder = '<PASSWORD>'
placeholderTextColor = {LIGHT_GREY}
onChangeText = {(text) => this.setState({password: text})} />
</View>
<View style={{height: verticalScale(20)}}/>
<TouchableOpacity onLongPress = {() => this.props.onLongPress()}
style={{paddingVertical: verticalScale(10), borderColor: SECONDARY_COLOR, borderWidth: 0.5, borderRadius: 10,
justifyContent: 'center', alignItems: 'center', backgroundColor: PRIMARY_COLOR}} onPress = {() => this.props.login()}>
<Text style={{fontSize: scale(16), fontWeight: 'bold', color: WHITE_COLOR}}>LOGIN</Text>
</TouchableOpacity>
<View style={{paddingVertical: verticalScale(10),justifyContent: 'center', alignItems:'center'}}>
<Text style={{color: WHITE_COLOR, fontSize: scale(14)}}>Don't have an account ?<Text onPress={() => this.props.navigateToSignup()} style={{color: BLACK_COLOR,}}> Signup</Text></Text>
</View>
</ScrollView>
</View>
)
}
render () {
return (
<SafeAreaView style={commonStyle.safeAreaViewContainer}>
<View style={{position: 'absolute', height, width, right: 0, bottom: 0, left: 0, top: 0, width: '100%', height: '100%'}}>
<Image style={{flex:1}} resizeMode='cover' source = {BACKGROUND_IMAGE}/>
</View>
{this.renderInputView()}
</SafeAreaView>
)
}
}<file_sep>import {createStackNavigator, createDrawerNavigator, StackActions, NavigationActions} from 'react-navigation';
import React from 'react';
import Login from './components/Login/LoginContainer';
import Signup from './components/Signup/SignupContainer';
import Drawer from './components/Drawer/DrawerContainer';
import Menu from './components/Menu/MenuContainer';
import PastOrders from './components/PastOrders/PastOrderContainer';
import Cart from './components/Cart/CartContainer';
import Checkout from './components/Checkout/CheckoutContainer';
import MenuItems from './components/MenuItems/MenuItemsContainer';
import ManagerOrders from './components/ManageOrders/ManageOrdersContainer';
import Charts from './components/Charts/ChartsContainer';
import scale from './util/scale';
const mainStackConfig = {
// mode: 'modal'
};
const drawerConfig = {
drawerWidth : scale(250),
contentComponent: (props) => (<Drawer {...props} />)
}
const managerDrawerConfig = {
drawerWidth : scale(250),
contentComponent: (props) => (<Drawer {...props} isManager = {true} />)
}
const UserDrawerRouter = createDrawerNavigator({
MenuGroupScreen: {screen: Menu},
PastOrderScreen: {screen: PastOrders},
MenuItemsScreen: {screen: MenuItems}
}, drawerConfig);
const ManagerDrawer = createDrawerNavigator({
OrdersScreen: {screen: ManagerOrders},
ChartsScreen: {screen: Charts},
}, managerDrawerConfig,)
const MainRouter = createStackNavigator({
LoginScreen: {screen: Login, navigationOptions: {header: null}},
SignupScreen: {screen: Signup, navigationOptions: {header: null}},
ManagersDrawer: {screen: ManagerDrawer, navigationOptions: {header: null}},
Drawer: {screen: UserDrawerRouter, navigationOptions: {header: null}},
CartScreen: {screen: Cart, navigationOptions: {header: null}},
CheckoutScreen: {screen: Checkout, navigationOptions: {header: null}},
// TabNavigator:
}, mainStackConfig);
const resetAction = (routeName) => StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName }),
],
});
// const TabNavigator = createBottomTabNavigator(
// /* screen config ommited */
// {
// tabBarComponent: TabBar,
// tabBarOptions: {
// activeTintColor: "#eeeeee",
// inactiveTintColor: "#222222"
// }
// }
// );
export {resetAction};
export default MainRouter;
// export default TabNavigator;<file_sep>import React, {Component} from 'react';
import {View, TouchableOpacity, ScrollView, Image, Text, SafeAreaView} from 'react-native';
import styles from './style';
import commonStyles from '../commonStyle';
import { WHITE_COLOR } from '../../util/Constants';
import Icon from 'react-native-vector-icons/MaterialIcons';
import showToast from '../../util/Toast';
import scale from '../../util/scale';
const HOME_ICON = require('../../../assets/icon_home_.png');
const ORDER_ICON = require('../../../assets/icon_order_.png');
const PROFILE_ICON = require('../../../assets/icon_profile_.png');
const BELL_ICON = require('../../../assets/icon_bell_.png');
const MENU_ICON = require('../../../assets/icon_menu_.png');
const CONTACT_ICON = require('../../../assets/icon_telephone_.png');
const LOGOUT_ICON = require('../../../assets/icon_logout_.png');
const SMALL_LOGO = require('../../../assets/icon_logo_small_.png')
export default class DrawerComponent extends Component {
constructor (props) {
super (props);
}
renderUserSection () {
return (
<View style={styles.drawerUserContainer}>
<View style={styles.userRectContainer}/>
<View style={styles.triangle}/>
<View style={styles.userContainer}>
<View style={styles.userPictureContainer}/>
<Text style={styles.userNameText}>Name here</Text>
<Text style={{color: WHITE_COLOR}}><EMAIL></Text>
</View>
</View>
)
}
renderDrawerItem = (name, action, image) => {
return (
<TouchableOpacity onPress={() =>action()} style={styles.drawerItemContainer}>
<View style={styles.drawerInnerItemContainer}>
<Image style={{height: scale(24), width: scale(24)}} source = {image} />
</View>
<View style={styles.drawerItemTextContainer}>
<Text style={styles.drawerItemText}>{name}</Text>
</View>
</TouchableOpacity>
)
}
renderBottomLogo() {
return (
<View style={{paddingVertical: scale(20), width: scale(250), alignContent: 'center',}}>
<Image source ={SMALL_LOGO} style={{alignSelf: 'center'}} />
<Text style={{fontSize: scale(14), fontWeight: 'bold', textAlign: 'center', color:WHITE_COLOR}}>HOLDERCLUBS</Text>
<Text style={{fontSize: scale(6), fontWeight: 'bold',textAlign: 'center', color:WHITE_COLOR}}>SIGABIT</Text>
</View>
)
}
render () {
const {navigateTo} = this.props;
return (
<SafeAreaView style={commonStyles.safeAreaViewContainer}>
<ScrollView showsVerticalScrollIndicator = {false} bounces = {false} style={{flex:1}}>
{this.renderUserSection ()}
{this.renderDrawerItem('Home', () => navigateTo('MenuGroupScreen'), HOME_ICON)}
{this.renderDrawerItem('My Orders', () => navigateTo('PastOrderScreen'), ORDER_ICON)}
{this.renderDrawerItem('Menu', () => navigateTo('MenuGroupScreen'), MENU_ICON)}
{this.renderDrawerItem('Profile', () => showToast('Feature yet to be developed'), PROFILE_ICON)}
{this.renderDrawerItem('Notifications', () => showToast('Feature yet to be developed'), BELL_ICON)}
{this.renderDrawerItem('Contact Us', () => showToast('Feature yet to be developed'), CONTACT_ICON)}
{this.renderDrawerItem('Log out', () => navigateTo('LoginScreen', {}, true), LOGOUT_ICON)}
{this.renderBottomLogo()}
</ScrollView>
</SafeAreaView>
)
}
}<file_sep>import ActualDimensions from './Device';
import * as CONST from './Constants';
/**
* Function to scale a value based on the size of the screen size and the original
* size used on the design.
*/
const {height, width} = ActualDimensions;
export default function (units = 1) {
return width / CONST.SCREEN_WIDTH * units;
}
const verticalScale = size => height / CONST.SCREEN_HEIGHT * size;
export { verticalScale };
|
63b5efb122e264a90dd3a3bf049aa5e5dccc579b
|
[
"JavaScript",
"Markdown"
] | 30
|
JavaScript
|
dkquocbao/masternode
|
e4358bae798978e3dc15d6149a34416a82558694
|
34301ac933b54a84924b2a517726fc53069d53b5
|
refs/heads/master
|
<repo_name>zhangtianfengRed/BoxGame3GameoffHYBRID<file_sep>/GameoffHYBRID/Assets/Script/map.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class map : MonoBehaviour {
public mapData minfo = null;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
enum Tag
{
ground,
box,
target
}
void mapGroud()
{
for(int x = 0; x < minfo.maphigh; x++)
{
for(int y = 0; y < minfo.mapwidth; y++)
{
GameObject ground= Instantiate(minfo.ground, new Vector3Int(x, y,0), Quaternion.identity);
ground.tag = Tag.ground.ToString();
}
}
}
}
<file_sep>/githubGameoffBox4/Assets/script/playInput.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playInput : MonoBehaviour {
Receiver receiver = new Receiver();
Commad commadup;
Commad commadleft;
Commad commadright;
Commad commaddown;
// Use this for initialization
void Start () {
commadleft = new Moveleft(receiver);
commadright = new MoveRight(receiver);
commaddown = new MoveDown(receiver);
}
// Update is called once per frame
void Update () {
if (Input.GetKeyUp(KeyCode.W))
{
commadup = new Moveup(receiver,);
InvokeCommad InvokeCommad = new InvokeCommad(commadup);
InvokeCommad.Excutecommad();
}
if (Input.GetKeyUp(KeyCode.A))
{
InvokeCommad InvokeCommad = new InvokeCommad(commadleft);
InvokeCommad.Excutecommad();
}
if (Input.GetKeyUp(KeyCode.S))
{
InvokeCommad InvokeCommad = new InvokeCommad(commaddown);
InvokeCommad.Excutecommad();
}
if (Input.GetKeyUp(KeyCode.D))
{
InvokeCommad InvokeCommad = new InvokeCommad(commadright);
InvokeCommad.Excutecommad();
}
}
public class InvokeCommad
{
public Commad Commad;
public InvokeCommad(Commad commad)
{
Commad = commad;
}
public void Excutecommad()
{
Commad.Action();
}
}
public class play
{
public GameObject
}
public class Receiver
{
public GameObject mygameobjet { get; set; }
public void up()
{
Debug.Log("up");
}
public void Down()
{
Debug.Log("down");
}
public void left()
{
Debug.Log("left");
}
public void right()
{
Debug.Log("right");
}
}
public abstract class Commad
{
protected Receiver PlayRecever;
public Commad(Receiver playRecever,GameObject gameObject)
{
PlayRecever = playRecever;
PlayRecever.mygameobjet = gameObject;
}
public virtual void Action() { }
}
public class MoveDown : Commad
{
public MoveDown(Receiver receiver,GameObject gameObject) : base(receiver, gameObject) { }
public override void Action()
{
PlayRecever.Down();
}
}
public class Moveup : Commad
{
public Moveup(Receiver receiver,GameObject gameObject) : base(receiver, gameObject) { }
public override void Action()
{
PlayRecever.up();
}
}
public class Moveleft : Commad
{
public Moveleft(Receiver receiver,GameObject gameObject) : base(receiver, gameObject) { }
public override void Action()
{
PlayRecever.left();
}
}
public class MoveRight : Commad
{
public MoveRight(Receiver receiver,GameObject gameObject) : base(receiver, gameObject) { }
public override void Action()
{
PlayRecever.right();
}
}
}
<file_sep>/githubGameoffBox4/Assets/script/Map.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Map : MonoBehaviour {
public int high;
public int width;
public GameObject ground;
// Use this for initialization
void Start () {
mapStart();
}
// Update is called once per frame
void Update () {
}
#region 加载关卡
public interface load
{
void loadlevel(int level);
}
class levelload : load
{
public void loadlevel(int level)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(level+1);
}
}
public interface level
{
void Done();
}
public class Level:level
{
public GameObject mylevel { get; set; }
private load Load;
public int _level { get; set; }
public Level(load _load)
{
this.Load = _load;
}
public void Done()
{
Load.loadlevel(_level);
}
}
#endregion
void mapStart()
{
for (int x = 0; x < high; x++) {
for(int y = 0; y < width; y++)
{
Instantiate(ground, new Vector3Int(x, y, 0), Quaternion.identity);
}
}
}
}
<file_sep>/GameoffHYBRID/Assets/Script/mapData.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mapData : ScriptableObject {
public mapData() {
GameobjetList = new GameObject[mapwidth, maphigh];
}
public int mapwidth;
public int maphigh;
public GameObject ground;
public GameObject Button;
public GameObject[,] GameobjetList;
public int pushdistance;
public GameObject MapParent;
public GameObject BoxParent;
public GameObject TargetParent;
public GameObject ButtonParent;
}
<file_sep>/GameoffHYBRID/Assets/Script/Editor/MapDataEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
[CustomEditor(typeof(map))]
public class MapDataEditor:Editor {
map mmap;
void OnEnable()
{
mmap = target as map;
if (mmap.minfo == null)
{
mmap.minfo = new mapData();
}
}
}
|
13fdca59d6ffe44b25ab68d10b27f5a98bbbb331
|
[
"C#"
] | 5
|
C#
|
zhangtianfengRed/BoxGame3GameoffHYBRID
|
1b50a1ab1626931405ca55f595d42408065e4b22
|
1892900d1b67edeb1a8bee2cdbcb359dfe45f60f
|
refs/heads/master
|
<repo_name>haryphamdev/snake-game-java-swing<file_sep>/main/Food.java
package main;
import java.awt.*;
import java.util.*;
// Food is a food item that the snake can eat. It is placed randomly in the pit.
public class Food {
//current food location(x,y) in cells
private int x,y;
//color for display
private Color color = Color.BLUE;
//for randomly placing the food
private Random rand = new Random();
//default constructor
public Food() {
//place outside the pit, so that it will not be "displayed"
x = -1;
y = -1;
}
//Regenerate a food item. Randomly place inside the pit
public void regenerate() {
x = rand.nextInt(GameMain.COLUMNS - 4) + 2;
y = rand.nextInt(GameMain.ROWS - 4) + 2;
}
//Return the x, y coordinate of the cell that contains this food item
public int getX() {
return x;
}
public int getY() {
return y;
}
//Draw itself
public void draw(Graphics g) {
g.setColor(color);
g.fill3DRect(x * GameMain.CELL_SIZE,
y* GameMain.CELL_SIZE,
GameMain.CELL_SIZE,
GameMain.CELL_SIZE,
true);
}
}
<file_sep>/README.md
# snake-game-java-swing
snake game 2d with java swing awt
<file_sep>/main/Snake.java
package main;
import java.awt.*;
import java.util.*;
/*
* A snake is made up of one or more SnakeSegment. The first SnakeSegment is the "head"
* of the snake . The last is the "tail". As the snake moves, it adds one cell to the head
* and then removes one from the tail
* if the snake eats food, the head adds one cell but the tail will not shrink
* */
public class Snake {
private static final int INIT_LENGTH = 3; //snake's cells
public static enum Direction {
UP, DOWN, LEFT, RIGHT
}
private Color color = Color.BLACK; // color for the snake body
private Color colorHead = Color.GREEN; // color for the head
private Snake.Direction direction; // get the current direction of the snake's head
// the snake segments that forms the snake
private java.util.List<SnakeSegment> snakeSegments = new ArrayList<SnakeSegment>();
private boolean dirUpdatePending; //Pending update for a direction change?
private Random random = new Random(); // randomly regenerating a snake
//Regenerate the snake
public void regenerate() {
snakeSegments.clear();
//Randomly generate a snake inside a pit
int length = INIT_LENGTH; // 3 cells
int headX = random.nextInt(GameMain.COLUMNS - length * 2) + length;
int headY = random.nextInt(GameMain.ROWS - length * 2) + length;
direction = Snake.Direction
.values()[random.nextInt(Snake.Direction.values().length)];
snakeSegments.add(new SnakeSegment(headX, headY, length, direction));
dirUpdatePending = false;
}
//Change the direction of the snake, but no 180 degree turn allowed
public void setDirection(Snake.Direction newDir) {
// Ignore if there is a direction change pending and no 180 degree turn
if(!dirUpdatePending
&& (newDir != direction)
&&((newDir == Snake.Direction.UP && direction != Snake.Direction.DOWN)
||(newDir == Snake.Direction.DOWN && direction != Snake.Direction.UP)
||(newDir == Snake.Direction.LEFT && direction != Snake.Direction.RIGHT)
||(newDir == Snake.Direction.RIGHT && direction != Snake.Direction.LEFT
))) {
SnakeSegment headSegment = snakeSegments.get(0);
int x = headSegment.getHeadX();
int y = headSegment.getHeadY();
//add a new segment with zero length as the new head segment
snakeSegments.add(0, new SnakeSegment(x, y, 0, newDir));
direction = newDir;
dirUpdatePending = true; //will be cleared after updated
}
}
//Move the snake by one step. The snake "head" segment grows by one cell
//the rest of the segments remain unchanged. The "tail" will later be shrink
//if collision detected
public void update() {
SnakeSegment headSegment = snakeSegments.get(0);
headSegment.grow();
dirUpdatePending = false; //can process the key input again
}
//Not eaten a food item. Shrink the tail by one cell
public void shrink() {
SnakeSegment tailSegment = snakeSegments.get(snakeSegments.size()-1);
tailSegment.shrink();
if(tailSegment.getLength() == 0) snakeSegments.remove(tailSegment);
}
//Get the X,Y coordinate of the cell that contains the snake's head segment
public int getHeadX() {
return snakeSegments.get(0).getHeadX();
}
public int getHeadY() {
return snakeSegments.get(0).getHeadY();
}
// Returns true if the snake contains the given (x,y) cell, Used in collision dectection
public boolean contains(int x, int y) {
for(int i =0; i< snakeSegments.size(); ++i) {
SnakeSegment segment = snakeSegments.get(i);
if(segment.contains(x,y))return true;
}
return false;
}
// return true if the snake eats itself
public boolean eatItself() {
int headX = getHeadX();
int headY = getHeadY();
//eat itself if the headX, headY hits its body segment (4th onwards)
for(int i =3; i <snakeSegments.size(); ++i) {
SnakeSegment segment = snakeSegments.get(i);
if(segment.contains(headX, headY)) return true;
}
return false;
}
// Draw itself
public void draw(Graphics g) {
g.setColor(color);
for(int i = 0; i< snakeSegments.size(); ++i) {
snakeSegments.get(i).draw(g); //draw all the segments
}
if(snakeSegments.size() > 0) {
g.setColor(colorHead);
g.fill3DRect(
getHeadX() * GameMain.CELL_SIZE,
getHeadY() * GameMain.CELL_SIZE,
GameMain.CELL_SIZE - 1,
GameMain.CELL_SIZE - 1,
true
);
}
}
// For debugging
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Snake[dir="+direction+"\n");
for(SnakeSegment segment: snakeSegments) {
sb.append(" ").append(segment).append("\n");
}
sb.append("]");
return sb.toString();
}
}
|
707d8e3cce5057d3550f7c98a2a2e70009d72b36
|
[
"Markdown",
"Java"
] | 3
|
Java
|
haryphamdev/snake-game-java-swing
|
dd2def6540a3d08060b7796ec8d833ddda41ce58
|
c9adc7b1ca145395e814bf847b7cafc26a55fdf0
|
refs/heads/master
|
<repo_name>Madhav-Malhotra/Madhav-Malhotra.github.io<file_sep>/blog/2021-Annual-Reflection/assets/js/init.js
// ================================ INIT CANVAS ================================
function initApp() {
//Check device width
const width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if (width < 1000) widthError()
else {
//Create PIXI application and add to body
app = new PIXI.Application({
backgroundColor: 0x202020, //Just add 0x and then a hex code.
width: 693,
height: 657
});
app.width = 693; app.height = 657;
right.appendChild(app.view);
left.className = "poetic dark"; right.className = "";
slidesChange("1");
initNav()
}
};
function initNav() {
const nav = document.createElement("div"); nav.className = "menu";
for (let i = 1; i < 13; i++) {
const link = document.createElement("a");
link.innerText = " "; link.onclick = () => changeLink(i);
if (i == 1) link.className = "active";
nav.appendChild(link);
}
body.prepend(nav);
}
function widthError() {
const p = document.createElement("p");
p.innerText = "I'm so sorry, but the poetic reflection is only available on desktop right now :/ Please excuse the inconvenience - Madhav"
p.className = "error";
body.prepend(p);
}
window.onload = initApp();<file_sep>/blog/helpfulness-tips.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-171137279-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-171137279-2');
</script>
<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="The work of a small guy hoping for a big change">
<meta name="keywords"
content="mhbthemes, resume, cv, portfolio, personal, developer, designer,personal resume, onepage, clean, modern">
<meta name="author" content="<NAME>">
<title>Helpfulness Tips</title>
<!-- Favicon -->
<link rel="shortcut icon" href="../assets/img/favicon.png" type="image/png">
<!--== bootstrap ==-->
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<!--== font-awesome ==-->
<link href="../assets/css/font-awesome.min.css" rel="stylesheet">
<!--== animate css ==-->
<link href="../assets/css/animate.min.css" rel="stylesheet">
<!--== style css ==-->
<link href="../style.css" rel="stylesheet">
<!--== responsive css ==-->
<link href="../assets/css/responsive.css" rel="stylesheet">
<!--== theme color css ==-->
<link href="../assets/theme-color/color_3.css" rel="stylesheet">
<!--== jQuery ==-->
<script src="../assets/js/jquery-2.1.4.min.js"></script>
<style>
figure {
margin: 2em 0;
text-align: center;
}
figcaption {
font-size: 1.4rem;
}
a {
color: #DB3F58;
text-decoration: none;
filter: brightness(1);
transition: 0.2s;
}
a:hover {
filter: brightness(0.8);
color: #DB3F58;
}
p.stop {
text-align: center;
}
</style>
<!--[if lt IE 9]>
<script src="//oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!--======= PRELOADER =======-->
<div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
</div>
<!--===== HEADER AREA =====-->
<header class="navbar custom-navbar navbar-fixed-top">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-3 col-xs-12">
<div class="logo">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<a class="theme-color" href="../index.html">Madhav</a>
<!--== logo ==-->
</div>
</div>
<div class="col-md-9 col-sm-8 col-xs-12">
<nav class="main-menu">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<!--== manin menu ==-->
<li><a class="smoth-scroll" href="../index.html#home">Home</a></li>
<li><a class="smoth-scroll" href="../index.html#about">About</a></li>
<li><a class="smoth-scroll" href="../index.html#services">Experience</a></li>
<li><a class="smoth-scroll" href="../index.html#work">Portfolio</a></li>
<li><a class="smoth-scroll" href="../index.html#contact">Contact</a></li>
<li class="active"><a class="smoth-scroll" href="../blog.html">blog</a></li>
</ul>
</div>
</nav>
</div>
</div>
<!--/.row-->
</div>
<!--/.container-->
</header>
<!--===== END HEADER AREA ======-->
<!--===== BREADCROUMB AREA =====-->
<div class="breadcroumb-area" style="background-image: url(../assets/img/blog-bg.JPG);">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>My Friend is her School's Unofficial Guidance Counsellor</h1>
<div class="breadcroumb">
<a href="../index.html">Home</a>
>
<a href="../blog.html">Blog</a>
>
<span class="current active">Helpfulness Tips</span>
</div>
</div>
</div>
</div>
</div>
<!--===== SINGLE POST AREA =====-->
<div class="single-blog-area section-padding">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="single-post-details wow fadeInUp" data-wow-delay="0.4s">
<div class="post-featured-content">
<img src="../assets/img/blog/helpfulness-tips/help.jpg" class="img-responsive" alt="">
</div>
<h2>My Friend is her School's Unofficial Guidance Counsellor</h2>
<div class="post-meta">
<span><i class="fa fa-calendar"></i> 26 August, 2021</span>
<span><i class="fa fa-folder-open"></i> Lessons</span>
<span><i class="fa fa-clock-o"></i> Reading time: 4 minutes</span>
</div>
<div>
<section data-field="body" class="e-content">
<section name="8d00" class="section section--body section--first">
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h4 name="798d" id="798d" class="graf graf--h4 graf-after--h3 graf--subtitle">So I asked her for
tips on how
to be helpful!</h4>
<p name="cd58" id="cd58" class="graf graf--p graf-after--h4">But seriously… every time we talk,
she tells me
a story of another student asking her for help. There are five themes I learned from her
stories:</p>
<ol class="postList">
<li name="df60" id="df60" class="graf graf--li graf-after--p">Recognising when to help</li>
<li name="16fe" id="16fe" class="graf graf--li graf-after--li">How to comfort well</li>
<li name="2d9c" id="2d9c" class="graf graf--li graf-after--li">How to listen well</li>
<li name="a156" id="a156" class="graf graf--li graf-after--li">How to encourage others</li>
<li name="c5ef" id="c5ef" class="graf graf--li graf-after--li">How to build trust</li>
</ol>
<p name="d7da" id="d7da" class="graf graf--p graf-after--li graf--trailing">I’ll cut the filler
and jump
straight to the actionables for each theme 😉</p>
</div>
</div>
</section>
<section name="42f1" class="section section--body">
<div class="section-divider">
<hr class="blog" class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="c05b" id="c05b" class="graf graf--h3 graf--leading">#1 Recognising when to help</h3>
<p name="724c" id="724c" class="graf graf--p graf-after--h3">Check in with friends every ______
period of
time.</p>
<p name="df2c" id="df2c" class="graf graf--p graf-after--p">When someone is visibly stressed /
seems to be
hiding things, ask subtle questions:</p>
<ul class="postList">
<li name="14d5" id="14d5" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“Hey, how have you been recently?”</strong>
</li>
<li name="1d6e" id="1d6e" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“Are you tired today?”</strong>
</li>
<li name="6c7e" id="6c7e" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“How are things back home?”</strong>
</li>
<li name="ca73" id="ca73" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“How are things at school?”</strong>
</li>
</ul>
<p name="7e95" id="7e95" class="graf graf--p graf-after--li">If they refuse to talk about it, only
press if
their safety is at stake.</p>
<ul class="postList">
<li name="4460" id="4460" class="graf graf--li graf-after--p">In that case, ask direct
questions: <strong class="markup--strong markup--li-strong">“I noticed ______ and I’m really
concerned about you and I
really want to help.”</strong></li>
<li name="1dbd" id="1dbd" class="graf graf--li graf-after--li graf--trailing">People can be
nervous in
person. If they don’t want to talk, <strong class="markup--strong markup--li-strong">let them
know they
can text you at a later time.</strong></li>
</ul>
</div>
</div>
</section>
<section name="0975" class="section section--body">
<div class="section-divider">
<hr class="blog" class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="4b72" id="4b72" class="graf graf--h3 graf--leading">#2 How to comfort well</h3>
<p name="4a52" id="4a52" class="graf graf--p graf-after--h3">Acknowledge what the person says and
prompt
them to keep going. <strong class="markup--strong markup--p-strong">The goal is to let them vent
it all
out.</strong></p>
<ul class="postList">
<li name="fb41" id="fb41" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“I’m so sorry to hear that. Is there anything
I can do to
help?”</strong>
</li>
<li name="dfa3" id="dfa3" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“I’m really sorry that happened to
you”</strong>
</li>
<li name="5cd3" id="5cd3" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“I can’t believe ____ did that. I don’t know
what they were
thinking.”</strong>
</li>
<li name="6ade" id="6ade" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“I can see how that causes a lot of
pain.”</strong>
</li>
</ul>
<p name="b5a5" id="b5a5" class="graf graf--p graf-after--li">Ask them about solutions they’ve
tried before
suggesting yours.</p>
<ul class="postList">
<li name="28d6" id="28d6" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“Have you had this happen in the
past?”</strong>
</li>
<li name="e99d" id="e99d" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“When did it start?”</strong>
</li>
<li name="6143" id="6143" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“How are you dealing with this right
now?”</strong>
</li>
<li name="67bb" id="67bb" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“Have you talked to anyone else about
this?”</strong>
</li>
</ul>
<p name="35b0" id="35b0" class="graf graf--p graf-after--li">Tell them it’s okay to be vulnerable.
Don’t
rationally tell them to ‘get over it.’ Especially if they’re crying, as they may feel ashamed.
</p>
<ul class="postList">
<li name="1da1" id="1da1" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“It’s okay to express your emotions. You can
let it
out.”</strong>
</li>
<li name="785a" id="785a" class="graf graf--li graf-after--li"><strong
class="markup--strong markup--li-strong">Quietly talk to them alone</strong> if they’re
crying.</li>
<li name="33db" id="33db" class="graf graf--li graf-after--li">Offer to give them space: <strong
class="markup--strong markup--li-strong">“Don’t worry if you need some time alone. I’ll make
sure you
can have some space.”</strong></li>
</ul>
<p name="0876" id="0876" class="graf graf--p graf-after--li"><strong
class="markup--strong markup--p-strong">Let them know if you relate to the
problem</strong> — IF it’s
not a very serious or unique issue. It can be comforting.</p>
<ul class="postList">
<li name="e3a0" id="e3a0" class="graf graf--li graf-after--p">It can help to ‘double-check’ that
you
understand their issue beforehand: <strong class="markup--strong markup--li-strong">“It sounds
like the
issue is _____?”</strong> If they say yes, then proceed.</li>
</ul>
<p name="4f6b" id="4f6b" class="graf graf--p graf-after--li">If you’re the reason they’re upset,
<strong class="markup--strong markup--p-strong">apologise specifically</strong>:
</p>
<ul class="postList">
<li name="ba91" id="ba91" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“I’m so sorry for being insensitive in saying
_____.”</strong>
</li>
<li name="91b5" id="91b5" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“I’m sorry, I just realised I’ve been really
hard on you.
Saying _____ was uncalled for.”</strong>
</li>
</ul>
<p name="6b3b" id="6b3b" class="graf graf--p graf-after--li">If you don’t know the person well,
tell them
what you noticed was wrong and that you care. Give them the <em
class="markup--em markup--p-em">option
</em>to text back later.</p>
<p name="07b7" id="07b7" class="graf graf--p graf-after--p graf--trailing"><strong
class="markup--strong markup--p-strong">Follow-up via text at the end of the day. </strong>It
shows you
care + people may be more comfortable virtually.</p>
</div>
</div>
</section>
<section name="ac4a" class="section section--body">
<div class="section-divider">
<hr class="blog" class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="07e9" id="07e9" class="graf graf--h3 graf--leading">#3 How to Listen Well</h3>
<p name="d1b9" id="d1b9" class="graf graf--p graf-after--h3">To actively listen:</p>
<ul class="postList">
<li name="3d1e" id="3d1e" class="graf graf--li graf-after--p"><strong
class="markup--strong markup--li-strong">Say back what you heard</strong></li>
<li name="1e5f" id="1e5f" class="graf graf--li graf-after--li"><strong
class="markup--strong markup--li-strong">Ask followups</strong></li>
<li name="b873" id="b873" class="graf graf--li graf-after--li">Remind yourself not to think
about what to
say next</li>
<li name="6e42" id="6e42" class="graf graf--li graf-after--li">Nod your head</li>
<li name="ca6f" id="ca6f" class="graf graf--li graf-after--li"><strong
class="markup--strong markup--li-strong">Say/text tiny affirmations: “Uh-hm. What? Really?
I’m so
sorry.”</strong></li>
</ul>
<p name="87d7" id="87d7" class="graf graf--p graf-after--li"><strong
class="markup--strong markup--p-strong">If you don’t relate to a problem, just acknowledge
that you’re
listening.</strong> Use the example prompts in #2.</p>
<p name="74df" id="74df" class="graf graf--p graf-after--p"><strong
class="markup--strong markup--p-strong">Don’t be rational when they’re emotional</strong>.
Don’t show
judgement if you don’t think their problem is a big deal. That includes body language: not
scoffing,
laughing, widening your eyes, etc.</p>
<p name="7ea4" id="7ea4" class="graf graf--p graf-after--p graf--trailing"><strong
class="markup--strong markup--p-strong">If people are too vague / complicated, just tell them
you’re
confused.</strong> “I’m sorry, could you please explain that?”</p>
</div>
</div>
</section>
<section name="a65e" class="section section--body">
<div class="section-divider">
<hr class="blog" class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="27ea" id="27ea" class="graf graf--h3 graf--leading">#4 How to encourage others</h3>
<p name="715e" id="715e" class="graf graf--p graf-after--h3"><strong
class="markup--strong markup--p-strong">Use specific examples when giving
compliments.</strong> It’s
more believable.</p>
<p name="2cc7" id="2cc7" class="graf graf--p graf-after--p">Still, <strong
class="markup--strong markup--p-strong">they might not respond to compliments. It’s usually
okay.</strong></p>
<ul class="postList">
<li name="f805" id="f805" class="graf graf--li graf-after--p">If they’re usually shy, it’s okay
if they
don’t respond to compliments.</li>
<li name="16ea" id="16ea" class="graf graf--li graf-after--li">If they’re usually outgoing but
start being
awkward, ask if you said something wrong.</li>
</ul>
<p name="156f" id="156f" class="graf graf--p graf-after--li"><strong
class="markup--strong markup--p-strong">Tell them specific examples of past successes they’ve
had.</strong> This can help with hopelessness / insecurity.</p>
<ul class="postList">
<li name="d0fd" id="d0fd" class="graf graf--li graf-after--p">If they used to be excited about
_____ and
are now demotivated, <strong class="markup--strong markup--li-strong">remind them what
motivated them to
start with.</strong></li>
</ul>
<p name="4a5f" id="4a5f" class="graf graf--p graf-after--li">If they’re making a big deal out of a
problem,
ASK THEM to break down the problem / take a tiny action to fix it. People believe what they say
themselves
more.</p>
<ul class="postList">
<li name="1987" id="1987" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“How could we make that better?”</strong>
</li>
<li name="6d5e" id="6d5e" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“Can we break down that problem?”</strong>
</li>
<li name="dcd2" id="dcd2" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“Maybe we could focus on one part of that
issue?”</strong>
</li>
</ul>
<p name="2279" id="2279" class="graf graf--p graf-after--li graf--trailing">P.S. People compliment
you about
things they like to be complimented about. <strong
class="markup--strong markup--p-strong">Notice what
others compliment you about + compliment them about those things.</strong></p>
</div>
</div>
</section>
<section name="4b3a" class="section section--body">
<div class="section-divider">
<hr class="blog" class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<h3 name="04bd" id="04bd" class="graf graf--h3 graf--leading">#5 How to Build Trust</h3>
<p name="0ee8" id="0ee8" class="graf graf--p graf-after--h3"><strong
class="markup--strong markup--p-strong">Make eye contact. And smile :-)</strong></p>
<p name="1287" id="1287" class="graf graf--p graf-after--p"><strong
class="markup--strong markup--p-strong">Share personal stories. Ex: about your youth, family,
hobbies,
etc. </strong>And invite them to reciprocate.</p>
<ul class="postList">
<li name="5d02" id="5d02" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">“Have
you also
experienced something like this?”</li>
</ul>
<p name="f75d" id="f75d" class="graf graf--p graf-after--li"><strong
class="markup--strong markup--p-strong">Find connections with their past or present lives. Or
their
future goals.</strong></p>
<ul class="postList">
<li name="4834" id="4834" class="graf graf--li graf-after--p">Past connections build comfort.
Ex: “Wow, we
both did Girl Scouts!”</li>
<li name="4885" id="4885" class="graf graf--li graf-after--li">Present connections build
understanding.
Ex: “Yeah, I’ve also been having work stress spill over at home.”</li>
<li name="b286" id="b286" class="graf graf--li graf-after--li">Future connections build
excitement. Ex:
“I’m dreaming so much about living like an adult in university!”</li>
</ul>
<p name="139b" id="139b" class="graf graf--p graf-after--li">Show appreciation. Especially about
little
things.</p>
<ul class="postList">
<li name="4e12" id="4e12" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“I really appreciate you trusting me enough
to talk about
this.”</strong>
</li>
<li name="82b3" id="82b3" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“You’ve been really brave in sharing all
this. Thank
you.”</strong>
</li>
<li name="185c" id="185c" class="graf graf--li graf--startsWithDoubleQuote graf-after--li">
<strong class="markup--strong markup--li-strong">“I think it’s <em
class="markup--em markup--li-em">so
</em>important that you’re looking for new solutions instead of giving up.”</strong>
</li>
</ul>
<p name="122b" id="122b" class="graf graf--p graf-after--li">Tell them your intention is to help
them:</p>
<ul class="postList">
<li name="1bb4" id="1bb4" class="graf graf--li graf-after--p">Before giving advice, say: <strong
class="markup--strong markup--li-strong">“I was thinking of how to help you with ______
and…”</strong>
</li>
</ul>
<p name="0c8a" id="0c8a" class="graf graf--p graf-after--li">Tell them your intention is to be
honest.
Especially during disagreements.</p>
<ul class="postList">
<li name="5b74" id="5b74" class="graf graf--li graf--startsWithDoubleQuote graf-after--p">
<strong class="markup--strong markup--li-strong">“I know this sounds unnatural, but I want to
be honest with
you. I actually think _____.”</strong>
</li>
</ul>
<p name="a67d" id="a67d" class="graf graf--p graf-after--li graf--trailing">Still, sometimes
people won’t
reciprocate trust / vulnerability. It’s easier to get yourself to move on than to get them to
change.</p>
</div>
</div>
</section>
<section name="edd2" class="section section--body section--last">
<div class="section-divider">
<hr class="blog" class="section-divider">
</div>
<div class="section-content">
<div class="section-inner sectionLayout--insetColumn">
<p name="45eb" id="45eb" class="graf graf--p graf--leading graf--trailing">Special thanks to <a
href="https://www.linkedin.com/in/ayleen-farnood-747b9614b?originalSubdomain=ca"
data-href="https://www.linkedin.com/in/ayleen-farnood-747b9614b?originalSubdomain=ca"
class="markup--anchor markup--p-anchor" rel="noopener" target="_blank"><NAME></a> to
sharing all
this wisdom. And for going through the trouble of learning it the hard way and making hundreds
of lives
brighter in the process :-)</p>
</div>
</div>
</section>
</section>
</div>
</div>
</div>
<div class="col-md-4">
<div class="widget about-me">
<!-- widget single -->
<h3 class="widget-title">About me</h3>
<img src="../assets/img/author.jpg" alt="">
<h4 class="about-heading" style="margin-top: 1.5em;">I'm a student training to solve
globally <span>neglected issues</span>!
</h4>
</div>
<div class="widget social">
<!-- widget single -->
<h3 class="widget-title">Get in Touch!</h3>
<ul class="social-links">
<!--=== social-links ===-->
<li><a href="https://www.linkedin.com/in/madhav-malhotra/" target="_blank"><i
class="fa fa-linkedin"></i></a></li>
<li><a href="https://madhav-malhotra003.medium.com/" target="_blank"><i class="fa fa-medium"></i></a></li>
<li><a href="https://github.com/Madhav-Malhotra" target="_blank"><i class="fa fa-github"></i></a></li>
<li><a href="https://www.youtube.com/channel/UCWopBNISjL7qCH2Qch58Skw" target="_blank"><i
class="fa fa-youtube-play"></i></a></li>
</ul>
</div>
</div>
</div>
<!--/.row-->
</div>
<!--/.container-->
</div>
<!--===== END BLOG POST AREA =====-->
<!--====== FOOTER AREA ======-->
<footer class="footer">
<div class="container">
<div class="row wow zoomIn" data-wow-delay="0.4s">
<div class="col-md-12 text-center">
<p>Find me here 👇 😋</p>
<ul class="social-links footer" style="margin-top: 0.25em;">
<!--=== social-links ===-->
<li><a href="https://www.linkedin.com/in/madhav-malhotra/" target="_blank"><i
class="fa fa-linkedin"></i></a></li>
<li><a href="https://madhav-malhotra003.medium.com/" target="_blank"><i class="fa fa-medium"></i></a></li>
<li><a href="https://github.com/Madhav-Malhotra" target="_blank"><i class="fa fa-github"></i></a></li>
<li><a href="https://www.youtube.com/channel/UCWopBNISjL7qCH2Qch58Skw" target="_blank"><i
class="fa fa-youtube-play"></i></a></li>
</ul>
<br>
<p id="copyright">©2020 <strong><NAME></strong></p>
</div>
</div>
</div>
</footer>
<!--====== END FOOTER AREA ======-->
<script src="/assets/js/insertParts/customCopyright.js"></script>
<script src="/assets/js/insertParts/customBlogAbout.js"></script>
<script src="/assets/js/insertParts/customSocialLinks.js"></script>
<script src="/assets/js/insertParts/customBlogNav.js"></script>
<!--== plugins js ==-->
<script src="../assets/js/plugins.js"></script>
<!--== typed js ==-->
<script src="../assets/js/typed.js"></script>
<!--== stellar js ==-->
<script src="../assets/js/jquery.stellar.min.js"></script>
<!--== counterup js ==-->
<script src="../assets/js/jquery.counterup.min.js"></script>
<!--== waypoints js ==-->
<script src="../assets/js/jquery.waypoints.min.js"></script>
<!--== wow js ==-->
<script src="../assets/js/wow.min.js"></script>
<!--== validator js ==-->
<script src="../assets/js/validator.min.js"></script>
<!--== mixitup js ==-->
<script src="../assets/js/jquery.mixitup.js"></script>
<!--== contact js ==-->
<script src="../assets/js/contact.js"></script>
<!--== main js ==-->
<script src="../assets/js/main.js"></script>
</body>
</html><file_sep>/blog/2021-Annual-Reflection/assets/js/scenes.js
// ================================ INITIALISATION ================================
let app;
const right = document.querySelector("#right");
const body = document.body;
const left = document.querySelector("#left");
let loader = PIXI.Loader.shared;
const Tween = createjs.Tween;
const Ticker = createjs.Ticker;
Ticker.framerate = 60;
// ================================ CHANGE SLIDES ================================
function slidesChange(slideNum) {
clearIntervals(); clearDomTween();
app.stage.removeChildren(); left.innerHTML = "";
const sceneLoad = slides[slideNum];
for (let i = 1; i <= slideNum; i++) {
const pos = `./assets/${i}/${i}.json`;
if (!loader.resources[pos] && i != slideNum) loader.add(pos);
else if (!loader.resources[pos] && i == slideNum) loader.add(pos).load(sceneLoad);
else if (loader.resources[pos] && i == slideNum) sceneLoad();
};
}
function changeLink(i) {
const nav = document.querySelector("div.menu");
for (let j = 0; j < 12; j++) {
if (j+1 != i) nav.children[j].className = "";
else nav.children[j].className = "active";
}
slidesChange(i);
}
const slides = {
"1": () => scene1(),
"2": () => scene2(),
"3": () => scene3(),
"4": () => scene4(),
"5": () => scene5(),
"6": () => scene6(),
"7": () => scene7(),
"8": () => scene8(),
"9": () => scene9(),
"10": () => scene10(),
"11": () => scene11(),
"12": () => scene12()
};
const slideText = {
"2": ["Throughout my life, I have relied on the kindness of strangers.", "", "Those who wiped away my very first tears.", "Those who welcomed me into their homes when I had none.", "Those who judged me on the content of my character,", "And not the colour of my skin.", "", "I have grown familiar with the kindness of strangers in life.", "I could not afford to do otherwise.", "", "The road still carries on."],
"3": ["We are all walking a journey.","To a destination we do not know.","We cannot know for we have never been.","","The sky's fire in a sunrise.","The open landscape amidst a clearing of trees.","Don't wait to appreciate beauty when it comes.","Just don't wait.","","Thinking is easy.","Believing is the hard part.","","The road still carries on."],
"4": ["We are all borne to the human hardship","That joy becomes struggle;","And struggle becomes joy.","","Yet they were never anything but entwined.","","What difference in the loss of peace and the loss of war?","Suffering is human, whether in wartime or peace.","","We all trek the hills of struggle and joy.","Weaving invisible, intractable, incomprehensible tracks.","Inevitably, the ground disappears beneath our feet.","","The road still carries on."],
"5": ["Sink down lower.","Let the waves crash and rise.","","I see but I do not look.","I look but I do not see.","","The universe is an ashen barrens.","","How low can I go?","How long till there is light?","","The road still carries on."],
"6": ["I fight up the hill.","","Though it is hot;","Though I do not like it;","Though I do not know why I started;","Nor what I will see when I get up there.","","I reach the top.","","Great the journey, little the gain.","Atop the hill: an unlit torch.","A silent beacon on the hill.","","Light the torch.",],
"7": ["Lights come and go,","But the darkness is constant.","Darkness is one;","It's the light that has distinctions.","","Look in the mirror;","But the reflection is not my own.","Look down to my hands;","See the monster I have been.","","But truth be told,","There is nothing separating light and darkness,","But the strain in our eyes.","","The road still carries on."],
"8": ["We search 'out there' for meaning.","Something to fill the emptiness.","Yet the truth is this:","There is no meaning to be found 'out there'.","","No matter how we chase the fog,","when we're in the fog it eludes us.","No matter how we admire the frost,","when we touch the frost it fades.","","Some things, we may only appreciate from afar.","The beauty of things in the end,","is the very fact they do not last.","","The road still carries on."],
"9": ["Our artificial boundaries in the sand","Are ever-fading in the tempest of life.","","In truth, all is connected. ","","The greeting of the breeze on my face","Takes and brings my warmth.","The grass on which I step","Is shaped by the footprints I leave.","The sun's rays and human smiles","Brighten my face just as theirs.","","The road still carries on."],
"10": ["We are like fire.","From dust we came;","And to dust we shall return.","Yet the transient spark in the middle is noble.","","In a way only we can understand.","In a way only we can celebrate.","In a way only we can be.","","I am proud to listen to the human.","Not in her divinity,","But in her imperfect growth.","","The road still carries on."],
"11": ["My story may not have had a happy beginning.","Yet it is not the beginning that defines a story.","","Art is to choose to create;","Knowing full well its lack of meaning;","And its inevitable demise.","","The excitement of creativity,","The pull of curiosity,","The relief of humour,","The awe of nature,","The compassion of giving.","","There are things that can block the meaningless of life.","","To live is to create meaning.","To live is art.","","The road still carries on."],
"12": ["Just as I am within the universe.","The universe is within me.","There is no world","But the world I choose to see.","","I am the source of darkness.","I am the source of light.","I am the lighter of torches.","The only citadel in night.","","Be not master of my fate","I am captain of my soul.","","The road still carries on."],
}
// ================================ SCENES ================================
function scene1() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/1/1.json"].spritesheet.textures;
const body = new PIXI.Sprite(s['BodyArms1.png']);
const hill = new PIXI.Sprite(s['roundHill1.png']);
let eyes = [new PIXI.Sprite(s['Eyes1.png']), new PIXI.Sprite(s['ClosedEyes1.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
//Init Text
const title = document.createElement('h1'); title.innerText = "The Road Still Carries On";
const text = document.createElement('p'); text.innerText = "A journey through fear.";
const button = document.createElement("button"); button.innerText = "Start"; button.className = "poetic"
//Size
person.addChild(body);
person.addChild(eyes);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 3; person.y = app.height / 6;
hill.scale.x = 1/1.24; hill.scale.y = 1/1.26; hill.y = app.height / 20;
//Create animation
Tween.get(person, {loop: true})
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
const blinkingEyes = () => {
if (eyes.currentFrame == 0 && Math.random() > 0.6) {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 100);
}
};
addInterval("blinkingEyes", 1000, blinkingEyes);
//Add to screen
scene.addChild(person); scene.addChild(hill); //addChild for PIXI.js el. appendChild for DOM el
left.appendChild(title); left.appendChild(text); left.appendChild(button);
button.onclick = () => changeLink(2);
app.stage.addChild(scene); addDomEl("person", person);
}
function scene2() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s1 = loader.resources["./assets/1/1.json"].spritesheet.textures;
const s = loader.resources["./assets/2/2.json"].spritesheet.textures;
const body = new PIXI.Sprite(s['Body2.png']); const child = new PIXI.Sprite(s["Body2.png"]);
const leftArm = new PIXI.Sprite(s['Left_trim2.png']); const rightArm = new PIXI.Sprite(s['Right_trim2.png']);
let eyes = [new PIXI.Sprite(s['SmilingEyes2.png']), new PIXI.Sprite(s1['Eyes1.png'])]; const oneEye = new PIXI.Sprite(s["OneEye2.png"]);
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
//Init Text
const poem = slideText["2"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
person.addChild(body); person.addChild(eyes); person.addChild(leftArm); person.addChild(rightArm);
person.scale.x = 0.7; person.scale.y = 0.7; person.x = app.width / 3; person.y = app.height / 6;
leftArm.pivot.set(0, 0); leftArm.x = person.width / 2.2; leftArm.y = person.height / 1.35; leftArm.angle = 20;
rightArm.pivot.set(0, 0); rightArm.x = person.width / 1.2; rightArm.y = person.height / 1.35; rightArm.angle = 30;
child.addChild(oneEye); oneEye.x = child.width / 5;
child.scale.x = 0.22; child.scale.y = 0.22; child.x = app.width / 2.3; child.y = app.height / 1.3; child.angle = -88;
//Create animation
Tween.get(person, {loop: true})
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
Tween.get(child, {loop: true})
.to({y: app.height / 1.37}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 1.3}, 1500, createjs.Ease.sineInOut)
const eyesAndRock = () => {
if (eyes.currentFrame == 0 && Math.random() > 0.6) {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 1500);
}
if (Math.random() > 0.5) {
Tween.get(leftArm)
.to({angle: -10}, 1200, createjs.Ease.sineInOut)
.to({angle: 20}, 1200, createjs.Ease.sineInOut)
Tween.get(rightArm)
.to({angle: -10}, 1200, createjs.Ease.sineInOut)
.to({angle: 30}, 1200, createjs.Ease.sineInOut)
Tween.get(child)
.to({angle: -92, x: app.width / 1.9}, 1200, createjs.Ease.sineInOut)
.to({angle: -88, x: app.width / 2.3}, 1200, createjs.Ease.sineInOut)
}
};
addInterval("eyesAndRock", 2500, eyesAndRock);
//Add to screen
scene.addChild(person); //addChild for PIXI.js el. appendChild for DOM el
scene.addChild(child);
button.onclick = () => changeLink(3);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("child", child);
}
function scene3() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/3/3.json"].spritesheet.textures;
const body = new PIXI.Sprite(s['SideBody3.png']);
const hill = new PIXI.Sprite(s['Hill3.png']);
let eyes = [new PIXI.Sprite(s['SideEye3.png']), new PIXI.Sprite(s['SideEyeGlare3.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
//Init Text
const poem = slideText["3"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
person.addChild(body); person.addChild(eyes);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 3; person.y = app.height / 6;
hill.scale.x = 1/1.24; hill.scale.y = 1/1.26; hill.anchor.set(0.75,0.2);
//Create animation
Tween.get(hill, {loop: true})
.wait(500)
.to({x: 500, y: -50}, 1000, createjs.Ease.sineIn)
.to({x: 1000, y: 450}, 700)
.to({x: 1932, y: 613}, 1600, createjs.Ease.sineOut)
.call(() => {
Tween.get(person)
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
})
.wait(1500)
Tween.get(person, {loop: true})
.wait(500)
.to({angle: -10}, 1000, createjs.Ease.sineInOut)
.to({angle: 20}, 350, createjs.Ease.sineInOut)
.wait(350)
.to({angle: 0}, 1600, createjs.Ease.sineOut)
.wait(1500)
const glaringEyes = () => {
setTimeout(() => eyes.gotoAndStop(1), 500);
setTimeout(() => eyes.gotoAndStop(0), 3800);
};
glaringEyes();
addInterval("glaringEyes", 5300, glaringEyes);
//Add to screen
scene.addChild(person); scene.addChild(hill); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(4);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("hill", hill);
}
function scene4() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/4/4.json"].spritesheet.textures;
const s3 = loader.resources["./assets/3/3.json"].spritesheet.textures;
const hill = new PIXI.Sprite(s['Flat4.png']);
const body = new PIXI.Sprite(s3['SideBody3.png']);
let eyes = [new PIXI.Sprite(s3['SideEye3.png']), new PIXI.Sprite(s['DizzyEye4.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
//Init Text
const poem = slideText["4"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
person.addChild(body); person.addChild(eyes);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 3; person.y = app.height / 6;
hill.scale.x = 1.2; hill.scale.y = 1.3; hill.anchor.set(0.7, -0.52)
//Create animation
Tween.get(person, {loop: true})
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
.to({y: 400}, 800, createjs.Ease.sineIn)
.to({x: 400}, 3000, createjs.Ease.sineIn)
.to({y: 500, x: 200}, 3000, createjs.Ease.sineOut)
.to({y: 600, x: app.width / 3}, 200, createjs.Ease.elasticIn)
.wait(500)
.to({y: app.height / 6}, 1000, createjs.Ease.sineIn)
.wait(1100) //14.1
Tween.get(person, {loop: true})
.wait(4000)
.to({angle: -10}, 1600, createjs.Ease.sineInOut)
.to({angle: -40}, 1500, createjs.Ease.sineInOut)
.to({angle: -440}, 6000, createjs.Ease.sineInOut)
.wait(500)
.to({angle: -360}, 1500, createjs.Ease.sineInOut)
.wait(500) //14.1
Tween.get(hill, {loop: true})
.wait(4000)
.to({x: 2500}, 3000, createjs.Ease.sineIn)
.wait(6000)
.to({x: 0, y: 300}, 1, createjs.Ease.elasticIn)
.to({x: 0, y: 0}, 150, createjs.Ease.elasticOut)
.wait(2400) //14.1
const dizzyEyes = () => {
setTimeout(() => eyes.gotoAndStop(1), 6550);
setTimeout(() => eyes.gotoAndStop(0), 13600);
};
dizzyEyes();
addInterval("dizzyEyes", 15600, dizzyEyes);
//Add to screen
scene.addChild(person); scene.addChild(hill); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(5);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("hill", hill);
}
function scene5() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/5/5.json"].spritesheet.textures;
const s4 = loader.resources["./assets/4/4.json"].spritesheet.textures;
const base = new PIXI.Sprite(s['SideBody5.png']); const head = new PIXI.Sprite(s['Head5.png']);
const sadEye = new PIXI.Sprite(s['SadEye5.png']); const hill = new PIXI.Sprite(s4['Flat4.png']);
//Init Text
const poem = slideText["5"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
head.addChild(sadEye); person.addChild(head); person.addChild(base);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 1.05; person.y = app.height / 6;
hill.scale.x = 1.2; hill.scale.y = 1.2; hill.anchor.set(0.7, -0.7)
//Create animation
Tween.get(person, {loop: true})
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
Tween.get(person, {loop: true})
.to({x: app.height / 3}, 8000, createjs.Ease.sineInOut)
.wait(8000)
.to({x: -170}, 8000, createjs.Ease.sineInOut)
Tween.get(head, {loop: true})
.wait(8000)
.to({angle: 20, x: 110, y: -50}, 4000, createjs.Ease.sineInOut)
.to({angle: 0, x: 0, y: 0}, 4000, createjs.Ease.sineInOut)
.wait(8000)
//Add to screen
scene.addChild(person); scene.addChild(hill); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(6);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("head", head);
}
function scene6() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/6/6.json"].spritesheet.textures;
const s1 = loader.resources["./assets/1/1.json"].spritesheet.textures;
const hill = new PIXI.Sprite(s1['roundHill1.png']);
const stone = new PIXI.Sprite(s["Stone6.png"]); const stone2 = new PIXI.Sprite(s["Stone6.png"])
const leftArm = new PIXI.Sprite(s["LeftArm6.png"]); const rightArm = new PIXI.Sprite(s["RightArm6.png"]);
const base = new PIXI.Sprite(s["BodyAndHead6.png"]); const stick = new PIXI.Sprite(s["Stick6.png"]);
let fire = getFire();
let eyes = [new PIXI.Sprite(s['Eyes6.png']), new PIXI.Sprite(s['ClosedEyes6.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
//Init Text
const poem = slideText["6"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; button.id = "light-button"; left.appendChild(button);
//Size
person.scale.x = 1/2.8; person.scale.y = 1/2.8; person.x = app.width / 2.3; person.y = app.height / 2.7;
hill.scale.x = 1/1.24; hill.scale.y = 1/1.2;
fire.scale.set(0.6); fire.position.set(205,280);
stick.scale.x = 1/4.7; stick.scale.y = 1/4.7; stick.x = 330; stick.y = 390;
stone.scale.set(1/2.2, 1/2.2); stone.anchor.set(0,-1.7); stone2.scale.set(1/2.2, 1/2.2); stone2.anchor.set(-0.1,-2.4);
//Create animation
Tween.get(person, {loop: true})
.to({y: app.height / 2.6}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 2.7}, 1500, createjs.Ease.sineInOut)
const blinkingEyes = () => {
if (eyes.currentFrame == 0 && Math.random() > 0.6) {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 100);
}
};
addInterval("blinkingEyes", 1000, blinkingEyes);
function light() {
const button = document.getElementById("light-button"); button.innerText = "The road still carries on."
button.onclick = () => changeLink(7);
let fireInterval
Tween.get(leftArm)
.to({angle: 10, x: 80, y: -50}, 500, createjs.Ease.sineIn)
.to({angle: 0, x: 0, y: 0}, 100)
.call(() => {
scene.removeChildren();
scene.addChild(stick, fire, hill, person);
let i = 0;
fireInterval = () => {
fire.children[1].gotoAndStop(i)
i++
if (i == 40) i = 0;
};
addInterval("firePlay", 42, fireInterval);
});
Tween.get(rightArm)
.to({angle: -10, x: -80, y: 50}, 500, createjs.Ease.sineIn)
.to({angle: 0, x: 0, y: 0}, 100)
Tween.get(person)
.wait(500)
.to({x: app.width / 1.3, angle: 20}, 600, createjs.Ease.sineInOut)
}
//Add to screen
rightArm.addChild(stone); person.addChild(rightArm); person.addChild(base);
leftArm.addChild(stone2); person.addChild(leftArm); person.addChild(eyes);
scene.addChild(stick); scene.addChild(hill); scene.addChild(person); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = light;
app.stage.addChild(scene); addDomEl("person", person); addDomEl("leftArm", leftArm); addDomEl("rightArm", rightArm);
}
function scene7() {
const scene = new PIXI.Container(); const person = new PIXI.Container(); const fg = new PIXI.Container();
//Init Sprites
const s1 = loader.resources["./assets/1/1.json"].spritesheet.textures;
const s = loader.resources["./assets/7/7.json"].spritesheet.textures;
const base = new PIXI.Sprite(s1['BodyArms1.png']);
const hill = new PIXI.Sprite(s1['roundHill1.png']); const bg = new PIXI.Sprite(s['HillTrail7.png']);
let eyes = [new PIXI.Sprite(s1['Eyes1.png']), new PIXI.Sprite(s1['ClosedEyes1.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
let fires = []
for (let f = 0; f < 4; f++) {
let fire = getFire();
if (f == 0) fg.addChild(fire);
else bg.addChild(fire);
fires.push(fire);
}
//Init Text
const poem = slideText["7"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
person.addChild(base); person.addChild(eyes); fg.addChild(person, hill);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 10; person.y = app.height / 6;
hill.anchor.set(0.08, 0.12); bg.scale.set(1/1.25, 1/1.25);
fires[0].scale.set(0.6); fires[0].pivot.set(-400,-470);
fires[1].scale.set(0.3); fires[1].pivot.set(-1600,-800);
fires[2].scale.set(0.15); fires[2].pivot.set(-4600, -900);
fires[3].scale.set(0.075); fires[3].pivot.set(-10900, -800);
//Create animation
const blurFG = new PIXI.filters.BlurFilter(0); const blurBG = new PIXI.filters.BlurFilter(10);
bg.filters = [blurBG]; fg.filters = [blurFG];
Tween.get(person, {loop: true})
.to({y: app.height / 8}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
Tween.get(blurBG, {loop: true})
.wait(4500)
.to({blur: 0}, 3000, createjs.Ease.sineInOut)
.wait(4500)
.to({blur: 10}, 3000, createjs.Ease.sineInOut)
Tween.get(blurFG, {loop: true})
.wait(4500)
.to({blur: 10}, 3000, createjs.Ease.sineInOut)
.wait(4500)
.to({blur: 0}, 3000, createjs.Ease.sineInOut)
const blinkingEyes = () => {
if (eyes.currentFrame == 0 && Math.random() > 0.6) {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 100);
}
};
addInterval("blinkingEyes", 1000, blinkingEyes);
let i = 0;
const firePlay = () => {
for (f of fires) {f.children[1].gotoAndStop(i)}
i++
if (i == 40) i = 0;
}
addInterval("firePlay", 42, firePlay);
//Add to screen
scene.addChild(bg); scene.addChild(fg); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(8);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("blurFG", blurFG); addDomEl("blurBG", blurBG);
}
function scene8() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/8/8.json"].spritesheet.textures;
const s1 = loader.resources["./assets/1/1.json"].spritesheet.textures;
const s2 = loader.resources["./assets/2/2.json"].spritesheet.textures;
const s4 = loader.resources["./assets/4/4.json"].spritesheet.textures;
const snow = new PIXI.Sprite(s['Snow8.png']); const hill = new PIXI.Sprite(s4["Flat4.png"]);
const body = new PIXI.Sprite(s2['Body2.png']);
const leftArm = new PIXI.Sprite(s['LeftArm8.png']); const rightArm = new PIXI.Sprite(s['RightArm8.png']);
let eyes = [new PIXI.Sprite(s1['Eyes1.png']), new PIXI.Sprite(s2['SmilingEyes2.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
//Init Text
const poem = slideText["8"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
hill.scale.x = 1.2; hill.scale.y = 1.2; hill.anchor.set(0.7, -0.7);
snow.scale.set(0.3,0.3); snow.position.set(250,-20);
person.addChild(body); person.addChild(eyes); person.addChild(leftArm); person.addChild(rightArm);
leftArm.pivot.set(1,0); leftArm.position.set(117,370); rightArm.position.set(300,385);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 3; person.y = app.height / 4.8;
//Create animation
Tween.get(person, {loop: true})
.wait(4300)
.to({y: app.height / 6}, 1500, createjs.Ease.sineInOut)
.to({y: app.height / 4.8}, 1500, createjs.Ease.sineInOut)
.wait(4300)
Tween.get(snow, {loop: true})
.to({x: 210}, 700, createjs.Ease.sineInOut).to({x: 250}, 700, createjs.Ease.sineInOut)
.to({x: 210}, 700, createjs.Ease.sineInOut).to({x: 250}, 700, createjs.Ease.sineInOut)
.to({x: 210}, 700, createjs.Ease.sineInOut).to({x: 250}, 700, createjs.Ease.sineInOut)
.wait(100).to({x: 440}, 0).wait(3000)
.to({x: 480}, 700, createjs.Ease.sineInOut).to({x: 440}, 700, createjs.Ease.sineInOut)
.to({x: 480}, 700, createjs.Ease.sineInOut).to({x: 440}, 700, createjs.Ease.sineInOut)
.to({x: 480}, 700, createjs.Ease.sineInOut).to({x: 440}, 700, createjs.Ease.sineInOut)
.wait(3100)
Tween.get(snow, {loop: true})
.to({y: 50}, 700).to({y: 100}, 700)
.to({y: 150}, 700).to({y: 200}, 700)
.call(() => {
Tween.get(leftArm)
.to({angle: 90, y: 320, x: 170}, 1500, createjs.Ease.sineInOut)
.wait(1000)
.to({angle: 0, y: 370, x: 117}, 1500, createjs.Ease.sineInOut)
})
.to({y: 250}, 700).to({y: 295}, 700)
.call(() => {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 1500)
})
.to({alpha: 0}, 100)
.to({y: -20, alpha: 1}, 0).wait(3000)
.to({y: 50}, 700).to({y: 100}, 700)
.to({y: 150}, 700).to({y: 200}, 700)
.call(() => {
Tween.get(rightArm)
.to({angle: -90}, 1500, createjs.Ease.sineInOut)
.wait(1000)
.to({angle: 0}, 1500, createjs.Ease.sineInOut)
})
.to({y: 250}, 700).to({y: 290}, 700)
.call(() => {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 1500)
})
.to({alpha: 0}, 100)
.wait(3000);
//Add to screen
scene.addChild(hill); scene.addChild(person); scene.addChild(snow); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(9);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("snow", snow); addDomEl("leftArm", leftArm); addDomEl("rightArm", rightArm);
}
function scene9() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/9/9.json"].spritesheet.textures;
const s1 = loader.resources["./assets/1/1.json"].spritesheet.textures;
const s2 = loader.resources["./assets/2/2.json"].spritesheet.textures;
const hill = new PIXI.Sprite(s1['roundHill1.png']); const base = new PIXI.Sprite(s2["Body2.png"]);
const rightArm = new PIXI.Sprite(s["RightArm9.png"]); const leftArm = new PIXI.Sprite(s["LeftArm9.png"]);
let eyes = [new PIXI.Sprite(s1["Eyes1.png"]), new PIXI.Sprite(s2["SmilingEyes2.png"])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
let wind = [];
for (let i = 0; i < 31; i++) {
j = i.toString();
do { j = "0" + j } while (j.length < 4)
wind.push(new PIXI.Sprite(s[`wind${j}.png`]));
}
wind = new PIXI.AnimatedSprite(wind); wind.gotoAndStop(31);
//Init Text
const poem = slideText["9"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
person.addChild(base, leftArm, rightArm, eyes);
leftArm.position.set(-10,-15); rightArm.position.set(-10,10);
wind.y = -30;
person.scale.x = 0.5; person.scale.y = 0.5; person.x = 205; person.y = 200; person.angle = -20;
hill.scale.x = 1/1.24; hill.scale.y = 1/1.26; hill.y = app.height / 20;
//Create animation
Tween.get(person, {loop: true})
.to({y: 220}, 1500, createjs.Ease.sineInOut)
.to({y: 200}, 1500, createjs.Ease.sineInOut)
const windRepeat = () => {
let i = 0;
wind.angle = Math.random() * 10;
const windPlay = () => {
wind.gotoAndStop(i);
i++
if (i == 32) {
removeSpecific("windPlay");
}
}
addInterval("windPlay", 42, windPlay);
setTimeout(() => eyes.gotoAndStop(1), 750);
setTimeout(() => eyes.gotoAndStop(0), 1750);
};
windRepeat();
addInterval("windRepeat", 3000, windRepeat);
//Add to screen
scene.addChild(hill); scene.addChild(person); scene.addChild(wind); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(10);
app.stage.addChild(scene); addDomEl("person", person);
}
function scene10() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/10/10.json"].spritesheet.textures;
const ashes = new PIXI.Sprite(s["Ashes10.png"]);
let fire = new PIXI.Texture.from("./assets/10/fire.mp4");
fire.baseTexture.resource.source.loop = true; fire = new PIXI.Sprite(fire);
//Init Text
const poem = slideText["10"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
fire.scale.set(0.7, 0.7); ashes.scale.set(0.7, 0.7);
fire.anchor.set(-0.21, -0.24); ashes.anchor.set(-0.21, -0.24);
fire.alpha = 0;
//Create animation
Tween.get(fire, {loop: true})
.wait(1000)
.to({alpha: 1}, 3000, createjs.Ease.sineInOut)
.wait(3000)
.to({alpha: 0}, 3000, createjs.Ease.sineInOut)
//Add to screen
scene.addChild(ashes, fire); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(11);
app.stage.addChild(scene); addDomEl("fire", fire);
}
function scene11() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/11/11.json"].spritesheet.textures;
const s2 = loader.resources["./assets/2/2.json"].spritesheet.textures;
const s8 = loader.resources["./assets/8/8.json"].spritesheet.textures;
const s4 = loader.resources["./assets/4/4.json"].spritesheet.textures;
const trace = new PIXI.Sprite(s["Trace11.png"]); const hill = new PIXI.Sprite(s4["Flat4.png"]);
const blockLeft = new PIXI.Sprite(s["Block11.png"]); const blockRight = new PIXI.Sprite(s["Block11.png"]);
const base = new PIXI.Sprite(s2['Body2.png']); const eyes = new PIXI.Sprite(s2['SmilingEyes2.png']);
const leftArm = new PIXI.Sprite(s8['LeftArm8.png']); const rightArm = new PIXI.Sprite(s8['RightArm8.png']);
//Init Text
const poem = slideText["11"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
hill.position.set(-1300,250); hill.scale.y = 1.25;
person.addChild(base, eyes, leftArm, rightArm);
leftArm.pivot.set(1,0); leftArm.angle = 110; leftArm.position.set(195,330);
rightArm.angle = -10; rightArm.position.set(298,385);
person.scale.x = 0.5; person.scale.y = 0.5; person.x = app.width / 6.5; person.y = app.height / 5.8;
trace.position.set(-875, 280); trace.scale.y = -0.6;
blockLeft.position.set(-540, 0); blockRight.scale.x = -1; blockRight.position.set(1200, 0);
//Create animation
Tween.get(trace, {loop: true})
.call(() => {
Tween.removeTweens(person);
person.y = app.height / 5.8;
Tween.get(person, {loop: true})
.to({y: 40}, 2600, createjs.Ease.sineInOut)
.to({y: app.height / 5.8}, 2600, createjs.Ease.sineInOut)
})
.to({x: 0}, 29700)
Tween.get(hill, {loop: true})
.to({x: 0}, 29700)
//Add to screen
scene.addChild(trace, blockLeft, blockRight, hill, person); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => changeLink(12);
app.stage.addChild(scene); addDomEl("person", person); addDomEl("trace", trace); addDomEl("hill", hill);
}
function scene12() {
const scene = new PIXI.Container(); const person = new PIXI.Container();
//Init Sprites
const s = loader.resources["./assets/12/12.json"].spritesheet.textures;
const s1 = loader.resources["./assets/1/1.json"].spritesheet.textures;
const s2 = loader.resources["./assets/2/2.json"].spritesheet.textures;
const s6 = loader.resources["./assets/6/6.json"].spritesheet.textures;
const arms = new PIXI.Sprite(s["Arms12.png"]); const base = new PIXI.Sprite(s2["Body2.png"]);
let eyes = [new PIXI.Sprite(s1['Eyes1.png']), new PIXI.Sprite(s1['ClosedEyes1.png'])];
eyes = new PIXI.AnimatedSprite(eyes); eyes.gotoAndStop(0);
let fire = getFire().children[1]; const stick = new PIXI.Sprite(s6["Stick6.png"]);
//Init Text
const poem = slideText["12"];
for (el of poem.slice(0, poem.length - 1)) {
const p = document.createElement("p")
p.innerText = el;
if (!el) p.className = "break";
left.appendChild(p)
}
const button = document.createElement("button"); button.innerText = poem[poem.length - 1];
button.className = "poetic"; left.appendChild(button);
//Size
person.addChild(base, arms, eyes, stick, fire);
person.scale.set(0.64); person.position.set(212, 100);
fire.position.set(-137, 50); stick.scale.set(0.75, 0.25); stick.position.set(165, 380);
fire.scale.set(1/0.64);
//Create animation
Tween.get(person, {loop: true})
.to({y: 70}, 1500, createjs.Ease.sineInOut)
.to({y: 100}, 1500, createjs.Ease.sineInOut)
let i = 0;
fireInterval = () => {
fire.gotoAndStop(i)
i++
if (i == 40) i = 0;
};
addInterval("firePlay", 42, fireInterval);
const blinkingEyes = () => {
if (eyes.currentFrame == 0 && Math.random() > 0.6) {
eyes.gotoAndStop(1);
setTimeout(() => eyes.gotoAndStop(0), 100);
}
};
addInterval("blinkingEyes", 1000, blinkingEyes);
//Add to screen
scene.addChild(person); //addChild for PIXI.js el. appendChild for DOM el
button.onclick = () => window.location = "./credits.html"
app.stage.addChild(scene); addDomEl("person", person);
}
function getFire() {
const all = new PIXI.Container(); const s6 = loader.resources["./assets/6/6.json"].spritesheet.textures;
const stick = new PIXI.Sprite(s6["Stick6.png"]);
let fire = [];
for (let i = 0; i < 41; i++) {
j = i.toString();
do { j = "0" + j } while (j.length < 4)
fire.push(new PIXI.Sprite(s6[`lit${j}.png`]));
}
fire = new PIXI.AnimatedSprite(fire);
stick.scale.x = 1/3; stick.scale.y = 1/3; stick.anchor.set(-2.53,-1);
all.addChild(stick, fire);
return all;
}<file_sep>/blog/getting-over-fears-for-success.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-171137279-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-171137279-2');
</script>
<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="The work of a small guy hoping for a big change">
<meta name="keywords"
content="mhbthemes, resume, cv, portfolio, personal, developer, designer,personal resume, onepage, clean, modern">
<meta name="author" content="<NAME>">
<title>Getting Over Fears</title>
<!-- Favicon -->
<link rel="shortcut icon" href="../assets/img/favicon.png" type="image/png">
<!--== bootstrap ==-->
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<!--== font-awesome ==-->
<link href="../assets/css/font-awesome.min.css" rel="stylesheet">
<!--== animate css ==-->
<link href="../assets/css/animate.min.css" rel="stylesheet">
<!--== style css ==-->
<link href="../style.css" rel="stylesheet">
<!--== responsive css ==-->
<link href="../assets/css/responsive.css" rel="stylesheet">
<!--== theme color css ==-->
<link href="../assets/theme-color/color_3.css" rel="stylesheet">
<!--== jQuery ==-->
<script src="../assets/js/jquery-2.1.4.min.js"></script>
<!--[if lt IE 9]>
<script src="//oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!--======= PRELOADER =======-->
<div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
</div>
<!--===== HEADER AREA =====-->
<header class="navbar custom-navbar navbar-fixed-top">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-3 col-xs-12">
<div class="logo">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<a class="theme-color" href="../index.html">Madhav</a>
<!--== logo ==-->
</div>
</div>
<div class="col-md-9 col-sm-8 col-xs-12">
<nav class="main-menu">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<!--== manin menu ==-->
<li><a class="smoth-scroll" href="../index.html#home">Home</a></li>
<li><a class="smoth-scroll" href="../index.html#about">About</a></li>
<li><a class="smoth-scroll" href="../index.html#services">Experience</a></li>
<li><a class="smoth-scroll" href="../index.html#work">Portfolio</a></li>
<li><a class="smoth-scroll" href="../index.html#contact">Contact</a></li>
<li class="active"><a class="smoth-scroll" href="../blog.html">blog</a></li>
</ul>
</div>
</nav>
</div>
</div>
<!--/.row-->
</div>
<!--/.container-->
</header>
<!--===== END HEADER AREA ======-->
<!--===== BREADCROUMB AREA =====-->
<div class="breadcroumb-area" style="background-image: url(../assets/img/blog-bg.JPG);">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>To Succeed: Get Over Existing Fears, Then Create your Own</h1>
<div class="breadcroumb">
<a href="../index.html">Home</a>
>
<a href="../blog-page-2.html">Blog</a>
>
<span class="current active">Getting Over Fears</span>
</div>
</div>
</div>
</div>
</div>
<!--===== SINGLE POST AREA =====-->
<div class="single-blog-area section-padding">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="single-post-details wow fadeInUp" data-wow-delay="0.4s">
<div class="post-featured-content">
<img src="../assets/img/blog/getting-over-fears/workout.jpg" class="img-responsive" alt="">
</div>
<h2>To Succeed: Get Over Existing Fears, Then Create your Own</h2>
<div class="post-meta">
<span><i class="fa fa-calendar"></i> 06 July, 2020</span>
<span><i class="fa fa-folder-open"></i> Reflections</span>
<span><i class="fa fa-clock-o"></i> Reading time: 6 minutes</span>
</div>
<div class="entry-content">
<p>Most people have had the experience of scrolling through Youtube or Instagram feeds to
have their gaze fall upon another self-help guru telling them to overcome their fears to
succeed. If you're like me, you might have scoffed at this content and moved on to
something more entertaining. 🙄</p>
<p>Well, at least until I was lucky enough to meet mentors like researchers and
entrepreneurs that were actually successful… and they told me the same thing. They
actually challenged me to overcome my fears (this idea that I'd only ever seen in
clickbait social media posts) as if it were one of the BIGGEST areas of growth I could
ever have.</p>
<p>And so I set my disbelief down and decided to listen.</p>
<p>I made a list of my fears (ex. giving presentations, looking stupid, talking to
strangers, etc. 😨) and found ideas people had online for how to overcome them.
Surprisingly, plenty of people had actually tried this out before (even though it seemed
bizarre to me) and even made a list of the challenges they'd done to make themselves
uncomfortable and get over their fears (discomfort/fear/rejection challenges).</p>
<p>And so, I hopped on board the wacky-express and started documenting my own discomfort
challenges to face my fears. I did things including:</p>
<ul>
<li>Asking a nice (but very perplexed) elderly lady that I'd never met before for $100.
😕</li>
<li>Recreating a battle between Luke Skywalker and Darth Vader using (very mushy)
bananas as lightsabers. 🤔</li>
<li>Hosting a ballet workshop for kids having never done ballet before. 😖</li>
<li>Singing the theme song from Moana in public… (badly 😬)</li>
</ul>
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9"
style="margin-top: 2em; margin-bottom: 2em;">
<iframe class="embed-responsive-item"
src="https://www.youtube.com/embed/GBsuJHny3uo"></iframe>
<p><small>The most uncomfortable discomfort challenge was when I sang the Moana theme
song in the middle of downtown Toronto… 😨(<a id="accentColor"
href="https://www.youtube.com/watch?v=cPAbx5kgCJo">This</a> is what it's
actually supposed to sound like 😁)</small></p>
</div>
<p>The result was very surprising to me (the rational, practical,
give-me-the-proof-and-it-better-be-scientific guy). Each time, I'd be too nervous and
sweaty about the discomfort challenge to even think about what I was doing. I'd go on
autopilot and get it over with. And then, I got out of it and realised that all the fear
I had about these things wasn't really a big deal given the tiny moment it was and how
no one else cared. 😤</p>
<p>Facing my fears led me to understand that I was capable of more than I thought and that
the limitations I placed on what I could/couldn't do were more about me than how
difficult a challenge actually was. Each time I'd do a discomfort challenge, I'd come
out of it feeling proud of having dealt with another fear. (And later on, I also learned
that facing your fears in this way perfectly reflected our current <a id="accentColor"
href="https://medium.com/@OFFRCRD/phil-stutz-on-off-rcrd-transcript-a518cf91ab1e">psychological
theories</a>!)</p>
<p>So facing your fear isn't just a clickbait idea promoted by charlatans. It's actually a
foundational part of psychology that helped me grow, thanks to the advice of my mentors!
In general, if you have many fears and insecurities, this restricts the possibilities of
what you're able to do. This, in turn, restricts what you can be successful at.</p>
<p>It's like that one saying:</p>
<blockquote>"Show me a guy who's afraid to look bad, and I'll show you a guy you can beat
every time." - <a id="accentColor"
href="https://www.brainyquote.com/quotes/lou_brock_131377"><NAME></a>
</blockquote>
<p>So the first step to achieving more success is to get over your fears so that you can go
out and take on more challenges. 💪</p>
<img src="../assets/img/blog/getting-over-fears/workout.jpg" alt="" class="img-responsive"
style="padding-top: 2em; padding-bottom: 2em;">
<p>But also, facing your fears lets you not have messy emotions in your head that prevent
you from realising that your fears aren't really a big deal. That's when you can do some
interesting reflection to learn about why/how you had those fears in the first place
(and how you can use lessons from getting over one fear to get over another)!</p>
<p>One thing I realised after these discomfort challenges was that often times, I wasn't in
direct control of my fears. For example, if I was scared of giving a presentation in
school - it was because of a combination of getting bad marks, looking stupid/weak in
front of others, etc.</p>
<p>But most of these things were artificial (they were factors out of my control and other
people had made me scared of them). Like with the fear of getting bad marks, my teachers
and parents had repeatedly convinced me that bad marks were something to be afraid of so
that I would have an incentive to do my best to avoid them. 🏃</p>
<p>But after I did things like sing Moana in public, I wasn't as scared of presentations
anymore and realised that this fear was artificial to begin with. At first, this
resulted in me not being as nervous when presenting (good). But later on, it also gave
me more of a reason to think that presentations would turn out fine because they're not
something worry about and I could get away with not putting in as much effort as I had
before (bad).</p>
<p>This is the unintended consequence of getting over your fears. Fear can be a good
motivation do get things done (if you're afraid of the thing that goes bump in the
night, you're more likely to run away immediately rather than wait around to be eaten by
it 😕). If you're not careful, you might realise your fears are artificial and get over
them, but also lose the sense of urgency and motivation they bring.</p>
<p>This is where the second step to achieving success comes in. You have to find other
motivations to maintain a sense of urgency without the old fears (that you've now gotten
over). And what's the best way to replace these old, artificial fears?</p>
<p>To create new, artificial fears! (Except ones that you're in control of.)</p>
<p>That sounds crazy, but let me explain. Psychologically speaking, we care more about the
downside of a negative thing than the upside of a positive thing (Source). Because of
this, the most effective way to motivate ourselves once we've gotten over our old fears
is to create new fears (as opposed to giving ourselves rewards). 🤔</p>
<p>But the key here is that you have to be in control of the artificial fears you create (as
opposed to continuing to let others be in control of your fears). This idea is easier to
understand with an example:</p>
<ul>
<li>So most students I've met in my life are always stressed out about marks and school.
But it doesn't help them get better marks if they're more anxious all the time 🤷♂️
(except if they weren't motivated to do any work before, but now they're motivated
to do some work because they're scared).</li>
<li>I realised that these worries about getting a high mark on every test were just
artificial fears (I was scared of teachers, parents, and other students judging me
more than I was scared of the consequences of bad marks).</li>
<li>So then, I got over my fear of school. But this left me less motivation to urgently
work hard for every next test or assignment… like this one economics research paper
I had to write sometime within a month but didn't really want to start writing😕
</li>
<li>The solution? I emailed the head of the economics department at my school (a
stranger to me) and asked him to schedule a meeting in two days to give me feedback
on my paper… that was due in a month 😨</li>
<li>The result? I got that paper done in two days! 🎉Even though I'd created an
artificial fear for myself, I still ended up better off from the sense of urgency it
gave me to get done my paper.</li>
</ul>
<p>My mentor summarised all this for me with an amazing analogy/ It's like all our lives,
we're running away from a lion behind our back. But when we look back to confront the
lion, we realise that there really is no lion to be scared of. So what do we do? We put
an artificial lion behind our backs so we keep on running and get to more places. 🦁🚀
</p>
<p>So there you have it. The first step to success is to get over your fears so you can go
out and take on more challenges. And the second step is to create your own fears so that
you maintain a sense of urgency and stay motivated to do more things more quickly 😅</p>
<p>Sure, there are probably people preaching this advice on social media who might be
charlatans. But from the perspective of someone skeptical who didn't believe all the
people saying this, one of the best things I can tell you to do to succeed is exactly
the same as the charlatans: go face your fears!</p>
<p>- <NAME></p>
<p>Monday, 06-Jul-2020 20:05:11 GMT+0000</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="widget about-me">
<!-- widget single -->
<h3 class="widget-title">About me</h3>
<img src="../assets/img/author.jpg" alt="">
<h4 class="about-heading" style="margin-top: 1.5em;">I'm a student training to solve
globally <span>neglected issues</span>!</h4>
</div>
<div class="widget social">
<!-- widget single -->
<h3 class="widget-title">Get in Touch!</h3>
<ul class="social-links">
<!--=== social-links ===-->
<li><a href="https://www.linkedin.com/in/madhav-malhotra/" target="_blank"><i
class="fa fa-linkedin"></i></a></li>
<li><a href="https://madhav-malhotra003.medium.com/" target="_blank"><i
class="fa fa-medium"></i></a></li>
<li><a href="https://github.com/Madhav-Malhotra" target="_blank"><i
class="fa fa-github"></i></a></li>
<li><a href="https://www.youtube.com/channel/UCWopBNISjL7qCH2Qch58Skw" target="_blank"><i
class="fa fa-youtube-play"></i></a></li>
</ul>
</div>
</div>
</div>
<!--/.row-->
</div>
<!--/.container-->
</div>
<!--===== END BLOG POST AREA =====-->
<!--====== FOOTER AREA ======-->
<footer class="footer">
<div class="container">
<div class="row wow zoomIn" data-wow-delay="0.4s">
<div class="col-md-12 text-center">
<p>Find me here 👇 😋</p>
<ul class="social-links footer" style="margin-top: 0.25em;">
<!--=== social-links ===-->
<li><a href="https://www.linkedin.com/in/madhav-malhotra/" target="_blank"><i
class="fa fa-linkedin"></i></a></li>
<li><a href="https://madhav-malhotra003.medium.com/" target="_blank"><i
class="fa fa-medium"></i></a></li>
<li><a href="https://github.com/Madhav-Malhotra" target="_blank"><i
class="fa fa-github"></i></a></li>
<li><a href="https://www.youtube.com/channel/UCWopBNISjL7qCH2Qch58Skw" target="_blank"><i
class="fa fa-youtube-play"></i></a></li>
</ul>
<br>
<p id="copyright">©2020 <strong><NAME></strong></p>
</div>
</div>
</div>
</footer>
<!--====== END FOOTER AREA ======-->
<script src="/assets/js/insertParts/customCopyright.js"></script>
<script src="/assets/js/insertParts/customBlogAbout.js"></script>
<script src="/assets/js/insertParts/customSocialLinks.js"></script>
<script src="/assets/js/insertParts/customBlogNav.js"></script>
<!--== plugins js ==-->
<script src="../assets/js/plugins.js"></script>
<!--== typed js ==-->
<script src="../assets/js/typed.js"></script>
<!--== stellar js ==-->
<script src="../assets/js/jquery.stellar.min.js"></script>
<!--== counterup js ==-->
<script src="../assets/js/jquery.counterup.min.js"></script>
<!--== waypoints js ==-->
<script src="../assets/js/jquery.waypoints.min.js"></script>
<!--== wow js ==-->
<script src="../assets/js/wow.min.js"></script>
<!--== validator js ==-->
<script src="../assets/js/validator.min.js"></script>
<!--== mixitup js ==-->
<script src="../assets/js/jquery.mixitup.js"></script>
<!--== contact js ==-->
<script src="../assets/js/contact.js"></script>
<!--== main js ==-->
<script src="../assets/js/main.js"></script>
</body>
</html><file_sep>/blog/2021-Annual-Reflection/assets/js/scroll.js
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
document.body.scrollTop = document.documentElement.scrollTop = 0;<file_sep>/README.md
# madhavmalhotra.com
This is a personal website I've built over the years. I use it as a place to share blog posts, add my portfolio, share resources I've grown from, etc.
You can visit the website at [madhavmalhotra.com](madhavmalhotra.com)

<file_sep>/assets/js/insertParts/customBlogNav.js
const navInsert = `
<li><a class="smoth-scroll" href="/index.html">Back to Home</a></li>
`;
const nav = document.querySelector("ul.nav.navbar-nav");
nav.innerHTML = navInsert;<file_sep>/blog/2021-Annual-Reflection/assets/js/intervals.js
const intervalManifest = {};
function addInterval(intervalName, intervalDuration, intervalCode) {
if (!intervalManifest[intervalName]) {
const id = setInterval(intervalCode, intervalDuration);
intervalManifest[intervalName] = id;
}
};
function clearIntervals() {
for (k of Object.keys(intervalManifest)) {
const id = intervalManifest[k];
clearInterval(id);
delete intervalManifest[k];
}
}
function removeSpecific(name) {
const id = intervalManifest[name];
clearInterval(id);
delete intervalManifest[name];
}
const domManifest = {};
function addDomEl(domName, domEl) {
if (!domManifest[domName]) domManifest[domName] = domEl;
}
function clearDomTween() {
for (k of Object.keys(domManifest)) {
createjs.Tween.removeTweens(domManifest[k]);
delete domManifest[k];
}
}
|
8c003f171d8dc2a0990464f38be367172293e539
|
[
"JavaScript",
"HTML",
"Markdown"
] | 8
|
JavaScript
|
Madhav-Malhotra/Madhav-Malhotra.github.io
|
0b045c3ce4a2fbbe521a308a344d488358040d70
|
19515c556a78a37451a75ac58202d27d2d71dbc5
|
refs/heads/master
|
<repo_name>SVYSHE/javautils<file_sep>/src/main/java/svyshe/com/github/libcommons/libformats/csv/ideas.md
# Ideas for libCSV
> <NAME>, 25.09.2020
## `CSVConverter`
To convert from CSV to and vice versa
- `.xlsx` Excel-Sheet
- Word table
- Database table
- Markdown table
- LaTeX table
- `CommaSeparatedValue` and `CommaSeparatedValues`
## `CSVParser`
To:
- validate CSV files
- *TODO: Make the parser accept different RFCs as enum*
### ABNF Grammar
- `Textdata`: ASCII(32,33,35-43,45-126)
- `CR`: ASCII(13)
- `LF`: ASCII(10)
- `Comma`: ASCII(44)
- `DQuote`: ASCII(34)
- `NonEscaped`: n*`Textdata`
- `Escaped`: `DQuote` n*(`Textdata`, `Comma`, `CR`, `LF`, 2*`DQuote`) `DQuote`
- `Field`: `Escaped` `NonEscaped`
- `Name`: `Field`
- `Record`: `Field` n* (`Comma` `Field`)
- `Header`: `Name` n*(`Comma` `Name`)
- `File`: [`Header` `CRLF`] `Record` n*(`CLRF` `Record`) [`CRLF`]
## `CommaSeparatedValue` and `CommaSeperatedValues`
Make `CommaSeparatedValue` represent a single line and `CommaSeperatedValues` representing a whole CSV-file. <file_sep>/src/main/java/svyshe/com/github/libcommons/libformats/csv/CSVClient.java
package svyshe.com.github.libcommons.libformats.csv;
import org.apache.commons.lang3.StringUtils;
import svyshe.com.github.libcommons.libformats.csv.exceptions.CSVClientException;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
/**
* This class is supposed to offer a way to handle CSV files.
* In difference to other existing CSV libraries, CSVClient will offer you options to read a file line by line or even
* the whole file at once which will be less memory efficient in further processing steps.
*
* @author https://www.github.com/SVYSHE
* @version 1.0
*/
public class CSVClient implements AutoCloseable {
private File file;
private CSVDelimiter delimiter;
private final Scanner reader;
/**
* Getter for the CSV file.
*
* @return The CSV file.
*/
public File getFile() {
return file;
}
/**
* The setter for the CSV file.
*
* @param file The file to set as CSV file.
*/
public void setFile(File file) {
this.file = file;
}
/**
* The getter for the delimiter in read mode.
*
* @return The delimiter in read mode.
*/
public CSVDelimiter getDelimiter() {
return delimiter;
}
/**
* The setter for the delimiter in read mode.
*
* @param delimiter The delimiter to set for read mode.
*/
public void setDelimiter(CSVDelimiter delimiter) {
this.delimiter = delimiter;
}
/**
* Constructs a new CSV client and initializes it with the specified CSV file.
*
* @param file The CSV file that the client should operate on.
* @throws CSVClientException If the specified file can't be found.
*/
public CSVClient(File file) throws CSVClientException {
this.file = file;
this.delimiter = CSVDelimiter.COMMA;
try {
this.reader = new Scanner(this.file);
} catch (FileNotFoundException e) {
throw new CSVClientException("Error while initializing CSV client reader.", e.getCause());
}
}
/**
* Reads the whole CSV file and returns it as a list of string arrays. The delimiter has to be already specified.
*
* @return A list of string arrays representing the whole file.
*/
public List<String[]> readAll() {
List<String[]> content = new LinkedList<>();
while (hasNextLine()) {
String[] line = readLine();
if (line.length > 0) {
content.add(line);
}
}
return content;
}
/**
* Reads a single line from the CSV file starting from the top.
*
* @return A string array containing the fields.
*/
public String[] readLine() {
String line = reader.nextLine();
if (StringUtils.isEmpty(line)) {
return new String[]{};
}
if (line.contains("\"")) {
if (hasOddCountOfDoubleQuotes(line)) {
line += reader.nextLine();
}
line = escapeDoubleQuotes(line);
}
return StringUtils.splitByWholeSeparator(line, String.valueOf(this.delimiter.character));
}
/**
* Checks whether the file-cursors next position will be a line.
*
* @return True if there is a next line, false if not.
*/
public boolean hasNextLine() {
return reader.hasNextLine();
}
/**
* Appends a line to the set file.
*
* @param line The contents to write to the file.
* @param charset The charset used to write with.
* @param delimiter The delimiter to separate the single fields.
* @throws CSVClientException In case the writer isn't able to write to the specified file.
*/
public void appendLine(String[] line, Charset charset, CSVDelimiter delimiter) throws CSVClientException {
String outputString = String.join(delimiter.character, line) + "\r\n";
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(String.valueOf(file)), charset, StandardOpenOption.APPEND)) {
writer.write(outputString);
} catch (IOException e) {
throw new CSVClientException("Error while trying to write to file: '" + file.getAbsolutePath() + "'.", e.getCause());
}
}
/**
* Writes multiple lines at once to a file.
*
* @param lines The lines represented as a list of string arrays.
* @param charset The charset used to write with.
* @param delimiter The delimiter to separate the single fields.
* @throws CSVClientException In case the writer isn't able to write to the specified file.
*/
public void writeAll(List<String[]> lines, final Charset charset, final CSVDelimiter delimiter) throws CSVClientException {
for (String[] line : lines) {
appendLine(line, charset, delimiter);
}
}
/**
* Closes the reader.
*/
@Override
public void close() {
if (this.reader != null) {
this.reader.close();
}
}
/**
* Checks whether the line (represented as single string) contains an odd number of double quotes.
*
* @param line The line as string to check.
* @return true if it has an odd count of double quotes, false if not.
*/
private boolean hasOddCountOfDoubleQuotes(String line) {
return StringUtils.countMatches(line, "\"") % 2 != 0;
}
/**
* Escapes double quotes in the given line (represented as single string).
*
* @param line The line as string to escape the double quotes from.
* @return The escaped line.
*/
private String escapeDoubleQuotes(String line) {
line = line.replace("\"", "");
return line;
}
}
<file_sep>/README.md
# javautils
This repository shall create a solution for my daily java programming tasks.
## Overview
### DateTime
Can handle dates and times. Combines `java.util.Date` and `java.time.LocalDateTime` functionality and extracts only the needed methods.
## Future plans
- [ ] Currency Class
- [ ] Euro, USD, etc. with different notations (€,$, etc...)
- [ ] A port of the C++ `Badge<T>` concept to java, to prevent internal API's from being misused
- [ ] libCSV (RFC 4180 compliant)
- [ ] SQL Query builder for major SQL dialects based of of [danfickle/java-sql-query-builder](https://github.com/danfickle/java-sql-query-builder)
## Some possible but not yet planned features
- [ ] A [HOCON](https://en.wikipedia.org/wiki/HOCON) base configuration class
<file_sep>/src/main/java/svyshe/com/github/libcommons/libweb/Port.java
package svyshe.com.github.libcommons.libweb;
public enum Port {
NOT_ASSIGNED(0, "N/A", "Not assigned"),
TCP_MUX(1, "TCPMUX", "TCP Port Service Multiplexer"),
REMOTE_JOB_ENTRY(5, "Remote Job Entry", "Remote Job Entry"),
ECHO_PROTOCOL(7, "Echo Protocol", "Echo Protocol"),
DISCARD_PROTOCOL(9, "Discard Protocol / Wake-on-LAN", "Discard Protocol / Wake-on-LAN"),
SYSSTAT_SERVICE(11, "sysstat", "Active Users (sysstat service)"),
DAYTIME_PROTOCOL(13, "Daytime Protocol", "Daytime Protocol"),
NETSTAT_OLD(15, "netstat service", "Previously netstat service"),
QOTD(17, "QOTD", "Quote of the Day (QOTD)"),
MSP(18, "MSP", "Message Send Protocol"),
CHARGEN(19, "CHARGEN", "Character Generator Protocol (CHARGEN"),
FTP_DATA(20, "FTP", "File Transfer Protocol (FTP) data transfer"),
FTP_CONTROL(21, "FTP", "File Transfer Protocol (FTP) control command"),
SSH(22, "SSH/SCP/SFTP", "Secure Shell (SSH), secure logins, file transfer (scp, sftp) and port forwarding"),
TELNET(23, "Telnet", "Telnet protocol"),
PRIV_MAIL_LMTP(24, "Priv-mail/LMTP", "Priv-mail / Local Mail Transport Protocol (LMTP)"),
SMTP(25, "SMTP", "Simple Mail Transfer Protocol (SMTP)"),
HA(28, "Palo Alto Networks HA", "Palo Alto Networks Panorama High Availability (HA) sync encrypted port"),
RF(34, "RF", "Remote File (RF)"),
PRIVATE_PRINTER(35, "Private Printer Protocols", "Private Printer Protocols"),
TIME_PROTOCOL(37, "Time Protocol", "Time Protocol"),
RLP(39, "RLP", "Resource Location Protocol"),
GRAPHICS(41, "Graphics", "Graphics"),
NAME_SERVICE(42, "Host Name Server Protocol/WINS",
"ARPA Host Name Server Protocol / Windows Internet Name Service (WINS)"),
WHOIS(43, "WHOIS", "WHOIS-Protocol"),
NI_FTP(47, "NI FTP", "NI FTP"),
TACACS(49, "TACACS", "TACACS Login Host Protocol"),
RMCP(50, "RMCP", "Remote Mail Checking Protocol"),
IMP_OLD(51, "IMP", "Interface Message Processor (IMC)"),
XNS_TIME(52, "XNS Time Protocol", "XNS (Xerox Network Systems) Time Protocol"),
DNS(53, "DNS", "Domain Name System (DNS)"),
XNS_CLEARINGHOUSE(54, "XNS Clearinghouse", "XNS (Xerox Network Systems) Clearinghouse"),
ISI_GL(55, "ISI-GL", "ISI Graphics Language"),
RAP_XNS_AUTH(56, "RAP/XNS Authentication",
"Route Access Protocol (RAP) / XNS (Xerox Network Systems) Authentication"),
MTP(57, "MTP", "Mail Transfer Protocol (MTP"),
XNS_MAIL(58, "XNS Mail", "XNS (Xerox Network Systems) Mail"),
NIFTP(61, "NIFTP-Based Mail", "NIFTP-Based Mail protocol"),
BOOTP_SERVER(67, "BOOTP Server", "Bootstrap Protocol (BOOTP) Server"),
BOOTP_CLIENT(68, "BOOTP Client", "Bootstrap Protocol (BOOTP) Client"),
TFTP(69, "TFTP", "Trivial File Transfer Protocol (TFTP)"),
GOPHER(70, "Gopher", "Gopher-Protocol"),
GENIUS_NETJRS(71, "Genius / NETJRS", "Genius Protocol / Remote Job Netry (NETJRS)"),
NETJRS_1(72, "NETJRS", "Remote Job Entry (NETJRS)"),
NETJRS_2(73, "NETJRS", "Remote Job Entry (NETJRS)"),
NETJRS_3(74, "NETJRS", "Remote Job Entry (NETJRS)"),
FINGER(79, "Finger", "Finger protocol"),
HTTP(80, "HTTP", "Hypertext Transfer Protocol (HTTP)"),
TORPARK_ONION_ROUTING(81, "TorPark onion routing", "TorPark onion routing"),
TORPARK_ONION_CONTROL(82, "TorPark onion control", "TorPark onion control"),
MIT_ML_DEVICE(83, "MIT ML Device", "MIT ML Device, networking file system"),
KERBEROS(88, "Kerberos Auth", "Kerberos authentication system"),
DNSIX_POINTCAST(90, "dnsix / Pointcast", "DoD Network Security for Information Exchange (dnsix) / PointCast"),
SUPDUP(95, "SUPDUP", "SUPDUP terminal independent remote login"),
WIP_MESSAGE(99, "WIP Message", "WIP Message"),
NIC_HOST_NAME(101, "NIC host name", "NIC host name"),
ISO_TSAP(102, "ISO-TSAP", "ISO Transport Service Access Point (TSAP)"),
DICOM(104, "DICOM", "Digital Imaging and Communications in Medicine (DICOM)"),
CCSO(105, "CCSO Nameserver", "CCSO Nameserver Protocol"),
RTELNET(107, "RTelnet", "Remote User Telnet Service (RTelnet)"),
IBM(108, "IBM SNA", "IBM Systems Network Architecture (IBM SNA)"),
POP2(109, "POP2", "Post Office Protocol, version 2 (POP2)"),
POP3(110, "POP3", "Post Office Protocol, version 3 (POP3)"),
ONC_RPC(111, "ONC RPC", "Open Network Computing Remote Procedure Call (ONC RPC)"),
IDENT_AUTH(113, "ident / auth", "ident / ex auth"),
SFTP(115, "SFTP", "Simple File Transfer Protocol"),
UUCP(117, "UUCP Path service", "UUCP Mapping Project (path service)"),
SQL(118, "SQL", "SQL-Services"),
NNTP(119, "NNTP", "Network News Transfer Protocol (NNTP)"),
NTP(123, "NTP", "Network Time Protocol (NTP)"),
UNISYS(126, "Unisys", "Unisys Unitary Login (Unisys)"),
DCE_EPMAP(135, "DCE / Microsoft EPMAP", "DCE endpoint resolution / Microsoft End Point Mapper (EPMAP)"),
NETBIOS_NAME_SERVICE(137, "NetBIOS Naame Service", "NetBIOS Naame Service"),
NETBIOS_DATAGRAM_SERVICE(138, "NetBIOS Datagram Service", "NetBIOS Datagram Service"),
NETBIOS_SESSION_SERVICE(139, "NetBIOS Session Service", "NetBIOS Session Service"),
IMAP(143, "IMAP", "Internet Message Access Protocol (IMAP)"),
JARGON(148, "jargon", "Jargon-Server"),
BFTP(152, "BFTP", "Background File Transfer Program (BFTP)"),
SGMP(153, "SGMP", "Simple Gateway Monitoring Protocol (SGMP)"),
SQL_SERVICE(156, "SQL Service", "SQL Service"),
DMSP(158, "DMSP", "Distributed Mail System Protocol (DMSP)"),
SNMP(161, "SNMP", "Simple Network Management Procotol (SNMP)"),
SNMP_TRAP(162, "SNMPTRAP", "Simple Network Management Procotol Trap (SNMPTRAP)"),
POSTSCRIPT(170, "PostScript", "PostScript Print Server"),
XDMCP(177, "XDMCP", "X Display Manager Control Protocol (XDMCP)"),
BGP(179, "BGP", "Border Gateway Protocol (BGP)"),
IRC(194, "IRC", "Internet Relay Chat (IRC)"),
SMUX(199, "SMUX", "SNMP Unix Multiplexer (SMUX)"),
APPLETALK(201, "AppleTalk", "AppleTalk Routing Maintenance"),
QMTP(209, "QMTP", "Quick Mail Transfer Protocol"),
ANSI_Z_39_50(210, "ANSI Z39.50", "ANSI Z39.50"),
IPX(213, "IPX", "Internet Packet Exchange (IPX)"),
MPP(218, "MPP", "Message Posting Protocol (MPP)"),
IMAP_V3(220, "IMAP", "Internet Message Access Protocol (IMAP), version 3"),
TWO_DEV_2SP(256, "2DEV 2SP Port", "2DEV 2SP Port"),
ESRO(259, "ESRO", "Efficient Short Remote Operations (ESRO)"),
ARCISDMS(262, "Arcisdms", "Arcisdms"),
BGMP(264, "BGMP", "Border Gateway Multicast Procotol (BGMP)"),
HTTP_MGMT(280, "http-mgmt", "http-mgmt"),
THIN_LINC(300, "ThinLinc Web Access", "ThinLinc Web Access"),
NOVASTOR(308, "Novastor Online Backup", "Novastor Online Backup"),
APPLE_SHARE_ADMIN(311, "AppleShare IP Web administration", "AppleShare IP Web administration"),
PKIX(318, "PKIX TSP", "PKIX Time Stamp Protocol (TSP)"),
PTP_EVENT(319, "PTP event messages", "Precision Time Protocol (PTP) event messages"),
PTP_GENERAL(320, "PTP general messages", "Precision Time Protocol (PTP) general messages"),
IMMP(323, "IMMP", "Internet Message Mapping Protocol (IMMP)"),
IT_MESSAGE_MESSAGE_EVENT(325, "IT-Message Message Event", "IT-Message Message Event"),
IT_MESSAGE_STATUS_CONTROL(327, "IT-Message Status-Control Event", "IT-Message Status-Control Event"),
IT_MESSAGE_GIF_EVENT(330, "IT-Message Gif Event", "IT-Message Gif Event"),
MATIP_A(350, "MATIP (A)", "Mapping of Airline Traffic over Internet Protocol (MATIP) type A"),
MATIP_B(351, "MATIP (B)", "Mapping of Airline Traffic over Internet Protocol (MATIP) type B"),
CLOANTO_NET(356, "cloanto-net-1", "cloanto-net-1 (used by Cloanto Amiga Explorer and VMs"),
ODMR(366, "ODMR", "On-Demand Mail Relay (ODMR)"),
RPC2PORTMAP(369, "Rpc2portmap", "Rpc2portmap"),
CODAAUTH2_SECURECAST1(370, "codaauth2 / securecast1",
"codaauth2, Coda authentication server / securecast1, outgoing packets to NAI's SecureCast servers as of 2000"),
CLEARCASE_ALBD(371, "ClearCase albd", "ClearCase albd"),
AMIGA(376, "Amiga Envoy Network Inquiry Protocol", "Amiga Envoy Network Inquiry Protcol"),
HP_DATA_ALARM(383, "HP data alarm messenger", "HP data alarm messenger"),
A_REMOTE_NETWORK_SERVER(384, "A Remote Network Server System", "A Remote Network Server System"),
AURP(387, "AURP", "AppleTalk Update-base Routing Protocol (AURP)"),
UNIDATA_LDM(388, "Unidata LDM", "Unidata LDM near real-time data distribution protocol"),
LDAP(389, "LDAP", "Lightweight Directory Access Protocol (LDAP)"),
DECNET(399, "DECnet+", "Digital Equipment Corporation DECnet+ (Phase V) over TCP/IP (RFC1859)"),
UPS(401, "UPS", "Uninterruptable Power Supply (UPS)"),
ALTIRIS(402, "Altiris", "Altiris Deployment Client"),
DIRECT_CONNECT_HUB(411, "Direct Connect Hub", "Direct Connect Hub"),
DIRECT_CONNECT_C2C(412, "Direct Connect Client-to-Client", "Direct Connect Client-to-Client"),
SLP(427, "SLP", "Service Location Protocol (SLP)"),
NNTP_2(433, "NNTP", "Network News Protocol (NNTP)"),
MOBILE_IP(434, "Mobile IP Agent (RFC 5944)", "Mobile IP Agent (RFC 5944)"),
HTTPS(443, "HTTPS", "Hypertext Transfer Protocol Secure (HTTPS)"),
SNPP(444, "SNPP", "Simple Network Paging Protocol (SNPP)"),
ACTIVE_DIRECTORY_SMB(445, "MS Active Directory / MS SMB",
"Microsoft-DS (Directory Services) Active Directory / SMB"),
KERBERES_CHANGE_SET_PASSWORD(464, "Kerberos Change/Set password", "Kerberos Change/Set password"),
URD_SMTPS_IGMPV3LITE(465, "URD / SMTPS / IGMP v3lite",
"URL Rendezvous Diretory for SSM (URD) / Simple Mail Transfer Protocol Secure (SMTPS) / IGMP over UDP for SSM (IGMP v3lite)"),
TCPNETHASPSRV(475, "tcpnethaspsrv", "tcpnethaspsrv, Aladdin Knowledge Systems Hasp services"),
CENTRO1(476, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO2(477, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO3(478, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO4(479, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO5(480, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO6(481, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO7(482, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO8(483, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO9(484, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTR010(485, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO11(486, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO12(487, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO13(488, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO14(489, "Centro Software ERP ports", "Centro Software ERP ports"),
CENTRO15(490, "Centro Software ERP ports", "Centro Software ERP ports"),
GO(491, "GO-Global", "GO-Global remote access and application publishing software"),
RETROSPECT(497, "Retrospect", "Dantz Retrospect"),
ISAKMP_IKE(500, "ISAKMP / IKE",
"Internet Security Association and Key Management Protol (ISAKMP) / Internet Key Exchange (IKE)"),
STMF(501, "SMTF", "Simple Transportation Management Framework (SMTF)"),
MODBUS_ASA_APPL_PROTO(502, "Modbus / asa-appl-proto", "Modbus Protocol / asa-appl-proto Protocol"),
CITADEL(504, "Citadel", "Citadel multiservice protocol for dedicated clients"),
FCP(510, "FCP", "FirstClass Protocol (FCP)"),
REXEC_COMSAT_BIFF(512, "Rexec / comsat / biff", "Remote Process Execution (Rexec) / comsat / biff"),
WHO_RLOGIN(513, "Who / rlogin", "Who / rlogin"),
RSH_SYSLOG(514, "rsh / Syslog", "Remote Shell (rsh) / Syslog"),
LPD(515, "LPD", "Line Printer Daemon (LPD), print service");
long number;
String name;
String longName;
Port(long number, String name, String longName) {
this.number = number;
this.name = name;
this.longName = longName;
}
public static Port getPort(int number)
{
switch (number)
{
case 0:
return NOT_ASSIGNED;
case 1:
return TCP_MUX;
case 5:
return REMOTE_JOB_ENTRY;
case 7:
return ECHO_PROTOCOL;
case 9:
return DISCARD_PROTOCOL;
case 11:
return SYSSTAT_SERVICE;
case 13:
return DAYTIME_PROTOCOL;
case 15:
return NETSTAT_OLD;
case 17:
return QOTD;
case 18:
return MSP;
case 19:
return CHARGEN;
case 20:
return FTP_DATA;
case 21:
return FTP_CONTROL;
case 22:
return SSH;
case 23:
return TELNET;
case 24:
return PRIV_MAIL_LMTP;
case 25:
return SMTP;
case 28:
return HA;
case 34:
return RF;
case 35:
return PRIVATE_PRINTER;
case 37:
return TIME_PROTOCOL;
case 39:
return RLP;
case 41:
return GRAPHICS;
case 42:
return NAME_SERVICE;
case 43:
return WHOIS;
case 47:
return NI_FTP;
case 49:
return TACACS;
case 50:
return RMCP;
case 51:
return IMP_OLD;
case 52:
return XNS_TIME;
case 53:
return DNS;
case 54:
return XNS_CLEARINGHOUSE;
case 55:
return ISI_GL;
case 56:
return RAP_XNS_AUTH;
case 57:
return MTP;
case 58:
return XNS_MAIL;
case 61:
return NIFTP;
case 67:
return BOOTP_SERVER;
case 68:
return BOOTP_CLIENT;
case 69:
return TFTP;
case 70:
return GOPHER;
case 71:
return GENIUS_NETJRS;
case 72:
return NETJRS_1;
case 73:
return NETJRS_2;
case 74:
return NETJRS_3;
case 79:
return FINGER;
case 80:
return HTTP;
case 81:
return TORPARK_ONION_ROUTING;
case 82:
return TORPARK_ONION_CONTROL;
case 83:
return MIT_ML_DEVICE;
case 88:
return KERBEROS;
case 90:
return DNSIX_POINTCAST;
case 95:
return SUPDUP;
case 99:
return WIP_MESSAGE;
case 101:
return NIC_HOST_NAME;
case 102:
return ISO_TSAP;
case 104:
return DICOM;
case 105:
return CCSO;
case 107:
return RTELNET;
case 108:
return IBM;
case 109:
return POP2;
case 110:
return POP3;
case 111:
return ONC_RPC;
case 113:
return IDENT_AUTH;
case 115:
return SFTP;
case 117:
return UUCP;
case 118:
return SQL;
case 119:
return NNTP;
case 123:
return NTP;
case 126:
return UNISYS;
case 135:
return DCE_EPMAP;
case 137:
return NETBIOS_NAME_SERVICE;
case 138:
return NETBIOS_DATAGRAM_SERVICE;
case 139:
return NETBIOS_SESSION_SERVICE;
case 143:
return IMAP;
case 148:
return JARGON;
case 152:
return BFTP;
case 153:
return SGMP;
case 156:
return SQL_SERVICE;
case 158:
return DMSP;
case 161:
return SNMP;
case 162:
return SNMP_TRAP;
case 170:
return POSTSCRIPT;
case 177:
return XDMCP;
case 179:
return BGP;
case 194:
return IRC;
case 199:
return SMUX;
case 201:
return APPLETALK;
case 209:
return QMTP;
case 210:
return ANSI_Z_39_50;
case 213:
return IPX;
case 218:
return MPP;
case 220:
return IMAP_V3;
case 256:
return TWO_DEV_2SP;
case 259:
return ESRO;
case 262:
return ARCISDMS;
case 264:
return BGMP;
case 280:
return HTTP_MGMT;
case 300:
return THIN_LINC;
case 308:
return NOVASTOR;
case 311:
return APPLE_SHARE_ADMIN;
case 318:
return PKIX;
case 319:
return PTP_EVENT;
case 320:
return PTP_GENERAL;
case 323:
return IMMP;
case 325:
return IT_MESSAGE_MESSAGE_EVENT;
case 327:
return IT_MESSAGE_STATUS_CONTROL;
case 330:
return IT_MESSAGE_GIF_EVENT;
case 350:
return MATIP_A;
case 351:
return MATIP_B;
case 356:
return CLOANTO_NET;
case 366:
return ODMR;
case 369:
return RPC2PORTMAP;
case 370:
return CODAAUTH2_SECURECAST1;
case 371:
return CLEARCASE_ALBD;
case 376:
return AMIGA;
case 383:
return HP_DATA_ALARM;
case 384:
return A_REMOTE_NETWORK_SERVER;
case 387:
return AURP;
case 388:
return UNIDATA_LDM;
case 389:
return LDAP;
case 399:
return DECNET;
case 401:
return UPS;
case 402:
return ALTIRIS;
case 411:
return DIRECT_CONNECT_HUB;
case 412:
return DIRECT_CONNECT_C2C;
case 427:
return SLP;
case 433:
return NNTP_2;
case 434:
return MOBILE_IP;
case 443:
return HTTPS;
case 444:
return SNPP;
case 445:
return ACTIVE_DIRECTORY_SMB;
case 464:
return URD_SMTPS_IGMPV3LITE;
case 475:
return TCPNETHASPSRV;
case 476:
return CENTRO1;
case 477:
return CENTRO2;
case 478:
return CENTRO3;
case 479:
return CENTRO4;
case 480:
return CENTRO5;
case 481:
return CENTRO6;
case 482:
return CENTRO7;
case 483:
return CENTRO8;
case 484:
return CENTRO9;
case 485:
return CENTR010;
case 486:
return CENTRO11;
case 487:
return CENTRO12;
case 488:
return CENTRO13;
case 489:
return CENTRO14;
case 490:
return CENTRO15;
case 491:
return GO;
case 497:
return RETROSPECT;
case 500:
return ISAKMP_IKE;
case 501:
return STMF;
case 502:
return MODBUS_ASA_APPL_PROTO;
case 504:
return CITADEL;
case 510:
return FCP;
case 512:
return REXEC_COMSAT_BIFF;
case 513:
return WHO_RLOGIN;
case 514:
return RSH_SYSLOG;
case 515:
return LPD;
default:
return null;
}
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLongName() {
return longName;
}
public void setLongName(String longName) {
this.longName = longName;
}
}
<file_sep>/src/test/java/svyshe/com/github/libcommons/libweb/test/PortTest.java
package svyshe.com.github.libcommons.libweb.test;
import svyshe.com.github.libcommons.libweb.Port;
public class PortTest {
String portName = Port.DAYTIME_PROTOCOL.getName();
}
<file_sep>/src/test/java/svyshe/com/github/libcommons/libformats/test/CSVClientTest.java
package svyshe.com.github.libcommons.libformats.test;
import org.junit.*;
import svyshe.com.github.libcommons.libformats.csv.CSVClient;
import svyshe.com.github.libcommons.libformats.csv.CSVDelimiter;
import svyshe.com.github.libcommons.libformats.csv.exceptions.CSVClientException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
// RFC4180
public class CSVClientTest {
private CSVClient client;
@Before
public void setup() throws CSVClientException {
this.client = new CSVClient(new File("src/test/resources/CSVTestFile.txt"));
}
@Test
public void readAll() {
List<String[]> expected = Arrays.asList(new String[]{"HEADER1", "HEADER2", "HEADER3"}, new String[]{"content1", "content2", "content3"});
List<String[]> actual = client.readAll();
Assert.assertThat(actual.toArray(), is(expected.toArray()));
}
@Test
public void writeAll() throws IOException {
final String absoluteFilePath = "src/test/resources/writeAllTest.txt";
createTestFile(absoluteFilePath);
String[] testLine1 = new String[]{"HEADER1 ","HEADER2","HEADER3"};
String[] testLine2 = new String[]{"CONTENT1", "CONTENT2 ", "CONTENT3"};
List<String[]> expected = new ArrayList<>();
expected.add(testLine1);
expected.add(testLine2);
try (CSVClient client = new CSVClient(new File(absoluteFilePath))) {
client.writeAll(expected, Charset.defaultCharset(), CSVDelimiter.COMMA);
}
List<String[]> actual;
try (CSVClient reader = new CSVClient(new File(absoluteFilePath))) {
actual = reader.readAll();
}
Assert.assertThat(actual.toArray(), is(expected.toArray()));
}
private static void createTestFile(String s) throws IOException {
if (!Files.exists(Paths.get(s))) {
File file = new File(s);
file.createNewFile();
}
}
@After
public void teardown() throws IOException {
this.client.close();
Files.deleteIfExists(Paths.get("src/test/resources/writeAllTest.txt"));
}
}
<file_sep>/src/main/java/svyshe/com/github/libcommons/libformats/csv/CSVDelimiter.java
package svyshe.com.github.libcommons.libformats.csv;
public enum CSVDelimiter {
COMMA(","),
SEMICOLON(";"),
TAB("\t");
CharSequence character;
CSVDelimiter(CharSequence character) {
this.character = character;
}
}
|
813e0a4cb049534f3464872c0714d6c5599f3f6e
|
[
"Markdown",
"Java"
] | 7
|
Markdown
|
SVYSHE/javautils
|
0696cd9d07fedb774e473ce52b261acba8cf3922
|
f93852fb7929c6e67c1ece4660281818879205a3
|
refs/heads/master
|
<repo_name>DolGit/react-redux-init-app<file_sep>/src/reducer-management.js
var reducers = {}
export {reducers}
var initialState = {}
export {initialState}
export function attachState(state) {
for (var name in state) {
initialState[name] = state[name]
}
}
export function attachReducers(defaultReducers) {
for (var name in defaultReducers) {
reducers[name] = defaultReducers[name]
}
}
export function combineXhrReducers(subReducers) {
for (let subReducerObject of subReducers) {
for (let subReducerName in subReducerObject) {
let subReducer = subReducerObject[subReducerName]
for (let name in subReducer) {
reducers[`${subReducerName}/${name}`] = subReducer[name]
}
}
}
}
export function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}<file_sep>/lib/index.js
"use strict";
exports.__esModule = true;
exports.store = exports.agent = exports.PreMounter = exports.history = exports.BaseRouter = exports.combineXhrReducers = exports.attachState = exports.attachReducers = exports.reducers = exports.initialState = undefined;
exports.InitApp = InitApp;
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _reactDom = require("react-dom");
var _reactDom2 = _interopRequireDefault(_reactDom);
var _redux = require("redux");
var _reactRedux = require("react-redux");
var _connectedReactRouter = require("connected-react-router");
var _middleware = require("./middleware");
var _agent = require("./agent.js");
var _agent2 = _interopRequireDefault(_agent);
var _styles = require("@material-ui/core/styles");
var _BaseRouter = require("./components/base-router/BaseRouter.js");
var _BaseRouter2 = _interopRequireDefault(_BaseRouter);
var _DefaultComponents = require("./components/default-components/DefaultComponents.js");
var _DefaultComponents2 = _interopRequireDefault(_DefaultComponents);
var _preMounter = require("./pre-mounter.js");
var _preMounter2 = _interopRequireDefault(_preMounter);
var _reducerManagement = require("./reducer-management.js");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function InitApp(opts) {
var reducer = (0, _reducerManagement.createReducer)(_reducerManagement.initialState, _reducerManagement.reducers);
exports.store = store = (0, _redux.createStore)((0, _connectedReactRouter.connectRouter)(_middleware.history)(reducer), _reducerManagement.initialState, (0, _middleware.middleware)(opts.logger));
return function (App, props) {
var app = _react2.default.createElement(App, props);
if (opts.theme) app = _react2.default.createElement(_styles.MuiThemeProvider, { theme: opts.theme }, app);
if (opts.defaultComponents) {
app = _react2.default.createElement(_DefaultComponents2.default, { components: opts.defaultComponents }, app);
}
app = _react2.default.createElement(_connectedReactRouter.ConnectedRouter, { history: _middleware.history }, app);
app = _react2.default.createElement(_reactRedux.Provider, { store: store }, app);
return function (handle) {
_preMounter2.default.mount(_reducerManagement.initialState, store);
var el = document.getElementById(handle);
_reactDom2.default.render(app, el);
};
};
}
var store = {};
exports.initialState = _reducerManagement.initialState;
exports.reducers = _reducerManagement.reducers;
exports.attachReducers = _reducerManagement.attachReducers;
exports.attachState = _reducerManagement.attachState;
exports.combineXhrReducers = _reducerManagement.combineXhrReducers;
exports.BaseRouter = _BaseRouter2.default;
exports.history = _middleware.history;
exports.PreMounter = _preMounter2.default;
exports.agent = _agent2.default;
exports.store = store;<file_sep>/lib/components/base-router/BaseRouter.js
'use strict';
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactRedux = require('react-redux');
var _connectedReactRouter = require('connected-react-router');
var _reducerManagement = require('../../reducer-management.js');
var _redirectCleanup = require('../../reducers/redirect-cleanup');
var _redirectCleanup2 = _interopRequireDefault(_redirectCleanup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
(0, _reducerManagement.attachReducers)({ 'REDIRECT_CLEANUP': _redirectCleanup2.default });
var mapStateToProps = function mapStateToProps(state) {
return {
redirect: state.redirect
};
};
var mapDispatchToProps = function mapDispatchToProps(dispatch) {
return {
redirectTo: function redirectTo(url) {
dispatch((0, _connectedReactRouter.push)(url));
dispatch({ type: 'REDIRECT_CLEANUP' });
}
};
};
var BaseRouter = function (_React$Component) {
_inherits(BaseRouter, _React$Component);
function BaseRouter() {
_classCallCheck(this, BaseRouter);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
BaseRouter.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps.redirect) {
this.props.redirectTo(nextProps.redirect);
}
};
BaseRouter.prototype.render = function render() {
return _react2.default.createElement(
'div',
{ className: this.props.className },
this.props.children
);
};
return BaseRouter;
}(_react2.default.Component);
BaseRouter.propTypes = process.env.NODE_ENV !== "production" ? {
redirect: _propTypes2.default.string
} : {};
exports.default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)(BaseRouter);
module.exports = exports['default'];<file_sep>/src/middleware/promise.js
const isPromise = (action) => action.payload && typeof action.payload.then === 'function'
const isInvokable = (action) => isPromise(action) && !action.invoked
export default store => next => action => {
if (!isInvokable(action)) return next(action)
action.invoked = true
store.dispatch({ ...action, type: `${action.type}/pre` });
action.payload.then(
res => {
action.payload = JSON.parse(res.response);
store.dispatch({ ...action, type: `${action.type}/success` });
},
error => {
action.error = true;
action.payload = JSON.parse(error.response.body.response);
if (!action.skipTracking) {
store.dispatch({ ...action, type: `${action.type}/fail` });
}
},
).catch(error => {
action.error = true;
action.payload = JSON.parse(error.response.body.response);
if (!action.skipTracking) {
store.dispatch({ ...action, type: `${action.type}/error` });
}
});
};
<file_sep>/README.md
# React Redux Init App
Minimal setup for an app that uses React and Redux.
Including:
- Routing component with redirect reducers
- State and Reducer management
- Material UI Theme optional integration
- Ajax handling through reducers
I'll add more and an usage example soon.
Based on the [react-redux-realworld-example](https://github.com/gothinkster/react-redux-realworld-example-app) by [Thinkster](https://github.com/gothinkster)<file_sep>/lib/reducer-management.js
"use strict";
exports.__esModule = true;
exports.attachState = attachState;
exports.attachReducers = attachReducers;
exports.combineXhrReducers = combineXhrReducers;
exports.createReducer = createReducer;
var reducers = {};
exports.reducers = reducers;
var initialState = {};
exports.initialState = initialState;
function attachState(state) {
for (var name in state) {
initialState[name] = state[name];
}
}
function attachReducers(defaultReducers) {
for (var name in defaultReducers) {
reducers[name] = defaultReducers[name];
}
}
function combineXhrReducers(subReducers) {
for (var _iterator = subReducers, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var subReducerObject = _ref;
for (var subReducerName in subReducerObject) {
var subReducer = subReducerObject[subReducerName];
for (var name in subReducer) {
reducers[subReducerName + "/" + name] = subReducer[name];
}
}
}
}
function createReducer(initialState, handlers) {
return function reducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var action = arguments[1];
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action);
} else {
return state;
}
};
}<file_sep>/src/reducers/redirect-cleanup.js
export default (state, action) => {
return { ...state, redirect: null };
}<file_sep>/es/agent.js
import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';
var superagent = superagentPromise(_superagent, global.Promise);
var encode = encodeURIComponent;
var responseBody = function responseBody(res) {
return res.body;
};
var token = null;
var tokenPlugin = function tokenPlugin(req) {
if (token) {
req.set('authorization', 'Token ' + token);
}
};
var csrfToken = document.head.querySelector('meta[name=csrf-token]').content;
var setDefaults = function setDefaults(req) {
return req.set('X-CSRF-Token', csrfToken).use(tokenPlugin).then(responseBody);
};
var requests = {
del: function del(url) {
return setDefaults(superagent.del(url));
},
get: function get(url, body) {
return setDefaults(superagent.get(url).query(body));
},
put: function put(url, body) {
return setDefaults(superagent.put(url, body));
},
post: function post(url, body) {
return setDefaults(superagent.post(url, body));
},
fileUpload: function fileUpload(url, body, fileParam, file, progressDispatch) {
return setDefaults(superagent.post(url).field("body", JSON.stringify(body)).attach(fileParam, file).on('progress', function (event) {
progressDispatch(event.percent);
}));
}
};
export default {
encode: encode,
requests: requests,
setToken: function setToken(_token) {
token = _token;
}
};<file_sep>/es/index.js
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { ConnectedRouter, connectRouter } from 'connected-react-router';
import { middleware, history } from './middleware';
import agent from './agent.js';
import { MuiThemeProvider } from '@material-ui/core/styles';
import BaseRouter from './components/base-router/BaseRouter.js';
import DefaultComponents from './components/default-components/DefaultComponents.js';
import PreMounter from './pre-mounter.js';
import { initialState, reducers, attachReducers, combineXhrReducers, attachState, createReducer } from './reducer-management.js';
export function InitApp(opts) {
var reducer = createReducer(initialState, reducers);
store = createStore(connectRouter(history)(reducer), initialState, middleware(opts.logger));
return function (App, props) {
var app = React.createElement(App, props);
if (opts.theme) app = React.createElement(MuiThemeProvider, { theme: opts.theme }, app);
if (opts.defaultComponents) {
app = React.createElement(DefaultComponents, { components: opts.defaultComponents }, app);
}
app = React.createElement(ConnectedRouter, { history: history }, app);
app = React.createElement(Provider, { store: store }, app);
return function (handle) {
PreMounter.mount(initialState, store);
var el = document.getElementById(handle);
ReactDOM.render(app, el);
};
};
}
var store = {};
export { initialState, reducers, attachReducers, attachState, combineXhrReducers, BaseRouter, history, PreMounter, agent, store };<file_sep>/lib/middleware/index.js
'use strict';
exports.__esModule = true;
exports.history = undefined;
exports.middleware = middleware;
var _redux = require('redux');
var _connectedReactRouter = require('connected-react-router');
var _createBrowserHistory = require('history/createBrowserHistory');
var _createBrowserHistory2 = _interopRequireDefault(_createBrowserHistory);
var _promise = require('./promise');
var _promise2 = _interopRequireDefault(_promise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var history = exports.history = (0, _createBrowserHistory2.default)();
var myRouterMiddleware = (0, _connectedReactRouter.routerMiddleware)(history);
function middleware(logger) {
if (logger) {
return (0, _redux.applyMiddleware)(myRouterMiddleware, _promise2.default, logger);
}
return (0, _redux.applyMiddleware)(myRouterMiddleware, _promise2.default);
};<file_sep>/es/reducer-management.js
var reducers = {};
export { reducers };
var initialState = {};
export { initialState };
export function attachState(state) {
for (var name in state) {
initialState[name] = state[name];
}
}
export function attachReducers(defaultReducers) {
for (var name in defaultReducers) {
reducers[name] = defaultReducers[name];
}
}
export function combineXhrReducers(subReducers) {
for (var _iterator = subReducers, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var subReducerObject = _ref;
for (var subReducerName in subReducerObject) {
var subReducer = subReducerObject[subReducerName];
for (var name in subReducer) {
reducers[subReducerName + "/" + name] = subReducer[name];
}
}
}
}
export function createReducer(initialState, handlers) {
return function reducer() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var action = arguments[1];
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action);
} else {
return state;
}
};
}<file_sep>/es/middleware/index.js
import { applyMiddleware } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createHistory from 'history/createBrowserHistory';
export var history = createHistory();
var myRouterMiddleware = routerMiddleware(history);
import promiseMiddleware from './promise';
export function middleware(logger) {
if (logger) {
return applyMiddleware(myRouterMiddleware, promiseMiddleware, logger);
}
return applyMiddleware(myRouterMiddleware, promiseMiddleware);
};<file_sep>/src/components/default-components/DefaultComponents.js
import React from 'react';
class DefaultComponents extends React.Component {
render() {
const Components = this.props.components
return(
<div>
{this.props.children}
<Components />
</div>
)
}
}
export default DefaultComponents<file_sep>/src/index.js
import React from "react"
import ReactDOM from "react-dom"
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { ConnectedRouter, connectRouter } from 'connected-react-router'
import { middleware, history } from './middleware'
import agent from './agent.js'
import { MuiThemeProvider } from '@material-ui/core/styles'
import BaseRouter from './components/base-router/BaseRouter.js'
import DefaultComponents from './components/default-components/DefaultComponents.js'
import PreMounter from './pre-mounter.js'
import { initialState, reducers, attachReducers, combineXhrReducers, attachState, createReducer } from './reducer-management.js'
export function InitApp(opts) {
const reducer = createReducer(initialState, reducers)
store = createStore(connectRouter(history)(reducer), initialState, middleware(opts.logger))
return function(App, props) {
let app = React.createElement(App, props)
if (opts.theme) app = React.createElement(MuiThemeProvider, {theme: opts.theme}, app)
if (opts.defaultComponents) {
app = React.createElement(DefaultComponents, {components: opts.defaultComponents}, app)
}
app = React.createElement(ConnectedRouter, {history}, app)
app = React.createElement(Provider, {store}, app)
return function(handle) {
PreMounter.mount(initialState, store)
const el = document.getElementById(handle)
ReactDOM.render(app, el)
}
}
}
var store = {}
export {
initialState,
reducers,
attachReducers,
attachState,
combineXhrReducers,
BaseRouter,
history,
PreMounter,
agent,
store
}<file_sep>/src/components/base-router/BaseRouter.js
import React from 'react'
import PropTypes from 'prop-types';
import {connect} from "react-redux";
import { push } from 'connected-react-router'
import { attachReducers } from '../../reducer-management.js'
import redirectCleanup from '../../reducers/redirect-cleanup'
attachReducers({'REDIRECT_CLEANUP': redirectCleanup})
const mapStateToProps = state => {
return {
redirect: state.redirect
}
};
const mapDispatchToProps = dispatch => ({
redirectTo: (url) => {
dispatch(push(url))
dispatch({ type: 'REDIRECT_CLEANUP' })
},
});
class BaseRouter extends React.Component {
componentWillReceiveProps(nextProps) {
if (nextProps.redirect) {
this.props.redirectTo(nextProps.redirect)
}
}
render() {
return (
<div className={this.props.className}>
{this.props.children}
</div>
)
}
}
BaseRouter.propTypes = {
redirect: PropTypes.string,
};
export default connect(mapStateToProps, mapDispatchToProps)(BaseRouter);<file_sep>/src/middleware/readme.md
#### Regarding promise middleware
There's 3 dispatches that happen on every request given the appropriate property:
1. pre is before the request is made, mainly for loading things
2. success is for after the request is made and is successful
3. fail is for after the request if unsuccessful
Each of these actions are namespaced to the original action. They are set up using a function called combineXhrReducers.
|
cf5bc052937b402384e971fa0049e36915096fd5
|
[
"JavaScript",
"Markdown"
] | 16
|
JavaScript
|
DolGit/react-redux-init-app
|
9ecbee16bb0a770937ef918a23f7e9fc6437d308
|
abfef6e78fc41a86ffa7baae0d339d758b9ecc89
|
refs/heads/master
|
<repo_name>Lukas-Ertl/Color-Community<file_sep>/src/app/color-grid/color-grid.component.ts
import { Component, OnInit } from '@angular/core';
import { ColorComponent } from '../color/color.component';
@Component({
selector: 'app-color-grid',
templateUrl: './color-grid.component.html',
styleUrls: ['./color-grid.component.css']
})
export class ColorGridComponent implements OnInit {
colors = [
{
name: "Black",
hexcode: "#000000"
},
{
name: "Yellow",
hexcode: "#ffff00"
},
{
name: "Cyan",
hexcode: "#00ffff"
},
{
name: "Green",
hexcode: "#32cd32"
},
{
name: "Red",
hexcode: "#ff0000"
},
{
name: "Blue",
hexcode: "#4169e1"
},
{
name: "Purple",
hexcode: "#9400d3"
},
{
name: "Pink",
hexcode: "#ffc0cb"
},
{
name: "Orange",
hexcode: "#ff8c00"
},
{
name: "Gray",
hexcode: "#708090"
},
{
name: "White",
hexcode: "#ffffff"
},
{
name: "Brown",
hexcode: "#8b4513"
},
];
constructor() { }
ngOnInit(): void {
}
OnAddColor():void{
console.log(this.colors);
}
}
<file_sep>/src/app/_interface/color.ts
export interface Color {
name: string;
hexcode:string;
}
|
bedcf5ba7fc242321a1b67e9f39bc2933c4db0a5
|
[
"TypeScript"
] | 2
|
TypeScript
|
Lukas-Ertl/Color-Community
|
ab3867da49719b4529c5a9abe33fd5730504e8f1
|
14aaa480ef30c2d340b2cc4c416ca3375274f9e1
|
refs/heads/master
|
<file_sep>var gulp = require('gulp');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var mainFile = './assets/src/scss/main.scss';
var scssFiles = './assets/src/scss/partials/*.scss';
var cssDest = './assets/dist/css';
gulp.task('style', function() {
return gulp.src(mainFile)
.pipe(sass().on('error', sass.logError))
.pipe(rename('app.css'))
.pipe(gulp.dest(cssDest));
});
gulp.task('watch', function() {
gulp.watch(scssFiles, ['style']);
});
gulp.task('default', ['style', 'watch']);
|
0fd478ca23662e51dd50c8081162225dd74dbf1f
|
[
"JavaScript"
] | 1
|
JavaScript
|
victortineo/docket-teste
|
a94e810fa740838ea13e7c4b1fd60fe1b0871667
|
6cae025f54df462383bea9d1a3c24bcd9aef708d
|
refs/heads/main
|
<repo_name>lorenatorog11/reproductor<file_sep>/src/App.js
import ReactPlayer from 'react-player';
import subtitles from './subtitles/subtitles.vtt';
function App() {
return (
<div className='video'>
<ReactPlayer
width='100%'
height='100%'
playing
controls
url='https://d2ni8vd6etkcfg.cloudfront.net/assets/2ea43277-ec46-4897-a551-066095ffd7d9/HLS/142_THE_TERMINAL_.m3u8'
config={{ file: {
tracks: [
{kind: 'subtitles', src: subtitles, srcLang: 'es', default:true, label:'Español'},
]
}}}
/>
</div>
);
}
export default App;
|
b2adcd4de14db3ce7980942437745b707a68d09e
|
[
"JavaScript"
] | 1
|
JavaScript
|
lorenatorog11/reproductor
|
cfc12964f507e0a556a8f14cbefde915f2bc64c6
|
baf1fa0c44792c265ed37336f3cac2dd715b0e57
|
refs/heads/master
|
<repo_name>lucas-clemente/ember-json-api<file_sep>/README.md
# ember-json-api
This is a [JSON API](http://jsonapi.org) adapter for [Ember Data](http://github.com/emberjs/data) 1.0 beta 3, that extends the built-in REST adapter. Please note that Ember Data and JSON API are both works in progress, use with caution.
### Download
- [json_api_adapter.js](http://raw.github.com/daliwali/ember-json-api/master/dist/json_api_adapter.js) (5.0 kb)
- [json_api_adapter.min.js](http://raw.github.com/daliwali/ember-json-api/master/dist/json_api_adapter.min.js) (2.3 kb)
### Usage
```javascript
App.ApplicationAdapter = DS.JsonApiAdapter;
```
### Build It Yourself
You will need `grunt-cli` installed on your system: `npm install -g grunt-cli`. Then run:
```
$ npm install && grunt
```
The output files go in the `dist` folder.
### Issues
- This adapter has preliminary support for URL-style JSON API. It currently only serializes one route per type, so if you have multiple ways to get a resource, it will not work as expected.
<file_sep>/Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/*! \n * <%= pkg.name %>\n * Built on ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? " * " + pkg.homepage + "\\n" : "" %>' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
' */\n'
},
concat: {
options: {
banner: '<%= meta.banner %>',
process: function(src, filepath) {
// wrap files in an anonymous function
return '(function() {\n"use strict";\n' + src + '\n}).call(this);\n';
}
},
dist: {
src: [
'src/json_api_serializer.js',
'src/json_api_adapter.js'
],
dest: 'dist/json_api_adapter.js'
}
},
uglify: {
dist: {
options: {
banner: '<%= meta.banner %>'
},
files: {
'dist/json_api_adapter.min.js': ['dist/json_api_adapter.js']
}
}
},
watch: {
scripts: {
files: ['src/**/*.js', 'lib/**/*.js'],
tasks: ['concat', 'uglify']
}
}
});
[
'grunt-contrib-concat',
'grunt-contrib-uglify',
'grunt-contrib-watch'
]
.forEach(function(task) {
grunt.loadNpmTasks(task);
});
grunt.registerTask('default', [
'concat',
'uglify'
]);
};
|
2e10a0f21eacc42699a95d87a1749854bc33133e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
lucas-clemente/ember-json-api
|
6128ead4215a4b1a31854d279554304d09ce920b
|
75494a5c525f8978844f12716e0c0c20ab0e21e9
|
refs/heads/main
|
<file_sep>package logica;
/**
*
* @author louisdhont
*/
public class Datum {
private String datum;
public Datum(String datum) {
this.datum = datum;
}
public String getDatum() {
return datum;
}
public void setDatum(String datum) {
if (datum == null) {
throw new IllegalArgumentException("Datum mag niet leeg zijn.");
}
this.datum = datum;
}
public String omzettenDatum(String datum) {
String maandGetal = "";
String dag = datum.substring(4, 6).replace(",", "");
if(Integer.valueOf(dag) > 31 || Integer.valueOf(dag) <= 0) {
throw new NumberFormatException("Opgegeven datum is niet geldig, dag is groter/kleiner dan toegestane waarde");
}
if (datum.contains("Jan")) {
maandGetal = "01";
} else if (datum.contains("Feb")) {
maandGetal = "02";
} else if (datum.contains("Mar")) {
maandGetal = "03";
} else if (datum.contains("Apr")) {
maandGetal = "04";
} else if (datum.contains("Mei")) {
maandGetal = "05";
} else if (datum.contains("Jun")) {
maandGetal = "06";
} else if (datum.contains("Jul")) {
maandGetal = "07";
} else if (datum.contains("Aug")) {
maandGetal = "08";
} else if (datum.contains("Sep")) {
maandGetal = "09";
} else if (datum.contains("Okt")) {
maandGetal = "10";
} else if (datum.contains("Nov")) {
maandGetal = "11";
} else if (datum.contains("Dec")) {
maandGetal = "12";
} else {
throw new IllegalArgumentException("Opgegeven datum is niet geldig, gelieve een geldige datum in te geven met formaat: MMM DD, YYYY (Jan 13, 2020)");
}
return datum.substring(7).trim() + "/" + maandGetal + "/" + dag;
}
}
<file_sep>package logica;
import java.text.DecimalFormat;
/**
*
* @author louisdhont
*/
public class Helper {
private static DecimalFormat formatter = new DecimalFormat("#,###;-#,###");
public static String getalFormatten(int getal) {
return formatter.format(getal);
}
}
<file_sep>package logica;
/**
*
* @author louisdhont
*/
public class Cijfers {
private int aantal;
public Cijfers(int aantal) {
this.aantal = aantal;
}
public int getAantal() {
return aantal;
}
public void setAantal(int aantal) {
this.aantal = aantal;
}
}
<file_sep># Java Corona Application
My corona viewer application made in Java for the Programming 2 class for my first bachelor year in Ghent.
<file_sep>package inlezen;
import data.Datalaag;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import logica.Land;
/**
*
* @author louisdhont
*/
public class InlezenLanden {
private static final String BESTAND = "src/main/java/gegevens/daily-cases-covid-19.csv";
private static final ArrayList<String> LANDNAMEN = new ArrayList<>();
private static final ArrayList<String> LANDCODES = new ArrayList<>();
Datalaag dataLaag;
public void landGegevensInlezen() throws SQLException, FileNotFoundException {
dataLaag = new Datalaag("dhontlouis");
Scanner scanLand = null;
Scanner scanCode = null;
try {
scanLand = new Scanner(new File(BESTAND));
scanCode = new Scanner(new File(BESTAND));
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Bestand: " + BESTAND + " kon niet worden gevonden", "CSV error", JOptionPane.ERROR_MESSAGE);
throw new FileNotFoundException("Kon het opgegeven bestand niet vinden");
}
// Opslaan van eerste lijn met kolomnamen
String lijstLandNaam = scanLand.nextLine().split(",")[0];
String lijstnaamCode = scanCode.nextLine().split(",")[0];
while (scanLand.hasNextLine()) {
LANDNAMEN.add(scanLand.nextLine().split(",")[0]);
LANDCODES.add(scanCode.nextLine().split(",")[1]);
}
for (int i = 0; i < LANDNAMEN.size(); i++) {
if (i == (LANDNAMEN.size() - 1)) {
Land landen = new Land(LANDNAMEN.get(i), LANDCODES.get(i));
dataLaag.invoegenLandInfo(landen.getLandCode(), landen.getLandNaam());
}
if (i + 1 != LANDNAMEN.size()) {
if (!LANDNAMEN.get(i).equals(LANDNAMEN.get(i + 1))) {
Land landen = new Land(LANDNAMEN.get(i), LANDCODES.get(i));
dataLaag.invoegenLandInfo(landen.getLandCode(), landen.getLandNaam());
}
} else {
break;
}
}
}
}
|
8b493b592134d65cdd166c1a512d251a13a12471
|
[
"Markdown",
"Java"
] | 5
|
Java
|
Xevro/2019-java-corona-application
|
ecbb86de7cb170a590f9630b4f5739f58e648e79
|
5d3c18617e6165733815458774826e016a3eb31e
|
refs/heads/master
|
<file_sep><?php
$id = 'acop';
$version = '1.0.0';
$ilias_min_version = '5.2.0';
$ilias_max_version = '5.2.999';
$responsible = '<NAME> / <NAME> / <NAME>';
$responsible_mail = '<EMAIL> / <EMAIL> / <EMAIL>';
?>
<file_sep><?php
include_once './Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php';
include_once("./Services/Table/classes/class.ilTable2GUI.php");
include_once("./Modules/Exercise/classes/class.ilExAssignment.php");
include_once("./Modules/Exercise/classes/class.ilExAssignmentMemberStatus.php");
include_once("./Modules/Exercise/classes/class.ilExAssignmentTeam.php");
include_once("./Modules/Exercise/classes/class.ilExSubmission.php");
/**
* Created by PhpStorm.
* User: Manuel
* Date: 15.02.2016
* Time: 17:34
*
* This class implements the functionality of the table of the groupfilter tab
* in excerxises.
*
*/
class ilACOExerciseMemberTableGUI extends ilTable2GUI
{
protected $exc;
protected $ass;
protected $exc_id;
protected $ass_id;
protected $sent_col;
protected $selected = array();
protected $teams = array();
protected $group;
function __construct($a_parent_obj, $a_parent_cmd, $a_exc, $a_ass, $group_id)
{
$this->group = $group_id;
global $ilCtrl, $lng;
$this->exc = $a_exc;
$this->exc_id = $this->exc->getId();
$this->ass = $a_ass;
$this->ass_id = $this->ass->getId();
$this->setId("exc_mem_" . $this->ass_id);
$this->pl = ilACOPlugin::getInstance();
include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php");
$this->storage = new ilFSStorageExercise($this->exc_id, $this->ass_id);
include_once("./Modules/Exercise/classes/class.ilExAssignment.php");
parent::__construct($a_parent_obj, $a_parent_cmd);
$this->setTitle($lng->txt("exc_assignment") . ": " . $this->ass->getTitle());
$this->setTopCommands(true);
$data = $this->ass->getMemberListData();
// team upload? (1 row == 1 team)
if ($this->ass->hasTeam()) {
$this->teams = ilExAssignmentTeam::getInstancesFromMap($this->ass_id);
$team_map = ilExAssignmentTeam::getAssignmentTeamMap($this->ass_id);
$tmp = array();
foreach ($data as $item) {
$team_id = $team_map[$item["usr_id"]];
if (!$team_id) {
$team_id = "nty" . $item["usr_id"];
}
if (!isset($tmp[$team_id])) {
$tmp[$team_id] = $item;
}
$tmp[$team_id]["team"][$item["usr_id"]] = $item["name"];
$tmp[$team_id]["team_id"] = $team_id;
}
$data = $tmp;
unset($tmp);
} else {
// peer review / rating
$ass_obj = new ilExAssignment($this->ass_id);
if ($ass_obj->getPeerReview()) {
include_once './Services/Rating/classes/class.ilRatingGUI.php';
}
}
$tmp = array();
foreach ($data as $member) {
if ($this->isGroupMember($member, $this->group)) {
array_push($tmp, $member);
}
}
$data = $tmp;
$this->setData($data);
$this->addColumn("", "", "1", true);
if (!$this->ass->hasTeam()) {
$this->selected = $this->getSelectedColumns();
if (in_array("image", $this->selected)) {
$this->addColumn($this->lng->txt("image"), "", "1");
}
$this->addColumn($this->lng->txt("name"), "name");
if (in_array("login", $this->selected)) {
$this->addColumn($this->lng->txt("login"), "login");
}
} else {
$this->addColumn($this->lng->txt("exc_team"));
}
$this->sent_col = ilExAssignmentMemberStatus::lookupAnyExerciseSent($this->ass_id);
if ($this->sent_col) {
$this->addColumn($this->lng->txt("exc_exercise_sent"), "sent_time");
}
$this->addColumn($this->lng->txt("exc_submission"), "submission");
$this->addColumn($this->lng->txt("exc_grading"), "solved_time");
$this->addColumn($this->lng->txt("feedback"), "feedback_time");
$this->setDefaultOrderField("name");
$this->setDefaultOrderDirection("asc");
$this->setEnableHeader(true);
$this->setFormAction($ilCtrl->getFormAction($a_parent_obj));
$this->setRowTemplate("tpl.exc_members_row.html", "Customizing/global/plugins/Services/UIComponent/UserInterfaceHook/ACO");
$this->setEnableTitle(true);
$this->setSelectAllCheckbox("member");
$this->addMultiCommand("redirectFeedbackMail", $lng->txt("exc_send_mail"));
if ($this->ass->hasTeam()) {
$this->addMultiCommand("createTeams", $lng->txt("exc_team_multi_create"));
$this->addMultiCommand("dissolveTeams", $lng->txt("exc_team_multi_dissolve"));
}
$this->addCommandButton("saveStatusAll", $this->pl->txt("exc_save_all_and_total"));
include_once "Services/Form/classes/class.ilPropertyFormGUI.php";
include_once "Services/UIComponent/Overlay/classes/class.ilOverlayGUI.php";
$this->overlay_tpl = new ilTemplate("tpl.exc_learner_comment_overlay.html", true, true, "Customizing/global/plugins/Services/UIComponent/UserInterfaceHook/ACO");
}
function getSelectableColumns()
{
$columns = array();
$columns["image"] = array(
"txt" => $this->lng->txt("image"),
"default" => true
);
$columns["login"] = array(
"txt" => $this->lng->txt("login"),
"default" => true
);
return $columns;
}
protected function fillRow($member)
{
if ($this->isGroupMember($member, $this->group)) {
global $lng, $ilCtrl;
$ilCtrl->setParameter($this->parent_obj, "ass_id", $this->ass_id);
$ilCtrl->setParameter($this->parent_obj, "grp_id", $this->group);
$ilCtrl->setParameter($this->parent_obj, "member_id", $member["usr_id"]);
include_once "./Services/Object/classes/class.ilObjectFactory.php";
$member_id = $member["usr_id"];
if (!($mem_obj = ilObjectFactory::getInstanceByObjId($member_id, false))) {
return;
}
$has_no_team_yet = (substr($member["team_id"], 0, 3) == "nty");
$member_status = $this->ass->getMemberStatus($member_id);
// checkbox
$this->tpl->setVariable("VAL_CHKBOX",
ilUtil::formCheckbox(0, "member[$member_id]", 1));
$this->tpl->setVariable("VAL_ID", $member_id);
if (!$has_no_team_yet) {
// mail sent
if ($this->sent_col) {
if ($member_status->getSent()) {
$this->tpl->setCurrentBlock("mail_sent");
if (($st = $member_status->getSentTime()) > 0) {
$this->tpl->setVariable("TXT_MAIL_SENT",
sprintf($lng->txt("exc_sent_at"),
ilDatePresentation::formatDate(new ilDateTime($st, IL_CAL_DATETIME))));
} else {
$this->tpl->setVariable("TXT_MAIL_SENT",
$lng->txt("sent"));
}
$this->tpl->parseCurrentBlock();
} else {
$this->tpl->setCurrentBlock("mail_sent");
$this->tpl->setVariable("TXT_MAIL_SENT",
" ");
$this->tpl->parseCurrentBlock();
}
}
}
if (!isset($member["team"])) {
$submission = new ilExSubmission($this->ass, $member_id);
} else {
if (!$has_no_team_yet) {
$member_team = $this->teams[$member["team_id"]];
} else {
// ilExSubmission should not try to auto-load
$member_team = new ilExAssignmentTeam();
}
$submission = new ilExSubmission($this->ass, $member_id, $member_team);
}
$file_info = $submission->getDownloadedFilesInfoForTableGUIS($this->parent_obj, $this->parent_cmd);
// name and login
if (!isset($member["team"])) {
$this->tpl->setVariable("TXT_NAME",
$member["name"]);
if (in_array("login", $this->selected)) {
$this->tpl->setVariable("TXT_LOGIN",
"[" . $member["login"] . "]");
}
if (in_array("image", $this->selected)) {
// image
$this->tpl->setVariable("USR_IMAGE",
$mem_obj->getPersonalPicturePath("xxsmall"));
$this->tpl->setVariable("USR_ALT", $lng->txt("personal_picture"));
}
} // team upload
else {
asort($member["team"]);
foreach ($member["team"] as $team_member_id => $team_member_name) // #10749
{
if (sizeof($member["team"]) > 1) {
$ilCtrl->setParameterByClass("ilExSubmissionTeamGUI", "id", $team_member_id);
$url = $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "confirmRemoveTeamMember");
$ilCtrl->setParameterByClass("ilExSubmissionTeamGUI", "id", "");
include_once "Services/UIComponent/Glyph/classes/class.ilGlyphGUI.php";
$this->tpl->setCurrentBlock("team_member_removal_bl");
$this->tpl->setVariable("URL_TEAM_MEMBER_REMOVAL", $url);
// $this->tpl->setVariable("TXT_TEAM_MEMBER_REMOVAL",
// ilGlyphGUI::get(ilGlyphGUI::CLOSE, $lng->txt("remove")));
$this->tpl->parseCurrentBlock();
}
$this->tpl->setCurrentBlock("team_member");
$this->tpl->setVariable("TXT_MEMBER_NAME", $team_member_name);
$this->tpl->parseCurrentBlock();
}
if (!$has_no_team_yet) {
// $this->tpl->setCurrentBlock("team_log");
// $this->tpl->setVariable("HREF_LOG",
// $ilCtrl->getLinkTargetByClass("ilExSubmissionTeamGUI", "showTeamLog"));
// $this->tpl->setVariable("TXT_LOG", $lng->txt("exc_team_log"));
// $this->tpl->parseCurrentBlock();
} else {
// #11957
$this->tpl->setCurrentBlock("team_info");
$this->tpl->setVariable("TXT_TEAM_INFO", $lng->txt("exc_no_team_yet"));
if ($file_info["files"]["count"]) {
$this->tpl->setVariable("TEAM_FILES_INFO", "<br />" .
$file_info["files"]["txt"] . ": " .
$file_info["files"]["count"]);
}
$this->tpl->parseCurrentBlock();
}
}
if (!$has_no_team_yet) {
$this->tpl->setVariable("VAL_LAST_SUBMISSION", $file_info["last_submission"]["value"]);
$this->tpl->setVariable("TXT_LAST_SUBMISSION", $file_info["last_submission"]["txt"]);
$this->tpl->setVariable("TXT_SUBMITTED_FILES", $file_info["files"]["txt"]);
$this->tpl->setVariable("VAL_SUBMITTED_FILES", $file_info["files"]["count"]);
if ($file_info["files"]["download_url"]) {
$this->tpl->setCurrentBlock("download_link");
$this->tpl->setVariable("LINK_DOWNLOAD", $file_info["files"]["download_url"]);
$this->tpl->setVariable("TXT_DOWNLOAD", $file_info["files"]["download_txt"]);
$this->tpl->parseCurrentBlock();
}
if ($file_info["files"]["download_new_url"]) {
$this->tpl->setCurrentBlock("download_link");
$this->tpl->setVariable("LINK_NEW_DOWNLOAD", $file_info["files"]["download_new_url"]);
$this->tpl->setVariable("TXT_NEW_DOWNLOAD", $file_info["files"]["download_new_txt"]);
$this->tpl->parseCurrentBlock();
}
// note
$this->tpl->setVariable("TXT_NOTE", $lng->txt("exc_note_for_tutor"));
$this->tpl->setVariable("NAME_NOTE",
"notice[$member_id]");
$this->tpl->setVariable("VAL_NOTE",
ilUtil::prepareFormOutput($member_status->getNotice()));
// comment for learner
$lcomment_value = $member_status->getComment();
$overlay_id = "excasscomm_" . $this->ass_id . "_" . $member_id;
$overlay_trigger_id = $overlay_id . "_tr";
$overlay = new ilOverlayGUI($overlay_id);
$overlay->setAnchor($overlay_trigger_id);
$overlay->setTrigger($overlay_trigger_id, "click", $overlay_trigger_id);
$overlay->add();
$this->tpl->setVariable("LCOMMENT_ID", $overlay_id . "_snip");
$this->tpl->setVariable("LCOMMENT_SNIPPET", ilUtil::shortenText($lcomment_value, 25, true));
$this->tpl->setVariable("COMMENT_OVERLAY_TRIGGER_ID", $overlay_trigger_id);
$this->tpl->setVariable("COMMENT_OVERLAY_TRIGGER_TEXT", $lng->txt("exc_comment_for_learner_edit"));
$lcomment_form = new ilPropertyFormGUI();
$lcomment_form->setId($overlay_id);
$lcomment_form->setPreventDoubleSubmission(false);
$lcomment = new ilTextAreaInputGUI($lng->txt("exc_comment_for_learner"), "lcomment_" . $this->ass_id . "_" . $member_id);
$lcomment->setInfo($lng->txt("exc_comment_for_learner_info"));
$lcomment->setValue($lcomment_value);
$lcomment->setCols(45);
$lcomment->setRows(10);
$lcomment_form->addItem($lcomment);
$lcomment_form->addCommandButton("save", $lng->txt("save"));
$this->overlay_tpl->setCurrentBlock("overlay_bl");
$this->overlay_tpl->setVariable("COMMENT_OVERLAY_ID", $overlay_id);
$this->overlay_tpl->setVariable("COMMENT_OVERLAY_FORM", $lcomment_form->getHTML());
$this->overlay_tpl->parseCurrentBlock();
$status = $member_status->getStatus();
$this->tpl->setVariable("SEL_" . strtoupper($status), ' selected="selected" ');
$this->tpl->setVariable("TXT_NOTGRADED", $lng->txt("exc_notgraded"));
$this->tpl->setVariable("TXT_PASSED", $lng->txt("exc_passed"));
$this->tpl->setVariable("TXT_FAILED", $lng->txt("exc_failed"));
if (($sd = $member_status->getStatusTime()) > 0) {
$this->tpl->setCurrentBlock("status_date");
$this->tpl->setVariable("TXT_LAST_CHANGE", $lng->txt("last_change"));
$this->tpl->setVariable('VAL_STATUS_DATE',
ilDatePresentation::formatDate(new ilDateTime($sd, IL_CAL_DATETIME)));
$this->tpl->parseCurrentBlock();
}
$pic = $member_status->getStatusIcon();
$this->tpl->setVariable("IMG_STATUS", ilUtil::getImagePath($pic));
$this->tpl->setVariable("ALT_STATUS", $lng->txt("exc_" . $status));
// mark
$this->tpl->setVariable("TXT_MARK", $lng->txt("exc_mark"));
$this->tpl->setVariable("NAME_MARK",
"mark[$member_id]");
$mark = $member_status->getMark();
$this->tpl->setVariable("VAL_MARK", ilUtil::prepareFormOutput($mark));
// feedback
if (($ft = $member_status->getFeedbackTime()) > 0) {
$this->tpl->setCurrentBlock("feedback_date");
$this->tpl->setVariable("TXT_FEEDBACK_MAIL_SENT",
sprintf($lng->txt("exc_sent_at"),
ilDatePresentation::formatDate(new ilDateTime($ft, IL_CAL_DATETIME))));
$this->tpl->parseCurrentBlock();
}
// feedback mail
$this->tpl->setVariable("LINK_FEEDBACK",
$ilCtrl->getLinkTarget($this->parent_obj, "redirectFeedbackMail"));
$this->tpl->setVariable("TXT_FEEDBACK",
$lng->txt("exc_send_mail"));
//
// peer review / rating
if ($peer_review = $submission->getPeerReview()) {
// :TODO: validate?
$given = $peer_review->countGivenFeedback(true, $member_id);
$received = sizeof($peer_review->getPeerReviewsByPeerId($member_id, true));
$this->tpl->setCurrentBlock("peer_review_bl");
$this->tpl->setVariable("LINK_PEER_REVIEW_GIVEN",
$ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showGivenPeerReview"));
$this->tpl->setVariable("TXT_PEER_REVIEW_GIVEN",
$lng->txt("exc_peer_review_given") . " (" . $given . ")");
$this->tpl->setVariable("TXT_PEER_REVIEW_RECEIVED",
$lng->txt("exc_peer_review_show") . " (" . $received . ")");
$this->tpl->setVariable("LINK_PEER_REVIEW_RECEIVED",
$ilCtrl->getLinkTargetByClass("ilexpeerreviewgui", "showReceivedPeerReview"));
$this->tpl->parseCurrentBlock();
}
$this->tpl->parseCurrentBlock();
} else {
$this->tpl->touchBlock("member_has_no_team_bl");
}
$ilCtrl->setParameter($this->parent_obj, "ass_id", $this->ass_id); // #17140
$ilCtrl->setParameter($this->parent_obj, "grp_id", $this->group);
$ilCtrl->setParameter($this->parent_obj, "member_id", "");
}
}
protected function isGroupMember($member, $group_id)
{
global $ilDB;
$user_id = $member['usr_id'];
$data = array();
$query = "select om.usr_id
from ilias.obj_members as om
where om.obj_id = '" . $group_id . "' and om.usr_id = '" . $user_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
return false;
}
return true;
}
public function render()
{
global $ilCtrl;
$url = $ilCtrl->getLinkTarget($this->getParentObject(), "saveCommentForLearners", "", true, false);
$this->overlay_tpl->setVariable("AJAX_URL", $url);
return parent::render() .
$this->overlay_tpl->get();
}
}<file_sep>ACO
============
ACO Plugin, entwickelt durch Studenten des StuPro IZIS (betreut durch das FMI Abteilung Algorithmik) an der Uni Stuttgart. Das Plugin unterliegt der GNU/GPL.
**HINWEIS**: Dieses Plugin wird open source der ILIAS Community zur Verfügung gestellt. Bei Fragen senden Sie uns eine E-Mail.
# Beschreibung/Description
Das ACO Plugin ist ein UIHook Plugin für die E-Learning Plattform ILIAS. Es ermöglicht das einfache erstellen und verwalten einer Gruppenstruktur mit Hilfe zusätzlicher Tabs (Gruppen verwalten, Gruppen erstellen, Mitglieder verschieben), sowie ein vereinfachtes Eintragen der Punkte für Abgaben, in dem sich Abgaben nach Gruppen filtern lassen.
Zudem lassen sich Excercises und Tests ebenfalls mit einem neuen Tab einfacher verlinken. Die vorgesehen Kursstruktur enthält dabei einen Admin Folder, über den sich die einzelnen Inhalte für die Gruppen verlinken lassen.
# Dokumentation/Documentation
## Installation
Beginnend im ILIAS-root-Verzeichnis:
```bash
mkdir -p Customizing/global/plugins/Services/UIComponent/UserInterfaceHook/
cd Customizing/global/plugins/Services/UIComponent/UserInterfaceHook
git clone https://github.com/Ilias-fmi/ACO.git
```
Als ILIAS Administrator, installieren und aktivieren Sie das Plugin unter "Administration->Plugins".
## Funktionalität/Functionality
### Gruppen verwalten/Manage groups tab
Zeigt innerhalb von Kursen drei weitere Subtabs an / shows inside of courses three subtabs
#### Gruppen erstellen/Create groups tab
Dieser Subtab ermöglicht beliebig viele Gruppen auf einmal anzulegen, mit den Parametern max. Mitglieder, Gruppenname, Beitrittstyp (mit oder ohne Passwort), Zeitrahmen (zeitlich begrenzter Beitritt) und Ordnerstruktur in den erstellten Gruppen und des Kurses.
#### Kurs bearbeiten/Edit course tab
Dieser Subtab ermöglicht sich alle Gruppen im Kurs anzeigen zu lassen und deren Parameter Gruppenname, Beschreibung (Raum/Uhrzeit), Tutor (Gruppenadmin), max. Mitglieder und zeitlich begrenzter Beitritt.
#### Mitglieder verschieben/Move a group member tab
Dieser Subtab ermöglicht es Gruppenmitglieder innerhalb des Kurses in eine andere Gruppe zu verschieben.
### Verlinkung/Link tab
Dieser Tab existiert innerhalb von Übungen und Tests / This tab exists inside of excercises and tests
Dabei lassen sich über diesen Übungen oder Tests in die einzelnen Gruppen verlinken, wahlweise von einem Admin Ordner in einen Ordner in den Gruppen.
### Gruppenfilter/Groupfilter tab
Dieser Tab existiert innerhalb von Übungen / This tab exists inside of excercises
Hiermit lassen sich in Übungen Abgaben nach Gruppen gefiltert anzeigen und herunterladen.
**Eine genauere Beschreibung der Funktionen bzw. Dokumentation und ein Manual finden sie unter folgendem Link**
https://github.com/Ilias-fmi/ACO/blob/master/doc/Dokumentation.pdf
### Kontakt/Contact
<NAME> <EMAIL>
<NAME> <EMAIL>
<NAME> <EMAIL>
<file_sep><?php
include_once 'class.ilACOExerciseMemberTableGUI.php';
include_once './Modules/Exercise/classes/class.ilExerciseManagementGUI.php';
include_once "Modules/Exercise/classes/class.ilExSubmission.php";
include_once "Modules/Exercise/classes/class.ilExSubmissionBaseGUI.php";
require_once './Services/Form/classes/class.ilPropertyFormGUI.php';
include_once("./Services/Form/classes/class.ilSelectInputGUI.php");
/**
* Created by PhpStorm.
* User: Manuel
* Date: 15.02.2017
* Time: 12:06
* @ilCtrl_IsCalledBy ilACOTutorGUI: ilUIPluginRouterGUI
* @ilCtrl_Calls ilACOTutorGUI: ilObjExerciseGUI, ilExSubmissionFileGUI, ilFileSystemGUI, ilRepositorySearchGUI, ilExSubmissionTeamGUI, ilExSubmissionTextGUI
*
* This class implements the functionality of the groupfilter/tutor tab in the excercises.
* The main use of this class is that you can filter the user submissions by groups
* if the excercise is linked into the groups
*
*/
class ilACOTutorGUI
{
const VIEW_ASSIGNMENT = 1;
const VIEW_PARTICIPANT = 2;
const VIEW_GRADES = 3;
protected $exercise;
protected $assignment;
public $assign = array();
protected $tree;
protected $lng;
protected $tabs;
protected $ilLocator;
protected $tpl;
protected $ctrl;
protected $pl;
protected $selected_assignment;
protected $group;
/**
* ilACOTutorGUI constructor.
*/
public function __construct()
{
global $tree, $ilCtrl, $tpl, $ilTabs, $ilLocator, $lng;
$this->tree = $tree;
$this->lng = $lng;
require_once "./Modules/Exercise/classes/class.ilObjExerciseGUI.php";
$ex_gui = new ilObjExerciseGUI("", (int)$_GET["ref_id"], true, false);
$this->exercise = $ex_gui->object;
$this->tabs = $ilTabs;
$this->ctrl = $ilCtrl;
$ilCtrl->saveParameter($this, array("vw", "member_id"));
$this->tpl = $tpl;
$this->ilLocator = $ilLocator;
$this->pl = ilACOPlugin::getInstance();
}
protected function prepareOutput()
{
global $ilLocator, $tpl, $lng, $ilCtrl;
$this->ctrl->setParameterByClass('ilobjexercisegui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilexercisehandlergui', 'ref_id', $_GET['ref_id']);
$this->ctrl->getRedirectSource();
$this->tabs->setBackTarget($this->pl->txt('back'), $this->ctrl->getLinkTargetByClass(array(
'ilrepositorygui',
'ilExerciseHandlerGUI',
)));
$this->setTitleAndIcon();
$ilLocator->addContextItems($_GET['ref_id']);
$tpl->setLocator();
}
protected function setTitleAndIcon()
{
$this->tpl->setTitleIcon(ilUtil::getImagePath('icon_exc.svg'));
$this->tpl->setTitle($this->pl->txt('obj_extu'));
$this->tpl->setDescription($this->pl->txt('obj_extu_desc'));
}
/**
*
*/
public function executeCommand()
{
global $ilCtrl, $ilTabs, $lng;
$this->checkAccess();
$cmd = $this->ctrl->getCmd('view');
$this->ctrl->saveParameter($this, 'ref_id');
$this->prepareOutput();
switch ($cmd) {
case 'view':
$this->view();
break;
default:
$this->assignment = $this->getAssignment($_GET["ass_id"]);
$this->group = $_GET["grp_id"];
$class = $ilCtrl->getNextClass($this);
$cmd = $ilCtrl->getCmd("listPublicSubmissions");
switch ($class) {
case "ilfilesystemgui":
$ilTabs->clearTargets();
$ilTabs->setBackTarget($lng->txt("back"),
$ilCtrl->getLinkTarget($this, $this->getViewBack()));
ilUtil::sendInfo($lng->txt("exc_fb_tutor_info"));
include_once("./Modules/Exercise/classes/class.ilFSStorageExercise.php");
$fstorage = new ilFSStorageExercise($this->exercise->getId(), $this->assignment->getId());
$fstorage->create();
$submission = new ilExSubmission($this->assignment, (int)$_GET["member_id"]);
$feedback_id = $submission->getFeedbackId();
$noti_rec_ids = $submission->getUserIds();
include_once("./Services/User/classes/class.ilUserUtil.php");
$fs_title = array();
foreach ($noti_rec_ids as $rec_id) {
$fs_title[] = ilUserUtil::getNamePresentation($rec_id, false, false, "", true);
}
$fs_title = implode(" / ", $fs_title);
include_once("./Services/FileSystem/classes/class.ilFileSystemGUI.php");
$fs_gui = new ilFileSystemGUI($fstorage->getFeedbackPath($feedback_id));
$fs_gui->setTableId("excfbfil" . $this->assignment->getId() . "_" . $feedback_id);
$fs_gui->setAllowDirectories(false);
$fs_gui->setTitle($lng->txt("exc_fb_files") . " - " .
$this->assignment->getTitle() . " - " .
$fs_title);
$pcommand = $fs_gui->getLastPerformedCommand();
if (is_array($pcommand) && $pcommand["cmd"] == "create_file") {
$this->exercise->sendFeedbackFileNotification($pcommand["name"],
$noti_rec_ids, $this->assignment->getId());
}
$this->ctrl->forwardCommand($fs_gui);
break;
case 'ilrepositorysearchgui':
include_once('./Services/Search/classes/class.ilRepositorySearchGUI.php');
$rep_search = new ilRepositorySearchGUI();
$rep_search->setTitle($this->lng->txt("exc_add_participant"));
$rep_search->setCallback($this, 'addMembersObject');
// Set tabs
$this->ctrl->setReturn($this, 'members');
$this->ctrl->forwardCommand($rep_search);
break;
case "ilexsubmissionteamgui":
include_once "Modules/Exercise/classes/class.ilExSubmissionTeamGUI.php";
$gui = new ilExSubmissionTeamGUI($this->exercise, $this->initSubmission());
$ilCtrl->forwardCommand($gui);
break;
case "ilexsubmissionfilegui":
include_once "Modules/Exercise/classes/class.ilExSubmissionFileGUI.php";
$gui = new ilExSubmissionFileGUI($this->exercise, $this->initSubmission());
$ilCtrl->forwardCommand($gui);
break;
case "ilexsubmissiontextgui":
include_once "Modules/Exercise/classes/class.ilExSubmissionTextGUI.php";
$gui = new ilExSubmissionTextGUI($this->exercise, $this->initSubmission());
$ilCtrl->forwardCommand($gui);
break;
case "ilexpeerreviewgui":
include_once "Modules/Exercise/classes/class.ilExPeerReviewGUI.php";
$gui = new ilExPeerReviewGUI($this->assignment, $this->initSubmission());
$ilCtrl->forwardCommand($gui);
break;
default:
$this->{$cmd . "Object"}();
break;
}
}
$this->tpl->getStandardTemplate();
$this->tpl->show();
}
protected function getViewBack()
{
switch ($_REQUEST["vw"]) {
case self::VIEW_PARTICIPANT:
$back_cmd = "showParticipant";
break;
case self::VIEW_GRADES:
$back_cmd = "showGradesOverview";
break;
default:
$back_cmd = "members";
break;
}
return $back_cmd;
}
protected function initSubmission()
{
$this->tabs_gui = $this->tabs;
$back_cmd = $this->getViewBack();
$this->ctrl->setReturn($this, $back_cmd);
$this->tabs_gui->setBackTarget($this->lng->txt("back"),
$this->ctrl->getLinkTarget($this, $back_cmd));
include_once "Modules/Exercise/classes/class.ilExSubmission.php";
return new ilExSubmission($this->assignment, $_REQUEST["member_id"], null, true);
}
/**
* default command
*/
protected function view()
{
$this->membersObject();
}
protected function getAssignment($ass_id)
{
$ass = ilExAssignment::getInstancesByExercise($this->exercise->getId());
foreach ($ass as $as) {
if ($as->getID() == $ass_id) {
return $as;
}
}
}
protected function isCourse($ref_id)
{
global $ilDB;
$data = array();
$query = "select od.title
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
where od.type = 'crs' and oref.ref_id = '" . $ref_id . "' ";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
return false;
}
return true;
}
protected function getParentIds($id)
{
global $ilDB;
$ids = array();
$data = array();
$query = "select tree.parent from ilias.tree as tree where child = '" . $id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
foreach ($data as $folder) {
array_push($ids, $folder['parent']);
}
return $ids;
}
protected function getGroups()
{
global $ilUser, $ilDB;
$user_id = $ilUser->getId();
$ref_id = $_GET['ref_id'];
do {
$parent_id = $this->getParentIds($ref_id);
$ref_id = $parent_id[0];
} while (!$this->isCourse($ref_id));
$data = array();
$query = "select od.title, od.obj_id
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.crs_items citem on citem.obj_id = oref.ref_id
join ilias.obj_members as om on om.obj_id = oref.obj_id
where oref.deleted is null and od.`type`='grp' and citem.parent_id = '" . $ref_id . "' and om.usr_id = '" . $user_id . "' and om.admin = 1 ";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
$output = array();
foreach ($data as $result) {
$output[$result['obj_id']] = $result['title'];
}
return $output;
}
public function membersObject()
{
global $tpl, $ilCtrl, $ilToolbar, $lng;
require_once "./Modules/Exercise/classes/class.ilObjExerciseGUI.php";
$ex_gui = new ilObjExerciseGUI("", (int)$_GET["ref_id"], true, false);
$this->exercise = $ex_gui->object;
$group_options = $this->getGroups();
include_once 'Services/Tracking/classes/class.ilLPMarks.php';
$seli = new ilSelectInputGUI($this->lng->txt(""), "grp_id");
$seli->setOptions($group_options);
$seli->setValue($_POST["grp_id"]);
$ilToolbar->addStickyItem($seli);
$this->group = $seli->getValue();
// assignment selection
include_once("./Modules/Exercise/classes/class.ilExAssignment.php");
$ass = ilExAssignment::getInstancesByExercise($this->exercise->getId());
if (!$this->assignment) {
$this->assignment = current($ass);
}
reset($ass);
if (count($ass) > 1) {
$options = array();
foreach ($ass as $a) {
$options[$a->getId()] = $a->getTitle();
}
include_once("./Services/Form/classes/class.ilSelectInputGUI.php");
$si = new ilSelectInputGUI($this->lng->txt(""), "ass_id");
$si->setOptions($options);
$si->setValue($this->assignment->getId());
$ilToolbar->addStickyItem($si);
include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php");
$button = ilSubmitButton::getInstance();
$button->setCaption($this->pl->txt("exc_select_ass_grp"));
$button->setCommand("selectAssignment");
$ilToolbar->addStickyItem($button);
$ilToolbar->addSeparator();
} // #16165 - if only 1 assignment dropdown is not displayed;
else if ($this->assignment) {
$ilCtrl->setParameter($this, "ass_id", $this->assignment->getId());
include_once("./Services/UIComponent/Button/classes/class.ilSubmitButton.php");
$button = ilSubmitButton::getInstance();
$button->setCaption($this->pl->txt("exc_select_ass_grp"));
$button->setCommand("selectAssignment");
$ilToolbar->addStickyItem($button);
$ilToolbar->addSeparator();
}
// #16168 - no assignments
if (count($ass) > 0) {
// we do not want the ilRepositorySearchGUI form action
$ilToolbar->setFormAction($ilCtrl->getFormAction($this));
$ilCtrl->setParameter($this, "ass_id", $this->assignment->getId());
// if (ilExSubmission::hasAnySubmissions($this->assignment->getId())) {
//
// if ($this->assignment->getType() == ilExAssignment::TYPE_TEXT) {
// $ilToolbar->addFormButton($lng->txt("exc_list_text_assignment"), "listTextAssignment");
// } else {
// $ilToolbar->addFormButton($lng->txt("download_all_returned_files"), "downloadAll");
// }
// }
$this->ctrl->setParameter($this, "vw", self::VIEW_ASSIGNMENT);
include_once("./Modules/Exercise/classes/class.ilExerciseMemberTableGUI.php");
$exc_tab = new ilACOExerciseMemberTableGUI($this, "members", $this->exercise, $this->assignment, $this->group);
$tpl->setContent($exc_tab->getHTML());
} else {
ilUtil::sendInfo($lng->txt("exc_no_assignments_available"));
}
$ilCtrl->setParameter($this, "ass_id", "");
return;
}
function downloadAllObject()
{
global $ilCtrl;
$members = array();
$this->assignment = $this->getAssignment($_POST['ass_id']);
$this->group = $_POST["grp_id"];
foreach ($this->exercise->members_obj->getMembers() as $member_id) {
if ($this->isGroupMember($member_id, $this->group)) {
$submission = new ilExSubmission($this->assignment, $member_id);
$submission->updateTutorDownloadTime();
// get member object (ilObjUser)
if (ilObject::_exists($member_id)) {
// adding file metadata
foreach ($submission->getFiles() as $file) {
$members[$file["user_id"]]["files"][$file["returned_id"]] = $file;
}
$tmp_obj =& ilObjectFactory::getInstanceByObjId($member_id);
$members[$member_id]["name"] = $tmp_obj->getFirstname() . " " . $tmp_obj->getLastname();
unset($tmp_obj);
}
} else {
$grps = $this->getGroups();
$grp_title = $grps[$this->group];
ilUtil::sendFailure($this->pl->txt("exc_no_submission_in_group") . " " . $grp_title, true);
$ilCtrl->redirect($this, $this->getViewBack());
}
}
ilExSubmission::downloadAllAssignmentFiles($this->assignment, $members);
}
protected function isGroupMember($member, $group_id)
{
global $ilDB;
$data = array();
$query = "select om.usr_id
from ilias.obj_members as om
where om.obj_id = '" . $group_id . "' and om.usr_id = '" . $member . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
return false;
}
return true;
}
function saveCommentsObject()
{
if (!isset($_POST['comments_value'])) {
return;
}
$this->exercise->members_obj->setNoticeForMember($_GET["member_id"],
ilUtil::stripSlashes($_POST["comments_value"]));
ilUtil::sendSuccess($this->lng->txt("exc_members_comments_saved"));
$this->membersObject();
}
/**
* Save comment for learner (asynch)
*/
function saveCommentForLearnersObject()
{
$res = array("result" => false);
if ($this->ctrl->isAsynch()) {
$ass_id = (int)$_POST["ass_id"];
$user_id = (int)$_POST["mem_id"];
$comment = trim($_POST["comm"]);
if ($ass_id && $user_id) {
$submission = new ilExSubmission($this->assignment, $user_id);
$user_ids = $submission->getUserIds();
$all_members = new ilExerciseMembers($this->exercise);
$all_members = $all_members->getMembers();
$reci_ids = array();
foreach ($user_ids as $user_id) {
if (in_array($user_id, $all_members)) {
$member_status = $this->assignment->getMemberStatus($user_id);
$member_status->setComment(ilUtil::stripSlashes($comment));
$member_status->update();
if (trim($comment)) {
$reci_ids[] = $user_id;
}
}
}
if (sizeof($reci_ids)) {
// send notification
$this->exercise->sendFeedbackFileNotification(null, $reci_ids,
$ass_id, true);
}
$res = array("result" => true, "snippet" => ilUtil::shortenText($comment, 25, true));
}
}
echo(json_encode($res));
exit();
}
function createTeamsObject()
{
global $ilCtrl;
$members = $this->getMultiActionUserIds(true);
if ($members) {
$new_members = array();
include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php";
foreach ($members as $group) {
if (is_array($group)) {
$new_members = array_merge($new_members, $group);
$first_user = $group;
$first_user = array_shift($first_user);
$team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user);
foreach ($group as $user_id) {
$team->removeTeamMember($user_id);
}
} else {
$new_members[] = $group;
}
}
if (sizeof($new_members)) {
// see ilExSubmissionTeamGUI::addTeamMemberActionObject()
$first_user = array_shift($new_members);
$team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user, true);
if (sizeof($new_members)) {
foreach ($new_members as $user_id) {
$team->addTeamMember($user_id);
}
}
// re-evaluate complete team, as some members might have had submitted
$submission = new ilExSubmission($this->assignment, $first_user);
$this->exercise->processExerciseStatus(
$this->assignment,
$team->getMembers(),
$submission->hasSubmitted(),
$submission->validatePeerReviews()
);
}
ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true);
}
$ilCtrl->redirect($this, "members");
}
function dissolveTeamsObject()
{
global $ilCtrl;
$members = $this->getMultiActionUserIds(true);
if ($members) {
include_once "Modules/Exercise/classes/class.ilExAssignmentTeam.php";
foreach ($members as $group) {
// if single member - nothing to do
if (is_array($group)) {
// see ilExSubmissionTeamGUI::removeTeamMemberObject()
$first_user = $group;
$first_user = array_shift($first_user);
$team = ilExAssignmentTeam::getInstanceByUserId($this->assignment->getId(), $first_user);
foreach ($group as $user_id) {
$team->removeTeamMember($user_id);
}
// reset ex team members, as any submission is not valid without team
$this->exercise->processExerciseStatus(
$this->assignment,
$group,
false
);
}
}
ilUtil::sendSuccess($this->lng->txt("msg_obj_modified"), true);
}
$ilCtrl->redirect($this, "members");
}
protected function getMultiActionUserIds($a_keep_teams = false)
{
if (!is_array($_POST["member"]) ||
count($_POST["member"]) == 0
) {
ilUtil::sendFailure($this->lng->txt("no_checkbox"), true);
} else {
$members = array();
foreach (array_keys($_POST["member"]) as $user_id) {
$submission = new ilExSubmission($this->assignment, $user_id);
$tmembers = $submission->getUserIds();
if (!(bool)$a_keep_teams) {
foreach ($tmembers as $tuser_id) {
$members[$tuser_id] = 1;
}
} else {
if ($tmembers) {
$members[] = $tmembers;
} else {
// no team yet
$members[] = $user_id;
}
}
}
return $members;
}
}
/**
* set feedback status for member and redirect to mail screen
*/
function redirectFeedbackMailObject()
{
$members = array();
if ($_GET["member_id"] != "") {
$submission = new ilExSubmission($this->assignment, $_GET["member_id"]);
$members = $submission->getUserIds();
} else if ($members = $this->getMultiActionUserIds()) {
$members = array_keys($members);
}
if ($members) {
$logins = array();
foreach ($members as $user_id) {
$member_status = $this->assignment->getMemberStatus($user_id);
$member_status->setFeedback(true);
$member_status->update();
$logins[] = ilObjUser::_lookupLogin($user_id);
}
$logins = implode($logins, ",");
// #16530 - see ilObjCourseGUI::createMailSignature
$sig = chr(13) . chr(10) . chr(13) . chr(10);
$sig .= $this->lng->txt('exc_mail_permanent_link');
$sig .= chr(13) . chr(10) . chr(13) . chr(10);
include_once './Services/Link/classes/class.ilLink.php';
$sig .= ilLink::_getLink($this->exercise->getRefId());
$sig = rawurlencode(base64_encode($sig));
require_once 'Services/Mail/classes/class.ilMailFormCall.php';
ilUtil::redirect(ilMailFormCall::getRedirectTarget(
$this,
$this->getViewBack(),
array(),
array(
'type' => 'new',
'rcp_to' => $logins,
ilMailFormCall::SIGNATURE_KEY => $sig
)
));
}
ilUtil::sendFailure($this->lng->txt("no_checkbox"), true);
$this->ctrl->redirect($this, "members");
}
/**
* Send assignment per mail to participants
*/
function sendMembersObject()
{
global $ilCtrl;
$members = $this->getMultiActionUserIds();
if (is_array($members)) {
$this->exercise->sendAssignment($this->assignment, $members);
ilUtil::sendSuccess($this->lng->txt("exc_sent"), true);
}
$ilCtrl->redirect($this, "members");
}
function saveStatusAllObject()
{
$this->group = $_POST["grp_id"];
$_GET["grp_id"] = $_POST["grp_id"];
$user_ids = array();
$data = array();
foreach (array_keys($_POST["id"]) as $user_id) {
array_push($user_ids, $user_id);
$data[-1][$user_id] = array(
"status" => ilUtil::stripSlashes($_POST["status"][$user_id])
, "notice" => ilUtil::stripSlashes($_POST["notice"][$user_id])
, "mark" => ilUtil::stripSlashes($_POST["mark"][$user_id])
);
}
$this->saveStatus($data, $user_ids);
}
protected function saveStatus(array $a_data, $user_ids = '')
{
global $ilCtrl;
include_once("./Modules/Exercise/classes/class.ilExAssignment.php");
$saved_for = array();
foreach ($a_data as $ass_id => $users) {
$ass = ($ass_id < 0)
? $this->assignment
: new ilExAssignment($ass_id);
foreach ($users as $user_id => $values) {
// this will add team members if available
$submission = new ilExSubmission($ass, $user_id);
foreach ($submission->getUserIds() as $sub_user_id) {
$uname = ilObjUser::_lookupName($sub_user_id);
$saved_for[$sub_user_id] = $uname["lastname"] . ", " . $uname["firstname"];
$member_status = $ass->getMemberStatus($sub_user_id);
$member_status->setStatus($values["status"]);
$member_status->setNotice($values["notice"]);
$member_status->setMark($values["mark"]);
$member_status->update();
}
}
}
if (count($saved_for) > 0) {
$save_for_str = "(" . implode($saved_for, " - ") . ")";
}
if (!empty($user_ids)) {
global $ilDB;
$ass = ilExAssignment::getInstancesByExercise($this->exercise->getId());
$exercise_id = $this->exercise->getId();
$ass_ids = array();
foreach ($ass as $assignment) {
array_push($ass_ids, $assignment->getId());
}
foreach ($user_ids as $usr_id) {
$data = array();
$query = 'SELECT ilias.exc_mem_ass_status.mark from ilias.exc_mem_ass_status where ilias.exc_mem_ass_status.ass_id in (' . implode(",", $ass_ids) . ') and ilias.exc_mem_ass_status.usr_id = ' . $usr_id . '';
$res = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($res)) {
array_push($data, $record);
}
$totalmark = 0;
foreach ($data as $ass_mark) {
$totalmark += $ass_mark['mark'];
}
$query = 'UPDATE ilias.ut_lp_marks
SET ilias.ut_lp_marks.mark = ' . $totalmark . '
WHERE ilias.ut_lp_marks.obj_id = ' . $exercise_id . ' AND ilias.ut_lp_marks.usr_id = ' . $usr_id . '';
$ilDB->manipulate($query);
}
}
ilUtil::sendSuccess($this->lng->txt("exc_status_saved") . " " . $save_for_str, true);
$ilCtrl->redirect($this, $this->getViewBack());
}
public function selectAssignmentObject()
{
global $ilTabs;
$_GET["grp_id"] = ilUtil::stripSlashes($_POST["grp_id"]);
$this->group = ilUtil::stripSlashes($_POST["grp_id"]);
$_GET["ass_id"] = ilUtil::stripSlashes($_POST["ass_id"]);
$this->selected_assignment = ilUtil::stripSlashes($_POST["ass_id"]);
$ass = ilExAssignment::getInstancesByExercise($this->exercise->getId());
foreach ($ass as $as) {
if ($as->getID() == $this->selected_assignment) {
$this->assignment = $as;
$this->assign[0] = $as;
}
}
$this->membersObject();
}
protected function checkAccess()
{
global $ilAccess, $ilErr;
if (!$ilAccess->checkAccess("write", "", $_GET['ref_id'])) {
$ilErr->raiseError($this->lng->txt("no_permission"), $ilErr->WARNING);
}
}
}
<file_sep><?php
include_once("./Services/UIComponent/classes/class.ilUIHookPluginGUI.php");
/**
* Class ilACOUIHookGUI
*
* This class implements the visability of every tab in our plugin and
* that they are only visible authorized users, eg. tutor or course admins.
*
* The structur is inspirated by the UIHookGUI class of the courseimport Plugin
* form studer&raiman (@author <NAME>)
*/
class ilACOUIHookGUI extends ilUIHookPluginGUI
{
/**
* @var ilCtrl
*/
protected $ctrl;
/**
* @var ilACOPlugin
*/
protected $pl;
public function __construct()
{
global $ilCtrl;
$this->ctrl = $ilCtrl;
$this->pl = ilACOPlugin::getInstance();
}
function getHTML($a_comp, $a_part, $a_par = array())
{
}
function modifyGUI($a_comp, $a_part, $a_par = array())
{
global $ilTabs, $ilAccess, $ilErr;
$tabs = $a_par['tabs'];
// Tab im einzelnen Kurs
if (($_GET["baseClass"] == 'ilRepositoryGUI' || $_GET["baseClass"] == 'ilrepositorygui')
&& $a_part == 'tabs' && $ilAccess->checkAccess("write", "", $_GET['ref_id'])
&& ilObject::_lookupType($_GET['ref_id'], true) == 'crs'
) {
$this->ctrl->setParameterByClass('ilacogroupgui', 'ref_id', $_GET['ref_id']);
$link1 = $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI'));
$tabs->addTab('course_management', $this->pl->txt('tab_course_management'), $link1);
}
// Tab in einer Uebung
if (($_GET["baseClass"] == 'ilExerciseHandlerGUI' || $_GET["baseClass"] == 'ilexercisehandlergui')
&& $a_part == 'tabs' && $ilAccess->checkAccess("write", "", $_GET['ref_id'])
) {
$this->ctrl->setParameterByClass('ilacolinkgui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacotutorgui', 'ref_id', $_GET['ref_id']);
$link2 = $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOLinkGUI'));
$link3 = $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOTutorGUI'));
$tabs->addTab('link', $this->pl->txt('tab_link'), $link2);
$tabs->addTab('tutor', $this->pl->txt('tab_tutor'), $link3);
}
//Tab in einem Test
if (($_GET["baseClass"] == 'ilRepositoryGUI' || $_GET["baseClass"] == 'ilrepositorygui') &&
$a_part == 'tabs' && $ilAccess->checkAccess("write", "", $_GET['ref_id'])
&& ilObject::_lookupType($_GET['ref_id'], true) == 'tst'
) {
$this->ctrl->setParameterByClass('ilacolinkgui', 'ref_id', $_GET['ref_id']);
$link4 = $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOLinkGUI'));
$tabs->addTab('link', $this->pl->txt('tab_link'), $link4);
}
}
}<file_sep><?php
include_once("./Services/UIComponent/classes/class.ilUIHookPluginGUI.php");
include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php");
require_once './Services/Form/classes/class.ilPropertyFormGUI.php';
require_once './Modules/Group/classes/class.ilObjGroup.php';
require_once './Services/Object/classes/class.ilObject2.php';
require_once './Services/Form/classes/class.ilNumberInputGUI.php';
require_once './Services/Form/classes/class.ilTextInputGUI.php';
require_once './Services/Form/classes/class.ilRadioGroupInputGUI.php';
require_once './Services/Form/classes/class.ilRadioOption.php';
require_once './Services/Form/classes/class.ilDateTimeInputGUI.php';
require_once './Modules/Folder/classes/class.ilObjFolder.php';
/**
* @ilCtrl_IsCalledBy ilACOGroupGUI: ilUIPluginRouterGUI
* @ilCtrl_Calls ilACOGroupGUI: ilObjCourseAdministrationGUI
*
* This class implements the functionality of the "groupcreator tab" which are
* the number of groups (checks the db and numbers the group consecutively),
* maximum members, how to join the group (password ord not), from/till which
* date and if you want a folder with a unique name in every created group.
*
*/
class ilACOGroupGUI
{
const CREATION_SUCCEEDED = 'creation_succeeded';
const CREATION_FAILED = 'creation_failed';
/**
* @var ilCtrl
*/
protected $ctrl;
/**
* @var ilTemplate
*/
protected $tpl;
/**
* @var ilACOPlugin
*/
protected $pl;
/**
* @var ilTabsGUI
*/
protected $tabs;
/**
* @var ilLocatorGUI
*/
protected $ilLocator;
/**
* @var ilLanguage
*/
protected $lng;
/**
* @var ilTree
*/
protected $tree;
protected $courses;
protected $members;
protected $group_count;
protected $number_grp;
protected $reg_proc;
protected $pass;
protected $group_time_start;
protected $group_name;
protected $group_folder_name;
protected $group_folder_name_checkbox;
public function __construct()
{
global $tree, $ilCtrl, $tpl, $ilTabs, $ilLocator, $lng;
$this->tree = $tree;
$this->lng = $lng;
$this->tabs = $ilTabs;
$this->ctrl = $ilCtrl;
$this->tpl = $tpl;
$this->ilLocator = $ilLocator;
$this->pl = ilACOPlugin::getInstance();
}
protected function prepareOutput()
{
global $ilLocator, $tpl;
$this->ctrl->setParameterByClass('ilobjcourseadministrationgui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacogroupdisplaygui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacomembergui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilrepositorygui', 'ref_id', $_GET['ref_id']);
$this->tabs->addTab('course_management', $this->pl->txt('tab_course_management'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI')));
$this->tabs->addSubTab('group_create', $this->pl->txt('group_create'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI')));
$this->tabs->addSubTab('course_edit', $this->pl->txt('course_edit'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupDisplayGUI')));
$this->tabs->addSubTab('member_edit', $this->pl->txt('member_edit'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOMemberGUI')));
$this->tabs->activateSubTab('group_create');
$this->ctrl->getRedirectSource();
$this->tabs->setBackTarget($this->pl->txt('back'), $this->ctrl->getLinkTargetByClass(array(
'ilrepositorygui',
'ilrepositorygui',
)));
$this->setTitleAndIcon();
$ilLocator->addRepositoryItems($_GET['ref_id']);
$tpl->setLocator();
}
protected function setTitleAndIcon()
{
$this->tpl->setTitleIcon(ilUtil::getImagePath('icon_crs.svg'));
$this->tpl->setTitle($this->pl->txt('obj_acop'));
$this->tpl->setDescription($this->pl->txt('obj_acop_desc'));
}
/**
*
*/
public function executeCommand()
{
$this->checkAccess();
$cmd = $this->ctrl->getCmd('view');
$this->ctrl->saveParameter($this, 'ref_id');
$this->prepareOutput();
switch ($cmd) {
default:
$this->$cmd();
break;
}
$this->tpl->getStandardTemplate();
$this->tpl->show();
}
/**
* default command
*/
protected function view()
{
$form = $this->initForm();
$this->tpl->setContent($form->getHTML());
}
protected function initForm()
{
$form = new ilPropertyFormGUI();
$form->setTitle($this->pl->txt('group_create_title'));
$form->setId('group_create');
$form->setFormAction($this->ctrl->getFormAction($this));
$this->group_name = new ilTextInputGUI($this->pl->txt("group_name"), "group_name");
$this->group_name->setRequired(true);
$form->addItem($this->group_name);
$this->group_count = new ilNumberInputGUI($this->pl->txt('group_count'), 'group_count');
$this->members = new ilNumberInputGUI($this->pl->txt('members'), 'members');
$this->group_count->setRequired(true);
$this->members->setRequired(true);
$form->addItem($this->group_count);
$form->addItem($this->members);
$this->reg_proc = new ilRadioGroupInputGUI($this->pl->txt('grp_registration_type'), 'subscription_type');
$opt = new ilRadioOption($this->pl->txt('grp_reg_direct_info_screen'), GRP_REGISTRATION_DIRECT);
$this->reg_proc->addOption($opt);
$opt = new ilRadioOption($this->pl->txt('grp_reg_passwd_info_screen'), GRP_REGISTRATION_PASSWORD);
$this->pass = new ilTextInputGUI($this->pl->txt("password"), 'subscription_password');
$this->pass->setSize(12);
$this->pass->setMaxLength(12);
$opt->addSubItem($this->pass);
$this->reg_proc->addOption($opt);
$form->addItem($this->reg_proc);
$time_limit = new ilCheckboxInputGUI($this->pl->txt('grp_reg_limited'), 'reg_limit_time');
$this->lng->loadLanguageModule('dateplaner');
include_once './Services/Form/classes/class.ilDateDurationInputGUI.php';
$this->tpl->addJavaScript('./Services/Form/js/date_duration.js');
$dur = new ilDateDurationInputGUI($this->pl->txt('grp_reg_period'), 'reg');
$dur->setStartText($this->pl->txt('cal_start'));
$dur->setEndText($this->pl->txt('cal_end'));
$dur->setShowTime(true);
$time_limit->addSubItem($dur);
$form->addItem($time_limit);
$this->group_folder_name_checkbox = new ilCheckboxInputGUI($this->pl->txt('group_folder_name_checkbox'), 'group_folder_name_checkbox');
$this->group_folder_name = new ilTextInputGUI($this->pl->txt("group_folder_name"), "group_folder_name");
$this->group_folder_name->setInfo($this->pl->txt("info_group_folder"));
$this->group_folder_name_checkbox->addSubItem($this->group_folder_name);
$form->addItem($this->group_folder_name_checkbox);
$form->addCommandButton('createGroups', $this->pl->txt('create_groups'));
return $form;
}
/**
* loads the date from the date input field
* the format is new since ilias 5.2.2
*
* @global type $ilUser
* @param type $a_field
* @return \ilDateTime
*/
protected function loadDate($a_field)
{
global $ilUser;
include_once('./Services/Calendar/classes/class.ilDateTime.php');
$dt = $_POST['reg'][$a_field];
$date = new ilDateTime($dt, IL_CAL_DATE, $ilUser->getTimeZone());
return $date;
}
/** counts the groups in the course and @return the result
* we have to look in the tree table on the field child because
* the same value in crs_item as obj_id is not immediately updated
*
* @global type $ilDB
* @param type $parent_id
* @return type
*/
protected function countGroups($parent_id)
{
global $ilDB;
$group_number = array();
$query = "select od.title as 'Übungsruppe'
from ilias.object_data od
join ilias.object_reference obr on od.obj_id = obr.obj_id
join ilias.tree crsi on obr.ref_id = crsi.child
where (od.type = 'grp') and (obr.deleted is null) and (crsi.parent = '" . $parent_id . "') ";
$results = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($results)) {
array_push($group_number, $record);
}
$result = count($group_number);
return $result;
}
/**
*
* @global type $ilDB
* @global type $ilUser
* @global type $rbacadmin
*/
protected function createGroups()
{
global $ilDB, $ilUser, $rbacadmin;
$userID = $ilUser->getId();
$form = $this->initForm();
$form->setValuesByPost();
$reg_start = $this->loadDate('start');
$reg_end = $this->loadDate('end');
$created = false;
$prefix = $this->group_name->getValue();
$number = $this->group_count->getValue();
$members = $this->members->getValue();
$password = $this->pass->getValue();
$reg_type = $this->reg_proc->getValue();
$folder_title = explode(";", $this->group_folder_name->getValue());
foreach ($folder_title as $forCourseFolderTitle) {
if ($_POST['group_folder_name_checkbox'] AND !($this->folderAlreadyExistingCourse($forCourseFolderTitle))) {
$courseFolder = new ilObjFolder();
$courseFolder->setTitle($forCourseFolderTitle);
$courseFolder->create();
$courseFolder->createReference();
$courseFolder->putInTree($_GET['ref_id']);
$courseFolder->setPermissions($_GET['ref_id']);
}
}
foreach ($this->groupsInCourse() as $groupsInCourse) {
//adminFolder is created in every existing group which hasn't had such a folder yet
foreach ($folder_title as $forGroupFolderTitle) {
if ($_POST['group_folder_name_checkbox'] AND
!($this->folderAlreadyExistingGroup($forGroupFolderTitle, $groupsInCourse['ref_id']))
) {
$oldGroupFolder = new ilObjFolder();
$oldGroupFolder->setTitle($forGroupFolderTitle);
$oldGroupFolder->create();
$oldGroupFolder->createReference();
$oldGroupFolder->putInTree($groupsInCourse['ref_id']);
$oldGroupFolder->setPermissions($groupsInCourse['ref_id']);
}
}
}
$parent_id = $_GET['ref_id'];
$result = $this->countGroups($parent_id);
$nn = 1;
if ($result > 0) {
$result++;
$nn = $result;
$number = $number + $nn - 1;
}
for ($n = $nn; $n <= $number; $n++) {
$group = new ilObjGroup();
if ($n < 10) { //is necessary for numerical sort
$group->setTitle($prefix . ' 0' . $n);
} else {
$group->setTitle($prefix . ' ' . $n);
}
$group->setGroupType(GRP_TYPE_CLOSED);
$group->setRegistrationType($reg_type);
if ($reg_type == GRP_REGISTRATION_PASSWORD) {
$group->setPassword($password);
}
$group->enableUnlimitedRegistration((bool)!$_POST['reg_limit_time']);
if ($reg_end < $reg_start) {
$reg_end = $reg_start;
}
$group->setRegistrationStart($reg_start);
$group->setRegistrationEnd($reg_end);
$group->setMaxMembers($members);
$group->enableMembershipLimitation(true);
$group->create();
$group->createReference();
$group->putInTree($_GET['ref_id']);
$group->setPermissions($_GET['ref_id']);
$admin_role = $group->getDefaultAdminRole();
$rbacadmin->assignUser($admin_role, $userID);
$query = "UPDATE ilias.obj_members as om
SET om.contact = 1, om.notification = 1
WHERE om.obj_id = '" . $group->getId() . "' AND om.usr_id = '" . $userID . "' ";
$ilDB->manipulate($query);
foreach ($folder_title as $forGroupFolderTitle) {
if ($_POST['group_folder_name_checkbox']) {
$groupFolder = new ilObjFolder();
$groupFolder->setTitle($forGroupFolderTitle);
$groupFolder->create();
$groupFolder->createReference();
$groupFolder->putInTree($group->getRefId());
$groupFolder->setPermissions($group->getRefId());
}
}
$this->courses['created'] .= ilObject2::_lookupTitle(ilObject2::_lookupObjId($_GET['ref_id'])) . ' - ' . $group->getTitle() . '<br>';
$created = true;
}
if ($created) {
ilUtil::sendSuccess(sprintf($this->pl->txt(self::CREATION_SUCCEEDED), $this->courses['created'], $this->courses['updated'], $this->courses['refs'], $this->courses['refs_del']));
$form = $this->initForm();
$this->tpl->setContent($form->getHTML());
} else {
ilUtil::sendFailure($this->pl->txt(self::CREATION_FAILED), true);
$this->tpl->setContent($form->getHTML());
}
}
protected function groupsInCourse()
{
global $ilDB;
$group_id = array();
$query = "select oref.ref_id from ilias.crs_items as citem
join ilias.object_reference as oref on oref.ref_id = citem.obj_id
join ilias.object_data as od on oref.obj_id = od.obj_id
join ilias.crs_items as ci on oref.ref_id = ci.obj_id
where od.type='grp' and ci.parent_id='" . $_GET['ref_id'] . "' and oref.deleted is null";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($group_id, $record);
}
return $group_id;
}
/**
*
* @global type $ilDB
* @param type $folder_name
* @return boolean
*/
protected function folderAlreadyExistingCourse($folder_name)
{
global $ilDB;
$folderCourse = array();
//check if the folder already exists in the course
$query = "select COUNT(*) from ilias.crs_items as citem
join ilias.object_reference as oref on oref.ref_id = citem.obj_id
join ilias.object_data as od on oref.obj_id = od.obj_id
join ilias.crs_items as ci on oref.ref_id = ci.obj_id
where od.type='fold' and ci.parent_id='" . $_GET['ref_id'] . "' and od.title='" . $folder_name . "' and oref.deleted is null";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($folderCourse, $record);
}
//if folder already exists in the course
if (strcmp($folderCourse[0]["COUNT(*)"], "0") !== 0) {
return true;
} else {
return false;
}
}
/**
*
* @global type $ilDB
* @param type $folder_name
* @param type $group_ref_id
* @return boolean
*/
protected function folderAlreadyExistingGroup($folder_name, $group_ref_id)
{
global $ilDB;
$folderGroup = array();
//check if folder exists in a group
$query = "select COUNT(*) from ilias.crs_items as citem
join ilias.object_reference as oref on oref.ref_id = citem.obj_id
join ilias.object_data as od on oref.obj_id = od.obj_id
join ilias.crs_items as ci on oref.ref_id = ci.obj_id
where od.type='fold' and ci.parent_id='" . $group_ref_id . "' and od.title='" . $folder_name . "' and oref.deleted is null";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($folderGroup, $record);
}
//if the folder already exists in a group
if (strcmp($folderGroup[0]["COUNT(*)"], "0") !== 0) {
return true;
} else {
return false;
}
}
/**
* @global type $ilAccess
* @global type $ilErr
*
* checks the access rights of the user
* should be redundant if the checkAccess in ilACOUIHookGUI works
*/
protected function checkAccess()
{
global $ilAccess, $ilErr;
if (!$ilAccess->checkAccess("read", "", $_GET['ref_id'])) {
$ilErr->raiseError($this->lng->txt("no_permission"), $ilErr->WARNING);
}
}
}
<file_sep><?php
require_once './Services/Form/classes/class.ilTextInputGUI.php';
require_once './Services/Form/classes/class.ilPropertyFormGUI.php';
define('IL_GRP_MEMBER', 5);
/**
* Created by PhpStorm.
* User: Manuel
* Date: 19.01.2017
* Time: 12:40
* @ilCtrl_IsCalledBy ilACOMemberGUI: ilUIPluginRouterGUI
* @ilCtrl_Calls ilACOMemberGUI: ilObjCourseAdministrationGUI
* @ilCtrl_Calls ilACOMemberGUI: ilRepositorySearchGUI
* @ilCtrl_Calls ilACOMemberGUI: ilObjCourseGUI
*
* This class implements the functionality of the tab move members.
* Which includes the the move of the member itself but also the drop down menu,
* the auto completion and error messages for wrong input.
*
*
*/
class ilACOMemberGUI
{
/**
* @var ilCtrl
*/
protected $ctrl;
/**
* @var ilTemplate
*/
protected $tpl;
/**
* @var ilACOPlugin
*/
protected $pl;
/**
* @var ilTabsGUI
*/
protected $tabs;
/**
* @var ilLocatorGUI
*/
protected $ilLocator;
/**
* @var ilLanguage
*/
protected $lng;
/**
* @var ilTree
*/
protected $tree;
protected $course_id;
protected $userLogin;
protected $groupTitle;
protected $destinationTitle;
protected $group_title;
protected $destination_title;
public function __construct()
{
global $tree, $ilCtrl, $tpl, $ilTabs, $ilLocator, $lng;
$this->tree = $tree;
$this->lng = $lng;
$this->tabs = $ilTabs;
$this->ctrl = $ilCtrl;
$this->tpl = $tpl;
$this->course_id = $_GET['ref_id'];
$this->ilLocator = $ilLocator;
$this->pl = ilACOPlugin::getInstance();
}
protected function prepareOutput()
{
global $ilLocator, $tpl;
$this->ctrl->setParameterByClass('ilobjcourseadministrationgui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacogroupgui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacogroupdisplaygui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacomembergui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilrepositorygui', 'ref_id', $_GET['ref_id']);
$this->tabs->addTab('course_management', $this->pl->txt('tab_course_management'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI')));
$this->tabs->addSubTab('group_create', $this->pl->txt('group_create'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI')));
$this->tabs->addSubTab('course_edit', $this->pl->txt('course_edit'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupDisplayGUI')));
$this->tabs->addSubTab('member_edit', $this->pl->txt('member_edit'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOMemberGUI')));
$this->tabs->activateSubTab('member_edit');
$this->ctrl->getRedirectSource();
$this->tabs->setBackTarget($this->pl->txt('back'), $this->ctrl->getLinkTargetByClass(array(
'ilrepositorygui',
'ilrepositorygui',
)));
$this->setTitleAndIcon();
$ilLocator->addRepositoryItems($_GET['ref_id']);
$tpl->setLocator();
}
protected function setTitleAndIcon()
{
$this->tpl->setTitleIcon(ilUtil::getImagePath('icon_crs.svg'));
$this->tpl->setTitle($this->pl->txt('obj_acop'));
$this->tpl->setDescription($this->pl->txt('obj_acop_desc'));
}
/**
*
*/
public function executeCommand()
{
$this->checkAccess();
$cmd = $this->ctrl->getCmd('view');
$this->ctrl->saveParameter($this, 'ref_id');
$this->prepareOutput();
switch ($cmd) {
default:
$this->$cmd();
break;
}
$this->tpl->getStandardTemplate();
$this->tpl->show();
}
/**
* default command
*/
protected function view()
{
$form = $this->initForm();
$form->setValuesByPost();
$this->tpl->setContent($form->getHTML());
}
protected function initForm()
{
global $lng, $ilCtrl;
$form = new ilPropertyFormGUI();
$form->setTitle($this->pl->txt('member_edit'));
$form->setDescription($this->pl->txt('member_description'));
$form->setId('member_edit');
$form->setFormAction($this->ctrl->getFormAction($this));
$a_options = array(
'auto_complete_name' => $lng->txt('user'),
);
$ajax_url = $ilCtrl->getLinkTargetByClass(array(get_class($this), 'ilRepositorySearchGUI'),
'doUserAutoComplete', '', true, false);
$this->userLogin = new ilTextInputGUI($a_options['auto_complete_name'], 'user_login');
$this->userLogin->setDataSource($ajax_url);
$this->userLogin->setRequired(true);
$form->addItem($this->userLogin);
$form->addCommandButton(selectMember, $this->pl->txt(select_member));
return $form;
}
protected function selectMember()
{
global $lng, $ilCtrl;
$form = new ilPropertyFormGUI();
$form->setTitle($this->pl->txt('member_edit'));
$form->setDescription($this->pl->txt('member_description'));
$form->setId('member_edit');
$form->setFormAction($this->ctrl->getFormAction($this));
$this->userLogin = new ilTextInputGUI($this->pl->txt('member_login'), 'user_login');
$this->userLogin->setValue($_POST["user_login"]);
$this->userLogin->setDisabled(true);
$this->groupTitle = new ilSelectInputGUI($this->pl->txt('group_title'), 'group_title');
$this->groupTitle->setOptions($this->getGroupsWhereMember($this->getMemberIdByLogin($_POST["user_login"])));
$this->destinationTitle = new ilSelectInputGUI($this->pl->txt('destination_title'), 'destination_title');
$this->destinationTitle->setOptions($this->getGroupsWhereNotMember($this->getMemberIdByLogin($_POST["user_login"])));
$this->userLogin->setRequired(true);
$this->groupTitle->setRequired(true);
$this->destinationTitle->setRequired(true);
$form->addItem($this->userLogin);
$form->addItem($this->groupTitle);
$form->addItem($this->destinationTitle);
$form->addCommandButton('moveMember', $this->pl->txt('move_member'));
$form->setValuesByPost();
$this->tpl->setContent($form->getHTML());
return $form;
}
/**
* Do auto completion
* @return void
*/
protected function doUserAutoComplete()
{
$a_fields = array('login', 'firstname', 'lastname', 'email');
$result_field = 'login';
include_once './Services/User/classes/class.ilUserAutoComplete.php';
$auto = new ilUserAutoComplete();
if (($_REQUEST['fetchall'])) {
$auto->setLimit(ilUserAutoComplete::MAX_ENTRIES);
}
$auto->setSearchFields($a_fields);
$auto->setResultField($result_field);
$auto->enableFieldSearchableCheck(true);
echo $auto->getList($_REQUEST['term']);
exit();
}
protected function moveMember()
{
$form = $this->selectMember();
$form->setValuesByPost();
$member_login = $this->userLogin->getValue();
$optionsGroupTitle = $this->groupTitle->getOptions();
$optionsDestinationTitle = $this->destinationTitle->getOptions();
$this->group_title = $optionsGroupTitle[$this->groupTitle->getValue()];
$this->destination_title = $optionsDestinationTitle[$this->destinationTitle->getValue()];
$member_id = $this->getMemberIdByLogin($member_login);
$group_id = $this->getGroupIdByTitle($this->group_title, $this->course_id);
$destination_id = $this->getGroupIdByTitle($this->destination_title, $this->course_id);
$description_dest = "Groupmember of group obj_no." . $destination_id[0]["obj_id"];
$description_source = "Groupmember of group obj_no." . $group_id[0]["obj_id"];
$role_id_dest = $this->getRoleID($description_dest);
$role_id_source = $this->getRoleID($description_source);
$group_id = $group_id[0]["obj_id"];
$destination_id = $destination_id[0]["obj_id"];
$role_id_source = $role_id_source[0]["obj_id"];
$role_id_dest = $role_id_dest[0]["obj_id"];
if (($this->checkIfGroupExists($group_id)) and ($this->checkIfGroupExists($destination_id)) and
($this->checkIfUserExistsInGroup($member_id, $group_id)) and
($this->checkIfUserNotExistsInGroup($member_id, $destination_id))
) {
$this->manipulateDB($member_id, $role_id_source, $destination_id, $role_id_dest, $group_id);
}
$this->view();
}
protected function getRoleID($description)
{
global $ilDB;
$role_id = array();
$query = "SELECT od.obj_id FROM ilias.object_data as od WHERE od.description = '" . $description . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($role_id, $record);
}
return $role_id;
}
protected function manipulateDB($member_id, $role_id_source, $destination_id, $role_id_dest, $source_id)
{
global $ilDB;
//insert in RBAC
$query = "INSERT INTO rbac_ua (usr_id, rol_id) " .
"VALUES (" . $member_id . "," . $role_id_dest . ")";
$res = $ilDB->manipulate($query);
//delete OLD from RBAC
$query = "DELETE FROM rbac_ua
WHERE usr_id = " . $member_id . "
AND rol_id = " . $role_id_source . " ";
$res = $ilDB->manipulate($query);
$query = "UPDATE ilias.obj_members as om
SET om.obj_id = '" . $destination_id . "' WHERE om.usr_id = '" . $member_id . "' AND om.obj_id = '"
. $source_id . "' AND om.member = 1";
$ilDB->manipulate($query);
ilUtil::sendSuccess($this->userLogin->getValue() . $this->pl->txt("movedSuccessful") .
$this->group_title . $this->pl->txt("movedTo") . $this->destination_title . $this->pl->txt("moved"));
}
protected function getGroupIdByTitle($group_title, $course_id)
{
global $ilDB;
$group_id = array();
$query = "select oref.obj_id from ilias.crs_items as citem
join ilias.object_reference as oref on oref.ref_id = citem.obj_id
join ilias.object_data as od on oref.obj_id = od.obj_id
join ilias.crs_items as ci on oref.ref_id = ci.obj_id
where od.title='" . $group_title . "' and ci.parent_id='" . $_GET['ref_id'] . "' and oref.deleted is null";
$result = $ilDB->queryF($query, array('text', 'integer'), array($group_title, $course_id));
while ($record = $ilDB->fetchAssoc($result)) {
array_push($group_id, $record);
}
return $group_id;
}
protected function getMemberIdByLogin($member_login)
{
global $ilDB;
$member_id = array();
$query = "select usr_id from ilias.usr_data as ud where (ud.login='" . $member_login . "')";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($member_id, $record);
}
return $member_id[0]["usr_id"];
}
//Uberpruefung, ob User in der bisherigen Gruppe vorhanden
protected function checkIfUserExistsInGroup($member_id, $group_id)
{
global $ilDB;
$queryResult = array();
$query = "SELECT COUNT(*) FROM ilias.object_data as od
join ilias.object_reference as obr on obr.obj_id = od.obj_id
join ilias.obj_members as om on obr.obj_id = om.obj_id
WHERE obr.deleted is null and od.obj_id = '" . $group_id . "' and om.usr_id = '" . $member_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($queryResult, $record);
}
if (strcmp($queryResult[0]["COUNT(*)"], "1") !== 0) {
ilUtil::sendFailure($this->pl->txt("userInGroupNotExistent") . ' ' . $this->pl->txt("only_in") . ' ' . implode(' - ', $this->getGroupsWhereMember($member_id["usr_id"])), true);
return false;
} else {
return true;
}
}
//Uberpruefung, ob User in der neuen Gruppe schon vorhanden
protected function checkIfUserNotExistsInGroup($member_id, $group_id)
{
global $ilDB;
$queryResult = array();
$query = "SELECT COUNT(*) FROM ilias.object_data as od
join ilias.object_reference as obr on obr.obj_id = od.obj_id
join ilias.obj_members as om on obr.obj_id = om.obj_id
WHERE obr.deleted is null and od.obj_id = '" . $group_id . "' and om.usr_id = '" . $member_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($queryResult, $record);
}
if (strcmp($queryResult[0]["COUNT(*)"], "1") == 0) {
ilUtil::sendFailure($this->pl->txt("userInGroupExistent"), true);
return false;
} else {
return true;
}
}
// Ueberpruefung, ob die Gruppe exisitiert
protected function checkIfGroupExists($group_id)
{
global $ilDB;
$queryResult = array();
$query = "SELECT COUNT(*) FROM ilias.object_data as od
join ilias.object_reference as obr on obr.obj_id = od.obj_id
WHERE obr.deleted is null and od.obj_id = '" . $group_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($queryResult, $record);
}
if (strcmp($queryResult[0]["COUNT(*)"], "1") !== 0) {
ilUtil::sendFailure($this->pl->txt("groupNotExistent"), true);
return false;
} else {
return true;
}
}
protected function getGroups()
{
global $ilDB;
$data = array();
$query = "select od.title as 'title'
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.tree tree on tree.child = oref.ref_id
where oref.deleted is null and od.`type`='grp' and tree.parent = '" . $_GET['ref_id'] . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
$output = array();
foreach ($data as $result) {
array_push($output, $result['title']);
}
return $output;
}
protected function getGroupsWhereMember($usr_id)
{
global $ilDB;
$data = array();
$query = "select od.title as 'title'
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.crs_items citem on citem.obj_id = oref.ref_id
join ilias.obj_members as om on om.obj_id = oref.obj_id
join ilias.usr_data as ud on ud.usr_id = om.usr_id
where oref.deleted is null and od.`type`='grp' and
citem.parent_id = '" . $_GET['ref_id'] . "' and om.usr_id='" . $usr_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
$output = array();
foreach ($data as $result) {
array_push($output, $result['title']);
}
return $output;
}
protected function getGroupsWhereNotMember($usr_id)
{
global $ilDB;
$data1 = array();
$query1 = "select od.obj_id as 'obj_id'
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.crs_items citem on citem.obj_id = oref.ref_id
join ilias.obj_members as om on om.obj_id = oref.obj_id
join ilias.usr_data as ud on ud.usr_id = om.usr_id
where oref.deleted is null and od.`type`='grp' and
citem.parent_id = '" . $_GET['ref_id'] . "' and om.usr_id='" . $usr_id . "'";
$result1 = $ilDB->query($query1);
while ($record1 = $ilDB->fetchAssoc($result1)) {
array_push($data1, $record1);
}
$groupsIDWhereMemberTMP = array();
foreach ($data1 as $result1) {
array_push($groupsIDWhereMemberTMP, $result1['obj_id']);
}
$groupsIDWhereMember = "'" . implode("','", $groupsIDWhereMemberTMP) . "'";
$data = array();
$query = "select distinct od.title as 'title'
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.crs_items citem on citem.obj_id = oref.ref_id
join ilias.obj_members as om on om.obj_id = oref.obj_id
join ilias.usr_data as ud on ud.usr_id = om.usr_id
where oref.deleted is null and od.`type`='grp' and
citem.parent_id = '" . $_GET['ref_id'] . "' and om.obj_id not in (" . $groupsIDWhereMember . ")";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
$output = array();
foreach ($data as $result) {
array_push($output, $result['title']);
}
return $output;
}
protected function checkAccess()
{
global $ilAccess, $ilErr;
if (!$ilAccess->checkAccess("read", "", $_GET['ref_id'])) {
$ilErr->raiseError($this->lng->txt("no_permission"), $ilErr->WARNING);
}
}
}<file_sep><?php
include_once("./Services/UIComponent/classes/class.ilUIHookPluginGUI.php");
include_once("./Services/UIComponent/Explorer2/classes/class.ilExplorerBaseGUI.php");
require_once './Services/Form/classes/class.ilPropertyFormGUI.php';
require_once './Modules/Group/classes/class.ilObjGroup.php';
require_once './Services/Object/classes/class.ilObject2.php';
require_once './Services/Form/classes/class.ilNumberInputGUI.php';
require_once './Services/Form/classes/class.ilTextInputGUI.php';
require_once './Services/Form/classes/class.ilRadioGroupInputGUI.php';
require_once './Services/Form/classes/class.ilRadioOption.php';
require_once './Services/Form/classes/class.ilDateTimeInputGUI.php';
/**
* Created by PhpStorm.
* User: Manuel
* Date: 06.02.2017
* Time: 14:16
* @ilCtrl_IsCalledBy ilACOLinkGUI: ilUIPluginRouterGUI
* @ilCtrl_Calls ilACOLinkGUI: ilExerciseHandlerGUI, ilRepositoryGUI, ilObjTest, ilObjExercise
*
* This class implements the functionality of the link tab in the tests or excercises.
* That means you can link these elements from the course into groups in the course.
* It includes a check if the elements are already and avoid thereby double links.
*
*/
class ilACOLinkGUI
{
/**
* @var ilCtrl
*/
protected $ctrl;
/**
* @var ilTemplate
*/
protected $tpl;
/**
* @var ilACOPlugin
*/
protected $pl;
/**
* @var ilTabsGUI
*/
protected $tabs;
/**
* @var ilLocatorGUI
*/
protected $ilLocator;
/**
* @var ilLanguage
*/
protected $lng;
public function __construct()
{
global $ilCtrl, $tpl, $ilTabs, $ilLocator, $lng;
$this->unique_id = md5(uniqid());
$this->lng = $lng;
$this->tabs = $ilTabs;
$this->ctrl = $ilCtrl;
$this->tpl = $tpl;
$this->ilLocator = $ilLocator;
$this->pl = ilACOPlugin::getInstance();
}
protected function prepareOutput()
{
global $ilLocator, $tpl;
$this->ctrl->setParameterByClass('ilexercisehandlergui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacolinkgui', 'ref_id', $_GET['ref_id']);
$this->tabs->addTab('link', $this->pl->txt('tab_link'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOLinkGUI')));
$this->ctrl->getRedirectSource();
$ilLocator->addContextItems($_GET['ref_id']);
$this->setTitleAndIcon();
$tpl->setLocator();
}
protected function setTitleAndIcon()
{
if (ilObject::_lookupType($_GET['ref_id'], true) == 'tst') {
$this->tpl->setTitleIcon(ilUtil::getImagePath('icon_tst.svg'));
} else {
$this->tpl->setTitleIcon(ilUtil::getImagePath('icon_exc.svg'));
}
$this->tpl->setTitle($this->pl->txt('obj_link'));
$this->tpl->setDescription($this->pl->txt('obj_link_desc'));
}
public function executeCommand()
{
$this->checkAccess();
$cmd = $this->ctrl->getCmd('view');
$this->ctrl->saveParameter($this, 'ref_id');
$this->prepareOutput();
switch ($cmd) {
default:
$this->$cmd();
break;
}
$this->tpl->getStandardTemplate();
$this->tpl->show();
}
/**
* default command
*/
protected function view()
{
$form = $this->initForm();
$this->tpl->setContent($form->getHTML());
}
protected function initForm()
{
$form = new ilPropertyFormGUI();
if (ilObject::_lookupType($_GET['ref_id'], true) == 'tst') {
$form->setTitle($this->pl->txt('link_test'));
} else {
$form->setTitle($this->pl->txt('link_exercise'));
}
$form->setFormAction($this->ctrl->getFormAction($this));
$data = $this->getGroups($_GET['ref_id']);
//radio button to select if to link to all groups or only to single ones
$link_proc = new ilRadioGroupInputGUI($this->pl->txt('link_type'), 'link_type');
$opt1 = new ilRadioOption($this->pl->txt('link_all'), 'link_all');
$opt2 = new ilRadioOption($this->pl->txt('link_selected'), 'link_selected');
foreach ($data as $row) {
$checkbox_link = new ilCheckboxInputGUI($row['title'], $row['ref_id']);
$opt2->addSubItem($checkbox_link);
}
$link_proc->addOption($opt1);
$link_proc->addOption($opt2);
$form->addItem($link_proc);
$form->addCommandButton('link', $this->pl->txt('save_link'));
return $form;
}
protected function getAdminFolderIds()
{
$ids = array();
$group_ids = array();
$form = $this->initForm();
$form->setValuesByPost();
$formitems = $form->getItems();
$checkFormItems = $formitems[0]->getValue();
$formitems = $formitems[0]->getOptions();
$formitems = $formitems[1]->getSubItems();
$folder_name = $this->getFolderName();
foreach ($formitems as $checkbox) {
if (($checkFormItems) == "link_all") {
$checkbox->setChecked(true);
}
if (!is_null($checkbox->getChecked())) {
$group_id = $checkbox->getPostVar();
$grid = array();
$grid[0] = $group_id;
array_push($group_ids, $grid);
$folder_id = $this->getGroupFolderID($group_id, $folder_name);
if ($folder_id == -2) {
ilUtil::sendInfo($this->pl->txt('inf_group_no_named_folder') . "'.$folder_name.'" .
$this->pl->txt('msg_linked_to_group_directory'));
$folder_id = array();
$folder_id[0] = $group_id;
array_push($ids, $folder_id);
} else {
array_push($ids, $folder_id);
}
}
}
if ($folder_name == -1) {
return $group_ids;
}
return $ids;
}
protected function getFolderName()
{
global $ilDB;
$exc_id = $_GET['ref_id'];
$folder_id = $this->getParentIds($exc_id);
//get Name of Parent Folder from Exercise
$data = array();
$query = "select od.title from ilias.object_data as od
join ilias.object_reference as oref on od.obj_id = oref.obj_id
where oref.ref_id = '" . $folder_id[0] . "' and od.type = 'fold' ";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
ilUtil::sendInfo($this->pl->txt('inf_parent_no_folder'));
return -1;
}
$folder = $data[0];
return $folder['title'];
}
protected function getParentIds($id)
{
global $ilDB;
$ids = array();
$data = array();
$query = "select tree.parent from ilias.tree as tree where child = '" . $id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
foreach ($data as $folder) {
array_push($ids, $folder['parent']);
}
return $ids;
}
protected function getGroupFolderID($group_id, $folder_name)
{
global $ilDB;
if ($folder_name == -1) {
$return = array();
$return[0] = $group_id;
return $return;
}
$data = array();
$query = "select folds.ref_id from (
select tree.parent, oref.ref_id, od.title
from ilias.object_data as od
join ilias.object_reference as oref on od.obj_id = oref.obj_id
join ilias.tree as tree on tree.child = oref.ref_id
where od.type = 'fold') as folds
where folds.parent = '" . $group_id . "' and folds.title = '" . $folder_name . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
return -2;
}
$ids = array();
foreach ($data as $folder) {
array_push($ids, $folder['ref_id']);
}
return $ids;
}
protected function link()
{
global $rbacreview, $log, $tree, $ilObjDataCache, $ilUser;
$linked_to_folders = array();
include_once "Services/AccessControl/classes/class.ilRbacLog.php";
include_once "Services/Tracking/classes/class.ilChangeEvent.php";
$rbac_log_active = ilRbacLog::isActive();
$group_admin_folder_ids = $this->getAdminFolderIds();
foreach ($group_admin_folder_ids as $folder_ref_id) {
$linked_to_folders[] = $ilObjDataCache->lookupTitle($ilObjDataCache->lookupObjId($folder_ref_id[0]));
//get Ref_id of Excercise or Test you want to link
$ref_id = $_GET['ref_id'];
//get obj_id of the excercise or Test we want to link
$obj_id[] = $ilObjDataCache->lookupObjId($ref_id);
$isAlreadyLinked = $this->isAlreadyLinked($folder_ref_id[0], $obj_id[0]);
//checks for each group if the object is already linked
//if this is the case we send a Failure to the user and we
//continue with the next selected group
if ($isAlreadyLinked == true) {
ilUtil::sendFailure(sprintf($this->pl->txt('some_folders_already_linked'), implode(', ', $linked_to_folders)), true);
continue;
}
// get node data
$top_node = $tree->getNodeData($ref_id);
// get subnodes of top nodes
$subnodes[$ref_id] = $tree->getSubtree($top_node);
// now move all subtrees to new location
foreach ($subnodes as $key => $subnode) {
// first paste top_node....
$obj_data = ilObjectFactory::getInstanceByRefId($key);
$new_ref_id = $obj_data->createReference();
$obj_data->putInTree($folder_ref_id[0]);
$obj_data->setPermissions($folder_ref_id[0]);
// rbac log
if ($rbac_log_active) {
$rbac_log_roles = $rbacreview->getParentRoleIds($new_ref_id, false);
$rbac_log = ilRbacLog::gatherFaPa($new_ref_id, array_keys($rbac_log_roles), true);
ilRbacLog::add(ilRbacLog::LINK_OBJECT, $new_ref_id, $rbac_log, $key);
}
// BEGIN ChangeEvent: Record link event.
$node_data = $tree->getNodeData($new_ref_id);
ilChangeEvent::_recordWriteEvent($node_data['obj_id'], $ilUser->getId(), 'add',
$ilObjDataCache->lookupObjId($folder_ref_id[0]));
ilChangeEvent::_catchupWriteEvents($node_data['obj_id'], $ilUser->getId());
// END PATCH ChangeEvent: Record link event.
}
$log->write(__METHOD__ . ', link finished');
ilUtil::sendSuccess(sprintf($this->pl->txt('mgs_objects_linked_to_the_following_folders'), implode(', ', $linked_to_folders)), true);
} // END LINK
}
protected function getGroups($ref_id)
{
global $ilDB;
do {
$parent_id = $this->getParentIds($ref_id);
$ref_id = $parent_id[0];
} while (!$this->isCourse($ref_id));
$data = array();
$query = "select od.title, oref.ref_id
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.crs_items citem on citem.obj_id = oref.ref_id
where oref.deleted is null and od.`type`='grp' and citem.parent_id = '" . $ref_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
return $data;
}
protected function isCourse($ref_id)
{
global $ilDB;
$data = array();
$query = "select od.title
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
where od.type = 'crs' and oref.ref_id = '" . $ref_id . "' ";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
return false;
}
return true;
}
protected function isAlreadyLinked($folder_ref_id, $obj_id)
{
global $ilDB;
$data = array();
$query = "select oref.obj_id
from ilias.tree as tr
join ilias.object_reference as oref on oref.ref_id = tr.child
where tr.parent = '" . $folder_ref_id . "'
and oref.obj_id = '" . $obj_id . "'
and oref.deleted is null";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
if (empty($data)) {
return false;
} else {
return true;
}
}
protected function checkAccess()
{
global $ilAccess, $ilErr;
if (!$ilAccess->checkAccess("write", "", $_GET['ref_id'])) {
$ilErr->raiseError($this->lng->txt("no_permission"), $ilErr->WARNING);
}
}
}
<file_sep><?php
include_once("./Services/UIComponent/classes/class.ilUserInterfaceHookPlugin.php");
/**
* Class ilACOPlugin
*
* @author <NAME>
*/
class ilACOPlugin extends ilUserInterfaceHookPlugin
{
/**
* @var ilACOPlugin
*/
protected static $instance;
/**
* @return ilACOPlugin
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
function getPluginName()
{
return "ACO";
}
}<file_sep><?php
require_once './Services/Form/classes/class.ilPropertyFormGUI.php';
require_once './Services/Form/classes/class.ilDateTimeInputGUI.php';
require_once './Services/Form/classes/class.ilDateDurationInputGUI.php';
/**
* Created by PhpStorm.
* User: Manuel
* Date: 16.12.2016
* Time: 13:50
* @ilCtrl_IsCalledBy ilACOGroupDisplayGUI: ilUIPluginRouterGUI
* @ilCtrl_Calls ilACOGroupDisplayGUI: ilObjCourseAdministrationGUI
* @ilCtrl_Calls ilACOGroupDisplayGUI: ilRepositorySearchGUI
* @ilCtrl_Calls ilACOGroupDisplayGUI: ilObjCourseGUI
*
*
* This class implements the functionality of the tab "Kurs bearbeiten" or "edit course"
* Which inlcludes the query to get the actual values of the following variables and the
* update query for them too.
* $obj_id float
* $title string
* $description string
* $tutor string
* $members float Maximum Members
* $reg_start ilDateTime Start of Registration Period
* $reg_end ilDateTime Start of Registration Period
*/
class ilACOGroupDisplayGUI
{
/**
* @var ilCtrl
*/
protected $ctrl;
/**
* @var ilTemplate
*/
protected $tpl;
/**
* @var ilACOPlugin
*/
protected $pl;
/**
* @var ilTabsGUI
*/
protected $tabs;
/**
* @var ilLocatorGUI
*/
protected $ilLocator;
/**
* @var ilLanguage
*/
protected $lng;
/**
* @var ilTree
*/
protected $tree;
protected $form;
protected $groupAdmins;
public function __construct()
{
global $tree, $ilCtrl, $tpl, $ilTabs, $ilLocator, $lng;
$this->tree = $tree;
$this->lng = $lng;
$this->tabs = $ilTabs;
$this->ctrl = $ilCtrl;
$this->tpl = $tpl;
$this->ilLocator = $ilLocator;
$this->groupAdmins = array();
$this->pl = ilACOPlugin::getInstance();
}
protected function prepareOutput()
{
global $ilLocator, $tpl;
$this->ctrl->setParameterByClass('ilobjcourseadministrationgui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacogroupdisplaygui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacogroupgui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilacomembergui', 'ref_id', $_GET['ref_id']);
$this->ctrl->setParameterByClass('ilrepositorygui', 'ref_id', $_GET['ref_id']);
$this->tabs->addTab('course_management', $this->pl->txt('tab_course_management'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI')));
$this->tabs->addSubTab('group_create', $this->pl->txt('group_create'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupGUI')));
$this->tabs->addSubTab('course_edit', $this->pl->txt('course_edit'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOGroupDisplayGUI')));
$this->tabs->addSubTab('member_edit', $this->pl->txt('member_edit'), $this->ctrl->getLinkTargetByClass(array('ilUIPluginRouterGUI', 'ilACOMemberGUI')));
$this->tabs->activateSubTab('course_edit');
$this->ctrl->getRedirectSource();
$this->tabs->setBackTarget($this->pl->txt('back'), $this->ctrl->getLinkTargetByClass(array(
'ilrepositorygui',
'ilrepositorygui',
)));
$this->setTitleAndIcon();
$ilLocator->addRepositoryItems($_GET['ref_id']);
$tpl->setLocator();
}
protected function setTitleAndIcon()
{
$this->tpl->setTitleIcon(ilUtil::getImagePath('icon_crs.svg'));
$this->tpl->setTitle($this->pl->txt('obj_acop'));
$this->tpl->setDescription($this->pl->txt('obj_acop_desc'));
}
public function executeCommand()
{
$this->checkAccess();
$cmd = $this->ctrl->getCmd('view');
$this->ctrl->saveParameter($this, 'ref_id');
$this->prepareOutput();
switch ($cmd) {
default:
$this->$cmd();
break;
}
$this->tpl->getStandardTemplate();
$this->tpl->show();
}
/**
* default command
*/
protected function view()
{
$this->form = $this->initForm();
$this->tpl->setContent($this->form->getHTML());
}
/**
* @return ilPropertyFormGUI
*/
protected function initForm()
{
global $ilCtrl;
$form = new ilPropertyFormGUI();
$form->setTitle($this->pl->txt('course_edit'));
$form->setFormAction($this->ctrl->getFormAction($this));
$data = $this->getTableData($_GET['ref_id']);
$a_options = array(
'auto_complete_name' => $this->pl->txt('group_tutor'),
);
$ajax_url = $ilCtrl->getLinkTargetByClass(array(get_class($this), 'ilRepositorySearchGUI'),
'doUserAutoComplete', '', true, false);
$n = 1;
$tmp_data = array();
$tmp_ids = array();
foreach ($data as $row) {
$this->groupAdmins[$row['obj_id']] = $row['login'];
$id = $row["obj_id"];
if (in_array($id, $tmp_ids)) {
foreach ($tmp_data as $grp) {
if ($grp["obj_id"] == $id) {
$course_admins = $this->getCourseAdminIDs($_GET["ref_id"]);
$course_admins = $this->getLoginbyIDS($course_admins);
if (in_array($grp["login"], $course_admins)) {
if (($key = array_search($grp, $tmp_data)) !== false) {
$tmp_data[$key] = $row;
}
}
}
}
} else {
array_push($tmp_ids, $id);
array_push($tmp_data, $row);
}
}
$data = $tmp_data;
foreach ($data as $row) {
$section = new ilFormSectionHeaderGUI();
$section->setTitle($row['title']);
$form->addItem($section);
$textfield_name = new ilTextInputGUI($this->pl->txt("group_name"), "group_name" . $n);
$textfield_description = new ilTextInputGUI($this->pl->txt("group_description"), "description" . $n);
$textfield_tutor = new ilTextInputGUI($a_options['auto_complete_name'], 'tutor' . $n);
$textfield_tutor->setDataSource($ajax_url);
$textfield_members = new ilNumberInputGUI($this->pl->txt("group_max_members"), "members" . $n);
$time_limit = new ilCheckboxInputGUI($this->pl->txt('grp_reg_limited'), 'reg_limit_time' . $n);
$this->tpl->addJavaScript('./Services/Form/js/date_duration.js');
$dur = new ilDateDurationInputGUI($this->pl->txt('grp_reg_period'), 'reg' . $n);
$dur->setStartText($this->pl->txt('cal_start'));
$dur->setEndText($this->pl->txt('cal_end'));
$dur->setShowTime(true);
$textfield_name->setValue($row['title']);
$textfield_name->setHiddenTitle($row['obj_id']);
$textfield_description->setValue($row['description']);
$textfield_tutor->setValue($row['login']);
$textfield_members->setValue($row['registration_max_members']);
$time_limit->setChecked(!$row['registration_unlimited']);
$start_time = new ilDateTime($row['registration_start'], IL_CAL_DATETIME);
$end_time = new ilDateTime($row['registration_end'], IL_CAL_DATETIME);
$dur->setStart($start_time);
$dur->setEnd($end_time);
$form->addItem($textfield_name);
$form->addItem($textfield_description);
$form->addItem($textfield_tutor);
$time_limit->addSubItem($dur);
$form->addItem($textfield_members);
$form->addItem($time_limit);
$n = $n + 1;
}
$form->addCommandButton('saveGroups', $this->pl->txt('save_groups'));
return $form;
}
protected function saveGroups()
{
$this->form = $this->initForm();
$this->form->setValuesByPost();
$items = $this->form->getItems();
$group_items = array_chunk($items, 6);
$n = 1;
foreach ($group_items as $group) {
$ref_id = $group[1]->getHiddenTitle();
$title = $group[1]->getValue();
$description = $group[2]->getValue();
$tutor = $group[3]->getValue();
$members = $group[4]->getValue();
$duration = $group[5];
$time_reg_enabled = $duration->getChecked();
$reg_start = $this->loadDate('reg' . $n, 'start');
$reg_end = $this->loadDate('reg' . $n, 'end');
$reg_start = $reg_start->get(IL_CAL_DATETIME);
$reg_end = $reg_end->get(IL_CAL_DATETIME);
//if reg_end before reg_start, we set the reg_start on the reg_end
//maybe not the best solution
if ($reg_end < $reg_start) {
$reg_end = $reg_start;
}
if (!(empty($tutor))){
$this->updateGroup($ref_id, $title, $description, $tutor, $members, $reg_start, $reg_end, $time_reg_enabled);
} else {
ilUtil::sendFailure($this->pl->txt('no_tutor_in_group'));
}
$n = $n + 1;
}
$this->form = $this->initForm();
$this->tpl->setContent($this->form->getHTML());
}
protected function getUserId($user_login)
{
global $ilDB;
$data = array();
$query = "select ud.usr_id
from ilias.usr_data as ud
where ud.login = '" . $user_login . "'";
$res = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($res)) {
array_push($data, $record);
}
return $data[0];
}
protected function getAdminRoleId($obj_id)
{
$description = "Groupadmin group obj_no." . $obj_id;
global $ilDB;
$role_id = array();
$query = "SELECT od.obj_id FROM ilias.object_data as od WHERE od.description = '" . $description . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($role_id, $record);
}
return $role_id[0];
}
protected function getLoginbyIDS($ids)
{
global $ilDB;
$logins = array();
$data = array();
$query = 'Select usr_data.login from ilias.usr_data where usr_data.usr_id in (' . implode(",", $ids) . ') ';
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
foreach ($data as $row) {
array_push($logins, $row['login']);
}
return $logins;
}
protected function getCourseAdminIDs($ref_id)
{
global $ilDB;
$ids = array();
$data = array();
$query = "select om.usr_id from ilias.obj_members as om
join ilias.object_reference as oref on oref.obj_id = om.obj_id
where om.admin = 1 and oref.ref_id = '" . $ref_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
foreach ($data as $row) {
array_push($ids, $row['usr_id']);
}
return $ids;
}
protected function loadDate($a_part, $a_field)
{
global $ilUser;
include_once('./Services/Calendar/classes/class.ilDateTime.php');
$dt = $_POST[$a_part][$a_field];
$date = new ilDateTime($dt, IL_CAL_DATE, $ilUser->getTimeZone());
return $date;
}
/**
* @param $obj_id float
* @param $title string
* @param $description string
* @param $tutor string
* @param $members float Maximum Members
* @param $reg_start ilDateTime Start of Registration Period
* @param $reg_end ilDateTime Start of Registration Period
*/
protected function updateGroup($obj_id, $title, $description, $tutor, $members, $reg_start, $reg_end, $time_reg)
{
global $ilDB, $rbacadmin;
//MANIPULATE GROUP ADMIN needs to be checked
//Update Group Admins if necessary
if ($this->groupAdmins[$obj_id] != $tutor) {
$user_id = $this->getUserId($tutor);
$user_id = $user_id['usr_id'];
$role_id = $this->getAdminRoleId($obj_id);
$role_id = $role_id['obj_id'];
$course_admins = $this->getCourseAdminIDs($_GET['ref_id']);
$rbacadmin->assignUser($role_id, $user_id);
if ((!empty($this->groupAdmins[$obj_id]))) {
$user_id_old = $this->getUserId($this->groupAdmins[$obj_id]);
$user_id_old = $user_id_old['usr_id'];
if (!in_array($user_id_old, $course_admins)) {
$rbacadmin->deassignUser($role_id, $user_id_old);
}
}
}
$query1 = "UPDATE ilias.object_data as od
SET od.title = '" . $title . "' , od.description = '" . $description . "'
WHERE od.obj_id = '" . $obj_id . "'";
$query2 = "UPDATE ilias.grp_settings as gs
SET gs.registration_max_members ='" . $members . "'
WHERE gs.obj_id = '" . $obj_id . "'";
if ($time_reg == "1") {
$query3 = "UPDATE ilias.grp_settings as gs
SET gs.registration_start = '" . $reg_start . "',gs.registration_end = '" . $reg_end . "',
gs.registration_unlimited = 0
WHERE gs.obj_id = '" . $obj_id . "'";
$ilDB->manipulate($query3);
} else {
$query3 = "UPDATE ilias.grp_settings as gs
SET gs.registration_start = NULL, gs.registration_end = NULL, gs.registration_unlimited = 1
WHERE gs.obj_id = '" . $obj_id . "'";
$ilDB->manipulate($query3);
}
$ilDB->manipulate($query1);
$ilDB->manipulate($query2);
}
protected function getTableData($ref_id)
{
global $ilDB;
$data = array();
$query = "select od.title, gs.registration_max_members, ud.login, od.description, gs.registration_start, gs.registration_end, od.obj_id, gs.registration_unlimited
from ilias.object_data as od
join ilias.object_reference as oref on oref.obj_id = od.obj_id
join ilias.grp_settings gs on gs.obj_id = oref.obj_id
join ilias.tree citem on citem.child = oref.ref_id
left join (select * from ilias.obj_members om where om.admin = 1) as obm on obm.obj_id = oref.obj_id
left join ilias.usr_data ud on ud.usr_id = obm.usr_id
where oref.deleted is null and od.`type`='grp' and citem.parent = '" . $ref_id . "'";
$result = $ilDB->query($query);
while ($record = $ilDB->fetchAssoc($result)) {
array_push($data, $record);
}
return $data;
}
/**
* Do auto completion
* @return void
*/
protected function doUserAutoComplete()
{
$a_fields = array('login', 'firstname', 'lastname', 'email');
$result_field = 'login';
include_once './Services/User/classes/class.ilUserAutoComplete.php';
$auto = new ilUserAutoComplete();
if (($_REQUEST['fetchall'])) {
$auto->setLimit(ilUserAutoComplete::MAX_ENTRIES);
}
$auto->setSearchFields($a_fields);
$auto->setResultField($result_field);
$auto->enableFieldSearchableCheck(true);
echo $auto->getList($_REQUEST['term']);
exit();
}
protected function checkAccess()
{
global $ilAccess, $ilErr;
if (!$ilAccess->checkAccess("read", "", $_GET['ref_id'])) {
$ilErr->raiseError($this->lng->txt("no_permission"), $ilErr->WARNING);
}
}
}
|
e4f7ed1fb6f26363b92a14e906dd7b75ea87346b
|
[
"Markdown",
"PHP"
] | 10
|
PHP
|
Ilias-fmi/ACO
|
9a64cca0a47639e8f26af3ee2d6bda844f9383f3
|
eea31a437b4a9335b6998e886c0788529d001118
|
refs/heads/master
|
<repo_name>rohanmahajan0396/Introduction-to-Data-Science---Coursework<file_sep>/Dataframes and Sorting/Homework2.R
#Course number - IST 687.
#Homework 2 - Submitted by <NAME> on September 12,2018.
#Name of Assignment - HW 2: Data Frames & Sorting.
#Due Date - September 12,2018.
#Step A: Initialize an 'arrests' dataframe - I created a variable named "arrests" and copied "USArrests" to a new variable.
arrests <- USArrests
arrests
#Step B: Explore the assault rate -
#Is a higher or lower assault rate best?
#Answer - The lower assault rate is the best assault rate. I used the "min()" command to find out the minimum assault rate and I assigned a variable called "best_assaultrate" to it. Then I displayed the state which has the best assault rate in the next command.
#The state which has the best assault rate is Vermont which is 48 per hundred thousand.
best_assaultrate <- min(arrests$Assault)
best_assaultrate
arrests[best_assaultrate,]
#Step C: Explore the murder rate
#I used to "max()" command to determine which state has the highest murder rate. Then, I assgined it to a variable and displayed the row of the State which had the highest murder rate. The State with the highest murder rate is Alabama with a murder rate of 2.2 per hundred thousand.
high_murderrate <- max(arrests$Murder)
high_murderrate
arrests[high_murderrate,]
#Below, I have created a sorted dataframe based on descending murder rate. I used the command "rev(order)" for this.
sorted_df <- arrests[rev(order(arrests$Murder)),]
sorted_df
#The first 10 states with the highest murder rate are given as follows.
head(arrests[order(arrests$Murder,decreasing=TRUE),],n=10)
#The value of the 20th row and 3rd column is 50. I have used the R code below for this.
sorted_df[20,3]
#Step D: Which state is the least safe? Explain your logic
#As mentioned last week in class, the values of Assault, Murder, Urban Population and Rape are per hundred thousand.
#So I first multiplied the entire "arrests" dataframe by 100,000 to get their exact values and stored it in another dataframe.
arrests_value <- arrests*100000
#To calculate the least safe state, I added the values of Assault, Murder and Rape of each value to get the total number of "Crimes" done in the respective states.
#Then I divided the total value by the total urban population to get the crime rate of each state. I used the variable "crime_rate" to assign this.
crime_rate <- (arrests_value[1] + arrests_value[2] + arrests_value[4])/arrests_value[3]
#I renamed the column of the new data frame due to "Murder" being published under the crime rates.
colnames(crime_rate) <- c("Crime")
#I then added this value to the first variable I created with the original "USArrests" dataframe.
arrests$newcolumn <- crime_rate
#The new dataframe is shown below.
arrests
#I then sorted this dataframe according to the highest crime rate.
least_safe <- arrests[rev(order(arrests$newcolumn)),]
#To show the least safe state, I then displayed the first row of the sorted dataframe.
#In this way, North Carolina is the least safe state with the crime rate of 8.135556.
least_safe[1,]<file_sep>/README.md
# Introduction-to-Data-Science---Coursework
Homeworks and Project from Introduction to Data Science
<file_sep>/Basic R Coding/Homework1.R
#Course number - IST 687.
#Homework 1 - Submitted by <NAME> on September 5,2018.
#Name of Assignment - HW 1: Basic R coding(vectors,conditionals)
#Due Date - September 5,2018.
#Step A - Create a Vector.
#Two vectors, "grades" and "courseName" are created and a variable "BetterThanB" is defined with the value 3.
grades <- c(4.0, 3.3, 3.7)
courseName <- c("Bio", "Math", "History")
BetterThanB <- 3
#Step B - Calculating statistics using R.
#The average of the values of the vector "grades" is calculated using the command "mean(vectorname)". The number of elements in the vector is also found using the command length(vectorname).
mean(grades)
length(grades)
total.length <- length(grades)
total.length
total <- sum(grades)
#Recomputng the average grades by diving "total" derived from Question 7 with "total length" derived from Question 5.
average_grades <- total/total.length
average_grades
#Step C - Using max/min functions in R.
#The maximum and minimum values of the vector "grades" are stored in maxG and minG respectively.
maxG <- max(grades)
maxG
minG <- min(grades)
minG
#Step D - Vector Math
#All elements of the vector "grades' is added by 0.3 and is stored in "betterGrades" The mean of "betterGrades is taken".
betterGrades <- grades + 0.3
mean(betterGrades)
#Step E - Use conditional if statements
#maxG is compared to the value 3.5 and if it is greater than 3.5, the output will print "yes" otherwise it will print "no".
if(maxG > 3.5) "yes" else "no"
#minG is compared to the value of "BetterThanB". If it is greater then the output will print "yes" otherwise it will print "no".
if(minG > BetterThanB) "yes" else "no"
#Step F - Accessing an element in a vector.
#Second element of the vector "courseName" is accessed.
courseName[2]
|
99a7e3914a6301935f45259f62a2521c2448c8e8
|
[
"Markdown",
"R"
] | 3
|
R
|
rohanmahajan0396/Introduction-to-Data-Science---Coursework
|
437f17d4a9187f89b64a7340b8e58904fa5149d5
|
cf70d946b3b7edc5c5533e2ef8e0408251f9ee50
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.